File:  [LON-CAPA] / loncom / interface / loncreateuser.pm
Revision 1.439: download - view: text, annotated - select for diffs
Sat Apr 1 14:00:23 2017 UTC (7 years, 2 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Show appropriate help for the user's context (i.e., domain, author or
  course), and user's permissions (i.e., edit versus view privilege).

    1: # The LearningOnline Network with CAPA
    2: # Create a user
    3: #
    4: # $Id: loncreateuser.pm,v 1.439 2017/04/01 14:00:23 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: 
   82: sub initialize_authen_forms {
   83:     my ($dom,$formname,$curr_authtype,$mode) = @_;
   84:     my ($krbdef,$krbdefdom) = &Apache::loncommon::get_kerberos_defaults($dom);
   85:     my %param = ( formname => $formname,
   86:                   kerb_def_dom => $krbdefdom,
   87:                   kerb_def_auth => $krbdef,
   88:                   domain => $dom,
   89:                 );
   90:     my %abv_auth = &auth_abbrev();
   91:     if ($curr_authtype =~ /^(krb4|krb5|internal|localauth|unix):(.*)$/) {
   92:         my $long_auth = $1;
   93:         my $curr_autharg = $2;
   94:         my %abv_auth = &auth_abbrev();
   95:         $param{'curr_authtype'} = $abv_auth{$long_auth};
   96:         if ($long_auth =~ /^krb(4|5)$/) {
   97:             $param{'curr_kerb_ver'} = $1;
   98:             $param{'curr_autharg'} = $curr_autharg;
   99:         }
  100:         if ($mode eq 'modifyuser') {
  101:             $param{'mode'} = $mode;
  102:         }
  103:     }
  104:     $loginscript  = &Apache::loncommon::authform_header(%param);
  105:     $authformkrb  = &Apache::loncommon::authform_kerberos(%param);
  106:     $authformnop  = &Apache::loncommon::authform_nochange(%param);
  107:     $authformint  = &Apache::loncommon::authform_internal(%param);
  108:     $authformfsys = &Apache::loncommon::authform_filesystem(%param);
  109:     $authformloc  = &Apache::loncommon::authform_local(%param);
  110: }
  111: 
  112: sub auth_abbrev {
  113:     my %abv_auth = (
  114:                      krb5      => 'krb',
  115:                      krb4      => 'krb',
  116:                      internal  => 'int',
  117:                      localauth => 'loc',
  118:                      unix      => 'fsys',
  119:                    );
  120:     return %abv_auth;
  121: }
  122: 
  123: # ====================================================
  124: 
  125: sub user_quotas {
  126:     my ($ccuname,$ccdomain) = @_;
  127:     my %lt = &Apache::lonlocal::texthash(
  128:                    'usrt'      => "User Tools",
  129:                    'cust'      => "Custom quota",
  130:                    'chqu'      => "Change quota",
  131:     );
  132:    
  133:     my $quota_javascript = <<"END_SCRIPT";
  134: <script type="text/javascript">
  135: // <![CDATA[
  136: function quota_changes(caller,context) {
  137:     var customoff = document.getElementById('custom_'+context+'quota_off');
  138:     var customon = document.getElementById('custom_'+context+'quota_on');
  139:     var number = document.getElementById(context+'quota');
  140:     if (caller == "custom") {
  141:         if (customoff) {
  142:             if (customoff.checked) {
  143:                 number.value = "";
  144:             }
  145:         }
  146:     }
  147:     if (caller == "quota") {
  148:         if (customon) {
  149:             customon.checked = true;
  150:         }
  151:     }
  152:     return;
  153: }
  154: // ]]>
  155: </script>
  156: END_SCRIPT
  157:     my $longinsttype;
  158:     my ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($ccdomain);
  159:     my $output = $quota_javascript."\n".
  160:                  '<h3>'.$lt{'usrt'}.'</h3>'."\n".
  161:                  &Apache::loncommon::start_data_table();
  162: 
  163:     if ((&Apache::lonnet::allowed('mut',$ccdomain)) ||
  164:         (&Apache::lonnet::allowed('udp',$ccdomain))) {
  165:         $output .= &build_tools_display($ccuname,$ccdomain,'tools');
  166:     }
  167: 
  168:     my %titles = &Apache::lonlocal::texthash (
  169:                     portfolio => "Disk space allocated to user's portfolio files",
  170:                     author    => "Disk space allocated to user's Authoring Space (if role assigned)",
  171:                  );
  172:     foreach my $name ('portfolio','author') {
  173:         my ($currquota,$quotatype,$inststatus,$defquota) =
  174:             &Apache::loncommon::get_user_quota($ccuname,$ccdomain,$name);
  175:         if ($longinsttype eq '') { 
  176:             if ($inststatus ne '') {
  177:                 if ($usertypes->{$inststatus} ne '') {
  178:                     $longinsttype = $usertypes->{$inststatus};
  179:                 }
  180:             }
  181:         }
  182:         my ($showquota,$custom_on,$custom_off,$defaultinfo);
  183:         $custom_on = ' ';
  184:         $custom_off = ' checked="checked" ';
  185:         if ($quotatype eq 'custom') {
  186:             $custom_on = $custom_off;
  187:             $custom_off = ' ';
  188:             $showquota = $currquota;
  189:             if ($longinsttype eq '') {
  190:                 $defaultinfo = &mt('For this user, the default quota would be [_1]'
  191:                               .' MB.',$defquota);
  192:             } else {
  193:                 $defaultinfo = &mt("For this user, the default quota would be [_1]".
  194:                                    " MB, as determined by the user's institutional".
  195:                                    " affiliation ([_2]).",$defquota,$longinsttype);
  196:             }
  197:         } else {
  198:             if ($longinsttype eq '') {
  199:                 $defaultinfo = &mt('For this user, the default quota is [_1]'
  200:                               .' MB.',$defquota);
  201:             } else {
  202:                 $defaultinfo = &mt("For this user, the default quota of [_1]".
  203:                                    " MB, is determined by the user's institutional".
  204:                                    " affiliation ([_2]).",$defquota,$longinsttype);
  205:             }
  206:         }
  207: 
  208:         if (&Apache::lonnet::allowed('mpq',$ccdomain)) {
  209:             $output .= '<tr class="LC_info_row">'."\n".
  210:                        '    <td>'.$titles{$name}.'</td>'."\n".
  211:                        '  </tr>'."\n".
  212:                        &Apache::loncommon::start_data_table_row()."\n".
  213:                        '  <td><span class="LC_nobreak">'.
  214:                        &mt('Current quota: [_1] MB',$currquota).'</span>&nbsp;&nbsp;'.
  215:                        $defaultinfo.'</td>'."\n".
  216:                        &Apache::loncommon::end_data_table_row()."\n".
  217:                        &Apache::loncommon::start_data_table_row()."\n".
  218:                        '  <td><span class="LC_nobreak">'.$lt{'chqu'}.
  219:                        ': <label>'.
  220:                        '<input type="radio" name="custom_'.$name.'quota" id="custom_'.$name.'quota_off" '.
  221:                        'value="0" '.$custom_off.' onchange="javascript:quota_changes('."'custom','$name'".');"'.
  222:                        ' /><span class="LC_nobreak">'.
  223:                        &mt('Default ([_1] MB)',$defquota).'</span></label>&nbsp;'.
  224:                        '&nbsp;<label><input type="radio" name="custom_'.$name.'quota" id="custom_'.$name.'quota_on" '.
  225:                        'value="1" '.$custom_on.'  onchange="javascript:quota_changes('."'custom','$name'".');"'.
  226:                        ' />'.$lt{'cust'}.':</label>&nbsp;'.
  227:                        '<input type="text" name="'.$name.'quota" id="'.$name.'quota" size ="5" '.
  228:                        'value="'.$showquota.'" onfocus="javascript:quota_changes('."'quota','$name'".');"'.
  229:                        ' />&nbsp;'.&mt('MB').'</span></td>'."\n".
  230:                        &Apache::loncommon::end_data_table_row()."\n";
  231:         }
  232:     }
  233:     $output .= &Apache::loncommon::end_data_table();
  234:     return $output;
  235: }
  236: 
  237: sub build_tools_display {
  238:     my ($ccuname,$ccdomain,$context) = @_;
  239:     my (@usertools,%userenv,$output,@options,%validations,%reqtitles,%reqdisplay,
  240:         $colspan,$isadv,%domconfig);
  241:     my %lt = &Apache::lonlocal::texthash (
  242:                    'blog'       => "Personal User Blog",
  243:                    'aboutme'    => "Personal Information Page",
  244:                    'webdav'     => "WebDAV access to Authoring Spaces (if SSL and author/co-author)",
  245:                    'portfolio'  => "Personal User Portfolio",
  246:                    'avai'       => "Available",
  247:                    'cusa'       => "availability",
  248:                    'chse'       => "Change setting",
  249:                    'usde'       => "Use default",
  250:                    'uscu'       => "Use custom",
  251:                    'official'   => 'Can request creation of official courses',
  252:                    'unofficial' => 'Can request creation of unofficial courses',
  253:                    'community'  => 'Can request creation of communities',
  254:                    'textbook'   => 'Can request creation of textbook courses',
  255:                    'placement'  => 'Can request creation of placement tests',
  256:                    'requestauthor'  => 'Can request author space',
  257:     );
  258:     if ($context eq 'requestcourses') {
  259:         %userenv = &Apache::lonnet::userenvironment($ccdomain,$ccuname,
  260:                       'requestcourses.official','requestcourses.unofficial',
  261:                       'requestcourses.community','requestcourses.textbook',
  262:                       'requestcourses.placement');
  263:         @usertools = ('official','unofficial','community','textbook','placement');
  264:         @options =('norequest','approval','autolimit','validate');
  265:         %validations = &Apache::lonnet::auto_courserequest_checks($ccdomain);
  266:         %reqtitles = &courserequest_titles();
  267:         %reqdisplay = &courserequest_display();
  268:         $colspan = ' colspan="2"';
  269:         %domconfig =
  270:             &Apache::lonnet::get_dom('configuration',['requestcourses'],$ccdomain);
  271:         $isadv = &Apache::lonnet::is_advanced_user($ccdomain,$ccuname);
  272:     } elsif ($context eq 'requestauthor') {
  273:         %userenv = &Apache::lonnet::userenvironment($ccdomain,$ccuname,
  274:                                                     'requestauthor');
  275:         @usertools = ('requestauthor');
  276:         @options =('norequest','approval','automatic');
  277:         %reqtitles = &requestauthor_titles();
  278:         %reqdisplay = &requestauthor_display();
  279:         $colspan = ' colspan="2"';
  280:         %domconfig =
  281:             &Apache::lonnet::get_dom('configuration',['requestauthor'],$ccdomain);
  282:     } else {
  283:         %userenv = &Apache::lonnet::userenvironment($ccdomain,$ccuname,
  284:                           'tools.aboutme','tools.portfolio','tools.blog',
  285:                           'tools.webdav');
  286:         @usertools = ('aboutme','blog','webdav','portfolio');
  287:     }
  288:     foreach my $item (@usertools) {
  289:         my ($custom_access,$curr_access,$cust_on,$cust_off,$tool_on,$tool_off,
  290:             $currdisp,$custdisp,$custradio);
  291:         $cust_off = 'checked="checked" ';
  292:         $tool_on = 'checked="checked" ';
  293:         $curr_access =  
  294:             &Apache::lonnet::usertools_access($ccuname,$ccdomain,$item,undef,
  295:                                               $context);
  296:         if ($context eq 'requestauthor') {
  297:             if ($userenv{$context} ne '') {
  298:                 $cust_on = ' checked="checked" ';
  299:                 $cust_off = '';
  300:             }  
  301:         } elsif ($userenv{$context.'.'.$item} ne '') {
  302:             $cust_on = ' checked="checked" ';
  303:             $cust_off = '';
  304:         }
  305:         if ($context eq 'requestcourses') {
  306:             if ($userenv{$context.'.'.$item} eq '') {
  307:                 $custom_access = &mt('Currently from default setting.');
  308:             } else {
  309:                 $custom_access = &mt('Currently from custom setting.');
  310:             }
  311:         } elsif ($context eq 'requestauthor') {
  312:             if ($userenv{$context} eq '') {
  313:                 $custom_access = &mt('Currently from default setting.');
  314:             } else {
  315:                 $custom_access = &mt('Currently from custom setting.');
  316:             }
  317:         } else {
  318:             if ($userenv{$context.'.'.$item} eq '') {
  319:                 $custom_access =
  320:                     &mt('Availability determined currently from default setting.');
  321:                 if (!$curr_access) {
  322:                     $tool_off = 'checked="checked" ';
  323:                     $tool_on = '';
  324:                 }
  325:             } else {
  326:                 $custom_access =
  327:                     &mt('Availability determined currently from custom setting.');
  328:                 if ($userenv{$context.'.'.$item} == 0) {
  329:                     $tool_off = 'checked="checked" ';
  330:                     $tool_on = '';
  331:                 }
  332:             }
  333:         }
  334:         $output .= '  <tr class="LC_info_row">'."\n".
  335:                    '   <td'.$colspan.'>'.$lt{$item}.'</td>'."\n".
  336:                    '  </tr>'."\n".
  337:                    &Apache::loncommon::start_data_table_row()."\n";
  338:   
  339:         if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
  340:             my ($curroption,$currlimit);
  341:             my $envkey = $context.'.'.$item;
  342:             if ($context eq 'requestauthor') {
  343:                 $envkey = $context;
  344:             }
  345:             if ($userenv{$envkey} ne '') {
  346:                 $curroption = $userenv{$envkey};
  347:             } else {
  348:                 my (@inststatuses);
  349:                 if ($context eq 'requestcourses') {
  350:                     $curroption =
  351:                         &Apache::loncoursequeueadmin::get_processtype('course',$ccuname,$ccdomain,
  352:                                                                       $isadv,$ccdomain,$item,
  353:                                                                       \@inststatuses,\%domconfig);
  354:                 } else {
  355:                      $curroption = 
  356:                          &Apache::loncoursequeueadmin::get_processtype('requestauthor',$ccuname,$ccdomain,
  357:                                                                        $isadv,$ccdomain,undef,
  358:                                                                        \@inststatuses,\%domconfig);
  359:                 }
  360:             }
  361:             if (!$curroption) {
  362:                 $curroption = 'norequest';
  363:             }
  364:             if ($curroption =~ /^autolimit=(\d*)$/) {
  365:                 $currlimit = $1;
  366:                 if ($currlimit eq '') {
  367:                     $currdisp = &mt('Yes, automatic creation');
  368:                 } else {
  369:                     $currdisp = &mt('Yes, up to [quant,_1,request]/user',$currlimit);
  370:                 }
  371:             } else {
  372:                 $currdisp = $reqdisplay{$curroption};
  373:             }
  374:             $custdisp = '<table>';
  375:             foreach my $option (@options) {
  376:                 my $val = $option;
  377:                 if ($option eq 'norequest') {
  378:                     $val = 0;
  379:                 }
  380:                 if ($option eq 'validate') {
  381:                     my $canvalidate = 0;
  382:                     if (ref($validations{$item}) eq 'HASH') {
  383:                         if ($validations{$item}{'_custom_'}) {
  384:                             $canvalidate = 1;
  385:                         }
  386:                     }
  387:                     next if (!$canvalidate);
  388:                 }
  389:                 my $checked = '';
  390:                 if ($option eq $curroption) {
  391:                     $checked = ' checked="checked"';
  392:                 } elsif ($option eq 'autolimit') {
  393:                     if ($curroption =~ /^autolimit/) {
  394:                         $checked = ' checked="checked"';
  395:                     }
  396:                 }
  397:                 my $name = 'crsreq_'.$item;
  398:                 if ($context eq 'requestauthor') {
  399:                     $name = $item;
  400:                 }
  401:                 $custdisp .= '<tr><td><span class="LC_nobreak"><label>'.
  402:                              '<input type="radio" name="'.$name.'" '.
  403:                              'value="'.$val.'"'.$checked.' />'.
  404:                              $reqtitles{$option}.'</label>&nbsp;';
  405:                 if ($option eq 'autolimit') {
  406:                     $custdisp .= '<input type="text" name="'.$name.
  407:                                  '_limit" size="1" '.
  408:                                  'value="'.$currlimit.'" /></span><br />'.
  409:                                  $reqtitles{'unlimited'};
  410:                 } else {
  411:                     $custdisp .= '</span>';
  412:                 }
  413:                 $custdisp .= '</td></tr>';
  414:             }
  415:             $custdisp .= '</table>';
  416:             $custradio = '</span></td><td>'.&mt('Custom setting').'<br />'.$custdisp;
  417:         } else {
  418:             $currdisp = ($curr_access?&mt('Yes'):&mt('No'));
  419:             my $name = $context.'_'.$item;
  420:             if ($context eq 'requestauthor') {
  421:                 $name = $context;
  422:             }
  423:             $custdisp = '<span class="LC_nobreak"><label>'.
  424:                         '<input type="radio" name="'.$name.'"'.
  425:                         ' value="1" '.$tool_on.'/>'.&mt('On').'</label>&nbsp;<label>'.
  426:                         '<input type="radio" name="'.$name.'" value="0" '.
  427:                         $tool_off.'/>'.&mt('Off').'</label></span>';
  428:             $custradio = ('&nbsp;'x2).'--'.$lt{'cusa'}.':&nbsp;'.$custdisp.
  429:                           '</span>';
  430:         }
  431:         $output .= '  <td'.$colspan.'>'.$custom_access.('&nbsp;'x4).
  432:                    $lt{'avai'}.': '.$currdisp.'</td>'."\n".
  433:                    &Apache::loncommon::end_data_table_row()."\n";
  434:         unless (&Apache::lonnet::allowed('udp',$ccdomain)) {
  435:             $output .=
  436:                    &Apache::loncommon::start_data_table_row()."\n".
  437:                    '  <td style="vertical-align:top;"><span class="LC_nobreak">'.
  438:                    $lt{'chse'}.': <label>'.
  439:                    '<input type="radio" name="custom'.$item.'" value="0" '.
  440:                    $cust_off.'/>'.$lt{'usde'}.'</label>'.('&nbsp;' x3).
  441:                    '<label><input type="radio" name="custom'.$item.'" value="1" '.
  442:                    $cust_on.'/>'.$lt{'uscu'}.'</label>'.$custradio.'</td>'.
  443:                    &Apache::loncommon::end_data_table_row()."\n";
  444:         }
  445:     }
  446:     return $output;
  447: }
  448: 
  449: sub coursereq_externaluser {
  450:     my ($ccuname,$ccdomain,$cdom) = @_;
  451:     my (@usertools,@options,%validations,%userenv,$output);
  452:     my %lt = &Apache::lonlocal::texthash (
  453:                    'official'   => 'Can request creation of official courses',
  454:                    'unofficial' => 'Can request creation of unofficial courses',
  455:                    'community'  => 'Can request creation of communities',
  456:                    'textbook'   => 'Can request creation of textbook courses',
  457:                    'placement'  => 'Can request creation of placement tests',
  458:     );
  459: 
  460:     %userenv = &Apache::lonnet::userenvironment($ccdomain,$ccuname,
  461:                       'reqcrsotherdom.official','reqcrsotherdom.unofficial',
  462:                       'reqcrsotherdom.community','reqcrsotherdom.textbook',
  463:                       'reqcrsotherdom.placement');
  464:     @usertools = ('official','unofficial','community','textbook','placement');
  465:     @options = ('approval','validate','autolimit');
  466:     %validations = &Apache::lonnet::auto_courserequest_checks($cdom);
  467:     my $optregex = join('|',@options);
  468:     my %reqtitles = &courserequest_titles();
  469:     foreach my $item (@usertools) {
  470:         my ($curroption,$currlimit,$tooloff);
  471:         if ($userenv{'reqcrsotherdom.'.$item} ne '') {
  472:             my @curr = split(',',$userenv{'reqcrsotherdom.'.$item});
  473:             foreach my $req (@curr) {
  474:                 if ($req =~ /^\Q$cdom\E\:($optregex)=?(\d*)$/) {
  475:                     $curroption = $1;
  476:                     $currlimit = $2;
  477:                     last;
  478:                 }
  479:             }
  480:             if (!$curroption) {
  481:                 $curroption = 'norequest';
  482:                 $tooloff = ' checked="checked"';
  483:             }
  484:         } else {
  485:             $curroption = 'norequest';
  486:             $tooloff = ' checked="checked"';
  487:         }
  488:         $output.= &Apache::loncommon::start_data_table_row()."\n".
  489:                   '  <td><span class="LC_nobreak">'.$lt{$item}.': </span></td><td>'.
  490:                   '<table><tr><td valign="top">'."\n".
  491:                   '<label><input type="radio" name="reqcrsotherdom_'.$item.
  492:                   '" value=""'.$tooloff.' />'.$reqtitles{'norequest'}.
  493:                   '</label></td>';
  494:         foreach my $option (@options) {
  495:             if ($option eq 'validate') {
  496:                 my $canvalidate = 0;
  497:                 if (ref($validations{$item}) eq 'HASH') {
  498:                     if ($validations{$item}{'_external_'}) {
  499:                         $canvalidate = 1;
  500:                     }
  501:                 }
  502:                 next if (!$canvalidate);
  503:             }
  504:             my $checked = '';
  505:             if ($option eq $curroption) {
  506:                 $checked = ' checked="checked"';
  507:             }
  508:             $output .= '<td valign="top"><span class="LC_nobreak"><label>'.
  509:                        '<input type="radio" name="reqcrsotherdom_'.$item.
  510:                        '" value="'.$option.'"'.$checked.' />'.
  511:                        $reqtitles{$option}.'</label>';
  512:             if ($option eq 'autolimit') {
  513:                 $output .= '&nbsp;<input type="text" name="reqcrsotherdom_'.
  514:                            $item.'_limit" size="1" '.
  515:                            'value="'.$currlimit.'" /></span>'.
  516:                            '<br />'.$reqtitles{'unlimited'};
  517:             } else {
  518:                 $output .= '</span>';
  519:             }
  520:             $output .= '</td>';
  521:         }
  522:         $output .= '</td></tr></table></td>'."\n".
  523:                    &Apache::loncommon::end_data_table_row()."\n";
  524:     }
  525:     return $output;
  526: }
  527: 
  528: sub domainrole_req {
  529:     my ($ccuname,$ccdomain) = @_;
  530:     return '<br /><h3>'.
  531:            &mt('User Can Request Assignment of Domain Roles?').
  532:            '</h3>'."\n".
  533:            &Apache::loncommon::start_data_table().
  534:            &build_tools_display($ccuname,$ccdomain,
  535:                                 'requestauthor').
  536:            &Apache::loncommon::end_data_table();
  537: }
  538: 
  539: sub courserequest_titles {
  540:     my %titles = &Apache::lonlocal::texthash (
  541:                                    official   => 'Official',
  542:                                    unofficial => 'Unofficial',
  543:                                    community  => 'Communities',
  544:                                    textbook   => 'Textbook',
  545:                                    placement  => 'Placement Tests',
  546:                                    norequest  => 'Not allowed',
  547:                                    approval   => 'Approval by Dom. Coord.',
  548:                                    validate   => 'With validation',
  549:                                    autolimit  => 'Numerical limit',
  550:                                    unlimited  => '(blank for unlimited)',
  551:                  );
  552:     return %titles;
  553: }
  554: 
  555: sub courserequest_display {
  556:     my %titles = &Apache::lonlocal::texthash (
  557:                                    approval   => 'Yes, need approval',
  558:                                    validate   => 'Yes, with validation',
  559:                                    norequest  => 'No',
  560:    );
  561:    return %titles;
  562: }
  563: 
  564: sub requestauthor_titles {
  565:     my %titles = &Apache::lonlocal::texthash (
  566:                                    norequest  => 'Not allowed',
  567:                                    approval   => 'Approval by Dom. Coord.',
  568:                                    automatic  => 'Automatic approval',
  569:                  );
  570:     return %titles;
  571: 
  572: }
  573: 
  574: sub requestauthor_display {
  575:     my %titles = &Apache::lonlocal::texthash (
  576:                                    approval   => 'Yes, need approval',
  577:                                    automatic  => 'Yes, automatic approval',
  578:                                    norequest  => 'No',
  579:    );
  580:    return %titles;
  581: }
  582: 
  583: sub requestchange_display {
  584:     my %titles = &Apache::lonlocal::texthash (
  585:                                    approval   => "availability set to 'on' (approval required)", 
  586:                                    automatic  => "availability set to 'on' (automatic approval)",
  587:                                    norequest  => "availability set to 'off'",
  588:    );
  589:    return %titles;
  590: }
  591: 
  592: sub curr_requestauthor {
  593:     my ($uname,$udom,$isadv,$inststatuses,$domconfig) = @_;
  594:     return unless ((ref($inststatuses) eq 'ARRAY') && (ref($domconfig) eq 'HASH'));
  595:     if ($uname eq '' || $udom eq '') {
  596:         $uname = $env{'user.name'};
  597:         $udom = $env{'user.domain'};
  598:         $isadv = $env{'user.adv'};
  599:     }
  600:     my (%userenv,%settings,$val);
  601:     my @options = ('automatic','approval');
  602:     %userenv =
  603:         &Apache::lonnet::userenvironment($udom,$uname,'requestauthor','inststatus');
  604:     if ($userenv{'requestauthor'}) {
  605:         $val = $userenv{'requestauthor'};
  606:         @{$inststatuses} = ('_custom_');
  607:     } else {
  608:         my %alltasks;
  609:         if (ref($domconfig->{'requestauthor'}) eq 'HASH') {
  610:             %settings = %{$domconfig->{'requestauthor'}};
  611:             if (($isadv) && ($settings{'_LC_adv'} ne '')) {
  612:                 $val = $settings{'_LC_adv'};
  613:                 @{$inststatuses} = ('_LC_adv_');
  614:             } else {
  615:                 if ($userenv{'inststatus'} ne '') {
  616:                     @{$inststatuses} = split(',',$userenv{'inststatus'});
  617:                 } else {
  618:                     @{$inststatuses} = ('default');
  619:                 }
  620:                 foreach my $status (@{$inststatuses}) {
  621:                     if (exists($settings{$status})) {
  622:                         my $value = $settings{$status};
  623:                         next unless ($value);
  624:                         unless (exists($alltasks{$value})) {
  625:                             if (ref($alltasks{$value}) eq 'ARRAY') {
  626:                                 unless(grep(/^\Q$status\E$/,@{$alltasks{$value}})) {
  627:                                     push(@{$alltasks{$value}},$status);
  628:                                 }
  629:                             } else {
  630:                                 @{$alltasks{$value}} = ($status);
  631:                             }
  632:                         }
  633:                     }
  634:                 }
  635:                 foreach my $option (@options) {
  636:                     if ($alltasks{$option}) {
  637:                         $val = $option;
  638:                         last;
  639:                     }
  640:                 }
  641:             }
  642:         }
  643:     }
  644:     return $val;
  645: }
  646: 
  647: # =================================================================== Phase one
  648: 
  649: sub print_username_entry_form {
  650:     my ($r,$context,$response,$srch,$forcenewuser,$crstype,$brcrum,
  651:         $permission) = @_;
  652:     my $defdom=$env{'request.role.domain'};
  653:     my $formtoset = 'crtuser';
  654:     if (exists($env{'form.startrolename'})) {
  655:         $formtoset = 'docustom';
  656:         $env{'form.rolename'} = $env{'form.startrolename'};
  657:     } elsif ($env{'form.origform'} eq 'crtusername') {
  658:         $formtoset =  $env{'form.origform'};
  659:     }
  660: 
  661:     my ($jsback,$elements) = &crumb_utilities();
  662: 
  663:     my $jscript = &Apache::loncommon::studentbrowser_javascript()."\n".
  664:         '<script type="text/javascript">'."\n".
  665:         '// <![CDATA['."\n".
  666:         &Apache::lonhtmlcommon::set_form_elements($elements->{$formtoset})."\n".
  667:         '// ]]>'."\n".
  668:         '</script>'."\n";
  669: 
  670:     my %existingroles=&Apache::lonuserutils::my_custom_roles($crstype);
  671:     if (($env{'form.action'} eq 'custom') && (keys(%existingroles) > 0)
  672:         && (&Apache::lonnet::allowed('mcr','/'))) {
  673:         $jscript .= &customrole_javascript();
  674:     }
  675:     my $helpitem = 'Course_Change_Privileges';
  676:     if ($env{'form.action'} eq 'custom') {
  677:         if ($context eq 'course') {
  678:             $helpitem = 'Course_Editing_Custom_Roles';
  679:         } elsif ($context eq 'domain') {
  680:             $helpitem = 'Domain_Editing_Custom_Roles';
  681:         }
  682:     } elsif ($env{'form.action'} eq 'singlestudent') {
  683:         $helpitem = 'Course_Add_Student';
  684:     } elsif ($env{'form.action'} eq 'accesslogs') {
  685:         $helpitem = 'Domain_User_Access_Logs';
  686:     } elsif ($context eq 'author') {
  687:         $helpitem = 'Author_Change_Privileges';
  688:     } elsif ($context eq 'domain') {
  689:         if ($permission->{'cusr'}) {
  690:             $helpitem = 'Domain_Change_Privileges';
  691:         } elsif ($permission->{'view'}) {
  692:             $helpitem = 'Domain_View_Privileges';
  693:         } else {
  694:             undef($helpitem);
  695:         }
  696:     }
  697:     my %breadcrumb_text = &singleuser_breadcrumb($crstype,$context,$defdom);
  698:     if ($env{'form.action'} eq 'custom') {
  699:         push(@{$brcrum},
  700:                  {href=>"javascript:backPage(document.crtuser)",       
  701:                   text=>"Pick custom role",
  702:                   help => $helpitem,}
  703:                  );
  704:     } else {
  705:         push (@{$brcrum},
  706:                   {href => "javascript:backPage(document.crtuser)",
  707:                    text => $breadcrumb_text{'search'},
  708:                    help => $helpitem,
  709:                    faq  => 282,
  710:                    bug  => 'Instructor Interface',}
  711:                   );
  712:     }
  713:     my %loaditems = (
  714:                 'onload' => "javascript:setFormElements(document.$formtoset)",
  715:                     );
  716:     my $args = {bread_crumbs           => $brcrum,
  717:                 bread_crumbs_component => 'User Management',
  718:                 add_entries            => \%loaditems,};
  719:     $r->print(&Apache::loncommon::start_page('User Management',$jscript,$args));
  720: 
  721:     my %lt=&Apache::lonlocal::texthash(
  722:                     'srst' => 'Search for a user and enroll as a student',
  723:                     'srme' => 'Search for a user and enroll as a member',
  724:                     'srad' => 'Search for a user and modify/add user information or roles',
  725:                     'srvu' => 'Search for a user and view user information and roles',
  726:                     'srva' => 'Search for a user and view access log information',
  727: 		    'usr'  => "Username",
  728:                     'dom'  => "Domain",
  729:                     'ecrp' => "Define or Edit Custom Role",
  730:                     'nr'   => "role name",
  731:                     'cre'  => "Next",
  732: 				       );
  733: 
  734:     if ($env{'form.action'} eq 'custom') {
  735:         if (&Apache::lonnet::allowed('mcr','/')) {
  736:             my $newroletext = &mt('Define new custom role:');
  737:             $r->print('<form action="/adm/createuser" method="post" name="docustom">'.
  738:                       '<input type="hidden" name="action" value="'.$env{'form.action'}.'" />'.
  739:                       '<input type="hidden" name="phase" value="selected_custom_edit" />'.
  740:                       '<h3>'.$lt{'ecrp'}.'</h3>'.
  741:                       &Apache::loncommon::start_data_table().
  742:                       &Apache::loncommon::start_data_table_row().
  743:                       '<td>');
  744:             if (keys(%existingroles) > 0) {
  745:                 $r->print('<br /><label><input type="radio" name="customroleaction" value="new" checked="checked" onclick="setCustomFields();" /><b>'.$newroletext.'</b></label>');
  746:             } else {
  747:                 $r->print('<br /><input type="hidden" name="customroleaction" value="new" /><b>'.$newroletext.'</b>');
  748:             }
  749:             $r->print('</td><td align="center">'.$lt{'nr'}.'<br /><input type="text" size="15" name="newrolename" onfocus="setCustomAction('."'new'".');" /></td>'.
  750:                       &Apache::loncommon::end_data_table_row());
  751:             if (keys(%existingroles) > 0) {
  752:                 $r->print(&Apache::loncommon::start_data_table_row().'<td><br />'.
  753:                           '<label><input type="radio" name="customroleaction" value="edit" onclick="setCustomFields();"/><b>'.
  754:                           &mt('View/Modify existing role:').'</b></label></td>'.
  755:                           '<td align="center"><br />'.
  756:                           '<select name="rolename" onchange="setCustomAction('."'edit'".');">'.
  757:                           '<option value="" selected="selected">'.
  758:                           &mt('Select'));
  759:                 foreach my $role (sort(keys(%existingroles))) {
  760:                     $r->print('<option value="'.$role.'">'.$role.'</option>');
  761:                 }
  762:                 $r->print('</select>'.
  763:                           '</td>'.
  764:                           &Apache::loncommon::end_data_table_row());
  765:             }
  766:             $r->print(&Apache::loncommon::end_data_table().'<p>'.
  767:                       '<input name="customeditor" type="submit" value="'.
  768:                       $lt{'cre'}.'" /></p>'.
  769:                       '</form>');
  770:         }
  771:     } else {
  772:         my $actiontext = $lt{'srad'};
  773:         my $fixeddom;
  774:         if ($env{'form.action'} eq 'singlestudent') {
  775:             if ($crstype eq 'Community') {
  776:                 $actiontext = $lt{'srme'};
  777:             } else {
  778:                 $actiontext = $lt{'srst'};
  779:             }
  780:         } elsif ($env{'form.action'} eq 'accesslogs') {
  781:             $actiontext = $lt{'srva'};
  782:             $fixeddom = 1;
  783:         } elsif (($env{'form.action'} eq 'singleuser') &&
  784:                  ($context eq 'domain') && (!&Apache::lonnet::allowed('mau',$defdom))) {
  785:             $actiontext = $lt{'srvu'};
  786:             $fixeddom = 1;
  787:         }
  788:         $r->print("<h3>$actiontext</h3>");
  789:         if ($env{'form.origform'} ne 'crtusername') {
  790:             if ($response) {
  791:                $r->print("\n<div>$response</div>".
  792:                          '<br clear="all" />');
  793:             }
  794:         }
  795:         $r->print(&entry_form($defdom,$srch,$forcenewuser,$context,$response,$crstype,$fixeddom));
  796:     }
  797: }
  798: 
  799: sub customrole_javascript {
  800:     my $js = <<"END";
  801: <script type="text/javascript">
  802: // <![CDATA[
  803: 
  804: function setCustomFields() {
  805:     if (document.docustom.customroleaction.length > 0) {
  806:         for (var i=0; i<document.docustom.customroleaction.length; i++) {
  807:             if (document.docustom.customroleaction[i].checked) {
  808:                 if (document.docustom.customroleaction[i].value == 'new') {
  809:                     document.docustom.rolename.selectedIndex = 0;
  810:                 } else {
  811:                     document.docustom.newrolename.value = '';
  812:                 }
  813:             }
  814:         }
  815:     }
  816:     return;
  817: }
  818: 
  819: function setCustomAction(caller) {
  820:     if (document.docustom.customroleaction.length > 0) {
  821:         for (var i=0; i<document.docustom.customroleaction.length; i++) {
  822:             if (document.docustom.customroleaction[i].value == caller) {
  823:                 document.docustom.customroleaction[i].checked = true;
  824:             }
  825:         }
  826:     }
  827:     setCustomFields();
  828:     return;
  829: }
  830: 
  831: // ]]>
  832: </script>
  833: END
  834:     return $js;
  835: }
  836: 
  837: sub entry_form {
  838:     my ($dom,$srch,$forcenewuser,$context,$responsemsg,$crstype,$fixeddom) = @_;
  839:     my ($usertype,$inexact);
  840:     if (ref($srch) eq 'HASH') {
  841:         if (($srch->{'srchin'} eq 'dom') &&
  842:             ($srch->{'srchby'} eq 'uname') &&
  843:             ($srch->{'srchtype'} eq 'exact') &&
  844:             ($srch->{'srchdomain'} ne '') &&
  845:             ($srch->{'srchterm'} ne '')) {
  846:             my (%curr_rules,%got_rules);
  847:             my ($rules,$ruleorder) =
  848:                 &Apache::lonnet::inst_userrules($srch->{'srchdomain'},'username');
  849:             $usertype = &Apache::lonuserutils::check_usertype($srch->{'srchdomain'},$srch->{'srchterm'},$rules,\%curr_rules,\%got_rules);
  850:         } else {
  851:             $inexact = 1;
  852:         }
  853:     }
  854:     my ($cancreate,$noinstd);
  855:     if ($env{'form.action'} eq 'accesslogs') {
  856:         $noinstd = 1;
  857:     } else {
  858:         $cancreate =
  859:             &Apache::lonuserutils::can_create_user($dom,$context,$usertype);
  860:     }
  861:     my ($userpicker,$cansearch) = 
  862:        &Apache::loncommon::user_picker($dom,$srch,$forcenewuser,
  863:                                        'document.crtuser',$cancreate,$usertype,$context,$fixeddom,$noinstd);
  864:     my $srchbutton = &mt('Search');
  865:     if ($env{'form.action'} eq 'singlestudent') {
  866:         $srchbutton = &mt('Search and Enroll');
  867:     } elsif ($env{'form.action'} eq 'accesslogs') {
  868:         $srchbutton = &mt('Search');
  869:     } elsif ($cancreate && $responsemsg ne '' && $inexact) {
  870:         $srchbutton = &mt('Search or Add New User');
  871:     }
  872:     my $output;
  873:     if ($cansearch) {
  874:         $output = <<"ENDBLOCK";
  875: <form action="/adm/createuser" method="post" name="crtuser">
  876: <input type="hidden" name="action" value="$env{'form.action'}" />
  877: <input type="hidden" name="phase" value="get_user_info" />
  878: $userpicker
  879: <input name="userrole" type="button" value="$srchbutton" onclick="javascript:validateEntry(document.crtuser)" />
  880: </form>
  881: ENDBLOCK
  882:     } else {
  883:         $output = '<p>'.$userpicker.'</p>';
  884:     }
  885:     if (($env{'form.phase'} eq '') && ($env{'form.action'} ne 'accesslogs') &&
  886:         (!(($env{'form.action'} eq 'singleuser') && ($context eq 'domain') &&
  887:         (!&Apache::lonnet::allowed('mau',$env{'request.role.domain'}))))) {
  888:         my $defdom=$env{'request.role.domain'};
  889:         my $domform = &Apache::loncommon::select_dom_form($defdom,'srchdomain');
  890:         my %lt=&Apache::lonlocal::texthash(
  891:                   'enro' => 'Enroll one student',
  892:                   'enrm' => 'Enroll one member',
  893:                   'admo' => 'Add/modify a single user',
  894:                   'crea' => 'create new user if required',
  895:                   'uskn' => "username is known",
  896:                   'crnu' => 'Create a new user',
  897:                   'usr'  => 'Username',
  898:                   'dom'  => 'in domain',
  899:                   'enrl' => 'Enroll',
  900:                   'cram'  => 'Create/Modify user',
  901:         );
  902:         my $sellink=&Apache::loncommon::selectstudent_link('crtusername','srchterm','srchdomain');
  903:         my ($title,$buttontext,$showresponse);
  904:         if ($env{'form.action'} eq 'singlestudent') {
  905:             if ($crstype eq 'Community') {
  906:                 $title = $lt{'enrm'};
  907:             } else {
  908:                 $title = $lt{'enro'};
  909:             }
  910:             $buttontext = $lt{'enrl'};
  911:         } else {
  912:             $title = $lt{'admo'};
  913:             $buttontext = $lt{'cram'};
  914:         }
  915:         if ($cancreate) {
  916:             $title .= ' <span class="LC_cusr_subheading">('.$lt{'crea'}.')</span>';
  917:         } else {
  918:             $title .= ' <span class="LC_cusr_subheading">('.$lt{'uskn'}.')</span>';
  919:         }
  920:         if ($env{'form.origform'} eq 'crtusername') {
  921:             $showresponse = $responsemsg;
  922:         }
  923:         $output .= <<"ENDDOCUMENT";
  924: <br />
  925: <form action="/adm/createuser" method="post" name="crtusername">
  926: <input type="hidden" name="action" value="$env{'form.action'}" />
  927: <input type="hidden" name="phase" value="createnewuser" />
  928: <input type="hidden" name="srchtype" value="exact" />
  929: <input type="hidden" name="srchby" value="uname" />
  930: <input type="hidden" name="srchin" value="dom" />
  931: <input type="hidden" name="forcenewuser" value="1" />
  932: <input type="hidden" name="origform" value="crtusername" />
  933: <h3>$title</h3>
  934: $showresponse
  935: <table>
  936:  <tr>
  937:   <td>$lt{'usr'}:</td>
  938:   <td><input type="text" size="15" name="srchterm" /></td>
  939:   <td>&nbsp;$lt{'dom'}:</td><td>$domform</td>
  940:   <td>&nbsp;$sellink&nbsp;</td>
  941:   <td>&nbsp;<input name="userrole" type="submit" value="$buttontext" /></td>
  942:  </tr>
  943: </table>
  944: </form>
  945: ENDDOCUMENT
  946:     }
  947:     return $output;
  948: }
  949: 
  950: sub user_modification_js {
  951:     my ($pjump_def,$dc_setcourse_code,$nondc_setsection_code,$groupslist)=@_;
  952:     
  953:     return <<END;
  954: <script type="text/javascript" language="Javascript">
  955: // <![CDATA[
  956: 
  957:     $pjump_def
  958:     $dc_setcourse_code
  959: 
  960:     function dateset() {
  961:         eval("document.cu."+document.cu.pres_marker.value+
  962:             ".value=document.cu.pres_value.value");
  963:         modalWindow.close();
  964:     }
  965: 
  966:     $nondc_setsection_code
  967: // ]]>
  968: </script>
  969: END
  970: }
  971: 
  972: # =================================================================== Phase two
  973: sub print_user_selection_page {
  974:     my ($r,$response,$srch,$srch_results,$srcharray,$context,$opener_elements,$crstype,$brcrum) = @_;
  975:     my @fields = ('username','domain','lastname','firstname','permanentemail');
  976:     my $sortby = $env{'form.sortby'};
  977: 
  978:     if (!grep(/^\Q$sortby\E$/,@fields)) {
  979:         $sortby = 'lastname';
  980:     }
  981: 
  982:     my ($jsback,$elements) = &crumb_utilities();
  983: 
  984:     my $jscript = (<<ENDSCRIPT);
  985: <script type="text/javascript">
  986: // <![CDATA[
  987: function pickuser(uname,udom) {
  988:     document.usersrchform.seluname.value=uname;
  989:     document.usersrchform.seludom.value=udom;
  990:     document.usersrchform.phase.value="userpicked";
  991:     document.usersrchform.submit();
  992: }
  993: 
  994: $jsback
  995: // ]]>
  996: </script>
  997: ENDSCRIPT
  998: 
  999:     my %lt=&Apache::lonlocal::texthash(
 1000:                                        'usrch'          => "User Search to add/modify roles",
 1001:                                        'stusrch'        => "User Search to enroll student",
 1002:                                        'memsrch'        => "User Search to enroll member",
 1003:                                        'srcva'          => "Search for a user and view access log information",
 1004:                                        'usrvu'          => "User Search to view user roles",
 1005:                                        'usel'           => "Select a user to add/modify roles",
 1006:                                        'suvr'           => "Select a user to view roles",
 1007:                                        'stusel'         => "Select a user to enroll as a student",
 1008:                                        'memsel'         => "Select a user to enroll as a member",
 1009:                                        'vacsel'         => "Select a user to view access log",
 1010:                                        'username'       => "username",
 1011:                                        'domain'         => "domain",
 1012:                                        'lastname'       => "last name",
 1013:                                        'firstname'      => "first name",
 1014:                                        'permanentemail' => "permanent e-mail",
 1015:                                       );
 1016:     if ($context eq 'requestcrs') {
 1017:         $r->print('<div>');
 1018:     } else {
 1019:         my %breadcrumb_text = &singleuser_breadcrumb($crstype,$context,$srch->{'srchdomain'});
 1020:         my $helpitem;
 1021:         if ($env{'form.action'} eq 'singleuser') {
 1022:             $helpitem = 'Course_Change_Privileges';
 1023:         } elsif ($env{'form.action'} eq 'singlestudent') {
 1024:             $helpitem = 'Course_Add_Student';
 1025:         } elsif ($context eq 'author') {
 1026:             $helpitem = 'Author_Change_Privileges';
 1027:         } elsif ($context eq 'domain') {
 1028:             $helpitem = 'Domain_Change_Privileges';
 1029:         }
 1030:         push (@{$brcrum},
 1031:                   {href => "javascript:backPage(document.usersrchform,'','')",
 1032:                    text => $breadcrumb_text{'search'},
 1033:                    faq  => 282,
 1034:                    bug  => 'Instructor Interface',},
 1035:                   {href => "javascript:backPage(document.usersrchform,'get_user_info','select')",
 1036:                    text => $breadcrumb_text{'userpicked'},
 1037:                    faq  => 282,
 1038:                    bug  => 'Instructor Interface',
 1039:                    help => $helpitem}
 1040:                   );
 1041:         $r->print(&Apache::loncommon::start_page('User Management',$jscript,{bread_crumbs => $brcrum}));
 1042:         if ($env{'form.action'} eq 'singleuser') {
 1043:             my $readonly;
 1044:             if (($context eq 'domain') && (!&Apache::lonnet::allowed('mau',$srch->{'srchdomain'}))) {
 1045:                 $readonly = 1;
 1046:                 $r->print("<b>$lt{'usrvu'}</b><br />");
 1047:             } else {
 1048:                 $r->print("<b>$lt{'usrch'}</b><br />");
 1049:             }
 1050:             $r->print(&entry_form($srch->{'srchdomain'},$srch,undef,$context,undef,$crstype));
 1051:             if ($readonly) {
 1052:                 $r->print('<h3>'.$lt{'suvr'}.'</h3>');
 1053:             } else {
 1054:                 $r->print('<h3>'.$lt{'usel'}.'</h3>');
 1055:             }
 1056:         } elsif ($env{'form.action'} eq 'singlestudent') {
 1057:             $r->print($jscript."<b>");
 1058:             if ($crstype eq 'Community') {
 1059:                 $r->print($lt{'memsrch'});
 1060:             } else {
 1061:                 $r->print($lt{'stusrch'});
 1062:             }
 1063:             $r->print("</b><br />");
 1064:             $r->print(&entry_form($srch->{'srchdomain'},$srch,undef,$context,undef,$crstype));
 1065:             $r->print('</form><h3>');
 1066:             if ($crstype eq 'Community') {
 1067:                 $r->print($lt{'memsel'});
 1068:             } else {
 1069:                 $r->print($lt{'stusel'});
 1070:             }
 1071:             $r->print('</h3>');
 1072:         } elsif ($env{'form.action'} eq 'accesslogs') {
 1073:             $r->print("<b>$lt{'srcva'}</b><br />");
 1074:             $r->print(&entry_form($srch->{'srchdomain'},$srch,undef,$context,undef,undef,1));
 1075:             $r->print('<h3>'.$lt{'vacsel'}.'</h3>');
 1076:         }
 1077:     }
 1078:     $r->print('<form name="usersrchform" method="post" action="">'.
 1079:               &Apache::loncommon::start_data_table()."\n".
 1080:               &Apache::loncommon::start_data_table_header_row()."\n".
 1081:               ' <th> </th>'."\n");
 1082:     foreach my $field (@fields) {
 1083:         $r->print(' <th><a href="javascript:document.usersrchform.sortby.value='.
 1084:                   "'".$field."'".';document.usersrchform.submit();">'.
 1085:                   $lt{$field}.'</a></th>'."\n");
 1086:     }
 1087:     $r->print(&Apache::loncommon::end_data_table_header_row());
 1088: 
 1089:     my @sorted_users = sort {
 1090:         lc($srch_results->{$a}->{$sortby})   cmp lc($srch_results->{$b}->{$sortby})
 1091:             ||
 1092:         lc($srch_results->{$a}->{lastname})  cmp lc($srch_results->{$b}->{lastname})
 1093:             ||
 1094:         lc($srch_results->{$a}->{firstname}) cmp lc($srch_results->{$b}->{firstname})
 1095: 	    ||
 1096: 	lc($a) cmp lc($b)
 1097:         } (keys(%$srch_results));
 1098: 
 1099:     foreach my $user (@sorted_users) {
 1100:         my ($uname,$udom) = split(/:/,$user);
 1101:         my $onclick;
 1102:         if ($context eq 'requestcrs') {
 1103:             $onclick =
 1104:                 'onclick="javascript:gochoose('."'$uname','$udom',".
 1105:                                                "'$srch_results->{$user}->{firstname}',".
 1106:                                                "'$srch_results->{$user}->{lastname}',".
 1107:                                                "'$srch_results->{$user}->{permanentemail}'".');"';
 1108:         } else {
 1109:             $onclick =
 1110:                 ' onclick="javascript:pickuser('."'".$uname."'".','."'".$udom."'".');"';
 1111:         }
 1112:         $r->print(&Apache::loncommon::start_data_table_row().
 1113:                   '<td><input type="button" name="seluser" value="'.&mt('Select').'" '.
 1114:                   $onclick.' /></td>'.
 1115:                   '<td><tt>'.$uname.'</tt></td>'.
 1116:                   '<td><tt>'.$udom.'</tt></td>');
 1117:         foreach my $field ('lastname','firstname','permanentemail') {
 1118:             $r->print('<td>'.$srch_results->{$user}->{$field}.'</td>');
 1119:         }
 1120:         $r->print(&Apache::loncommon::end_data_table_row());
 1121:     }
 1122:     $r->print(&Apache::loncommon::end_data_table().'<br /><br />');
 1123:     if (ref($srcharray) eq 'ARRAY') {
 1124:         foreach my $item (@{$srcharray}) {
 1125:             $r->print('<input type="hidden" name="'.$item.'" value="'.$env{'form.'.$item}.'" />'."\n");
 1126:         }
 1127:     }
 1128:     $r->print(' <input type="hidden" name="sortby" value="'.$sortby.'" />'."\n".
 1129:               ' <input type="hidden" name="seluname" value="" />'."\n".
 1130:               ' <input type="hidden" name="seludom" value="" />'."\n".
 1131:               ' <input type="hidden" name="currstate" value="select" />'."\n".
 1132:               ' <input type="hidden" name="phase" value="get_user_info" />'."\n".
 1133:               ' <input type="hidden" name="action" value="'.$env{'form.action'}.'" />'."\n");
 1134:     if ($context eq 'requestcrs') {
 1135:         $r->print($opener_elements.'</form></div>');
 1136:     } else {
 1137:         $r->print($response.'</form>');
 1138:     }
 1139: }
 1140: 
 1141: sub print_user_query_page {
 1142:     my ($r,$caller,$brcrum) = @_;
 1143: # FIXME - this is for a network-wide name search (similar to catalog search)
 1144: # To use frames with similar behavior to catalog/portfolio search.
 1145: # To be implemented. 
 1146:     return;
 1147: }
 1148: 
 1149: sub print_user_modification_page {
 1150:     my ($r,$ccuname,$ccdomain,$srch,$response,$context,$permission,$crstype,
 1151:         $brcrum,$showcredits) = @_;
 1152:     if (($ccuname eq '') || ($ccdomain eq '')) {
 1153:         my $usermsg = &mt('No username and/or domain provided.');
 1154:         $env{'form.phase'} = '';
 1155: 	&print_username_entry_form($r,$context,$usermsg,'','',$crstype,$brcrum,
 1156:                                    $permission);
 1157:         return;
 1158:     }
 1159:     my ($form,$formname);
 1160:     if ($env{'form.action'} eq 'singlestudent') {
 1161:         $form = 'document.enrollstudent';
 1162:         $formname = 'enrollstudent';
 1163:     } else {
 1164:         $form = 'document.cu';
 1165:         $formname = 'cu';
 1166:     }
 1167:     my %abv_auth = &auth_abbrev();
 1168:     my (%rulematch,%inst_results,$newuser,%alerts,%curr_rules,%got_rules);
 1169:     my $uhome=&Apache::lonnet::homeserver($ccuname,$ccdomain);
 1170:     if ($uhome eq 'no_host') {
 1171:         my $usertype;
 1172:         my ($rules,$ruleorder) =
 1173:             &Apache::lonnet::inst_userrules($ccdomain,'username');
 1174:             $usertype =
 1175:                 &Apache::lonuserutils::check_usertype($ccdomain,$ccuname,$rules,
 1176:                                                       \%curr_rules,\%got_rules);
 1177:         my $cancreate =
 1178:             &Apache::lonuserutils::can_create_user($ccdomain,$context,
 1179:                                                    $usertype);
 1180:         if (!$cancreate) {
 1181:             my $helplink = 'javascript:helpMenu('."'display'".')';
 1182:             my %usertypetext = (
 1183:                 official   => 'institutional',
 1184:                 unofficial => 'non-institutional',
 1185:             );
 1186:             my $response;
 1187:             if ($env{'form.origform'} eq 'crtusername') {
 1188:                 $response = '<span class="LC_warning">'.
 1189:                             &mt('No match found for the username [_1] in LON-CAPA domain: [_2]',
 1190:                                 '<b>'.$ccuname.'</b>',$ccdomain).
 1191:                             '</span><br />';
 1192:             }
 1193:             $response .= '<p class="LC_warning">'
 1194:                         .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
 1195:                         .' ';
 1196:             if ($context eq 'domain') {
 1197:                 $response .= &mt('Please contact a [_1] for assistance.',
 1198:                                  &Apache::lonnet::plaintext('dc'));
 1199:             } else {
 1200:                 $response .= &mt('Please contact the [_1]helpdesk[_2] for assistance.'
 1201:                                 ,'<a href="'.$helplink.'">','</a>');
 1202:             }
 1203:             $response .= '</p><br />';
 1204:             $env{'form.phase'} = '';
 1205:             &print_username_entry_form($r,$context,$response,undef,undef,$crstype,$brcrum,
 1206:                                        $permission);
 1207:             return;
 1208:         }
 1209:         $newuser = 1;
 1210:         my $checkhash;
 1211:         my $checks = { 'username' => 1 };
 1212:         $checkhash->{$ccuname.':'.$ccdomain} = { 'newuser' => $newuser };
 1213:         &Apache::loncommon::user_rule_check($checkhash,$checks,
 1214:             \%alerts,\%rulematch,\%inst_results,\%curr_rules,\%got_rules);
 1215:         if (ref($alerts{'username'}) eq 'HASH') {
 1216:             if (ref($alerts{'username'}{$ccdomain}) eq 'HASH') {
 1217:                 my $domdesc =
 1218:                     &Apache::lonnet::domain($ccdomain,'description');
 1219:                 if ($alerts{'username'}{$ccdomain}{$ccuname}) {
 1220:                     my $userchkmsg;
 1221:                     if (ref($curr_rules{$ccdomain}) eq 'HASH') {  
 1222:                         $userchkmsg = 
 1223:                             &Apache::loncommon::instrule_disallow_msg('username',
 1224:                                                                  $domdesc,1).
 1225:                         &Apache::loncommon::user_rule_formats($ccdomain,
 1226:                             $domdesc,$curr_rules{$ccdomain}{'username'},
 1227:                             'username');
 1228:                     }
 1229:                     $env{'form.phase'} = '';
 1230:                     &print_username_entry_form($r,$context,$userchkmsg,undef,undef,$crstype,$brcrum,
 1231:                                                $permission);
 1232:                     return;
 1233:                 }
 1234:             }
 1235:         }
 1236:     } else {
 1237:         $newuser = 0;
 1238:     }
 1239:     if ($response) {
 1240:         $response = '<br />'.$response;
 1241:     }
 1242: 
 1243:     my $pjump_def = &Apache::lonhtmlcommon::pjump_javascript_definition();
 1244:     my $dc_setcourse_code = '';
 1245:     my $nondc_setsection_code = '';                                        
 1246:     my %loaditem;
 1247: 
 1248:     my $groupslist = &Apache::lonuserutils::get_groupslist();
 1249: 
 1250:     my $js = &validation_javascript($context,$ccdomain,$pjump_def,$crstype,
 1251:                                $groupslist,$newuser,$formname,\%loaditem);
 1252:     my %breadcrumb_text = &singleuser_breadcrumb($crstype,$context,$ccdomain);
 1253:     my $helpitem = 'Course_Change_Privileges';
 1254:     if ($env{'form.action'} eq 'singlestudent') {
 1255:         $helpitem = 'Course_Add_Student';
 1256:     } elsif ($context eq 'author') {
 1257:         $helpitem = 'Author_Change_Privileges';
 1258:     } elsif ($context eq 'domain') {
 1259:         $helpitem = 'Domain_Change_Privileges';
 1260:     }
 1261:     push (@{$brcrum},
 1262:         {href => "javascript:backPage($form)",
 1263:          text => $breadcrumb_text{'search'},
 1264:          faq  => 282,
 1265:          bug  => 'Instructor Interface',});
 1266:     if ($env{'form.phase'} eq 'userpicked') {
 1267:        push(@{$brcrum},
 1268:               {href => "javascript:backPage($form,'get_user_info','select')",
 1269:                text => $breadcrumb_text{'userpicked'},
 1270:                faq  => 282,
 1271:                bug  => 'Instructor Interface',});
 1272:     }
 1273:     push(@{$brcrum},
 1274:             {href => "javascript:backPage($form,'$env{'form.phase'}','modify')",
 1275:              text => $breadcrumb_text{'modify'},
 1276:              faq  => 282,
 1277:              bug  => 'Instructor Interface',
 1278:              help => $helpitem});
 1279:     my $args = {'add_entries'           => \%loaditem,
 1280:                 'bread_crumbs'          => $brcrum,
 1281:                 'bread_crumbs_component' => 'User Management'};
 1282:     if ($env{'form.popup'}) {
 1283:         $args->{'no_nav_bar'} = 1;
 1284:     }
 1285:     my $start_page =
 1286:         &Apache::loncommon::start_page('User Management',$js,$args);
 1287: 
 1288:     my $forminfo =<<"ENDFORMINFO";
 1289: <form action="/adm/createuser" method="post" name="$formname">
 1290: <input type="hidden" name="phase" value="update_user_data" />
 1291: <input type="hidden" name="ccuname" value="$ccuname" />
 1292: <input type="hidden" name="ccdomain" value="$ccdomain" />
 1293: <input type="hidden" name="pres_value"  value="" />
 1294: <input type="hidden" name="pres_type"   value="" />
 1295: <input type="hidden" name="pres_marker" value="" />
 1296: ENDFORMINFO
 1297:     my (%inccourses,$roledom,$defaultcredits);
 1298:     if ($context eq 'course') {
 1299:         $inccourses{$env{'request.course.id'}}=1;
 1300:         $roledom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 1301:         if ($showcredits) {
 1302:             $defaultcredits = &Apache::lonuserutils::get_defaultcredits();
 1303:         }
 1304:     } elsif ($context eq 'author') {
 1305:         $roledom = $env{'request.role.domain'};
 1306:     } elsif ($context eq 'domain') {
 1307:         foreach my $key (keys(%env)) {
 1308:             $roledom = $env{'request.role.domain'};
 1309:             if ($key=~/^user\.priv\.cm\.\/($roledom)\/($match_username)/) {
 1310:                 $inccourses{$1.'_'.$2}=1;
 1311:             }
 1312:         }
 1313:     } else {
 1314:         foreach my $key (keys(%env)) {
 1315: 	    if ($key=~/^user\.priv\.cm\.\/($match_domain)\/($match_username)/) {
 1316: 	        $inccourses{$1.'_'.$2}=1;
 1317:             }
 1318:         }
 1319:     }
 1320:     my $title = '';
 1321:     if ($newuser) {
 1322:         my ($portfolioform,$domroleform);
 1323:         if ((&Apache::lonnet::allowed('mpq',$env{'request.role.domain'})) ||
 1324:             (&Apache::lonnet::allowed('mut',$env{'request.role.domain'}))) {
 1325:             # Current user has quota or user tools modification privileges
 1326:             $portfolioform = '<br />'.&user_quotas($ccuname,$ccdomain);
 1327:         }
 1328:         if ((&Apache::lonnet::allowed('cau',$env{'request.role.domain'})) &&
 1329:             ($ccdomain eq $env{'request.role.domain'})) {
 1330:             $domroleform = '<br />'.&domainrole_req($ccuname,$ccdomain);
 1331:         }
 1332:         &initialize_authen_forms($ccdomain,$formname);
 1333:         my %lt=&Apache::lonlocal::texthash(
 1334:                 'lg'             => 'Login Data',
 1335:                 'hs'             => "Home Server",
 1336:         );
 1337: 	$r->print(<<ENDTITLE);
 1338: $start_page
 1339: $response
 1340: $forminfo
 1341: <script type="text/javascript" language="Javascript">
 1342: // <![CDATA[
 1343: $loginscript
 1344: // ]]>
 1345: </script>
 1346: <input type='hidden' name='makeuser' value='1' />
 1347: ENDTITLE
 1348:         if ($env{'form.action'} eq 'singlestudent') {
 1349:             if ($crstype eq 'Community') {
 1350:                 $title = &mt('Create New User [_1] in domain [_2] as a member',
 1351:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1352:             } else {
 1353:                 $title = &mt('Create New User [_1] in domain [_2] as a student',
 1354:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1355:             }
 1356:         } else {
 1357:                 $title = &mt('Create New User [_1] in domain [_2]',
 1358:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1359:         }
 1360:         $r->print('<h2>'.$title.'</h2>'."\n");
 1361:         $r->print('<div class="LC_left_float">');
 1362:         $r->print(&personal_data_display($ccuname,$ccdomain,$newuser,$context,
 1363:                                          $inst_results{$ccuname.':'.$ccdomain}));
 1364:         # Option to disable student/employee ID conflict checking not offerred for new users.
 1365:         my ($home_server_pick,$numlib) = 
 1366:             &Apache::loncommon::home_server_form_item($ccdomain,'hserver',
 1367:                                                       'default','hide');
 1368:         if ($numlib > 1) {
 1369:             $r->print("
 1370: <br />
 1371: $lt{'hs'}: $home_server_pick
 1372: <br />");
 1373:         } else {
 1374:             $r->print($home_server_pick);
 1375:         }
 1376:         if (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) {
 1377:             $r->print('<br /><h3>'.
 1378:                       &mt('User Can Request Creation of Courses/Communities in this Domain?').'</h3>'.
 1379:                       &Apache::loncommon::start_data_table().
 1380:                       &build_tools_display($ccuname,$ccdomain,
 1381:                                            'requestcourses').
 1382:                       &Apache::loncommon::end_data_table());
 1383:         }
 1384:         $r->print('</div>'."\n".'<div class="LC_left_float"><h3>'.
 1385:                   $lt{'lg'}.'</h3>');
 1386:         my ($fixedauth,$varauth,$authmsg); 
 1387:         if (ref($rulematch{$ccuname.':'.$ccdomain}) eq 'HASH') {
 1388:             my $matchedrule = $rulematch{$ccuname.':'.$ccdomain}{'username'};
 1389:             my ($rules,$ruleorder) = 
 1390:                 &Apache::lonnet::inst_userrules($ccdomain,'username');
 1391:             if (ref($rules) eq 'HASH') {
 1392:                 if (ref($rules->{$matchedrule}) eq 'HASH') {
 1393:                     my $authtype = $rules->{$matchedrule}{'authtype'};
 1394:                     if ($authtype !~ /^(krb4|krb5|int|fsys|loc)$/) {
 1395:                         $r->print(&Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc));
 1396:                     } else { 
 1397:                         my $authparm = $rules->{$matchedrule}{'authparm'};
 1398:                         $authmsg = $rules->{$matchedrule}{'authmsg'};
 1399:                         if ($authtype =~ /^krb(4|5)$/) {
 1400:                             my $ver = $1;
 1401:                             if ($authparm ne '') {
 1402:                                 $fixedauth = <<"KERB"; 
 1403: <input type="hidden" name="login" value="krb" />
 1404: <input type="hidden" name="krbver" value="$ver" />
 1405: <input type="hidden" name="krbarg" value="$authparm" />
 1406: KERB
 1407:                             }
 1408:                         } else {
 1409:                             $fixedauth = 
 1410: '<input type="hidden" name="login" value="'.$authtype.'" />'."\n";
 1411:                             if ($rules->{$matchedrule}{'authparmfixed'}) {
 1412:                                 $fixedauth .=    
 1413: '<input type="hidden" name="'.$authtype.'arg" value="'.$authparm.'" />'."\n";
 1414:                             } else {
 1415:                                 if ($authtype eq 'int') {
 1416:                                     $varauth = '<br />'.
 1417: &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>';
 1418:                                 } elsif ($authtype eq 'loc') {
 1419:                                     $varauth = '<br />'.
 1420: &mt('[_1] Local Authentication with argument [_2]','','<input type="text" name="'.$authtype.'arg" value="" />')."\n";
 1421:                                 } else {
 1422:                                     $varauth =
 1423: '<input type="text" name="'.$authtype.'arg" value="" />'."\n";
 1424:                                 }
 1425:                             }
 1426:                         }
 1427:                     }
 1428:                 } else {
 1429:                     $r->print(&Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc));
 1430:                 }
 1431:             }
 1432:             if ($authmsg) {
 1433:                 $r->print(<<ENDAUTH);
 1434: $fixedauth
 1435: $authmsg
 1436: $varauth
 1437: ENDAUTH
 1438:             }
 1439:         } else {
 1440:             $r->print(&Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc)); 
 1441:         }
 1442:         $r->print($portfolioform.$domroleform);
 1443:         if ($env{'form.action'} eq 'singlestudent') {
 1444:             $r->print(&date_sections_select($context,$newuser,$formname,
 1445:                                             $permission,$crstype,$ccuname,
 1446:                                             $ccdomain,$showcredits));
 1447:         }
 1448:         $r->print('</div><div class="LC_clear_float_footer"></div>');
 1449:     } else { # user already exists
 1450: 	$r->print($start_page.$forminfo);
 1451:         if ($env{'form.action'} eq 'singlestudent') {
 1452:             if ($crstype eq 'Community') {
 1453:                 $title = &mt('Enroll one member: [_1] in domain [_2]',
 1454:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1455:             } else {
 1456:                 $title = &mt('Enroll one student: [_1] in domain [_2]',
 1457:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1458:             }
 1459:         } else {
 1460:             if ($permission->{'cusr'}) {
 1461:                 $title = &mt('Modify existing user: [_1] in domain [_2]',
 1462:                              '"'.$ccuname.'"','"'.$ccdomain.'"');
 1463:             } else {
 1464:                 $title = &mt('Existing user: [_1] in domain [_2]',
 1465:                              '"'.$ccuname.'"','"'.$ccdomain.'"');
 1466:             }
 1467:         }
 1468:         $r->print('<h2>'.$title.'</h2>'."\n");
 1469:         $r->print('<div class="LC_left_float">');
 1470:         $r->print(&personal_data_display($ccuname,$ccdomain,$newuser,$context,
 1471:                                          $inst_results{$ccuname.':'.$ccdomain}));
 1472:         if ((&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) ||
 1473:             (&Apache::lonnet::allowed('udp',$env{'request.role.domain'}))) {
 1474:             $r->print('<br /><h3>'.&mt('User Can Request Creation of Courses/Communities in this Domain?').'</h3>'.
 1475:                       &Apache::loncommon::start_data_table());
 1476:             if ($env{'request.role.domain'} eq $ccdomain) {
 1477:                 $r->print(&build_tools_display($ccuname,$ccdomain,'requestcourses'));
 1478:             } else {
 1479:                 $r->print(&coursereq_externaluser($ccuname,$ccdomain,
 1480:                                                   $env{'request.role.domain'}));
 1481:             }
 1482:             $r->print(&Apache::loncommon::end_data_table());
 1483:         }
 1484:         $r->print('</div>');
 1485:         my @order = ('auth','quota','tools','requestauthor');
 1486:         my %user_text;
 1487:         my ($isadv,$isauthor) = 
 1488:             &Apache::lonnet::is_advanced_user($ccdomain,$ccuname);
 1489:         if ((!$isauthor) && 
 1490:             ((&Apache::lonnet::allowed('cau',$env{'request.role.domain'})) ||
 1491:              (&Apache::lonnet::allowed('udp',$env{'request.role.domain'}))) &&
 1492:              ($env{'request.role.domain'} eq $ccdomain)) {
 1493:             $user_text{'requestauthor'} = &domainrole_req($ccuname,$ccdomain);
 1494:         }
 1495:         $user_text{'auth'} =  &user_authentication($ccuname,$ccdomain,$formname);
 1496:         if ((&Apache::lonnet::allowed('mpq',$ccdomain)) ||
 1497:             (&Apache::lonnet::allowed('mut',$ccdomain)) ||
 1498:             (&Apache::lonnet::allowed('udp',$ccdomain))) {
 1499:             # Current user has quota modification privileges
 1500:             $user_text{'quota'} = &user_quotas($ccuname,$ccdomain);
 1501:         }
 1502:         if (!&Apache::lonnet::allowed('mpq',$ccdomain)) {
 1503:             if (&Apache::lonnet::allowed('mpq',$env{'request.role.domain'})) {
 1504:                 my %lt=&Apache::lonlocal::texthash(
 1505:                     'dska'  => "Disk quotas for user's portfolio and Authoring Space",
 1506:                     'youd'  => "You do not have privileges to modify the portfolio and/or Authoring Space quotas for this user.",
 1507:                     'ichr'  => "If a change is required, contact a domain coordinator for the domain",
 1508:                 );
 1509:                 $user_text{'quota'} = <<ENDNOPORTPRIV;
 1510: <h3>$lt{'dska'}</h3>
 1511: $lt{'youd'} $lt{'ichr'}: $ccdomain
 1512: ENDNOPORTPRIV
 1513:             }
 1514:         }
 1515:         if (!&Apache::lonnet::allowed('mut',$ccdomain)) {
 1516:             if (&Apache::lonnet::allowed('mut',$env{'request.role.domain'})) {
 1517:                 my %lt=&Apache::lonlocal::texthash(
 1518:                     'utav'  => "User Tools Availability",
 1519:                     'yodo'  => "You do not have privileges to modify Portfolio, Blog, WebDAV, or Personal Information Page settings for this user.",
 1520:                     'ifch'  => "If a change is required, contact a domain coordinator for the domain",
 1521:                 );
 1522:                 $user_text{'tools'} = <<ENDNOTOOLSPRIV;
 1523: <h3>$lt{'utav'}</h3>
 1524: $lt{'yodo'} $lt{'ifch'}: $ccdomain
 1525: ENDNOTOOLSPRIV
 1526:             }
 1527:         }
 1528:         my $gotdiv = 0; 
 1529:         foreach my $item (@order) {
 1530:             if ($user_text{$item} ne '') {
 1531:                 unless ($gotdiv) {
 1532:                     $r->print('<div class="LC_left_float">');
 1533:                     $gotdiv = 1;
 1534:                 }
 1535:                 $r->print('<br />'.$user_text{$item});
 1536:             }
 1537:         }
 1538:         if ($env{'form.action'} eq 'singlestudent') {
 1539:             unless ($gotdiv) {
 1540:                 $r->print('<div class="LC_left_float">');
 1541:             }
 1542:             my $credits;
 1543:             if ($showcredits) {
 1544:                 $credits = &get_user_credits($ccuname,$ccdomain,$defaultcredits);
 1545:                 if ($credits eq '') {
 1546:                     $credits = $defaultcredits;
 1547:                 }
 1548:             }
 1549:             $r->print(&date_sections_select($context,$newuser,$formname,
 1550:                                             $permission,$crstype,$ccuname,
 1551:                                             $ccdomain,$showcredits));
 1552:         }
 1553:         if ($gotdiv) {
 1554:             $r->print('</div><div class="LC_clear_float_footer"></div>');
 1555:         }
 1556:         my $statuses;
 1557:         if (($context eq 'domain') && (&Apache::lonnet::allowed('udp',$ccdomain)) &&
 1558:             (!&Apache::lonnet::allowed('mau',$ccdomain))) {
 1559:             $statuses = ['active'];
 1560:         } elsif (($context eq 'course') && ((&Apache::lonnet::allowed('vcl',$env{'request.course.id'})) ||
 1561:                  ($env{'request.course.sec'} &&
 1562:                   &Apache::lonnet::allowed('vcl',$env{'request.course.id'}.'/'.$env{'request.course.sec'})))) {
 1563:             $statuses = ['active'];
 1564:         }
 1565:         if ($env{'form.action'} ne 'singlestudent') {
 1566:             &display_existing_roles($r,$ccuname,$ccdomain,\%inccourses,$context,
 1567:                                     $roledom,$crstype,$showcredits,$statuses);
 1568:         }
 1569:     } ## End of new user/old user logic
 1570:     if ($env{'form.action'} eq 'singlestudent') {
 1571:         my $btntxt;
 1572:         if ($crstype eq 'Community') {
 1573:             $btntxt = &mt('Enroll Member');
 1574:         } else {
 1575:             $btntxt = &mt('Enroll Student');
 1576:         }
 1577:         $r->print('<br /><input type="button" value="'.$btntxt.'" onclick="setSections(this.form)" />'."\n");
 1578:     } elsif ($permission->{'cusr'}) {
 1579:         $r->print('<div class="LC_left_float">'.
 1580:                   '<fieldset><legend>'.&mt('Add Roles').'</legend>');
 1581:         my $addrolesdisplay = 0;
 1582:         if ($context eq 'domain' || $context eq 'author') {
 1583:             $addrolesdisplay = &new_coauthor_roles($r,$ccuname,$ccdomain);
 1584:         }
 1585:         if ($context eq 'domain') {
 1586:             my $add_domainroles = &new_domain_roles($r,$ccdomain);
 1587:             if (!$addrolesdisplay) {
 1588:                 $addrolesdisplay = $add_domainroles;
 1589:             }
 1590:             $r->print(&course_level_dc($env{'request.role.domain'},$showcredits));
 1591:             $r->print('</fieldset></div><div class="LC_clear_float_footer"></div>'.
 1592:                       '<br /><input type="button" value="'.&mt('Save').'" onclick="setCourse()" />'."\n");
 1593:         } elsif ($context eq 'author') {
 1594:             if ($addrolesdisplay) {
 1595:                 $r->print('</fieldset></div><div class="LC_clear_float_footer"></div>'.
 1596:                           '<br /><input type="button" value="'.&mt('Save').'"');
 1597:                 if ($newuser) {
 1598:                     $r->print(' onclick="auth_check()" \>'."\n");
 1599:                 } else {
 1600:                     $r->print('onclick="this.form.submit()" \>'."\n");
 1601:                 }
 1602:             } else {
 1603:                 $r->print('</fieldset></div>'.
 1604:                           '<div class="LC_clear_float_footer"></div>'.
 1605:                           '<br /><a href="javascript:backPage(document.cu)">'.
 1606:                           &mt('Back to previous page').'</a>');
 1607:             }
 1608:         } else {
 1609:             $r->print(&course_level_table(\%inccourses,$showcredits,$defaultcredits));
 1610:             $r->print('</fieldset></div><div class="LC_clear_float_footer"></div>'.
 1611:                       '<br /><input type="button" value="'.&mt('Save').'" onclick="setSections(this.form)" />'."\n");
 1612:         }
 1613:     }
 1614:     $r->print(&Apache::lonhtmlcommon::echo_form_input(['phase','userrole','ccdomain','prevphase','currstate','ccuname','ccdomain']));
 1615:     $r->print('<input type="hidden" name="currstate" value="" />');
 1616:     $r->print('<input type="hidden" name="prevphase" value="'.$env{'form.phase'}.'" /></form><br /><br />');
 1617:     return;
 1618: }
 1619: 
 1620: sub singleuser_breadcrumb {
 1621:     my ($crstype,$context,$domain) = @_;
 1622:     my %breadcrumb_text;
 1623:     if ($env{'form.action'} eq 'singlestudent') {
 1624:         if ($crstype eq 'Community') {
 1625:             $breadcrumb_text{'search'} = 'Enroll a member';
 1626:         } else {
 1627:             $breadcrumb_text{'search'} = 'Enroll a student';
 1628:         }
 1629:         $breadcrumb_text{'userpicked'} = 'Select a user';
 1630:         $breadcrumb_text{'modify'} = 'Set section/dates';
 1631:     } elsif ($env{'form.action'} eq 'accesslogs') {
 1632:         $breadcrumb_text{'search'} = 'View access logs for a user';
 1633:         $breadcrumb_text{'userpicked'} = 'Select a user';
 1634:         $breadcrumb_text{'activity'} = 'Activity';
 1635:     } elsif (($env{'form.action'} eq 'singleuser') && ($context eq 'domain') &&
 1636:              (!&Apache::lonnet::allowed('mau',$domain))) {
 1637:         $breadcrumb_text{'search'} = "View user's roles";
 1638:         $breadcrumb_text{'userpicked'} = 'Select a user';
 1639:         $breadcrumb_text{'modify'} = 'User roles';
 1640:     } else {
 1641:         $breadcrumb_text{'search'} = 'Create/modify a user';
 1642:         $breadcrumb_text{'userpicked'} = 'Select a user';
 1643:         $breadcrumb_text{'modify'} = 'Set user role';
 1644:     }
 1645:     return %breadcrumb_text;
 1646: }
 1647: 
 1648: sub date_sections_select {
 1649:     my ($context,$newuser,$formname,$permission,$crstype,$ccuname,$ccdomain,
 1650:         $showcredits) = @_;
 1651:     my $credits;
 1652:     if ($showcredits) {
 1653:         my $defaultcredits = &Apache::lonuserutils::get_defaultcredits();
 1654:         $credits = &get_user_credits($ccuname,$ccdomain,$defaultcredits);
 1655:         if ($credits eq '') {
 1656:             $credits = $defaultcredits;
 1657:         }
 1658:     }
 1659:     my $cid = $env{'request.course.id'};
 1660:     my ($cnum,$cdom) = &Apache::lonuserutils::get_course_identity($cid);
 1661:     my $date_table = '<h3>'.&mt('Starting and Ending Dates').'</h3>'."\n".
 1662:         &Apache::lonuserutils::date_setting_table(undef,undef,$context,
 1663:                                                   undef,$formname,$permission);
 1664:     my $rowtitle = 'Section';
 1665:     my $secbox = '<h3>'.&mt('Section and Credits').'</h3>'."\n".
 1666:         &Apache::lonuserutils::section_picker($cdom,$cnum,'st',$rowtitle,
 1667:                                               $permission,$context,'',$crstype,
 1668:                                               $showcredits,$credits);
 1669:     my $output = $date_table.$secbox;
 1670:     return $output;
 1671: }
 1672: 
 1673: sub validation_javascript {
 1674:     my ($context,$ccdomain,$pjump_def,$crstype,$groupslist,$newuser,$formname,
 1675:         $loaditem) = @_;
 1676:     my $dc_setcourse_code = '';
 1677:     my $nondc_setsection_code = '';
 1678:     if ($context eq 'domain') {
 1679:         my $dcdom = $env{'request.role.domain'};
 1680:         $loaditem->{'onload'} = "document.cu.coursedesc.value='';";
 1681:         $dc_setcourse_code = 
 1682:             &Apache::lonuserutils::dc_setcourse_js('cu','singleuser',$context);
 1683:     } else {
 1684:         my $checkauth; 
 1685:         if (($newuser) || (&Apache::lonnet::allowed('mau',$ccdomain))) {
 1686:             $checkauth = 1;
 1687:         }
 1688:         if ($context eq 'course') {
 1689:             $nondc_setsection_code =
 1690:                 &Apache::lonuserutils::setsections_javascript($formname,$groupslist,
 1691:                                                               undef,$checkauth,
 1692:                                                               $crstype);
 1693:         }
 1694:         if ($checkauth) {
 1695:             $nondc_setsection_code .= 
 1696:                 &Apache::lonuserutils::verify_authen($formname,$context);
 1697:         }
 1698:     }
 1699:     my $js = &user_modification_js($pjump_def,$dc_setcourse_code,
 1700:                                    $nondc_setsection_code,$groupslist);
 1701:     my ($jsback,$elements) = &crumb_utilities();
 1702:     $js .= "\n".
 1703:            '<script type="text/javascript">'."\n".
 1704:            '// <![CDATA['."\n".
 1705:            $jsback."\n".
 1706:            '// ]]>'."\n".
 1707:            '</script>'."\n";
 1708:     return $js;
 1709: }
 1710: 
 1711: sub display_existing_roles {
 1712:     my ($r,$ccuname,$ccdomain,$inccourses,$context,$roledom,$crstype,
 1713:         $showcredits,$statuses) = @_;
 1714:     my $now=time;
 1715:     my $showall = 1;
 1716:     my ($showexpired,$showactive);
 1717:     if ((ref($statuses) eq 'ARRAY') && (@{$statuses} > 0)) {
 1718:         $showall = 0;
 1719:         if (grep(/^expired$/,@{$statuses})) {
 1720:             $showexpired = 1;
 1721:         }
 1722:         if (grep(/^active$/,@{$statuses})) {
 1723:             $showactive = 1;
 1724:         }
 1725:         if ($showexpired && $showactive) {
 1726:             $showall = 1;
 1727:         }
 1728:     }
 1729:     my %lt=&Apache::lonlocal::texthash(
 1730:                     'rer'  => "Existing Roles",
 1731:                     'rev'  => "Revoke",
 1732:                     'del'  => "Delete",
 1733:                     'ren'  => "Re-Enable",
 1734:                     'rol'  => "Role",
 1735:                     'ext'  => "Extent",
 1736:                     'crd'  => "Credits",
 1737:                     'sta'  => "Start",
 1738:                     'end'  => "End",
 1739:                                        );
 1740:     my (%rolesdump,%roletext,%sortrole,%roleclass,%rolepriv);
 1741:     if ($context eq 'course' || $context eq 'author') {
 1742:         my @roles = &Apache::lonuserutils::roles_by_context($context,1,$crstype);
 1743:         my %roleshash = 
 1744:             &Apache::lonnet::get_my_roles($ccuname,$ccdomain,'userroles',
 1745:                               ['active','previous','future'],\@roles,$roledom,1);
 1746:         foreach my $key (keys(%roleshash)) {
 1747:             my ($start,$end) = split(':',$roleshash{$key});
 1748:             next if ($start eq '-1' || $end eq '-1');
 1749:             my ($rnum,$rdom,$role,$sec) = split(':',$key);
 1750:             if ($context eq 'course') {
 1751:                 next unless (($rnum eq $env{'course.'.$env{'request.course.id'}.'.num'})
 1752:                              && ($rdom eq $env{'course.'.$env{'request.course.id'}.'.domain'}));
 1753:             } elsif ($context eq 'author') {
 1754:                 next unless (($rnum eq $env{'user.name'}) && ($rdom eq $env{'request.role.domain'}));
 1755:             }
 1756:             my ($newkey,$newvalue,$newrole);
 1757:             $newkey = '/'.$rdom.'/'.$rnum;
 1758:             if ($sec ne '') {
 1759:                 $newkey .= '/'.$sec;
 1760:             }
 1761:             $newvalue = $role;
 1762:             if ($role =~ /^cr/) {
 1763:                 $newrole = 'cr';
 1764:             } else {
 1765:                 $newrole = $role;
 1766:             }
 1767:             $newkey .= '_'.$newrole;
 1768:             if ($start ne '' && $end ne '') {
 1769:                 $newvalue .= '_'.$end.'_'.$start;
 1770:             } elsif ($end ne '') {
 1771:                 $newvalue .= '_'.$end;
 1772:             }
 1773:             $rolesdump{$newkey} = $newvalue;
 1774:         }
 1775:     } else {
 1776:         %rolesdump=&Apache::lonnet::dump('roles',$ccdomain,$ccuname);
 1777:     }
 1778:     # Build up table of user roles to allow revocation and re-enabling of roles.
 1779:     my ($tmp) = keys(%rolesdump);
 1780:     return if ($tmp =~ /^(con_lost|error)/i);
 1781:     foreach my $area (sort { my $a1=join('_',(split('_',$a))[1,0]);
 1782:                                 my $b1=join('_',(split('_',$b))[1,0]);
 1783:                                 return $a1 cmp $b1;
 1784:                             } keys(%rolesdump)) {
 1785:         next if ($area =~ /^rolesdef/);
 1786:         my $envkey=$area;
 1787:         my $role = $rolesdump{$area};
 1788:         my $thisrole=$area;
 1789:         $area =~ s/\_\w\w$//;
 1790:         my ($role_code,$role_end_time,$role_start_time) =
 1791:             split(/_/,$role);
 1792:         my $active=1;
 1793:         $active=0 if (($role_end_time) && ($now>$role_end_time));
 1794:         if ($active) {
 1795:             next unless($showall || $showactive);
 1796:         } else {
 1797:             next unless($showall || $showexpired);
 1798:         }
 1799: # Is this a custom role? Get role owner and title.
 1800:         my ($croleudom,$croleuname,$croletitle)=
 1801:             ($role_code=~m{^cr/($match_domain)/($match_username)/(\w+)$});
 1802:         my $allowed=0;
 1803:         my $delallowed=0;
 1804:         my $sortkey=$role_code;
 1805:         my $class='Unknown';
 1806:         my $credits='';
 1807:         my $csec;
 1808:         if ($area =~ m{^/($match_domain)/($match_courseid)}) {
 1809:             $class='Course';
 1810:             my ($coursedom,$coursedir) = ($1,$2);
 1811:             my $cid = $1.'_'.$2;
 1812:             # $1.'_'.$2 is the course id (eg. 103_12345abcef103l3).
 1813:             next if ($envkey =~ m{^/$match_domain/$match_courseid/[A-Za-z0-9]+_gr$});
 1814:             my %coursedata=
 1815:                 &Apache::lonnet::coursedescription($cid);
 1816:             if ($coursedir =~ /^$match_community$/) {
 1817:                 $class='Community';
 1818:             }
 1819:             $sortkey.="\0$coursedom";
 1820:             my $carea;
 1821:             if (defined($coursedata{'description'})) {
 1822:                 $carea=$coursedata{'description'}.
 1823:                     '<br />'.&mt('Domain').': '.$coursedom.('&nbsp;'x8).
 1824:     &Apache::loncommon::syllabuswrapper(&mt('Syllabus'),$coursedir,$coursedom);
 1825:                 $sortkey.="\0".$coursedata{'description'};
 1826:             } else {
 1827:                 if ($class eq 'Community') {
 1828:                     $carea=&mt('Unavailable community').': '.$area;
 1829:                     $sortkey.="\0".&mt('Unavailable community').': '.$area;
 1830:                 } else {
 1831:                     $carea=&mt('Unavailable course').': '.$area;
 1832:                     $sortkey.="\0".&mt('Unavailable course').': '.$area;
 1833:                 }
 1834:             }
 1835:             $sortkey.="\0$coursedir";
 1836:             $inccourses->{$cid}=1;
 1837:             if (($showcredits) && ($class eq 'Course') && ($role_code eq 'st')) {
 1838:                 my $defaultcredits = $coursedata{'internal.defaultcredits'};
 1839:                 $credits =
 1840:                     &get_user_credits($ccuname,$ccdomain,$defaultcredits,
 1841:                                       $coursedom,$coursedir);
 1842:                 if ($credits eq '') {
 1843:                     $credits = $defaultcredits;
 1844:                 }
 1845:             }
 1846:             if ((&Apache::lonnet::allowed('c'.$role_code,$coursedom.'/'.$coursedir)) ||
 1847:                 (&Apache::lonnet::allowed('c'.$role_code,$ccdomain))) {
 1848:                 $allowed=1;
 1849:             }
 1850:             unless ($allowed) {
 1851:                 my $isowner = &Apache::lonuserutils::is_courseowner($cid,$coursedata{'internal.courseowner'});
 1852:                 if ($isowner) {
 1853:                     if (($role_code eq 'co') && ($class eq 'Community')) {
 1854:                         $allowed = 1;
 1855:                     } elsif (($role_code eq 'cc') && ($class eq 'Course')) {
 1856:                         $allowed = 1;
 1857:                     }
 1858:                 }
 1859:             } 
 1860:             if ((&Apache::lonnet::allowed('dro',$coursedom)) ||
 1861:                 (&Apache::lonnet::allowed('dro',$ccdomain))) {
 1862:                 $delallowed=1;
 1863:             }
 1864: # - custom role. Needs more info, too
 1865:             if ($croletitle) {
 1866:                 if (&Apache::lonnet::allowed('ccr',$coursedom.'/'.$coursedir)) {
 1867:                     $allowed=1;
 1868:                     $thisrole.='.'.$role_code;
 1869:                 }
 1870:             }
 1871:             if ($area=~m{^/($match_domain/$match_courseid/(\w+))}) {
 1872:                 $csec = $2;
 1873:                 $carea.='<br />'.&mt('Section: [_1]',$csec);
 1874:                 $sortkey.="\0$csec";
 1875:                 if (!$allowed) {
 1876:                     if ($env{'request.course.sec'} eq $csec) {
 1877:                         if (&Apache::lonnet::allowed('c'.$role_code,$1)) {
 1878:                             $allowed = 1;
 1879:                         }
 1880:                     }
 1881:                 }
 1882:             }
 1883:             $area=$carea;
 1884:         } else {
 1885:             $sortkey.="\0".$area;
 1886:             # Determine if current user is able to revoke privileges
 1887:             if ($area=~m{^/($match_domain)/}) {
 1888:                 if ((&Apache::lonnet::allowed('c'.$role_code,$1)) ||
 1889:                    (&Apache::lonnet::allowed('c'.$role_code,$ccdomain))) {
 1890:                    $allowed=1;
 1891:                 }
 1892:                 if (((&Apache::lonnet::allowed('dro',$1))  ||
 1893:                     (&Apache::lonnet::allowed('dro',$ccdomain))) &&
 1894:                     ($role_code ne 'dc')) {
 1895:                     $delallowed=1;
 1896:                 }
 1897:             } else {
 1898:                 if (&Apache::lonnet::allowed('c'.$role_code,'/')) {
 1899:                     $allowed=1;
 1900:                 }
 1901:             }
 1902:             if ($role_code eq 'ca' || $role_code eq 'au' || $role_code eq 'aa') {
 1903:                 $class='Authoring Space';
 1904:             } elsif ($role_code eq 'su') {
 1905:                 $class='System';
 1906:             } else {
 1907:                 $class='Domain';
 1908:             }
 1909:         }
 1910:         if (($role_code eq 'ca') || ($role_code eq 'aa')) {
 1911:             $area=~m{/($match_domain)/($match_username)};
 1912:             if (&Apache::lonuserutils::authorpriv($2,$1)) {
 1913:                 $allowed=1;
 1914:             } else {
 1915:                 $allowed=0;
 1916:             }
 1917:         }
 1918:         my $row = '';
 1919:         if ($showall) {
 1920:             $row.= '<td>';
 1921:             if (($active) && ($allowed)) {
 1922:                 $row.= '<input type="checkbox" name="rev:'.$thisrole.'" />';
 1923:             } else {
 1924:                 if ($active) {
 1925:                     $row.='&nbsp;';
 1926:                 } else {
 1927:                     $row.=&mt('expired or revoked');
 1928:                 }
 1929:             }
 1930:             $row.='</td><td>';
 1931:             if ($allowed && !$active) {
 1932:                 $row.= '<input type="checkbox" name="ren:'.$thisrole.'" />';
 1933:             } else {
 1934:                 $row.='&nbsp;';
 1935:             }
 1936:             $row.='</td><td>';
 1937:             if ($delallowed) {
 1938:                 $row.= '<input type="checkbox" name="del:'.$thisrole.'" />';
 1939:             } else {
 1940:                 $row.='&nbsp;';
 1941:             }
 1942:             $row.= '</td>';
 1943:         }
 1944:         my $plaintext='';
 1945:         if (!$croletitle) {
 1946:             $plaintext=&Apache::lonnet::plaintext($role_code,$class);
 1947:             if (($showcredits) && ($credits ne '')) {
 1948:                 $plaintext .= '<br/ ><span class="LC_nobreak">'.
 1949:                               '<span class="LC_fontsize_small">'.
 1950:                               &mt('Credits: [_1]',$credits).
 1951:                               '</span></span>';
 1952:             }
 1953:         } else {
 1954:             $plaintext=
 1955:                 &mt('Custom role [_1][_2]defined by [_3]',
 1956:                         '"'.$croletitle.'"',
 1957:                         '<br />',
 1958:                         $croleuname.':'.$croleudom);
 1959:         }
 1960:         $row.= '<td>'.$plaintext.'</td>'.
 1961:                '<td>'.$area.'</td>'.
 1962:                '<td>'.($role_start_time?&Apache::lonlocal::locallocaltime($role_start_time)
 1963:                                             : '&nbsp;' ).'</td>'.
 1964:                '<td>'.($role_end_time  ?&Apache::lonlocal::locallocaltime($role_end_time)
 1965:                                             : '&nbsp;' ).'</td>';
 1966:         $sortrole{$sortkey}=$envkey;
 1967:         $roletext{$envkey}=$row;
 1968:         $roleclass{$envkey}=$class;
 1969:         if ($allowed) {
 1970:             $rolepriv{$envkey}='edit';
 1971:         } else {
 1972:             if ($context eq 'domain') {
 1973:                 if ((&Apache::lonnet::allowed('vur',$ccdomain)) &&
 1974:                     ($envkey=~m{^/$ccdomain/})) {
 1975:                     $rolepriv{$envkey}='view';
 1976:                 }
 1977:             } elsif ($context eq 'course') {
 1978:                 if ((&Apache::lonnet::allowed('vcl',$env{'request.course.id'})) ||
 1979:                     ($env{'request.course.sec'} && ($env{'request.course.sec'} eq $csec) &&
 1980:                      &Apache::lonnet::allowed('vcl',$env{'request.course.id'}.'/'.$env{'request.course.sec'}))) {
 1981:                     $rolepriv{$envkey}='view';
 1982:                 }
 1983:             }
 1984:         }
 1985:     } # end of foreach        (table building loop)
 1986: 
 1987:     my $rolesdisplay = 0;
 1988:     my %output = ();
 1989:     foreach my $type ('Authoring Space','Course','Community','Domain','System','Unknown') {
 1990:         $output{$type} = '';
 1991:         foreach my $which (sort {uc($a) cmp uc($b)} (keys(%sortrole))) {
 1992:             if ( ($roleclass{$sortrole{$which}} =~ /^\Q$type\E/ ) && ($rolepriv{$sortrole{$which}}) ) {
 1993:                  $output{$type}.=
 1994:                       &Apache::loncommon::start_data_table_row().
 1995:                       $roletext{$sortrole{$which}}.
 1996:                       &Apache::loncommon::end_data_table_row();
 1997:             }
 1998:         }
 1999:         unless($output{$type} eq '') {
 2000:             $output{$type} = '<tr class="LC_info_row">'.
 2001:                       "<td align='center' colspan='7'>".&mt($type)."</td></tr>".
 2002:                       $output{$type};
 2003:             $rolesdisplay = 1;
 2004:         }
 2005:     }
 2006:     if ($rolesdisplay == 1) {
 2007:         my $contextrole='';
 2008:         if ($env{'request.course.id'}) {
 2009:             if (&Apache::loncommon::course_type() eq 'Community') {
 2010:                 $contextrole = &mt('Existing Roles in this Community');
 2011:             } else {
 2012:                 $contextrole = &mt('Existing Roles in this Course');
 2013:             }
 2014:         } elsif ($env{'request.role'} =~ /^au\./) {
 2015:             $contextrole = &mt('Existing Co-Author Roles in your Authoring Space');
 2016:         } else {
 2017:             if ($showall) {
 2018:                 $contextrole = &mt('Existing Roles in this Domain');
 2019:             } elsif ($showactive) {
 2020:                 $contextrole = &mt('Unexpired Roles in this Domain');
 2021:             } elsif ($showexpired) {
 2022:                 $contextrole = &mt('Expired or Revoked Roles in this Domain');
 2023:             }
 2024:         }
 2025:         $r->print('<div class="LC_left_float">'.
 2026: '<fieldset><legend>'.$contextrole.'</legend>'.
 2027: &Apache::loncommon::start_data_table("LC_createuser").
 2028: &Apache::loncommon::start_data_table_header_row());
 2029:         if ($showall) {
 2030:             $r->print(
 2031: '<th>'.$lt{'rev'}.'</th><th>'.$lt{'ren'}.'</th><th>'.$lt{'del'}.'</th>'
 2032:             );
 2033:         } elsif ($showexpired) {
 2034:             $r->print('<th>'.$lt{'rev'}.'</th>');
 2035:         }
 2036:         $r->print(
 2037: '<th>'.$lt{'rol'}.'</th><th>'.$lt{'ext'}.'</th>'.
 2038: '<th>'.$lt{'sta'}.'</th><th>'.$lt{'end'}.'</th>'.
 2039: &Apache::loncommon::end_data_table_header_row());
 2040:         foreach my $type ('Authoring Space','Course','Community','Domain','System','Unknown') {
 2041:             if ($output{$type}) {
 2042:                 $r->print($output{$type}."\n");
 2043:             }
 2044:         }
 2045:         $r->print(&Apache::loncommon::end_data_table().
 2046:                   '</fieldset></div>');
 2047:     }
 2048:     return;
 2049: }
 2050: 
 2051: sub new_coauthor_roles {
 2052:     my ($r,$ccuname,$ccdomain) = @_;
 2053:     my $addrolesdisplay = 0;
 2054:     #
 2055:     # Co-Author
 2056:     #
 2057:     if (&Apache::lonuserutils::authorpriv($env{'user.name'},
 2058:                                           $env{'request.role.domain'}) &&
 2059:         ($env{'user.name'} ne $ccuname || $env{'user.domain'} ne $ccdomain)) {
 2060:         # No sense in assigning co-author role to yourself
 2061:         $addrolesdisplay = 1;
 2062:         my $cuname=$env{'user.name'};
 2063:         my $cudom=$env{'request.role.domain'};
 2064:         my %lt=&Apache::lonlocal::texthash(
 2065:                     'cs'   => "Authoring Space",
 2066:                     'act'  => "Activate",
 2067:                     'rol'  => "Role",
 2068:                     'ext'  => "Extent",
 2069:                     'sta'  => "Start",
 2070:                     'end'  => "End",
 2071:                     'cau'  => "Co-Author",
 2072:                     'caa'  => "Assistant Co-Author",
 2073:                     'ssd'  => "Set Start Date",
 2074:                     'sed'  => "Set End Date"
 2075:                                        );
 2076:         $r->print('<h4>'.$lt{'cs'}.'</h4>'."\n".
 2077:                   &Apache::loncommon::start_data_table()."\n".
 2078:                   &Apache::loncommon::start_data_table_header_row()."\n".
 2079:                   '<th>'.$lt{'act'}.'</th><th>'.$lt{'rol'}.'</th>'.
 2080:                   '<th>'.$lt{'ext'}.'</th><th>'.$lt{'sta'}.'</th>'.
 2081:                   '<th>'.$lt{'end'}.'</th>'."\n".
 2082:                   &Apache::loncommon::end_data_table_header_row()."\n".
 2083:                   &Apache::loncommon::start_data_table_row().'
 2084:            <td>
 2085:             <input type="checkbox" name="act_'.$cudom.'_'.$cuname.'_ca" />
 2086:            </td>
 2087:            <td>'.$lt{'cau'}.'</td>
 2088:            <td>'.$cudom.'_'.$cuname.'</td>
 2089:            <td><input type="hidden" name="start_'.$cudom.'_'.$cuname.'_ca" value="" />
 2090:              <a href=
 2091: "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>
 2092: <td><input type="hidden" name="end_'.$cudom.'_'.$cuname.'_ca" value="" />
 2093: <a href=
 2094: "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".
 2095:               &Apache::loncommon::end_data_table_row()."\n".
 2096:               &Apache::loncommon::start_data_table_row()."\n".
 2097: '<td><input type="checkbox" name="act_'.$cudom.'_'.$cuname.'_aa" /></td>
 2098: <td>'.$lt{'caa'}.'</td>
 2099: <td>'.$cudom.'_'.$cuname.'</td>
 2100: <td><input type="hidden" name="start_'.$cudom.'_'.$cuname.'_aa" value="" />
 2101: <a href=
 2102: "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>
 2103: <td><input type="hidden" name="end_'.$cudom.'_'.$cuname.'_aa" value="" />
 2104: <a href=
 2105: "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".
 2106:              &Apache::loncommon::end_data_table_row()."\n".
 2107:              &Apache::loncommon::end_data_table());
 2108:     } elsif ($env{'request.role'} =~ /^au\./) {
 2109:         if (!(&Apache::lonuserutils::authorpriv($env{'user.name'},
 2110:                                                 $env{'request.role.domain'}))) {
 2111:             $r->print('<span class="LC_error">'.
 2112:                       &mt('You do not have privileges to assign co-author roles.').
 2113:                       '</span>');
 2114:         } elsif (($env{'user.name'} eq $ccuname) &&
 2115:              ($env{'user.domain'} eq $ccdomain)) {
 2116:             $r->print(&mt('Assigning yourself a co-author or assistant co-author role in your own author area in Authoring Space is not permitted'));
 2117:         }
 2118:     }
 2119:     return $addrolesdisplay;;
 2120: }
 2121: 
 2122: sub new_domain_roles {
 2123:     my ($r,$ccdomain) = @_;
 2124:     my $addrolesdisplay = 0;
 2125:     #
 2126:     # Domain level
 2127:     #
 2128:     my $num_domain_level = 0;
 2129:     my $domaintext =
 2130:     '<h4>'.&mt('Domain Level').'</h4>'.
 2131:     &Apache::loncommon::start_data_table().
 2132:     &Apache::loncommon::start_data_table_header_row().
 2133:     '<th>'.&mt('Activate').'</th><th>'.&mt('Role').'</th><th>'.
 2134:     &mt('Extent').'</th>'.
 2135:     '<th>'.&mt('Start').'</th><th>'.&mt('End').'</th>'.
 2136:     &Apache::loncommon::end_data_table_header_row();
 2137:     my @allroles = &Apache::lonuserutils::roles_by_context('domain');
 2138:     foreach my $thisdomain (sort(&Apache::lonnet::all_domains())) {
 2139:         foreach my $role (@allroles) {
 2140:             next if ($role eq 'ad');
 2141:             next if (($role eq 'au') && ($ccdomain ne $thisdomain));
 2142:             if (&Apache::lonnet::allowed('c'.$role,$thisdomain)) {
 2143:                my $plrole=&Apache::lonnet::plaintext($role);
 2144:                my %lt=&Apache::lonlocal::texthash(
 2145:                     'ssd'  => "Set Start Date",
 2146:                     'sed'  => "Set End Date"
 2147:                                        );
 2148:                $num_domain_level ++;
 2149:                $domaintext .=
 2150: &Apache::loncommon::start_data_table_row().
 2151: '<td><input type="checkbox" name="act_'.$thisdomain.'_'.$role.'" /></td>
 2152: <td>'.$plrole.'</td>
 2153: <td>'.$thisdomain.'</td>
 2154: <td><input type="hidden" name="start_'.$thisdomain.'_'.$role.'" value="" />
 2155: <a href=
 2156: "javascript:pjump('."'date_start','Start Date $plrole',document.cu.start_$thisdomain\_$role.value,'start_$thisdomain\_$role','cu.pres','dateset'".')">'.$lt{'ssd'}.'</a></td>
 2157: <td><input type="hidden" name="end_'.$thisdomain.'_'.$role.'" value="" />
 2158: <a href=
 2159: "javascript:pjump('."'date_end','End Date $plrole',document.cu.end_$thisdomain\_$role.value,'end_$thisdomain\_$role','cu.pres','dateset'".')">'.$lt{'sed'}.'</a></td>'.
 2160: &Apache::loncommon::end_data_table_row();
 2161:             }
 2162:         }
 2163:     }
 2164:     $domaintext.= &Apache::loncommon::end_data_table();
 2165:     if ($num_domain_level > 0) {
 2166:         $r->print($domaintext);
 2167:         $addrolesdisplay = 1;
 2168:     }
 2169:     return $addrolesdisplay;
 2170: }
 2171: 
 2172: sub user_authentication {
 2173:     my ($ccuname,$ccdomain,$formname) = @_;
 2174:     my $currentauth=&Apache::lonnet::queryauthenticate($ccuname,$ccdomain);
 2175:     my $outcome;
 2176:     my %lt=&Apache::lonlocal::texthash(
 2177:                    'err'   => "ERROR",
 2178:                    'uuas'  => "This user has an unrecognized authentication scheme",
 2179:                    'adcs'  => "Please alert a domain coordinator of this situation",
 2180:                    'sldb'  => "Please specify login data below",
 2181:                    'ld'    => "Login Data"
 2182:     );
 2183:     # Check for a bad authentication type
 2184:     if ($currentauth !~ /^(krb4|krb5|unix|internal|localauth):/) {
 2185:         # bad authentication scheme
 2186:         if (&Apache::lonnet::allowed('mau',$ccdomain)) {
 2187:             &initialize_authen_forms($ccdomain,$formname);
 2188: 
 2189:             my $choices = &Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc);
 2190:             $outcome = <<ENDBADAUTH;
 2191: <script type="text/javascript" language="Javascript">
 2192: // <![CDATA[
 2193: $loginscript
 2194: // ]]>
 2195: </script>
 2196: <span class="LC_error">$lt{'err'}:
 2197: $lt{'uuas'} ($currentauth). $lt{'sldb'}.</span>
 2198: <h3>$lt{'ld'}</h3>
 2199: $choices
 2200: ENDBADAUTH
 2201:         } else {
 2202:             # This user is not allowed to modify the user's
 2203:             # authentication scheme, so just notify them of the problem
 2204:             $outcome = <<ENDBADAUTH;
 2205: <span class="LC_error"> $lt{'err'}: 
 2206: $lt{'uuas'} ($currentauth). $lt{'adcs'}.
 2207: </span>
 2208: ENDBADAUTH
 2209:         }
 2210:     } else { # Authentication type is valid
 2211:         
 2212:         &initialize_authen_forms($ccdomain,$formname,$currentauth,'modifyuser');
 2213:         my ($authformcurrent,$can_modify,@authform_others) =
 2214:             &modify_login_block($ccdomain,$currentauth);
 2215:         if (&Apache::lonnet::allowed('mau',$ccdomain)) {
 2216:             # Current user has login modification privileges
 2217:             $outcome =
 2218:                        '<script type="text/javascript" language="Javascript">'."\n".
 2219:                        '// <![CDATA['."\n".
 2220:                        $loginscript."\n".
 2221:                        '// ]]>'."\n".
 2222:                        '</script>'."\n".
 2223:                        '<h3>'.$lt{'ld'}.'</h3>'.
 2224:                        &Apache::loncommon::start_data_table().
 2225:                        &Apache::loncommon::start_data_table_row().
 2226:                        '<td>'.$authformnop;
 2227:             if (($can_modify) && (&Apache::lonnet::allowed('mau',$ccdomain))) {
 2228:                 $outcome .= '</td>'."\n".
 2229:                             &Apache::loncommon::end_data_table_row().
 2230:                             &Apache::loncommon::start_data_table_row().
 2231:                             '<td>'.$authformcurrent.'</td>'.
 2232:                             &Apache::loncommon::end_data_table_row()."\n";
 2233:             } else {
 2234:                 $outcome .= '&nbsp;('.$authformcurrent.')</td>'.
 2235:                             &Apache::loncommon::end_data_table_row()."\n";
 2236:             }
 2237:             if (&Apache::lonnet::allowed('mau',$ccdomain)) {
 2238:                 foreach my $item (@authform_others) { 
 2239:                     $outcome .= &Apache::loncommon::start_data_table_row().
 2240:                                 '<td>'.$item.'</td>'.
 2241:                                 &Apache::loncommon::end_data_table_row()."\n";
 2242:                 }
 2243:             }
 2244:             $outcome .= &Apache::loncommon::end_data_table();
 2245:         } else {
 2246:             if (&Apache::lonnet::allowed('udp',$ccdomain)) {
 2247:                 # Current user has rights to view domain preferences for user's domain
 2248:                 my $result;
 2249:                 if ($currentauth =~ /^krb(4|5):([^:]*)$/) {
 2250:                     my ($krbver,$krbrealm) = ($1,$2);
 2251:                     if ($krbrealm eq '') {
 2252:                         $result = &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
 2253:                     } else {
 2254:                         $result = &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
 2255:                                       $krbrealm,$krbver);
 2256:                     }
 2257:                 } elsif ($currentauth =~ /^internal:/) {
 2258:                     $result = &mt('Currently internally authenticated.');
 2259:                 } elsif ($currentauth =~ /^localauth:/) {
 2260:                     $result = &mt('Currently using local (institutional) authentication.');
 2261:                 } elsif ($currentauth =~ /^unix:/) {
 2262:                     $result = &mt('Currently Filesystem Authenticated.');
 2263:                 }
 2264:                 $outcome = '<h3>'.$lt{'ld'}.'</h3>'.
 2265:                            &Apache::loncommon::start_data_table().
 2266:                            &Apache::loncommon::start_data_table_row().
 2267:                            '<td>'.$result.'</td>'.
 2268:                            &Apache::loncommon::end_data_table_row()."\n".
 2269:                            &Apache::loncommon::end_data_table();
 2270:             } elsif (&Apache::lonnet::allowed('mau',$env{'request.role.domain'})) {
 2271:                 my %lt=&Apache::lonlocal::texthash(
 2272:                            'ccld'  => "Change Current Login Data",
 2273:                            'yodo'  => "You do not have privileges to modify the authentication configuration for this user.",
 2274:                            'ifch'  => "If a change is required, contact a domain coordinator for the domain",
 2275:                 );
 2276:                 $outcome .= <<ENDNOPRIV;
 2277: <h3>$lt{'ccld'}</h3>
 2278: $lt{'yodo'} $lt{'ifch'}: $ccdomain
 2279: <input type="hidden" name="login" value="nochange" />
 2280: ENDNOPRIV
 2281:             }
 2282:         }
 2283:     }  ## End of "check for bad authentication type" logic
 2284:     return $outcome;
 2285: }
 2286: 
 2287: sub modify_login_block {
 2288:     my ($dom,$currentauth) = @_;
 2289:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 2290:     my ($authnum,%can_assign) =
 2291:         &Apache::loncommon::get_assignable_auth($dom);
 2292:     my ($authformcurrent,@authform_others,$show_override_msg);
 2293:     if ($currentauth=~/^krb(4|5):/) {
 2294:         $authformcurrent=$authformkrb;
 2295:         if ($can_assign{'int'}) {
 2296:             push(@authform_others,$authformint);
 2297:         }
 2298:         if ($can_assign{'loc'}) {
 2299:             push(@authform_others,$authformloc);
 2300:         }
 2301:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2302:             $show_override_msg = 1;
 2303:         }
 2304:     } elsif ($currentauth=~/^internal:/) {
 2305:         $authformcurrent=$authformint;
 2306:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2307:             push(@authform_others,$authformkrb);
 2308:         }
 2309:         if ($can_assign{'loc'}) {
 2310:             push(@authform_others,$authformloc);
 2311:         }
 2312:         if ($can_assign{'int'}) {
 2313:             $show_override_msg = 1;
 2314:         }
 2315:     } elsif ($currentauth=~/^unix:/) {
 2316:         $authformcurrent=$authformfsys;
 2317:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2318:             push(@authform_others,$authformkrb);
 2319:         }
 2320:         if ($can_assign{'int'}) {
 2321:             push(@authform_others,$authformint);
 2322:         }
 2323:         if ($can_assign{'loc'}) {
 2324:             push(@authform_others,$authformloc);
 2325:         }
 2326:         if ($can_assign{'fsys'}) {
 2327:             $show_override_msg = 1;
 2328:         }
 2329:     } elsif ($currentauth=~/^localauth:/) {
 2330:         $authformcurrent=$authformloc;
 2331:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2332:             push(@authform_others,$authformkrb);
 2333:         }
 2334:         if ($can_assign{'int'}) {
 2335:             push(@authform_others,$authformint);
 2336:         }
 2337:         if ($can_assign{'loc'}) {
 2338:             $show_override_msg = 1;
 2339:         }
 2340:     }
 2341:     if ($show_override_msg) {
 2342:         $authformcurrent = '<table><tr><td colspan="3">'.$authformcurrent.
 2343:                            '</td></tr>'."\n".
 2344:                            '<tr><td>&nbsp;&nbsp;&nbsp;</td>'.
 2345:                            '<td><b>'.&mt('Currently in use').'</b></td>'.
 2346:                            '<td align="right"><span class="LC_cusr_emph">'.
 2347:                             &mt('will override current values').
 2348:                             '</span></td></tr></table>';
 2349:     }
 2350:     return ($authformcurrent,$show_override_msg,@authform_others); 
 2351: }
 2352: 
 2353: sub personal_data_display {
 2354:     my ($ccuname,$ccdomain,$newuser,$context,$inst_results,$rolesarray,
 2355:         $now,$captchaform,$emailusername,$usertype) = @_;
 2356:     my ($output,%userenv,%canmodify,%canmodify_status);
 2357:     my @userinfo = ('firstname','middlename','lastname','generation',
 2358:                     'permanentemail','id');
 2359:     my $rowcount = 0;
 2360:     my $editable = 0;
 2361:     my %textboxsize = (
 2362:                        firstname      => '15',
 2363:                        middlename     => '15',
 2364:                        lastname       => '15',
 2365:                        generation     => '5',
 2366:                        permanentemail => '25',
 2367:                        id             => '15',
 2368:                       );
 2369: 
 2370:     my %lt=&Apache::lonlocal::texthash(
 2371:                 'pd'             => "Personal Data",
 2372:                 'firstname'      => "First Name",
 2373:                 'middlename'     => "Middle Name",
 2374:                 'lastname'       => "Last Name",
 2375:                 'generation'     => "Generation",
 2376:                 'permanentemail' => "Permanent e-mail address",
 2377:                 'id'             => "Student/Employee ID",
 2378:                 'lg'             => "Login Data",
 2379:                 'inststatus'     => "Affiliation",
 2380:                 'email'          => 'E-mail address',
 2381:                 'valid'          => 'Validation',
 2382:     );
 2383: 
 2384:     %canmodify_status =
 2385:         &Apache::lonuserutils::can_modify_userinfo($context,$ccdomain,
 2386:                                                    ['inststatus'],$rolesarray);
 2387:     if (!$newuser) {
 2388:         # Get the users information
 2389:         %userenv = &Apache::lonnet::get('environment',
 2390:                    ['firstname','middlename','lastname','generation',
 2391:                     'permanentemail','id','inststatus'],$ccdomain,$ccuname);
 2392:         %canmodify =
 2393:             &Apache::lonuserutils::can_modify_userinfo($context,$ccdomain,
 2394:                                                        \@userinfo,$rolesarray);
 2395:     } elsif ($context eq 'selfcreate') {
 2396:         if ($newuser eq 'email') {
 2397:             if (ref($emailusername) eq 'HASH') {
 2398:                 if (ref($emailusername->{$usertype}) eq 'HASH') {
 2399:                     my ($infofields,$infotitles) = &Apache::loncommon::emailusername_info();
 2400:                     @userinfo = ();          
 2401:                     if ((ref($infofields) eq 'ARRAY') && (ref($infotitles) eq 'HASH')) {
 2402:                         foreach my $field (@{$infofields}) { 
 2403:                             if ($emailusername->{$usertype}->{$field}) {
 2404:                                 push(@userinfo,$field);
 2405:                                 $canmodify{$field} = 1;
 2406:                                 unless ($textboxsize{$field}) {
 2407:                                     $textboxsize{$field} = 25;
 2408:                                 }
 2409:                                 unless ($lt{$field}) {
 2410:                                     $lt{$field} = $infotitles->{$field};
 2411:                                 }
 2412:                                 if ($emailusername->{$usertype}->{$field} eq 'required') {
 2413:                                     $lt{$field} .= '<b>*</b>';
 2414:                                 }
 2415:                             }
 2416:                         }
 2417:                     }
 2418:                 }
 2419:             }
 2420:         } else {
 2421:             %canmodify = &selfcreate_canmodify($context,$ccdomain,\@userinfo,
 2422:                                                $inst_results,$rolesarray);
 2423:         }
 2424:     }
 2425: 
 2426:     my $genhelp=&Apache::loncommon::help_open_topic('Generation');
 2427:     $output = '<h3>'.$lt{'pd'}.'</h3>'.
 2428:               &Apache::lonhtmlcommon::start_pick_box();
 2429:     if (($context eq 'selfcreate') && ($newuser eq 'email')) {
 2430:         $output .= &Apache::lonhtmlcommon::row_title($lt{'email'}.'<b>*</b>',undef,
 2431:                                                      'LC_oddrow_value')."\n".
 2432:                    '<input type="text" name="uname" size="25" value="" autocomplete="off" />';
 2433:         $rowcount ++;
 2434:         $output .= &Apache::lonhtmlcommon::row_closure(1);
 2435:         my $upassone = '<input type="password" name="upass'.$now.'" size="20" autocomplete="off" />';
 2436:         my $upasstwo = '<input type="password" name="upasscheck'.$now.'" size="20" autocomplete="off" />';
 2437:         $output .= &Apache::lonhtmlcommon::row_title(&mt('Password').'<b>*</b>',
 2438:                                                     'LC_pick_box_title',
 2439:                                                     'LC_oddrow_value')."\n".
 2440:                    $upassone."\n".
 2441:                    &Apache::lonhtmlcommon::row_closure(1)."\n".
 2442:                    &Apache::lonhtmlcommon::row_title(&mt('Confirm password').'<b>*</b>',
 2443:                                                      'LC_pick_box_title',
 2444:                                                      'LC_oddrow_value')."\n".
 2445:                    $upasstwo.
 2446:                    &Apache::lonhtmlcommon::row_closure()."\n";
 2447:     }
 2448:     foreach my $item (@userinfo) {
 2449:         my $rowtitle = $lt{$item};
 2450:         my $hiderow = 0;
 2451:         if ($item eq 'generation') {
 2452:             $rowtitle = $genhelp.$rowtitle;
 2453:         }
 2454:         my $row = &Apache::lonhtmlcommon::row_title($rowtitle,undef,'LC_oddrow_value')."\n";
 2455:         if ($newuser) {
 2456:             if (ref($inst_results) eq 'HASH') {
 2457:                 if ($inst_results->{$item} ne '') {
 2458:                     $row .= '<input type="hidden" name="c'.$item.'" value="'.$inst_results->{$item}.'" />'.$inst_results->{$item};
 2459:                 } else {
 2460:                     if ($context eq 'selfcreate') {
 2461:                         if ($canmodify{$item}) {
 2462:                             $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="" autocomplete="off" />';
 2463:                             $editable ++;
 2464:                         } else {
 2465:                             $hiderow = 1;
 2466:                         }
 2467:                     } else {
 2468:                         $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="" />';
 2469:                     }
 2470:                 }
 2471:             } else {
 2472:                 if ($context eq 'selfcreate') {
 2473:                     if ($canmodify{$item}) {
 2474:                         if ($newuser eq 'email') {
 2475:                             $row .= '<input type="text" name="'.$item.'" size="'.$textboxsize{$item}.'" value="" autocomplete="off" />';
 2476:                         } else {
 2477:                             $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="" autocomplete="off" />';
 2478:                         }
 2479:                         $editable ++;
 2480:                     } else {
 2481:                         $hiderow = 1;
 2482:                     }
 2483:                 } else {
 2484:                     $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="" />';
 2485:                 }
 2486:             }
 2487:         } else {
 2488:             if ($canmodify{$item}) {
 2489:                 $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="'.$userenv{$item}.'" />';
 2490:                 if (($item eq 'id') && (!$newuser)) {
 2491:                     $row .= '<br />'.&Apache::lonuserutils::forceid_change($context);
 2492:                 }
 2493:             } else {
 2494:                 $row .= $userenv{$item};
 2495:             }
 2496:         }
 2497:         $row .= &Apache::lonhtmlcommon::row_closure(1);
 2498:         if (!$hiderow) {
 2499:             $output .= $row;
 2500:             $rowcount ++;
 2501:         }
 2502:     }
 2503:     if (($canmodify_status{'inststatus'}) || ($context ne 'selfcreate')) {
 2504:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($ccdomain);
 2505:         if (ref($types) eq 'ARRAY') {
 2506:             if (@{$types} > 0) {
 2507:                 my ($hiderow,$shown);
 2508:                 if ($canmodify_status{'inststatus'}) {
 2509:                     $shown = &pick_inst_statuses($userenv{'inststatus'},$usertypes,$types);
 2510:                 } else {
 2511:                     if ($userenv{'inststatus'} eq '') {
 2512:                         $hiderow = 1;
 2513:                     } else {
 2514:                         my @showitems;
 2515:                         foreach my $item ( map { &unescape($_); } split(':',$userenv{'inststatus'})) {
 2516:                             if (exists($usertypes->{$item})) {
 2517:                                 push(@showitems,$usertypes->{$item});
 2518:                             } else {
 2519:                                 push(@showitems,$item);
 2520:                             }
 2521:                         }
 2522:                         if (@showitems) {
 2523:                             $shown = join(', ',@showitems);
 2524:                         } else {
 2525:                             $hiderow = 1;
 2526:                         }
 2527:                     }
 2528:                 }
 2529:                 if (!$hiderow) {
 2530:                     my $row = &Apache::lonhtmlcommon::row_title(&mt('Affiliations'),undef,'LC_oddrow_value')."\n".
 2531:                               $shown.&Apache::lonhtmlcommon::row_closure(1); 
 2532:                     if ($context eq 'selfcreate') {
 2533:                         $rowcount ++;
 2534:                     }
 2535:                     $output .= $row;
 2536:                 }
 2537:             }
 2538:         }
 2539:     }
 2540:     if (($context eq 'selfcreate') && ($newuser eq 'email')) {
 2541:         if ($captchaform) {
 2542:             $output .= &Apache::lonhtmlcommon::row_title($lt{'valid'}.'*',
 2543:                                                          'LC_pick_box_title')."\n".
 2544:                        $captchaform."\n".'<br /><br />'.
 2545:                        &Apache::lonhtmlcommon::row_closure(1); 
 2546:             $rowcount ++;
 2547:         }
 2548:         my $submit_text = &mt('Create account');
 2549:         $output .= &Apache::lonhtmlcommon::row_title()."\n".
 2550:                    '<br /><input type="submit" name="createaccount" value="'.
 2551:                    $submit_text.'" />'.
 2552:                    '<input type="hidden" name="type" value="'.$usertype.'" />'.
 2553:                    &Apache::lonhtmlcommon::row_closure(1);
 2554:     }
 2555:     $output .= &Apache::lonhtmlcommon::end_pick_box();
 2556:     if (wantarray) {
 2557:         if ($context eq 'selfcreate') {
 2558:             return($output,$rowcount,$editable);
 2559:         } else {
 2560:             return $output;
 2561:         }
 2562:     } else {
 2563:         return $output;
 2564:     }
 2565: }
 2566: 
 2567: sub pick_inst_statuses {
 2568:     my ($curr,$usertypes,$types) = @_;
 2569:     my ($output,$rem,@currtypes);
 2570:     if ($curr ne '') {
 2571:         @currtypes = map { &unescape($_); } split(/:/,$curr);
 2572:     }
 2573:     my $numinrow = 2;
 2574:     if (ref($types) eq 'ARRAY') {
 2575:         $output = '<table>';
 2576:         my $lastcolspan; 
 2577:         for (my $i=0; $i<@{$types}; $i++) {
 2578:             if (defined($usertypes->{$types->[$i]})) {
 2579:                 my $rem = $i%($numinrow);
 2580:                 if ($rem == 0) {
 2581:                     if ($i<@{$types}-1) {
 2582:                         if ($i > 0) { 
 2583:                             $output .= '</tr>';
 2584:                         }
 2585:                         $output .= '<tr>';
 2586:                     }
 2587:                 } elsif ($i==@{$types}-1) {
 2588:                     my $colsleft = $numinrow - $rem;
 2589:                     if ($colsleft > 1) {
 2590:                         $lastcolspan = ' colspan="'.$colsleft.'"';
 2591:                     }
 2592:                 }
 2593:                 my $check = ' ';
 2594:                 if (grep(/^\Q$types->[$i]\E$/,@currtypes)) {
 2595:                     $check = ' checked="checked" ';
 2596:                 }
 2597:                 $output .= '<td class="LC_left_item"'.$lastcolspan.'>'.
 2598:                            '<span class="LC_nobreak"><label>'.
 2599:                            '<input type="checkbox" name="inststatus" '.
 2600:                            'value="'.$types->[$i].'"'.$check.'/>'.
 2601:                            $usertypes->{$types->[$i]}.'</label></span></td>';
 2602:             }
 2603:         }
 2604:         $output .= '</tr></table>';
 2605:     }
 2606:     return $output;
 2607: }
 2608: 
 2609: sub selfcreate_canmodify {
 2610:     my ($context,$dom,$userinfo,$inst_results,$rolesarray) = @_;
 2611:     if (ref($inst_results) eq 'HASH') {
 2612:         my @inststatuses = &get_inststatuses($inst_results);
 2613:         if (@inststatuses == 0) {
 2614:             @inststatuses = ('default');
 2615:         }
 2616:         $rolesarray = \@inststatuses;
 2617:     }
 2618:     my %canmodify =
 2619:         &Apache::lonuserutils::can_modify_userinfo($context,$dom,$userinfo,
 2620:                                                    $rolesarray);
 2621:     return %canmodify;
 2622: }
 2623: 
 2624: sub get_inststatuses {
 2625:     my ($insthashref) = @_;
 2626:     my @inststatuses = ();
 2627:     if (ref($insthashref) eq 'HASH') {
 2628:         if (ref($insthashref->{'inststatus'}) eq 'ARRAY') {
 2629:             @inststatuses = @{$insthashref->{'inststatus'}};
 2630:         }
 2631:     }
 2632:     return @inststatuses;
 2633: }
 2634: 
 2635: # ================================================================= Phase Three
 2636: sub update_user_data {
 2637:     my ($r,$context,$crstype,$brcrum,$showcredits) = @_; 
 2638:     my $uhome=&Apache::lonnet::homeserver($env{'form.ccuname'},
 2639:                                           $env{'form.ccdomain'});
 2640:     # Error messages
 2641:     my $error     = '<span class="LC_error">'.&mt('Error').': ';
 2642:     my $end       = '</span><br /><br />';
 2643:     my $rtnlink   = '<a href="javascript:backPage(document.userupdate,'.
 2644:                     "'$env{'form.prevphase'}','modify')".'" />'.
 2645:                     &mt('Return to previous page').'</a>'.
 2646:                     &Apache::loncommon::end_page();
 2647:     my $now = time;
 2648:     my $title;
 2649:     if (exists($env{'form.makeuser'})) {
 2650: 	$title='Set Privileges for New User';
 2651:     } else {
 2652:         $title='Modify User Privileges';
 2653:     }
 2654:     my $newuser = 0;
 2655:     my ($jsback,$elements) = &crumb_utilities();
 2656:     my $jscript = '<script type="text/javascript">'."\n".
 2657:                   '// <![CDATA['."\n".
 2658:                   $jsback."\n".
 2659:                   '// ]]>'."\n".
 2660:                   '</script>'."\n";
 2661:     my %breadcrumb_text = &singleuser_breadcrumb($crstype,$context,$env{'form.ccdomain'});
 2662:     push (@{$brcrum},
 2663:              {href => "javascript:backPage(document.userupdate)",
 2664:               text => $breadcrumb_text{'search'},
 2665:               faq  => 282,
 2666:               bug  => 'Instructor Interface',}
 2667:              );
 2668:     if ($env{'form.prevphase'} eq 'userpicked') {
 2669:         push(@{$brcrum},
 2670:                {href => "javascript:backPage(document.userupdate,'get_user_info','select')",
 2671:                 text => $breadcrumb_text{'userpicked'},
 2672:                 faq  => 282,
 2673:                 bug  => 'Instructor Interface',});
 2674:     }
 2675:     my $helpitem = 'Course_Change_Privileges';
 2676:     if ($env{'form.action'} eq 'singlestudent') {
 2677:         $helpitem = 'Course_Add_Student';
 2678:     } elsif ($context eq 'author') {
 2679:         $helpitem = 'Author_Change_Privileges';
 2680:     } elsif ($context eq 'domain') {
 2681:         $helpitem = 'Domain_Change_Privileges';
 2682:     }
 2683:     push(@{$brcrum}, 
 2684:             {href => "javascript:backPage(document.userupdate,'$env{'form.prevphase'}','modify')",
 2685:              text => $breadcrumb_text{'modify'},
 2686:              faq  => 282,
 2687:              bug  => 'Instructor Interface',},
 2688:             {href => "/adm/createuser",
 2689:              text => "Result",
 2690:              faq  => 282,
 2691:              bug  => 'Instructor Interface',
 2692:              help => $helpitem});
 2693:     my $args = {bread_crumbs          => $brcrum,
 2694:                 bread_crumbs_component => 'User Management'};
 2695:     if ($env{'form.popup'}) {
 2696:         $args->{'no_nav_bar'} = 1;
 2697:     }
 2698:     $r->print(&Apache::loncommon::start_page($title,$jscript,$args));
 2699:     $r->print(&update_result_form($uhome));
 2700:     # Check Inputs
 2701:     if (! $env{'form.ccuname'} ) {
 2702: 	$r->print($error.&mt('No login name specified').'.'.$end.$rtnlink);
 2703: 	return;
 2704:     }
 2705:     if (  $env{'form.ccuname'} ne 
 2706: 	  &LONCAPA::clean_username($env{'form.ccuname'}) ) {
 2707: 	$r->print($error.&mt('Invalid login name.').'  '.
 2708: 		  &mt('Only letters, numbers, periods, dashes, @, and underscores are valid.').
 2709: 		  $end.$rtnlink);
 2710: 	return;
 2711:     }
 2712:     if (! $env{'form.ccdomain'}       ) {
 2713: 	$r->print($error.&mt('No domain specified').'.'.$end.$rtnlink);
 2714: 	return;
 2715:     }
 2716:     if (  $env{'form.ccdomain'} ne
 2717: 	  &LONCAPA::clean_domain($env{'form.ccdomain'}) ) {
 2718: 	$r->print($error.&mt('Invalid domain name.').'  '.
 2719: 		  &mt('Only letters, numbers, periods, dashes, and underscores are valid.').
 2720: 		  $end.$rtnlink);
 2721: 	return;
 2722:     }
 2723:     if ($uhome eq 'no_host') {
 2724:         $newuser = 1;
 2725:     }
 2726:     if (! exists($env{'form.makeuser'})) {
 2727:         # Modifying an existing user, so check the validity of the name
 2728:         if ($uhome eq 'no_host') {
 2729:             $r->print(
 2730:                 $error
 2731:                .'<p class="LC_error">'
 2732:                .&mt('Unable to determine home server for [_1] in domain [_2].',
 2733:                         '"'.$env{'form.ccuname'}.'"','"'.$env{'form.ccdomain'}.'"')
 2734:                .'</p>');
 2735:             return;
 2736:         }
 2737:     }
 2738:     # Determine authentication method and password for the user being modified
 2739:     my $amode='';
 2740:     my $genpwd='';
 2741:     if ($env{'form.login'} eq 'krb') {
 2742: 	$amode='krb';
 2743: 	$amode.=$env{'form.krbver'};
 2744: 	$genpwd=$env{'form.krbarg'};
 2745:     } elsif ($env{'form.login'} eq 'int') {
 2746: 	$amode='internal';
 2747: 	$genpwd=$env{'form.intarg'};
 2748:     } elsif ($env{'form.login'} eq 'fsys') {
 2749: 	$amode='unix';
 2750: 	$genpwd=$env{'form.fsysarg'};
 2751:     } elsif ($env{'form.login'} eq 'loc') {
 2752: 	$amode='localauth';
 2753: 	$genpwd=$env{'form.locarg'};
 2754: 	$genpwd=" " if (!$genpwd);
 2755:     } elsif (($env{'form.login'} eq 'nochange') ||
 2756:              ($env{'form.login'} eq ''        )) { 
 2757:         # There is no need to tell the user we did not change what they
 2758:         # did not ask us to change.
 2759:         # If they are creating a new user but have not specified login
 2760:         # information this will be caught below.
 2761:     } else {
 2762:             $r->print($error.&mt('Invalid login mode or password').$end.$rtnlink);
 2763:             return;
 2764:     }
 2765: 
 2766:     $r->print('<h3>'.&mt('User [_1] in domain [_2]',
 2767:                         $env{'form.ccuname'}.' ('.&Apache::loncommon::plainname($env{'form.ccuname'},
 2768:                         $env{'form.ccdomain'}).')', $env{'form.ccdomain'}).'</h3>');
 2769:     my %prog_state = &Apache::lonhtmlcommon::Create_PrgWin($r,2);
 2770: 
 2771:     my (%alerts,%rulematch,%inst_results,%curr_rules);
 2772:     my @userinfo = ('firstname','middlename','lastname','generation','permanentemail','id');
 2773:     my @usertools = ('aboutme','blog','webdav','portfolio');
 2774:     my @requestcourses = ('official','unofficial','community','textbook','placement');
 2775:     my @requestauthor = ('requestauthor');
 2776:     my ($othertitle,$usertypes,$types) = 
 2777:         &Apache::loncommon::sorted_inst_types($env{'form.ccdomain'});
 2778:     my %canmodify_status =
 2779:         &Apache::lonuserutils::can_modify_userinfo($context,$env{'form.ccdomain'},
 2780:                                                    ['inststatus']);
 2781:     if ($env{'form.makeuser'}) {
 2782: 	$r->print('<h3>'.&mt('Creating new account.').'</h3>');
 2783:         # Check for the authentication mode and password
 2784:         if (! $amode || ! $genpwd) {
 2785: 	    $r->print($error.&mt('Invalid login mode or password').$end.$rtnlink);    
 2786: 	    return;
 2787: 	}
 2788:         # Determine desired host
 2789:         my $desiredhost = $env{'form.hserver'};
 2790:         if (lc($desiredhost) eq 'default') {
 2791:             $desiredhost = undef;
 2792:         } else {
 2793:             my %home_servers = 
 2794: 		&Apache::lonnet::get_servers($env{'form.ccdomain'},'library');
 2795:             if (! exists($home_servers{$desiredhost})) {
 2796:                 $r->print($error.&mt('Invalid home server specified').$end.$rtnlink);
 2797:                 return;
 2798:             }
 2799:         }
 2800:         # Check ID format
 2801:         my %checkhash;
 2802:         my %checks = ('id' => 1);
 2803:         %{$checkhash{$env{'form.ccuname'}.':'.$env{'form.ccdomain'}}} = (
 2804:             'newuser' => $newuser, 
 2805:             'id' => $env{'form.cid'},
 2806:         );
 2807:         if ($env{'form.cid'} ne '') {
 2808:             &Apache::loncommon::user_rule_check(\%checkhash,\%checks,\%alerts,
 2809:                                           \%rulematch,\%inst_results,\%curr_rules);
 2810:             if (ref($alerts{'id'}) eq 'HASH') {
 2811:                 if (ref($alerts{'id'}{$env{'form.ccdomain'}}) eq 'HASH') {
 2812:                     my $domdesc =
 2813:                         &Apache::lonnet::domain($env{'form.ccdomain'},'description');
 2814:                     if ($alerts{'id'}{$env{'form.ccdomain'}}{$env{'form.cid'}}) {
 2815:                         my $userchkmsg;
 2816:                         if (ref($curr_rules{$env{'form.ccdomain'}}) eq 'HASH') {
 2817:                             $userchkmsg  = 
 2818:                                 &Apache::loncommon::instrule_disallow_msg('id',
 2819:                                                                     $domdesc,1).
 2820:                                 &Apache::loncommon::user_rule_formats($env{'form.ccdomain'},
 2821:                                     $domdesc,$curr_rules{$env{'form.ccdomain'}}{'id'},'id');
 2822:                         }
 2823:                         $r->print($error.&mt('Invalid ID format').$end.
 2824:                                   $userchkmsg.$rtnlink);
 2825:                         return;
 2826:                     }
 2827:                 }
 2828:             }
 2829:         }
 2830:         &Apache::lonhtmlcommon::Increment_PrgWin($r, \%prog_state);
 2831: 	# Call modifyuser
 2832: 	my $result = &Apache::lonnet::modifyuser
 2833: 	    ($env{'form.ccdomain'},$env{'form.ccuname'},$env{'form.cid'},
 2834:              $amode,$genpwd,$env{'form.cfirstname'},
 2835:              $env{'form.cmiddlename'},$env{'form.clastname'},
 2836:              $env{'form.cgeneration'},undef,$desiredhost,
 2837:              $env{'form.cpermanentemail'});
 2838: 	$r->print(&mt('Generating user').': '.$result);
 2839:         $uhome = &Apache::lonnet::homeserver($env{'form.ccuname'},
 2840:                                                $env{'form.ccdomain'});
 2841:         my (%changeHash,%newcustom,%changed,%changedinfo);
 2842:         if ($uhome ne 'no_host') {
 2843:             if ($context eq 'domain') {
 2844:                 foreach my $name ('portfolio','author') {
 2845:                     if ($env{'form.custom_'.$name.'quota'} == 1) {
 2846:                         if ($env{'form.'.$name.'quota'} eq '') {
 2847:                             $newcustom{$name.'quota'} = 0;
 2848:                         } else {
 2849:                             $newcustom{$name.'quota'} = $env{'form.'.$name.'quota'};
 2850:                             $newcustom{$name.'quota'} =~ s/[^\d\.]//g;
 2851:                         }
 2852:                         if (&quota_admin($newcustom{$name.'quota'},\%changeHash,$name)) {
 2853:                             $changed{$name.'quota'} = 1;
 2854:                         }
 2855:                     }
 2856:                 }
 2857:                 foreach my $item (@usertools) {
 2858:                     if ($env{'form.custom'.$item} == 1) {
 2859:                         $newcustom{$item} = $env{'form.tools_'.$item};
 2860:                         $changed{$item} = &tool_admin($item,$newcustom{$item},
 2861:                                                      \%changeHash,'tools');
 2862:                     }
 2863:                 }
 2864:                 foreach my $item (@requestcourses) {
 2865:                     if ($env{'form.custom'.$item} == 1) {
 2866:                         $newcustom{$item} = $env{'form.crsreq_'.$item};
 2867:                         if ($env{'form.crsreq_'.$item} eq 'autolimit') {
 2868:                             $newcustom{$item} .= '=';
 2869:                             $env{'form.crsreq_'.$item.'_limit'} =~ s/\D+//g;
 2870:                             if ($env{'form.crsreq_'.$item.'_limit'}) {
 2871:                                 $newcustom{$item} .= $env{'form.crsreq_'.$item.'_limit'};
 2872:                             }
 2873:                         }
 2874:                         $changed{$item} = &tool_admin($item,$newcustom{$item},
 2875:                                                       \%changeHash,'requestcourses');
 2876:                     }
 2877:                 }
 2878:                 if ($env{'form.customrequestauthor'} == 1) {
 2879:                     $newcustom{'requestauthor'} = $env{'form.requestauthor'};
 2880:                     $changed{'requestauthor'} = &tool_admin('requestauthor',
 2881:                                                     $newcustom{'requestauthor'},
 2882:                                                     \%changeHash,'requestauthor');
 2883:                 }
 2884:             }
 2885:             if ($canmodify_status{'inststatus'}) {
 2886:                 if (exists($env{'form.inststatus'})) {
 2887:                     my @inststatuses = &Apache::loncommon::get_env_multiple('form.inststatus');
 2888:                     if (@inststatuses > 0) {
 2889:                         $changeHash{'inststatus'} = join(',',@inststatuses);
 2890:                         $changed{'inststatus'} = $changeHash{'inststatus'};
 2891:                     }
 2892:                 }
 2893:             }
 2894:             if (keys(%changed)) {
 2895:                 foreach my $item (@userinfo) {
 2896:                     $changeHash{$item}  = $env{'form.c'.$item};
 2897:                 }
 2898:                 my $chgresult =
 2899:                      &Apache::lonnet::put('environment',\%changeHash,
 2900:                                           $env{'form.ccdomain'},$env{'form.ccuname'});
 2901:             } 
 2902:         }
 2903:         $r->print('<br />'.&mt('Home server').': '.$uhome.' '.
 2904:                   &Apache::lonnet::hostname($uhome));
 2905:     } elsif (($env{'form.login'} ne 'nochange') &&
 2906:              ($env{'form.login'} ne ''        )) {
 2907: 	# Modify user privileges
 2908:         if (! $amode || ! $genpwd) {
 2909: 	    $r->print($error.'Invalid login mode or password'.$end.$rtnlink);    
 2910: 	    return;
 2911: 	}
 2912: 	# Only allow authentication modification if the person has authority
 2913: 	if (&Apache::lonnet::allowed('mau',$env{'form.ccdomain'})) {
 2914: 	    $r->print('Modifying authentication: '.
 2915:                       &Apache::lonnet::modifyuserauth(
 2916: 		       $env{'form.ccdomain'},$env{'form.ccuname'},
 2917:                        $amode,$genpwd));
 2918:             $r->print('<br />'.&mt('Home server').': '.&Apache::lonnet::homeserver
 2919: 		  ($env{'form.ccuname'},$env{'form.ccdomain'}));
 2920: 	} else {
 2921: 	    # Okay, this is a non-fatal error.
 2922: 	    $r->print($error.&mt('You do not have the authority to modify this users authentication information.').$end);    
 2923: 	}
 2924:     }
 2925:     $r->rflush(); # Finish display of header before time consuming actions start
 2926:     &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state);
 2927:     ##
 2928:     my (@userroles,%userupdate,$cnum,$cdom,$defaultcredits,%namechanged);
 2929:     if ($context eq 'course') {
 2930:         ($cnum,$cdom) =
 2931:             &Apache::lonuserutils::get_course_identity();
 2932:         $crstype = &Apache::loncommon::course_type($cdom.'_'.$cnum);
 2933:         if ($showcredits) {
 2934:            $defaultcredits = &Apache::lonuserutils::get_defaultcredits($cdom,$cnum);
 2935:         }
 2936:     }
 2937:     if (! $env{'form.makeuser'} ) {
 2938:         # Check for need to change
 2939:         my %userenv = &Apache::lonnet::get
 2940:             ('environment',['firstname','middlename','lastname','generation',
 2941:              'id','permanentemail','portfolioquota','authorquota','inststatus',
 2942:              'tools.aboutme','tools.blog','tools.webdav','tools.portfolio',
 2943:              'requestcourses.official','requestcourses.unofficial',
 2944:              'requestcourses.community','requestcourses.textbook',
 2945:              'reqcrsotherdom.official','reqcrsotherdom.unofficial',
 2946:              'reqcrsotherdom.community','reqcrsotherdom.textbook',
 2947:              'reqcrsotherdom.placement','requestauthor'],
 2948:               $env{'form.ccdomain'},$env{'form.ccuname'});
 2949:         my ($tmp) = keys(%userenv);
 2950:         if ($tmp =~ /^(con_lost|error)/i) { 
 2951:             %userenv = ();
 2952:         }
 2953:         my $no_forceid_alert;
 2954:         # Check to see if user information can be changed
 2955:         my %domconfig =
 2956:             &Apache::lonnet::get_dom('configuration',['usermodification'],
 2957:                                      $env{'form.ccdomain'});
 2958:         my @statuses = ('active','future');
 2959:         my %roles = &Apache::lonnet::get_my_roles($env{'form.ccuname'},$env{'form.ccdomain'},'userroles',\@statuses,undef,$env{'request.role.domain'});
 2960:         my ($auname,$audom);
 2961:         if ($context eq 'author') {
 2962:             $auname = $env{'user.name'};
 2963:             $audom = $env{'user.domain'};     
 2964:         }
 2965:         foreach my $item (keys(%roles)) {
 2966:             my ($rolenum,$roledom,$role) = split(/:/,$item,-1);
 2967:             if ($context eq 'course') {
 2968:                 if ($cnum ne '' && $cdom ne '') {
 2969:                     if ($rolenum eq $cnum && $roledom eq $cdom) {
 2970:                         if (!grep(/^\Q$role\E$/,@userroles)) {
 2971:                             push(@userroles,$role);
 2972:                         }
 2973:                     }
 2974:                 }
 2975:             } elsif ($context eq 'author') {
 2976:                 if ($rolenum eq $auname && $roledom eq $audom) {
 2977:                     if (!grep(/^\Q$role\E$/,@userroles)) { 
 2978:                         push(@userroles,$role);
 2979:                     }
 2980:                 }
 2981:             }
 2982:         }
 2983:         if ($env{'form.action'} eq 'singlestudent') {
 2984:             if (!grep(/^st$/,@userroles)) {
 2985:                 push(@userroles,'st');
 2986:             }
 2987:         } else {
 2988:             # Check for course or co-author roles being activated or re-enabled
 2989:             if ($context eq 'author' || $context eq 'course') {
 2990:                 foreach my $key (keys(%env)) {
 2991:                     if ($context eq 'author') {
 2992:                         if ($key=~/^form\.act_\Q$audom\E_\Q$auname\E_([^_]+)/) {
 2993:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 2994:                                 push(@userroles,$1);
 2995:                             }
 2996:                         } elsif ($key =~/^form\.ren\:\Q$audom\E\/\Q$auname\E_([^_]+)/) {
 2997:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 2998:                                 push(@userroles,$1);
 2999:                             }
 3000:                         }
 3001:                     } elsif ($context eq 'course') {
 3002:                         if ($key=~/^form\.act_\Q$cdom\E_\Q$cnum\E_([^_]+)/) {
 3003:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 3004:                                 push(@userroles,$1);
 3005:                             }
 3006:                         } elsif ($key =~/^form\.ren\:\Q$cdom\E\/\Q$cnum\E(\/?\w*)_([^_]+)/) {
 3007:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 3008:                                 push(@userroles,$1);
 3009:                             }
 3010:                         }
 3011:                     }
 3012:                 }
 3013:             }
 3014:         }
 3015:         #Check to see if we can change personal data for the user 
 3016:         my (@mod_disallowed,@longroles);
 3017:         foreach my $role (@userroles) {
 3018:             if ($role eq 'cr') {
 3019:                 push(@longroles,'Custom');
 3020:             } else {
 3021:                 push(@longroles,&Apache::lonnet::plaintext($role,$crstype)); 
 3022:             }
 3023:         }
 3024:         my %canmodify = &Apache::lonuserutils::can_modify_userinfo($context,$env{'form.ccdomain'},\@userinfo,\@userroles);
 3025:         foreach my $item (@userinfo) {
 3026:             # Strip leading and trailing whitespace
 3027:             $env{'form.c'.$item} =~ s/(\s+$|^\s+)//g;
 3028:             if (!$canmodify{$item}) {
 3029:                 if (defined($env{'form.c'.$item})) {
 3030:                     if ($env{'form.c'.$item} ne $userenv{$item}) {
 3031:                         push(@mod_disallowed,$item);
 3032:                     }
 3033:                 }
 3034:                 $env{'form.c'.$item} = $userenv{$item};
 3035:             }
 3036:         }
 3037:         # Check to see if we can change the Student/Employee ID
 3038:         my $forceid = $env{'form.forceid'};
 3039:         my $recurseid = $env{'form.recurseid'};
 3040:         my (%alerts,%rulematch,%idinst_results,%curr_rules,%got_rules);
 3041:         my %uidhash = &Apache::lonnet::idrget($env{'form.ccdomain'},
 3042:                                             $env{'form.ccuname'});
 3043:         if (($uidhash{$env{'form.ccuname'}}) && 
 3044:             ($uidhash{$env{'form.ccuname'}}!~/error\:/) && 
 3045:             (!$forceid)) {
 3046:             if ($env{'form.cid'} ne $uidhash{$env{'form.ccuname'}}) {
 3047:                 $env{'form.cid'} = $userenv{'id'};
 3048:                 $no_forceid_alert = &mt('New student/employee ID does not match existing ID for this user.')
 3049:                                    .'<br />'
 3050:                                    .&mt("Change is not permitted without checking the 'Force ID change' checkbox on the previous page.")
 3051:                                    .'<br />'."\n";
 3052:             }
 3053:         }
 3054:         if ($env{'form.cid'} ne $userenv{'id'}) {
 3055:             my $checkhash;
 3056:             my $checks = { 'id' => 1 };
 3057:             $checkhash->{$env{'form.ccuname'}.':'.$env{'form.ccdomain'}} = 
 3058:                    { 'newuser' => $newuser,
 3059:                      'id'  => $env{'form.cid'}, 
 3060:                    };
 3061:             &Apache::loncommon::user_rule_check($checkhash,$checks,
 3062:                 \%alerts,\%rulematch,\%idinst_results,\%curr_rules,\%got_rules);
 3063:             if (ref($alerts{'id'}) eq 'HASH') {
 3064:                 if (ref($alerts{'id'}{$env{'form.ccdomain'}}) eq 'HASH') {
 3065:                    $env{'form.cid'} = $userenv{'id'};
 3066:                 }
 3067:             }
 3068:         }
 3069:         my (%quotachanged,%oldquota,%newquota,%olddefquota,%newdefquota, 
 3070:             $oldinststatus,$newinststatus,%oldisdefault,%newisdefault,%oldsettings,
 3071:             %oldsettingstext,%newsettings,%newsettingstext,@disporder,
 3072:             %oldsettingstatus,%newsettingstatus);
 3073:         @disporder = ('inststatus');
 3074:         if ($env{'request.role.domain'} eq $env{'form.ccdomain'}) {
 3075:             push(@disporder,'requestcourses','requestauthor');
 3076:         } else {
 3077:             push(@disporder,'reqcrsotherdom');
 3078:         }
 3079:         push(@disporder,('quota','tools'));
 3080:         $oldinststatus = $userenv{'inststatus'};
 3081:         foreach my $name ('portfolio','author') {
 3082:             ($olddefquota{$name},$oldsettingstatus{$name}) = 
 3083:                 &Apache::loncommon::default_quota($env{'form.ccdomain'},$oldinststatus,$name);
 3084:             ($newdefquota{$name},$newsettingstatus{$name}) = ($olddefquota{$name},$oldsettingstatus{$name});
 3085:         }
 3086:         my %canshow;
 3087:         if (&Apache::lonnet::allowed('mpq',$env{'form.ccdomain'})) {
 3088:             $canshow{'quota'} = 1;
 3089:         }
 3090:         if (&Apache::lonnet::allowed('mut',$env{'form.ccdomain'})) {
 3091:             $canshow{'tools'} = 1;
 3092:         }
 3093:         if (&Apache::lonnet::allowed('ccc',$env{'form.ccdomain'})) {
 3094:             $canshow{'requestcourses'} = 1;
 3095:         } elsif (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) {
 3096:             $canshow{'reqcrsotherdom'} = 1;
 3097:         }
 3098:         if (&Apache::lonnet::allowed('mau',$env{'form.ccdomain'})) {
 3099:             $canshow{'inststatus'} = 1;
 3100:         }
 3101:         if (&Apache::lonnet::allowed('cau',$env{'form.ccdomain'})) {
 3102:             $canshow{'requestauthor'} = 1;
 3103:         }
 3104:         my (%changeHash,%changed);
 3105:         if ($oldinststatus eq '') {
 3106:             $oldsettings{'inststatus'} = $othertitle; 
 3107:         } else {
 3108:             if (ref($usertypes) eq 'HASH') {
 3109:                 $oldsettings{'inststatus'} = join(', ',map{ $usertypes->{ &unescape($_) }; } (split(/:/,$userenv{'inststatus'})));
 3110:             } else {
 3111:                 $oldsettings{'inststatus'} = join(', ',map{ &unescape($_); } (split(/:/,$userenv{'inststatus'})));
 3112:             }
 3113:         }
 3114:         $changeHash{'inststatus'} = $userenv{'inststatus'};
 3115:         if ($canmodify_status{'inststatus'}) {
 3116:             $canshow{'inststatus'} = 1;
 3117:             if (exists($env{'form.inststatus'})) {
 3118:                 my @inststatuses = &Apache::loncommon::get_env_multiple('form.inststatus');
 3119:                 if (@inststatuses > 0) {
 3120:                     $newinststatus = join(':',map { &escape($_); } @inststatuses);
 3121:                     $changeHash{'inststatus'} = $newinststatus;
 3122:                     if ($newinststatus ne $oldinststatus) {
 3123:                         $changed{'inststatus'} = $newinststatus;
 3124:                         foreach my $name ('portfolio','author') {
 3125:                             ($newdefquota{$name},$newsettingstatus{$name}) =
 3126:                                 &Apache::loncommon::default_quota($env{'form.ccdomain'},$newinststatus,$name);
 3127:                         }
 3128:                     }
 3129:                     if (ref($usertypes) eq 'HASH') {
 3130:                         $newsettings{'inststatus'} = join(', ',map{ $usertypes->{$_}; } (@inststatuses)); 
 3131:                     } else {
 3132:                         $newsettings{'inststatus'} = join(', ',@inststatuses);
 3133:                     }
 3134:                 }
 3135:             } else {
 3136:                 $newinststatus = '';
 3137:                 $changeHash{'inststatus'} = $newinststatus;
 3138:                 $newsettings{'inststatus'} = $othertitle;
 3139:                 if ($newinststatus ne $oldinststatus) {
 3140:                     $changed{'inststatus'} = $changeHash{'inststatus'};
 3141:                     foreach my $name ('portfolio','author') {
 3142:                         ($newdefquota{$name},$newsettingstatus{$name}) =
 3143:                             &Apache::loncommon::default_quota($env{'form.ccdomain'},$newinststatus,$name);
 3144:                     }
 3145:                 }
 3146:             }
 3147:         } elsif ($context ne 'selfcreate') {
 3148:             $canshow{'inststatus'} = 1;
 3149:             $newsettings{'inststatus'} = $oldsettings{'inststatus'};
 3150:         }
 3151:         foreach my $name ('portfolio','author') {
 3152:             $changeHash{$name.'quota'} = $userenv{$name.'quota'};
 3153:         }
 3154:         if ($context eq 'domain') {
 3155:             foreach my $name ('portfolio','author') {
 3156:                 if ($userenv{$name.'quota'} ne '') {
 3157:                     $oldquota{$name} = $userenv{$name.'quota'};
 3158:                     if ($env{'form.custom_'.$name.'quota'} == 1) {
 3159:                         if ($env{'form.'.$name.'quota'} eq '') {
 3160:                             $newquota{$name} = 0;
 3161:                         } else {
 3162:                             $newquota{$name} = $env{'form.'.$name.'quota'};
 3163:                             $newquota{$name} =~ s/[^\d\.]//g;
 3164:                         }
 3165:                         if ($newquota{$name} != $oldquota{$name}) {
 3166:                             if (&quota_admin($newquota{$name},\%changeHash,$name)) {
 3167:                                 $changed{$name.'quota'} = 1;
 3168:                             }
 3169:                         }
 3170:                     } else {
 3171:                         if (&quota_admin('',\%changeHash,$name)) {
 3172:                             $changed{$name.'quota'} = 1;
 3173:                             $newquota{$name} = $newdefquota{$name};
 3174:                             $newisdefault{$name} = 1;
 3175:                         }
 3176:                     }
 3177:                 } else {
 3178:                     $oldisdefault{$name} = 1;
 3179:                     $oldquota{$name} = $olddefquota{$name};
 3180:                     if ($env{'form.custom_'.$name.'quota'} == 1) {
 3181:                         if ($env{'form.'.$name.'quota'} eq '') {
 3182:                             $newquota{$name} = 0;
 3183:                         } else {
 3184:                             $newquota{$name} = $env{'form.'.$name.'quota'};
 3185:                             $newquota{$name} =~ s/[^\d\.]//g;
 3186:                         }
 3187:                         if (&quota_admin($newquota{$name},\%changeHash,$name)) {
 3188:                             $changed{$name.'quota'} = 1;
 3189:                         }
 3190:                     } else {
 3191:                         $newquota{$name} = $newdefquota{$name};
 3192:                         $newisdefault{$name} = 1;
 3193:                     }
 3194:                 }
 3195:                 if ($oldisdefault{$name}) {
 3196:                     $oldsettingstext{'quota'}{$name} = &get_defaultquota_text($oldsettingstatus{$name});
 3197:                 }  else {
 3198:                     $oldsettingstext{'quota'}{$name} = &mt('custom quota: [_1] MB',$oldquota{$name});
 3199:                 }
 3200:                 if ($newisdefault{$name}) {
 3201:                     $newsettingstext{'quota'}{$name} = &get_defaultquota_text($newsettingstatus{$name});
 3202:                 } else {
 3203:                     $newsettingstext{'quota'}{$name} = &mt('custom quota: [_1] MB',$newquota{$name});
 3204:                 }
 3205:             }
 3206:             &tool_changes('tools',\@usertools,\%oldsettings,\%oldsettingstext,\%userenv,
 3207:                           \%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3208:             if ($env{'form.ccdomain'} eq $env{'request.role.domain'}) {
 3209:                 &tool_changes('requestcourses',\@requestcourses,\%oldsettings,\%oldsettingstext,
 3210:                               \%userenv,\%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3211:                 &tool_changes('requestauthor',\@requestauthor,\%oldsettings,\%oldsettingstext,
 3212:                               \%userenv,\%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3213:             } else {
 3214:                 &tool_changes('reqcrsotherdom',\@requestcourses,\%oldsettings,\%oldsettingstext,
 3215:                               \%userenv,\%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3216:             }
 3217:         }
 3218:         foreach my $item (@userinfo) {
 3219:             if ($env{'form.c'.$item} ne $userenv{$item}) {
 3220:                 $namechanged{$item} = 1;
 3221:             }
 3222:         }
 3223:         foreach my $name ('portfolio','author') {
 3224:             $oldsettings{'quota'}{$name} = &mt('[_1] MB',$oldquota{$name});
 3225:             $newsettings{'quota'}{$name} = &mt('[_1] MB',$newquota{$name});
 3226:         }
 3227:         if ((keys(%namechanged) > 0) || (keys(%changed) > 0)) {
 3228:             my ($chgresult,$namechgresult);
 3229:             if (keys(%changed) > 0) {
 3230:                 $chgresult = 
 3231:                     &Apache::lonnet::put('environment',\%changeHash,
 3232:                                   $env{'form.ccdomain'},$env{'form.ccuname'});
 3233:                 if ($chgresult eq 'ok') {
 3234:                     if (($env{'user.name'} eq $env{'form.ccuname'}) &&
 3235:                         ($env{'user.domain'} eq $env{'form.ccdomain'})) {
 3236:                         my %newenvhash;
 3237:                         foreach my $key (keys(%changed)) {
 3238:                             if (($key eq 'official') || ($key eq 'unofficial') ||
 3239:                                 ($key eq 'community') || ($key eq 'textbook') ||
 3240:                                 ($key eq 'placement')) {
 3241:                                 $newenvhash{'environment.requestcourses.'.$key} =
 3242:                                     $changeHash{'requestcourses.'.$key};
 3243:                                 if ($changeHash{'requestcourses.'.$key}) {
 3244:                                     $newenvhash{'environment.canrequest.'.$key} = 1;
 3245:                                 } else {
 3246:                                     $newenvhash{'environment.canrequest.'.$key} =
 3247:           &Apache::lonnet::usertools_access($env{'user.name'},$env{'user.domain'},
 3248:                                             $key,'reload','requestcourses');
 3249:                                 }
 3250:                             } elsif ($key eq 'requestauthor') {
 3251:                                 $newenvhash{'environment.'.$key} = $changeHash{$key};
 3252:                                 if ($changeHash{$key}) {
 3253:                                     $newenvhash{'environment.canrequest.author'} = 1;
 3254:                                 } else {
 3255:                                     $newenvhash{'environment.canrequest.author'} =
 3256:           &Apache::lonnet::usertools_access($env{'user.name'},$env{'user.domain'},
 3257:                                             $key,'reload','requestauthor');
 3258:                                 }
 3259:                             } elsif ($key ne 'quota') {
 3260:                                 $newenvhash{'environment.tools.'.$key} = 
 3261:                                     $changeHash{'tools.'.$key};
 3262:                                 if ($changeHash{'tools.'.$key} ne '') {
 3263:                                     $newenvhash{'environment.availabletools.'.$key} =
 3264:                                         $changeHash{'tools.'.$key};
 3265:                                 } else {
 3266:                                     $newenvhash{'environment.availabletools.'.$key} =
 3267:           &Apache::lonnet::usertools_access($env{'user.name'},$env{'user.domain'},
 3268:           $key,'reload','tools');
 3269:                                 }
 3270:                             }
 3271:                         }
 3272:                         if (keys(%newenvhash)) {
 3273:                             &Apache::lonnet::appenv(\%newenvhash);
 3274:                         }
 3275:                     }
 3276:                 }
 3277:             }
 3278:             if (keys(%namechanged) > 0) {
 3279:                 foreach my $field (@userinfo) {
 3280:                     $changeHash{$field}  = $env{'form.c'.$field};
 3281:                 }
 3282: # Make the change
 3283:                 $namechgresult =
 3284:                     &Apache::lonnet::modifyuser($env{'form.ccdomain'},
 3285:                         $env{'form.ccuname'},$changeHash{'id'},undef,undef,
 3286:                         $changeHash{'firstname'},$changeHash{'middlename'},
 3287:                         $changeHash{'lastname'},$changeHash{'generation'},
 3288:                         $changeHash{'id'},undef,$changeHash{'permanentemail'},undef,\@userinfo);
 3289:                 %userupdate = (
 3290:                                lastname   => $env{'form.clastname'},
 3291:                                middlename => $env{'form.cmiddlename'},
 3292:                                firstname  => $env{'form.cfirstname'},
 3293:                                generation => $env{'form.cgeneration'},
 3294:                                id         => $env{'form.cid'},
 3295:                              );
 3296:             }
 3297:             if (((keys(%namechanged) > 0) && $namechgresult eq 'ok') || 
 3298:                 ((keys(%changed) > 0) && $chgresult eq 'ok')) {
 3299:             # Tell the user we changed the name
 3300:                 &display_userinfo($r,1,\@disporder,\%canshow,\@requestcourses,
 3301:                                   \@usertools,\@requestauthor,\%userenv,\%changed,\%namechanged,
 3302:                                   \%oldsettings, \%oldsettingstext,\%newsettings,
 3303:                                   \%newsettingstext);
 3304:                 if ($env{'form.cid'} ne $userenv{'id'}) {
 3305:                     &Apache::lonnet::idput($env{'form.ccdomain'},
 3306:                          {$env{'form.ccuname'} => $env{'form.cid'}},$uhome,'ids');
 3307:                     if (($recurseid) &&
 3308:                         (&Apache::lonnet::allowed('mau',$env{'form.ccdomain'}))) {
 3309:                         my $idresult = 
 3310:                             &Apache::lonuserutils::propagate_id_change(
 3311:                                 $env{'form.ccuname'},$env{'form.ccdomain'},
 3312:                                 \%userupdate);
 3313:                         $r->print('<br />'.$idresult.'<br />');
 3314:                     }
 3315:                 }
 3316:                 if (($env{'form.ccdomain'} eq $env{'user.domain'}) && 
 3317:                     ($env{'form.ccuname'} eq $env{'user.name'})) {
 3318:                     my %newenvhash;
 3319:                     foreach my $key (keys(%changeHash)) {
 3320:                         $newenvhash{'environment.'.$key} = $changeHash{$key};
 3321:                     }
 3322:                     &Apache::lonnet::appenv(\%newenvhash);
 3323:                 }
 3324:             } else { # error occurred
 3325:                 $r->print(
 3326:                     '<p class="LC_error">'
 3327:                    .&mt('Unable to successfully change environment for [_1] in domain [_2].',
 3328:                             '"'.$env{'form.ccuname'}.'"',
 3329:                             '"'.$env{'form.ccdomain'}.'"')
 3330:                    .'</p>');
 3331:             }
 3332:         } else { # End of if ($env ... ) logic
 3333:             # They did not want to change the users name, quota, tool availability,
 3334:             # or ability to request creation of courses, 
 3335:             # but we can still tell them what the name and quota and availabilities are  
 3336:             &display_userinfo($r,undef,\@disporder,\%canshow,\@requestcourses,
 3337:                               \@usertools,\@requestauthor,\%userenv,\%changed,\%namechanged,\%oldsettings,
 3338:                               \%oldsettingstext,\%newsettings,\%newsettingstext);
 3339:         }
 3340:         if (@mod_disallowed) {
 3341:             my ($rolestr,$contextname);
 3342:             if (@longroles > 0) {
 3343:                 $rolestr = join(', ',@longroles);
 3344:             } else {
 3345:                 $rolestr = &mt('No roles');
 3346:             }
 3347:             if ($context eq 'course') {
 3348:                 $contextname = 'course';
 3349:             } elsif ($context eq 'author') {
 3350:                 $contextname = 'co-author';
 3351:             }
 3352:             $r->print(&mt('The following fields were not updated: ').'<ul>');
 3353:             my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
 3354:             foreach my $field (@mod_disallowed) {
 3355:                 $r->print('<li>'.$fieldtitles{$field}.'</li>'."\n"); 
 3356:             }
 3357:             $r->print('</ul>');
 3358:             if (@mod_disallowed == 1) {
 3359:                 $r->print(&mt("You do not have the authority to change this field given the user's current set of active/future $contextname roles:"));
 3360:             } else {
 3361:                 $r->print(&mt("You do not have the authority to change these fields given the user's current set of active/future $contextname roles:"));
 3362:             }
 3363:             my $helplink = 'javascript:helpMenu('."'display'".')';
 3364:             $r->print('<span class="LC_cusr_emph">'.$rolestr.'</span><br />'
 3365:                      .&mt('Please contact your [_1]helpdesk[_2] for more information.'
 3366:                          ,'<a href="'.$helplink.'">','</a>')
 3367:                       .'<br />');
 3368:         }
 3369:         $r->print('<span class="LC_warning">'
 3370:                   .$no_forceid_alert
 3371:                   .&Apache::lonuserutils::print_namespacing_alerts($env{'form.ccdomain'},\%alerts,\%curr_rules)
 3372:                   .'</span>');
 3373:     }
 3374:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 3375:     if ($env{'form.action'} eq 'singlestudent') {
 3376:         &enroll_single_student($r,$uhome,$amode,$genpwd,$now,$newuser,$context,
 3377:                                $crstype,$showcredits,$defaultcredits);
 3378:         my $linktext = ($crstype eq 'Community' ?
 3379:             &mt('Enroll Another Member') : &mt('Enroll Another Student'));
 3380:         $r->print(
 3381:             &Apache::lonhtmlcommon::actionbox([
 3382:                 '<a href="javascript:backPage(document.userupdate)">'
 3383:                .($crstype eq 'Community' ? 
 3384:                     &mt('Enroll Another Member') : &mt('Enroll Another Student'))
 3385:                .'</a>']));
 3386:     } else {
 3387:         my @rolechanges = &update_roles($r,$context,$showcredits);
 3388:         if (keys(%namechanged) > 0) {
 3389:             if ($context eq 'course') {
 3390:                 if (@userroles > 0) {
 3391:                     if ((@rolechanges == 0) || 
 3392:                         (!(grep(/^st$/,@rolechanges)))) {
 3393:                         if (grep(/^st$/,@userroles)) {
 3394:                             my $classlistupdated =
 3395:                                 &Apache::lonuserutils::update_classlist($cdom,
 3396:                                               $cnum,$env{'form.ccdomain'},
 3397:                                        $env{'form.ccuname'},\%userupdate);
 3398:                         }
 3399:                     }
 3400:                 }
 3401:             }
 3402:         }
 3403:         my $userinfo = &Apache::loncommon::plainname($env{'form.ccuname'},
 3404:                                                      $env{'form.ccdomain'});
 3405:         if ($env{'form.popup'}) {
 3406:             $r->print('<p><a href="javascript:window.close()">'.&mt('Close window').'</a></p>');
 3407:         } else {
 3408:             $r->print('<br />'.&Apache::lonhtmlcommon::actionbox(['<a href="javascript:backPage(document.userupdate,'."'$env{'form.prevphase'}','modify'".')">'
 3409:                      .&mt('Modify this user: [_1]','<span class="LC_cusr_emph">'.$env{'form.ccuname'}.':'.$env{'form.ccdomain'}.' ('.$userinfo.')</span>').'</a>',
 3410:                      '<a href="javascript:backPage(document.userupdate)">'.&mt('Create/Modify Another User').'</a>']));
 3411:         }
 3412:     }
 3413: }
 3414: 
 3415: sub display_userinfo {
 3416:     my ($r,$changed,$order,$canshow,$requestcourses,$usertools,$requestauthor,
 3417:         $userenv,$changedhash,$namechangedhash,$oldsetting,$oldsettingtext,
 3418:         $newsetting,$newsettingtext) = @_;
 3419:     return unless (ref($order) eq 'ARRAY' &&
 3420:                    ref($canshow) eq 'HASH' && 
 3421:                    ref($requestcourses) eq 'ARRAY' && 
 3422:                    ref($requestauthor) eq 'ARRAY' &&
 3423:                    ref($usertools) eq 'ARRAY' && 
 3424:                    ref($userenv) eq 'HASH' &&
 3425:                    ref($changedhash) eq 'HASH' &&
 3426:                    ref($oldsetting) eq 'HASH' &&
 3427:                    ref($oldsettingtext) eq 'HASH' &&
 3428:                    ref($newsetting) eq 'HASH' &&
 3429:                    ref($newsettingtext) eq 'HASH');
 3430:     my %lt=&Apache::lonlocal::texthash(
 3431:          'ui'             => 'User Information',
 3432:          'uic'            => 'User Information Changed',
 3433:          'firstname'      => 'First Name',
 3434:          'middlename'     => 'Middle Name',
 3435:          'lastname'       => 'Last Name',
 3436:          'generation'     => 'Generation',
 3437:          'id'             => 'Student/Employee ID',
 3438:          'permanentemail' => 'Permanent e-mail address',
 3439:          'portfolioquota' => 'Disk space allocated to portfolio files',
 3440:          'authorquota'    => 'Disk space allocated to Authoring Space',
 3441:          'blog'           => 'Blog Availability',
 3442:          'webdav'         => 'WebDAV Availability',
 3443:          'aboutme'        => 'Personal Information Page Availability',
 3444:          'portfolio'      => 'Portfolio Availability',
 3445:          'official'       => 'Can Request Official Courses',
 3446:          'unofficial'     => 'Can Request Unofficial Courses',
 3447:          'community'      => 'Can Request Communities',
 3448:          'textbook'       => 'Can Request Textbook Courses',
 3449:          'placement'      => 'Can Request Placement Tests',
 3450:          'requestauthor'  => 'Can Request Author Role',
 3451:          'inststatus'     => "Affiliation",
 3452:          'prvs'           => 'Previous Value:',
 3453:          'chto'           => 'Changed To:'
 3454:     );
 3455:     if ($changed) {
 3456:         $r->print('<h3>'.$lt{'uic'}.'</h3>'.
 3457:                 &Apache::loncommon::start_data_table().
 3458:                 &Apache::loncommon::start_data_table_header_row());
 3459:         $r->print("<th>&nbsp;</th>\n");
 3460:         $r->print('<th><b>'.$lt{'prvs'}.'</b></th>');
 3461:         $r->print('<th><span class="LC_nobreak"><b>'.$lt{'chto'}.'</b></span></th>');
 3462:         $r->print(&Apache::loncommon::end_data_table_header_row());
 3463:         my @userinfo = ('firstname','middlename','lastname','generation','permanentemail','id');
 3464: 
 3465:         foreach my $item (@userinfo) {
 3466:             my $value = $env{'form.c'.$item};
 3467:             #show changes only:
 3468:             unless ($value eq $userenv->{$item}){
 3469:                 $r->print(&Apache::loncommon::start_data_table_row());
 3470:                 $r->print("<td>$lt{$item}</td>\n");
 3471:                 $r->print("<td>".$userenv->{$item}."</td>\n");
 3472:                 $r->print("<td>$value </td>\n");
 3473:                 $r->print(&Apache::loncommon::end_data_table_row());
 3474:             }
 3475:         }
 3476:         foreach my $entry (@{$order}) {
 3477:             if ($canshow->{$entry}) {
 3478:                 if (($entry eq 'requestcourses') || ($entry eq 'reqcrsotherdom') || ($entry eq 'requestauthor')) {
 3479:                     my @items;
 3480:                     if ($entry eq 'requestauthor') {
 3481:                         @items = ($entry);
 3482:                     } else {
 3483:                         @items = @{$requestcourses};
 3484:                     }
 3485:                     foreach my $item (@items) {
 3486:                         if (($newsetting->{$item} ne $oldsetting->{$item}) || 
 3487:                             ($newsettingtext->{$item} ne $oldsettingtext->{$item})) {
 3488:                             $r->print(&Apache::loncommon::start_data_table_row()."\n");  
 3489:                             $r->print("<td>$lt{$item}</td>\n");
 3490:                             $r->print("<td>".$oldsetting->{$item});
 3491:                             if ($oldsettingtext->{$item}) {
 3492:                                 if ($oldsetting->{$item}) {
 3493:                                     $r->print(' -- ');
 3494:                                 }
 3495:                                 $r->print($oldsettingtext->{$item});
 3496:                             }
 3497:                             $r->print("</td>\n");
 3498:                             $r->print("<td>".$newsetting->{$item});
 3499:                             if ($newsettingtext->{$item}) {
 3500:                                 if ($newsetting->{$item}) {
 3501:                                     $r->print(' -- ');
 3502:                                 }
 3503:                                 $r->print($newsettingtext->{$item});
 3504:                             }
 3505:                             $r->print("</td>\n");
 3506:                             $r->print(&Apache::loncommon::end_data_table_row()."\n");
 3507:                         }
 3508:                     }
 3509:                 } elsif ($entry eq 'tools') {
 3510:                     foreach my $item (@{$usertools}) {
 3511:                         if ($newsetting->{$item} ne $oldsetting->{$item}) {
 3512:                             $r->print(&Apache::loncommon::start_data_table_row()."\n");
 3513:                             $r->print("<td>$lt{$item}</td>\n");
 3514:                             $r->print("<td>".$oldsetting->{$item}.' '.$oldsettingtext->{$item}."</td>\n");
 3515:                             $r->print("<td>".$newsetting->{$item}.' '.$newsettingtext->{$item}."</td>\n");
 3516:                             $r->print(&Apache::loncommon::end_data_table_row()."\n");
 3517:                         }
 3518:                     }
 3519:                 } elsif ($entry eq 'quota') {
 3520:                     if ((ref($oldsetting->{$entry}) eq 'HASH') && (ref($oldsettingtext->{$entry}) eq 'HASH') &&
 3521:                         (ref($newsetting->{$entry}) eq 'HASH') && (ref($newsettingtext->{$entry}) eq 'HASH')) {
 3522:                         foreach my $name ('portfolio','author') {
 3523:                             if ($newsetting->{$entry}->{$name} ne $oldsetting->{$entry}->{$name}) {
 3524:                                 $r->print(&Apache::loncommon::start_data_table_row()."\n");
 3525:                                 $r->print("<td>$lt{$name.$entry}</td>\n");
 3526:                                 $r->print("<td>".$oldsettingtext->{$entry}->{$name}."</td>\n");
 3527:                                 $r->print("<td>".$newsettingtext->{$entry}->{$name}."</td>\n");
 3528:                                 $r->print(&Apache::loncommon::end_data_table_row()."\n");
 3529:                             }
 3530:                         }
 3531:                     }
 3532:                 } else {
 3533:                     if ($newsetting->{$entry} ne $oldsetting->{$entry}) {
 3534:                         $r->print(&Apache::loncommon::start_data_table_row()."\n");
 3535:                         $r->print("<td>$lt{$entry}</td>\n");
 3536:                         $r->print("<td>".$oldsetting->{$entry}.' '.$oldsettingtext->{$entry}."</td>\n");
 3537:                         $r->print("<td>".$newsetting->{$entry}.' '.$newsettingtext->{$entry}."</td>\n");
 3538:                         $r->print(&Apache::loncommon::end_data_table_row()."\n");
 3539:                     }
 3540:                 }
 3541:             }
 3542:         }
 3543:         $r->print(&Apache::loncommon::end_data_table().'<br />');
 3544:     } else {
 3545:         $r->print('<h3>'.$lt{'ui'}.'</h3>'.
 3546:                   '<p>'.&mt('No changes made to user information').'</p>');
 3547:     }
 3548:     return;
 3549: }
 3550: 
 3551: sub tool_changes {
 3552:     my ($context,$usertools,$oldaccess,$oldaccesstext,$userenv,$changeHash,
 3553:         $changed,$newaccess,$newaccesstext) = @_;
 3554:     if (!((ref($usertools) eq 'ARRAY') && (ref($oldaccess) eq 'HASH') &&
 3555:           (ref($oldaccesstext) eq 'HASH') && (ref($userenv) eq 'HASH') &&
 3556:           (ref($changeHash) eq 'HASH') && (ref($changed) eq 'HASH') &&
 3557:           (ref($newaccess) eq 'HASH') && (ref($newaccesstext) eq 'HASH'))) {
 3558:         return;
 3559:     }
 3560:     my %reqdisplay = &requestchange_display();
 3561:     if ($context eq 'reqcrsotherdom') {
 3562:         my @options = ('approval','validate','autolimit');
 3563:         my $optregex = join('|',@options);
 3564:         my $cdom = $env{'request.role.domain'};
 3565:         foreach my $tool (@{$usertools}) {
 3566:             $oldaccesstext->{$tool} = &mt("availability set to 'off'");
 3567:             $newaccesstext->{$tool} = $oldaccesstext->{$tool};
 3568:             $changeHash->{$context.'.'.$tool} = $userenv->{$context.'.'.$tool};
 3569:             my ($newop,$limit);
 3570:             if ($env{'form.'.$context.'_'.$tool}) {
 3571:                 $newop = $env{'form.'.$context.'_'.$tool};
 3572:                 if ($newop eq 'autolimit') {
 3573:                     $limit = $env{'form.'.$context.'_'.$tool.'_limit'};
 3574:                     $limit =~ s/\D+//g;
 3575:                     $newop .= '='.$limit;
 3576:                 }
 3577:             }
 3578:             if ($userenv->{$context.'.'.$tool} eq '') {
 3579:                 if ($newop) {
 3580:                     $changed->{$tool}=&tool_admin($tool,$cdom.':'.$newop,
 3581:                                                   $changeHash,$context);
 3582:                     if ($changed->{$tool}) {
 3583:                         if ($newop =~ /^autolimit/) {
 3584:                             if ($limit) {
 3585:                                 $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3586:                             } else {
 3587:                                 $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3588:                             }
 3589:                         } else {
 3590:                             $newaccesstext->{$tool} = $reqdisplay{$newop};
 3591:                         }
 3592:                     } else {
 3593:                         $newaccesstext->{$tool} = $oldaccesstext->{$tool};
 3594:                     }
 3595:                 }
 3596:             } else {
 3597:                 my @curr = split(',',$userenv->{$context.'.'.$tool});
 3598:                 my @new;
 3599:                 my $changedoms;
 3600:                 foreach my $req (@curr) {
 3601:                     if ($req =~ /^\Q$cdom\E\:($optregex\=?\d*)$/) {
 3602:                         my $oldop = $1;
 3603:                         if ($oldop =~ /^autolimit=(\d*)/) {
 3604:                             my $limit = $1;
 3605:                             if ($limit) {
 3606:                                 $oldaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3607:                             } else {
 3608:                                 $oldaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3609:                             }
 3610:                         } else {
 3611:                             $oldaccesstext->{$tool} = $reqdisplay{$oldop};
 3612:                         }
 3613:                         if ($oldop ne $newop) {
 3614:                             $changedoms = 1;
 3615:                             foreach my $item (@curr) {
 3616:                                 my ($reqdom,$option) = split(':',$item);
 3617:                                 unless ($reqdom eq $cdom) {
 3618:                                     push(@new,$item);
 3619:                                 }
 3620:                             }
 3621:                             if ($newop) {
 3622:                                 push(@new,$cdom.':'.$newop);
 3623:                             }
 3624:                             @new = sort(@new);
 3625:                         }
 3626:                         last;
 3627:                     }
 3628:                 }
 3629:                 if ((!$changedoms) && ($newop)) {
 3630:                     $changedoms = 1;
 3631:                     @new = sort(@curr,$cdom.':'.$newop);
 3632:                 }
 3633:                 if ($changedoms) {
 3634:                     my $newdomstr;
 3635:                     if (@new) {
 3636:                         $newdomstr = join(',',@new);
 3637:                     }
 3638:                     $changed->{$tool}=&tool_admin($tool,$newdomstr,$changeHash,
 3639:                                                   $context);
 3640:                     if ($changed->{$tool}) {
 3641:                         if ($env{'form.'.$context.'_'.$tool}) {
 3642:                             if ($env{'form.'.$context.'_'.$tool} eq 'autolimit') {
 3643:                                 my $limit = $env{'form.'.$context.'_'.$tool.'_limit'};
 3644:                                 $limit =~ s/\D+//g;
 3645:                                 if ($limit) {
 3646:                                     $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3647:                                 } else {
 3648:                                     $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3649:                                 }
 3650:                             } else {
 3651:                                 $newaccesstext->{$tool} = $reqdisplay{$env{'form.'.$context.'_'.$tool}};
 3652:                             }
 3653:                         } else {
 3654:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3655:                         }
 3656:                     }
 3657:                 }
 3658:             }
 3659:         }
 3660:         return;
 3661:     }
 3662:     foreach my $tool (@{$usertools}) {
 3663:         my ($newval,$limit,$envkey);
 3664:         $envkey = $context.'.'.$tool;
 3665:         if ($context eq 'requestcourses') {
 3666:             $newval = $env{'form.crsreq_'.$tool};
 3667:             if ($newval eq 'autolimit') {
 3668:                 $limit = $env{'form.crsreq_'.$tool.'_limit'};
 3669:                 $limit =~ s/\D+//g;
 3670:                 $newval .= '='.$limit;
 3671:             }
 3672:         } elsif ($context eq 'requestauthor') {
 3673:             $newval = $env{'form.'.$context};
 3674:             $envkey = $context;
 3675:         } else {
 3676:             $newval = $env{'form.'.$context.'_'.$tool};
 3677:         }
 3678:         if ($userenv->{$envkey} ne '') {
 3679:             $oldaccess->{$tool} = &mt('custom');
 3680:             if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 3681:                 if ($userenv->{$envkey} =~ /^autolimit=(\d*)$/) {
 3682:                     my $currlimit = $1;
 3683:                     if ($currlimit eq '') {
 3684:                         $oldaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3685:                     } else {
 3686:                         $oldaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$currlimit);
 3687:                     }
 3688:                 } elsif ($userenv->{$envkey}) {
 3689:                     $oldaccesstext->{$tool} = $reqdisplay{$userenv->{$envkey}};
 3690:                 } else {
 3691:                     $oldaccesstext->{$tool} = &mt("availability set to 'off'");
 3692:                 }
 3693:             } else {
 3694:                 if ($userenv->{$envkey}) {
 3695:                     $oldaccesstext->{$tool} = &mt("availability set to 'on'");
 3696:                 } else {
 3697:                     $oldaccesstext->{$tool} = &mt("availability set to 'off'");
 3698:                 }
 3699:             }
 3700:             $changeHash->{$envkey} = $userenv->{$envkey};
 3701:             if ($env{'form.custom'.$tool} == 1) {
 3702:                 if ($newval ne $userenv->{$envkey}) {
 3703:                     $changed->{$tool} = &tool_admin($tool,$newval,$changeHash,
 3704:                                                     $context);
 3705:                     if ($changed->{$tool}) {
 3706:                         $newaccess->{$tool} = &mt('custom');
 3707:                         if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 3708:                             if ($newval =~ /^autolimit/) {
 3709:                                 if ($limit) {
 3710:                                     $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3711:                                 } else {
 3712:                                     $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3713:                                 }
 3714:                             } elsif ($newval) {
 3715:                                 $newaccesstext->{$tool} = $reqdisplay{$newval};
 3716:                             } else {
 3717:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3718:                             }
 3719:                         } else {
 3720:                             if ($newval) {
 3721:                                 $newaccesstext->{$tool} = &mt("availability set to 'on'");
 3722:                             } else {
 3723:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3724:                             }
 3725:                         }
 3726:                     } else {
 3727:                         $newaccess->{$tool} = $oldaccess->{$tool};
 3728:                         if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 3729:                             if ($newval =~ /^autolimit/) {
 3730:                                 if ($limit) {
 3731:                                     $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3732:                                 } else {
 3733:                                     $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3734:                                 }
 3735:                             } elsif ($newval) {
 3736:                                 $newaccesstext->{$tool} = $reqdisplay{$newval};
 3737:                             } else {
 3738:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3739:                             }
 3740:                         } else {
 3741:                             if ($userenv->{$context.'.'.$tool}) {
 3742:                                 $newaccesstext->{$tool} = &mt("availability set to 'on'");
 3743:                             } else {
 3744:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3745:                             }
 3746:                         }
 3747:                     }
 3748:                 } else {
 3749:                     $newaccess->{$tool} = $oldaccess->{$tool};
 3750:                     $newaccesstext->{$tool} = $oldaccesstext->{$tool};
 3751:                 }
 3752:             } else {
 3753:                 $changed->{$tool} = &tool_admin($tool,'',$changeHash,$context);
 3754:                 if ($changed->{$tool}) {
 3755:                     $newaccess->{$tool} = &mt('default');
 3756:                 } else {
 3757:                     $newaccess->{$tool} = $oldaccess->{$tool};
 3758:                     if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 3759:                         if ($newval =~ /^autolimit/) {
 3760:                             if ($limit) {
 3761:                                 $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3762:                             } else {
 3763:                                 $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3764:                             }
 3765:                         } elsif ($newval) {
 3766:                             $newaccesstext->{$tool} = $reqdisplay{$newval};
 3767:                         } else {
 3768:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3769:                         }
 3770:                     } else {
 3771:                         if ($userenv->{$context.'.'.$tool}) {
 3772:                             $newaccesstext->{$tool} = &mt("availability set to 'on'");
 3773:                         } else {
 3774:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3775:                         }
 3776:                     }
 3777:                 }
 3778:             }
 3779:         } else {
 3780:             $oldaccess->{$tool} = &mt('default');
 3781:             if ($env{'form.custom'.$tool} == 1) {
 3782:                 $changed->{$tool} = &tool_admin($tool,$newval,$changeHash,
 3783:                                                 $context);
 3784:                 if ($changed->{$tool}) {
 3785:                     $newaccess->{$tool} = &mt('custom');
 3786:                     if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 3787:                         if ($newval =~ /^autolimit/) {
 3788:                             if ($limit) {
 3789:                                 $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3790:                             } else {
 3791:                                 $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3792:                             }
 3793:                         } elsif ($newval) {
 3794:                             $newaccesstext->{$tool} = $reqdisplay{$newval};
 3795:                         } else {
 3796:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3797:                         }
 3798:                     } else {
 3799:                         if ($newval) {
 3800:                             $newaccesstext->{$tool} = &mt("availability set to 'on'");
 3801:                         } else {
 3802:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3803:                         }
 3804:                     }
 3805:                 } else {
 3806:                     $newaccess->{$tool} = $oldaccess->{$tool};
 3807:                 }
 3808:             } else {
 3809:                 $newaccess->{$tool} = $oldaccess->{$tool};
 3810:             }
 3811:         }
 3812:     }
 3813:     return;
 3814: }
 3815: 
 3816: sub update_roles {
 3817:     my ($r,$context,$showcredits) = @_;
 3818:     my $now=time;
 3819:     my @rolechanges;
 3820:     my %disallowed;
 3821:     $r->print('<h3>'.&mt('Modifying Roles').'</h3>');
 3822:     foreach my $key (keys(%env)) {
 3823: 	next if (! $env{$key});
 3824:         next if ($key eq 'form.action');
 3825: 	# Revoke roles
 3826: 	if ($key=~/^form\.rev/) {
 3827: 	    if ($key=~/^form\.rev\:([^\_]+)\_([^\_\.]+)$/) {
 3828: # Revoke standard role
 3829: 		my ($scope,$role) = ($1,$2);
 3830: 		my $result =
 3831: 		    &Apache::lonnet::revokerole($env{'form.ccdomain'},
 3832: 						$env{'form.ccuname'},
 3833: 						$scope,$role,'','',$context);
 3834:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
 3835:                             &mt('Revoking [_1] in [_2]',
 3836:                                 &Apache::lonnet::plaintext($role),
 3837:                                 &Apache::loncommon::show_role_extent($scope,$context,$role)),
 3838:                                 $result ne "ok").'<br />');
 3839:                 if ($result ne "ok") {
 3840:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 3841:                 }
 3842: 		if ($role eq 'st') {
 3843: 		    my $result = 
 3844:                         &Apache::lonuserutils::classlist_drop($scope,
 3845:                             $env{'form.ccuname'},$env{'form.ccdomain'},
 3846: 			    $now);
 3847:                     $r->print(&Apache::lonhtmlcommon::confirm_success($result));
 3848: 		}
 3849:                 if (!grep(/^\Q$role\E$/,@rolechanges)) {
 3850:                     push(@rolechanges,$role);
 3851:                 }
 3852: 	    }
 3853: 	    if ($key=~m{^form\.rev\:([^_]+)_cr\.cr/($match_domain)/($match_username)/(\w+)$}s) {
 3854: # Revoke custom role
 3855:                 my $result = &Apache::lonnet::revokecustomrole(
 3856:                     $env{'form.ccdomain'},$env{'form.ccuname'},$1,$2,$3,$4,'','',$context);
 3857:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
 3858:                             &mt('Revoking custom role [_1] by [_2] in [_3]',
 3859:                                 $4,$3.':'.$2,&Apache::loncommon::show_role_extent($1,$context,'cr')),
 3860:                             $result ne 'ok').'<br />');
 3861:                 if ($result ne "ok") {
 3862:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 3863:                 }
 3864:                 if (!grep(/^cr$/,@rolechanges)) {
 3865:                     push(@rolechanges,'cr');
 3866:                 }
 3867: 	    }
 3868: 	} elsif ($key=~/^form\.del/) {
 3869: 	    if ($key=~/^form\.del\:([^\_]+)\_([^\_\.]+)$/) {
 3870: # Delete standard role
 3871: 		my ($scope,$role) = ($1,$2);
 3872: 		my $result =
 3873: 		    &Apache::lonnet::assignrole($env{'form.ccdomain'},
 3874: 						$env{'form.ccuname'},
 3875: 						$scope,$role,$now,0,1,'',
 3876:                                                 $context);
 3877:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
 3878:                             &mt('Deleting [_1] in [_2]',
 3879:                                 &Apache::lonnet::plaintext($role),
 3880:                                 &Apache::loncommon::show_role_extent($scope,$context,$role)),
 3881:                             $result ne 'ok').'<br />');
 3882:                 if ($result ne "ok") {
 3883:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 3884:                 }
 3885: 
 3886: 		if ($role eq 'st') {
 3887: 		    my $result = 
 3888:                         &Apache::lonuserutils::classlist_drop($scope,
 3889:                             $env{'form.ccuname'},$env{'form.ccdomain'},
 3890: 			    $now);
 3891: 		    $r->print(&Apache::lonhtmlcommon::confirm_success($result));
 3892: 		}
 3893:                 if (!grep(/^\Q$role\E$/,@rolechanges)) {
 3894:                     push(@rolechanges,$role);
 3895:                 }
 3896:             }
 3897: 	    if ($key=~m{^form\.del\:([^_]+)_cr\.cr/($match_domain)/($match_username)/(\w+)$}) {
 3898:                 my ($url,$rdom,$rnam,$rolename) = ($1,$2,$3,$4);
 3899: # Delete custom role
 3900:                 my $result =
 3901:                     &Apache::lonnet::assigncustomrole($env{'form.ccdomain'},
 3902:                         $env{'form.ccuname'},$url,$rdom,$rnam,$rolename,$now,
 3903:                         0,1,$context);
 3904:                 $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('Deleting custom role [_1] by [_2] in [_3]',
 3905:                       $rolename,$rnam.':'.$rdom,&Apache::loncommon::show_role_extent($1,$context,'cr')),
 3906:                       $result ne "ok").'<br />');
 3907:                 if ($result ne "ok") {
 3908:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 3909:                 }
 3910: 
 3911:                 if (!grep(/^cr$/,@rolechanges)) {
 3912:                     push(@rolechanges,'cr');
 3913:                 }
 3914:             }
 3915: 	} elsif ($key=~/^form\.ren/) {
 3916:             my $udom = $env{'form.ccdomain'};
 3917:             my $uname = $env{'form.ccuname'};
 3918: # Re-enable standard role
 3919: 	    if ($key=~/^form\.ren\:([^\_]+)\_([^\_\.]+)$/) {
 3920:                 my $url = $1;
 3921:                 my $role = $2;
 3922:                 my $logmsg;
 3923:                 my $output;
 3924:                 if ($role eq 'st') {
 3925:                     if ($url =~ m-^/($match_domain)/($match_courseid)/?(\w*)$-) {
 3926:                         my ($cdom,$cnum,$csec) = ($1,$2,$3);
 3927:                         my $credits;
 3928:                         if ($showcredits) {
 3929:                             my $defaultcredits = 
 3930:                                 &Apache::lonuserutils::get_defaultcredits($cdom,$cnum);
 3931:                             $credits = &get_user_credits($defaultcredits,$cdom,$cnum);
 3932:                         }
 3933:                         my $result = &Apache::loncommon::commit_studentrole(\$logmsg,$udom,$uname,$url,$role,$now,0,$cdom,$cnum,$csec,$context,$credits);
 3934:                         if (($result =~ /^error/) || ($result eq 'not_in_class') || ($result eq 'unknown_course') || ($result eq 'refused')) {
 3935:                             if ($result eq 'refused' && $logmsg) {
 3936:                                 $output = $logmsg;
 3937:                             } else { 
 3938:                                 $output = &mt('Error: [_1]',$result)."\n";
 3939:                             }
 3940:                         } else {
 3941:                             $output = &Apache::lonhtmlcommon::confirm_success(&mt('Assigning [_1] in [_2] starting [_3]',
 3942:                                         &Apache::lonnet::plaintext($role),
 3943:                                         &Apache::loncommon::show_role_extent($url,$context,'st'),
 3944:                                         &Apache::lonlocal::locallocaltime($now))).'<br />'.$logmsg.'<br />';
 3945:                         }
 3946:                     }
 3947:                 } else {
 3948: 		    my $result=&Apache::lonnet::assignrole($env{'form.ccdomain'},
 3949:                                $env{'form.ccuname'},$url,$role,0,$now,'','',
 3950:                                $context);
 3951:                         $output = &Apache::lonhtmlcommon::confirm_success(&mt('Re-enabling [_1] in [_2]',
 3952:                                         &Apache::lonnet::plaintext($role),
 3953:                                         &Apache::loncommon::show_role_extent($url,$context,$role)),$result ne "ok").'<br />';
 3954:                     if ($result ne "ok") {
 3955:                         $output .= &mt('Error: [_1]',$result).'<br />';
 3956:                     }
 3957:                 }
 3958:                 $r->print($output);
 3959:                 if (!grep(/^\Q$role\E$/,@rolechanges)) {
 3960:                     push(@rolechanges,$role);
 3961:                 }
 3962: 	    }
 3963: # Re-enable custom role
 3964: 	    if ($key=~m{^form\.ren\:([^_]+)_cr\.cr/($match_domain)/($match_username)/(\w+)$}) {
 3965:                 my ($url,$rdom,$rnam,$rolename) = ($1,$2,$3,$4);
 3966:                 my $result = &Apache::lonnet::assigncustomrole(
 3967:                                $env{'form.ccdomain'}, $env{'form.ccuname'},
 3968:                                $url,$rdom,$rnam,$rolename,0,$now,undef,$context);
 3969:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
 3970:                     &mt('Re-enabling custom role [_1] by [_2] in [_3]',
 3971:                         $rolename,$rnam.':'.$rdom,&Apache::loncommon::show_role_extent($1,$context,'cr')),
 3972:                     $result ne "ok").'<br />');
 3973:                 if ($result ne "ok") {
 3974:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 3975:                 }
 3976:                 if (!grep(/^cr$/,@rolechanges)) {
 3977:                     push(@rolechanges,'cr');
 3978:                 }
 3979:             }
 3980: 	} elsif ($key=~/^form\.act/) {
 3981:             my $udom = $env{'form.ccdomain'};
 3982:             my $uname = $env{'form.ccuname'};
 3983: 	    if ($key=~/^form\.act\_($match_domain)\_($match_courseid)\_cr_cr_($match_domain)_($match_username)_([^\_]+)$/) {
 3984:                 # Activate a custom role
 3985: 		my ($one,$two,$three,$four,$five)=($1,$2,$3,$4,$5);
 3986: 		my $url='/'.$one.'/'.$two;
 3987: 		my $full=$one.'_'.$two.'_cr_cr_'.$three.'_'.$four.'_'.$five;
 3988: 
 3989:                 my $start = ( $env{'form.start_'.$full} ?
 3990:                               $env{'form.start_'.$full} :
 3991:                               $now );
 3992:                 my $end   = ( $env{'form.end_'.$full} ?
 3993:                               $env{'form.end_'.$full} :
 3994:                               0 );
 3995:                                                                                      
 3996:                 # split multiple sections
 3997:                 my %sections = ();
 3998:                 my $num_sections = &build_roles($env{'form.sec_'.$full},\%sections,$5);
 3999:                 if ($num_sections == 0) {
 4000:                     $r->print(&Apache::loncommon::commit_customrole($udom,$uname,$url,$three,$four,$five,$start,$end,$context));
 4001:                 } else {
 4002: 		    my %curr_groups =
 4003: 			&Apache::longroup::coursegroups($one,$two);
 4004:                     foreach my $sec (sort {$a cmp $b} keys(%sections)) {
 4005:                         if (($sec eq 'none') || ($sec eq 'all') || 
 4006:                             exists($curr_groups{$sec})) {
 4007:                             $disallowed{$sec} = $url;
 4008:                             next;
 4009:                         }
 4010:                         my $securl = $url.'/'.$sec;
 4011: 		        $r->print(&Apache::loncommon::commit_customrole($udom,$uname,$securl,$three,$four,$five,$start,$end,$context));
 4012:                     }
 4013:                 }
 4014:                 if (!grep(/^cr$/,@rolechanges)) {
 4015:                     push(@rolechanges,'cr');
 4016:                 }
 4017: 	    } elsif ($key=~/^form\.act\_($match_domain)\_($match_name)\_([^\_]+)$/) {
 4018: 		# Activate roles for sections with 3 id numbers
 4019: 		# set start, end times, and the url for the class
 4020: 		my ($one,$two,$three)=($1,$2,$3);
 4021: 		my $start = ( $env{'form.start_'.$one.'_'.$two.'_'.$three} ? 
 4022: 			      $env{'form.start_'.$one.'_'.$two.'_'.$three} : 
 4023: 			      $now );
 4024: 		my $end   = ( $env{'form.end_'.$one.'_'.$two.'_'.$three} ? 
 4025: 			      $env{'form.end_'.$one.'_'.$two.'_'.$three} :
 4026: 			      0 );
 4027: 		my $url='/'.$one.'/'.$two;
 4028:                 my $type = 'three';
 4029:                 # split multiple sections
 4030:                 my %sections = ();
 4031:                 my $num_sections = &build_roles($env{'form.sec_'.$one.'_'.$two.'_'.$three},\%sections,$three);
 4032:                 my $credits;
 4033:                 if ($three eq 'st') {
 4034:                     if ($showcredits) { 
 4035:                         my $defaultcredits = 
 4036:                             &Apache::lonuserutils::get_defaultcredits($one,$two);
 4037:                         $credits = $env{'form.credits_'.$one.'_'.$two.'_'.$three};
 4038:                         $credits =~ s/[^\d\.]//g;
 4039:                         if ($credits eq $defaultcredits) {
 4040:                             undef($credits);
 4041:                         }
 4042:                     }
 4043:                 }
 4044:                 if ($num_sections == 0) {
 4045:                     $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$three,$start,$end,$one,$two,'',$context,$credits));
 4046:                 } else {
 4047:                     my %curr_groups = 
 4048: 			&Apache::longroup::coursegroups($one,$two);
 4049:                     my $emptysec = 0;
 4050:                     foreach my $sec (sort {$a cmp $b} keys(%sections)) {
 4051:                         $sec =~ s/\W//g;
 4052:                         if ($sec ne '') {
 4053:                             if (($sec eq 'none') || ($sec eq 'all') || 
 4054:                                 exists($curr_groups{$sec})) {
 4055:                                 $disallowed{$sec} = $url;
 4056:                                 next;
 4057:                             }
 4058:                             my $securl = $url.'/'.$sec;
 4059:                             $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$securl,$three,$start,$end,$one,$two,$sec,$context,$credits));
 4060:                         } else {
 4061:                             $emptysec = 1;
 4062:                         }
 4063:                     }
 4064:                     if ($emptysec) {
 4065:                         $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$three,$start,$end,$one,$two,'',$context,$credits));
 4066:                     }
 4067:                 }
 4068:                 if (!grep(/^\Q$three\E$/,@rolechanges)) {
 4069:                     push(@rolechanges,$three);
 4070:                 }
 4071: 	    } elsif ($key=~/^form\.act\_([^\_]+)\_([^\_]+)$/) {
 4072: 		# Activate roles for sections with two id numbers
 4073: 		# set start, end times, and the url for the class
 4074: 		my $start = ( $env{'form.start_'.$1.'_'.$2} ? 
 4075: 			      $env{'form.start_'.$1.'_'.$2} : 
 4076: 			      $now );
 4077: 		my $end   = ( $env{'form.end_'.$1.'_'.$2} ? 
 4078: 			      $env{'form.end_'.$1.'_'.$2} :
 4079: 			      0 );
 4080:                 my $one = $1;
 4081:                 my $two = $2;
 4082: 		my $url='/'.$one.'/';
 4083:                 # split multiple sections
 4084:                 my %sections = ();
 4085:                 my $num_sections = &build_roles($env{'form.sec_'.$one.'_'.$two},\%sections,$two);
 4086:                 if ($num_sections == 0) {
 4087:                     $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$two,$start,$end,$one,undef,'',$context));
 4088:                 } else {
 4089:                     my $emptysec = 0;
 4090:                     foreach my $sec (sort {$a cmp $b} keys(%sections)) {
 4091:                         if ($sec ne '') {
 4092:                             my $securl = $url.'/'.$sec;
 4093:                             $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$securl,$two,$start,$end,$one,undef,$sec,$context));
 4094:                         } else {
 4095:                             $emptysec = 1;
 4096:                         }
 4097:                     }
 4098:                     if ($emptysec) {
 4099:                         $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$two,$start,$end,$one,undef,'',$context));
 4100:                     }
 4101:                 }
 4102:                 if (!grep(/^\Q$two\E$/,@rolechanges)) {
 4103:                     push(@rolechanges,$two);
 4104:                 }
 4105: 	    } else {
 4106: 		$r->print('<p><span class="LC_error">'.&mt('ERROR').': '.&mt('Unknown command').' <tt>'.$key.'</tt></span></p><br />');
 4107:             }
 4108:             foreach my $key (sort(keys(%disallowed))) {
 4109:                 $r->print('<p class="LC_warning">');
 4110:                 if (($key eq 'none') || ($key eq 'all')) {  
 4111:                     $r->print(&mt('[_1] may not be used as the name for a section, as it is a reserved word.','<tt>'.$key.'</tt>'));
 4112:                 } else {
 4113:                     $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>'));
 4114:                 }
 4115:                 $r->print('</p><p>'
 4116:                          .&mt('Please [_1]go back[_2] and choose a different section name.'
 4117:                              ,'<a href="javascript:history.go(-1)'
 4118:                              ,'</a>')
 4119:                          .'</p><br />'
 4120:                 );
 4121:             }
 4122: 	}
 4123:     } # End of foreach (keys(%env))
 4124: # Flush the course logs so reverse user roles immediately updated
 4125:     $r->register_cleanup(\&Apache::lonnet::flushcourselogs);
 4126:     if (@rolechanges == 0) {
 4127:         $r->print('<p>'.&mt('No roles to modify').'</p>');
 4128:     }
 4129:     return @rolechanges;
 4130: }
 4131: 
 4132: sub get_user_credits {
 4133:     my ($uname,$udom,$defaultcredits,$cdom,$cnum) = @_;
 4134:     if ($cdom eq '' || $cnum eq '') {
 4135:         return unless ($env{'request.course.id'});
 4136:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4137:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4138:     }
 4139:     my $credits;
 4140:     my %currhash =
 4141:         &Apache::lonnet::get('classlist',[$uname.':'.$udom],$cdom,$cnum);
 4142:     if (keys(%currhash) > 0) {
 4143:         my @items = split(/:/,$currhash{$uname.':'.$udom});
 4144:         my $crdidx = &Apache::loncoursedata::CL_CREDITS() - 3;
 4145:         $credits = $items[$crdidx];
 4146:         $credits =~ s/[^\d\.]//g;
 4147:     }
 4148:     if ($credits eq $defaultcredits) {
 4149:         undef($credits);
 4150:     }
 4151:     return $credits;
 4152: }
 4153: 
 4154: sub enroll_single_student {
 4155:     my ($r,$uhome,$amode,$genpwd,$now,$newuser,$context,$crstype,
 4156:         $showcredits,$defaultcredits) = @_;
 4157:     $r->print('<h3>');
 4158:     if ($crstype eq 'Community') {
 4159:         $r->print(&mt('Enrolling Member'));
 4160:     } else {
 4161:         $r->print(&mt('Enrolling Student'));
 4162:     }
 4163:     $r->print('</h3>');
 4164: 
 4165:     # Remove non alphanumeric values from section
 4166:     $env{'form.sections'}=~s/\W//g;
 4167: 
 4168:     my $credits;
 4169:     if (($showcredits) && ($env{'form.credits'} ne '')) {
 4170:         $credits = $env{'form.credits'};
 4171:         $credits =~ s/[^\d\.]//g;
 4172:         if ($credits ne '') {
 4173:             if ($credits eq $defaultcredits) {
 4174:                 undef($credits);
 4175:             }
 4176:         }
 4177:     }
 4178: 
 4179:     # Clean out any old student roles the user has in this class.
 4180:     &Apache::lonuserutils::modifystudent($env{'form.ccdomain'},
 4181:          $env{'form.ccuname'},$env{'request.course.id'},undef,$uhome);
 4182:     my ($startdate,$enddate) = &Apache::lonuserutils::get_dates_from_form();
 4183:     my $enroll_result =
 4184:         &Apache::lonnet::modify_student_enrollment($env{'form.ccdomain'},
 4185:             $env{'form.ccuname'},$env{'form.cid'},$env{'form.cfirstname'},
 4186:             $env{'form.cmiddlename'},$env{'form.clastname'},
 4187:             $env{'form.generation'},$env{'form.sections'},$enddate,
 4188:             $startdate,'manual',undef,$env{'request.course.id'},'',$context,
 4189:             $credits);
 4190:     if ($enroll_result =~ /^ok/) {
 4191:         $r->print(&mt('[_1] enrolled','<b>'.$env{'form.ccuname'}.':'.$env{'form.ccdomain'}.'</b>'));
 4192:         if ($env{'form.sections'} ne '') {
 4193:             $r->print(' '.&mt('in section [_1]',$env{'form.sections'}));
 4194:         }
 4195:         my ($showstart,$showend);
 4196:         if ($startdate <= $now) {
 4197:             $showstart = &mt('Access starts immediately');
 4198:         } else {
 4199:             $showstart = &mt('Access starts: ').&Apache::lonlocal::locallocaltime($startdate);
 4200:         }
 4201:         if ($enddate == 0) {
 4202:             $showend = &mt('ends: no ending date');
 4203:         } else {
 4204:             $showend = &mt('ends: ').&Apache::lonlocal::locallocaltime($enddate);
 4205:         }
 4206:         $r->print('.<br />'.$showstart.'; '.$showend);
 4207:         if ($startdate <= $now && !$newuser) {
 4208:             $r->print('<p class="LC_info">');
 4209:             if ($crstype eq 'Community') {
 4210:                 $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.'));
 4211:             } else {
 4212:                 $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.'));
 4213:            }
 4214:            $r->print('</p>');
 4215:         }
 4216:     } else {
 4217:         $r->print(&mt('unable to enroll').": ".$enroll_result);
 4218:     }
 4219:     return;
 4220: }
 4221: 
 4222: sub get_defaultquota_text {
 4223:     my ($settingstatus) = @_;
 4224:     my $defquotatext; 
 4225:     if ($settingstatus eq '') {
 4226:         $defquotatext = &mt('default');
 4227:     } else {
 4228:         my ($usertypes,$order) =
 4229:             &Apache::lonnet::retrieve_inst_usertypes($env{'form.ccdomain'});
 4230:         if ($usertypes->{$settingstatus} eq '') {
 4231:             $defquotatext = &mt('default');
 4232:         } else {
 4233:             $defquotatext = &mt('default for [_1]',$usertypes->{$settingstatus});
 4234:         }
 4235:     }
 4236:     return $defquotatext;
 4237: }
 4238: 
 4239: sub update_result_form {
 4240:     my ($uhome) = @_;
 4241:     my $outcome = 
 4242:     '<form name="userupdate" method="post" action="">'."\n";
 4243:     foreach my $item ('srchby','srchin','srchtype','srchterm','srchdomain','ccuname','ccdomain') {
 4244:         $outcome .= '<input type="hidden" name="'.$item.'" value="'.$env{'form.'.$item}.'" />'."\n";
 4245:     }
 4246:     if ($env{'form.origname'} ne '') {
 4247:         $outcome .= '<input type="hidden" name="origname" value="'.$env{'form.origname'}.'" />'."\n";
 4248:     }
 4249:     foreach my $item ('sortby','seluname','seludom') {
 4250:         if (exists($env{'form.'.$item})) {
 4251:             $outcome .= '<input type="hidden" name="'.$item.'" value="'.$env{'form.'.$item}.'" />'."\n";
 4252:         }
 4253:     }
 4254:     if ($uhome eq 'no_host') {
 4255:         $outcome .= '<input type="hidden" name="forcenewuser" value="1" />'."\n";
 4256:     }
 4257:     $outcome .= '<input type="hidden" name="phase" value="" />'."\n".
 4258:                 '<input type="hidden" name="currstate" value="" />'."\n".
 4259:                 '<input type="hidden" name="action" value="'.$env{'form.action'}.'" />'."\n".
 4260:                 '</form>';
 4261:     return $outcome;
 4262: }
 4263: 
 4264: sub quota_admin {
 4265:     my ($setquota,$changeHash,$name) = @_;
 4266:     my $quotachanged;
 4267:     if (&Apache::lonnet::allowed('mpq',$env{'form.ccdomain'})) {
 4268:         # Current user has quota modification privileges
 4269:         if (ref($changeHash) eq 'HASH') {
 4270:             $quotachanged = 1;
 4271:             $changeHash->{$name.'quota'} = $setquota;
 4272:         }
 4273:     }
 4274:     return $quotachanged;
 4275: }
 4276: 
 4277: sub tool_admin {
 4278:     my ($tool,$settool,$changeHash,$context) = @_;
 4279:     my $canchange = 0; 
 4280:     if ($context eq 'requestcourses') {
 4281:         if (&Apache::lonnet::allowed('ccc',$env{'form.ccdomain'})) {
 4282:             $canchange = 1;
 4283:         }
 4284:     } elsif ($context eq 'reqcrsotherdom') {
 4285:         if (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) {
 4286:             $canchange = 1;
 4287:         }
 4288:     } elsif ($context eq 'requestauthor') {
 4289:         if (&Apache::lonnet::allowed('cau',$env{'request.role.domain'})) {
 4290:             $canchange = 1;
 4291:         }
 4292:     } elsif (&Apache::lonnet::allowed('mut',$env{'form.ccdomain'})) {
 4293:         # Current user has quota modification privileges
 4294:         $canchange = 1;
 4295:     }
 4296:     my $toolchanged;
 4297:     if ($canchange) {
 4298:         if (ref($changeHash) eq 'HASH') {
 4299:             $toolchanged = 1;
 4300:             if ($tool eq 'requestauthor') {
 4301:                 $changeHash->{$context} = $settool;
 4302:             } else {
 4303:                 $changeHash->{$context.'.'.$tool} = $settool;
 4304:             }
 4305:         }
 4306:     }
 4307:     return $toolchanged;
 4308: }
 4309: 
 4310: sub build_roles {
 4311:     my ($sectionstr,$sections,$role) = @_;
 4312:     my $num_sections = 0;
 4313:     if ($sectionstr=~ /,/) {
 4314:         my @secnums = split/,/,$sectionstr;
 4315:         if ($role eq 'st') {
 4316:             $secnums[0] =~ s/\W//g;
 4317:             $$sections{$secnums[0]} = 1;
 4318:             $num_sections = 1;
 4319:         } else {
 4320:             foreach my $sec (@secnums) {
 4321:                 $sec =~ ~s/\W//g;
 4322:                 if (!($sec eq "")) {
 4323:                     if (exists($$sections{$sec})) {
 4324:                         $$sections{$sec} ++;
 4325:                     } else {
 4326:                         $$sections{$sec} = 1;
 4327:                         $num_sections ++;
 4328:                     }
 4329:                 }
 4330:             }
 4331:         }
 4332:     } else {
 4333:         $sectionstr=~s/\W//g;
 4334:         unless ($sectionstr eq '') {
 4335:             $$sections{$sectionstr} = 1;
 4336:             $num_sections ++;
 4337:         }
 4338:     }
 4339: 
 4340:     return $num_sections;
 4341: }
 4342: 
 4343: # ========================================================== Custom Role Editor
 4344: 
 4345: sub custom_role_editor {
 4346:     my ($r,$context,$brcrum,$prefix,$permission) = @_;
 4347:     my $action = $env{'form.customroleaction'};
 4348:     my ($rolename,$helpitem);
 4349:     if ($action eq 'new') {
 4350:         $rolename=$env{'form.newrolename'};
 4351:     } else {
 4352:         $rolename=$env{'form.rolename'};
 4353:     }
 4354: 
 4355:     my ($crstype,$context);
 4356:     if ($env{'request.course.id'}) {
 4357:         $crstype = &Apache::loncommon::course_type();
 4358:         $context = 'course';
 4359:         $helpitem = 'Course_Editing_Custom_Roles';
 4360:     } else {
 4361:         $context = 'domain';
 4362:         $crstype = 'course';
 4363:         $helpitem = 'Domain_Editing_Custom_Roles';
 4364:     }
 4365: 
 4366:     $rolename=~s/[^A-Za-z0-9]//gs;
 4367:     if (!$rolename || $env{'form.phase'} eq 'pickrole') {
 4368: 	&print_username_entry_form($r,$context,undef,undef,undef,$crstype,$brcrum,
 4369:                                    $permission);
 4370:         return;
 4371:     }
 4372: 
 4373:     my $formname = 'form1';
 4374:     my %privs=();
 4375:     my $body_top = '<h2>';
 4376: # ------------------------------------------------------- Does this role exist?
 4377:     my ($rdummy,$roledef)=
 4378: 			 &Apache::lonnet::get('roles',["rolesdef_$rolename"]);
 4379:     if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 4380:         $body_top .= &mt('Existing Role').' "';
 4381: # ------------------------------------------------- Get current role privileges
 4382:         ($privs{'system'},$privs{'domain'},$privs{'course'})=split(/\_/,$roledef);
 4383:         if ($privs{'system'} =~ /bre\&S/) {
 4384:             if ($context eq 'domain') {
 4385:                 $crstype = 'Course';
 4386:             } elsif ($crstype eq 'Community') {
 4387:                 $privs{'system'} =~ s/bre\&S//;
 4388:             }
 4389:         } elsif ($context eq 'domain') {
 4390:             $crstype = 'Course';
 4391:         }
 4392:     } else {
 4393:         $body_top .= &mt('New Role').' "';
 4394:         $roledef='';
 4395:     }
 4396:     $body_top .= $rolename.'"</h2>';
 4397: 
 4398: # ------------------------------------------------------- What can be assigned?
 4399:     my %full=();
 4400:     my %levels=(
 4401:                  course => {},
 4402:                  domain => {},
 4403:                  system => {},
 4404:                );
 4405:     my %levelscurrent=(
 4406:                         course => {},
 4407:                         domain => {},
 4408:                         system => {},
 4409:                       );
 4410:     &Apache::lonuserutils::custom_role_privs(\%privs,\%full,\%levels,\%levelscurrent);
 4411:     my ($jsback,$elements) = &crumb_utilities();
 4412:     my @templateroles = &Apache::lonuserutils::custom_template_roles($context,$crstype);
 4413:     my $head_script =
 4414:         &Apache::lonuserutils::custom_roledefs_js($context,$crstype,$formname,
 4415:                                                   \%full,\@templateroles,$jsback);
 4416:     push (@{$brcrum},
 4417:               {href => "javascript:backPage(document.$formname,'pickrole','')",
 4418:                text => "Pick custom role",
 4419:                faq  => 282,bug=>'Instructor Interface',},
 4420:               {href => "javascript:backPage(document.$formname,'','')",
 4421:                text => "Edit custom role",
 4422:                faq  => 282,
 4423:                bug  => 'Instructor Interface',
 4424:                help => $helpitem}
 4425:               );
 4426:     my $args = { bread_crumbs          => $brcrum,
 4427:                  bread_crumbs_component => 'User Management'};
 4428:     $r->print(&Apache::loncommon::start_page('Custom Role Editor',
 4429:                                              $head_script,$args).
 4430:               $body_top);
 4431:     $r->print('<form name="'.$formname.'" method="post" action="">'."\n".
 4432:               &Apache::lonuserutils::custom_role_header($context,$crstype,
 4433:                                                         \@templateroles,$prefix));
 4434: 
 4435:     $r->print(<<ENDCCF);
 4436: <input type="hidden" name="phase" value="set_custom_roles" />
 4437: <input type="hidden" name="rolename" value="$rolename" />
 4438: ENDCCF
 4439:     $r->print(&Apache::lonuserutils::custom_role_table($crstype,\%full,\%levels,
 4440:                                                        \%levelscurrent,$prefix));
 4441:     $r->print(&Apache::loncommon::end_data_table().
 4442:    '<input type="hidden" name="action" value="'.$env{'form.action'}.'" />'.
 4443:    '<input type="hidden" name="startrolename" value="'.$env{'form.rolename'}.
 4444:    '" />'."\n".'<input type="hidden" name="currstate" value="" />'."\n".
 4445:    '<input type="reset" value="'.&mt("Reset").'" />'."\n".
 4446:    '<input type="submit" value="'.&mt('Save').'" /></form>');
 4447: }
 4448: 
 4449: # ---------------------------------------------------------- Call to definerole
 4450: sub set_custom_role {
 4451:     my ($r,$context,$brcrum,$prefix,$permission) = @_;
 4452:     my $rolename=$env{'form.rolename'};
 4453:     $rolename=~s/[^A-Za-z0-9]//gs;
 4454:     if (!$rolename) {
 4455: 	&custom_role_editor($r,$context,$brcrum,$prefix,$permission);
 4456:         return;
 4457:     }
 4458:     my ($jsback,$elements) = &crumb_utilities();
 4459:     my $jscript = '<script type="text/javascript">'
 4460:                  .'// <![CDATA['."\n"
 4461:                  .$jsback."\n"
 4462:                  .'// ]]>'."\n"
 4463:                  .'</script>'."\n";
 4464:     my $helpitem = 'Course_Editing_Custom_Roles';
 4465:     if ($context eq 'domain') {
 4466:         $helpitem = 'Domain_Editing_Custom_Roles';
 4467:     }
 4468:     push(@{$brcrum},
 4469:         {href => "javascript:backPage(document.customresult,'pickrole','')",
 4470:          text => "Pick custom role",
 4471:          faq  => 282,
 4472:          bug  => 'Instructor Interface',},
 4473:         {href => "javascript:backPage(document.customresult,'selected_custom_edit','')",
 4474:          text => "Edit custom role",
 4475:          faq  => 282,
 4476:          bug  => 'Instructor Interface',},
 4477:         {href => "javascript:backPage(document.customresult,'set_custom_roles','')",
 4478:          text => "Result",
 4479:          faq  => 282,
 4480:          bug  => 'Instructor Interface',
 4481:          help => $helpitem,}
 4482:         );
 4483:     my $args = { bread_crumbs           => $brcrum,
 4484:                  bread_crumbs_component => 'User Management'};
 4485:     $r->print(&Apache::loncommon::start_page('Save Custom Role',$jscript,$args));
 4486: 
 4487:     my $newrole;
 4488:     my ($rdummy,$roledef)=
 4489: 	&Apache::lonnet::get('roles',["rolesdef_$rolename"]);
 4490: 
 4491: # ------------------------------------------------------- Does this role exist?
 4492:     $r->print('<h3>');
 4493:     if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 4494: 	$r->print(&mt('Existing Role').' "');
 4495:     } else {
 4496: 	$r->print(&mt('New Role').' "');
 4497: 	$roledef='';
 4498:         $newrole = 1;
 4499:     }
 4500:     $r->print($rolename.'"</h3>');
 4501: # ------------------------------------------------- Assign role and show result
 4502: 
 4503:     my $errmsg;
 4504:     my %newprivs = &Apache::lonuserutils::custom_role_update($rolename,$prefix);
 4505:     # Assign role and return result
 4506:     my $result = &Apache::lonnet::definerole($rolename,$newprivs{'s'},$newprivs{'d'},
 4507:                                              $newprivs{'c'});
 4508:     if ($result ne 'ok') {
 4509:         $errmsg = ': '.$result;
 4510:     }
 4511:     my $message =
 4512:         &Apache::lonhtmlcommon::confirm_success(
 4513:             &mt('Defining Role').$errmsg, ($result eq 'ok' ? 0 : 1));
 4514:     if ($env{'request.course.id'}) {
 4515:         my $url='/'.$env{'request.course.id'};
 4516:         $url=~s/\_/\//g;
 4517:         $result =
 4518:             &Apache::lonnet::assigncustomrole(
 4519:                 $env{'user.domain'},$env{'user.name'},
 4520:                 $url,
 4521:                 $env{'user.domain'},$env{'user.name'},
 4522:                 $rolename,undef,undef,undef,$context);
 4523:         if ($result ne 'ok') {
 4524:             $errmsg = ': '.$result;
 4525:         }
 4526:         $message .=
 4527:             '<br />'
 4528:            .&Apache::lonhtmlcommon::confirm_success(
 4529:                 &mt('Assigning Role to Self').$errmsg, ($result eq 'ok' ? 0 : 1));
 4530:     }
 4531:     $r->print(
 4532:         &Apache::loncommon::confirmwrapper($message)
 4533:        .'<br />'
 4534:        .&Apache::lonhtmlcommon::actionbox([
 4535:             '<a href="javascript:backPage(document.customresult,'."'pickrole'".')">'
 4536:            .&mt('Create or edit another custom role')
 4537:            .'</a>'])
 4538:        .'<form name="customresult" method="post" action="">'
 4539:        .&Apache::lonhtmlcommon::echo_form_input([])
 4540:        .'</form>'
 4541:     );
 4542: }
 4543: 
 4544: # ================================================================ Main Handler
 4545: sub handler {
 4546:     my $r = shift;
 4547:     if ($r->header_only) {
 4548:        &Apache::loncommon::content_type($r,'text/html');
 4549:        $r->send_http_header;
 4550:        return OK;
 4551:     }
 4552:     my ($context,$crstype,$cid,$cnum,$cdom,$allhelpitems);
 4553: 
 4554:     if ($env{'request.course.id'}) {
 4555:         $context = 'course';
 4556:         $crstype = &Apache::loncommon::course_type();
 4557:     } elsif ($env{'request.role'} =~ /^au\./) {
 4558:         $context = 'author';
 4559:     } else {
 4560:         $context = 'domain';
 4561:     }
 4562: 
 4563:     my ($permission,$allowed) =
 4564:         &Apache::lonuserutils::get_permission($context,$crstype);
 4565: 
 4566:     if ($allowed) {
 4567:         my @allhelp;
 4568:         if ($context eq 'course') {
 4569:             $cid = $env{'request.course.id'};
 4570:             $cdom = $env{'course.'.$cid.'.domain'};
 4571:             $cnum = $env{'course.'.$cid.'.num'};
 4572: 
 4573:             if ($permission->{'cusr'}) {
 4574:                 push(@allhelp,'Course_Create_Class_List');
 4575:             }
 4576:             if ($permission->{'view'} || $permission->{'cusr'}) {
 4577:                 push(@allhelp,('Course_Change_Privileges','Course_View_Class_List'));
 4578:             }
 4579:             if ($permission->{'custom'}) {
 4580:                 push(@allhelp,'Course_Editing_Custom_Roles');
 4581:             }
 4582:             if ($permission->{'cusr'}) {
 4583:                 push(@allhelp,('Course_Add_Student','Course_Drop_Student'));
 4584:             }
 4585:             unless ($permission->{'cusr_section'}) {
 4586:                 if (&Apache::lonnet::auto_run($cnum,$cdom) && (($permission->{'cusr'}) || ($permission->{'view'}))) {
 4587:                     push(@allhelp,'Course_Automated_Enrollment');
 4588:                 }
 4589:                 if ($permission->{'selfenrolladmin'}) {
 4590:                     push(@allhelp,'Course_Approve_Selfenroll');
 4591:                 }
 4592:             }
 4593:             if ($permission->{'grp_manage'}) {
 4594:                 push(@allhelp,'Course_Manage_Group');
 4595:             }
 4596:             if ($permission->{'view'} || $permission->{'cusr'}) {
 4597:                 push(@allhelp,'Course_User_Logs');
 4598:             }
 4599:         } elsif ($context eq 'author') {
 4600:             push(@allhelp,('Author_Change_Privileges','Author_Create_Coauthor_List',
 4601:                            'Author_View_Coauthor_List','Author_User_Logs'));
 4602:         } else {
 4603:             if ($permission->{'cusr'}) {
 4604:                 push(@allhelp,'Domain_Change_Privileges');
 4605:                 if ($permission->{'activity'}) {
 4606:                     push(@allhelp,'Domain_User_Access_Logs');
 4607:                 }
 4608:                 push(@allhelp,('Domain_Create_Users','Domain_View_Users_List'));
 4609:                 if ($permission->{'custom'}) {
 4610:                     push(@allhelp,'Domain_Editing_Custom_Roles');
 4611:                 }
 4612:                 push(@allhelp,('Domain_Role_Approvals','Domain_Username_Approvals','Domain_Change_Logs'));
 4613:             } elsif ($permission->{'view'}) {
 4614:                 push(@allhelp,'Domain_View_Privileges');
 4615:                 if ($permission->{'activity'}) {
 4616:                     push(@allhelp,'Domain_User_Access_Logs');
 4617:                 }
 4618:                 push(@allhelp,('Domain_View_Users_List','Domain_Change_Logs'));
 4619:             }
 4620:         }
 4621:         if (@allhelp) {
 4622:             $allhelpitems = join(',',@allhelp);
 4623:         }
 4624:     }
 4625: 
 4626:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 4627:         ['action','state','callingform','roletype','showrole','bulkaction','popup','phase',
 4628:          'username','domain','srchterm','srchdomain','srchin','srchby','srchtype','queue']);
 4629:     &Apache::lonhtmlcommon::clear_breadcrumbs();
 4630:     my $args;
 4631:     my $brcrum = [];
 4632:     my $bread_crumbs_component = 'User Management';
 4633:     if (($env{'form.action'} ne 'dateselect') && ($env{'form.action'} ne 'displayuserreq')) {
 4634:         $brcrum = [{href=>"/adm/createuser",
 4635:                     text=>"User Management",
 4636:                     help=>$allhelpitems}
 4637:                   ];
 4638:     }
 4639:     #SD Following files not added to help, because the corresponding .tex-files seem to
 4640:     #be missing: Course_Approve_Selfenroll,Course_User_Logs,
 4641:     my ($permission,$allowed) = 
 4642:         &Apache::lonuserutils::get_permission($context,$crstype);
 4643:     if (!$allowed) {
 4644:         if ($context eq 'course') {
 4645:             $r->internal_redirect('/adm/viewclasslist');
 4646:             return OK;
 4647:         }
 4648:         $env{'user.error.msg'}=
 4649:             "/adm/createuser:cst:0:0:Cannot create/modify user data ".
 4650:                                  "or view user status.";
 4651:         return HTTP_NOT_ACCEPTABLE;
 4652:     }
 4653: 
 4654:     &Apache::loncommon::content_type($r,'text/html');
 4655:     $r->send_http_header;
 4656: 
 4657:     my $showcredits;
 4658:     if ((($context eq 'course') && ($crstype eq 'Course')) || 
 4659:          ($context eq 'domain')) {
 4660:         my %domdefaults = 
 4661:             &Apache::lonnet::get_domain_defaults($env{'request.role.domain'});
 4662:         if ($domdefaults{'officialcredits'} || $domdefaults{'unofficialcredits'}) {
 4663:             $showcredits = 1;
 4664:         }
 4665:     }
 4666: 
 4667:     # Main switch on form.action and form.state, as appropriate
 4668:     if (! exists($env{'form.action'})) {
 4669:         $args = {bread_crumbs => $brcrum,
 4670:                  bread_crumbs_component => $bread_crumbs_component}; 
 4671:         $r->print(&header(undef,$args));
 4672:         $r->print(&print_main_menu($permission,$context,$crstype));
 4673:     } elsif ($env{'form.action'} eq 'upload' && $permission->{'cusr'}) {
 4674:         my $helpitem = 'Course_Create_Class_List';
 4675:         if ($context eq 'author') {
 4676:             $helpitem = 'Author_Create_Coauthor_List';
 4677:         } elsif ($context eq 'domain') {
 4678:             $helpitem = 'Domain_Create_Users';
 4679:         }
 4680:         push(@{$brcrum},
 4681:               { href => '/adm/createuser?action=upload&state=',
 4682:                 text => 'Upload Users List',
 4683:                 help => $helpitem,
 4684:               });
 4685:         $bread_crumbs_component = 'Upload Users List';
 4686:         $args = {bread_crumbs           => $brcrum,
 4687:                  bread_crumbs_component => $bread_crumbs_component};
 4688:         $r->print(&header(undef,$args));
 4689:         $r->print('<form name="studentform" method="post" '.
 4690:                   'enctype="multipart/form-data" '.
 4691:                   ' action="/adm/createuser">'."\n");
 4692:         if (! exists($env{'form.state'})) {
 4693:             &Apache::lonuserutils::print_first_users_upload_form($r,$context);
 4694:         } elsif ($env{'form.state'} eq 'got_file') {
 4695:             &Apache::lonuserutils::print_upload_manager_form($r,$context,$permission,
 4696:                                                              $crstype,$showcredits);
 4697:         } elsif ($env{'form.state'} eq 'enrolling') {
 4698:             if ($env{'form.datatoken'}) {
 4699:                 &Apache::lonuserutils::upfile_drop_add($r,$context,$permission,
 4700:                                                        $showcredits);
 4701:             }
 4702:         } else {
 4703:             &Apache::lonuserutils::print_first_users_upload_form($r,$context);
 4704:         }
 4705:     } elsif (((($env{'form.action'} eq 'singleuser') || ($env{'form.action'}
 4706:               eq 'singlestudent')) && ($permission->{'cusr'})) ||
 4707:              (($env{'form.action'} eq 'singleuser') && ($permission->{'view'})) ||
 4708:              (($env{'form.action'} eq 'accesslogs') && ($permission->{'activity'}))) {
 4709:         my $phase = $env{'form.phase'};
 4710:         my @search = ('srchterm','srchby','srchin','srchtype','srchdomain');
 4711: 	&Apache::loncreateuser::restore_prev_selections();
 4712: 	my $srch;
 4713: 	foreach my $item (@search) {
 4714: 	    $srch->{$item} = $env{'form.'.$item};
 4715: 	}
 4716:         if (($phase eq 'get_user_info') || ($phase eq 'userpicked') ||
 4717:             ($phase eq 'createnewuser') || ($phase eq 'activity')) {
 4718:             if ($env{'form.phase'} eq 'createnewuser') {
 4719:                 my $response;
 4720:                 if ($env{'form.srchterm'} !~ /^$match_username$/) {
 4721:                     my $response =
 4722:                         '<span class="LC_warning">'
 4723:                        .&mt('You must specify a valid username. Only the following are allowed:'
 4724:                            .' letters numbers - . @')
 4725:                        .'</span>';
 4726:                     $env{'form.phase'} = '';
 4727:                     &print_username_entry_form($r,$context,$response,$srch,undef,
 4728:                                                $crstype,$brcrum,$permission);
 4729:                 } else {
 4730:                     my $ccuname =&LONCAPA::clean_username($srch->{'srchterm'});
 4731:                     my $ccdomain=&LONCAPA::clean_domain($srch->{'srchdomain'});
 4732:                     &print_user_modification_page($r,$ccuname,$ccdomain,
 4733:                                                   $srch,$response,$context,
 4734:                                                   $permission,$crstype,$brcrum,
 4735:                                                   $showcredits);
 4736:                 }
 4737:             } elsif ($env{'form.phase'} eq 'get_user_info') {
 4738:                 my ($currstate,$response,$forcenewuser,$results) = 
 4739:                     &user_search_result($context,$srch);
 4740:                 if ($env{'form.currstate'} eq 'modify') {
 4741:                     $currstate = $env{'form.currstate'};
 4742:                 }
 4743:                 if ($currstate eq 'select') {
 4744:                     &print_user_selection_page($r,$response,$srch,$results,
 4745:                                                \@search,$context,undef,$crstype,
 4746:                                                $brcrum);
 4747:                 } elsif (($currstate eq 'modify') || ($env{'form.action'} eq 'accesslogs')) {
 4748:                     my ($ccuname,$ccdomain,$uhome);
 4749:                     if (($srch->{'srchby'} eq 'uname') && 
 4750:                         ($srch->{'srchtype'} eq 'exact')) {
 4751:                         $ccuname = $srch->{'srchterm'};
 4752:                         $ccdomain= $srch->{'srchdomain'};
 4753:                     } else {
 4754:                         my @matchedunames = keys(%{$results});
 4755:                         ($ccuname,$ccdomain) = split(/:/,$matchedunames[0]);
 4756:                     }
 4757:                     $ccuname =&LONCAPA::clean_username($ccuname);
 4758:                     $ccdomain=&LONCAPA::clean_domain($ccdomain);
 4759:                     if ($env{'form.action'} eq 'accesslogs') {
 4760:                         my $uhome;
 4761:                         if (($ccuname ne '') && ($ccdomain ne '')) {
 4762:                            $uhome = &Apache::lonnet::homeserver($ccuname,$ccdomain);
 4763:                         }
 4764:                         if (($uhome eq '') || ($uhome eq 'no_host')) {
 4765:                             $env{'form.phase'} = '';
 4766:                             undef($forcenewuser);
 4767:                             #if ($response) {
 4768:                             #    unless ($response =~ m{\Q<br /><br />\E$}) {
 4769:                             #        $response .= '<br /><br />';
 4770:                             #    }
 4771:                             #}
 4772:                             &print_username_entry_form($r,$context,$response,$srch,
 4773:                                                        $forcenewuser,$crstype,$brcrum,
 4774:                                                        $permission);
 4775:                         } else {
 4776:                             &print_useraccesslogs_display($r,$ccuname,$ccdomain,$permission,$brcrum);
 4777:                         }
 4778:                     } else {
 4779:                         if ($env{'form.forcenewuser'}) {
 4780:                             $response = '';
 4781:                         }
 4782:                         &print_user_modification_page($r,$ccuname,$ccdomain,
 4783:                                                       $srch,$response,$context,
 4784:                                                       $permission,$crstype,$brcrum);
 4785:                     }
 4786:                 } elsif ($currstate eq 'query') {
 4787:                     &print_user_query_page($r,'createuser',$brcrum);
 4788:                 } else {
 4789:                     $env{'form.phase'} = '';
 4790:                     &print_username_entry_form($r,$context,$response,$srch,
 4791:                                                $forcenewuser,$crstype,$brcrum,
 4792:                                                $permission);
 4793:                 }
 4794:             } elsif ($env{'form.phase'} eq 'userpicked') {
 4795:                 my $ccuname = &LONCAPA::clean_username($env{'form.seluname'});
 4796:                 my $ccdomain = &LONCAPA::clean_domain($env{'form.seludom'});
 4797:                 if ($env{'form.action'} eq 'accesslogs') {
 4798:                     &print_useraccesslogs_display($r,$ccuname,$ccdomain,$permission,$brcrum);
 4799:                 } else {
 4800:                     &print_user_modification_page($r,$ccuname,$ccdomain,$srch,'',
 4801:                                                   $context,$permission,$crstype,
 4802:                                                   $brcrum);
 4803:                 }
 4804:             } elsif ($env{'form.action'} eq 'accesslogs') {
 4805:                 my $ccuname = &LONCAPA::clean_username($env{'form.accessuname'});
 4806:                 my $ccdomain = &LONCAPA::clean_domain($env{'form.accessudom'});
 4807:                 &print_useraccesslogs_display($r,$ccuname,$ccdomain,$permission,$brcrum);
 4808:             }
 4809:         } elsif ($env{'form.phase'} eq 'update_user_data') {
 4810:             &update_user_data($r,$context,$crstype,$brcrum,$showcredits);
 4811:         } else {
 4812:             &print_username_entry_form($r,$context,undef,$srch,undef,$crstype,
 4813:                                        $brcrum,$permission);
 4814:         }
 4815:     } elsif ($env{'form.action'} eq 'custom' && $permission->{'custom'}) {
 4816:         my $prefix;
 4817:         if ($env{'form.phase'} eq 'set_custom_roles') {
 4818:             &set_custom_role($r,$context,$brcrum,$prefix,$permission);
 4819:         } else {
 4820:             &custom_role_editor($r,$context,$brcrum,$prefix,$permission);
 4821:         }
 4822:     } elsif (($env{'form.action'} eq 'processauthorreq') &&
 4823:              ($permission->{'cusr'}) && 
 4824:              (&Apache::lonnet::allowed('cau',$env{'request.role.domain'}))) {
 4825:         push(@{$brcrum},
 4826:                  {href => '/adm/createuser?action=processauthorreq',
 4827:                   text => 'Authoring Space requests',
 4828:                   help => 'Domain_Role_Approvals'});
 4829:         $bread_crumbs_component = 'Authoring requests';
 4830:         if ($env{'form.state'} eq 'done') {
 4831:             push(@{$brcrum},
 4832:                      {href => '/adm/createuser?action=authorreqqueue',
 4833:                       text => 'Result',
 4834:                       help => 'Domain_Role_Approvals'});
 4835:             $bread_crumbs_component = 'Authoring request result';
 4836:         }
 4837:         $args = { bread_crumbs           => $brcrum,
 4838:                   bread_crumbs_component => $bread_crumbs_component};
 4839:         my $js = &usernamerequest_javascript();
 4840:         $r->print(&header(&add_script($js),$args));
 4841:         if (!exists($env{'form.state'})) {
 4842:             $r->print(&Apache::loncoursequeueadmin::display_queued_requests('requestauthor',
 4843:                                                                             $env{'request.role.domain'}));
 4844:         } elsif ($env{'form.state'} eq 'done') {
 4845:             $r->print('<h3>'.&mt('Authoring request processing').'</h3>'."\n");
 4846:             $r->print(&Apache::loncoursequeueadmin::update_request_queue('requestauthor',
 4847:                                                                          $env{'request.role.domain'}));
 4848:         }
 4849:     } elsif (($env{'form.action'} eq 'processusernamereq') &&
 4850:              ($permission->{'cusr'}) &&
 4851:              (&Apache::lonnet::allowed('cau',$env{'request.role.domain'}))) {
 4852:         push(@{$brcrum},
 4853:                  {href => '/adm/createuser?action=processusernamereq',
 4854:                   text => 'LON-CAPA account requests',
 4855:                   help => 'Domain_Username_Approvals'});
 4856:         $bread_crumbs_component = 'Account requests';
 4857:         if ($env{'form.state'} eq 'done') {
 4858:             push(@{$brcrum},
 4859:                      {href => '/adm/createuser?action=usernamereqqueue',
 4860:                       text => 'Result',
 4861:                       help => 'Domain_Username_Approvals'});
 4862:             $bread_crumbs_component = 'LON-CAPA account request result';
 4863:         }
 4864:         $args = { bread_crumbs           => $brcrum,
 4865:                   bread_crumbs_component => $bread_crumbs_component};
 4866:         my $js = &usernamerequest_javascript();
 4867:         $r->print(&header(&add_script($js),$args));
 4868:         if (!exists($env{'form.state'})) {
 4869:             $r->print(&Apache::loncoursequeueadmin::display_queued_requests('requestusername',
 4870:                                                                             $env{'request.role.domain'}));
 4871:         } elsif ($env{'form.state'} eq 'done') {
 4872:             $r->print('<h3>'.&mt('LON-CAPA account request processing').'</h3>'."\n");
 4873:             $r->print(&Apache::loncoursequeueadmin::update_request_queue('requestusername',
 4874:                                                                          $env{'request.role.domain'}));
 4875:         }
 4876:     } elsif (($env{'form.action'} eq 'displayuserreq') &&
 4877:              ($permission->{'cusr'})) {
 4878:         my $dom = $env{'form.domain'};
 4879:         my $uname = $env{'form.username'};
 4880:         my $warning;
 4881:         if (($dom =~ /^$match_domain$/) && (&Apache::lonnet::domain($dom) ne '')) {
 4882:             if (($dom eq $env{'request.role.domain'}) && (&Apache::lonnet::allowed('ccc',$dom))) {
 4883:                 if (($uname =~ /^$match_username$/) && ($env{'form.queue'} eq 'approval')) {
 4884:                     my $uhome = &Apache::lonnet::homeserver($uname,$dom);
 4885:                     if ($uhome eq 'no_host') {
 4886:                         my $queue = $env{'form.queue'};
 4887:                         my $reqkey = &escape($uname).'_'.$queue; 
 4888:                         my $namespace = 'usernamequeue';
 4889:                         my $domconfig = &Apache::lonnet::get_domainconfiguser($dom);
 4890:                         my %queued =
 4891:                             &Apache::lonnet::get($namespace,[$reqkey],$dom,$domconfig);
 4892:                         unless ($queued{$reqkey}) {
 4893:                             $warning = &mt('No information was found for this LON-CAPA account request.');
 4894:                         }
 4895:                     } else {
 4896:                         $warning = &mt('A LON-CAPA account already exists for the requested username and domain.');
 4897:                     }
 4898:                 } else {
 4899:                     $warning = &mt('LON-CAPA account request status check is for an invalid username.');
 4900:                 }
 4901:             } else {
 4902:                 $warning = &mt('You do not have rights to view LON-CAPA account requests in the domain specified.');
 4903:             }
 4904:         } else {
 4905:             $warning = &mt('LON-CAPA account request status check is for an invalid domain.');
 4906:         }
 4907:         my $args = { only_body => 1 };
 4908:         $r->print(&header(undef,$args).
 4909:                   '<h3>'.&mt('LON-CAPA Account Request Details').'</h3>');
 4910:         if ($warning ne '') {
 4911:             $r->print('<div class="LC_warning">'.$warning.'</div>');
 4912:         } else {
 4913:             my ($infofields,$infotitles) = &Apache::loncommon::emailusername_info();
 4914:             my $domconfiguser = &Apache::lonnet::get_domainconfiguser($dom);
 4915:             my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 4916:             if (ref($domconfig{'usercreation'}) eq 'HASH') {
 4917:                 if (ref($domconfig{'usercreation'}{'cancreate'}) eq 'HASH') {
 4918:                     if (ref($domconfig{'usercreation'}{'cancreate'}{'emailusername'}) eq 'HASH') {
 4919:                         my %info =
 4920:                             &Apache::lonnet::get('nohist_requestedusernames',[$uname],$dom,$domconfiguser);
 4921:                         if (ref($info{$uname}) eq 'HASH') {
 4922:                             my $usertype = $info{$uname}{'inststatus'};
 4923:                             unless ($usertype) {
 4924:                                 $usertype = 'default';
 4925:                             }
 4926:                             if (ref($domconfig{'usercreation'}{'cancreate'}{'emailusername'}{$usertype}) eq 'HASH') {
 4927:                                 if ((ref($infofields) eq 'ARRAY') && (ref($infotitles) eq 'HASH')) {
 4928:                                     $r->print('<div>'.&Apache::lonhtmlcommon::start_pick_box());
 4929:                                     my ($num,$count,$showstatus);
 4930:                                     $count = scalar(keys(%{$domconfig{'usercreation'}{'cancreate'}{'emailusername'}{$usertype}}));
 4931:                                     unless ($usertype eq 'default') {
 4932:                                         my ($othertitle,$usertypes,$types) = 
 4933:                                             &Apache::loncommon::sorted_inst_types($dom);
 4934:                                         if (ref($usertypes) eq 'HASH') {
 4935:                                             if ($usertypes->{$usertype}) {
 4936:                                                 $showstatus = $usertypes->{$usertype};
 4937:                                                 $count ++;
 4938:                                             }
 4939:                                         }
 4940:                                     }
 4941:                                     foreach my $field (@{$infofields}) {
 4942:                                         next unless ($domconfig{'usercreation'}{'cancreate'}{'emailusername'}{$usertype}{$field});
 4943:                                         next unless ($infotitles->{$field});
 4944:                                         $r->print(&Apache::lonhtmlcommon::row_title($infotitles->{$field}).
 4945:                                                   $info{$uname}{$field});
 4946:                                         $num ++;
 4947:                                         if ($count == $num) {
 4948:                                             $r->print(&Apache::lonhtmlcommon::row_closure(1));
 4949:                                         } else {
 4950:                                             $r->print(&Apache::lonhtmlcommon::row_closure());
 4951:                                         }
 4952:                                     }
 4953:                                     if ($showstatus) {
 4954:                                         $r->print(&Apache::lonhtmlcommon::row_title(&mt('Status type (self-reported)')).
 4955:                                                   $showstatus.
 4956:                                                   &Apache::lonhtmlcommon::row_closure(1));
 4957:                                     }
 4958:                                     $r->print(&Apache::lonhtmlcommon::end_pick_box().'</div>');
 4959:                                 }
 4960:                             }
 4961:                         }
 4962:                     }
 4963:                 }
 4964:             }
 4965:             $r->print(&close_popup_form());
 4966:         }
 4967:     } elsif (($env{'form.action'} eq 'listusers') && 
 4968:              ($permission->{'view'} || $permission->{'cusr'})) {
 4969:         my $helpitem = 'Course_View_Class_List';
 4970:         if ($context eq 'author') {
 4971:             $helpitem = 'Author_View_Coauthor_List';
 4972:         } elsif ($context eq 'domain') {
 4973:             $helpitem = 'Domain_View_Users_List';
 4974:         }
 4975:         if ($env{'form.phase'} eq 'bulkchange') {
 4976:             push(@{$brcrum},
 4977:                     {href => '/adm/createuser?action=listusers',
 4978:                      text => "List Users"},
 4979:                     {href => "/adm/createuser",
 4980:                      text => "Result",
 4981:                      help => $helpitem});
 4982:             $bread_crumbs_component = 'Update Users';
 4983:             $args = {bread_crumbs           => $brcrum,
 4984:                      bread_crumbs_component => $bread_crumbs_component};
 4985:             $r->print(&header(undef,$args));
 4986:             my $setting = $env{'form.roletype'};
 4987:             my $choice = $env{'form.bulkaction'};
 4988:             if ($permission->{'cusr'}) {
 4989:                 &Apache::lonuserutils::update_user_list($r,$context,$setting,$choice,$crstype);
 4990:             } else {
 4991:                 $r->print(&mt('You are not authorized to make bulk changes to user roles'));
 4992:                 $r->print('<p><a href="/adm/createuser?action=listusers">'.&mt('Display User Lists').'</a>');
 4993:             }
 4994:         } else {
 4995:             push(@{$brcrum},
 4996:                     {href => '/adm/createuser?action=listusers',
 4997:                      text => "List Users",
 4998:                      help => $helpitem});
 4999:             $bread_crumbs_component = 'List Users';
 5000:             $args = {bread_crumbs           => $brcrum,
 5001:                      bread_crumbs_component => $bread_crumbs_component};
 5002:             my ($cb_jscript,$jscript,$totcodes,$codetitles,$idlist,$idlist_titles);
 5003:             my $formname = 'studentform';
 5004:             my $hidecall = "hide_searching();";
 5005:             if (($context eq 'domain') && (($env{'form.roletype'} eq 'course') ||
 5006:                 ($env{'form.roletype'} eq 'community'))) {
 5007:                 if ($env{'form.roletype'} eq 'course') {
 5008:                     ($cb_jscript,$jscript,$totcodes,$codetitles,$idlist,$idlist_titles) = 
 5009:                         &Apache::lonuserutils::courses_selector($env{'request.role.domain'},
 5010:                                                                 $formname);
 5011:                 } elsif ($env{'form.roletype'} eq 'community') {
 5012:                     $cb_jscript = 
 5013:                         &Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'});
 5014:                     my %elements = (
 5015:                                       coursepick => 'radio',
 5016:                                       coursetotal => 'text',
 5017:                                       courselist => 'text',
 5018:                                    );
 5019:                     $jscript = &Apache::lonhtmlcommon::set_form_elements(\%elements);
 5020:                 }
 5021:                 $jscript .= &verify_user_display($context)."\n".
 5022:                             &Apache::loncommon::check_uncheck_jscript();
 5023:                 my $js = &add_script($jscript).$cb_jscript;
 5024:                 my $loadcode = 
 5025:                     &Apache::lonuserutils::course_selector_loadcode($formname);
 5026:                 if ($loadcode ne '') {
 5027:                     $args->{add_entries} = {onload => "$loadcode;$hidecall"};
 5028:                 } else {
 5029:                     $args->{add_entries} = {onload => $hidecall};
 5030:                 }
 5031:                 $r->print(&header($js,$args));
 5032:             } else {
 5033:                 $args->{add_entries} = {onload => $hidecall};
 5034:                 $jscript = &verify_user_display($context).
 5035:                            &Apache::loncommon::check_uncheck_jscript(); 
 5036:                 $r->print(&header(&add_script($jscript),$args));
 5037:             }
 5038:             &Apache::lonuserutils::print_userlist($r,undef,$permission,$context,
 5039:                          $formname,$totcodes,$codetitles,$idlist,$idlist_titles,
 5040:                          $showcredits);
 5041:         }
 5042:     } elsif ($env{'form.action'} eq 'drop' && $permission->{'cusr'}) {
 5043:         my $brtext;
 5044:         if ($crstype eq 'Community') {
 5045:             $brtext = 'Drop Members';
 5046:         } else {
 5047:             $brtext = 'Drop Students';
 5048:         }
 5049:         push(@{$brcrum},
 5050:                 {href => '/adm/createuser?action=drop',
 5051:                  text => $brtext,
 5052:                  help => 'Course_Drop_Student'});
 5053:         if ($env{'form.state'} eq 'done') {
 5054:             push(@{$brcrum},
 5055:                      {href=>'/adm/createuser?action=drop',
 5056:                       text=>"Result"});
 5057:         }
 5058:         $bread_crumbs_component = $brtext;
 5059:         $args = {bread_crumbs           => $brcrum,
 5060:                  bread_crumbs_component => $bread_crumbs_component}; 
 5061:         $r->print(&header(undef,$args));
 5062:         if (!exists($env{'form.state'})) {
 5063:             &Apache::lonuserutils::print_drop_menu($r,$context,$permission,$crstype);
 5064:         } elsif ($env{'form.state'} eq 'done') {
 5065:             &Apache::lonuserutils::update_user_list($r,$context,undef,
 5066:                                                     $env{'form.action'});
 5067:         }
 5068:     } elsif ($env{'form.action'} eq 'dateselect') {
 5069:         if ($permission->{'cusr'}) {
 5070:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 5071:                       &Apache::lonuserutils::date_section_selector($context,$permission,
 5072:                                                                    $crstype,$showcredits));
 5073:         } else {
 5074:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 5075:                      '<span class="LC_error">'.&mt('You do not have permission to modify dates or sections for users').'</span>'); 
 5076:         }
 5077:     } elsif ($env{'form.action'} eq 'selfenroll') {
 5078:         if ($permission->{selfenrolladmin}) {
 5079:             my %currsettings = (
 5080:                 selfenroll_types              => $env{'course.'.$cid.'.internal.selfenroll_types'},
 5081:                 selfenroll_registered         => $env{'course.'.$cid.'.internal.selfenroll_registered'},
 5082:                 selfenroll_section            => $env{'course.'.$cid.'.internal.selfenroll_section'},
 5083:                 selfenroll_notifylist         => $env{'course.'.$cid.'.internal.selfenroll_notifylist'},
 5084:                 selfenroll_approval           => $env{'course.'.$cid.'.internal.selfenroll_approval'},
 5085:                 selfenroll_limit              => $env{'course.'.$cid.'.internal.selfenroll_limit'},
 5086:                 selfenroll_cap                => $env{'course.'.$cid.'.internal.selfenroll_cap'},
 5087:                 selfenroll_start_date         => $env{'course.'.$cid.'.internal.selfenroll_start_date'},
 5088:                 selfenroll_end_date           => $env{'course.'.$cid.'.internal.selfenroll_end_date'},
 5089:                 selfenroll_start_access       => $env{'course.'.$cid.'.internal.selfenroll_start_access'},
 5090:                 selfenroll_end_access         => $env{'course.'.$cid.'.internal.selfenroll_end_access'},
 5091:                 default_enrollment_start_date => $env{'course.'.$cid.'.default_enrollment_start_date'},
 5092:                 default_enrollment_end_date   => $env{'course.'.$cid.'.default_enrollment_end_date'},
 5093:                 uniquecode                    => $env{'course.'.$cid.'.internal.uniquecode'},
 5094:             );
 5095:             push(@{$brcrum},
 5096:                     {href => '/adm/createuser?action=selfenroll',
 5097:                      text => "Configure Self-enrollment",
 5098:                      help => 'Course_Self_Enrollment'});
 5099:             if (!exists($env{'form.state'})) {
 5100:                 $args = { bread_crumbs           => $brcrum,
 5101:                           bread_crumbs_component => 'Configure Self-enrollment'};
 5102:                 $r->print(&header(undef,$args));
 5103:                 $r->print('<h3>'.&mt('Self-enrollment with a student role').'</h3>'."\n");
 5104:                 &print_selfenroll_menu($r,'course',$cid,$cdom,$cnum,\%currsettings);
 5105:             } elsif ($env{'form.state'} eq 'done') {
 5106:                 push (@{$brcrum},
 5107:                           {href=>'/adm/createuser?action=selfenroll',
 5108:                            text=>"Result"});
 5109:                 $args = { bread_crumbs           => $brcrum,
 5110:                           bread_crumbs_component => 'Self-enrollment result'};
 5111:                 $r->print(&header(undef,$args));
 5112:                 $r->print('<h3>'.&mt('Self-enrollment with a student role').'</h3>'."\n");
 5113:                 &update_selfenroll_config($r,$cid,$cdom,$cnum,$context,$crstype,\%currsettings);
 5114:             }
 5115:         } else {
 5116:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 5117:                      '<span class="LC_error">'.&mt('You do not have permission to configure self-enrollment').'</span>');
 5118:         }
 5119:     } elsif ($env{'form.action'} eq 'selfenrollqueue') {
 5120:         if ($permission->{selfenrolladmin}) {
 5121:             push(@{$brcrum},
 5122:                      {href => '/adm/createuser?action=selfenrollqueue',
 5123:                       text => 'Enrollment requests',
 5124:                       help => 'Course_Approve_Selfenroll'});
 5125:             $bread_crumbs_component = 'Enrollment requests';
 5126:             if ($env{'form.state'} eq 'done') {
 5127:                 push(@{$brcrum},
 5128:                          {href => '/adm/createuser?action=selfenrollqueue',
 5129:                           text => 'Result',
 5130:                           help => 'Course_Approve_Selfenroll'});
 5131:                 $bread_crumbs_component = 'Enrollment result';
 5132:             }
 5133:             $args = { bread_crumbs           => $brcrum,
 5134:                       bread_crumbs_component => $bread_crumbs_component};
 5135:             $r->print(&header(undef,$args));
 5136:             my $coursedesc = $env{'course.'.$cid.'.description'};
 5137:             if (!exists($env{'form.state'})) {
 5138:                 $r->print('<h3>'.&mt('Pending enrollment requests').'</h3>'."\n");
 5139:                 $r->print(&Apache::loncoursequeueadmin::display_queued_requests($context,
 5140:                                                                                 $cdom,$cnum));
 5141:             } elsif ($env{'form.state'} eq 'done') {
 5142:                 $r->print('<h3>'.&mt('Enrollment request processing').'</h3>'."\n");
 5143:                 $r->print(&Apache::loncoursequeueadmin::update_request_queue($context,
 5144:                               $cdom,$cnum,$coursedesc));
 5145:             }
 5146:         } else {
 5147:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 5148:                      '<span class="LC_error">'.&mt('You do not have permission to manage self-enrollment').'</span>');
 5149:         }
 5150:     } elsif ($env{'form.action'} eq 'changelogs') {
 5151:         if ($permission->{cusr} || $permission->{view}) {
 5152:             &print_userchangelogs_display($r,$context,$permission,$brcrum);
 5153:         } else {
 5154:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 5155:                      '<span class="LC_error">'.&mt('You do not have permission to view change logs').'</span>');
 5156:         }
 5157:     } elsif ($env{'form.action'} eq 'helpdesk') {
 5158:         if (($permission->{'owner'}) || ($permission->{'co-owner'})) {
 5159:             if ($env{'form.state'} eq 'process') {
 5160:                 if ($permission->{'owner'}) {
 5161:                     &update_helpdeskaccess($r,$permission,$brcrum);
 5162:                 } else {
 5163:                     &print_helpdeskaccess_display($r,$permission,$brcrum);
 5164:                 }
 5165:             } else {
 5166:                 &print_helpdeskaccess_display($r,$permission,$brcrum);
 5167:             }
 5168:         } else {
 5169:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 5170:                       '<span class="LC_error">'.&mt('You do not have permission to view helpdesk access').'</span>');
 5171:         }
 5172:     } else {
 5173:         $bread_crumbs_component = 'User Management';
 5174:         $args = { bread_crumbs           => $brcrum,
 5175:                   bread_crumbs_component => $bread_crumbs_component};
 5176:         $r->print(&header(undef,$args));
 5177:         $r->print(&print_main_menu($permission,$context,$crstype));
 5178:     }
 5179:     $r->print(&Apache::loncommon::end_page());
 5180:     return OK;
 5181: }
 5182: 
 5183: sub header {
 5184:     my ($jscript,$args) = @_;
 5185:     my $start_page;
 5186:     if (ref($args) eq 'HASH') {
 5187:         $start_page=&Apache::loncommon::start_page('User Management',$jscript,$args);
 5188:     } else {
 5189:         $start_page=&Apache::loncommon::start_page('User Management',$jscript);
 5190:     }
 5191:     return $start_page;
 5192: }
 5193: 
 5194: sub add_script {
 5195:     my ($js) = @_;
 5196:     return '<script type="text/javascript">'."\n"
 5197:           .'// <![CDATA['."\n"
 5198:           .$js."\n"
 5199:           .'// ]]>'."\n"
 5200:           .'</script>'."\n";
 5201: }
 5202: 
 5203: sub usernamerequest_javascript {
 5204:     my $js = <<ENDJS;
 5205: 
 5206: function openusernamereqdisplay(dom,uname,queue) {
 5207:     var url = '/adm/createuser?action=displayuserreq';
 5208:     url += '&domain='+dom+'&username='+uname+'&queue='+queue;
 5209:     var title = 'Account_Request_Browser';
 5210:     var options = 'scrollbars=1,resizable=1,menubar=0';
 5211:     options += ',width=700,height=600';
 5212:     var stdeditbrowser = open(url,title,options,'1');
 5213:     stdeditbrowser.focus();
 5214:     return;
 5215: }
 5216:  
 5217: ENDJS
 5218: }
 5219: 
 5220: sub close_popup_form {
 5221:     my $close= &mt('Close Window');
 5222:     return << "END";
 5223: <p><form name="displayreq" action="" method="post">
 5224: <input type="button" name="closeme" value="$close" onclick="javascript:self.close();" />
 5225: </form></p>
 5226: END
 5227: }
 5228: 
 5229: sub verify_user_display {
 5230:     my ($context) = @_;
 5231:     my %lt = &Apache::lonlocal::texthash (
 5232:         course    => 'course(s): description, section(s), status',
 5233:         community => 'community(s): description, section(s), status',
 5234:         author    => 'author',
 5235:     );
 5236:     my $photos;
 5237:     if (($context eq 'course') && $env{'request.course.id'}) {
 5238:         $photos = $env{'course.'.$env{'request.course.id'}.'.internal.showphoto'};
 5239:     }
 5240:     my $output = <<"END";
 5241: 
 5242: function hide_searching() {
 5243:     if (document.getElementById('searching')) {
 5244:         document.getElementById('searching').style.display = 'none';
 5245:     }
 5246:     return;
 5247: }
 5248: 
 5249: function display_update() {
 5250:     document.studentform.action.value = 'listusers';
 5251:     document.studentform.phase.value = 'display';
 5252:     document.studentform.submit();
 5253: }
 5254: 
 5255: function updateCols(caller) {
 5256:     var context = '$context';
 5257:     var photos = '$photos';
 5258:     if (caller == 'Status') {
 5259:         if ((context == 'domain') && 
 5260:             ((document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'course') ||
 5261:              (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'community'))) {
 5262:             document.getElementById('showcolstatus').checked = false;
 5263:             document.getElementById('showcolstatus').disabled = 'disabled';
 5264:             document.getElementById('showcolstart').checked = false;
 5265:             document.getElementById('showcolend').checked = false;
 5266:         } else {
 5267:             if (document.studentform.Status.options[document.studentform.Status.selectedIndex].value == 'Any') {
 5268:                 document.getElementById('showcolstatus').checked = true;
 5269:                 document.getElementById('showcolstatus').disabled = '';
 5270:                 document.getElementById('showcolstart').checked = true;
 5271:                 document.getElementById('showcolend').checked = true;
 5272:             } else {
 5273:                 document.getElementById('showcolstatus').checked = false;
 5274:                 document.getElementById('showcolstatus').disabled = 'disabled';
 5275:                 document.getElementById('showcolstart').checked = false;
 5276:                 document.getElementById('showcolend').checked = false;
 5277:             }
 5278:         }
 5279:     }
 5280:     if (caller == 'output') {
 5281:         if (photos == 1) {
 5282:             if (document.getElementById('showcolphoto')) {
 5283:                 var photoitem = document.getElementById('showcolphoto');
 5284:                 if (document.studentform.output.options[document.studentform.output.selectedIndex].value == 'html') {
 5285:                     photoitem.checked = true;
 5286:                     photoitem.disabled = '';
 5287:                 } else {
 5288:                     photoitem.checked = false;
 5289:                     photoitem.disabled = 'disabled';
 5290:                 }
 5291:             }
 5292:         }
 5293:     }
 5294:     if (caller == 'showrole') {
 5295:         if ((document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'Any') ||
 5296:             (document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'cr')) {
 5297:             document.getElementById('showcolrole').checked = true;
 5298:             document.getElementById('showcolrole').disabled = '';
 5299:         } else {
 5300:             document.getElementById('showcolrole').checked = false;
 5301:             document.getElementById('showcolrole').disabled = 'disabled';
 5302:         }
 5303:         if (context == 'domain') {
 5304:             var quotausageshow = 0;
 5305:             if ((document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'course') ||
 5306:                 (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'community')) {
 5307:                 document.getElementById('showcolstatus').checked = false;
 5308:                 document.getElementById('showcolstatus').disabled = 'disabled';
 5309:                 document.getElementById('showcolstart').checked = false;
 5310:                 document.getElementById('showcolend').checked = false;
 5311:             } else {
 5312:                 if (document.studentform.Status.options[document.studentform.Status.selectedIndex].value == 'Any') {
 5313:                     document.getElementById('showcolstatus').checked = true;
 5314:                     document.getElementById('showcolstatus').disabled = '';
 5315:                     document.getElementById('showcolstart').checked = true;
 5316:                     document.getElementById('showcolend').checked = true;
 5317:                 }
 5318:             }
 5319:             if (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'domain') {
 5320:                 document.getElementById('showcolextent').disabled = 'disabled';
 5321:                 document.getElementById('showcolextent').checked = 'false';
 5322:                 document.getElementById('showextent').style.display='none';
 5323:                 document.getElementById('showcoltextextent').innerHTML = '';
 5324:                 if ((document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'au') ||
 5325:                     (document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'Any')) {
 5326:                     if (document.getElementById('showcolauthorusage')) {
 5327:                         document.getElementById('showcolauthorusage').disabled = '';
 5328:                     }
 5329:                     if (document.getElementById('showcolauthorquota')) {
 5330:                         document.getElementById('showcolauthorquota').disabled = '';
 5331:                     }
 5332:                     quotausageshow = 1;
 5333:                 }
 5334:             } else {
 5335:                 document.getElementById('showextent').style.display='block';
 5336:                 document.getElementById('showextent').style.textAlign='left';
 5337:                 document.getElementById('showextent').style.textFace='normal';
 5338:                 if (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'author') {
 5339:                     document.getElementById('showcolextent').disabled = '';
 5340:                     document.getElementById('showcolextent').checked = 'true';
 5341:                     document.getElementById('showcoltextextent').innerHTML="$lt{'author'}";
 5342:                 } else {
 5343:                     document.getElementById('showcolextent').disabled = '';
 5344:                     document.getElementById('showcolextent').checked = 'true';
 5345:                     if (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'community') {
 5346:                         document.getElementById('showcoltextextent').innerHTML="$lt{'community'}";
 5347:                     } else {
 5348:                         document.getElementById('showcoltextextent').innerHTML="$lt{'course'}";
 5349:                     }
 5350:                 }
 5351:             }
 5352:             if (quotausageshow == 0)  {
 5353:                 if (document.getElementById('showcolauthorusage')) {
 5354:                     document.getElementById('showcolauthorusage').checked = false;
 5355:                     document.getElementById('showcolauthorusage').disabled = 'disabled';
 5356:                 }
 5357:                 if (document.getElementById('showcolauthorquota')) {
 5358:                     document.getElementById('showcolauthorquota').checked = false;
 5359:                     document.getElementById('showcolauthorquota').disabled = 'disabled';
 5360:                 }
 5361:             }
 5362:         }
 5363:     }
 5364:     return;
 5365: }
 5366: 
 5367: END
 5368:     return $output;
 5369: 
 5370: }
 5371: 
 5372: ###############################################################
 5373: ###############################################################
 5374: #  Menu Phase One
 5375: sub print_main_menu {
 5376:     my ($permission,$context,$crstype) = @_;
 5377:     my $linkcontext = $context;
 5378:     my $stuterm = lc(&Apache::lonnet::plaintext('st',$crstype));
 5379:     if (($context eq 'course') && ($crstype eq 'Community')) {
 5380:         $linkcontext = lc($crstype);
 5381:         $stuterm = 'Members';
 5382:     }
 5383:     my %links = (
 5384:                 domain => {
 5385:                             upload     => 'Upload a File of Users',
 5386:                             singleuser => 'Add/Modify a User',
 5387:                             listusers  => 'Manage Users',
 5388:                             },
 5389:                 author => {
 5390:                             upload     => 'Upload a File of Co-authors',
 5391:                             singleuser => 'Add/Modify a Co-author',
 5392:                             listusers  => 'Manage Co-authors',
 5393:                             },
 5394:                 course => {
 5395:                             upload     => 'Upload a File of Course Users',
 5396:                             singleuser => 'Add/Modify a Course User',
 5397:                             listusers  => 'List and Modify Multiple Course Users',
 5398:                             },
 5399:                 community => {
 5400:                             upload     => 'Upload a File of Community Users',
 5401:                             singleuser => 'Add/Modify a Community User',
 5402:                             listusers  => 'List and Modify Multiple Community Users',
 5403:                            },
 5404:                 );
 5405:      my %linktitles = (
 5406:                 domain => {
 5407:                             singleuser => 'Add a user to the domain, and/or a course or community in the domain.',
 5408:                             listusers  => 'Show and manage users in this domain.',
 5409:                             },
 5410:                 author => {
 5411:                             singleuser => 'Add a user with a co- or assistant author role.',
 5412:                             listusers  => 'Show and manage co- or assistant authors.',
 5413:                             },
 5414:                 course => {
 5415:                             singleuser => 'Add a user with a certain role to this course.',
 5416:                             listusers  => 'Show and manage users in this course.',
 5417:                             },
 5418:                 community => {
 5419:                             singleuser => 'Add a user with a certain role to this community.',
 5420:                             listusers  => 'Show and manage users in this community.',
 5421:                            },
 5422:                 );
 5423:   if ($linkcontext eq 'domain') {
 5424:       unless ($permission->{'cusr'}) {
 5425:           $links{'domain'}{'singleuser'} = 'View a User';
 5426:           $linktitles{'domain'}{'singleuser'} = 'View information about a user in the domain';
 5427:       }
 5428:   } elsif ($linkcontext eq 'course') {
 5429:       unless ($permission->{'cusr'}) {
 5430:           $links{'course'}{'singleuser'} = 'View a Course User';
 5431:           $linktitles{'course'}{'singleuser'} = 'View information about a user in this course';
 5432:           $links{'course'}{'listusers'} = 'List Course Users';
 5433:           $linktitles{'course'}{'listusers'} = 'Show information about users in this course';
 5434:       }
 5435:   } elsif ($linkcontext eq 'community') {
 5436:       unless ($permission->{'cusr'}) {
 5437:           $links{'community'}{'singleuser'} = 'View a Community User';
 5438:           $linktitles{'community'}{'singleuser'} = 'View information about a user in this community';
 5439:           $links{'community'}{'listusers'} = 'List Community Users';
 5440:           $linktitles{'community'}{'listusers'} = 'Show information about users in this community';
 5441:       }
 5442:   }
 5443:   my @menu = ( {categorytitle => 'Single Users', 
 5444:          items =>
 5445:          [
 5446:             {
 5447:              linktext => $links{$linkcontext}{'singleuser'},
 5448:              icon => 'edit-redo.png',
 5449:              #help => 'Course_Change_Privileges',
 5450:              url => '/adm/createuser?action=singleuser',
 5451:              permission => ($permission->{'view'} || $permission->{'cusr'}),
 5452:              linktitle => $linktitles{$linkcontext}{'singleuser'},
 5453:             },
 5454:          ]},
 5455: 
 5456:          {categorytitle => 'Multiple Users',
 5457:          items => 
 5458:          [
 5459:             {
 5460:              linktext => $links{$linkcontext}{'upload'},
 5461:              icon => 'uplusr.png',
 5462:              #help => 'Course_Create_Class_List',
 5463:              url => '/adm/createuser?action=upload',
 5464:              permission => $permission->{'cusr'},
 5465:              linktitle => 'Upload a CSV or a text file containing users.',
 5466:             },
 5467:             {
 5468:              linktext => $links{$linkcontext}{'listusers'},
 5469:              icon => 'mngcu.png',
 5470:              #help => 'Course_View_Class_List',
 5471:              url => '/adm/createuser?action=listusers',
 5472:              permission => ($permission->{'view'} || $permission->{'cusr'}),
 5473:              linktitle => $linktitles{$linkcontext}{'listusers'}, 
 5474:             },
 5475: 
 5476:          ]},
 5477: 
 5478:          {categorytitle => 'Administration',
 5479:          items => [ ]},
 5480:        );
 5481: 
 5482:     if ($context eq 'domain'){
 5483:         push(@{  $menu[0]->{items} }, # Single Users
 5484:             {
 5485:              linktext => 'User Access Log',
 5486:              icon => 'document-properties.png',
 5487:              #help => 'Domain_User_Access_Logs',
 5488:              url => '/adm/createuser?action=accesslogs',
 5489:              permission => $permission->{'activity'},
 5490:              linktitle => 'View user access log.',
 5491:             }
 5492:         );
 5493:         
 5494:         push(@{ $menu[2]->{items} }, #Category: Administration
 5495:             {
 5496:              linktext => 'Custom Roles',
 5497:              icon => 'emblem-photos.png',
 5498:              #help => 'Course_Editing_Custom_Roles',
 5499:              url => '/adm/createuser?action=custom',
 5500:              permission => $permission->{'custom'},
 5501:              linktitle => 'Configure a custom role.',
 5502:             },
 5503:             {
 5504:              linktext => 'Authoring Space Requests',
 5505:              icon => 'selfenrl-queue.png',
 5506:              #help => 'Domain_Role_Approvals',
 5507:              url => '/adm/createuser?action=processauthorreq',
 5508:              permission => $permission->{'cusr'},
 5509:              linktitle => 'Approve or reject author role requests',
 5510:             },
 5511:             {
 5512:              linktext => 'LON-CAPA Account Requests',
 5513:              icon => 'list-add.png',
 5514:              #help => 'Domain_Username_Approvals',
 5515:              url => '/adm/createuser?action=processusernamereq',
 5516:              permission => $permission->{'cusr'},
 5517:              linktitle => 'Approve or reject LON-CAPA account requests',
 5518:             },
 5519:             {
 5520:              linktext => 'Change Log',
 5521:              icon => 'document-properties.png',
 5522:              #help => 'Course_User_Logs',
 5523:              url => '/adm/createuser?action=changelogs',
 5524:              permission => ($permission->{'cusr'} || $permission->{'view'}),
 5525:              linktitle => 'View change log.',
 5526:             },
 5527:         );
 5528:         
 5529:     }elsif ($context eq 'course'){
 5530:         my ($cnum,$cdom) = &Apache::lonuserutils::get_course_identity();
 5531: 
 5532:         my %linktext = (
 5533:                          'Course'    => {
 5534:                                           single => 'Add/Modify a Student', 
 5535:                                           drop   => 'Drop Students',
 5536:                                           groups => 'Course Groups',
 5537:                                         },
 5538:                          'Community' => {
 5539:                                           single => 'Add/Modify a Member', 
 5540:                                           drop   => 'Drop Members',
 5541:                                           groups => 'Community Groups',
 5542:                                         },
 5543:                        );
 5544:         $linktext{'Placement'} = $linktext{'Course'};
 5545: 
 5546:         my %linktitle = (
 5547:             'Course' => {
 5548:                   single => 'Add a user with the role of student to this course',
 5549:                   drop   => 'Remove a student from this course.',
 5550:                   groups => 'Manage course groups',
 5551:                         },
 5552:             'Community' => {
 5553:                   single => 'Add a user with the role of member to this community',
 5554:                   drop   => 'Remove a member from this community.',
 5555:                   groups => 'Manage community groups',
 5556:                            },
 5557:         );
 5558: 
 5559:         $linktitle{'Placement'} = $linktitle{'Course'};
 5560: 
 5561:         push(@{ $menu[0]->{items} }, #Category: Single Users
 5562:             {   
 5563:              linktext => $linktext{$crstype}{'single'},
 5564:              #help => 'Course_Add_Student',
 5565:              icon => 'list-add.png',
 5566:              url => '/adm/createuser?action=singlestudent',
 5567:              permission => $permission->{'cusr'},
 5568:              linktitle => $linktitle{$crstype}{'single'},
 5569:             },
 5570:         );
 5571:         
 5572:         push(@{ $menu[1]->{items} }, #Category: Multiple Users 
 5573:             {
 5574:              linktext => $linktext{$crstype}{'drop'},
 5575:              icon => 'edit-undo.png',
 5576:              #help => 'Course_Drop_Student',
 5577:              url => '/adm/createuser?action=drop',
 5578:              permission => $permission->{'cusr'},
 5579:              linktitle => $linktitle{$crstype}{'drop'},
 5580:             },
 5581:         );
 5582:         push(@{ $menu[2]->{items} }, #Category: Administration
 5583:             {
 5584:              linktext => 'Helpdesk Access',
 5585:              icon => 'helpdesk-access.png',
 5586:              #help => 'Course_Helpdesk_Access',
 5587:              url => '/adm/createuser?action=helpdesk',
 5588:              permission => ($permission->{'owner'} || $permission->{'co-owner'}),
 5589:              linktitle => 'Helpdesk access options',
 5590:             },
 5591:             {
 5592:              linktext => 'Custom Roles',
 5593:              icon => 'emblem-photos.png',
 5594:              #help => 'Course_Editing_Custom_Roles',
 5595:              url => '/adm/createuser?action=custom',
 5596:              permission => $permission->{'custom'},
 5597:              linktitle => 'Configure a custom role.',
 5598:             },
 5599:             {
 5600:              linktext => $linktext{$crstype}{'groups'},
 5601:              icon => 'grps.png',
 5602:              #help => 'Course_Manage_Group',
 5603:              url => '/adm/coursegroups?refpage=cusr',
 5604:              permission => $permission->{'grp_manage'},
 5605:              linktitle => $linktitle{$crstype}{'groups'},
 5606:             },
 5607:             {
 5608:              linktext => 'Change Log',
 5609:              icon => 'document-properties.png',
 5610:              #help => 'Course_User_Logs',
 5611:              url => '/adm/createuser?action=changelogs',
 5612:              permission => ($permission->{'view'} || $permission->{'cusr'}),
 5613:              linktitle => 'View change log.',
 5614:             },
 5615:         );
 5616:         if ($env{'course.'.$env{'request.course.id'}.'.internal.selfenroll_approval'}) {
 5617:             push(@{ $menu[2]->{items} },
 5618:                     {
 5619:                      linktext => 'Enrollment Requests',
 5620:                      icon => 'selfenrl-queue.png',
 5621:                      #help => 'Course_Approve_Selfenroll',
 5622:                      url => '/adm/createuser?action=selfenrollqueue',
 5623:                      permission => $permission->{'selfenrolladmin'},
 5624:                      linktitle =>'Approve or reject enrollment requests.',
 5625:                     },
 5626:             );
 5627:         }
 5628:         
 5629:         if (!exists($permission->{'cusr_section'})){
 5630:             if ($crstype ne 'Community') {
 5631:                 push(@{ $menu[2]->{items} },
 5632:                     {
 5633:                      linktext => 'Automated Enrollment',
 5634:                      icon => 'roles.png',
 5635:                      #help => 'Course_Automated_Enrollment',
 5636:                      permission => (&Apache::lonnet::auto_run($cnum,$cdom)
 5637:                                          && (($permission->{'cusr'}) ||
 5638:                                              ($permission->{'view'}))),
 5639:                      url  => '/adm/populate',
 5640:                      linktitle => 'Automated enrollment manager.',
 5641:                     }
 5642:                 );
 5643:             }
 5644:             push(@{ $menu[2]->{items} }, 
 5645:                 {
 5646:                  linktext => 'User Self-Enrollment',
 5647:                  icon => 'self_enroll.png',
 5648:                  #help => 'Course_Self_Enrollment',
 5649:                  url => '/adm/createuser?action=selfenroll',
 5650:                  permission => $permission->{'selfenrolladmin'},
 5651:                  linktitle => 'Configure user self-enrollment.',
 5652:                 },
 5653:             );
 5654:         }
 5655:     } elsif ($context eq 'author') {
 5656:         push(@{ $menu[2]->{items} }, #Category: Administration
 5657:             {
 5658:              linktext => 'Change Log',
 5659:              icon => 'document-properties.png',
 5660:              #help => 'Course_User_Logs',
 5661:              url => '/adm/createuser?action=changelogs',
 5662:              permission => $permission->{'cusr'},
 5663:              linktitle => 'View change log.',
 5664:             },
 5665:         );
 5666:     }
 5667:     return Apache::lonhtmlcommon::generate_menu(@menu);
 5668: #               { text => 'View Log-in History',
 5669: #                 help => 'Course_User_Logins',
 5670: #                 action => 'logins',
 5671: #                 permission => $permission->{'cusr'},
 5672: #               });
 5673: }
 5674: 
 5675: sub restore_prev_selections {
 5676:     my %saveable_parameters = ('srchby'   => 'scalar',
 5677: 			       'srchin'   => 'scalar',
 5678: 			       'srchtype' => 'scalar',
 5679: 			       );
 5680:     &Apache::loncommon::store_settings('user','user_picker',
 5681: 				       \%saveable_parameters);
 5682:     &Apache::loncommon::restore_settings('user','user_picker',
 5683: 					 \%saveable_parameters);
 5684: }
 5685: 
 5686: sub print_selfenroll_menu {
 5687:     my ($r,$context,$cid,$cdom,$cnum,$currsettings,$additional,$readonly) = @_;
 5688:     my $crstype = &Apache::loncommon::course_type();
 5689:     my $formname = 'selfenroll';
 5690:     my $nolink = 1;
 5691:     my ($row,$lt) = &Apache::lonuserutils::get_selfenroll_titles();
 5692:     my $groupslist = &Apache::lonuserutils::get_groupslist();
 5693:     my $setsec_js = 
 5694:         &Apache::lonuserutils::setsections_javascript($formname,$groupslist);
 5695:     my %alerts = &Apache::lonlocal::texthash(
 5696:         acto => 'Activation of self-enrollment was selected for the following domain(s)',
 5697:         butn => 'but no user types have been checked.',
 5698:         wilf => "Please uncheck 'activate' or check at least one type.",
 5699:     );
 5700:     my $disabled;
 5701:     if ($readonly) {
 5702:        $disabled = ' disabled="disabled"';
 5703:     }
 5704:     &js_escape(\%alerts);
 5705:     my $selfenroll_js = <<"ENDSCRIPT";
 5706: function update_types(caller,num) {
 5707:     var delidx = getIndexByName('selfenroll_delete');
 5708:     var actidx = getIndexByName('selfenroll_activate');
 5709:     if (caller == 'selfenroll_all') {
 5710:         var selall;
 5711:         for (var i=0; i<document.$formname.selfenroll_all.length; i++) {
 5712:             if (document.$formname.selfenroll_all[i].checked) {
 5713:                 selall = document.$formname.selfenroll_all[i].value;
 5714:             }
 5715:         }
 5716:         if (selall == 1) {
 5717:             if (delidx != -1) {
 5718:                 if (document.$formname.selfenroll_delete.length) {
 5719:                     for (var j=0; j<document.$formname.selfenroll_delete.length; j++) {
 5720:                         document.$formname.selfenroll_delete[j].checked = true;
 5721:                     }
 5722:                 } else {
 5723:                     document.$formname.elements[delidx].checked = true;
 5724:                 }
 5725:             }
 5726:             if (actidx != -1) {
 5727:                 if (document.$formname.selfenroll_activate.length) {
 5728:                     for (var j=0; j<document.$formname.selfenroll_activate.length; j++) {
 5729:                         document.$formname.selfenroll_activate[j].checked = false;
 5730:                     }
 5731:                 } else {
 5732:                     document.$formname.elements[actidx].checked = false;
 5733:                 }
 5734:             }
 5735:             document.$formname.selfenroll_newdom.selectedIndex = 0; 
 5736:         }
 5737:     }
 5738:     if (caller == 'selfenroll_activate') {
 5739:         if (document.$formname.selfenroll_activate.length) {
 5740:             for (var j=0; j<document.$formname.selfenroll_activate.length; j++) {
 5741:                 if (document.$formname.selfenroll_activate[j].value == num) {
 5742:                     if (document.$formname.selfenroll_activate[j].checked) {
 5743:                         for (var i=0; i<document.$formname.selfenroll_all.length; i++) {
 5744:                             if (document.$formname.selfenroll_all[i].value == '1') {
 5745:                                 document.$formname.selfenroll_all[i].checked = false;
 5746:                             }
 5747:                             if (document.$formname.selfenroll_all[i].value == '0') {
 5748:                                 document.$formname.selfenroll_all[i].checked = true;
 5749:                             }
 5750:                         }
 5751:                     }
 5752:                 }
 5753:             }
 5754:         } else {
 5755:             for (var i=0; i<document.$formname.selfenroll_all.length; i++) {
 5756:                 if (document.$formname.selfenroll_all[i].value == '1') {
 5757:                     document.$formname.selfenroll_all[i].checked = false;
 5758:                 }
 5759:                 if (document.$formname.selfenroll_all[i].value == '0') {
 5760:                     document.$formname.selfenroll_all[i].checked = true;
 5761:                 }
 5762:             }
 5763:         }
 5764:     }
 5765:     if (caller == 'selfenroll_delete') {
 5766:         if (document.$formname.selfenroll_delete.length) {
 5767:             for (var j=0; j<document.$formname.selfenroll_delete.length; j++) {
 5768:                 if (document.$formname.selfenroll_delete[j].value == num) {
 5769:                     if (document.$formname.selfenroll_delete[j].checked) {
 5770:                         var delindex = getIndexByName('selfenroll_types_'+num);
 5771:                         if (delindex != -1) { 
 5772:                             if (document.$formname.elements[delindex].length) {
 5773:                                 for (var k=0; k<document.$formname.elements[delindex].length; k++) {
 5774:                                     document.$formname.elements[delindex][k].checked = false;
 5775:                                 }
 5776:                             } else {
 5777:                                 document.$formname.elements[delindex].checked = false;
 5778:                             }
 5779:                         }
 5780:                     }
 5781:                 }
 5782:             }
 5783:         } else {
 5784:             if (document.$formname.selfenroll_delete.checked) {
 5785:                 var delindex = getIndexByName('selfenroll_types_'+num);
 5786:                 if (delindex != -1) {
 5787:                     if (document.$formname.elements[delindex].length) {
 5788:                         for (var k=0; k<document.$formname.elements[delindex].length; k++) {
 5789:                             document.$formname.elements[delindex][k].checked = false;
 5790:                         }
 5791:                     } else {
 5792:                         document.$formname.elements[delindex].checked = false;
 5793:                     }
 5794:                 }
 5795:             }
 5796:         }
 5797:     }
 5798:     return;
 5799: }
 5800: 
 5801: function validate_types(form) {
 5802:     var needaction = new Array();
 5803:     var countfail = 0;
 5804:     var actidx = getIndexByName('selfenroll_activate');
 5805:     if (actidx != -1) {
 5806:         if (document.$formname.selfenroll_activate.length) {
 5807:             for (var j=0; j<document.$formname.selfenroll_activate.length; j++) {
 5808:                 var num = document.$formname.selfenroll_activate[j].value;
 5809:                 if (document.$formname.selfenroll_activate[j].checked) {
 5810:                     countfail = check_types(num,countfail,needaction)
 5811:                 }
 5812:             }
 5813:         } else {
 5814:             if (document.$formname.selfenroll_activate.checked) {
 5815:                 var num = document.$formname.selfenroll_activate.value;
 5816:                 countfail = check_types(num,countfail,needaction)
 5817:             }
 5818:         }
 5819:     }
 5820:     if (countfail > 0) {
 5821:         var msg = "$alerts{'acto'}\\n";
 5822:         var loopend = needaction.length -1;
 5823:         if (loopend > 0) {
 5824:             for (var m=0; m<loopend; m++) {
 5825:                 msg += needaction[m]+", ";
 5826:             }
 5827:         }
 5828:         msg += needaction[loopend]+"\\n$alerts{'butn'}\\n$alerts{'wilf'}";
 5829:         alert(msg);
 5830:         return; 
 5831:     }
 5832:     setSections(form);
 5833: }
 5834: 
 5835: function check_types(num,countfail,needaction) {
 5836:     var typeidx = getIndexByName('selfenroll_types_'+num);
 5837:     var count = 0;
 5838:     if (typeidx != -1) {
 5839:         if (document.$formname.elements[typeidx].length) {
 5840:             for (var k=0; k<document.$formname.elements[typeidx].length; k++) {
 5841:                 if (document.$formname.elements[typeidx][k].checked) {
 5842:                     count ++;
 5843:                 }
 5844:             }
 5845:         } else {
 5846:             if (document.$formname.elements[typeidx].checked) {
 5847:                 count ++;
 5848:             }
 5849:         }
 5850:         if (count == 0) {
 5851:             var domidx = getIndexByName('selfenroll_dom_'+num);
 5852:             if (domidx != -1) {
 5853:                 var domname = document.$formname.elements[domidx].value;
 5854:                 needaction[countfail] = domname;
 5855:                 countfail ++;
 5856:             }
 5857:         }
 5858:     }
 5859:     return countfail;
 5860: }
 5861: 
 5862: function toggleNotify() {
 5863:     var selfenrollApproval = 0;
 5864:     if (document.$formname.selfenroll_approval.length) {
 5865:         for (var i=0; i<document.$formname.selfenroll_approval.length; i++) {
 5866:             if (document.$formname.selfenroll_approval[i].checked) {
 5867:                 selfenrollApproval = document.$formname.selfenroll_approval[i].value;
 5868:                 break;        
 5869:             }
 5870:         }
 5871:     }
 5872:     if (document.getElementById('notified')) {
 5873:         if (selfenrollApproval == 0) {
 5874:             document.getElementById('notified').style.display='none';
 5875:         } else {
 5876:             document.getElementById('notified').style.display='block';
 5877:         }
 5878:     }
 5879:     return;
 5880: }
 5881: 
 5882: function getIndexByName(item) {
 5883:     for (var i=0;i<document.$formname.elements.length;i++) {
 5884:         if (document.$formname.elements[i].name == item) {
 5885:             return i;
 5886:         }
 5887:     }
 5888:     return -1;
 5889: }
 5890: ENDSCRIPT
 5891: 
 5892:     my $output = '<script type="text/javascript">'."\n".
 5893:                  '// <![CDATA['."\n".
 5894:                  $setsec_js."\n".$selfenroll_js."\n".
 5895:                  '// ]]>'."\n".
 5896:                  '</script>'."\n".
 5897:                  '<h3>'.$lt->{'selfenroll'}.'</h3>'."\n";
 5898:  
 5899:     my $visactions = &cat_visibility();
 5900:     my ($cathash,%cattype);
 5901:     my %domconfig = &Apache::lonnet::get_dom('configuration',['coursecategories'],$cdom);
 5902:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 5903:         $cathash = $domconfig{'coursecategories'}{'cats'};
 5904:         $cattype{'auth'} = $domconfig{'coursecategories'}{'auth'};
 5905:         $cattype{'unauth'} = $domconfig{'coursecategories'}{'unauth'};
 5906:         if ($cattype{'auth'} eq '') {
 5907:             $cattype{'auth'} = 'std';
 5908:         }
 5909:         if ($cattype{'unauth'} eq '') {
 5910:             $cattype{'unauth'} = 'std';
 5911:         }
 5912:     } else {
 5913:         $cathash = {};
 5914:         $cattype{'auth'} = 'std';
 5915:         $cattype{'unauth'} = 'std';
 5916:     }
 5917:     if (($cattype{'auth'} eq 'none') && ($cattype{'unauth'} eq 'none')) {
 5918:         $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
 5919:                   '<br />'.
 5920:                   '<br />'.$visactions->{'take'}.'<ul>'.
 5921:                   '<li>'.$visactions->{'dc_chgconf'}.'</li>'.
 5922:                   '</ul>');
 5923:     } elsif (($cattype{'auth'} !~ /^(std|domonly)$/) && ($cattype{'unauth'} !~ /^(std|domonly)$/)) {
 5924:         if ($currsettings->{'uniquecode'}) {
 5925:             $r->print('<span class="LC_info">'.$visactions->{'vis'}.'</span>');
 5926:         } else {
 5927:             $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
 5928:                   '<br />'.
 5929:                   '<br />'.$visactions->{'take'}.'<ul>'.
 5930:                   '<li>'.$visactions->{'dc_setcode'}.'</li>'.
 5931:                   '</ul><br />');
 5932:         }
 5933:     } else {
 5934:         my ($visible,$cansetvis,$vismsgs) = &visible_in_stdcat($cdom,$cnum,\%domconfig);
 5935:         if (ref($visactions) eq 'HASH') {
 5936:             if ($visible) {
 5937:                 $output .= '<p class="LC_info">'.$visactions->{'vis'}.'</p>';
 5938:            } else {
 5939:                 $output .= '<p class="LC_warning">'.$visactions->{'miss'}.'</p>'
 5940:                           .$visactions->{'yous'}.
 5941:                            '<p>'.$visactions->{'gen'}.'<br />'.$visactions->{'coca'};
 5942:                 if (ref($vismsgs) eq 'ARRAY') {
 5943:                     $output .= '<br />'.$visactions->{'make'}.'<ul>';
 5944:                     foreach my $item (@{$vismsgs}) {
 5945:                         $output .= '<li>'.$visactions->{$item}.'</li>';
 5946:                     }
 5947:                     $output .= '</ul>';
 5948:                 }
 5949:                 $output .= '</p>';
 5950:             }
 5951:         }
 5952:     }
 5953:     my $actionhref = '/adm/createuser';
 5954:     if ($context eq 'domain') {
 5955:         $actionhref = '/adm/modifycourse';
 5956:     }
 5957: 
 5958:     my %noedit;
 5959:     unless ($context eq 'domain') {
 5960:         %noedit = &get_noedit_fields($cdom,$cnum,$crstype,$row);
 5961:     }
 5962:     $output .= '<form name="'.$formname.'" method="post" action="'.$actionhref.'">'."\n".
 5963:                &Apache::lonhtmlcommon::start_pick_box();
 5964:     if (ref($row) eq 'ARRAY') {
 5965:         foreach my $item (@{$row}) {
 5966:             my $title = $item; 
 5967:             if (ref($lt) eq 'HASH') {
 5968:                 $title = $lt->{$item};
 5969:             }
 5970:             $output .= &Apache::lonhtmlcommon::row_title($title);
 5971:             if ($item eq 'types') {
 5972:                 my $curr_types;
 5973:                 if (ref($currsettings) eq 'HASH') {
 5974:                     $curr_types = $currsettings->{'selfenroll_types'};
 5975:                 }
 5976:                 if ($noedit{$item}) {
 5977:                     if ($curr_types eq '*') {
 5978:                         $output .= &mt('Any user in any domain');   
 5979:                     } else {
 5980:                         my @entries = split(/;/,$curr_types);
 5981:                         if (@entries > 0) {
 5982:                             $output .= '<ul>'; 
 5983:                             foreach my $entry (@entries) {
 5984:                                 my ($currdom,$typestr) = split(/:/,$entry);
 5985:                                 next if ($typestr eq '');
 5986:                                 my $domdesc = &Apache::lonnet::domain($currdom);
 5987:                                 my @currinsttypes = split(',',$typestr);
 5988:                                 my ($othertitle,$usertypes,$types) = 
 5989:                                     &Apache::loncommon::sorted_inst_types($currdom);
 5990:                                 if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 5991:                                     $usertypes->{'any'} = &mt('any user'); 
 5992:                                     if (keys(%{$usertypes}) > 0) {
 5993:                                         $usertypes->{'other'} = &mt('other users');
 5994:                                     }
 5995:                                     my @longinsttypes = map { $usertypes->{$_}; } @currinsttypes;
 5996:                                     $output .= '<li>'.$domdesc.':'.join(', ',@longinsttypes).'</li>';
 5997:                                  }
 5998:                             }
 5999:                             $output .= '</ul>';
 6000:                         } else {
 6001:                             $output .= &mt('None');
 6002:                         }
 6003:                     }
 6004:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 6005:                     next;
 6006:                 }
 6007:                 my $showdomdesc = 1;
 6008:                 my $includeempty = 1;
 6009:                 my $num = 0;
 6010:                 $output .= &Apache::loncommon::start_data_table().
 6011:                            &Apache::loncommon::start_data_table_row()
 6012:                            .'<td colspan="2"><span class="LC_nobreak"><label>'
 6013:                            .&mt('Any user in any domain:')
 6014:                            .'&nbsp;<input type="radio" name="selfenroll_all" value="1" ';
 6015:                 if ($curr_types eq '*') {
 6016:                     $output .= ' checked="checked" '; 
 6017:                 }
 6018:                 $output .= 'onchange="javascript:update_types('.
 6019:                            "'selfenroll_all'".');"'.$disabled.' />'.&mt('Yes').'</label>'.
 6020:                            '&nbsp;&nbsp;<input type="radio" name="selfenroll_all" value="0" ';
 6021:                 if ($curr_types ne '*') {
 6022:                     $output .= ' checked="checked" ';
 6023:                 }
 6024:                 $output .= ' onchange="javascript:update_types('.
 6025:                            "'selfenroll_all'".');"'.$disabled.' />'.&mt('No').'</label></td>'.
 6026:                            &Apache::loncommon::end_data_table_row().
 6027:                            &Apache::loncommon::end_data_table().
 6028:                            &mt('Or').'<br />'.
 6029:                            &Apache::loncommon::start_data_table();
 6030:                 my %currdoms;
 6031:                 if ($curr_types eq '') {
 6032:                     $output .= &new_selfenroll_dom_row($cdom,'0');
 6033:                 } elsif ($curr_types ne '*') {
 6034:                     my @entries = split(/;/,$curr_types);
 6035:                     if (@entries > 0) {
 6036:                         foreach my $entry (@entries) {
 6037:                             my ($currdom,$typestr) = split(/:/,$entry);
 6038:                             $currdoms{$currdom} = 1;
 6039:                             my $domdesc = &Apache::lonnet::domain($currdom);
 6040:                             my @currinsttypes = split(',',$typestr);
 6041:                             $output .= &Apache::loncommon::start_data_table_row()
 6042:                                        .'<td valign="top"><span class="LC_nobreak">'.&mt('Domain:').'<b>'
 6043:                                        .'&nbsp;'.$domdesc.' ('.$currdom.')'
 6044:                                        .'</b><input type="hidden" name="selfenroll_dom_'.$num
 6045:                                        .'" value="'.$currdom.'" /></span><br />'
 6046:                                        .'<span class="LC_nobreak"><label><input type="checkbox" '
 6047:                                        .'name="selfenroll_delete" value="'.$num.'" onchange="javascript:update_types('."'selfenroll_delete','$num'".');"'.$disabled.' />'
 6048:                                        .&mt('Delete').'</label></span></td>';
 6049:                             $output .= '<td valign="top">&nbsp;&nbsp;'.&mt('User types:').'<br />'
 6050:                                        .&selfenroll_inst_types($num,$currdom,\@currinsttypes,$readonly).'</td>'
 6051:                                        .&Apache::loncommon::end_data_table_row();
 6052:                             $num ++;
 6053:                         }
 6054:                     }
 6055:                 }
 6056:                 my $add_domtitle = &mt('Users in additional domain:');
 6057:                 if ($curr_types eq '*') { 
 6058:                     $add_domtitle = &mt('Users in specific domain:');
 6059:                 } elsif ($curr_types eq '') {
 6060:                     $add_domtitle = &mt('Users in other domain:');
 6061:                 }
 6062:                 $output .= &Apache::loncommon::start_data_table_row()
 6063:                            .'<td colspan="2"><span class="LC_nobreak">'.$add_domtitle.'</span><br />'
 6064:                            .&Apache::loncommon::select_dom_form('','selfenroll_newdom',
 6065:                                                                 $includeempty,$showdomdesc,'','','',$readonly)
 6066:                            .'<input type="hidden" name="selfenroll_types_total" value="'.$num.'" />'
 6067:                            .'</td>'.&Apache::loncommon::end_data_table_row()
 6068:                            .&Apache::loncommon::end_data_table();
 6069:             } elsif ($item eq 'registered') {
 6070:                 my ($regon,$regoff);
 6071:                 my $registered;
 6072:                 if (ref($currsettings) eq 'HASH') {
 6073:                     $registered = $currsettings->{'selfenroll_registered'};
 6074:                 }
 6075:                 if ($noedit{$item}) {
 6076:                     if ($registered) {
 6077:                         $output .= &mt('Must be registered in course');
 6078:                     } else {
 6079:                         $output .= &mt('No requirement');
 6080:                     }
 6081:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 6082:                     next;
 6083:                 }
 6084:                 if ($registered) {
 6085:                     $regon = ' checked="checked" ';
 6086:                     $regoff = '';
 6087:                 } else {
 6088:                     $regon = '';
 6089:                     $regoff = ' checked="checked" ';
 6090:                 }
 6091:                 $output .= '<label>'.
 6092:                            '<input type="radio" name="selfenroll_registered" value="1"'.$regon.$disabled.' />'.
 6093:                            &mt('Yes').'</label>&nbsp;&nbsp;<label>'.
 6094:                            '<input type="radio" name="selfenroll_registered" value="0"'.$regoff.$disabled.' />'.
 6095:                            &mt('No').'</label>';
 6096:             } elsif ($item eq 'enroll_dates') {
 6097:                 my ($starttime,$endtime);
 6098:                 if (ref($currsettings) eq 'HASH') {
 6099:                     $starttime = $currsettings->{'selfenroll_start_date'};
 6100:                     $endtime = $currsettings->{'selfenroll_end_date'};
 6101:                     if ($starttime eq '') {
 6102:                         $starttime = $currsettings->{'default_enrollment_start_date'};
 6103:                     }
 6104:                     if ($endtime eq '') {
 6105:                         $endtime = $currsettings->{'default_enrollment_end_date'};
 6106:                     }
 6107:                 }
 6108:                 if ($noedit{$item}) {
 6109:                     $output .= &mt('From: [_1], to: [_2]',&Apache::lonlocal::locallocaltime($starttime),
 6110:                                                           &Apache::lonlocal::locallocaltime($endtime));
 6111:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 6112:                     next;
 6113:                 }
 6114:                 my $startform =
 6115:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_start_date',$starttime,
 6116:                                       $disabled,undef,undef,undef,undef,undef,undef,$nolink);
 6117:                 my $endform =
 6118:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_end_date',$endtime,
 6119:                                       $disabled,undef,undef,undef,undef,undef,undef,$nolink);
 6120:                 $output .= &selfenroll_date_forms($startform,$endform);
 6121:             } elsif ($item eq 'access_dates') {
 6122:                 my ($starttime,$endtime);
 6123:                 if (ref($currsettings) eq 'HASH') {
 6124:                     $starttime = $currsettings->{'selfenroll_start_access'};
 6125:                     $endtime = $currsettings->{'selfenroll_end_access'};
 6126:                     if ($starttime eq '') {
 6127:                         $starttime = $currsettings->{'default_enrollment_start_date'};
 6128:                     }
 6129:                     if ($endtime eq '') {
 6130:                         $endtime = $currsettings->{'default_enrollment_end_date'};
 6131:                     }
 6132:                 }
 6133:                 if ($noedit{$item}) {
 6134:                     $output .= &mt('From: [_1], to: [_2]',&Apache::lonlocal::locallocaltime($starttime),
 6135:                                                           &Apache::lonlocal::locallocaltime($endtime));
 6136:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 6137:                     next;
 6138:                 }
 6139:                 my $startform =
 6140:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_start_access',$starttime,
 6141:                                       $disabled,undef,undef,undef,undef,undef,undef,$nolink);
 6142:                 my $endform =
 6143:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_end_access',$endtime,
 6144:                                       $disabled,undef,undef,undef,undef,undef,undef,$nolink);
 6145:                 $output .= &selfenroll_date_forms($startform,$endform);
 6146:             } elsif ($item eq 'section') {
 6147:                 my $currsec;
 6148:                 if (ref($currsettings) eq 'HASH') {
 6149:                     $currsec = $currsettings->{'selfenroll_section'};
 6150:                 }
 6151:                 my %sections_count = &Apache::loncommon::get_sections($cdom,$cnum);
 6152:                 my $newsecval;
 6153:                 if ($currsec ne 'none' && $currsec ne '') {
 6154:                     if (!defined($sections_count{$currsec})) {
 6155:                         $newsecval = $currsec;
 6156:                     }
 6157:                 }
 6158:                 if ($noedit{$item}) {
 6159:                     if ($currsec ne '') {
 6160:                         $output .= $currsec;
 6161:                     } else {
 6162:                         $output .= &mt('No specific section');
 6163:                     }
 6164:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 6165:                     next;
 6166:                 }
 6167:                 my $sections_select = 
 6168:                     &Apache::lonuserutils::course_sections(\%sections_count,'st',$currsec,$disabled);
 6169:                 $output .= '<table class="LC_createuser">'."\n".
 6170:                            '<tr class="LC_section_row">'."\n".
 6171:                            '<td align="center">'.&mt('Existing sections')."\n".
 6172:                            '<br />'.$sections_select.'</td><td align="center">'.
 6173:                            &mt('New section').'<br />'."\n".
 6174:                            '<input type="text" name="newsec" size="15" value="'.$newsecval.'"'.$disabled.' />'."\n".
 6175:                            '<input type="hidden" name="sections" value="" />'."\n".
 6176:                            '</td></tr></table>'."\n";
 6177:             } elsif ($item eq 'approval') {
 6178:                 my ($currnotified,$currapproval,%appchecked);
 6179:                 my %selfdescs = &Apache::lonuserutils::selfenroll_default_descs();
 6180:                 if (ref($currsettings) eq 'HASH') {
 6181:                     $currnotified = $currsettings->{'selfenroll_notifylist'};
 6182:                     $currapproval = $currsettings->{'selfenroll_approval'};
 6183:                 }
 6184:                 if ($currapproval !~ /^[012]$/) {
 6185:                     $currapproval = 0;
 6186:                 }
 6187:                 if ($noedit{$item}) {
 6188:                     $output .=  $selfdescs{'approval'}{$currapproval}.
 6189:                                 '<br />'.&mt('(Set by Domain Coordinator)');
 6190:                     next;
 6191:                 }
 6192:                 $appchecked{$currapproval} = ' checked="checked"';
 6193:                 for my $i (0..2) {
 6194:                     $output .= '<label>'.
 6195:                                '<input type="radio" name="selfenroll_approval" value="'.$i.'"'.
 6196:                                $appchecked{$i}.' onclick="toggleNotify();"'.$disabled.' />'.
 6197:                                $selfdescs{'approval'}{$i}.'</label>'.('&nbsp;'x2);
 6198:                 }
 6199:                 my %advhash = &Apache::lonnet::get_course_adv_roles($cid,1);
 6200:                 my (@ccs,%notified);
 6201:                 my $ccrole = 'cc';
 6202:                 if ($crstype eq 'Community') {
 6203:                     $ccrole = 'co';
 6204:                 }
 6205:                 if ($advhash{$ccrole}) {
 6206:                     @ccs = split(/,/,$advhash{$ccrole});
 6207:                 }
 6208:                 if ($currnotified) {
 6209:                     foreach my $current (split(/,/,$currnotified)) {
 6210:                         $notified{$current} = 1;
 6211:                         if (!grep(/^\Q$current\E$/,@ccs)) {
 6212:                             push(@ccs,$current);
 6213:                         }
 6214:                     }
 6215:                 }
 6216:                 if (@ccs) {
 6217:                     my $style;
 6218:                     unless ($currapproval) {
 6219:                         $style = ' style="display: none;"'; 
 6220:                     }
 6221:                     $output .= '<br /><div id="notified"'.$style.'>'.
 6222:                                &mt('Personnel to be notified when an enrollment request needs approval, or has been approved:').'&nbsp;'.
 6223:                                &Apache::loncommon::start_data_table().
 6224:                                &Apache::loncommon::start_data_table_row();
 6225:                     my $count = 0;
 6226:                     my $numcols = 4;
 6227:                     foreach my $cc (sort(@ccs)) {
 6228:                         my $notifyon;
 6229:                         my ($ccuname,$ccudom) = split(/:/,$cc);
 6230:                         if ($notified{$cc}) {
 6231:                             $notifyon = ' checked="checked" ';
 6232:                         }
 6233:                         if ($count && !$count%$numcols) {
 6234:                             $output .= &Apache::loncommon::end_data_table_row().
 6235:                                        &Apache::loncommon::start_data_table_row()
 6236:                         }
 6237:                         $output .= '<td><span class="LC_nobreak"><label>'.
 6238:                                    '<input type="checkbox" name="selfenroll_notify"'.$notifyon.' value="'.$cc.'"'.$disabled.' />'.
 6239:                                    &Apache::loncommon::plainname($ccuname,$ccudom).
 6240:                                    '</label></span></td>';
 6241:                         $count ++;
 6242:                     }
 6243:                     my $rem = $count%$numcols;
 6244:                     if ($rem) {
 6245:                         my $emptycols = $numcols - $rem;
 6246:                         for (my $i=0; $i<$emptycols; $i++) { 
 6247:                             $output .= '<td>&nbsp;</td>';
 6248:                         }
 6249:                     }
 6250:                     $output .= &Apache::loncommon::end_data_table_row().
 6251:                                &Apache::loncommon::end_data_table().
 6252:                                '</div>';
 6253:                 }
 6254:             } elsif ($item eq 'limit') {
 6255:                 my ($crslimit,$selflimit,$nolimit,$currlim,$currcap);
 6256:                 if (ref($currsettings) eq 'HASH') {
 6257:                     $currlim = $currsettings->{'selfenroll_limit'};
 6258:                     $currcap = $currsettings->{'selfenroll_cap'};
 6259:                 }
 6260:                 if ($noedit{$item}) {
 6261:                     if (($currlim eq 'allstudents') || ($currlim eq 'selfenrolled')) {
 6262:                         if ($currlim eq 'allstudents') {
 6263:                             $output .= &mt('Limit by total students');
 6264:                         } elsif ($currlim eq 'selfenrolled') {
 6265:                             $output .= &mt('Limit by total self-enrolled students');
 6266:                         }
 6267:                         $output .= ' '.&mt('Maximum: [_1]',$currcap).
 6268:                                    '<br />'.&mt('(Set by Domain Coordinator)');
 6269:                     } else {
 6270:                         $output .= &mt('No limit').'<br />'.&mt('(Set by Domain Coordinator)');
 6271:                     }
 6272:                     next;
 6273:                 }
 6274:                 if ($currlim eq 'allstudents') {
 6275:                     $crslimit = ' checked="checked" ';
 6276:                     $selflimit = ' ';
 6277:                     $nolimit = ' ';
 6278:                 } elsif ($currlim eq 'selfenrolled') {
 6279:                     $crslimit = ' ';
 6280:                     $selflimit = ' checked="checked" ';
 6281:                     $nolimit = ' '; 
 6282:                 } else {
 6283:                     $crslimit = ' ';
 6284:                     $selflimit = ' ';
 6285:                     $nolimit = ' checked="checked" ';
 6286:                 }
 6287:                 $output .= '<table><tr><td><label>'.
 6288:                            '<input type="radio" name="selfenroll_limit" value="none"'.$nolimit.$disabled.'/>'.
 6289:                            &mt('No limit').'</label></td><td><label>'.
 6290:                            '<input type="radio" name="selfenroll_limit" value="allstudents"'.$crslimit.$disabled.'/>'.
 6291:                            &mt('Limit by total students').'</label></td><td><label>'.
 6292:                            '<input type="radio" name="selfenroll_limit" value="selfenrolled"'.$selflimit.$disabled.'/>'.
 6293:                            &mt('Limit by total self-enrolled students').
 6294:                            '</td></tr><tr>'.
 6295:                            '<td>&nbsp;</td><td colspan="2"><span class="LC_nobreak">'.
 6296:                            ('&nbsp;'x3).&mt('Maximum number allowed: ').
 6297:                            '<input type="text" name="selfenroll_cap" size = "5" value="'.$currcap.'"'.$disabled.' /></td></tr></table>';
 6298:             }
 6299:             $output .= &Apache::lonhtmlcommon::row_closure(1);
 6300:         }
 6301:     }
 6302:     $output .= &Apache::lonhtmlcommon::end_pick_box().'<br />';
 6303:     unless ($readonly) {
 6304:         $output .= '<input type="button" name="selfenrollconf" value="'
 6305:                    .&mt('Save').'" onclick="validate_types(this.form);" />';
 6306:     }
 6307:     $output .= '<input type="hidden" name="action" value="selfenroll" />'
 6308:               .'<input type="hidden" name="state" value="done" />'."\n"
 6309:               .$additional.'</form>';
 6310:     $r->print($output);
 6311:     return;
 6312: }
 6313: 
 6314: sub get_noedit_fields {
 6315:     my ($cdom,$cnum,$crstype,$row) = @_;
 6316:     my %noedit;
 6317:     if (ref($row) eq 'ARRAY') {
 6318:         my %settings = &Apache::lonnet::get('environment',['internal.coursecode','internal.textbook',
 6319:                                                            'internal.selfenrollmgrdc',
 6320:                                                            'internal.selfenrollmgrcc'],$cdom,$cnum);
 6321:         my $type = &Apache::lonuserutils::get_extended_type($cdom,$cnum,$crstype,\%settings);
 6322:         my (%specific_managebydc,%specific_managebycc,%default_managebydc);
 6323:         map { $specific_managebydc{$_} = 1; } (split(/,/,$settings{'internal.selfenrollmgrdc'}));
 6324:         map { $specific_managebycc{$_} = 1; } (split(/,/,$settings{'internal.selfenrollmgrcc'}));
 6325:         my %domdefaults = &Apache::lonnet::get_domain_defaults($cdom);
 6326:         map { $default_managebydc{$_} = 1; } (split(/,/,$domdefaults{$type.'selfenrolladmdc'}));
 6327: 
 6328:         foreach my $item (@{$row}) {
 6329:             next if ($specific_managebycc{$item});
 6330:             if (($specific_managebydc{$item}) || ($default_managebydc{$item})) {
 6331:                 $noedit{$item} = 1;
 6332:             }
 6333:         }
 6334:     }
 6335:     return %noedit;
 6336: } 
 6337: 
 6338: sub visible_in_stdcat {
 6339:     my ($cdom,$cnum,$domconf) = @_;
 6340:     my ($cathash,%settable,@vismsgs,$cansetvis,$visible);
 6341:     unless (ref($domconf) eq 'HASH') {
 6342:         return ($visible,$cansetvis,\@vismsgs);
 6343:     }
 6344:     if (ref($domconf->{'coursecategories'}) eq 'HASH') {
 6345:         if ($domconf->{'coursecategories'}{'togglecats'} eq 'crs') {
 6346:             $settable{'togglecats'} = 1;
 6347:         }
 6348:         if ($domconf->{'coursecategories'}{'categorize'} eq 'crs') {
 6349:             $settable{'categorize'} = 1;
 6350:         }
 6351:         $cathash = $domconf->{'coursecategories'}{'cats'};
 6352:     }
 6353:     if ($settable{'togglecats'} && $settable{'categorize'}) {
 6354:         $cansetvis = &mt('You are able to both assign a course category and choose to exclude this course from the catalog.');   
 6355:     } elsif ($settable{'togglecats'}) {
 6356:         $cansetvis = &mt('You are able to choose to exclude this course from the catalog, but only a Domain Coordinator may assign a course category.'); 
 6357:     } elsif ($settable{'categorize'}) {
 6358:         $cansetvis = &mt('You may assign a course category, but only a Domain Coordinator may choose to exclude this course from the catalog.');  
 6359:     } else {
 6360:         $cansetvis = &mt('Only a Domain Coordinator may assign a course category or choose to exclude this course from the catalog.'); 
 6361:     }
 6362:      
 6363:     my %currsettings =
 6364:         &Apache::lonnet::get('environment',['hidefromcat','categories','internal.coursecode'],
 6365:                              $cdom,$cnum);
 6366:     $visible = 0;
 6367:     if ($currsettings{'internal.coursecode'} ne '') {
 6368:         if (ref($domconf->{'coursecategories'}) eq 'HASH') {
 6369:             $cathash = $domconf->{'coursecategories'}{'cats'};
 6370:             if (ref($cathash) eq 'HASH') {
 6371:                 if ($cathash->{'instcode::0'} eq '') {
 6372:                     push(@vismsgs,'dc_addinst'); 
 6373:                 } else {
 6374:                     $visible = 1;
 6375:                 }
 6376:             } else {
 6377:                 $visible = 1;
 6378:             }
 6379:         } else {
 6380:             $visible = 1;
 6381:         }
 6382:     } else {
 6383:         if (ref($cathash) eq 'HASH') {
 6384:             if ($cathash->{'instcode::0'} ne '') {
 6385:                 push(@vismsgs,'dc_instcode');
 6386:             }
 6387:         } else {
 6388:             push(@vismsgs,'dc_instcode');
 6389:         }
 6390:     }
 6391:     if ($currsettings{'categories'} ne '') {
 6392:         my $cathash;
 6393:         if (ref($domconf->{'coursecategories'}) eq 'HASH') {
 6394:             $cathash = $domconf->{'coursecategories'}{'cats'};
 6395:             if (ref($cathash) eq 'HASH') {
 6396:                 if (keys(%{$cathash}) == 0) {
 6397:                     push(@vismsgs,'dc_catalog');
 6398:                 } elsif ((keys(%{$cathash}) == 1) && ($cathash->{'instcode::0'} ne '')) {
 6399:                     push(@vismsgs,'dc_categories');
 6400:                 } else {
 6401:                     my @currcategories = split('&',$currsettings{'categories'});
 6402:                     my $matched = 0;
 6403:                     foreach my $cat (@currcategories) {
 6404:                         if ($cathash->{$cat} ne '') {
 6405:                             $visible = 1;
 6406:                             $matched = 1;
 6407:                             last;
 6408:                         }
 6409:                     }
 6410:                     if (!$matched) {
 6411:                         if ($settable{'categorize'}) { 
 6412:                             push(@vismsgs,'chgcat');
 6413:                         } else {
 6414:                             push(@vismsgs,'dc_chgcat');
 6415:                         }
 6416:                     }
 6417:                 }
 6418:             }
 6419:         }
 6420:     } else {
 6421:         if (ref($cathash) eq 'HASH') {
 6422:             if ((keys(%{$cathash}) > 1) || 
 6423:                 (keys(%{$cathash}) == 1) && ($cathash->{'instcode::0'} eq '')) {
 6424:                 if ($settable{'categorize'}) {
 6425:                     push(@vismsgs,'addcat');
 6426:                 } else {
 6427:                     push(@vismsgs,'dc_addcat');
 6428:                 }
 6429:             }
 6430:         }
 6431:     }
 6432:     if ($currsettings{'hidefromcat'} eq 'yes') {
 6433:         $visible = 0;
 6434:         if ($settable{'togglecats'}) {
 6435:             unshift(@vismsgs,'unhide');
 6436:         } else {
 6437:             unshift(@vismsgs,'dc_unhide')
 6438:         }
 6439:     }
 6440:     return ($visible,$cansetvis,\@vismsgs);
 6441: }
 6442: 
 6443: sub cat_visibility {
 6444:     my %visactions = &Apache::lonlocal::texthash(
 6445:                    vis => 'This course/community currently appears in the Course/Community Catalog for this domain.',
 6446:                    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.',
 6447:                    miss => 'This course/community does not currently appear in the Course/Community Catalog for this domain.',
 6448:                    none => 'Display of a course catalog is disabled for this domain.',
 6449:                    yous => 'You should remedy this if you plan to allow self-enrollment, otherwise students will have difficulty finding this course.',
 6450:                    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.',
 6451:                    make => 'Make any changes to self-enrollment settings below, click "Save", then take action to include the course in the Catalog:',
 6452:                    take => 'Take the following action to ensure the course appears in the Catalog:',
 6453:                    dc_chgconf => 'Ask a domain coordinator to change the Catalog type for this domain.',
 6454:                    dc_setcode => 'Ask a domain coordinator to assign a six character code to the course',
 6455:                    dc_unhide  => 'Ask a domain coordinator to change the "Exclude from course catalog" setting.',
 6456:                    dc_addinst => 'Ask a domain coordinator to enable display the catalog of "Official courses (with institutional codes)".',
 6457:                    dc_instcode => 'Ask a domain coordinator to assign an institutional code (if this is an official course).',
 6458:                    dc_catalog  => 'Ask a domain coordinator to enable or create at least one course category in the domain.',
 6459:                    dc_categories => 'Ask a domain coordinator to create a hierarchy of categories and sub categories for courses in the domain.',
 6460:                    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',
 6461:                    dc_addcat => 'Ask a domain coordinator to assign a category to the course.',
 6462:     );
 6463:     $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>"');
 6464:     $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>"');
 6465:     $visactions{'addcat'} = &mt('Use [_1]Categorize course[_2] to assign a category to the course.','"<a href="/adm/courseprefs?phase=display&actions=courseinfo">','</a>"');
 6466:     return \%visactions;
 6467: }
 6468: 
 6469: sub new_selfenroll_dom_row {
 6470:     my ($newdom,$num) = @_;
 6471:     my $domdesc = &Apache::lonnet::domain($newdom);
 6472:     my $output;
 6473:     if ($domdesc ne '') {
 6474:         $output .= &Apache::loncommon::start_data_table_row()
 6475:                    .'<td valign="top"><span class="LC_nobreak">'.&mt('Domain:').'&nbsp;<b>'.$domdesc
 6476:                    .' ('.$newdom.')</b><input type="hidden" name="selfenroll_dom_'.$num
 6477:                    .'" value="'.$newdom.'" /></span><br />'
 6478:                    .'<span class="LC_nobreak"><label><input type="checkbox" '
 6479:                    .'name="selfenroll_activate" value="'.$num.'" '
 6480:                    .'onchange="javascript:update_types('
 6481:                    ."'selfenroll_activate','$num'".');" />'
 6482:                    .&mt('Activate').'</label></span></td>';
 6483:         my @currinsttypes;
 6484:         $output .= '<td>'.&mt('User types:').'<br />'
 6485:                    .&selfenroll_inst_types($num,$newdom,\@currinsttypes).'</td>'
 6486:                    .&Apache::loncommon::end_data_table_row();
 6487:     }
 6488:     return $output;
 6489: }
 6490: 
 6491: sub selfenroll_inst_types {
 6492:     my ($num,$currdom,$currinsttypes,$readonly) = @_;
 6493:     my $output;
 6494:     my $numinrow = 4;
 6495:     my $count = 0;
 6496:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($currdom);
 6497:     my $othervalue = 'any';
 6498:     my $disabled;
 6499:     if ($readonly) {
 6500:         $disabled = ' disabled="disabled"';
 6501:     }
 6502:     if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 6503:         if (keys(%{$usertypes}) > 0) {
 6504:             $othervalue = 'other';
 6505:         }
 6506:         $output .= '<table><tr>';
 6507:         foreach my $type (@{$types}) {
 6508:             if (($count > 0) && ($count%$numinrow == 0)) {
 6509:                 $output .= '</tr><tr>';
 6510:             }
 6511:             if (defined($usertypes->{$type})) {
 6512:                 my $esc_type = &escape($type);
 6513:                 $output .= '<td><span class="LC_nobreak"><label><input type = "checkbox" value="'.
 6514:                            $esc_type.'" ';
 6515:                 if (ref($currinsttypes) eq 'ARRAY') {
 6516:                     if (@{$currinsttypes} > 0) {
 6517:                         if (grep(/^any$/,@{$currinsttypes})) {
 6518:                             $output .= 'checked="checked"';
 6519:                         } elsif (grep(/^\Q$esc_type\E$/,@{$currinsttypes})) {
 6520:                             $output .= 'checked="checked"';
 6521:                         }
 6522:                     } else {
 6523:                         $output .= 'checked="checked"';
 6524:                     }
 6525:                 }
 6526:                 $output .= ' name="selfenroll_types_'.$num.'"'.$disabled.' />'.$usertypes->{$type}.'</label></span></td>';
 6527:             }
 6528:             $count ++;
 6529:         }
 6530:         if (($count > 0) && ($count%$numinrow == 0)) {
 6531:             $output .= '</tr><tr>';
 6532:         }
 6533:         $output .= '<td><span class="LC_nobreak"><label><input type = "checkbox" value="'.$othervalue.'"';
 6534:         if (ref($currinsttypes) eq 'ARRAY') {
 6535:             if (@{$currinsttypes} > 0) {
 6536:                 if (grep(/^any$/,@{$currinsttypes})) { 
 6537:                     $output .= ' checked="checked"';
 6538:                 } elsif ($othervalue eq 'other') {
 6539:                     if (grep(/^\Q$othervalue\E$/,@{$currinsttypes})) {
 6540:                         $output .= ' checked="checked"';
 6541:                     }
 6542:                 }
 6543:             } else {
 6544:                 $output .= ' checked="checked"';
 6545:             }
 6546:         } else {
 6547:             $output .= ' checked="checked"';
 6548:         }
 6549:         $output .= ' name="selfenroll_types_'.$num.'"'.$disabled.' />'.$othertitle.'</label></span></td></tr></table>';
 6550:     }
 6551:     return $output;
 6552: }
 6553: 
 6554: sub selfenroll_date_forms {
 6555:     my ($startform,$endform) = @_;
 6556:     my $output .= &Apache::lonhtmlcommon::start_pick_box()."\n".
 6557:                   &Apache::lonhtmlcommon::row_title(&mt('Start date'),
 6558:                                                     'LC_oddrow_value')."\n".
 6559:                   $startform."\n".
 6560:                   &Apache::lonhtmlcommon::row_closure(1).
 6561:                   &Apache::lonhtmlcommon::row_title(&mt('End date'),
 6562:                                                    'LC_oddrow_value')."\n".
 6563:                   $endform."\n".
 6564:                   &Apache::lonhtmlcommon::row_closure(1).
 6565:                   &Apache::lonhtmlcommon::end_pick_box();
 6566:     return $output;
 6567: }
 6568: 
 6569: sub print_userchangelogs_display {
 6570:     my ($r,$context,$permission,$brcrum) = @_;
 6571:     my $formname = 'rolelog';
 6572:     my ($username,$domain,$crstype,$viewablesec,%roleslog);
 6573:     if ($context eq 'domain') {
 6574:         $domain = $env{'request.role.domain'};
 6575:         %roleslog=&Apache::lonnet::dump_dom('nohist_rolelog',$domain);
 6576:     } else {
 6577:         if ($context eq 'course') { 
 6578:             $domain = $env{'course.'.$env{'request.course.id'}.'.domain'};
 6579:             $username = $env{'course.'.$env{'request.course.id'}.'.num'};
 6580:             $crstype = &Apache::loncommon::course_type();
 6581:             $viewablesec = &Apache::lonuserutils::viewable_section($permission);
 6582:             my %saveable_parameters = ('show' => 'scalar',);
 6583:             &Apache::loncommon::store_course_settings('roles_log',
 6584:                                                       \%saveable_parameters);
 6585:             &Apache::loncommon::restore_course_settings('roles_log',
 6586:                                                         \%saveable_parameters);
 6587:         } elsif ($context eq 'author') {
 6588:             $domain = $env{'user.domain'}; 
 6589:             if ($env{'request.role'} =~ m{^au\./\Q$domain\E/$}) {
 6590:                 $username = $env{'user.name'};
 6591:             } else {
 6592:                 undef($domain);
 6593:             }
 6594:         }
 6595:         if ($domain ne '' && $username ne '') { 
 6596:             %roleslog=&Apache::lonnet::dump('nohist_rolelog',$domain,$username);
 6597:         }
 6598:     }
 6599:     if ((keys(%roleslog))[0]=~/^error\:/) { undef(%roleslog); }
 6600: 
 6601:     my $helpitem;
 6602:     if ($context eq 'course') {
 6603:         $helpitem = 'Course_User_Logs';
 6604:     } elsif ($context eq 'domain') {
 6605:         $helpitem = 'Domain_Role_Logs';
 6606:     } elsif ($context eq 'author') {
 6607:         $helpitem = 'Author_User_Logs';
 6608:     }
 6609:     push (@{$brcrum},
 6610:              {href => '/adm/createuser?action=changelogs',
 6611:               text => 'User Management Logs',
 6612:               help => $helpitem});
 6613:     my $bread_crumbs_component = 'User Changes';
 6614:     my $args = { bread_crumbs           => $brcrum,
 6615:                  bread_crumbs_component => $bread_crumbs_component};
 6616: 
 6617:     # Create navigation javascript
 6618:     my $jsnav = &userlogdisplay_js($formname);
 6619: 
 6620:     my $jscript = (<<ENDSCRIPT);
 6621: <script type="text/javascript">
 6622: // <![CDATA[
 6623: $jsnav
 6624: // ]]>
 6625: </script>
 6626: ENDSCRIPT
 6627: 
 6628:     # print page header
 6629:     $r->print(&header($jscript,$args));
 6630: 
 6631:     # set defaults
 6632:     my $now = time();
 6633:     my $defstart = $now - (7*24*3600); #7 days ago 
 6634:     my %defaults = (
 6635:                      page               => '1',
 6636:                      show               => '10',
 6637:                      role               => 'any',
 6638:                      chgcontext         => 'any',
 6639:                      rolelog_start_date => $defstart,
 6640:                      rolelog_end_date   => $now,
 6641:                    );
 6642:     my $more_records = 0;
 6643: 
 6644:     # set current
 6645:     my %curr;
 6646:     foreach my $item ('show','page','role','chgcontext') {
 6647:         $curr{$item} = $env{'form.'.$item};
 6648:     }
 6649:     my ($startdate,$enddate) = 
 6650:         &Apache::lonuserutils::get_dates_from_form('rolelog_start_date','rolelog_end_date');
 6651:     $curr{'rolelog_start_date'} = $startdate;
 6652:     $curr{'rolelog_end_date'} = $enddate;
 6653:     foreach my $key (keys(%defaults)) {
 6654:         if ($curr{$key} eq '') {
 6655:             $curr{$key} = $defaults{$key};
 6656:         }
 6657:     }
 6658:     my (%whodunit,%changed,$version);
 6659:     ($version) = ($r->dir_config('lonVersion') =~ /^([\d\.]+)\-/);
 6660:     my ($minshown,$maxshown);
 6661:     $minshown = 1;
 6662:     my $count = 0;
 6663:     if ($curr{'show'} =~ /\D/) {
 6664:         $curr{'page'} = 1;
 6665:     } else {
 6666:         $maxshown = $curr{'page'} * $curr{'show'};
 6667:         if ($curr{'page'} > 1) {
 6668:             $minshown = 1 + ($curr{'page'} - 1) * $curr{'show'};
 6669:         }
 6670:     }
 6671: 
 6672:     # Form Header
 6673:     $r->print('<form action="/adm/createuser" method="post" name="'.$formname.'">'.
 6674:               &role_display_filter($context,$formname,$domain,$username,\%curr,
 6675:                                    $version,$crstype));
 6676: 
 6677:     my $showntableheader = 0;
 6678: 
 6679:     # Table Header
 6680:     my $tableheader = 
 6681:         &Apache::loncommon::start_data_table_header_row()
 6682:        .'<th>&nbsp;</th>'
 6683:        .'<th>'.&mt('When').'</th>'
 6684:        .'<th>'.&mt('Who made the change').'</th>'
 6685:        .'<th>'.&mt('Changed User').'</th>'
 6686:        .'<th>'.&mt('Role').'</th>';
 6687: 
 6688:     if ($context eq 'course') {
 6689:         $tableheader .= '<th>'.&mt('Section').'</th>';
 6690:     }
 6691:     $tableheader .=
 6692:         '<th>'.&mt('Context').'</th>'
 6693:        .'<th>'.&mt('Start').'</th>'
 6694:        .'<th>'.&mt('End').'</th>'
 6695:        .&Apache::loncommon::end_data_table_header_row();
 6696: 
 6697:     # Display user change log data
 6698:     foreach my $id (sort { $roleslog{$b}{'exe_time'}<=>$roleslog{$a}{'exe_time'} } (keys(%roleslog))) {
 6699:         next if (($roleslog{$id}{'exe_time'} < $curr{'rolelog_start_date'}) ||
 6700:                  ($roleslog{$id}{'exe_time'} > $curr{'rolelog_end_date'}));
 6701:         if ($curr{'show'} !~ /\D/) {
 6702:             if ($count >= $curr{'page'} * $curr{'show'}) {
 6703:                 $more_records = 1;
 6704:                 last;
 6705:             }
 6706:         }
 6707:         if ($curr{'role'} ne 'any') {
 6708:             next if ($roleslog{$id}{'logentry'}{'role'} ne $curr{'role'}); 
 6709:         }
 6710:         if ($curr{'chgcontext'} ne 'any') {
 6711:             if ($curr{'chgcontext'} eq 'selfenroll') {
 6712:                 next if (!$roleslog{$id}{'logentry'}{'selfenroll'});
 6713:             } else {
 6714:                 next if ($roleslog{$id}{'logentry'}{'context'} ne $curr{'chgcontext'});
 6715:             }
 6716:         }
 6717:         if (($context eq 'course') && ($viewablesec ne '')) {
 6718:             next if ($roleslog{$id}{'logentry'}{'section'} ne $viewablesec);
 6719:         }
 6720:         $count ++;
 6721:         next if ($count < $minshown);
 6722:         unless ($showntableheader) {
 6723:             $r->print(&Apache::loncommon::start_data_table()
 6724:                      .$tableheader);
 6725:             $r->rflush();
 6726:             $showntableheader = 1;
 6727:         }
 6728:         if ($whodunit{$roleslog{$id}{'exe_uname'}.':'.$roleslog{$id}{'exe_udom'}} eq '') {
 6729:             $whodunit{$roleslog{$id}{'exe_uname'}.':'.$roleslog{$id}{'exe_udom'}} =
 6730:                 &Apache::loncommon::plainname($roleslog{$id}{'exe_uname'},$roleslog{$id}{'exe_udom'});
 6731:         }
 6732:         if ($changed{$roleslog{$id}{'uname'}.':'.$roleslog{$id}{'udom'}} eq '') {
 6733:             $changed{$roleslog{$id}{'uname'}.':'.$roleslog{$id}{'udom'}} =
 6734:                 &Apache::loncommon::plainname($roleslog{$id}{'uname'},$roleslog{$id}{'udom'});
 6735:         }
 6736:         my $sec = $roleslog{$id}{'logentry'}{'section'};
 6737:         if ($sec eq '') {
 6738:             $sec = &mt('None');
 6739:         }
 6740:         my ($rolestart,$roleend);
 6741:         if ($roleslog{$id}{'delflag'}) {
 6742:             $rolestart = &mt('deleted');
 6743:             $roleend = &mt('deleted');
 6744:         } else {
 6745:             $rolestart = $roleslog{$id}{'logentry'}{'start'};
 6746:             $roleend = $roleslog{$id}{'logentry'}{'end'};
 6747:             if ($rolestart eq '' || $rolestart == 0) {
 6748:                 $rolestart = &mt('No start date'); 
 6749:             } else {
 6750:                 $rolestart = &Apache::lonlocal::locallocaltime($rolestart);
 6751:             }
 6752:             if ($roleend eq '' || $roleend == 0) { 
 6753:                 $roleend = &mt('No end date');
 6754:             } else {
 6755:                 $roleend = &Apache::lonlocal::locallocaltime($roleend);
 6756:             }
 6757:         }
 6758:         my $chgcontext = $roleslog{$id}{'logentry'}{'context'};
 6759:         if ($roleslog{$id}{'logentry'}{'selfenroll'}) {
 6760:             $chgcontext = 'selfenroll';
 6761:         }
 6762:         my %lt = &rolechg_contexts($context,$crstype);
 6763:         if ($chgcontext ne '' && $lt{$chgcontext} ne '') {
 6764:             $chgcontext = $lt{$chgcontext};
 6765:         }
 6766:         $r->print(
 6767:             &Apache::loncommon::start_data_table_row()
 6768:            .'<td>'.$count.'</td>'
 6769:            .'<td>'.&Apache::lonlocal::locallocaltime($roleslog{$id}{'exe_time'}).'</td>'
 6770:            .'<td>'.$whodunit{$roleslog{$id}{'exe_uname'}.':'.$roleslog{$id}{'exe_udom'}}.'</td>'
 6771:            .'<td>'.$changed{$roleslog{$id}{'uname'}.':'.$roleslog{$id}{'udom'}}.'</td>'
 6772:            .'<td>'.&Apache::lonnet::plaintext($roleslog{$id}{'logentry'}{'role'},$crstype).'</td>');
 6773:         if ($context eq 'course') { 
 6774:             $r->print('<td>'.$sec.'</td>');
 6775:         }
 6776:         $r->print(
 6777:             '<td>'.$chgcontext.'</td>'
 6778:            .'<td>'.$rolestart.'</td>'
 6779:            .'<td>'.$roleend.'</td>'
 6780:            .&Apache::loncommon::end_data_table_row()."\n");
 6781:     }
 6782: 
 6783:     if ($showntableheader) { # Table footer, if content displayed above
 6784:         $r->print(&Apache::loncommon::end_data_table().
 6785:                   &userlogdisplay_navlinks(\%curr,$more_records));
 6786:     } else { # No content displayed above
 6787:         $r->print('<p class="LC_info">'
 6788:                  .&mt('There are no records to display.')
 6789:                  .'</p>'
 6790:         );
 6791:     }
 6792: 
 6793:     # Form Footer
 6794:     $r->print( 
 6795:         '<input type="hidden" name="page" value="'.$curr{'page'}.'" />'
 6796:        .'<input type="hidden" name="action" value="changelogs" />'
 6797:        .'</form>');
 6798:     return;
 6799: }
 6800: 
 6801: sub print_useraccesslogs_display {
 6802:     my ($r,$uname,$udom,$permission,$brcrum) = @_;
 6803:     my $formname = 'accesslog';
 6804:     my $form = 'document.accesslog';
 6805: 
 6806: # set breadcrumbs
 6807:     my %breadcrumb_text = &singleuser_breadcrumb('','domain',$udom);
 6808:     my $prevphasestr;
 6809:     if ($env{'form.popup'}) {
 6810:         $brcrum = [];
 6811:     } else {
 6812:         push (@{$brcrum},
 6813:             {href => "javascript:backPage($form)",
 6814:              text => $breadcrumb_text{'search'}});
 6815:         my @prevphases;
 6816:         if ($env{'form.prevphases'}) {
 6817:             @prevphases = split(/,/,$env{'form.prevphases'});
 6818:             $prevphasestr = $env{'form.prevphases'};
 6819:         }
 6820:         if (($env{'form.phase'} eq 'userpicked') || (grep(/^userpicked$/,@prevphases))) {
 6821:             push(@{$brcrum},
 6822:                   {href => "javascript:backPage($form,'get_user_info','select')",
 6823:                    text => $breadcrumb_text{'userpicked'}});
 6824:             if ($env{'form.phase'} eq 'userpicked') {
 6825:                 $prevphasestr = 'userpicked';
 6826:             }
 6827:         }
 6828:     }
 6829:     push(@{$brcrum},
 6830:              {href => '/adm/createuser?action=accesslogs',
 6831:               text => 'User access logs',
 6832:               help => 'Domain_User_Access_Logs'});
 6833:     my $bread_crumbs_component = 'User Access Logs';
 6834:     my $args = { bread_crumbs           => $brcrum,
 6835:                  bread_crumbs_component => 'User Management'};
 6836:     if ($env{'form.popup'}) {
 6837:         $args->{'no_nav_bar'} = 1;
 6838:         $args->{'bread_crumbs_nomenu'} = 1;
 6839:     }
 6840: 
 6841: # set javascript
 6842:     my ($jsback,$elements) = &crumb_utilities();
 6843:     my $jsnav = &userlogdisplay_js($formname);
 6844: 
 6845:     my $jscript = (<<ENDSCRIPT);
 6846: <script type="text/javascript">
 6847: // <![CDATA[
 6848: 
 6849: $jsback
 6850: $jsnav
 6851: 
 6852: // ]]>
 6853: </script>
 6854: 
 6855: ENDSCRIPT
 6856: 
 6857: # print page header
 6858:     $r->print(&header($jscript,$args));
 6859: 
 6860: # early out unless log data can be displayed.
 6861:     unless ($permission->{'activity'}) {
 6862:         $r->print('<p class="LC_warning">'
 6863:                  .&mt('You do not have rights to display user access logs.')
 6864:                  .'</p>');
 6865:         if ($env{'form.popup'}) {
 6866:             $r->print('<p><a href="javascript:window.close()">'.&mt('Close window').'</a></p>');
 6867:         } else {
 6868:             $r->print(&earlyout_accesslog_form($formname,$prevphasestr,$udom));
 6869:         }
 6870:         return;
 6871:     }
 6872: 
 6873:     unless ($udom eq $env{'request.role.domain'}) {
 6874:         $r->print('<p class="LC_warning">'
 6875:                  .&mt("User's domain must match role's domain")
 6876:                  .'</p>'
 6877:                  .&earlyout_accesslog_form($formname,$prevphasestr,$udom));
 6878:         return;
 6879:     }
 6880: 
 6881:     if (($uname eq '') || ($udom eq '')) {
 6882:         $r->print('<p class="LC_warning">'
 6883:                  .&mt('Invalid username or domain')
 6884:                  .'</p>'
 6885:                  .&earlyout_accesslog_form($formname,$prevphasestr,$udom));
 6886:         return;
 6887:     }
 6888: 
 6889:     if (&Apache::lonnet::privileged($uname,$udom,
 6890:                                     [$env{'request.role.domain'}],['dc','su'])) {
 6891:         unless (&Apache::lonnet::privileged($env{'user.name'},$env{'user.domain'},
 6892:                                             [$env{'request.role.domain'}],['dc','su'])) {
 6893:             $r->print('<p class="LC_warning">'
 6894:                  .&mt('You need to be a privileged user to display user access logs for [_1]',
 6895:                       &Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($uname,$udom),
 6896:                                                          $uname,$udom))
 6897:                  .'</p>');
 6898:             if ($env{'form.popup'}) {
 6899:                 $r->print('<p><a href="javascript:window.close()">'.&mt('Close window').'</a></p>');
 6900:             } else {
 6901:                 $r->print(&earlyout_accesslog_form($formname,$prevphasestr,$udom));
 6902:             }
 6903:             return;
 6904:         }
 6905:     }
 6906: 
 6907: # set defaults
 6908:     my $now = time();
 6909:     my $defstart = $now - (7*24*3600);
 6910:     my %defaults = (
 6911:                      page                 => '1',
 6912:                      show                 => '10',
 6913:                      activity             => 'any',
 6914:                      accesslog_start_date => $defstart,
 6915:                      accesslog_end_date   => $now,
 6916:                    );
 6917:     my $more_records = 0;
 6918: 
 6919: # set current
 6920:     my %curr;
 6921:     foreach my $item ('show','page','activity') {
 6922:         $curr{$item} = $env{'form.'.$item};
 6923:     }
 6924:     my ($startdate,$enddate) =
 6925:         &Apache::lonuserutils::get_dates_from_form('accesslog_start_date','accesslog_end_date');
 6926:     $curr{'accesslog_start_date'} = $startdate;
 6927:     $curr{'accesslog_end_date'} = $enddate;
 6928:     foreach my $key (keys(%defaults)) {
 6929:         if ($curr{$key} eq '') {
 6930:             $curr{$key} = $defaults{$key};
 6931:         }
 6932:     }
 6933:     my ($minshown,$maxshown);
 6934:     $minshown = 1;
 6935:     my $count = 0;
 6936:     if ($curr{'show'} =~ /\D/) {
 6937:         $curr{'page'} = 1;
 6938:     } else {
 6939:         $maxshown = $curr{'page'} * $curr{'show'};
 6940:         if ($curr{'page'} > 1) {
 6941:             $minshown = 1 + ($curr{'page'} - 1) * $curr{'show'};
 6942:         }
 6943:     }
 6944: 
 6945: # form header
 6946:     $r->print('<form action="/adm/createuser" method="post" name="'.$formname.'">'.
 6947:               &activity_display_filter($formname,\%curr));
 6948: 
 6949:     my $showntableheader = 0;
 6950:     my ($nav_script,$nav_links);
 6951: 
 6952: # table header
 6953:     my $tableheader = '<h3>'.
 6954:         &mt('User access logs for: [_1]',
 6955:             &Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($uname,$udom),$uname,$udom)).'</h3>'
 6956:        .&Apache::loncommon::start_data_table_header_row()
 6957:        .'<th>&nbsp;</th>'
 6958:        .'<th>'.&mt('When').'</th>'
 6959:        .'<th>'.&mt('HostID').'</th>'
 6960:        .'<th>'.&mt('Event').'</th>'
 6961:        .'<th>'.&mt('Other data').'</th>'
 6962:        .&Apache::loncommon::end_data_table_header_row();
 6963: 
 6964:     my %filters=(
 6965:         start  => $curr{'accesslog_start_date'},
 6966:         end    => $curr{'accesslog_end_date'},
 6967:         action => $curr{'activity'},
 6968:     );
 6969: 
 6970:     my $reply = &Apache::lonnet::userlog_query($uname,$udom,%filters);
 6971:     unless ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 6972:         my (%courses,%missing);
 6973:         my @results = split(/\&/,$reply);
 6974:         foreach my $item (reverse(@results)) {
 6975:             my ($timestamp,$host,$event) = split(/:/,$item);
 6976:             next unless ($event =~ /^(Log|Role)/);
 6977:             if ($curr{'show'} !~ /\D/) {
 6978:                 if ($count >= $curr{'page'} * $curr{'show'}) {
 6979:                     $more_records = 1;
 6980:                     last;
 6981:                 }
 6982:             }
 6983:             $count ++;
 6984:             next if ($count < $minshown);
 6985:             unless ($showntableheader) {
 6986:                 $r->print($nav_script
 6987:                          .&Apache::loncommon::start_data_table()
 6988:                          .$tableheader);
 6989:                 $r->rflush();
 6990:                 $showntableheader = 1;
 6991:             }
 6992:             my ($shown,$extra);
 6993:             my ($event,$data) = split(/\s+/,&unescape($event),2);
 6994:             if ($event eq 'Role') {
 6995:                 my ($rolecode,$extent) = split(/\./,$data,2);
 6996:                 next if ($extent eq '');
 6997:                 my ($crstype,$desc,$info);
 6998:                 if ($extent =~ m{^/($match_domain)/($match_courseid)(?:/(\w+)|)$}) {
 6999:                     my ($cdom,$cnum,$sec) = ($1,$2,$3);
 7000:                     my $cid = $cdom.'_'.$cnum;
 7001:                     if (exists($courses{$cid})) {
 7002:                         $crstype = $courses{$cid}{'type'};
 7003:                         $desc = $courses{$cid}{'description'};
 7004:                     } elsif ($missing{$cid}) {
 7005:                         $crstype = 'Course';
 7006:                         $desc = 'Course/Community';
 7007:                     } else {
 7008:                         my %crsinfo = &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 7009:                         if (ref($crsinfo{$cdom.'_'.$cnum}) eq 'HASH') {
 7010:                             $courses{$cid} = $crsinfo{$cid};
 7011:                             $crstype = $crsinfo{$cid}{'type'};
 7012:                             $desc = $crsinfo{$cid}{'description'};
 7013:                         } else {
 7014:                             $missing{$cid} = 1;
 7015:                         }
 7016:                     }
 7017:                     $extra = &mt($crstype).': <a href="/public/'.$cdom.'/'.$cnum.'/syllabus">'.$desc.'</a>';
 7018:                     if ($sec ne '') {
 7019:                        $extra .= ' ('.&mt('Section: [_1]',$sec).')';
 7020:                     }
 7021:                 } elsif ($extent =~ m{^/($match_domain)/($match_username|$)}) {
 7022:                     my ($dom,$name) = ($1,$2);
 7023:                     if ($rolecode eq 'au') {
 7024:                         $extra = '';
 7025:                     } elsif ($rolecode =~ /^(ca|aa)$/) {
 7026:                         $extra = &mt('Authoring Space: [_1]',$name.':'.$dom);
 7027:                     } elsif ($rolecode =~ /^(li|dg|dh|dc|sc)$/) {
 7028:                         $extra = &mt('Domain: [_1]',$dom);
 7029:                     }
 7030:                 }
 7031:                 my $rolename;
 7032:                 if ($rolecode =~ m{^cr/($match_domain)/($match_username)/(\w+)}) {
 7033:                     my $role = $3;
 7034:                     my $owner = "($2:$1)";
 7035:                     if ($2 eq $1.'-domainconfig') {
 7036:                         $owner = '(ad hoc)';
 7037:                     }
 7038:                     $rolename = &mt('Custom role: [_1]',$role.' '.$owner);
 7039:                 } else {
 7040:                     $rolename = &Apache::lonnet::plaintext($rolecode,$crstype);
 7041:                 }
 7042:                 $shown = &mt('Role selection: [_1]',$rolename);
 7043:             } else {
 7044:                 $shown = &mt($event);
 7045:                 if ($data =~ /^webdav/) {
 7046:                     my ($path,$clientip) = split(/\s+/,$data,2);
 7047:                     $path =~ s/^webdav//;
 7048:                     if ($clientip ne '') {
 7049:                         $extra = &mt('Client IP address: [_1]',$clientip);
 7050:                     }
 7051:                     if ($path ne '') {
 7052:                         $shown .= ' '.&mt('(WebDAV access to [_1])',$path);
 7053:                     }
 7054:                 } elsif ($data ne '') {
 7055:                     $extra = &mt('Client IP address: [_1]',$data);
 7056:                 }
 7057:             }
 7058:             $r->print(
 7059:             &Apache::loncommon::start_data_table_row()
 7060:            .'<td>'.$count.'</td>'
 7061:            .'<td>'.&Apache::lonlocal::locallocaltime($timestamp).'</td>'
 7062:            .'<td>'.$host.'</td>'
 7063:            .'<td>'.$shown.'</td>'
 7064:            .'<td>'.$extra.'</td>'
 7065:            .&Apache::loncommon::end_data_table_row()."\n");
 7066:         }
 7067:     }
 7068: 
 7069:     if ($showntableheader) { # Table footer, if content displayed above
 7070:         $r->print(&Apache::loncommon::end_data_table().
 7071:                   &userlogdisplay_navlinks(\%curr,$more_records));
 7072:     } else { # No content displayed above
 7073:         $r->print('<p class="LC_info">'
 7074:                  .&mt('There are no records to display.')
 7075:                  .'</p>');
 7076:     }
 7077: 
 7078:     if ($env{'form.popup'} == 1) {
 7079:         $r->print('<input type="hidden" name="popup" value="1" />'."\n");
 7080:     }
 7081: 
 7082:     # Form Footer
 7083:     $r->print(
 7084:         '<input type="hidden" name="currstate" value="" />'
 7085:        .'<input type="hidden" name="accessuname" value="'.$uname.'" />'
 7086:        .'<input type="hidden" name="accessudom" value="'.$udom.'" />'
 7087:        .'<input type="hidden" name="page" value="'.$curr{'page'}.'" />'
 7088:        .'<input type="hidden" name="prevphases" value="'.$prevphasestr.'" />'
 7089:        .'<input type="hidden" name="phase" value="activity" />'
 7090:        .'<input type="hidden" name="action" value="accesslogs" />'
 7091:        .'<input type="hidden" name="srchdomain" value="'.$udom.'" />'
 7092:        .'<input type="hidden" name="srchby" value="'.$env{'form.srchby'}.'" />'
 7093:        .'<input type="hidden" name="srchtype" value="'.$env{'form.srchtype'}.'" />'
 7094:        .'<input type="hidden" name="srchterm" value="'.&HTML::Entities::encode($env{'form.srchterm'},'<>"&').'" />'
 7095:        .'<input type="hidden" name="srchin" value="'.$env{'form.srchin'}.'" />'
 7096:        .'</form>');
 7097:     return;
 7098: }
 7099: 
 7100: sub earlyout_accesslog_form {
 7101:     my ($formname,$prevphasestr,$udom) = @_;
 7102:     my $srchterm = &HTML::Entities::encode($env{'form.srchterm'},'<>"&');
 7103:    return <<"END";
 7104: <form action="/adm/createuser" method="post" name="$formname">
 7105: <input type="hidden" name="currstate" value="" />
 7106: <input type="hidden" name="prevphases" value="$prevphasestr" />
 7107: <input type="hidden" name="phase" value="activity" />
 7108: <input type="hidden" name="action" value="accesslogs" />
 7109: <input type="hidden" name="srchdomain" value="$udom" />
 7110: <input type="hidden" name="srchby" value="$env{'form.srchby'}" />
 7111: <input type="hidden" name="srchtype" value="$env{'form.srchtype'}" />
 7112: <input type="hidden" name="srchterm" value="$srchterm" />
 7113: <input type="hidden" name="srchin" value="$env{'form.srchin'}" />
 7114: </form>
 7115: END
 7116: }
 7117: 
 7118: sub activity_display_filter {
 7119:     my ($formname,$curr) = @_;
 7120:     my $nolink = 1;
 7121:     my $output = '<table><tr><td valign="top">'.
 7122:                  '<span class="LC_nobreak"><b>'.&mt('Actions/page:').'</b></span><br />'.
 7123:                  &Apache::lonmeta::selectbox('show',$curr->{'show'},undef,
 7124:                                               (&mt('all'),5,10,20,50,100,1000,10000)).
 7125:                  '</td><td>&nbsp;&nbsp;</td>';
 7126:     my $startform =
 7127:         &Apache::lonhtmlcommon::date_setter($formname,'accesslog_start_date',
 7128:                                             $curr->{'accesslog_start_date'},undef,
 7129:                                             undef,undef,undef,undef,undef,undef,$nolink);
 7130:     my $endform =
 7131:         &Apache::lonhtmlcommon::date_setter($formname,'accesslog_end_date',
 7132:                                             $curr->{'accesslog_end_date'},undef,
 7133:                                             undef,undef,undef,undef,undef,undef,$nolink);
 7134:     my %lt = &Apache::lonlocal::texthash (
 7135:                                           activity => 'Activity',
 7136:                                           Role     => 'Role selection',
 7137:                                           log      => 'Log-in or Logout',
 7138:     );
 7139:     $output .= '<td valign="top"><b>'.&mt('Window during which actions occurred:').'</b><br />'.
 7140:                '<table><tr><td>'.&mt('After:').
 7141:                '</td><td>'.$startform.'</td></tr>'.
 7142:                '<tr><td>'.&mt('Before:').'</td>'.
 7143:                '<td>'.$endform.'</td></tr></table>'.
 7144:                '</td>'.
 7145:                '<td>&nbsp;&nbsp;</td>'.
 7146:                '<td valign="top"><b>'.&mt('Activities').'</b><br />'.
 7147:                '<select name="activity"><option value="any"';
 7148:     if ($curr->{'activity'} eq 'any') {
 7149:         $output .= ' selected="selected"';
 7150:     }
 7151:     $output .= '>'.&mt('Any').'</option>'."\n";
 7152:     foreach my $activity ('Role','log') {
 7153:         my $selstr = '';
 7154:         if ($activity eq $curr->{'activity'}) {
 7155:             $selstr = ' selected="selected"';
 7156:         }
 7157:         $output .= '<option value="'.$activity.'"'.$selstr.'>'.$lt{$activity}.'</option>';
 7158:     }
 7159:     $output .= '</select></td>'.
 7160:                '</tr></table>';
 7161:     # Update Display button
 7162:     $output .= '<p>'
 7163:               .'<input type="submit" value="'.&mt('Update Display').'" />'
 7164:               .'</p><hr />';
 7165:     return $output;
 7166: }
 7167: 
 7168: sub userlogdisplay_js {
 7169:     my ($formname) = @_;
 7170:     return <<"ENDSCRIPT";
 7171: 
 7172: function chgPage(caller) {
 7173:     if (caller == 'previous') {
 7174:         document.$formname.page.value --;
 7175:     }
 7176:     if (caller == 'next') {
 7177:         document.$formname.page.value ++;
 7178:     }
 7179:     document.$formname.submit();
 7180:     return;
 7181: }
 7182: ENDSCRIPT
 7183: }
 7184: 
 7185: sub userlogdisplay_navlinks {
 7186:     my ($curr,$more_records) = @_;
 7187:     return unless(ref($curr) eq 'HASH');
 7188:     # Navigation Buttons
 7189:     my $nav_links = '<p>';
 7190:     if (($curr->{'page'} > 1) || ($more_records)) {
 7191:         if (($curr->{'page'} > 1) && ($curr->{'show'} !~ /\D/)) {
 7192:             $nav_links .= '<input type="button"'
 7193:                          .' onclick="javascript:chgPage('."'previous'".');"'
 7194:                          .' value="'.&mt('Previous [_1] changes',$curr->{'show'})
 7195:                          .'" /> ';
 7196:         }
 7197:         if ($more_records) {
 7198:             $nav_links .= '<input type="button"'
 7199:                          .' onclick="javascript:chgPage('."'next'".');"'
 7200:                          .' value="'.&mt('Next [_1] changes',$curr->{'show'})
 7201:                          .'" />';
 7202:         }
 7203:     }
 7204:     $nav_links .= '</p>';
 7205:     return $nav_links;
 7206: }
 7207: 
 7208: sub role_display_filter {
 7209:     my ($context,$formname,$cdom,$cnum,$curr,$version,$crstype) = @_;
 7210:     my $lctype;
 7211:     if ($context eq 'course') {
 7212:         $lctype = lc($crstype);
 7213:     }
 7214:     my $nolink = 1;
 7215:     my $output = '<table><tr><td valign="top">'.
 7216:                  '<span class="LC_nobreak"><b>'.&mt('Changes/page:').'</b></span><br />'.
 7217:                  &Apache::lonmeta::selectbox('show',$curr->{'show'},undef,
 7218:                                               (&mt('all'),5,10,20,50,100,1000,10000)).
 7219:                  '</td><td>&nbsp;&nbsp;</td>';
 7220:     my $startform =
 7221:         &Apache::lonhtmlcommon::date_setter($formname,'rolelog_start_date',
 7222:                                             $curr->{'rolelog_start_date'},undef,
 7223:                                             undef,undef,undef,undef,undef,undef,$nolink);
 7224:     my $endform =
 7225:         &Apache::lonhtmlcommon::date_setter($formname,'rolelog_end_date',
 7226:                                             $curr->{'rolelog_end_date'},undef,
 7227:                                             undef,undef,undef,undef,undef,undef,$nolink);
 7228:     my %lt = &rolechg_contexts($context,$crstype);
 7229:     $output .= '<td valign="top"><b>'.&mt('Window during which changes occurred:').'</b><br />'.
 7230:                '<table><tr><td>'.&mt('After:').
 7231:                '</td><td>'.$startform.'</td></tr>'.
 7232:                '<tr><td>'.&mt('Before:').'</td>'.
 7233:                '<td>'.$endform.'</td></tr></table>'.
 7234:                '</td>'.
 7235:                '<td>&nbsp;&nbsp;</td>'.
 7236:                '<td valign="top"><b>'.&mt('Role:').'</b><br />'.
 7237:                '<select name="role"><option value="any"';
 7238:     if ($curr->{'role'} eq 'any') {
 7239:         $output .= ' selected="selected"';
 7240:     }
 7241:     $output .=  '>'.&mt('Any').'</option>'."\n";
 7242:     my @roles = &Apache::lonuserutils::roles_by_context($context,1,$crstype);
 7243:     foreach my $role (@roles) {
 7244:         my $plrole;
 7245:         if ($role eq 'cr') {
 7246:             $plrole = &mt('Custom Role');
 7247:         } else {
 7248:             $plrole=&Apache::lonnet::plaintext($role,$crstype);
 7249:         }
 7250:         my $selstr = '';
 7251:         if ($role eq $curr->{'role'}) {
 7252:             $selstr = ' selected="selected"';
 7253:         }
 7254:         $output .= '  <option value="'.$role.'"'.$selstr.'>'.$plrole.'</option>';
 7255:     }
 7256:     $output .= '</select></td>'.
 7257:                '<td>&nbsp;&nbsp;</td>'.
 7258:                '<td valign="top"><b>'.
 7259:                &mt('Context:').'</b><br /><select name="chgcontext">';
 7260:     my @posscontexts;
 7261:     if ($context eq 'course') {
 7262:         @posscontexts = ('any','automated','updatenow','createcourse','course','domain','selfenroll','requestcourses');
 7263:     } elsif ($context eq 'domain') {
 7264:         @posscontexts = ('any','domain','requestauthor','domconfig','server');
 7265:     } else {
 7266:         @posscontexts = ('any','author','domain');
 7267:     } 
 7268:     foreach my $chgtype (@posscontexts) {
 7269:         my $selstr = '';
 7270:         if ($curr->{'chgcontext'} eq $chgtype) {
 7271:             $selstr = ' selected="selected"';
 7272:         }
 7273:         if ($context eq 'course') {
 7274:             if (($chgtype eq 'automated') || ($chgtype eq 'updatenow')) {
 7275:                 next if (!&Apache::lonnet::auto_run($cnum,$cdom));
 7276:             }
 7277:         }
 7278:         $output .= '<option value="'.$chgtype.'"'.$selstr.'>'.$lt{$chgtype}.'</option>'."\n";
 7279:     }
 7280:     $output .= '</select></td>'
 7281:               .'</tr></table>';
 7282: 
 7283:     # Update Display button
 7284:     $output .= '<p>'
 7285:               .'<input type="submit" value="'.&mt('Update Display').'" />'
 7286:               .'</p>';
 7287: 
 7288:     # Server version info
 7289:     my $needsrev = '2.11.0';
 7290:     if ($context eq 'course') {
 7291:         $needsrev = '2.7.0';
 7292:     }
 7293:     
 7294:     $output .= '<p class="LC_info">'
 7295:               .&mt('Only changes made from servers running LON-CAPA [_1] or later are displayed.'
 7296:                   ,$needsrev);
 7297:     if ($version) {
 7298:         $output .= ' '.&mt('This LON-CAPA server is version [_1]',$version);
 7299:     }
 7300:     $output .= '</p><hr />';
 7301:     return $output;
 7302: }
 7303: 
 7304: sub rolechg_contexts {
 7305:     my ($context,$crstype) = @_;
 7306:     my %lt;
 7307:     if ($context eq 'course') {
 7308:         %lt = &Apache::lonlocal::texthash (
 7309:                                              any          => 'Any',
 7310:                                              automated    => 'Automated Enrollment',
 7311:                                              updatenow    => 'Roster Update',
 7312:                                              createcourse => 'Course Creation',
 7313:                                              course       => 'User Management in course',
 7314:                                              domain       => 'User Management in domain',
 7315:                                              selfenroll   => 'Self-enrolled',
 7316:                                              requestcourses => 'Course Request',
 7317:                                          );
 7318:         if ($crstype eq 'Community') {
 7319:             $lt{'createcourse'} = &mt('Community Creation');
 7320:             $lt{'course'} = &mt('User Management in community');
 7321:             $lt{'requestcourses'} = &mt('Community Request');
 7322:         }
 7323:     } elsif ($context eq 'domain') {
 7324:         %lt = &Apache::lonlocal::texthash (
 7325:                                              any           => 'Any',
 7326:                                              domain        => 'User Management in domain',
 7327:                                              requestauthor => 'Authoring Request',
 7328:                                              server        => 'Command line script (DC role)',
 7329:                                              domconfig     => 'Self-enrolled',
 7330:                                          );
 7331:     } else {
 7332:         %lt = &Apache::lonlocal::texthash (
 7333:                                              any    => 'Any',
 7334:                                              domain => 'User Management in domain',
 7335:                                              author => 'User Management by author',
 7336:                                          );
 7337:     } 
 7338:     return %lt;
 7339: }
 7340: 
 7341: sub print_helpdeskaccess_display {
 7342:     my ($r,$permission,$brcrum) = @_;
 7343:     my $formname = 'helpdeskaccess';
 7344:     my $helpitem = 'Course_Helpdesk_Access';
 7345:     push (@{$brcrum},
 7346:              {href => '/adm/createuser?action=helpdesk',
 7347:               text => 'Helpdesk Access',
 7348:               help => $helpitem});
 7349:     my $bread_crumbs_component = 'Helpdesk Staff Access';
 7350:     my $args = { bread_crumbs           => $brcrum,
 7351:                  bread_crumbs_component => $bread_crumbs_component};
 7352: 
 7353:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7354:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7355:     my $confname = $cdom.'-domainconfig';
 7356:     my $crstype = &Apache::loncommon::course_type();
 7357: 
 7358:     my @accesstypes = ('all','dh','da','none');
 7359:     my ($numstatustypes,@jsarray);
 7360:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($cdom);
 7361:     if (ref($types) eq 'ARRAY') {
 7362:         if (@{$types} > 0) {
 7363:             $numstatustypes = scalar(@{$types});
 7364:             push(@accesstypes,'status');
 7365:             @jsarray = ('bystatus');
 7366:         }
 7367:     }
 7368:     my %customroles = &get_domain_customroles($cdom,$confname);
 7369:     my %domhelpdesk = &Apache::lonnet::get_active_domroles($cdom,['dh','da']);
 7370:     if (keys(%domhelpdesk)) {
 7371:        push(@accesstypes,('inc','exc'));
 7372:        push(@jsarray,('notinc','notexc'));
 7373:     }
 7374:     push(@jsarray,'privs');
 7375:     my $hiddenstr = join("','",@jsarray);
 7376:     my $rolestr = join("','",sort(keys(%customroles)));
 7377: 
 7378:     my $jscript;
 7379:     my (%settings,%overridden);
 7380:     if (keys(%customroles)) {
 7381:         &get_adhocrole_settings($env{'request.course.id'},\@accesstypes,
 7382:                                 $types,\%customroles,\%settings,\%overridden);
 7383:         my %jsfull=();
 7384:         my %jslevels= (
 7385:                      course => {},
 7386:                      domain => {},
 7387:                      system => {},
 7388:                     );
 7389:         my %jslevelscurrent=(
 7390:                            course => {},
 7391:                            domain => {},
 7392:                            system => {},
 7393:                           );
 7394:         my (%privs,%jsprivs);
 7395:         &Apache::lonuserutils::custom_role_privs(\%privs,\%jsfull,\%jslevels,\%jslevelscurrent);
 7396:         foreach my $priv (keys(%jsfull)) {
 7397:             if ($jslevels{'course'}{$priv}) {
 7398:                 $jsprivs{$priv} = 1;
 7399:             }
 7400:         }
 7401:         my (%elements,%stored);
 7402:         foreach my $role (keys(%customroles)) {
 7403:             $elements{$role.'_access'} = 'radio';
 7404:             $elements{$role.'_incrs'} = 'radio';
 7405:             if ($numstatustypes) {
 7406:                 $elements{$role.'_status'} = 'checkbox';
 7407:             }
 7408:             if (keys(%domhelpdesk) > 0) {
 7409:                 $elements{$role.'_staff_inc'} = 'checkbox';
 7410:                 $elements{$role.'_staff_exc'} = 'checkbox';
 7411:             }
 7412:             $elements{$role.'_override'} = 'checkbox';
 7413:             if (ref($settings{$role}) eq 'HASH') {
 7414:                 if ($settings{$role}{'access'} ne '') {
 7415:                     my $curraccess = $settings{$role}{'access'};
 7416:                     $stored{$role.'_access'} = $curraccess;
 7417:                     $stored{$role.'_incrs'} = 1;
 7418:                     if ($curraccess eq 'status') {
 7419:                         if (ref($settings{$role}{'status'}) eq 'ARRAY') {
 7420:                             $stored{$role.'_status'} = $settings{$role}{'status'};
 7421:                         }
 7422:                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 7423:                         if (ref($settings{$role}{$curraccess}) eq 'ARRAY') {
 7424:                             $stored{$role.'_staff_'.$curraccess} = $settings{$role}{$curraccess};
 7425:                         }
 7426:                     }
 7427:                 } else {
 7428:                     $stored{$role.'_incrs'} = 0;
 7429:                 }
 7430:                 $stored{$role.'_override'} = [];
 7431:                 if ($env{'course.'.$env{'request.course.id'}.'.internal.adhocpriv.'.$role}) {
 7432:                     if (ref($settings{$role}{'off'}) eq 'ARRAY') {
 7433:                         foreach my $priv (@{$settings{$role}{'off'}}) {
 7434:                             push(@{$stored{$role.'_override'}},$priv);
 7435:                         }
 7436:                     }
 7437:                     if (ref($settings{$role}{'on'}) eq 'ARRAY') {
 7438:                         foreach my $priv (@{$settings{$role}{'on'}}) {
 7439:                             unless (grep(/^$priv$/,@{$stored{$role.'_override'}})) {
 7440:                                 push(@{$stored{$role.'_override'}},$priv);
 7441:                             }
 7442:                         }
 7443:                     }
 7444:                 }
 7445:             } else {
 7446:                 $stored{$role.'_incrs'} = 0;
 7447:             }
 7448:         }
 7449:         $jscript = &Apache::lonhtmlcommon::set_form_elements(\%elements,\%stored);
 7450:     }
 7451: 
 7452:     my $js = <<"ENDJS";
 7453: <script type="text/javascript">
 7454: // <![CDATA[
 7455: $jscript;
 7456: 
 7457: function switchRoleTab(caller,role) {
 7458:     if (document.getElementById(role+'_maindiv')) {
 7459:         if (caller.id != 'LC_current_minitab') {
 7460:             if (document.getElementById('LC_current_minitab')) {
 7461:                 document.getElementById('LC_current_minitab').id=null;
 7462:             }
 7463:             var roledivs = Array('$rolestr');
 7464:             if (roledivs.length > 0) {
 7465:                 for (var i=0; i<roledivs.length; i++) {
 7466:                     if (document.getElementById(roledivs[i]+'_maindiv')) {
 7467:                         document.getElementById(roledivs[i]+'_maindiv').style.display='none';
 7468:                     }
 7469:                 }
 7470:             }
 7471:             caller.id = 'LC_current_minitab';
 7472:             document.getElementById(role+'_maindiv').style.display='block';
 7473:         }
 7474:     }
 7475:     return false;
 7476: }
 7477: 
 7478: function helpdeskAccess(role) {
 7479:     var curraccess = null;
 7480:     if (document.$formname.elements[role+'_access'].length) {
 7481:         for (var i=0; i<document.$formname.elements[role+'_access'].length; i++) {
 7482:             if (document.$formname.elements[role+'_access'][i].checked) {
 7483:                 curraccess = document.$formname.elements[role+'_access'][i].value;
 7484:             }
 7485:         }
 7486:     }
 7487:     var shown = Array();
 7488:     var hidden = Array();
 7489:     if (curraccess == 'none') {
 7490:         hidden = Array ('$hiddenstr');
 7491:     } else {
 7492:         if (curraccess == 'status') {
 7493:             shown = Array ('bystatus','privs');
 7494:             hidden = Array ('notinc','notexc');
 7495:         } else {
 7496:             if (curraccess == 'exc') {
 7497:                 shown = Array ('notexc','privs');
 7498:                 hidden = Array ('notinc','bystatus');
 7499:             }
 7500:             if (curraccess == 'inc') {
 7501:                 shown = Array ('notinc','privs');
 7502:                 hidden = Array ('notexc','bystatus');
 7503:             }
 7504:             if (curraccess == 'all') {
 7505:                 shown = Array ('privs');
 7506:                 hidden = Array ('notinc','notexc','bystatus');
 7507:             }
 7508:         }
 7509:     }
 7510:     if (hidden.length > 0) {
 7511:         for (var i=0; i<hidden.length; i++) {
 7512:             if (document.getElementById(role+'_'+hidden[i])) {
 7513:                 document.getElementById(role+'_'+hidden[i]).style.display = 'none';
 7514:             }
 7515:         }
 7516:     }
 7517:     if (shown.length > 0) {
 7518:         for (var i=0; i<shown.length; i++) {
 7519:             if (document.getElementById(role+'_'+shown[i])) {
 7520:                 if (shown[i] == 'privs') {
 7521:                     document.getElementById(role+'_'+shown[i]).style.display = 'block';
 7522:                 } else {
 7523:                     document.getElementById(role+'_'+shown[i]).style.display = 'inline';
 7524:                 }
 7525:             }
 7526:         }
 7527:     }
 7528:     return;
 7529: }
 7530: 
 7531: function toggleAccess(role) {
 7532:     if ((document.getElementById(role+'_setincrs')) &&
 7533:         (document.getElementById(role+'_setindom'))) {
 7534:         for (var i=0; i<document.$formname.elements[role+'_incrs'].length; i++) {
 7535:             if (document.$formname.elements[role+'_incrs'][i].checked) {
 7536:                 if (document.$formname.elements[role+'_incrs'][i].value == 1) {
 7537:                     document.getElementById(role+'_setindom').style.display = 'none';
 7538:                     document.getElementById(role+'_setincrs').style.display = 'block';
 7539:                 } else {
 7540:                     document.getElementById(role+'_setincrs').style.display = 'none';
 7541:                     document.getElementById(role+'_setindom').style.display = 'block';
 7542:                 }
 7543:                 break;
 7544:             }
 7545:         }
 7546:     }
 7547:     return;
 7548: }
 7549: 
 7550: // ]]>
 7551: </script>
 7552: ENDJS
 7553: 
 7554:     $args->{add_entries} = {onload => "javascript:setFormElements(document.$formname)"};
 7555: 
 7556:     # print page header
 7557:     $r->print(&header($js,$args));
 7558:     # print form header
 7559:     $r->print('<form action="/adm/createuser" method="post" name="'.$formname.'">');
 7560: 
 7561:     if (keys(%customroles)) {
 7562:         my %lt = &Apache::lonlocal::texthash(
 7563:                     'aco'    => 'As course owner you may override the defaults set in the domain for role usage and/or privileges.',
 7564:                     'rou'    => 'Role usage',
 7565:                     'whi'    => 'Which helpdesk personnel may use this role?',
 7566:                     'udd'    => 'Use domain default',
 7567:                     'all'    => 'All with domain helpdesk or helpdesk assistant role',
 7568:                     'dh'     => 'All with domain helpdesk role',
 7569:                     'da'     => 'All with domain helpdesk assistant role',
 7570:                     'none'   => 'None',
 7571:                     'status' => 'Determined based on institutional status',
 7572:                     'inc'    => 'Include all, but exclude specific personnel',
 7573:                     'exc'    => 'Exclude all, but include specific personnel',
 7574:                     'hel'    => 'Helpdesk',
 7575:                     'rpr'    => 'Role privileges',
 7576:                  );
 7577:         $lt{'tfh'} = &mt("Custom [_1]ad hoc[_2] course roles available for use by the domain's helpdesk are as follows",'<i>','</i>');
 7578:         my %domconfig = &Apache::lonnet::get_dom('configuration',['helpsettings'],$cdom);
 7579:         my (%domcurrent,%ordered,%description,%domusage,$disabled);
 7580:         if (ref($domconfig{'helpsettings'}) eq 'HASH') {
 7581:             if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
 7582:                 %domcurrent = %{$domconfig{'helpsettings'}{'adhoc'}};
 7583:             }
 7584:         }
 7585:         my $count = 0;
 7586:         foreach my $role (sort(keys(%customroles))) {
 7587:             my ($order,$desc,$access_in_dom);
 7588:             if (ref($domcurrent{$role}) eq 'HASH') {
 7589:                 $order = $domcurrent{$role}{'order'};
 7590:                 $desc = $domcurrent{$role}{'desc'};
 7591:                 $access_in_dom = $domcurrent{$role}{'access'};
 7592:             }
 7593:             if ($order eq '') {
 7594:                 $order = $count;
 7595:             }
 7596:             $ordered{$order} = $role;
 7597:             if ($desc ne '') {
 7598:                 $description{$role} = $desc;
 7599:             } else {
 7600:                 $description{$role}= $role;
 7601:             }
 7602:             $count++;
 7603:         }
 7604:         %domusage = &domain_adhoc_access(\%customroles,\%domcurrent,\@accesstypes,$usertypes,$othertitle);
 7605:         my @roles_by_num = ();
 7606:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 7607:             push(@roles_by_num,$ordered{$item});
 7608:         }
 7609:         $r->print('<p>'.$lt{'tfh'}.': <i>'.join('</i>, <i>',map { $description{$_}; } @roles_by_num).'</i>.');
 7610:         if ($permission->{'owner'}) {
 7611:             $r->print('<br />'.$lt{'aco'}.'</p><p>');
 7612:             $r->print('<input type="hidden" name="state" value="process" />'.
 7613:                       '<input type="submit" value="'.&mt('Save changes').'" />');
 7614:         } else {
 7615:             if ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'}) {
 7616:                 my ($ownername,$ownerdom) = split(/:/,$env{'course.'.$env{'request.course.id'}.'.internal.courseowner'});
 7617:                 $r->print('<br />'.&mt('The course owner -- [_1] -- can override the default access and/or privileges for these ad hoc roles.',
 7618:                                     &Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($ownername,$ownerdom),$ownername,$ownerdom)));
 7619:             }
 7620:             $disabled = ' disabled="disabled"';
 7621:         }
 7622:         $r->print('</p>');
 7623: 
 7624:         $r->print('<div id="LC_minitab_header"><ul>');
 7625:         my $count = 0;
 7626:         my %visibility;
 7627:         foreach my $role (@roles_by_num) {
 7628:             my $id;
 7629:             if ($count == 0) {
 7630:                 $id=' id="LC_current_minitab"';
 7631:                 $visibility{$role} = ' style="display:block"';
 7632:             } else {
 7633:                 $visibility{$role} = ' style="display:none"';
 7634:             }
 7635:             $count ++;
 7636:             $r->print('<li'.$id.'><a href="#" onclick="javascript:switchRoleTab(this.parentNode,'."'$role'".');">'.$description{$role}.'</a></li>');
 7637:         }
 7638:         $r->print('</ul></div>');
 7639: 
 7640:         foreach my $role (@roles_by_num) {
 7641:             my %usecheck = (
 7642:                              all => ' checked="checked"',
 7643:                            );
 7644:             my %displaydiv = (
 7645:                                 status => 'none',
 7646:                                 inc    => 'none',
 7647:                                 exc    => 'none',
 7648:                                 priv   => 'block',
 7649:                              );
 7650:             my (%selected,$overridden,$incrscheck,$indomcheck,$indomvis,$incrsvis);
 7651:             if (ref($settings{$role}) eq 'HASH') {
 7652:                 if ($settings{$role}{'access'} ne '') {
 7653:                     $indomvis = ' style="display:none"';
 7654:                     $incrsvis = ' style="display:block"';
 7655:                     $incrscheck = ' checked="checked"';
 7656:                     if ($settings{$role}{'access'} ne 'all') {
 7657:                         $usecheck{$settings{$role}{'access'}} = $usecheck{'all'};
 7658:                         delete($usecheck{'all'});
 7659:                         if ($settings{$role}{'access'} eq 'status') {
 7660:                             my $access = 'status';
 7661:                             $displaydiv{$access} = 'inline';
 7662:                             if (ref($settings{$role}{$access}) eq 'ARRAY') {
 7663:                                 $selected{$access} = $settings{$role}{$access};
 7664:                             }
 7665:                         } elsif ($settings{$role}{'access'} =~ /^(inc|exc)$/) {
 7666:                             my $access = $1;
 7667:                             $displaydiv{$access} = 'inline';
 7668:                             if (ref($settings{$role}{$access}) eq 'ARRAY') {
 7669:                                 $selected{$access} = $settings{$role}{$access};
 7670:                             }
 7671:                         } elsif ($settings{$role}{'access'} eq 'none') {
 7672:                             $displaydiv{'priv'} = 'none';
 7673:                         }
 7674:                     }
 7675:                 } else {
 7676:                     $indomcheck = ' checked="checked"';
 7677:                     $indomvis = ' style="display:block"';
 7678:                     $incrsvis = ' style="display:none"';
 7679:                 }
 7680:             } else {
 7681:                 $indomcheck = ' checked="checked"';
 7682:                 $indomvis = ' style="display:block"';
 7683:                 $incrsvis = ' style="display:none"';
 7684:             }
 7685:             $r->print('<div class="LC_left_float" id="'.$role.'_maindiv"'.$visibility{$role}.'>'.
 7686:                       '<fieldset><legend>'.$lt{'rou'}.'</legend>'.
 7687:                       '<p>'.$lt{'whi'}.' <span class="LC_nobreak">'.
 7688:                       '<label><input type="radio" name="'.$role.'_incrs" value="1"'.$incrscheck.' onclick="toggleAccess('."'$role'".');"'.$disabled.'>'.
 7689:                       &mt('Set here in [_1]',lc($crstype)).'</label>'.
 7690:                       '<span>'.('&nbsp;'x2).
 7691:                       '<label><input type="radio" name="'.$role.'_incrs" value="0"'.$indomcheck.' onclick="toggleAccess('."'$role'".');"'.$disabled.'>'.
 7692:                       $lt{'udd'}.'</label><span></p>'.
 7693:                       '<div id="'.$role.'_setindom"'.$indomvis.'>'.
 7694:                       '<span class="LC_cusr_emph">'.$domusage{$role}.'</span></div>'.
 7695:                       '<div id="'.$role.'_setincrs"'.$incrsvis.'>');
 7696:             foreach my $access (@accesstypes) {
 7697:                 $r->print('<p><label><input type="radio" name="'.$role.'_access" value="'.$access.'" '.$usecheck{$access}.
 7698:                           ' onclick="helpdeskAccess('."'$role'".');"'.$disabled.' />'.$lt{$access}.'</label>');
 7699:                 if ($access eq 'status') {
 7700:                     $r->print('<div id="'.$role.'_bystatus" style="display:'.$displaydiv{$access}.'">'.
 7701:                               &Apache::lonuserutils::adhoc_status_types($cdom,undef,$role,$selected{$access},
 7702:                                                                         $othertitle,$usertypes,$types,$disabled).
 7703:                               '</div>');
 7704:                 } elsif (($access eq 'inc') && (keys(%domhelpdesk) > 0)) {
 7705:                     $r->print('<div id="'.$role.'_notinc" style="display:'.$displaydiv{$access}.'">'.
 7706:                               &Apache::lonuserutils::adhoc_staff($access,undef,$role,$selected{$access},
 7707:                                                                  \%domhelpdesk,$disabled).
 7708:                               '</div>');
 7709:                 } elsif (($access eq 'exc') && (keys(%domhelpdesk) > 0)) {
 7710:                     $r->print('<div id="'.$role.'_notexc" style="display:'.$displaydiv{$access}.'">'.
 7711:                               &Apache::lonuserutils::adhoc_staff($access,undef,$role,$selected{$access},
 7712:                                                                  \%domhelpdesk,$disabled).
 7713:                               '</div>');
 7714:                 }
 7715:                 $r->print('</p>');
 7716:             }
 7717:             $r->print('</div></fieldset>');
 7718:             my %full=();
 7719:             my %levels= (
 7720:                          course => {},
 7721:                          domain => {},
 7722:                          system => {},
 7723:                         );
 7724:             my %levelscurrent=(
 7725:                                course => {},
 7726:                                domain => {},
 7727:                                system => {},
 7728:                               );
 7729:             &Apache::lonuserutils::custom_role_privs($customroles{$role},\%full,\%levels,\%levelscurrent);
 7730:             $r->print('<fieldset id="'.$role.'_privs" style="display:'.$displaydiv{'priv'}.'">'.
 7731:                       '<legend>'.$lt{'rpr'}.'</legend>'.
 7732:                       &role_priv_table($role,$permission,$crstype,\%full,\%levels,\%levelscurrent,$overridden{$role}).
 7733:                       '</fieldset></div><div style="padding:0;clear:both;margin:0;border:0"></div>');
 7734:         }
 7735:         if ($permission->{'owner'}) {
 7736:             $r->print('<p><input type="submit" value="'.&mt('Save changes').'" /></p>');
 7737:         }
 7738:     } else {
 7739:         $r->print(&mt('Helpdesk roles have not yet been created in this domain.'));
 7740:     }
 7741:     # Form Footer
 7742:     $r->print('<input type="hidden" name="action" value="helpdesk" />'
 7743:              .'</form>');
 7744:     return;
 7745: }
 7746: 
 7747: sub domain_adhoc_access {
 7748:     my ($roles,$domcurrent,$accesstypes,$usertypes,$othertitle) = @_;
 7749:     my %domusage;
 7750:     return unless ((ref($roles) eq 'HASH') && (ref($domcurrent) eq 'HASH') && (ref($accesstypes) eq 'ARRAY'));
 7751:     foreach my $role (keys(%{$roles})) {
 7752:         if (ref($domcurrent->{$role}) eq 'HASH') {
 7753:             my $access = $domcurrent->{$role}{'access'};
 7754:             if (($access eq '') || (!grep(/^\Q$access\E$/,@{$accesstypes}))) {
 7755:                 $access = 'all';
 7756:                 $domusage{$role} = &mt('Any user in domain with active [_1] or [_2] role',&Apache::lonnet::plaintext('dh'),
 7757:                                                                                           &Apache::lonnet::plaintext('da'));
 7758:             } elsif ($access eq 'status') {
 7759:                 if (ref($domcurrent->{$role}{$access}) eq 'ARRAY') {
 7760:                     my @shown;
 7761:                     foreach my $type (@{$domcurrent->{$role}{$access}}) {
 7762:                         unless ($type eq 'default') {
 7763:                             if ($usertypes->{$type}) {
 7764:                                 push(@shown,$usertypes->{$type});
 7765:                             }
 7766:                         }
 7767:                     }
 7768:                     if (grep(/^default$/,@{$domcurrent->{$role}{$access}})) {
 7769:                         push(@shown,$othertitle);
 7770:                     }
 7771:                     if (@shown) {
 7772:                         my $shownstatus = join(' '.&mt('or').' ',@shown);
 7773:                         $domusage{$role} = &mt('Any user in domain with active [_1] or [_2] role, and institutional status: [_3]',
 7774:                                                &Apache::lonnet::plaintext('dh'),&Apache::lonnet::plaintext('da'),$shownstatus);
 7775:                     } else {
 7776:                         $domusage{$role} = &mt('No one in the domain');
 7777:                     }
 7778:                 }
 7779:             } elsif ($access eq 'inc') {
 7780:                 my @dominc = ();
 7781:                 if (ref($domcurrent->{$role}{'inc'}) eq 'ARRAY') {
 7782:                     foreach my $user (@{$domcurrent->{$role}{'inc'}}) {
 7783:                         my ($uname,$udom) = split(/:/,$user);
 7784:                         push(@dominc,&Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($uname,$udom),$uname,$udom));
 7785:                     }
 7786:                     my $showninc = join(', ',@dominc);
 7787:                     if ($showninc ne '') {
 7788:                         $domusage{$role} = &mt('Include any user in domain with active [_1] or [_2] role, except: [_3]',
 7789:                                                &Apache::lonnet::plaintext('dh'),&Apache::lonnet::plaintext('da'),$showninc);
 7790:                     } else {
 7791:                         $domusage{$role} = &mt('Any user in domain with active [_1] or [_2] role',
 7792:                                                &Apache::lonnet::plaintext('dh'),&Apache::lonnet::plaintext('da'));
 7793:                     }
 7794:                 }
 7795:             } elsif ($access eq 'exc') {
 7796:                 my @domexc = ();
 7797:                 if (ref($domcurrent->{$role}{'exc'}) eq 'ARRAY') {
 7798:                     foreach my $user (@{$domcurrent->{$role}{'exc'}}) {
 7799:                         my ($uname,$udom) = split(/:/,$user);
 7800:                         push(@domexc,&Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($uname,$udom),$uname,$udom));
 7801:                     }
 7802:                 }
 7803:                 my $shownexc = join(', ',@domexc);
 7804:                 if ($shownexc ne '') {
 7805:                     $domusage{$role} = &mt('Only the following in the domain with active [_1] or [_2] role: [_3]',
 7806:                                            &Apache::lonnet::plaintext('dh'),&Apache::lonnet::plaintext('da'),$shownexc);
 7807:                 } else {
 7808:                     $domusage{$role} = &mt('No one in the domain');
 7809:                 }
 7810:             } elsif ($access eq 'none') {
 7811:                 $domusage{$role} = &mt('No one in the domain');
 7812:             } elsif ($access eq 'dh') {
 7813:                 $domusage{$role} = &mt('Any user in domain with active [_1] role',&Apache::lonnet::plaintext('dh'));
 7814:             } elsif ($access eq 'da') {
 7815:                 $domusage{$role} = &mt('Any user in domain with active [_1] role',&Apache::lonnet::plaintext('da'));
 7816:             } elsif ($access eq 'all') {
 7817:                 $domusage{$role} = &mt('Any user in domain with active [_1] or [_2] role',
 7818:                                        &Apache::lonnet::plaintext('dh'),&Apache::lonnet::plaintext('da'));
 7819:             }
 7820:         } else {
 7821:             $domusage{$role} = &mt('Any user in domain with active [_1] or [_2] role',
 7822:                                    &Apache::lonnet::plaintext('dh'),&Apache::lonnet::plaintext('da'));
 7823:         }
 7824:     }
 7825:     return %domusage;
 7826: }
 7827: 
 7828: sub get_domain_customroles {
 7829:     my ($cdom,$confname) = @_;
 7830:     my %existing=&Apache::lonnet::dump('roles',$cdom,$confname,'rolesdef_');
 7831:     my %customroles;
 7832:     foreach my $key (keys(%existing)) {
 7833:         if ($key=~/^rolesdef\_(\w+)$/) {
 7834:             my $rolename = $1;
 7835:             my %privs;
 7836:             ($privs{'system'},$privs{'domain'},$privs{'course'}) = split(/\_/,$existing{$key});
 7837:             $customroles{$rolename} = \%privs;
 7838:         }
 7839:     }
 7840:     return %customroles;
 7841: }
 7842: 
 7843: sub role_priv_table {
 7844:     my ($role,$permission,$crstype,$full,$levels,$levelscurrent,$overridden) = @_;
 7845:     return unless ((ref($full) eq 'HASH') && (ref($levels) eq 'HASH') &&
 7846:                    (ref($levelscurrent) eq 'HASH'));
 7847:     my %lt=&Apache::lonlocal::texthash (
 7848:                     'crl'  => 'Course Level Privilege',
 7849:                     'def'  => 'Domain Defaults',
 7850:                     'ove'  => 'Override in Course',
 7851:                     'ine'  => 'In effect',
 7852:                     'dis'  => 'Disabled',
 7853:                     'ena'  => 'Enabled',
 7854:                    );
 7855:     if ($crstype eq 'Community') {
 7856:         $lt{'ove'} = 'Override in Community',
 7857:     }
 7858:     my @status = ('Disabled','Enabled');
 7859:     my (%on,%off);
 7860:     if (ref($overridden) eq 'HASH') {
 7861:         if (ref($overridden->{'on'}) eq 'ARRAY') {
 7862:             map { $on{$_} = 1; } (@{$overridden->{'on'}});
 7863:         }
 7864:         if (ref($overridden->{'off'}) eq 'ARRAY') {
 7865:             map { $off{$_} = 1; } (@{$overridden->{'off'}});
 7866:         }
 7867:     }
 7868:     my $output=&Apache::loncommon::start_data_table().
 7869:                &Apache::loncommon::start_data_table_header_row().
 7870:                '<th>'.$lt{'crl'}.'</th><th>'.$lt{'def'}.'</th><th>'.$lt{'ove'}.
 7871:                '</th><th>'.$lt{'ine'}.'</th>'.
 7872:                &Apache::loncommon::end_data_table_header_row();
 7873:     foreach my $priv (sort(keys(%{$full}))) {
 7874:         next unless ($levels->{'course'}{$priv});
 7875:         my $privtext = &Apache::lonnet::plaintext($priv,$crstype);
 7876:         my ($default,$ineffect);
 7877:         if ($levelscurrent->{'course'}{$priv}) {
 7878:             $default = '<img src="/adm/lonIcons/navmap.correct.gif" alt="'.$lt{'ena'}.'" />';
 7879:             $ineffect = $default;
 7880:         }
 7881:         my ($customstatus,$checked);
 7882:         $output .= &Apache::loncommon::start_data_table_row().
 7883:                    '<td>'.$privtext.'</td>'.
 7884:                    '<td>'.$default.'</td><td>';
 7885:         if (($levelscurrent->{'course'}{$priv}) && ($off{$priv})) {
 7886:             if ($permission->{'owner'}) {
 7887:                 $checked = ' checked="checked"';
 7888:             }
 7889:             $customstatus = '<img src="/adm/lonIcons/navmap.wrong.gif" alt="'.$lt{'dis'}.'" />';
 7890:             $ineffect = $customstatus;
 7891:         } elsif ((!$levelscurrent->{'course'}{$priv}) && ($on{$priv})) {
 7892:             if ($permission->{'owner'}) {
 7893:                 $checked = ' checked="checked"';
 7894:             }
 7895:             $customstatus = '<img src="/adm/lonIcons/navmap.correct.gif" alt="'.$lt{'ena'}.'" />';
 7896:             $ineffect = $customstatus;
 7897:         }
 7898:         if ($permission->{'owner'}) {
 7899:             $output .= '<input type="checkbox" name="'.$role.'_override" value="'.$priv.'"'.$checked.' />';
 7900:         } else {
 7901:             $output .= $customstatus;
 7902:         }
 7903:         $output .= '</td><td>'.$ineffect.'</td>'.
 7904:                    &Apache::loncommon::end_data_table_row();
 7905:     }
 7906:     $output .= &Apache::loncommon::end_data_table();
 7907:     return $output;
 7908: }
 7909: 
 7910: sub get_adhocrole_settings {
 7911:     my ($cid,$accesstypes,$types,$customroles,$settings,$overridden) = @_;
 7912:     return unless ((ref($accesstypes) eq 'ARRAY') && (ref($customroles) eq 'HASH') &&
 7913:                    (ref($settings) eq 'HASH') && (ref($overridden) eq 'HASH'));
 7914:     foreach my $role (split(/,/,$env{'course.'.$cid.'.internal.adhocaccess'})) {
 7915:         my ($curraccess,$rest) = split(/=/,$env{'course.'.$cid.'.internal.adhoc.'.$role});
 7916:         if (($curraccess ne '') && (grep(/^\Q$curraccess\E$/,@{$accesstypes}))) {
 7917:             $settings->{$role}{'access'} = $curraccess;
 7918:             if (($curraccess eq 'status') && (ref($types) eq 'ARRAY')) {
 7919:                 my @status = split(/,/,$rest);
 7920:                 my @currstatus;
 7921:                 foreach my $type (@status) {
 7922:                     if ($type eq 'default') {
 7923:                         push(@currstatus,$type);
 7924:                     } elsif (grep(/^\Q$type\E$/,@{$types})) {
 7925:                         push(@currstatus,$type);
 7926:                     }
 7927:                 }
 7928:                 if (@currstatus) {
 7929:                     $settings->{$role}{$curraccess} = \@currstatus;
 7930:                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 7931:                     my @personnel = split(/,/,$rest);
 7932:                     $settings->{$role}{$curraccess} = \@personnel;
 7933:                 }
 7934:             }
 7935:         }
 7936:     }
 7937:     foreach my $role (keys(%{$customroles})) {
 7938:         if ($env{'course.'.$cid.'.internal.adhocpriv.'.$role}) {
 7939:             my %currentprivs;
 7940:             if (ref($customroles->{$role}) eq 'HASH') {
 7941:                 if (exists($customroles->{$role}{'course'})) {
 7942:                     my %full=();
 7943:                     my %levels= (
 7944:                                   course => {},
 7945:                                   domain => {},
 7946:                                   system => {},
 7947:                                 );
 7948:                     my %levelscurrent=(
 7949:                                         course => {},
 7950:                                         domain => {},
 7951:                                         system => {},
 7952:                                       );
 7953:                     &Apache::lonuserutils::custom_role_privs($customroles->{$role},\%full,\%levels,\%levelscurrent);
 7954:                     %currentprivs = %{$levelscurrent{'course'}};
 7955:                 }
 7956:             }
 7957:             foreach my $item (split(/,/,$env{'course.'.$cid.'.internal.adhocpriv.'.$role})) {
 7958:                 next if ($item eq '');
 7959:                 my ($rule,$rest) = split(/=/,$item);
 7960:                 next unless (($rule eq 'off') || ($rule eq 'on'));
 7961:                 foreach my $priv (split(/:/,$rest)) {
 7962:                     if ($priv ne '') {
 7963:                         if ($rule eq 'off') {
 7964:                             push(@{$overridden->{$role}{'off'}},$priv);
 7965:                             if ($currentprivs{$priv}) {
 7966:                                 push(@{$settings->{$role}{'off'}},$priv);
 7967:                             }
 7968:                         } else {
 7969:                             push(@{$overridden->{$role}{'on'}},$priv);
 7970:                             unless ($currentprivs{$priv}) {
 7971:                                 push(@{$settings->{$role}{'on'}},$priv);
 7972:                             }
 7973:                         }
 7974:                     }
 7975:                 }
 7976:             }
 7977:         }
 7978:     }
 7979:     return;
 7980: }
 7981: 
 7982: sub update_helpdeskaccess {
 7983:     my ($r,$permission,$brcrum) = @_;
 7984:     my $helpitem = 'Course_Helpdesk_Access';
 7985:     push (@{$brcrum},
 7986:              {href => '/adm/createuser?action=helpdesk',
 7987:               text => 'Helpdesk Access',
 7988:               help => $helpitem},
 7989:              {href => '/adm/createuser?action=helpdesk',
 7990:               text => 'Result',
 7991:               help => $helpitem}
 7992:          );
 7993:     my $bread_crumbs_component = 'Helpdesk Staff Access';
 7994:     my $args = { bread_crumbs           => $brcrum,
 7995:                  bread_crumbs_component => $bread_crumbs_component};
 7996: 
 7997:     # print page header
 7998:     $r->print(&header('',$args));
 7999:     unless ((ref($permission) eq 'HASH') && ($permission->{'owner'})) {
 8000:         $r->print('<p class="LC_error">'.&mt('You do not have permission to change helpdesk access.').'</p>');
 8001:         return;
 8002:     }
 8003:     my @accesstypes = ('all','dh','da','none','status','inc','exc');
 8004:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8005:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 8006:     my $confname = $cdom.'-domainconfig';
 8007:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($cdom);
 8008:     my $crstype = &Apache::loncommon::course_type();
 8009:     my %customroles = &get_domain_customroles($cdom,$confname);
 8010:     my (%settings,%overridden);
 8011:     &get_adhocrole_settings($env{'request.course.id'},\@accesstypes,
 8012:                             $types,\%customroles,\%settings,\%overridden);
 8013:     my %domhelpdesk = &Apache::lonnet::get_active_domroles($cdom,['dh','da']);
 8014:     my (%changed,%storehash,@todelete);
 8015: 
 8016:     if (keys(%customroles)) {
 8017:         my (%newsettings,@incrs);
 8018:         foreach my $role (keys(%customroles)) {
 8019:             $newsettings{$role} = {
 8020:                                     access => '',
 8021:                                     status => '',
 8022:                                     exc    => '',
 8023:                                     inc    => '',
 8024:                                     on     => '',
 8025:                                     off    => '',
 8026:                                   };
 8027:             my %current;
 8028:             if (ref($settings{$role}) eq 'HASH') {
 8029:                 %current = %{$settings{$role}};
 8030:             }
 8031:             if (ref($overridden{$role}) eq 'HASH') {
 8032:                 $current{'overridden'} = $overridden{$role};
 8033:             }
 8034:             if ($env{'form.'.$role.'_incrs'}) {
 8035:                 my $access = $env{'form.'.$role.'_access'};
 8036:                 if (grep(/^\Q$access\E$/,@accesstypes)) {
 8037:                     push(@incrs,$role);
 8038:                     unless ($current{'access'} eq $access) {
 8039:                         $changed{$role}{'access'} = 1;
 8040:                         $storehash{'internal.adhoc.'.$role} = $access;
 8041:                     }
 8042:                     if ($access eq 'status') {
 8043:                         my @statuses = &Apache::loncommon::get_env_multiple('form.'.$role.'_status');
 8044:                         my @stored;
 8045:                         my @shownstatus;
 8046:                         if (ref($types) eq 'ARRAY') {
 8047:                             foreach my $type (sort(@statuses)) {
 8048:                                 if ($type eq 'default') {
 8049:                                     push(@stored,$type);
 8050:                                 } elsif (grep(/^\Q$type\E$/,@{$types})) {
 8051:                                     push(@stored,$type);
 8052:                                     push(@shownstatus,$usertypes->{$type});
 8053:                                 }
 8054:                             }
 8055:                             if (grep(/^default$/,@statuses)) {
 8056:                                 push(@shownstatus,$othertitle);
 8057:                             }
 8058:                             $storehash{'internal.adhoc.'.$role} .= '='.join(',',@stored);
 8059:                         }
 8060:                         $newsettings{$role}{'status'} = join(' '.&mt('or').' ',@shownstatus);
 8061:                         if (ref($current{'status'}) eq 'ARRAY') {
 8062:                             my @diffs = &Apache::loncommon::compare_arrays(\@stored,$current{'status'});
 8063:                             if (@diffs) {
 8064:                                 $changed{$role}{'status'} = 1;
 8065:                             }
 8066:                         } elsif (@stored) {
 8067:                             $changed{$role}{'status'} = 1;
 8068:                         }
 8069:                     } elsif (($access eq 'inc') || ($access eq 'exc')) {
 8070:                         my @personnel = &Apache::loncommon::get_env_multiple('form.'.$role.'_staff_'.$access);
 8071:                         my @newspecstaff;
 8072:                         my @stored;
 8073:                         my @currstaff;
 8074:                         foreach my $person (sort(@personnel)) {
 8075:                             if ($domhelpdesk{$person}) {
 8076:                                 push(@stored,$person);
 8077:                             }
 8078:                         }
 8079:                         if (ref($current{$access}) eq 'ARRAY') {
 8080:                             my @diffs = &Apache::loncommon::compare_arrays(\@stored,$current{$access});
 8081:                             if (@diffs) {
 8082:                                 $changed{$role}{$access} = 1;
 8083:                             }
 8084:                         } elsif (@stored) {
 8085:                             $changed{$role}{$access} = 1;
 8086:                         }
 8087:                         $storehash{'internal.adhoc.'.$role} .= '='.join(',',@stored);
 8088:                         foreach my $person (@stored) {
 8089:                             my ($uname,$udom) = split(/:/,$person);
 8090:                             push(@newspecstaff,&Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($uname,$udom,'lastname'),$uname,$udom));
 8091:                         }
 8092:                         $newsettings{$role}{$access} = join(', ',sort(@newspecstaff));
 8093:                     }
 8094:                     $newsettings{$role}{'access'} = $access;
 8095:                 }
 8096:             } else {
 8097:                 if (($current{'access'} ne '') && (grep(/^\Q$current{'access'}\E$/,@accesstypes))) {
 8098:                     $changed{$role}{'access'} = 1;
 8099:                     $newsettings{$role} = {};
 8100:                     push(@todelete,'internal.adhoc.'.$role);
 8101:                 }
 8102:             }
 8103:             if (($env{'form.'.$role.'_incrs'}) && ($env{'form.'.$role.'_access'} eq 'none')) {
 8104:                 if (ref($current{'overridden'}) eq 'HASH') {
 8105:                     push(@todelete,'internal.adhocpriv.'.$role);
 8106:                 }
 8107:             } else {
 8108:                 my %full=();
 8109:                 my %levels= (
 8110:                              course => {},
 8111:                              domain => {},
 8112:                              system => {},
 8113:                             );
 8114:                 my %levelscurrent=(
 8115:                                    course => {},
 8116:                                    domain => {},
 8117:                                    system => {},
 8118:                                   );
 8119:                 &Apache::lonuserutils::custom_role_privs($customroles{$role},\%full,\%levels,\%levelscurrent);
 8120:                 my (@updatedon,@updatedoff,@override);
 8121:                 @override = &Apache::loncommon::get_env_multiple('form.'.$role.'_override');
 8122:                 if (@override) {
 8123:                     foreach my $priv (sort(keys(%full))) {
 8124:                         next unless ($levels{'course'}{$priv});
 8125:                         if (grep(/^\Q$priv\E$/,@override)) {
 8126:                             if ($levelscurrent{'course'}{$priv}) {
 8127:                                 push(@updatedoff,$priv);
 8128:                             } else {
 8129:                                 push(@updatedon,$priv);
 8130:                             }
 8131:                         }
 8132:                     }
 8133:                 }
 8134:                 if (@updatedon) {
 8135:                     $newsettings{$role}{'on'} = join('</li><li>', map { &Apache::lonnet::plaintext($_,$crstype) } (@updatedon));
 8136:                 }
 8137:                 if (@updatedoff) {
 8138:                     $newsettings{$role}{'off'} = join('</li><li>', map { &Apache::lonnet::plaintext($_,$crstype) } (@updatedoff));
 8139:                 }
 8140:                 if (ref($current{'overridden'}) eq 'HASH') {
 8141:                     if (ref($current{'overridden'}{'on'}) eq 'ARRAY') {
 8142:                         if (@updatedon) {
 8143:                             my @diffs = &Apache::loncommon::compare_arrays(\@updatedon,$current{'overridden'}{'on'});
 8144:                             if (@diffs) {
 8145:                                 $changed{$role}{'on'} = 1;
 8146:                             }
 8147:                         } else {
 8148:                             $changed{$role}{'on'} = 1;
 8149:                         }
 8150:                     } elsif (@updatedon) {
 8151:                         $changed{$role}{'on'} = 1;
 8152:                     }
 8153:                     if (ref($current{'overridden'}{'off'}) eq 'ARRAY') {
 8154:                         if (@updatedoff) {
 8155:                             my @diffs = &Apache::loncommon::compare_arrays(\@updatedoff,$current{'overridden'}{'off'});
 8156:                             if (@diffs) {
 8157:                                 $changed{$role}{'off'} = 1;
 8158:                             }
 8159:                         } else {
 8160:                             $changed{$role}{'off'} = 1;
 8161:                         }
 8162:                     } elsif (@updatedoff) {
 8163:                         $changed{$role}{'off'} = 1;
 8164:                     }
 8165:                 } else {
 8166:                     if (@updatedon) {
 8167:                         $changed{$role}{'on'} = 1;
 8168:                     }
 8169:                     if (@updatedoff) {
 8170:                         $changed{$role}{'off'} = 1;
 8171:                     }
 8172:                 }
 8173:                 if (ref($changed{$role}) eq 'HASH') {
 8174:                     if (($changed{$role}{'on'} || $changed{$role}{'off'})) {
 8175:                         my $newpriv;
 8176:                         if (@updatedon) {
 8177:                             $newpriv = 'on='.join(':',@updatedon);
 8178:                         }
 8179:                         if (@updatedoff) {
 8180:                             $newpriv .= ($newpriv ? ',' : '' ).'off='.join(':',@updatedoff);
 8181:                         }
 8182:                         if ($newpriv eq '') {
 8183:                             push(@todelete,'internal.adhocpriv.'.$role);
 8184:                         } else {
 8185:                             $storehash{'internal.adhocpriv.'.$role} = $newpriv;
 8186:                         }
 8187:                     }
 8188:                 }
 8189:             }
 8190:         }
 8191:         if (@incrs) {
 8192:             $storehash{'internal.adhocaccess'} = join(',',@incrs);
 8193:         } elsif (@todelete) {
 8194:             push(@todelete,'internal.adhocaccess');
 8195:         }
 8196:         if (keys(%changed)) {
 8197:             my ($putres,$delres);
 8198:             if (keys(%storehash)) {
 8199:                 $putres = &Apache::lonnet::put('environment',\%storehash,$cdom,$cnum);
 8200:                 my %newenvhash;
 8201:                 foreach my $key (keys(%storehash)) {
 8202:                     $newenvhash{'course.'.$env{'request.course.id'}.'.'.$key} = $storehash{$key};
 8203:                 }
 8204:                 &Apache::lonnet::appenv(\%newenvhash);
 8205:             }
 8206:             if (@todelete) {
 8207:                 $delres = &Apache::lonnet::del('environment',\@todelete,$cdom,$cnum);
 8208:                 foreach my $key (@todelete) {
 8209:                     &Apache::lonnet::delenv('course.'.$env{'request.course.id'}.'.'.$key);
 8210:                 }
 8211:             }
 8212:             if (($putres eq 'ok') || ($delres eq 'ok')) {
 8213:                 my %domconfig = &Apache::lonnet::get_dom('configuration',['helpsettings'],$cdom);
 8214:                 my (%domcurrent,%ordered,%description,%domusage);
 8215:                 if (ref($domconfig{'helpsettings'}) eq 'HASH') {
 8216:                     if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
 8217:                         %domcurrent = %{$domconfig{'helpsettings'}{'adhoc'}};
 8218:                     }
 8219:                 }
 8220:                 my $count = 0;
 8221:                 foreach my $role (sort(keys(%customroles))) {
 8222:                     my ($order,$desc);
 8223:                     if (ref($domcurrent{$role}) eq 'HASH') {
 8224:                         $order = $domcurrent{$role}{'order'};
 8225:                         $desc = $domcurrent{$role}{'desc'};
 8226:                     }
 8227:                     if ($order eq '') {
 8228:                         $order = $count;
 8229:                     }
 8230:                     $ordered{$order} = $role;
 8231:                     if ($desc ne '') {
 8232:                         $description{$role} = $desc;
 8233:                     } else {
 8234:                         $description{$role}= $role;
 8235:                     }
 8236:                     $count++;
 8237:                 }
 8238:                 my @roles_by_num = ();
 8239:                 foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 8240:                     push(@roles_by_num,$ordered{$item});
 8241:                 }
 8242:                 %domusage = &domain_adhoc_access(\%changed,\%domcurrent,\@accesstypes,$usertypes,$othertitle);
 8243:                 $r->print(&mt('Helpdesk access settings have been changed as follows').'<br />');
 8244:                 $r->print('<ul>');
 8245:                 foreach my $role (@roles_by_num) {
 8246:                     next unless (ref($changed{$role}) eq 'HASH');
 8247:                     $r->print('<li>'.&mt('Ad hoc role').': <b>'.$description{$role}.'</b>'.
 8248:                               '<ul>');
 8249:                     if ($changed{$role}{'access'} || $changed{$role}{'status'} || $changed{$role}{'inc'} || $changed{$role}{'exc'}) {
 8250:                         $r->print('<li>');
 8251:                         if ($env{'form.'.$role.'_incrs'}) {
 8252:                             if ($newsettings{$role}{'access'} eq 'all') {
 8253:                                 $r->print(&mt('All helpdesk staff can access '.lc($crstype).' with this role.'));
 8254:                             } elsif ($newsettings{$role}{'access'} eq 'dh') {
 8255:                                 $r->print(&mt('Helpdesk staff can use this role if they have an active [_1] role',
 8256:                                               &Apache::lonnet::plaintext('dh')));
 8257:                             } elsif ($newsettings{$role}{'access'} eq 'da') {
 8258:                                 $r->print(&mt('Helpdesk staff can use this role if they have an active [_1] role',
 8259:                                               &Apache::lonnet::plaintext('da')));
 8260:                             } elsif ($newsettings{$role}{'access'} eq 'none') {
 8261:                                 $r->print(&mt('No helpdesk staff can access '.lc($crstype).' with this role.'));
 8262:                             } elsif ($newsettings{$role}{'access'} eq 'status') {
 8263:                                 if ($newsettings{$role}{'status'}) {
 8264:                                     my ($access,$rest) = split(/=/,$storehash{'internal.adhoc.'.$role});
 8265:                                     if (split(/,/,$rest) > 1) {
 8266:                                         $r->print(&mt('Helpdesk staff can use this role if their institutional type is one of: [_1].',
 8267:                                                       $newsettings{$role}{'status'}));
 8268:                                     } else {
 8269:                                         $r->print(&mt('Helpdesk staff can use this role if their institutional type is: [_1].',
 8270:                                                       $newsettings{$role}{'status'}));
 8271:                                     }
 8272:                                 } else {
 8273:                                     $r->print(&mt('No helpdesk staff can access '.lc($crstype).' with this role.'));
 8274:                                 }
 8275:                             } elsif ($newsettings{$role}{'access'} eq 'exc') {
 8276:                                 if ($newsettings{$role}{'exc'}) {
 8277:                                     $r->print(&mt('Helpdesk staff who can use this role are as follows:').' '.$newsettings{$role}{'exc'}.'.');
 8278:                                 } else {
 8279:                                     $r->print(&mt('No helpdesk staff can access '.lc($crstype).' with this role.'));
 8280:                                 }
 8281:                             } elsif ($newsettings{$role}{'access'} eq 'inc') {
 8282:                                 if ($newsettings{$role}{'inc'}) {
 8283:                                     $r->print(&mt('All helpdesk staff may use this role except the following:').' '.$newsettings{$role}{'inc'}.'.');
 8284:                                 } else {
 8285:                                     $r->print(&mt('All helpdesk staff may use this role.'));
 8286:                                 }
 8287:                             }
 8288:                         } else {
 8289:                             $r->print(&mt('Default access set in the domain now applies.').'<br />'.
 8290:                                       '<span class="LC_cusr_emph">'.$domusage{$role}.'</span>');
 8291:                         }
 8292:                         $r->print('</li>');
 8293:                     }
 8294:                     unless ($newsettings{$role}{'access'} eq 'none') {
 8295:                         if ($changed{$role}{'off'}) {
 8296:                             if ($newsettings{$role}{'off'}) {
 8297:                                 $r->print('<li>'.&mt('Privileges which are available by default for this ad hoc role, but are disabled for this specific '.lc($crstype).':').
 8298:                                           '<ul><li>'.$newsettings{$role}{'off'}.'</li></ul></li>');
 8299:                             } else {
 8300:                                 $r->print('<li>'.&mt('All privileges available by default for this ad hoc role are enabled.').'</li>');
 8301:                             }
 8302:                         }
 8303:                         if ($changed{$role}{'on'}) {
 8304:                             if ($newsettings{$role}{'on'}) {
 8305:                                 $r->print('<li>'.&mt('Privileges which are not available by default for this ad hoc role, but are enabled for this specific '.lc($crstype).':').
 8306:                                           '<ul><li>'.$newsettings{$role}{'on'}.'</li></ul></li>');
 8307:                             } else {
 8308:                                 $r->print('<li>'.&mt('None of the privileges unavailable by default for this ad hoc role are enabled.').'</li>');
 8309:                             }
 8310:                         }
 8311:                     }
 8312:                     $r->print('</ul></li>');
 8313:                 }
 8314:                 $r->print('</ul>');
 8315:             }
 8316:         } else {
 8317:             $r->print(&mt('No changes made to helpdesk access settings.'));
 8318:         }
 8319:     }
 8320:     return;
 8321: }
 8322: 
 8323: #-------------------------------------------------- functions for &phase_two
 8324: sub user_search_result {
 8325:     my ($context,$srch) = @_;
 8326:     my %allhomes;
 8327:     my %inst_matches;
 8328:     my %srch_results;
 8329:     my ($response,$currstate,$forcenewuser,$dirsrchres);
 8330:     $srch->{'srchterm'} =~ s/\s+/ /g;
 8331:     if ($srch->{'srchby'} !~ /^(uname|lastname|lastfirst)$/) {
 8332:         $response = &mt('Invalid search.');
 8333:     }
 8334:     if ($srch->{'srchin'} !~ /^(crs|dom|alc|instd)$/) {
 8335:         $response = &mt('Invalid search.');
 8336:     }
 8337:     if ($srch->{'srchtype'} !~ /^(exact|contains|begins)$/) {
 8338:         $response = &mt('Invalid search.');
 8339:     }
 8340:     if ($srch->{'srchterm'} eq '') {
 8341:         $response = &mt('You must enter a search term.');
 8342:     }
 8343:     if ($srch->{'srchterm'} =~ /^\s+$/) {
 8344:         $response = &mt('Your search term must contain more than just spaces.');
 8345:     }
 8346:     if (($srch->{'srchin'} eq 'dom') || ($srch->{'srchin'} eq 'instd')) {
 8347:         if (($srch->{'srchdomain'} eq '') || 
 8348: 	    ! (&Apache::lonnet::domain($srch->{'srchdomain'}))) {
 8349:             $response = &mt('You must specify a valid domain when searching in a domain or institutional directory.')
 8350:         }
 8351:     }
 8352:     if (($srch->{'srchin'} eq 'dom') || ($srch->{'srchin'} eq 'crs') ||
 8353:         ($srch->{'srchin'} eq 'alc')) {
 8354:         if ($srch->{'srchby'} eq 'uname') {
 8355:             my $unamecheck = $srch->{'srchterm'};
 8356:             if ($srch->{'srchtype'} eq 'contains') {
 8357:                 if ($unamecheck !~ /^\w/) {
 8358:                     $unamecheck = 'a'.$unamecheck; 
 8359:                 }
 8360:             }
 8361:             if ($unamecheck !~ /^$match_username$/) {
 8362:                 $response = &mt('You must specify a valid username. Only the following are allowed: letters numbers - . @');
 8363:             }
 8364:         }
 8365:     }
 8366:     if ($response ne '') {
 8367:         $response = '<span class="LC_warning">'.$response.'</span><br />';
 8368:     }
 8369:     if ($srch->{'srchin'} eq 'instd') {
 8370:         my $instd_chk = &instdirectorysrch_check($srch);
 8371:         if ($instd_chk ne 'ok') {
 8372:             my $domd_chk = &domdirectorysrch_check($srch);
 8373:             $response .= '<span class="LC_warning">'.$instd_chk.'</span><br />';
 8374:             if ($domd_chk eq 'ok') {
 8375:                 $response .= &mt('You may want to search in the LON-CAPA domain instead of in the institutional directory.');
 8376:             }
 8377:             $response .= '<br />';
 8378:         }
 8379:     } else {
 8380:         unless (($context eq 'requestcrs') && ($srch->{'srchtype'} eq 'exact')) {
 8381:             my $domd_chk = &domdirectorysrch_check($srch);
 8382:             if (($domd_chk ne 'ok') && ($env{'form.action'} ne 'accesslogs')) {
 8383:                 my $instd_chk = &instdirectorysrch_check($srch);
 8384:                 $response .= '<span class="LC_warning">'.$domd_chk.'</span><br />';
 8385:                 if ($instd_chk eq 'ok') {
 8386:                     $response .= &mt('You may want to search in the institutional directory instead of in the LON-CAPA domain.');
 8387:                 }
 8388:                 $response .= '<br />';
 8389:             }
 8390:         }
 8391:     }
 8392:     if ($response ne '') {
 8393:         return ($currstate,$response);
 8394:     }
 8395:     if ($srch->{'srchby'} eq 'uname') {
 8396:         if (($srch->{'srchin'} eq 'dom') || ($srch->{'srchin'} eq 'crs')) {
 8397:             if ($env{'form.forcenew'}) {
 8398:                 if ($srch->{'srchdomain'} ne $env{'request.role.domain'}) {
 8399:                     my $uhome=&Apache::lonnet::homeserver($srch->{'srchterm'},$srch->{'srchdomain'});
 8400:                     if ($uhome eq 'no_host') {
 8401:                         my $domdesc = &Apache::lonnet::domain($env{'request.role.domain'},'description');
 8402:                         my $showdom = &display_domain_info($env{'request.role.domain'});
 8403:                         $response = &mt('New users can only be created in the domain to which your current role belongs - [_1].',$showdom);
 8404:                     } else {
 8405:                         $currstate = 'modify';
 8406:                     }
 8407:                 } else {
 8408:                     $currstate = 'modify';
 8409:                 }
 8410:             } else {
 8411:                 if ($srch->{'srchin'} eq 'dom') {
 8412:                     if ($srch->{'srchtype'} eq 'exact') {
 8413:                         my $uhome=&Apache::lonnet::homeserver($srch->{'srchterm'},$srch->{'srchdomain'});
 8414:                         if ($uhome eq 'no_host') {
 8415:                             ($currstate,$response,$forcenewuser) =
 8416:                                 &build_search_response($context,$srch,%srch_results);
 8417:                         } else {
 8418:                             $currstate = 'modify';
 8419:                             if ($env{'form.action'} eq 'accesslogs') {
 8420:                                 $currstate = 'activity';
 8421:                             }
 8422:                             my $uname = $srch->{'srchterm'};
 8423:                             my $udom = $srch->{'srchdomain'};
 8424:                             $srch_results{$uname.':'.$udom} =
 8425:                                 { &Apache::lonnet::get('environment',
 8426:                                                        ['firstname',
 8427:                                                         'lastname',
 8428:                                                         'permanentemail'],
 8429:                                                          $udom,$uname)
 8430:                                 };
 8431:                         }
 8432:                     } else {
 8433:                         %srch_results = &Apache::lonnet::usersearch($srch);
 8434:                         ($currstate,$response,$forcenewuser) =
 8435:                             &build_search_response($context,$srch,%srch_results);
 8436:                     }
 8437:                 } else {
 8438:                     my $courseusers = &get_courseusers();
 8439:                     if ($srch->{'srchtype'} eq 'exact') {
 8440:                         if (exists($courseusers->{$srch->{'srchterm'}.':'.$srch->{'srchdomain'}})) {
 8441:                             $currstate = 'modify';
 8442:                         } else {
 8443:                             ($currstate,$response,$forcenewuser) =
 8444:                                 &build_search_response($context,$srch,%srch_results);
 8445:                         }
 8446:                     } else {
 8447:                         foreach my $user (keys(%$courseusers)) {
 8448:                             my ($cuname,$cudomain) = split(/:/,$user);
 8449:                             if ($cudomain eq $srch->{'srchdomain'}) {
 8450:                                 my $matched = 0;
 8451:                                 if ($srch->{'srchtype'} eq 'begins') {
 8452:                                     if ($cuname =~ /^\Q$srch->{'srchterm'}\E/i) {
 8453:                                         $matched = 1;
 8454:                                     }
 8455:                                 } else {
 8456:                                     if ($cuname =~ /\Q$srch->{'srchterm'}\E/i) {
 8457:                                         $matched = 1;
 8458:                                     }
 8459:                                 }
 8460:                                 if ($matched) {
 8461:                                     $srch_results{$user} = 
 8462: 					{&Apache::lonnet::get('environment',
 8463: 							     ['firstname',
 8464: 							      'lastname',
 8465: 							      'permanentemail'],
 8466: 							      $cudomain,$cuname)};
 8467:                                 }
 8468:                             }
 8469:                         }
 8470:                         ($currstate,$response,$forcenewuser) =
 8471:                             &build_search_response($context,$srch,%srch_results);
 8472:                     }
 8473:                 }
 8474:             }
 8475:         } elsif ($srch->{'srchin'} eq 'alc') {
 8476:             $currstate = 'query';
 8477:         } elsif ($srch->{'srchin'} eq 'instd') {
 8478:             ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query($srch);
 8479:             if ($dirsrchres eq 'ok') {
 8480:                 ($currstate,$response,$forcenewuser) = 
 8481:                     &build_search_response($context,$srch,%srch_results);
 8482:             } else {
 8483:                 my $showdom = &display_domain_info($srch->{'srchdomain'});
 8484:                 $response = '<span class="LC_warning">'.
 8485:                     &mt('Institutional directory search is not available in domain: [_1]',$showdom).
 8486:                     '</span><br />'.
 8487:                     &mt('You may want to search in the LON-CAPA domain instead of in the institutional directory.').
 8488:                     '<br />'; 
 8489:             }
 8490:         }
 8491:     } else {
 8492:         if ($srch->{'srchin'} eq 'dom') {
 8493:             %srch_results = &Apache::lonnet::usersearch($srch);
 8494:             ($currstate,$response,$forcenewuser) = 
 8495:                 &build_search_response($context,$srch,%srch_results); 
 8496:         } elsif ($srch->{'srchin'} eq 'crs') {
 8497:             my $courseusers = &get_courseusers(); 
 8498:             foreach my $user (keys(%$courseusers)) {
 8499:                 my ($uname,$udom) = split(/:/,$user);
 8500:                 my %names = &Apache::loncommon::getnames($uname,$udom);
 8501:                 my %emails = &Apache::loncommon::getemails($uname,$udom);
 8502:                 if ($srch->{'srchby'} eq 'lastname') {
 8503:                     if ((($srch->{'srchtype'} eq 'exact') && 
 8504:                          ($names{'lastname'} eq $srch->{'srchterm'})) || 
 8505:                         (($srch->{'srchtype'} eq 'begins') &&
 8506:                          ($names{'lastname'} =~ /^\Q$srch->{'srchterm'}\E/i)) ||
 8507:                         (($srch->{'srchtype'} eq 'contains') &&
 8508:                          ($names{'lastname'} =~ /\Q$srch->{'srchterm'}\E/i))) {
 8509:                         $srch_results{$user} = {firstname => $names{'firstname'},
 8510:                                             lastname => $names{'lastname'},
 8511:                                             permanentemail => $emails{'permanentemail'},
 8512:                                            };
 8513:                     }
 8514:                 } elsif ($srch->{'srchby'} eq 'lastfirst') {
 8515:                     my ($srchlast,$srchfirst) = split(/,/,$srch->{'srchterm'});
 8516:                     $srchlast =~ s/\s+$//;
 8517:                     $srchfirst =~ s/^\s+//;
 8518:                     if ($srch->{'srchtype'} eq 'exact') {
 8519:                         if (($names{'lastname'} eq $srchlast) &&
 8520:                             ($names{'firstname'} eq $srchfirst)) {
 8521:                             $srch_results{$user} = {firstname => $names{'firstname'},
 8522:                                                 lastname => $names{'lastname'},
 8523:                                                 permanentemail => $emails{'permanentemail'},
 8524: 
 8525:                                            };
 8526:                         }
 8527:                     } elsif ($srch->{'srchtype'} eq 'begins') {
 8528:                         if (($names{'lastname'} =~ /^\Q$srchlast\E/i) &&
 8529:                             ($names{'firstname'} =~ /^\Q$srchfirst\E/i)) {
 8530:                             $srch_results{$user} = {firstname => $names{'firstname'},
 8531:                                                 lastname => $names{'lastname'},
 8532:                                                 permanentemail => $emails{'permanentemail'},
 8533:                                                };
 8534:                         }
 8535:                     } else {
 8536:                         if (($names{'lastname'} =~ /\Q$srchlast\E/i) && 
 8537:                             ($names{'firstname'} =~ /\Q$srchfirst\E/i)) {
 8538:                             $srch_results{$user} = {firstname => $names{'firstname'},
 8539:                                                 lastname => $names{'lastname'},
 8540:                                                 permanentemail => $emails{'permanentemail'},
 8541:                                                };
 8542:                         }
 8543:                     }
 8544:                 }
 8545:             }
 8546:             ($currstate,$response,$forcenewuser) = 
 8547:                 &build_search_response($context,$srch,%srch_results); 
 8548:         } elsif ($srch->{'srchin'} eq 'alc') {
 8549:             $currstate = 'query';
 8550:         } elsif ($srch->{'srchin'} eq 'instd') {
 8551:             ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query($srch); 
 8552:             if ($dirsrchres eq 'ok') {
 8553:                 ($currstate,$response,$forcenewuser) = 
 8554:                     &build_search_response($context,$srch,%srch_results);
 8555:             } else {
 8556:                 my $showdom = &display_domain_info($srch->{'srchdomain'});
 8557:                 $response = '<span class="LC_warning">'.
 8558:                     &mt('Institutional directory search is not available in domain: [_1]',$showdom).
 8559:                     '</span><br />'.
 8560:                     &mt('You may want to search in the LON-CAPA domain instead of in the institutional directory.').
 8561:                     '<br />';
 8562:             }
 8563:         }
 8564:     }
 8565:     return ($currstate,$response,$forcenewuser,\%srch_results);
 8566: }
 8567: 
 8568: sub domdirectorysrch_check {
 8569:     my ($srch) = @_;
 8570:     my $response;
 8571:     my %dom_inst_srch = &Apache::lonnet::get_dom('configuration',
 8572:                                              ['directorysrch'],$srch->{'srchdomain'});
 8573:     my $showdom = &display_domain_info($srch->{'srchdomain'});
 8574:     if (ref($dom_inst_srch{'directorysrch'}) eq 'HASH') {
 8575:         if ($dom_inst_srch{'directorysrch'}{'lcavailable'} eq '0') {
 8576:             return &mt('LON-CAPA directory search is not available in domain: [_1]',$showdom);
 8577:         }
 8578:         if ($dom_inst_srch{'directorysrch'}{'lclocalonly'}) {
 8579:             if ($env{'request.role.domain'} ne $srch->{'srchdomain'}) {
 8580:                 return &mt('LON-CAPA directory search in domain: [_1] is only allowed for users with a current role in the domain.',$showdom);
 8581:             }
 8582:         }
 8583:     }
 8584:     return 'ok';
 8585: }
 8586: 
 8587: sub instdirectorysrch_check {
 8588:     my ($srch) = @_;
 8589:     my $can_search = 0;
 8590:     my $response;
 8591:     my %dom_inst_srch = &Apache::lonnet::get_dom('configuration',
 8592:                                              ['directorysrch'],$srch->{'srchdomain'});
 8593:     my $showdom = &display_domain_info($srch->{'srchdomain'});
 8594:     if (ref($dom_inst_srch{'directorysrch'}) eq 'HASH') {
 8595:         if (!$dom_inst_srch{'directorysrch'}{'available'}) {
 8596:             return &mt('Institutional directory search is not available in domain: [_1]',$showdom); 
 8597:         }
 8598:         if ($dom_inst_srch{'directorysrch'}{'localonly'}) {
 8599:             if ($env{'request.role.domain'} ne $srch->{'srchdomain'}) {
 8600:                 return &mt('Institutional directory search in domain: [_1] is only allowed for users with a current role in the domain.',$showdom); 
 8601:             }
 8602:             my @usertypes = split(/:/,$env{'environment.inststatus'});
 8603:             if (!@usertypes) {
 8604:                 push(@usertypes,'default');
 8605:             }
 8606:             if (ref($dom_inst_srch{'directorysrch'}{'cansearch'}) eq 'ARRAY') {
 8607:                 foreach my $type (@usertypes) {
 8608:                     if (grep(/^\Q$type\E$/,@{$dom_inst_srch{'directorysrch'}{'cansearch'}})) {
 8609:                         $can_search = 1;
 8610:                         last;
 8611:                     }
 8612:                 }
 8613:             }
 8614:             if (!$can_search) {
 8615:                 my ($insttypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($srch->{'srchdomain'});
 8616:                 my @longtypes; 
 8617:                 foreach my $item (@usertypes) {
 8618:                     if (defined($insttypes->{$item})) { 
 8619:                         push (@longtypes,$insttypes->{$item});
 8620:                     } elsif ($item eq 'default') {
 8621:                         push (@longtypes,&mt('other')); 
 8622:                     }
 8623:                 }
 8624:                 my $insttype_str = join(', ',@longtypes); 
 8625:                 return &mt('Institutional directory search in domain: [_1] is not available to your user type: ',$showdom).$insttype_str;
 8626:             }
 8627:         } else {
 8628:             $can_search = 1;
 8629:         }
 8630:     } else {
 8631:         return &mt('Institutional directory search has not been configured for domain: [_1]',$showdom);
 8632:     }
 8633:     my %longtext = &Apache::lonlocal::texthash (
 8634:                        uname     => 'username',
 8635:                        lastfirst => 'last name, first name',
 8636:                        lastname  => 'last name',
 8637:                        contains  => 'contains',
 8638:                        exact     => 'as exact match to',
 8639:                        begins    => 'begins with',
 8640:                    );
 8641:     if ($can_search) {
 8642:         if (ref($dom_inst_srch{'directorysrch'}{'searchby'}) eq 'ARRAY') {
 8643:             if (!grep(/^\Q$srch->{'srchby'}\E$/,@{$dom_inst_srch{'directorysrch'}{'searchby'}})) {
 8644:                 return &mt('Institutional directory search in domain: [_1] is not available for searching by "[_2]"',$showdom,$longtext{$srch->{'srchby'}});
 8645:             }
 8646:         } else {
 8647:             return &mt('Institutional directory search in domain: [_1] is not available.', $showdom);
 8648:         }
 8649:     }
 8650:     if ($can_search) {
 8651:         if (ref($dom_inst_srch{'directorysrch'}{'searchtypes'}) eq 'ARRAY') {
 8652:             if (grep(/^\Q$srch->{'srchtype'}\E/,@{$dom_inst_srch{'directorysrch'}{'searchtypes'}})) {
 8653:                 return 'ok';
 8654:             } else {
 8655:                 return &mt('Institutional directory search in domain [_1] is not available for the requested search type: "[_2]"',$showdom,$longtext{$srch->{'srchtype'}});
 8656:             }
 8657:         } else {
 8658:             if ((($dom_inst_srch{'directorysrch'}{'searchtypes'} eq 'specify') &&
 8659:                  ($srch->{'srchtype'} eq 'exact' || $srch->{'srchtype'} eq 'contains')) ||
 8660:                 ($dom_inst_srch{'directorysrch'}{'searchtypes'} eq $srch->{'srchtype'})) {
 8661:                 return 'ok';
 8662:             } else {
 8663:                 return &mt('Institutional directory search in domain [_1] is not available for the requested search type: "[_2]"',$showdom,$longtext{$srch->{'srchtype'}});
 8664:             }
 8665:         }
 8666:     }
 8667: }
 8668: 
 8669: sub get_courseusers {
 8670:     my %advhash;
 8671:     my $classlist = &Apache::loncoursedata::get_classlist();
 8672:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles();
 8673:     foreach my $role (sort(keys(%coursepersonnel))) {
 8674:         foreach my $user (split(/\,/,$coursepersonnel{$role})) {
 8675: 	    if (!exists($classlist->{$user})) {
 8676: 		$classlist->{$user} = [];
 8677: 	    }
 8678:         }
 8679:     }
 8680:     return $classlist;
 8681: }
 8682: 
 8683: sub build_search_response {
 8684:     my ($context,$srch,%srch_results) = @_;
 8685:     my ($currstate,$response,$forcenewuser);
 8686:     my %names = (
 8687:           'uname'     => 'username',
 8688:           'lastname'  => 'last name',
 8689:           'lastfirst' => 'last name, first name',
 8690:           'crs'       => 'this course',
 8691:           'dom'       => 'LON-CAPA domain',
 8692:           'instd'     => 'the institutional directory for domain',
 8693:     );
 8694: 
 8695:     my %single = (
 8696:                    begins   => 'A match',
 8697:                    contains => 'A match',
 8698:                    exact    => 'An exact match',
 8699:                  );
 8700:     my %nomatch = (
 8701:                    begins   => 'No match',
 8702:                    contains => 'No match',
 8703:                    exact    => 'No exact match',
 8704:                   );
 8705:     if (keys(%srch_results) > 1) {
 8706:         $currstate = 'select';
 8707:     } else {
 8708:         if (keys(%srch_results) == 1) {
 8709:             if ($env{'form.action'} eq 'accesslogs') {
 8710:                 $currstate = 'activity';
 8711:             } else {
 8712:                 $currstate = 'modify';
 8713:             }
 8714:             $response = &mt("$single{$srch->{'srchtype'}} was found for the $names{$srch->{'srchby'}} ([_1]) in $names{$srch->{'srchin'}}.",$srch->{'srchterm'});
 8715:             if ($srch->{'srchin'} eq 'dom' || $srch->{'srchin'} eq 'instd') {
 8716:                 $response .= ': '.&display_domain_info($srch->{'srchdomain'});
 8717:             }
 8718:         } else { # Search has nothing found. Prepare message to user.
 8719:             $response = '<span class="LC_warning">';
 8720:             if ($srch->{'srchin'} eq 'dom' || $srch->{'srchin'} eq 'instd') {
 8721:                 $response .= &mt("$nomatch{$srch->{'srchtype'}} found for the $names{$srch->{'srchby'}} [_1] in $names{$srch->{'srchin'}}: [_2]",
 8722:                                  '<b>'.$srch->{'srchterm'}.'</b>',
 8723:                                  &display_domain_info($srch->{'srchdomain'}));
 8724:             } else {
 8725:                 $response .= &mt("$nomatch{$srch->{'srchtype'}} found for the $names{$srch->{'srchby'}} [_1] in $names{$srch->{'srchin'}}.",
 8726:                                  '<b>'.$srch->{'srchterm'}.'</b>');
 8727:             }
 8728:             $response .= '</span>';
 8729: 
 8730:             if ($srch->{'srchin'} ne 'alc') {
 8731:                 $forcenewuser = 1;
 8732:                 my $cansrchinst = 0; 
 8733:                 if (($srch->{'srchdomain'}) && ($env{'form.action'} ne 'accesslogs')) {
 8734:                     my %domconfig = &Apache::lonnet::get_dom('configuration',['directorysrch'],$srch->{'srchdomain'});
 8735:                     if (ref($domconfig{'directorysrch'}) eq 'HASH') {
 8736:                         if ($domconfig{'directorysrch'}{'available'}) {
 8737:                             $cansrchinst = 1;
 8738:                         } 
 8739:                     }
 8740:                 }
 8741:                 if ((($srch->{'srchby'} eq 'lastfirst') || 
 8742:                      ($srch->{'srchby'} eq 'lastname')) &&
 8743:                     ($srch->{'srchin'} eq 'dom')) {
 8744:                     if ($cansrchinst) {
 8745:                         $response .= '<br />'.&mt('You may want to broaden your search to a search of the institutional directory for the domain.');
 8746:                     }
 8747:                 }
 8748:                 if ($srch->{'srchin'} eq 'crs') {
 8749:                     $response .= '<br />'.&mt('You may want to broaden your search to the selected LON-CAPA domain.');
 8750:                 }
 8751:             }
 8752:             my $createdom = $env{'request.role.domain'};
 8753:             if ($context eq 'requestcrs') {
 8754:                 if ($env{'form.coursedom'} ne '') {
 8755:                     $createdom = $env{'form.coursedom'};
 8756:                 }
 8757:             }
 8758:             unless (($env{'form.action'} eq 'accesslogs') || (($srch->{'srchby'} eq 'uname') && ($srch->{'srchin'} eq 'dom') &&
 8759:                     ($srch->{'srchtype'} eq 'exact') && ($srch->{'srchdomain'} eq $createdom))) {
 8760:                 my $cancreate =
 8761:                     &Apache::lonuserutils::can_create_user($createdom,$context);
 8762:                 my $targetdom = '<span class="LC_cusr_emph">'.$createdom.'</span>';
 8763:                 if ($cancreate) {
 8764:                     my $showdom = &display_domain_info($createdom); 
 8765:                     $response .= '<br /><br />'
 8766:                                 .'<b>'.&mt('To add a new user:').'</b>'
 8767:                                 .'<br />';
 8768:                     if ($context eq 'requestcrs') {
 8769:                         $response .= &mt("(You can only define new users in the new course's domain - [_1])",$targetdom);
 8770:                     } else {
 8771:                         $response .= &mt("(You can only create new users in your current role's domain - [_1])",$targetdom);
 8772:                     }
 8773:                     $response .='<ul><li>'
 8774:                                 .&mt("Set 'Domain/institution to search' to: [_1]",'<span class="LC_cusr_emph">'.$showdom.'</span>')
 8775:                                 .'</li><li>'
 8776:                                 .&mt("Set 'Search criteria' to: [_1]username is ..... in selected LON-CAPA domain[_2]",'<span class="LC_cusr_emph">','</span>')
 8777:                                 .'</li><li>'
 8778:                                 .&mt('Provide the proposed username')
 8779:                                 .'</li><li>'
 8780:                                 .&mt("Click 'Search'")
 8781:                                 .'</li></ul><br />';
 8782:                 } else {
 8783:                     unless (($context eq 'domain') && ($env{'form.action'} eq 'singleuser')) {
 8784:                         my $helplink = ' href="javascript:helpMenu('."'display'".')"';
 8785:                         $response .= '<br /><br />';
 8786:                         if ($context eq 'requestcrs') {
 8787:                             $response .= &mt("You are not authorized to define new users in the new course's domain - [_1].",$targetdom);
 8788:                         } else {
 8789:                             $response .= &mt("You are not authorized to create new users in your current role's domain - [_1].",$targetdom);
 8790:                         }
 8791:                         $response .= '<br />'
 8792:                                      .&mt('Please contact the [_1]helpdesk[_2] if you need to create a new user.'
 8793:                                         ,' <a'.$helplink.'>'
 8794:                                         ,'</a>')
 8795:                                      .'<br />';
 8796:                     }
 8797:                 }
 8798:             }
 8799:         }
 8800:     }
 8801:     return ($currstate,$response,$forcenewuser);
 8802: }
 8803: 
 8804: sub display_domain_info {
 8805:     my ($dom) = @_;
 8806:     my $output = $dom;
 8807:     if ($dom ne '') { 
 8808:         my $domdesc = &Apache::lonnet::domain($dom,'description');
 8809:         if ($domdesc ne '') {
 8810:             $output .= ' <span class="LC_cusr_emph">('.$domdesc.')</span>';
 8811:         }
 8812:     }
 8813:     return $output;
 8814: }
 8815: 
 8816: sub crumb_utilities {
 8817:     my %elements = (
 8818:        crtuser => {
 8819:            srchterm => 'text',
 8820:            srchin => 'selectbox',
 8821:            srchby => 'selectbox',
 8822:            srchtype => 'selectbox',
 8823:            srchdomain => 'selectbox',
 8824:        },
 8825:        crtusername => {
 8826:            srchterm => 'text',
 8827:            srchdomain => 'selectbox',
 8828:        },
 8829:        docustom => {
 8830:            rolename => 'selectbox',
 8831:            newrolename => 'textbox',
 8832:        },
 8833:        studentform => {
 8834:            srchterm => 'text',
 8835:            srchin => 'selectbox',
 8836:            srchby => 'selectbox',
 8837:            srchtype => 'selectbox',
 8838:            srchdomain => 'selectbox',
 8839:        },
 8840:     );
 8841: 
 8842:     my $jsback .= qq|
 8843: function backPage(formname,prevphase,prevstate) {
 8844:     if (typeof prevphase == 'undefined') {
 8845:         formname.phase.value = '';
 8846:     }
 8847:     else {  
 8848:         formname.phase.value = prevphase;
 8849:     }
 8850:     if (typeof prevstate == 'undefined') {
 8851:         formname.currstate.value = '';
 8852:     }
 8853:     else {
 8854:         formname.currstate.value = prevstate;
 8855:     }
 8856:     formname.submit();
 8857: }
 8858: |;
 8859:     return ($jsback,\%elements);
 8860: }
 8861: 
 8862: sub course_level_table {
 8863:     my ($inccourses,$showcredits,$defaultcredits) = @_;
 8864:     return unless (ref($inccourses) eq 'HASH');
 8865:     my $table = '';
 8866: # Custom Roles?
 8867: 
 8868:     my %customroles=&Apache::lonuserutils::my_custom_roles();
 8869:     my %lt=&Apache::lonlocal::texthash(
 8870:             'exs'  => "Existing sections",
 8871:             'new'  => "Define new section",
 8872:             'ssd'  => "Set Start Date",
 8873:             'sed'  => "Set End Date",
 8874:             'crl'  => "Course Level",
 8875:             'act'  => "Activate",
 8876:             'rol'  => "Role",
 8877:             'ext'  => "Extent",
 8878:             'grs'  => "Section",
 8879:             'crd'  => "Credits",
 8880:             'sta'  => "Start",
 8881:             'end'  => "End"
 8882:     );
 8883: 
 8884:     foreach my $protectedcourse (sort(keys(%{$inccourses}))) {
 8885: 	my $thiscourse=$protectedcourse;
 8886: 	$thiscourse=~s:_:/:g;
 8887: 	my %coursedata=&Apache::lonnet::coursedescription($thiscourse);
 8888:         my $isowner = &Apache::lonuserutils::is_courseowner($protectedcourse,$coursedata{'internal.courseowner'});
 8889: 	my $area=$coursedata{'description'};
 8890:         my $crstype=$coursedata{'type'};
 8891: 	if (!defined($area)) { $area=&mt('Unavailable course').': '.$protectedcourse; }
 8892: 	my ($domain,$cnum)=split(/\//,$thiscourse);
 8893:         my %sections_count;
 8894:         if (defined($env{'request.course.id'})) {
 8895:             if ($env{'request.course.id'} eq $domain.'_'.$cnum) {
 8896:                 %sections_count = 
 8897: 		    &Apache::loncommon::get_sections($domain,$cnum);
 8898:             }
 8899:         }
 8900:         my @roles = &Apache::lonuserutils::roles_by_context('course','',$crstype);
 8901: 	foreach my $role (@roles) {
 8902:             my $plrole=&Apache::lonnet::plaintext($role,$crstype);
 8903: 	    if ((&Apache::lonnet::allowed('c'.$role,$thiscourse)) ||
 8904:                 ((($role eq 'cc') || ($role eq 'co')) && ($isowner))) {
 8905:                 $table .= &course_level_row($protectedcourse,$role,$area,$domain,
 8906:                                             $plrole,\%sections_count,\%lt,
 8907:                                             $showcredits,$defaultcredits,$crstype);
 8908:             } elsif ($env{'request.course.sec'} ne '') {
 8909:                 if (&Apache::lonnet::allowed('c'.$role,$thiscourse.'/'.
 8910:                                              $env{'request.course.sec'})) {
 8911:                     $table .= &course_level_row($protectedcourse,$role,$area,$domain,
 8912:                                                 $plrole,\%sections_count,\%lt,
 8913:                                                 $showcredits,$defaultcredits,$crstype);
 8914:                 }
 8915:             }
 8916:         }
 8917:         if (&Apache::lonnet::allowed('ccr',$thiscourse)) {
 8918:             foreach my $cust (sort(keys(%customroles))) {
 8919:                 next if ($crstype eq 'Community' && $customroles{$cust} =~ /bre\&S/);
 8920:                 my $role = 'cr_cr_'.$env{'user.domain'}.'_'.$env{'user.name'}.'_'.$cust;
 8921:                 $table .= &course_level_row($protectedcourse,$role,$area,$domain,
 8922:                                             $cust,\%sections_count,\%lt,
 8923:                                             $showcredits,$defaultcredits,$crstype);
 8924:             }
 8925: 	}
 8926:     }
 8927:     return '' if ($table eq ''); # return nothing if there is nothing 
 8928:                                  # in the table
 8929:     my $result;
 8930:     if (!$env{'request.course.id'}) {
 8931:         $result = '<h4>'.$lt{'crl'}.'</h4>'."\n";
 8932:     }
 8933:     $result .= 
 8934: &Apache::loncommon::start_data_table().
 8935: &Apache::loncommon::start_data_table_header_row().
 8936: '<th>'.$lt{'act'}.'</th><th>'.$lt{'rol'}.'</th>'."\n".
 8937: '<th>'.$lt{'ext'}.'</th><th>'."\n";
 8938:     if ($showcredits) {
 8939:         $result .= $lt{'crd'}.'</th>';
 8940:     }
 8941:     $result .=
 8942: '<th>'.$lt{'grs'}.'</th><th>'.$lt{'sta'}.'</th>'."\n".
 8943: '<th>'.$lt{'end'}.'</th>'.
 8944: &Apache::loncommon::end_data_table_header_row().
 8945: $table.
 8946: &Apache::loncommon::end_data_table();
 8947:     return $result;
 8948: }
 8949: 
 8950: sub course_level_row {
 8951:     my ($protectedcourse,$role,$area,$domain,$plrole,$sections_count,
 8952:         $lt,$showcredits,$defaultcredits,$crstype) = @_;
 8953:     my $creditem;
 8954:     my $row = &Apache::loncommon::start_data_table_row().
 8955:               ' <td><input type="checkbox" name="act_'.
 8956:               $protectedcourse.'_'.$role.'" /></td>'."\n".
 8957:               ' <td>'.$plrole.'</td>'."\n".
 8958:               ' <td>'.$area.'<br />Domain: '.$domain.'</td>'."\n";
 8959:     if (($showcredits) && ($role eq 'st') && ($crstype eq 'Course')) {
 8960:         $row .= 
 8961:             '<td><input type="text" name="credits_'.$protectedcourse.'_'.
 8962:             $role.'" size="3" value="'.$defaultcredits.'" /></td>';
 8963:     } else {
 8964:         $row .= '<td>&nbsp;</td>';
 8965:     }
 8966:     if (($role eq 'cc') || ($role eq 'co')) {
 8967:         $row .= '<td>&nbsp;</td>';
 8968:     } elsif ($env{'request.course.sec'} ne '') {
 8969:         $row .= ' <td><input type="hidden" value="'.
 8970:                 $env{'request.course.sec'}.'" '.
 8971:                 'name="sec_'.$protectedcourse.'_'.$role.'" />'.
 8972:                 $env{'request.course.sec'}.'</td>';
 8973:     } else {
 8974:         if (ref($sections_count) eq 'HASH') {
 8975:             my $currsec = 
 8976:                 &Apache::lonuserutils::course_sections($sections_count,
 8977:                                                        $protectedcourse.'_'.$role);
 8978:             $row .= '<td><table class="LC_createuser">'."\n".
 8979:                     '<tr class="LC_section_row">'."\n".
 8980:                     ' <td valign="top">'.$lt->{'exs'}.'<br />'.
 8981:                        $currsec.'</td>'."\n".
 8982:                      ' <td>&nbsp;&nbsp;</td>'."\n".
 8983:                      ' <td valign="top">&nbsp;'.$lt->{'new'}.'<br />'.
 8984:                      '<input type="text" name="newsec_'.$protectedcourse.'_'.$role.
 8985:                      '" value="" />'.
 8986:                      '<input type="hidden" '.
 8987:                      'name="sec_'.$protectedcourse.'_'.$role.'" /></td>'."\n".
 8988:                      '</tr></table></td>'."\n";
 8989:         } else {
 8990:             $row .= '<td><input type="text" size="10" '.
 8991:                     'name="sec_'.$protectedcourse.'_'.$role.'" /></td>'."\n";
 8992:         }
 8993:     }
 8994:     $row .= <<ENDTIMEENTRY;
 8995: <td><input type="hidden" name="start_$protectedcourse\_$role" value="" />
 8996: <a href=
 8997: "javascript:pjump('date_start','Start Date $plrole',document.cu.start_$protectedcourse\_$role.value,'start_$protectedcourse\_$role','cu.pres','dateset')">$lt->{'ssd'}</a></td>
 8998: <td><input type="hidden" name="end_$protectedcourse\_$role" value="" />
 8999: <a href=
 9000: "javascript:pjump('date_end','End Date $plrole',document.cu.end_$protectedcourse\_$role.value,'end_$protectedcourse\_$role','cu.pres','dateset')">$lt->{'sed'}</a></td>
 9001: ENDTIMEENTRY
 9002:     $row .= &Apache::loncommon::end_data_table_row();
 9003:     return $row;
 9004: }
 9005: 
 9006: sub course_level_dc {
 9007:     my ($dcdom,$showcredits) = @_;
 9008:     my %customroles=&Apache::lonuserutils::my_custom_roles();
 9009:     my @roles = &Apache::lonuserutils::roles_by_context('course');
 9010:     my $hiddenitems = '<input type="hidden" name="dcdomain" value="'.$dcdom.'" />'.
 9011:                       '<input type="hidden" name="origdom" value="'.$dcdom.'" />'.
 9012:                       '<input type="hidden" name="dccourse" value="" />';
 9013:     my $courseform=&Apache::loncommon::selectcourse_link
 9014:             ('cu','dccourse','dcdomain','coursedesc',undef,undef,'Select','crstype');
 9015:     my $credit_elem;
 9016:     if ($showcredits) {
 9017:         $credit_elem = 'credits';
 9018:     }
 9019:     my $cb_jscript = &Apache::loncommon::coursebrowser_javascript($dcdom,'currsec','cu','role','Course/Community Browser',$credit_elem);
 9020:     my %lt=&Apache::lonlocal::texthash(
 9021:                     'rol'  => "Role",
 9022:                     'grs'  => "Section",
 9023:                     'exs'  => "Existing sections",
 9024:                     'new'  => "Define new section", 
 9025:                     'sta'  => "Start",
 9026:                     'end'  => "End",
 9027:                     'ssd'  => "Set Start Date",
 9028:                     'sed'  => "Set End Date",
 9029:                     'scc'  => "Course/Community",
 9030:                     'crd'  => "Credits",
 9031:                   );
 9032:     my $header = '<h4>'.&mt('Course/Community Level').'</h4>'.
 9033:                  &Apache::loncommon::start_data_table().
 9034:                  &Apache::loncommon::start_data_table_header_row().
 9035:                  '<th>'.$lt{'scc'}.'</th><th>'.$lt{'rol'}.'</th>'."\n".
 9036:                  '<th>'.$lt{'grs'}.'</th>'."\n";
 9037:     $header .=   '<th>'.$lt{'crd'}.'</th>'."\n" if ($showcredits);
 9038:     $header .=   '<th>'.$lt{'sta'}.'</th><th>'.$lt{'end'}.'</th>'."\n".
 9039:                  &Apache::loncommon::end_data_table_header_row();
 9040:     my $otheritems = &Apache::loncommon::start_data_table_row()."\n".
 9041:                      '<td><br /><span class="LC_nobreak"><input type="text" name="coursedesc" value="" onfocus="this.blur();opencrsbrowser('."'cu','dccourse','dcdomain','coursedesc','','','','crstype'".')" />'.
 9042:                      $courseform.('&nbsp;' x4).'</span></td>'."\n".
 9043:                      '<td valign="top"><br /><select name="role">'."\n";
 9044:     foreach my $role (@roles) {
 9045:         my $plrole=&Apache::lonnet::plaintext($role);
 9046:         $otheritems .= '  <option value="'.$role.'">'.$plrole.'</option>';
 9047:     }
 9048:     if ( keys(%customroles) > 0) {
 9049:         foreach my $cust (sort(keys(%customroles))) {
 9050:             my $custrole='cr_cr_'.$env{'user.domain'}.
 9051:                     '_'.$env{'user.name'}.'_'.$cust;
 9052:             $otheritems .= '  <option value="'.$custrole.'">'.$cust.'</option>';
 9053:         }
 9054:     }
 9055:     $otheritems .= '</select></td><td>'.
 9056:                      '<table border="0" cellspacing="0" cellpadding="0">'.
 9057:                      '<tr><td valign="top"><b>'.$lt{'exs'}.'</b><br /><select name="currsec">'.
 9058:                      ' <option value="">&lt;--'.&mt('Pick course first').'</option></select></td>'.
 9059:                      '<td>&nbsp;&nbsp;</td>'.
 9060:                      '<td valign="top">&nbsp;<b>'.$lt{'new'}.'</b><br />'.
 9061:                      '<input type="text" name="newsec" value="" />'.
 9062:                      '<input type="hidden" name="section" value="" />'.
 9063:                      '<input type="hidden" name="groups" value="" />'.
 9064:                      '<input type="hidden" name="crstype" value="" /></td>'.
 9065:                      '</tr></table></td>'."\n";
 9066:     if ($showcredits) {
 9067:         $otheritems .= '<td><br />'."\n".
 9068:                        '<input type="text" size="3" name="credits" value="" /></td>'."\n";
 9069:     }
 9070:     $otheritems .= <<ENDTIMEENTRY;
 9071: <td><br /><input type="hidden" name="start" value='' />
 9072: <a href=
 9073: "javascript:pjump('date_start','Start Date',document.cu.start.value,'start','cu.pres','dateset')">$lt{'ssd'}</a></td>
 9074: <td><br /><input type="hidden" name="end" value='' />
 9075: <a href=
 9076: "javascript:pjump('date_end','End Date',document.cu.end.value,'end','cu.pres','dateset')">$lt{'sed'}</a></td>
 9077: ENDTIMEENTRY
 9078:     $otheritems .= &Apache::loncommon::end_data_table_row().
 9079:                    &Apache::loncommon::end_data_table()."\n";
 9080:     return $cb_jscript.$header.$hiddenitems.$otheritems;
 9081: }
 9082: 
 9083: sub update_selfenroll_config {
 9084:     my ($r,$cid,$cdom,$cnum,$context,$crstype,$currsettings) = @_;
 9085:     return unless (ref($currsettings) eq 'HASH');
 9086:     my ($row,$lt) = &Apache::lonuserutils::get_selfenroll_titles();
 9087:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
 9088:     my (%changes,%warning);
 9089:     my $curr_types;
 9090:     my %noedit;
 9091:     unless ($context eq 'domain') {
 9092:         %noedit = &get_noedit_fields($cdom,$cnum,$crstype,$row);
 9093:     }
 9094:     if (ref($row) eq 'ARRAY') {
 9095:         foreach my $item (@{$row}) {
 9096:             next if ($noedit{$item});
 9097:             if ($item eq 'enroll_dates') {
 9098:                 my (%currenrolldate,%newenrolldate);
 9099:                 foreach my $type ('start','end') {
 9100:                     $currenrolldate{$type} = $currsettings->{'selfenroll_'.$type.'_date'};
 9101:                     $newenrolldate{$type} = &Apache::lonhtmlcommon::get_date_from_form('selfenroll_'.$type.'_date');
 9102:                     if ($newenrolldate{$type} ne $currenrolldate{$type}) {
 9103:                         $changes{'internal.selfenroll_'.$type.'_date'} = $newenrolldate{$type};
 9104:                     }
 9105:                 }
 9106:             } elsif ($item eq 'access_dates') {
 9107:                 my (%currdate,%newdate);
 9108:                 foreach my $type ('start','end') {
 9109:                     $currdate{$type} = $currsettings->{'selfenroll_'.$type.'_access'};
 9110:                     $newdate{$type} = &Apache::lonhtmlcommon::get_date_from_form('selfenroll_'.$type.'_access');
 9111:                     if ($newdate{$type} ne $currdate{$type}) {
 9112:                         $changes{'internal.selfenroll_'.$type.'_access'} = $newdate{$type};
 9113:                     }
 9114:                 }
 9115:             } elsif ($item eq 'types') {
 9116:                 $curr_types = $currsettings->{'selfenroll_'.$item};
 9117:                 if ($env{'form.selfenroll_all'}) {
 9118:                     if ($curr_types ne '*') {
 9119:                         $changes{'internal.selfenroll_types'} = '*';
 9120:                     } else {
 9121:                         next;
 9122:                     }
 9123:                 } else {
 9124:                     my %currdoms;
 9125:                     my @entries = split(/;/,$curr_types);
 9126:                     my @deletedoms = &Apache::loncommon::get_env_multiple('form.selfenroll_delete');
 9127:                     my @activations = &Apache::loncommon::get_env_multiple('form.selfenroll_activate');
 9128:                     my $newnum = 0;
 9129:                     my @latesttypes;
 9130:                     foreach my $num (@activations) {
 9131:                         my @types = &Apache::loncommon::get_env_multiple('form.selfenroll_types_'.$num);
 9132:                         if (@types > 0) {
 9133:                             @types = sort(@types);
 9134:                             my $typestr = join(',',@types);
 9135:                             my $typedom = $env{'form.selfenroll_dom_'.$num};
 9136:                             $latesttypes[$newnum] = $typedom.':'.$typestr;
 9137:                             $currdoms{$typedom} = 1;
 9138:                             $newnum ++;
 9139:                         }
 9140:                     }
 9141:                     for (my $j=0; $j<$env{'form.selfenroll_types_total'}; $j++) {
 9142:                         if ((!grep(/^$j$/,@deletedoms)) && (!grep(/^$j$/,@activations))) {
 9143:                             my @types = &Apache::loncommon::get_env_multiple('form.selfenroll_types_'.$j);
 9144:                             if (@types > 0) {
 9145:                                 @types = sort(@types);
 9146:                                 my $typestr = join(',',@types);
 9147:                                 my $typedom = $env{'form.selfenroll_dom_'.$j};
 9148:                                 $latesttypes[$newnum] = $typedom.':'.$typestr;
 9149:                                 $currdoms{$typedom} = 1;
 9150:                                 $newnum ++;
 9151:                             }
 9152:                         }
 9153:                     }
 9154:                     if ($env{'form.selfenroll_newdom'} ne '') {
 9155:                         my $typedom = $env{'form.selfenroll_newdom'};
 9156:                         if ((!defined($currdoms{$typedom})) && 
 9157:                             (&Apache::lonnet::domain($typedom) ne '')) {
 9158:                             my $typestr;
 9159:                             my ($othertitle,$usertypes,$types) = 
 9160:                                 &Apache::loncommon::sorted_inst_types($typedom);
 9161:                             my $othervalue = 'any';
 9162:                             if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 9163:                                 if (@{$types} > 0) {
 9164:                                     my @esc_types = map { &escape($_); } @{$types};
 9165:                                     $othervalue = 'other';
 9166:                                     $typestr = join(',',(@esc_types,$othervalue));
 9167:                                 }
 9168:                                 $typestr = $othervalue;
 9169:                             } else {
 9170:                                 $typestr = $othervalue;
 9171:                             } 
 9172:                             $latesttypes[$newnum] = $typedom.':'.$typestr;
 9173:                             $newnum ++ ;
 9174:                         }
 9175:                     }
 9176:                     my $selfenroll_types = join(';',@latesttypes);
 9177:                     if ($selfenroll_types ne $curr_types) {
 9178:                         $changes{'internal.selfenroll_types'} = $selfenroll_types;
 9179:                     }
 9180:                 }
 9181:             } elsif ($item eq 'limit') {
 9182:                 my $newlimit = $env{'form.selfenroll_limit'};
 9183:                 my $newcap = $env{'form.selfenroll_cap'};
 9184:                 $newcap =~s/\s+//g;
 9185:                 my $currlimit =  $currsettings->{'selfenroll_limit'};
 9186:                 $currlimit = 'none' if ($currlimit eq '');
 9187:                 my $currcap = $currsettings->{'selfenroll_cap'};
 9188:                 if ($newlimit ne $currlimit) {
 9189:                     if ($newlimit ne 'none') {
 9190:                         if ($newcap =~ /^\d+$/) {
 9191:                             if ($newcap ne $currcap) {
 9192:                                 $changes{'internal.selfenroll_cap'} = $newcap;
 9193:                             }
 9194:                             $changes{'internal.selfenroll_limit'} = $newlimit;
 9195:                         } else {
 9196:                             $warning{$item} = &mt('Maximum enrollment setting unchanged.').'<br />'.
 9197:                                 &mt('The value provided was invalid - it must be a positive integer if enrollment is being limited.'); 
 9198:                         }
 9199:                     } elsif ($currcap ne '') {
 9200:                         $changes{'internal.selfenroll_cap'} = '';
 9201:                         $changes{'internal.selfenroll_limit'} = $newlimit; 
 9202:                     }
 9203:                 } elsif ($currlimit ne 'none') {
 9204:                     if ($newcap =~ /^\d+$/) {
 9205:                         if ($newcap ne $currcap) {
 9206:                             $changes{'internal.selfenroll_cap'} = $newcap;
 9207:                         }
 9208:                     } else {
 9209:                         $warning{$item} = &mt('Maximum enrollment setting unchanged.').'<br />'.
 9210:                             &mt('The value provided was invalid - it must be a positive integer if enrollment is being limited.');
 9211:                     }
 9212:                 }
 9213:             } elsif ($item eq 'approval') {
 9214:                 my (@currnotified,@newnotified);
 9215:                 my $currapproval = $currsettings->{'selfenroll_approval'};
 9216:                 my $currnotifylist = $currsettings->{'selfenroll_notifylist'};
 9217:                 if ($currnotifylist ne '') {
 9218:                     @currnotified = split(/,/,$currnotifylist);
 9219:                     @currnotified = sort(@currnotified);
 9220:                 }
 9221:                 my $newapproval = $env{'form.selfenroll_approval'};
 9222:                 @newnotified = &Apache::loncommon::get_env_multiple('form.selfenroll_notify');
 9223:                 @newnotified = sort(@newnotified);
 9224:                 if ($newapproval ne $currapproval) {
 9225:                     $changes{'internal.selfenroll_approval'} = $newapproval;
 9226:                     if (!$newapproval) {
 9227:                         if ($currnotifylist ne '') {
 9228:                             $changes{'internal.selfenroll_notifylist'} = '';
 9229:                         }
 9230:                     } else {
 9231:                         my @differences =  
 9232:                             &Apache::loncommon::compare_arrays(\@currnotified,\@newnotified);
 9233:                         if (@differences > 0) {
 9234:                             if (@newnotified > 0) {
 9235:                                 $changes{'internal.selfenroll_notifylist'} = join(',',@newnotified);
 9236:                             } else {
 9237:                                 $changes{'internal.selfenroll_notifylist'} = join(',',@newnotified);
 9238:                             }
 9239:                         }
 9240:                     }
 9241:                 } else {
 9242:                     my @differences = &Apache::loncommon::compare_arrays(\@currnotified,\@newnotified);
 9243:                     if (@differences > 0) {
 9244:                         if (@newnotified > 0) {
 9245:                             $changes{'internal.selfenroll_notifylist'} = join(',',@newnotified);
 9246:                         } else {
 9247:                             $changes{'internal.selfenroll_notifylist'} = '';
 9248:                         }
 9249:                     }
 9250:                 }
 9251:             } else {
 9252:                 my $curr_val = $currsettings->{'selfenroll_'.$item};
 9253:                 my $newval = $env{'form.selfenroll_'.$item};
 9254:                 if ($item eq 'section') {
 9255:                     $newval = $env{'form.sections'};
 9256:                     if (defined($curr_groups{$newval})) {
 9257:                         $newval = $curr_val;
 9258:                         $warning{$item} = &mt('Section for self-enrolled users unchanged as the proposed section is a group').'<br />'.
 9259:                                           &mt('Group names and section names must be distinct');
 9260:                     } elsif ($newval eq 'all') {
 9261:                         $newval = $curr_val;
 9262:                         $warning{$item} = &mt('Section for self-enrolled users unchanged, as "all" is a reserved section name.');
 9263:                     }
 9264:                     if ($newval eq '') {
 9265:                         $newval = 'none';
 9266:                     }
 9267:                 }
 9268:                 if ($newval ne $curr_val) {
 9269:                     $changes{'internal.selfenroll_'.$item} = $newval;
 9270:                 }
 9271:             }
 9272:         }
 9273:         if (keys(%warning) > 0) {
 9274:             foreach my $item (@{$row}) {
 9275:                 if (exists($warning{$item})) {
 9276:                     $r->print($warning{$item}.'<br />');
 9277:                 }
 9278:             } 
 9279:         }
 9280:         if (keys(%changes) > 0) {
 9281:             my $putresult = &Apache::lonnet::put('environment',\%changes,$cdom,$cnum);
 9282:             if ($putresult eq 'ok') {
 9283:                 if ((exists($changes{'internal.selfenroll_types'})) ||
 9284:                     (exists($changes{'internal.selfenroll_start_date'}))  ||
 9285:                     (exists($changes{'internal.selfenroll_end_date'}))) {
 9286:                     my %crsinfo = &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',
 9287:                                                                 $cnum,undef,undef,'Course');
 9288:                     my $chome = &Apache::lonnet::homeserver($cnum,$cdom);
 9289:                     if (ref($crsinfo{$cid}) eq 'HASH') {
 9290:                         foreach my $item ('selfenroll_types','selfenroll_start_date','selfenroll_end_date') {
 9291:                             if (exists($changes{'internal.'.$item})) {
 9292:                                 $crsinfo{$cid}{$item} = $changes{'internal.'.$item};
 9293:                             }
 9294:                         }
 9295:                         my $crsputresult =
 9296:                             &Apache::lonnet::courseidput($cdom,\%crsinfo,
 9297:                                                          $chome,'notime');
 9298:                     }
 9299:                 }
 9300:                 $r->print(&mt('The following changes were made to self-enrollment settings:').'<ul>');
 9301:                 foreach my $item (@{$row}) {
 9302:                     my $title = $item;
 9303:                     if (ref($lt) eq 'HASH') {
 9304:                         $title = $lt->{$item};
 9305:                     }
 9306:                     if ($item eq 'enroll_dates') {
 9307:                         foreach my $type ('start','end') {
 9308:                             if (exists($changes{'internal.selfenroll_'.$type.'_date'})) {
 9309:                                 my $newdate = &Apache::lonlocal::locallocaltime($changes{'internal.selfenroll_'.$type.'_date'});
 9310:                                 $r->print('<li>'.&mt('[_1]: "[_2]" set to "[_3]".',
 9311:                                           $title,$type,$newdate).'</li>');
 9312:                             }
 9313:                         }
 9314:                     } elsif ($item eq 'access_dates') {
 9315:                         foreach my $type ('start','end') {
 9316:                             if (exists($changes{'internal.selfenroll_'.$type.'_access'})) {
 9317:                                 my $newdate = &Apache::lonlocal::locallocaltime($changes{'internal.selfenroll_'.$type.'_access'});
 9318:                                 $r->print('<li>'.&mt('[_1]: "[_2]" set to "[_3]".',
 9319:                                           $title,$type,$newdate).'</li>');
 9320:                             }
 9321:                         }
 9322:                     } elsif ($item eq 'limit') {
 9323:                         if ((exists($changes{'internal.selfenroll_limit'})) ||
 9324:                             (exists($changes{'internal.selfenroll_cap'}))) {
 9325:                             my ($newval,$newcap);
 9326:                             if ($changes{'internal.selfenroll_cap'} ne '') {
 9327:                                 $newcap = $changes{'internal.selfenroll_cap'}
 9328:                             } else {
 9329:                                 $newcap = $currsettings->{'selfenroll_cap'};
 9330:                             }
 9331:                             if ($changes{'internal.selfenroll_limit'} eq 'none') {
 9332:                                 $newval = &mt('No limit');
 9333:                             } elsif ($changes{'internal.selfenroll_limit'} eq 
 9334:                                      'allstudents') {
 9335:                                 $newval = &mt('New self-enrollment no longer allowed when total (all students) reaches [_1].',$newcap);
 9336:                             } elsif ($changes{'internal.selfenroll_limit'} eq 'selfenrolled') {
 9337:                                 $newval = &mt('New self-enrollment no longer allowed when total number of self-enrolled students reaches [_1].',$newcap);
 9338:                             } else {
 9339:                                 my $currlimit =  $currsettings->{'selfenroll_limit'};
 9340:                                 if ($currlimit eq 'allstudents') {
 9341:                                     $newval = &mt('New self-enrollment no longer allowed when total (all students) reaches [_1].',$newcap);
 9342:                                 } elsif ($changes{'internal.selfenroll_limit'} eq 'selfenrolled') {
 9343:                                     $newval =  &mt('New self-enrollment no longer allowed when total number of self-enrolled students reaches [_1].',$newcap);
 9344:                                 }
 9345:                             }
 9346:                             $r->print('<li>'.&mt('"[_1]" set to "[_2]".',$title,$newval).'</li>'."\n");
 9347:                         }
 9348:                     } elsif ($item eq 'approval') {
 9349:                         if ((exists($changes{'internal.selfenroll_approval'})) ||
 9350:                             (exists($changes{'internal.selfenroll_notifylist'}))) {
 9351:                             my %selfdescs = &Apache::lonuserutils::selfenroll_default_descs();
 9352:                             my ($newval,$newnotify);
 9353:                             if (exists($changes{'internal.selfenroll_notifylist'})) {
 9354:                                 $newnotify = $changes{'internal.selfenroll_notifylist'};
 9355:                             } else {   
 9356:                                 $newnotify = $currsettings->{'selfenroll_notifylist'};
 9357:                             }
 9358:                             if (exists($changes{'internal.selfenroll_approval'})) {
 9359:                                 if ($changes{'internal.selfenroll_approval'} !~ /^[012]$/) {
 9360:                                     $changes{'internal.selfenroll_approval'} = '0';
 9361:                                 }
 9362:                                 $newval = $selfdescs{'approval'}{$changes{'internal.selfenroll_approval'}};
 9363:                             } else {
 9364:                                 my $currapproval = $currsettings->{'selfenroll_approval'}; 
 9365:                                 if ($currapproval !~ /^[012]$/) {
 9366:                                     $currapproval = 0;
 9367:                                 }
 9368:                                 $newval = $selfdescs{'approval'}{$currapproval};
 9369:                             }
 9370:                             $r->print('<li>'.&mt('"[_1]" set to "[_2]".',$title,$newval));
 9371:                             if ($newnotify) {
 9372:                                 $r->print('<br />'.&mt('The following will be notified when an enrollment request needs approval, or has been approved: [_1].',$newnotify));
 9373:                             } else {
 9374:                                 $r->print('<br />'.&mt('No notifications sent when an enrollment request needs approval, or has been approved.'));
 9375:                             }
 9376:                             $r->print('</li>'."\n");
 9377:                         }
 9378:                     } else {
 9379:                         if (exists($changes{'internal.selfenroll_'.$item})) {
 9380:                             my $newval = $changes{'internal.selfenroll_'.$item};
 9381:                             if ($item eq 'types') {
 9382:                                 if ($newval eq '') {
 9383:                                     $newval = &mt('None');
 9384:                                 } elsif ($newval eq '*') {
 9385:                                     $newval = &mt('Any user in any domain');
 9386:                                 }
 9387:                             } elsif ($item eq 'registered') {
 9388:                                 if ($newval eq '1') {
 9389:                                     $newval = &mt('Yes');
 9390:                                 } elsif ($newval eq '0') {
 9391:                                     $newval = &mt('No');
 9392:                                 }
 9393:                             }
 9394:                             $r->print('<li>'.&mt('"[_1]" set to "[_2]".',$title,$newval).'</li>'."\n");
 9395:                         }
 9396:                     }
 9397:                 }
 9398:                 $r->print('</ul>');
 9399:                 if ($env{'course.'.$cid.'.description'} ne '') {
 9400:                     my %newenvhash;
 9401:                     foreach my $key (keys(%changes)) {
 9402:                         $newenvhash{'course.'.$cid.'.'.$key} = $changes{$key};
 9403:                     }
 9404:                     &Apache::lonnet::appenv(\%newenvhash);
 9405:                 }
 9406:             } else {
 9407:                 $r->print(&mt('An error occurred when saving changes to self-enrollment settings in this course.').'<br />'.
 9408:                           &mt('The error was: [_1].',$putresult));
 9409:             }
 9410:         } else {
 9411:             $r->print(&mt('No changes were made to the existing self-enrollment settings in this course.'));
 9412:         }
 9413:     } else {
 9414:         $r->print(&mt('No changes were made to the existing self-enrollment settings in this course.'));
 9415:     }
 9416:     my $visactions = &cat_visibility();
 9417:     my ($cathash,%cattype);
 9418:     my %domconfig = &Apache::lonnet::get_dom('configuration',['coursecategories'],$cdom);
 9419:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 9420:         $cathash = $domconfig{'coursecategories'}{'cats'};
 9421:         $cattype{'auth'} = $domconfig{'coursecategories'}{'auth'};
 9422:         $cattype{'unauth'} = $domconfig{'coursecategories'}{'unauth'};
 9423:     } else {
 9424:         $cathash = {};
 9425:         $cattype{'auth'} = 'std';
 9426:         $cattype{'unauth'} = 'std';
 9427:     }
 9428:     if (($cattype{'auth'} eq 'none') && ($cattype{'unauth'} eq 'none')) {
 9429:         $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
 9430:                   '<br />'.
 9431:                   '<br />'.$visactions->{'take'}.'<ul>'.
 9432:                   '<li>'.$visactions->{'dc_chgconf'}.'</li>'.
 9433:                   '</ul>');
 9434:     } elsif (($cattype{'auth'} !~ /^(std|domonly)$/) && ($cattype{'unauth'} !~ /^(std|domonly)$/)) {
 9435:         if ($currsettings->{'uniquecode'}) {
 9436:             $r->print('<span class="LC_info">'.$visactions->{'vis'}.'</span>');
 9437:         } else {
 9438:             $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
 9439:                   '<br />'.
 9440:                   '<br />'.$visactions->{'take'}.'<ul>'.
 9441:                   '<li>'.$visactions->{'dc_setcode'}.'</li>'.
 9442:                   '</ul><br />');
 9443:         }
 9444:     } else {
 9445:         my ($visible,$cansetvis,$vismsgs) = &visible_in_stdcat($cdom,$cnum,\%domconfig);
 9446:         if (ref($visactions) eq 'HASH') {
 9447:             if (!$visible) {
 9448:                 $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
 9449:                           '<br />');
 9450:                 if (ref($vismsgs) eq 'ARRAY') {
 9451:                     $r->print('<br />'.$visactions->{'take'}.'<ul>');
 9452:                     foreach my $item (@{$vismsgs}) {
 9453:                         $r->print('<li>'.$visactions->{$item}.'</li>');
 9454:                     }
 9455:                     $r->print('</ul>');
 9456:                 }
 9457:                 $r->print($cansetvis);
 9458:             }
 9459:         }
 9460:     } 
 9461:     return;
 9462: }
 9463: 
 9464: #---------------------------------------------- end functions for &phase_two
 9465: 
 9466: #--------------------------------- functions for &phase_two and &phase_three
 9467: 
 9468: #--------------------------end of functions for &phase_two and &phase_three
 9469: 
 9470: 1;
 9471: __END__
 9472: 
 9473: 

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