File:  [LON-CAPA] / loncom / interface / loncreateuser.pm
Revision 1.446: download - view: text, annotated - select for diffs
Fri Aug 11 00:24:53 2017 UTC (6 years, 9 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Trust Settings
  - lonnet::trusted_domains() returns array or array refs, for passing to
    loncommon::select_dom_form() or lonnet::will_trust().

    1: # The LearningOnline Network with CAPA
    2: # Create a user
    3: #
    4: # $Id: loncreateuser.pm,v 1.446 2017/08/11 00:24:53 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 ($trusted,$untrusted);
  890:         if ($context eq 'course') {
  891:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('enroll',$defdom);
  892:         } elsif ($context eq 'author') {
  893:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('othcoau',$defdom);
  894:         } elsif ($context eq 'domain') {
  895:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('domroles',$defdom); 
  896:         }
  897:         my $domform = &Apache::loncommon::select_dom_form($defdom,'srchdomain',undef,undef,undef,$trusted,$untrusted);
  898:         my %lt=&Apache::lonlocal::texthash(
  899:                   'enro' => 'Enroll one student',
  900:                   'enrm' => 'Enroll one member',
  901:                   'admo' => 'Add/modify a single user',
  902:                   'crea' => 'create new user if required',
  903:                   'uskn' => "username is known",
  904:                   'crnu' => 'Create a new user',
  905:                   'usr'  => 'Username',
  906:                   'dom'  => 'in domain',
  907:                   'enrl' => 'Enroll',
  908:                   'cram'  => 'Create/Modify user',
  909:         );
  910:         my $sellink=&Apache::loncommon::selectstudent_link('crtusername','srchterm','srchdomain');
  911:         my ($title,$buttontext,$showresponse);
  912:         if ($env{'form.action'} eq 'singlestudent') {
  913:             if ($crstype eq 'Community') {
  914:                 $title = $lt{'enrm'};
  915:             } else {
  916:                 $title = $lt{'enro'};
  917:             }
  918:             $buttontext = $lt{'enrl'};
  919:         } else {
  920:             $title = $lt{'admo'};
  921:             $buttontext = $lt{'cram'};
  922:         }
  923:         if ($cancreate) {
  924:             $title .= ' <span class="LC_cusr_subheading">('.$lt{'crea'}.')</span>';
  925:         } else {
  926:             $title .= ' <span class="LC_cusr_subheading">('.$lt{'uskn'}.')</span>';
  927:         }
  928:         if ($env{'form.origform'} eq 'crtusername') {
  929:             $showresponse = $responsemsg;
  930:         }
  931:         $output .= <<"ENDDOCUMENT";
  932: <br />
  933: <form action="/adm/createuser" method="post" name="crtusername">
  934: <input type="hidden" name="action" value="$env{'form.action'}" />
  935: <input type="hidden" name="phase" value="createnewuser" />
  936: <input type="hidden" name="srchtype" value="exact" />
  937: <input type="hidden" name="srchby" value="uname" />
  938: <input type="hidden" name="srchin" value="dom" />
  939: <input type="hidden" name="forcenewuser" value="1" />
  940: <input type="hidden" name="origform" value="crtusername" />
  941: <h3>$title</h3>
  942: $showresponse
  943: <table>
  944:  <tr>
  945:   <td>$lt{'usr'}:</td>
  946:   <td><input type="text" size="15" name="srchterm" /></td>
  947:   <td>&nbsp;$lt{'dom'}:</td><td>$domform</td>
  948:   <td>&nbsp;$sellink&nbsp;</td>
  949:   <td>&nbsp;<input name="userrole" type="submit" value="$buttontext" /></td>
  950:  </tr>
  951: </table>
  952: </form>
  953: ENDDOCUMENT
  954:     }
  955:     return $output;
  956: }
  957: 
  958: sub user_modification_js {
  959:     my ($pjump_def,$dc_setcourse_code,$nondc_setsection_code,$groupslist)=@_;
  960:     
  961:     return <<END;
  962: <script type="text/javascript" language="Javascript">
  963: // <![CDATA[
  964: 
  965:     $pjump_def
  966:     $dc_setcourse_code
  967: 
  968:     function dateset() {
  969:         eval("document.cu."+document.cu.pres_marker.value+
  970:             ".value=document.cu.pres_value.value");
  971:         modalWindow.close();
  972:     }
  973: 
  974:     $nondc_setsection_code
  975: // ]]>
  976: </script>
  977: END
  978: }
  979: 
  980: # =================================================================== Phase two
  981: sub print_user_selection_page {
  982:     my ($r,$response,$srch,$srch_results,$srcharray,$context,$opener_elements,$crstype,$brcrum) = @_;
  983:     my @fields = ('username','domain','lastname','firstname','permanentemail');
  984:     my $sortby = $env{'form.sortby'};
  985: 
  986:     if (!grep(/^\Q$sortby\E$/,@fields)) {
  987:         $sortby = 'lastname';
  988:     }
  989: 
  990:     my ($jsback,$elements) = &crumb_utilities();
  991: 
  992:     my $jscript = (<<ENDSCRIPT);
  993: <script type="text/javascript">
  994: // <![CDATA[
  995: function pickuser(uname,udom) {
  996:     document.usersrchform.seluname.value=uname;
  997:     document.usersrchform.seludom.value=udom;
  998:     document.usersrchform.phase.value="userpicked";
  999:     document.usersrchform.submit();
 1000: }
 1001: 
 1002: $jsback
 1003: // ]]>
 1004: </script>
 1005: ENDSCRIPT
 1006: 
 1007:     my %lt=&Apache::lonlocal::texthash(
 1008:                                        'usrch'          => "User Search to add/modify roles",
 1009:                                        'stusrch'        => "User Search to enroll student",
 1010:                                        'memsrch'        => "User Search to enroll member",
 1011:                                        'srcva'          => "Search for a user and view access log information",
 1012:                                        'usrvu'          => "User Search to view user roles",
 1013:                                        'usel'           => "Select a user to add/modify roles",
 1014:                                        'suvr'           => "Select a user to view roles",
 1015:                                        'stusel'         => "Select a user to enroll as a student",
 1016:                                        'memsel'         => "Select a user to enroll as a member",
 1017:                                        'vacsel'         => "Select a user to view access log",
 1018:                                        'username'       => "username",
 1019:                                        'domain'         => "domain",
 1020:                                        'lastname'       => "last name",
 1021:                                        'firstname'      => "first name",
 1022:                                        'permanentemail' => "permanent e-mail",
 1023:                                       );
 1024:     if ($context eq 'requestcrs') {
 1025:         $r->print('<div>');
 1026:     } else {
 1027:         my %breadcrumb_text = &singleuser_breadcrumb($crstype,$context,$srch->{'srchdomain'});
 1028:         my $helpitem;
 1029:         if ($env{'form.action'} eq 'singleuser') {
 1030:             $helpitem = 'Course_Change_Privileges';
 1031:         } elsif ($env{'form.action'} eq 'singlestudent') {
 1032:             $helpitem = 'Course_Add_Student';
 1033:         } elsif ($context eq 'author') {
 1034:             $helpitem = 'Author_Change_Privileges';
 1035:         } elsif ($context eq 'domain') {
 1036:             $helpitem = 'Domain_Change_Privileges';
 1037:         }
 1038:         push (@{$brcrum},
 1039:                   {href => "javascript:backPage(document.usersrchform,'','')",
 1040:                    text => $breadcrumb_text{'search'},
 1041:                    faq  => 282,
 1042:                    bug  => 'Instructor Interface',},
 1043:                   {href => "javascript:backPage(document.usersrchform,'get_user_info','select')",
 1044:                    text => $breadcrumb_text{'userpicked'},
 1045:                    faq  => 282,
 1046:                    bug  => 'Instructor Interface',
 1047:                    help => $helpitem}
 1048:                   );
 1049:         $r->print(&Apache::loncommon::start_page('User Management',$jscript,{bread_crumbs => $brcrum}));
 1050:         if ($env{'form.action'} eq 'singleuser') {
 1051:             my $readonly;
 1052:             if (($context eq 'domain') && (!&Apache::lonnet::allowed('mau',$srch->{'srchdomain'}))) {
 1053:                 $readonly = 1;
 1054:                 $r->print("<b>$lt{'usrvu'}</b><br />");
 1055:             } else {
 1056:                 $r->print("<b>$lt{'usrch'}</b><br />");
 1057:             }
 1058:             $r->print(&entry_form($srch->{'srchdomain'},$srch,undef,$context,undef,$crstype));
 1059:             if ($readonly) {
 1060:                 $r->print('<h3>'.$lt{'suvr'}.'</h3>');
 1061:             } else {
 1062:                 $r->print('<h3>'.$lt{'usel'}.'</h3>');
 1063:             }
 1064:         } elsif ($env{'form.action'} eq 'singlestudent') {
 1065:             $r->print($jscript."<b>");
 1066:             if ($crstype eq 'Community') {
 1067:                 $r->print($lt{'memsrch'});
 1068:             } else {
 1069:                 $r->print($lt{'stusrch'});
 1070:             }
 1071:             $r->print("</b><br />");
 1072:             $r->print(&entry_form($srch->{'srchdomain'},$srch,undef,$context,undef,$crstype));
 1073:             $r->print('</form><h3>');
 1074:             if ($crstype eq 'Community') {
 1075:                 $r->print($lt{'memsel'});
 1076:             } else {
 1077:                 $r->print($lt{'stusel'});
 1078:             }
 1079:             $r->print('</h3>');
 1080:         } elsif ($env{'form.action'} eq 'accesslogs') {
 1081:             $r->print("<b>$lt{'srcva'}</b><br />");
 1082:             $r->print(&entry_form($srch->{'srchdomain'},$srch,undef,$context,undef,undef,1));
 1083:             $r->print('<h3>'.$lt{'vacsel'}.'</h3>');
 1084:         }
 1085:     }
 1086:     $r->print('<form name="usersrchform" method="post" action="">'.
 1087:               &Apache::loncommon::start_data_table()."\n".
 1088:               &Apache::loncommon::start_data_table_header_row()."\n".
 1089:               ' <th> </th>'."\n");
 1090:     foreach my $field (@fields) {
 1091:         $r->print(' <th><a href="javascript:document.usersrchform.sortby.value='.
 1092:                   "'".$field."'".';document.usersrchform.submit();">'.
 1093:                   $lt{$field}.'</a></th>'."\n");
 1094:     }
 1095:     $r->print(&Apache::loncommon::end_data_table_header_row());
 1096: 
 1097:     my @sorted_users = sort {
 1098:         lc($srch_results->{$a}->{$sortby})   cmp lc($srch_results->{$b}->{$sortby})
 1099:             ||
 1100:         lc($srch_results->{$a}->{lastname})  cmp lc($srch_results->{$b}->{lastname})
 1101:             ||
 1102:         lc($srch_results->{$a}->{firstname}) cmp lc($srch_results->{$b}->{firstname})
 1103: 	    ||
 1104: 	lc($a) cmp lc($b)
 1105:         } (keys(%$srch_results));
 1106: 
 1107:     foreach my $user (@sorted_users) {
 1108:         my ($uname,$udom) = split(/:/,$user);
 1109:         my $onclick;
 1110:         if ($context eq 'requestcrs') {
 1111:             $onclick =
 1112:                 'onclick="javascript:gochoose('."'$uname','$udom',".
 1113:                                                "'$srch_results->{$user}->{firstname}',".
 1114:                                                "'$srch_results->{$user}->{lastname}',".
 1115:                                                "'$srch_results->{$user}->{permanentemail}'".');"';
 1116:         } else {
 1117:             $onclick =
 1118:                 ' onclick="javascript:pickuser('."'".$uname."'".','."'".$udom."'".');"';
 1119:         }
 1120:         $r->print(&Apache::loncommon::start_data_table_row().
 1121:                   '<td><input type="button" name="seluser" value="'.&mt('Select').'" '.
 1122:                   $onclick.' /></td>'.
 1123:                   '<td><tt>'.$uname.'</tt></td>'.
 1124:                   '<td><tt>'.$udom.'</tt></td>');
 1125:         foreach my $field ('lastname','firstname','permanentemail') {
 1126:             $r->print('<td>'.$srch_results->{$user}->{$field}.'</td>');
 1127:         }
 1128:         $r->print(&Apache::loncommon::end_data_table_row());
 1129:     }
 1130:     $r->print(&Apache::loncommon::end_data_table().'<br /><br />');
 1131:     if (ref($srcharray) eq 'ARRAY') {
 1132:         foreach my $item (@{$srcharray}) {
 1133:             $r->print('<input type="hidden" name="'.$item.'" value="'.$env{'form.'.$item}.'" />'."\n");
 1134:         }
 1135:     }
 1136:     $r->print(' <input type="hidden" name="sortby" value="'.$sortby.'" />'."\n".
 1137:               ' <input type="hidden" name="seluname" value="" />'."\n".
 1138:               ' <input type="hidden" name="seludom" value="" />'."\n".
 1139:               ' <input type="hidden" name="currstate" value="select" />'."\n".
 1140:               ' <input type="hidden" name="phase" value="get_user_info" />'."\n".
 1141:               ' <input type="hidden" name="action" value="'.$env{'form.action'}.'" />'."\n");
 1142:     if ($context eq 'requestcrs') {
 1143:         $r->print($opener_elements.'</form></div>');
 1144:     } else {
 1145:         $r->print($response.'</form>');
 1146:     }
 1147: }
 1148: 
 1149: sub print_user_query_page {
 1150:     my ($r,$caller,$brcrum) = @_;
 1151: # FIXME - this is for a network-wide name search (similar to catalog search)
 1152: # To use frames with similar behavior to catalog/portfolio search.
 1153: # To be implemented. 
 1154:     return;
 1155: }
 1156: 
 1157: sub print_user_modification_page {
 1158:     my ($r,$ccuname,$ccdomain,$srch,$response,$context,$permission,$crstype,
 1159:         $brcrum,$showcredits) = @_;
 1160:     if (($ccuname eq '') || ($ccdomain eq '')) {
 1161:         my $usermsg = &mt('No username and/or domain provided.');
 1162:         $env{'form.phase'} = '';
 1163: 	&print_username_entry_form($r,$context,$usermsg,'','',$crstype,$brcrum,
 1164:                                    $permission);
 1165:         return;
 1166:     }
 1167:     my ($form,$formname);
 1168:     if ($env{'form.action'} eq 'singlestudent') {
 1169:         $form = 'document.enrollstudent';
 1170:         $formname = 'enrollstudent';
 1171:     } else {
 1172:         $form = 'document.cu';
 1173:         $formname = 'cu';
 1174:     }
 1175:     my %abv_auth = &auth_abbrev();
 1176:     my (%rulematch,%inst_results,$newuser,%alerts,%curr_rules,%got_rules);
 1177:     my $uhome=&Apache::lonnet::homeserver($ccuname,$ccdomain);
 1178:     if ($uhome eq 'no_host') {
 1179:         my $usertype;
 1180:         my ($rules,$ruleorder) =
 1181:             &Apache::lonnet::inst_userrules($ccdomain,'username');
 1182:             $usertype =
 1183:                 &Apache::lonuserutils::check_usertype($ccdomain,$ccuname,$rules,
 1184:                                                       \%curr_rules,\%got_rules);
 1185:         my $cancreate =
 1186:             &Apache::lonuserutils::can_create_user($ccdomain,$context,
 1187:                                                    $usertype);
 1188:         if (!$cancreate) {
 1189:             my $helplink = 'javascript:helpMenu('."'display'".')';
 1190:             my %usertypetext = (
 1191:                 official   => 'institutional',
 1192:                 unofficial => 'non-institutional',
 1193:             );
 1194:             my $response;
 1195:             if ($env{'form.origform'} eq 'crtusername') {
 1196:                 $response = '<span class="LC_warning">'.
 1197:                             &mt('No match found for the username [_1] in LON-CAPA domain: [_2]',
 1198:                                 '<b>'.$ccuname.'</b>',$ccdomain).
 1199:                             '</span><br />';
 1200:             }
 1201:             $response .= '<p class="LC_warning">'
 1202:                         .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
 1203:                         .' ';
 1204:             if ($context eq 'domain') {
 1205:                 $response .= &mt('Please contact a [_1] for assistance.',
 1206:                                  &Apache::lonnet::plaintext('dc'));
 1207:             } else {
 1208:                 $response .= &mt('Please contact the [_1]helpdesk[_2] for assistance.'
 1209:                                 ,'<a href="'.$helplink.'">','</a>');
 1210:             }
 1211:             $response .= '</p><br />';
 1212:             $env{'form.phase'} = '';
 1213:             &print_username_entry_form($r,$context,$response,undef,undef,$crstype,$brcrum,
 1214:                                        $permission);
 1215:             return;
 1216:         }
 1217:         $newuser = 1;
 1218:         my $checkhash;
 1219:         my $checks = { 'username' => 1 };
 1220:         $checkhash->{$ccuname.':'.$ccdomain} = { 'newuser' => $newuser };
 1221:         &Apache::loncommon::user_rule_check($checkhash,$checks,
 1222:             \%alerts,\%rulematch,\%inst_results,\%curr_rules,\%got_rules);
 1223:         if (ref($alerts{'username'}) eq 'HASH') {
 1224:             if (ref($alerts{'username'}{$ccdomain}) eq 'HASH') {
 1225:                 my $domdesc =
 1226:                     &Apache::lonnet::domain($ccdomain,'description');
 1227:                 if ($alerts{'username'}{$ccdomain}{$ccuname}) {
 1228:                     my $userchkmsg;
 1229:                     if (ref($curr_rules{$ccdomain}) eq 'HASH') {  
 1230:                         $userchkmsg = 
 1231:                             &Apache::loncommon::instrule_disallow_msg('username',
 1232:                                                                  $domdesc,1).
 1233:                         &Apache::loncommon::user_rule_formats($ccdomain,
 1234:                             $domdesc,$curr_rules{$ccdomain}{'username'},
 1235:                             'username');
 1236:                     }
 1237:                     $env{'form.phase'} = '';
 1238:                     &print_username_entry_form($r,$context,$userchkmsg,undef,undef,$crstype,$brcrum,
 1239:                                                $permission);
 1240:                     return;
 1241:                 }
 1242:             }
 1243:         }
 1244:     } else {
 1245:         $newuser = 0;
 1246:     }
 1247:     if ($response) {
 1248:         $response = '<br />'.$response;
 1249:     }
 1250: 
 1251:     my $pjump_def = &Apache::lonhtmlcommon::pjump_javascript_definition();
 1252:     my $dc_setcourse_code = '';
 1253:     my $nondc_setsection_code = '';                                        
 1254:     my %loaditem;
 1255: 
 1256:     my $groupslist = &Apache::lonuserutils::get_groupslist();
 1257: 
 1258:     my $js = &validation_javascript($context,$ccdomain,$pjump_def,$crstype,
 1259:                                $groupslist,$newuser,$formname,\%loaditem);
 1260:     my %breadcrumb_text = &singleuser_breadcrumb($crstype,$context,$ccdomain);
 1261:     my $helpitem = 'Course_Change_Privileges';
 1262:     if ($env{'form.action'} eq 'singlestudent') {
 1263:         $helpitem = 'Course_Add_Student';
 1264:     } elsif ($context eq 'author') {
 1265:         $helpitem = 'Author_Change_Privileges';
 1266:     } elsif ($context eq 'domain') {
 1267:         $helpitem = 'Domain_Change_Privileges';
 1268:     }
 1269:     push (@{$brcrum},
 1270:         {href => "javascript:backPage($form)",
 1271:          text => $breadcrumb_text{'search'},
 1272:          faq  => 282,
 1273:          bug  => 'Instructor Interface',});
 1274:     if ($env{'form.phase'} eq 'userpicked') {
 1275:        push(@{$brcrum},
 1276:               {href => "javascript:backPage($form,'get_user_info','select')",
 1277:                text => $breadcrumb_text{'userpicked'},
 1278:                faq  => 282,
 1279:                bug  => 'Instructor Interface',});
 1280:     }
 1281:     push(@{$brcrum},
 1282:             {href => "javascript:backPage($form,'$env{'form.phase'}','modify')",
 1283:              text => $breadcrumb_text{'modify'},
 1284:              faq  => 282,
 1285:              bug  => 'Instructor Interface',
 1286:              help => $helpitem});
 1287:     my $args = {'add_entries'           => \%loaditem,
 1288:                 'bread_crumbs'          => $brcrum,
 1289:                 'bread_crumbs_component' => 'User Management'};
 1290:     if ($env{'form.popup'}) {
 1291:         $args->{'no_nav_bar'} = 1;
 1292:     }
 1293:     my $start_page =
 1294:         &Apache::loncommon::start_page('User Management',$js,$args);
 1295: 
 1296:     my $forminfo =<<"ENDFORMINFO";
 1297: <form action="/adm/createuser" method="post" name="$formname">
 1298: <input type="hidden" name="phase" value="update_user_data" />
 1299: <input type="hidden" name="ccuname" value="$ccuname" />
 1300: <input type="hidden" name="ccdomain" value="$ccdomain" />
 1301: <input type="hidden" name="pres_value"  value="" />
 1302: <input type="hidden" name="pres_type"   value="" />
 1303: <input type="hidden" name="pres_marker" value="" />
 1304: ENDFORMINFO
 1305:     my (%inccourses,$roledom,$defaultcredits);
 1306:     if ($context eq 'course') {
 1307:         $inccourses{$env{'request.course.id'}}=1;
 1308:         $roledom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 1309:         if ($showcredits) {
 1310:             $defaultcredits = &Apache::lonuserutils::get_defaultcredits();
 1311:         }
 1312:     } elsif ($context eq 'author') {
 1313:         $roledom = $env{'request.role.domain'};
 1314:     } elsif ($context eq 'domain') {
 1315:         foreach my $key (keys(%env)) {
 1316:             $roledom = $env{'request.role.domain'};
 1317:             if ($key=~/^user\.priv\.cm\.\/($roledom)\/($match_username)/) {
 1318:                 $inccourses{$1.'_'.$2}=1;
 1319:             }
 1320:         }
 1321:     } else {
 1322:         foreach my $key (keys(%env)) {
 1323: 	    if ($key=~/^user\.priv\.cm\.\/($match_domain)\/($match_username)/) {
 1324: 	        $inccourses{$1.'_'.$2}=1;
 1325:             }
 1326:         }
 1327:     }
 1328:     my $title = '';
 1329:     if ($newuser) {
 1330:         my ($portfolioform,$domroleform);
 1331:         if ((&Apache::lonnet::allowed('mpq',$env{'request.role.domain'})) ||
 1332:             (&Apache::lonnet::allowed('mut',$env{'request.role.domain'}))) {
 1333:             # Current user has quota or user tools modification privileges
 1334:             $portfolioform = '<br />'.&user_quotas($ccuname,$ccdomain);
 1335:         }
 1336:         if ((&Apache::lonnet::allowed('cau',$env{'request.role.domain'})) &&
 1337:             ($ccdomain eq $env{'request.role.domain'})) {
 1338:             $domroleform = '<br />'.&domainrole_req($ccuname,$ccdomain);
 1339:         }
 1340:         &initialize_authen_forms($ccdomain,$formname);
 1341:         my %lt=&Apache::lonlocal::texthash(
 1342:                 'lg'             => 'Login Data',
 1343:                 'hs'             => "Home Server",
 1344:         );
 1345: 	$r->print(<<ENDTITLE);
 1346: $start_page
 1347: $response
 1348: $forminfo
 1349: <script type="text/javascript" language="Javascript">
 1350: // <![CDATA[
 1351: $loginscript
 1352: // ]]>
 1353: </script>
 1354: <input type='hidden' name='makeuser' value='1' />
 1355: ENDTITLE
 1356:         if ($env{'form.action'} eq 'singlestudent') {
 1357:             if ($crstype eq 'Community') {
 1358:                 $title = &mt('Create New User [_1] in domain [_2] as a member',
 1359:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1360:             } else {
 1361:                 $title = &mt('Create New User [_1] in domain [_2] as a student',
 1362:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1363:             }
 1364:         } else {
 1365:                 $title = &mt('Create New User [_1] in domain [_2]',
 1366:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1367:         }
 1368:         $r->print('<h2>'.$title.'</h2>'."\n");
 1369:         $r->print('<div class="LC_left_float">');
 1370:         $r->print(&personal_data_display($ccuname,$ccdomain,$newuser,$context,
 1371:                                          $inst_results{$ccuname.':'.$ccdomain}));
 1372:         # Option to disable student/employee ID conflict checking not offerred for new users.
 1373:         my ($home_server_pick,$numlib) = 
 1374:             &Apache::loncommon::home_server_form_item($ccdomain,'hserver',
 1375:                                                       'default','hide');
 1376:         if ($numlib > 1) {
 1377:             $r->print("
 1378: <br />
 1379: $lt{'hs'}: $home_server_pick
 1380: <br />");
 1381:         } else {
 1382:             $r->print($home_server_pick);
 1383:         }
 1384:         if (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) {
 1385:             $r->print('<br /><h3>'.
 1386:                       &mt('User Can Request Creation of Courses/Communities in this Domain?').'</h3>'.
 1387:                       &Apache::loncommon::start_data_table().
 1388:                       &build_tools_display($ccuname,$ccdomain,
 1389:                                            'requestcourses').
 1390:                       &Apache::loncommon::end_data_table());
 1391:         }
 1392:         $r->print('</div>'."\n".'<div class="LC_left_float"><h3>'.
 1393:                   $lt{'lg'}.'</h3>');
 1394:         my ($fixedauth,$varauth,$authmsg); 
 1395:         if (ref($rulematch{$ccuname.':'.$ccdomain}) eq 'HASH') {
 1396:             my $matchedrule = $rulematch{$ccuname.':'.$ccdomain}{'username'};
 1397:             my ($rules,$ruleorder) = 
 1398:                 &Apache::lonnet::inst_userrules($ccdomain,'username');
 1399:             if (ref($rules) eq 'HASH') {
 1400:                 if (ref($rules->{$matchedrule}) eq 'HASH') {
 1401:                     my $authtype = $rules->{$matchedrule}{'authtype'};
 1402:                     if ($authtype !~ /^(krb4|krb5|int|fsys|loc)$/) {
 1403:                         $r->print(&Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc));
 1404:                     } else { 
 1405:                         my $authparm = $rules->{$matchedrule}{'authparm'};
 1406:                         $authmsg = $rules->{$matchedrule}{'authmsg'};
 1407:                         if ($authtype =~ /^krb(4|5)$/) {
 1408:                             my $ver = $1;
 1409:                             if ($authparm ne '') {
 1410:                                 $fixedauth = <<"KERB"; 
 1411: <input type="hidden" name="login" value="krb" />
 1412: <input type="hidden" name="krbver" value="$ver" />
 1413: <input type="hidden" name="krbarg" value="$authparm" />
 1414: KERB
 1415:                             }
 1416:                         } else {
 1417:                             $fixedauth = 
 1418: '<input type="hidden" name="login" value="'.$authtype.'" />'."\n";
 1419:                             if ($rules->{$matchedrule}{'authparmfixed'}) {
 1420:                                 $fixedauth .=    
 1421: '<input type="hidden" name="'.$authtype.'arg" value="'.$authparm.'" />'."\n";
 1422:                             } else {
 1423:                                 if ($authtype eq 'int') {
 1424:                                     $varauth = '<br />'.
 1425: &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>';
 1426:                                 } elsif ($authtype eq 'loc') {
 1427:                                     $varauth = '<br />'.
 1428: &mt('[_1] Local Authentication with argument [_2]','','<input type="text" name="'.$authtype.'arg" value="" />')."\n";
 1429:                                 } else {
 1430:                                     $varauth =
 1431: '<input type="text" name="'.$authtype.'arg" value="" />'."\n";
 1432:                                 }
 1433:                             }
 1434:                         }
 1435:                     }
 1436:                 } else {
 1437:                     $r->print(&Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc));
 1438:                 }
 1439:             }
 1440:             if ($authmsg) {
 1441:                 $r->print(<<ENDAUTH);
 1442: $fixedauth
 1443: $authmsg
 1444: $varauth
 1445: ENDAUTH
 1446:             }
 1447:         } else {
 1448:             $r->print(&Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc)); 
 1449:         }
 1450:         $r->print($portfolioform.$domroleform);
 1451:         if ($env{'form.action'} eq 'singlestudent') {
 1452:             $r->print(&date_sections_select($context,$newuser,$formname,
 1453:                                             $permission,$crstype,$ccuname,
 1454:                                             $ccdomain,$showcredits));
 1455:         }
 1456:         $r->print('</div><div class="LC_clear_float_footer"></div>');
 1457:     } else { # user already exists
 1458: 	$r->print($start_page.$forminfo);
 1459:         if ($env{'form.action'} eq 'singlestudent') {
 1460:             if ($crstype eq 'Community') {
 1461:                 $title = &mt('Enroll one member: [_1] in domain [_2]',
 1462:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1463:             } else {
 1464:                 $title = &mt('Enroll one student: [_1] in domain [_2]',
 1465:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1466:             }
 1467:         } else {
 1468:             if ($permission->{'cusr'}) {
 1469:                 $title = &mt('Modify existing user: [_1] in domain [_2]',
 1470:                              '"'.$ccuname.'"','"'.$ccdomain.'"');
 1471:             } else {
 1472:                 $title = &mt('Existing user: [_1] in domain [_2]',
 1473:                              '"'.$ccuname.'"','"'.$ccdomain.'"');
 1474:             }
 1475:         }
 1476:         $r->print('<h2>'.$title.'</h2>'."\n");
 1477:         $r->print('<div class="LC_left_float">');
 1478:         $r->print(&personal_data_display($ccuname,$ccdomain,$newuser,$context,
 1479:                                          $inst_results{$ccuname.':'.$ccdomain}));
 1480:         if ((&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) ||
 1481:             (&Apache::lonnet::allowed('udp',$env{'request.role.domain'}))) {
 1482:             $r->print('<br /><h3>'.&mt('User Can Request Creation of Courses/Communities in this Domain?').'</h3>'.
 1483:                       &Apache::loncommon::start_data_table());
 1484:             if ($env{'request.role.domain'} eq $ccdomain) {
 1485:                 $r->print(&build_tools_display($ccuname,$ccdomain,'requestcourses'));
 1486:             } else {
 1487:                 if (&Apache::lonnet::will_trust('reqcrs',$ccdomain,$env{'request.role.domain'})) {
 1488:                     $r->print(&coursereq_externaluser($ccuname,$ccdomain,
 1489:                                                       $env{'request.role.domain'}));
 1490:                 }
 1491:             }
 1492:             $r->print(&Apache::loncommon::end_data_table());
 1493:         }
 1494:         $r->print('</div>');
 1495:         my @order = ('auth','quota','tools','requestauthor');
 1496:         my %user_text;
 1497:         my ($isadv,$isauthor) = 
 1498:             &Apache::lonnet::is_advanced_user($ccdomain,$ccuname);
 1499:         if ((!$isauthor) && 
 1500:             ((&Apache::lonnet::allowed('cau',$env{'request.role.domain'})) ||
 1501:              (&Apache::lonnet::allowed('udp',$env{'request.role.domain'}))) &&
 1502:              ($env{'request.role.domain'} eq $ccdomain)) {
 1503:             $user_text{'requestauthor'} = &domainrole_req($ccuname,$ccdomain);
 1504:         }
 1505:         $user_text{'auth'} =  &user_authentication($ccuname,$ccdomain,$formname);
 1506:         if ((&Apache::lonnet::allowed('mpq',$ccdomain)) ||
 1507:             (&Apache::lonnet::allowed('mut',$ccdomain)) ||
 1508:             (&Apache::lonnet::allowed('udp',$ccdomain))) {
 1509:             # Current user has quota modification privileges
 1510:             $user_text{'quota'} = &user_quotas($ccuname,$ccdomain);
 1511:         }
 1512:         if (!&Apache::lonnet::allowed('mpq',$ccdomain)) {
 1513:             if (&Apache::lonnet::allowed('mpq',$env{'request.role.domain'})) {
 1514:                 my %lt=&Apache::lonlocal::texthash(
 1515:                     'dska'  => "Disk quotas for user's portfolio and Authoring Space",
 1516:                     'youd'  => "You do not have privileges to modify the portfolio and/or Authoring Space quotas for this user.",
 1517:                     'ichr'  => "If a change is required, contact a domain coordinator for the domain",
 1518:                 );
 1519:                 $user_text{'quota'} = <<ENDNOPORTPRIV;
 1520: <h3>$lt{'dska'}</h3>
 1521: $lt{'youd'} $lt{'ichr'}: $ccdomain
 1522: ENDNOPORTPRIV
 1523:             }
 1524:         }
 1525:         if (!&Apache::lonnet::allowed('mut',$ccdomain)) {
 1526:             if (&Apache::lonnet::allowed('mut',$env{'request.role.domain'})) {
 1527:                 my %lt=&Apache::lonlocal::texthash(
 1528:                     'utav'  => "User Tools Availability",
 1529:                     'yodo'  => "You do not have privileges to modify Portfolio, Blog, WebDAV, or Personal Information Page settings for this user.",
 1530:                     'ifch'  => "If a change is required, contact a domain coordinator for the domain",
 1531:                 );
 1532:                 $user_text{'tools'} = <<ENDNOTOOLSPRIV;
 1533: <h3>$lt{'utav'}</h3>
 1534: $lt{'yodo'} $lt{'ifch'}: $ccdomain
 1535: ENDNOTOOLSPRIV
 1536:             }
 1537:         }
 1538:         my $gotdiv = 0; 
 1539:         foreach my $item (@order) {
 1540:             if ($user_text{$item} ne '') {
 1541:                 unless ($gotdiv) {
 1542:                     $r->print('<div class="LC_left_float">');
 1543:                     $gotdiv = 1;
 1544:                 }
 1545:                 $r->print('<br />'.$user_text{$item});
 1546:             }
 1547:         }
 1548:         if ($env{'form.action'} eq 'singlestudent') {
 1549:             unless ($gotdiv) {
 1550:                 $r->print('<div class="LC_left_float">');
 1551:             }
 1552:             my $credits;
 1553:             if ($showcredits) {
 1554:                 $credits = &get_user_credits($ccuname,$ccdomain,$defaultcredits);
 1555:                 if ($credits eq '') {
 1556:                     $credits = $defaultcredits;
 1557:                 }
 1558:             }
 1559:             $r->print(&date_sections_select($context,$newuser,$formname,
 1560:                                             $permission,$crstype,$ccuname,
 1561:                                             $ccdomain,$showcredits));
 1562:         }
 1563:         if ($gotdiv) {
 1564:             $r->print('</div><div class="LC_clear_float_footer"></div>');
 1565:         }
 1566:         my $statuses;
 1567:         if (($context eq 'domain') && (&Apache::lonnet::allowed('udp',$ccdomain)) &&
 1568:             (!&Apache::lonnet::allowed('mau',$ccdomain))) {
 1569:             $statuses = ['active'];
 1570:         } elsif (($context eq 'course') && ((&Apache::lonnet::allowed('vcl',$env{'request.course.id'})) ||
 1571:                  ($env{'request.course.sec'} &&
 1572:                   &Apache::lonnet::allowed('vcl',$env{'request.course.id'}.'/'.$env{'request.course.sec'})))) {
 1573:             $statuses = ['active'];
 1574:         }
 1575:         if ($env{'form.action'} ne 'singlestudent') {
 1576:             &display_existing_roles($r,$ccuname,$ccdomain,\%inccourses,$context,
 1577:                                     $roledom,$crstype,$showcredits,$statuses);
 1578:         }
 1579:     } ## End of new user/old user logic
 1580:     if ($env{'form.action'} eq 'singlestudent') {
 1581:         my $btntxt;
 1582:         if ($crstype eq 'Community') {
 1583:             $btntxt = &mt('Enroll Member');
 1584:         } else {
 1585:             $btntxt = &mt('Enroll Student');
 1586:         }
 1587:         $r->print('<br /><input type="button" value="'.$btntxt.'" onclick="setSections(this.form)" />'."\n");
 1588:     } elsif ($permission->{'cusr'}) {
 1589:         $r->print('<div class="LC_left_float">'.
 1590:                   '<fieldset><legend>'.&mt('Add Roles').'</legend>');
 1591:         my $addrolesdisplay = 0;
 1592:         if ($context eq 'domain' || $context eq 'author') {
 1593:             $addrolesdisplay = &new_coauthor_roles($r,$ccuname,$ccdomain);
 1594:         }
 1595:         if ($context eq 'domain') {
 1596:             my $add_domainroles = &new_domain_roles($r,$ccdomain);
 1597:             if (!$addrolesdisplay) {
 1598:                 $addrolesdisplay = $add_domainroles;
 1599:             }
 1600:             $r->print(&course_level_dc($env{'request.role.domain'},$showcredits));
 1601:             $r->print('</fieldset></div><div class="LC_clear_float_footer"></div>'.
 1602:                       '<br /><input type="button" value="'.&mt('Save').'" onclick="setCourse()" />'."\n");
 1603:         } elsif ($context eq 'author') {
 1604:             if ($addrolesdisplay) {
 1605:                 $r->print('</fieldset></div><div class="LC_clear_float_footer"></div>'.
 1606:                           '<br /><input type="button" value="'.&mt('Save').'"');
 1607:                 if ($newuser) {
 1608:                     $r->print(' onclick="auth_check()" \>'."\n");
 1609:                 } else {
 1610:                     $r->print('onclick="this.form.submit()" \>'."\n");
 1611:                 }
 1612:             } else {
 1613:                 $r->print('</fieldset></div>'.
 1614:                           '<div class="LC_clear_float_footer"></div>'.
 1615:                           '<br /><a href="javascript:backPage(document.cu)">'.
 1616:                           &mt('Back to previous page').'</a>');
 1617:             }
 1618:         } else {
 1619:             $r->print(&course_level_table(\%inccourses,$showcredits,$defaultcredits));
 1620:             $r->print('</fieldset></div><div class="LC_clear_float_footer"></div>'.
 1621:                       '<br /><input type="button" value="'.&mt('Save').'" onclick="setSections(this.form)" />'."\n");
 1622:         }
 1623:     }
 1624:     $r->print(&Apache::lonhtmlcommon::echo_form_input(['phase','userrole','ccdomain','prevphase','currstate','ccuname','ccdomain']));
 1625:     $r->print('<input type="hidden" name="currstate" value="" />');
 1626:     $r->print('<input type="hidden" name="prevphase" value="'.$env{'form.phase'}.'" /></form><br /><br />');
 1627:     return;
 1628: }
 1629: 
 1630: sub singleuser_breadcrumb {
 1631:     my ($crstype,$context,$domain) = @_;
 1632:     my %breadcrumb_text;
 1633:     if ($env{'form.action'} eq 'singlestudent') {
 1634:         if ($crstype eq 'Community') {
 1635:             $breadcrumb_text{'search'} = 'Enroll a member';
 1636:         } else {
 1637:             $breadcrumb_text{'search'} = 'Enroll a student';
 1638:         }
 1639:         $breadcrumb_text{'userpicked'} = 'Select a user';
 1640:         $breadcrumb_text{'modify'} = 'Set section/dates';
 1641:     } elsif ($env{'form.action'} eq 'accesslogs') {
 1642:         $breadcrumb_text{'search'} = 'View access logs for a user';
 1643:         $breadcrumb_text{'userpicked'} = 'Select a user';
 1644:         $breadcrumb_text{'activity'} = 'Activity';
 1645:     } elsif (($env{'form.action'} eq 'singleuser') && ($context eq 'domain') &&
 1646:              (!&Apache::lonnet::allowed('mau',$domain))) {
 1647:         $breadcrumb_text{'search'} = "View user's roles";
 1648:         $breadcrumb_text{'userpicked'} = 'Select a user';
 1649:         $breadcrumb_text{'modify'} = 'User roles';
 1650:     } else {
 1651:         $breadcrumb_text{'search'} = 'Create/modify a user';
 1652:         $breadcrumb_text{'userpicked'} = 'Select a user';
 1653:         $breadcrumb_text{'modify'} = 'Set user role';
 1654:     }
 1655:     return %breadcrumb_text;
 1656: }
 1657: 
 1658: sub date_sections_select {
 1659:     my ($context,$newuser,$formname,$permission,$crstype,$ccuname,$ccdomain,
 1660:         $showcredits) = @_;
 1661:     my $credits;
 1662:     if ($showcredits) {
 1663:         my $defaultcredits = &Apache::lonuserutils::get_defaultcredits();
 1664:         $credits = &get_user_credits($ccuname,$ccdomain,$defaultcredits);
 1665:         if ($credits eq '') {
 1666:             $credits = $defaultcredits;
 1667:         }
 1668:     }
 1669:     my $cid = $env{'request.course.id'};
 1670:     my ($cnum,$cdom) = &Apache::lonuserutils::get_course_identity($cid);
 1671:     my $date_table = '<h3>'.&mt('Starting and Ending Dates').'</h3>'."\n".
 1672:         &Apache::lonuserutils::date_setting_table(undef,undef,$context,
 1673:                                                   undef,$formname,$permission);
 1674:     my $rowtitle = 'Section';
 1675:     my $secbox = '<h3>'.&mt('Section and Credits').'</h3>'."\n".
 1676:         &Apache::lonuserutils::section_picker($cdom,$cnum,'st',$rowtitle,
 1677:                                               $permission,$context,'',$crstype,
 1678:                                               $showcredits,$credits);
 1679:     my $output = $date_table.$secbox;
 1680:     return $output;
 1681: }
 1682: 
 1683: sub validation_javascript {
 1684:     my ($context,$ccdomain,$pjump_def,$crstype,$groupslist,$newuser,$formname,
 1685:         $loaditem) = @_;
 1686:     my $dc_setcourse_code = '';
 1687:     my $nondc_setsection_code = '';
 1688:     if ($context eq 'domain') {
 1689:         my $dcdom = $env{'request.role.domain'};
 1690:         $loaditem->{'onload'} = "document.cu.coursedesc.value='';";
 1691:         $dc_setcourse_code = 
 1692:             &Apache::lonuserutils::dc_setcourse_js('cu','singleuser',$context);
 1693:     } else {
 1694:         my $checkauth; 
 1695:         if (($newuser) || (&Apache::lonnet::allowed('mau',$ccdomain))) {
 1696:             $checkauth = 1;
 1697:         }
 1698:         if ($context eq 'course') {
 1699:             $nondc_setsection_code =
 1700:                 &Apache::lonuserutils::setsections_javascript($formname,$groupslist,
 1701:                                                               undef,$checkauth,
 1702:                                                               $crstype);
 1703:         }
 1704:         if ($checkauth) {
 1705:             $nondc_setsection_code .= 
 1706:                 &Apache::lonuserutils::verify_authen($formname,$context);
 1707:         }
 1708:     }
 1709:     my $js = &user_modification_js($pjump_def,$dc_setcourse_code,
 1710:                                    $nondc_setsection_code,$groupslist);
 1711:     my ($jsback,$elements) = &crumb_utilities();
 1712:     $js .= "\n".
 1713:            '<script type="text/javascript">'."\n".
 1714:            '// <![CDATA['."\n".
 1715:            $jsback."\n".
 1716:            '// ]]>'."\n".
 1717:            '</script>'."\n";
 1718:     return $js;
 1719: }
 1720: 
 1721: sub display_existing_roles {
 1722:     my ($r,$ccuname,$ccdomain,$inccourses,$context,$roledom,$crstype,
 1723:         $showcredits,$statuses) = @_;
 1724:     my $now=time;
 1725:     my $showall = 1;
 1726:     my ($showexpired,$showactive);
 1727:     if ((ref($statuses) eq 'ARRAY') && (@{$statuses} > 0)) {
 1728:         $showall = 0;
 1729:         if (grep(/^expired$/,@{$statuses})) {
 1730:             $showexpired = 1;
 1731:         }
 1732:         if (grep(/^active$/,@{$statuses})) {
 1733:             $showactive = 1;
 1734:         }
 1735:         if ($showexpired && $showactive) {
 1736:             $showall = 1;
 1737:         }
 1738:     }
 1739:     my %lt=&Apache::lonlocal::texthash(
 1740:                     'rer'  => "Existing Roles",
 1741:                     'rev'  => "Revoke",
 1742:                     'del'  => "Delete",
 1743:                     'ren'  => "Re-Enable",
 1744:                     'rol'  => "Role",
 1745:                     'ext'  => "Extent",
 1746:                     'crd'  => "Credits",
 1747:                     'sta'  => "Start",
 1748:                     'end'  => "End",
 1749:                                        );
 1750:     my (%rolesdump,%roletext,%sortrole,%roleclass,%rolepriv);
 1751:     if ($context eq 'course' || $context eq 'author') {
 1752:         my @roles = &Apache::lonuserutils::roles_by_context($context,1,$crstype);
 1753:         my %roleshash = 
 1754:             &Apache::lonnet::get_my_roles($ccuname,$ccdomain,'userroles',
 1755:                               ['active','previous','future'],\@roles,$roledom,1);
 1756:         foreach my $key (keys(%roleshash)) {
 1757:             my ($start,$end) = split(':',$roleshash{$key});
 1758:             next if ($start eq '-1' || $end eq '-1');
 1759:             my ($rnum,$rdom,$role,$sec) = split(':',$key);
 1760:             if ($context eq 'course') {
 1761:                 next unless (($rnum eq $env{'course.'.$env{'request.course.id'}.'.num'})
 1762:                              && ($rdom eq $env{'course.'.$env{'request.course.id'}.'.domain'}));
 1763:             } elsif ($context eq 'author') {
 1764:                 next unless (($rnum eq $env{'user.name'}) && ($rdom eq $env{'request.role.domain'}));
 1765:             }
 1766:             my ($newkey,$newvalue,$newrole);
 1767:             $newkey = '/'.$rdom.'/'.$rnum;
 1768:             if ($sec ne '') {
 1769:                 $newkey .= '/'.$sec;
 1770:             }
 1771:             $newvalue = $role;
 1772:             if ($role =~ /^cr/) {
 1773:                 $newrole = 'cr';
 1774:             } else {
 1775:                 $newrole = $role;
 1776:             }
 1777:             $newkey .= '_'.$newrole;
 1778:             if ($start ne '' && $end ne '') {
 1779:                 $newvalue .= '_'.$end.'_'.$start;
 1780:             } elsif ($end ne '') {
 1781:                 $newvalue .= '_'.$end;
 1782:             }
 1783:             $rolesdump{$newkey} = $newvalue;
 1784:         }
 1785:     } else {
 1786:         %rolesdump=&Apache::lonnet::dump('roles',$ccdomain,$ccuname);
 1787:     }
 1788:     # Build up table of user roles to allow revocation and re-enabling of roles.
 1789:     my ($tmp) = keys(%rolesdump);
 1790:     return if ($tmp =~ /^(con_lost|error)/i);
 1791:     foreach my $area (sort { my $a1=join('_',(split('_',$a))[1,0]);
 1792:                                 my $b1=join('_',(split('_',$b))[1,0]);
 1793:                                 return $a1 cmp $b1;
 1794:                             } keys(%rolesdump)) {
 1795:         next if ($area =~ /^rolesdef/);
 1796:         my $envkey=$area;
 1797:         my $role = $rolesdump{$area};
 1798:         my $thisrole=$area;
 1799:         $area =~ s/\_\w\w$//;
 1800:         my ($role_code,$role_end_time,$role_start_time) =
 1801:             split(/_/,$role);
 1802:         my $active=1;
 1803:         $active=0 if (($role_end_time) && ($now>$role_end_time));
 1804:         if ($active) {
 1805:             next unless($showall || $showactive);
 1806:         } else {
 1807:             next unless($showall || $showexpired);
 1808:         }
 1809: # Is this a custom role? Get role owner and title.
 1810:         my ($croleudom,$croleuname,$croletitle)=
 1811:             ($role_code=~m{^cr/($match_domain)/($match_username)/(\w+)$});
 1812:         my $allowed=0;
 1813:         my $delallowed=0;
 1814:         my $sortkey=$role_code;
 1815:         my $class='Unknown';
 1816:         my $credits='';
 1817:         my $csec;
 1818:         if ($area =~ m{^/($match_domain)/($match_courseid)}) {
 1819:             $class='Course';
 1820:             my ($coursedom,$coursedir) = ($1,$2);
 1821:             my $cid = $1.'_'.$2;
 1822:             # $1.'_'.$2 is the course id (eg. 103_12345abcef103l3).
 1823:             next if ($envkey =~ m{^/$match_domain/$match_courseid/[A-Za-z0-9]+_gr$});
 1824:             my %coursedata=
 1825:                 &Apache::lonnet::coursedescription($cid);
 1826:             if ($coursedir =~ /^$match_community$/) {
 1827:                 $class='Community';
 1828:             }
 1829:             $sortkey.="\0$coursedom";
 1830:             my $carea;
 1831:             if (defined($coursedata{'description'})) {
 1832:                 $carea=$coursedata{'description'}.
 1833:                     '<br />'.&mt('Domain').': '.$coursedom.('&nbsp;'x8).
 1834:     &Apache::loncommon::syllabuswrapper(&mt('Syllabus'),$coursedir,$coursedom);
 1835:                 $sortkey.="\0".$coursedata{'description'};
 1836:             } else {
 1837:                 if ($class eq 'Community') {
 1838:                     $carea=&mt('Unavailable community').': '.$area;
 1839:                     $sortkey.="\0".&mt('Unavailable community').': '.$area;
 1840:                 } else {
 1841:                     $carea=&mt('Unavailable course').': '.$area;
 1842:                     $sortkey.="\0".&mt('Unavailable course').': '.$area;
 1843:                 }
 1844:             }
 1845:             $sortkey.="\0$coursedir";
 1846:             $inccourses->{$cid}=1;
 1847:             if (($showcredits) && ($class eq 'Course') && ($role_code eq 'st')) {
 1848:                 my $defaultcredits = $coursedata{'internal.defaultcredits'};
 1849:                 $credits =
 1850:                     &get_user_credits($ccuname,$ccdomain,$defaultcredits,
 1851:                                       $coursedom,$coursedir);
 1852:                 if ($credits eq '') {
 1853:                     $credits = $defaultcredits;
 1854:                 }
 1855:             }
 1856:             if ((&Apache::lonnet::allowed('c'.$role_code,$coursedom.'/'.$coursedir)) ||
 1857:                 (&Apache::lonnet::allowed('c'.$role_code,$ccdomain))) {
 1858:                 $allowed=1;
 1859:             }
 1860:             unless ($allowed) {
 1861:                 my $isowner = &Apache::lonuserutils::is_courseowner($cid,$coursedata{'internal.courseowner'});
 1862:                 if ($isowner) {
 1863:                     if (($role_code eq 'co') && ($class eq 'Community')) {
 1864:                         $allowed = 1;
 1865:                     } elsif (($role_code eq 'cc') && ($class eq 'Course')) {
 1866:                         $allowed = 1;
 1867:                     }
 1868:                 }
 1869:             } 
 1870:             if ((&Apache::lonnet::allowed('dro',$coursedom)) ||
 1871:                 (&Apache::lonnet::allowed('dro',$ccdomain))) {
 1872:                 $delallowed=1;
 1873:             }
 1874: # - custom role. Needs more info, too
 1875:             if ($croletitle) {
 1876:                 if (&Apache::lonnet::allowed('ccr',$coursedom.'/'.$coursedir)) {
 1877:                     $allowed=1;
 1878:                     $thisrole.='.'.$role_code;
 1879:                 }
 1880:             }
 1881:             if ($area=~m{^/($match_domain/$match_courseid/(\w+))}) {
 1882:                 $csec = $2;
 1883:                 $carea.='<br />'.&mt('Section: [_1]',$csec);
 1884:                 $sortkey.="\0$csec";
 1885:                 if (!$allowed) {
 1886:                     if ($env{'request.course.sec'} eq $csec) {
 1887:                         if (&Apache::lonnet::allowed('c'.$role_code,$1)) {
 1888:                             $allowed = 1;
 1889:                         }
 1890:                     }
 1891:                 }
 1892:             }
 1893:             $area=$carea;
 1894:         } else {
 1895:             $sortkey.="\0".$area;
 1896:             # Determine if current user is able to revoke privileges
 1897:             if ($area=~m{^/($match_domain)/}) {
 1898:                 if ((&Apache::lonnet::allowed('c'.$role_code,$1)) ||
 1899:                    (&Apache::lonnet::allowed('c'.$role_code,$ccdomain))) {
 1900:                    $allowed=1;
 1901:                 }
 1902:                 if (((&Apache::lonnet::allowed('dro',$1))  ||
 1903:                     (&Apache::lonnet::allowed('dro',$ccdomain))) &&
 1904:                     ($role_code ne 'dc')) {
 1905:                     $delallowed=1;
 1906:                 }
 1907:             } else {
 1908:                 if (&Apache::lonnet::allowed('c'.$role_code,'/')) {
 1909:                     $allowed=1;
 1910:                 }
 1911:             }
 1912:             if ($role_code eq 'ca' || $role_code eq 'au' || $role_code eq 'aa') {
 1913:                 $class='Authoring Space';
 1914:             } elsif ($role_code eq 'su') {
 1915:                 $class='System';
 1916:             } else {
 1917:                 $class='Domain';
 1918:             }
 1919:         }
 1920:         if (($role_code eq 'ca') || ($role_code eq 'aa')) {
 1921:             $area=~m{/($match_domain)/($match_username)};
 1922:             if (&Apache::lonuserutils::authorpriv($2,$1)) {
 1923:                 $allowed=1;
 1924:             } else {
 1925:                 $allowed=0;
 1926:             }
 1927:         }
 1928:         my $row = '';
 1929:         if ($showall) {
 1930:             $row.= '<td>';
 1931:             if (($active) && ($allowed)) {
 1932:                 $row.= '<input type="checkbox" name="rev:'.$thisrole.'" />';
 1933:             } else {
 1934:                 if ($active) {
 1935:                     $row.='&nbsp;';
 1936:                 } else {
 1937:                     $row.=&mt('expired or revoked');
 1938:                 }
 1939:             }
 1940:             $row.='</td><td>';
 1941:             if ($allowed && !$active) {
 1942:                 $row.= '<input type="checkbox" name="ren:'.$thisrole.'" />';
 1943:             } else {
 1944:                 $row.='&nbsp;';
 1945:             }
 1946:             $row.='</td><td>';
 1947:             if ($delallowed) {
 1948:                 $row.= '<input type="checkbox" name="del:'.$thisrole.'" />';
 1949:             } else {
 1950:                 $row.='&nbsp;';
 1951:             }
 1952:             $row.= '</td>';
 1953:         }
 1954:         my $plaintext='';
 1955:         if (!$croletitle) {
 1956:             $plaintext=&Apache::lonnet::plaintext($role_code,$class);
 1957:             if (($showcredits) && ($credits ne '')) {
 1958:                 $plaintext .= '<br/ ><span class="LC_nobreak">'.
 1959:                               '<span class="LC_fontsize_small">'.
 1960:                               &mt('Credits: [_1]',$credits).
 1961:                               '</span></span>';
 1962:             }
 1963:         } else {
 1964:             $plaintext=
 1965:                 &mt('Custom role [_1][_2]defined by [_3]',
 1966:                         '"'.$croletitle.'"',
 1967:                         '<br />',
 1968:                         $croleuname.':'.$croleudom);
 1969:         }
 1970:         $row.= '<td>'.$plaintext.'</td>'.
 1971:                '<td>'.$area.'</td>'.
 1972:                '<td>'.($role_start_time?&Apache::lonlocal::locallocaltime($role_start_time)
 1973:                                             : '&nbsp;' ).'</td>'.
 1974:                '<td>'.($role_end_time  ?&Apache::lonlocal::locallocaltime($role_end_time)
 1975:                                             : '&nbsp;' ).'</td>';
 1976:         $sortrole{$sortkey}=$envkey;
 1977:         $roletext{$envkey}=$row;
 1978:         $roleclass{$envkey}=$class;
 1979:         if ($allowed) {
 1980:             $rolepriv{$envkey}='edit';
 1981:         } else {
 1982:             if ($context eq 'domain') {
 1983:                 if ((&Apache::lonnet::allowed('vur',$ccdomain)) &&
 1984:                     ($envkey=~m{^/$ccdomain/})) {
 1985:                     $rolepriv{$envkey}='view';
 1986:                 }
 1987:             } elsif ($context eq 'course') {
 1988:                 if ((&Apache::lonnet::allowed('vcl',$env{'request.course.id'})) ||
 1989:                     ($env{'request.course.sec'} && ($env{'request.course.sec'} eq $csec) &&
 1990:                      &Apache::lonnet::allowed('vcl',$env{'request.course.id'}.'/'.$env{'request.course.sec'}))) {
 1991:                     $rolepriv{$envkey}='view';
 1992:                 }
 1993:             }
 1994:         }
 1995:     } # end of foreach        (table building loop)
 1996: 
 1997:     my $rolesdisplay = 0;
 1998:     my %output = ();
 1999:     foreach my $type ('Authoring Space','Course','Community','Domain','System','Unknown') {
 2000:         $output{$type} = '';
 2001:         foreach my $which (sort {uc($a) cmp uc($b)} (keys(%sortrole))) {
 2002:             if ( ($roleclass{$sortrole{$which}} =~ /^\Q$type\E/ ) && ($rolepriv{$sortrole{$which}}) ) {
 2003:                  $output{$type}.=
 2004:                       &Apache::loncommon::start_data_table_row().
 2005:                       $roletext{$sortrole{$which}}.
 2006:                       &Apache::loncommon::end_data_table_row();
 2007:             }
 2008:         }
 2009:         unless($output{$type} eq '') {
 2010:             $output{$type} = '<tr class="LC_info_row">'.
 2011:                       "<td align='center' colspan='7'>".&mt($type)."</td></tr>".
 2012:                       $output{$type};
 2013:             $rolesdisplay = 1;
 2014:         }
 2015:     }
 2016:     if ($rolesdisplay == 1) {
 2017:         my $contextrole='';
 2018:         if ($env{'request.course.id'}) {
 2019:             if (&Apache::loncommon::course_type() eq 'Community') {
 2020:                 $contextrole = &mt('Existing Roles in this Community');
 2021:             } else {
 2022:                 $contextrole = &mt('Existing Roles in this Course');
 2023:             }
 2024:         } elsif ($env{'request.role'} =~ /^au\./) {
 2025:             $contextrole = &mt('Existing Co-Author Roles in your Authoring Space');
 2026:         } else {
 2027:             if ($showall) {
 2028:                 $contextrole = &mt('Existing Roles in this Domain');
 2029:             } elsif ($showactive) {
 2030:                 $contextrole = &mt('Unexpired Roles in this Domain');
 2031:             } elsif ($showexpired) {
 2032:                 $contextrole = &mt('Expired or Revoked Roles in this Domain');
 2033:             }
 2034:         }
 2035:         $r->print('<div class="LC_left_float">'.
 2036: '<fieldset><legend>'.$contextrole.'</legend>'.
 2037: &Apache::loncommon::start_data_table("LC_createuser").
 2038: &Apache::loncommon::start_data_table_header_row());
 2039:         if ($showall) {
 2040:             $r->print(
 2041: '<th>'.$lt{'rev'}.'</th><th>'.$lt{'ren'}.'</th><th>'.$lt{'del'}.'</th>'
 2042:             );
 2043:         } elsif ($showexpired) {
 2044:             $r->print('<th>'.$lt{'rev'}.'</th>');
 2045:         }
 2046:         $r->print(
 2047: '<th>'.$lt{'rol'}.'</th><th>'.$lt{'ext'}.'</th>'.
 2048: '<th>'.$lt{'sta'}.'</th><th>'.$lt{'end'}.'</th>'.
 2049: &Apache::loncommon::end_data_table_header_row());
 2050:         foreach my $type ('Authoring Space','Course','Community','Domain','System','Unknown') {
 2051:             if ($output{$type}) {
 2052:                 $r->print($output{$type}."\n");
 2053:             }
 2054:         }
 2055:         $r->print(&Apache::loncommon::end_data_table().
 2056:                   '</fieldset></div>');
 2057:     }
 2058:     return;
 2059: }
 2060: 
 2061: sub new_coauthor_roles {
 2062:     my ($r,$ccuname,$ccdomain) = @_;
 2063:     my $addrolesdisplay = 0;
 2064:     #
 2065:     # Co-Author
 2066:     #
 2067:     if (&Apache::lonuserutils::authorpriv($env{'user.name'},
 2068:                                           $env{'request.role.domain'}) &&
 2069:         ($env{'user.name'} ne $ccuname || $env{'user.domain'} ne $ccdomain)) {
 2070:         # No sense in assigning co-author role to yourself
 2071:         $addrolesdisplay = 1;
 2072:         my $cuname=$env{'user.name'};
 2073:         my $cudom=$env{'request.role.domain'};
 2074:         my %lt=&Apache::lonlocal::texthash(
 2075:                     'cs'   => "Authoring Space",
 2076:                     'act'  => "Activate",
 2077:                     'rol'  => "Role",
 2078:                     'ext'  => "Extent",
 2079:                     'sta'  => "Start",
 2080:                     'end'  => "End",
 2081:                     'cau'  => "Co-Author",
 2082:                     'caa'  => "Assistant Co-Author",
 2083:                     'ssd'  => "Set Start Date",
 2084:                     'sed'  => "Set End Date"
 2085:                                        );
 2086:         $r->print('<h4>'.$lt{'cs'}.'</h4>'."\n".
 2087:                   &Apache::loncommon::start_data_table()."\n".
 2088:                   &Apache::loncommon::start_data_table_header_row()."\n".
 2089:                   '<th>'.$lt{'act'}.'</th><th>'.$lt{'rol'}.'</th>'.
 2090:                   '<th>'.$lt{'ext'}.'</th><th>'.$lt{'sta'}.'</th>'.
 2091:                   '<th>'.$lt{'end'}.'</th>'."\n".
 2092:                   &Apache::loncommon::end_data_table_header_row()."\n".
 2093:                   &Apache::loncommon::start_data_table_row().'
 2094:            <td>
 2095:             <input type="checkbox" name="act_'.$cudom.'_'.$cuname.'_ca" />
 2096:            </td>
 2097:            <td>'.$lt{'cau'}.'</td>
 2098:            <td>'.$cudom.'_'.$cuname.'</td>
 2099:            <td><input type="hidden" name="start_'.$cudom.'_'.$cuname.'_ca" value="" />
 2100:              <a href=
 2101: "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>
 2102: <td><input type="hidden" name="end_'.$cudom.'_'.$cuname.'_ca" value="" />
 2103: <a href=
 2104: "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".
 2105:               &Apache::loncommon::end_data_table_row()."\n".
 2106:               &Apache::loncommon::start_data_table_row()."\n".
 2107: '<td><input type="checkbox" name="act_'.$cudom.'_'.$cuname.'_aa" /></td>
 2108: <td>'.$lt{'caa'}.'</td>
 2109: <td>'.$cudom.'_'.$cuname.'</td>
 2110: <td><input type="hidden" name="start_'.$cudom.'_'.$cuname.'_aa" value="" />
 2111: <a href=
 2112: "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>
 2113: <td><input type="hidden" name="end_'.$cudom.'_'.$cuname.'_aa" value="" />
 2114: <a href=
 2115: "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".
 2116:              &Apache::loncommon::end_data_table_row()."\n".
 2117:              &Apache::loncommon::end_data_table());
 2118:     } elsif ($env{'request.role'} =~ /^au\./) {
 2119:         if (!(&Apache::lonuserutils::authorpriv($env{'user.name'},
 2120:                                                 $env{'request.role.domain'}))) {
 2121:             $r->print('<span class="LC_error">'.
 2122:                       &mt('You do not have privileges to assign co-author roles.').
 2123:                       '</span>');
 2124:         } elsif (($env{'user.name'} eq $ccuname) &&
 2125:              ($env{'user.domain'} eq $ccdomain)) {
 2126:             $r->print(&mt('Assigning yourself a co-author or assistant co-author role in your own author area in Authoring Space is not permitted'));
 2127:         }
 2128:     }
 2129:     return $addrolesdisplay;;
 2130: }
 2131: 
 2132: sub new_domain_roles {
 2133:     my ($r,$ccdomain) = @_;
 2134:     my $addrolesdisplay = 0;
 2135:     #
 2136:     # Domain level
 2137:     #
 2138:     my $num_domain_level = 0;
 2139:     my $domaintext =
 2140:     '<h4>'.&mt('Domain Level').'</h4>'.
 2141:     &Apache::loncommon::start_data_table().
 2142:     &Apache::loncommon::start_data_table_header_row().
 2143:     '<th>'.&mt('Activate').'</th><th>'.&mt('Role').'</th><th>'.
 2144:     &mt('Extent').'</th>'.
 2145:     '<th>'.&mt('Start').'</th><th>'.&mt('End').'</th>'.
 2146:     &Apache::loncommon::end_data_table_header_row();
 2147:     my @allroles = &Apache::lonuserutils::roles_by_context('domain');
 2148:     my $uprimary = &Apache::lonnet::domain($env{'request.role.domain'},'primary');
 2149:     my $uintdom = &Apache::lonnet::internet_dom($uprimary);
 2150:     foreach my $thisdomain (sort(&Apache::lonnet::all_domains())) {
 2151:         foreach my $role (@allroles) {
 2152:             next if ($role eq 'ad');
 2153:             next if (($role eq 'au') && ($ccdomain ne $thisdomain));
 2154:             if (&Apache::lonnet::allowed('c'.$role,$thisdomain)) {
 2155:                if ($role eq 'dc') {
 2156:                    unless ($thisdomain eq $env{'request.role.domain'}) {
 2157:                        my $domprim = &Apache::lonnet::domain($thisdomain,'primary');
 2158:                        my $intdom = &Apache::lonnet::internet_dom($domprim);
 2159:                        next unless ($uintdom eq $intdom);
 2160:                    }
 2161:                }
 2162:                my $plrole=&Apache::lonnet::plaintext($role);
 2163:                my %lt=&Apache::lonlocal::texthash(
 2164:                     'ssd'  => "Set Start Date",
 2165:                     'sed'  => "Set End Date"
 2166:                                        );
 2167:                $num_domain_level ++;
 2168:                $domaintext .=
 2169: &Apache::loncommon::start_data_table_row().
 2170: '<td><input type="checkbox" name="act_'.$thisdomain.'_'.$role.'" /></td>
 2171: <td>'.$plrole.'</td>
 2172: <td>'.$thisdomain.'</td>
 2173: <td><input type="hidden" name="start_'.$thisdomain.'_'.$role.'" value="" />
 2174: <a href=
 2175: "javascript:pjump('."'date_start','Start Date $plrole',document.cu.start_$thisdomain\_$role.value,'start_$thisdomain\_$role','cu.pres','dateset'".')">'.$lt{'ssd'}.'</a></td>
 2176: <td><input type="hidden" name="end_'.$thisdomain.'_'.$role.'" value="" />
 2177: <a href=
 2178: "javascript:pjump('."'date_end','End Date $plrole',document.cu.end_$thisdomain\_$role.value,'end_$thisdomain\_$role','cu.pres','dateset'".')">'.$lt{'sed'}.'</a></td>'.
 2179: &Apache::loncommon::end_data_table_row();
 2180:             }
 2181:         }
 2182:     }
 2183:     $domaintext.= &Apache::loncommon::end_data_table();
 2184:     if ($num_domain_level > 0) {
 2185:         $r->print($domaintext);
 2186:         $addrolesdisplay = 1;
 2187:     }
 2188:     return $addrolesdisplay;
 2189: }
 2190: 
 2191: sub user_authentication {
 2192:     my ($ccuname,$ccdomain,$formname) = @_;
 2193:     my $currentauth=&Apache::lonnet::queryauthenticate($ccuname,$ccdomain);
 2194:     my $outcome;
 2195:     my %lt=&Apache::lonlocal::texthash(
 2196:                    'err'   => "ERROR",
 2197:                    'uuas'  => "This user has an unrecognized authentication scheme",
 2198:                    'adcs'  => "Please alert a domain coordinator of this situation",
 2199:                    'sldb'  => "Please specify login data below",
 2200:                    'ld'    => "Login Data"
 2201:     );
 2202:     # Check for a bad authentication type
 2203:     if ($currentauth !~ /^(krb4|krb5|unix|internal|localauth):/) {
 2204:         # bad authentication scheme
 2205:         if (&Apache::lonnet::allowed('mau',$ccdomain)) {
 2206:             &initialize_authen_forms($ccdomain,$formname);
 2207: 
 2208:             my $choices = &Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc);
 2209:             $outcome = <<ENDBADAUTH;
 2210: <script type="text/javascript" language="Javascript">
 2211: // <![CDATA[
 2212: $loginscript
 2213: // ]]>
 2214: </script>
 2215: <span class="LC_error">$lt{'err'}:
 2216: $lt{'uuas'} ($currentauth). $lt{'sldb'}.</span>
 2217: <h3>$lt{'ld'}</h3>
 2218: $choices
 2219: ENDBADAUTH
 2220:         } else {
 2221:             # This user is not allowed to modify the user's
 2222:             # authentication scheme, so just notify them of the problem
 2223:             $outcome = <<ENDBADAUTH;
 2224: <span class="LC_error"> $lt{'err'}: 
 2225: $lt{'uuas'} ($currentauth). $lt{'adcs'}.
 2226: </span>
 2227: ENDBADAUTH
 2228:         }
 2229:     } else { # Authentication type is valid
 2230:         
 2231:         &initialize_authen_forms($ccdomain,$formname,$currentauth,'modifyuser');
 2232:         my ($authformcurrent,$can_modify,@authform_others) =
 2233:             &modify_login_block($ccdomain,$currentauth);
 2234:         if (&Apache::lonnet::allowed('mau',$ccdomain)) {
 2235:             # Current user has login modification privileges
 2236:             $outcome =
 2237:                        '<script type="text/javascript" language="Javascript">'."\n".
 2238:                        '// <![CDATA['."\n".
 2239:                        $loginscript."\n".
 2240:                        '// ]]>'."\n".
 2241:                        '</script>'."\n".
 2242:                        '<h3>'.$lt{'ld'}.'</h3>'.
 2243:                        &Apache::loncommon::start_data_table().
 2244:                        &Apache::loncommon::start_data_table_row().
 2245:                        '<td>'.$authformnop;
 2246:             if (($can_modify) && (&Apache::lonnet::allowed('mau',$ccdomain))) {
 2247:                 $outcome .= '</td>'."\n".
 2248:                             &Apache::loncommon::end_data_table_row().
 2249:                             &Apache::loncommon::start_data_table_row().
 2250:                             '<td>'.$authformcurrent.'</td>'.
 2251:                             &Apache::loncommon::end_data_table_row()."\n";
 2252:             } else {
 2253:                 $outcome .= '&nbsp;('.$authformcurrent.')</td>'.
 2254:                             &Apache::loncommon::end_data_table_row()."\n";
 2255:             }
 2256:             if (&Apache::lonnet::allowed('mau',$ccdomain)) {
 2257:                 foreach my $item (@authform_others) { 
 2258:                     $outcome .= &Apache::loncommon::start_data_table_row().
 2259:                                 '<td>'.$item.'</td>'.
 2260:                                 &Apache::loncommon::end_data_table_row()."\n";
 2261:                 }
 2262:             }
 2263:             $outcome .= &Apache::loncommon::end_data_table();
 2264:         } else {
 2265:             if (&Apache::lonnet::allowed('udp',$ccdomain)) {
 2266:                 # Current user has rights to view domain preferences for user's domain
 2267:                 my $result;
 2268:                 if ($currentauth =~ /^krb(4|5):([^:]*)$/) {
 2269:                     my ($krbver,$krbrealm) = ($1,$2);
 2270:                     if ($krbrealm eq '') {
 2271:                         $result = &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
 2272:                     } else {
 2273:                         $result = &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
 2274:                                       $krbrealm,$krbver);
 2275:                     }
 2276:                 } elsif ($currentauth =~ /^internal:/) {
 2277:                     $result = &mt('Currently internally authenticated.');
 2278:                 } elsif ($currentauth =~ /^localauth:/) {
 2279:                     $result = &mt('Currently using local (institutional) authentication.');
 2280:                 } elsif ($currentauth =~ /^unix:/) {
 2281:                     $result = &mt('Currently Filesystem Authenticated.');
 2282:                 }
 2283:                 $outcome = '<h3>'.$lt{'ld'}.'</h3>'.
 2284:                            &Apache::loncommon::start_data_table().
 2285:                            &Apache::loncommon::start_data_table_row().
 2286:                            '<td>'.$result.'</td>'.
 2287:                            &Apache::loncommon::end_data_table_row()."\n".
 2288:                            &Apache::loncommon::end_data_table();
 2289:             } elsif (&Apache::lonnet::allowed('mau',$env{'request.role.domain'})) {
 2290:                 my %lt=&Apache::lonlocal::texthash(
 2291:                            'ccld'  => "Change Current Login Data",
 2292:                            'yodo'  => "You do not have privileges to modify the authentication configuration for this user.",
 2293:                            'ifch'  => "If a change is required, contact a domain coordinator for the domain",
 2294:                 );
 2295:                 $outcome .= <<ENDNOPRIV;
 2296: <h3>$lt{'ccld'}</h3>
 2297: $lt{'yodo'} $lt{'ifch'}: $ccdomain
 2298: <input type="hidden" name="login" value="nochange" />
 2299: ENDNOPRIV
 2300:             }
 2301:         }
 2302:     }  ## End of "check for bad authentication type" logic
 2303:     return $outcome;
 2304: }
 2305: 
 2306: sub modify_login_block {
 2307:     my ($dom,$currentauth) = @_;
 2308:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 2309:     my ($authnum,%can_assign) =
 2310:         &Apache::loncommon::get_assignable_auth($dom);
 2311:     my ($authformcurrent,@authform_others,$show_override_msg);
 2312:     if ($currentauth=~/^krb(4|5):/) {
 2313:         $authformcurrent=$authformkrb;
 2314:         if ($can_assign{'int'}) {
 2315:             push(@authform_others,$authformint);
 2316:         }
 2317:         if ($can_assign{'loc'}) {
 2318:             push(@authform_others,$authformloc);
 2319:         }
 2320:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2321:             $show_override_msg = 1;
 2322:         }
 2323:     } elsif ($currentauth=~/^internal:/) {
 2324:         $authformcurrent=$authformint;
 2325:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2326:             push(@authform_others,$authformkrb);
 2327:         }
 2328:         if ($can_assign{'loc'}) {
 2329:             push(@authform_others,$authformloc);
 2330:         }
 2331:         if ($can_assign{'int'}) {
 2332:             $show_override_msg = 1;
 2333:         }
 2334:     } elsif ($currentauth=~/^unix:/) {
 2335:         $authformcurrent=$authformfsys;
 2336:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2337:             push(@authform_others,$authformkrb);
 2338:         }
 2339:         if ($can_assign{'int'}) {
 2340:             push(@authform_others,$authformint);
 2341:         }
 2342:         if ($can_assign{'loc'}) {
 2343:             push(@authform_others,$authformloc);
 2344:         }
 2345:         if ($can_assign{'fsys'}) {
 2346:             $show_override_msg = 1;
 2347:         }
 2348:     } elsif ($currentauth=~/^localauth:/) {
 2349:         $authformcurrent=$authformloc;
 2350:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2351:             push(@authform_others,$authformkrb);
 2352:         }
 2353:         if ($can_assign{'int'}) {
 2354:             push(@authform_others,$authformint);
 2355:         }
 2356:         if ($can_assign{'loc'}) {
 2357:             $show_override_msg = 1;
 2358:         }
 2359:     }
 2360:     if ($show_override_msg) {
 2361:         $authformcurrent = '<table><tr><td colspan="3">'.$authformcurrent.
 2362:                            '</td></tr>'."\n".
 2363:                            '<tr><td>&nbsp;&nbsp;&nbsp;</td>'.
 2364:                            '<td><b>'.&mt('Currently in use').'</b></td>'.
 2365:                            '<td align="right"><span class="LC_cusr_emph">'.
 2366:                             &mt('will override current values').
 2367:                             '</span></td></tr></table>';
 2368:     }
 2369:     return ($authformcurrent,$show_override_msg,@authform_others); 
 2370: }
 2371: 
 2372: sub personal_data_display {
 2373:     my ($ccuname,$ccdomain,$newuser,$context,$inst_results,$rolesarray,
 2374:         $now,$captchaform,$emailusername,$usertype,$usernameset,$condition,$excluded) = @_;
 2375:     my ($output,%userenv,%canmodify,%canmodify_status);
 2376:     my @userinfo = ('firstname','middlename','lastname','generation',
 2377:                     'permanentemail','id');
 2378:     my $rowcount = 0;
 2379:     my $editable = 0;
 2380:     my %textboxsize = (
 2381:                        firstname      => '15',
 2382:                        middlename     => '15',
 2383:                        lastname       => '15',
 2384:                        generation     => '5',
 2385:                        permanentemail => '25',
 2386:                        id             => '15',
 2387:                       );
 2388: 
 2389:     my %lt=&Apache::lonlocal::texthash(
 2390:                 'pd'             => "Personal Data",
 2391:                 'firstname'      => "First Name",
 2392:                 'middlename'     => "Middle Name",
 2393:                 'lastname'       => "Last Name",
 2394:                 'generation'     => "Generation",
 2395:                 'permanentemail' => "Permanent e-mail address",
 2396:                 'id'             => "Student/Employee ID",
 2397:                 'lg'             => "Login Data",
 2398:                 'inststatus'     => "Affiliation",
 2399:                 'email'          => 'E-mail address',
 2400:                 'valid'          => 'Validation',
 2401:                 'username'       => 'Username',
 2402:     );
 2403: 
 2404:     %canmodify_status =
 2405:         &Apache::lonuserutils::can_modify_userinfo($context,$ccdomain,
 2406:                                                    ['inststatus'],$rolesarray);
 2407:     if (!$newuser) {
 2408:         # Get the users information
 2409:         %userenv = &Apache::lonnet::get('environment',
 2410:                    ['firstname','middlename','lastname','generation',
 2411:                     'permanentemail','id','inststatus'],$ccdomain,$ccuname);
 2412:         %canmodify =
 2413:             &Apache::lonuserutils::can_modify_userinfo($context,$ccdomain,
 2414:                                                        \@userinfo,$rolesarray);
 2415:     } elsif ($context eq 'selfcreate') {
 2416:         if ($newuser eq 'email') {
 2417:             if (ref($emailusername) eq 'HASH') {
 2418:                 if (ref($emailusername->{$usertype}) eq 'HASH') {
 2419:                     my ($infofields,$infotitles) = &Apache::loncommon::emailusername_info();
 2420:                     @userinfo = ();
 2421:                     if ((ref($infofields) eq 'ARRAY') && (ref($infotitles) eq 'HASH')) {
 2422:                         foreach my $field (@{$infofields}) { 
 2423:                             if ($emailusername->{$usertype}->{$field}) {
 2424:                                 push(@userinfo,$field);
 2425:                                 $canmodify{$field} = 1;
 2426:                                 unless ($textboxsize{$field}) {
 2427:                                     $textboxsize{$field} = 25;
 2428:                                 }
 2429:                                 unless ($lt{$field}) {
 2430:                                     $lt{$field} = $infotitles->{$field};
 2431:                                 }
 2432:                                 if ($emailusername->{$usertype}->{$field} eq 'required') {
 2433:                                     $lt{$field} .= '<b>*</b>';
 2434:                                 }
 2435:                             }
 2436:                         }
 2437:                     }
 2438:                 }
 2439:             }
 2440:         } else {
 2441:             %canmodify = &selfcreate_canmodify($context,$ccdomain,\@userinfo,
 2442:                                                $inst_results,$rolesarray);
 2443:         }
 2444:     }
 2445: 
 2446:     my $genhelp=&Apache::loncommon::help_open_topic('Generation');
 2447:     $output = '<h3>'.$lt{'pd'}.'</h3>'.
 2448:               &Apache::lonhtmlcommon::start_pick_box();
 2449:     if (($context eq 'selfcreate') && ($newuser eq 'email')) {
 2450:         my $size = 25;
 2451:         if ($condition) {
 2452:             if ($condition =~ /^\@[^\@]+$/) {
 2453:                 $size = 10;
 2454:             } else {
 2455:                 undef($condition);
 2456:             }
 2457:         } 
 2458:         if ($excluded) {
 2459:             unless ($excluded =~ /^\@[^\@]+$/) {
 2460:                 undef($condition);
 2461:             }
 2462:         }
 2463:         $output .= &Apache::lonhtmlcommon::row_title($lt{'email'}.'<b>*</b>',undef,
 2464:                                                      'LC_oddrow_value')."\n".
 2465:                    '<input type="text" name="uname" size="'.$size.'" value="" autocomplete="off" />';
 2466:         if ($condition) {
 2467:             $output .= $condition;
 2468:         } elsif ($excluded) {
 2469:             $output .= '<br /><span style="font-size: smaller">'.&mt('You must use an e-mail address that does not end with [_1]',
 2470:                                                                      $excluded).'</span>';
 2471:         }
 2472:         if ($usernameset eq 'first') {
 2473:             $output .= '<br /><span style="font-size: smaller">';
 2474:             if ($condition) {
 2475:                 $output .= &mt('Your username in LON-CAPA will be the part of your e-mail address before [_1]',
 2476:                                       $condition);
 2477:             } else {
 2478:                 $output .= &mt('Your username in LON-CAPA will be the part of your e-mail address before the @');
 2479:             }
 2480:             $output .= '</span>';
 2481:         }
 2482:         $rowcount ++;
 2483:         $output .= &Apache::lonhtmlcommon::row_closure(1);
 2484:         my $upassone = '<input type="password" name="upass'.$now.'" size="20" autocomplete="off" />';
 2485:         my $upasstwo = '<input type="password" name="upasscheck'.$now.'" size="20" autocomplete="off" />';
 2486:         $output .= &Apache::lonhtmlcommon::row_title(&mt('Password').'<b>*</b>',
 2487:                                                     'LC_pick_box_title',
 2488:                                                     'LC_oddrow_value')."\n".
 2489:                    $upassone."\n".
 2490:                    &Apache::lonhtmlcommon::row_closure(1)."\n".
 2491:                    &Apache::lonhtmlcommon::row_title(&mt('Confirm password').'<b>*</b>',
 2492:                                                      'LC_pick_box_title',
 2493:                                                      'LC_oddrow_value')."\n".
 2494:                    $upasstwo.
 2495:                    &Apache::lonhtmlcommon::row_closure()."\n";
 2496:         if ($usernameset eq 'free') {
 2497:             my $onclick = "toggleUsernameDisp(this,'selfcreateusername');"; 
 2498:             $output .= &Apache::lonhtmlcommon::row_title($lt{'username'},undef,'LC_oddrow_value')."\n".
 2499:                        &mt('Use e-mail address: ').
 2500:                        '<label><input type="radio" name="emailused" value="1" checked="checked" onclick="'.$onclick.'" />'.&mt('Yes').'</label>'."\n".
 2501:                        ('&nbsp;'x2).
 2502:                        '<label><input type="radio" name="emailused" value="0" onclick="'.$onclick.'" />'.&mt('No').'</label>'."\n".
 2503:                        '<div id="selfcreateusername" style="display: none; font-size: smaller">'.
 2504:                        '<br /><span class="LC_nobreak">'.&mt('Preferred username').
 2505:                        '&nbsp;<input type="text" name="username" value="" size="20" autocomplete="off"/>'.
 2506:                        '</span></div>'."\n".&Apache::lonhtmlcommon::row_closure(1);
 2507:             $rowcount ++;
 2508:         }
 2509:     }
 2510:     foreach my $item (@userinfo) {
 2511:         my $rowtitle = $lt{$item};
 2512:         my $hiderow = 0;
 2513:         if ($item eq 'generation') {
 2514:             $rowtitle = $genhelp.$rowtitle;
 2515:         }
 2516:         my $row = &Apache::lonhtmlcommon::row_title($rowtitle,undef,'LC_oddrow_value')."\n";
 2517:         if ($newuser) {
 2518:             if (ref($inst_results) eq 'HASH') {
 2519:                 if ($inst_results->{$item} ne '') {
 2520:                     $row .= '<input type="hidden" name="c'.$item.'" value="'.$inst_results->{$item}.'" />'.$inst_results->{$item};
 2521:                 } else {
 2522:                     if ($context eq 'selfcreate') {
 2523:                         if ($canmodify{$item}) {
 2524:                             $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="" autocomplete="off" />';
 2525:                             $editable ++;
 2526:                         } else {
 2527:                             $hiderow = 1;
 2528:                         }
 2529:                     } else {
 2530:                         $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="" />';
 2531:                     }
 2532:                 }
 2533:             } else {
 2534:                 if ($context eq 'selfcreate') {
 2535:                     if ($canmodify{$item}) {
 2536:                         if ($newuser eq 'email') {
 2537:                             $row .= '<input type="text" name="'.$item.'" size="'.$textboxsize{$item}.'" value="" autocomplete="off" />';
 2538:                         } else {
 2539:                             $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="" autocomplete="off" />';
 2540:                         }
 2541:                         $editable ++;
 2542:                     } else {
 2543:                         $hiderow = 1;
 2544:                     }
 2545:                 } else {
 2546:                     $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="" />';
 2547:                 }
 2548:             }
 2549:         } else {
 2550:             if ($canmodify{$item}) {
 2551:                 $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="'.$userenv{$item}.'" />';
 2552:                 if (($item eq 'id') && (!$newuser)) {
 2553:                     $row .= '<br />'.&Apache::lonuserutils::forceid_change($context);
 2554:                 }
 2555:             } else {
 2556:                 $row .= $userenv{$item};
 2557:             }
 2558:         }
 2559:         $row .= &Apache::lonhtmlcommon::row_closure(1);
 2560:         if (!$hiderow) {
 2561:             $output .= $row;
 2562:             $rowcount ++;
 2563:         }
 2564:     }
 2565:     if (($canmodify_status{'inststatus'}) || ($context ne 'selfcreate')) {
 2566:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($ccdomain);
 2567:         if (ref($types) eq 'ARRAY') {
 2568:             if (@{$types} > 0) {
 2569:                 my ($hiderow,$shown);
 2570:                 if ($canmodify_status{'inststatus'}) {
 2571:                     $shown = &pick_inst_statuses($userenv{'inststatus'},$usertypes,$types);
 2572:                 } else {
 2573:                     if ($userenv{'inststatus'} eq '') {
 2574:                         $hiderow = 1;
 2575:                     } else {
 2576:                         my @showitems;
 2577:                         foreach my $item ( map { &unescape($_); } split(':',$userenv{'inststatus'})) {
 2578:                             if (exists($usertypes->{$item})) {
 2579:                                 push(@showitems,$usertypes->{$item});
 2580:                             } else {
 2581:                                 push(@showitems,$item);
 2582:                             }
 2583:                         }
 2584:                         if (@showitems) {
 2585:                             $shown = join(', ',@showitems);
 2586:                         } else {
 2587:                             $hiderow = 1;
 2588:                         }
 2589:                     }
 2590:                 }
 2591:                 if (!$hiderow) {
 2592:                     my $row = &Apache::lonhtmlcommon::row_title(&mt('Affiliations'),undef,'LC_oddrow_value')."\n".
 2593:                               $shown.&Apache::lonhtmlcommon::row_closure(1); 
 2594:                     if ($context eq 'selfcreate') {
 2595:                         $rowcount ++;
 2596:                     }
 2597:                     $output .= $row;
 2598:                 }
 2599:             }
 2600:         }
 2601:     }
 2602:     if (($context eq 'selfcreate') && ($newuser eq 'email')) {
 2603:         if ($captchaform) {
 2604:             $output .= &Apache::lonhtmlcommon::row_title($lt{'valid'}.'*',
 2605:                                                          'LC_pick_box_title')."\n".
 2606:                        $captchaform."\n".'<br /><br />'.
 2607:                        &Apache::lonhtmlcommon::row_closure(1); 
 2608:             $rowcount ++;
 2609:         }
 2610:         my $submit_text = &mt('Create account');
 2611:         $output .= &Apache::lonhtmlcommon::row_title()."\n".
 2612:                    '<br /><input type="submit" name="createaccount" value="'.
 2613:                    $submit_text.'" />'.
 2614:                    '<input type="hidden" name="type" value="'.$usertype.'" />'.
 2615:                    &Apache::lonhtmlcommon::row_closure(1);
 2616:     }
 2617:     $output .= &Apache::lonhtmlcommon::end_pick_box();
 2618:     if (wantarray) {
 2619:         if ($context eq 'selfcreate') {
 2620:             return($output,$rowcount,$editable);
 2621:         } else {
 2622:             return $output;
 2623:         }
 2624:     } else {
 2625:         return $output;
 2626:     }
 2627: }
 2628: 
 2629: sub pick_inst_statuses {
 2630:     my ($curr,$usertypes,$types) = @_;
 2631:     my ($output,$rem,@currtypes);
 2632:     if ($curr ne '') {
 2633:         @currtypes = map { &unescape($_); } split(/:/,$curr);
 2634:     }
 2635:     my $numinrow = 2;
 2636:     if (ref($types) eq 'ARRAY') {
 2637:         $output = '<table>';
 2638:         my $lastcolspan; 
 2639:         for (my $i=0; $i<@{$types}; $i++) {
 2640:             if (defined($usertypes->{$types->[$i]})) {
 2641:                 my $rem = $i%($numinrow);
 2642:                 if ($rem == 0) {
 2643:                     if ($i<@{$types}-1) {
 2644:                         if ($i > 0) { 
 2645:                             $output .= '</tr>';
 2646:                         }
 2647:                         $output .= '<tr>';
 2648:                     }
 2649:                 } elsif ($i==@{$types}-1) {
 2650:                     my $colsleft = $numinrow - $rem;
 2651:                     if ($colsleft > 1) {
 2652:                         $lastcolspan = ' colspan="'.$colsleft.'"';
 2653:                     }
 2654:                 }
 2655:                 my $check = ' ';
 2656:                 if (grep(/^\Q$types->[$i]\E$/,@currtypes)) {
 2657:                     $check = ' checked="checked" ';
 2658:                 }
 2659:                 $output .= '<td class="LC_left_item"'.$lastcolspan.'>'.
 2660:                            '<span class="LC_nobreak"><label>'.
 2661:                            '<input type="checkbox" name="inststatus" '.
 2662:                            'value="'.$types->[$i].'"'.$check.'/>'.
 2663:                            $usertypes->{$types->[$i]}.'</label></span></td>';
 2664:             }
 2665:         }
 2666:         $output .= '</tr></table>';
 2667:     }
 2668:     return $output;
 2669: }
 2670: 
 2671: sub selfcreate_canmodify {
 2672:     my ($context,$dom,$userinfo,$inst_results,$rolesarray) = @_;
 2673:     if (ref($inst_results) eq 'HASH') {
 2674:         my @inststatuses = &get_inststatuses($inst_results);
 2675:         if (@inststatuses == 0) {
 2676:             @inststatuses = ('default');
 2677:         }
 2678:         $rolesarray = \@inststatuses;
 2679:     }
 2680:     my %canmodify =
 2681:         &Apache::lonuserutils::can_modify_userinfo($context,$dom,$userinfo,
 2682:                                                    $rolesarray);
 2683:     return %canmodify;
 2684: }
 2685: 
 2686: sub get_inststatuses {
 2687:     my ($insthashref) = @_;
 2688:     my @inststatuses = ();
 2689:     if (ref($insthashref) eq 'HASH') {
 2690:         if (ref($insthashref->{'inststatus'}) eq 'ARRAY') {
 2691:             @inststatuses = @{$insthashref->{'inststatus'}};
 2692:         }
 2693:     }
 2694:     return @inststatuses;
 2695: }
 2696: 
 2697: # ================================================================= Phase Three
 2698: sub update_user_data {
 2699:     my ($r,$context,$crstype,$brcrum,$showcredits) = @_; 
 2700:     my $uhome=&Apache::lonnet::homeserver($env{'form.ccuname'},
 2701:                                           $env{'form.ccdomain'});
 2702:     # Error messages
 2703:     my $error     = '<span class="LC_error">'.&mt('Error').': ';
 2704:     my $end       = '</span><br /><br />';
 2705:     my $rtnlink   = '<a href="javascript:backPage(document.userupdate,'.
 2706:                     "'$env{'form.prevphase'}','modify')".'" />'.
 2707:                     &mt('Return to previous page').'</a>'.
 2708:                     &Apache::loncommon::end_page();
 2709:     my $now = time;
 2710:     my $title;
 2711:     if (exists($env{'form.makeuser'})) {
 2712: 	$title='Set Privileges for New User';
 2713:     } else {
 2714:         $title='Modify User Privileges';
 2715:     }
 2716:     my $newuser = 0;
 2717:     my ($jsback,$elements) = &crumb_utilities();
 2718:     my $jscript = '<script type="text/javascript">'."\n".
 2719:                   '// <![CDATA['."\n".
 2720:                   $jsback."\n".
 2721:                   '// ]]>'."\n".
 2722:                   '</script>'."\n";
 2723:     my %breadcrumb_text = &singleuser_breadcrumb($crstype,$context,$env{'form.ccdomain'});
 2724:     push (@{$brcrum},
 2725:              {href => "javascript:backPage(document.userupdate)",
 2726:               text => $breadcrumb_text{'search'},
 2727:               faq  => 282,
 2728:               bug  => 'Instructor Interface',}
 2729:              );
 2730:     if ($env{'form.prevphase'} eq 'userpicked') {
 2731:         push(@{$brcrum},
 2732:                {href => "javascript:backPage(document.userupdate,'get_user_info','select')",
 2733:                 text => $breadcrumb_text{'userpicked'},
 2734:                 faq  => 282,
 2735:                 bug  => 'Instructor Interface',});
 2736:     }
 2737:     my $helpitem = 'Course_Change_Privileges';
 2738:     if ($env{'form.action'} eq 'singlestudent') {
 2739:         $helpitem = 'Course_Add_Student';
 2740:     } elsif ($context eq 'author') {
 2741:         $helpitem = 'Author_Change_Privileges';
 2742:     } elsif ($context eq 'domain') {
 2743:         $helpitem = 'Domain_Change_Privileges';
 2744:     }
 2745:     push(@{$brcrum}, 
 2746:             {href => "javascript:backPage(document.userupdate,'$env{'form.prevphase'}','modify')",
 2747:              text => $breadcrumb_text{'modify'},
 2748:              faq  => 282,
 2749:              bug  => 'Instructor Interface',},
 2750:             {href => "/adm/createuser",
 2751:              text => "Result",
 2752:              faq  => 282,
 2753:              bug  => 'Instructor Interface',
 2754:              help => $helpitem});
 2755:     my $args = {bread_crumbs          => $brcrum,
 2756:                 bread_crumbs_component => 'User Management'};
 2757:     if ($env{'form.popup'}) {
 2758:         $args->{'no_nav_bar'} = 1;
 2759:     }
 2760:     $r->print(&Apache::loncommon::start_page($title,$jscript,$args));
 2761:     $r->print(&update_result_form($uhome));
 2762:     # Check Inputs
 2763:     if (! $env{'form.ccuname'} ) {
 2764: 	$r->print($error.&mt('No login name specified').'.'.$end.$rtnlink);
 2765: 	return;
 2766:     }
 2767:     if (  $env{'form.ccuname'} ne 
 2768: 	  &LONCAPA::clean_username($env{'form.ccuname'}) ) {
 2769: 	$r->print($error.&mt('Invalid login name.').'  '.
 2770: 		  &mt('Only letters, numbers, periods, dashes, @, and underscores are valid.').
 2771: 		  $end.$rtnlink);
 2772: 	return;
 2773:     }
 2774:     if (! $env{'form.ccdomain'}       ) {
 2775: 	$r->print($error.&mt('No domain specified').'.'.$end.$rtnlink);
 2776: 	return;
 2777:     }
 2778:     if (  $env{'form.ccdomain'} ne
 2779: 	  &LONCAPA::clean_domain($env{'form.ccdomain'}) ) {
 2780: 	$r->print($error.&mt('Invalid domain name.').'  '.
 2781: 		  &mt('Only letters, numbers, periods, dashes, and underscores are valid.').
 2782: 		  $end.$rtnlink);
 2783: 	return;
 2784:     }
 2785:     if ($uhome eq 'no_host') {
 2786:         $newuser = 1;
 2787:     }
 2788:     if (! exists($env{'form.makeuser'})) {
 2789:         # Modifying an existing user, so check the validity of the name
 2790:         if ($uhome eq 'no_host') {
 2791:             $r->print(
 2792:                 $error
 2793:                .'<p class="LC_error">'
 2794:                .&mt('Unable to determine home server for [_1] in domain [_2].',
 2795:                         '"'.$env{'form.ccuname'}.'"','"'.$env{'form.ccdomain'}.'"')
 2796:                .'</p>');
 2797:             return;
 2798:         }
 2799:     }
 2800:     # Determine authentication method and password for the user being modified
 2801:     my $amode='';
 2802:     my $genpwd='';
 2803:     if ($env{'form.login'} eq 'krb') {
 2804: 	$amode='krb';
 2805: 	$amode.=$env{'form.krbver'};
 2806: 	$genpwd=$env{'form.krbarg'};
 2807:     } elsif ($env{'form.login'} eq 'int') {
 2808: 	$amode='internal';
 2809: 	$genpwd=$env{'form.intarg'};
 2810:     } elsif ($env{'form.login'} eq 'fsys') {
 2811: 	$amode='unix';
 2812: 	$genpwd=$env{'form.fsysarg'};
 2813:     } elsif ($env{'form.login'} eq 'loc') {
 2814: 	$amode='localauth';
 2815: 	$genpwd=$env{'form.locarg'};
 2816: 	$genpwd=" " if (!$genpwd);
 2817:     } elsif (($env{'form.login'} eq 'nochange') ||
 2818:              ($env{'form.login'} eq ''        )) { 
 2819:         # There is no need to tell the user we did not change what they
 2820:         # did not ask us to change.
 2821:         # If they are creating a new user but have not specified login
 2822:         # information this will be caught below.
 2823:     } else {
 2824:             $r->print($error.&mt('Invalid login mode or password').$end.$rtnlink);
 2825:             return;
 2826:     }
 2827: 
 2828:     $r->print('<h3>'.&mt('User [_1] in domain [_2]',
 2829:                         $env{'form.ccuname'}.' ('.&Apache::loncommon::plainname($env{'form.ccuname'},
 2830:                         $env{'form.ccdomain'}).')', $env{'form.ccdomain'}).'</h3>');
 2831:     my %prog_state = &Apache::lonhtmlcommon::Create_PrgWin($r,2);
 2832: 
 2833:     my (%alerts,%rulematch,%inst_results,%curr_rules);
 2834:     my @userinfo = ('firstname','middlename','lastname','generation','permanentemail','id');
 2835:     my @usertools = ('aboutme','blog','webdav','portfolio');
 2836:     my @requestcourses = ('official','unofficial','community','textbook','placement');
 2837:     my @requestauthor = ('requestauthor');
 2838:     my ($othertitle,$usertypes,$types) = 
 2839:         &Apache::loncommon::sorted_inst_types($env{'form.ccdomain'});
 2840:     my %canmodify_status =
 2841:         &Apache::lonuserutils::can_modify_userinfo($context,$env{'form.ccdomain'},
 2842:                                                    ['inststatus']);
 2843:     if ($env{'form.makeuser'}) {
 2844: 	$r->print('<h3>'.&mt('Creating new account.').'</h3>');
 2845:         # Check for the authentication mode and password
 2846:         if (! $amode || ! $genpwd) {
 2847: 	    $r->print($error.&mt('Invalid login mode or password').$end.$rtnlink);    
 2848: 	    return;
 2849: 	}
 2850:         # Determine desired host
 2851:         my $desiredhost = $env{'form.hserver'};
 2852:         if (lc($desiredhost) eq 'default') {
 2853:             $desiredhost = undef;
 2854:         } else {
 2855:             my %home_servers = 
 2856: 		&Apache::lonnet::get_servers($env{'form.ccdomain'},'library');
 2857:             if (! exists($home_servers{$desiredhost})) {
 2858:                 $r->print($error.&mt('Invalid home server specified').$end.$rtnlink);
 2859:                 return;
 2860:             }
 2861:         }
 2862:         # Check ID format
 2863:         my %checkhash;
 2864:         my %checks = ('id' => 1);
 2865:         %{$checkhash{$env{'form.ccuname'}.':'.$env{'form.ccdomain'}}} = (
 2866:             'newuser' => $newuser, 
 2867:             'id' => $env{'form.cid'},
 2868:         );
 2869:         if ($env{'form.cid'} ne '') {
 2870:             &Apache::loncommon::user_rule_check(\%checkhash,\%checks,\%alerts,
 2871:                                           \%rulematch,\%inst_results,\%curr_rules);
 2872:             if (ref($alerts{'id'}) eq 'HASH') {
 2873:                 if (ref($alerts{'id'}{$env{'form.ccdomain'}}) eq 'HASH') {
 2874:                     my $domdesc =
 2875:                         &Apache::lonnet::domain($env{'form.ccdomain'},'description');
 2876:                     if ($alerts{'id'}{$env{'form.ccdomain'}}{$env{'form.cid'}}) {
 2877:                         my $userchkmsg;
 2878:                         if (ref($curr_rules{$env{'form.ccdomain'}}) eq 'HASH') {
 2879:                             $userchkmsg  = 
 2880:                                 &Apache::loncommon::instrule_disallow_msg('id',
 2881:                                                                     $domdesc,1).
 2882:                                 &Apache::loncommon::user_rule_formats($env{'form.ccdomain'},
 2883:                                     $domdesc,$curr_rules{$env{'form.ccdomain'}}{'id'},'id');
 2884:                         }
 2885:                         $r->print($error.&mt('Invalid ID format').$end.
 2886:                                   $userchkmsg.$rtnlink);
 2887:                         return;
 2888:                     }
 2889:                 }
 2890:             }
 2891:         }
 2892:         &Apache::lonhtmlcommon::Increment_PrgWin($r, \%prog_state);
 2893: 	# Call modifyuser
 2894: 	my $result = &Apache::lonnet::modifyuser
 2895: 	    ($env{'form.ccdomain'},$env{'form.ccuname'},$env{'form.cid'},
 2896:              $amode,$genpwd,$env{'form.cfirstname'},
 2897:              $env{'form.cmiddlename'},$env{'form.clastname'},
 2898:              $env{'form.cgeneration'},undef,$desiredhost,
 2899:              $env{'form.cpermanentemail'});
 2900: 	$r->print(&mt('Generating user').': '.$result);
 2901:         $uhome = &Apache::lonnet::homeserver($env{'form.ccuname'},
 2902:                                                $env{'form.ccdomain'});
 2903:         my (%changeHash,%newcustom,%changed,%changedinfo);
 2904:         if ($uhome ne 'no_host') {
 2905:             if ($context eq 'domain') {
 2906:                 foreach my $name ('portfolio','author') {
 2907:                     if ($env{'form.custom_'.$name.'quota'} == 1) {
 2908:                         if ($env{'form.'.$name.'quota'} eq '') {
 2909:                             $newcustom{$name.'quota'} = 0;
 2910:                         } else {
 2911:                             $newcustom{$name.'quota'} = $env{'form.'.$name.'quota'};
 2912:                             $newcustom{$name.'quota'} =~ s/[^\d\.]//g;
 2913:                         }
 2914:                         if (&quota_admin($newcustom{$name.'quota'},\%changeHash,$name)) {
 2915:                             $changed{$name.'quota'} = 1;
 2916:                         }
 2917:                     }
 2918:                 }
 2919:                 foreach my $item (@usertools) {
 2920:                     if ($env{'form.custom'.$item} == 1) {
 2921:                         $newcustom{$item} = $env{'form.tools_'.$item};
 2922:                         $changed{$item} = &tool_admin($item,$newcustom{$item},
 2923:                                                      \%changeHash,'tools');
 2924:                     }
 2925:                 }
 2926:                 foreach my $item (@requestcourses) {
 2927:                     if ($env{'form.custom'.$item} == 1) {
 2928:                         $newcustom{$item} = $env{'form.crsreq_'.$item};
 2929:                         if ($env{'form.crsreq_'.$item} eq 'autolimit') {
 2930:                             $newcustom{$item} .= '=';
 2931:                             $env{'form.crsreq_'.$item.'_limit'} =~ s/\D+//g;
 2932:                             if ($env{'form.crsreq_'.$item.'_limit'}) {
 2933:                                 $newcustom{$item} .= $env{'form.crsreq_'.$item.'_limit'};
 2934:                             }
 2935:                         }
 2936:                         $changed{$item} = &tool_admin($item,$newcustom{$item},
 2937:                                                       \%changeHash,'requestcourses');
 2938:                     }
 2939:                 }
 2940:                 if ($env{'form.customrequestauthor'} == 1) {
 2941:                     $newcustom{'requestauthor'} = $env{'form.requestauthor'};
 2942:                     $changed{'requestauthor'} = &tool_admin('requestauthor',
 2943:                                                     $newcustom{'requestauthor'},
 2944:                                                     \%changeHash,'requestauthor');
 2945:                 }
 2946:             }
 2947:             if ($canmodify_status{'inststatus'}) {
 2948:                 if (exists($env{'form.inststatus'})) {
 2949:                     my @inststatuses = &Apache::loncommon::get_env_multiple('form.inststatus');
 2950:                     if (@inststatuses > 0) {
 2951:                         $changeHash{'inststatus'} = join(',',@inststatuses);
 2952:                         $changed{'inststatus'} = $changeHash{'inststatus'};
 2953:                     }
 2954:                 }
 2955:             }
 2956:             if (keys(%changed)) {
 2957:                 foreach my $item (@userinfo) {
 2958:                     $changeHash{$item}  = $env{'form.c'.$item};
 2959:                 }
 2960:                 my $chgresult =
 2961:                      &Apache::lonnet::put('environment',\%changeHash,
 2962:                                           $env{'form.ccdomain'},$env{'form.ccuname'});
 2963:             } 
 2964:         }
 2965:         $r->print('<br />'.&mt('Home server').': '.$uhome.' '.
 2966:                   &Apache::lonnet::hostname($uhome));
 2967:     } elsif (($env{'form.login'} ne 'nochange') &&
 2968:              ($env{'form.login'} ne ''        )) {
 2969: 	# Modify user privileges
 2970:         if (! $amode || ! $genpwd) {
 2971: 	    $r->print($error.'Invalid login mode or password'.$end.$rtnlink);    
 2972: 	    return;
 2973: 	}
 2974: 	# Only allow authentication modification if the person has authority
 2975: 	if (&Apache::lonnet::allowed('mau',$env{'form.ccdomain'})) {
 2976: 	    $r->print('Modifying authentication: '.
 2977:                       &Apache::lonnet::modifyuserauth(
 2978: 		       $env{'form.ccdomain'},$env{'form.ccuname'},
 2979:                        $amode,$genpwd));
 2980:             $r->print('<br />'.&mt('Home server').': '.&Apache::lonnet::homeserver
 2981: 		  ($env{'form.ccuname'},$env{'form.ccdomain'}));
 2982: 	} else {
 2983: 	    # Okay, this is a non-fatal error.
 2984: 	    $r->print($error.&mt('You do not have the authority to modify this users authentication information.').$end);    
 2985: 	}
 2986:     }
 2987:     $r->rflush(); # Finish display of header before time consuming actions start
 2988:     &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state);
 2989:     ##
 2990:     my (@userroles,%userupdate,$cnum,$cdom,$defaultcredits,%namechanged);
 2991:     if ($context eq 'course') {
 2992:         ($cnum,$cdom) =
 2993:             &Apache::lonuserutils::get_course_identity();
 2994:         $crstype = &Apache::loncommon::course_type($cdom.'_'.$cnum);
 2995:         if ($showcredits) {
 2996:            $defaultcredits = &Apache::lonuserutils::get_defaultcredits($cdom,$cnum);
 2997:         }
 2998:     }
 2999:     if (! $env{'form.makeuser'} ) {
 3000:         # Check for need to change
 3001:         my %userenv = &Apache::lonnet::get
 3002:             ('environment',['firstname','middlename','lastname','generation',
 3003:              'id','permanentemail','portfolioquota','authorquota','inststatus',
 3004:              'tools.aboutme','tools.blog','tools.webdav','tools.portfolio',
 3005:              'requestcourses.official','requestcourses.unofficial',
 3006:              'requestcourses.community','requestcourses.textbook',
 3007:              'reqcrsotherdom.official','reqcrsotherdom.unofficial',
 3008:              'reqcrsotherdom.community','reqcrsotherdom.textbook',
 3009:              'reqcrsotherdom.placement','requestauthor'],
 3010:               $env{'form.ccdomain'},$env{'form.ccuname'});
 3011:         my ($tmp) = keys(%userenv);
 3012:         if ($tmp =~ /^(con_lost|error)/i) { 
 3013:             %userenv = ();
 3014:         }
 3015:         my $no_forceid_alert;
 3016:         # Check to see if user information can be changed
 3017:         my %domconfig =
 3018:             &Apache::lonnet::get_dom('configuration',['usermodification'],
 3019:                                      $env{'form.ccdomain'});
 3020:         my @statuses = ('active','future');
 3021:         my %roles = &Apache::lonnet::get_my_roles($env{'form.ccuname'},$env{'form.ccdomain'},'userroles',\@statuses,undef,$env{'request.role.domain'});
 3022:         my ($auname,$audom);
 3023:         if ($context eq 'author') {
 3024:             $auname = $env{'user.name'};
 3025:             $audom = $env{'user.domain'};     
 3026:         }
 3027:         foreach my $item (keys(%roles)) {
 3028:             my ($rolenum,$roledom,$role) = split(/:/,$item,-1);
 3029:             if ($context eq 'course') {
 3030:                 if ($cnum ne '' && $cdom ne '') {
 3031:                     if ($rolenum eq $cnum && $roledom eq $cdom) {
 3032:                         if (!grep(/^\Q$role\E$/,@userroles)) {
 3033:                             push(@userroles,$role);
 3034:                         }
 3035:                     }
 3036:                 }
 3037:             } elsif ($context eq 'author') {
 3038:                 if ($rolenum eq $auname && $roledom eq $audom) {
 3039:                     if (!grep(/^\Q$role\E$/,@userroles)) { 
 3040:                         push(@userroles,$role);
 3041:                     }
 3042:                 }
 3043:             }
 3044:         }
 3045:         if ($env{'form.action'} eq 'singlestudent') {
 3046:             if (!grep(/^st$/,@userroles)) {
 3047:                 push(@userroles,'st');
 3048:             }
 3049:         } else {
 3050:             # Check for course or co-author roles being activated or re-enabled
 3051:             if ($context eq 'author' || $context eq 'course') {
 3052:                 foreach my $key (keys(%env)) {
 3053:                     if ($context eq 'author') {
 3054:                         if ($key=~/^form\.act_\Q$audom\E_\Q$auname\E_([^_]+)/) {
 3055:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 3056:                                 push(@userroles,$1);
 3057:                             }
 3058:                         } elsif ($key =~/^form\.ren\:\Q$audom\E\/\Q$auname\E_([^_]+)/) {
 3059:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 3060:                                 push(@userroles,$1);
 3061:                             }
 3062:                         }
 3063:                     } elsif ($context eq 'course') {
 3064:                         if ($key=~/^form\.act_\Q$cdom\E_\Q$cnum\E_([^_]+)/) {
 3065:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 3066:                                 push(@userroles,$1);
 3067:                             }
 3068:                         } elsif ($key =~/^form\.ren\:\Q$cdom\E\/\Q$cnum\E(\/?\w*)_([^_]+)/) {
 3069:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 3070:                                 push(@userroles,$1);
 3071:                             }
 3072:                         }
 3073:                     }
 3074:                 }
 3075:             }
 3076:         }
 3077:         #Check to see if we can change personal data for the user 
 3078:         my (@mod_disallowed,@longroles);
 3079:         foreach my $role (@userroles) {
 3080:             if ($role eq 'cr') {
 3081:                 push(@longroles,'Custom');
 3082:             } else {
 3083:                 push(@longroles,&Apache::lonnet::plaintext($role,$crstype)); 
 3084:             }
 3085:         }
 3086:         my %canmodify = &Apache::lonuserutils::can_modify_userinfo($context,$env{'form.ccdomain'},\@userinfo,\@userroles);
 3087:         foreach my $item (@userinfo) {
 3088:             # Strip leading and trailing whitespace
 3089:             $env{'form.c'.$item} =~ s/(\s+$|^\s+)//g;
 3090:             if (!$canmodify{$item}) {
 3091:                 if (defined($env{'form.c'.$item})) {
 3092:                     if ($env{'form.c'.$item} ne $userenv{$item}) {
 3093:                         push(@mod_disallowed,$item);
 3094:                     }
 3095:                 }
 3096:                 $env{'form.c'.$item} = $userenv{$item};
 3097:             }
 3098:         }
 3099:         # Check to see if we can change the Student/Employee ID
 3100:         my $forceid = $env{'form.forceid'};
 3101:         my $recurseid = $env{'form.recurseid'};
 3102:         my (%alerts,%rulematch,%idinst_results,%curr_rules,%got_rules);
 3103:         my %uidhash = &Apache::lonnet::idrget($env{'form.ccdomain'},
 3104:                                             $env{'form.ccuname'});
 3105:         if (($uidhash{$env{'form.ccuname'}}) && 
 3106:             ($uidhash{$env{'form.ccuname'}}!~/error\:/) && 
 3107:             (!$forceid)) {
 3108:             if ($env{'form.cid'} ne $uidhash{$env{'form.ccuname'}}) {
 3109:                 $env{'form.cid'} = $userenv{'id'};
 3110:                 $no_forceid_alert = &mt('New student/employee ID does not match existing ID for this user.')
 3111:                                    .'<br />'
 3112:                                    .&mt("Change is not permitted without checking the 'Force ID change' checkbox on the previous page.")
 3113:                                    .'<br />'."\n";
 3114:             }
 3115:         }
 3116:         if ($env{'form.cid'} ne $userenv{'id'}) {
 3117:             my $checkhash;
 3118:             my $checks = { 'id' => 1 };
 3119:             $checkhash->{$env{'form.ccuname'}.':'.$env{'form.ccdomain'}} = 
 3120:                    { 'newuser' => $newuser,
 3121:                      'id'  => $env{'form.cid'}, 
 3122:                    };
 3123:             &Apache::loncommon::user_rule_check($checkhash,$checks,
 3124:                 \%alerts,\%rulematch,\%idinst_results,\%curr_rules,\%got_rules);
 3125:             if (ref($alerts{'id'}) eq 'HASH') {
 3126:                 if (ref($alerts{'id'}{$env{'form.ccdomain'}}) eq 'HASH') {
 3127:                    $env{'form.cid'} = $userenv{'id'};
 3128:                 }
 3129:             }
 3130:         }
 3131:         my (%quotachanged,%oldquota,%newquota,%olddefquota,%newdefquota, 
 3132:             $oldinststatus,$newinststatus,%oldisdefault,%newisdefault,%oldsettings,
 3133:             %oldsettingstext,%newsettings,%newsettingstext,@disporder,
 3134:             %oldsettingstatus,%newsettingstatus);
 3135:         @disporder = ('inststatus');
 3136:         if ($env{'request.role.domain'} eq $env{'form.ccdomain'}) {
 3137:             push(@disporder,'requestcourses','requestauthor');
 3138:         } else {
 3139:             push(@disporder,'reqcrsotherdom');
 3140:         }
 3141:         push(@disporder,('quota','tools'));
 3142:         $oldinststatus = $userenv{'inststatus'};
 3143:         foreach my $name ('portfolio','author') {
 3144:             ($olddefquota{$name},$oldsettingstatus{$name}) = 
 3145:                 &Apache::loncommon::default_quota($env{'form.ccdomain'},$oldinststatus,$name);
 3146:             ($newdefquota{$name},$newsettingstatus{$name}) = ($olddefquota{$name},$oldsettingstatus{$name});
 3147:         }
 3148:         my %canshow;
 3149:         if (&Apache::lonnet::allowed('mpq',$env{'form.ccdomain'})) {
 3150:             $canshow{'quota'} = 1;
 3151:         }
 3152:         if (&Apache::lonnet::allowed('mut',$env{'form.ccdomain'})) {
 3153:             $canshow{'tools'} = 1;
 3154:         }
 3155:         if (&Apache::lonnet::allowed('ccc',$env{'form.ccdomain'})) {
 3156:             $canshow{'requestcourses'} = 1;
 3157:         } elsif (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) {
 3158:             $canshow{'reqcrsotherdom'} = 1;
 3159:         }
 3160:         if (&Apache::lonnet::allowed('mau',$env{'form.ccdomain'})) {
 3161:             $canshow{'inststatus'} = 1;
 3162:         }
 3163:         if (&Apache::lonnet::allowed('cau',$env{'form.ccdomain'})) {
 3164:             $canshow{'requestauthor'} = 1;
 3165:         }
 3166:         my (%changeHash,%changed);
 3167:         if ($oldinststatus eq '') {
 3168:             $oldsettings{'inststatus'} = $othertitle; 
 3169:         } else {
 3170:             if (ref($usertypes) eq 'HASH') {
 3171:                 $oldsettings{'inststatus'} = join(', ',map{ $usertypes->{ &unescape($_) }; } (split(/:/,$userenv{'inststatus'})));
 3172:             } else {
 3173:                 $oldsettings{'inststatus'} = join(', ',map{ &unescape($_); } (split(/:/,$userenv{'inststatus'})));
 3174:             }
 3175:         }
 3176:         $changeHash{'inststatus'} = $userenv{'inststatus'};
 3177:         if ($canmodify_status{'inststatus'}) {
 3178:             $canshow{'inststatus'} = 1;
 3179:             if (exists($env{'form.inststatus'})) {
 3180:                 my @inststatuses = &Apache::loncommon::get_env_multiple('form.inststatus');
 3181:                 if (@inststatuses > 0) {
 3182:                     $newinststatus = join(':',map { &escape($_); } @inststatuses);
 3183:                     $changeHash{'inststatus'} = $newinststatus;
 3184:                     if ($newinststatus ne $oldinststatus) {
 3185:                         $changed{'inststatus'} = $newinststatus;
 3186:                         foreach my $name ('portfolio','author') {
 3187:                             ($newdefquota{$name},$newsettingstatus{$name}) =
 3188:                                 &Apache::loncommon::default_quota($env{'form.ccdomain'},$newinststatus,$name);
 3189:                         }
 3190:                     }
 3191:                     if (ref($usertypes) eq 'HASH') {
 3192:                         $newsettings{'inststatus'} = join(', ',map{ $usertypes->{$_}; } (@inststatuses)); 
 3193:                     } else {
 3194:                         $newsettings{'inststatus'} = join(', ',@inststatuses);
 3195:                     }
 3196:                 }
 3197:             } else {
 3198:                 $newinststatus = '';
 3199:                 $changeHash{'inststatus'} = $newinststatus;
 3200:                 $newsettings{'inststatus'} = $othertitle;
 3201:                 if ($newinststatus ne $oldinststatus) {
 3202:                     $changed{'inststatus'} = $changeHash{'inststatus'};
 3203:                     foreach my $name ('portfolio','author') {
 3204:                         ($newdefquota{$name},$newsettingstatus{$name}) =
 3205:                             &Apache::loncommon::default_quota($env{'form.ccdomain'},$newinststatus,$name);
 3206:                     }
 3207:                 }
 3208:             }
 3209:         } elsif ($context ne 'selfcreate') {
 3210:             $canshow{'inststatus'} = 1;
 3211:             $newsettings{'inststatus'} = $oldsettings{'inststatus'};
 3212:         }
 3213:         foreach my $name ('portfolio','author') {
 3214:             $changeHash{$name.'quota'} = $userenv{$name.'quota'};
 3215:         }
 3216:         if ($context eq 'domain') {
 3217:             foreach my $name ('portfolio','author') {
 3218:                 if ($userenv{$name.'quota'} ne '') {
 3219:                     $oldquota{$name} = $userenv{$name.'quota'};
 3220:                     if ($env{'form.custom_'.$name.'quota'} == 1) {
 3221:                         if ($env{'form.'.$name.'quota'} eq '') {
 3222:                             $newquota{$name} = 0;
 3223:                         } else {
 3224:                             $newquota{$name} = $env{'form.'.$name.'quota'};
 3225:                             $newquota{$name} =~ s/[^\d\.]//g;
 3226:                         }
 3227:                         if ($newquota{$name} != $oldquota{$name}) {
 3228:                             if (&quota_admin($newquota{$name},\%changeHash,$name)) {
 3229:                                 $changed{$name.'quota'} = 1;
 3230:                             }
 3231:                         }
 3232:                     } else {
 3233:                         if (&quota_admin('',\%changeHash,$name)) {
 3234:                             $changed{$name.'quota'} = 1;
 3235:                             $newquota{$name} = $newdefquota{$name};
 3236:                             $newisdefault{$name} = 1;
 3237:                         }
 3238:                     }
 3239:                 } else {
 3240:                     $oldisdefault{$name} = 1;
 3241:                     $oldquota{$name} = $olddefquota{$name};
 3242:                     if ($env{'form.custom_'.$name.'quota'} == 1) {
 3243:                         if ($env{'form.'.$name.'quota'} eq '') {
 3244:                             $newquota{$name} = 0;
 3245:                         } else {
 3246:                             $newquota{$name} = $env{'form.'.$name.'quota'};
 3247:                             $newquota{$name} =~ s/[^\d\.]//g;
 3248:                         }
 3249:                         if (&quota_admin($newquota{$name},\%changeHash,$name)) {
 3250:                             $changed{$name.'quota'} = 1;
 3251:                         }
 3252:                     } else {
 3253:                         $newquota{$name} = $newdefquota{$name};
 3254:                         $newisdefault{$name} = 1;
 3255:                     }
 3256:                 }
 3257:                 if ($oldisdefault{$name}) {
 3258:                     $oldsettingstext{'quota'}{$name} = &get_defaultquota_text($oldsettingstatus{$name});
 3259:                 }  else {
 3260:                     $oldsettingstext{'quota'}{$name} = &mt('custom quota: [_1] MB',$oldquota{$name});
 3261:                 }
 3262:                 if ($newisdefault{$name}) {
 3263:                     $newsettingstext{'quota'}{$name} = &get_defaultquota_text($newsettingstatus{$name});
 3264:                 } else {
 3265:                     $newsettingstext{'quota'}{$name} = &mt('custom quota: [_1] MB',$newquota{$name});
 3266:                 }
 3267:             }
 3268:             &tool_changes('tools',\@usertools,\%oldsettings,\%oldsettingstext,\%userenv,
 3269:                           \%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3270:             if ($env{'form.ccdomain'} eq $env{'request.role.domain'}) {
 3271:                 &tool_changes('requestcourses',\@requestcourses,\%oldsettings,\%oldsettingstext,
 3272:                               \%userenv,\%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3273:                 &tool_changes('requestauthor',\@requestauthor,\%oldsettings,\%oldsettingstext,
 3274:                               \%userenv,\%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3275:             } else {
 3276:                 &tool_changes('reqcrsotherdom',\@requestcourses,\%oldsettings,\%oldsettingstext,
 3277:                               \%userenv,\%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3278:             }
 3279:         }
 3280:         foreach my $item (@userinfo) {
 3281:             if ($env{'form.c'.$item} ne $userenv{$item}) {
 3282:                 $namechanged{$item} = 1;
 3283:             }
 3284:         }
 3285:         foreach my $name ('portfolio','author') {
 3286:             $oldsettings{'quota'}{$name} = &mt('[_1] MB',$oldquota{$name});
 3287:             $newsettings{'quota'}{$name} = &mt('[_1] MB',$newquota{$name});
 3288:         }
 3289:         if ((keys(%namechanged) > 0) || (keys(%changed) > 0)) {
 3290:             my ($chgresult,$namechgresult);
 3291:             if (keys(%changed) > 0) {
 3292:                 $chgresult = 
 3293:                     &Apache::lonnet::put('environment',\%changeHash,
 3294:                                   $env{'form.ccdomain'},$env{'form.ccuname'});
 3295:                 if ($chgresult eq 'ok') {
 3296:                     if (($env{'user.name'} eq $env{'form.ccuname'}) &&
 3297:                         ($env{'user.domain'} eq $env{'form.ccdomain'})) {
 3298:                         my %newenvhash;
 3299:                         foreach my $key (keys(%changed)) {
 3300:                             if (($key eq 'official') || ($key eq 'unofficial') ||
 3301:                                 ($key eq 'community') || ($key eq 'textbook') ||
 3302:                                 ($key eq 'placement')) {
 3303:                                 $newenvhash{'environment.requestcourses.'.$key} =
 3304:                                     $changeHash{'requestcourses.'.$key};
 3305:                                 if ($changeHash{'requestcourses.'.$key}) {
 3306:                                     $newenvhash{'environment.canrequest.'.$key} = 1;
 3307:                                 } else {
 3308:                                     $newenvhash{'environment.canrequest.'.$key} =
 3309:           &Apache::lonnet::usertools_access($env{'user.name'},$env{'user.domain'},
 3310:                                             $key,'reload','requestcourses');
 3311:                                 }
 3312:                             } elsif ($key eq 'requestauthor') {
 3313:                                 $newenvhash{'environment.'.$key} = $changeHash{$key};
 3314:                                 if ($changeHash{$key}) {
 3315:                                     $newenvhash{'environment.canrequest.author'} = 1;
 3316:                                 } else {
 3317:                                     $newenvhash{'environment.canrequest.author'} =
 3318:           &Apache::lonnet::usertools_access($env{'user.name'},$env{'user.domain'},
 3319:                                             $key,'reload','requestauthor');
 3320:                                 }
 3321:                             } elsif ($key ne 'quota') {
 3322:                                 $newenvhash{'environment.tools.'.$key} = 
 3323:                                     $changeHash{'tools.'.$key};
 3324:                                 if ($changeHash{'tools.'.$key} ne '') {
 3325:                                     $newenvhash{'environment.availabletools.'.$key} =
 3326:                                         $changeHash{'tools.'.$key};
 3327:                                 } else {
 3328:                                     $newenvhash{'environment.availabletools.'.$key} =
 3329:           &Apache::lonnet::usertools_access($env{'user.name'},$env{'user.domain'},
 3330:           $key,'reload','tools');
 3331:                                 }
 3332:                             }
 3333:                         }
 3334:                         if (keys(%newenvhash)) {
 3335:                             &Apache::lonnet::appenv(\%newenvhash);
 3336:                         }
 3337:                     }
 3338:                 }
 3339:             }
 3340:             if (keys(%namechanged) > 0) {
 3341:                 foreach my $field (@userinfo) {
 3342:                     $changeHash{$field}  = $env{'form.c'.$field};
 3343:                 }
 3344: # Make the change
 3345:                 $namechgresult =
 3346:                     &Apache::lonnet::modifyuser($env{'form.ccdomain'},
 3347:                         $env{'form.ccuname'},$changeHash{'id'},undef,undef,
 3348:                         $changeHash{'firstname'},$changeHash{'middlename'},
 3349:                         $changeHash{'lastname'},$changeHash{'generation'},
 3350:                         $changeHash{'id'},undef,$changeHash{'permanentemail'},undef,\@userinfo);
 3351:                 %userupdate = (
 3352:                                lastname   => $env{'form.clastname'},
 3353:                                middlename => $env{'form.cmiddlename'},
 3354:                                firstname  => $env{'form.cfirstname'},
 3355:                                generation => $env{'form.cgeneration'},
 3356:                                id         => $env{'form.cid'},
 3357:                              );
 3358:             }
 3359:             if (((keys(%namechanged) > 0) && $namechgresult eq 'ok') || 
 3360:                 ((keys(%changed) > 0) && $chgresult eq 'ok')) {
 3361:             # Tell the user we changed the name
 3362:                 &display_userinfo($r,1,\@disporder,\%canshow,\@requestcourses,
 3363:                                   \@usertools,\@requestauthor,\%userenv,\%changed,\%namechanged,
 3364:                                   \%oldsettings, \%oldsettingstext,\%newsettings,
 3365:                                   \%newsettingstext);
 3366:                 if ($env{'form.cid'} ne $userenv{'id'}) {
 3367:                     &Apache::lonnet::idput($env{'form.ccdomain'},
 3368:                          {$env{'form.ccuname'} => $env{'form.cid'}},$uhome,'ids');
 3369:                     if (($recurseid) &&
 3370:                         (&Apache::lonnet::allowed('mau',$env{'form.ccdomain'}))) {
 3371:                         my $idresult = 
 3372:                             &Apache::lonuserutils::propagate_id_change(
 3373:                                 $env{'form.ccuname'},$env{'form.ccdomain'},
 3374:                                 \%userupdate);
 3375:                         $r->print('<br />'.$idresult.'<br />');
 3376:                     }
 3377:                 }
 3378:                 if (($env{'form.ccdomain'} eq $env{'user.domain'}) && 
 3379:                     ($env{'form.ccuname'} eq $env{'user.name'})) {
 3380:                     my %newenvhash;
 3381:                     foreach my $key (keys(%changeHash)) {
 3382:                         $newenvhash{'environment.'.$key} = $changeHash{$key};
 3383:                     }
 3384:                     &Apache::lonnet::appenv(\%newenvhash);
 3385:                 }
 3386:             } else { # error occurred
 3387:                 $r->print(
 3388:                     '<p class="LC_error">'
 3389:                    .&mt('Unable to successfully change environment for [_1] in domain [_2].',
 3390:                             '"'.$env{'form.ccuname'}.'"',
 3391:                             '"'.$env{'form.ccdomain'}.'"')
 3392:                    .'</p>');
 3393:             }
 3394:         } else { # End of if ($env ... ) logic
 3395:             # They did not want to change the users name, quota, tool availability,
 3396:             # or ability to request creation of courses, 
 3397:             # but we can still tell them what the name and quota and availabilities are  
 3398:             &display_userinfo($r,undef,\@disporder,\%canshow,\@requestcourses,
 3399:                               \@usertools,\@requestauthor,\%userenv,\%changed,\%namechanged,\%oldsettings,
 3400:                               \%oldsettingstext,\%newsettings,\%newsettingstext);
 3401:         }
 3402:         if (@mod_disallowed) {
 3403:             my ($rolestr,$contextname);
 3404:             if (@longroles > 0) {
 3405:                 $rolestr = join(', ',@longroles);
 3406:             } else {
 3407:                 $rolestr = &mt('No roles');
 3408:             }
 3409:             if ($context eq 'course') {
 3410:                 $contextname = 'course';
 3411:             } elsif ($context eq 'author') {
 3412:                 $contextname = 'co-author';
 3413:             }
 3414:             $r->print(&mt('The following fields were not updated: ').'<ul>');
 3415:             my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
 3416:             foreach my $field (@mod_disallowed) {
 3417:                 $r->print('<li>'.$fieldtitles{$field}.'</li>'."\n"); 
 3418:             }
 3419:             $r->print('</ul>');
 3420:             if (@mod_disallowed == 1) {
 3421:                 $r->print(&mt("You do not have the authority to change this field given the user's current set of active/future $contextname roles:"));
 3422:             } else {
 3423:                 $r->print(&mt("You do not have the authority to change these fields given the user's current set of active/future $contextname roles:"));
 3424:             }
 3425:             my $helplink = 'javascript:helpMenu('."'display'".')';
 3426:             $r->print('<span class="LC_cusr_emph">'.$rolestr.'</span><br />'
 3427:                      .&mt('Please contact your [_1]helpdesk[_2] for more information.'
 3428:                          ,'<a href="'.$helplink.'">','</a>')
 3429:                       .'<br />');
 3430:         }
 3431:         $r->print('<span class="LC_warning">'
 3432:                   .$no_forceid_alert
 3433:                   .&Apache::lonuserutils::print_namespacing_alerts($env{'form.ccdomain'},\%alerts,\%curr_rules)
 3434:                   .'</span>');
 3435:     }
 3436:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 3437:     if ($env{'form.action'} eq 'singlestudent') {
 3438:         &enroll_single_student($r,$uhome,$amode,$genpwd,$now,$newuser,$context,
 3439:                                $crstype,$showcredits,$defaultcredits);
 3440:         my $linktext = ($crstype eq 'Community' ?
 3441:             &mt('Enroll Another Member') : &mt('Enroll Another Student'));
 3442:         $r->print(
 3443:             &Apache::lonhtmlcommon::actionbox([
 3444:                 '<a href="javascript:backPage(document.userupdate)">'
 3445:                .($crstype eq 'Community' ? 
 3446:                     &mt('Enroll Another Member') : &mt('Enroll Another Student'))
 3447:                .'</a>']));
 3448:     } else {
 3449:         my @rolechanges = &update_roles($r,$context,$showcredits);
 3450:         if (keys(%namechanged) > 0) {
 3451:             if ($context eq 'course') {
 3452:                 if (@userroles > 0) {
 3453:                     if ((@rolechanges == 0) || 
 3454:                         (!(grep(/^st$/,@rolechanges)))) {
 3455:                         if (grep(/^st$/,@userroles)) {
 3456:                             my $classlistupdated =
 3457:                                 &Apache::lonuserutils::update_classlist($cdom,
 3458:                                               $cnum,$env{'form.ccdomain'},
 3459:                                        $env{'form.ccuname'},\%userupdate);
 3460:                         }
 3461:                     }
 3462:                 }
 3463:             }
 3464:         }
 3465:         my $userinfo = &Apache::loncommon::plainname($env{'form.ccuname'},
 3466:                                                      $env{'form.ccdomain'});
 3467:         if ($env{'form.popup'}) {
 3468:             $r->print('<p><a href="javascript:window.close()">'.&mt('Close window').'</a></p>');
 3469:         } else {
 3470:             $r->print('<br />'.&Apache::lonhtmlcommon::actionbox(['<a href="javascript:backPage(document.userupdate,'."'$env{'form.prevphase'}','modify'".')">'
 3471:                      .&mt('Modify this user: [_1]','<span class="LC_cusr_emph">'.$env{'form.ccuname'}.':'.$env{'form.ccdomain'}.' ('.$userinfo.')</span>').'</a>',
 3472:                      '<a href="javascript:backPage(document.userupdate)">'.&mt('Create/Modify Another User').'</a>']));
 3473:         }
 3474:     }
 3475: }
 3476: 
 3477: sub display_userinfo {
 3478:     my ($r,$changed,$order,$canshow,$requestcourses,$usertools,$requestauthor,
 3479:         $userenv,$changedhash,$namechangedhash,$oldsetting,$oldsettingtext,
 3480:         $newsetting,$newsettingtext) = @_;
 3481:     return unless (ref($order) eq 'ARRAY' &&
 3482:                    ref($canshow) eq 'HASH' && 
 3483:                    ref($requestcourses) eq 'ARRAY' && 
 3484:                    ref($requestauthor) eq 'ARRAY' &&
 3485:                    ref($usertools) eq 'ARRAY' && 
 3486:                    ref($userenv) eq 'HASH' &&
 3487:                    ref($changedhash) eq 'HASH' &&
 3488:                    ref($oldsetting) eq 'HASH' &&
 3489:                    ref($oldsettingtext) eq 'HASH' &&
 3490:                    ref($newsetting) eq 'HASH' &&
 3491:                    ref($newsettingtext) eq 'HASH');
 3492:     my %lt=&Apache::lonlocal::texthash(
 3493:          'ui'             => 'User Information',
 3494:          'uic'            => 'User Information Changed',
 3495:          'firstname'      => 'First Name',
 3496:          'middlename'     => 'Middle Name',
 3497:          'lastname'       => 'Last Name',
 3498:          'generation'     => 'Generation',
 3499:          'id'             => 'Student/Employee ID',
 3500:          'permanentemail' => 'Permanent e-mail address',
 3501:          'portfolioquota' => 'Disk space allocated to portfolio files',
 3502:          'authorquota'    => 'Disk space allocated to Authoring Space',
 3503:          'blog'           => 'Blog Availability',
 3504:          'webdav'         => 'WebDAV Availability',
 3505:          'aboutme'        => 'Personal Information Page Availability',
 3506:          'portfolio'      => 'Portfolio Availability',
 3507:          'official'       => 'Can Request Official Courses',
 3508:          'unofficial'     => 'Can Request Unofficial Courses',
 3509:          'community'      => 'Can Request Communities',
 3510:          'textbook'       => 'Can Request Textbook Courses',
 3511:          'placement'      => 'Can Request Placement Tests',
 3512:          'requestauthor'  => 'Can Request Author Role',
 3513:          'inststatus'     => "Affiliation",
 3514:          'prvs'           => 'Previous Value:',
 3515:          'chto'           => 'Changed To:'
 3516:     );
 3517:     if ($changed) {
 3518:         $r->print('<h3>'.$lt{'uic'}.'</h3>'.
 3519:                 &Apache::loncommon::start_data_table().
 3520:                 &Apache::loncommon::start_data_table_header_row());
 3521:         $r->print("<th>&nbsp;</th>\n");
 3522:         $r->print('<th><b>'.$lt{'prvs'}.'</b></th>');
 3523:         $r->print('<th><span class="LC_nobreak"><b>'.$lt{'chto'}.'</b></span></th>');
 3524:         $r->print(&Apache::loncommon::end_data_table_header_row());
 3525:         my @userinfo = ('firstname','middlename','lastname','generation','permanentemail','id');
 3526: 
 3527:         foreach my $item (@userinfo) {
 3528:             my $value = $env{'form.c'.$item};
 3529:             #show changes only:
 3530:             unless ($value eq $userenv->{$item}){
 3531:                 $r->print(&Apache::loncommon::start_data_table_row());
 3532:                 $r->print("<td>$lt{$item}</td>\n");
 3533:                 $r->print("<td>".$userenv->{$item}."</td>\n");
 3534:                 $r->print("<td>$value </td>\n");
 3535:                 $r->print(&Apache::loncommon::end_data_table_row());
 3536:             }
 3537:         }
 3538:         foreach my $entry (@{$order}) {
 3539:             if ($canshow->{$entry}) {
 3540:                 if (($entry eq 'requestcourses') || ($entry eq 'reqcrsotherdom') || ($entry eq 'requestauthor')) {
 3541:                     my @items;
 3542:                     if ($entry eq 'requestauthor') {
 3543:                         @items = ($entry);
 3544:                     } else {
 3545:                         @items = @{$requestcourses};
 3546:                     }
 3547:                     foreach my $item (@items) {
 3548:                         if (($newsetting->{$item} ne $oldsetting->{$item}) || 
 3549:                             ($newsettingtext->{$item} ne $oldsettingtext->{$item})) {
 3550:                             $r->print(&Apache::loncommon::start_data_table_row()."\n");  
 3551:                             $r->print("<td>$lt{$item}</td>\n");
 3552:                             $r->print("<td>".$oldsetting->{$item});
 3553:                             if ($oldsettingtext->{$item}) {
 3554:                                 if ($oldsetting->{$item}) {
 3555:                                     $r->print(' -- ');
 3556:                                 }
 3557:                                 $r->print($oldsettingtext->{$item});
 3558:                             }
 3559:                             $r->print("</td>\n");
 3560:                             $r->print("<td>".$newsetting->{$item});
 3561:                             if ($newsettingtext->{$item}) {
 3562:                                 if ($newsetting->{$item}) {
 3563:                                     $r->print(' -- ');
 3564:                                 }
 3565:                                 $r->print($newsettingtext->{$item});
 3566:                             }
 3567:                             $r->print("</td>\n");
 3568:                             $r->print(&Apache::loncommon::end_data_table_row()."\n");
 3569:                         }
 3570:                     }
 3571:                 } elsif ($entry eq 'tools') {
 3572:                     foreach my $item (@{$usertools}) {
 3573:                         if ($newsetting->{$item} ne $oldsetting->{$item}) {
 3574:                             $r->print(&Apache::loncommon::start_data_table_row()."\n");
 3575:                             $r->print("<td>$lt{$item}</td>\n");
 3576:                             $r->print("<td>".$oldsetting->{$item}.' '.$oldsettingtext->{$item}."</td>\n");
 3577:                             $r->print("<td>".$newsetting->{$item}.' '.$newsettingtext->{$item}."</td>\n");
 3578:                             $r->print(&Apache::loncommon::end_data_table_row()."\n");
 3579:                         }
 3580:                     }
 3581:                 } elsif ($entry eq 'quota') {
 3582:                     if ((ref($oldsetting->{$entry}) eq 'HASH') && (ref($oldsettingtext->{$entry}) eq 'HASH') &&
 3583:                         (ref($newsetting->{$entry}) eq 'HASH') && (ref($newsettingtext->{$entry}) eq 'HASH')) {
 3584:                         foreach my $name ('portfolio','author') {
 3585:                             if ($newsetting->{$entry}->{$name} ne $oldsetting->{$entry}->{$name}) {
 3586:                                 $r->print(&Apache::loncommon::start_data_table_row()."\n");
 3587:                                 $r->print("<td>$lt{$name.$entry}</td>\n");
 3588:                                 $r->print("<td>".$oldsettingtext->{$entry}->{$name}."</td>\n");
 3589:                                 $r->print("<td>".$newsettingtext->{$entry}->{$name}."</td>\n");
 3590:                                 $r->print(&Apache::loncommon::end_data_table_row()."\n");
 3591:                             }
 3592:                         }
 3593:                     }
 3594:                 } else {
 3595:                     if ($newsetting->{$entry} ne $oldsetting->{$entry}) {
 3596:                         $r->print(&Apache::loncommon::start_data_table_row()."\n");
 3597:                         $r->print("<td>$lt{$entry}</td>\n");
 3598:                         $r->print("<td>".$oldsetting->{$entry}.' '.$oldsettingtext->{$entry}."</td>\n");
 3599:                         $r->print("<td>".$newsetting->{$entry}.' '.$newsettingtext->{$entry}."</td>\n");
 3600:                         $r->print(&Apache::loncommon::end_data_table_row()."\n");
 3601:                     }
 3602:                 }
 3603:             }
 3604:         }
 3605:         $r->print(&Apache::loncommon::end_data_table().'<br />');
 3606:     } else {
 3607:         $r->print('<h3>'.$lt{'ui'}.'</h3>'.
 3608:                   '<p>'.&mt('No changes made to user information').'</p>');
 3609:     }
 3610:     return;
 3611: }
 3612: 
 3613: sub tool_changes {
 3614:     my ($context,$usertools,$oldaccess,$oldaccesstext,$userenv,$changeHash,
 3615:         $changed,$newaccess,$newaccesstext) = @_;
 3616:     if (!((ref($usertools) eq 'ARRAY') && (ref($oldaccess) eq 'HASH') &&
 3617:           (ref($oldaccesstext) eq 'HASH') && (ref($userenv) eq 'HASH') &&
 3618:           (ref($changeHash) eq 'HASH') && (ref($changed) eq 'HASH') &&
 3619:           (ref($newaccess) eq 'HASH') && (ref($newaccesstext) eq 'HASH'))) {
 3620:         return;
 3621:     }
 3622:     my %reqdisplay = &requestchange_display();
 3623:     if ($context eq 'reqcrsotherdom') {
 3624:         my @options = ('approval','validate','autolimit');
 3625:         my $optregex = join('|',@options);
 3626:         my $cdom = $env{'request.role.domain'};
 3627:         foreach my $tool (@{$usertools}) {
 3628:             $oldaccesstext->{$tool} = &mt("availability set to 'off'");
 3629:             $newaccesstext->{$tool} = $oldaccesstext->{$tool};
 3630:             $changeHash->{$context.'.'.$tool} = $userenv->{$context.'.'.$tool};
 3631:             my ($newop,$limit);
 3632:             if ($env{'form.'.$context.'_'.$tool}) {
 3633:                 $newop = $env{'form.'.$context.'_'.$tool};
 3634:                 if ($newop eq 'autolimit') {
 3635:                     $limit = $env{'form.'.$context.'_'.$tool.'_limit'};
 3636:                     $limit =~ s/\D+//g;
 3637:                     $newop .= '='.$limit;
 3638:                 }
 3639:             }
 3640:             if ($userenv->{$context.'.'.$tool} eq '') {
 3641:                 if ($newop) {
 3642:                     $changed->{$tool}=&tool_admin($tool,$cdom.':'.$newop,
 3643:                                                   $changeHash,$context);
 3644:                     if ($changed->{$tool}) {
 3645:                         if ($newop =~ /^autolimit/) {
 3646:                             if ($limit) {
 3647:                                 $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3648:                             } else {
 3649:                                 $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3650:                             }
 3651:                         } else {
 3652:                             $newaccesstext->{$tool} = $reqdisplay{$newop};
 3653:                         }
 3654:                     } else {
 3655:                         $newaccesstext->{$tool} = $oldaccesstext->{$tool};
 3656:                     }
 3657:                 }
 3658:             } else {
 3659:                 my @curr = split(',',$userenv->{$context.'.'.$tool});
 3660:                 my @new;
 3661:                 my $changedoms;
 3662:                 foreach my $req (@curr) {
 3663:                     if ($req =~ /^\Q$cdom\E\:($optregex\=?\d*)$/) {
 3664:                         my $oldop = $1;
 3665:                         if ($oldop =~ /^autolimit=(\d*)/) {
 3666:                             my $limit = $1;
 3667:                             if ($limit) {
 3668:                                 $oldaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3669:                             } else {
 3670:                                 $oldaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3671:                             }
 3672:                         } else {
 3673:                             $oldaccesstext->{$tool} = $reqdisplay{$oldop};
 3674:                         }
 3675:                         if ($oldop ne $newop) {
 3676:                             $changedoms = 1;
 3677:                             foreach my $item (@curr) {
 3678:                                 my ($reqdom,$option) = split(':',$item);
 3679:                                 unless ($reqdom eq $cdom) {
 3680:                                     push(@new,$item);
 3681:                                 }
 3682:                             }
 3683:                             if ($newop) {
 3684:                                 push(@new,$cdom.':'.$newop);
 3685:                             }
 3686:                             @new = sort(@new);
 3687:                         }
 3688:                         last;
 3689:                     }
 3690:                 }
 3691:                 if ((!$changedoms) && ($newop)) {
 3692:                     $changedoms = 1;
 3693:                     @new = sort(@curr,$cdom.':'.$newop);
 3694:                 }
 3695:                 if ($changedoms) {
 3696:                     my $newdomstr;
 3697:                     if (@new) {
 3698:                         $newdomstr = join(',',@new);
 3699:                     }
 3700:                     $changed->{$tool}=&tool_admin($tool,$newdomstr,$changeHash,
 3701:                                                   $context);
 3702:                     if ($changed->{$tool}) {
 3703:                         if ($env{'form.'.$context.'_'.$tool}) {
 3704:                             if ($env{'form.'.$context.'_'.$tool} eq 'autolimit') {
 3705:                                 my $limit = $env{'form.'.$context.'_'.$tool.'_limit'};
 3706:                                 $limit =~ s/\D+//g;
 3707:                                 if ($limit) {
 3708:                                     $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3709:                                 } else {
 3710:                                     $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3711:                                 }
 3712:                             } else {
 3713:                                 $newaccesstext->{$tool} = $reqdisplay{$env{'form.'.$context.'_'.$tool}};
 3714:                             }
 3715:                         } else {
 3716:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3717:                         }
 3718:                     }
 3719:                 }
 3720:             }
 3721:         }
 3722:         return;
 3723:     }
 3724:     foreach my $tool (@{$usertools}) {
 3725:         my ($newval,$limit,$envkey);
 3726:         $envkey = $context.'.'.$tool;
 3727:         if ($context eq 'requestcourses') {
 3728:             $newval = $env{'form.crsreq_'.$tool};
 3729:             if ($newval eq 'autolimit') {
 3730:                 $limit = $env{'form.crsreq_'.$tool.'_limit'};
 3731:                 $limit =~ s/\D+//g;
 3732:                 $newval .= '='.$limit;
 3733:             }
 3734:         } elsif ($context eq 'requestauthor') {
 3735:             $newval = $env{'form.'.$context};
 3736:             $envkey = $context;
 3737:         } else {
 3738:             $newval = $env{'form.'.$context.'_'.$tool};
 3739:         }
 3740:         if ($userenv->{$envkey} ne '') {
 3741:             $oldaccess->{$tool} = &mt('custom');
 3742:             if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 3743:                 if ($userenv->{$envkey} =~ /^autolimit=(\d*)$/) {
 3744:                     my $currlimit = $1;
 3745:                     if ($currlimit eq '') {
 3746:                         $oldaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3747:                     } else {
 3748:                         $oldaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$currlimit);
 3749:                     }
 3750:                 } elsif ($userenv->{$envkey}) {
 3751:                     $oldaccesstext->{$tool} = $reqdisplay{$userenv->{$envkey}};
 3752:                 } else {
 3753:                     $oldaccesstext->{$tool} = &mt("availability set to 'off'");
 3754:                 }
 3755:             } else {
 3756:                 if ($userenv->{$envkey}) {
 3757:                     $oldaccesstext->{$tool} = &mt("availability set to 'on'");
 3758:                 } else {
 3759:                     $oldaccesstext->{$tool} = &mt("availability set to 'off'");
 3760:                 }
 3761:             }
 3762:             $changeHash->{$envkey} = $userenv->{$envkey};
 3763:             if ($env{'form.custom'.$tool} == 1) {
 3764:                 if ($newval ne $userenv->{$envkey}) {
 3765:                     $changed->{$tool} = &tool_admin($tool,$newval,$changeHash,
 3766:                                                     $context);
 3767:                     if ($changed->{$tool}) {
 3768:                         $newaccess->{$tool} = &mt('custom');
 3769:                         if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 3770:                             if ($newval =~ /^autolimit/) {
 3771:                                 if ($limit) {
 3772:                                     $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3773:                                 } else {
 3774:                                     $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3775:                                 }
 3776:                             } elsif ($newval) {
 3777:                                 $newaccesstext->{$tool} = $reqdisplay{$newval};
 3778:                             } else {
 3779:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3780:                             }
 3781:                         } else {
 3782:                             if ($newval) {
 3783:                                 $newaccesstext->{$tool} = &mt("availability set to 'on'");
 3784:                             } else {
 3785:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3786:                             }
 3787:                         }
 3788:                     } else {
 3789:                         $newaccess->{$tool} = $oldaccess->{$tool};
 3790:                         if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 3791:                             if ($newval =~ /^autolimit/) {
 3792:                                 if ($limit) {
 3793:                                     $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3794:                                 } else {
 3795:                                     $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3796:                                 }
 3797:                             } elsif ($newval) {
 3798:                                 $newaccesstext->{$tool} = $reqdisplay{$newval};
 3799:                             } else {
 3800:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3801:                             }
 3802:                         } else {
 3803:                             if ($userenv->{$context.'.'.$tool}) {
 3804:                                 $newaccesstext->{$tool} = &mt("availability set to 'on'");
 3805:                             } else {
 3806:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3807:                             }
 3808:                         }
 3809:                     }
 3810:                 } else {
 3811:                     $newaccess->{$tool} = $oldaccess->{$tool};
 3812:                     $newaccesstext->{$tool} = $oldaccesstext->{$tool};
 3813:                 }
 3814:             } else {
 3815:                 $changed->{$tool} = &tool_admin($tool,'',$changeHash,$context);
 3816:                 if ($changed->{$tool}) {
 3817:                     $newaccess->{$tool} = &mt('default');
 3818:                 } else {
 3819:                     $newaccess->{$tool} = $oldaccess->{$tool};
 3820:                     if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 3821:                         if ($newval =~ /^autolimit/) {
 3822:                             if ($limit) {
 3823:                                 $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3824:                             } else {
 3825:                                 $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3826:                             }
 3827:                         } elsif ($newval) {
 3828:                             $newaccesstext->{$tool} = $reqdisplay{$newval};
 3829:                         } else {
 3830:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3831:                         }
 3832:                     } else {
 3833:                         if ($userenv->{$context.'.'.$tool}) {
 3834:                             $newaccesstext->{$tool} = &mt("availability set to 'on'");
 3835:                         } else {
 3836:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3837:                         }
 3838:                     }
 3839:                 }
 3840:             }
 3841:         } else {
 3842:             $oldaccess->{$tool} = &mt('default');
 3843:             if ($env{'form.custom'.$tool} == 1) {
 3844:                 $changed->{$tool} = &tool_admin($tool,$newval,$changeHash,
 3845:                                                 $context);
 3846:                 if ($changed->{$tool}) {
 3847:                     $newaccess->{$tool} = &mt('custom');
 3848:                     if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 3849:                         if ($newval =~ /^autolimit/) {
 3850:                             if ($limit) {
 3851:                                 $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3852:                             } else {
 3853:                                 $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3854:                             }
 3855:                         } elsif ($newval) {
 3856:                             $newaccesstext->{$tool} = $reqdisplay{$newval};
 3857:                         } else {
 3858:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3859:                         }
 3860:                     } else {
 3861:                         if ($newval) {
 3862:                             $newaccesstext->{$tool} = &mt("availability set to 'on'");
 3863:                         } else {
 3864:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3865:                         }
 3866:                     }
 3867:                 } else {
 3868:                     $newaccess->{$tool} = $oldaccess->{$tool};
 3869:                 }
 3870:             } else {
 3871:                 $newaccess->{$tool} = $oldaccess->{$tool};
 3872:             }
 3873:         }
 3874:     }
 3875:     return;
 3876: }
 3877: 
 3878: sub update_roles {
 3879:     my ($r,$context,$showcredits) = @_;
 3880:     my $now=time;
 3881:     my @rolechanges;
 3882:     my %disallowed;
 3883:     $r->print('<h3>'.&mt('Modifying Roles').'</h3>');
 3884:     foreach my $key (keys(%env)) {
 3885: 	next if (! $env{$key});
 3886:         next if ($key eq 'form.action');
 3887: 	# Revoke roles
 3888: 	if ($key=~/^form\.rev/) {
 3889: 	    if ($key=~/^form\.rev\:([^\_]+)\_([^\_\.]+)$/) {
 3890: # Revoke standard role
 3891: 		my ($scope,$role) = ($1,$2);
 3892: 		my $result =
 3893: 		    &Apache::lonnet::revokerole($env{'form.ccdomain'},
 3894: 						$env{'form.ccuname'},
 3895: 						$scope,$role,'','',$context);
 3896:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
 3897:                             &mt('Revoking [_1] in [_2]',
 3898:                                 &Apache::lonnet::plaintext($role),
 3899:                                 &Apache::loncommon::show_role_extent($scope,$context,$role)),
 3900:                                 $result ne "ok").'<br />');
 3901:                 if ($result ne "ok") {
 3902:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 3903:                 }
 3904: 		if ($role eq 'st') {
 3905: 		    my $result = 
 3906:                         &Apache::lonuserutils::classlist_drop($scope,
 3907:                             $env{'form.ccuname'},$env{'form.ccdomain'},
 3908: 			    $now);
 3909:                     $r->print(&Apache::lonhtmlcommon::confirm_success($result));
 3910: 		}
 3911:                 if (!grep(/^\Q$role\E$/,@rolechanges)) {
 3912:                     push(@rolechanges,$role);
 3913:                 }
 3914: 	    }
 3915: 	    if ($key=~m{^form\.rev\:([^_]+)_cr\.cr/($match_domain)/($match_username)/(\w+)$}s) {
 3916: # Revoke custom role
 3917:                 my $result = &Apache::lonnet::revokecustomrole(
 3918:                     $env{'form.ccdomain'},$env{'form.ccuname'},$1,$2,$3,$4,'','',$context);
 3919:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
 3920:                             &mt('Revoking custom role [_1] by [_2] in [_3]',
 3921:                                 $4,$3.':'.$2,&Apache::loncommon::show_role_extent($1,$context,'cr')),
 3922:                             $result ne 'ok').'<br />');
 3923:                 if ($result ne "ok") {
 3924:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 3925:                 }
 3926:                 if (!grep(/^cr$/,@rolechanges)) {
 3927:                     push(@rolechanges,'cr');
 3928:                 }
 3929: 	    }
 3930: 	} elsif ($key=~/^form\.del/) {
 3931: 	    if ($key=~/^form\.del\:([^\_]+)\_([^\_\.]+)$/) {
 3932: # Delete standard role
 3933: 		my ($scope,$role) = ($1,$2);
 3934: 		my $result =
 3935: 		    &Apache::lonnet::assignrole($env{'form.ccdomain'},
 3936: 						$env{'form.ccuname'},
 3937: 						$scope,$role,$now,0,1,'',
 3938:                                                 $context);
 3939:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
 3940:                             &mt('Deleting [_1] in [_2]',
 3941:                                 &Apache::lonnet::plaintext($role),
 3942:                                 &Apache::loncommon::show_role_extent($scope,$context,$role)),
 3943:                             $result ne 'ok').'<br />');
 3944:                 if ($result ne "ok") {
 3945:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 3946:                 }
 3947: 
 3948: 		if ($role eq 'st') {
 3949: 		    my $result = 
 3950:                         &Apache::lonuserutils::classlist_drop($scope,
 3951:                             $env{'form.ccuname'},$env{'form.ccdomain'},
 3952: 			    $now);
 3953: 		    $r->print(&Apache::lonhtmlcommon::confirm_success($result));
 3954: 		}
 3955:                 if (!grep(/^\Q$role\E$/,@rolechanges)) {
 3956:                     push(@rolechanges,$role);
 3957:                 }
 3958:             }
 3959: 	    if ($key=~m{^form\.del\:([^_]+)_cr\.cr/($match_domain)/($match_username)/(\w+)$}) {
 3960:                 my ($url,$rdom,$rnam,$rolename) = ($1,$2,$3,$4);
 3961: # Delete custom role
 3962:                 my $result =
 3963:                     &Apache::lonnet::assigncustomrole($env{'form.ccdomain'},
 3964:                         $env{'form.ccuname'},$url,$rdom,$rnam,$rolename,$now,
 3965:                         0,1,$context);
 3966:                 $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('Deleting custom role [_1] by [_2] in [_3]',
 3967:                       $rolename,$rnam.':'.$rdom,&Apache::loncommon::show_role_extent($1,$context,'cr')),
 3968:                       $result ne "ok").'<br />');
 3969:                 if ($result ne "ok") {
 3970:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 3971:                 }
 3972: 
 3973:                 if (!grep(/^cr$/,@rolechanges)) {
 3974:                     push(@rolechanges,'cr');
 3975:                 }
 3976:             }
 3977: 	} elsif ($key=~/^form\.ren/) {
 3978:             my $udom = $env{'form.ccdomain'};
 3979:             my $uname = $env{'form.ccuname'};
 3980: # Re-enable standard role
 3981: 	    if ($key=~/^form\.ren\:([^\_]+)\_([^\_\.]+)$/) {
 3982:                 my $url = $1;
 3983:                 my $role = $2;
 3984:                 my $logmsg;
 3985:                 my $output;
 3986:                 if ($role eq 'st') {
 3987:                     if ($url =~ m-^/($match_domain)/($match_courseid)/?(\w*)$-) {
 3988:                         my ($cdom,$cnum,$csec) = ($1,$2,$3);
 3989:                         my $credits;
 3990:                         if ($showcredits) {
 3991:                             my $defaultcredits = 
 3992:                                 &Apache::lonuserutils::get_defaultcredits($cdom,$cnum);
 3993:                             $credits = &get_user_credits($defaultcredits,$cdom,$cnum);
 3994:                         }
 3995:                         my $result = &Apache::loncommon::commit_studentrole(\$logmsg,$udom,$uname,$url,$role,$now,0,$cdom,$cnum,$csec,$context,$credits);
 3996:                         if (($result =~ /^error/) || ($result eq 'not_in_class') || ($result eq 'unknown_course') || ($result eq 'refused')) {
 3997:                             if ($result eq 'refused' && $logmsg) {
 3998:                                 $output = $logmsg;
 3999:                             } else { 
 4000:                                 $output = &mt('Error: [_1]',$result)."\n";
 4001:                             }
 4002:                         } else {
 4003:                             $output = &Apache::lonhtmlcommon::confirm_success(&mt('Assigning [_1] in [_2] starting [_3]',
 4004:                                         &Apache::lonnet::plaintext($role),
 4005:                                         &Apache::loncommon::show_role_extent($url,$context,'st'),
 4006:                                         &Apache::lonlocal::locallocaltime($now))).'<br />'.$logmsg.'<br />';
 4007:                         }
 4008:                     }
 4009:                 } else {
 4010: 		    my $result=&Apache::lonnet::assignrole($env{'form.ccdomain'},
 4011:                                $env{'form.ccuname'},$url,$role,0,$now,'','',
 4012:                                $context);
 4013:                         $output = &Apache::lonhtmlcommon::confirm_success(&mt('Re-enabling [_1] in [_2]',
 4014:                                         &Apache::lonnet::plaintext($role),
 4015:                                         &Apache::loncommon::show_role_extent($url,$context,$role)),$result ne "ok").'<br />';
 4016:                     if ($result ne "ok") {
 4017:                         $output .= &mt('Error: [_1]',$result).'<br />';
 4018:                     }
 4019:                 }
 4020:                 $r->print($output);
 4021:                 if (!grep(/^\Q$role\E$/,@rolechanges)) {
 4022:                     push(@rolechanges,$role);
 4023:                 }
 4024: 	    }
 4025: # Re-enable custom role
 4026: 	    if ($key=~m{^form\.ren\:([^_]+)_cr\.cr/($match_domain)/($match_username)/(\w+)$}) {
 4027:                 my ($url,$rdom,$rnam,$rolename) = ($1,$2,$3,$4);
 4028:                 my $result = &Apache::lonnet::assigncustomrole(
 4029:                                $env{'form.ccdomain'}, $env{'form.ccuname'},
 4030:                                $url,$rdom,$rnam,$rolename,0,$now,undef,$context);
 4031:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
 4032:                     &mt('Re-enabling custom role [_1] by [_2] in [_3]',
 4033:                         $rolename,$rnam.':'.$rdom,&Apache::loncommon::show_role_extent($1,$context,'cr')),
 4034:                     $result ne "ok").'<br />');
 4035:                 if ($result ne "ok") {
 4036:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 4037:                 }
 4038:                 if (!grep(/^cr$/,@rolechanges)) {
 4039:                     push(@rolechanges,'cr');
 4040:                 }
 4041:             }
 4042: 	} elsif ($key=~/^form\.act/) {
 4043:             my $udom = $env{'form.ccdomain'};
 4044:             my $uname = $env{'form.ccuname'};
 4045: 	    if ($key=~/^form\.act\_($match_domain)\_($match_courseid)\_cr_cr_($match_domain)_($match_username)_([^\_]+)$/) {
 4046:                 # Activate a custom role
 4047: 		my ($one,$two,$three,$four,$five)=($1,$2,$3,$4,$5);
 4048: 		my $url='/'.$one.'/'.$two;
 4049: 		my $full=$one.'_'.$two.'_cr_cr_'.$three.'_'.$four.'_'.$five;
 4050: 
 4051:                 my $start = ( $env{'form.start_'.$full} ?
 4052:                               $env{'form.start_'.$full} :
 4053:                               $now );
 4054:                 my $end   = ( $env{'form.end_'.$full} ?
 4055:                               $env{'form.end_'.$full} :
 4056:                               0 );
 4057:                                                                                      
 4058:                 # split multiple sections
 4059:                 my %sections = ();
 4060:                 my $num_sections = &build_roles($env{'form.sec_'.$full},\%sections,$5);
 4061:                 if ($num_sections == 0) {
 4062:                     $r->print(&Apache::loncommon::commit_customrole($udom,$uname,$url,$three,$four,$five,$start,$end,$context));
 4063:                 } else {
 4064: 		    my %curr_groups =
 4065: 			&Apache::longroup::coursegroups($one,$two);
 4066:                     foreach my $sec (sort {$a cmp $b} keys(%sections)) {
 4067:                         if (($sec eq 'none') || ($sec eq 'all') || 
 4068:                             exists($curr_groups{$sec})) {
 4069:                             $disallowed{$sec} = $url;
 4070:                             next;
 4071:                         }
 4072:                         my $securl = $url.'/'.$sec;
 4073: 		        $r->print(&Apache::loncommon::commit_customrole($udom,$uname,$securl,$three,$four,$five,$start,$end,$context));
 4074:                     }
 4075:                 }
 4076:                 if (!grep(/^cr$/,@rolechanges)) {
 4077:                     push(@rolechanges,'cr');
 4078:                 }
 4079: 	    } elsif ($key=~/^form\.act\_($match_domain)\_($match_name)\_([^\_]+)$/) {
 4080: 		# Activate roles for sections with 3 id numbers
 4081: 		# set start, end times, and the url for the class
 4082: 		my ($one,$two,$three)=($1,$2,$3);
 4083: 		my $start = ( $env{'form.start_'.$one.'_'.$two.'_'.$three} ? 
 4084: 			      $env{'form.start_'.$one.'_'.$two.'_'.$three} : 
 4085: 			      $now );
 4086: 		my $end   = ( $env{'form.end_'.$one.'_'.$two.'_'.$three} ? 
 4087: 			      $env{'form.end_'.$one.'_'.$two.'_'.$three} :
 4088: 			      0 );
 4089: 		my $url='/'.$one.'/'.$two;
 4090:                 my $type = 'three';
 4091:                 # split multiple sections
 4092:                 my %sections = ();
 4093:                 my $num_sections = &build_roles($env{'form.sec_'.$one.'_'.$two.'_'.$three},\%sections,$three);
 4094:                 my $credits;
 4095:                 if ($three eq 'st') {
 4096:                     if ($showcredits) { 
 4097:                         my $defaultcredits = 
 4098:                             &Apache::lonuserutils::get_defaultcredits($one,$two);
 4099:                         $credits = $env{'form.credits_'.$one.'_'.$two.'_'.$three};
 4100:                         $credits =~ s/[^\d\.]//g;
 4101:                         if ($credits eq $defaultcredits) {
 4102:                             undef($credits);
 4103:                         }
 4104:                     }
 4105:                 }
 4106:                 if ($num_sections == 0) {
 4107:                     $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$three,$start,$end,$one,$two,'',$context,$credits));
 4108:                 } else {
 4109:                     my %curr_groups = 
 4110: 			&Apache::longroup::coursegroups($one,$two);
 4111:                     my $emptysec = 0;
 4112:                     foreach my $sec (sort {$a cmp $b} keys(%sections)) {
 4113:                         $sec =~ s/\W//g;
 4114:                         if ($sec ne '') {
 4115:                             if (($sec eq 'none') || ($sec eq 'all') || 
 4116:                                 exists($curr_groups{$sec})) {
 4117:                                 $disallowed{$sec} = $url;
 4118:                                 next;
 4119:                             }
 4120:                             my $securl = $url.'/'.$sec;
 4121:                             $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$securl,$three,$start,$end,$one,$two,$sec,$context,$credits));
 4122:                         } else {
 4123:                             $emptysec = 1;
 4124:                         }
 4125:                     }
 4126:                     if ($emptysec) {
 4127:                         $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$three,$start,$end,$one,$two,'',$context,$credits));
 4128:                     }
 4129:                 }
 4130:                 if (!grep(/^\Q$three\E$/,@rolechanges)) {
 4131:                     push(@rolechanges,$three);
 4132:                 }
 4133: 	    } elsif ($key=~/^form\.act\_([^\_]+)\_([^\_]+)$/) {
 4134: 		# Activate roles for sections with two id numbers
 4135: 		# set start, end times, and the url for the class
 4136: 		my $start = ( $env{'form.start_'.$1.'_'.$2} ? 
 4137: 			      $env{'form.start_'.$1.'_'.$2} : 
 4138: 			      $now );
 4139: 		my $end   = ( $env{'form.end_'.$1.'_'.$2} ? 
 4140: 			      $env{'form.end_'.$1.'_'.$2} :
 4141: 			      0 );
 4142:                 my $one = $1;
 4143:                 my $two = $2;
 4144: 		my $url='/'.$one.'/';
 4145:                 # split multiple sections
 4146:                 my %sections = ();
 4147:                 my $num_sections = &build_roles($env{'form.sec_'.$one.'_'.$two},\%sections,$two);
 4148:                 if ($num_sections == 0) {
 4149:                     $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$two,$start,$end,$one,undef,'',$context));
 4150:                 } else {
 4151:                     my $emptysec = 0;
 4152:                     foreach my $sec (sort {$a cmp $b} keys(%sections)) {
 4153:                         if ($sec ne '') {
 4154:                             my $securl = $url.'/'.$sec;
 4155:                             $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$securl,$two,$start,$end,$one,undef,$sec,$context));
 4156:                         } else {
 4157:                             $emptysec = 1;
 4158:                         }
 4159:                     }
 4160:                     if ($emptysec) {
 4161:                         $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$two,$start,$end,$one,undef,'',$context));
 4162:                     }
 4163:                 }
 4164:                 if (!grep(/^\Q$two\E$/,@rolechanges)) {
 4165:                     push(@rolechanges,$two);
 4166:                 }
 4167: 	    } else {
 4168: 		$r->print('<p><span class="LC_error">'.&mt('ERROR').': '.&mt('Unknown command').' <tt>'.$key.'</tt></span></p><br />');
 4169:             }
 4170:             foreach my $key (sort(keys(%disallowed))) {
 4171:                 $r->print('<p class="LC_warning">');
 4172:                 if (($key eq 'none') || ($key eq 'all')) {  
 4173:                     $r->print(&mt('[_1] may not be used as the name for a section, as it is a reserved word.','<tt>'.$key.'</tt>'));
 4174:                 } else {
 4175:                     $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>'));
 4176:                 }
 4177:                 $r->print('</p><p>'
 4178:                          .&mt('Please [_1]go back[_2] and choose a different section name.'
 4179:                              ,'<a href="javascript:history.go(-1)'
 4180:                              ,'</a>')
 4181:                          .'</p><br />'
 4182:                 );
 4183:             }
 4184: 	}
 4185:     } # End of foreach (keys(%env))
 4186: # Flush the course logs so reverse user roles immediately updated
 4187:     $r->register_cleanup(\&Apache::lonnet::flushcourselogs);
 4188:     if (@rolechanges == 0) {
 4189:         $r->print('<p>'.&mt('No roles to modify').'</p>');
 4190:     }
 4191:     return @rolechanges;
 4192: }
 4193: 
 4194: sub get_user_credits {
 4195:     my ($uname,$udom,$defaultcredits,$cdom,$cnum) = @_;
 4196:     if ($cdom eq '' || $cnum eq '') {
 4197:         return unless ($env{'request.course.id'});
 4198:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4199:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4200:     }
 4201:     my $credits;
 4202:     my %currhash =
 4203:         &Apache::lonnet::get('classlist',[$uname.':'.$udom],$cdom,$cnum);
 4204:     if (keys(%currhash) > 0) {
 4205:         my @items = split(/:/,$currhash{$uname.':'.$udom});
 4206:         my $crdidx = &Apache::loncoursedata::CL_CREDITS() - 3;
 4207:         $credits = $items[$crdidx];
 4208:         $credits =~ s/[^\d\.]//g;
 4209:     }
 4210:     if ($credits eq $defaultcredits) {
 4211:         undef($credits);
 4212:     }
 4213:     return $credits;
 4214: }
 4215: 
 4216: sub enroll_single_student {
 4217:     my ($r,$uhome,$amode,$genpwd,$now,$newuser,$context,$crstype,
 4218:         $showcredits,$defaultcredits) = @_;
 4219:     $r->print('<h3>');
 4220:     if ($crstype eq 'Community') {
 4221:         $r->print(&mt('Enrolling Member'));
 4222:     } else {
 4223:         $r->print(&mt('Enrolling Student'));
 4224:     }
 4225:     $r->print('</h3>');
 4226: 
 4227:     # Remove non alphanumeric values from section
 4228:     $env{'form.sections'}=~s/\W//g;
 4229: 
 4230:     my $credits;
 4231:     if (($showcredits) && ($env{'form.credits'} ne '')) {
 4232:         $credits = $env{'form.credits'};
 4233:         $credits =~ s/[^\d\.]//g;
 4234:         if ($credits ne '') {
 4235:             if ($credits eq $defaultcredits) {
 4236:                 undef($credits);
 4237:             }
 4238:         }
 4239:     }
 4240: 
 4241:     # Clean out any old student roles the user has in this class.
 4242:     &Apache::lonuserutils::modifystudent($env{'form.ccdomain'},
 4243:          $env{'form.ccuname'},$env{'request.course.id'},undef,$uhome);
 4244:     my ($startdate,$enddate) = &Apache::lonuserutils::get_dates_from_form();
 4245:     my $enroll_result =
 4246:         &Apache::lonnet::modify_student_enrollment($env{'form.ccdomain'},
 4247:             $env{'form.ccuname'},$env{'form.cid'},$env{'form.cfirstname'},
 4248:             $env{'form.cmiddlename'},$env{'form.clastname'},
 4249:             $env{'form.generation'},$env{'form.sections'},$enddate,
 4250:             $startdate,'manual',undef,$env{'request.course.id'},'',$context,
 4251:             $credits);
 4252:     if ($enroll_result =~ /^ok/) {
 4253:         $r->print(&mt('[_1] enrolled','<b>'.$env{'form.ccuname'}.':'.$env{'form.ccdomain'}.'</b>'));
 4254:         if ($env{'form.sections'} ne '') {
 4255:             $r->print(' '.&mt('in section [_1]',$env{'form.sections'}));
 4256:         }
 4257:         my ($showstart,$showend);
 4258:         if ($startdate <= $now) {
 4259:             $showstart = &mt('Access starts immediately');
 4260:         } else {
 4261:             $showstart = &mt('Access starts: ').&Apache::lonlocal::locallocaltime($startdate);
 4262:         }
 4263:         if ($enddate == 0) {
 4264:             $showend = &mt('ends: no ending date');
 4265:         } else {
 4266:             $showend = &mt('ends: ').&Apache::lonlocal::locallocaltime($enddate);
 4267:         }
 4268:         $r->print('.<br />'.$showstart.'; '.$showend);
 4269:         if ($startdate <= $now && !$newuser) {
 4270:             $r->print('<p class="LC_info">');
 4271:             if ($crstype eq 'Community') {
 4272:                 $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.'));
 4273:             } else {
 4274:                 $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.'));
 4275:            }
 4276:            $r->print('</p>');
 4277:         }
 4278:     } else {
 4279:         $r->print(&mt('unable to enroll').": ".$enroll_result);
 4280:     }
 4281:     return;
 4282: }
 4283: 
 4284: sub get_defaultquota_text {
 4285:     my ($settingstatus) = @_;
 4286:     my $defquotatext; 
 4287:     if ($settingstatus eq '') {
 4288:         $defquotatext = &mt('default');
 4289:     } else {
 4290:         my ($usertypes,$order) =
 4291:             &Apache::lonnet::retrieve_inst_usertypes($env{'form.ccdomain'});
 4292:         if ($usertypes->{$settingstatus} eq '') {
 4293:             $defquotatext = &mt('default');
 4294:         } else {
 4295:             $defquotatext = &mt('default for [_1]',$usertypes->{$settingstatus});
 4296:         }
 4297:     }
 4298:     return $defquotatext;
 4299: }
 4300: 
 4301: sub update_result_form {
 4302:     my ($uhome) = @_;
 4303:     my $outcome = 
 4304:     '<form name="userupdate" method="post" action="">'."\n";
 4305:     foreach my $item ('srchby','srchin','srchtype','srchterm','srchdomain','ccuname','ccdomain') {
 4306:         $outcome .= '<input type="hidden" name="'.$item.'" value="'.$env{'form.'.$item}.'" />'."\n";
 4307:     }
 4308:     if ($env{'form.origname'} ne '') {
 4309:         $outcome .= '<input type="hidden" name="origname" value="'.$env{'form.origname'}.'" />'."\n";
 4310:     }
 4311:     foreach my $item ('sortby','seluname','seludom') {
 4312:         if (exists($env{'form.'.$item})) {
 4313:             $outcome .= '<input type="hidden" name="'.$item.'" value="'.$env{'form.'.$item}.'" />'."\n";
 4314:         }
 4315:     }
 4316:     if ($uhome eq 'no_host') {
 4317:         $outcome .= '<input type="hidden" name="forcenewuser" value="1" />'."\n";
 4318:     }
 4319:     $outcome .= '<input type="hidden" name="phase" value="" />'."\n".
 4320:                 '<input type="hidden" name="currstate" value="" />'."\n".
 4321:                 '<input type="hidden" name="action" value="'.$env{'form.action'}.'" />'."\n".
 4322:                 '</form>';
 4323:     return $outcome;
 4324: }
 4325: 
 4326: sub quota_admin {
 4327:     my ($setquota,$changeHash,$name) = @_;
 4328:     my $quotachanged;
 4329:     if (&Apache::lonnet::allowed('mpq',$env{'form.ccdomain'})) {
 4330:         # Current user has quota modification privileges
 4331:         if (ref($changeHash) eq 'HASH') {
 4332:             $quotachanged = 1;
 4333:             $changeHash->{$name.'quota'} = $setquota;
 4334:         }
 4335:     }
 4336:     return $quotachanged;
 4337: }
 4338: 
 4339: sub tool_admin {
 4340:     my ($tool,$settool,$changeHash,$context) = @_;
 4341:     my $canchange = 0; 
 4342:     if ($context eq 'requestcourses') {
 4343:         if (&Apache::lonnet::allowed('ccc',$env{'form.ccdomain'})) {
 4344:             $canchange = 1;
 4345:         }
 4346:     } elsif ($context eq 'reqcrsotherdom') {
 4347:         if (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) {
 4348:             $canchange = 1;
 4349:         }
 4350:     } elsif ($context eq 'requestauthor') {
 4351:         if (&Apache::lonnet::allowed('cau',$env{'request.role.domain'})) {
 4352:             $canchange = 1;
 4353:         }
 4354:     } elsif (&Apache::lonnet::allowed('mut',$env{'form.ccdomain'})) {
 4355:         # Current user has quota modification privileges
 4356:         $canchange = 1;
 4357:     }
 4358:     my $toolchanged;
 4359:     if ($canchange) {
 4360:         if (ref($changeHash) eq 'HASH') {
 4361:             $toolchanged = 1;
 4362:             if ($tool eq 'requestauthor') {
 4363:                 $changeHash->{$context} = $settool;
 4364:             } else {
 4365:                 $changeHash->{$context.'.'.$tool} = $settool;
 4366:             }
 4367:         }
 4368:     }
 4369:     return $toolchanged;
 4370: }
 4371: 
 4372: sub build_roles {
 4373:     my ($sectionstr,$sections,$role) = @_;
 4374:     my $num_sections = 0;
 4375:     if ($sectionstr=~ /,/) {
 4376:         my @secnums = split/,/,$sectionstr;
 4377:         if ($role eq 'st') {
 4378:             $secnums[0] =~ s/\W//g;
 4379:             $$sections{$secnums[0]} = 1;
 4380:             $num_sections = 1;
 4381:         } else {
 4382:             foreach my $sec (@secnums) {
 4383:                 $sec =~ ~s/\W//g;
 4384:                 if (!($sec eq "")) {
 4385:                     if (exists($$sections{$sec})) {
 4386:                         $$sections{$sec} ++;
 4387:                     } else {
 4388:                         $$sections{$sec} = 1;
 4389:                         $num_sections ++;
 4390:                     }
 4391:                 }
 4392:             }
 4393:         }
 4394:     } else {
 4395:         $sectionstr=~s/\W//g;
 4396:         unless ($sectionstr eq '') {
 4397:             $$sections{$sectionstr} = 1;
 4398:             $num_sections ++;
 4399:         }
 4400:     }
 4401: 
 4402:     return $num_sections;
 4403: }
 4404: 
 4405: # ========================================================== Custom Role Editor
 4406: 
 4407: sub custom_role_editor {
 4408:     my ($r,$context,$brcrum,$prefix,$permission) = @_;
 4409:     my $action = $env{'form.customroleaction'};
 4410:     my ($rolename,$helpitem);
 4411:     if ($action eq 'new') {
 4412:         $rolename=$env{'form.newrolename'};
 4413:     } else {
 4414:         $rolename=$env{'form.rolename'};
 4415:     }
 4416: 
 4417:     my ($crstype,$context);
 4418:     if ($env{'request.course.id'}) {
 4419:         $crstype = &Apache::loncommon::course_type();
 4420:         $context = 'course';
 4421:         $helpitem = 'Course_Editing_Custom_Roles';
 4422:     } else {
 4423:         $context = 'domain';
 4424:         $crstype = 'course';
 4425:         $helpitem = 'Domain_Editing_Custom_Roles';
 4426:     }
 4427: 
 4428:     $rolename=~s/[^A-Za-z0-9]//gs;
 4429:     if (!$rolename || $env{'form.phase'} eq 'pickrole') {
 4430: 	&print_username_entry_form($r,$context,undef,undef,undef,$crstype,$brcrum,
 4431:                                    $permission);
 4432:         return;
 4433:     }
 4434: 
 4435:     my $formname = 'form1';
 4436:     my %privs=();
 4437:     my $body_top = '<h2>';
 4438: # ------------------------------------------------------- Does this role exist?
 4439:     my ($rdummy,$roledef)=
 4440: 			 &Apache::lonnet::get('roles',["rolesdef_$rolename"]);
 4441:     if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 4442:         $body_top .= &mt('Existing Role').' "';
 4443: # ------------------------------------------------- Get current role privileges
 4444:         ($privs{'system'},$privs{'domain'},$privs{'course'})=split(/\_/,$roledef);
 4445:         if ($privs{'system'} =~ /bre\&S/) {
 4446:             if ($context eq 'domain') {
 4447:                 $crstype = 'Course';
 4448:             } elsif ($crstype eq 'Community') {
 4449:                 $privs{'system'} =~ s/bre\&S//;
 4450:             }
 4451:         } elsif ($context eq 'domain') {
 4452:             $crstype = 'Course';
 4453:         }
 4454:     } else {
 4455:         $body_top .= &mt('New Role').' "';
 4456:         $roledef='';
 4457:     }
 4458:     $body_top .= $rolename.'"</h2>';
 4459: 
 4460: # ------------------------------------------------------- What can be assigned?
 4461:     my %full=();
 4462:     my %levels=(
 4463:                  course => {},
 4464:                  domain => {},
 4465:                  system => {},
 4466:                );
 4467:     my %levelscurrent=(
 4468:                         course => {},
 4469:                         domain => {},
 4470:                         system => {},
 4471:                       );
 4472:     &Apache::lonuserutils::custom_role_privs(\%privs,\%full,\%levels,\%levelscurrent);
 4473:     my ($jsback,$elements) = &crumb_utilities();
 4474:     my @templateroles = &Apache::lonuserutils::custom_template_roles($context,$crstype);
 4475:     my $head_script =
 4476:         &Apache::lonuserutils::custom_roledefs_js($context,$crstype,$formname,
 4477:                                                   \%full,\@templateroles,$jsback);
 4478:     push (@{$brcrum},
 4479:               {href => "javascript:backPage(document.$formname,'pickrole','')",
 4480:                text => "Pick custom role",
 4481:                faq  => 282,bug=>'Instructor Interface',},
 4482:               {href => "javascript:backPage(document.$formname,'','')",
 4483:                text => "Edit custom role",
 4484:                faq  => 282,
 4485:                bug  => 'Instructor Interface',
 4486:                help => $helpitem}
 4487:               );
 4488:     my $args = { bread_crumbs          => $brcrum,
 4489:                  bread_crumbs_component => 'User Management'};
 4490:     $r->print(&Apache::loncommon::start_page('Custom Role Editor',
 4491:                                              $head_script,$args).
 4492:               $body_top);
 4493:     $r->print('<form name="'.$formname.'" method="post" action="">'."\n".
 4494:               &Apache::lonuserutils::custom_role_header($context,$crstype,
 4495:                                                         \@templateroles,$prefix));
 4496: 
 4497:     $r->print(<<ENDCCF);
 4498: <input type="hidden" name="phase" value="set_custom_roles" />
 4499: <input type="hidden" name="rolename" value="$rolename" />
 4500: ENDCCF
 4501:     $r->print(&Apache::lonuserutils::custom_role_table($crstype,\%full,\%levels,
 4502:                                                        \%levelscurrent,$prefix));
 4503:     $r->print(&Apache::loncommon::end_data_table().
 4504:    '<input type="hidden" name="action" value="'.$env{'form.action'}.'" />'.
 4505:    '<input type="hidden" name="startrolename" value="'.$env{'form.rolename'}.
 4506:    '" />'."\n".'<input type="hidden" name="currstate" value="" />'."\n".
 4507:    '<input type="reset" value="'.&mt("Reset").'" />'."\n".
 4508:    '<input type="submit" value="'.&mt('Save').'" /></form>');
 4509: }
 4510: 
 4511: # ---------------------------------------------------------- Call to definerole
 4512: sub set_custom_role {
 4513:     my ($r,$context,$brcrum,$prefix,$permission) = @_;
 4514:     my $rolename=$env{'form.rolename'};
 4515:     $rolename=~s/[^A-Za-z0-9]//gs;
 4516:     if (!$rolename) {
 4517: 	&custom_role_editor($r,$context,$brcrum,$prefix,$permission);
 4518:         return;
 4519:     }
 4520:     my ($jsback,$elements) = &crumb_utilities();
 4521:     my $jscript = '<script type="text/javascript">'
 4522:                  .'// <![CDATA['."\n"
 4523:                  .$jsback."\n"
 4524:                  .'// ]]>'."\n"
 4525:                  .'</script>'."\n";
 4526:     my $helpitem = 'Course_Editing_Custom_Roles';
 4527:     if ($context eq 'domain') {
 4528:         $helpitem = 'Domain_Editing_Custom_Roles';
 4529:     }
 4530:     push(@{$brcrum},
 4531:         {href => "javascript:backPage(document.customresult,'pickrole','')",
 4532:          text => "Pick custom role",
 4533:          faq  => 282,
 4534:          bug  => 'Instructor Interface',},
 4535:         {href => "javascript:backPage(document.customresult,'selected_custom_edit','')",
 4536:          text => "Edit custom role",
 4537:          faq  => 282,
 4538:          bug  => 'Instructor Interface',},
 4539:         {href => "javascript:backPage(document.customresult,'set_custom_roles','')",
 4540:          text => "Result",
 4541:          faq  => 282,
 4542:          bug  => 'Instructor Interface',
 4543:          help => $helpitem,}
 4544:         );
 4545:     my $args = { bread_crumbs           => $brcrum,
 4546:                  bread_crumbs_component => 'User Management'};
 4547:     $r->print(&Apache::loncommon::start_page('Save Custom Role',$jscript,$args));
 4548: 
 4549:     my $newrole;
 4550:     my ($rdummy,$roledef)=
 4551: 	&Apache::lonnet::get('roles',["rolesdef_$rolename"]);
 4552: 
 4553: # ------------------------------------------------------- Does this role exist?
 4554:     $r->print('<h3>');
 4555:     if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 4556: 	$r->print(&mt('Existing Role').' "');
 4557:     } else {
 4558: 	$r->print(&mt('New Role').' "');
 4559: 	$roledef='';
 4560:         $newrole = 1;
 4561:     }
 4562:     $r->print($rolename.'"</h3>');
 4563: # ------------------------------------------------- Assign role and show result
 4564: 
 4565:     my $errmsg;
 4566:     my %newprivs = &Apache::lonuserutils::custom_role_update($rolename,$prefix);
 4567:     # Assign role and return result
 4568:     my $result = &Apache::lonnet::definerole($rolename,$newprivs{'s'},$newprivs{'d'},
 4569:                                              $newprivs{'c'});
 4570:     if ($result ne 'ok') {
 4571:         $errmsg = ': '.$result;
 4572:     }
 4573:     my $message =
 4574:         &Apache::lonhtmlcommon::confirm_success(
 4575:             &mt('Defining Role').$errmsg, ($result eq 'ok' ? 0 : 1));
 4576:     if ($env{'request.course.id'}) {
 4577:         my $url='/'.$env{'request.course.id'};
 4578:         $url=~s/\_/\//g;
 4579:         $result =
 4580:             &Apache::lonnet::assigncustomrole(
 4581:                 $env{'user.domain'},$env{'user.name'},
 4582:                 $url,
 4583:                 $env{'user.domain'},$env{'user.name'},
 4584:                 $rolename,undef,undef,undef,$context);
 4585:         if ($result ne 'ok') {
 4586:             $errmsg = ': '.$result;
 4587:         }
 4588:         $message .=
 4589:             '<br />'
 4590:            .&Apache::lonhtmlcommon::confirm_success(
 4591:                 &mt('Assigning Role to Self').$errmsg, ($result eq 'ok' ? 0 : 1));
 4592:     }
 4593:     $r->print(
 4594:         &Apache::loncommon::confirmwrapper($message)
 4595:        .'<br />'
 4596:        .&Apache::lonhtmlcommon::actionbox([
 4597:             '<a href="javascript:backPage(document.customresult,'."'pickrole'".')">'
 4598:            .&mt('Create or edit another custom role')
 4599:            .'</a>'])
 4600:        .'<form name="customresult" method="post" action="">'
 4601:        .&Apache::lonhtmlcommon::echo_form_input([])
 4602:        .'</form>'
 4603:     );
 4604: }
 4605: 
 4606: # ================================================================ Main Handler
 4607: sub handler {
 4608:     my $r = shift;
 4609:     if ($r->header_only) {
 4610:        &Apache::loncommon::content_type($r,'text/html');
 4611:        $r->send_http_header;
 4612:        return OK;
 4613:     }
 4614:     my ($context,$crstype,$cid,$cnum,$cdom,$allhelpitems);
 4615: 
 4616:     if ($env{'request.course.id'}) {
 4617:         $context = 'course';
 4618:         $crstype = &Apache::loncommon::course_type();
 4619:     } elsif ($env{'request.role'} =~ /^au\./) {
 4620:         $context = 'author';
 4621:     } else {
 4622:         $context = 'domain';
 4623:     }
 4624: 
 4625:     my ($permission,$allowed) =
 4626:         &Apache::lonuserutils::get_permission($context,$crstype);
 4627: 
 4628:     if ($allowed) {
 4629:         my @allhelp;
 4630:         if ($context eq 'course') {
 4631:             $cid = $env{'request.course.id'};
 4632:             $cdom = $env{'course.'.$cid.'.domain'};
 4633:             $cnum = $env{'course.'.$cid.'.num'};
 4634: 
 4635:             if ($permission->{'cusr'}) {
 4636:                 push(@allhelp,'Course_Create_Class_List');
 4637:             }
 4638:             if ($permission->{'view'} || $permission->{'cusr'}) {
 4639:                 push(@allhelp,('Course_Change_Privileges','Course_View_Class_List'));
 4640:             }
 4641:             if ($permission->{'custom'}) {
 4642:                 push(@allhelp,'Course_Editing_Custom_Roles');
 4643:             }
 4644:             if ($permission->{'cusr'}) {
 4645:                 push(@allhelp,('Course_Add_Student','Course_Drop_Student'));
 4646:             }
 4647:             unless ($permission->{'cusr_section'}) {
 4648:                 if (&Apache::lonnet::auto_run($cnum,$cdom) && (($permission->{'cusr'}) || ($permission->{'view'}))) {
 4649:                     push(@allhelp,'Course_Automated_Enrollment');
 4650:                 }
 4651:                 if ($permission->{'selfenrolladmin'}) {
 4652:                     push(@allhelp,'Course_Approve_Selfenroll');
 4653:                 }
 4654:             }
 4655:             if ($permission->{'grp_manage'}) {
 4656:                 push(@allhelp,'Course_Manage_Group');
 4657:             }
 4658:             if ($permission->{'view'} || $permission->{'cusr'}) {
 4659:                 push(@allhelp,'Course_User_Logs');
 4660:             }
 4661:         } elsif ($context eq 'author') {
 4662:             push(@allhelp,('Author_Change_Privileges','Author_Create_Coauthor_List',
 4663:                            'Author_View_Coauthor_List','Author_User_Logs'));
 4664:         } else {
 4665:             if ($permission->{'cusr'}) {
 4666:                 push(@allhelp,'Domain_Change_Privileges');
 4667:                 if ($permission->{'activity'}) {
 4668:                     push(@allhelp,'Domain_User_Access_Logs');
 4669:                 }
 4670:                 push(@allhelp,('Domain_Create_Users','Domain_View_Users_List'));
 4671:                 if ($permission->{'custom'}) {
 4672:                     push(@allhelp,'Domain_Editing_Custom_Roles');
 4673:                 }
 4674:                 push(@allhelp,('Domain_Role_Approvals','Domain_Username_Approvals','Domain_Change_Logs'));
 4675:             } elsif ($permission->{'view'}) {
 4676:                 push(@allhelp,'Domain_View_Privileges');
 4677:                 if ($permission->{'activity'}) {
 4678:                     push(@allhelp,'Domain_User_Access_Logs');
 4679:                 }
 4680:                 push(@allhelp,('Domain_View_Users_List','Domain_Change_Logs'));
 4681:             }
 4682:         }
 4683:         if (@allhelp) {
 4684:             $allhelpitems = join(',',@allhelp);
 4685:         }
 4686:     }
 4687: 
 4688:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 4689:         ['action','state','callingform','roletype','showrole','bulkaction','popup','phase',
 4690:          'username','domain','srchterm','srchdomain','srchin','srchby','srchtype','queue']);
 4691:     &Apache::lonhtmlcommon::clear_breadcrumbs();
 4692:     my $args;
 4693:     my $brcrum = [];
 4694:     my $bread_crumbs_component = 'User Management';
 4695:     if (($env{'form.action'} ne 'dateselect') && ($env{'form.action'} ne 'displayuserreq')) {
 4696:         $brcrum = [{href=>"/adm/createuser",
 4697:                     text=>"User Management",
 4698:                     help=>$allhelpitems}
 4699:                   ];
 4700:     }
 4701:     if (!$allowed) {
 4702:         if ($context eq 'course') {
 4703:             $r->internal_redirect('/adm/viewclasslist');
 4704:             return OK;
 4705:         }
 4706:         $env{'user.error.msg'}=
 4707:             "/adm/createuser:cst:0:0:Cannot create/modify user data ".
 4708:                                  "or view user status.";
 4709:         return HTTP_NOT_ACCEPTABLE;
 4710:     }
 4711: 
 4712:     &Apache::loncommon::content_type($r,'text/html');
 4713:     $r->send_http_header;
 4714: 
 4715:     my $showcredits;
 4716:     if ((($context eq 'course') && ($crstype eq 'Course')) || 
 4717:          ($context eq 'domain')) {
 4718:         my %domdefaults = 
 4719:             &Apache::lonnet::get_domain_defaults($env{'request.role.domain'});
 4720:         if ($domdefaults{'officialcredits'} || $domdefaults{'unofficialcredits'}) {
 4721:             $showcredits = 1;
 4722:         }
 4723:     }
 4724: 
 4725:     # Main switch on form.action and form.state, as appropriate
 4726:     if (! exists($env{'form.action'})) {
 4727:         $args = {bread_crumbs => $brcrum,
 4728:                  bread_crumbs_component => $bread_crumbs_component}; 
 4729:         $r->print(&header(undef,$args));
 4730:         $r->print(&print_main_menu($permission,$context,$crstype));
 4731:     } elsif ($env{'form.action'} eq 'upload' && $permission->{'cusr'}) {
 4732:         my $helpitem = 'Course_Create_Class_List';
 4733:         if ($context eq 'author') {
 4734:             $helpitem = 'Author_Create_Coauthor_List';
 4735:         } elsif ($context eq 'domain') {
 4736:             $helpitem = 'Domain_Create_Users';
 4737:         }
 4738:         push(@{$brcrum},
 4739:               { href => '/adm/createuser?action=upload&state=',
 4740:                 text => 'Upload Users List',
 4741:                 help => $helpitem,
 4742:               });
 4743:         $bread_crumbs_component = 'Upload Users List';
 4744:         $args = {bread_crumbs           => $brcrum,
 4745:                  bread_crumbs_component => $bread_crumbs_component};
 4746:         $r->print(&header(undef,$args));
 4747:         $r->print('<form name="studentform" method="post" '.
 4748:                   'enctype="multipart/form-data" '.
 4749:                   ' action="/adm/createuser">'."\n");
 4750:         if (! exists($env{'form.state'})) {
 4751:             &Apache::lonuserutils::print_first_users_upload_form($r,$context);
 4752:         } elsif ($env{'form.state'} eq 'got_file') {
 4753:             &Apache::lonuserutils::print_upload_manager_form($r,$context,$permission,
 4754:                                                              $crstype,$showcredits);
 4755:         } elsif ($env{'form.state'} eq 'enrolling') {
 4756:             if ($env{'form.datatoken'}) {
 4757:                 &Apache::lonuserutils::upfile_drop_add($r,$context,$permission,
 4758:                                                        $showcredits);
 4759:             }
 4760:         } else {
 4761:             &Apache::lonuserutils::print_first_users_upload_form($r,$context);
 4762:         }
 4763:     } elsif (((($env{'form.action'} eq 'singleuser') || ($env{'form.action'}
 4764:               eq 'singlestudent')) && ($permission->{'cusr'})) ||
 4765:              (($env{'form.action'} eq 'singleuser') && ($permission->{'view'})) ||
 4766:              (($env{'form.action'} eq 'accesslogs') && ($permission->{'activity'}))) {
 4767:         my $phase = $env{'form.phase'};
 4768:         my @search = ('srchterm','srchby','srchin','srchtype','srchdomain');
 4769: 	&Apache::loncreateuser::restore_prev_selections();
 4770: 	my $srch;
 4771: 	foreach my $item (@search) {
 4772: 	    $srch->{$item} = $env{'form.'.$item};
 4773: 	}
 4774:         if (($phase eq 'get_user_info') || ($phase eq 'userpicked') ||
 4775:             ($phase eq 'createnewuser') || ($phase eq 'activity')) {
 4776:             if ($env{'form.phase'} eq 'createnewuser') {
 4777:                 my $response;
 4778:                 if ($env{'form.srchterm'} !~ /^$match_username$/) {
 4779:                     my $response =
 4780:                         '<span class="LC_warning">'
 4781:                        .&mt('You must specify a valid username. Only the following are allowed:'
 4782:                            .' letters numbers - . @')
 4783:                        .'</span>';
 4784:                     $env{'form.phase'} = '';
 4785:                     &print_username_entry_form($r,$context,$response,$srch,undef,
 4786:                                                $crstype,$brcrum,$permission);
 4787:                 } else {
 4788:                     my $ccuname =&LONCAPA::clean_username($srch->{'srchterm'});
 4789:                     my $ccdomain=&LONCAPA::clean_domain($srch->{'srchdomain'});
 4790:                     &print_user_modification_page($r,$ccuname,$ccdomain,
 4791:                                                   $srch,$response,$context,
 4792:                                                   $permission,$crstype,$brcrum,
 4793:                                                   $showcredits);
 4794:                 }
 4795:             } elsif ($env{'form.phase'} eq 'get_user_info') {
 4796:                 my ($currstate,$response,$forcenewuser,$results) = 
 4797:                     &user_search_result($context,$srch);
 4798:                 if ($env{'form.currstate'} eq 'modify') {
 4799:                     $currstate = $env{'form.currstate'};
 4800:                 }
 4801:                 if ($currstate eq 'select') {
 4802:                     &print_user_selection_page($r,$response,$srch,$results,
 4803:                                                \@search,$context,undef,$crstype,
 4804:                                                $brcrum);
 4805:                 } elsif (($currstate eq 'modify') || ($env{'form.action'} eq 'accesslogs')) {
 4806:                     my ($ccuname,$ccdomain,$uhome);
 4807:                     if (($srch->{'srchby'} eq 'uname') && 
 4808:                         ($srch->{'srchtype'} eq 'exact')) {
 4809:                         $ccuname = $srch->{'srchterm'};
 4810:                         $ccdomain= $srch->{'srchdomain'};
 4811:                     } else {
 4812:                         my @matchedunames = keys(%{$results});
 4813:                         ($ccuname,$ccdomain) = split(/:/,$matchedunames[0]);
 4814:                     }
 4815:                     $ccuname =&LONCAPA::clean_username($ccuname);
 4816:                     $ccdomain=&LONCAPA::clean_domain($ccdomain);
 4817:                     if ($env{'form.action'} eq 'accesslogs') {
 4818:                         my $uhome;
 4819:                         if (($ccuname ne '') && ($ccdomain ne '')) {
 4820:                            $uhome = &Apache::lonnet::homeserver($ccuname,$ccdomain);
 4821:                         }
 4822:                         if (($uhome eq '') || ($uhome eq 'no_host')) {
 4823:                             $env{'form.phase'} = '';
 4824:                             undef($forcenewuser);
 4825:                             #if ($response) {
 4826:                             #    unless ($response =~ m{\Q<br /><br />\E$}) {
 4827:                             #        $response .= '<br /><br />';
 4828:                             #    }
 4829:                             #}
 4830:                             &print_username_entry_form($r,$context,$response,$srch,
 4831:                                                        $forcenewuser,$crstype,$brcrum,
 4832:                                                        $permission);
 4833:                         } else {
 4834:                             &print_useraccesslogs_display($r,$ccuname,$ccdomain,$permission,$brcrum);
 4835:                         }
 4836:                     } else {
 4837:                         if ($env{'form.forcenewuser'}) {
 4838:                             $response = '';
 4839:                         }
 4840:                         &print_user_modification_page($r,$ccuname,$ccdomain,
 4841:                                                       $srch,$response,$context,
 4842:                                                       $permission,$crstype,$brcrum);
 4843:                     }
 4844:                 } elsif ($currstate eq 'query') {
 4845:                     &print_user_query_page($r,'createuser',$brcrum);
 4846:                 } else {
 4847:                     $env{'form.phase'} = '';
 4848:                     &print_username_entry_form($r,$context,$response,$srch,
 4849:                                                $forcenewuser,$crstype,$brcrum,
 4850:                                                $permission);
 4851:                 }
 4852:             } elsif ($env{'form.phase'} eq 'userpicked') {
 4853:                 my $ccuname = &LONCAPA::clean_username($env{'form.seluname'});
 4854:                 my $ccdomain = &LONCAPA::clean_domain($env{'form.seludom'});
 4855:                 if ($env{'form.action'} eq 'accesslogs') {
 4856:                     &print_useraccesslogs_display($r,$ccuname,$ccdomain,$permission,$brcrum);
 4857:                 } else {
 4858:                     &print_user_modification_page($r,$ccuname,$ccdomain,$srch,'',
 4859:                                                   $context,$permission,$crstype,
 4860:                                                   $brcrum);
 4861:                 }
 4862:             } elsif ($env{'form.action'} eq 'accesslogs') {
 4863:                 my $ccuname = &LONCAPA::clean_username($env{'form.accessuname'});
 4864:                 my $ccdomain = &LONCAPA::clean_domain($env{'form.accessudom'});
 4865:                 &print_useraccesslogs_display($r,$ccuname,$ccdomain,$permission,$brcrum);
 4866:             }
 4867:         } elsif ($env{'form.phase'} eq 'update_user_data') {
 4868:             &update_user_data($r,$context,$crstype,$brcrum,$showcredits);
 4869:         } else {
 4870:             &print_username_entry_form($r,$context,undef,$srch,undef,$crstype,
 4871:                                        $brcrum,$permission);
 4872:         }
 4873:     } elsif ($env{'form.action'} eq 'custom' && $permission->{'custom'}) {
 4874:         my $prefix;
 4875:         if ($env{'form.phase'} eq 'set_custom_roles') {
 4876:             &set_custom_role($r,$context,$brcrum,$prefix,$permission);
 4877:         } else {
 4878:             &custom_role_editor($r,$context,$brcrum,$prefix,$permission);
 4879:         }
 4880:     } elsif (($env{'form.action'} eq 'processauthorreq') &&
 4881:              ($permission->{'cusr'}) && 
 4882:              (&Apache::lonnet::allowed('cau',$env{'request.role.domain'}))) {
 4883:         push(@{$brcrum},
 4884:                  {href => '/adm/createuser?action=processauthorreq',
 4885:                   text => 'Authoring Space requests',
 4886:                   help => 'Domain_Role_Approvals'});
 4887:         $bread_crumbs_component = 'Authoring requests';
 4888:         if ($env{'form.state'} eq 'done') {
 4889:             push(@{$brcrum},
 4890:                      {href => '/adm/createuser?action=authorreqqueue',
 4891:                       text => 'Result',
 4892:                       help => 'Domain_Role_Approvals'});
 4893:             $bread_crumbs_component = 'Authoring request result';
 4894:         }
 4895:         $args = { bread_crumbs           => $brcrum,
 4896:                   bread_crumbs_component => $bread_crumbs_component};
 4897:         my $js = &usernamerequest_javascript();
 4898:         $r->print(&header(&add_script($js),$args));
 4899:         if (!exists($env{'form.state'})) {
 4900:             $r->print(&Apache::loncoursequeueadmin::display_queued_requests('requestauthor',
 4901:                                                                             $env{'request.role.domain'}));
 4902:         } elsif ($env{'form.state'} eq 'done') {
 4903:             $r->print('<h3>'.&mt('Authoring request processing').'</h3>'."\n");
 4904:             $r->print(&Apache::loncoursequeueadmin::update_request_queue('requestauthor',
 4905:                                                                          $env{'request.role.domain'}));
 4906:         }
 4907:     } elsif (($env{'form.action'} eq 'processusernamereq') &&
 4908:              ($permission->{'cusr'}) &&
 4909:              (&Apache::lonnet::allowed('cau',$env{'request.role.domain'}))) {
 4910:         push(@{$brcrum},
 4911:                  {href => '/adm/createuser?action=processusernamereq',
 4912:                   text => 'LON-CAPA account requests',
 4913:                   help => 'Domain_Username_Approvals'});
 4914:         $bread_crumbs_component = 'Account requests';
 4915:         if ($env{'form.state'} eq 'done') {
 4916:             push(@{$brcrum},
 4917:                      {href => '/adm/createuser?action=usernamereqqueue',
 4918:                       text => 'Result',
 4919:                       help => 'Domain_Username_Approvals'});
 4920:             $bread_crumbs_component = 'LON-CAPA account request result';
 4921:         }
 4922:         $args = { bread_crumbs           => $brcrum,
 4923:                   bread_crumbs_component => $bread_crumbs_component};
 4924:         my $js = &usernamerequest_javascript();
 4925:         $r->print(&header(&add_script($js),$args));
 4926:         if (!exists($env{'form.state'})) {
 4927:             $r->print(&Apache::loncoursequeueadmin::display_queued_requests('requestusername',
 4928:                                                                             $env{'request.role.domain'}));
 4929:         } elsif ($env{'form.state'} eq 'done') {
 4930:             $r->print('<h3>'.&mt('LON-CAPA account request processing').'</h3>'."\n");
 4931:             $r->print(&Apache::loncoursequeueadmin::update_request_queue('requestusername',
 4932:                                                                          $env{'request.role.domain'}));
 4933:         }
 4934:     } elsif (($env{'form.action'} eq 'displayuserreq') &&
 4935:              ($permission->{'cusr'})) {
 4936:         my $dom = $env{'form.domain'};
 4937:         my $uname = $env{'form.username'};
 4938:         my $warning;
 4939:         if (($dom =~ /^$match_domain$/) && (&Apache::lonnet::domain($dom) ne '')) {
 4940:             if (($dom eq $env{'request.role.domain'}) && (&Apache::lonnet::allowed('ccc',$dom))) {
 4941:                 if (($uname =~ /^$match_username$/) && ($env{'form.queue'} eq 'approval')) {
 4942:                     my $uhome = &Apache::lonnet::homeserver($uname,$dom);
 4943:                     if ($uhome eq 'no_host') {
 4944:                         my $queue = $env{'form.queue'};
 4945:                         my $reqkey = &escape($uname).'_'.$queue; 
 4946:                         my $namespace = 'usernamequeue';
 4947:                         my $domconfig = &Apache::lonnet::get_domainconfiguser($dom);
 4948:                         my %queued =
 4949:                             &Apache::lonnet::get($namespace,[$reqkey],$dom,$domconfig);
 4950:                         unless ($queued{$reqkey}) {
 4951:                             $warning = &mt('No information was found for this LON-CAPA account request.');
 4952:                         }
 4953:                     } else {
 4954:                         $warning = &mt('A LON-CAPA account already exists for the requested username and domain.');
 4955:                     }
 4956:                 } else {
 4957:                     $warning = &mt('LON-CAPA account request status check is for an invalid username.');
 4958:                 }
 4959:             } else {
 4960:                 $warning = &mt('You do not have rights to view LON-CAPA account requests in the domain specified.');
 4961:             }
 4962:         } else {
 4963:             $warning = &mt('LON-CAPA account request status check is for an invalid domain.');
 4964:         }
 4965:         my $args = { only_body => 1 };
 4966:         $r->print(&header(undef,$args).
 4967:                   '<h3>'.&mt('LON-CAPA Account Request Details').'</h3>');
 4968:         if ($warning ne '') {
 4969:             $r->print('<div class="LC_warning">'.$warning.'</div>');
 4970:         } else {
 4971:             my ($infofields,$infotitles) = &Apache::loncommon::emailusername_info();
 4972:             my $domconfiguser = &Apache::lonnet::get_domainconfiguser($dom);
 4973:             my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 4974:             if (ref($domconfig{'usercreation'}) eq 'HASH') {
 4975:                 if (ref($domconfig{'usercreation'}{'cancreate'}) eq 'HASH') {
 4976:                     if (ref($domconfig{'usercreation'}{'cancreate'}{'emailusername'}) eq 'HASH') {
 4977:                         my %info =
 4978:                             &Apache::lonnet::get('nohist_requestedusernames',[$uname],$dom,$domconfiguser);
 4979:                         if (ref($info{$uname}) eq 'HASH') {
 4980:                             my $usertype = $info{$uname}{'inststatus'};
 4981:                             unless ($usertype) {
 4982:                                 $usertype = 'default';
 4983:                             }
 4984:                             my ($showstatus,$showemail,$pickstart);
 4985:                             my $numextras = 0;
 4986:                             my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 4987:                             if ((ref($types) eq 'ARRAY') && (@{$types} > 0)) {
 4988:                                 if (ref($usertypes) eq 'HASH') {
 4989:                                     if ($usertypes->{$usertype}) {
 4990:                                         $showstatus = $usertypes->{$usertype};
 4991:                                     } else {
 4992:                                         $showstatus = $othertitle;
 4993:                                     }
 4994:                                     if ($showstatus) {
 4995:                                         $numextras ++;
 4996:                                     }
 4997:                                 }
 4998:                             }
 4999:                             if (($info{$uname}{'email'} ne '') && ($info{$uname}{'email'} ne $uname)) {
 5000:                                 $showemail = $info{$uname}{'email'};
 5001:                                 $numextras ++;
 5002:                             }
 5003:                             if (ref($domconfig{'usercreation'}{'cancreate'}{'emailusername'}{$usertype}) eq 'HASH') {
 5004:                                 if ((ref($infofields) eq 'ARRAY') && (ref($infotitles) eq 'HASH')) {
 5005:                                     $pickstart = 1;
 5006:                                     $r->print('<div>'.&Apache::lonhtmlcommon::start_pick_box());
 5007:                                     my ($num,$count);
 5008:                                     $count = scalar(keys(%{$domconfig{'usercreation'}{'cancreate'}{'emailusername'}{$usertype}}));
 5009:                                     $count += $numextras;
 5010:                                     foreach my $field (@{$infofields}) {
 5011:                                         next unless ($domconfig{'usercreation'}{'cancreate'}{'emailusername'}{$usertype}{$field});
 5012:                                         next unless ($infotitles->{$field});
 5013:                                         $r->print(&Apache::lonhtmlcommon::row_title($infotitles->{$field}).
 5014:                                                   $info{$uname}{$field});
 5015:                                         $num ++;
 5016:                                         unless ($count == $num) {
 5017:                                             $r->print(&Apache::lonhtmlcommon::row_closure());
 5018:                                         }
 5019:                                     }
 5020:                                 }
 5021:                             }
 5022:                             if ($numextras) {
 5023:                                 unless ($pickstart) {
 5024:                                     $r->print('<div>'.&Apache::lonhtmlcommon::start_pick_box());
 5025:                                     $pickstart = 1;
 5026:                                 }
 5027:                                 if ($showemail) {
 5028:                                     my $closure = '';
 5029:                                     unless ($showstatus) {
 5030:                                         $closure = 1;
 5031:                                     }
 5032:                                     $r->print(&Apache::lonhtmlcommon::row_title(&mt('E-mail address')).
 5033:                                               $showemail.
 5034:                                               &Apache::lonhtmlcommon::row_closure($closure));
 5035:                                 }
 5036:                                 if ($showstatus) {
 5037:                                     $r->print(&Apache::lonhtmlcommon::row_title(&mt('Status type[_1](self-reported)','<br />')).
 5038:                                               $showstatus.
 5039:                                               &Apache::lonhtmlcommon::row_closure(1));
 5040:                                 }
 5041:                             }
 5042:                             if ($pickstart) { 
 5043:                                 $r->print(&Apache::lonhtmlcommon::end_pick_box().'</div>');
 5044:                             } else {
 5045:                                 $r->print('<div>'.&mt('No information to display for this account request.').'</div>');
 5046:                             }
 5047:                         } else {
 5048:                             $r->print('<div>'.&mt('No information available for this account request.').'</div>');
 5049:                         }
 5050:                     }
 5051:                 }
 5052:             }
 5053:         }
 5054:         $r->print(&close_popup_form());
 5055:     } elsif (($env{'form.action'} eq 'listusers') && 
 5056:              ($permission->{'view'} || $permission->{'cusr'})) {
 5057:         my $helpitem = 'Course_View_Class_List';
 5058:         if ($context eq 'author') {
 5059:             $helpitem = 'Author_View_Coauthor_List';
 5060:         } elsif ($context eq 'domain') {
 5061:             $helpitem = 'Domain_View_Users_List';
 5062:         }
 5063:         if ($env{'form.phase'} eq 'bulkchange') {
 5064:             push(@{$brcrum},
 5065:                     {href => '/adm/createuser?action=listusers',
 5066:                      text => "List Users"},
 5067:                     {href => "/adm/createuser",
 5068:                      text => "Result",
 5069:                      help => $helpitem});
 5070:             $bread_crumbs_component = 'Update Users';
 5071:             $args = {bread_crumbs           => $brcrum,
 5072:                      bread_crumbs_component => $bread_crumbs_component};
 5073:             $r->print(&header(undef,$args));
 5074:             my $setting = $env{'form.roletype'};
 5075:             my $choice = $env{'form.bulkaction'};
 5076:             if ($permission->{'cusr'}) {
 5077:                 &Apache::lonuserutils::update_user_list($r,$context,$setting,$choice,$crstype);
 5078:             } else {
 5079:                 $r->print(&mt('You are not authorized to make bulk changes to user roles'));
 5080:                 $r->print('<p><a href="/adm/createuser?action=listusers">'.&mt('Display User Lists').'</a>');
 5081:             }
 5082:         } else {
 5083:             push(@{$brcrum},
 5084:                     {href => '/adm/createuser?action=listusers',
 5085:                      text => "List Users",
 5086:                      help => $helpitem});
 5087:             $bread_crumbs_component = 'List Users';
 5088:             $args = {bread_crumbs           => $brcrum,
 5089:                      bread_crumbs_component => $bread_crumbs_component};
 5090:             my ($cb_jscript,$jscript,$totcodes,$codetitles,$idlist,$idlist_titles);
 5091:             my $formname = 'studentform';
 5092:             my $hidecall = "hide_searching();";
 5093:             if (($context eq 'domain') && (($env{'form.roletype'} eq 'course') ||
 5094:                 ($env{'form.roletype'} eq 'community'))) {
 5095:                 if ($env{'form.roletype'} eq 'course') {
 5096:                     ($cb_jscript,$jscript,$totcodes,$codetitles,$idlist,$idlist_titles) = 
 5097:                         &Apache::lonuserutils::courses_selector($env{'request.role.domain'},
 5098:                                                                 $formname);
 5099:                 } elsif ($env{'form.roletype'} eq 'community') {
 5100:                     $cb_jscript = 
 5101:                         &Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'});
 5102:                     my %elements = (
 5103:                                       coursepick => 'radio',
 5104:                                       coursetotal => 'text',
 5105:                                       courselist => 'text',
 5106:                                    );
 5107:                     $jscript = &Apache::lonhtmlcommon::set_form_elements(\%elements);
 5108:                 }
 5109:                 $jscript .= &verify_user_display($context)."\n".
 5110:                             &Apache::loncommon::check_uncheck_jscript();
 5111:                 my $js = &add_script($jscript).$cb_jscript;
 5112:                 my $loadcode = 
 5113:                     &Apache::lonuserutils::course_selector_loadcode($formname);
 5114:                 if ($loadcode ne '') {
 5115:                     $args->{add_entries} = {onload => "$loadcode;$hidecall"};
 5116:                 } else {
 5117:                     $args->{add_entries} = {onload => $hidecall};
 5118:                 }
 5119:                 $r->print(&header($js,$args));
 5120:             } else {
 5121:                 $args->{add_entries} = {onload => $hidecall};
 5122:                 $jscript = &verify_user_display($context).
 5123:                            &Apache::loncommon::check_uncheck_jscript(); 
 5124:                 $r->print(&header(&add_script($jscript),$args));
 5125:             }
 5126:             &Apache::lonuserutils::print_userlist($r,undef,$permission,$context,
 5127:                          $formname,$totcodes,$codetitles,$idlist,$idlist_titles,
 5128:                          $showcredits);
 5129:         }
 5130:     } elsif ($env{'form.action'} eq 'drop' && $permission->{'cusr'}) {
 5131:         my $brtext;
 5132:         if ($crstype eq 'Community') {
 5133:             $brtext = 'Drop Members';
 5134:         } else {
 5135:             $brtext = 'Drop Students';
 5136:         }
 5137:         push(@{$brcrum},
 5138:                 {href => '/adm/createuser?action=drop',
 5139:                  text => $brtext,
 5140:                  help => 'Course_Drop_Student'});
 5141:         if ($env{'form.state'} eq 'done') {
 5142:             push(@{$brcrum},
 5143:                      {href=>'/adm/createuser?action=drop',
 5144:                       text=>"Result"});
 5145:         }
 5146:         $bread_crumbs_component = $brtext;
 5147:         $args = {bread_crumbs           => $brcrum,
 5148:                  bread_crumbs_component => $bread_crumbs_component}; 
 5149:         $r->print(&header(undef,$args));
 5150:         if (!exists($env{'form.state'})) {
 5151:             &Apache::lonuserutils::print_drop_menu($r,$context,$permission,$crstype);
 5152:         } elsif ($env{'form.state'} eq 'done') {
 5153:             &Apache::lonuserutils::update_user_list($r,$context,undef,
 5154:                                                     $env{'form.action'});
 5155:         }
 5156:     } elsif ($env{'form.action'} eq 'dateselect') {
 5157:         if ($permission->{'cusr'}) {
 5158:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 5159:                       &Apache::lonuserutils::date_section_selector($context,$permission,
 5160:                                                                    $crstype,$showcredits));
 5161:         } else {
 5162:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 5163:                      '<span class="LC_error">'.&mt('You do not have permission to modify dates or sections for users').'</span>'); 
 5164:         }
 5165:     } elsif ($env{'form.action'} eq 'selfenroll') {
 5166:         if ($permission->{selfenrolladmin}) {
 5167:             my %currsettings = (
 5168:                 selfenroll_types              => $env{'course.'.$cid.'.internal.selfenroll_types'},
 5169:                 selfenroll_registered         => $env{'course.'.$cid.'.internal.selfenroll_registered'},
 5170:                 selfenroll_section            => $env{'course.'.$cid.'.internal.selfenroll_section'},
 5171:                 selfenroll_notifylist         => $env{'course.'.$cid.'.internal.selfenroll_notifylist'},
 5172:                 selfenroll_approval           => $env{'course.'.$cid.'.internal.selfenroll_approval'},
 5173:                 selfenroll_limit              => $env{'course.'.$cid.'.internal.selfenroll_limit'},
 5174:                 selfenroll_cap                => $env{'course.'.$cid.'.internal.selfenroll_cap'},
 5175:                 selfenroll_start_date         => $env{'course.'.$cid.'.internal.selfenroll_start_date'},
 5176:                 selfenroll_end_date           => $env{'course.'.$cid.'.internal.selfenroll_end_date'},
 5177:                 selfenroll_start_access       => $env{'course.'.$cid.'.internal.selfenroll_start_access'},
 5178:                 selfenroll_end_access         => $env{'course.'.$cid.'.internal.selfenroll_end_access'},
 5179:                 default_enrollment_start_date => $env{'course.'.$cid.'.default_enrollment_start_date'},
 5180:                 default_enrollment_end_date   => $env{'course.'.$cid.'.default_enrollment_end_date'},
 5181:                 uniquecode                    => $env{'course.'.$cid.'.internal.uniquecode'},
 5182:             );
 5183:             push(@{$brcrum},
 5184:                     {href => '/adm/createuser?action=selfenroll',
 5185:                      text => "Configure Self-enrollment",
 5186:                      help => 'Course_Self_Enrollment'});
 5187:             if (!exists($env{'form.state'})) {
 5188:                 $args = { bread_crumbs           => $brcrum,
 5189:                           bread_crumbs_component => 'Configure Self-enrollment'};
 5190:                 $r->print(&header(undef,$args));
 5191:                 $r->print('<h3>'.&mt('Self-enrollment with a student role').'</h3>'."\n");
 5192:                 &print_selfenroll_menu($r,'course',$cid,$cdom,$cnum,\%currsettings);
 5193:             } elsif ($env{'form.state'} eq 'done') {
 5194:                 push (@{$brcrum},
 5195:                           {href=>'/adm/createuser?action=selfenroll',
 5196:                            text=>"Result"});
 5197:                 $args = { bread_crumbs           => $brcrum,
 5198:                           bread_crumbs_component => 'Self-enrollment result'};
 5199:                 $r->print(&header(undef,$args));
 5200:                 $r->print('<h3>'.&mt('Self-enrollment with a student role').'</h3>'."\n");
 5201:                 &update_selfenroll_config($r,$cid,$cdom,$cnum,$context,$crstype,\%currsettings);
 5202:             }
 5203:         } else {
 5204:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 5205:                      '<span class="LC_error">'.&mt('You do not have permission to configure self-enrollment').'</span>');
 5206:         }
 5207:     } elsif ($env{'form.action'} eq 'selfenrollqueue') {
 5208:         if ($permission->{selfenrolladmin}) {
 5209:             push(@{$brcrum},
 5210:                      {href => '/adm/createuser?action=selfenrollqueue',
 5211:                       text => 'Enrollment requests',
 5212:                       help => 'Course_Approve_Selfenroll'});
 5213:             $bread_crumbs_component = 'Enrollment requests';
 5214:             if ($env{'form.state'} eq 'done') {
 5215:                 push(@{$brcrum},
 5216:                          {href => '/adm/createuser?action=selfenrollqueue',
 5217:                           text => 'Result',
 5218:                           help => 'Course_Approve_Selfenroll'});
 5219:                 $bread_crumbs_component = 'Enrollment result';
 5220:             }
 5221:             $args = { bread_crumbs           => $brcrum,
 5222:                       bread_crumbs_component => $bread_crumbs_component};
 5223:             $r->print(&header(undef,$args));
 5224:             my $coursedesc = $env{'course.'.$cid.'.description'};
 5225:             if (!exists($env{'form.state'})) {
 5226:                 $r->print('<h3>'.&mt('Pending enrollment requests').'</h3>'."\n");
 5227:                 $r->print(&Apache::loncoursequeueadmin::display_queued_requests($context,
 5228:                                                                                 $cdom,$cnum));
 5229:             } elsif ($env{'form.state'} eq 'done') {
 5230:                 $r->print('<h3>'.&mt('Enrollment request processing').'</h3>'."\n");
 5231:                 $r->print(&Apache::loncoursequeueadmin::update_request_queue($context,
 5232:                               $cdom,$cnum,$coursedesc));
 5233:             }
 5234:         } else {
 5235:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 5236:                      '<span class="LC_error">'.&mt('You do not have permission to manage self-enrollment').'</span>');
 5237:         }
 5238:     } elsif ($env{'form.action'} eq 'changelogs') {
 5239:         if ($permission->{cusr} || $permission->{view}) {
 5240:             &print_userchangelogs_display($r,$context,$permission,$brcrum);
 5241:         } else {
 5242:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 5243:                      '<span class="LC_error">'.&mt('You do not have permission to view change logs').'</span>');
 5244:         }
 5245:     } elsif ($env{'form.action'} eq 'helpdesk') {
 5246:         if (($permission->{'owner'}) || ($permission->{'co-owner'})) {
 5247:             if ($env{'form.state'} eq 'process') {
 5248:                 if ($permission->{'owner'}) {
 5249:                     &update_helpdeskaccess($r,$permission,$brcrum);
 5250:                 } else {
 5251:                     &print_helpdeskaccess_display($r,$permission,$brcrum);
 5252:                 }
 5253:             } else {
 5254:                 &print_helpdeskaccess_display($r,$permission,$brcrum);
 5255:             }
 5256:         } else {
 5257:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 5258:                       '<span class="LC_error">'.&mt('You do not have permission to view helpdesk access').'</span>');
 5259:         }
 5260:     } else {
 5261:         $bread_crumbs_component = 'User Management';
 5262:         $args = { bread_crumbs           => $brcrum,
 5263:                   bread_crumbs_component => $bread_crumbs_component};
 5264:         $r->print(&header(undef,$args));
 5265:         $r->print(&print_main_menu($permission,$context,$crstype));
 5266:     }
 5267:     $r->print(&Apache::loncommon::end_page());
 5268:     return OK;
 5269: }
 5270: 
 5271: sub header {
 5272:     my ($jscript,$args) = @_;
 5273:     my $start_page;
 5274:     if (ref($args) eq 'HASH') {
 5275:         $start_page=&Apache::loncommon::start_page('User Management',$jscript,$args);
 5276:     } else {
 5277:         $start_page=&Apache::loncommon::start_page('User Management',$jscript);
 5278:     }
 5279:     return $start_page;
 5280: }
 5281: 
 5282: sub add_script {
 5283:     my ($js) = @_;
 5284:     return '<script type="text/javascript">'."\n"
 5285:           .'// <![CDATA['."\n"
 5286:           .$js."\n"
 5287:           .'// ]]>'."\n"
 5288:           .'</script>'."\n";
 5289: }
 5290: 
 5291: sub usernamerequest_javascript {
 5292:     my $js = <<ENDJS;
 5293: 
 5294: function openusernamereqdisplay(dom,uname,queue) {
 5295:     var url = '/adm/createuser?action=displayuserreq';
 5296:     url += '&domain='+dom+'&username='+uname+'&queue='+queue;
 5297:     var title = 'Account_Request_Browser';
 5298:     var options = 'scrollbars=1,resizable=1,menubar=0';
 5299:     options += ',width=700,height=600';
 5300:     var stdeditbrowser = open(url,title,options,'1');
 5301:     stdeditbrowser.focus();
 5302:     return;
 5303: }
 5304:  
 5305: ENDJS
 5306: }
 5307: 
 5308: sub close_popup_form {
 5309:     my $close= &mt('Close Window');
 5310:     return << "END";
 5311: <p><form name="displayreq" action="" method="post">
 5312: <input type="button" name="closeme" value="$close" onclick="javascript:self.close();" />
 5313: </form></p>
 5314: END
 5315: }
 5316: 
 5317: sub verify_user_display {
 5318:     my ($context) = @_;
 5319:     my %lt = &Apache::lonlocal::texthash (
 5320:         course    => 'course(s): description, section(s), status',
 5321:         community => 'community(s): description, section(s), status',
 5322:         author    => 'author',
 5323:     );
 5324:     my $photos;
 5325:     if (($context eq 'course') && $env{'request.course.id'}) {
 5326:         $photos = $env{'course.'.$env{'request.course.id'}.'.internal.showphoto'};
 5327:     }
 5328:     my $output = <<"END";
 5329: 
 5330: function hide_searching() {
 5331:     if (document.getElementById('searching')) {
 5332:         document.getElementById('searching').style.display = 'none';
 5333:     }
 5334:     return;
 5335: }
 5336: 
 5337: function display_update() {
 5338:     document.studentform.action.value = 'listusers';
 5339:     document.studentform.phase.value = 'display';
 5340:     document.studentform.submit();
 5341: }
 5342: 
 5343: function updateCols(caller) {
 5344:     var context = '$context';
 5345:     var photos = '$photos';
 5346:     if (caller == 'Status') {
 5347:         if ((context == 'domain') && 
 5348:             ((document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'course') ||
 5349:              (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'community'))) {
 5350:             document.getElementById('showcolstatus').checked = false;
 5351:             document.getElementById('showcolstatus').disabled = 'disabled';
 5352:             document.getElementById('showcolstart').checked = false;
 5353:             document.getElementById('showcolend').checked = false;
 5354:         } else {
 5355:             if (document.studentform.Status.options[document.studentform.Status.selectedIndex].value == 'Any') {
 5356:                 document.getElementById('showcolstatus').checked = true;
 5357:                 document.getElementById('showcolstatus').disabled = '';
 5358:                 document.getElementById('showcolstart').checked = true;
 5359:                 document.getElementById('showcolend').checked = true;
 5360:             } else {
 5361:                 document.getElementById('showcolstatus').checked = false;
 5362:                 document.getElementById('showcolstatus').disabled = 'disabled';
 5363:                 document.getElementById('showcolstart').checked = false;
 5364:                 document.getElementById('showcolend').checked = false;
 5365:             }
 5366:         }
 5367:     }
 5368:     if (caller == 'output') {
 5369:         if (photos == 1) {
 5370:             if (document.getElementById('showcolphoto')) {
 5371:                 var photoitem = document.getElementById('showcolphoto');
 5372:                 if (document.studentform.output.options[document.studentform.output.selectedIndex].value == 'html') {
 5373:                     photoitem.checked = true;
 5374:                     photoitem.disabled = '';
 5375:                 } else {
 5376:                     photoitem.checked = false;
 5377:                     photoitem.disabled = 'disabled';
 5378:                 }
 5379:             }
 5380:         }
 5381:     }
 5382:     if (caller == 'showrole') {
 5383:         if ((document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'Any') ||
 5384:             (document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'cr')) {
 5385:             document.getElementById('showcolrole').checked = true;
 5386:             document.getElementById('showcolrole').disabled = '';
 5387:         } else {
 5388:             document.getElementById('showcolrole').checked = false;
 5389:             document.getElementById('showcolrole').disabled = 'disabled';
 5390:         }
 5391:         if (context == 'domain') {
 5392:             var quotausageshow = 0;
 5393:             if ((document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'course') ||
 5394:                 (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'community')) {
 5395:                 document.getElementById('showcolstatus').checked = false;
 5396:                 document.getElementById('showcolstatus').disabled = 'disabled';
 5397:                 document.getElementById('showcolstart').checked = false;
 5398:                 document.getElementById('showcolend').checked = false;
 5399:             } else {
 5400:                 if (document.studentform.Status.options[document.studentform.Status.selectedIndex].value == 'Any') {
 5401:                     document.getElementById('showcolstatus').checked = true;
 5402:                     document.getElementById('showcolstatus').disabled = '';
 5403:                     document.getElementById('showcolstart').checked = true;
 5404:                     document.getElementById('showcolend').checked = true;
 5405:                 }
 5406:             }
 5407:             if (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'domain') {
 5408:                 document.getElementById('showcolextent').disabled = 'disabled';
 5409:                 document.getElementById('showcolextent').checked = 'false';
 5410:                 document.getElementById('showextent').style.display='none';
 5411:                 document.getElementById('showcoltextextent').innerHTML = '';
 5412:                 if ((document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'au') ||
 5413:                     (document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'Any')) {
 5414:                     if (document.getElementById('showcolauthorusage')) {
 5415:                         document.getElementById('showcolauthorusage').disabled = '';
 5416:                     }
 5417:                     if (document.getElementById('showcolauthorquota')) {
 5418:                         document.getElementById('showcolauthorquota').disabled = '';
 5419:                     }
 5420:                     quotausageshow = 1;
 5421:                 }
 5422:             } else {
 5423:                 document.getElementById('showextent').style.display='block';
 5424:                 document.getElementById('showextent').style.textAlign='left';
 5425:                 document.getElementById('showextent').style.textFace='normal';
 5426:                 if (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'author') {
 5427:                     document.getElementById('showcolextent').disabled = '';
 5428:                     document.getElementById('showcolextent').checked = 'true';
 5429:                     document.getElementById('showcoltextextent').innerHTML="$lt{'author'}";
 5430:                 } else {
 5431:                     document.getElementById('showcolextent').disabled = '';
 5432:                     document.getElementById('showcolextent').checked = 'true';
 5433:                     if (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'community') {
 5434:                         document.getElementById('showcoltextextent').innerHTML="$lt{'community'}";
 5435:                     } else {
 5436:                         document.getElementById('showcoltextextent').innerHTML="$lt{'course'}";
 5437:                     }
 5438:                 }
 5439:             }
 5440:             if (quotausageshow == 0)  {
 5441:                 if (document.getElementById('showcolauthorusage')) {
 5442:                     document.getElementById('showcolauthorusage').checked = false;
 5443:                     document.getElementById('showcolauthorusage').disabled = 'disabled';
 5444:                 }
 5445:                 if (document.getElementById('showcolauthorquota')) {
 5446:                     document.getElementById('showcolauthorquota').checked = false;
 5447:                     document.getElementById('showcolauthorquota').disabled = 'disabled';
 5448:                 }
 5449:             }
 5450:         }
 5451:     }
 5452:     return;
 5453: }
 5454: 
 5455: END
 5456:     return $output;
 5457: 
 5458: }
 5459: 
 5460: ###############################################################
 5461: ###############################################################
 5462: #  Menu Phase One
 5463: sub print_main_menu {
 5464:     my ($permission,$context,$crstype) = @_;
 5465:     my $linkcontext = $context;
 5466:     my $stuterm = lc(&Apache::lonnet::plaintext('st',$crstype));
 5467:     if (($context eq 'course') && ($crstype eq 'Community')) {
 5468:         $linkcontext = lc($crstype);
 5469:         $stuterm = 'Members';
 5470:     }
 5471:     my %links = (
 5472:                 domain => {
 5473:                             upload     => 'Upload a File of Users',
 5474:                             singleuser => 'Add/Modify a User',
 5475:                             listusers  => 'Manage Users',
 5476:                             },
 5477:                 author => {
 5478:                             upload     => 'Upload a File of Co-authors',
 5479:                             singleuser => 'Add/Modify a Co-author',
 5480:                             listusers  => 'Manage Co-authors',
 5481:                             },
 5482:                 course => {
 5483:                             upload     => 'Upload a File of Course Users',
 5484:                             singleuser => 'Add/Modify a Course User',
 5485:                             listusers  => 'List and Modify Multiple Course Users',
 5486:                             },
 5487:                 community => {
 5488:                             upload     => 'Upload a File of Community Users',
 5489:                             singleuser => 'Add/Modify a Community User',
 5490:                             listusers  => 'List and Modify Multiple Community Users',
 5491:                            },
 5492:                 );
 5493:      my %linktitles = (
 5494:                 domain => {
 5495:                             singleuser => 'Add a user to the domain, and/or a course or community in the domain.',
 5496:                             listusers  => 'Show and manage users in this domain.',
 5497:                             },
 5498:                 author => {
 5499:                             singleuser => 'Add a user with a co- or assistant author role.',
 5500:                             listusers  => 'Show and manage co- or assistant authors.',
 5501:                             },
 5502:                 course => {
 5503:                             singleuser => 'Add a user with a certain role to this course.',
 5504:                             listusers  => 'Show and manage users in this course.',
 5505:                             },
 5506:                 community => {
 5507:                             singleuser => 'Add a user with a certain role to this community.',
 5508:                             listusers  => 'Show and manage users in this community.',
 5509:                            },
 5510:                 );
 5511:   if ($linkcontext eq 'domain') {
 5512:       unless ($permission->{'cusr'}) {
 5513:           $links{'domain'}{'singleuser'} = 'View a User';
 5514:           $linktitles{'domain'}{'singleuser'} = 'View information about a user in the domain';
 5515:       }
 5516:   } elsif ($linkcontext eq 'course') {
 5517:       unless ($permission->{'cusr'}) {
 5518:           $links{'course'}{'singleuser'} = 'View a Course User';
 5519:           $linktitles{'course'}{'singleuser'} = 'View information about a user in this course';
 5520:           $links{'course'}{'listusers'} = 'List Course Users';
 5521:           $linktitles{'course'}{'listusers'} = 'Show information about users in this course';
 5522:       }
 5523:   } elsif ($linkcontext eq 'community') {
 5524:       unless ($permission->{'cusr'}) {
 5525:           $links{'community'}{'singleuser'} = 'View a Community User';
 5526:           $linktitles{'community'}{'singleuser'} = 'View information about a user in this community';
 5527:           $links{'community'}{'listusers'} = 'List Community Users';
 5528:           $linktitles{'community'}{'listusers'} = 'Show information about users in this community';
 5529:       }
 5530:   }
 5531:   my @menu = ( {categorytitle => 'Single Users', 
 5532:          items =>
 5533:          [
 5534:             {
 5535:              linktext => $links{$linkcontext}{'singleuser'},
 5536:              icon => 'edit-redo.png',
 5537:              #help => 'Course_Change_Privileges',
 5538:              url => '/adm/createuser?action=singleuser',
 5539:              permission => ($permission->{'view'} || $permission->{'cusr'}),
 5540:              linktitle => $linktitles{$linkcontext}{'singleuser'},
 5541:             },
 5542:          ]},
 5543: 
 5544:          {categorytitle => 'Multiple Users',
 5545:          items => 
 5546:          [
 5547:             {
 5548:              linktext => $links{$linkcontext}{'upload'},
 5549:              icon => 'uplusr.png',
 5550:              #help => 'Course_Create_Class_List',
 5551:              url => '/adm/createuser?action=upload',
 5552:              permission => $permission->{'cusr'},
 5553:              linktitle => 'Upload a CSV or a text file containing users.',
 5554:             },
 5555:             {
 5556:              linktext => $links{$linkcontext}{'listusers'},
 5557:              icon => 'mngcu.png',
 5558:              #help => 'Course_View_Class_List',
 5559:              url => '/adm/createuser?action=listusers',
 5560:              permission => ($permission->{'view'} || $permission->{'cusr'}),
 5561:              linktitle => $linktitles{$linkcontext}{'listusers'}, 
 5562:             },
 5563: 
 5564:          ]},
 5565: 
 5566:          {categorytitle => 'Administration',
 5567:          items => [ ]},
 5568:        );
 5569: 
 5570:     if ($context eq 'domain'){
 5571:         push(@{  $menu[0]->{items} }, # Single Users
 5572:             {
 5573:              linktext => 'User Access Log',
 5574:              icon => 'document-properties.png',
 5575:              #help => 'Domain_User_Access_Logs',
 5576:              url => '/adm/createuser?action=accesslogs',
 5577:              permission => $permission->{'activity'},
 5578:              linktitle => 'View user access log.',
 5579:             }
 5580:         );
 5581:         
 5582:         push(@{ $menu[2]->{items} }, #Category: Administration
 5583:             {
 5584:              linktext => 'Custom Roles',
 5585:              icon => 'emblem-photos.png',
 5586:              #help => 'Course_Editing_Custom_Roles',
 5587:              url => '/adm/createuser?action=custom',
 5588:              permission => $permission->{'custom'},
 5589:              linktitle => 'Configure a custom role.',
 5590:             },
 5591:             {
 5592:              linktext => 'Authoring Space Requests',
 5593:              icon => 'selfenrl-queue.png',
 5594:              #help => 'Domain_Role_Approvals',
 5595:              url => '/adm/createuser?action=processauthorreq',
 5596:              permission => $permission->{'cusr'},
 5597:              linktitle => 'Approve or reject author role requests',
 5598:             },
 5599:             {
 5600:              linktext => 'LON-CAPA Account Requests',
 5601:              icon => 'list-add.png',
 5602:              #help => 'Domain_Username_Approvals',
 5603:              url => '/adm/createuser?action=processusernamereq',
 5604:              permission => $permission->{'cusr'},
 5605:              linktitle => 'Approve or reject LON-CAPA account requests',
 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->{'cusr'} || $permission->{'view'}),
 5613:              linktitle => 'View change log.',
 5614:             },
 5615:         );
 5616:         
 5617:     }elsif ($context eq 'course'){
 5618:         my ($cnum,$cdom) = &Apache::lonuserutils::get_course_identity();
 5619: 
 5620:         my %linktext = (
 5621:                          'Course'    => {
 5622:                                           single => 'Add/Modify a Student', 
 5623:                                           drop   => 'Drop Students',
 5624:                                           groups => 'Course Groups',
 5625:                                         },
 5626:                          'Community' => {
 5627:                                           single => 'Add/Modify a Member', 
 5628:                                           drop   => 'Drop Members',
 5629:                                           groups => 'Community Groups',
 5630:                                         },
 5631:                        );
 5632:         $linktext{'Placement'} = $linktext{'Course'};
 5633: 
 5634:         my %linktitle = (
 5635:             'Course' => {
 5636:                   single => 'Add a user with the role of student to this course',
 5637:                   drop   => 'Remove a student from this course.',
 5638:                   groups => 'Manage course groups',
 5639:                         },
 5640:             'Community' => {
 5641:                   single => 'Add a user with the role of member to this community',
 5642:                   drop   => 'Remove a member from this community.',
 5643:                   groups => 'Manage community groups',
 5644:                            },
 5645:         );
 5646: 
 5647:         $linktitle{'Placement'} = $linktitle{'Course'};
 5648: 
 5649:         push(@{ $menu[0]->{items} }, #Category: Single Users
 5650:             {   
 5651:              linktext => $linktext{$crstype}{'single'},
 5652:              #help => 'Course_Add_Student',
 5653:              icon => 'list-add.png',
 5654:              url => '/adm/createuser?action=singlestudent',
 5655:              permission => $permission->{'cusr'},
 5656:              linktitle => $linktitle{$crstype}{'single'},
 5657:             },
 5658:         );
 5659:         
 5660:         push(@{ $menu[1]->{items} }, #Category: Multiple Users 
 5661:             {
 5662:              linktext => $linktext{$crstype}{'drop'},
 5663:              icon => 'edit-undo.png',
 5664:              #help => 'Course_Drop_Student',
 5665:              url => '/adm/createuser?action=drop',
 5666:              permission => $permission->{'cusr'},
 5667:              linktitle => $linktitle{$crstype}{'drop'},
 5668:             },
 5669:         );
 5670:         push(@{ $menu[2]->{items} }, #Category: Administration
 5671:             {
 5672:              linktext => 'Helpdesk Access',
 5673:              icon => 'helpdesk-access.png',
 5674:              #help => 'Course_Helpdesk_Access',
 5675:              url => '/adm/createuser?action=helpdesk',
 5676:              permission => ($permission->{'owner'} || $permission->{'co-owner'}),
 5677:              linktitle => 'Helpdesk access options',
 5678:             },
 5679:             {
 5680:              linktext => 'Custom Roles',
 5681:              icon => 'emblem-photos.png',
 5682:              #help => 'Course_Editing_Custom_Roles',
 5683:              url => '/adm/createuser?action=custom',
 5684:              permission => $permission->{'custom'},
 5685:              linktitle => 'Configure a custom role.',
 5686:             },
 5687:             {
 5688:              linktext => $linktext{$crstype}{'groups'},
 5689:              icon => 'grps.png',
 5690:              #help => 'Course_Manage_Group',
 5691:              url => '/adm/coursegroups?refpage=cusr',
 5692:              permission => $permission->{'grp_manage'},
 5693:              linktitle => $linktitle{$crstype}{'groups'},
 5694:             },
 5695:             {
 5696:              linktext => 'Change Log',
 5697:              icon => 'document-properties.png',
 5698:              #help => 'Course_User_Logs',
 5699:              url => '/adm/createuser?action=changelogs',
 5700:              permission => ($permission->{'view'} || $permission->{'cusr'}),
 5701:              linktitle => 'View change log.',
 5702:             },
 5703:         );
 5704:         if ($env{'course.'.$env{'request.course.id'}.'.internal.selfenroll_approval'}) {
 5705:             push(@{ $menu[2]->{items} },
 5706:                     {
 5707:                      linktext => 'Enrollment Requests',
 5708:                      icon => 'selfenrl-queue.png',
 5709:                      #help => 'Course_Approve_Selfenroll',
 5710:                      url => '/adm/createuser?action=selfenrollqueue',
 5711:                      permission => $permission->{'selfenrolladmin'},
 5712:                      linktitle =>'Approve or reject enrollment requests.',
 5713:                     },
 5714:             );
 5715:         }
 5716:         
 5717:         if (!exists($permission->{'cusr_section'})){
 5718:             if ($crstype ne 'Community') {
 5719:                 push(@{ $menu[2]->{items} },
 5720:                     {
 5721:                      linktext => 'Automated Enrollment',
 5722:                      icon => 'roles.png',
 5723:                      #help => 'Course_Automated_Enrollment',
 5724:                      permission => (&Apache::lonnet::auto_run($cnum,$cdom)
 5725:                                          && (($permission->{'cusr'}) ||
 5726:                                              ($permission->{'view'}))),
 5727:                      url  => '/adm/populate',
 5728:                      linktitle => 'Automated enrollment manager.',
 5729:                     }
 5730:                 );
 5731:             }
 5732:             push(@{ $menu[2]->{items} }, 
 5733:                 {
 5734:                  linktext => 'User Self-Enrollment',
 5735:                  icon => 'self_enroll.png',
 5736:                  #help => 'Course_Self_Enrollment',
 5737:                  url => '/adm/createuser?action=selfenroll',
 5738:                  permission => $permission->{'selfenrolladmin'},
 5739:                  linktitle => 'Configure user self-enrollment.',
 5740:                 },
 5741:             );
 5742:         }
 5743:     } elsif ($context eq 'author') {
 5744:         push(@{ $menu[2]->{items} }, #Category: Administration
 5745:             {
 5746:              linktext => 'Change Log',
 5747:              icon => 'document-properties.png',
 5748:              #help => 'Course_User_Logs',
 5749:              url => '/adm/createuser?action=changelogs',
 5750:              permission => $permission->{'cusr'},
 5751:              linktitle => 'View change log.',
 5752:             },
 5753:         );
 5754:     }
 5755:     return Apache::lonhtmlcommon::generate_menu(@menu);
 5756: #               { text => 'View Log-in History',
 5757: #                 help => 'Course_User_Logins',
 5758: #                 action => 'logins',
 5759: #                 permission => $permission->{'cusr'},
 5760: #               });
 5761: }
 5762: 
 5763: sub restore_prev_selections {
 5764:     my %saveable_parameters = ('srchby'   => 'scalar',
 5765: 			       'srchin'   => 'scalar',
 5766: 			       'srchtype' => 'scalar',
 5767: 			       );
 5768:     &Apache::loncommon::store_settings('user','user_picker',
 5769: 				       \%saveable_parameters);
 5770:     &Apache::loncommon::restore_settings('user','user_picker',
 5771: 					 \%saveable_parameters);
 5772: }
 5773: 
 5774: sub print_selfenroll_menu {
 5775:     my ($r,$context,$cid,$cdom,$cnum,$currsettings,$additional,$readonly) = @_;
 5776:     my $crstype = &Apache::loncommon::course_type();
 5777:     my $formname = 'selfenroll';
 5778:     my $nolink = 1;
 5779:     my ($row,$lt) = &Apache::lonuserutils::get_selfenroll_titles();
 5780:     my $groupslist = &Apache::lonuserutils::get_groupslist();
 5781:     my $setsec_js = 
 5782:         &Apache::lonuserutils::setsections_javascript($formname,$groupslist);
 5783:     my %alerts = &Apache::lonlocal::texthash(
 5784:         acto => 'Activation of self-enrollment was selected for the following domain(s)',
 5785:         butn => 'but no user types have been checked.',
 5786:         wilf => "Please uncheck 'activate' or check at least one type.",
 5787:     );
 5788:     my $disabled;
 5789:     if ($readonly) {
 5790:        $disabled = ' disabled="disabled"';
 5791:     }
 5792:     &js_escape(\%alerts);
 5793:     my $selfenroll_js = <<"ENDSCRIPT";
 5794: function update_types(caller,num) {
 5795:     var delidx = getIndexByName('selfenroll_delete');
 5796:     var actidx = getIndexByName('selfenroll_activate');
 5797:     if (caller == 'selfenroll_all') {
 5798:         var selall;
 5799:         for (var i=0; i<document.$formname.selfenroll_all.length; i++) {
 5800:             if (document.$formname.selfenroll_all[i].checked) {
 5801:                 selall = document.$formname.selfenroll_all[i].value;
 5802:             }
 5803:         }
 5804:         if (selall == 1) {
 5805:             if (delidx != -1) {
 5806:                 if (document.$formname.selfenroll_delete.length) {
 5807:                     for (var j=0; j<document.$formname.selfenroll_delete.length; j++) {
 5808:                         document.$formname.selfenroll_delete[j].checked = true;
 5809:                     }
 5810:                 } else {
 5811:                     document.$formname.elements[delidx].checked = true;
 5812:                 }
 5813:             }
 5814:             if (actidx != -1) {
 5815:                 if (document.$formname.selfenroll_activate.length) {
 5816:                     for (var j=0; j<document.$formname.selfenroll_activate.length; j++) {
 5817:                         document.$formname.selfenroll_activate[j].checked = false;
 5818:                     }
 5819:                 } else {
 5820:                     document.$formname.elements[actidx].checked = false;
 5821:                 }
 5822:             }
 5823:             document.$formname.selfenroll_newdom.selectedIndex = 0; 
 5824:         }
 5825:     }
 5826:     if (caller == 'selfenroll_activate') {
 5827:         if (document.$formname.selfenroll_activate.length) {
 5828:             for (var j=0; j<document.$formname.selfenroll_activate.length; j++) {
 5829:                 if (document.$formname.selfenroll_activate[j].value == num) {
 5830:                     if (document.$formname.selfenroll_activate[j].checked) {
 5831:                         for (var i=0; i<document.$formname.selfenroll_all.length; i++) {
 5832:                             if (document.$formname.selfenroll_all[i].value == '1') {
 5833:                                 document.$formname.selfenroll_all[i].checked = false;
 5834:                             }
 5835:                             if (document.$formname.selfenroll_all[i].value == '0') {
 5836:                                 document.$formname.selfenroll_all[i].checked = true;
 5837:                             }
 5838:                         }
 5839:                     }
 5840:                 }
 5841:             }
 5842:         } else {
 5843:             for (var i=0; i<document.$formname.selfenroll_all.length; i++) {
 5844:                 if (document.$formname.selfenroll_all[i].value == '1') {
 5845:                     document.$formname.selfenroll_all[i].checked = false;
 5846:                 }
 5847:                 if (document.$formname.selfenroll_all[i].value == '0') {
 5848:                     document.$formname.selfenroll_all[i].checked = true;
 5849:                 }
 5850:             }
 5851:         }
 5852:     }
 5853:     if (caller == 'selfenroll_delete') {
 5854:         if (document.$formname.selfenroll_delete.length) {
 5855:             for (var j=0; j<document.$formname.selfenroll_delete.length; j++) {
 5856:                 if (document.$formname.selfenroll_delete[j].value == num) {
 5857:                     if (document.$formname.selfenroll_delete[j].checked) {
 5858:                         var delindex = getIndexByName('selfenroll_types_'+num);
 5859:                         if (delindex != -1) { 
 5860:                             if (document.$formname.elements[delindex].length) {
 5861:                                 for (var k=0; k<document.$formname.elements[delindex].length; k++) {
 5862:                                     document.$formname.elements[delindex][k].checked = false;
 5863:                                 }
 5864:                             } else {
 5865:                                 document.$formname.elements[delindex].checked = false;
 5866:                             }
 5867:                         }
 5868:                     }
 5869:                 }
 5870:             }
 5871:         } else {
 5872:             if (document.$formname.selfenroll_delete.checked) {
 5873:                 var delindex = getIndexByName('selfenroll_types_'+num);
 5874:                 if (delindex != -1) {
 5875:                     if (document.$formname.elements[delindex].length) {
 5876:                         for (var k=0; k<document.$formname.elements[delindex].length; k++) {
 5877:                             document.$formname.elements[delindex][k].checked = false;
 5878:                         }
 5879:                     } else {
 5880:                         document.$formname.elements[delindex].checked = false;
 5881:                     }
 5882:                 }
 5883:             }
 5884:         }
 5885:     }
 5886:     return;
 5887: }
 5888: 
 5889: function validate_types(form) {
 5890:     var needaction = new Array();
 5891:     var countfail = 0;
 5892:     var actidx = getIndexByName('selfenroll_activate');
 5893:     if (actidx != -1) {
 5894:         if (document.$formname.selfenroll_activate.length) {
 5895:             for (var j=0; j<document.$formname.selfenroll_activate.length; j++) {
 5896:                 var num = document.$formname.selfenroll_activate[j].value;
 5897:                 if (document.$formname.selfenroll_activate[j].checked) {
 5898:                     countfail = check_types(num,countfail,needaction)
 5899:                 }
 5900:             }
 5901:         } else {
 5902:             if (document.$formname.selfenroll_activate.checked) {
 5903:                 var num = document.$formname.selfenroll_activate.value;
 5904:                 countfail = check_types(num,countfail,needaction)
 5905:             }
 5906:         }
 5907:     }
 5908:     if (countfail > 0) {
 5909:         var msg = "$alerts{'acto'}\\n";
 5910:         var loopend = needaction.length -1;
 5911:         if (loopend > 0) {
 5912:             for (var m=0; m<loopend; m++) {
 5913:                 msg += needaction[m]+", ";
 5914:             }
 5915:         }
 5916:         msg += needaction[loopend]+"\\n$alerts{'butn'}\\n$alerts{'wilf'}";
 5917:         alert(msg);
 5918:         return; 
 5919:     }
 5920:     setSections(form);
 5921: }
 5922: 
 5923: function check_types(num,countfail,needaction) {
 5924:     var boxname = 'selfenroll_types_'+num;
 5925:     var typeidx = getIndexByName(boxname);
 5926:     var count = 0;
 5927:     if (typeidx != -1) {
 5928:         if (document.$formname.elements[boxname].length) {
 5929:             for (var k=0; k<document.$formname.elements[boxname].length; k++) {
 5930:                 if (document.$formname.elements[boxname][k].checked) {
 5931:                     count ++;
 5932:                 }
 5933:             }
 5934:         } else {
 5935:             if (document.$formname.elements[typeidx].checked) {
 5936:                 count ++;
 5937:             }
 5938:         }
 5939:         if (count == 0) {
 5940:             var domidx = getIndexByName('selfenroll_dom_'+num);
 5941:             if (domidx != -1) {
 5942:                 var domname = document.$formname.elements[domidx].value;
 5943:                 needaction[countfail] = domname;
 5944:                 countfail ++;
 5945:             }
 5946:         }
 5947:     }
 5948:     return countfail;
 5949: }
 5950: 
 5951: function toggleNotify() {
 5952:     var selfenrollApproval = 0;
 5953:     if (document.$formname.selfenroll_approval.length) {
 5954:         for (var i=0; i<document.$formname.selfenroll_approval.length; i++) {
 5955:             if (document.$formname.selfenroll_approval[i].checked) {
 5956:                 selfenrollApproval = document.$formname.selfenroll_approval[i].value;
 5957:                 break;        
 5958:             }
 5959:         }
 5960:     }
 5961:     if (document.getElementById('notified')) {
 5962:         if (selfenrollApproval == 0) {
 5963:             document.getElementById('notified').style.display='none';
 5964:         } else {
 5965:             document.getElementById('notified').style.display='block';
 5966:         }
 5967:     }
 5968:     return;
 5969: }
 5970: 
 5971: function getIndexByName(item) {
 5972:     for (var i=0;i<document.$formname.elements.length;i++) {
 5973:         if (document.$formname.elements[i].name == item) {
 5974:             return i;
 5975:         }
 5976:     }
 5977:     return -1;
 5978: }
 5979: ENDSCRIPT
 5980: 
 5981:     my $output = '<script type="text/javascript">'."\n".
 5982:                  '// <![CDATA['."\n".
 5983:                  $setsec_js."\n".$selfenroll_js."\n".
 5984:                  '// ]]>'."\n".
 5985:                  '</script>'."\n".
 5986:                  '<h3>'.$lt->{'selfenroll'}.'</h3>'."\n";
 5987:  
 5988:     my $visactions = &cat_visibility();
 5989:     my ($cathash,%cattype);
 5990:     my %domconfig = &Apache::lonnet::get_dom('configuration',['coursecategories'],$cdom);
 5991:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 5992:         $cathash = $domconfig{'coursecategories'}{'cats'};
 5993:         $cattype{'auth'} = $domconfig{'coursecategories'}{'auth'};
 5994:         $cattype{'unauth'} = $domconfig{'coursecategories'}{'unauth'};
 5995:         if ($cattype{'auth'} eq '') {
 5996:             $cattype{'auth'} = 'std';
 5997:         }
 5998:         if ($cattype{'unauth'} eq '') {
 5999:             $cattype{'unauth'} = 'std';
 6000:         }
 6001:     } else {
 6002:         $cathash = {};
 6003:         $cattype{'auth'} = 'std';
 6004:         $cattype{'unauth'} = 'std';
 6005:     }
 6006:     if (($cattype{'auth'} eq 'none') && ($cattype{'unauth'} eq 'none')) {
 6007:         $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
 6008:                   '<br />'.
 6009:                   '<br />'.$visactions->{'take'}.'<ul>'.
 6010:                   '<li>'.$visactions->{'dc_chgconf'}.'</li>'.
 6011:                   '</ul>');
 6012:     } elsif (($cattype{'auth'} !~ /^(std|domonly)$/) && ($cattype{'unauth'} !~ /^(std|domonly)$/)) {
 6013:         if ($currsettings->{'uniquecode'}) {
 6014:             $r->print('<span class="LC_info">'.$visactions->{'vis'}.'</span>');
 6015:         } else {
 6016:             $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
 6017:                   '<br />'.
 6018:                   '<br />'.$visactions->{'take'}.'<ul>'.
 6019:                   '<li>'.$visactions->{'dc_setcode'}.'</li>'.
 6020:                   '</ul><br />');
 6021:         }
 6022:     } else {
 6023:         my ($visible,$cansetvis,$vismsgs) = &visible_in_stdcat($cdom,$cnum,\%domconfig);
 6024:         if (ref($visactions) eq 'HASH') {
 6025:             if ($visible) {
 6026:                 $output .= '<p class="LC_info">'.$visactions->{'vis'}.'</p>';
 6027:            } else {
 6028:                 $output .= '<p class="LC_warning">'.$visactions->{'miss'}.'</p>'
 6029:                           .$visactions->{'yous'}.
 6030:                            '<p>'.$visactions->{'gen'}.'<br />'.$visactions->{'coca'};
 6031:                 if (ref($vismsgs) eq 'ARRAY') {
 6032:                     $output .= '<br />'.$visactions->{'make'}.'<ul>';
 6033:                     foreach my $item (@{$vismsgs}) {
 6034:                         $output .= '<li>'.$visactions->{$item}.'</li>';
 6035:                     }
 6036:                     $output .= '</ul>';
 6037:                 }
 6038:                 $output .= '</p>';
 6039:             }
 6040:         }
 6041:     }
 6042:     my $actionhref = '/adm/createuser';
 6043:     if ($context eq 'domain') {
 6044:         $actionhref = '/adm/modifycourse';
 6045:     }
 6046: 
 6047:     my %noedit;
 6048:     unless ($context eq 'domain') {
 6049:         %noedit = &get_noedit_fields($cdom,$cnum,$crstype,$row);
 6050:     }
 6051:     $output .= '<form name="'.$formname.'" method="post" action="'.$actionhref.'">'."\n".
 6052:                &Apache::lonhtmlcommon::start_pick_box();
 6053:     if (ref($row) eq 'ARRAY') {
 6054:         foreach my $item (@{$row}) {
 6055:             my $title = $item; 
 6056:             if (ref($lt) eq 'HASH') {
 6057:                 $title = $lt->{$item};
 6058:             }
 6059:             $output .= &Apache::lonhtmlcommon::row_title($title);
 6060:             if ($item eq 'types') {
 6061:                 my $curr_types;
 6062:                 if (ref($currsettings) eq 'HASH') {
 6063:                     $curr_types = $currsettings->{'selfenroll_types'};
 6064:                 }
 6065:                 if ($noedit{$item}) {
 6066:                     if ($curr_types eq '*') {
 6067:                         $output .= &mt('Any user in any domain');   
 6068:                     } else {
 6069:                         my @entries = split(/;/,$curr_types);
 6070:                         if (@entries > 0) {
 6071:                             $output .= '<ul>'; 
 6072:                             foreach my $entry (@entries) {
 6073:                                 my ($currdom,$typestr) = split(/:/,$entry);
 6074:                                 next if ($typestr eq '');
 6075:                                 my $domdesc = &Apache::lonnet::domain($currdom);
 6076:                                 my @currinsttypes = split(',',$typestr);
 6077:                                 my ($othertitle,$usertypes,$types) = 
 6078:                                     &Apache::loncommon::sorted_inst_types($currdom);
 6079:                                 if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 6080:                                     $usertypes->{'any'} = &mt('any user'); 
 6081:                                     if (keys(%{$usertypes}) > 0) {
 6082:                                         $usertypes->{'other'} = &mt('other users');
 6083:                                     }
 6084:                                     my @longinsttypes = map { $usertypes->{$_}; } @currinsttypes;
 6085:                                     $output .= '<li>'.$domdesc.':'.join(', ',@longinsttypes).'</li>';
 6086:                                  }
 6087:                             }
 6088:                             $output .= '</ul>';
 6089:                         } else {
 6090:                             $output .= &mt('None');
 6091:                         }
 6092:                     }
 6093:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 6094:                     next;
 6095:                 }
 6096:                 my $showdomdesc = 1;
 6097:                 my $includeempty = 1;
 6098:                 my $num = 0;
 6099:                 $output .= &Apache::loncommon::start_data_table().
 6100:                            &Apache::loncommon::start_data_table_row()
 6101:                            .'<td colspan="2"><span class="LC_nobreak"><label>'
 6102:                            .&mt('Any user in any domain:')
 6103:                            .'&nbsp;<input type="radio" name="selfenroll_all" value="1" ';
 6104:                 if ($curr_types eq '*') {
 6105:                     $output .= ' checked="checked" '; 
 6106:                 }
 6107:                 $output .= 'onchange="javascript:update_types('.
 6108:                            "'selfenroll_all'".');"'.$disabled.' />'.&mt('Yes').'</label>'.
 6109:                            '&nbsp;&nbsp;<input type="radio" name="selfenroll_all" value="0" ';
 6110:                 if ($curr_types ne '*') {
 6111:                     $output .= ' checked="checked" ';
 6112:                 }
 6113:                 $output .= ' onchange="javascript:update_types('.
 6114:                            "'selfenroll_all'".');"'.$disabled.' />'.&mt('No').'</label></td>'.
 6115:                            &Apache::loncommon::end_data_table_row().
 6116:                            &Apache::loncommon::end_data_table().
 6117:                            &mt('Or').'<br />'.
 6118:                            &Apache::loncommon::start_data_table();
 6119:                 my %currdoms;
 6120:                 if ($curr_types eq '') {
 6121:                     $output .= &new_selfenroll_dom_row($cdom,'0');
 6122:                 } elsif ($curr_types ne '*') {
 6123:                     my @entries = split(/;/,$curr_types);
 6124:                     if (@entries > 0) {
 6125:                         foreach my $entry (@entries) {
 6126:                             my ($currdom,$typestr) = split(/:/,$entry);
 6127:                             $currdoms{$currdom} = 1;
 6128:                             my $domdesc = &Apache::lonnet::domain($currdom);
 6129:                             my @currinsttypes = split(',',$typestr);
 6130:                             $output .= &Apache::loncommon::start_data_table_row()
 6131:                                        .'<td valign="top"><span class="LC_nobreak">'.&mt('Domain:').'<b>'
 6132:                                        .'&nbsp;'.$domdesc.' ('.$currdom.')'
 6133:                                        .'</b><input type="hidden" name="selfenroll_dom_'.$num
 6134:                                        .'" value="'.$currdom.'" /></span><br />'
 6135:                                        .'<span class="LC_nobreak"><label><input type="checkbox" '
 6136:                                        .'name="selfenroll_delete" value="'.$num.'" onchange="javascript:update_types('."'selfenroll_delete','$num'".');"'.$disabled.' />'
 6137:                                        .&mt('Delete').'</label></span></td>';
 6138:                             $output .= '<td valign="top">&nbsp;&nbsp;'.&mt('User types:').'<br />'
 6139:                                        .&selfenroll_inst_types($num,$currdom,\@currinsttypes,$readonly).'</td>'
 6140:                                        .&Apache::loncommon::end_data_table_row();
 6141:                             $num ++;
 6142:                         }
 6143:                     }
 6144:                 }
 6145:                 my $add_domtitle = &mt('Users in additional domain:');
 6146:                 if ($curr_types eq '*') { 
 6147:                     $add_domtitle = &mt('Users in specific domain:');
 6148:                 } elsif ($curr_types eq '') {
 6149:                     $add_domtitle = &mt('Users in other domain:');
 6150:                 }
 6151:                 my ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('enroll',$cdom);
 6152:                 $output .= &Apache::loncommon::start_data_table_row()
 6153:                            .'<td colspan="2"><span class="LC_nobreak">'.$add_domtitle.'</span><br />'
 6154:                            .&Apache::loncommon::select_dom_form('','selfenroll_newdom',
 6155:                                                                 $includeempty,$showdomdesc,'',$trusted,$untrusted,$readonly)
 6156:                            .'<input type="hidden" name="selfenroll_types_total" value="'.$num.'" />'
 6157:                            .'</td>'.&Apache::loncommon::end_data_table_row()
 6158:                            .&Apache::loncommon::end_data_table();
 6159:             } elsif ($item eq 'registered') {
 6160:                 my ($regon,$regoff);
 6161:                 my $registered;
 6162:                 if (ref($currsettings) eq 'HASH') {
 6163:                     $registered = $currsettings->{'selfenroll_registered'};
 6164:                 }
 6165:                 if ($noedit{$item}) {
 6166:                     if ($registered) {
 6167:                         $output .= &mt('Must be registered in course');
 6168:                     } else {
 6169:                         $output .= &mt('No requirement');
 6170:                     }
 6171:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 6172:                     next;
 6173:                 }
 6174:                 if ($registered) {
 6175:                     $regon = ' checked="checked" ';
 6176:                     $regoff = '';
 6177:                 } else {
 6178:                     $regon = '';
 6179:                     $regoff = ' checked="checked" ';
 6180:                 }
 6181:                 $output .= '<label>'.
 6182:                            '<input type="radio" name="selfenroll_registered" value="1"'.$regon.$disabled.' />'.
 6183:                            &mt('Yes').'</label>&nbsp;&nbsp;<label>'.
 6184:                            '<input type="radio" name="selfenroll_registered" value="0"'.$regoff.$disabled.' />'.
 6185:                            &mt('No').'</label>';
 6186:             } elsif ($item eq 'enroll_dates') {
 6187:                 my ($starttime,$endtime);
 6188:                 if (ref($currsettings) eq 'HASH') {
 6189:                     $starttime = $currsettings->{'selfenroll_start_date'};
 6190:                     $endtime = $currsettings->{'selfenroll_end_date'};
 6191:                     if ($starttime eq '') {
 6192:                         $starttime = $currsettings->{'default_enrollment_start_date'};
 6193:                     }
 6194:                     if ($endtime eq '') {
 6195:                         $endtime = $currsettings->{'default_enrollment_end_date'};
 6196:                     }
 6197:                 }
 6198:                 if ($noedit{$item}) {
 6199:                     $output .= &mt('From: [_1], to: [_2]',&Apache::lonlocal::locallocaltime($starttime),
 6200:                                                           &Apache::lonlocal::locallocaltime($endtime));
 6201:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 6202:                     next;
 6203:                 }
 6204:                 my $startform =
 6205:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_start_date',$starttime,
 6206:                                       $disabled,undef,undef,undef,undef,undef,undef,$nolink);
 6207:                 my $endform =
 6208:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_end_date',$endtime,
 6209:                                       $disabled,undef,undef,undef,undef,undef,undef,$nolink);
 6210:                 $output .= &selfenroll_date_forms($startform,$endform);
 6211:             } elsif ($item eq 'access_dates') {
 6212:                 my ($starttime,$endtime);
 6213:                 if (ref($currsettings) eq 'HASH') {
 6214:                     $starttime = $currsettings->{'selfenroll_start_access'};
 6215:                     $endtime = $currsettings->{'selfenroll_end_access'};
 6216:                     if ($starttime eq '') {
 6217:                         $starttime = $currsettings->{'default_enrollment_start_date'};
 6218:                     }
 6219:                     if ($endtime eq '') {
 6220:                         $endtime = $currsettings->{'default_enrollment_end_date'};
 6221:                     }
 6222:                 }
 6223:                 if ($noedit{$item}) {
 6224:                     $output .= &mt('From: [_1], to: [_2]',&Apache::lonlocal::locallocaltime($starttime),
 6225:                                                           &Apache::lonlocal::locallocaltime($endtime));
 6226:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 6227:                     next;
 6228:                 }
 6229:                 my $startform =
 6230:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_start_access',$starttime,
 6231:                                       $disabled,undef,undef,undef,undef,undef,undef,$nolink);
 6232:                 my $endform =
 6233:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_end_access',$endtime,
 6234:                                       $disabled,undef,undef,undef,undef,undef,undef,$nolink);
 6235:                 $output .= &selfenroll_date_forms($startform,$endform);
 6236:             } elsif ($item eq 'section') {
 6237:                 my $currsec;
 6238:                 if (ref($currsettings) eq 'HASH') {
 6239:                     $currsec = $currsettings->{'selfenroll_section'};
 6240:                 }
 6241:                 my %sections_count = &Apache::loncommon::get_sections($cdom,$cnum);
 6242:                 my $newsecval;
 6243:                 if ($currsec ne 'none' && $currsec ne '') {
 6244:                     if (!defined($sections_count{$currsec})) {
 6245:                         $newsecval = $currsec;
 6246:                     }
 6247:                 }
 6248:                 if ($noedit{$item}) {
 6249:                     if ($currsec ne '') {
 6250:                         $output .= $currsec;
 6251:                     } else {
 6252:                         $output .= &mt('No specific section');
 6253:                     }
 6254:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 6255:                     next;
 6256:                 }
 6257:                 my $sections_select = 
 6258:                     &Apache::lonuserutils::course_sections(\%sections_count,'st',$currsec,$disabled);
 6259:                 $output .= '<table class="LC_createuser">'."\n".
 6260:                            '<tr class="LC_section_row">'."\n".
 6261:                            '<td align="center">'.&mt('Existing sections')."\n".
 6262:                            '<br />'.$sections_select.'</td><td align="center">'.
 6263:                            &mt('New section').'<br />'."\n".
 6264:                            '<input type="text" name="newsec" size="15" value="'.$newsecval.'"'.$disabled.' />'."\n".
 6265:                            '<input type="hidden" name="sections" value="" />'."\n".
 6266:                            '</td></tr></table>'."\n";
 6267:             } elsif ($item eq 'approval') {
 6268:                 my ($currnotified,$currapproval,%appchecked);
 6269:                 my %selfdescs = &Apache::lonuserutils::selfenroll_default_descs();
 6270:                 if (ref($currsettings) eq 'HASH') {
 6271:                     $currnotified = $currsettings->{'selfenroll_notifylist'};
 6272:                     $currapproval = $currsettings->{'selfenroll_approval'};
 6273:                 }
 6274:                 if ($currapproval !~ /^[012]$/) {
 6275:                     $currapproval = 0;
 6276:                 }
 6277:                 if ($noedit{$item}) {
 6278:                     $output .=  $selfdescs{'approval'}{$currapproval}.
 6279:                                 '<br />'.&mt('(Set by Domain Coordinator)');
 6280:                     next;
 6281:                 }
 6282:                 $appchecked{$currapproval} = ' checked="checked"';
 6283:                 for my $i (0..2) {
 6284:                     $output .= '<label>'.
 6285:                                '<input type="radio" name="selfenroll_approval" value="'.$i.'"'.
 6286:                                $appchecked{$i}.' onclick="toggleNotify();"'.$disabled.' />'.
 6287:                                $selfdescs{'approval'}{$i}.'</label>'.('&nbsp;'x2);
 6288:                 }
 6289:                 my %advhash = &Apache::lonnet::get_course_adv_roles($cid,1);
 6290:                 my (@ccs,%notified);
 6291:                 my $ccrole = 'cc';
 6292:                 if ($crstype eq 'Community') {
 6293:                     $ccrole = 'co';
 6294:                 }
 6295:                 if ($advhash{$ccrole}) {
 6296:                     @ccs = split(/,/,$advhash{$ccrole});
 6297:                 }
 6298:                 if ($currnotified) {
 6299:                     foreach my $current (split(/,/,$currnotified)) {
 6300:                         $notified{$current} = 1;
 6301:                         if (!grep(/^\Q$current\E$/,@ccs)) {
 6302:                             push(@ccs,$current);
 6303:                         }
 6304:                     }
 6305:                 }
 6306:                 if (@ccs) {
 6307:                     my $style;
 6308:                     unless ($currapproval) {
 6309:                         $style = ' style="display: none;"'; 
 6310:                     }
 6311:                     $output .= '<br /><div id="notified"'.$style.'>'.
 6312:                                &mt('Personnel to be notified when an enrollment request needs approval, or has been approved:').'&nbsp;'.
 6313:                                &Apache::loncommon::start_data_table().
 6314:                                &Apache::loncommon::start_data_table_row();
 6315:                     my $count = 0;
 6316:                     my $numcols = 4;
 6317:                     foreach my $cc (sort(@ccs)) {
 6318:                         my $notifyon;
 6319:                         my ($ccuname,$ccudom) = split(/:/,$cc);
 6320:                         if ($notified{$cc}) {
 6321:                             $notifyon = ' checked="checked" ';
 6322:                         }
 6323:                         if ($count && !$count%$numcols) {
 6324:                             $output .= &Apache::loncommon::end_data_table_row().
 6325:                                        &Apache::loncommon::start_data_table_row()
 6326:                         }
 6327:                         $output .= '<td><span class="LC_nobreak"><label>'.
 6328:                                    '<input type="checkbox" name="selfenroll_notify"'.$notifyon.' value="'.$cc.'"'.$disabled.' />'.
 6329:                                    &Apache::loncommon::plainname($ccuname,$ccudom).
 6330:                                    '</label></span></td>';
 6331:                         $count ++;
 6332:                     }
 6333:                     my $rem = $count%$numcols;
 6334:                     if ($rem) {
 6335:                         my $emptycols = $numcols - $rem;
 6336:                         for (my $i=0; $i<$emptycols; $i++) { 
 6337:                             $output .= '<td>&nbsp;</td>';
 6338:                         }
 6339:                     }
 6340:                     $output .= &Apache::loncommon::end_data_table_row().
 6341:                                &Apache::loncommon::end_data_table().
 6342:                                '</div>';
 6343:                 }
 6344:             } elsif ($item eq 'limit') {
 6345:                 my ($crslimit,$selflimit,$nolimit,$currlim,$currcap);
 6346:                 if (ref($currsettings) eq 'HASH') {
 6347:                     $currlim = $currsettings->{'selfenroll_limit'};
 6348:                     $currcap = $currsettings->{'selfenroll_cap'};
 6349:                 }
 6350:                 if ($noedit{$item}) {
 6351:                     if (($currlim eq 'allstudents') || ($currlim eq 'selfenrolled')) {
 6352:                         if ($currlim eq 'allstudents') {
 6353:                             $output .= &mt('Limit by total students');
 6354:                         } elsif ($currlim eq 'selfenrolled') {
 6355:                             $output .= &mt('Limit by total self-enrolled students');
 6356:                         }
 6357:                         $output .= ' '.&mt('Maximum: [_1]',$currcap).
 6358:                                    '<br />'.&mt('(Set by Domain Coordinator)');
 6359:                     } else {
 6360:                         $output .= &mt('No limit').'<br />'.&mt('(Set by Domain Coordinator)');
 6361:                     }
 6362:                     next;
 6363:                 }
 6364:                 if ($currlim eq 'allstudents') {
 6365:                     $crslimit = ' checked="checked" ';
 6366:                     $selflimit = ' ';
 6367:                     $nolimit = ' ';
 6368:                 } elsif ($currlim eq 'selfenrolled') {
 6369:                     $crslimit = ' ';
 6370:                     $selflimit = ' checked="checked" ';
 6371:                     $nolimit = ' '; 
 6372:                 } else {
 6373:                     $crslimit = ' ';
 6374:                     $selflimit = ' ';
 6375:                     $nolimit = ' checked="checked" ';
 6376:                 }
 6377:                 $output .= '<table><tr><td><label>'.
 6378:                            '<input type="radio" name="selfenroll_limit" value="none"'.$nolimit.$disabled.'/>'.
 6379:                            &mt('No limit').'</label></td><td><label>'.
 6380:                            '<input type="radio" name="selfenroll_limit" value="allstudents"'.$crslimit.$disabled.'/>'.
 6381:                            &mt('Limit by total students').'</label></td><td><label>'.
 6382:                            '<input type="radio" name="selfenroll_limit" value="selfenrolled"'.$selflimit.$disabled.'/>'.
 6383:                            &mt('Limit by total self-enrolled students').
 6384:                            '</td></tr><tr>'.
 6385:                            '<td>&nbsp;</td><td colspan="2"><span class="LC_nobreak">'.
 6386:                            ('&nbsp;'x3).&mt('Maximum number allowed: ').
 6387:                            '<input type="text" name="selfenroll_cap" size = "5" value="'.$currcap.'"'.$disabled.' /></td></tr></table>';
 6388:             }
 6389:             $output .= &Apache::lonhtmlcommon::row_closure(1);
 6390:         }
 6391:     }
 6392:     $output .= &Apache::lonhtmlcommon::end_pick_box().'<br />';
 6393:     unless ($readonly) {
 6394:         $output .= '<input type="button" name="selfenrollconf" value="'
 6395:                    .&mt('Save').'" onclick="validate_types(this.form);" />';
 6396:     }
 6397:     $output .= '<input type="hidden" name="action" value="selfenroll" />'
 6398:               .'<input type="hidden" name="state" value="done" />'."\n"
 6399:               .$additional.'</form>';
 6400:     $r->print($output);
 6401:     return;
 6402: }
 6403: 
 6404: sub get_noedit_fields {
 6405:     my ($cdom,$cnum,$crstype,$row) = @_;
 6406:     my %noedit;
 6407:     if (ref($row) eq 'ARRAY') {
 6408:         my %settings = &Apache::lonnet::get('environment',['internal.coursecode','internal.textbook',
 6409:                                                            'internal.selfenrollmgrdc',
 6410:                                                            'internal.selfenrollmgrcc'],$cdom,$cnum);
 6411:         my $type = &Apache::lonuserutils::get_extended_type($cdom,$cnum,$crstype,\%settings);
 6412:         my (%specific_managebydc,%specific_managebycc,%default_managebydc);
 6413:         map { $specific_managebydc{$_} = 1; } (split(/,/,$settings{'internal.selfenrollmgrdc'}));
 6414:         map { $specific_managebycc{$_} = 1; } (split(/,/,$settings{'internal.selfenrollmgrcc'}));
 6415:         my %domdefaults = &Apache::lonnet::get_domain_defaults($cdom);
 6416:         map { $default_managebydc{$_} = 1; } (split(/,/,$domdefaults{$type.'selfenrolladmdc'}));
 6417: 
 6418:         foreach my $item (@{$row}) {
 6419:             next if ($specific_managebycc{$item});
 6420:             if (($specific_managebydc{$item}) || ($default_managebydc{$item})) {
 6421:                 $noedit{$item} = 1;
 6422:             }
 6423:         }
 6424:     }
 6425:     return %noedit;
 6426: } 
 6427: 
 6428: sub visible_in_stdcat {
 6429:     my ($cdom,$cnum,$domconf) = @_;
 6430:     my ($cathash,%settable,@vismsgs,$cansetvis,$visible);
 6431:     unless (ref($domconf) eq 'HASH') {
 6432:         return ($visible,$cansetvis,\@vismsgs);
 6433:     }
 6434:     if (ref($domconf->{'coursecategories'}) eq 'HASH') {
 6435:         if ($domconf->{'coursecategories'}{'togglecats'} eq 'crs') {
 6436:             $settable{'togglecats'} = 1;
 6437:         }
 6438:         if ($domconf->{'coursecategories'}{'categorize'} eq 'crs') {
 6439:             $settable{'categorize'} = 1;
 6440:         }
 6441:         $cathash = $domconf->{'coursecategories'}{'cats'};
 6442:     }
 6443:     if ($settable{'togglecats'} && $settable{'categorize'}) {
 6444:         $cansetvis = &mt('You are able to both assign a course category and choose to exclude this course from the catalog.');   
 6445:     } elsif ($settable{'togglecats'}) {
 6446:         $cansetvis = &mt('You are able to choose to exclude this course from the catalog, but only a Domain Coordinator may assign a course category.'); 
 6447:     } elsif ($settable{'categorize'}) {
 6448:         $cansetvis = &mt('You may assign a course category, but only a Domain Coordinator may choose to exclude this course from the catalog.');  
 6449:     } else {
 6450:         $cansetvis = &mt('Only a Domain Coordinator may assign a course category or choose to exclude this course from the catalog.'); 
 6451:     }
 6452:      
 6453:     my %currsettings =
 6454:         &Apache::lonnet::get('environment',['hidefromcat','categories','internal.coursecode'],
 6455:                              $cdom,$cnum);
 6456:     $visible = 0;
 6457:     if ($currsettings{'internal.coursecode'} ne '') {
 6458:         if (ref($domconf->{'coursecategories'}) eq 'HASH') {
 6459:             $cathash = $domconf->{'coursecategories'}{'cats'};
 6460:             if (ref($cathash) eq 'HASH') {
 6461:                 if ($cathash->{'instcode::0'} eq '') {
 6462:                     push(@vismsgs,'dc_addinst'); 
 6463:                 } else {
 6464:                     $visible = 1;
 6465:                 }
 6466:             } else {
 6467:                 $visible = 1;
 6468:             }
 6469:         } else {
 6470:             $visible = 1;
 6471:         }
 6472:     } else {
 6473:         if (ref($cathash) eq 'HASH') {
 6474:             if ($cathash->{'instcode::0'} ne '') {
 6475:                 push(@vismsgs,'dc_instcode');
 6476:             }
 6477:         } else {
 6478:             push(@vismsgs,'dc_instcode');
 6479:         }
 6480:     }
 6481:     if ($currsettings{'categories'} ne '') {
 6482:         my $cathash;
 6483:         if (ref($domconf->{'coursecategories'}) eq 'HASH') {
 6484:             $cathash = $domconf->{'coursecategories'}{'cats'};
 6485:             if (ref($cathash) eq 'HASH') {
 6486:                 if (keys(%{$cathash}) == 0) {
 6487:                     push(@vismsgs,'dc_catalog');
 6488:                 } elsif ((keys(%{$cathash}) == 1) && ($cathash->{'instcode::0'} ne '')) {
 6489:                     push(@vismsgs,'dc_categories');
 6490:                 } else {
 6491:                     my @currcategories = split('&',$currsettings{'categories'});
 6492:                     my $matched = 0;
 6493:                     foreach my $cat (@currcategories) {
 6494:                         if ($cathash->{$cat} ne '') {
 6495:                             $visible = 1;
 6496:                             $matched = 1;
 6497:                             last;
 6498:                         }
 6499:                     }
 6500:                     if (!$matched) {
 6501:                         if ($settable{'categorize'}) { 
 6502:                             push(@vismsgs,'chgcat');
 6503:                         } else {
 6504:                             push(@vismsgs,'dc_chgcat');
 6505:                         }
 6506:                     }
 6507:                 }
 6508:             }
 6509:         }
 6510:     } else {
 6511:         if (ref($cathash) eq 'HASH') {
 6512:             if ((keys(%{$cathash}) > 1) || 
 6513:                 (keys(%{$cathash}) == 1) && ($cathash->{'instcode::0'} eq '')) {
 6514:                 if ($settable{'categorize'}) {
 6515:                     push(@vismsgs,'addcat');
 6516:                 } else {
 6517:                     push(@vismsgs,'dc_addcat');
 6518:                 }
 6519:             }
 6520:         }
 6521:     }
 6522:     if ($currsettings{'hidefromcat'} eq 'yes') {
 6523:         $visible = 0;
 6524:         if ($settable{'togglecats'}) {
 6525:             unshift(@vismsgs,'unhide');
 6526:         } else {
 6527:             unshift(@vismsgs,'dc_unhide')
 6528:         }
 6529:     }
 6530:     return ($visible,$cansetvis,\@vismsgs);
 6531: }
 6532: 
 6533: sub cat_visibility {
 6534:     my %visactions = &Apache::lonlocal::texthash(
 6535:                    vis => 'This course/community currently appears in the Course/Community Catalog for this domain.',
 6536:                    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.',
 6537:                    miss => 'This course/community does not currently appear in the Course/Community Catalog for this domain.',
 6538:                    none => 'Display of a course catalog is disabled for this domain.',
 6539:                    yous => 'You should remedy this if you plan to allow self-enrollment, otherwise students will have difficulty finding this course.',
 6540:                    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.',
 6541:                    make => 'Make any changes to self-enrollment settings below, click "Save", then take action to include the course in the Catalog:',
 6542:                    take => 'Take the following action to ensure the course appears in the Catalog:',
 6543:                    dc_chgconf => 'Ask a domain coordinator to change the Catalog type for this domain.',
 6544:                    dc_setcode => 'Ask a domain coordinator to assign a six character code to the course',
 6545:                    dc_unhide  => 'Ask a domain coordinator to change the "Exclude from course catalog" setting.',
 6546:                    dc_addinst => 'Ask a domain coordinator to enable display the catalog of "Official courses (with institutional codes)".',
 6547:                    dc_instcode => 'Ask a domain coordinator to assign an institutional code (if this is an official course).',
 6548:                    dc_catalog  => 'Ask a domain coordinator to enable or create at least one course category in the domain.',
 6549:                    dc_categories => 'Ask a domain coordinator to create a hierarchy of categories and sub categories for courses in the domain.',
 6550:                    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',
 6551:                    dc_addcat => 'Ask a domain coordinator to assign a category to the course.',
 6552:     );
 6553:     $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>"');
 6554:     $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>"');
 6555:     $visactions{'addcat'} = &mt('Use [_1]Categorize course[_2] to assign a category to the course.','"<a href="/adm/courseprefs?phase=display&actions=courseinfo">','</a>"');
 6556:     return \%visactions;
 6557: }
 6558: 
 6559: sub new_selfenroll_dom_row {
 6560:     my ($newdom,$num) = @_;
 6561:     my $domdesc = &Apache::lonnet::domain($newdom);
 6562:     my $output;
 6563:     if ($domdesc ne '') {
 6564:         $output .= &Apache::loncommon::start_data_table_row()
 6565:                    .'<td valign="top"><span class="LC_nobreak">'.&mt('Domain:').'&nbsp;<b>'.$domdesc
 6566:                    .' ('.$newdom.')</b><input type="hidden" name="selfenroll_dom_'.$num
 6567:                    .'" value="'.$newdom.'" /></span><br />'
 6568:                    .'<span class="LC_nobreak"><label><input type="checkbox" '
 6569:                    .'name="selfenroll_activate" value="'.$num.'" '
 6570:                    .'onchange="javascript:update_types('
 6571:                    ."'selfenroll_activate','$num'".');" />'
 6572:                    .&mt('Activate').'</label></span></td>';
 6573:         my @currinsttypes;
 6574:         $output .= '<td>'.&mt('User types:').'<br />'
 6575:                    .&selfenroll_inst_types($num,$newdom,\@currinsttypes).'</td>'
 6576:                    .&Apache::loncommon::end_data_table_row();
 6577:     }
 6578:     return $output;
 6579: }
 6580: 
 6581: sub selfenroll_inst_types {
 6582:     my ($num,$currdom,$currinsttypes,$readonly) = @_;
 6583:     my $output;
 6584:     my $numinrow = 4;
 6585:     my $count = 0;
 6586:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($currdom);
 6587:     my $othervalue = 'any';
 6588:     my $disabled;
 6589:     if ($readonly) {
 6590:         $disabled = ' disabled="disabled"';
 6591:     }
 6592:     if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 6593:         if (keys(%{$usertypes}) > 0) {
 6594:             $othervalue = 'other';
 6595:         }
 6596:         $output .= '<table><tr>';
 6597:         foreach my $type (@{$types}) {
 6598:             if (($count > 0) && ($count%$numinrow == 0)) {
 6599:                 $output .= '</tr><tr>';
 6600:             }
 6601:             if (defined($usertypes->{$type})) {
 6602:                 my $esc_type = &escape($type);
 6603:                 $output .= '<td><span class="LC_nobreak"><label><input type = "checkbox" value="'.
 6604:                            $esc_type.'" ';
 6605:                 if (ref($currinsttypes) eq 'ARRAY') {
 6606:                     if (@{$currinsttypes} > 0) {
 6607:                         if (grep(/^any$/,@{$currinsttypes})) {
 6608:                             $output .= 'checked="checked"';
 6609:                         } elsif (grep(/^\Q$esc_type\E$/,@{$currinsttypes})) {
 6610:                             $output .= 'checked="checked"';
 6611:                         }
 6612:                     } else {
 6613:                         $output .= 'checked="checked"';
 6614:                     }
 6615:                 }
 6616:                 $output .= ' name="selfenroll_types_'.$num.'"'.$disabled.' />'.$usertypes->{$type}.'</label></span></td>';
 6617:             }
 6618:             $count ++;
 6619:         }
 6620:         if (($count > 0) && ($count%$numinrow == 0)) {
 6621:             $output .= '</tr><tr>';
 6622:         }
 6623:         $output .= '<td><span class="LC_nobreak"><label><input type = "checkbox" value="'.$othervalue.'"';
 6624:         if (ref($currinsttypes) eq 'ARRAY') {
 6625:             if (@{$currinsttypes} > 0) {
 6626:                 if (grep(/^any$/,@{$currinsttypes})) { 
 6627:                     $output .= ' checked="checked"';
 6628:                 } elsif ($othervalue eq 'other') {
 6629:                     if (grep(/^\Q$othervalue\E$/,@{$currinsttypes})) {
 6630:                         $output .= ' checked="checked"';
 6631:                     }
 6632:                 }
 6633:             } else {
 6634:                 $output .= ' checked="checked"';
 6635:             }
 6636:         } else {
 6637:             $output .= ' checked="checked"';
 6638:         }
 6639:         $output .= ' name="selfenroll_types_'.$num.'"'.$disabled.' />'.$othertitle.'</label></span></td></tr></table>';
 6640:     }
 6641:     return $output;
 6642: }
 6643: 
 6644: sub selfenroll_date_forms {
 6645:     my ($startform,$endform) = @_;
 6646:     my $output .= &Apache::lonhtmlcommon::start_pick_box()."\n".
 6647:                   &Apache::lonhtmlcommon::row_title(&mt('Start date'),
 6648:                                                     'LC_oddrow_value')."\n".
 6649:                   $startform."\n".
 6650:                   &Apache::lonhtmlcommon::row_closure(1).
 6651:                   &Apache::lonhtmlcommon::row_title(&mt('End date'),
 6652:                                                    'LC_oddrow_value')."\n".
 6653:                   $endform."\n".
 6654:                   &Apache::lonhtmlcommon::row_closure(1).
 6655:                   &Apache::lonhtmlcommon::end_pick_box();
 6656:     return $output;
 6657: }
 6658: 
 6659: sub print_userchangelogs_display {
 6660:     my ($r,$context,$permission,$brcrum) = @_;
 6661:     my $formname = 'rolelog';
 6662:     my ($username,$domain,$crstype,$viewablesec,%roleslog);
 6663:     if ($context eq 'domain') {
 6664:         $domain = $env{'request.role.domain'};
 6665:         %roleslog=&Apache::lonnet::dump_dom('nohist_rolelog',$domain);
 6666:     } else {
 6667:         if ($context eq 'course') { 
 6668:             $domain = $env{'course.'.$env{'request.course.id'}.'.domain'};
 6669:             $username = $env{'course.'.$env{'request.course.id'}.'.num'};
 6670:             $crstype = &Apache::loncommon::course_type();
 6671:             $viewablesec = &Apache::lonuserutils::viewable_section($permission);
 6672:             my %saveable_parameters = ('show' => 'scalar',);
 6673:             &Apache::loncommon::store_course_settings('roles_log',
 6674:                                                       \%saveable_parameters);
 6675:             &Apache::loncommon::restore_course_settings('roles_log',
 6676:                                                         \%saveable_parameters);
 6677:         } elsif ($context eq 'author') {
 6678:             $domain = $env{'user.domain'}; 
 6679:             if ($env{'request.role'} =~ m{^au\./\Q$domain\E/$}) {
 6680:                 $username = $env{'user.name'};
 6681:             } else {
 6682:                 undef($domain);
 6683:             }
 6684:         }
 6685:         if ($domain ne '' && $username ne '') { 
 6686:             %roleslog=&Apache::lonnet::dump('nohist_rolelog',$domain,$username);
 6687:         }
 6688:     }
 6689:     if ((keys(%roleslog))[0]=~/^error\:/) { undef(%roleslog); }
 6690: 
 6691:     my $helpitem;
 6692:     if ($context eq 'course') {
 6693:         $helpitem = 'Course_User_Logs';
 6694:     } elsif ($context eq 'domain') {
 6695:         $helpitem = 'Domain_Role_Logs';
 6696:     } elsif ($context eq 'author') {
 6697:         $helpitem = 'Author_User_Logs';
 6698:     }
 6699:     push (@{$brcrum},
 6700:              {href => '/adm/createuser?action=changelogs',
 6701:               text => 'User Management Logs',
 6702:               help => $helpitem});
 6703:     my $bread_crumbs_component = 'User Changes';
 6704:     my $args = { bread_crumbs           => $brcrum,
 6705:                  bread_crumbs_component => $bread_crumbs_component};
 6706: 
 6707:     # Create navigation javascript
 6708:     my $jsnav = &userlogdisplay_js($formname);
 6709: 
 6710:     my $jscript = (<<ENDSCRIPT);
 6711: <script type="text/javascript">
 6712: // <![CDATA[
 6713: $jsnav
 6714: // ]]>
 6715: </script>
 6716: ENDSCRIPT
 6717: 
 6718:     # print page header
 6719:     $r->print(&header($jscript,$args));
 6720: 
 6721:     # set defaults
 6722:     my $now = time();
 6723:     my $defstart = $now - (7*24*3600); #7 days ago 
 6724:     my %defaults = (
 6725:                      page               => '1',
 6726:                      show               => '10',
 6727:                      role               => 'any',
 6728:                      chgcontext         => 'any',
 6729:                      rolelog_start_date => $defstart,
 6730:                      rolelog_end_date   => $now,
 6731:                    );
 6732:     my $more_records = 0;
 6733: 
 6734:     # set current
 6735:     my %curr;
 6736:     foreach my $item ('show','page','role','chgcontext') {
 6737:         $curr{$item} = $env{'form.'.$item};
 6738:     }
 6739:     my ($startdate,$enddate) = 
 6740:         &Apache::lonuserutils::get_dates_from_form('rolelog_start_date','rolelog_end_date');
 6741:     $curr{'rolelog_start_date'} = $startdate;
 6742:     $curr{'rolelog_end_date'} = $enddate;
 6743:     foreach my $key (keys(%defaults)) {
 6744:         if ($curr{$key} eq '') {
 6745:             $curr{$key} = $defaults{$key};
 6746:         }
 6747:     }
 6748:     my (%whodunit,%changed,$version);
 6749:     ($version) = ($r->dir_config('lonVersion') =~ /^([\d\.]+)\-/);
 6750:     my ($minshown,$maxshown);
 6751:     $minshown = 1;
 6752:     my $count = 0;
 6753:     if ($curr{'show'} =~ /\D/) {
 6754:         $curr{'page'} = 1;
 6755:     } else {
 6756:         $maxshown = $curr{'page'} * $curr{'show'};
 6757:         if ($curr{'page'} > 1) {
 6758:             $minshown = 1 + ($curr{'page'} - 1) * $curr{'show'};
 6759:         }
 6760:     }
 6761: 
 6762:     # Form Header
 6763:     $r->print('<form action="/adm/createuser" method="post" name="'.$formname.'">'.
 6764:               &role_display_filter($context,$formname,$domain,$username,\%curr,
 6765:                                    $version,$crstype));
 6766: 
 6767:     my $showntableheader = 0;
 6768: 
 6769:     # Table Header
 6770:     my $tableheader = 
 6771:         &Apache::loncommon::start_data_table_header_row()
 6772:        .'<th>&nbsp;</th>'
 6773:        .'<th>'.&mt('When').'</th>'
 6774:        .'<th>'.&mt('Who made the change').'</th>'
 6775:        .'<th>'.&mt('Changed User').'</th>'
 6776:        .'<th>'.&mt('Role').'</th>';
 6777: 
 6778:     if ($context eq 'course') {
 6779:         $tableheader .= '<th>'.&mt('Section').'</th>';
 6780:     }
 6781:     $tableheader .=
 6782:         '<th>'.&mt('Context').'</th>'
 6783:        .'<th>'.&mt('Start').'</th>'
 6784:        .'<th>'.&mt('End').'</th>'
 6785:        .&Apache::loncommon::end_data_table_header_row();
 6786: 
 6787:     # Display user change log data
 6788:     foreach my $id (sort { $roleslog{$b}{'exe_time'}<=>$roleslog{$a}{'exe_time'} } (keys(%roleslog))) {
 6789:         next if (($roleslog{$id}{'exe_time'} < $curr{'rolelog_start_date'}) ||
 6790:                  ($roleslog{$id}{'exe_time'} > $curr{'rolelog_end_date'}));
 6791:         if ($curr{'show'} !~ /\D/) {
 6792:             if ($count >= $curr{'page'} * $curr{'show'}) {
 6793:                 $more_records = 1;
 6794:                 last;
 6795:             }
 6796:         }
 6797:         if ($curr{'role'} ne 'any') {
 6798:             next if ($roleslog{$id}{'logentry'}{'role'} ne $curr{'role'}); 
 6799:         }
 6800:         if ($curr{'chgcontext'} ne 'any') {
 6801:             if ($curr{'chgcontext'} eq 'selfenroll') {
 6802:                 next if (!$roleslog{$id}{'logentry'}{'selfenroll'});
 6803:             } else {
 6804:                 next if ($roleslog{$id}{'logentry'}{'context'} ne $curr{'chgcontext'});
 6805:             }
 6806:         }
 6807:         if (($context eq 'course') && ($viewablesec ne '')) {
 6808:             next if ($roleslog{$id}{'logentry'}{'section'} ne $viewablesec);
 6809:         }
 6810:         $count ++;
 6811:         next if ($count < $minshown);
 6812:         unless ($showntableheader) {
 6813:             $r->print(&Apache::loncommon::start_data_table()
 6814:                      .$tableheader);
 6815:             $r->rflush();
 6816:             $showntableheader = 1;
 6817:         }
 6818:         if ($whodunit{$roleslog{$id}{'exe_uname'}.':'.$roleslog{$id}{'exe_udom'}} eq '') {
 6819:             $whodunit{$roleslog{$id}{'exe_uname'}.':'.$roleslog{$id}{'exe_udom'}} =
 6820:                 &Apache::loncommon::plainname($roleslog{$id}{'exe_uname'},$roleslog{$id}{'exe_udom'});
 6821:         }
 6822:         if ($changed{$roleslog{$id}{'uname'}.':'.$roleslog{$id}{'udom'}} eq '') {
 6823:             $changed{$roleslog{$id}{'uname'}.':'.$roleslog{$id}{'udom'}} =
 6824:                 &Apache::loncommon::plainname($roleslog{$id}{'uname'},$roleslog{$id}{'udom'});
 6825:         }
 6826:         my $sec = $roleslog{$id}{'logentry'}{'section'};
 6827:         if ($sec eq '') {
 6828:             $sec = &mt('None');
 6829:         }
 6830:         my ($rolestart,$roleend);
 6831:         if ($roleslog{$id}{'delflag'}) {
 6832:             $rolestart = &mt('deleted');
 6833:             $roleend = &mt('deleted');
 6834:         } else {
 6835:             $rolestart = $roleslog{$id}{'logentry'}{'start'};
 6836:             $roleend = $roleslog{$id}{'logentry'}{'end'};
 6837:             if ($rolestart eq '' || $rolestart == 0) {
 6838:                 $rolestart = &mt('No start date'); 
 6839:             } else {
 6840:                 $rolestart = &Apache::lonlocal::locallocaltime($rolestart);
 6841:             }
 6842:             if ($roleend eq '' || $roleend == 0) { 
 6843:                 $roleend = &mt('No end date');
 6844:             } else {
 6845:                 $roleend = &Apache::lonlocal::locallocaltime($roleend);
 6846:             }
 6847:         }
 6848:         my $chgcontext = $roleslog{$id}{'logentry'}{'context'};
 6849:         if ($roleslog{$id}{'logentry'}{'selfenroll'}) {
 6850:             $chgcontext = 'selfenroll';
 6851:         }
 6852:         my %lt = &rolechg_contexts($context,$crstype);
 6853:         if ($chgcontext ne '' && $lt{$chgcontext} ne '') {
 6854:             $chgcontext = $lt{$chgcontext};
 6855:         }
 6856:         $r->print(
 6857:             &Apache::loncommon::start_data_table_row()
 6858:            .'<td>'.$count.'</td>'
 6859:            .'<td>'.&Apache::lonlocal::locallocaltime($roleslog{$id}{'exe_time'}).'</td>'
 6860:            .'<td>'.$whodunit{$roleslog{$id}{'exe_uname'}.':'.$roleslog{$id}{'exe_udom'}}.'</td>'
 6861:            .'<td>'.$changed{$roleslog{$id}{'uname'}.':'.$roleslog{$id}{'udom'}}.'</td>'
 6862:            .'<td>'.&Apache::lonnet::plaintext($roleslog{$id}{'logentry'}{'role'},$crstype).'</td>');
 6863:         if ($context eq 'course') { 
 6864:             $r->print('<td>'.$sec.'</td>');
 6865:         }
 6866:         $r->print(
 6867:             '<td>'.$chgcontext.'</td>'
 6868:            .'<td>'.$rolestart.'</td>'
 6869:            .'<td>'.$roleend.'</td>'
 6870:            .&Apache::loncommon::end_data_table_row()."\n");
 6871:     }
 6872: 
 6873:     if ($showntableheader) { # Table footer, if content displayed above
 6874:         $r->print(&Apache::loncommon::end_data_table().
 6875:                   &userlogdisplay_navlinks(\%curr,$more_records));
 6876:     } else { # No content displayed above
 6877:         $r->print('<p class="LC_info">'
 6878:                  .&mt('There are no records to display.')
 6879:                  .'</p>'
 6880:         );
 6881:     }
 6882: 
 6883:     # Form Footer
 6884:     $r->print( 
 6885:         '<input type="hidden" name="page" value="'.$curr{'page'}.'" />'
 6886:        .'<input type="hidden" name="action" value="changelogs" />'
 6887:        .'</form>');
 6888:     return;
 6889: }
 6890: 
 6891: sub print_useraccesslogs_display {
 6892:     my ($r,$uname,$udom,$permission,$brcrum) = @_;
 6893:     my $formname = 'accesslog';
 6894:     my $form = 'document.accesslog';
 6895: 
 6896: # set breadcrumbs
 6897:     my %breadcrumb_text = &singleuser_breadcrumb('','domain',$udom);
 6898:     my $prevphasestr;
 6899:     if ($env{'form.popup'}) {
 6900:         $brcrum = [];
 6901:     } else {
 6902:         push (@{$brcrum},
 6903:             {href => "javascript:backPage($form)",
 6904:              text => $breadcrumb_text{'search'}});
 6905:         my @prevphases;
 6906:         if ($env{'form.prevphases'}) {
 6907:             @prevphases = split(/,/,$env{'form.prevphases'});
 6908:             $prevphasestr = $env{'form.prevphases'};
 6909:         }
 6910:         if (($env{'form.phase'} eq 'userpicked') || (grep(/^userpicked$/,@prevphases))) {
 6911:             push(@{$brcrum},
 6912:                   {href => "javascript:backPage($form,'get_user_info','select')",
 6913:                    text => $breadcrumb_text{'userpicked'}});
 6914:             if ($env{'form.phase'} eq 'userpicked') {
 6915:                 $prevphasestr = 'userpicked';
 6916:             }
 6917:         }
 6918:     }
 6919:     push(@{$brcrum},
 6920:              {href => '/adm/createuser?action=accesslogs',
 6921:               text => 'User access logs',
 6922:               help => 'Domain_User_Access_Logs'});
 6923:     my $bread_crumbs_component = 'User Access Logs';
 6924:     my $args = { bread_crumbs           => $brcrum,
 6925:                  bread_crumbs_component => 'User Management'};
 6926:     if ($env{'form.popup'}) {
 6927:         $args->{'no_nav_bar'} = 1;
 6928:         $args->{'bread_crumbs_nomenu'} = 1;
 6929:     }
 6930: 
 6931: # set javascript
 6932:     my ($jsback,$elements) = &crumb_utilities();
 6933:     my $jsnav = &userlogdisplay_js($formname);
 6934: 
 6935:     my $jscript = (<<ENDSCRIPT);
 6936: <script type="text/javascript">
 6937: // <![CDATA[
 6938: 
 6939: $jsback
 6940: $jsnav
 6941: 
 6942: // ]]>
 6943: </script>
 6944: 
 6945: ENDSCRIPT
 6946: 
 6947: # print page header
 6948:     $r->print(&header($jscript,$args));
 6949: 
 6950: # early out unless log data can be displayed.
 6951:     unless ($permission->{'activity'}) {
 6952:         $r->print('<p class="LC_warning">'
 6953:                  .&mt('You do not have rights to display user access logs.')
 6954:                  .'</p>');
 6955:         if ($env{'form.popup'}) {
 6956:             $r->print('<p><a href="javascript:window.close()">'.&mt('Close window').'</a></p>');
 6957:         } else {
 6958:             $r->print(&earlyout_accesslog_form($formname,$prevphasestr,$udom));
 6959:         }
 6960:         return;
 6961:     }
 6962: 
 6963:     unless ($udom eq $env{'request.role.domain'}) {
 6964:         $r->print('<p class="LC_warning">'
 6965:                  .&mt("User's domain must match role's domain")
 6966:                  .'</p>'
 6967:                  .&earlyout_accesslog_form($formname,$prevphasestr,$udom));
 6968:         return;
 6969:     }
 6970: 
 6971:     if (($uname eq '') || ($udom eq '')) {
 6972:         $r->print('<p class="LC_warning">'
 6973:                  .&mt('Invalid username or domain')
 6974:                  .'</p>'
 6975:                  .&earlyout_accesslog_form($formname,$prevphasestr,$udom));
 6976:         return;
 6977:     }
 6978: 
 6979:     if (&Apache::lonnet::privileged($uname,$udom,
 6980:                                     [$env{'request.role.domain'}],['dc','su'])) {
 6981:         unless (&Apache::lonnet::privileged($env{'user.name'},$env{'user.domain'},
 6982:                                             [$env{'request.role.domain'}],['dc','su'])) {
 6983:             $r->print('<p class="LC_warning">'
 6984:                  .&mt('You need to be a privileged user to display user access logs for [_1]',
 6985:                       &Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($uname,$udom),
 6986:                                                          $uname,$udom))
 6987:                  .'</p>');
 6988:             if ($env{'form.popup'}) {
 6989:                 $r->print('<p><a href="javascript:window.close()">'.&mt('Close window').'</a></p>');
 6990:             } else {
 6991:                 $r->print(&earlyout_accesslog_form($formname,$prevphasestr,$udom));
 6992:             }
 6993:             return;
 6994:         }
 6995:     }
 6996: 
 6997: # set defaults
 6998:     my $now = time();
 6999:     my $defstart = $now - (7*24*3600);
 7000:     my %defaults = (
 7001:                      page                 => '1',
 7002:                      show                 => '10',
 7003:                      activity             => 'any',
 7004:                      accesslog_start_date => $defstart,
 7005:                      accesslog_end_date   => $now,
 7006:                    );
 7007:     my $more_records = 0;
 7008: 
 7009: # set current
 7010:     my %curr;
 7011:     foreach my $item ('show','page','activity') {
 7012:         $curr{$item} = $env{'form.'.$item};
 7013:     }
 7014:     my ($startdate,$enddate) =
 7015:         &Apache::lonuserutils::get_dates_from_form('accesslog_start_date','accesslog_end_date');
 7016:     $curr{'accesslog_start_date'} = $startdate;
 7017:     $curr{'accesslog_end_date'} = $enddate;
 7018:     foreach my $key (keys(%defaults)) {
 7019:         if ($curr{$key} eq '') {
 7020:             $curr{$key} = $defaults{$key};
 7021:         }
 7022:     }
 7023:     my ($minshown,$maxshown);
 7024:     $minshown = 1;
 7025:     my $count = 0;
 7026:     if ($curr{'show'} =~ /\D/) {
 7027:         $curr{'page'} = 1;
 7028:     } else {
 7029:         $maxshown = $curr{'page'} * $curr{'show'};
 7030:         if ($curr{'page'} > 1) {
 7031:             $minshown = 1 + ($curr{'page'} - 1) * $curr{'show'};
 7032:         }
 7033:     }
 7034: 
 7035: # form header
 7036:     $r->print('<form action="/adm/createuser" method="post" name="'.$formname.'">'.
 7037:               &activity_display_filter($formname,\%curr));
 7038: 
 7039:     my $showntableheader = 0;
 7040:     my ($nav_script,$nav_links);
 7041: 
 7042: # table header
 7043:     my $tableheader = '<h3>'.
 7044:         &mt('User access logs for: [_1]',
 7045:             &Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($uname,$udom),$uname,$udom)).'</h3>'
 7046:        .&Apache::loncommon::start_data_table_header_row()
 7047:        .'<th>&nbsp;</th>'
 7048:        .'<th>'.&mt('When').'</th>'
 7049:        .'<th>'.&mt('HostID').'</th>'
 7050:        .'<th>'.&mt('Event').'</th>'
 7051:        .'<th>'.&mt('Other data').'</th>'
 7052:        .&Apache::loncommon::end_data_table_header_row();
 7053: 
 7054:     my %filters=(
 7055:         start  => $curr{'accesslog_start_date'},
 7056:         end    => $curr{'accesslog_end_date'},
 7057:         action => $curr{'activity'},
 7058:     );
 7059: 
 7060:     my $reply = &Apache::lonnet::userlog_query($uname,$udom,%filters);
 7061:     unless ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 7062:         my (%courses,%missing);
 7063:         my @results = split(/\&/,$reply);
 7064:         foreach my $item (reverse(@results)) {
 7065:             my ($timestamp,$host,$event) = split(/:/,$item);
 7066:             next unless ($event =~ /^(Log|Role)/);
 7067:             if ($curr{'show'} !~ /\D/) {
 7068:                 if ($count >= $curr{'page'} * $curr{'show'}) {
 7069:                     $more_records = 1;
 7070:                     last;
 7071:                 }
 7072:             }
 7073:             $count ++;
 7074:             next if ($count < $minshown);
 7075:             unless ($showntableheader) {
 7076:                 $r->print($nav_script
 7077:                          .&Apache::loncommon::start_data_table()
 7078:                          .$tableheader);
 7079:                 $r->rflush();
 7080:                 $showntableheader = 1;
 7081:             }
 7082:             my ($shown,$extra);
 7083:             my ($event,$data) = split(/\s+/,&unescape($event),2);
 7084:             if ($event eq 'Role') {
 7085:                 my ($rolecode,$extent) = split(/\./,$data,2);
 7086:                 next if ($extent eq '');
 7087:                 my ($crstype,$desc,$info);
 7088:                 if ($extent =~ m{^/($match_domain)/($match_courseid)(?:/(\w+)|)$}) {
 7089:                     my ($cdom,$cnum,$sec) = ($1,$2,$3);
 7090:                     my $cid = $cdom.'_'.$cnum;
 7091:                     if (exists($courses{$cid})) {
 7092:                         $crstype = $courses{$cid}{'type'};
 7093:                         $desc = $courses{$cid}{'description'};
 7094:                     } elsif ($missing{$cid}) {
 7095:                         $crstype = 'Course';
 7096:                         $desc = 'Course/Community';
 7097:                     } else {
 7098:                         my %crsinfo = &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 7099:                         if (ref($crsinfo{$cdom.'_'.$cnum}) eq 'HASH') {
 7100:                             $courses{$cid} = $crsinfo{$cid};
 7101:                             $crstype = $crsinfo{$cid}{'type'};
 7102:                             $desc = $crsinfo{$cid}{'description'};
 7103:                         } else {
 7104:                             $missing{$cid} = 1;
 7105:                         }
 7106:                     }
 7107:                     $extra = &mt($crstype).': <a href="/public/'.$cdom.'/'.$cnum.'/syllabus">'.$desc.'</a>';
 7108:                     if ($sec ne '') {
 7109:                        $extra .= ' ('.&mt('Section: [_1]',$sec).')';
 7110:                     }
 7111:                 } elsif ($extent =~ m{^/($match_domain)/($match_username|$)}) {
 7112:                     my ($dom,$name) = ($1,$2);
 7113:                     if ($rolecode eq 'au') {
 7114:                         $extra = '';
 7115:                     } elsif ($rolecode =~ /^(ca|aa)$/) {
 7116:                         $extra = &mt('Authoring Space: [_1]',$name.':'.$dom);
 7117:                     } elsif ($rolecode =~ /^(li|dg|dh|dc|sc)$/) {
 7118:                         $extra = &mt('Domain: [_1]',$dom);
 7119:                     }
 7120:                 }
 7121:                 my $rolename;
 7122:                 if ($rolecode =~ m{^cr/($match_domain)/($match_username)/(\w+)}) {
 7123:                     my $role = $3;
 7124:                     my $owner = "($2:$1)";
 7125:                     if ($2 eq $1.'-domainconfig') {
 7126:                         $owner = '(ad hoc)';
 7127:                     }
 7128:                     $rolename = &mt('Custom role: [_1]',$role.' '.$owner);
 7129:                 } else {
 7130:                     $rolename = &Apache::lonnet::plaintext($rolecode,$crstype);
 7131:                 }
 7132:                 $shown = &mt('Role selection: [_1]',$rolename);
 7133:             } else {
 7134:                 $shown = &mt($event);
 7135:                 if ($data =~ /^webdav/) {
 7136:                     my ($path,$clientip) = split(/\s+/,$data,2);
 7137:                     $path =~ s/^webdav//;
 7138:                     if ($clientip ne '') {
 7139:                         $extra = &mt('Client IP address: [_1]',$clientip);
 7140:                     }
 7141:                     if ($path ne '') {
 7142:                         $shown .= ' '.&mt('(WebDAV access to [_1])',$path);
 7143:                     }
 7144:                 } elsif ($data ne '') {
 7145:                     $extra = &mt('Client IP address: [_1]',$data);
 7146:                 }
 7147:             }
 7148:             $r->print(
 7149:             &Apache::loncommon::start_data_table_row()
 7150:            .'<td>'.$count.'</td>'
 7151:            .'<td>'.&Apache::lonlocal::locallocaltime($timestamp).'</td>'
 7152:            .'<td>'.$host.'</td>'
 7153:            .'<td>'.$shown.'</td>'
 7154:            .'<td>'.$extra.'</td>'
 7155:            .&Apache::loncommon::end_data_table_row()."\n");
 7156:         }
 7157:     }
 7158: 
 7159:     if ($showntableheader) { # Table footer, if content displayed above
 7160:         $r->print(&Apache::loncommon::end_data_table().
 7161:                   &userlogdisplay_navlinks(\%curr,$more_records));
 7162:     } else { # No content displayed above
 7163:         $r->print('<p class="LC_info">'
 7164:                  .&mt('There are no records to display.')
 7165:                  .'</p>');
 7166:     }
 7167: 
 7168:     if ($env{'form.popup'} == 1) {
 7169:         $r->print('<input type="hidden" name="popup" value="1" />'."\n");
 7170:     }
 7171: 
 7172:     # Form Footer
 7173:     $r->print(
 7174:         '<input type="hidden" name="currstate" value="" />'
 7175:        .'<input type="hidden" name="accessuname" value="'.$uname.'" />'
 7176:        .'<input type="hidden" name="accessudom" value="'.$udom.'" />'
 7177:        .'<input type="hidden" name="page" value="'.$curr{'page'}.'" />'
 7178:        .'<input type="hidden" name="prevphases" value="'.$prevphasestr.'" />'
 7179:        .'<input type="hidden" name="phase" value="activity" />'
 7180:        .'<input type="hidden" name="action" value="accesslogs" />'
 7181:        .'<input type="hidden" name="srchdomain" value="'.$udom.'" />'
 7182:        .'<input type="hidden" name="srchby" value="'.$env{'form.srchby'}.'" />'
 7183:        .'<input type="hidden" name="srchtype" value="'.$env{'form.srchtype'}.'" />'
 7184:        .'<input type="hidden" name="srchterm" value="'.&HTML::Entities::encode($env{'form.srchterm'},'<>"&').'" />'
 7185:        .'<input type="hidden" name="srchin" value="'.$env{'form.srchin'}.'" />'
 7186:        .'</form>');
 7187:     return;
 7188: }
 7189: 
 7190: sub earlyout_accesslog_form {
 7191:     my ($formname,$prevphasestr,$udom) = @_;
 7192:     my $srchterm = &HTML::Entities::encode($env{'form.srchterm'},'<>"&');
 7193:    return <<"END";
 7194: <form action="/adm/createuser" method="post" name="$formname">
 7195: <input type="hidden" name="currstate" value="" />
 7196: <input type="hidden" name="prevphases" value="$prevphasestr" />
 7197: <input type="hidden" name="phase" value="activity" />
 7198: <input type="hidden" name="action" value="accesslogs" />
 7199: <input type="hidden" name="srchdomain" value="$udom" />
 7200: <input type="hidden" name="srchby" value="$env{'form.srchby'}" />
 7201: <input type="hidden" name="srchtype" value="$env{'form.srchtype'}" />
 7202: <input type="hidden" name="srchterm" value="$srchterm" />
 7203: <input type="hidden" name="srchin" value="$env{'form.srchin'}" />
 7204: </form>
 7205: END
 7206: }
 7207: 
 7208: sub activity_display_filter {
 7209:     my ($formname,$curr) = @_;
 7210:     my $nolink = 1;
 7211:     my $output = '<table><tr><td valign="top">'.
 7212:                  '<span class="LC_nobreak"><b>'.&mt('Actions/page:').'</b></span><br />'.
 7213:                  &Apache::lonmeta::selectbox('show',$curr->{'show'},undef,
 7214:                                               (&mt('all'),5,10,20,50,100,1000,10000)).
 7215:                  '</td><td>&nbsp;&nbsp;</td>';
 7216:     my $startform =
 7217:         &Apache::lonhtmlcommon::date_setter($formname,'accesslog_start_date',
 7218:                                             $curr->{'accesslog_start_date'},undef,
 7219:                                             undef,undef,undef,undef,undef,undef,$nolink);
 7220:     my $endform =
 7221:         &Apache::lonhtmlcommon::date_setter($formname,'accesslog_end_date',
 7222:                                             $curr->{'accesslog_end_date'},undef,
 7223:                                             undef,undef,undef,undef,undef,undef,$nolink);
 7224:     my %lt = &Apache::lonlocal::texthash (
 7225:                                           activity => 'Activity',
 7226:                                           Role     => 'Role selection',
 7227:                                           log      => 'Log-in or Logout',
 7228:     );
 7229:     $output .= '<td valign="top"><b>'.&mt('Window during which actions 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('Activities').'</b><br />'.
 7237:                '<select name="activity"><option value="any"';
 7238:     if ($curr->{'activity'} eq 'any') {
 7239:         $output .= ' selected="selected"';
 7240:     }
 7241:     $output .= '>'.&mt('Any').'</option>'."\n";
 7242:     foreach my $activity ('Role','log') {
 7243:         my $selstr = '';
 7244:         if ($activity eq $curr->{'activity'}) {
 7245:             $selstr = ' selected="selected"';
 7246:         }
 7247:         $output .= '<option value="'.$activity.'"'.$selstr.'>'.$lt{$activity}.'</option>';
 7248:     }
 7249:     $output .= '</select></td>'.
 7250:                '</tr></table>';
 7251:     # Update Display button
 7252:     $output .= '<p>'
 7253:               .'<input type="submit" value="'.&mt('Update Display').'" />'
 7254:               .'</p><hr />';
 7255:     return $output;
 7256: }
 7257: 
 7258: sub userlogdisplay_js {
 7259:     my ($formname) = @_;
 7260:     return <<"ENDSCRIPT";
 7261: 
 7262: function chgPage(caller) {
 7263:     if (caller == 'previous') {
 7264:         document.$formname.page.value --;
 7265:     }
 7266:     if (caller == 'next') {
 7267:         document.$formname.page.value ++;
 7268:     }
 7269:     document.$formname.submit();
 7270:     return;
 7271: }
 7272: ENDSCRIPT
 7273: }
 7274: 
 7275: sub userlogdisplay_navlinks {
 7276:     my ($curr,$more_records) = @_;
 7277:     return unless(ref($curr) eq 'HASH');
 7278:     # Navigation Buttons
 7279:     my $nav_links = '<p>';
 7280:     if (($curr->{'page'} > 1) || ($more_records)) {
 7281:         if (($curr->{'page'} > 1) && ($curr->{'show'} !~ /\D/)) {
 7282:             $nav_links .= '<input type="button"'
 7283:                          .' onclick="javascript:chgPage('."'previous'".');"'
 7284:                          .' value="'.&mt('Previous [_1] changes',$curr->{'show'})
 7285:                          .'" /> ';
 7286:         }
 7287:         if ($more_records) {
 7288:             $nav_links .= '<input type="button"'
 7289:                          .' onclick="javascript:chgPage('."'next'".');"'
 7290:                          .' value="'.&mt('Next [_1] changes',$curr->{'show'})
 7291:                          .'" />';
 7292:         }
 7293:     }
 7294:     $nav_links .= '</p>';
 7295:     return $nav_links;
 7296: }
 7297: 
 7298: sub role_display_filter {
 7299:     my ($context,$formname,$cdom,$cnum,$curr,$version,$crstype) = @_;
 7300:     my $lctype;
 7301:     if ($context eq 'course') {
 7302:         $lctype = lc($crstype);
 7303:     }
 7304:     my $nolink = 1;
 7305:     my $output = '<table><tr><td valign="top">'.
 7306:                  '<span class="LC_nobreak"><b>'.&mt('Changes/page:').'</b></span><br />'.
 7307:                  &Apache::lonmeta::selectbox('show',$curr->{'show'},undef,
 7308:                                               (&mt('all'),5,10,20,50,100,1000,10000)).
 7309:                  '</td><td>&nbsp;&nbsp;</td>';
 7310:     my $startform =
 7311:         &Apache::lonhtmlcommon::date_setter($formname,'rolelog_start_date',
 7312:                                             $curr->{'rolelog_start_date'},undef,
 7313:                                             undef,undef,undef,undef,undef,undef,$nolink);
 7314:     my $endform =
 7315:         &Apache::lonhtmlcommon::date_setter($formname,'rolelog_end_date',
 7316:                                             $curr->{'rolelog_end_date'},undef,
 7317:                                             undef,undef,undef,undef,undef,undef,$nolink);
 7318:     my %lt = &rolechg_contexts($context,$crstype);
 7319:     $output .= '<td valign="top"><b>'.&mt('Window during which changes occurred:').'</b><br />'.
 7320:                '<table><tr><td>'.&mt('After:').
 7321:                '</td><td>'.$startform.'</td></tr>'.
 7322:                '<tr><td>'.&mt('Before:').'</td>'.
 7323:                '<td>'.$endform.'</td></tr></table>'.
 7324:                '</td>'.
 7325:                '<td>&nbsp;&nbsp;</td>'.
 7326:                '<td valign="top"><b>'.&mt('Role:').'</b><br />'.
 7327:                '<select name="role"><option value="any"';
 7328:     if ($curr->{'role'} eq 'any') {
 7329:         $output .= ' selected="selected"';
 7330:     }
 7331:     $output .=  '>'.&mt('Any').'</option>'."\n";
 7332:     my @roles = &Apache::lonuserutils::roles_by_context($context,1,$crstype);
 7333:     foreach my $role (@roles) {
 7334:         my $plrole;
 7335:         if ($role eq 'cr') {
 7336:             $plrole = &mt('Custom Role');
 7337:         } else {
 7338:             $plrole=&Apache::lonnet::plaintext($role,$crstype);
 7339:         }
 7340:         my $selstr = '';
 7341:         if ($role eq $curr->{'role'}) {
 7342:             $selstr = ' selected="selected"';
 7343:         }
 7344:         $output .= '  <option value="'.$role.'"'.$selstr.'>'.$plrole.'</option>';
 7345:     }
 7346:     $output .= '</select></td>'.
 7347:                '<td>&nbsp;&nbsp;</td>'.
 7348:                '<td valign="top"><b>'.
 7349:                &mt('Context:').'</b><br /><select name="chgcontext">';
 7350:     my @posscontexts;
 7351:     if ($context eq 'course') {
 7352:         @posscontexts = ('any','automated','updatenow','createcourse','course','domain','selfenroll','requestcourses');
 7353:     } elsif ($context eq 'domain') {
 7354:         @posscontexts = ('any','domain','requestauthor','domconfig','server');
 7355:     } else {
 7356:         @posscontexts = ('any','author','domain');
 7357:     } 
 7358:     foreach my $chgtype (@posscontexts) {
 7359:         my $selstr = '';
 7360:         if ($curr->{'chgcontext'} eq $chgtype) {
 7361:             $selstr = ' selected="selected"';
 7362:         }
 7363:         if ($context eq 'course') {
 7364:             if (($chgtype eq 'automated') || ($chgtype eq 'updatenow')) {
 7365:                 next if (!&Apache::lonnet::auto_run($cnum,$cdom));
 7366:             }
 7367:         }
 7368:         $output .= '<option value="'.$chgtype.'"'.$selstr.'>'.$lt{$chgtype}.'</option>'."\n";
 7369:     }
 7370:     $output .= '</select></td>'
 7371:               .'</tr></table>';
 7372: 
 7373:     # Update Display button
 7374:     $output .= '<p>'
 7375:               .'<input type="submit" value="'.&mt('Update Display').'" />'
 7376:               .'</p>';
 7377: 
 7378:     # Server version info
 7379:     my $needsrev = '2.11.0';
 7380:     if ($context eq 'course') {
 7381:         $needsrev = '2.7.0';
 7382:     }
 7383:     
 7384:     $output .= '<p class="LC_info">'
 7385:               .&mt('Only changes made from servers running LON-CAPA [_1] or later are displayed.'
 7386:                   ,$needsrev);
 7387:     if ($version) {
 7388:         $output .= ' '.&mt('This LON-CAPA server is version [_1]',$version);
 7389:     }
 7390:     $output .= '</p><hr />';
 7391:     return $output;
 7392: }
 7393: 
 7394: sub rolechg_contexts {
 7395:     my ($context,$crstype) = @_;
 7396:     my %lt;
 7397:     if ($context eq 'course') {
 7398:         %lt = &Apache::lonlocal::texthash (
 7399:                                              any          => 'Any',
 7400:                                              automated    => 'Automated Enrollment',
 7401:                                              updatenow    => 'Roster Update',
 7402:                                              createcourse => 'Course Creation',
 7403:                                              course       => 'User Management in course',
 7404:                                              domain       => 'User Management in domain',
 7405:                                              selfenroll   => 'Self-enrolled',
 7406:                                              requestcourses => 'Course Request',
 7407:                                          );
 7408:         if ($crstype eq 'Community') {
 7409:             $lt{'createcourse'} = &mt('Community Creation');
 7410:             $lt{'course'} = &mt('User Management in community');
 7411:             $lt{'requestcourses'} = &mt('Community Request');
 7412:         }
 7413:     } elsif ($context eq 'domain') {
 7414:         %lt = &Apache::lonlocal::texthash (
 7415:                                              any           => 'Any',
 7416:                                              domain        => 'User Management in domain',
 7417:                                              requestauthor => 'Authoring Request',
 7418:                                              server        => 'Command line script (DC role)',
 7419:                                              domconfig     => 'Self-enrolled',
 7420:                                          );
 7421:     } else {
 7422:         %lt = &Apache::lonlocal::texthash (
 7423:                                              any    => 'Any',
 7424:                                              domain => 'User Management in domain',
 7425:                                              author => 'User Management by author',
 7426:                                          );
 7427:     } 
 7428:     return %lt;
 7429: }
 7430: 
 7431: sub print_helpdeskaccess_display {
 7432:     my ($r,$permission,$brcrum) = @_;
 7433:     my $formname = 'helpdeskaccess';
 7434:     my $helpitem = 'Course_Helpdesk_Access';
 7435:     push (@{$brcrum},
 7436:              {href => '/adm/createuser?action=helpdesk',
 7437:               text => 'Helpdesk Access',
 7438:               help => $helpitem});
 7439:     my $bread_crumbs_component = 'Helpdesk Staff Access';
 7440:     my $args = { bread_crumbs           => $brcrum,
 7441:                  bread_crumbs_component => $bread_crumbs_component};
 7442: 
 7443:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7444:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7445:     my $confname = $cdom.'-domainconfig';
 7446:     my $crstype = &Apache::loncommon::course_type();
 7447: 
 7448:     my @accesstypes = ('all','dh','da','none');
 7449:     my ($numstatustypes,@jsarray);
 7450:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($cdom);
 7451:     if (ref($types) eq 'ARRAY') {
 7452:         if (@{$types} > 0) {
 7453:             $numstatustypes = scalar(@{$types});
 7454:             push(@accesstypes,'status');
 7455:             @jsarray = ('bystatus');
 7456:         }
 7457:     }
 7458:     my %customroles = &get_domain_customroles($cdom,$confname);
 7459:     my %domhelpdesk = &Apache::lonnet::get_active_domroles($cdom,['dh','da']);
 7460:     if (keys(%domhelpdesk)) {
 7461:        push(@accesstypes,('inc','exc'));
 7462:        push(@jsarray,('notinc','notexc'));
 7463:     }
 7464:     push(@jsarray,'privs');
 7465:     my $hiddenstr = join("','",@jsarray);
 7466:     my $rolestr = join("','",sort(keys(%customroles)));
 7467: 
 7468:     my $jscript;
 7469:     my (%settings,%overridden);
 7470:     if (keys(%customroles)) {
 7471:         &get_adhocrole_settings($env{'request.course.id'},\@accesstypes,
 7472:                                 $types,\%customroles,\%settings,\%overridden);
 7473:         my %jsfull=();
 7474:         my %jslevels= (
 7475:                      course => {},
 7476:                      domain => {},
 7477:                      system => {},
 7478:                     );
 7479:         my %jslevelscurrent=(
 7480:                            course => {},
 7481:                            domain => {},
 7482:                            system => {},
 7483:                           );
 7484:         my (%privs,%jsprivs);
 7485:         &Apache::lonuserutils::custom_role_privs(\%privs,\%jsfull,\%jslevels,\%jslevelscurrent);
 7486:         foreach my $priv (keys(%jsfull)) {
 7487:             if ($jslevels{'course'}{$priv}) {
 7488:                 $jsprivs{$priv} = 1;
 7489:             }
 7490:         }
 7491:         my (%elements,%stored);
 7492:         foreach my $role (keys(%customroles)) {
 7493:             $elements{$role.'_access'} = 'radio';
 7494:             $elements{$role.'_incrs'} = 'radio';
 7495:             if ($numstatustypes) {
 7496:                 $elements{$role.'_status'} = 'checkbox';
 7497:             }
 7498:             if (keys(%domhelpdesk) > 0) {
 7499:                 $elements{$role.'_staff_inc'} = 'checkbox';
 7500:                 $elements{$role.'_staff_exc'} = 'checkbox';
 7501:             }
 7502:             $elements{$role.'_override'} = 'checkbox';
 7503:             if (ref($settings{$role}) eq 'HASH') {
 7504:                 if ($settings{$role}{'access'} ne '') {
 7505:                     my $curraccess = $settings{$role}{'access'};
 7506:                     $stored{$role.'_access'} = $curraccess;
 7507:                     $stored{$role.'_incrs'} = 1;
 7508:                     if ($curraccess eq 'status') {
 7509:                         if (ref($settings{$role}{'status'}) eq 'ARRAY') {
 7510:                             $stored{$role.'_status'} = $settings{$role}{'status'};
 7511:                         }
 7512:                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 7513:                         if (ref($settings{$role}{$curraccess}) eq 'ARRAY') {
 7514:                             $stored{$role.'_staff_'.$curraccess} = $settings{$role}{$curraccess};
 7515:                         }
 7516:                     }
 7517:                 } else {
 7518:                     $stored{$role.'_incrs'} = 0;
 7519:                 }
 7520:                 $stored{$role.'_override'} = [];
 7521:                 if ($env{'course.'.$env{'request.course.id'}.'.internal.adhocpriv.'.$role}) {
 7522:                     if (ref($settings{$role}{'off'}) eq 'ARRAY') {
 7523:                         foreach my $priv (@{$settings{$role}{'off'}}) {
 7524:                             push(@{$stored{$role.'_override'}},$priv);
 7525:                         }
 7526:                     }
 7527:                     if (ref($settings{$role}{'on'}) eq 'ARRAY') {
 7528:                         foreach my $priv (@{$settings{$role}{'on'}}) {
 7529:                             unless (grep(/^$priv$/,@{$stored{$role.'_override'}})) {
 7530:                                 push(@{$stored{$role.'_override'}},$priv);
 7531:                             }
 7532:                         }
 7533:                     }
 7534:                 }
 7535:             } else {
 7536:                 $stored{$role.'_incrs'} = 0;
 7537:             }
 7538:         }
 7539:         $jscript = &Apache::lonhtmlcommon::set_form_elements(\%elements,\%stored);
 7540:     }
 7541: 
 7542:     my $js = <<"ENDJS";
 7543: <script type="text/javascript">
 7544: // <![CDATA[
 7545: $jscript;
 7546: 
 7547: function switchRoleTab(caller,role) {
 7548:     if (document.getElementById(role+'_maindiv')) {
 7549:         if (caller.id != 'LC_current_minitab') {
 7550:             if (document.getElementById('LC_current_minitab')) {
 7551:                 document.getElementById('LC_current_minitab').id=null;
 7552:             }
 7553:             var roledivs = Array('$rolestr');
 7554:             if (roledivs.length > 0) {
 7555:                 for (var i=0; i<roledivs.length; i++) {
 7556:                     if (document.getElementById(roledivs[i]+'_maindiv')) {
 7557:                         document.getElementById(roledivs[i]+'_maindiv').style.display='none';
 7558:                     }
 7559:                 }
 7560:             }
 7561:             caller.id = 'LC_current_minitab';
 7562:             document.getElementById(role+'_maindiv').style.display='block';
 7563:         }
 7564:     }
 7565:     return false;
 7566: }
 7567: 
 7568: function helpdeskAccess(role) {
 7569:     var curraccess = null;
 7570:     if (document.$formname.elements[role+'_access'].length) {
 7571:         for (var i=0; i<document.$formname.elements[role+'_access'].length; i++) {
 7572:             if (document.$formname.elements[role+'_access'][i].checked) {
 7573:                 curraccess = document.$formname.elements[role+'_access'][i].value;
 7574:             }
 7575:         }
 7576:     }
 7577:     var shown = Array();
 7578:     var hidden = Array();
 7579:     if (curraccess == 'none') {
 7580:         hidden = Array ('$hiddenstr');
 7581:     } else {
 7582:         if (curraccess == 'status') {
 7583:             shown = Array ('bystatus','privs');
 7584:             hidden = Array ('notinc','notexc');
 7585:         } else {
 7586:             if (curraccess == 'exc') {
 7587:                 shown = Array ('notexc','privs');
 7588:                 hidden = Array ('notinc','bystatus');
 7589:             }
 7590:             if (curraccess == 'inc') {
 7591:                 shown = Array ('notinc','privs');
 7592:                 hidden = Array ('notexc','bystatus');
 7593:             }
 7594:             if (curraccess == 'all') {
 7595:                 shown = Array ('privs');
 7596:                 hidden = Array ('notinc','notexc','bystatus');
 7597:             }
 7598:         }
 7599:     }
 7600:     if (hidden.length > 0) {
 7601:         for (var i=0; i<hidden.length; i++) {
 7602:             if (document.getElementById(role+'_'+hidden[i])) {
 7603:                 document.getElementById(role+'_'+hidden[i]).style.display = 'none';
 7604:             }
 7605:         }
 7606:     }
 7607:     if (shown.length > 0) {
 7608:         for (var i=0; i<shown.length; i++) {
 7609:             if (document.getElementById(role+'_'+shown[i])) {
 7610:                 if (shown[i] == 'privs') {
 7611:                     document.getElementById(role+'_'+shown[i]).style.display = 'block';
 7612:                 } else {
 7613:                     document.getElementById(role+'_'+shown[i]).style.display = 'inline';
 7614:                 }
 7615:             }
 7616:         }
 7617:     }
 7618:     return;
 7619: }
 7620: 
 7621: function toggleAccess(role) {
 7622:     if ((document.getElementById(role+'_setincrs')) &&
 7623:         (document.getElementById(role+'_setindom'))) {
 7624:         for (var i=0; i<document.$formname.elements[role+'_incrs'].length; i++) {
 7625:             if (document.$formname.elements[role+'_incrs'][i].checked) {
 7626:                 if (document.$formname.elements[role+'_incrs'][i].value == 1) {
 7627:                     document.getElementById(role+'_setindom').style.display = 'none';
 7628:                     document.getElementById(role+'_setincrs').style.display = 'block';
 7629:                 } else {
 7630:                     document.getElementById(role+'_setincrs').style.display = 'none';
 7631:                     document.getElementById(role+'_setindom').style.display = 'block';
 7632:                 }
 7633:                 break;
 7634:             }
 7635:         }
 7636:     }
 7637:     return;
 7638: }
 7639: 
 7640: // ]]>
 7641: </script>
 7642: ENDJS
 7643: 
 7644:     $args->{add_entries} = {onload => "javascript:setFormElements(document.$formname)"};
 7645: 
 7646:     # print page header
 7647:     $r->print(&header($js,$args));
 7648:     # print form header
 7649:     $r->print('<form action="/adm/createuser" method="post" name="'.$formname.'">');
 7650: 
 7651:     if (keys(%customroles)) {
 7652:         my %lt = &Apache::lonlocal::texthash(
 7653:                     'aco'    => 'As course owner you may override the defaults set in the domain for role usage and/or privileges.',
 7654:                     'rou'    => 'Role usage',
 7655:                     'whi'    => 'Which helpdesk personnel may use this role?',
 7656:                     'udd'    => 'Use domain default',
 7657:                     'all'    => 'All with domain helpdesk or helpdesk assistant role',
 7658:                     'dh'     => 'All with domain helpdesk role',
 7659:                     'da'     => 'All with domain helpdesk assistant role',
 7660:                     'none'   => 'None',
 7661:                     'status' => 'Determined based on institutional status',
 7662:                     'inc'    => 'Include all, but exclude specific personnel',
 7663:                     'exc'    => 'Exclude all, but include specific personnel',
 7664:                     'hel'    => 'Helpdesk',
 7665:                     'rpr'    => 'Role privileges',
 7666:                  );
 7667:         $lt{'tfh'} = &mt("Custom [_1]ad hoc[_2] course roles available for use by the domain's helpdesk are as follows",'<i>','</i>');
 7668:         my %domconfig = &Apache::lonnet::get_dom('configuration',['helpsettings'],$cdom);
 7669:         my (%domcurrent,%ordered,%description,%domusage,$disabled);
 7670:         if (ref($domconfig{'helpsettings'}) eq 'HASH') {
 7671:             if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
 7672:                 %domcurrent = %{$domconfig{'helpsettings'}{'adhoc'}};
 7673:             }
 7674:         }
 7675:         my $count = 0;
 7676:         foreach my $role (sort(keys(%customroles))) {
 7677:             my ($order,$desc,$access_in_dom);
 7678:             if (ref($domcurrent{$role}) eq 'HASH') {
 7679:                 $order = $domcurrent{$role}{'order'};
 7680:                 $desc = $domcurrent{$role}{'desc'};
 7681:                 $access_in_dom = $domcurrent{$role}{'access'};
 7682:             }
 7683:             if ($order eq '') {
 7684:                 $order = $count;
 7685:             }
 7686:             $ordered{$order} = $role;
 7687:             if ($desc ne '') {
 7688:                 $description{$role} = $desc;
 7689:             } else {
 7690:                 $description{$role}= $role;
 7691:             }
 7692:             $count++;
 7693:         }
 7694:         %domusage = &domain_adhoc_access(\%customroles,\%domcurrent,\@accesstypes,$usertypes,$othertitle);
 7695:         my @roles_by_num = ();
 7696:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 7697:             push(@roles_by_num,$ordered{$item});
 7698:         }
 7699:         $r->print('<p>'.$lt{'tfh'}.': <i>'.join('</i>, <i>',map { $description{$_}; } @roles_by_num).'</i>.');
 7700:         if ($permission->{'owner'}) {
 7701:             $r->print('<br />'.$lt{'aco'}.'</p><p>');
 7702:             $r->print('<input type="hidden" name="state" value="process" />'.
 7703:                       '<input type="submit" value="'.&mt('Save changes').'" />');
 7704:         } else {
 7705:             if ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'}) {
 7706:                 my ($ownername,$ownerdom) = split(/:/,$env{'course.'.$env{'request.course.id'}.'.internal.courseowner'});
 7707:                 $r->print('<br />'.&mt('The course owner -- [_1] -- can override the default access and/or privileges for these ad hoc roles.',
 7708:                                     &Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($ownername,$ownerdom),$ownername,$ownerdom)));
 7709:             }
 7710:             $disabled = ' disabled="disabled"';
 7711:         }
 7712:         $r->print('</p>');
 7713: 
 7714:         $r->print('<div id="LC_minitab_header"><ul>');
 7715:         my $count = 0;
 7716:         my %visibility;
 7717:         foreach my $role (@roles_by_num) {
 7718:             my $id;
 7719:             if ($count == 0) {
 7720:                 $id=' id="LC_current_minitab"';
 7721:                 $visibility{$role} = ' style="display:block"';
 7722:             } else {
 7723:                 $visibility{$role} = ' style="display:none"';
 7724:             }
 7725:             $count ++;
 7726:             $r->print('<li'.$id.'><a href="#" onclick="javascript:switchRoleTab(this.parentNode,'."'$role'".');">'.$description{$role}.'</a></li>');
 7727:         }
 7728:         $r->print('</ul></div>');
 7729: 
 7730:         foreach my $role (@roles_by_num) {
 7731:             my %usecheck = (
 7732:                              all => ' checked="checked"',
 7733:                            );
 7734:             my %displaydiv = (
 7735:                                 status => 'none',
 7736:                                 inc    => 'none',
 7737:                                 exc    => 'none',
 7738:                                 priv   => 'block',
 7739:                              );
 7740:             my (%selected,$overridden,$incrscheck,$indomcheck,$indomvis,$incrsvis);
 7741:             if (ref($settings{$role}) eq 'HASH') {
 7742:                 if ($settings{$role}{'access'} ne '') {
 7743:                     $indomvis = ' style="display:none"';
 7744:                     $incrsvis = ' style="display:block"';
 7745:                     $incrscheck = ' checked="checked"';
 7746:                     if ($settings{$role}{'access'} ne 'all') {
 7747:                         $usecheck{$settings{$role}{'access'}} = $usecheck{'all'};
 7748:                         delete($usecheck{'all'});
 7749:                         if ($settings{$role}{'access'} eq 'status') {
 7750:                             my $access = 'status';
 7751:                             $displaydiv{$access} = 'inline';
 7752:                             if (ref($settings{$role}{$access}) eq 'ARRAY') {
 7753:                                 $selected{$access} = $settings{$role}{$access};
 7754:                             }
 7755:                         } elsif ($settings{$role}{'access'} =~ /^(inc|exc)$/) {
 7756:                             my $access = $1;
 7757:                             $displaydiv{$access} = 'inline';
 7758:                             if (ref($settings{$role}{$access}) eq 'ARRAY') {
 7759:                                 $selected{$access} = $settings{$role}{$access};
 7760:                             }
 7761:                         } elsif ($settings{$role}{'access'} eq 'none') {
 7762:                             $displaydiv{'priv'} = 'none';
 7763:                         }
 7764:                     }
 7765:                 } else {
 7766:                     $indomcheck = ' checked="checked"';
 7767:                     $indomvis = ' style="display:block"';
 7768:                     $incrsvis = ' style="display:none"';
 7769:                 }
 7770:             } else {
 7771:                 $indomcheck = ' checked="checked"';
 7772:                 $indomvis = ' style="display:block"';
 7773:                 $incrsvis = ' style="display:none"';
 7774:             }
 7775:             $r->print('<div class="LC_left_float" id="'.$role.'_maindiv"'.$visibility{$role}.'>'.
 7776:                       '<fieldset><legend>'.$lt{'rou'}.'</legend>'.
 7777:                       '<p>'.$lt{'whi'}.' <span class="LC_nobreak">'.
 7778:                       '<label><input type="radio" name="'.$role.'_incrs" value="1"'.$incrscheck.' onclick="toggleAccess('."'$role'".');"'.$disabled.'>'.
 7779:                       &mt('Set here in [_1]',lc($crstype)).'</label>'.
 7780:                       '<span>'.('&nbsp;'x2).
 7781:                       '<label><input type="radio" name="'.$role.'_incrs" value="0"'.$indomcheck.' onclick="toggleAccess('."'$role'".');"'.$disabled.'>'.
 7782:                       $lt{'udd'}.'</label><span></p>'.
 7783:                       '<div id="'.$role.'_setindom"'.$indomvis.'>'.
 7784:                       '<span class="LC_cusr_emph">'.$domusage{$role}.'</span></div>'.
 7785:                       '<div id="'.$role.'_setincrs"'.$incrsvis.'>');
 7786:             foreach my $access (@accesstypes) {
 7787:                 $r->print('<p><label><input type="radio" name="'.$role.'_access" value="'.$access.'" '.$usecheck{$access}.
 7788:                           ' onclick="helpdeskAccess('."'$role'".');"'.$disabled.' />'.$lt{$access}.'</label>');
 7789:                 if ($access eq 'status') {
 7790:                     $r->print('<div id="'.$role.'_bystatus" style="display:'.$displaydiv{$access}.'">'.
 7791:                               &Apache::lonuserutils::adhoc_status_types($cdom,undef,$role,$selected{$access},
 7792:                                                                         $othertitle,$usertypes,$types,$disabled).
 7793:                               '</div>');
 7794:                 } elsif (($access eq 'inc') && (keys(%domhelpdesk) > 0)) {
 7795:                     $r->print('<div id="'.$role.'_notinc" style="display:'.$displaydiv{$access}.'">'.
 7796:                               &Apache::lonuserutils::adhoc_staff($access,undef,$role,$selected{$access},
 7797:                                                                  \%domhelpdesk,$disabled).
 7798:                               '</div>');
 7799:                 } elsif (($access eq 'exc') && (keys(%domhelpdesk) > 0)) {
 7800:                     $r->print('<div id="'.$role.'_notexc" style="display:'.$displaydiv{$access}.'">'.
 7801:                               &Apache::lonuserutils::adhoc_staff($access,undef,$role,$selected{$access},
 7802:                                                                  \%domhelpdesk,$disabled).
 7803:                               '</div>');
 7804:                 }
 7805:                 $r->print('</p>');
 7806:             }
 7807:             $r->print('</div></fieldset>');
 7808:             my %full=();
 7809:             my %levels= (
 7810:                          course => {},
 7811:                          domain => {},
 7812:                          system => {},
 7813:                         );
 7814:             my %levelscurrent=(
 7815:                                course => {},
 7816:                                domain => {},
 7817:                                system => {},
 7818:                               );
 7819:             &Apache::lonuserutils::custom_role_privs($customroles{$role},\%full,\%levels,\%levelscurrent);
 7820:             $r->print('<fieldset id="'.$role.'_privs" style="display:'.$displaydiv{'priv'}.'">'.
 7821:                       '<legend>'.$lt{'rpr'}.'</legend>'.
 7822:                       &role_priv_table($role,$permission,$crstype,\%full,\%levels,\%levelscurrent,$overridden{$role}).
 7823:                       '</fieldset></div><div style="padding:0;clear:both;margin:0;border:0"></div>');
 7824:         }
 7825:         if ($permission->{'owner'}) {
 7826:             $r->print('<p><input type="submit" value="'.&mt('Save changes').'" /></p>');
 7827:         }
 7828:     } else {
 7829:         $r->print(&mt('Helpdesk roles have not yet been created in this domain.'));
 7830:     }
 7831:     # Form Footer
 7832:     $r->print('<input type="hidden" name="action" value="helpdesk" />'
 7833:              .'</form>');
 7834:     return;
 7835: }
 7836: 
 7837: sub domain_adhoc_access {
 7838:     my ($roles,$domcurrent,$accesstypes,$usertypes,$othertitle) = @_;
 7839:     my %domusage;
 7840:     return unless ((ref($roles) eq 'HASH') && (ref($domcurrent) eq 'HASH') && (ref($accesstypes) eq 'ARRAY'));
 7841:     foreach my $role (keys(%{$roles})) {
 7842:         if (ref($domcurrent->{$role}) eq 'HASH') {
 7843:             my $access = $domcurrent->{$role}{'access'};
 7844:             if (($access eq '') || (!grep(/^\Q$access\E$/,@{$accesstypes}))) {
 7845:                 $access = 'all';
 7846:                 $domusage{$role} = &mt('Any user in domain with active [_1] or [_2] role',&Apache::lonnet::plaintext('dh'),
 7847:                                                                                           &Apache::lonnet::plaintext('da'));
 7848:             } elsif ($access eq 'status') {
 7849:                 if (ref($domcurrent->{$role}{$access}) eq 'ARRAY') {
 7850:                     my @shown;
 7851:                     foreach my $type (@{$domcurrent->{$role}{$access}}) {
 7852:                         unless ($type eq 'default') {
 7853:                             if ($usertypes->{$type}) {
 7854:                                 push(@shown,$usertypes->{$type});
 7855:                             }
 7856:                         }
 7857:                     }
 7858:                     if (grep(/^default$/,@{$domcurrent->{$role}{$access}})) {
 7859:                         push(@shown,$othertitle);
 7860:                     }
 7861:                     if (@shown) {
 7862:                         my $shownstatus = join(' '.&mt('or').' ',@shown);
 7863:                         $domusage{$role} = &mt('Any user in domain with active [_1] or [_2] role, and institutional status: [_3]',
 7864:                                                &Apache::lonnet::plaintext('dh'),&Apache::lonnet::plaintext('da'),$shownstatus);
 7865:                     } else {
 7866:                         $domusage{$role} = &mt('No one in the domain');
 7867:                     }
 7868:                 }
 7869:             } elsif ($access eq 'inc') {
 7870:                 my @dominc = ();
 7871:                 if (ref($domcurrent->{$role}{'inc'}) eq 'ARRAY') {
 7872:                     foreach my $user (@{$domcurrent->{$role}{'inc'}}) {
 7873:                         my ($uname,$udom) = split(/:/,$user);
 7874:                         push(@dominc,&Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($uname,$udom),$uname,$udom));
 7875:                     }
 7876:                     my $showninc = join(', ',@dominc);
 7877:                     if ($showninc ne '') {
 7878:                         $domusage{$role} = &mt('Include any user in domain with active [_1] or [_2] role, except: [_3]',
 7879:                                                &Apache::lonnet::plaintext('dh'),&Apache::lonnet::plaintext('da'),$showninc);
 7880:                     } else {
 7881:                         $domusage{$role} = &mt('Any user in domain with active [_1] or [_2] role',
 7882:                                                &Apache::lonnet::plaintext('dh'),&Apache::lonnet::plaintext('da'));
 7883:                     }
 7884:                 }
 7885:             } elsif ($access eq 'exc') {
 7886:                 my @domexc = ();
 7887:                 if (ref($domcurrent->{$role}{'exc'}) eq 'ARRAY') {
 7888:                     foreach my $user (@{$domcurrent->{$role}{'exc'}}) {
 7889:                         my ($uname,$udom) = split(/:/,$user);
 7890:                         push(@domexc,&Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($uname,$udom),$uname,$udom));
 7891:                     }
 7892:                 }
 7893:                 my $shownexc = join(', ',@domexc);
 7894:                 if ($shownexc ne '') {
 7895:                     $domusage{$role} = &mt('Only the following in the domain with active [_1] or [_2] role: [_3]',
 7896:                                            &Apache::lonnet::plaintext('dh'),&Apache::lonnet::plaintext('da'),$shownexc);
 7897:                 } else {
 7898:                     $domusage{$role} = &mt('No one in the domain');
 7899:                 }
 7900:             } elsif ($access eq 'none') {
 7901:                 $domusage{$role} = &mt('No one in the domain');
 7902:             } elsif ($access eq 'dh') {
 7903:                 $domusage{$role} = &mt('Any user in domain with active [_1] role',&Apache::lonnet::plaintext('dh'));
 7904:             } elsif ($access eq 'da') {
 7905:                 $domusage{$role} = &mt('Any user in domain with active [_1] role',&Apache::lonnet::plaintext('da'));
 7906:             } elsif ($access eq 'all') {
 7907:                 $domusage{$role} = &mt('Any user in domain with active [_1] or [_2] role',
 7908:                                        &Apache::lonnet::plaintext('dh'),&Apache::lonnet::plaintext('da'));
 7909:             }
 7910:         } else {
 7911:             $domusage{$role} = &mt('Any user in domain with active [_1] or [_2] role',
 7912:                                    &Apache::lonnet::plaintext('dh'),&Apache::lonnet::plaintext('da'));
 7913:         }
 7914:     }
 7915:     return %domusage;
 7916: }
 7917: 
 7918: sub get_domain_customroles {
 7919:     my ($cdom,$confname) = @_;
 7920:     my %existing=&Apache::lonnet::dump('roles',$cdom,$confname,'rolesdef_');
 7921:     my %customroles;
 7922:     foreach my $key (keys(%existing)) {
 7923:         if ($key=~/^rolesdef\_(\w+)$/) {
 7924:             my $rolename = $1;
 7925:             my %privs;
 7926:             ($privs{'system'},$privs{'domain'},$privs{'course'}) = split(/\_/,$existing{$key});
 7927:             $customroles{$rolename} = \%privs;
 7928:         }
 7929:     }
 7930:     return %customroles;
 7931: }
 7932: 
 7933: sub role_priv_table {
 7934:     my ($role,$permission,$crstype,$full,$levels,$levelscurrent,$overridden) = @_;
 7935:     return unless ((ref($full) eq 'HASH') && (ref($levels) eq 'HASH') &&
 7936:                    (ref($levelscurrent) eq 'HASH'));
 7937:     my %lt=&Apache::lonlocal::texthash (
 7938:                     'crl'  => 'Course Level Privilege',
 7939:                     'def'  => 'Domain Defaults',
 7940:                     'ove'  => 'Override in Course',
 7941:                     'ine'  => 'In effect',
 7942:                     'dis'  => 'Disabled',
 7943:                     'ena'  => 'Enabled',
 7944:                    );
 7945:     if ($crstype eq 'Community') {
 7946:         $lt{'ove'} = 'Override in Community',
 7947:     }
 7948:     my @status = ('Disabled','Enabled');
 7949:     my (%on,%off);
 7950:     if (ref($overridden) eq 'HASH') {
 7951:         if (ref($overridden->{'on'}) eq 'ARRAY') {
 7952:             map { $on{$_} = 1; } (@{$overridden->{'on'}});
 7953:         }
 7954:         if (ref($overridden->{'off'}) eq 'ARRAY') {
 7955:             map { $off{$_} = 1; } (@{$overridden->{'off'}});
 7956:         }
 7957:     }
 7958:     my $output=&Apache::loncommon::start_data_table().
 7959:                &Apache::loncommon::start_data_table_header_row().
 7960:                '<th>'.$lt{'crl'}.'</th><th>'.$lt{'def'}.'</th><th>'.$lt{'ove'}.
 7961:                '</th><th>'.$lt{'ine'}.'</th>'.
 7962:                &Apache::loncommon::end_data_table_header_row();
 7963:     foreach my $priv (sort(keys(%{$full}))) {
 7964:         next unless ($levels->{'course'}{$priv});
 7965:         my $privtext = &Apache::lonnet::plaintext($priv,$crstype);
 7966:         my ($default,$ineffect);
 7967:         if ($levelscurrent->{'course'}{$priv}) {
 7968:             $default = '<img src="/adm/lonIcons/navmap.correct.gif" alt="'.$lt{'ena'}.'" />';
 7969:             $ineffect = $default;
 7970:         }
 7971:         my ($customstatus,$checked);
 7972:         $output .= &Apache::loncommon::start_data_table_row().
 7973:                    '<td>'.$privtext.'</td>'.
 7974:                    '<td>'.$default.'</td><td>';
 7975:         if (($levelscurrent->{'course'}{$priv}) && ($off{$priv})) {
 7976:             if ($permission->{'owner'}) {
 7977:                 $checked = ' checked="checked"';
 7978:             }
 7979:             $customstatus = '<img src="/adm/lonIcons/navmap.wrong.gif" alt="'.$lt{'dis'}.'" />';
 7980:             $ineffect = $customstatus;
 7981:         } elsif ((!$levelscurrent->{'course'}{$priv}) && ($on{$priv})) {
 7982:             if ($permission->{'owner'}) {
 7983:                 $checked = ' checked="checked"';
 7984:             }
 7985:             $customstatus = '<img src="/adm/lonIcons/navmap.correct.gif" alt="'.$lt{'ena'}.'" />';
 7986:             $ineffect = $customstatus;
 7987:         }
 7988:         if ($permission->{'owner'}) {
 7989:             $output .= '<input type="checkbox" name="'.$role.'_override" value="'.$priv.'"'.$checked.' />';
 7990:         } else {
 7991:             $output .= $customstatus;
 7992:         }
 7993:         $output .= '</td><td>'.$ineffect.'</td>'.
 7994:                    &Apache::loncommon::end_data_table_row();
 7995:     }
 7996:     $output .= &Apache::loncommon::end_data_table();
 7997:     return $output;
 7998: }
 7999: 
 8000: sub get_adhocrole_settings {
 8001:     my ($cid,$accesstypes,$types,$customroles,$settings,$overridden) = @_;
 8002:     return unless ((ref($accesstypes) eq 'ARRAY') && (ref($customroles) eq 'HASH') &&
 8003:                    (ref($settings) eq 'HASH') && (ref($overridden) eq 'HASH'));
 8004:     foreach my $role (split(/,/,$env{'course.'.$cid.'.internal.adhocaccess'})) {
 8005:         my ($curraccess,$rest) = split(/=/,$env{'course.'.$cid.'.internal.adhoc.'.$role});
 8006:         if (($curraccess ne '') && (grep(/^\Q$curraccess\E$/,@{$accesstypes}))) {
 8007:             $settings->{$role}{'access'} = $curraccess;
 8008:             if (($curraccess eq 'status') && (ref($types) eq 'ARRAY')) {
 8009:                 my @status = split(/,/,$rest);
 8010:                 my @currstatus;
 8011:                 foreach my $type (@status) {
 8012:                     if ($type eq 'default') {
 8013:                         push(@currstatus,$type);
 8014:                     } elsif (grep(/^\Q$type\E$/,@{$types})) {
 8015:                         push(@currstatus,$type);
 8016:                     }
 8017:                 }
 8018:                 if (@currstatus) {
 8019:                     $settings->{$role}{$curraccess} = \@currstatus;
 8020:                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 8021:                     my @personnel = split(/,/,$rest);
 8022:                     $settings->{$role}{$curraccess} = \@personnel;
 8023:                 }
 8024:             }
 8025:         }
 8026:     }
 8027:     foreach my $role (keys(%{$customroles})) {
 8028:         if ($env{'course.'.$cid.'.internal.adhocpriv.'.$role}) {
 8029:             my %currentprivs;
 8030:             if (ref($customroles->{$role}) eq 'HASH') {
 8031:                 if (exists($customroles->{$role}{'course'})) {
 8032:                     my %full=();
 8033:                     my %levels= (
 8034:                                   course => {},
 8035:                                   domain => {},
 8036:                                   system => {},
 8037:                                 );
 8038:                     my %levelscurrent=(
 8039:                                         course => {},
 8040:                                         domain => {},
 8041:                                         system => {},
 8042:                                       );
 8043:                     &Apache::lonuserutils::custom_role_privs($customroles->{$role},\%full,\%levels,\%levelscurrent);
 8044:                     %currentprivs = %{$levelscurrent{'course'}};
 8045:                 }
 8046:             }
 8047:             foreach my $item (split(/,/,$env{'course.'.$cid.'.internal.adhocpriv.'.$role})) {
 8048:                 next if ($item eq '');
 8049:                 my ($rule,$rest) = split(/=/,$item);
 8050:                 next unless (($rule eq 'off') || ($rule eq 'on'));
 8051:                 foreach my $priv (split(/:/,$rest)) {
 8052:                     if ($priv ne '') {
 8053:                         if ($rule eq 'off') {
 8054:                             push(@{$overridden->{$role}{'off'}},$priv);
 8055:                             if ($currentprivs{$priv}) {
 8056:                                 push(@{$settings->{$role}{'off'}},$priv);
 8057:                             }
 8058:                         } else {
 8059:                             push(@{$overridden->{$role}{'on'}},$priv);
 8060:                             unless ($currentprivs{$priv}) {
 8061:                                 push(@{$settings->{$role}{'on'}},$priv);
 8062:                             }
 8063:                         }
 8064:                     }
 8065:                 }
 8066:             }
 8067:         }
 8068:     }
 8069:     return;
 8070: }
 8071: 
 8072: sub update_helpdeskaccess {
 8073:     my ($r,$permission,$brcrum) = @_;
 8074:     my $helpitem = 'Course_Helpdesk_Access';
 8075:     push (@{$brcrum},
 8076:              {href => '/adm/createuser?action=helpdesk',
 8077:               text => 'Helpdesk Access',
 8078:               help => $helpitem},
 8079:              {href => '/adm/createuser?action=helpdesk',
 8080:               text => 'Result',
 8081:               help => $helpitem}
 8082:          );
 8083:     my $bread_crumbs_component = 'Helpdesk Staff Access';
 8084:     my $args = { bread_crumbs           => $brcrum,
 8085:                  bread_crumbs_component => $bread_crumbs_component};
 8086: 
 8087:     # print page header
 8088:     $r->print(&header('',$args));
 8089:     unless ((ref($permission) eq 'HASH') && ($permission->{'owner'})) {
 8090:         $r->print('<p class="LC_error">'.&mt('You do not have permission to change helpdesk access.').'</p>');
 8091:         return;
 8092:     }
 8093:     my @accesstypes = ('all','dh','da','none','status','inc','exc');
 8094:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8095:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 8096:     my $confname = $cdom.'-domainconfig';
 8097:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($cdom);
 8098:     my $crstype = &Apache::loncommon::course_type();
 8099:     my %customroles = &get_domain_customroles($cdom,$confname);
 8100:     my (%settings,%overridden);
 8101:     &get_adhocrole_settings($env{'request.course.id'},\@accesstypes,
 8102:                             $types,\%customroles,\%settings,\%overridden);
 8103:     my %domhelpdesk = &Apache::lonnet::get_active_domroles($cdom,['dh','da']);
 8104:     my (%changed,%storehash,@todelete);
 8105: 
 8106:     if (keys(%customroles)) {
 8107:         my (%newsettings,@incrs);
 8108:         foreach my $role (keys(%customroles)) {
 8109:             $newsettings{$role} = {
 8110:                                     access => '',
 8111:                                     status => '',
 8112:                                     exc    => '',
 8113:                                     inc    => '',
 8114:                                     on     => '',
 8115:                                     off    => '',
 8116:                                   };
 8117:             my %current;
 8118:             if (ref($settings{$role}) eq 'HASH') {
 8119:                 %current = %{$settings{$role}};
 8120:             }
 8121:             if (ref($overridden{$role}) eq 'HASH') {
 8122:                 $current{'overridden'} = $overridden{$role};
 8123:             }
 8124:             if ($env{'form.'.$role.'_incrs'}) {
 8125:                 my $access = $env{'form.'.$role.'_access'};
 8126:                 if (grep(/^\Q$access\E$/,@accesstypes)) {
 8127:                     push(@incrs,$role);
 8128:                     unless ($current{'access'} eq $access) {
 8129:                         $changed{$role}{'access'} = 1;
 8130:                         $storehash{'internal.adhoc.'.$role} = $access;
 8131:                     }
 8132:                     if ($access eq 'status') {
 8133:                         my @statuses = &Apache::loncommon::get_env_multiple('form.'.$role.'_status');
 8134:                         my @stored;
 8135:                         my @shownstatus;
 8136:                         if (ref($types) eq 'ARRAY') {
 8137:                             foreach my $type (sort(@statuses)) {
 8138:                                 if ($type eq 'default') {
 8139:                                     push(@stored,$type);
 8140:                                 } elsif (grep(/^\Q$type\E$/,@{$types})) {
 8141:                                     push(@stored,$type);
 8142:                                     push(@shownstatus,$usertypes->{$type});
 8143:                                 }
 8144:                             }
 8145:                             if (grep(/^default$/,@statuses)) {
 8146:                                 push(@shownstatus,$othertitle);
 8147:                             }
 8148:                             $storehash{'internal.adhoc.'.$role} .= '='.join(',',@stored);
 8149:                         }
 8150:                         $newsettings{$role}{'status'} = join(' '.&mt('or').' ',@shownstatus);
 8151:                         if (ref($current{'status'}) eq 'ARRAY') {
 8152:                             my @diffs = &Apache::loncommon::compare_arrays(\@stored,$current{'status'});
 8153:                             if (@diffs) {
 8154:                                 $changed{$role}{'status'} = 1;
 8155:                             }
 8156:                         } elsif (@stored) {
 8157:                             $changed{$role}{'status'} = 1;
 8158:                         }
 8159:                     } elsif (($access eq 'inc') || ($access eq 'exc')) {
 8160:                         my @personnel = &Apache::loncommon::get_env_multiple('form.'.$role.'_staff_'.$access);
 8161:                         my @newspecstaff;
 8162:                         my @stored;
 8163:                         my @currstaff;
 8164:                         foreach my $person (sort(@personnel)) {
 8165:                             if ($domhelpdesk{$person}) {
 8166:                                 push(@stored,$person);
 8167:                             }
 8168:                         }
 8169:                         if (ref($current{$access}) eq 'ARRAY') {
 8170:                             my @diffs = &Apache::loncommon::compare_arrays(\@stored,$current{$access});
 8171:                             if (@diffs) {
 8172:                                 $changed{$role}{$access} = 1;
 8173:                             }
 8174:                         } elsif (@stored) {
 8175:                             $changed{$role}{$access} = 1;
 8176:                         }
 8177:                         $storehash{'internal.adhoc.'.$role} .= '='.join(',',@stored);
 8178:                         foreach my $person (@stored) {
 8179:                             my ($uname,$udom) = split(/:/,$person);
 8180:                             push(@newspecstaff,&Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($uname,$udom,'lastname'),$uname,$udom));
 8181:                         }
 8182:                         $newsettings{$role}{$access} = join(', ',sort(@newspecstaff));
 8183:                     }
 8184:                     $newsettings{$role}{'access'} = $access;
 8185:                 }
 8186:             } else {
 8187:                 if (($current{'access'} ne '') && (grep(/^\Q$current{'access'}\E$/,@accesstypes))) {
 8188:                     $changed{$role}{'access'} = 1;
 8189:                     $newsettings{$role} = {};
 8190:                     push(@todelete,'internal.adhoc.'.$role);
 8191:                 }
 8192:             }
 8193:             if (($env{'form.'.$role.'_incrs'}) && ($env{'form.'.$role.'_access'} eq 'none')) {
 8194:                 if (ref($current{'overridden'}) eq 'HASH') {
 8195:                     push(@todelete,'internal.adhocpriv.'.$role);
 8196:                 }
 8197:             } else {
 8198:                 my %full=();
 8199:                 my %levels= (
 8200:                              course => {},
 8201:                              domain => {},
 8202:                              system => {},
 8203:                             );
 8204:                 my %levelscurrent=(
 8205:                                    course => {},
 8206:                                    domain => {},
 8207:                                    system => {},
 8208:                                   );
 8209:                 &Apache::lonuserutils::custom_role_privs($customroles{$role},\%full,\%levels,\%levelscurrent);
 8210:                 my (@updatedon,@updatedoff,@override);
 8211:                 @override = &Apache::loncommon::get_env_multiple('form.'.$role.'_override');
 8212:                 if (@override) {
 8213:                     foreach my $priv (sort(keys(%full))) {
 8214:                         next unless ($levels{'course'}{$priv});
 8215:                         if (grep(/^\Q$priv\E$/,@override)) {
 8216:                             if ($levelscurrent{'course'}{$priv}) {
 8217:                                 push(@updatedoff,$priv);
 8218:                             } else {
 8219:                                 push(@updatedon,$priv);
 8220:                             }
 8221:                         }
 8222:                     }
 8223:                 }
 8224:                 if (@updatedon) {
 8225:                     $newsettings{$role}{'on'} = join('</li><li>', map { &Apache::lonnet::plaintext($_,$crstype) } (@updatedon));
 8226:                 }
 8227:                 if (@updatedoff) {
 8228:                     $newsettings{$role}{'off'} = join('</li><li>', map { &Apache::lonnet::plaintext($_,$crstype) } (@updatedoff));
 8229:                 }
 8230:                 if (ref($current{'overridden'}) eq 'HASH') {
 8231:                     if (ref($current{'overridden'}{'on'}) eq 'ARRAY') {
 8232:                         if (@updatedon) {
 8233:                             my @diffs = &Apache::loncommon::compare_arrays(\@updatedon,$current{'overridden'}{'on'});
 8234:                             if (@diffs) {
 8235:                                 $changed{$role}{'on'} = 1;
 8236:                             }
 8237:                         } else {
 8238:                             $changed{$role}{'on'} = 1;
 8239:                         }
 8240:                     } elsif (@updatedon) {
 8241:                         $changed{$role}{'on'} = 1;
 8242:                     }
 8243:                     if (ref($current{'overridden'}{'off'}) eq 'ARRAY') {
 8244:                         if (@updatedoff) {
 8245:                             my @diffs = &Apache::loncommon::compare_arrays(\@updatedoff,$current{'overridden'}{'off'});
 8246:                             if (@diffs) {
 8247:                                 $changed{$role}{'off'} = 1;
 8248:                             }
 8249:                         } else {
 8250:                             $changed{$role}{'off'} = 1;
 8251:                         }
 8252:                     } elsif (@updatedoff) {
 8253:                         $changed{$role}{'off'} = 1;
 8254:                     }
 8255:                 } else {
 8256:                     if (@updatedon) {
 8257:                         $changed{$role}{'on'} = 1;
 8258:                     }
 8259:                     if (@updatedoff) {
 8260:                         $changed{$role}{'off'} = 1;
 8261:                     }
 8262:                 }
 8263:                 if (ref($changed{$role}) eq 'HASH') {
 8264:                     if (($changed{$role}{'on'} || $changed{$role}{'off'})) {
 8265:                         my $newpriv;
 8266:                         if (@updatedon) {
 8267:                             $newpriv = 'on='.join(':',@updatedon);
 8268:                         }
 8269:                         if (@updatedoff) {
 8270:                             $newpriv .= ($newpriv ? ',' : '' ).'off='.join(':',@updatedoff);
 8271:                         }
 8272:                         if ($newpriv eq '') {
 8273:                             push(@todelete,'internal.adhocpriv.'.$role);
 8274:                         } else {
 8275:                             $storehash{'internal.adhocpriv.'.$role} = $newpriv;
 8276:                         }
 8277:                     }
 8278:                 }
 8279:             }
 8280:         }
 8281:         if (@incrs) {
 8282:             $storehash{'internal.adhocaccess'} = join(',',@incrs);
 8283:         } elsif (@todelete) {
 8284:             push(@todelete,'internal.adhocaccess');
 8285:         }
 8286:         if (keys(%changed)) {
 8287:             my ($putres,$delres);
 8288:             if (keys(%storehash)) {
 8289:                 $putres = &Apache::lonnet::put('environment',\%storehash,$cdom,$cnum);
 8290:                 my %newenvhash;
 8291:                 foreach my $key (keys(%storehash)) {
 8292:                     $newenvhash{'course.'.$env{'request.course.id'}.'.'.$key} = $storehash{$key};
 8293:                 }
 8294:                 &Apache::lonnet::appenv(\%newenvhash);
 8295:             }
 8296:             if (@todelete) {
 8297:                 $delres = &Apache::lonnet::del('environment',\@todelete,$cdom,$cnum);
 8298:                 foreach my $key (@todelete) {
 8299:                     &Apache::lonnet::delenv('course.'.$env{'request.course.id'}.'.'.$key);
 8300:                 }
 8301:             }
 8302:             if (($putres eq 'ok') || ($delres eq 'ok')) {
 8303:                 my %domconfig = &Apache::lonnet::get_dom('configuration',['helpsettings'],$cdom);
 8304:                 my (%domcurrent,%ordered,%description,%domusage);
 8305:                 if (ref($domconfig{'helpsettings'}) eq 'HASH') {
 8306:                     if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
 8307:                         %domcurrent = %{$domconfig{'helpsettings'}{'adhoc'}};
 8308:                     }
 8309:                 }
 8310:                 my $count = 0;
 8311:                 foreach my $role (sort(keys(%customroles))) {
 8312:                     my ($order,$desc);
 8313:                     if (ref($domcurrent{$role}) eq 'HASH') {
 8314:                         $order = $domcurrent{$role}{'order'};
 8315:                         $desc = $domcurrent{$role}{'desc'};
 8316:                     }
 8317:                     if ($order eq '') {
 8318:                         $order = $count;
 8319:                     }
 8320:                     $ordered{$order} = $role;
 8321:                     if ($desc ne '') {
 8322:                         $description{$role} = $desc;
 8323:                     } else {
 8324:                         $description{$role}= $role;
 8325:                     }
 8326:                     $count++;
 8327:                 }
 8328:                 my @roles_by_num = ();
 8329:                 foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 8330:                     push(@roles_by_num,$ordered{$item});
 8331:                 }
 8332:                 %domusage = &domain_adhoc_access(\%changed,\%domcurrent,\@accesstypes,$usertypes,$othertitle);
 8333:                 $r->print(&mt('Helpdesk access settings have been changed as follows').'<br />');
 8334:                 $r->print('<ul>');
 8335:                 foreach my $role (@roles_by_num) {
 8336:                     next unless (ref($changed{$role}) eq 'HASH');
 8337:                     $r->print('<li>'.&mt('Ad hoc role').': <b>'.$description{$role}.'</b>'.
 8338:                               '<ul>');
 8339:                     if ($changed{$role}{'access'} || $changed{$role}{'status'} || $changed{$role}{'inc'} || $changed{$role}{'exc'}) {
 8340:                         $r->print('<li>');
 8341:                         if ($env{'form.'.$role.'_incrs'}) {
 8342:                             if ($newsettings{$role}{'access'} eq 'all') {
 8343:                                 $r->print(&mt('All helpdesk staff can access '.lc($crstype).' with this role.'));
 8344:                             } elsif ($newsettings{$role}{'access'} eq 'dh') {
 8345:                                 $r->print(&mt('Helpdesk staff can use this role if they have an active [_1] role',
 8346:                                               &Apache::lonnet::plaintext('dh')));
 8347:                             } elsif ($newsettings{$role}{'access'} eq 'da') {
 8348:                                 $r->print(&mt('Helpdesk staff can use this role if they have an active [_1] role',
 8349:                                               &Apache::lonnet::plaintext('da')));
 8350:                             } elsif ($newsettings{$role}{'access'} eq 'none') {
 8351:                                 $r->print(&mt('No helpdesk staff can access '.lc($crstype).' with this role.'));
 8352:                             } elsif ($newsettings{$role}{'access'} eq 'status') {
 8353:                                 if ($newsettings{$role}{'status'}) {
 8354:                                     my ($access,$rest) = split(/=/,$storehash{'internal.adhoc.'.$role});
 8355:                                     if (split(/,/,$rest) > 1) {
 8356:                                         $r->print(&mt('Helpdesk staff can use this role if their institutional type is one of: [_1].',
 8357:                                                       $newsettings{$role}{'status'}));
 8358:                                     } else {
 8359:                                         $r->print(&mt('Helpdesk staff can use this role if their institutional type is: [_1].',
 8360:                                                       $newsettings{$role}{'status'}));
 8361:                                     }
 8362:                                 } else {
 8363:                                     $r->print(&mt('No helpdesk staff can access '.lc($crstype).' with this role.'));
 8364:                                 }
 8365:                             } elsif ($newsettings{$role}{'access'} eq 'exc') {
 8366:                                 if ($newsettings{$role}{'exc'}) {
 8367:                                     $r->print(&mt('Helpdesk staff who can use this role are as follows:').' '.$newsettings{$role}{'exc'}.'.');
 8368:                                 } else {
 8369:                                     $r->print(&mt('No helpdesk staff can access '.lc($crstype).' with this role.'));
 8370:                                 }
 8371:                             } elsif ($newsettings{$role}{'access'} eq 'inc') {
 8372:                                 if ($newsettings{$role}{'inc'}) {
 8373:                                     $r->print(&mt('All helpdesk staff may use this role except the following:').' '.$newsettings{$role}{'inc'}.'.');
 8374:                                 } else {
 8375:                                     $r->print(&mt('All helpdesk staff may use this role.'));
 8376:                                 }
 8377:                             }
 8378:                         } else {
 8379:                             $r->print(&mt('Default access set in the domain now applies.').'<br />'.
 8380:                                       '<span class="LC_cusr_emph">'.$domusage{$role}.'</span>');
 8381:                         }
 8382:                         $r->print('</li>');
 8383:                     }
 8384:                     unless ($newsettings{$role}{'access'} eq 'none') {
 8385:                         if ($changed{$role}{'off'}) {
 8386:                             if ($newsettings{$role}{'off'}) {
 8387:                                 $r->print('<li>'.&mt('Privileges which are available by default for this ad hoc role, but are disabled for this specific '.lc($crstype).':').
 8388:                                           '<ul><li>'.$newsettings{$role}{'off'}.'</li></ul></li>');
 8389:                             } else {
 8390:                                 $r->print('<li>'.&mt('All privileges available by default for this ad hoc role are enabled.').'</li>');
 8391:                             }
 8392:                         }
 8393:                         if ($changed{$role}{'on'}) {
 8394:                             if ($newsettings{$role}{'on'}) {
 8395:                                 $r->print('<li>'.&mt('Privileges which are not available by default for this ad hoc role, but are enabled for this specific '.lc($crstype).':').
 8396:                                           '<ul><li>'.$newsettings{$role}{'on'}.'</li></ul></li>');
 8397:                             } else {
 8398:                                 $r->print('<li>'.&mt('None of the privileges unavailable by default for this ad hoc role are enabled.').'</li>');
 8399:                             }
 8400:                         }
 8401:                     }
 8402:                     $r->print('</ul></li>');
 8403:                 }
 8404:                 $r->print('</ul>');
 8405:             }
 8406:         } else {
 8407:             $r->print(&mt('No changes made to helpdesk access settings.'));
 8408:         }
 8409:     }
 8410:     return;
 8411: }
 8412: 
 8413: #-------------------------------------------------- functions for &phase_two
 8414: sub user_search_result {
 8415:     my ($context,$srch) = @_;
 8416:     my %allhomes;
 8417:     my %inst_matches;
 8418:     my %srch_results;
 8419:     my ($response,$currstate,$forcenewuser,$dirsrchres);
 8420:     $srch->{'srchterm'} =~ s/\s+/ /g;
 8421:     if ($srch->{'srchby'} !~ /^(uname|lastname|lastfirst)$/) {
 8422:         $response = &mt('Invalid search.');
 8423:     }
 8424:     if ($srch->{'srchin'} !~ /^(crs|dom|alc|instd)$/) {
 8425:         $response = &mt('Invalid search.');
 8426:     }
 8427:     if ($srch->{'srchtype'} !~ /^(exact|contains|begins)$/) {
 8428:         $response = &mt('Invalid search.');
 8429:     }
 8430:     if ($srch->{'srchterm'} eq '') {
 8431:         $response = &mt('You must enter a search term.');
 8432:     }
 8433:     if ($srch->{'srchterm'} =~ /^\s+$/) {
 8434:         $response = &mt('Your search term must contain more than just spaces.');
 8435:     }
 8436:     if (($srch->{'srchin'} eq 'dom') || ($srch->{'srchin'} eq 'instd')) {
 8437:         if (($srch->{'srchdomain'} eq '') || 
 8438: 	    ! (&Apache::lonnet::domain($srch->{'srchdomain'}))) {
 8439:             $response = &mt('You must specify a valid domain when searching in a domain or institutional directory.')
 8440:         }
 8441:     }
 8442:     if (($srch->{'srchin'} eq 'dom') || ($srch->{'srchin'} eq 'crs') ||
 8443:         ($srch->{'srchin'} eq 'alc')) {
 8444:         if ($srch->{'srchby'} eq 'uname') {
 8445:             my $unamecheck = $srch->{'srchterm'};
 8446:             if ($srch->{'srchtype'} eq 'contains') {
 8447:                 if ($unamecheck !~ /^\w/) {
 8448:                     $unamecheck = 'a'.$unamecheck; 
 8449:                 }
 8450:             }
 8451:             if ($unamecheck !~ /^$match_username$/) {
 8452:                 $response = &mt('You must specify a valid username. Only the following are allowed: letters numbers - . @');
 8453:             }
 8454:         }
 8455:     }
 8456:     if ($response ne '') {
 8457:         $response = '<span class="LC_warning">'.$response.'</span><br />';
 8458:     }
 8459:     if ($srch->{'srchin'} eq 'instd') {
 8460:         my $instd_chk = &instdirectorysrch_check($srch);
 8461:         if ($instd_chk ne 'ok') {
 8462:             my $domd_chk = &domdirectorysrch_check($srch);
 8463:             $response .= '<span class="LC_warning">'.$instd_chk.'</span><br />';
 8464:             if ($domd_chk eq 'ok') {
 8465:                 $response .= &mt('You may want to search in the LON-CAPA domain instead of in the institutional directory.');
 8466:             }
 8467:             $response .= '<br />';
 8468:         }
 8469:     } else {
 8470:         unless (($context eq 'requestcrs') && ($srch->{'srchtype'} eq 'exact')) {
 8471:             my $domd_chk = &domdirectorysrch_check($srch);
 8472:             if (($domd_chk ne 'ok') && ($env{'form.action'} ne 'accesslogs')) {
 8473:                 my $instd_chk = &instdirectorysrch_check($srch);
 8474:                 $response .= '<span class="LC_warning">'.$domd_chk.'</span><br />';
 8475:                 if ($instd_chk eq 'ok') {
 8476:                     $response .= &mt('You may want to search in the institutional directory instead of in the LON-CAPA domain.');
 8477:                 }
 8478:                 $response .= '<br />';
 8479:             }
 8480:         }
 8481:     }
 8482:     if ($response ne '') {
 8483:         return ($currstate,$response);
 8484:     }
 8485:     if ($srch->{'srchby'} eq 'uname') {
 8486:         if (($srch->{'srchin'} eq 'dom') || ($srch->{'srchin'} eq 'crs')) {
 8487:             if ($env{'form.forcenew'}) {
 8488:                 if ($srch->{'srchdomain'} ne $env{'request.role.domain'}) {
 8489:                     my $uhome=&Apache::lonnet::homeserver($srch->{'srchterm'},$srch->{'srchdomain'});
 8490:                     if ($uhome eq 'no_host') {
 8491:                         my $domdesc = &Apache::lonnet::domain($env{'request.role.domain'},'description');
 8492:                         my $showdom = &display_domain_info($env{'request.role.domain'});
 8493:                         $response = &mt('New users can only be created in the domain to which your current role belongs - [_1].',$showdom);
 8494:                     } else {
 8495:                         $currstate = 'modify';
 8496:                     }
 8497:                 } else {
 8498:                     $currstate = 'modify';
 8499:                 }
 8500:             } else {
 8501:                 if ($srch->{'srchin'} eq 'dom') {
 8502:                     if ($srch->{'srchtype'} eq 'exact') {
 8503:                         my $uhome=&Apache::lonnet::homeserver($srch->{'srchterm'},$srch->{'srchdomain'});
 8504:                         if ($uhome eq 'no_host') {
 8505:                             ($currstate,$response,$forcenewuser) =
 8506:                                 &build_search_response($context,$srch,%srch_results);
 8507:                         } else {
 8508:                             $currstate = 'modify';
 8509:                             if ($env{'form.action'} eq 'accesslogs') {
 8510:                                 $currstate = 'activity';
 8511:                             }
 8512:                             my $uname = $srch->{'srchterm'};
 8513:                             my $udom = $srch->{'srchdomain'};
 8514:                             $srch_results{$uname.':'.$udom} =
 8515:                                 { &Apache::lonnet::get('environment',
 8516:                                                        ['firstname',
 8517:                                                         'lastname',
 8518:                                                         'permanentemail'],
 8519:                                                          $udom,$uname)
 8520:                                 };
 8521:                         }
 8522:                     } else {
 8523:                         %srch_results = &Apache::lonnet::usersearch($srch);
 8524:                         ($currstate,$response,$forcenewuser) =
 8525:                             &build_search_response($context,$srch,%srch_results);
 8526:                     }
 8527:                 } else {
 8528:                     my $courseusers = &get_courseusers();
 8529:                     if ($srch->{'srchtype'} eq 'exact') {
 8530:                         if (exists($courseusers->{$srch->{'srchterm'}.':'.$srch->{'srchdomain'}})) {
 8531:                             $currstate = 'modify';
 8532:                         } else {
 8533:                             ($currstate,$response,$forcenewuser) =
 8534:                                 &build_search_response($context,$srch,%srch_results);
 8535:                         }
 8536:                     } else {
 8537:                         foreach my $user (keys(%$courseusers)) {
 8538:                             my ($cuname,$cudomain) = split(/:/,$user);
 8539:                             if ($cudomain eq $srch->{'srchdomain'}) {
 8540:                                 my $matched = 0;
 8541:                                 if ($srch->{'srchtype'} eq 'begins') {
 8542:                                     if ($cuname =~ /^\Q$srch->{'srchterm'}\E/i) {
 8543:                                         $matched = 1;
 8544:                                     }
 8545:                                 } else {
 8546:                                     if ($cuname =~ /\Q$srch->{'srchterm'}\E/i) {
 8547:                                         $matched = 1;
 8548:                                     }
 8549:                                 }
 8550:                                 if ($matched) {
 8551:                                     $srch_results{$user} = 
 8552: 					{&Apache::lonnet::get('environment',
 8553: 							     ['firstname',
 8554: 							      'lastname',
 8555: 							      'permanentemail'],
 8556: 							      $cudomain,$cuname)};
 8557:                                 }
 8558:                             }
 8559:                         }
 8560:                         ($currstate,$response,$forcenewuser) =
 8561:                             &build_search_response($context,$srch,%srch_results);
 8562:                     }
 8563:                 }
 8564:             }
 8565:         } elsif ($srch->{'srchin'} eq 'alc') {
 8566:             $currstate = 'query';
 8567:         } elsif ($srch->{'srchin'} eq 'instd') {
 8568:             ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query($srch);
 8569:             if ($dirsrchres eq 'ok') {
 8570:                 ($currstate,$response,$forcenewuser) = 
 8571:                     &build_search_response($context,$srch,%srch_results);
 8572:             } else {
 8573:                 my $showdom = &display_domain_info($srch->{'srchdomain'});
 8574:                 $response = '<span class="LC_warning">'.
 8575:                     &mt('Institutional directory search is not available in domain: [_1]',$showdom).
 8576:                     '</span><br />'.
 8577:                     &mt('You may want to search in the LON-CAPA domain instead of in the institutional directory.').
 8578:                     '<br />'; 
 8579:             }
 8580:         }
 8581:     } else {
 8582:         if ($srch->{'srchin'} eq 'dom') {
 8583:             %srch_results = &Apache::lonnet::usersearch($srch);
 8584:             ($currstate,$response,$forcenewuser) = 
 8585:                 &build_search_response($context,$srch,%srch_results); 
 8586:         } elsif ($srch->{'srchin'} eq 'crs') {
 8587:             my $courseusers = &get_courseusers(); 
 8588:             foreach my $user (keys(%$courseusers)) {
 8589:                 my ($uname,$udom) = split(/:/,$user);
 8590:                 my %names = &Apache::loncommon::getnames($uname,$udom);
 8591:                 my %emails = &Apache::loncommon::getemails($uname,$udom);
 8592:                 if ($srch->{'srchby'} eq 'lastname') {
 8593:                     if ((($srch->{'srchtype'} eq 'exact') && 
 8594:                          ($names{'lastname'} eq $srch->{'srchterm'})) || 
 8595:                         (($srch->{'srchtype'} eq 'begins') &&
 8596:                          ($names{'lastname'} =~ /^\Q$srch->{'srchterm'}\E/i)) ||
 8597:                         (($srch->{'srchtype'} eq 'contains') &&
 8598:                          ($names{'lastname'} =~ /\Q$srch->{'srchterm'}\E/i))) {
 8599:                         $srch_results{$user} = {firstname => $names{'firstname'},
 8600:                                             lastname => $names{'lastname'},
 8601:                                             permanentemail => $emails{'permanentemail'},
 8602:                                            };
 8603:                     }
 8604:                 } elsif ($srch->{'srchby'} eq 'lastfirst') {
 8605:                     my ($srchlast,$srchfirst) = split(/,/,$srch->{'srchterm'});
 8606:                     $srchlast =~ s/\s+$//;
 8607:                     $srchfirst =~ s/^\s+//;
 8608:                     if ($srch->{'srchtype'} eq 'exact') {
 8609:                         if (($names{'lastname'} eq $srchlast) &&
 8610:                             ($names{'firstname'} eq $srchfirst)) {
 8611:                             $srch_results{$user} = {firstname => $names{'firstname'},
 8612:                                                 lastname => $names{'lastname'},
 8613:                                                 permanentemail => $emails{'permanentemail'},
 8614: 
 8615:                                            };
 8616:                         }
 8617:                     } elsif ($srch->{'srchtype'} eq 'begins') {
 8618:                         if (($names{'lastname'} =~ /^\Q$srchlast\E/i) &&
 8619:                             ($names{'firstname'} =~ /^\Q$srchfirst\E/i)) {
 8620:                             $srch_results{$user} = {firstname => $names{'firstname'},
 8621:                                                 lastname => $names{'lastname'},
 8622:                                                 permanentemail => $emails{'permanentemail'},
 8623:                                                };
 8624:                         }
 8625:                     } else {
 8626:                         if (($names{'lastname'} =~ /\Q$srchlast\E/i) && 
 8627:                             ($names{'firstname'} =~ /\Q$srchfirst\E/i)) {
 8628:                             $srch_results{$user} = {firstname => $names{'firstname'},
 8629:                                                 lastname => $names{'lastname'},
 8630:                                                 permanentemail => $emails{'permanentemail'},
 8631:                                                };
 8632:                         }
 8633:                     }
 8634:                 }
 8635:             }
 8636:             ($currstate,$response,$forcenewuser) = 
 8637:                 &build_search_response($context,$srch,%srch_results); 
 8638:         } elsif ($srch->{'srchin'} eq 'alc') {
 8639:             $currstate = 'query';
 8640:         } elsif ($srch->{'srchin'} eq 'instd') {
 8641:             ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query($srch); 
 8642:             if ($dirsrchres eq 'ok') {
 8643:                 ($currstate,$response,$forcenewuser) = 
 8644:                     &build_search_response($context,$srch,%srch_results);
 8645:             } else {
 8646:                 my $showdom = &display_domain_info($srch->{'srchdomain'});
 8647:                 $response = '<span class="LC_warning">'.
 8648:                     &mt('Institutional directory search is not available in domain: [_1]',$showdom).
 8649:                     '</span><br />'.
 8650:                     &mt('You may want to search in the LON-CAPA domain instead of in the institutional directory.').
 8651:                     '<br />';
 8652:             }
 8653:         }
 8654:     }
 8655:     return ($currstate,$response,$forcenewuser,\%srch_results);
 8656: }
 8657: 
 8658: sub domdirectorysrch_check {
 8659:     my ($srch) = @_;
 8660:     my $response;
 8661:     my %dom_inst_srch = &Apache::lonnet::get_dom('configuration',
 8662:                                              ['directorysrch'],$srch->{'srchdomain'});
 8663:     my $showdom = &display_domain_info($srch->{'srchdomain'});
 8664:     if (ref($dom_inst_srch{'directorysrch'}) eq 'HASH') {
 8665:         if ($dom_inst_srch{'directorysrch'}{'lcavailable'} eq '0') {
 8666:             return &mt('LON-CAPA directory search is not available in domain: [_1]',$showdom);
 8667:         }
 8668:         if ($dom_inst_srch{'directorysrch'}{'lclocalonly'}) {
 8669:             if ($env{'request.role.domain'} ne $srch->{'srchdomain'}) {
 8670:                 return &mt('LON-CAPA directory search in domain: [_1] is only allowed for users with a current role in the domain.',$showdom);
 8671:             }
 8672:         }
 8673:     }
 8674:     return 'ok';
 8675: }
 8676: 
 8677: sub instdirectorysrch_check {
 8678:     my ($srch) = @_;
 8679:     my $can_search = 0;
 8680:     my $response;
 8681:     my %dom_inst_srch = &Apache::lonnet::get_dom('configuration',
 8682:                                              ['directorysrch'],$srch->{'srchdomain'});
 8683:     my $showdom = &display_domain_info($srch->{'srchdomain'});
 8684:     if (ref($dom_inst_srch{'directorysrch'}) eq 'HASH') {
 8685:         if (!$dom_inst_srch{'directorysrch'}{'available'}) {
 8686:             return &mt('Institutional directory search is not available in domain: [_1]',$showdom); 
 8687:         }
 8688:         if ($dom_inst_srch{'directorysrch'}{'localonly'}) {
 8689:             if ($env{'request.role.domain'} ne $srch->{'srchdomain'}) {
 8690:                 return &mt('Institutional directory search in domain: [_1] is only allowed for users with a current role in the domain.',$showdom); 
 8691:             }
 8692:             my @usertypes = split(/:/,$env{'environment.inststatus'});
 8693:             if (!@usertypes) {
 8694:                 push(@usertypes,'default');
 8695:             }
 8696:             if (ref($dom_inst_srch{'directorysrch'}{'cansearch'}) eq 'ARRAY') {
 8697:                 foreach my $type (@usertypes) {
 8698:                     if (grep(/^\Q$type\E$/,@{$dom_inst_srch{'directorysrch'}{'cansearch'}})) {
 8699:                         $can_search = 1;
 8700:                         last;
 8701:                     }
 8702:                 }
 8703:             }
 8704:             if (!$can_search) {
 8705:                 my ($insttypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($srch->{'srchdomain'});
 8706:                 my @longtypes; 
 8707:                 foreach my $item (@usertypes) {
 8708:                     if (defined($insttypes->{$item})) { 
 8709:                         push (@longtypes,$insttypes->{$item});
 8710:                     } elsif ($item eq 'default') {
 8711:                         push (@longtypes,&mt('other')); 
 8712:                     }
 8713:                 }
 8714:                 my $insttype_str = join(', ',@longtypes); 
 8715:                 return &mt('Institutional directory search in domain: [_1] is not available to your user type: ',$showdom).$insttype_str;
 8716:             }
 8717:         } else {
 8718:             $can_search = 1;
 8719:         }
 8720:     } else {
 8721:         return &mt('Institutional directory search has not been configured for domain: [_1]',$showdom);
 8722:     }
 8723:     my %longtext = &Apache::lonlocal::texthash (
 8724:                        uname     => 'username',
 8725:                        lastfirst => 'last name, first name',
 8726:                        lastname  => 'last name',
 8727:                        contains  => 'contains',
 8728:                        exact     => 'as exact match to',
 8729:                        begins    => 'begins with',
 8730:                    );
 8731:     if ($can_search) {
 8732:         if (ref($dom_inst_srch{'directorysrch'}{'searchby'}) eq 'ARRAY') {
 8733:             if (!grep(/^\Q$srch->{'srchby'}\E$/,@{$dom_inst_srch{'directorysrch'}{'searchby'}})) {
 8734:                 return &mt('Institutional directory search in domain: [_1] is not available for searching by "[_2]"',$showdom,$longtext{$srch->{'srchby'}});
 8735:             }
 8736:         } else {
 8737:             return &mt('Institutional directory search in domain: [_1] is not available.', $showdom);
 8738:         }
 8739:     }
 8740:     if ($can_search) {
 8741:         if (ref($dom_inst_srch{'directorysrch'}{'searchtypes'}) eq 'ARRAY') {
 8742:             if (grep(/^\Q$srch->{'srchtype'}\E/,@{$dom_inst_srch{'directorysrch'}{'searchtypes'}})) {
 8743:                 return 'ok';
 8744:             } else {
 8745:                 return &mt('Institutional directory search in domain [_1] is not available for the requested search type: "[_2]"',$showdom,$longtext{$srch->{'srchtype'}});
 8746:             }
 8747:         } else {
 8748:             if ((($dom_inst_srch{'directorysrch'}{'searchtypes'} eq 'specify') &&
 8749:                  ($srch->{'srchtype'} eq 'exact' || $srch->{'srchtype'} eq 'contains')) ||
 8750:                 ($dom_inst_srch{'directorysrch'}{'searchtypes'} eq $srch->{'srchtype'})) {
 8751:                 return 'ok';
 8752:             } else {
 8753:                 return &mt('Institutional directory search in domain [_1] is not available for the requested search type: "[_2]"',$showdom,$longtext{$srch->{'srchtype'}});
 8754:             }
 8755:         }
 8756:     }
 8757: }
 8758: 
 8759: sub get_courseusers {
 8760:     my %advhash;
 8761:     my $classlist = &Apache::loncoursedata::get_classlist();
 8762:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles();
 8763:     foreach my $role (sort(keys(%coursepersonnel))) {
 8764:         foreach my $user (split(/\,/,$coursepersonnel{$role})) {
 8765: 	    if (!exists($classlist->{$user})) {
 8766: 		$classlist->{$user} = [];
 8767: 	    }
 8768:         }
 8769:     }
 8770:     return $classlist;
 8771: }
 8772: 
 8773: sub build_search_response {
 8774:     my ($context,$srch,%srch_results) = @_;
 8775:     my ($currstate,$response,$forcenewuser);
 8776:     my %names = (
 8777:           'uname'     => 'username',
 8778:           'lastname'  => 'last name',
 8779:           'lastfirst' => 'last name, first name',
 8780:           'crs'       => 'this course',
 8781:           'dom'       => 'LON-CAPA domain',
 8782:           'instd'     => 'the institutional directory for domain',
 8783:     );
 8784: 
 8785:     my %single = (
 8786:                    begins   => 'A match',
 8787:                    contains => 'A match',
 8788:                    exact    => 'An exact match',
 8789:                  );
 8790:     my %nomatch = (
 8791:                    begins   => 'No match',
 8792:                    contains => 'No match',
 8793:                    exact    => 'No exact match',
 8794:                   );
 8795:     if (keys(%srch_results) > 1) {
 8796:         $currstate = 'select';
 8797:     } else {
 8798:         if (keys(%srch_results) == 1) {
 8799:             if ($env{'form.action'} eq 'accesslogs') {
 8800:                 $currstate = 'activity';
 8801:             } else {
 8802:                 $currstate = 'modify';
 8803:             }
 8804:             $response = &mt("$single{$srch->{'srchtype'}} was found for the $names{$srch->{'srchby'}} ([_1]) in $names{$srch->{'srchin'}}.",$srch->{'srchterm'});
 8805:             if ($srch->{'srchin'} eq 'dom' || $srch->{'srchin'} eq 'instd') {
 8806:                 $response .= ': '.&display_domain_info($srch->{'srchdomain'});
 8807:             }
 8808:         } else { # Search has nothing found. Prepare message to user.
 8809:             $response = '<span class="LC_warning">';
 8810:             if ($srch->{'srchin'} eq 'dom' || $srch->{'srchin'} eq 'instd') {
 8811:                 $response .= &mt("$nomatch{$srch->{'srchtype'}} found for the $names{$srch->{'srchby'}} [_1] in $names{$srch->{'srchin'}}: [_2]",
 8812:                                  '<b>'.$srch->{'srchterm'}.'</b>',
 8813:                                  &display_domain_info($srch->{'srchdomain'}));
 8814:             } else {
 8815:                 $response .= &mt("$nomatch{$srch->{'srchtype'}} found for the $names{$srch->{'srchby'}} [_1] in $names{$srch->{'srchin'}}.",
 8816:                                  '<b>'.$srch->{'srchterm'}.'</b>');
 8817:             }
 8818:             $response .= '</span>';
 8819: 
 8820:             if ($srch->{'srchin'} ne 'alc') {
 8821:                 $forcenewuser = 1;
 8822:                 my $cansrchinst = 0; 
 8823:                 if (($srch->{'srchdomain'}) && ($env{'form.action'} ne 'accesslogs')) {
 8824:                     my %domconfig = &Apache::lonnet::get_dom('configuration',['directorysrch'],$srch->{'srchdomain'});
 8825:                     if (ref($domconfig{'directorysrch'}) eq 'HASH') {
 8826:                         if ($domconfig{'directorysrch'}{'available'}) {
 8827:                             $cansrchinst = 1;
 8828:                         } 
 8829:                     }
 8830:                 }
 8831:                 if ((($srch->{'srchby'} eq 'lastfirst') || 
 8832:                      ($srch->{'srchby'} eq 'lastname')) &&
 8833:                     ($srch->{'srchin'} eq 'dom')) {
 8834:                     if ($cansrchinst) {
 8835:                         $response .= '<br />'.&mt('You may want to broaden your search to a search of the institutional directory for the domain.');
 8836:                     }
 8837:                 }
 8838:                 if ($srch->{'srchin'} eq 'crs') {
 8839:                     $response .= '<br />'.&mt('You may want to broaden your search to the selected LON-CAPA domain.');
 8840:                 }
 8841:             }
 8842:             my $createdom = $env{'request.role.domain'};
 8843:             if ($context eq 'requestcrs') {
 8844:                 if ($env{'form.coursedom'} ne '') {
 8845:                     $createdom = $env{'form.coursedom'};
 8846:                 }
 8847:             }
 8848:             unless (($env{'form.action'} eq 'accesslogs') || (($srch->{'srchby'} eq 'uname') && ($srch->{'srchin'} eq 'dom') &&
 8849:                     ($srch->{'srchtype'} eq 'exact') && ($srch->{'srchdomain'} eq $createdom))) {
 8850:                 my $cancreate =
 8851:                     &Apache::lonuserutils::can_create_user($createdom,$context);
 8852:                 my $targetdom = '<span class="LC_cusr_emph">'.$createdom.'</span>';
 8853:                 if ($cancreate) {
 8854:                     my $showdom = &display_domain_info($createdom); 
 8855:                     $response .= '<br /><br />'
 8856:                                 .'<b>'.&mt('To add a new user:').'</b>'
 8857:                                 .'<br />';
 8858:                     if ($context eq 'requestcrs') {
 8859:                         $response .= &mt("(You can only define new users in the new course's domain - [_1])",$targetdom);
 8860:                     } else {
 8861:                         $response .= &mt("(You can only create new users in your current role's domain - [_1])",$targetdom);
 8862:                     }
 8863:                     $response .='<ul><li>'
 8864:                                 .&mt("Set 'Domain/institution to search' to: [_1]",'<span class="LC_cusr_emph">'.$showdom.'</span>')
 8865:                                 .'</li><li>'
 8866:                                 .&mt("Set 'Search criteria' to: [_1]username is ..... in selected LON-CAPA domain[_2]",'<span class="LC_cusr_emph">','</span>')
 8867:                                 .'</li><li>'
 8868:                                 .&mt('Provide the proposed username')
 8869:                                 .'</li><li>'
 8870:                                 .&mt("Click 'Search'")
 8871:                                 .'</li></ul><br />';
 8872:                 } else {
 8873:                     unless (($context eq 'domain') && ($env{'form.action'} eq 'singleuser')) {
 8874:                         my $helplink = ' href="javascript:helpMenu('."'display'".')"';
 8875:                         $response .= '<br /><br />';
 8876:                         if ($context eq 'requestcrs') {
 8877:                             $response .= &mt("You are not authorized to define new users in the new course's domain - [_1].",$targetdom);
 8878:                         } else {
 8879:                             $response .= &mt("You are not authorized to create new users in your current role's domain - [_1].",$targetdom);
 8880:                         }
 8881:                         $response .= '<br />'
 8882:                                      .&mt('Please contact the [_1]helpdesk[_2] if you need to create a new user.'
 8883:                                         ,' <a'.$helplink.'>'
 8884:                                         ,'</a>')
 8885:                                      .'<br />';
 8886:                     }
 8887:                 }
 8888:             }
 8889:         }
 8890:     }
 8891:     return ($currstate,$response,$forcenewuser);
 8892: }
 8893: 
 8894: sub display_domain_info {
 8895:     my ($dom) = @_;
 8896:     my $output = $dom;
 8897:     if ($dom ne '') { 
 8898:         my $domdesc = &Apache::lonnet::domain($dom,'description');
 8899:         if ($domdesc ne '') {
 8900:             $output .= ' <span class="LC_cusr_emph">('.$domdesc.')</span>';
 8901:         }
 8902:     }
 8903:     return $output;
 8904: }
 8905: 
 8906: sub crumb_utilities {
 8907:     my %elements = (
 8908:        crtuser => {
 8909:            srchterm => 'text',
 8910:            srchin => 'selectbox',
 8911:            srchby => 'selectbox',
 8912:            srchtype => 'selectbox',
 8913:            srchdomain => 'selectbox',
 8914:        },
 8915:        crtusername => {
 8916:            srchterm => 'text',
 8917:            srchdomain => 'selectbox',
 8918:        },
 8919:        docustom => {
 8920:            rolename => 'selectbox',
 8921:            newrolename => 'textbox',
 8922:        },
 8923:        studentform => {
 8924:            srchterm => 'text',
 8925:            srchin => 'selectbox',
 8926:            srchby => 'selectbox',
 8927:            srchtype => 'selectbox',
 8928:            srchdomain => 'selectbox',
 8929:        },
 8930:     );
 8931: 
 8932:     my $jsback .= qq|
 8933: function backPage(formname,prevphase,prevstate) {
 8934:     if (typeof prevphase == 'undefined') {
 8935:         formname.phase.value = '';
 8936:     }
 8937:     else {  
 8938:         formname.phase.value = prevphase;
 8939:     }
 8940:     if (typeof prevstate == 'undefined') {
 8941:         formname.currstate.value = '';
 8942:     }
 8943:     else {
 8944:         formname.currstate.value = prevstate;
 8945:     }
 8946:     formname.submit();
 8947: }
 8948: |;
 8949:     return ($jsback,\%elements);
 8950: }
 8951: 
 8952: sub course_level_table {
 8953:     my ($inccourses,$showcredits,$defaultcredits) = @_;
 8954:     return unless (ref($inccourses) eq 'HASH');
 8955:     my $table = '';
 8956: # Custom Roles?
 8957: 
 8958:     my %customroles=&Apache::lonuserutils::my_custom_roles();
 8959:     my %lt=&Apache::lonlocal::texthash(
 8960:             'exs'  => "Existing sections",
 8961:             'new'  => "Define new section",
 8962:             'ssd'  => "Set Start Date",
 8963:             'sed'  => "Set End Date",
 8964:             'crl'  => "Course Level",
 8965:             'act'  => "Activate",
 8966:             'rol'  => "Role",
 8967:             'ext'  => "Extent",
 8968:             'grs'  => "Section",
 8969:             'crd'  => "Credits",
 8970:             'sta'  => "Start",
 8971:             'end'  => "End"
 8972:     );
 8973: 
 8974:     foreach my $protectedcourse (sort(keys(%{$inccourses}))) {
 8975: 	my $thiscourse=$protectedcourse;
 8976: 	$thiscourse=~s:_:/:g;
 8977: 	my %coursedata=&Apache::lonnet::coursedescription($thiscourse);
 8978:         my $isowner = &Apache::lonuserutils::is_courseowner($protectedcourse,$coursedata{'internal.courseowner'});
 8979: 	my $area=$coursedata{'description'};
 8980:         my $crstype=$coursedata{'type'};
 8981: 	if (!defined($area)) { $area=&mt('Unavailable course').': '.$protectedcourse; }
 8982: 	my ($domain,$cnum)=split(/\//,$thiscourse);
 8983:         my %sections_count;
 8984:         if (defined($env{'request.course.id'})) {
 8985:             if ($env{'request.course.id'} eq $domain.'_'.$cnum) {
 8986:                 %sections_count = 
 8987: 		    &Apache::loncommon::get_sections($domain,$cnum);
 8988:             }
 8989:         }
 8990:         my @roles = &Apache::lonuserutils::roles_by_context('course','',$crstype);
 8991: 	foreach my $role (@roles) {
 8992:             my $plrole=&Apache::lonnet::plaintext($role,$crstype);
 8993: 	    if ((&Apache::lonnet::allowed('c'.$role,$thiscourse)) ||
 8994:                 ((($role eq 'cc') || ($role eq 'co')) && ($isowner))) {
 8995:                 $table .= &course_level_row($protectedcourse,$role,$area,$domain,
 8996:                                             $plrole,\%sections_count,\%lt,
 8997:                                             $showcredits,$defaultcredits,$crstype);
 8998:             } elsif ($env{'request.course.sec'} ne '') {
 8999:                 if (&Apache::lonnet::allowed('c'.$role,$thiscourse.'/'.
 9000:                                              $env{'request.course.sec'})) {
 9001:                     $table .= &course_level_row($protectedcourse,$role,$area,$domain,
 9002:                                                 $plrole,\%sections_count,\%lt,
 9003:                                                 $showcredits,$defaultcredits,$crstype);
 9004:                 }
 9005:             }
 9006:         }
 9007:         if (&Apache::lonnet::allowed('ccr',$thiscourse)) {
 9008:             foreach my $cust (sort(keys(%customroles))) {
 9009:                 next if ($crstype eq 'Community' && $customroles{$cust} =~ /bre\&S/);
 9010:                 my $role = 'cr_cr_'.$env{'user.domain'}.'_'.$env{'user.name'}.'_'.$cust;
 9011:                 $table .= &course_level_row($protectedcourse,$role,$area,$domain,
 9012:                                             $cust,\%sections_count,\%lt,
 9013:                                             $showcredits,$defaultcredits,$crstype);
 9014:             }
 9015: 	}
 9016:     }
 9017:     return '' if ($table eq ''); # return nothing if there is nothing 
 9018:                                  # in the table
 9019:     my $result;
 9020:     if (!$env{'request.course.id'}) {
 9021:         $result = '<h4>'.$lt{'crl'}.'</h4>'."\n";
 9022:     }
 9023:     $result .= 
 9024: &Apache::loncommon::start_data_table().
 9025: &Apache::loncommon::start_data_table_header_row().
 9026: '<th>'.$lt{'act'}.'</th><th>'.$lt{'rol'}.'</th>'."\n".
 9027: '<th>'.$lt{'ext'}.'</th><th>'."\n";
 9028:     if ($showcredits) {
 9029:         $result .= $lt{'crd'}.'</th>';
 9030:     }
 9031:     $result .=
 9032: '<th>'.$lt{'grs'}.'</th><th>'.$lt{'sta'}.'</th>'."\n".
 9033: '<th>'.$lt{'end'}.'</th>'.
 9034: &Apache::loncommon::end_data_table_header_row().
 9035: $table.
 9036: &Apache::loncommon::end_data_table();
 9037:     return $result;
 9038: }
 9039: 
 9040: sub course_level_row {
 9041:     my ($protectedcourse,$role,$area,$domain,$plrole,$sections_count,
 9042:         $lt,$showcredits,$defaultcredits,$crstype) = @_;
 9043:     my $creditem;
 9044:     my $row = &Apache::loncommon::start_data_table_row().
 9045:               ' <td><input type="checkbox" name="act_'.
 9046:               $protectedcourse.'_'.$role.'" /></td>'."\n".
 9047:               ' <td>'.$plrole.'</td>'."\n".
 9048:               ' <td>'.$area.'<br />Domain: '.$domain.'</td>'."\n";
 9049:     if (($showcredits) && ($role eq 'st') && ($crstype eq 'Course')) {
 9050:         $row .= 
 9051:             '<td><input type="text" name="credits_'.$protectedcourse.'_'.
 9052:             $role.'" size="3" value="'.$defaultcredits.'" /></td>';
 9053:     } else {
 9054:         $row .= '<td>&nbsp;</td>';
 9055:     }
 9056:     if (($role eq 'cc') || ($role eq 'co')) {
 9057:         $row .= '<td>&nbsp;</td>';
 9058:     } elsif ($env{'request.course.sec'} ne '') {
 9059:         $row .= ' <td><input type="hidden" value="'.
 9060:                 $env{'request.course.sec'}.'" '.
 9061:                 'name="sec_'.$protectedcourse.'_'.$role.'" />'.
 9062:                 $env{'request.course.sec'}.'</td>';
 9063:     } else {
 9064:         if (ref($sections_count) eq 'HASH') {
 9065:             my $currsec = 
 9066:                 &Apache::lonuserutils::course_sections($sections_count,
 9067:                                                        $protectedcourse.'_'.$role);
 9068:             $row .= '<td><table class="LC_createuser">'."\n".
 9069:                     '<tr class="LC_section_row">'."\n".
 9070:                     ' <td valign="top">'.$lt->{'exs'}.'<br />'.
 9071:                        $currsec.'</td>'."\n".
 9072:                      ' <td>&nbsp;&nbsp;</td>'."\n".
 9073:                      ' <td valign="top">&nbsp;'.$lt->{'new'}.'<br />'.
 9074:                      '<input type="text" name="newsec_'.$protectedcourse.'_'.$role.
 9075:                      '" value="" />'.
 9076:                      '<input type="hidden" '.
 9077:                      'name="sec_'.$protectedcourse.'_'.$role.'" /></td>'."\n".
 9078:                      '</tr></table></td>'."\n";
 9079:         } else {
 9080:             $row .= '<td><input type="text" size="10" '.
 9081:                     'name="sec_'.$protectedcourse.'_'.$role.'" /></td>'."\n";
 9082:         }
 9083:     }
 9084:     $row .= <<ENDTIMEENTRY;
 9085: <td><input type="hidden" name="start_$protectedcourse\_$role" value="" />
 9086: <a href=
 9087: "javascript:pjump('date_start','Start Date $plrole',document.cu.start_$protectedcourse\_$role.value,'start_$protectedcourse\_$role','cu.pres','dateset')">$lt->{'ssd'}</a></td>
 9088: <td><input type="hidden" name="end_$protectedcourse\_$role" value="" />
 9089: <a href=
 9090: "javascript:pjump('date_end','End Date $plrole',document.cu.end_$protectedcourse\_$role.value,'end_$protectedcourse\_$role','cu.pres','dateset')">$lt->{'sed'}</a></td>
 9091: ENDTIMEENTRY
 9092:     $row .= &Apache::loncommon::end_data_table_row();
 9093:     return $row;
 9094: }
 9095: 
 9096: sub course_level_dc {
 9097:     my ($dcdom,$showcredits) = @_;
 9098:     my %customroles=&Apache::lonuserutils::my_custom_roles();
 9099:     my @roles = &Apache::lonuserutils::roles_by_context('course');
 9100:     my $hiddenitems = '<input type="hidden" name="dcdomain" value="'.$dcdom.'" />'.
 9101:                       '<input type="hidden" name="origdom" value="'.$dcdom.'" />'.
 9102:                       '<input type="hidden" name="dccourse" value="" />';
 9103:     my $courseform=&Apache::loncommon::selectcourse_link
 9104:             ('cu','dccourse','dcdomain','coursedesc',undef,undef,'Select','crstype');
 9105:     my $credit_elem;
 9106:     if ($showcredits) {
 9107:         $credit_elem = 'credits';
 9108:     }
 9109:     my $cb_jscript = &Apache::loncommon::coursebrowser_javascript($dcdom,'currsec','cu','role','Course/Community Browser',$credit_elem);
 9110:     my %lt=&Apache::lonlocal::texthash(
 9111:                     'rol'  => "Role",
 9112:                     'grs'  => "Section",
 9113:                     'exs'  => "Existing sections",
 9114:                     'new'  => "Define new section", 
 9115:                     'sta'  => "Start",
 9116:                     'end'  => "End",
 9117:                     'ssd'  => "Set Start Date",
 9118:                     'sed'  => "Set End Date",
 9119:                     'scc'  => "Course/Community",
 9120:                     'crd'  => "Credits",
 9121:                   );
 9122:     my $header = '<h4>'.&mt('Course/Community Level').'</h4>'.
 9123:                  &Apache::loncommon::start_data_table().
 9124:                  &Apache::loncommon::start_data_table_header_row().
 9125:                  '<th>'.$lt{'scc'}.'</th><th>'.$lt{'rol'}.'</th>'."\n".
 9126:                  '<th>'.$lt{'grs'}.'</th>'."\n";
 9127:     $header .=   '<th>'.$lt{'crd'}.'</th>'."\n" if ($showcredits);
 9128:     $header .=   '<th>'.$lt{'sta'}.'</th><th>'.$lt{'end'}.'</th>'."\n".
 9129:                  &Apache::loncommon::end_data_table_header_row();
 9130:     my $otheritems = &Apache::loncommon::start_data_table_row()."\n".
 9131:                      '<td><br /><span class="LC_nobreak"><input type="text" name="coursedesc" value="" onfocus="this.blur();opencrsbrowser('."'cu','dccourse','dcdomain','coursedesc','','','','crstype'".')" />'.
 9132:                      $courseform.('&nbsp;' x4).'</span></td>'."\n".
 9133:                      '<td valign="top"><br /><select name="role">'."\n";
 9134:     foreach my $role (@roles) {
 9135:         my $plrole=&Apache::lonnet::plaintext($role);
 9136:         $otheritems .= '  <option value="'.$role.'">'.$plrole.'</option>';
 9137:     }
 9138:     if ( keys(%customroles) > 0) {
 9139:         foreach my $cust (sort(keys(%customroles))) {
 9140:             my $custrole='cr_cr_'.$env{'user.domain'}.
 9141:                     '_'.$env{'user.name'}.'_'.$cust;
 9142:             $otheritems .= '  <option value="'.$custrole.'">'.$cust.'</option>';
 9143:         }
 9144:     }
 9145:     $otheritems .= '</select></td><td>'.
 9146:                      '<table border="0" cellspacing="0" cellpadding="0">'.
 9147:                      '<tr><td valign="top"><b>'.$lt{'exs'}.'</b><br /><select name="currsec">'.
 9148:                      ' <option value="">&lt;--'.&mt('Pick course first').'</option></select></td>'.
 9149:                      '<td>&nbsp;&nbsp;</td>'.
 9150:                      '<td valign="top">&nbsp;<b>'.$lt{'new'}.'</b><br />'.
 9151:                      '<input type="text" name="newsec" value="" />'.
 9152:                      '<input type="hidden" name="section" value="" />'.
 9153:                      '<input type="hidden" name="groups" value="" />'.
 9154:                      '<input type="hidden" name="crstype" value="" /></td>'.
 9155:                      '</tr></table></td>'."\n";
 9156:     if ($showcredits) {
 9157:         $otheritems .= '<td><br />'."\n".
 9158:                        '<input type="text" size="3" name="credits" value="" /></td>'."\n";
 9159:     }
 9160:     $otheritems .= <<ENDTIMEENTRY;
 9161: <td><br /><input type="hidden" name="start" value='' />
 9162: <a href=
 9163: "javascript:pjump('date_start','Start Date',document.cu.start.value,'start','cu.pres','dateset')">$lt{'ssd'}</a></td>
 9164: <td><br /><input type="hidden" name="end" value='' />
 9165: <a href=
 9166: "javascript:pjump('date_end','End Date',document.cu.end.value,'end','cu.pres','dateset')">$lt{'sed'}</a></td>
 9167: ENDTIMEENTRY
 9168:     $otheritems .= &Apache::loncommon::end_data_table_row().
 9169:                    &Apache::loncommon::end_data_table()."\n";
 9170:     return $cb_jscript.$header.$hiddenitems.$otheritems;
 9171: }
 9172: 
 9173: sub update_selfenroll_config {
 9174:     my ($r,$cid,$cdom,$cnum,$context,$crstype,$currsettings) = @_;
 9175:     return unless (ref($currsettings) eq 'HASH');
 9176:     my ($row,$lt) = &Apache::lonuserutils::get_selfenroll_titles();
 9177:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
 9178:     my (%changes,%warning);
 9179:     my $curr_types;
 9180:     my %noedit;
 9181:     unless ($context eq 'domain') {
 9182:         %noedit = &get_noedit_fields($cdom,$cnum,$crstype,$row);
 9183:     }
 9184:     if (ref($row) eq 'ARRAY') {
 9185:         foreach my $item (@{$row}) {
 9186:             next if ($noedit{$item});
 9187:             if ($item eq 'enroll_dates') {
 9188:                 my (%currenrolldate,%newenrolldate);
 9189:                 foreach my $type ('start','end') {
 9190:                     $currenrolldate{$type} = $currsettings->{'selfenroll_'.$type.'_date'};
 9191:                     $newenrolldate{$type} = &Apache::lonhtmlcommon::get_date_from_form('selfenroll_'.$type.'_date');
 9192:                     if ($newenrolldate{$type} ne $currenrolldate{$type}) {
 9193:                         $changes{'internal.selfenroll_'.$type.'_date'} = $newenrolldate{$type};
 9194:                     }
 9195:                 }
 9196:             } elsif ($item eq 'access_dates') {
 9197:                 my (%currdate,%newdate);
 9198:                 foreach my $type ('start','end') {
 9199:                     $currdate{$type} = $currsettings->{'selfenroll_'.$type.'_access'};
 9200:                     $newdate{$type} = &Apache::lonhtmlcommon::get_date_from_form('selfenroll_'.$type.'_access');
 9201:                     if ($newdate{$type} ne $currdate{$type}) {
 9202:                         $changes{'internal.selfenroll_'.$type.'_access'} = $newdate{$type};
 9203:                     }
 9204:                 }
 9205:             } elsif ($item eq 'types') {
 9206:                 $curr_types = $currsettings->{'selfenroll_'.$item};
 9207:                 if ($env{'form.selfenroll_all'}) {
 9208:                     if ($curr_types ne '*') {
 9209:                         $changes{'internal.selfenroll_types'} = '*';
 9210:                     } else {
 9211:                         next;
 9212:                     }
 9213:                 } else {
 9214:                     my %currdoms;
 9215:                     my @entries = split(/;/,$curr_types);
 9216:                     my @deletedoms = &Apache::loncommon::get_env_multiple('form.selfenroll_delete');
 9217:                     my @activations = &Apache::loncommon::get_env_multiple('form.selfenroll_activate');
 9218:                     my $newnum = 0;
 9219:                     my @latesttypes;
 9220:                     foreach my $num (@activations) {
 9221:                         my @types = &Apache::loncommon::get_env_multiple('form.selfenroll_types_'.$num);
 9222:                         if (@types > 0) {
 9223:                             @types = sort(@types);
 9224:                             my $typestr = join(',',@types);
 9225:                             my $typedom = $env{'form.selfenroll_dom_'.$num};
 9226:                             $latesttypes[$newnum] = $typedom.':'.$typestr;
 9227:                             $currdoms{$typedom} = 1;
 9228:                             $newnum ++;
 9229:                         }
 9230:                     }
 9231:                     for (my $j=0; $j<$env{'form.selfenroll_types_total'}; $j++) {
 9232:                         if ((!grep(/^$j$/,@deletedoms)) && (!grep(/^$j$/,@activations))) {
 9233:                             my @types = &Apache::loncommon::get_env_multiple('form.selfenroll_types_'.$j);
 9234:                             if (@types > 0) {
 9235:                                 @types = sort(@types);
 9236:                                 my $typestr = join(',',@types);
 9237:                                 my $typedom = $env{'form.selfenroll_dom_'.$j};
 9238:                                 $latesttypes[$newnum] = $typedom.':'.$typestr;
 9239:                                 $currdoms{$typedom} = 1;
 9240:                                 $newnum ++;
 9241:                             }
 9242:                         }
 9243:                     }
 9244:                     if ($env{'form.selfenroll_newdom'} ne '') {
 9245:                         my $typedom = $env{'form.selfenroll_newdom'};
 9246:                         if ((!defined($currdoms{$typedom})) && 
 9247:                             (&Apache::lonnet::domain($typedom) ne '')) {
 9248:                             my $typestr;
 9249:                             my ($othertitle,$usertypes,$types) = 
 9250:                                 &Apache::loncommon::sorted_inst_types($typedom);
 9251:                             my $othervalue = 'any';
 9252:                             if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 9253:                                 if (@{$types} > 0) {
 9254:                                     my @esc_types = map { &escape($_); } @{$types};
 9255:                                     $othervalue = 'other';
 9256:                                     $typestr = join(',',(@esc_types,$othervalue));
 9257:                                 }
 9258:                                 $typestr = $othervalue;
 9259:                             } else {
 9260:                                 $typestr = $othervalue;
 9261:                             } 
 9262:                             $latesttypes[$newnum] = $typedom.':'.$typestr;
 9263:                             $newnum ++ ;
 9264:                         }
 9265:                     }
 9266:                     my $selfenroll_types = join(';',@latesttypes);
 9267:                     if ($selfenroll_types ne $curr_types) {
 9268:                         $changes{'internal.selfenroll_types'} = $selfenroll_types;
 9269:                     }
 9270:                 }
 9271:             } elsif ($item eq 'limit') {
 9272:                 my $newlimit = $env{'form.selfenroll_limit'};
 9273:                 my $newcap = $env{'form.selfenroll_cap'};
 9274:                 $newcap =~s/\s+//g;
 9275:                 my $currlimit =  $currsettings->{'selfenroll_limit'};
 9276:                 $currlimit = 'none' if ($currlimit eq '');
 9277:                 my $currcap = $currsettings->{'selfenroll_cap'};
 9278:                 if ($newlimit ne $currlimit) {
 9279:                     if ($newlimit ne 'none') {
 9280:                         if ($newcap =~ /^\d+$/) {
 9281:                             if ($newcap ne $currcap) {
 9282:                                 $changes{'internal.selfenroll_cap'} = $newcap;
 9283:                             }
 9284:                             $changes{'internal.selfenroll_limit'} = $newlimit;
 9285:                         } else {
 9286:                             $warning{$item} = &mt('Maximum enrollment setting unchanged.').'<br />'.
 9287:                                 &mt('The value provided was invalid - it must be a positive integer if enrollment is being limited.'); 
 9288:                         }
 9289:                     } elsif ($currcap ne '') {
 9290:                         $changes{'internal.selfenroll_cap'} = '';
 9291:                         $changes{'internal.selfenroll_limit'} = $newlimit; 
 9292:                     }
 9293:                 } elsif ($currlimit ne 'none') {
 9294:                     if ($newcap =~ /^\d+$/) {
 9295:                         if ($newcap ne $currcap) {
 9296:                             $changes{'internal.selfenroll_cap'} = $newcap;
 9297:                         }
 9298:                     } else {
 9299:                         $warning{$item} = &mt('Maximum enrollment setting unchanged.').'<br />'.
 9300:                             &mt('The value provided was invalid - it must be a positive integer if enrollment is being limited.');
 9301:                     }
 9302:                 }
 9303:             } elsif ($item eq 'approval') {
 9304:                 my (@currnotified,@newnotified);
 9305:                 my $currapproval = $currsettings->{'selfenroll_approval'};
 9306:                 my $currnotifylist = $currsettings->{'selfenroll_notifylist'};
 9307:                 if ($currnotifylist ne '') {
 9308:                     @currnotified = split(/,/,$currnotifylist);
 9309:                     @currnotified = sort(@currnotified);
 9310:                 }
 9311:                 my $newapproval = $env{'form.selfenroll_approval'};
 9312:                 @newnotified = &Apache::loncommon::get_env_multiple('form.selfenroll_notify');
 9313:                 @newnotified = sort(@newnotified);
 9314:                 if ($newapproval ne $currapproval) {
 9315:                     $changes{'internal.selfenroll_approval'} = $newapproval;
 9316:                     if (!$newapproval) {
 9317:                         if ($currnotifylist ne '') {
 9318:                             $changes{'internal.selfenroll_notifylist'} = '';
 9319:                         }
 9320:                     } else {
 9321:                         my @differences =  
 9322:                             &Apache::loncommon::compare_arrays(\@currnotified,\@newnotified);
 9323:                         if (@differences > 0) {
 9324:                             if (@newnotified > 0) {
 9325:                                 $changes{'internal.selfenroll_notifylist'} = join(',',@newnotified);
 9326:                             } else {
 9327:                                 $changes{'internal.selfenroll_notifylist'} = join(',',@newnotified);
 9328:                             }
 9329:                         }
 9330:                     }
 9331:                 } else {
 9332:                     my @differences = &Apache::loncommon::compare_arrays(\@currnotified,\@newnotified);
 9333:                     if (@differences > 0) {
 9334:                         if (@newnotified > 0) {
 9335:                             $changes{'internal.selfenroll_notifylist'} = join(',',@newnotified);
 9336:                         } else {
 9337:                             $changes{'internal.selfenroll_notifylist'} = '';
 9338:                         }
 9339:                     }
 9340:                 }
 9341:             } else {
 9342:                 my $curr_val = $currsettings->{'selfenroll_'.$item};
 9343:                 my $newval = $env{'form.selfenroll_'.$item};
 9344:                 if ($item eq 'section') {
 9345:                     $newval = $env{'form.sections'};
 9346:                     if (defined($curr_groups{$newval})) {
 9347:                         $newval = $curr_val;
 9348:                         $warning{$item} = &mt('Section for self-enrolled users unchanged as the proposed section is a group').'<br />'.
 9349:                                           &mt('Group names and section names must be distinct');
 9350:                     } elsif ($newval eq 'all') {
 9351:                         $newval = $curr_val;
 9352:                         $warning{$item} = &mt('Section for self-enrolled users unchanged, as "all" is a reserved section name.');
 9353:                     }
 9354:                     if ($newval eq '') {
 9355:                         $newval = 'none';
 9356:                     }
 9357:                 }
 9358:                 if ($newval ne $curr_val) {
 9359:                     $changes{'internal.selfenroll_'.$item} = $newval;
 9360:                 }
 9361:             }
 9362:         }
 9363:         if (keys(%warning) > 0) {
 9364:             foreach my $item (@{$row}) {
 9365:                 if (exists($warning{$item})) {
 9366:                     $r->print($warning{$item}.'<br />');
 9367:                 }
 9368:             } 
 9369:         }
 9370:         if (keys(%changes) > 0) {
 9371:             my $putresult = &Apache::lonnet::put('environment',\%changes,$cdom,$cnum);
 9372:             if ($putresult eq 'ok') {
 9373:                 if ((exists($changes{'internal.selfenroll_types'})) ||
 9374:                     (exists($changes{'internal.selfenroll_start_date'}))  ||
 9375:                     (exists($changes{'internal.selfenroll_end_date'}))) {
 9376:                     my %crsinfo = &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',
 9377:                                                                 $cnum,undef,undef,'Course');
 9378:                     my $chome = &Apache::lonnet::homeserver($cnum,$cdom);
 9379:                     if (ref($crsinfo{$cid}) eq 'HASH') {
 9380:                         foreach my $item ('selfenroll_types','selfenroll_start_date','selfenroll_end_date') {
 9381:                             if (exists($changes{'internal.'.$item})) {
 9382:                                 $crsinfo{$cid}{$item} = $changes{'internal.'.$item};
 9383:                             }
 9384:                         }
 9385:                         my $crsputresult =
 9386:                             &Apache::lonnet::courseidput($cdom,\%crsinfo,
 9387:                                                          $chome,'notime');
 9388:                     }
 9389:                 }
 9390:                 $r->print(&mt('The following changes were made to self-enrollment settings:').'<ul>');
 9391:                 foreach my $item (@{$row}) {
 9392:                     my $title = $item;
 9393:                     if (ref($lt) eq 'HASH') {
 9394:                         $title = $lt->{$item};
 9395:                     }
 9396:                     if ($item eq 'enroll_dates') {
 9397:                         foreach my $type ('start','end') {
 9398:                             if (exists($changes{'internal.selfenroll_'.$type.'_date'})) {
 9399:                                 my $newdate = &Apache::lonlocal::locallocaltime($changes{'internal.selfenroll_'.$type.'_date'});
 9400:                                 $r->print('<li>'.&mt('[_1]: "[_2]" set to "[_3]".',
 9401:                                           $title,$type,$newdate).'</li>');
 9402:                             }
 9403:                         }
 9404:                     } elsif ($item eq 'access_dates') {
 9405:                         foreach my $type ('start','end') {
 9406:                             if (exists($changes{'internal.selfenroll_'.$type.'_access'})) {
 9407:                                 my $newdate = &Apache::lonlocal::locallocaltime($changes{'internal.selfenroll_'.$type.'_access'});
 9408:                                 $r->print('<li>'.&mt('[_1]: "[_2]" set to "[_3]".',
 9409:                                           $title,$type,$newdate).'</li>');
 9410:                             }
 9411:                         }
 9412:                     } elsif ($item eq 'limit') {
 9413:                         if ((exists($changes{'internal.selfenroll_limit'})) ||
 9414:                             (exists($changes{'internal.selfenroll_cap'}))) {
 9415:                             my ($newval,$newcap);
 9416:                             if ($changes{'internal.selfenroll_cap'} ne '') {
 9417:                                 $newcap = $changes{'internal.selfenroll_cap'}
 9418:                             } else {
 9419:                                 $newcap = $currsettings->{'selfenroll_cap'};
 9420:                             }
 9421:                             if ($changes{'internal.selfenroll_limit'} eq 'none') {
 9422:                                 $newval = &mt('No limit');
 9423:                             } elsif ($changes{'internal.selfenroll_limit'} eq 
 9424:                                      'allstudents') {
 9425:                                 $newval = &mt('New self-enrollment no longer allowed when total (all students) reaches [_1].',$newcap);
 9426:                             } elsif ($changes{'internal.selfenroll_limit'} eq 'selfenrolled') {
 9427:                                 $newval = &mt('New self-enrollment no longer allowed when total number of self-enrolled students reaches [_1].',$newcap);
 9428:                             } else {
 9429:                                 my $currlimit =  $currsettings->{'selfenroll_limit'};
 9430:                                 if ($currlimit eq 'allstudents') {
 9431:                                     $newval = &mt('New self-enrollment no longer allowed when total (all students) reaches [_1].',$newcap);
 9432:                                 } elsif ($changes{'internal.selfenroll_limit'} eq 'selfenrolled') {
 9433:                                     $newval =  &mt('New self-enrollment no longer allowed when total number of self-enrolled students reaches [_1].',$newcap);
 9434:                                 }
 9435:                             }
 9436:                             $r->print('<li>'.&mt('"[_1]" set to "[_2]".',$title,$newval).'</li>'."\n");
 9437:                         }
 9438:                     } elsif ($item eq 'approval') {
 9439:                         if ((exists($changes{'internal.selfenroll_approval'})) ||
 9440:                             (exists($changes{'internal.selfenroll_notifylist'}))) {
 9441:                             my %selfdescs = &Apache::lonuserutils::selfenroll_default_descs();
 9442:                             my ($newval,$newnotify);
 9443:                             if (exists($changes{'internal.selfenroll_notifylist'})) {
 9444:                                 $newnotify = $changes{'internal.selfenroll_notifylist'};
 9445:                             } else {   
 9446:                                 $newnotify = $currsettings->{'selfenroll_notifylist'};
 9447:                             }
 9448:                             if (exists($changes{'internal.selfenroll_approval'})) {
 9449:                                 if ($changes{'internal.selfenroll_approval'} !~ /^[012]$/) {
 9450:                                     $changes{'internal.selfenroll_approval'} = '0';
 9451:                                 }
 9452:                                 $newval = $selfdescs{'approval'}{$changes{'internal.selfenroll_approval'}};
 9453:                             } else {
 9454:                                 my $currapproval = $currsettings->{'selfenroll_approval'}; 
 9455:                                 if ($currapproval !~ /^[012]$/) {
 9456:                                     $currapproval = 0;
 9457:                                 }
 9458:                                 $newval = $selfdescs{'approval'}{$currapproval};
 9459:                             }
 9460:                             $r->print('<li>'.&mt('"[_1]" set to "[_2]".',$title,$newval));
 9461:                             if ($newnotify) {
 9462:                                 $r->print('<br />'.&mt('The following will be notified when an enrollment request needs approval, or has been approved: [_1].',$newnotify));
 9463:                             } else {
 9464:                                 $r->print('<br />'.&mt('No notifications sent when an enrollment request needs approval, or has been approved.'));
 9465:                             }
 9466:                             $r->print('</li>'."\n");
 9467:                         }
 9468:                     } else {
 9469:                         if (exists($changes{'internal.selfenroll_'.$item})) {
 9470:                             my $newval = $changes{'internal.selfenroll_'.$item};
 9471:                             if ($item eq 'types') {
 9472:                                 if ($newval eq '') {
 9473:                                     $newval = &mt('None');
 9474:                                 } elsif ($newval eq '*') {
 9475:                                     $newval = &mt('Any user in any domain');
 9476:                                 }
 9477:                             } elsif ($item eq 'registered') {
 9478:                                 if ($newval eq '1') {
 9479:                                     $newval = &mt('Yes');
 9480:                                 } elsif ($newval eq '0') {
 9481:                                     $newval = &mt('No');
 9482:                                 }
 9483:                             }
 9484:                             $r->print('<li>'.&mt('"[_1]" set to "[_2]".',$title,$newval).'</li>'."\n");
 9485:                         }
 9486:                     }
 9487:                 }
 9488:                 $r->print('</ul>');
 9489:                 if ($env{'course.'.$cid.'.description'} ne '') {
 9490:                     my %newenvhash;
 9491:                     foreach my $key (keys(%changes)) {
 9492:                         $newenvhash{'course.'.$cid.'.'.$key} = $changes{$key};
 9493:                     }
 9494:                     &Apache::lonnet::appenv(\%newenvhash);
 9495:                 }
 9496:             } else {
 9497:                 $r->print(&mt('An error occurred when saving changes to self-enrollment settings in this course.').'<br />'.
 9498:                           &mt('The error was: [_1].',$putresult));
 9499:             }
 9500:         } else {
 9501:             $r->print(&mt('No changes were made to the existing self-enrollment settings in this course.'));
 9502:         }
 9503:     } else {
 9504:         $r->print(&mt('No changes were made to the existing self-enrollment settings in this course.'));
 9505:     }
 9506:     my $visactions = &cat_visibility();
 9507:     my ($cathash,%cattype);
 9508:     my %domconfig = &Apache::lonnet::get_dom('configuration',['coursecategories'],$cdom);
 9509:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 9510:         $cathash = $domconfig{'coursecategories'}{'cats'};
 9511:         $cattype{'auth'} = $domconfig{'coursecategories'}{'auth'};
 9512:         $cattype{'unauth'} = $domconfig{'coursecategories'}{'unauth'};
 9513:     } else {
 9514:         $cathash = {};
 9515:         $cattype{'auth'} = 'std';
 9516:         $cattype{'unauth'} = 'std';
 9517:     }
 9518:     if (($cattype{'auth'} eq 'none') && ($cattype{'unauth'} eq 'none')) {
 9519:         $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
 9520:                   '<br />'.
 9521:                   '<br />'.$visactions->{'take'}.'<ul>'.
 9522:                   '<li>'.$visactions->{'dc_chgconf'}.'</li>'.
 9523:                   '</ul>');
 9524:     } elsif (($cattype{'auth'} !~ /^(std|domonly)$/) && ($cattype{'unauth'} !~ /^(std|domonly)$/)) {
 9525:         if ($currsettings->{'uniquecode'}) {
 9526:             $r->print('<span class="LC_info">'.$visactions->{'vis'}.'</span>');
 9527:         } else {
 9528:             $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
 9529:                   '<br />'.
 9530:                   '<br />'.$visactions->{'take'}.'<ul>'.
 9531:                   '<li>'.$visactions->{'dc_setcode'}.'</li>'.
 9532:                   '</ul><br />');
 9533:         }
 9534:     } else {
 9535:         my ($visible,$cansetvis,$vismsgs) = &visible_in_stdcat($cdom,$cnum,\%domconfig);
 9536:         if (ref($visactions) eq 'HASH') {
 9537:             if (!$visible) {
 9538:                 $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
 9539:                           '<br />');
 9540:                 if (ref($vismsgs) eq 'ARRAY') {
 9541:                     $r->print('<br />'.$visactions->{'take'}.'<ul>');
 9542:                     foreach my $item (@{$vismsgs}) {
 9543:                         $r->print('<li>'.$visactions->{$item}.'</li>');
 9544:                     }
 9545:                     $r->print('</ul>');
 9546:                 }
 9547:                 $r->print($cansetvis);
 9548:             }
 9549:         }
 9550:     } 
 9551:     return;
 9552: }
 9553: 
 9554: #---------------------------------------------- end functions for &phase_two
 9555: 
 9556: #--------------------------------- functions for &phase_two and &phase_three
 9557: 
 9558: #--------------------------end of functions for &phase_two and &phase_three
 9559: 
 9560: 1;
 9561: __END__
 9562: 
 9563: 

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