File:  [LON-CAPA] / loncom / interface / loncreateuser.pm
Revision 1.406.2.20.2.4: download - view: text, annotated - select for diffs
Mon Sep 4 16:16:19 2023 UTC (9 months ago) by raeburn
Branches: version_2_11_4_msu
Diff to branchpoint 1.406.2.20: preferred, unified
- For 2.11.4 (modified)
  Include changes in rev. 1.469

    1: # The LearningOnline Network with CAPA
    2: # Create a user
    3: #
    4: # $Id: loncreateuser.pm,v 1.406.2.20.2.4 2023/09/04 16:16:19 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: ###
   29: 
   30: package Apache::loncreateuser;
   31: 
   32: =pod
   33: 
   34: =head1 NAME
   35: 
   36: Apache::loncreateuser.pm
   37: 
   38: =head1 SYNOPSIS
   39: 
   40:     Handler to create users and custom roles
   41: 
   42:     Provides an Apache handler for creating users,
   43:     editing their login parameters, roles, and removing roles, and
   44:     also creating and assigning custom roles.
   45: 
   46: =head1 OVERVIEW
   47: 
   48: =head2 Custom Roles
   49: 
   50: In LON-CAPA, roles are actually collections of privileges. "Teaching
   51: Assistant", "Course Coordinator", and other such roles are really just
   52: collection of privileges that are useful in many circumstances.
   53: 
   54: Custom roles can be defined by a Domain Coordinator, Course Coordinator
   55: or Community Coordinator via the Manage User functionality.
   56: The custom role editor screen will show all privileges which can be
   57: assigned to users. For a complete list of privileges, please see 
   58: C</home/httpd/lonTabs/rolesplain.tab>.
   59: 
   60: Custom role definitions are stored in the C<roles.db> file of the creator
   61: of the role.
   62: 
   63: =cut
   64: 
   65: use strict;
   66: use Apache::Constants qw(:common :http);
   67: use Apache::lonnet;
   68: use Apache::loncommon;
   69: use Apache::lonlocal;
   70: use Apache::longroup;
   71: use Apache::lonuserutils;
   72: use Apache::loncoursequeueadmin;
   73: use LONCAPA qw(:DEFAULT :match);
   74: use HTML::Entities;
   75: 
   76: my $loginscript; # piece of javascript used in two separate instances
   77: my $authformnop;
   78: my $authformkrb;
   79: my $authformint;
   80: my $authformfsys;
   81: my $authformloc;
   82: 
   83: sub initialize_authen_forms {
   84:     my ($dom,$formname,$curr_authtype,$mode) = @_;
   85:     my ($krbdef,$krbdefdom) = &Apache::loncommon::get_kerberos_defaults($dom);
   86:     my %param = ( formname => $formname,
   87:                   kerb_def_dom => $krbdefdom,
   88:                   kerb_def_auth => $krbdef,
   89:                   domain => $dom,
   90:                 );
   91:     my %abv_auth = &auth_abbrev();
   92:     if ($curr_authtype =~ /^(krb4|krb5|internal|localauth|unix):(.*)$/) {
   93:         my $long_auth = $1;
   94:         my $curr_autharg = $2;
   95:         my %abv_auth = &auth_abbrev();
   96:         $param{'curr_authtype'} = $abv_auth{$long_auth};
   97:         if ($long_auth =~ /^krb(4|5)$/) {
   98:             $param{'curr_kerb_ver'} = $1;
   99:             $param{'curr_autharg'} = $curr_autharg;
  100:         }
  101:         if ($mode eq 'modifyuser') {
  102:             $param{'mode'} = $mode;
  103:         }
  104:     }
  105:     $loginscript  = &Apache::loncommon::authform_header(%param);
  106:     $authformkrb  = &Apache::loncommon::authform_kerberos(%param);
  107:     $authformnop  = &Apache::loncommon::authform_nochange(%param);
  108:     $authformint  = &Apache::loncommon::authform_internal(%param);
  109:     $authformfsys = &Apache::loncommon::authform_filesystem(%param);
  110:     $authformloc  = &Apache::loncommon::authform_local(%param);
  111: }
  112: 
  113: sub auth_abbrev {
  114:     my %abv_auth = (
  115:                      krb5      => 'krb',
  116:                      krb4      => 'krb',
  117:                      internal  => 'int',
  118:                      localauth => 'loc',
  119:                      unix      => 'fsys',
  120:                    );
  121:     return %abv_auth;
  122: }
  123: 
  124: # ====================================================
  125: 
  126: sub user_quotas {
  127:     my ($ccuname,$ccdomain) = @_;
  128:     my %lt = &Apache::lonlocal::texthash(
  129:                    'usrt'      => "User Tools",
  130:                    'cust'      => "Custom quota",
  131:                    'chqu'      => "Change quota",
  132:     );
  133:    
  134:     my $quota_javascript = <<"END_SCRIPT";
  135: <script type="text/javascript">
  136: // <![CDATA[
  137: function quota_changes(caller,context) {
  138:     var customoff = document.getElementById('custom_'+context+'quota_off');
  139:     var customon = document.getElementById('custom_'+context+'quota_on');
  140:     var number = document.getElementById(context+'quota');
  141:     if (caller == "custom") {
  142:         if (customoff) {
  143:             if (customoff.checked) {
  144:                 number.value = "";
  145:             }
  146:         }
  147:     }
  148:     if (caller == "quota") {
  149:         if (customon) {
  150:             customon.checked = true;
  151:         }
  152:     }
  153:     return;
  154: }
  155: // ]]>
  156: </script>
  157: END_SCRIPT
  158:     my $longinsttype;
  159:     my ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($ccdomain);
  160:     my $output = $quota_javascript."\n".
  161:                  '<h3>'.$lt{'usrt'}.'</h3>'."\n".
  162:                  &Apache::loncommon::start_data_table();
  163: 
  164:     if ((&Apache::lonnet::allowed('mut',$ccdomain)) ||
  165:         (&Apache::lonnet::allowed('udp',$ccdomain))) {
  166:         $output .= &build_tools_display($ccuname,$ccdomain,'tools');
  167:     }
  168: 
  169:     my %titles = &Apache::lonlocal::texthash (
  170:                     portfolio => "Disk space allocated to user's portfolio files",
  171:                     author    => "Disk space allocated to user's Authoring Space (if role assigned)",
  172:                  );
  173:     foreach my $name ('portfolio','author') {
  174:         my ($currquota,$quotatype,$inststatus,$defquota) =
  175:             &Apache::loncommon::get_user_quota($ccuname,$ccdomain,$name);
  176:         if ($longinsttype eq '') { 
  177:             if ($inststatus ne '') {
  178:                 if ($usertypes->{$inststatus} ne '') {
  179:                     $longinsttype = $usertypes->{$inststatus};
  180:                 }
  181:             }
  182:         }
  183:         my ($showquota,$custom_on,$custom_off,$defaultinfo);
  184:         $custom_on = ' ';
  185:         $custom_off = ' checked="checked" ';
  186:         if ($quotatype eq 'custom') {
  187:             $custom_on = $custom_off;
  188:             $custom_off = ' ';
  189:             $showquota = $currquota;
  190:             if ($longinsttype eq '') {
  191:                 $defaultinfo = &mt('For this user, the default quota would be [_1]'
  192:                               .' MB.',$defquota);
  193:             } else {
  194:                 $defaultinfo = &mt("For this user, the default quota would be [_1]".
  195:                                    " MB, as determined by the user's institutional".
  196:                                    " affiliation ([_2]).",$defquota,$longinsttype);
  197:             }
  198:         } else {
  199:             if ($longinsttype eq '') {
  200:                 $defaultinfo = &mt('For this user, the default quota is [_1]'
  201:                               .' MB.',$defquota);
  202:             } else {
  203:                 $defaultinfo = &mt("For this user, the default quota of [_1]".
  204:                                    " MB, is determined by the user's institutional".
  205:                                    " affiliation ([_2]).",$defquota,$longinsttype);
  206:             }
  207:         }
  208: 
  209:         if (&Apache::lonnet::allowed('mpq',$ccdomain)) {
  210:             $output .= '<tr class="LC_info_row">'."\n".
  211:                        '    <td>'.$titles{$name}.'</td>'."\n".
  212:                        '  </tr>'."\n".
  213:                        &Apache::loncommon::start_data_table_row()."\n".
  214:                        '  <td><span class="LC_nobreak">'.
  215:                        &mt('Current quota: [_1] MB',$currquota).'</span>&nbsp;&nbsp;'.
  216:                        $defaultinfo.'</td>'."\n".
  217:                        &Apache::loncommon::end_data_table_row()."\n".
  218:                        &Apache::loncommon::start_data_table_row()."\n".
  219:                        '  <td><span class="LC_nobreak">'.$lt{'chqu'}.
  220:                        ': <label>'.
  221:                        '<input type="radio" name="custom_'.$name.'quota" id="custom_'.$name.'quota_off" '.
  222:                        'value="0" '.$custom_off.' onchange="javascript:quota_changes('."'custom','$name'".');"'.
  223:                        ' /><span class="LC_nobreak">'.
  224:                        &mt('Default ([_1] MB)',$defquota).'</span></label>&nbsp;'.
  225:                        '&nbsp;<label><input type="radio" name="custom_'.$name.'quota" id="custom_'.$name.'quota_on" '.
  226:                        'value="1" '.$custom_on.'  onchange="javascript:quota_changes('."'custom','$name'".');"'.
  227:                        ' />'.$lt{'cust'}.':</label>&nbsp;'.
  228:                        '<input type="text" name="'.$name.'quota" id="'.$name.'quota" size ="5" '.
  229:                        'value="'.$showquota.'" onfocus="javascript:quota_changes('."'quota','$name'".');"'.
  230:                        ' />&nbsp;'.&mt('MB').'</span></td>'."\n".
  231:                        &Apache::loncommon::end_data_table_row()."\n";
  232:         }
  233:     }
  234:     $output .= &Apache::loncommon::end_data_table();
  235:     return $output;
  236: }
  237: 
  238: sub build_tools_display {
  239:     my ($ccuname,$ccdomain,$context) = @_;
  240:     my (@usertools,%userenv,$output,@options,%validations,%reqtitles,%reqdisplay,
  241:         $colspan,$isadv,%domconfig);
  242:     my %lt = &Apache::lonlocal::texthash (
  243:                    'blog'       => "Personal User Blog",
  244:                    'aboutme'    => "Personal Information Page",
  245:                    'webdav'     => "WebDAV access to Authoring Spaces (if SSL and author/co-author)",
  246:                    'portfolio'  => "Personal User Portfolio",
  247:                    'timezone'   => "Can set Time Zone",
  248:                    'avai'       => "Available",
  249:                    'cusa'       => "availability",
  250:                    'chse'       => "Change setting",
  251:                    'usde'       => "Use default",
  252:                    'uscu'       => "Use custom",
  253:                    'official'   => 'Can request creation of official courses',
  254:                    'unofficial' => 'Can request creation of unofficial courses',
  255:                    'community'  => 'Can request creation of communities',
  256:                    'textbook'   => 'Can request creation of textbook courses',
  257:                    'requestauthor'  => 'Can request author space',
  258:     );
  259:     $isadv = &Apache::lonnet::is_advanced_user($ccdomain,$ccuname);
  260:     if ($context eq 'requestcourses') {
  261:         %userenv = &Apache::lonnet::userenvironment($ccdomain,$ccuname,
  262:                       'requestcourses.official','requestcourses.unofficial',
  263:                       'requestcourses.community','requestcourses.textbook');
  264:         @usertools = ('official','unofficial','community','textbook');
  265:         @options =('norequest','approval','autolimit','validate');
  266:         %validations = &Apache::lonnet::auto_courserequest_checks($ccdomain);
  267:         %reqtitles = &courserequest_titles();
  268:         %reqdisplay = &courserequest_display();
  269:         $colspan = ' colspan="2"';
  270:         %domconfig =
  271:             &Apache::lonnet::get_dom('configuration',['requestcourses'],$ccdomain);
  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','tools.timezone');
  286:         @usertools = ('aboutme','blog','webdav','portfolio','timezone');
  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,\%userenv,'',
  296:                                               {'is_adv' => $isadv});
  297:         if ($context eq 'requestauthor') {
  298:             if ($userenv{$context} ne '') {
  299:                 $cust_on = ' checked="checked" ';
  300:                 $cust_off = '';
  301:             }  
  302:         } elsif ($userenv{$context.'.'.$item} ne '') {
  303:             $cust_on = ' checked="checked" ';
  304:             $cust_off = '';
  305:         }
  306:         if ($context eq 'requestcourses') {
  307:             if ($userenv{$context.'.'.$item} eq '') {
  308:                 $custom_access = &mt('Currently from default setting.');
  309:             } else {
  310:                 $custom_access = &mt('Currently from custom setting.');
  311:             }
  312:         } elsif ($context eq 'requestauthor') {
  313:             if ($userenv{$context} eq '') {
  314:                 $custom_access = &mt('Currently from default setting.');
  315:             } else {
  316:                 $custom_access = &mt('Currently from custom setting.');
  317:             }
  318:         } else {
  319:             if ($userenv{$context.'.'.$item} eq '') {
  320:                 $custom_access =
  321:                     &mt('Availability determined currently from default setting.');
  322:                 if (!$curr_access) {
  323:                     $tool_off = 'checked="checked" ';
  324:                     $tool_on = '';
  325:                 }
  326:             } else {
  327:                 $custom_access =
  328:                     &mt('Availability determined currently from custom setting.');
  329:                 if ($userenv{$context.'.'.$item} == 0) {
  330:                     $tool_off = 'checked="checked" ';
  331:                     $tool_on = '';
  332:                 }
  333:             }
  334:         }
  335:         $output .= '  <tr class="LC_info_row">'."\n".
  336:                    '   <td'.$colspan.'>'.$lt{$item}.'</td>'."\n".
  337:                    '  </tr>'."\n".
  338:                    &Apache::loncommon::start_data_table_row()."\n";
  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:     );
  458: 
  459:     %userenv = &Apache::lonnet::userenvironment($ccdomain,$ccuname,
  460:                       'reqcrsotherdom.official','reqcrsotherdom.unofficial',
  461:                       'reqcrsotherdom.community','reqcrsotherdom.textbook');
  462:     @usertools = ('official','unofficial','community','textbook');
  463:     @options = ('approval','validate','autolimit');
  464:     %validations = &Apache::lonnet::auto_courserequest_checks($cdom);
  465:     my $optregex = join('|',@options);
  466:     my %reqtitles = &courserequest_titles();
  467:     foreach my $item (@usertools) {
  468:         my ($curroption,$currlimit,$tooloff);
  469:         if ($userenv{'reqcrsotherdom.'.$item} ne '') {
  470:             my @curr = split(',',$userenv{'reqcrsotherdom.'.$item});
  471:             foreach my $req (@curr) {
  472:                 if ($req =~ /^\Q$cdom\E\:($optregex)=?(\d*)$/) {
  473:                     $curroption = $1;
  474:                     $currlimit = $2;
  475:                     last;
  476:                 }
  477:             }
  478:             if (!$curroption) {
  479:                 $curroption = 'norequest';
  480:                 $tooloff = ' checked="checked"';
  481:             }
  482:         } else {
  483:             $curroption = 'norequest';
  484:             $tooloff = ' checked="checked"';
  485:         }
  486:         $output.= &Apache::loncommon::start_data_table_row()."\n".
  487:                   '  <td><span class="LC_nobreak">'.$lt{$item}.': </span></td><td>'.
  488:                   '<table><tr><td valign="top">'."\n".
  489:                   '<label><input type="radio" name="reqcrsotherdom_'.$item.
  490:                   '" value=""'.$tooloff.' />'.$reqtitles{'norequest'}.
  491:                   '</label></td>';
  492:         foreach my $option (@options) {
  493:             if ($option eq 'validate') {
  494:                 my $canvalidate = 0;
  495:                 if (ref($validations{$item}) eq 'HASH') {
  496:                     if ($validations{$item}{'_external_'}) {
  497:                         $canvalidate = 1;
  498:                     }
  499:                 }
  500:                 next if (!$canvalidate);
  501:             }
  502:             my $checked = '';
  503:             if ($option eq $curroption) {
  504:                 $checked = ' checked="checked"';
  505:             }
  506:             $output .= '<td valign="top"><span class="LC_nobreak"><label>'.
  507:                        '<input type="radio" name="reqcrsotherdom_'.$item.
  508:                        '" value="'.$option.'"'.$checked.' />'.
  509:                        $reqtitles{$option}.'</label>';
  510:             if ($option eq 'autolimit') {
  511:                 $output .= '&nbsp;<input type="text" name="reqcrsotherdom_'.
  512:                            $item.'_limit" size="1" '.
  513:                            'value="'.$currlimit.'" /></span>'.
  514:                            '<br />'.$reqtitles{'unlimited'};
  515:             } else {
  516:                 $output .= '</span>';
  517:             }
  518:             $output .= '</td>';
  519:         }
  520:         $output .= '</td></tr></table></td>'."\n".
  521:                    &Apache::loncommon::end_data_table_row()."\n";
  522:     }
  523:     return $output;
  524: }
  525: 
  526: sub domainrole_req {
  527:     my ($ccuname,$ccdomain) = @_;
  528:     return '<br /><h3>'.
  529:            &mt('User Can Request Assignment of Domain Roles?').
  530:            '</h3>'."\n".
  531:            &Apache::loncommon::start_data_table().
  532:            &build_tools_display($ccuname,$ccdomain,
  533:                                 'requestauthor').
  534:            &Apache::loncommon::end_data_table();
  535: }
  536: 
  537: sub courserequest_titles {
  538:     my %titles = &Apache::lonlocal::texthash (
  539:                                    official   => 'Official',
  540:                                    unofficial => 'Unofficial',
  541:                                    community  => 'Communities',
  542:                                    textbook   => 'Textbook',
  543:                                    norequest  => 'Not allowed',
  544:                                    approval   => 'Approval by Dom. Coord.',
  545:                                    validate   => 'With validation',
  546:                                    autolimit  => 'Numerical limit',
  547:                                    unlimited  => '(blank for unlimited)',
  548:                  );
  549:     return %titles;
  550: }
  551: 
  552: sub courserequest_display {
  553:     my %titles = &Apache::lonlocal::texthash (
  554:                                    approval   => 'Yes, need approval',
  555:                                    validate   => 'Yes, with validation',
  556:                                    norequest  => 'No',
  557:    );
  558:    return %titles;
  559: }
  560: 
  561: sub requestauthor_titles {
  562:     my %titles = &Apache::lonlocal::texthash (
  563:                                    norequest  => 'Not allowed',
  564:                                    approval   => 'Approval by Dom. Coord.',
  565:                                    automatic  => 'Automatic approval',
  566:                  );
  567:     return %titles;
  568: 
  569: }
  570: 
  571: sub requestauthor_display {
  572:     my %titles = &Apache::lonlocal::texthash (
  573:                                    approval   => 'Yes, need approval',
  574:                                    automatic  => 'Yes, automatic approval',
  575:                                    norequest  => 'No',
  576:    );
  577:    return %titles;
  578: }
  579: 
  580: sub requestchange_display {
  581:     my %titles = &Apache::lonlocal::texthash (
  582:                                    approval   => "availability set to 'on' (approval required)", 
  583:                                    automatic  => "availability set to 'on' (automatic approval)",
  584:                                    norequest  => "availability set to 'off'",
  585:    );
  586:    return %titles;
  587: }
  588: 
  589: sub curr_requestauthor {
  590:     my ($uname,$udom,$isadv,$inststatuses,$domconfig) = @_;
  591:     return unless ((ref($inststatuses) eq 'ARRAY') && (ref($domconfig) eq 'HASH'));
  592:     if ($uname eq '' || $udom eq '') {
  593:         $uname = $env{'user.name'};
  594:         $udom = $env{'user.domain'};
  595:         $isadv = $env{'user.adv'};
  596:     }
  597:     my (%userenv,%settings,$val);
  598:     my @options = ('automatic','approval');
  599:     %userenv =
  600:         &Apache::lonnet::userenvironment($udom,$uname,'requestauthor','inststatus');
  601:     if ($userenv{'requestauthor'}) {
  602:         $val = $userenv{'requestauthor'};
  603:         @{$inststatuses} = ('_custom_');
  604:     } else {
  605:         my %alltasks;
  606:         if (ref($domconfig->{'requestauthor'}) eq 'HASH') {
  607:             %settings = %{$domconfig->{'requestauthor'}};
  608:             if (($isadv) && ($settings{'_LC_adv'} ne '')) {
  609:                 $val = $settings{'_LC_adv'};
  610:                 @{$inststatuses} = ('_LC_adv_');
  611:             } else {
  612:                 if ($userenv{'inststatus'} ne '') {
  613:                     @{$inststatuses} = split(',',$userenv{'inststatus'});
  614:                 } else {
  615:                     @{$inststatuses} = ('default');
  616:                 }
  617:                 foreach my $status (@{$inststatuses}) {
  618:                     if (exists($settings{$status})) {
  619:                         my $value = $settings{$status};
  620:                         next unless ($value);
  621:                         unless (exists($alltasks{$value})) {
  622:                             if (ref($alltasks{$value}) eq 'ARRAY') {
  623:                                 unless(grep(/^\Q$status\E$/,@{$alltasks{$value}})) {
  624:                                     push(@{$alltasks{$value}},$status);
  625:                                 }
  626:                             } else {
  627:                                 @{$alltasks{$value}} = ($status);
  628:                             }
  629:                         }
  630:                     }
  631:                 }
  632:                 foreach my $option (@options) {
  633:                     if ($alltasks{$option}) {
  634:                         $val = $option;
  635:                         last;
  636:                     }
  637:                 }
  638:             }
  639:         }
  640:     }
  641:     return $val;
  642: }
  643: 
  644: # =================================================================== Phase one
  645: 
  646: sub print_username_entry_form {
  647:     my ($r,$context,$response,$srch,$forcenewuser,$crstype,$brcrum,
  648:         $permission) = @_;
  649:     my $defdom=$env{'request.role.domain'};
  650:     my $formtoset = 'crtuser';
  651:     if (exists($env{'form.startrolename'})) {
  652:         $formtoset = 'docustom';
  653:         $env{'form.rolename'} = $env{'form.startrolename'};
  654:     } elsif ($env{'form.origform'} eq 'crtusername') {
  655:         $formtoset =  $env{'form.origform'};
  656:     }
  657: 
  658:     my ($jsback,$elements) = &crumb_utilities();
  659: 
  660:     my $jscript = &Apache::loncommon::studentbrowser_javascript()."\n".
  661:         '<script type="text/javascript">'."\n".
  662:         '// <![CDATA['."\n".
  663:         &Apache::lonhtmlcommon::set_form_elements($elements->{$formtoset})."\n".
  664:         '// ]]>'."\n".
  665:         '</script>'."\n";
  666: 
  667:     my %existingroles=&Apache::lonuserutils::my_custom_roles($crstype);
  668:     if (($env{'form.action'} eq 'custom') && (keys(%existingroles) > 0)
  669:         && (&Apache::lonnet::allowed('mcr','/'))) {
  670:         $jscript .= &customrole_javascript();
  671:     }
  672:     my $helpitem = 'Course_Change_Privileges';
  673:     if ($env{'form.action'} eq 'custom') {
  674:         if ($context eq 'course') {
  675:             $helpitem = 'Course_Editing_Custom_Roles';
  676:         } elsif ($context eq 'domain') {
  677:             $helpitem = 'Domain_Editing_Custom_Roles';
  678:         }
  679:     } elsif ($env{'form.action'} eq 'singlestudent') {
  680:         $helpitem = 'Course_Add_Student';
  681:     } elsif ($env{'form.action'} eq 'accesslogs') {
  682:         $helpitem = 'Domain_User_Access_Logs';
  683:     } elsif ($context eq 'author') {
  684:         $helpitem = 'Author_Change_Privileges';
  685:     } elsif ($context eq 'domain') {
  686:         if ($permission->{'cusr'}) {
  687:             $helpitem = 'Domain_Change_Privileges';
  688:         } elsif ($permission->{'view'}) {
  689:             $helpitem = 'Domain_View_Privileges';
  690:         } else {
  691:             undef($helpitem);
  692:         }
  693:     }
  694:     my %breadcrumb_text = &singleuser_breadcrumb($crstype,$context,$defdom);
  695:     if ($env{'form.action'} eq 'custom') {
  696:         push(@{$brcrum},
  697:                  {href=>"javascript:backPage(document.crtuser)",       
  698:                   text=>"Pick custom role",
  699:                   help => $helpitem,}
  700:                  );
  701:     } else {
  702:         push (@{$brcrum},
  703:                   {href => "javascript:backPage(document.crtuser)",
  704:                    text => $breadcrumb_text{'search'},
  705:                    help => $helpitem,
  706:                    faq  => 282,
  707:                    bug  => 'Instructor Interface',}
  708:                   );
  709:     }
  710:     my %loaditems = (
  711:                 'onload' => "javascript:setFormElements(document.$formtoset)",
  712:                     );
  713:     my $args = {bread_crumbs           => $brcrum,
  714:                 bread_crumbs_component => 'User Management',
  715:                 add_entries            => \%loaditems,};
  716:     $r->print(&Apache::loncommon::start_page('User Management',$jscript,$args));
  717: 
  718:     my %lt=&Apache::lonlocal::texthash(
  719:                     'srst' => 'Search for a user and enroll as a student',
  720:                     'srme' => 'Search for a user and enroll as a member',
  721:                     'srad' => 'Search for a user and modify/add user information or roles',
  722:                     'srvu' => 'Search for a user and view user information and roles',
  723:                     'srva' => 'Search for a user and view access log information',
  724: 		    'usr'  => "Username",
  725:                     'dom'  => "Domain",
  726:                     'ecrp' => "Define or Edit Custom Role",
  727:                     'nr'   => "role name",
  728:                     'cre'  => "Next",
  729: 				       );
  730: 
  731:     if ($env{'form.action'} eq 'custom') {
  732:         if (&Apache::lonnet::allowed('mcr','/')) {
  733:             my $newroletext = &mt('Define new custom role:');
  734:             $r->print('<form action="/adm/createuser" method="post" name="docustom">'.
  735:                       '<input type="hidden" name="action" value="'.$env{'form.action'}.'" />'.
  736:                       '<input type="hidden" name="phase" value="selected_custom_edit" />'.
  737:                       '<h3>'.$lt{'ecrp'}.'</h3>'.
  738:                       &Apache::loncommon::start_data_table().
  739:                       &Apache::loncommon::start_data_table_row().
  740:                       '<td>');
  741:             if (keys(%existingroles) > 0) {
  742:                 $r->print('<br /><label><input type="radio" name="customroleaction" value="new" checked="checked" onclick="setCustomFields();" /><b>'.$newroletext.'</b></label>');
  743:             } else {
  744:                 $r->print('<br /><input type="hidden" name="customroleaction" value="new" /><b>'.$newroletext.'</b>');
  745:             }
  746:             $r->print('</td><td align="center">'.$lt{'nr'}.'<br /><input type="text" size="15" name="newrolename" onfocus="setCustomAction('."'new'".');" /></td>'.
  747:                       &Apache::loncommon::end_data_table_row());
  748:             if (keys(%existingroles) > 0) {
  749:                 $r->print(&Apache::loncommon::start_data_table_row().'<td><br />'.
  750:                           '<label><input type="radio" name="customroleaction" value="edit" onclick="setCustomFields();"/><b>'.
  751:                           &mt('View/Modify existing role:').'</b></label></td>'.
  752:                           '<td align="center"><br />'.
  753:                           '<select name="rolename" onchange="setCustomAction('."'edit'".');">'.
  754:                           '<option value="" selected="selected">'.
  755:                           &mt('Select'));
  756:                 foreach my $role (sort(keys(%existingroles))) {
  757:                     $r->print('<option value="'.$role.'">'.$role.'</option>');
  758:                 }
  759:                 $r->print('</select>'.
  760:                           '</td>'.
  761:                           &Apache::loncommon::end_data_table_row());
  762:             }
  763:             $r->print(&Apache::loncommon::end_data_table().'<p>'.
  764:                       '<input name="customeditor" type="submit" value="'.
  765:                       $lt{'cre'}.'" /></p>'.
  766:                       '</form>');
  767:         }
  768:     } else {
  769:         my $actiontext = $lt{'srad'};
  770:         my $fixeddom;
  771:         if ($env{'form.action'} eq 'singlestudent') {
  772:             if ($crstype eq 'Community') {
  773:                 $actiontext = $lt{'srme'};
  774:             } else {
  775:                 $actiontext = $lt{'srst'};
  776:             }
  777:         } elsif ($env{'form.action'} eq 'accesslogs') {
  778:             $actiontext = $lt{'srva'};
  779:             $fixeddom = 1;
  780:         } elsif (($env{'form.action'} eq 'singleuser') &&
  781:                  ($context eq 'domain') && (!&Apache::lonnet::allowed('mau',$defdom))) {
  782:             $actiontext = $lt{'srvu'};
  783:             $fixeddom = 1;
  784:         }
  785:         $r->print("<h3>$actiontext</h3>");
  786:         if ($env{'form.origform'} ne 'crtusername') {
  787:             if ($response) {
  788:                $r->print("\n<div>$response</div>".
  789:                          '<br clear="all" />');
  790:             }
  791:         }
  792:         $r->print(&entry_form($defdom,$srch,$forcenewuser,$context,$response,$crstype,$fixeddom));
  793:     }
  794: }
  795: 
  796: sub customrole_javascript {
  797:     my $js = <<"END";
  798: <script type="text/javascript">
  799: // <![CDATA[
  800: 
  801: function setCustomFields() {
  802:     if (document.docustom.customroleaction.length > 0) {
  803:         for (var i=0; i<document.docustom.customroleaction.length; i++) {
  804:             if (document.docustom.customroleaction[i].checked) {
  805:                 if (document.docustom.customroleaction[i].value == 'new') {
  806:                     document.docustom.rolename.selectedIndex = 0;
  807:                 } else {
  808:                     document.docustom.newrolename.value = '';
  809:                 }
  810:             }
  811:         }
  812:     }
  813:     return;
  814: }
  815: 
  816: function setCustomAction(caller) {
  817:     if (document.docustom.customroleaction.length > 0) {
  818:         for (var i=0; i<document.docustom.customroleaction.length; i++) {
  819:             if (document.docustom.customroleaction[i].value == caller) {
  820:                 document.docustom.customroleaction[i].checked = true;
  821:             }
  822:         }
  823:     }
  824:     setCustomFields();
  825:     return;
  826: }
  827: 
  828: // ]]>
  829: </script>
  830: END
  831:     return $js;
  832: }
  833: 
  834: sub entry_form {
  835:     my ($dom,$srch,$forcenewuser,$context,$responsemsg,$crstype,$fixeddom) = @_;
  836:     my ($usertype,$inexact);
  837:     if (ref($srch) eq 'HASH') {
  838:         if (($srch->{'srchin'} eq 'dom') &&
  839:             ($srch->{'srchby'} eq 'uname') &&
  840:             ($srch->{'srchtype'} eq 'exact') &&
  841:             ($srch->{'srchdomain'} ne '') &&
  842:             ($srch->{'srchterm'} ne '')) {
  843:             my (%curr_rules,%got_rules);
  844:             my ($rules,$ruleorder) =
  845:                 &Apache::lonnet::inst_userrules($srch->{'srchdomain'},'username');
  846:             $usertype = &Apache::lonuserutils::check_usertype($srch->{'srchdomain'},$srch->{'srchterm'},$rules,\%curr_rules,\%got_rules);
  847:         } else {
  848:             $inexact = 1;
  849:         }
  850:     }
  851:     my ($cancreate,$noinstd);
  852:     if ($env{'form.action'} eq 'accesslogs') {
  853:         $noinstd = 1;
  854:     } else {
  855:         $cancreate =
  856:             &Apache::lonuserutils::can_create_user($dom,$context,$usertype);
  857:     }
  858:     my ($userpicker,$cansearch) = 
  859:        &Apache::loncommon::user_picker($dom,$srch,$forcenewuser,
  860:                                        'document.crtuser',$cancreate,$usertype,$context,$fixeddom,$noinstd);
  861:     my $srchbutton = &mt('Search');
  862:     if ($env{'form.action'} eq 'singlestudent') {
  863:         $srchbutton = &mt('Search and Enroll');
  864:     } elsif ($env{'form.action'} eq 'accesslogs') {
  865:         $srchbutton = &mt('Search');
  866:     } elsif ($cancreate && $responsemsg ne '' && $inexact) {
  867:         $srchbutton = &mt('Search or Add New User');
  868:     }
  869:     my $output;
  870:     if ($cansearch) {
  871:         $output = <<"ENDBLOCK";
  872: <form action="/adm/createuser" method="post" name="crtuser">
  873: <input type="hidden" name="action" value="$env{'form.action'}" />
  874: <input type="hidden" name="phase" value="get_user_info" />
  875: $userpicker
  876: <input name="userrole" type="button" value="$srchbutton" onclick="javascript:validateEntry(document.crtuser)" />
  877: </form>
  878: ENDBLOCK
  879:     } else {
  880:         $output = '<p>'.$userpicker.'</p>';
  881:     }
  882:     if (($env{'form.phase'} eq '') && ($env{'form.action'} ne 'accesslogs') &&
  883:         (!(($env{'form.action'} eq 'singleuser') && ($context eq 'domain') &&
  884:         (!&Apache::lonnet::allowed('mau',$env{'request.role.domain'}))))) {
  885:         my $defdom=$env{'request.role.domain'};
  886:         my $domform = &Apache::loncommon::select_dom_form($defdom,'srchdomain');
  887:         my %lt=&Apache::lonlocal::texthash(
  888:                   'enro' => 'Enroll one student',
  889:                   'enrm' => 'Enroll one member',
  890:                   'admo' => 'Add/modify a single user',
  891:                   'crea' => 'create new user if required',
  892:                   'uskn' => "username is known",
  893:                   'crnu' => 'Create a new user',
  894:                   'usr'  => 'Username',
  895:                   'dom'  => 'in domain',
  896:                   'enrl' => 'Enroll',
  897:                   'cram'  => 'Create/Modify user',
  898:         );
  899:         my $sellink=&Apache::loncommon::selectstudent_link('crtusername','srchterm','srchdomain');
  900:         my ($title,$buttontext,$showresponse);
  901:         if ($env{'form.action'} eq 'singlestudent') {
  902:             if ($crstype eq 'Community') {
  903:                 $title = $lt{'enrm'};
  904:             } else {
  905:                 $title = $lt{'enro'};
  906:             }
  907:             $buttontext = $lt{'enrl'};
  908:         } else {
  909:             $title = $lt{'admo'};
  910:             $buttontext = $lt{'cram'};
  911:         }
  912:         if ($cancreate) {
  913:             $title .= ' <span class="LC_cusr_subheading">('.$lt{'crea'}.')</span>';
  914:         } else {
  915:             $title .= ' <span class="LC_cusr_subheading">('.$lt{'uskn'}.')</span>';
  916:         }
  917:         if ($env{'form.origform'} eq 'crtusername') {
  918:             $showresponse = $responsemsg;
  919:         }
  920:         $output .= <<"ENDDOCUMENT";
  921: <br />
  922: <form action="/adm/createuser" method="post" name="crtusername">
  923: <input type="hidden" name="action" value="$env{'form.action'}" />
  924: <input type="hidden" name="phase" value="createnewuser" />
  925: <input type="hidden" name="srchtype" value="exact" />
  926: <input type="hidden" name="srchby" value="uname" />
  927: <input type="hidden" name="srchin" value="dom" />
  928: <input type="hidden" name="forcenewuser" value="1" />
  929: <input type="hidden" name="origform" value="crtusername" />
  930: <h3>$title</h3>
  931: $showresponse
  932: <table>
  933:  <tr>
  934:   <td>$lt{'usr'}:</td>
  935:   <td><input type="text" size="15" name="srchterm" /></td>
  936:   <td>&nbsp;$lt{'dom'}:</td><td>$domform</td>
  937:   <td>&nbsp;$sellink&nbsp;</td>
  938:   <td>&nbsp;<input name="userrole" type="submit" value="$buttontext" /></td>
  939:  </tr>
  940: </table>
  941: </form>
  942: ENDDOCUMENT
  943:     }
  944:     return $output;
  945: }
  946: 
  947: sub user_modification_js {
  948:     my ($pjump_def,$dc_setcourse_code,$nondc_setsection_code,$groupslist)=@_;
  949:     
  950:     return <<END;
  951: <script type="text/javascript" language="Javascript">
  952: // <![CDATA[
  953: 
  954:     $pjump_def
  955:     $dc_setcourse_code
  956: 
  957:     function dateset() {
  958:         eval("document.cu."+document.cu.pres_marker.value+
  959:             ".value=document.cu.pres_value.value");
  960:         modalWindow.close();
  961:     }
  962: 
  963:     $nondc_setsection_code
  964: // ]]>
  965: </script>
  966: END
  967: }
  968: 
  969: # =================================================================== Phase two
  970: sub print_user_selection_page {
  971:     my ($r,$response,$srch,$srch_results,$srcharray,$context,$opener_elements,$crstype,$brcrum) = @_;
  972:     my @fields = ('username','domain','lastname','firstname','permanentemail');
  973:     my $sortby = $env{'form.sortby'};
  974: 
  975:     if (!grep(/^\Q$sortby\E$/,@fields)) {
  976:         $sortby = 'lastname';
  977:     }
  978: 
  979:     my ($jsback,$elements) = &crumb_utilities();
  980: 
  981:     my $jscript = (<<ENDSCRIPT);
  982: <script type="text/javascript">
  983: // <![CDATA[
  984: function pickuser(uname,udom) {
  985:     document.usersrchform.seluname.value=uname;
  986:     document.usersrchform.seludom.value=udom;
  987:     document.usersrchform.phase.value="userpicked";
  988:     document.usersrchform.submit();
  989: }
  990: 
  991: $jsback
  992: // ]]>
  993: </script>
  994: ENDSCRIPT
  995: 
  996:     my %lt=&Apache::lonlocal::texthash(
  997:                                        'usrch'          => "User Search to add/modify roles",
  998:                                        'stusrch'        => "User Search to enroll student",
  999:                                        'memsrch'        => "User Search to enroll member",
 1000:                                        'srcva'          => "Search for a user and view access log information",
 1001:                                        'usrvu'          => "User Search to view user roles",
 1002:                                        'usel'           => "Select a user to add/modify roles",
 1003:                                        'suvr'           => "Select a user to view roles",
 1004:                                        'stusel'         => "Select a user to enroll as a student",
 1005:                                        'memsel'         => "Select a user to enroll as a member",
 1006:                                        'vacsel'         => "Select a user to view access log",
 1007:                                        'username'       => "username",
 1008:                                        'domain'         => "domain",
 1009:                                        'lastname'       => "last name",
 1010:                                        'firstname'      => "first name",
 1011:                                        'permanentemail' => "permanent e-mail",
 1012:                                       );
 1013:     if ($context eq 'requestcrs') {
 1014:         $r->print('<div>');
 1015:     } else {
 1016:         my %breadcrumb_text = &singleuser_breadcrumb($crstype,$context,$srch->{'srchdomain'});
 1017:         my $helpitem;
 1018:         if ($env{'form.action'} eq 'singleuser') {
 1019:             $helpitem = 'Course_Change_Privileges';
 1020:         } elsif ($env{'form.action'} eq 'singlestudent') {
 1021:             $helpitem = 'Course_Add_Student';
 1022:         } elsif ($context eq 'author') {
 1023:             $helpitem = 'Author_Change_Privileges';
 1024:         } elsif ($context eq 'domain') {
 1025:             $helpitem = 'Domain_Change_Privileges';
 1026:         }
 1027:         push (@{$brcrum},
 1028:                   {href => "javascript:backPage(document.usersrchform,'','')",
 1029:                    text => $breadcrumb_text{'search'},
 1030:                    faq  => 282,
 1031:                    bug  => 'Instructor Interface',},
 1032:                   {href => "javascript:backPage(document.usersrchform,'get_user_info','select')",
 1033:                    text => $breadcrumb_text{'userpicked'},
 1034:                    faq  => 282,
 1035:                    bug  => 'Instructor Interface',
 1036:                    help => $helpitem}
 1037:                   );
 1038:         $r->print(&Apache::loncommon::start_page('User Management',$jscript,{bread_crumbs => $brcrum}));
 1039:         if ($env{'form.action'} eq 'singleuser') {
 1040:             my $readonly;
 1041:             if (($context eq 'domain') && (!&Apache::lonnet::allowed('mau',$srch->{'srchdomain'}))) {
 1042:                 $readonly = 1;
 1043:                 $r->print("<b>$lt{'usrvu'}</b><br />");
 1044:             } else {
 1045:                 $r->print("<b>$lt{'usrch'}</b><br />");
 1046:             }
 1047:             $r->print(&entry_form($srch->{'srchdomain'},$srch,undef,$context,undef,$crstype));
 1048:             if ($readonly) {
 1049:                 $r->print('<h3>'.$lt{'suvr'}.'</h3>');
 1050:             } else {
 1051:                 $r->print('<h3>'.$lt{'usel'}.'</h3>');
 1052:             }
 1053:         } elsif ($env{'form.action'} eq 'singlestudent') {
 1054:             $r->print($jscript."<b>");
 1055:             if ($crstype eq 'Community') {
 1056:                 $r->print($lt{'memsrch'});
 1057:             } else {
 1058:                 $r->print($lt{'stusrch'});
 1059:             }
 1060:             $r->print("</b><br />");
 1061:             $r->print(&entry_form($srch->{'srchdomain'},$srch,undef,$context,undef,$crstype));
 1062:             $r->print('</form><h3>');
 1063:             if ($crstype eq 'Community') {
 1064:                 $r->print($lt{'memsel'});
 1065:             } else {
 1066:                 $r->print($lt{'stusel'});
 1067:             }
 1068:             $r->print('</h3>');
 1069:         } elsif ($env{'form.action'} eq 'accesslogs') {
 1070:             $r->print("<b>$lt{'srcva'}</b><br />");
 1071:             $r->print(&entry_form($srch->{'srchdomain'},$srch,undef,$context,undef,undef,1));
 1072:             $r->print('<h3>'.$lt{'vacsel'}.'</h3>');
 1073:         }
 1074:     }
 1075:     $r->print('<form name="usersrchform" method="post" action="">'.
 1076:               &Apache::loncommon::start_data_table()."\n".
 1077:               &Apache::loncommon::start_data_table_header_row()."\n".
 1078:               ' <th> </th>'."\n");
 1079:     foreach my $field (@fields) {
 1080:         $r->print(' <th><a href="javascript:document.usersrchform.sortby.value='.
 1081:                   "'".$field."'".';document.usersrchform.submit();">'.
 1082:                   $lt{$field}.'</a></th>'."\n");
 1083:     }
 1084:     $r->print(&Apache::loncommon::end_data_table_header_row());
 1085: 
 1086:     my @sorted_users = sort {
 1087:         lc($srch_results->{$a}->{$sortby})   cmp lc($srch_results->{$b}->{$sortby})
 1088:             ||
 1089:         lc($srch_results->{$a}->{lastname})  cmp lc($srch_results->{$b}->{lastname})
 1090:             ||
 1091:         lc($srch_results->{$a}->{firstname}) cmp lc($srch_results->{$b}->{firstname})
 1092: 	    ||
 1093: 	lc($a) cmp lc($b)
 1094:         } (keys(%$srch_results));
 1095: 
 1096:     foreach my $user (@sorted_users) {
 1097:         my ($uname,$udom) = split(/:/,$user);
 1098:         my $onclick;
 1099:         if ($context eq 'requestcrs') {
 1100:             $onclick =
 1101:                 'onclick="javascript:gochoose('."'$uname','$udom',".
 1102:                                                "'$srch_results->{$user}->{firstname}',".
 1103:                                                "'$srch_results->{$user}->{lastname}',".
 1104:                                                "'$srch_results->{$user}->{permanentemail}'".');"';
 1105:         } else {
 1106:             $onclick =
 1107:                 ' onclick="javascript:pickuser('."'".$uname."'".','."'".$udom."'".');"';
 1108:         }
 1109:         $r->print(&Apache::loncommon::start_data_table_row().
 1110:                   '<td><input type="button" name="seluser" value="'.&mt('Select').'" '.
 1111:                   $onclick.' /></td>'.
 1112:                   '<td><tt>'.$uname.'</tt></td>'.
 1113:                   '<td><tt>'.$udom.'</tt></td>');
 1114:         foreach my $field ('lastname','firstname','permanentemail') {
 1115:             $r->print('<td>'.$srch_results->{$user}->{$field}.'</td>');
 1116:         }
 1117:         $r->print(&Apache::loncommon::end_data_table_row());
 1118:     }
 1119:     $r->print(&Apache::loncommon::end_data_table().'<br /><br />');
 1120:     if (ref($srcharray) eq 'ARRAY') {
 1121:         foreach my $item (@{$srcharray}) {
 1122:             $r->print('<input type="hidden" name="'.$item.'" value="'.$env{'form.'.$item}.'" />'."\n");
 1123:         }
 1124:     }
 1125:     $r->print(' <input type="hidden" name="sortby" value="'.$sortby.'" />'."\n".
 1126:               ' <input type="hidden" name="seluname" value="" />'."\n".
 1127:               ' <input type="hidden" name="seludom" value="" />'."\n".
 1128:               ' <input type="hidden" name="currstate" value="select" />'."\n".
 1129:               ' <input type="hidden" name="phase" value="get_user_info" />'."\n".
 1130:               ' <input type="hidden" name="action" value="'.$env{'form.action'}.'" />'."\n");
 1131:     if ($context eq 'requestcrs') {
 1132:         $r->print($opener_elements.'</form></div>');
 1133:     } else {
 1134:         $r->print($response.'</form>');
 1135:     }
 1136: }
 1137: 
 1138: sub print_user_query_page {
 1139:     my ($r,$caller,$brcrum) = @_;
 1140: # FIXME - this is for a network-wide name search (similar to catalog search)
 1141: # To use frames with similar behavior to catalog/portfolio search.
 1142: # To be implemented. 
 1143:     return;
 1144: }
 1145: 
 1146: sub print_user_modification_page {
 1147:     my ($r,$ccuname,$ccdomain,$srch,$response,$context,$permission,$crstype,
 1148:         $brcrum,$showcredits) = @_;
 1149:     if (($ccuname eq '') || ($ccdomain eq '')) {
 1150:         my $usermsg = &mt('No username and/or domain provided.');
 1151:         $env{'form.phase'} = '';
 1152: 	&print_username_entry_form($r,$context,$usermsg,'','',$crstype,$brcrum,
 1153:                                    $permission);
 1154:         return;
 1155:     }
 1156:     my ($form,$formname);
 1157:     if ($env{'form.action'} eq 'singlestudent') {
 1158:         $form = 'document.enrollstudent';
 1159:         $formname = 'enrollstudent';
 1160:     } else {
 1161:         $form = 'document.cu';
 1162:         $formname = 'cu';
 1163:     }
 1164:     my %abv_auth = &auth_abbrev();
 1165:     my (%rulematch,%inst_results,$newuser,%alerts,%curr_rules,%got_rules);
 1166:     my $uhome=&Apache::lonnet::homeserver($ccuname,$ccdomain);
 1167:     if ($uhome eq 'no_host') {
 1168:         my $usertype;
 1169:         my ($rules,$ruleorder) =
 1170:             &Apache::lonnet::inst_userrules($ccdomain,'username');
 1171:             $usertype =
 1172:                 &Apache::lonuserutils::check_usertype($ccdomain,$ccuname,$rules,
 1173:                                                       \%curr_rules,\%got_rules);
 1174:         my $cancreate =
 1175:             &Apache::lonuserutils::can_create_user($ccdomain,$context,
 1176:                                                    $usertype);
 1177:         if (!$cancreate) {
 1178:             my $helplink = 'javascript:helpMenu('."'display'".')';
 1179:             my %usertypetext = (
 1180:                 official   => 'institutional',
 1181:                 unofficial => 'non-institutional',
 1182:             );
 1183:             my $response;
 1184:             if ($env{'form.origform'} eq 'crtusername') {
 1185:                 $response = '<span class="LC_warning">'.
 1186:                             &mt('No match found for the username [_1] in LON-CAPA domain: [_2]',
 1187:                                 '<b>'.$ccuname.'</b>',$ccdomain).
 1188:                             '</span><br />';
 1189:             }
 1190:             $response .= '<p class="LC_warning">'
 1191:                         .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
 1192:                         .' ';
 1193:             if ($context eq 'domain') {
 1194:                 $response .= &mt('Please contact a [_1] for assistance.',
 1195:                                  &Apache::lonnet::plaintext('dc'));
 1196:             } else {
 1197:                 $response .= &mt('Please contact the [_1]helpdesk[_2] for assistance.'
 1198:                                 ,'<a href="'.$helplink.'">','</a>');
 1199:             }
 1200:             $response .= '</p><br />';
 1201:             $env{'form.phase'} = '';
 1202:             &print_username_entry_form($r,$context,$response,undef,undef,$crstype,$brcrum,
 1203:                                        $permission);
 1204:             return;
 1205:         }
 1206:         $newuser = 1;
 1207:         my $checkhash;
 1208:         my $checks = { 'username' => 1 };
 1209:         $checkhash->{$ccuname.':'.$ccdomain} = { 'newuser' => $newuser };
 1210:         &Apache::loncommon::user_rule_check($checkhash,$checks,
 1211:             \%alerts,\%rulematch,\%inst_results,\%curr_rules,\%got_rules);
 1212:         if (ref($alerts{'username'}) eq 'HASH') {
 1213:             if (ref($alerts{'username'}{$ccdomain}) eq 'HASH') {
 1214:                 my $domdesc =
 1215:                     &Apache::lonnet::domain($ccdomain,'description');
 1216:                 if ($alerts{'username'}{$ccdomain}{$ccuname}) {
 1217:                     my $userchkmsg;
 1218:                     if (ref($curr_rules{$ccdomain}) eq 'HASH') {  
 1219:                         $userchkmsg = 
 1220:                             &Apache::loncommon::instrule_disallow_msg('username',
 1221:                                                                  $domdesc,1).
 1222:                         &Apache::loncommon::user_rule_formats($ccdomain,
 1223:                             $domdesc,$curr_rules{$ccdomain}{'username'},
 1224:                             'username');
 1225:                     }
 1226:                     $env{'form.phase'} = '';
 1227:                     &print_username_entry_form($r,$context,$userchkmsg,undef,undef,$crstype,$brcrum,
 1228:                                                $permission);
 1229:                     return;
 1230:                 }
 1231:             }
 1232:         }
 1233:     } else {
 1234:         $newuser = 0;
 1235:     }
 1236:     if ($response) {
 1237:         $response = '<br />'.$response;
 1238:     }
 1239: 
 1240:     my $pjump_def = &Apache::lonhtmlcommon::pjump_javascript_definition();
 1241:     my $dc_setcourse_code = '';
 1242:     my $nondc_setsection_code = '';                                        
 1243:     my %loaditem;
 1244: 
 1245:     my $groupslist = &Apache::lonuserutils::get_groupslist();
 1246: 
 1247:     my $js = &validation_javascript($context,$ccdomain,$pjump_def,$crstype,
 1248:                                $groupslist,$newuser,$formname,\%loaditem);
 1249:     my %breadcrumb_text = &singleuser_breadcrumb($crstype,$context,$ccdomain);
 1250:     my $helpitem = 'Course_Change_Privileges';
 1251:     if ($env{'form.action'} eq 'singlestudent') {
 1252:         $helpitem = 'Course_Add_Student';
 1253:     } elsif ($context eq 'author') {
 1254:         $helpitem = 'Author_Change_Privileges';
 1255:     } elsif ($context eq 'domain') {
 1256:         $helpitem = 'Domain_Change_Privileges';
 1257:     }
 1258:     push (@{$brcrum},
 1259:         {href => "javascript:backPage($form)",
 1260:          text => $breadcrumb_text{'search'},
 1261:          faq  => 282,
 1262:          bug  => 'Instructor Interface',});
 1263:     if ($env{'form.phase'} eq 'userpicked') {
 1264:        push(@{$brcrum},
 1265:               {href => "javascript:backPage($form,'get_user_info','select')",
 1266:                text => $breadcrumb_text{'userpicked'},
 1267:                faq  => 282,
 1268:                bug  => 'Instructor Interface',});
 1269:     }
 1270:     push(@{$brcrum},
 1271:             {href => "javascript:backPage($form,'$env{'form.phase'}','modify')",
 1272:              text => $breadcrumb_text{'modify'},
 1273:              faq  => 282,
 1274:              bug  => 'Instructor Interface',
 1275:              help => $helpitem});
 1276:     my $args = {'add_entries'           => \%loaditem,
 1277:                 'bread_crumbs'          => $brcrum,
 1278:                 'bread_crumbs_component' => 'User Management'};
 1279:     if ($env{'form.popup'}) {
 1280:         $args->{'no_nav_bar'} = 1;
 1281:     }
 1282:     my $start_page =
 1283:         &Apache::loncommon::start_page('User Management',$js,$args);
 1284: 
 1285:     my $forminfo =<<"ENDFORMINFO";
 1286: <form action="/adm/createuser" method="post" name="$formname">
 1287: <input type="hidden" name="phase" value="update_user_data" />
 1288: <input type="hidden" name="ccuname" value="$ccuname" />
 1289: <input type="hidden" name="ccdomain" value="$ccdomain" />
 1290: <input type="hidden" name="pres_value"  value="" />
 1291: <input type="hidden" name="pres_type"   value="" />
 1292: <input type="hidden" name="pres_marker" value="" />
 1293: ENDFORMINFO
 1294:     my (%inccourses,$roledom,$defaultcredits);
 1295:     if ($context eq 'course') {
 1296:         $inccourses{$env{'request.course.id'}}=1;
 1297:         $roledom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 1298:         if ($showcredits) {
 1299:             $defaultcredits = &Apache::lonuserutils::get_defaultcredits();
 1300:         }
 1301:     } elsif ($context eq 'author') {
 1302:         $roledom = $env{'request.role.domain'};
 1303:     } elsif ($context eq 'domain') {
 1304:         foreach my $key (keys(%env)) {
 1305:             $roledom = $env{'request.role.domain'};
 1306:             if ($key=~/^user\.priv\.cm\.\/($roledom)\/($match_username)/) {
 1307:                 $inccourses{$1.'_'.$2}=1;
 1308:             }
 1309:         }
 1310:     } else {
 1311:         foreach my $key (keys(%env)) {
 1312: 	    if ($key=~/^user\.priv\.cm\.\/($match_domain)\/($match_username)/) {
 1313: 	        $inccourses{$1.'_'.$2}=1;
 1314:             }
 1315:         }
 1316:     }
 1317:     my $title = '';
 1318:     if ($newuser) {
 1319:         my ($portfolioform,$domroleform);
 1320:         if ((&Apache::lonnet::allowed('mpq',$env{'request.role.domain'})) ||
 1321:             (&Apache::lonnet::allowed('mut',$env{'request.role.domain'}))) {
 1322:             # Current user has quota or user tools modification privileges
 1323:             $portfolioform = '<br />'.&user_quotas($ccuname,$ccdomain);
 1324:         }
 1325:         if ((&Apache::lonnet::allowed('cau',$env{'request.role.domain'})) &&
 1326:             ($ccdomain eq $env{'request.role.domain'})) {
 1327:             $domroleform = '<br />'.&domainrole_req($ccuname,$ccdomain);
 1328:         }
 1329:         &initialize_authen_forms($ccdomain,$formname);
 1330:         my %lt=&Apache::lonlocal::texthash(
 1331:                 'lg'             => 'Login Data',
 1332:                 'hs'             => "Home Server",
 1333:         );
 1334: 	$r->print(<<ENDTITLE);
 1335: $start_page
 1336: $response
 1337: $forminfo
 1338: <script type="text/javascript" language="Javascript">
 1339: // <![CDATA[
 1340: $loginscript
 1341: // ]]>
 1342: </script>
 1343: <input type='hidden' name='makeuser' value='1' />
 1344: ENDTITLE
 1345:         if ($env{'form.action'} eq 'singlestudent') {
 1346:             if ($crstype eq 'Community') {
 1347:                 $title = &mt('Create New User [_1] in domain [_2] as a member',
 1348:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1349:             } else {
 1350:                 $title = &mt('Create New User [_1] in domain [_2] as a student',
 1351:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1352:             }
 1353:         } else {
 1354:                 $title = &mt('Create New User [_1] in domain [_2]',
 1355:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1356:         }
 1357:         $r->print('<h2>'.$title.'</h2>'."\n");
 1358:         $r->print('<div class="LC_left_float">');
 1359:         $r->print(&personal_data_display($ccuname,$ccdomain,$newuser,$context,
 1360:                                          $inst_results{$ccuname.':'.$ccdomain}));
 1361:         # Option to disable student/employee ID conflict checking not offerred for new users.
 1362:         my ($home_server_pick,$numlib) = 
 1363:             &Apache::loncommon::home_server_form_item($ccdomain,'hserver',
 1364:                                                       'default','hide');
 1365:         if ($numlib > 1) {
 1366:             $r->print("
 1367: <br />
 1368: $lt{'hs'}: $home_server_pick
 1369: <br />");
 1370:         } else {
 1371:             $r->print($home_server_pick);
 1372:         }
 1373:         if (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) {
 1374:             $r->print('<br /><h3>'.
 1375:                       &mt('User Can Request Creation of Courses/Communities in this Domain?').'</h3>'.
 1376:                       &Apache::loncommon::start_data_table().
 1377:                       &build_tools_display($ccuname,$ccdomain,
 1378:                                            'requestcourses').
 1379:                       &Apache::loncommon::end_data_table());
 1380:         }
 1381:         $r->print('</div>'."\n".'<div class="LC_left_float"><h3>'.
 1382:                   $lt{'lg'}.'</h3>');
 1383:         my ($fixedauth,$varauth,$authmsg); 
 1384:         if (ref($rulematch{$ccuname.':'.$ccdomain}) eq 'HASH') {
 1385:             my $matchedrule = $rulematch{$ccuname.':'.$ccdomain}{'username'};
 1386:             my ($rules,$ruleorder) = 
 1387:                 &Apache::lonnet::inst_userrules($ccdomain,'username');
 1388:             if (ref($rules) eq 'HASH') {
 1389:                 if (ref($rules->{$matchedrule}) eq 'HASH') {
 1390:                     my $authtype = $rules->{$matchedrule}{'authtype'};
 1391:                     if ($authtype !~ /^(krb4|krb5|int|fsys|loc)$/) {
 1392:                         $r->print(&Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc));
 1393:                     } else { 
 1394:                         my $authparm = $rules->{$matchedrule}{'authparm'};
 1395:                         $authmsg = $rules->{$matchedrule}{'authmsg'};
 1396:                         if ($authtype =~ /^krb(4|5)$/) {
 1397:                             my $ver = $1;
 1398:                             if ($authparm ne '') {
 1399:                                 $fixedauth = <<"KERB"; 
 1400: <input type="hidden" name="login" value="krb" />
 1401: <input type="hidden" name="krbver" value="$ver" />
 1402: <input type="hidden" name="krbarg" value="$authparm" />
 1403: KERB
 1404:                             }
 1405:                         } else {
 1406:                             $fixedauth = 
 1407: '<input type="hidden" name="login" value="'.$authtype.'" />'."\n";
 1408:                             if ($rules->{$matchedrule}{'authparmfixed'}) {
 1409:                                 $fixedauth .=    
 1410: '<input type="hidden" name="'.$authtype.'arg" value="'.$authparm.'" />'."\n";
 1411:                             } else {
 1412:                                 if ($authtype eq 'int') {
 1413:                                     $varauth = '<br />'.
 1414: &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>';
 1415:                                 } elsif ($authtype eq 'loc') {
 1416:                                     $varauth = '<br />'.
 1417: &mt('[_1] Local Authentication with argument [_2]','','<input type="text" name="'.$authtype.'arg" value="" />')."\n";
 1418:                                 } else {
 1419:                                     $varauth =
 1420: '<input type="text" name="'.$authtype.'arg" value="" />'."\n";
 1421:                                 }
 1422:                             }
 1423:                         }
 1424:                     }
 1425:                 } else {
 1426:                     $r->print(&Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc));
 1427:                 }
 1428:             }
 1429:             if ($authmsg) {
 1430:                 $r->print(<<ENDAUTH);
 1431: $fixedauth
 1432: $authmsg
 1433: $varauth
 1434: ENDAUTH
 1435:             }
 1436:         } else {
 1437:             $r->print(&Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc)); 
 1438:         }
 1439:         $r->print($portfolioform.$domroleform);
 1440:         if ($env{'form.action'} eq 'singlestudent') {
 1441:             $r->print(&date_sections_select($context,$newuser,$formname,
 1442:                                             $permission,$crstype,$ccuname,
 1443:                                             $ccdomain,$showcredits));
 1444:         }
 1445:         $r->print('</div><div class="LC_clear_float_footer"></div>');
 1446:     } else { # user already exists
 1447: 	$r->print($start_page.$forminfo);
 1448:         if ($env{'form.action'} eq 'singlestudent') {
 1449:             if ($crstype eq 'Community') {
 1450:                 $title = &mt('Enroll one member: [_1] in domain [_2]',
 1451:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1452:             } else {
 1453:                 $title = &mt('Enroll one student: [_1] in domain [_2]',
 1454:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1455:             }
 1456:         } else {
 1457:             if ($permission->{'cusr'}) {
 1458:                 $title = &mt('Modify existing user: [_1] in domain [_2]',
 1459:                              '"'.$ccuname.'"','"'.$ccdomain.'"');
 1460:             } else {
 1461:                 $title = &mt('Existing user: [_1] in domain [_2]',
 1462:                              '"'.$ccuname.'"','"'.$ccdomain.'"');
 1463:             }
 1464:         }
 1465:         $r->print('<h2>'.$title.'</h2>'."\n");
 1466:         $r->print('<div class="LC_left_float">');
 1467:         $r->print(&personal_data_display($ccuname,$ccdomain,$newuser,$context,
 1468:                                          $inst_results{$ccuname.':'.$ccdomain}));
 1469:         if ((&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) ||
 1470:             (&Apache::lonnet::allowed('udp',$env{'request.role.domain'}))) {
 1471:             $r->print('<br /><h3>'.&mt('User Can Request Creation of Courses/Communities in this Domain?').'</h3>'.
 1472:                       &Apache::loncommon::start_data_table());
 1473:             if ($env{'request.role.domain'} eq $ccdomain) {
 1474:                 $r->print(&build_tools_display($ccuname,$ccdomain,'requestcourses'));
 1475:             } else {
 1476:                 $r->print(&coursereq_externaluser($ccuname,$ccdomain,
 1477:                                                   $env{'request.role.domain'}));
 1478:             }
 1479:             $r->print(&Apache::loncommon::end_data_table());
 1480:         }
 1481:         $r->print('</div>');
 1482:         my @order = ('auth','quota','tools','requestauthor');
 1483:         my %user_text;
 1484:         my ($isadv,$isauthor) = 
 1485:             &Apache::lonnet::is_advanced_user($ccdomain,$ccuname);
 1486:         if ((!$isauthor) && 
 1487:             ((&Apache::lonnet::allowed('cau',$env{'request.role.domain'})) ||
 1488:              (&Apache::lonnet::allowed('udp',$env{'request.role.domain'}))) &&
 1489:              ($env{'request.role.domain'} eq $ccdomain)) {
 1490:             $user_text{'requestauthor'} = &domainrole_req($ccuname,$ccdomain);
 1491:         }
 1492:         $user_text{'auth'} =  &user_authentication($ccuname,$ccdomain,$formname,$crstype,$permission);
 1493:         if ((&Apache::lonnet::allowed('mpq',$ccdomain)) ||
 1494:             (&Apache::lonnet::allowed('mut',$ccdomain)) ||
 1495:             (&Apache::lonnet::allowed('udp',$ccdomain))) {
 1496:             # Current user has quota modification privileges
 1497:             $user_text{'quota'} = &user_quotas($ccuname,$ccdomain);
 1498:         }
 1499:         if (!&Apache::lonnet::allowed('mpq',$ccdomain)) {
 1500:             if (&Apache::lonnet::allowed('mpq',$env{'request.role.domain'})) {
 1501:                 my %lt=&Apache::lonlocal::texthash(
 1502:                     'dska'  => "Disk quotas for user's portfolio and Authoring Space",
 1503:                     'youd'  => "You do not have privileges to modify the portfolio and/or Authoring Space quotas for this user.",
 1504:                     'ichr'  => "If a change is required, contact a domain coordinator for the domain",
 1505:                 );
 1506:                 $user_text{'quota'} = <<ENDNOPORTPRIV;
 1507: <h3>$lt{'dska'}</h3>
 1508: $lt{'youd'} $lt{'ichr'}: $ccdomain
 1509: ENDNOPORTPRIV
 1510:             }
 1511:         }
 1512:         if (!&Apache::lonnet::allowed('mut',$ccdomain)) {
 1513:             if (&Apache::lonnet::allowed('mut',$env{'request.role.domain'})) {
 1514:                 my %lt=&Apache::lonlocal::texthash(
 1515:                     'utav'  => "User Tools Availability",
 1516:                     'yodo'  => "You do not have privileges to modify Portfolio, Blog, WebDAV, or Personal Information Page settings for this user.",
 1517:                     'ifch'  => "If a change is required, contact a domain coordinator for the domain",
 1518:                 );
 1519:                 $user_text{'tools'} = <<ENDNOTOOLSPRIV;
 1520: <h3>$lt{'utav'}</h3>
 1521: $lt{'yodo'} $lt{'ifch'}: $ccdomain
 1522: ENDNOTOOLSPRIV
 1523:             }
 1524:         }
 1525:         my $gotdiv = 0; 
 1526:         foreach my $item (@order) {
 1527:             if ($user_text{$item} ne '') {
 1528:                 unless ($gotdiv) {
 1529:                     $r->print('<div class="LC_left_float">');
 1530:                     $gotdiv = 1;
 1531:                 }
 1532:                 $r->print('<br />'.$user_text{$item});
 1533:             }
 1534:         }
 1535:         if ($env{'form.action'} eq 'singlestudent') {
 1536:             unless ($gotdiv) {
 1537:                 $r->print('<div class="LC_left_float">');
 1538:             }
 1539:             my $credits;
 1540:             if ($showcredits) {
 1541:                 $credits = &get_user_credits($ccuname,$ccdomain,$defaultcredits);
 1542:                 if ($credits eq '') {
 1543:                     $credits = $defaultcredits;
 1544:                 }
 1545:             }
 1546:             $r->print(&date_sections_select($context,$newuser,$formname,
 1547:                                             $permission,$crstype,$ccuname,
 1548:                                             $ccdomain,$showcredits));
 1549:         }
 1550:         if ($gotdiv) {
 1551:             $r->print('</div><div class="LC_clear_float_footer"></div>');
 1552:         }
 1553:         my $statuses;
 1554:         if (($context eq 'domain') && (&Apache::lonnet::allowed('udp',$ccdomain)) &&
 1555:             (!&Apache::lonnet::allowed('mau',$ccdomain))) {
 1556:             $statuses = ['active'];
 1557:         } elsif (($context eq 'course') && ((&Apache::lonnet::allowed('vcl',$env{'request.course.id'})) ||
 1558:                  ($env{'request.course.sec'} &&
 1559:                   &Apache::lonnet::allowed('vcl',$env{'request.course.id'}.'/'.$env{'request.course.sec'})))) {
 1560:             $statuses = ['active'];
 1561:         }
 1562:         if ($env{'form.action'} ne 'singlestudent') {
 1563:             &display_existing_roles($r,$ccuname,$ccdomain,\%inccourses,$context,
 1564:                                     $roledom,$crstype,$showcredits,$statuses);
 1565:         }
 1566:     } ## End of new user/old user logic
 1567:     if ($env{'form.action'} eq 'singlestudent') {
 1568:         my $btntxt;
 1569:         if ($crstype eq 'Community') {
 1570:             $btntxt = &mt('Enroll Member');
 1571:         } else {
 1572:             $btntxt = &mt('Enroll Student');
 1573:         }
 1574:         $r->print('<br /><input type="button" value="'.$btntxt.'" onclick="setSections(this.form)" />'."\n");
 1575:     } elsif ($permission->{'cusr'}) {
 1576:         $r->print('<div class="LC_left_float">'.
 1577:                   '<fieldset><legend>'.&mt('Add Roles').'</legend>');
 1578:         my $addrolesdisplay = 0;
 1579:         if ($context eq 'domain' || $context eq 'author') {
 1580:             $addrolesdisplay = &new_coauthor_roles($r,$ccuname,$ccdomain);
 1581:         }
 1582:         if ($context eq 'domain') {
 1583:             my $add_domainroles = &new_domain_roles($r,$ccdomain);
 1584:             if (!$addrolesdisplay) {
 1585:                 $addrolesdisplay = $add_domainroles;
 1586:             }
 1587:             $r->print(&course_level_dc($env{'request.role.domain'},$showcredits));
 1588:             $r->print('</fieldset></div><div class="LC_clear_float_footer"></div>'.
 1589:                       '<br /><input type="button" value="'.&mt('Save').'" onclick="setCourse()" />'."\n");
 1590:         } elsif ($context eq 'author') {
 1591:             if ($addrolesdisplay) {
 1592:                 $r->print('</fieldset></div><div class="LC_clear_float_footer"></div>'.
 1593:                           '<br /><input type="button" value="'.&mt('Save').'"');
 1594:                 if ($newuser) {
 1595:                     $r->print(' onclick="auth_check()" \>'."\n");
 1596:                 } else {
 1597:                     $r->print(' onclick="this.form.submit()" \>'."\n");
 1598:                 }
 1599:             } else {
 1600:                 $r->print('</fieldset></div>'.
 1601:                           '<div class="LC_clear_float_footer"></div>'.
 1602:                           '<br /><a href="javascript:backPage(document.cu)">'.
 1603:                           &mt('Back to previous page').'</a>');
 1604:             }
 1605:         } else {
 1606:             $r->print(&course_level_table(\%inccourses,$showcredits,$defaultcredits));
 1607:             $r->print('</fieldset></div><div class="LC_clear_float_footer"></div>'.
 1608:                       '<br /><input type="button" value="'.&mt('Save').'" onclick="setSections(this.form)" />'."\n");
 1609:         }
 1610:     }
 1611:     $r->print(&Apache::lonhtmlcommon::echo_form_input(['phase','userrole','ccdomain','prevphase','currstate','ccuname','ccdomain']));
 1612:     $r->print('<input type="hidden" name="currstate" value="" />');
 1613:     $r->print('<input type="hidden" name="prevphase" value="'.$env{'form.phase'}.'" /></form><br /><br />');
 1614:     return;
 1615: }
 1616: 
 1617: sub singleuser_breadcrumb {
 1618:     my ($crstype,$context,$domain) = @_;
 1619:     my %breadcrumb_text;
 1620:     if ($env{'form.action'} eq 'singlestudent') {
 1621:         if ($crstype eq 'Community') {
 1622:             $breadcrumb_text{'search'} = 'Enroll a member';
 1623:         } else {
 1624:             $breadcrumb_text{'search'} = 'Enroll a student';
 1625:         }
 1626:         $breadcrumb_text{'userpicked'} = 'Select a user';
 1627:         $breadcrumb_text{'modify'} = 'Set section/dates';
 1628:     } elsif ($env{'form.action'} eq 'accesslogs') {
 1629:         $breadcrumb_text{'search'} = 'View access logs for a user';
 1630:         $breadcrumb_text{'userpicked'} = 'Select a user';
 1631:         $breadcrumb_text{'activity'} = 'Activity';
 1632:     } elsif (($env{'form.action'} eq 'singleuser') && ($context eq 'domain') &&
 1633:              (!&Apache::lonnet::allowed('mau',$domain))) {
 1634:         $breadcrumb_text{'search'} = "View user's roles";
 1635:         $breadcrumb_text{'userpicked'} = 'Select a user';
 1636:         $breadcrumb_text{'modify'} = 'User roles';
 1637:     } else {
 1638:         $breadcrumb_text{'search'} = 'Create/modify a user';
 1639:         $breadcrumb_text{'userpicked'} = 'Select a user';
 1640:         $breadcrumb_text{'modify'} = 'Set user role';
 1641:     }
 1642:     return %breadcrumb_text;
 1643: }
 1644: 
 1645: sub date_sections_select {
 1646:     my ($context,$newuser,$formname,$permission,$crstype,$ccuname,$ccdomain,
 1647:         $showcredits) = @_;
 1648:     my $credits;
 1649:     if ($showcredits) {
 1650:         my $defaultcredits = &Apache::lonuserutils::get_defaultcredits();
 1651:         $credits = &get_user_credits($ccuname,$ccdomain,$defaultcredits);
 1652:         if ($credits eq '') {
 1653:             $credits = $defaultcredits;
 1654:         }
 1655:     }
 1656:     my $cid = $env{'request.course.id'};
 1657:     my ($cnum,$cdom) = &Apache::lonuserutils::get_course_identity($cid);
 1658:     my $date_table = '<h3>'.&mt('Starting and Ending Dates').'</h3>'."\n".
 1659:         &Apache::lonuserutils::date_setting_table(undef,undef,$context,
 1660:                                                   undef,$formname,$permission);
 1661:     my $rowtitle = 'Section';
 1662:     my $secbox = '<h3>'.&mt('Section and Credits').'</h3>'."\n".
 1663:         &Apache::lonuserutils::section_picker($cdom,$cnum,'st',$rowtitle,
 1664:                                               $permission,$context,'',$crstype,
 1665:                                               $showcredits,$credits);
 1666:     my $output = $date_table.$secbox;
 1667:     return $output;
 1668: }
 1669: 
 1670: sub validation_javascript {
 1671:     my ($context,$ccdomain,$pjump_def,$crstype,$groupslist,$newuser,$formname,
 1672:         $loaditem) = @_;
 1673:     my $dc_setcourse_code = '';
 1674:     my $nondc_setsection_code = '';
 1675:     if ($context eq 'domain') {
 1676:         my $dcdom = $env{'request.role.domain'};
 1677:         $loaditem->{'onload'} = "document.cu.coursedesc.value='';";
 1678:         $dc_setcourse_code = 
 1679:             &Apache::lonuserutils::dc_setcourse_js('cu','singleuser',$context);
 1680:     } else {
 1681:         my $checkauth; 
 1682:         if (($newuser) || (&Apache::lonnet::allowed('mau',$ccdomain))) {
 1683:             $checkauth = 1;
 1684:         }
 1685:         if ($context eq 'course') {
 1686:             $nondc_setsection_code =
 1687:                 &Apache::lonuserutils::setsections_javascript($formname,$groupslist,
 1688:                                                               undef,$checkauth,
 1689:                                                               $crstype);
 1690:         }
 1691:         if ($checkauth) {
 1692:             $nondc_setsection_code .= 
 1693:                 &Apache::lonuserutils::verify_authen($formname,$context);
 1694:         }
 1695:     }
 1696:     my $js = &user_modification_js($pjump_def,$dc_setcourse_code,
 1697:                                    $nondc_setsection_code,$groupslist);
 1698:     my ($jsback,$elements) = &crumb_utilities();
 1699:     $js .= "\n".
 1700:            '<script type="text/javascript">'."\n".
 1701:            '// <![CDATA['."\n".
 1702:            $jsback."\n".
 1703:            '// ]]>'."\n".
 1704:            '</script>'."\n";
 1705:     return $js;
 1706: }
 1707: 
 1708: sub display_existing_roles {
 1709:     my ($r,$ccuname,$ccdomain,$inccourses,$context,$roledom,$crstype,
 1710:         $showcredits,$statuses) = @_;
 1711:     my $now=time;
 1712:     my $showall = 1;
 1713:     my ($showexpired,$showactive);
 1714:     if ((ref($statuses) eq 'ARRAY') && (@{$statuses} > 0)) {
 1715:         $showall = 0;
 1716:         if (grep(/^expired$/,@{$statuses})) {
 1717:             $showexpired = 1;
 1718:         }
 1719:         if (grep(/^active$/,@{$statuses})) {
 1720:             $showactive = 1;
 1721:         }
 1722:         if ($showexpired && $showactive) {
 1723:             $showall = 1;
 1724:         }
 1725:     }
 1726:     my %lt=&Apache::lonlocal::texthash(
 1727:                     'rer'  => "Existing Roles",
 1728:                     'rev'  => "Revoke",
 1729:                     'del'  => "Delete",
 1730:                     'ren'  => "Re-Enable",
 1731:                     'rol'  => "Role",
 1732:                     'ext'  => "Extent",
 1733:                     'crd'  => "Credits",
 1734:                     'sta'  => "Start",
 1735:                     'end'  => "End",
 1736:                                        );
 1737:     my (%rolesdump,%roletext,%sortrole,%roleclass,%rolepriv);
 1738:     if ($context eq 'course' || $context eq 'author') {
 1739:         my @roles = &Apache::lonuserutils::roles_by_context($context,1,$crstype);
 1740:         my %roleshash = 
 1741:             &Apache::lonnet::get_my_roles($ccuname,$ccdomain,'userroles',
 1742:                               ['active','previous','future'],\@roles,$roledom,1);
 1743:         foreach my $key (keys(%roleshash)) {
 1744:             my ($start,$end) = split(':',$roleshash{$key});
 1745:             next if ($start eq '-1' || $end eq '-1');
 1746:             my ($rnum,$rdom,$role,$sec) = split(':',$key);
 1747:             if ($context eq 'course') {
 1748:                 next unless (($rnum eq $env{'course.'.$env{'request.course.id'}.'.num'})
 1749:                              && ($rdom eq $env{'course.'.$env{'request.course.id'}.'.domain'}));
 1750:             } elsif ($context eq 'author') {
 1751:                 next unless (($rnum eq $env{'user.name'}) && ($rdom eq $env{'request.role.domain'}));
 1752:             }
 1753:             my ($newkey,$newvalue,$newrole);
 1754:             $newkey = '/'.$rdom.'/'.$rnum;
 1755:             if ($sec ne '') {
 1756:                 $newkey .= '/'.$sec;
 1757:             }
 1758:             $newvalue = $role;
 1759:             if ($role =~ /^cr/) {
 1760:                 $newrole = 'cr';
 1761:             } else {
 1762:                 $newrole = $role;
 1763:             }
 1764:             $newkey .= '_'.$newrole;
 1765:             if ($start ne '' && $end ne '') {
 1766:                 $newvalue .= '_'.$end.'_'.$start;
 1767:             } elsif ($end ne '') {
 1768:                 $newvalue .= '_'.$end;
 1769:             }
 1770:             $rolesdump{$newkey} = $newvalue;
 1771:         }
 1772:     } else {
 1773:         %rolesdump=&Apache::lonnet::dump('roles',$ccdomain,$ccuname);
 1774:     }
 1775:     # Build up table of user roles to allow revocation and re-enabling of roles.
 1776:     my ($tmp) = keys(%rolesdump);
 1777:     return if ($tmp =~ /^(con_lost|error)/i);
 1778:     foreach my $area (sort { my $a1=join('_',(split('_',$a))[1,0]);
 1779:                                 my $b1=join('_',(split('_',$b))[1,0]);
 1780:                                 return $a1 cmp $b1;
 1781:                             } keys(%rolesdump)) {
 1782:         next if ($area =~ /^rolesdef/);
 1783:         my $envkey=$area;
 1784:         my $role = $rolesdump{$area};
 1785:         my $thisrole=$area;
 1786:         $area =~ s/\_\w\w$//;
 1787:         my ($role_code,$role_end_time,$role_start_time) =
 1788:             split(/_/,$role);
 1789:         my $active=1;
 1790:         $active=0 if (($role_end_time) && ($now>$role_end_time));
 1791:         if ($active) {
 1792:             next unless($showall || $showactive);
 1793:         } else {
 1794:             next unless($showall || $showexpired);
 1795:         }
 1796: # Is this a custom role? Get role owner and title.
 1797:         my ($croleudom,$croleuname,$croletitle)=
 1798:             ($role_code=~m{^cr/($match_domain)/($match_username)/(\w+)$});
 1799:         my $allowed=0;
 1800:         my $delallowed=0;
 1801:         my $sortkey=$role_code;
 1802:         my $class='Unknown';
 1803:         my $credits='';
 1804:         my $csec;
 1805:         if ($area =~ m{^/($match_domain)/($match_courseid)}) {
 1806:             $class='Course';
 1807:             my ($coursedom,$coursedir) = ($1,$2);
 1808:             my $cid = $1.'_'.$2;
 1809:             # $1.'_'.$2 is the course id (eg. 103_12345abcef103l3).
 1810:             next if ($envkey =~ m{^/$match_domain/$match_courseid/[A-Za-z0-9]+_gr$});
 1811:             my %coursedata=
 1812:                 &Apache::lonnet::coursedescription($cid);
 1813:             if ($coursedir =~ /^$match_community$/) {
 1814:                 $class='Community';
 1815:             }
 1816:             $sortkey.="\0$coursedom";
 1817:             my $carea;
 1818:             if (defined($coursedata{'description'})) {
 1819:                 $carea=$coursedata{'description'}.
 1820:                     '<br />'.&mt('Domain').': '.$coursedom.('&nbsp;'x8).
 1821:     &Apache::loncommon::syllabuswrapper(&mt('Syllabus'),$coursedir,$coursedom);
 1822:                 $sortkey.="\0".$coursedata{'description'};
 1823:             } else {
 1824:                 if ($class eq 'Community') {
 1825:                     $carea=&mt('Unavailable community').': '.$area;
 1826:                     $sortkey.="\0".&mt('Unavailable community').': '.$area;
 1827:                 } else {
 1828:                     $carea=&mt('Unavailable course').': '.$area;
 1829:                     $sortkey.="\0".&mt('Unavailable course').': '.$area;
 1830:                 }
 1831:             }
 1832:             $sortkey.="\0$coursedir";
 1833:             $inccourses->{$cid}=1;
 1834:             if (($showcredits) && ($class eq 'Course') && ($role_code eq 'st')) {
 1835:                 my $defaultcredits = $coursedata{'internal.defaultcredits'};
 1836:                 $credits =
 1837:                     &get_user_credits($ccuname,$ccdomain,$defaultcredits,
 1838:                                       $coursedom,$coursedir);
 1839:                 if ($credits eq '') {
 1840:                     $credits = $defaultcredits;
 1841:                 }
 1842:             }
 1843:             if ((&Apache::lonnet::allowed('c'.$role_code,$coursedom.'/'.$coursedir)) ||
 1844:                 (&Apache::lonnet::allowed('c'.$role_code,$ccdomain))) {
 1845:                 $allowed=1;
 1846:             }
 1847:             unless ($allowed) {
 1848:                 my $isowner = &Apache::lonuserutils::is_courseowner($cid,$coursedata{'internal.courseowner'});
 1849:                 if ($isowner) {
 1850:                     if (($role_code eq 'co') && ($class eq 'Community')) {
 1851:                         $allowed = 1;
 1852:                     } elsif (($role_code eq 'cc') && ($class eq 'Course')) {
 1853:                         $allowed = 1;
 1854:                     }
 1855:                 }
 1856:             } 
 1857:             if ((&Apache::lonnet::allowed('dro',$coursedom)) ||
 1858:                 (&Apache::lonnet::allowed('dro',$ccdomain))) {
 1859:                 $delallowed=1;
 1860:             }
 1861: # - custom role. Needs more info, too
 1862:             if ($croletitle) {
 1863:                 if (&Apache::lonnet::allowed('ccr',$coursedom.'/'.$coursedir)) {
 1864:                     $allowed=1;
 1865:                     $thisrole.='.'.$role_code;
 1866:                 }
 1867:             }
 1868:             if ($area=~m{^/($match_domain/$match_courseid/(\w+))}) {
 1869:                 $csec = $2;
 1870:                 $carea.='<br />'.&mt('Section: [_1]',$csec);
 1871:                 $sortkey.="\0$csec";
 1872:                 if (!$allowed) {
 1873:                     if ($env{'request.course.sec'} eq $csec) {
 1874:                         if (&Apache::lonnet::allowed('c'.$role_code,$1)) {
 1875:                             $allowed = 1;
 1876:                         }
 1877:                     }
 1878:                 }
 1879:             }
 1880:             $area=$carea;
 1881:         } else {
 1882:             $sortkey.="\0".$area;
 1883:             # Determine if current user is able to revoke privileges
 1884:             if ($area=~m{^/($match_domain)/}) {
 1885:                 if ((&Apache::lonnet::allowed('c'.$role_code,$1)) ||
 1886:                    (&Apache::lonnet::allowed('c'.$role_code,$ccdomain))) {
 1887:                    $allowed=1;
 1888:                 }
 1889:                 if (((&Apache::lonnet::allowed('dro',$1))  ||
 1890:                     (&Apache::lonnet::allowed('dro',$ccdomain))) &&
 1891:                     ($role_code ne 'dc')) {
 1892:                     $delallowed=1;
 1893:                 }
 1894:             } else {
 1895:                 if (&Apache::lonnet::allowed('c'.$role_code,'/')) {
 1896:                     $allowed=1;
 1897:                 }
 1898:             }
 1899:             if ($role_code eq 'ca' || $role_code eq 'au' || $role_code eq 'aa') {
 1900:                 $class='Authoring Space';
 1901:             } elsif ($role_code eq 'su') {
 1902:                 $class='System';
 1903:             } else {
 1904:                 $class='Domain';
 1905:             }
 1906:         }
 1907:         if (($role_code eq 'ca') || ($role_code eq 'aa')) {
 1908:             $area=~m{/($match_domain)/($match_username)};
 1909:             if (&Apache::lonuserutils::authorpriv($2,$1)) {
 1910:                 $allowed=1;
 1911:             } else {
 1912:                 $allowed=0;
 1913:             }
 1914:         }
 1915:         my $row = '';
 1916:         if ($showall) {
 1917:             $row.= '<td>';
 1918:             if (($active) && ($allowed)) {
 1919:                 $row.= '<input type="checkbox" name="rev:'.$thisrole.'" />';
 1920:             } else {
 1921:                 if ($active) {
 1922:                     $row.='&nbsp;';
 1923:                 } else {
 1924:                     $row.=&mt('expired or revoked');
 1925:                 }
 1926:             }
 1927:             $row.='</td><td>';
 1928:             if ($allowed && !$active) {
 1929:                 $row.= '<input type="checkbox" name="ren:'.$thisrole.'" />';
 1930:             } else {
 1931:                 $row.='&nbsp;';
 1932:             }
 1933:             $row.='</td><td>';
 1934:             if ($delallowed) {
 1935:                 $row.= '<input type="checkbox" name="del:'.$thisrole.'" />';
 1936:             } else {
 1937:                 $row.='&nbsp;';
 1938:             }
 1939:             $row.= '</td>';
 1940:         }
 1941:         my $plaintext='';
 1942:         if (!$croletitle) {
 1943:             $plaintext=&Apache::lonnet::plaintext($role_code,$class);
 1944:             if (($showcredits) && ($credits ne '')) {
 1945:                 $plaintext .= '<br/ ><span class="LC_nobreak">'.
 1946:                               '<span class="LC_fontsize_small">'.
 1947:                               &mt('Credits: [_1]',$credits).
 1948:                               '</span></span>';
 1949:             }
 1950:         } else {
 1951:             $plaintext=
 1952:                 &mt('Custom role [_1][_2]defined by [_3]',
 1953:                         '"'.$croletitle.'"',
 1954:                         '<br />',
 1955:                         $croleuname.':'.$croleudom);
 1956:         }
 1957:         $row.= '<td>'.$plaintext.'</td>'.
 1958:                '<td>'.$area.'</td>'.
 1959:                '<td>'.($role_start_time?&Apache::lonlocal::locallocaltime($role_start_time)
 1960:                                             : '&nbsp;' ).'</td>'.
 1961:                '<td>'.($role_end_time  ?&Apache::lonlocal::locallocaltime($role_end_time)
 1962:                                             : '&nbsp;' ).'</td>';
 1963:         $sortrole{$sortkey}=$envkey;
 1964:         $roletext{$envkey}=$row;
 1965:         $roleclass{$envkey}=$class;
 1966:         if ($allowed) {
 1967:             $rolepriv{$envkey}='edit';
 1968:         } else {
 1969:             if ($context eq 'domain') {
 1970:                 if ((&Apache::lonnet::allowed('vur',$ccdomain)) &&
 1971:                     ($envkey=~m{^/$ccdomain/})) {
 1972:                     $rolepriv{$envkey}='view';
 1973:                 }
 1974:             } elsif ($context eq 'course') {
 1975:                 if ((&Apache::lonnet::allowed('vcl',$env{'request.course.id'})) ||
 1976:                     ($env{'request.course.sec'} && ($env{'request.course.sec'} eq $csec) &&
 1977:                      &Apache::lonnet::allowed('vcl',$env{'request.course.id'}.'/'.$env{'request.course.sec'}))) {
 1978:                     $rolepriv{$envkey}='view';
 1979:                 }
 1980:             }
 1981:         }
 1982:     } # end of foreach        (table building loop)
 1983: 
 1984:     my $rolesdisplay = 0;
 1985:     my %output = ();
 1986:     foreach my $type ('Authoring Space','Course','Community','Domain','System','Unknown') {
 1987:         $output{$type} = '';
 1988:         foreach my $which (sort {uc($a) cmp uc($b)} (keys(%sortrole))) {
 1989:             if ( ($roleclass{$sortrole{$which}} =~ /^\Q$type\E/ ) && ($rolepriv{$sortrole{$which}}) ) {
 1990:                  $output{$type}.=
 1991:                       &Apache::loncommon::start_data_table_row().
 1992:                       $roletext{$sortrole{$which}}.
 1993:                       &Apache::loncommon::end_data_table_row();
 1994:             }
 1995:         }
 1996:         unless($output{$type} eq '') {
 1997:             $output{$type} = '<tr class="LC_info_row">'.
 1998:                       "<td align='center' colspan='7'>".&mt($type)."</td></tr>".
 1999:                       $output{$type};
 2000:             $rolesdisplay = 1;
 2001:         }
 2002:     }
 2003:     if ($rolesdisplay == 1) {
 2004:         my $contextrole='';
 2005:         if ($env{'request.course.id'}) {
 2006:             if (&Apache::loncommon::course_type() eq 'Community') {
 2007:                 $contextrole = &mt('Existing Roles in this Community');
 2008:             } else {
 2009:                 $contextrole = &mt('Existing Roles in this Course');
 2010:             }
 2011:         } elsif ($env{'request.role'} =~ /^au\./) {
 2012:             $contextrole = &mt('Existing Co-Author Roles in your Authoring Space');
 2013:         } else {
 2014:             if ($showall) {
 2015:                 $contextrole = &mt('Existing Roles in this Domain');
 2016:             } elsif ($showactive) {
 2017:                 $contextrole = &mt('Unexpired Roles in this Domain');
 2018:             } elsif ($showexpired) {
 2019:                 $contextrole = &mt('Expired or Revoked Roles in this Domain');
 2020:             }
 2021:         }
 2022:         $r->print('<div class="LC_left_float">'.
 2023: '<fieldset><legend>'.$contextrole.'</legend>'.
 2024: &Apache::loncommon::start_data_table("LC_createuser").
 2025: &Apache::loncommon::start_data_table_header_row());
 2026:         if ($showall) {
 2027:             $r->print(
 2028: '<th>'.$lt{'rev'}.'</th><th>'.$lt{'ren'}.'</th><th>'.$lt{'del'}.'</th>'
 2029:             );
 2030:         } elsif ($showexpired) {
 2031:             $r->print('<th>'.$lt{'rev'}.'</th>');
 2032:         }
 2033:         $r->print(
 2034: '<th>'.$lt{'rol'}.'</th><th>'.$lt{'ext'}.'</th>'.
 2035: '<th>'.$lt{'sta'}.'</th><th>'.$lt{'end'}.'</th>'.
 2036: &Apache::loncommon::end_data_table_header_row());
 2037:         foreach my $type ('Authoring Space','Course','Community','Domain','System','Unknown') {
 2038:             if ($output{$type}) {
 2039:                 $r->print($output{$type}."\n");
 2040:             }
 2041:         }
 2042:         $r->print(&Apache::loncommon::end_data_table().
 2043:                   '</fieldset></div>');
 2044:     }
 2045:     return;
 2046: }
 2047: 
 2048: sub new_coauthor_roles {
 2049:     my ($r,$ccuname,$ccdomain) = @_;
 2050:     my $addrolesdisplay = 0;
 2051:     #
 2052:     # Co-Author
 2053:     #
 2054:     if (&Apache::lonuserutils::authorpriv($env{'user.name'},
 2055:                                           $env{'request.role.domain'}) &&
 2056:         ($env{'user.name'} ne $ccuname || $env{'user.domain'} ne $ccdomain)) {
 2057:         # No sense in assigning co-author role to yourself
 2058:         $addrolesdisplay = 1;
 2059:         my $cuname=$env{'user.name'};
 2060:         my $cudom=$env{'request.role.domain'};
 2061:         my %lt=&Apache::lonlocal::texthash(
 2062:                     'cs'   => "Authoring Space",
 2063:                     'act'  => "Activate",
 2064:                     'rol'  => "Role",
 2065:                     'ext'  => "Extent",
 2066:                     'sta'  => "Start",
 2067:                     'end'  => "End",
 2068:                     'cau'  => "Co-Author",
 2069:                     'caa'  => "Assistant Co-Author",
 2070:                     'ssd'  => "Set Start Date",
 2071:                     'sed'  => "Set End Date"
 2072:                                        );
 2073:         $r->print('<h4>'.$lt{'cs'}.'</h4>'."\n".
 2074:                   &Apache::loncommon::start_data_table()."\n".
 2075:                   &Apache::loncommon::start_data_table_header_row()."\n".
 2076:                   '<th>'.$lt{'act'}.'</th><th>'.$lt{'rol'}.'</th>'.
 2077:                   '<th>'.$lt{'ext'}.'</th><th>'.$lt{'sta'}.'</th>'.
 2078:                   '<th>'.$lt{'end'}.'</th>'."\n".
 2079:                   &Apache::loncommon::end_data_table_header_row()."\n".
 2080:                   &Apache::loncommon::start_data_table_row().'
 2081:            <td>
 2082:             <input type="checkbox" name="act_'.$cudom.'_'.$cuname.'_ca" />
 2083:            </td>
 2084:            <td>'.$lt{'cau'}.'</td>
 2085:            <td>'.$cudom.'_'.$cuname.'</td>
 2086:            <td><input type="hidden" name="start_'.$cudom.'_'.$cuname.'_ca" value="" />
 2087:              <a href=
 2088: "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>
 2089: <td><input type="hidden" name="end_'.$cudom.'_'.$cuname.'_ca" value="" />
 2090: <a href=
 2091: "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".
 2092:               &Apache::loncommon::end_data_table_row()."\n".
 2093:               &Apache::loncommon::start_data_table_row()."\n".
 2094: '<td><input type="checkbox" name="act_'.$cudom.'_'.$cuname.'_aa" /></td>
 2095: <td>'.$lt{'caa'}.'</td>
 2096: <td>'.$cudom.'_'.$cuname.'</td>
 2097: <td><input type="hidden" name="start_'.$cudom.'_'.$cuname.'_aa" value="" />
 2098: <a href=
 2099: "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>
 2100: <td><input type="hidden" name="end_'.$cudom.'_'.$cuname.'_aa" value="" />
 2101: <a href=
 2102: "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".
 2103:              &Apache::loncommon::end_data_table_row()."\n".
 2104:              &Apache::loncommon::end_data_table());
 2105:     } elsif ($env{'request.role'} =~ /^au\./) {
 2106:         if (!(&Apache::lonuserutils::authorpriv($env{'user.name'},
 2107:                                                 $env{'request.role.domain'}))) {
 2108:             $r->print('<span class="LC_error">'.
 2109:                       &mt('You do not have privileges to assign co-author roles.').
 2110:                       '</span>');
 2111:         } elsif (($env{'user.name'} eq $ccuname) &&
 2112:              ($env{'user.domain'} eq $ccdomain)) {
 2113:             $r->print(&mt('Assigning yourself a co-author or assistant co-author role in your own author area in Authoring Space is not permitted'));
 2114:         }
 2115:     }
 2116:     return $addrolesdisplay;;
 2117: }
 2118: 
 2119: sub new_domain_roles {
 2120:     my ($r,$ccdomain) = @_;
 2121:     my $addrolesdisplay = 0;
 2122:     #
 2123:     # Domain level
 2124:     #
 2125:     my $num_domain_level = 0;
 2126:     my $domaintext =
 2127:     '<h4>'.&mt('Domain Level').'</h4>'.
 2128:     &Apache::loncommon::start_data_table().
 2129:     &Apache::loncommon::start_data_table_header_row().
 2130:     '<th>'.&mt('Activate').'</th><th>'.&mt('Role').'</th><th>'.
 2131:     &mt('Extent').'</th>'.
 2132:     '<th>'.&mt('Start').'</th><th>'.&mt('End').'</th>'.
 2133:     &Apache::loncommon::end_data_table_header_row();
 2134:     my @allroles = &Apache::lonuserutils::roles_by_context('domain');
 2135:     foreach my $thisdomain (sort(&Apache::lonnet::all_domains())) {
 2136:         foreach my $role (@allroles) {
 2137:             next if ($role eq 'ad');
 2138:             next if (($role eq 'au') && ($ccdomain ne $thisdomain));
 2139:             if (&Apache::lonnet::allowed('c'.$role,$thisdomain)) {
 2140:                my $plrole=&Apache::lonnet::plaintext($role);
 2141:                my %lt=&Apache::lonlocal::texthash(
 2142:                     'ssd'  => "Set Start Date",
 2143:                     'sed'  => "Set End Date"
 2144:                                        );
 2145:                $num_domain_level ++;
 2146:                $domaintext .=
 2147: &Apache::loncommon::start_data_table_row().
 2148: '<td><input type="checkbox" name="act_'.$thisdomain.'_'.$role.'" /></td>
 2149: <td>'.$plrole.'</td>
 2150: <td>'.$thisdomain.'</td>
 2151: <td><input type="hidden" name="start_'.$thisdomain.'_'.$role.'" value="" />
 2152: <a href=
 2153: "javascript:pjump('."'date_start','Start Date $plrole',document.cu.start_$thisdomain\_$role.value,'start_$thisdomain\_$role','cu.pres','dateset'".')">'.$lt{'ssd'}.'</a></td>
 2154: <td><input type="hidden" name="end_'.$thisdomain.'_'.$role.'" value="" />
 2155: <a href=
 2156: "javascript:pjump('."'date_end','End Date $plrole',document.cu.end_$thisdomain\_$role.value,'end_$thisdomain\_$role','cu.pres','dateset'".')">'.$lt{'sed'}.'</a></td>'.
 2157: &Apache::loncommon::end_data_table_row();
 2158:             }
 2159:         }
 2160:     }
 2161:     $domaintext.= &Apache::loncommon::end_data_table();
 2162:     if ($num_domain_level > 0) {
 2163:         $r->print($domaintext);
 2164:         $addrolesdisplay = 1;
 2165:     }
 2166:     return $addrolesdisplay;
 2167: }
 2168: 
 2169: sub user_authentication {
 2170:     my ($ccuname,$ccdomain,$formname,$crstype,$permission) = @_;
 2171:     my $currentauth=&Apache::lonnet::queryauthenticate($ccuname,$ccdomain);
 2172:     my $outcome;
 2173:     my %lt=&Apache::lonlocal::texthash(
 2174:                    'err'   => "ERROR",
 2175:                    'uuas'  => "This user has an unrecognized authentication scheme",
 2176:                    'adcs'  => "Please alert a domain coordinator of this situation",
 2177:                    'sldb'  => "Please specify login data below",
 2178:                    'ld'    => "Login Data"
 2179:     );
 2180:     # Check for a bad authentication type
 2181:     if ($currentauth !~ /^(krb4|krb5|unix|internal|localauth):/) {
 2182:         # bad authentication scheme
 2183:         if (&Apache::lonnet::allowed('mau',$ccdomain)) {
 2184:             &initialize_authen_forms($ccdomain,$formname);
 2185: 
 2186:             my $choices = &Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc);
 2187:             $outcome = <<ENDBADAUTH;
 2188: <script type="text/javascript" language="Javascript">
 2189: // <![CDATA[
 2190: $loginscript
 2191: // ]]>
 2192: </script>
 2193: <span class="LC_error">$lt{'err'}:
 2194: $lt{'uuas'} ($currentauth). $lt{'sldb'}.</span>
 2195: <h3>$lt{'ld'}</h3>
 2196: $choices
 2197: ENDBADAUTH
 2198:         } else {
 2199:             # This user is not allowed to modify the user's
 2200:             # authentication scheme, so just notify them of the problem
 2201:             $outcome = <<ENDBADAUTH;
 2202: <span class="LC_error"> $lt{'err'}: 
 2203: $lt{'uuas'} ($currentauth). $lt{'adcs'}.
 2204: </span>
 2205: ENDBADAUTH
 2206:         }
 2207:     } else { # Authentication type is valid
 2208:         &initialize_authen_forms($ccdomain,$formname,$currentauth,'modifyuser');
 2209:         my ($authformcurrent,$can_modify,@authform_others) =
 2210:             &modify_login_block($ccdomain,$currentauth);
 2211:         if (&Apache::lonnet::allowed('mau',$ccdomain)) {
 2212:             # Current user has login modification privileges
 2213:             $outcome =
 2214:                        '<script type="text/javascript" language="Javascript">'."\n".
 2215:                        '// <![CDATA['."\n".
 2216:                        $loginscript."\n".
 2217:                        '// ]]>'."\n".
 2218:                        '</script>'."\n".
 2219:                        '<h3>'.$lt{'ld'}.'</h3>'.
 2220:                        &Apache::loncommon::start_data_table().
 2221:                        &Apache::loncommon::start_data_table_row().
 2222:                        '<td>'.$authformnop;
 2223:             if (($can_modify) && (&Apache::lonnet::allowed('mau',$ccdomain))) {
 2224:                 $outcome .= '</td>'."\n".
 2225:                             &Apache::loncommon::end_data_table_row().
 2226:                             &Apache::loncommon::start_data_table_row().
 2227:                             '<td>'.$authformcurrent.'</td>'.
 2228:                             &Apache::loncommon::end_data_table_row()."\n";
 2229:             } else {
 2230:                 $outcome .= '&nbsp;('.$authformcurrent.')</td>'.
 2231:                             &Apache::loncommon::end_data_table_row()."\n";
 2232:             }
 2233:             if (&Apache::lonnet::allowed('mau',$ccdomain)) {
 2234:                 foreach my $item (@authform_others) { 
 2235:                     $outcome .= &Apache::loncommon::start_data_table_row().
 2236:                                 '<td>'.$item.'</td>'.
 2237:                                 &Apache::loncommon::end_data_table_row()."\n";
 2238:                 }
 2239:             }
 2240:             $outcome .= &Apache::loncommon::end_data_table();
 2241:         } else {
 2242:             if (($currentauth =~ /^internal:/) &&
 2243:                 (&Apache::lonuserutils::can_change_internalpass($ccuname,$ccdomain,$crstype,$permission))) {
 2244:                 $outcome = <<"ENDJS";
 2245: <script type="text/javascript">
 2246: // <![CDATA[
 2247: function togglePwd(form) {
 2248:     if (form.newintpwd.length) {
 2249:         if (document.getElementById('LC_ownersetpwd')) {
 2250:             for (var i=0; i<form.newintpwd.length; i++) {
 2251:                 if (form.newintpwd[i].checked) {
 2252:                     if (form.newintpwd[i].value == 1) {
 2253:                         document.getElementById('LC_ownersetpwd').style.display = 'inline-block';
 2254:                     } else {
 2255:                         document.getElementById('LC_ownersetpwd').style.display = 'none';
 2256:                     }
 2257:                 }
 2258:             }
 2259:         }
 2260:     }
 2261: }
 2262: // ]]>
 2263: </script>
 2264: ENDJS
 2265: 
 2266:                 $outcome .= '<h3>'.$lt{'ld'}.'</h3>'.
 2267:                             &Apache::loncommon::start_data_table().
 2268:                             &Apache::loncommon::start_data_table_row().
 2269:                             '<td>'.&mt('Internally authenticated').'<br />'.&mt("Change user's password?").
 2270:                             '<label><input type="radio" name="newintpwd" value="0" checked="checked" onclick="togglePwd(this.form);" />'.
 2271:                             &mt('No').'</label>'.('&nbsp;'x2).
 2272:                             '<label><input type="radio" name="newintpwd" value="1" onclick="togglePwd(this.form);" />'.&mt('Yes').'</label>'.
 2273:                             '<div id="LC_ownersetpwd" style="display:none">'.
 2274:                             '&nbsp;&nbsp;'.&mt('Password').' <input type="password" size="15" name="intarg" value="" />'.
 2275:                             '<label><input type="checkbox" name="visible" onclick="if (this.checked) { this.form.intarg.type='."'text'".' } else { this.form.intarg.type='."'password'".' }" />'.&mt('Visible input').'</label></div></td>'.
 2276:                             &Apache::loncommon::end_data_table_row().
 2277:                             &Apache::loncommon::end_data_table();
 2278:             }
 2279:             if (&Apache::lonnet::allowed('udp',$ccdomain)) {
 2280:                 # Current user has rights to view domain preferences for user's domain
 2281:                 my $result;
 2282:                 if ($currentauth =~ /^krb(4|5):([^:]*)$/) {
 2283:                     my ($krbver,$krbrealm) = ($1,$2);
 2284:                     if ($krbrealm eq '') {
 2285:                         $result = &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
 2286:                     } else {
 2287:                         $result = &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
 2288:                                       $krbrealm,$krbver);
 2289:                     }
 2290:                 } elsif ($currentauth =~ /^internal:/) {
 2291:                     $result = &mt('Currently internally authenticated.');
 2292:                 } elsif ($currentauth =~ /^localauth:/) {
 2293:                     $result = &mt('Currently using local (institutional) authentication.');
 2294:                 } elsif ($currentauth =~ /^unix:/) {
 2295:                     $result = &mt('Currently Filesystem Authenticated.');
 2296:                 }
 2297:                 $outcome = '<h3>'.$lt{'ld'}.'</h3>'.
 2298:                            &Apache::loncommon::start_data_table().
 2299:                            &Apache::loncommon::start_data_table_row().
 2300:                            '<td>'.$result.'</td>'.
 2301:                            &Apache::loncommon::end_data_table_row()."\n".
 2302:                            &Apache::loncommon::end_data_table();
 2303:             } elsif (&Apache::lonnet::allowed('mau',$env{'request.role.domain'})) {
 2304:                 my %lt=&Apache::lonlocal::texthash(
 2305:                            'ccld'  => "Change Current Login Data",
 2306:                            'yodo'  => "You do not have privileges to modify the authentication configuration for this user.",
 2307:                            'ifch'  => "If a change is required, contact a domain coordinator for the domain",
 2308:                 );
 2309:                 $outcome .= <<ENDNOPRIV;
 2310: <h3>$lt{'ccld'}</h3>
 2311: $lt{'yodo'} $lt{'ifch'}: $ccdomain
 2312: <input type="hidden" name="login" value="nochange" />
 2313: ENDNOPRIV
 2314:             }
 2315:         }
 2316:     }  ## End of "check for bad authentication type" logic
 2317:     return $outcome;
 2318: }
 2319: 
 2320: sub modify_login_block {
 2321:     my ($dom,$currentauth) = @_;
 2322:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 2323:     my ($authnum,%can_assign) =
 2324:         &Apache::loncommon::get_assignable_auth($dom);
 2325:     my ($authformcurrent,@authform_others,$show_override_msg);
 2326:     if ($currentauth=~/^krb(4|5):/) {
 2327:         $authformcurrent=$authformkrb;
 2328:         if ($can_assign{'int'}) {
 2329:             push(@authform_others,$authformint);
 2330:         }
 2331:         if ($can_assign{'loc'}) {
 2332:             push(@authform_others,$authformloc);
 2333:         }
 2334:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2335:             $show_override_msg = 1;
 2336:         }
 2337:     } elsif ($currentauth=~/^internal:/) {
 2338:         $authformcurrent=$authformint;
 2339:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2340:             push(@authform_others,$authformkrb);
 2341:         }
 2342:         if ($can_assign{'loc'}) {
 2343:             push(@authform_others,$authformloc);
 2344:         }
 2345:         if ($can_assign{'int'}) {
 2346:             $show_override_msg = 1;
 2347:         }
 2348:     } elsif ($currentauth=~/^unix:/) {
 2349:         $authformcurrent=$authformfsys;
 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:             push(@authform_others,$authformloc);
 2358:         }
 2359:         if ($can_assign{'fsys'}) {
 2360:             $show_override_msg = 1;
 2361:         }
 2362:     } elsif ($currentauth=~/^localauth:/) {
 2363:         $authformcurrent=$authformloc;
 2364:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2365:             push(@authform_others,$authformkrb);
 2366:         }
 2367:         if ($can_assign{'int'}) {
 2368:             push(@authform_others,$authformint);
 2369:         }
 2370:         if ($can_assign{'loc'}) {
 2371:             $show_override_msg = 1;
 2372:         }
 2373:     }
 2374:     if ($show_override_msg) {
 2375:         $authformcurrent = '<table><tr><td colspan="3">'.$authformcurrent.
 2376:                            '</td></tr>'."\n".
 2377:                            '<tr><td>&nbsp;&nbsp;&nbsp;</td>'.
 2378:                            '<td><b>'.&mt('Currently in use').'</b></td>'.
 2379:                            '<td align="right"><span class="LC_cusr_emph">'.
 2380:                             &mt('will override current values').
 2381:                             '</span></td></tr></table>';
 2382:     }
 2383:     return ($authformcurrent,$show_override_msg,@authform_others); 
 2384: }
 2385: 
 2386: sub personal_data_display {
 2387:     my ($ccuname,$ccdomain,$newuser,$context,$inst_results,$rolesarray,$now,
 2388:         $captchaform,$emailusername,$usertype,$usernameset,$condition,$excluded,$showsubmit) = @_;
 2389:     my ($output,%userenv,%canmodify,%canmodify_status);
 2390:     my @userinfo = ('firstname','middlename','lastname','generation',
 2391:                     'permanentemail','id');
 2392:     my $rowcount = 0;
 2393:     my $editable = 0;
 2394:     my %textboxsize = (
 2395:                        firstname      => '15',
 2396:                        middlename     => '15',
 2397:                        lastname       => '15',
 2398:                        generation     => '5',
 2399:                        permanentemail => '25',
 2400:                        id             => '15',
 2401:                       );
 2402: 
 2403:     my %lt=&Apache::lonlocal::texthash(
 2404:                 'pd'             => "Personal Data",
 2405:                 'firstname'      => "First Name",
 2406:                 'middlename'     => "Middle Name",
 2407:                 'lastname'       => "Last Name",
 2408:                 'generation'     => "Generation",
 2409:                 'permanentemail' => "Permanent e-mail address",
 2410:                 'id'             => "Student/Employee ID",
 2411:                 'lg'             => "Login Data",
 2412:                 'inststatus'     => "Affiliation",
 2413:                 'email'          => 'E-mail address',
 2414:                 'valid'          => 'Validation',
 2415:                 'username'       => 'Username',
 2416:     );
 2417: 
 2418:     %canmodify_status =
 2419:         &Apache::lonuserutils::can_modify_userinfo($context,$ccdomain,
 2420:                                                    ['inststatus'],$rolesarray);
 2421:     if (!$newuser) {
 2422:         # Get the users information
 2423:         %userenv = &Apache::lonnet::get('environment',
 2424:                    ['firstname','middlename','lastname','generation',
 2425:                     'permanentemail','id','inststatus'],$ccdomain,$ccuname);
 2426:         %canmodify =
 2427:             &Apache::lonuserutils::can_modify_userinfo($context,$ccdomain,
 2428:                                                        \@userinfo,$rolesarray);
 2429:     } elsif ($context eq 'selfcreate') {
 2430:         if ($newuser eq 'email') {
 2431:             if (ref($emailusername) eq 'HASH') {
 2432:                 if (ref($emailusername->{$usertype}) eq 'HASH') {
 2433:                     my ($infofields,$infotitles) = &Apache::loncommon::emailusername_info();
 2434:                     @userinfo = ();
 2435:                     if ((ref($infofields) eq 'ARRAY') && (ref($infotitles) eq 'HASH')) {
 2436:                         foreach my $field (@{$infofields}) { 
 2437:                             if ($emailusername->{$usertype}->{$field}) {
 2438:                                 push(@userinfo,$field);
 2439:                                 $canmodify{$field} = 1;
 2440:                                 unless ($textboxsize{$field}) {
 2441:                                     $textboxsize{$field} = 25;
 2442:                                 }
 2443:                                 unless ($lt{$field}) {
 2444:                                     $lt{$field} = $infotitles->{$field};
 2445:                                 }
 2446:                                 if ($emailusername->{$usertype}->{$field} eq 'required') {
 2447:                                     $lt{$field} .= '<b>*</b>';
 2448:                                 }
 2449:                             }
 2450:                         }
 2451:                     }
 2452:                 }
 2453:             }
 2454:         } else {
 2455:             %canmodify = &selfcreate_canmodify($context,$ccdomain,\@userinfo,
 2456:                                                $inst_results,$rolesarray);
 2457:         }
 2458:     }
 2459: 
 2460:     my $genhelp=&Apache::loncommon::help_open_topic('Generation');
 2461:     $output = '<h3>'.$lt{'pd'}.'</h3>'.
 2462:               &Apache::lonhtmlcommon::start_pick_box();
 2463:     if (($context eq 'selfcreate') && ($newuser eq 'email')) {
 2464:         my $size = 25;
 2465:         if ($condition) {
 2466:             if ($condition =~ /^\@[^\@]+$/) {
 2467:                 $size = 10;
 2468:             } else {
 2469:                 undef($condition);
 2470:             }
 2471:         }
 2472:         if ($excluded) {
 2473:             unless ($excluded =~ /^\@[^\@]+$/) {
 2474:                 undef($condition);
 2475:             }
 2476:         }
 2477:         $output .= &Apache::lonhtmlcommon::row_title($lt{'email'}.'<b>*</b>',undef,
 2478:                                                      'LC_oddrow_value')."\n".
 2479:                    '<input type="text" name="uname" size="'.$size.'" value="" autocomplete="off" />';
 2480:         if ($condition) {
 2481:             $output .= $condition;
 2482:         } elsif ($excluded) {
 2483:             $output .= '<br /><span style="font-size: smaller">'.&mt('You must use an e-mail address that does not end with [_1]',
 2484:                                                                      $excluded).'</span>';
 2485:         }
 2486:         if ($usernameset eq 'first') {
 2487:             $output .= '<br /><span style="font-size: smaller">';
 2488:             if ($condition) {
 2489:                 $output .= &mt('Your username in LON-CAPA will be the part of your e-mail address before [_1]',
 2490:                                       $condition);
 2491:             } else {
 2492:                 $output .= &mt('Your username in LON-CAPA will be the part of your e-mail address before the @');
 2493:             }
 2494:             $output .= '</span>';
 2495:         }
 2496:         $rowcount ++;
 2497:         $output .= &Apache::lonhtmlcommon::row_closure(1);
 2498:         my $upassone = '<input type="password" name="upass'.$now.'" size="20" autocomplete="new-password" />';
 2499:         my $upasstwo = '<input type="password" name="upasscheck'.$now.'" size="20" autocomplete="new-password" />';
 2500:         $output .= &Apache::lonhtmlcommon::row_title(&mt('Password').'<b>*</b>',
 2501:                                                     'LC_pick_box_title',
 2502:                                                     'LC_oddrow_value')."\n".
 2503:                    $upassone."\n".
 2504:                    &Apache::lonhtmlcommon::row_closure(1)."\n".
 2505:                    &Apache::lonhtmlcommon::row_title(&mt('Confirm password').'<b>*</b>',
 2506:                                                      'LC_pick_box_title',
 2507:                                                      'LC_oddrow_value')."\n".
 2508:                    $upasstwo.
 2509:                    &Apache::lonhtmlcommon::row_closure()."\n";
 2510:         if ($usernameset eq 'free') {
 2511:             my $onclick = "toggleUsernameDisp(this,'selfcreateusername');";
 2512:             $output .= &Apache::lonhtmlcommon::row_title($lt{'username'},undef,'LC_oddrow_value')."\n".
 2513:                        '<span class="LC_nobreak">'.&mt('Use e-mail address: ').
 2514:                        '<label><input type="radio" name="emailused" value="1" checked="checked" onclick="'.$onclick.'" />'.
 2515:                        &mt('Yes').'</label>'.('&nbsp;'x2).
 2516:                        '<label><input type="radio" name="emailused" value="0" onclick="'.$onclick.'" />'.
 2517:                        &mt('No').'</label></span>'."\n".
 2518:                        '<div id="selfcreateusername" style="display: none; font-size: smaller">'.
 2519:                        '<br /><span class="LC_nobreak">'.&mt('Preferred username').
 2520:                        '&nbsp;<input type="text" name="username" value="" size="20" autocomplete="off"/>'.
 2521:                        '</span></div>'."\n".&Apache::lonhtmlcommon::row_closure(1);
 2522:             $rowcount ++;
 2523:         }
 2524:     }
 2525:     foreach my $item (@userinfo) {
 2526:         my $rowtitle = $lt{$item};
 2527:         my $hiderow = 0;
 2528:         if ($item eq 'generation') {
 2529:             $rowtitle = $genhelp.$rowtitle;
 2530:         }
 2531:         my $row = &Apache::lonhtmlcommon::row_title($rowtitle,undef,'LC_oddrow_value')."\n";
 2532:         if ($newuser) {
 2533:             if (ref($inst_results) eq 'HASH') {
 2534:                 if ($inst_results->{$item} ne '') {
 2535:                     $row .= '<input type="hidden" name="c'.$item.'" value="'.$inst_results->{$item}.'" />'.$inst_results->{$item};
 2536:                 } else {
 2537:                     if ($context eq 'selfcreate') {
 2538:                         if ($canmodify{$item}) {
 2539:                             $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="" autocomplete="off" />';
 2540:                             $editable ++;
 2541:                         } else {
 2542:                             $hiderow = 1;
 2543:                         }
 2544:                     } else {
 2545:                         $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="" />';
 2546:                     }
 2547:                 }
 2548:             } else {
 2549:                 if ($context eq 'selfcreate') {
 2550:                     if ($canmodify{$item}) {
 2551:                         if ($newuser eq 'email') {
 2552:                             $row .= '<input type="text" name="'.$item.'" size="'.$textboxsize{$item}.'" value="" autocomplete="off" />';
 2553:                         } else {
 2554:                             $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="" autocomplete="off" />';
 2555:                         }
 2556:                         $editable ++;
 2557:                     } else {
 2558:                         $hiderow = 1;
 2559:                     }
 2560:                 } else {
 2561:                     $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="" />';
 2562:                 }
 2563:             }
 2564:         } else {
 2565:             if ($canmodify{$item}) {
 2566:                 $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="'.$userenv{$item}.'" />';
 2567:                 if (($item eq 'id') && (!$newuser)) {
 2568:                     $row .= '<br />'.&Apache::lonuserutils::forceid_change($context);
 2569:                 }
 2570:             } else {
 2571:                 $row .= $userenv{$item};
 2572:             }
 2573:         }
 2574:         $row .= &Apache::lonhtmlcommon::row_closure(1);
 2575:         if (!$hiderow) {
 2576:             $output .= $row;
 2577:             $rowcount ++;
 2578:         }
 2579:     }
 2580:     if (($canmodify_status{'inststatus'}) || ($context ne 'selfcreate')) {
 2581:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($ccdomain);
 2582:         if (ref($types) eq 'ARRAY') {
 2583:             if (@{$types} > 0) {
 2584:                 my ($hiderow,$shown);
 2585:                 if ($canmodify_status{'inststatus'}) {
 2586:                     $shown = &pick_inst_statuses($userenv{'inststatus'},$usertypes,$types);
 2587:                 } else {
 2588:                     if ($userenv{'inststatus'} eq '') {
 2589:                         $hiderow = 1;
 2590:                     } else {
 2591:                         my @showitems;
 2592:                         foreach my $item ( map { &unescape($_); } split(':',$userenv{'inststatus'})) {
 2593:                             if (exists($usertypes->{$item})) {
 2594:                                 push(@showitems,$usertypes->{$item});
 2595:                             } else {
 2596:                                 push(@showitems,$item);
 2597:                             }
 2598:                         }
 2599:                         if (@showitems) {
 2600:                             $shown = join(', ',@showitems);
 2601:                         } else {
 2602:                             $hiderow = 1;
 2603:                         }
 2604:                     }
 2605:                 }
 2606:                 if (!$hiderow) {
 2607:                     my $row = &Apache::lonhtmlcommon::row_title(&mt('Affiliations'),undef,'LC_oddrow_value')."\n".
 2608:                               $shown.&Apache::lonhtmlcommon::row_closure(1); 
 2609:                     if ($context eq 'selfcreate') {
 2610:                         $rowcount ++;
 2611:                     }
 2612:                     $output .= $row;
 2613:                 }
 2614:             }
 2615:         }
 2616:     }
 2617:     if (($context eq 'selfcreate') && ($newuser eq 'email')) {
 2618:         if ($captchaform) {
 2619:             $output .= &Apache::lonhtmlcommon::row_title($lt{'valid'}.'*',
 2620:                                                          'LC_pick_box_title')."\n".
 2621:                        $captchaform."\n".'<br /><br />'.
 2622:                        &Apache::lonhtmlcommon::row_closure(1); 
 2623:             $rowcount ++;
 2624:         }
 2625:         if ($showsubmit) {
 2626:             my $submit_text = &mt('Create account');
 2627:             $output .= &Apache::lonhtmlcommon::row_title()."\n".
 2628:                        '<br /><input type="submit" name="createaccount" value="'.
 2629:                        $submit_text.'" />';
 2630:             if ($usertype ne '') {
 2631:                 $output .= '<input type="hidden" name="type" value="'.$usertype.'" />'.
 2632:                            &Apache::lonhtmlcommon::row_closure(1);
 2633:             }
 2634:         }
 2635:     }
 2636:     $output .= &Apache::lonhtmlcommon::end_pick_box();
 2637:     if (wantarray) {
 2638:         if ($context eq 'selfcreate') {
 2639:             return($output,$rowcount,$editable);
 2640:         } else {
 2641:             return $output;
 2642:         }
 2643:     } else {
 2644:         return $output;
 2645:     }
 2646: }
 2647: 
 2648: sub pick_inst_statuses {
 2649:     my ($curr,$usertypes,$types) = @_;
 2650:     my ($output,$rem,@currtypes);
 2651:     if ($curr ne '') {
 2652:         @currtypes = map { &unescape($_); } split(/:/,$curr);
 2653:     }
 2654:     my $numinrow = 2;
 2655:     if (ref($types) eq 'ARRAY') {
 2656:         $output = '<table>';
 2657:         my $lastcolspan; 
 2658:         for (my $i=0; $i<@{$types}; $i++) {
 2659:             if (defined($usertypes->{$types->[$i]})) {
 2660:                 my $rem = $i%($numinrow);
 2661:                 if ($rem == 0) {
 2662:                     if ($i<@{$types}-1) {
 2663:                         if ($i > 0) { 
 2664:                             $output .= '</tr>';
 2665:                         }
 2666:                         $output .= '<tr>';
 2667:                     }
 2668:                 } elsif ($i==@{$types}-1) {
 2669:                     my $colsleft = $numinrow - $rem;
 2670:                     if ($colsleft > 1) {
 2671:                         $lastcolspan = ' colspan="'.$colsleft.'"';
 2672:                     }
 2673:                 }
 2674:                 my $check = ' ';
 2675:                 if (grep(/^\Q$types->[$i]\E$/,@currtypes)) {
 2676:                     $check = ' checked="checked" ';
 2677:                 }
 2678:                 $output .= '<td class="LC_left_item"'.$lastcolspan.'>'.
 2679:                            '<span class="LC_nobreak"><label>'.
 2680:                            '<input type="checkbox" name="inststatus" '.
 2681:                            'value="'.$types->[$i].'"'.$check.'/>'.
 2682:                            $usertypes->{$types->[$i]}.'</label></span></td>';
 2683:             }
 2684:         }
 2685:         $output .= '</tr></table>';
 2686:     }
 2687:     return $output;
 2688: }
 2689: 
 2690: sub selfcreate_canmodify {
 2691:     my ($context,$dom,$userinfo,$inst_results,$rolesarray) = @_;
 2692:     if (ref($inst_results) eq 'HASH') {
 2693:         my @inststatuses = &get_inststatuses($inst_results);
 2694:         if (@inststatuses == 0) {
 2695:             @inststatuses = ('default');
 2696:         }
 2697:         $rolesarray = \@inststatuses;
 2698:     }
 2699:     my %canmodify =
 2700:         &Apache::lonuserutils::can_modify_userinfo($context,$dom,$userinfo,
 2701:                                                    $rolesarray);
 2702:     return %canmodify;
 2703: }
 2704: 
 2705: sub get_inststatuses {
 2706:     my ($insthashref) = @_;
 2707:     my @inststatuses = ();
 2708:     if (ref($insthashref) eq 'HASH') {
 2709:         if (ref($insthashref->{'inststatus'}) eq 'ARRAY') {
 2710:             @inststatuses = @{$insthashref->{'inststatus'}};
 2711:         }
 2712:     }
 2713:     return @inststatuses;
 2714: }
 2715: 
 2716: # ================================================================= Phase Three
 2717: sub update_user_data {
 2718:     my ($r,$context,$crstype,$brcrum,$showcredits,$permission) = @_; 
 2719:     my $uhome=&Apache::lonnet::homeserver($env{'form.ccuname'},
 2720:                                           $env{'form.ccdomain'});
 2721:     # Error messages
 2722:     my $error     = '<span class="LC_error">'.&mt('Error').': ';
 2723:     my $end       = '</span><br /><br />';
 2724:     my $rtnlink   = '<a href="javascript:backPage(document.userupdate,'.
 2725:                     "'$env{'form.prevphase'}','modify')".'" />'.
 2726:                     &mt('Return to previous page').'</a>'.
 2727:                     &Apache::loncommon::end_page();
 2728:     my $now = time;
 2729:     my $title;
 2730:     if (exists($env{'form.makeuser'})) {
 2731: 	$title='Set Privileges for New User';
 2732:     } else {
 2733:         $title='Modify User Privileges';
 2734:     }
 2735:     my $newuser = 0;
 2736:     my ($jsback,$elements) = &crumb_utilities();
 2737:     my $jscript = '<script type="text/javascript">'."\n".
 2738:                   '// <![CDATA['."\n".
 2739:                   $jsback."\n".
 2740:                   '// ]]>'."\n".
 2741:                   '</script>'."\n";
 2742:     my %breadcrumb_text = &singleuser_breadcrumb($crstype,$context,$env{'form.ccdomain'});
 2743:     push (@{$brcrum},
 2744:              {href => "javascript:backPage(document.userupdate)",
 2745:               text => $breadcrumb_text{'search'},
 2746:               faq  => 282,
 2747:               bug  => 'Instructor Interface',}
 2748:              );
 2749:     if ($env{'form.prevphase'} eq 'userpicked') {
 2750:         push(@{$brcrum},
 2751:                {href => "javascript:backPage(document.userupdate,'get_user_info','select')",
 2752:                 text => $breadcrumb_text{'userpicked'},
 2753:                 faq  => 282,
 2754:                 bug  => 'Instructor Interface',});
 2755:     }
 2756:     my $helpitem = 'Course_Change_Privileges';
 2757:     if ($env{'form.action'} eq 'singlestudent') {
 2758:         $helpitem = 'Course_Add_Student';
 2759:     } elsif ($context eq 'author') {
 2760:         $helpitem = 'Author_Change_Privileges';
 2761:     } elsif ($context eq 'domain') {
 2762:         $helpitem = 'Domain_Change_Privileges';
 2763:     }
 2764:     push(@{$brcrum}, 
 2765:             {href => "javascript:backPage(document.userupdate,'$env{'form.prevphase'}','modify')",
 2766:              text => $breadcrumb_text{'modify'},
 2767:              faq  => 282,
 2768:              bug  => 'Instructor Interface',},
 2769:             {href => "/adm/createuser",
 2770:              text => "Result",
 2771:              faq  => 282,
 2772:              bug  => 'Instructor Interface',
 2773:              help => $helpitem});
 2774:     my $args = {bread_crumbs          => $brcrum,
 2775:                 bread_crumbs_component => 'User Management'};
 2776:     if ($env{'form.popup'}) {
 2777:         $args->{'no_nav_bar'} = 1;
 2778:     }
 2779:     $r->print(&Apache::loncommon::start_page($title,$jscript,$args));
 2780:     $r->print(&update_result_form($uhome));
 2781:     # Check Inputs
 2782:     if (! $env{'form.ccuname'} ) {
 2783: 	$r->print($error.&mt('No login name specified').'.'.$end.$rtnlink);
 2784: 	return;
 2785:     }
 2786:     if (  $env{'form.ccuname'} ne 
 2787: 	  &LONCAPA::clean_username($env{'form.ccuname'}) ) {
 2788: 	$r->print($error.&mt('Invalid login name.').'  '.
 2789: 		  &mt('Only letters, numbers, periods, dashes, @, and underscores are valid.').
 2790: 		  $end.$rtnlink);
 2791: 	return;
 2792:     }
 2793:     if (! $env{'form.ccdomain'}       ) {
 2794: 	$r->print($error.&mt('No domain specified').'.'.$end.$rtnlink);
 2795: 	return;
 2796:     }
 2797:     if (  $env{'form.ccdomain'} ne
 2798: 	  &LONCAPA::clean_domain($env{'form.ccdomain'}) ) {
 2799: 	$r->print($error.&mt('Invalid domain name.').'  '.
 2800: 		  &mt('Only letters, numbers, periods, dashes, and underscores are valid.').
 2801: 		  $end.$rtnlink);
 2802: 	return;
 2803:     }
 2804:     if ($uhome eq 'no_host') {
 2805:         $newuser = 1;
 2806:     }
 2807:     if (! exists($env{'form.makeuser'})) {
 2808:         # Modifying an existing user, so check the validity of the name
 2809:         if ($uhome eq 'no_host') {
 2810:             $r->print(
 2811:                 $error
 2812:                .'<p class="LC_error">'
 2813:                .&mt('Unable to determine home server for [_1] in domain [_2].',
 2814:                         '"'.$env{'form.ccuname'}.'"','"'.$env{'form.ccdomain'}.'"')
 2815:                .'</p>');
 2816:             return;
 2817:         }
 2818:     }
 2819:     # Determine authentication method and password for the user being modified
 2820:     my $amode='';
 2821:     my $genpwd='';
 2822:     if ($env{'form.login'} eq 'krb') {
 2823: 	$amode='krb';
 2824: 	$amode.=$env{'form.krbver'};
 2825: 	$genpwd=$env{'form.krbarg'};
 2826:     } elsif ($env{'form.login'} eq 'int') {
 2827: 	$amode='internal';
 2828: 	$genpwd=$env{'form.intarg'};
 2829:     } elsif ($env{'form.login'} eq 'fsys') {
 2830: 	$amode='unix';
 2831: 	$genpwd=$env{'form.fsysarg'};
 2832:     } elsif ($env{'form.login'} eq 'loc') {
 2833: 	$amode='localauth';
 2834: 	$genpwd=$env{'form.locarg'};
 2835: 	$genpwd=" " if (!$genpwd);
 2836:     } elsif (($env{'form.login'} eq 'nochange') ||
 2837:              ($env{'form.login'} eq ''        )) { 
 2838:         # There is no need to tell the user we did not change what they
 2839:         # did not ask us to change.
 2840:         # If they are creating a new user but have not specified login
 2841:         # information this will be caught below.
 2842:     } else {
 2843:             $r->print($error.&mt('Invalid login mode or password').$end.$rtnlink);
 2844:             return;
 2845:     }
 2846: 
 2847:     $r->print('<h3>'.&mt('User [_1] in domain [_2]',
 2848:                         $env{'form.ccuname'}.' ('.&Apache::loncommon::plainname($env{'form.ccuname'},
 2849:                         $env{'form.ccdomain'}).')', $env{'form.ccdomain'}).'</h3>');
 2850:     my %prog_state = &Apache::lonhtmlcommon::Create_PrgWin($r,2);
 2851: 
 2852:     my (%alerts,%rulematch,%inst_results,%curr_rules);
 2853:     my @userinfo = ('firstname','middlename','lastname','generation','permanentemail','id');
 2854:     my @usertools = ('aboutme','blog','webdav','portfolio','timezone');
 2855:     my @requestcourses = ('official','unofficial','community','textbook');
 2856:     my @requestauthor = ('requestauthor');
 2857:     my ($othertitle,$usertypes,$types) = 
 2858:         &Apache::loncommon::sorted_inst_types($env{'form.ccdomain'});
 2859:     my %canmodify_status =
 2860:         &Apache::lonuserutils::can_modify_userinfo($context,$env{'form.ccdomain'},
 2861:                                                    ['inststatus']);
 2862:     if ($env{'form.makeuser'}) {
 2863: 	$r->print('<h3>'.&mt('Creating new account.').'</h3>');
 2864:         # Check for the authentication mode and password
 2865:         if (! $amode || ! $genpwd) {
 2866: 	    $r->print($error.&mt('Invalid login mode or password').$end.$rtnlink);    
 2867: 	    return;
 2868: 	}
 2869:         # Determine desired host
 2870:         my $desiredhost = $env{'form.hserver'};
 2871:         if (lc($desiredhost) eq 'default') {
 2872:             $desiredhost = undef;
 2873:         } else {
 2874:             my %home_servers = 
 2875: 		&Apache::lonnet::get_servers($env{'form.ccdomain'},'library');
 2876:             if (! exists($home_servers{$desiredhost})) {
 2877:                 $r->print($error.&mt('Invalid home server specified').$end.$rtnlink);
 2878:                 return;
 2879:             }
 2880:         }
 2881:         # Check ID format
 2882:         my %checkhash;
 2883:         my %checks = ('id' => 1);
 2884:         %{$checkhash{$env{'form.ccuname'}.':'.$env{'form.ccdomain'}}} = (
 2885:             'newuser' => $newuser, 
 2886:             'id' => $env{'form.cid'},
 2887:         );
 2888:         if ($env{'form.cid'} ne '') {
 2889:             &Apache::loncommon::user_rule_check(\%checkhash,\%checks,\%alerts,
 2890:                                           \%rulematch,\%inst_results,\%curr_rules);
 2891:             if (ref($alerts{'id'}) eq 'HASH') {
 2892:                 if (ref($alerts{'id'}{$env{'form.ccdomain'}}) eq 'HASH') {
 2893:                     my $domdesc =
 2894:                         &Apache::lonnet::domain($env{'form.ccdomain'},'description');
 2895:                     if ($alerts{'id'}{$env{'form.ccdomain'}}{$env{'form.cid'}}) {
 2896:                         my $userchkmsg;
 2897:                         if (ref($curr_rules{$env{'form.ccdomain'}}) eq 'HASH') {
 2898:                             $userchkmsg  = 
 2899:                                 &Apache::loncommon::instrule_disallow_msg('id',
 2900:                                                                     $domdesc,1).
 2901:                                 &Apache::loncommon::user_rule_formats($env{'form.ccdomain'},
 2902:                                     $domdesc,$curr_rules{$env{'form.ccdomain'}}{'id'},'id');
 2903:                         }
 2904:                         $r->print($error.&mt('Invalid ID format').$end.
 2905:                                   $userchkmsg.$rtnlink);
 2906:                         return;
 2907:                     }
 2908:                 }
 2909:             }
 2910:         }
 2911:         &Apache::lonhtmlcommon::Increment_PrgWin($r, \%prog_state);
 2912: 	# Call modifyuser
 2913: 	my $result = &Apache::lonnet::modifyuser
 2914: 	    ($env{'form.ccdomain'},$env{'form.ccuname'},$env{'form.cid'},
 2915:              $amode,$genpwd,$env{'form.cfirstname'},
 2916:              $env{'form.cmiddlename'},$env{'form.clastname'},
 2917:              $env{'form.cgeneration'},undef,$desiredhost,
 2918:              $env{'form.cpermanentemail'});
 2919: 	$r->print(&mt('Generating user').': '.$result);
 2920:         $uhome = &Apache::lonnet::homeserver($env{'form.ccuname'},
 2921:                                                $env{'form.ccdomain'});
 2922:         my (%changeHash,%newcustom,%changed,%changedinfo);
 2923:         if ($uhome ne 'no_host') {
 2924:             if ($context eq 'domain') {
 2925:                 foreach my $name ('portfolio','author') {
 2926:                     if ($env{'form.custom_'.$name.'quota'} == 1) {
 2927:                         if ($env{'form.'.$name.'quota'} eq '') {
 2928:                             $newcustom{$name.'quota'} = 0;
 2929:                         } else {
 2930:                             $newcustom{$name.'quota'} = $env{'form.'.$name.'quota'};
 2931:                             $newcustom{$name.'quota'} =~ s/[^\d\.]//g;
 2932:                         }
 2933:                         if (&quota_admin($newcustom{$name.'quota'},\%changeHash,$name)) {
 2934:                             $changed{$name.'quota'} = 1;
 2935:                         }
 2936:                     }
 2937:                 }
 2938:                 foreach my $item (@usertools) {
 2939:                     if ($env{'form.custom'.$item} == 1) {
 2940:                         $newcustom{$item} = $env{'form.tools_'.$item};
 2941:                         $changed{$item} = &tool_admin($item,$newcustom{$item},
 2942:                                                      \%changeHash,'tools');
 2943:                     }
 2944:                 }
 2945:                 foreach my $item (@requestcourses) {
 2946:                     if ($env{'form.custom'.$item} == 1) {
 2947:                         $newcustom{$item} = $env{'form.crsreq_'.$item};
 2948:                         if ($env{'form.crsreq_'.$item} eq 'autolimit') {
 2949:                             $newcustom{$item} .= '=';
 2950:                             $env{'form.crsreq_'.$item.'_limit'} =~ s/\D+//g;
 2951:                             if ($env{'form.crsreq_'.$item.'_limit'}) {
 2952:                                 $newcustom{$item} .= $env{'form.crsreq_'.$item.'_limit'};
 2953:                             }
 2954:                         }
 2955:                         $changed{$item} = &tool_admin($item,$newcustom{$item},
 2956:                                                       \%changeHash,'requestcourses');
 2957:                     }
 2958:                 }
 2959:                 if ($env{'form.customrequestauthor'} == 1) {
 2960:                     $newcustom{'requestauthor'} = $env{'form.requestauthor'};
 2961:                     $changed{'requestauthor'} = &tool_admin('requestauthor',
 2962:                                                     $newcustom{'requestauthor'},
 2963:                                                     \%changeHash,'requestauthor');
 2964:                 }
 2965:             }
 2966:             if ($canmodify_status{'inststatus'}) {
 2967:                 if (exists($env{'form.inststatus'})) {
 2968:                     my @inststatuses = &Apache::loncommon::get_env_multiple('form.inststatus');
 2969:                     if (@inststatuses > 0) {
 2970:                         $changeHash{'inststatus'} = join(',',@inststatuses);
 2971:                         $changed{'inststatus'} = $changeHash{'inststatus'};
 2972:                     }
 2973:                 }
 2974:             }
 2975:             if (keys(%changed)) {
 2976:                 foreach my $item (@userinfo) {
 2977:                     $changeHash{$item}  = $env{'form.c'.$item};
 2978:                 }
 2979:                 my $chgresult =
 2980:                      &Apache::lonnet::put('environment',\%changeHash,
 2981:                                           $env{'form.ccdomain'},$env{'form.ccuname'});
 2982:             } 
 2983:         }
 2984:         $r->print('<br />'.&mt('Home Server').': '.$uhome.' '.
 2985:                   &Apache::lonnet::hostname($uhome));
 2986:     } elsif (($env{'form.login'} ne 'nochange') &&
 2987:              ($env{'form.login'} ne ''        )) {
 2988: 	# Modify user privileges
 2989:         if (! $amode || ! $genpwd) {
 2990: 	    $r->print($error.'Invalid login mode or password'.$end.$rtnlink);    
 2991: 	    return;
 2992: 	}
 2993: 	# Only allow authentication modification if the person has authority
 2994: 	if (&Apache::lonnet::allowed('mau',$env{'form.ccdomain'})) {
 2995: 	    $r->print('Modifying authentication: '.
 2996:                       &Apache::lonnet::modifyuserauth(
 2997: 		       $env{'form.ccdomain'},$env{'form.ccuname'},
 2998:                        $amode,$genpwd));
 2999:             $r->print('<br />'.&mt('Home Server').': '.&Apache::lonnet::homeserver
 3000: 		  ($env{'form.ccuname'},$env{'form.ccdomain'}));
 3001: 	} else {
 3002: 	    # Okay, this is a non-fatal error.
 3003: 	    $r->print($error.&mt('You do not have privileges to modify the authentication configuration for this user.').$end);    
 3004: 	}
 3005:     } elsif (($env{'form.intarg'} ne '') &&
 3006:              (&Apache::lonnet::queryauthenticate($env{'form.ccuname'},$env{'form.ccdomain'}) =~ /^internal:/) &&
 3007:              (&Apache::lonuserutils::can_change_internalpass($env{'form.ccuname'},$env{'form.ccdomain'},$crstype,$permission))) {
 3008:         $r->print('Modifying authentication: '.
 3009:                   &Apache::lonnet::modifyuserauth(
 3010:                   $env{'form.ccdomain'},$env{'form.ccuname'},
 3011:                   'internal',$env{'form.intarg'}));
 3012:     }
 3013:     $r->rflush(); # Finish display of header before time consuming actions start
 3014:     &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state);
 3015:     ##
 3016:     my (@userroles,%userupdate,$cnum,$cdom,$defaultcredits,%namechanged);
 3017:     if ($context eq 'course') {
 3018:         ($cnum,$cdom) =
 3019:             &Apache::lonuserutils::get_course_identity();
 3020:         $crstype = &Apache::loncommon::course_type($cdom.'_'.$cnum);
 3021:         if ($showcredits) {
 3022:            $defaultcredits = &Apache::lonuserutils::get_defaultcredits($cdom,$cnum);
 3023:         }
 3024:     }
 3025:     if (! $env{'form.makeuser'} ) {
 3026:         # Check for need to change
 3027:         my %userenv = &Apache::lonnet::get
 3028:             ('environment',['firstname','middlename','lastname','generation',
 3029:              'id','permanentemail','portfolioquota','authorquota','inststatus',
 3030:              'tools.aboutme','tools.blog','tools.webdav',
 3031:              'tools.portfolio','tools.timezone',
 3032:              'requestcourses.official','requestcourses.unofficial',
 3033:              'requestcourses.community','requestcourses.textbook',
 3034:              'reqcrsotherdom.official','reqcrsotherdom.unofficial',
 3035:              'reqcrsotherdom.community','reqcrsotherdom.textbook',
 3036:              'requestauthor'],
 3037:               $env{'form.ccdomain'},$env{'form.ccuname'});
 3038:         my ($tmp) = keys(%userenv);
 3039:         if ($tmp =~ /^(con_lost|error)/i) { 
 3040:             %userenv = ();
 3041:         }
 3042:         my $no_forceid_alert;
 3043:         # Check to see if user information can be changed
 3044:         my %domconfig =
 3045:             &Apache::lonnet::get_dom('configuration',['usermodification'],
 3046:                                      $env{'form.ccdomain'});
 3047:         my @statuses = ('active','future');
 3048:         my %roles = &Apache::lonnet::get_my_roles($env{'form.ccuname'},$env{'form.ccdomain'},'userroles',\@statuses,undef,$env{'request.role.domain'});
 3049:         my ($auname,$audom);
 3050:         if ($context eq 'author') {
 3051:             $auname = $env{'user.name'};
 3052:             $audom = $env{'user.domain'};     
 3053:         }
 3054:         foreach my $item (keys(%roles)) {
 3055:             my ($rolenum,$roledom,$role) = split(/:/,$item,-1);
 3056:             if ($context eq 'course') {
 3057:                 if ($cnum ne '' && $cdom ne '') {
 3058:                     if ($rolenum eq $cnum && $roledom eq $cdom) {
 3059:                         if (!grep(/^\Q$role\E$/,@userroles)) {
 3060:                             push(@userroles,$role);
 3061:                         }
 3062:                     }
 3063:                 }
 3064:             } elsif ($context eq 'author') {
 3065:                 if ($rolenum eq $auname && $roledom eq $audom) {
 3066:                     if (!grep(/^\Q$role\E$/,@userroles)) { 
 3067:                         push(@userroles,$role);
 3068:                     }
 3069:                 }
 3070:             }
 3071:         }
 3072:         if ($env{'form.action'} eq 'singlestudent') {
 3073:             if (!grep(/^st$/,@userroles)) {
 3074:                 push(@userroles,'st');
 3075:             }
 3076:         } else {
 3077:             # Check for course or co-author roles being activated or re-enabled
 3078:             if ($context eq 'author' || $context eq 'course') {
 3079:                 foreach my $key (keys(%env)) {
 3080:                     if ($context eq 'author') {
 3081:                         if ($key=~/^form\.act_\Q$audom\E_\Q$auname\E_([^_]+)/) {
 3082:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 3083:                                 push(@userroles,$1);
 3084:                             }
 3085:                         } elsif ($key =~/^form\.ren\:\Q$audom\E\/\Q$auname\E_([^_]+)/) {
 3086:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 3087:                                 push(@userroles,$1);
 3088:                             }
 3089:                         }
 3090:                     } elsif ($context eq 'course') {
 3091:                         if ($key=~/^form\.act_\Q$cdom\E_\Q$cnum\E_([^_]+)/) {
 3092:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 3093:                                 push(@userroles,$1);
 3094:                             }
 3095:                         } elsif ($key =~/^form\.ren\:\Q$cdom\E\/\Q$cnum\E(\/?\w*)_([^_]+)/) {
 3096:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 3097:                                 push(@userroles,$1);
 3098:                             }
 3099:                         }
 3100:                     }
 3101:                 }
 3102:             }
 3103:         }
 3104:         #Check to see if we can change personal data for the user 
 3105:         my (@mod_disallowed,@longroles);
 3106:         foreach my $role (@userroles) {
 3107:             if ($role eq 'cr') {
 3108:                 push(@longroles,'Custom');
 3109:             } else {
 3110:                 push(@longroles,&Apache::lonnet::plaintext($role,$crstype)); 
 3111:             }
 3112:         }
 3113:         my %canmodify = &Apache::lonuserutils::can_modify_userinfo($context,$env{'form.ccdomain'},\@userinfo,\@userroles);
 3114:         foreach my $item (@userinfo) {
 3115:             # Strip leading and trailing whitespace
 3116:             $env{'form.c'.$item} =~ s/(\s+$|^\s+)//g;
 3117:             if (!$canmodify{$item}) {
 3118:                 if (defined($env{'form.c'.$item})) {
 3119:                     if ($env{'form.c'.$item} ne $userenv{$item}) {
 3120:                         push(@mod_disallowed,$item);
 3121:                     }
 3122:                 }
 3123:                 $env{'form.c'.$item} = $userenv{$item};
 3124:             }
 3125:         }
 3126:         # Check to see if we can change the Student/Employee ID
 3127:         my $forceid = $env{'form.forceid'};
 3128:         my $recurseid = $env{'form.recurseid'};
 3129:         my (%alerts,%rulematch,%idinst_results,%curr_rules,%got_rules);
 3130:         my %uidhash = &Apache::lonnet::idrget($env{'form.ccdomain'},
 3131:                                             $env{'form.ccuname'});
 3132:         if (($uidhash{$env{'form.ccuname'}}) && 
 3133:             ($uidhash{$env{'form.ccuname'}}!~/error\:/) && 
 3134:             (!$forceid)) {
 3135:             if ($env{'form.cid'} ne $uidhash{$env{'form.ccuname'}}) {
 3136:                 $env{'form.cid'} = $userenv{'id'};
 3137:                 $no_forceid_alert = &mt('New student/employee ID does not match existing ID for this user.')
 3138:                                    .'<br />'
 3139:                                    .&mt("Change is not permitted without checking the 'Force ID change' checkbox on the previous page.")
 3140:                                    .'<br />'."\n";
 3141:             }
 3142:         }
 3143:         if ($env{'form.cid'} ne $userenv{'id'}) {
 3144:             my $checkhash;
 3145:             my $checks = { 'id' => 1 };
 3146:             $checkhash->{$env{'form.ccuname'}.':'.$env{'form.ccdomain'}} = 
 3147:                    { 'newuser' => $newuser,
 3148:                      'id'  => $env{'form.cid'}, 
 3149:                    };
 3150:             &Apache::loncommon::user_rule_check($checkhash,$checks,
 3151:                 \%alerts,\%rulematch,\%idinst_results,\%curr_rules,\%got_rules);
 3152:             if (ref($alerts{'id'}) eq 'HASH') {
 3153:                 if (ref($alerts{'id'}{$env{'form.ccdomain'}}) eq 'HASH') {
 3154:                    $env{'form.cid'} = $userenv{'id'};
 3155:                 }
 3156:             }
 3157:         }
 3158:         my (%quotachanged,%oldquota,%newquota,%olddefquota,%newdefquota, 
 3159:             $oldinststatus,$newinststatus,%oldisdefault,%newisdefault,%oldsettings,
 3160:             %oldsettingstext,%newsettings,%newsettingstext,@disporder,
 3161:             %oldsettingstatus,%newsettingstatus);
 3162:         @disporder = ('inststatus');
 3163:         if ($env{'request.role.domain'} eq $env{'form.ccdomain'}) {
 3164:             push(@disporder,'requestcourses','requestauthor');
 3165:         } else {
 3166:             push(@disporder,'reqcrsotherdom');
 3167:         }
 3168:         push(@disporder,('quota','tools'));
 3169:         $oldinststatus = $userenv{'inststatus'};
 3170:         foreach my $name ('portfolio','author') {
 3171:             ($olddefquota{$name},$oldsettingstatus{$name}) = 
 3172:                 &Apache::loncommon::default_quota($env{'form.ccdomain'},$oldinststatus,$name);
 3173:             ($newdefquota{$name},$newsettingstatus{$name}) = ($olddefquota{$name},$oldsettingstatus{$name});
 3174:         }
 3175:         my %canshow;
 3176:         if (&Apache::lonnet::allowed('mpq',$env{'form.ccdomain'})) {
 3177:             $canshow{'quota'} = 1;
 3178:         }
 3179:         if (&Apache::lonnet::allowed('mut',$env{'form.ccdomain'})) {
 3180:             $canshow{'tools'} = 1;
 3181:         }
 3182:         if (&Apache::lonnet::allowed('ccc',$env{'form.ccdomain'})) {
 3183:             $canshow{'requestcourses'} = 1;
 3184:         } elsif (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) {
 3185:             $canshow{'reqcrsotherdom'} = 1;
 3186:         }
 3187:         if (&Apache::lonnet::allowed('mau',$env{'form.ccdomain'})) {
 3188:             $canshow{'inststatus'} = 1;
 3189:         }
 3190:         if (&Apache::lonnet::allowed('cau',$env{'form.ccdomain'})) {
 3191:             $canshow{'requestauthor'} = 1;
 3192:         }
 3193:         my (%changeHash,%changed);
 3194:         if ($oldinststatus eq '') {
 3195:             $oldsettings{'inststatus'} = $othertitle; 
 3196:         } else {
 3197:             if (ref($usertypes) eq 'HASH') {
 3198:                 $oldsettings{'inststatus'} = join(', ',map{ $usertypes->{ &unescape($_) }; } (split(/:/,$userenv{'inststatus'})));
 3199:             } else {
 3200:                 $oldsettings{'inststatus'} = join(', ',map{ &unescape($_); } (split(/:/,$userenv{'inststatus'})));
 3201:             }
 3202:         }
 3203:         $changeHash{'inststatus'} = $userenv{'inststatus'};
 3204:         if ($canmodify_status{'inststatus'}) {
 3205:             $canshow{'inststatus'} = 1;
 3206:             if (exists($env{'form.inststatus'})) {
 3207:                 my @inststatuses = &Apache::loncommon::get_env_multiple('form.inststatus');
 3208:                 if (@inststatuses > 0) {
 3209:                     $newinststatus = join(':',map { &escape($_); } @inststatuses);
 3210:                     $changeHash{'inststatus'} = $newinststatus;
 3211:                     if ($newinststatus ne $oldinststatus) {
 3212:                         $changed{'inststatus'} = $newinststatus;
 3213:                         foreach my $name ('portfolio','author') {
 3214:                             ($newdefquota{$name},$newsettingstatus{$name}) =
 3215:                                 &Apache::loncommon::default_quota($env{'form.ccdomain'},$newinststatus,$name);
 3216:                         }
 3217:                     }
 3218:                     if (ref($usertypes) eq 'HASH') {
 3219:                         $newsettings{'inststatus'} = join(', ',map{ $usertypes->{$_}; } (@inststatuses)); 
 3220:                     } else {
 3221:                         $newsettings{'inststatus'} = join(', ',@inststatuses);
 3222:                     }
 3223:                 }
 3224:             } else {
 3225:                 $newinststatus = '';
 3226:                 $changeHash{'inststatus'} = $newinststatus;
 3227:                 $newsettings{'inststatus'} = $othertitle;
 3228:                 if ($newinststatus ne $oldinststatus) {
 3229:                     $changed{'inststatus'} = $changeHash{'inststatus'};
 3230:                     foreach my $name ('portfolio','author') {
 3231:                         ($newdefquota{$name},$newsettingstatus{$name}) =
 3232:                             &Apache::loncommon::default_quota($env{'form.ccdomain'},$newinststatus,$name);
 3233:                     }
 3234:                 }
 3235:             }
 3236:         } elsif ($context ne 'selfcreate') {
 3237:             $canshow{'inststatus'} = 1;
 3238:             $newsettings{'inststatus'} = $oldsettings{'inststatus'};
 3239:         }
 3240:         foreach my $name ('portfolio','author') {
 3241:             $changeHash{$name.'quota'} = $userenv{$name.'quota'};
 3242:         }
 3243:         if ($context eq 'domain') {
 3244:             foreach my $name ('portfolio','author') {
 3245:                 if ($userenv{$name.'quota'} ne '') {
 3246:                     $oldquota{$name} = $userenv{$name.'quota'};
 3247:                     if ($env{'form.custom_'.$name.'quota'} == 1) {
 3248:                         if ($env{'form.'.$name.'quota'} eq '') {
 3249:                             $newquota{$name} = 0;
 3250:                         } else {
 3251:                             $newquota{$name} = $env{'form.'.$name.'quota'};
 3252:                             $newquota{$name} =~ s/[^\d\.]//g;
 3253:                         }
 3254:                         if ($newquota{$name} != $oldquota{$name}) {
 3255:                             if (&quota_admin($newquota{$name},\%changeHash,$name)) {
 3256:                                 $changed{$name.'quota'} = 1;
 3257:                             }
 3258:                         }
 3259:                     } else {
 3260:                         if (&quota_admin('',\%changeHash,$name)) {
 3261:                             $changed{$name.'quota'} = 1;
 3262:                             $newquota{$name} = $newdefquota{$name};
 3263:                             $newisdefault{$name} = 1;
 3264:                         }
 3265:                     }
 3266:                 } else {
 3267:                     $oldisdefault{$name} = 1;
 3268:                     $oldquota{$name} = $olddefquota{$name};
 3269:                     if ($env{'form.custom_'.$name.'quota'} == 1) {
 3270:                         if ($env{'form.'.$name.'quota'} eq '') {
 3271:                             $newquota{$name} = 0;
 3272:                         } else {
 3273:                             $newquota{$name} = $env{'form.'.$name.'quota'};
 3274:                             $newquota{$name} =~ s/[^\d\.]//g;
 3275:                         }
 3276:                         if (&quota_admin($newquota{$name},\%changeHash,$name)) {
 3277:                             $changed{$name.'quota'} = 1;
 3278:                         }
 3279:                     } else {
 3280:                         $newquota{$name} = $newdefquota{$name};
 3281:                         $newisdefault{$name} = 1;
 3282:                     }
 3283:                 }
 3284:                 if ($oldisdefault{$name}) {
 3285:                     $oldsettingstext{'quota'}{$name} = &get_defaultquota_text($oldsettingstatus{$name});
 3286:                 }  else {
 3287:                     $oldsettingstext{'quota'}{$name} = &mt('custom quota: [_1] MB',$oldquota{$name});
 3288:                 }
 3289:                 if ($newisdefault{$name}) {
 3290:                     $newsettingstext{'quota'}{$name} = &get_defaultquota_text($newsettingstatus{$name});
 3291:                 } else {
 3292:                     $newsettingstext{'quota'}{$name} = &mt('custom quota: [_1] MB',$newquota{$name});
 3293:                 }
 3294:             }
 3295:             &tool_changes('tools',\@usertools,\%oldsettings,\%oldsettingstext,\%userenv,
 3296:                           \%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3297:             if ($env{'form.ccdomain'} eq $env{'request.role.domain'}) {
 3298:                 &tool_changes('requestcourses',\@requestcourses,\%oldsettings,\%oldsettingstext,
 3299:                               \%userenv,\%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3300:                 &tool_changes('requestauthor',\@requestauthor,\%oldsettings,\%oldsettingstext,
 3301:                               \%userenv,\%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3302:             } else {
 3303:                 &tool_changes('reqcrsotherdom',\@requestcourses,\%oldsettings,\%oldsettingstext,
 3304:                               \%userenv,\%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3305:             }
 3306:         }
 3307:         foreach my $item (@userinfo) {
 3308:             if ($env{'form.c'.$item} ne $userenv{$item}) {
 3309:                 $namechanged{$item} = 1;
 3310:             }
 3311:         }
 3312:         foreach my $name ('portfolio','author') {
 3313:             $oldsettings{'quota'}{$name} = &mt('[_1] MB',$oldquota{$name});
 3314:             $newsettings{'quota'}{$name} = &mt('[_1] MB',$newquota{$name});
 3315:         }
 3316:         if ((keys(%namechanged) > 0) || (keys(%changed) > 0)) {
 3317:             my ($chgresult,$namechgresult);
 3318:             if (keys(%changed) > 0) {
 3319:                 $chgresult = 
 3320:                     &Apache::lonnet::put('environment',\%changeHash,
 3321:                                   $env{'form.ccdomain'},$env{'form.ccuname'});
 3322:                 if ($chgresult eq 'ok') {
 3323:                     if (($env{'user.name'} eq $env{'form.ccuname'}) &&
 3324:                         ($env{'user.domain'} eq $env{'form.ccdomain'})) {
 3325:                         my %newenvhash;
 3326:                         foreach my $key (keys(%changed)) {
 3327:                             if (($key eq 'official') || ($key eq 'unofficial')
 3328:                                 || ($key eq 'community') || ($key eq 'textbook')) {
 3329:                                 $newenvhash{'environment.requestcourses.'.$key} =
 3330:                                     $changeHash{'requestcourses.'.$key};
 3331:                                 if ($changeHash{'requestcourses.'.$key}) {
 3332:                                     $newenvhash{'environment.canrequest.'.$key} = 1;
 3333:                                 } else {
 3334:                                     $newenvhash{'environment.canrequest.'.$key} =
 3335:           &Apache::lonnet::usertools_access($env{'user.name'},$env{'user.domain'},
 3336:                                             $key,'reload','requestcourses');
 3337:                                 }
 3338:                             } elsif ($key eq 'requestauthor') {
 3339:                                 $newenvhash{'environment.'.$key} = $changeHash{$key};
 3340:                                 if ($changeHash{$key}) {
 3341:                                     $newenvhash{'environment.canrequest.author'} = 1;
 3342:                                 } else {
 3343:                                     $newenvhash{'environment.canrequest.author'} =
 3344:           &Apache::lonnet::usertools_access($env{'user.name'},$env{'user.domain'},
 3345:                                             $key,'reload','requestauthor');
 3346:                                 }
 3347:                             } elsif ($key ne 'quota') {
 3348:                                 $newenvhash{'environment.tools.'.$key} = 
 3349:                                     $changeHash{'tools.'.$key};
 3350:                                 if ($changeHash{'tools.'.$key} ne '') {
 3351:                                     $newenvhash{'environment.availabletools.'.$key} =
 3352:                                         $changeHash{'tools.'.$key};
 3353:                                 } else {
 3354:                                     $newenvhash{'environment.availabletools.'.$key} =
 3355:           &Apache::lonnet::usertools_access($env{'user.name'},$env{'user.domain'},
 3356:           $key,'reload','tools');
 3357:                                 }
 3358:                             }
 3359:                         }
 3360:                         if (keys(%newenvhash)) {
 3361:                             &Apache::lonnet::appenv(\%newenvhash);
 3362:                         }
 3363:                     }
 3364:                     if ($changed{'aboutme'}) {
 3365:                         &Apache::loncommon::devalidate_aboutme_cache($env{'form.ccuname'},
 3366:                                                                      $env{'form.ccdomain'});
 3367:                     }
 3368:                 }
 3369:             }
 3370:             if (keys(%namechanged) > 0) {
 3371:                 foreach my $field (@userinfo) {
 3372:                     $changeHash{$field}  = $env{'form.c'.$field};
 3373:                 }
 3374: # Make the change
 3375:                 $namechgresult =
 3376:                     &Apache::lonnet::modifyuser($env{'form.ccdomain'},
 3377:                         $env{'form.ccuname'},$changeHash{'id'},undef,undef,
 3378:                         $changeHash{'firstname'},$changeHash{'middlename'},
 3379:                         $changeHash{'lastname'},$changeHash{'generation'},
 3380:                         $changeHash{'id'},undef,$changeHash{'permanentemail'},undef,\@userinfo);
 3381:                 %userupdate = (
 3382:                                lastname   => $env{'form.clastname'},
 3383:                                middlename => $env{'form.cmiddlename'},
 3384:                                firstname  => $env{'form.cfirstname'},
 3385:                                generation => $env{'form.cgeneration'},
 3386:                                id         => $env{'form.cid'},
 3387:                              );
 3388:             }
 3389:             if (((keys(%namechanged) > 0) && $namechgresult eq 'ok') || 
 3390:                 ((keys(%changed) > 0) && $chgresult eq 'ok')) {
 3391:             # Tell the user we changed the name
 3392:                 &display_userinfo($r,1,\@disporder,\%canshow,\@requestcourses,
 3393:                                   \@usertools,\@requestauthor,\%userenv,\%changed,\%namechanged,
 3394:                                   \%oldsettings, \%oldsettingstext,\%newsettings,
 3395:                                   \%newsettingstext);
 3396:                 if ($env{'form.cid'} ne $userenv{'id'}) {
 3397:                     &Apache::lonnet::idput($env{'form.ccdomain'},
 3398:                          {$env{'form.ccuname'} => $env{'form.cid'}});
 3399:                     if (($recurseid) &&
 3400:                         (&Apache::lonnet::allowed('mau',$env{'form.ccdomain'}))) {
 3401:                         my $idresult = 
 3402:                             &Apache::lonuserutils::propagate_id_change(
 3403:                                 $env{'form.ccuname'},$env{'form.ccdomain'},
 3404:                                 \%userupdate);
 3405:                         $r->print('<br />'.$idresult.'<br />');
 3406:                     }
 3407:                 }
 3408:                 if (($env{'form.ccdomain'} eq $env{'user.domain'}) && 
 3409:                     ($env{'form.ccuname'} eq $env{'user.name'})) {
 3410:                     my %newenvhash;
 3411:                     foreach my $key (keys(%changeHash)) {
 3412:                         $newenvhash{'environment.'.$key} = $changeHash{$key};
 3413:                     }
 3414:                     &Apache::lonnet::appenv(\%newenvhash);
 3415:                 }
 3416:             } else { # error occurred
 3417:                 $r->print(
 3418:                     '<p class="LC_error">'
 3419:                    .&mt('Unable to successfully change environment for [_1] in domain [_2].',
 3420:                             '"'.$env{'form.ccuname'}.'"',
 3421:                             '"'.$env{'form.ccdomain'}.'"')
 3422:                    .'</p>');
 3423:             }
 3424:         } else { # End of if ($env ... ) logic
 3425:             # They did not want to change the users name, quota, tool availability,
 3426:             # or ability to request creation of courses, 
 3427:             # but we can still tell them what the name and quota and availabilities are  
 3428:             &display_userinfo($r,undef,\@disporder,\%canshow,\@requestcourses,
 3429:                               \@usertools,\@requestauthor,\%userenv,\%changed,\%namechanged,\%oldsettings,
 3430:                               \%oldsettingstext,\%newsettings,\%newsettingstext);
 3431:         }
 3432:         if (@mod_disallowed) {
 3433:             my ($rolestr,$contextname);
 3434:             if (@longroles > 0) {
 3435:                 $rolestr = join(', ',@longroles);
 3436:             } else {
 3437:                 $rolestr = &mt('No roles');
 3438:             }
 3439:             if ($context eq 'course') {
 3440:                 $contextname = 'course';
 3441:             } elsif ($context eq 'author') {
 3442:                 $contextname = 'co-author';
 3443:             }
 3444:             $r->print(&mt('The following fields were not updated: ').'<ul>');
 3445:             my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
 3446:             foreach my $field (@mod_disallowed) {
 3447:                 $r->print('<li>'.$fieldtitles{$field}.'</li>'."\n"); 
 3448:             }
 3449:             $r->print('</ul>');
 3450:             if (@mod_disallowed == 1) {
 3451:                 $r->print(&mt("You do not have the authority to change this field given the user's current set of active/future $contextname roles:"));
 3452:             } else {
 3453:                 $r->print(&mt("You do not have the authority to change these fields given the user's current set of active/future $contextname roles:"));
 3454:             }
 3455:             my $helplink = 'javascript:helpMenu('."'display'".')';
 3456:             $r->print('<span class="LC_cusr_emph">'.$rolestr.'</span><br />'
 3457:                      .&mt('Please contact your [_1]helpdesk[_2] for more information.'
 3458:                          ,'<a href="'.$helplink.'">','</a>')
 3459:                       .'<br />');
 3460:         }
 3461:         $r->print('<span class="LC_warning">'
 3462:                   .$no_forceid_alert
 3463:                   .&Apache::lonuserutils::print_namespacing_alerts($env{'form.ccdomain'},\%alerts,\%curr_rules)
 3464:                   .'</span>');
 3465:     }
 3466:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 3467:     if ($env{'form.action'} eq 'singlestudent') {
 3468:         &enroll_single_student($r,$uhome,$amode,$genpwd,$now,$newuser,$context,
 3469:                                $crstype,$showcredits,$defaultcredits);
 3470:         my $linktext = ($crstype eq 'Community' ?
 3471:             &mt('Enroll Another Member') : &mt('Enroll Another Student'));
 3472:         $r->print(
 3473:             &Apache::lonhtmlcommon::actionbox([
 3474:                 '<a href="javascript:backPage(document.userupdate)">'
 3475:                .($crstype eq 'Community' ? 
 3476:                     &mt('Enroll Another Member') : &mt('Enroll Another Student'))
 3477:                .'</a>']));
 3478:     } else {
 3479:         my @rolechanges = &update_roles($r,$context,$showcredits);
 3480:         if (keys(%namechanged) > 0) {
 3481:             if ($context eq 'course') {
 3482:                 if (@userroles > 0) {
 3483:                     if ((@rolechanges == 0) || 
 3484:                         (!(grep(/^st$/,@rolechanges)))) {
 3485:                         if (grep(/^st$/,@userroles)) {
 3486:                             my $classlistupdated =
 3487:                                 &Apache::lonuserutils::update_classlist($cdom,
 3488:                                               $cnum,$env{'form.ccdomain'},
 3489:                                        $env{'form.ccuname'},\%userupdate);
 3490:                         }
 3491:                     }
 3492:                 }
 3493:             }
 3494:         }
 3495:         my $userinfo = &Apache::loncommon::plainname($env{'form.ccuname'},
 3496:                                                      $env{'form.ccdomain'});
 3497:         if ($env{'form.popup'}) {
 3498:             $r->print('<p><a href="javascript:window.close()">'.&mt('Close window').'</a></p>');
 3499:         } else {
 3500:             $r->print('<br />'.&Apache::lonhtmlcommon::actionbox(['<a href="javascript:backPage(document.userupdate,'."'$env{'form.prevphase'}','modify'".')">'
 3501:                      .&mt('Modify this user: [_1]','<span class="LC_cusr_emph">'.$env{'form.ccuname'}.':'.$env{'form.ccdomain'}.' ('.$userinfo.')</span>').'</a>',
 3502:                      '<a href="javascript:backPage(document.userupdate)">'.&mt('Create/Modify Another User').'</a>']));
 3503:         }
 3504:     }
 3505: }
 3506: 
 3507: sub display_userinfo {
 3508:     my ($r,$changed,$order,$canshow,$requestcourses,$usertools,$requestauthor,
 3509:         $userenv,$changedhash,$namechangedhash,$oldsetting,$oldsettingtext,
 3510:         $newsetting,$newsettingtext) = @_;
 3511:     return unless (ref($order) eq 'ARRAY' &&
 3512:                    ref($canshow) eq 'HASH' && 
 3513:                    ref($requestcourses) eq 'ARRAY' && 
 3514:                    ref($requestauthor) eq 'ARRAY' &&
 3515:                    ref($usertools) eq 'ARRAY' && 
 3516:                    ref($userenv) eq 'HASH' &&
 3517:                    ref($changedhash) eq 'HASH' &&
 3518:                    ref($oldsetting) eq 'HASH' &&
 3519:                    ref($oldsettingtext) eq 'HASH' &&
 3520:                    ref($newsetting) eq 'HASH' &&
 3521:                    ref($newsettingtext) eq 'HASH');
 3522:     my %lt=&Apache::lonlocal::texthash(
 3523:          'ui'             => 'User Information',
 3524:          'uic'            => 'User Information Changed',
 3525:          'firstname'      => 'First Name',
 3526:          'middlename'     => 'Middle Name',
 3527:          'lastname'       => 'Last Name',
 3528:          'generation'     => 'Generation',
 3529:          'id'             => 'Student/Employee ID',
 3530:          'permanentemail' => 'Permanent e-mail address',
 3531:          'portfolioquota' => 'Disk space allocated to portfolio files',
 3532:          'authorquota'    => 'Disk space allocated to Authoring Space',
 3533:          'blog'           => 'Blog Availability',
 3534:          'webdav'         => 'WebDAV Availability',
 3535:          'aboutme'        => 'Personal Information Page Availability',
 3536:          'portfolio'      => 'Portfolio Availability',
 3537:          'timezone'       => 'Can set own Time Zone',
 3538:          'official'       => 'Can Request Official Courses',
 3539:          'unofficial'     => 'Can Request Unofficial Courses',
 3540:          'community'      => 'Can Request Communities',
 3541:          'textbook'       => 'Can Request Textbook Courses',
 3542:          'requestauthor'  => 'Can Request Author Role',
 3543:          'inststatus'     => "Affiliation",
 3544:          'prvs'           => 'Previous Value:',
 3545:          'chto'           => 'Changed To:'
 3546:     );
 3547:     if ($changed) {
 3548:         $r->print('<h3>'.$lt{'uic'}.'</h3>'.
 3549:                 &Apache::loncommon::start_data_table().
 3550:                 &Apache::loncommon::start_data_table_header_row());
 3551:         $r->print("<th>&nbsp;</th>\n");
 3552:         $r->print('<th><b>'.$lt{'prvs'}.'</b></th>');
 3553:         $r->print('<th><span class="LC_nobreak"><b>'.$lt{'chto'}.'</b></span></th>');
 3554:         $r->print(&Apache::loncommon::end_data_table_header_row());
 3555:         my @userinfo = ('firstname','middlename','lastname','generation','permanentemail','id');
 3556: 
 3557:         foreach my $item (@userinfo) {
 3558:             my $value = $env{'form.c'.$item};
 3559:             #show changes only:
 3560:             unless ($value eq $userenv->{$item}){
 3561:                 $r->print(&Apache::loncommon::start_data_table_row());
 3562:                 $r->print("<td>$lt{$item}</td>\n");
 3563:                 $r->print("<td>".$userenv->{$item}."</td>\n");
 3564:                 $r->print("<td>$value </td>\n");
 3565:                 $r->print(&Apache::loncommon::end_data_table_row());
 3566:             }
 3567:         }
 3568:         foreach my $entry (@{$order}) {
 3569:             if ($canshow->{$entry}) {
 3570:                 if (($entry eq 'requestcourses') || ($entry eq 'reqcrsotherdom') || ($entry eq 'requestauthor')) {
 3571:                     my @items;
 3572:                     if ($entry eq 'requestauthor') {
 3573:                         @items = ($entry);
 3574:                     } else {
 3575:                         @items = @{$requestcourses};
 3576:                     }
 3577:                     foreach my $item (@items) {
 3578:                         if (($newsetting->{$item} ne $oldsetting->{$item}) || 
 3579:                             ($newsettingtext->{$item} ne $oldsettingtext->{$item})) {
 3580:                             $r->print(&Apache::loncommon::start_data_table_row()."\n");  
 3581:                             $r->print("<td>$lt{$item}</td>\n");
 3582:                             $r->print("<td>".$oldsetting->{$item});
 3583:                             if ($oldsettingtext->{$item}) {
 3584:                                 if ($oldsetting->{$item}) {
 3585:                                     $r->print(' -- ');
 3586:                                 }
 3587:                                 $r->print($oldsettingtext->{$item});
 3588:                             }
 3589:                             $r->print("</td>\n");
 3590:                             $r->print("<td>".$newsetting->{$item});
 3591:                             if ($newsettingtext->{$item}) {
 3592:                                 if ($newsetting->{$item}) {
 3593:                                     $r->print(' -- ');
 3594:                                 }
 3595:                                 $r->print($newsettingtext->{$item});
 3596:                             }
 3597:                             $r->print("</td>\n");
 3598:                             $r->print(&Apache::loncommon::end_data_table_row()."\n");
 3599:                         }
 3600:                     }
 3601:                 } elsif ($entry eq 'tools') {
 3602:                     foreach my $item (@{$usertools}) {
 3603:                         if ($newsetting->{$item} ne $oldsetting->{$item}) {
 3604:                             $r->print(&Apache::loncommon::start_data_table_row()."\n");
 3605:                             $r->print("<td>$lt{$item}</td>\n");
 3606:                             $r->print("<td>".$oldsetting->{$item}.' '.$oldsettingtext->{$item}."</td>\n");
 3607:                             $r->print("<td>".$newsetting->{$item}.' '.$newsettingtext->{$item}."</td>\n");
 3608:                             $r->print(&Apache::loncommon::end_data_table_row()."\n");
 3609:                         }
 3610:                     }
 3611:                 } elsif ($entry eq 'quota') {
 3612:                     if ((ref($oldsetting->{$entry}) eq 'HASH') && (ref($oldsettingtext->{$entry}) eq 'HASH') &&
 3613:                         (ref($newsetting->{$entry}) eq 'HASH') && (ref($newsettingtext->{$entry}) eq 'HASH')) {
 3614:                         foreach my $name ('portfolio','author') {
 3615:                             if ($newsetting->{$entry}->{$name} ne $oldsetting->{$entry}->{$name}) {
 3616:                                 $r->print(&Apache::loncommon::start_data_table_row()."\n");
 3617:                                 $r->print("<td>$lt{$name.$entry}</td>\n");
 3618:                                 $r->print("<td>".$oldsettingtext->{$entry}->{$name}."</td>\n");
 3619:                                 $r->print("<td>".$newsettingtext->{$entry}->{$name}."</td>\n");
 3620:                                 $r->print(&Apache::loncommon::end_data_table_row()."\n");
 3621:                             }
 3622:                         }
 3623:                     }
 3624:                 } else {
 3625:                     if ($newsetting->{$entry} ne $oldsetting->{$entry}) {
 3626:                         $r->print(&Apache::loncommon::start_data_table_row()."\n");
 3627:                         $r->print("<td>$lt{$entry}</td>\n");
 3628:                         $r->print("<td>".$oldsetting->{$entry}.' '.$oldsettingtext->{$entry}."</td>\n");
 3629:                         $r->print("<td>".$newsetting->{$entry}.' '.$newsettingtext->{$entry}."</td>\n");
 3630:                         $r->print(&Apache::loncommon::end_data_table_row()."\n");
 3631:                     }
 3632:                 }
 3633:             }
 3634:         }
 3635:         $r->print(&Apache::loncommon::end_data_table().'<br />');
 3636:     } else {
 3637:         $r->print('<h3>'.$lt{'ui'}.'</h3>'.
 3638:                   '<p>'.&mt('No changes made to user information').'</p>');
 3639:     }
 3640:     return;
 3641: }
 3642: 
 3643: sub tool_changes {
 3644:     my ($context,$usertools,$oldaccess,$oldaccesstext,$userenv,$changeHash,
 3645:         $changed,$newaccess,$newaccesstext) = @_;
 3646:     if (!((ref($usertools) eq 'ARRAY') && (ref($oldaccess) eq 'HASH') &&
 3647:           (ref($oldaccesstext) eq 'HASH') && (ref($userenv) eq 'HASH') &&
 3648:           (ref($changeHash) eq 'HASH') && (ref($changed) eq 'HASH') &&
 3649:           (ref($newaccess) eq 'HASH') && (ref($newaccesstext) eq 'HASH'))) {
 3650:         return;
 3651:     }
 3652:     my %reqdisplay = &requestchange_display();
 3653:     if ($context eq 'reqcrsotherdom') {
 3654:         my @options = ('approval','validate','autolimit');
 3655:         my $optregex = join('|',@options);
 3656:         my $cdom = $env{'request.role.domain'};
 3657:         foreach my $tool (@{$usertools}) {
 3658:             $oldaccesstext->{$tool} = &mt("availability set to 'off'");
 3659:             $newaccesstext->{$tool} = $oldaccesstext->{$tool};
 3660:             $changeHash->{$context.'.'.$tool} = $userenv->{$context.'.'.$tool};
 3661:             my ($newop,$limit);
 3662:             if ($env{'form.'.$context.'_'.$tool}) {
 3663:                 $newop = $env{'form.'.$context.'_'.$tool};
 3664:                 if ($newop eq 'autolimit') {
 3665:                     $limit = $env{'form.'.$context.'_'.$tool.'_limit'};
 3666:                     $limit =~ s/\D+//g;
 3667:                     $newop .= '='.$limit;
 3668:                 }
 3669:             }
 3670:             if ($userenv->{$context.'.'.$tool} eq '') {
 3671:                 if ($newop) {
 3672:                     $changed->{$tool}=&tool_admin($tool,$cdom.':'.$newop,
 3673:                                                   $changeHash,$context);
 3674:                     if ($changed->{$tool}) {
 3675:                         if ($newop =~ /^autolimit/) {
 3676:                             if ($limit) {
 3677:                                 $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3678:                             } else {
 3679:                                 $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3680:                             }
 3681:                         } else {
 3682:                             $newaccesstext->{$tool} = $reqdisplay{$newop};
 3683:                         }
 3684:                     } else {
 3685:                         $newaccesstext->{$tool} = $oldaccesstext->{$tool};
 3686:                     }
 3687:                 }
 3688:             } else {
 3689:                 my @curr = split(',',$userenv->{$context.'.'.$tool});
 3690:                 my @new;
 3691:                 my $changedoms;
 3692:                 foreach my $req (@curr) {
 3693:                     if ($req =~ /^\Q$cdom\E\:($optregex\=?\d*)$/) {
 3694:                         my $oldop = $1;
 3695:                         if ($oldop =~ /^autolimit=(\d*)/) {
 3696:                             my $limit = $1;
 3697:                             if ($limit) {
 3698:                                 $oldaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3699:                             } else {
 3700:                                 $oldaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3701:                             }
 3702:                         } else {
 3703:                             $oldaccesstext->{$tool} = $reqdisplay{$oldop};
 3704:                         }
 3705:                         if ($oldop ne $newop) {
 3706:                             $changedoms = 1;
 3707:                             foreach my $item (@curr) {
 3708:                                 my ($reqdom,$option) = split(':',$item);
 3709:                                 unless ($reqdom eq $cdom) {
 3710:                                     push(@new,$item);
 3711:                                 }
 3712:                             }
 3713:                             if ($newop) {
 3714:                                 push(@new,$cdom.':'.$newop);
 3715:                             }
 3716:                             @new = sort(@new);
 3717:                         }
 3718:                         last;
 3719:                     }
 3720:                 }
 3721:                 if ((!$changedoms) && ($newop)) {
 3722:                     $changedoms = 1;
 3723:                     @new = sort(@curr,$cdom.':'.$newop);
 3724:                 }
 3725:                 if ($changedoms) {
 3726:                     my $newdomstr;
 3727:                     if (@new) {
 3728:                         $newdomstr = join(',',@new);
 3729:                     }
 3730:                     $changed->{$tool}=&tool_admin($tool,$newdomstr,$changeHash,
 3731:                                                   $context);
 3732:                     if ($changed->{$tool}) {
 3733:                         if ($env{'form.'.$context.'_'.$tool}) {
 3734:                             if ($env{'form.'.$context.'_'.$tool} eq 'autolimit') {
 3735:                                 my $limit = $env{'form.'.$context.'_'.$tool.'_limit'};
 3736:                                 $limit =~ s/\D+//g;
 3737:                                 if ($limit) {
 3738:                                     $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3739:                                 } else {
 3740:                                     $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3741:                                 }
 3742:                             } else {
 3743:                                 $newaccesstext->{$tool} = $reqdisplay{$env{'form.'.$context.'_'.$tool}};
 3744:                             }
 3745:                         } else {
 3746:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3747:                         }
 3748:                     }
 3749:                 }
 3750:             }
 3751:         }
 3752:         return;
 3753:     }
 3754:     foreach my $tool (@{$usertools}) {
 3755:         my ($newval,$limit,$envkey);
 3756:         $envkey = $context.'.'.$tool;
 3757:         if ($context eq 'requestcourses') {
 3758:             $newval = $env{'form.crsreq_'.$tool};
 3759:             if ($newval eq 'autolimit') {
 3760:                 $limit = $env{'form.crsreq_'.$tool.'_limit'};
 3761:                 $limit =~ s/\D+//g;
 3762:                 $newval .= '='.$limit;
 3763:             }
 3764:         } elsif ($context eq 'requestauthor') {
 3765:             $newval = $env{'form.'.$context};
 3766:             $envkey = $context;
 3767:         } else {
 3768:             $newval = $env{'form.'.$context.'_'.$tool};
 3769:         }
 3770:         if ($userenv->{$envkey} ne '') {
 3771:             $oldaccess->{$tool} = &mt('custom');
 3772:             if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 3773:                 if ($userenv->{$envkey} =~ /^autolimit=(\d*)$/) {
 3774:                     my $currlimit = $1;
 3775:                     if ($currlimit eq '') {
 3776:                         $oldaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3777:                     } else {
 3778:                         $oldaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$currlimit);
 3779:                     }
 3780:                 } elsif ($userenv->{$envkey}) {
 3781:                     $oldaccesstext->{$tool} = $reqdisplay{$userenv->{$envkey}};
 3782:                 } else {
 3783:                     $oldaccesstext->{$tool} = &mt("availability set to 'off'");
 3784:                 }
 3785:             } else {
 3786:                 if ($userenv->{$envkey}) {
 3787:                     $oldaccesstext->{$tool} = &mt("availability set to 'on'");
 3788:                 } else {
 3789:                     $oldaccesstext->{$tool} = &mt("availability set to 'off'");
 3790:                 }
 3791:             }
 3792:             $changeHash->{$envkey} = $userenv->{$envkey};
 3793:             if ($env{'form.custom'.$tool} == 1) {
 3794:                 if ($newval ne $userenv->{$envkey}) {
 3795:                     $changed->{$tool} = &tool_admin($tool,$newval,$changeHash,
 3796:                                                     $context);
 3797:                     if ($changed->{$tool}) {
 3798:                         $newaccess->{$tool} = &mt('custom');
 3799:                         if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 3800:                             if ($newval =~ /^autolimit/) {
 3801:                                 if ($limit) {
 3802:                                     $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3803:                                 } else {
 3804:                                     $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3805:                                 }
 3806:                             } elsif ($newval) {
 3807:                                 $newaccesstext->{$tool} = $reqdisplay{$newval};
 3808:                             } else {
 3809:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3810:                             }
 3811:                         } else {
 3812:                             if ($newval) {
 3813:                                 $newaccesstext->{$tool} = &mt("availability set to 'on'");
 3814:                             } else {
 3815:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3816:                             }
 3817:                         }
 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:                 } else {
 3841:                     $newaccess->{$tool} = $oldaccess->{$tool};
 3842:                     $newaccesstext->{$tool} = $oldaccesstext->{$tool};
 3843:                 }
 3844:             } else {
 3845:                 $changed->{$tool} = &tool_admin($tool,'',$changeHash,$context);
 3846:                 if ($changed->{$tool}) {
 3847:                     $newaccess->{$tool} = &mt('default');
 3848:                 } else {
 3849:                     $newaccess->{$tool} = $oldaccess->{$tool};
 3850:                     if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 3851:                         if ($newval =~ /^autolimit/) {
 3852:                             if ($limit) {
 3853:                                 $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3854:                             } else {
 3855:                                 $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3856:                             }
 3857:                         } elsif ($newval) {
 3858:                             $newaccesstext->{$tool} = $reqdisplay{$newval};
 3859:                         } else {
 3860:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3861:                         }
 3862:                     } else {
 3863:                         if ($userenv->{$context.'.'.$tool}) {
 3864:                             $newaccesstext->{$tool} = &mt("availability set to 'on'");
 3865:                         } else {
 3866:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3867:                         }
 3868:                     }
 3869:                 }
 3870:             }
 3871:         } else {
 3872:             $oldaccess->{$tool} = &mt('default');
 3873:             if ($env{'form.custom'.$tool} == 1) {
 3874:                 $changed->{$tool} = &tool_admin($tool,$newval,$changeHash,
 3875:                                                 $context);
 3876:                 if ($changed->{$tool}) {
 3877:                     $newaccess->{$tool} = &mt('custom');
 3878:                     if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 3879:                         if ($newval =~ /^autolimit/) {
 3880:                             if ($limit) {
 3881:                                 $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3882:                             } else {
 3883:                                 $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3884:                             }
 3885:                         } elsif ($newval) {
 3886:                             $newaccesstext->{$tool} = $reqdisplay{$newval};
 3887:                         } else {
 3888:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3889:                         }
 3890:                     } else {
 3891:                         if ($newval) {
 3892:                             $newaccesstext->{$tool} = &mt("availability set to 'on'");
 3893:                         } else {
 3894:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3895:                         }
 3896:                     }
 3897:                 } else {
 3898:                     $newaccess->{$tool} = $oldaccess->{$tool};
 3899:                 }
 3900:             } else {
 3901:                 $newaccess->{$tool} = $oldaccess->{$tool};
 3902:             }
 3903:         }
 3904:     }
 3905:     return;
 3906: }
 3907: 
 3908: sub update_roles {
 3909:     my ($r,$context,$showcredits) = @_;
 3910:     my $now=time;
 3911:     my @rolechanges;
 3912:     my %disallowed;
 3913:     $r->print('<h3>'.&mt('Modifying Roles').'</h3>');
 3914:     foreach my $key (keys(%env)) {
 3915: 	next if (! $env{$key});
 3916:         next if ($key eq 'form.action');
 3917: 	# Revoke roles
 3918: 	if ($key=~/^form\.rev/) {
 3919: 	    if ($key=~/^form\.rev\:([^\_]+)\_([^\_\.]+)$/) {
 3920: # Revoke standard role
 3921: 		my ($scope,$role) = ($1,$2);
 3922: 		my $result =
 3923: 		    &Apache::lonnet::revokerole($env{'form.ccdomain'},
 3924: 						$env{'form.ccuname'},
 3925: 						$scope,$role,'','',$context);
 3926:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
 3927:                             &mt('Revoking [_1] in [_2]',
 3928:                                 &Apache::lonnet::plaintext($role),
 3929:                                 &Apache::loncommon::show_role_extent($scope,$context,$role)),
 3930:                                 $result ne "ok").'<br />');
 3931:                 if ($result ne "ok") {
 3932:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 3933:                 }
 3934: 		if ($role eq 'st') {
 3935: 		    my $result = 
 3936:                         &Apache::lonuserutils::classlist_drop($scope,
 3937:                             $env{'form.ccuname'},$env{'form.ccdomain'},
 3938: 			    $now);
 3939:                     $r->print(&Apache::lonhtmlcommon::confirm_success($result));
 3940: 		}
 3941:                 if (!grep(/^\Q$role\E$/,@rolechanges)) {
 3942:                     push(@rolechanges,$role);
 3943:                 }
 3944: 	    }
 3945: 	    if ($key=~m{^form\.rev\:([^_]+)_cr\.cr/($match_domain)/($match_username)/(\w+)$}s) {
 3946: # Revoke custom role
 3947:                 my $result = &Apache::lonnet::revokecustomrole(
 3948:                     $env{'form.ccdomain'},$env{'form.ccuname'},$1,$2,$3,$4,'','',$context);
 3949:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
 3950:                             &mt('Revoking custom role [_1] by [_2] in [_3]',
 3951:                                 $4,$3.':'.$2,&Apache::loncommon::show_role_extent($1,$context,'cr')),
 3952:                             $result ne 'ok').'<br />');
 3953:                 if ($result ne "ok") {
 3954:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 3955:                 }
 3956:                 if (!grep(/^cr$/,@rolechanges)) {
 3957:                     push(@rolechanges,'cr');
 3958:                 }
 3959: 	    }
 3960: 	} elsif ($key=~/^form\.del/) {
 3961: 	    if ($key=~/^form\.del\:([^\_]+)\_([^\_\.]+)$/) {
 3962: # Delete standard role
 3963: 		my ($scope,$role) = ($1,$2);
 3964: 		my $result =
 3965: 		    &Apache::lonnet::assignrole($env{'form.ccdomain'},
 3966: 						$env{'form.ccuname'},
 3967: 						$scope,$role,$now,0,1,'',
 3968:                                                 $context);
 3969:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
 3970:                             &mt('Deleting [_1] in [_2]',
 3971:                                 &Apache::lonnet::plaintext($role),
 3972:                                 &Apache::loncommon::show_role_extent($scope,$context,$role)),
 3973:                             $result ne 'ok').'<br />');
 3974:                 if ($result ne "ok") {
 3975:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 3976:                 }
 3977: 
 3978: 		if ($role eq 'st') {
 3979: 		    my $result = 
 3980:                         &Apache::lonuserutils::classlist_drop($scope,
 3981:                             $env{'form.ccuname'},$env{'form.ccdomain'},
 3982: 			    $now);
 3983: 		    $r->print(&Apache::lonhtmlcommon::confirm_success($result));
 3984: 		}
 3985:                 if (!grep(/^\Q$role\E$/,@rolechanges)) {
 3986:                     push(@rolechanges,$role);
 3987:                 }
 3988:             }
 3989: 	    if ($key=~m{^form\.del\:([^_]+)_cr\.cr/($match_domain)/($match_username)/(\w+)$}) {
 3990:                 my ($url,$rdom,$rnam,$rolename) = ($1,$2,$3,$4);
 3991: # Delete custom role
 3992:                 my $result =
 3993:                     &Apache::lonnet::assigncustomrole($env{'form.ccdomain'},
 3994:                         $env{'form.ccuname'},$url,$rdom,$rnam,$rolename,$now,
 3995:                         0,1,$context);
 3996:                 $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('Deleting custom role [_1] by [_2] in [_3]',
 3997:                       $rolename,$rnam.':'.$rdom,&Apache::loncommon::show_role_extent($1,$context,'cr')),
 3998:                       $result ne "ok").'<br />');
 3999:                 if ($result ne "ok") {
 4000:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 4001:                 }
 4002: 
 4003:                 if (!grep(/^cr$/,@rolechanges)) {
 4004:                     push(@rolechanges,'cr');
 4005:                 }
 4006:             }
 4007: 	} elsif ($key=~/^form\.ren/) {
 4008:             my $udom = $env{'form.ccdomain'};
 4009:             my $uname = $env{'form.ccuname'};
 4010: # Re-enable standard role
 4011: 	    if ($key=~/^form\.ren\:([^\_]+)\_([^\_\.]+)$/) {
 4012:                 my $url = $1;
 4013:                 my $role = $2;
 4014:                 my $logmsg;
 4015:                 my $output;
 4016:                 if ($role eq 'st') {
 4017:                     if ($url =~ m-^/($match_domain)/($match_courseid)/?(\w*)$-) {
 4018:                         my ($cdom,$cnum,$csec) = ($1,$2,$3);
 4019:                         my $credits;
 4020:                         if ($showcredits) {
 4021:                             my $defaultcredits = 
 4022:                                 &Apache::lonuserutils::get_defaultcredits($cdom,$cnum);
 4023:                             $credits = &get_user_credits($defaultcredits,$cdom,$cnum);
 4024:                         }
 4025:                         my $result = &Apache::loncommon::commit_studentrole(\$logmsg,$udom,$uname,$url,$role,$now,0,$cdom,$cnum,$csec,$context,$credits);
 4026:                         if (($result =~ /^error/) || ($result eq 'not_in_class') || ($result eq 'unknown_course') || ($result eq 'refused')) {
 4027:                             if ($result eq 'refused' && $logmsg) {
 4028:                                 $output = $logmsg;
 4029:                             } else { 
 4030:                                 $output = &mt('Error: [_1]',$result)."\n";
 4031:                             }
 4032:                         } else {
 4033:                             $output = &Apache::lonhtmlcommon::confirm_success(&mt('Assigning [_1] in [_2] starting [_3]',
 4034:                                         &Apache::lonnet::plaintext($role),
 4035:                                         &Apache::loncommon::show_role_extent($url,$context,'st'),
 4036:                                         &Apache::lonlocal::locallocaltime($now))).'<br />'.$logmsg.'<br />';
 4037:                         }
 4038:                     }
 4039:                 } else {
 4040: 		    my $result=&Apache::lonnet::assignrole($env{'form.ccdomain'},
 4041:                                $env{'form.ccuname'},$url,$role,0,$now,'','',
 4042:                                $context);
 4043:                         $output = &Apache::lonhtmlcommon::confirm_success(&mt('Re-enabling [_1] in [_2]',
 4044:                                         &Apache::lonnet::plaintext($role),
 4045:                                         &Apache::loncommon::show_role_extent($url,$context,$role)),$result ne "ok").'<br />';
 4046:                     if ($result ne "ok") {
 4047:                         $output .= &mt('Error: [_1]',$result).'<br />';
 4048:                     }
 4049:                 }
 4050:                 $r->print($output);
 4051:                 if (!grep(/^\Q$role\E$/,@rolechanges)) {
 4052:                     push(@rolechanges,$role);
 4053:                 }
 4054: 	    }
 4055: # Re-enable custom role
 4056: 	    if ($key=~m{^form\.ren\:([^_]+)_cr\.cr/($match_domain)/($match_username)/(\w+)$}) {
 4057:                 my ($url,$rdom,$rnam,$rolename) = ($1,$2,$3,$4);
 4058:                 my $result = &Apache::lonnet::assigncustomrole(
 4059:                                $env{'form.ccdomain'}, $env{'form.ccuname'},
 4060:                                $url,$rdom,$rnam,$rolename,0,$now,undef,$context);
 4061:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
 4062:                     &mt('Re-enabling custom role [_1] by [_2] in [_3]',
 4063:                         $rolename,$rnam.':'.$rdom,&Apache::loncommon::show_role_extent($1,$context,'cr')),
 4064:                     $result ne "ok").'<br />');
 4065:                 if ($result ne "ok") {
 4066:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 4067:                 }
 4068:                 if (!grep(/^cr$/,@rolechanges)) {
 4069:                     push(@rolechanges,'cr');
 4070:                 }
 4071:             }
 4072: 	} elsif ($key=~/^form\.act/) {
 4073:             my $udom = $env{'form.ccdomain'};
 4074:             my $uname = $env{'form.ccuname'};
 4075: 	    if ($key=~/^form\.act\_($match_domain)\_($match_courseid)\_cr_cr_($match_domain)_($match_username)_([^\_]+)$/) {
 4076:                 # Activate a custom role
 4077: 		my ($one,$two,$three,$four,$five)=($1,$2,$3,$4,$5);
 4078: 		my $url='/'.$one.'/'.$two;
 4079: 		my $full=$one.'_'.$two.'_cr_cr_'.$three.'_'.$four.'_'.$five;
 4080: 
 4081:                 my $start = ( $env{'form.start_'.$full} ?
 4082:                               $env{'form.start_'.$full} :
 4083:                               $now );
 4084:                 my $end   = ( $env{'form.end_'.$full} ?
 4085:                               $env{'form.end_'.$full} :
 4086:                               0 );
 4087:                                                                                      
 4088:                 # split multiple sections
 4089:                 my %sections = ();
 4090:                 my $num_sections = &build_roles($env{'form.sec_'.$full},\%sections,$5);
 4091:                 if ($num_sections == 0) {
 4092:                     $r->print(&Apache::loncommon::commit_customrole($udom,$uname,$url,$three,$four,$five,$start,$end,$context));
 4093:                 } else {
 4094: 		    my %curr_groups =
 4095: 			&Apache::longroup::coursegroups($one,$two);
 4096:                     foreach my $sec (sort {$a cmp $b} keys(%sections)) {
 4097:                         if (($sec eq 'none') || ($sec eq 'all') || 
 4098:                             exists($curr_groups{$sec})) {
 4099:                             $disallowed{$sec} = $url;
 4100:                             next;
 4101:                         }
 4102:                         my $securl = $url.'/'.$sec;
 4103: 		        $r->print(&Apache::loncommon::commit_customrole($udom,$uname,$securl,$three,$four,$five,$start,$end,$context));
 4104:                     }
 4105:                 }
 4106:                 if (!grep(/^cr$/,@rolechanges)) {
 4107:                     push(@rolechanges,'cr');
 4108:                 }
 4109: 	    } elsif ($key=~/^form\.act\_($match_domain)\_($match_name)\_([^\_]+)$/) {
 4110: 		# Activate roles for sections with 3 id numbers
 4111: 		# set start, end times, and the url for the class
 4112: 		my ($one,$two,$three)=($1,$2,$3);
 4113: 		my $start = ( $env{'form.start_'.$one.'_'.$two.'_'.$three} ? 
 4114: 			      $env{'form.start_'.$one.'_'.$two.'_'.$three} : 
 4115: 			      $now );
 4116: 		my $end   = ( $env{'form.end_'.$one.'_'.$two.'_'.$three} ? 
 4117: 			      $env{'form.end_'.$one.'_'.$two.'_'.$three} :
 4118: 			      0 );
 4119: 		my $url='/'.$one.'/'.$two;
 4120:                 my $type = 'three';
 4121:                 # split multiple sections
 4122:                 my %sections = ();
 4123:                 my $num_sections = &build_roles($env{'form.sec_'.$one.'_'.$two.'_'.$three},\%sections,$three);
 4124:                 my $credits;
 4125:                 if ($three eq 'st') {
 4126:                     if ($showcredits) { 
 4127:                         my $defaultcredits = 
 4128:                             &Apache::lonuserutils::get_defaultcredits($one,$two);
 4129:                         $credits = $env{'form.credits_'.$one.'_'.$two.'_'.$three};
 4130:                         $credits =~ s/[^\d\.]//g;
 4131:                         if ($credits eq $defaultcredits) {
 4132:                             undef($credits);
 4133:                         }
 4134:                     }
 4135:                 }
 4136:                 if ($num_sections == 0) {
 4137:                     $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$three,$start,$end,$one,$two,'',$context,$credits));
 4138:                 } else {
 4139:                     my %curr_groups = 
 4140: 			&Apache::longroup::coursegroups($one,$two);
 4141:                     my $emptysec = 0;
 4142:                     foreach my $sec (sort {$a cmp $b} keys(%sections)) {
 4143:                         $sec =~ s/\W//g;
 4144:                         if ($sec ne '') {
 4145:                             if (($sec eq 'none') || ($sec eq 'all') || 
 4146:                                 exists($curr_groups{$sec})) {
 4147:                                 $disallowed{$sec} = $url;
 4148:                                 next;
 4149:                             }
 4150:                             my $securl = $url.'/'.$sec;
 4151:                             $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$securl,$three,$start,$end,$one,$two,$sec,$context,$credits));
 4152:                         } else {
 4153:                             $emptysec = 1;
 4154:                         }
 4155:                     }
 4156:                     if ($emptysec) {
 4157:                         $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$three,$start,$end,$one,$two,'',$context,$credits));
 4158:                     }
 4159:                 }
 4160:                 if (!grep(/^\Q$three\E$/,@rolechanges)) {
 4161:                     push(@rolechanges,$three);
 4162:                 }
 4163: 	    } elsif ($key=~/^form\.act\_([^\_]+)\_([^\_]+)$/) {
 4164: 		# Activate roles for sections with two id numbers
 4165: 		# set start, end times, and the url for the class
 4166: 		my $start = ( $env{'form.start_'.$1.'_'.$2} ? 
 4167: 			      $env{'form.start_'.$1.'_'.$2} : 
 4168: 			      $now );
 4169: 		my $end   = ( $env{'form.end_'.$1.'_'.$2} ? 
 4170: 			      $env{'form.end_'.$1.'_'.$2} :
 4171: 			      0 );
 4172:                 my $one = $1;
 4173:                 my $two = $2;
 4174: 		my $url='/'.$one.'/';
 4175:                 # split multiple sections
 4176:                 my %sections = ();
 4177:                 my $num_sections = &build_roles($env{'form.sec_'.$one.'_'.$two},\%sections,$two);
 4178:                 if ($num_sections == 0) {
 4179:                     $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$two,$start,$end,$one,undef,'',$context));
 4180:                 } else {
 4181:                     my $emptysec = 0;
 4182:                     foreach my $sec (sort {$a cmp $b} keys(%sections)) {
 4183:                         if ($sec ne '') {
 4184:                             my $securl = $url.'/'.$sec;
 4185:                             $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$securl,$two,$start,$end,$one,undef,$sec,$context));
 4186:                         } else {
 4187:                             $emptysec = 1;
 4188:                         }
 4189:                     }
 4190:                     if ($emptysec) {
 4191:                         $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$two,$start,$end,$one,undef,'',$context));
 4192:                     }
 4193:                 }
 4194:                 if (!grep(/^\Q$two\E$/,@rolechanges)) {
 4195:                     push(@rolechanges,$two);
 4196:                 }
 4197: 	    } else {
 4198: 		$r->print('<p><span class="LC_error">'.&mt('ERROR').': '.&mt('Unknown command').' <tt>'.$key.'</tt></span></p><br />');
 4199:             }
 4200:             foreach my $key (sort(keys(%disallowed))) {
 4201:                 $r->print('<p class="LC_warning">');
 4202:                 if (($key eq 'none') || ($key eq 'all')) {  
 4203:                     $r->print(&mt('[_1] may not be used as the name for a section, as it is a reserved word.','<tt>'.$key.'</tt>'));
 4204:                 } else {
 4205:                     $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>'));
 4206:                 }
 4207:                 $r->print('</p><p>'
 4208:                          .&mt('Please [_1]go back[_2] and choose a different section name.'
 4209:                              ,'<a href="javascript:history.go(-1)'
 4210:                              ,'</a>')
 4211:                          .'</p><br />'
 4212:                 );
 4213:             }
 4214: 	}
 4215:     } # End of foreach (keys(%env))
 4216: # Flush the course logs so reverse user roles immediately updated
 4217:     $r->register_cleanup(\&Apache::lonnet::flushcourselogs);
 4218:     if (@rolechanges == 0) {
 4219:         $r->print('<p>'.&mt('No roles to modify').'</p>');
 4220:     }
 4221:     return @rolechanges;
 4222: }
 4223: 
 4224: sub get_user_credits {
 4225:     my ($uname,$udom,$defaultcredits,$cdom,$cnum) = @_;
 4226:     if ($cdom eq '' || $cnum eq '') {
 4227:         return unless ($env{'request.course.id'});
 4228:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4229:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4230:     }
 4231:     my $credits;
 4232:     my %currhash =
 4233:         &Apache::lonnet::get('classlist',[$uname.':'.$udom],$cdom,$cnum);
 4234:     if (keys(%currhash) > 0) {
 4235:         my @items = split(/:/,$currhash{$uname.':'.$udom});
 4236:         my $crdidx = &Apache::loncoursedata::CL_CREDITS() - 3;
 4237:         $credits = $items[$crdidx];
 4238:         $credits =~ s/[^\d\.]//g;
 4239:     }
 4240:     if ($credits eq $defaultcredits) {
 4241:         undef($credits);
 4242:     }
 4243:     return $credits;
 4244: }
 4245: 
 4246: sub enroll_single_student {
 4247:     my ($r,$uhome,$amode,$genpwd,$now,$newuser,$context,$crstype,
 4248:         $showcredits,$defaultcredits) = @_;
 4249:     $r->print('<h3>');
 4250:     if ($crstype eq 'Community') {
 4251:         $r->print(&mt('Enrolling Member'));
 4252:     } else {
 4253:         $r->print(&mt('Enrolling Student'));
 4254:     }
 4255:     $r->print('</h3>');
 4256: 
 4257:     # Remove non alphanumeric values from section
 4258:     $env{'form.sections'}=~s/\W//g;
 4259: 
 4260:     my $credits;
 4261:     if (($showcredits) && ($env{'form.credits'} ne '')) {
 4262:         $credits = $env{'form.credits'};
 4263:         $credits =~ s/[^\d\.]//g;
 4264:         if ($credits ne '') {
 4265:             if ($credits eq $defaultcredits) {
 4266:                 undef($credits);
 4267:             }
 4268:         }
 4269:     }
 4270: 
 4271:     # Clean out any old student roles the user has in this class.
 4272:     &Apache::lonuserutils::modifystudent($env{'form.ccdomain'},
 4273:          $env{'form.ccuname'},$env{'request.course.id'},undef,$uhome);
 4274:     my ($startdate,$enddate) = &Apache::lonuserutils::get_dates_from_form();
 4275:     my $enroll_result =
 4276:         &Apache::lonnet::modify_student_enrollment($env{'form.ccdomain'},
 4277:             $env{'form.ccuname'},$env{'form.cid'},$env{'form.cfirstname'},
 4278:             $env{'form.cmiddlename'},$env{'form.clastname'},
 4279:             $env{'form.generation'},$env{'form.sections'},$enddate,
 4280:             $startdate,'manual',undef,$env{'request.course.id'},'',$context,
 4281:             $credits);
 4282:     if ($enroll_result =~ /^ok/) {
 4283:         $r->print(&mt('[_1] enrolled','<b>'.$env{'form.ccuname'}.':'.$env{'form.ccdomain'}.'</b>'));
 4284:         if ($env{'form.sections'} ne '') {
 4285:             $r->print(' '.&mt('in section [_1]',$env{'form.sections'}));
 4286:         }
 4287:         my ($showstart,$showend);
 4288:         if ($startdate <= $now) {
 4289:             $showstart = &mt('Access starts immediately');
 4290:         } else {
 4291:             $showstart = &mt('Access starts: ').&Apache::lonlocal::locallocaltime($startdate);
 4292:         }
 4293:         if ($enddate == 0) {
 4294:             $showend = &mt('ends: no ending date');
 4295:         } else {
 4296:             $showend = &mt('ends: ').&Apache::lonlocal::locallocaltime($enddate);
 4297:         }
 4298:         $r->print('.<br />'.$showstart.'; '.$showend);
 4299:         if ($startdate <= $now && !$newuser) {
 4300:             $r->print('<p class="LC_info">');
 4301:             if ($crstype eq 'Community') {
 4302:                 $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.'));
 4303:             } else {
 4304:                 $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.'));
 4305:            }
 4306:            $r->print('</p>');
 4307:         }
 4308:     } else {
 4309:         $r->print(&mt('unable to enroll').": ".$enroll_result);
 4310:     }
 4311:     return;
 4312: }
 4313: 
 4314: sub get_defaultquota_text {
 4315:     my ($settingstatus) = @_;
 4316:     my $defquotatext; 
 4317:     if ($settingstatus eq '') {
 4318:         $defquotatext = &mt('default');
 4319:     } else {
 4320:         my ($usertypes,$order) =
 4321:             &Apache::lonnet::retrieve_inst_usertypes($env{'form.ccdomain'});
 4322:         if ($usertypes->{$settingstatus} eq '') {
 4323:             $defquotatext = &mt('default');
 4324:         } else {
 4325:             $defquotatext = &mt('default for [_1]',$usertypes->{$settingstatus});
 4326:         }
 4327:     }
 4328:     return $defquotatext;
 4329: }
 4330: 
 4331: sub update_result_form {
 4332:     my ($uhome) = @_;
 4333:     my $outcome = 
 4334:     '<form name="userupdate" method="post" action="">'."\n";
 4335:     foreach my $item ('srchby','srchin','srchtype','srchterm','srchdomain','ccuname','ccdomain') {
 4336:         $outcome .= '<input type="hidden" name="'.$item.'" value="'.$env{'form.'.$item}.'" />'."\n";
 4337:     }
 4338:     if ($env{'form.origname'} ne '') {
 4339:         $outcome .= '<input type="hidden" name="origname" value="'.$env{'form.origname'}.'" />'."\n";
 4340:     }
 4341:     foreach my $item ('sortby','seluname','seludom') {
 4342:         if (exists($env{'form.'.$item})) {
 4343:             $outcome .= '<input type="hidden" name="'.$item.'" value="'.$env{'form.'.$item}.'" />'."\n";
 4344:         }
 4345:     }
 4346:     if ($uhome eq 'no_host') {
 4347:         $outcome .= '<input type="hidden" name="forcenewuser" value="1" />'."\n";
 4348:     }
 4349:     $outcome .= '<input type="hidden" name="phase" value="" />'."\n".
 4350:                 '<input type="hidden" name="currstate" value="" />'."\n".
 4351:                 '<input type="hidden" name="action" value="'.$env{'form.action'}.'" />'."\n".
 4352:                 '</form>';
 4353:     return $outcome;
 4354: }
 4355: 
 4356: sub quota_admin {
 4357:     my ($setquota,$changeHash,$name) = @_;
 4358:     my $quotachanged;
 4359:     if (&Apache::lonnet::allowed('mpq',$env{'form.ccdomain'})) {
 4360:         # Current user has quota modification privileges
 4361:         if (ref($changeHash) eq 'HASH') {
 4362:             $quotachanged = 1;
 4363:             $changeHash->{$name.'quota'} = $setquota;
 4364:         }
 4365:     }
 4366:     return $quotachanged;
 4367: }
 4368: 
 4369: sub tool_admin {
 4370:     my ($tool,$settool,$changeHash,$context) = @_;
 4371:     my $canchange = 0; 
 4372:     if ($context eq 'requestcourses') {
 4373:         if (&Apache::lonnet::allowed('ccc',$env{'form.ccdomain'})) {
 4374:             $canchange = 1;
 4375:         }
 4376:     } elsif ($context eq 'reqcrsotherdom') {
 4377:         if (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) {
 4378:             $canchange = 1;
 4379:         }
 4380:     } elsif ($context eq 'requestauthor') {
 4381:         if (&Apache::lonnet::allowed('cau',$env{'request.role.domain'})) {
 4382:             $canchange = 1;
 4383:         }
 4384:     } elsif (&Apache::lonnet::allowed('mut',$env{'form.ccdomain'})) {
 4385:         # Current user has quota modification privileges
 4386:         $canchange = 1;
 4387:     }
 4388:     my $toolchanged;
 4389:     if ($canchange) {
 4390:         if (ref($changeHash) eq 'HASH') {
 4391:             $toolchanged = 1;
 4392:             if ($tool eq 'requestauthor') {
 4393:                 $changeHash->{$context} = $settool;
 4394:             } else {
 4395:                 $changeHash->{$context.'.'.$tool} = $settool;
 4396:             }
 4397:         }
 4398:     }
 4399:     return $toolchanged;
 4400: }
 4401: 
 4402: sub build_roles {
 4403:     my ($sectionstr,$sections,$role) = @_;
 4404:     my $num_sections = 0;
 4405:     if ($sectionstr=~ /,/) {
 4406:         my @secnums = split/,/,$sectionstr;
 4407:         if ($role eq 'st') {
 4408:             $secnums[0] =~ s/\W//g;
 4409:             $$sections{$secnums[0]} = 1;
 4410:             $num_sections = 1;
 4411:         } else {
 4412:             foreach my $sec (@secnums) {
 4413:                 $sec =~ ~s/\W//g;
 4414:                 if (!($sec eq "")) {
 4415:                     if (exists($$sections{$sec})) {
 4416:                         $$sections{$sec} ++;
 4417:                     } else {
 4418:                         $$sections{$sec} = 1;
 4419:                         $num_sections ++;
 4420:                     }
 4421:                 }
 4422:             }
 4423:         }
 4424:     } else {
 4425:         $sectionstr=~s/\W//g;
 4426:         unless ($sectionstr eq '') {
 4427:             $$sections{$sectionstr} = 1;
 4428:             $num_sections ++;
 4429:         }
 4430:     }
 4431: 
 4432:     return $num_sections;
 4433: }
 4434: 
 4435: # ========================================================== Custom Role Editor
 4436: 
 4437: sub custom_role_editor {
 4438:     my ($r,$context,$brcrum,$prefix,$permission) = @_;
 4439:     my $action = $env{'form.customroleaction'};
 4440:     my ($rolename,$helpitem);
 4441:     if ($action eq 'new') {
 4442:         $rolename=$env{'form.newrolename'};
 4443:     } else {
 4444:         $rolename=$env{'form.rolename'};
 4445:     }
 4446: 
 4447:     my ($crstype,$context);
 4448:     if ($env{'request.course.id'}) {
 4449:         $crstype = &Apache::loncommon::course_type();
 4450:         $context = 'course';
 4451:         $helpitem = 'Course_Editing_Custom_Roles';
 4452:     } else {
 4453:         $context = 'domain';
 4454:         $crstype = 'course';
 4455:         $helpitem = 'Domain_Editing_Custom_Roles';
 4456:     }
 4457: 
 4458:     $rolename=~s/[^A-Za-z0-9]//gs;
 4459:     if (!$rolename || $env{'form.phase'} eq 'pickrole') {
 4460: 	&print_username_entry_form($r,$context,undef,undef,undef,$crstype,$brcrum,
 4461:                                    $permission);
 4462:         return;
 4463:     }
 4464: 
 4465:     my $formname = 'form1';
 4466:     my %privs=();
 4467:     my $body_top = '<h2>';
 4468: # ------------------------------------------------------- Does this role exist?
 4469:     my ($rdummy,$roledef)=
 4470: 			 &Apache::lonnet::get('roles',["rolesdef_$rolename"]);
 4471:     if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 4472:         $body_top .= &mt('Existing Role').' "';
 4473: # ------------------------------------------------- Get current role privileges
 4474:         ($privs{'system'},$privs{'domain'},$privs{'course'})=split(/\_/,$roledef);
 4475:         if ($privs{'system'} =~ /bre\&S/) {
 4476:             if ($context eq 'domain') {
 4477:                 $crstype = 'Course';
 4478:             } elsif ($crstype eq 'Community') {
 4479:                 $privs{'system'} =~ s/bre\&S//;
 4480:             }
 4481:         } elsif ($context eq 'domain') {
 4482:             $crstype = 'Course';
 4483:         }
 4484:     } else {
 4485:         $body_top .= &mt('New Role').' "';
 4486:         $roledef='';
 4487:     }
 4488:     $body_top .= $rolename.'"</h2>';
 4489: 
 4490: # ------------------------------------------------------- What can be assigned?
 4491:     my %full=();
 4492:     my %levels=(
 4493:                  course => {},
 4494:                  domain => {},
 4495:                  system => {},
 4496:                );
 4497:     my %levelscurrent=(
 4498:                         course => {},
 4499:                         domain => {},
 4500:                         system => {},
 4501:                       );
 4502:     &Apache::lonuserutils::custom_role_privs(\%privs,\%full,\%levels,\%levelscurrent);
 4503:     my ($jsback,$elements) = &crumb_utilities();
 4504:     my @templateroles = &Apache::lonuserutils::custom_template_roles($context,$crstype);
 4505:     my $head_script =
 4506:         &Apache::lonuserutils::custom_roledefs_js($context,$crstype,$formname,
 4507:                                                   \%full,\@templateroles,$jsback);
 4508:     push (@{$brcrum},
 4509:               {href => "javascript:backPage(document.$formname,'pickrole','')",
 4510:                text => "Pick custom role",
 4511:                faq  => 282,bug=>'Instructor Interface',},
 4512:               {href => "javascript:backPage(document.$formname,'','')",
 4513:                text => "Edit custom role",
 4514:                faq  => 282,
 4515:                bug  => 'Instructor Interface',
 4516:                help => $helpitem}
 4517:               );
 4518:     my $args = { bread_crumbs          => $brcrum,
 4519:                  bread_crumbs_component => 'User Management'};
 4520:     $r->print(&Apache::loncommon::start_page('Custom Role Editor',
 4521:                                              $head_script,$args).
 4522:               $body_top);
 4523:     $r->print('<form name="'.$formname.'" method="post" action="">'."\n".
 4524:               &Apache::lonuserutils::custom_role_header($context,$crstype,
 4525:                                                         \@templateroles,$prefix));
 4526: 
 4527:     $r->print(<<ENDCCF);
 4528: <input type="hidden" name="phase" value="set_custom_roles" />
 4529: <input type="hidden" name="rolename" value="$rolename" />
 4530: ENDCCF
 4531:     $r->print(&Apache::lonuserutils::custom_role_table($crstype,\%full,\%levels,
 4532:                                                        \%levelscurrent,$prefix));
 4533:     $r->print(&Apache::loncommon::end_data_table().
 4534:    '<input type="hidden" name="action" value="'.$env{'form.action'}.'" />'.
 4535:    '<input type="hidden" name="startrolename" value="'.$env{'form.rolename'}.
 4536:    '" />'."\n".'<input type="hidden" name="currstate" value="" />'."\n".
 4537:    '<input type="reset" value="'.&mt("Reset").'" />'."\n".
 4538:    '<input type="submit" value="'.&mt('Save').'" /></form>');
 4539: }
 4540: 
 4541: # ---------------------------------------------------------- Call to definerole
 4542: sub set_custom_role {
 4543:     my ($r,$context,$brcrum,$prefix,$permission) = @_;
 4544:     my $rolename=$env{'form.rolename'};
 4545:     $rolename=~s/[^A-Za-z0-9]//gs;
 4546:     if (!$rolename) {
 4547: 	&custom_role_editor($r,$context,$brcrum,$prefix,$permission);
 4548:         return;
 4549:     }
 4550:     my ($jsback,$elements) = &crumb_utilities();
 4551:     my $jscript = '<script type="text/javascript">'
 4552:                  .'// <![CDATA['."\n"
 4553:                  .$jsback."\n"
 4554:                  .'// ]]>'."\n"
 4555:                  .'</script>'."\n";
 4556:     my $helpitem = 'Course_Editing_Custom_Roles';
 4557:     if ($context eq 'domain') {
 4558:         $helpitem = 'Domain_Editing_Custom_Roles';
 4559:     }
 4560:     push(@{$brcrum},
 4561:         {href => "javascript:backPage(document.customresult,'pickrole','')",
 4562:          text => "Pick custom role",
 4563:          faq  => 282,
 4564:          bug  => 'Instructor Interface',},
 4565:         {href => "javascript:backPage(document.customresult,'selected_custom_edit','')",
 4566:          text => "Edit custom role",
 4567:          faq  => 282,
 4568:          bug  => 'Instructor Interface',},
 4569:         {href => "javascript:backPage(document.customresult,'set_custom_roles','')",
 4570:          text => "Result",
 4571:          faq  => 282,
 4572:          bug  => 'Instructor Interface',
 4573:          help => $helpitem,}
 4574:         );
 4575:     my $args = { bread_crumbs           => $brcrum,
 4576:                  bread_crumbs_component => 'User Management'};
 4577:     $r->print(&Apache::loncommon::start_page('Save Custom Role',$jscript,$args));
 4578: 
 4579:     my $newrole;
 4580:     my ($rdummy,$roledef)=
 4581: 	&Apache::lonnet::get('roles',["rolesdef_$rolename"]);
 4582: 
 4583: # ------------------------------------------------------- Does this role exist?
 4584:     $r->print('<h3>');
 4585:     if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 4586: 	$r->print(&mt('Existing Role').' "');
 4587:     } else {
 4588: 	$r->print(&mt('New Role').' "');
 4589: 	$roledef='';
 4590:         $newrole = 1;
 4591:     }
 4592:     $r->print($rolename.'"</h3>');
 4593: # ------------------------------------------------- Assign role and show result
 4594: 
 4595:     my $errmsg;
 4596:     my %newprivs = &Apache::lonuserutils::custom_role_update($rolename,$prefix);
 4597:     # Assign role and return result
 4598:     my $result = &Apache::lonnet::definerole($rolename,$newprivs{'s'},$newprivs{'d'},
 4599:                                              $newprivs{'c'});
 4600:     if ($result ne 'ok') {
 4601:         $errmsg = ': '.$result;
 4602:     }
 4603:     my $message =
 4604:         &Apache::lonhtmlcommon::confirm_success(
 4605:             &mt('Defining Role').$errmsg, ($result eq 'ok' ? 0 : 1));
 4606:     if ($env{'request.course.id'}) {
 4607:         my $url='/'.$env{'request.course.id'};
 4608:         $url=~s/\_/\//g;
 4609:         $result =
 4610:             &Apache::lonnet::assigncustomrole(
 4611:                 $env{'user.domain'},$env{'user.name'},
 4612:                 $url,
 4613:                 $env{'user.domain'},$env{'user.name'},
 4614:                 $rolename,undef,undef,undef,$context);
 4615:         if ($result ne 'ok') {
 4616:             $errmsg = ': '.$result;
 4617:         }
 4618:         $message .=
 4619:             '<br />'
 4620:            .&Apache::lonhtmlcommon::confirm_success(
 4621:                 &mt('Assigning Role to Self').$errmsg, ($result eq 'ok' ? 0 : 1));
 4622:     }
 4623:     $r->print(
 4624:         &Apache::loncommon::confirmwrapper($message)
 4625:        .'<br />'
 4626:        .&Apache::lonhtmlcommon::actionbox([
 4627:             '<a href="javascript:backPage(document.customresult,'."'pickrole'".')">'
 4628:            .&mt('Create or edit another custom role')
 4629:            .'</a>'])
 4630:        .'<form name="customresult" method="post" action="">'
 4631:        .&Apache::lonhtmlcommon::echo_form_input([])
 4632:        .'</form>'
 4633:     );
 4634: }
 4635: 
 4636: # ================================================================ Main Handler
 4637: sub handler {
 4638:     my $r = shift;
 4639:     if ($r->header_only) {
 4640:        &Apache::loncommon::content_type($r,'text/html');
 4641:        $r->send_http_header;
 4642:        return OK;
 4643:     }
 4644:     my ($context,$crstype,$cid,$cnum,$cdom,$allhelpitems);
 4645: 
 4646:     if ($env{'request.course.id'}) {
 4647:         $context = 'course';
 4648:         $crstype = &Apache::loncommon::course_type();
 4649:     } elsif ($env{'request.role'} =~ /^au\./) {
 4650:         $context = 'author';
 4651:     } else {
 4652:         $context = 'domain';
 4653:     }
 4654: 
 4655:     my ($permission,$allowed) =
 4656:         &Apache::lonuserutils::get_permission($context,$crstype);
 4657: 
 4658:     if ($allowed) {
 4659:         my @allhelp;
 4660:         if ($context eq 'course') {
 4661:             $cid = $env{'request.course.id'};
 4662:             $cdom = $env{'course.'.$cid.'.domain'};
 4663:             $cnum = $env{'course.'.$cid.'.num'};
 4664: 
 4665:             if ($permission->{'cusr'}) {
 4666:                 push(@allhelp,'Course_Create_Class_List');
 4667:             }
 4668:             if ($permission->{'view'} || $permission->{'cusr'}) {
 4669:                 push(@allhelp,('Course_Change_Privileges','Course_View_Class_List'));
 4670:             }
 4671:             if ($permission->{'custom'}) {
 4672:                 push(@allhelp,'Course_Editing_Custom_Roles');
 4673:             }
 4674:             if ($permission->{'cusr'}) {
 4675:                 push(@allhelp,('Course_Add_Student','Course_Drop_Student'));
 4676:             }
 4677:             unless ($permission->{'cusr_section'}) {
 4678:                 if (&Apache::lonnet::auto_run($cnum,$cdom) && (($permission->{'cusr'}) || ($permission->{'view'}))) {
 4679:                     push(@allhelp,'Course_Automated_Enrollment');
 4680:                 }
 4681:                 if (($permission->{'selfenrolladmin'}) || ($permission->{'selfenrollview'})) {
 4682:                     push(@allhelp,'Course_Approve_Selfenroll');
 4683:                 }
 4684:             }
 4685:             if ($permission->{'grp_manage'}) {
 4686:                 push(@allhelp,'Course_Manage_Group');
 4687:             }
 4688:             if ($permission->{'view'} || $permission->{'cusr'}) {
 4689:                 push(@allhelp,'Course_User_Logs');
 4690:             }
 4691:         } elsif ($context eq 'author') {
 4692:             push(@allhelp,('Author_Change_Privileges','Author_Create_Coauthor_List',
 4693:                            'Author_View_Coauthor_List','Author_User_Logs'));
 4694:         } else {
 4695:             if ($permission->{'cusr'}) {
 4696:                 push(@allhelp,'Domain_Change_Privileges');
 4697:                 if ($permission->{'activity'}) {
 4698:                     push(@allhelp,'Domain_User_Access_Logs');
 4699:                 }
 4700:                 push(@allhelp,('Domain_Create_Users','Domain_View_Users_List'));
 4701:                 if ($permission->{'custom'}) {
 4702:                     push(@allhelp,'Domain_Editing_Custom_Roles');
 4703:                 }
 4704:                 push(@allhelp,('Domain_Role_Approvals','Domain_Username_Approvals','Domain_Change_Logs'));
 4705:             } elsif ($permission->{'view'}) {
 4706:                 push(@allhelp,'Domain_View_Privileges');
 4707:                 if ($permission->{'activity'}) {
 4708:                     push(@allhelp,'Domain_User_Access_Logs');
 4709:                 }
 4710:                 push(@allhelp,('Domain_View_Users_List','Domain_Change_Logs'));
 4711:             }
 4712:         }
 4713:         if (@allhelp) {
 4714:             $allhelpitems = join(',',@allhelp);
 4715:         }
 4716:     }
 4717: 
 4718:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 4719:         ['action','state','callingform','roletype','showrole','bulkaction','popup','phase',
 4720:          'username','domain','srchterm','srchdomain','srchin','srchby','srchtype','queue']);
 4721:     &Apache::lonhtmlcommon::clear_breadcrumbs();
 4722:     my $args;
 4723:     my $brcrum = [];
 4724:     my $bread_crumbs_component = 'User Management';
 4725:     if (($env{'form.action'} ne 'dateselect') && ($env{'form.action'} ne 'displayuserreq')) {
 4726:         $brcrum = [{href=>"/adm/createuser",
 4727:                     text=>"User Management",
 4728:                     help=>$allhelpitems}
 4729:                   ];
 4730:     }
 4731:     if (!$allowed) {
 4732:         if ($context eq 'course') {
 4733:             $r->internal_redirect('/adm/viewclasslist');
 4734:             return OK;
 4735:         }
 4736:         $env{'user.error.msg'}=
 4737:             "/adm/createuser:cst:0:0:Cannot create/modify user data ".
 4738:                                  "or view user status.";
 4739:         return HTTP_NOT_ACCEPTABLE;
 4740:     }
 4741: 
 4742:     &Apache::loncommon::content_type($r,'text/html');
 4743:     $r->send_http_header;
 4744: 
 4745:     my $showcredits;
 4746:     if ((($context eq 'course') && ($crstype eq 'Course')) || 
 4747:          ($context eq 'domain')) {
 4748:         my %domdefaults = 
 4749:             &Apache::lonnet::get_domain_defaults($env{'request.role.domain'});
 4750:         if ($domdefaults{'officialcredits'} || $domdefaults{'unofficialcredits'}) {
 4751:             $showcredits = 1;
 4752:         }
 4753:     }
 4754: 
 4755:     # Main switch on form.action and form.state, as appropriate
 4756:     if (! exists($env{'form.action'})) {
 4757:         $args = {bread_crumbs => $brcrum,
 4758:                  bread_crumbs_component => $bread_crumbs_component}; 
 4759:         $r->print(&header(undef,$args));
 4760:         $r->print(&print_main_menu($permission,$context,$crstype));
 4761:     } elsif ($env{'form.action'} eq 'upload' && $permission->{'cusr'}) {
 4762:         my $helpitem = 'Course_Create_Class_List';
 4763:         if ($context eq 'author') {
 4764:             $helpitem = 'Author_Create_Coauthor_List';
 4765:         } elsif ($context eq 'domain') {
 4766:             $helpitem = 'Domain_Create_Users';
 4767:         }
 4768:         push(@{$brcrum},
 4769:               { href => '/adm/createuser?action=upload&state=',
 4770:                 text => 'Upload Users List',
 4771:                 help => $helpitem,
 4772:               });
 4773:         $bread_crumbs_component = 'Upload Users List';
 4774:         $args = {bread_crumbs           => $brcrum,
 4775:                  bread_crumbs_component => $bread_crumbs_component};
 4776:         $r->print(&header(undef,$args));
 4777:         $r->print('<form name="studentform" method="post" '.
 4778:                   'enctype="multipart/form-data" '.
 4779:                   ' action="/adm/createuser">'."\n");
 4780:         if (! exists($env{'form.state'})) {
 4781:             &Apache::lonuserutils::print_first_users_upload_form($r,$context);
 4782:         } elsif ($env{'form.state'} eq 'got_file') {
 4783:             my $result =
 4784:                 &Apache::lonuserutils::print_upload_manager_form($r,$context,
 4785:                                                                  $permission,
 4786:                                                                  $crstype,$showcredits);
 4787:             if ($result eq 'missingdata') {
 4788:                 delete($env{'form.state'});
 4789:                 &Apache::lonuserutils::print_first_users_upload_form($r,$context);
 4790:             }
 4791:         } elsif ($env{'form.state'} eq 'enrolling') {
 4792:             if ($env{'form.datatoken'}) {
 4793:                 my $result = &Apache::lonuserutils::upfile_drop_add($r,$context,
 4794:                                                                     $permission,
 4795:                                                                     $showcredits);
 4796:                 if ($result eq 'missingdata') {
 4797:                     delete($env{'form.state'});
 4798:                     &Apache::lonuserutils::print_first_users_upload_form($r,$context);
 4799:                 } elsif ($result eq 'invalidhome') {
 4800:                     $env{'form.state'} = 'got_file';
 4801:                     delete($env{'form.lcserver'});
 4802:                     my $result =
 4803:                         &Apache::lonuserutils::print_upload_manager_form($r,$context,$permission,
 4804:                                                                          $crstype,$showcredits);
 4805:                     if ($result eq 'missingdata') {
 4806:                         delete($env{'form.state'});
 4807:                         &Apache::lonuserutils::print_first_users_upload_form($r,$context);
 4808:                     }
 4809:                 }
 4810:             } else {
 4811:                 delete($env{'form.state'});
 4812:                 &Apache::lonuserutils::print_first_users_upload_form($r,$context);
 4813:             }
 4814:         } else {
 4815:             &Apache::lonuserutils::print_first_users_upload_form($r,$context);
 4816:         }
 4817:         $r->print('</form>');
 4818:     } elsif (((($env{'form.action'} eq 'singleuser') || ($env{'form.action'}
 4819:               eq 'singlestudent')) && ($permission->{'cusr'})) ||
 4820:              (($env{'form.action'} eq 'singleuser') && ($permission->{'view'})) ||
 4821:              (($env{'form.action'} eq 'accesslogs') && ($permission->{'activity'}))) {
 4822:         my $phase = $env{'form.phase'};
 4823:         my @search = ('srchterm','srchby','srchin','srchtype','srchdomain');
 4824: 	&Apache::loncreateuser::restore_prev_selections();
 4825: 	my $srch;
 4826: 	foreach my $item (@search) {
 4827: 	    $srch->{$item} = $env{'form.'.$item};
 4828: 	}
 4829:         if (($phase eq 'get_user_info') || ($phase eq 'userpicked') ||
 4830:             ($phase eq 'createnewuser') || ($phase eq 'activity')) {
 4831:             if ($env{'form.phase'} eq 'createnewuser') {
 4832:                 my $response;
 4833:                 if ($env{'form.srchterm'} !~ /^$match_username$/) {
 4834:                     my $response =
 4835:                         '<span class="LC_warning">'
 4836:                        .&mt('You must specify a valid username. Only the following are allowed:'
 4837:                            .' letters numbers - . @')
 4838:                        .'</span>';
 4839:                     $env{'form.phase'} = '';
 4840:                     &print_username_entry_form($r,$context,$response,$srch,undef,
 4841:                                                $crstype,$brcrum,$permission);
 4842:                 } else {
 4843:                     my $ccuname =&LONCAPA::clean_username($srch->{'srchterm'});
 4844:                     my $ccdomain=&LONCAPA::clean_domain($srch->{'srchdomain'});
 4845:                     &print_user_modification_page($r,$ccuname,$ccdomain,
 4846:                                                   $srch,$response,$context,
 4847:                                                   $permission,$crstype,$brcrum,
 4848:                                                   $showcredits);
 4849:                 }
 4850:             } elsif ($env{'form.phase'} eq 'get_user_info') {
 4851:                 my ($currstate,$response,$forcenewuser,$results) = 
 4852:                     &user_search_result($context,$srch);
 4853:                 if ($env{'form.currstate'} eq 'modify') {
 4854:                     $currstate = $env{'form.currstate'};
 4855:                 }
 4856:                 if ($currstate eq 'select') {
 4857:                     &print_user_selection_page($r,$response,$srch,$results,
 4858:                                                \@search,$context,undef,$crstype,
 4859:                                                $brcrum);
 4860:                 } elsif (($currstate eq 'modify') || ($env{'form.action'} eq 'accesslogs')) {
 4861:                     my ($ccuname,$ccdomain,$uhome);
 4862:                     if (($srch->{'srchby'} eq 'uname') && 
 4863:                         ($srch->{'srchtype'} eq 'exact')) {
 4864:                         $ccuname = $srch->{'srchterm'};
 4865:                         $ccdomain= $srch->{'srchdomain'};
 4866:                     } else {
 4867:                         my @matchedunames = keys(%{$results});
 4868:                         ($ccuname,$ccdomain) = split(/:/,$matchedunames[0]);
 4869:                     }
 4870:                     $ccuname =&LONCAPA::clean_username($ccuname);
 4871:                     $ccdomain=&LONCAPA::clean_domain($ccdomain);
 4872:                     if ($env{'form.action'} eq 'accesslogs') {
 4873:                         my $uhome;
 4874:                         if (($ccuname ne '') && ($ccdomain ne '')) {
 4875:                            $uhome = &Apache::lonnet::homeserver($ccuname,$ccdomain);
 4876:                         }
 4877:                         if (($uhome eq '') || ($uhome eq 'no_host')) {
 4878:                             $env{'form.phase'} = '';
 4879:                             undef($forcenewuser);
 4880:                             #if ($response) {
 4881:                             #    unless ($response =~ m{\Q<br /><br />\E$}) {
 4882:                             #        $response .= '<br /><br />';
 4883:                             #    }
 4884:                             #}
 4885:                             &print_username_entry_form($r,$context,$response,$srch,
 4886:                                                        $forcenewuser,$crstype,$brcrum,
 4887:                                                        $permission);
 4888:                         } else {
 4889:                             &print_useraccesslogs_display($r,$ccuname,$ccdomain,$permission,$brcrum);
 4890:                         }
 4891:                     } else {
 4892:                         if ($env{'form.forcenewuser'}) {
 4893:                             $response = '';
 4894:                         }
 4895:                         &print_user_modification_page($r,$ccuname,$ccdomain,
 4896:                                                       $srch,$response,$context,
 4897:                                                       $permission,$crstype,$brcrum);
 4898:                     }
 4899:                 } elsif ($currstate eq 'query') {
 4900:                     &print_user_query_page($r,'createuser',$brcrum);
 4901:                 } else {
 4902:                     $env{'form.phase'} = '';
 4903:                     &print_username_entry_form($r,$context,$response,$srch,
 4904:                                                $forcenewuser,$crstype,$brcrum,
 4905:                                                $permission);
 4906:                 }
 4907:             } elsif ($env{'form.phase'} eq 'userpicked') {
 4908:                 my $ccuname = &LONCAPA::clean_username($env{'form.seluname'});
 4909:                 my $ccdomain = &LONCAPA::clean_domain($env{'form.seludom'});
 4910:                 if ($env{'form.action'} eq 'accesslogs') {
 4911:                     &print_useraccesslogs_display($r,$ccuname,$ccdomain,$permission,$brcrum);
 4912:                 } else {
 4913:                     &print_user_modification_page($r,$ccuname,$ccdomain,$srch,'',
 4914:                                                   $context,$permission,$crstype,
 4915:                                                   $brcrum);
 4916:                 }
 4917:             } elsif ($env{'form.action'} eq 'accesslogs') {
 4918:                 my $ccuname = &LONCAPA::clean_username($env{'form.accessuname'});
 4919:                 my $ccdomain = &LONCAPA::clean_domain($env{'form.accessudom'});
 4920:                 &print_useraccesslogs_display($r,$ccuname,$ccdomain,$permission,$brcrum);
 4921:             }
 4922:         } elsif ($env{'form.phase'} eq 'update_user_data') {
 4923:             &update_user_data($r,$context,$crstype,$brcrum,$showcredits,$permission);
 4924:         } else {
 4925:             &print_username_entry_form($r,$context,undef,$srch,undef,$crstype,
 4926:                                        $brcrum,$permission);
 4927:         }
 4928:     } elsif ($env{'form.action'} eq 'custom' && $permission->{'custom'}) {
 4929:         my $prefix;
 4930:         if ($env{'form.phase'} eq 'set_custom_roles') {
 4931:             &set_custom_role($r,$context,$brcrum,$prefix,$permission);
 4932:         } else {
 4933:             &custom_role_editor($r,$context,$brcrum,$prefix,$permission);
 4934:         }
 4935:     } elsif (($env{'form.action'} eq 'processauthorreq') &&
 4936:              ($permission->{'cusr'}) && 
 4937:              (&Apache::lonnet::allowed('cau',$env{'request.role.domain'}))) {
 4938:         push(@{$brcrum},
 4939:                  {href => '/adm/createuser?action=processauthorreq',
 4940:                   text => 'Authoring Space requests',
 4941:                   help => 'Domain_Role_Approvals'});
 4942:         $bread_crumbs_component = 'Authoring requests';
 4943:         if ($env{'form.state'} eq 'done') {
 4944:             push(@{$brcrum},
 4945:                      {href => '/adm/createuser?action=authorreqqueue',
 4946:                       text => 'Result',
 4947:                       help => 'Domain_Role_Approvals'});
 4948:             $bread_crumbs_component = 'Authoring request result';
 4949:         }
 4950:         $args = { bread_crumbs           => $brcrum,
 4951:                   bread_crumbs_component => $bread_crumbs_component};
 4952:         my $js = &usernamerequest_javascript();
 4953:         $r->print(&header(&add_script($js),$args));
 4954:         if (!exists($env{'form.state'})) {
 4955:             $r->print(&Apache::loncoursequeueadmin::display_queued_requests('requestauthor',
 4956:                                                                             $env{'request.role.domain'}));
 4957:         } elsif ($env{'form.state'} eq 'done') {
 4958:             $r->print('<h3>'.&mt('Authoring request processing').'</h3>'."\n");
 4959:             $r->print(&Apache::loncoursequeueadmin::update_request_queue('requestauthor',
 4960:                                                                          $env{'request.role.domain'}));
 4961:         }
 4962:     } elsif (($env{'form.action'} eq 'processusernamereq') &&
 4963:              ($permission->{'cusr'}) &&
 4964:              (&Apache::lonnet::allowed('cau',$env{'request.role.domain'}))) {
 4965:         push(@{$brcrum},
 4966:                  {href => '/adm/createuser?action=processusernamereq',
 4967:                   text => 'LON-CAPA account requests',
 4968:                   help => 'Domain_Username_Approvals'});
 4969:         $bread_crumbs_component = 'Account requests';
 4970:         if ($env{'form.state'} eq 'done') {
 4971:             push(@{$brcrum},
 4972:                      {href => '/adm/createuser?action=usernamereqqueue',
 4973:                       text => 'Result',
 4974:                       help => 'Domain_Username_Approvals'});
 4975:             $bread_crumbs_component = 'LON-CAPA account request result';
 4976:         }
 4977:         $args = { bread_crumbs           => $brcrum,
 4978:                   bread_crumbs_component => $bread_crumbs_component};
 4979:         my $js = &usernamerequest_javascript();
 4980:         $r->print(&header(&add_script($js),$args));
 4981:         if (!exists($env{'form.state'})) {
 4982:             $r->print(&Apache::loncoursequeueadmin::display_queued_requests('requestusername',
 4983:                                                                             $env{'request.role.domain'}));
 4984:         } elsif ($env{'form.state'} eq 'done') {
 4985:             $r->print('<h3>'.&mt('LON-CAPA account request processing').'</h3>'."\n");
 4986:             $r->print(&Apache::loncoursequeueadmin::update_request_queue('requestusername',
 4987:                                                                          $env{'request.role.domain'}));
 4988:         }
 4989:     } elsif (($env{'form.action'} eq 'displayuserreq') &&
 4990:              ($permission->{'cusr'})) {
 4991:         my $dom = $env{'form.domain'};
 4992:         my $uname = $env{'form.username'};
 4993:         my $warning;
 4994:         if (($dom =~ /^$match_domain$/) && (&Apache::lonnet::domain($dom) ne '')) {
 4995:             if (($dom eq $env{'request.role.domain'}) && (&Apache::lonnet::allowed('ccc',$dom))) {
 4996:                 if (($uname =~ /^$match_username$/) && ($env{'form.queue'} eq 'approval')) {
 4997:                     my $uhome = &Apache::lonnet::homeserver($uname,$dom);
 4998:                     if ($uhome eq 'no_host') {
 4999:                         my $queue = $env{'form.queue'};
 5000:                         my $reqkey = &escape($uname).'_'.$queue; 
 5001:                         my $namespace = 'usernamequeue';
 5002:                         my $domconfig = &Apache::lonnet::get_domainconfiguser($dom);
 5003:                         my %queued =
 5004:                             &Apache::lonnet::get($namespace,[$reqkey],$dom,$domconfig);
 5005:                         unless ($queued{$reqkey}) {
 5006:                             $warning = &mt('No information was found for this LON-CAPA account request.');
 5007:                         }
 5008:                     } else {
 5009:                         $warning = &mt('A LON-CAPA account already exists for the requested username and domain.');
 5010:                     }
 5011:                 } else {
 5012:                     $warning = &mt('LON-CAPA account request status check is for an invalid username.');
 5013:                 }
 5014:             } else {
 5015:                 $warning = &mt('You do not have rights to view LON-CAPA account requests in the domain specified.');
 5016:             }
 5017:         } else {
 5018:             $warning = &mt('LON-CAPA account request status check is for an invalid domain.');
 5019:         }
 5020:         my $args = { only_body => 1 };
 5021:         $r->print(&header(undef,$args).
 5022:                   '<h3>'.&mt('LON-CAPA Account Request Details').'</h3>');
 5023:         if ($warning ne '') {
 5024:             $r->print('<div class="LC_warning">'.$warning.'</div>');
 5025:         } else {
 5026:             my ($infofields,$infotitles) = &Apache::loncommon::emailusername_info();
 5027:             my $domconfiguser = &Apache::lonnet::get_domainconfiguser($dom);
 5028:             my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 5029:             if (ref($domconfig{'usercreation'}) eq 'HASH') {
 5030:                 if (ref($domconfig{'usercreation'}{'cancreate'}) eq 'HASH') {
 5031:                     if (ref($domconfig{'usercreation'}{'cancreate'}{'emailusername'}) eq 'HASH') {
 5032:                         my %info =
 5033:                             &Apache::lonnet::get('nohist_requestedusernames',[$uname],$dom,$domconfiguser);
 5034:                         if (ref($info{$uname}) eq 'HASH') {
 5035:                             my $usertype = $info{$uname}{'inststatus'};
 5036:                             unless ($usertype) {
 5037:                                 $usertype = 'default';
 5038:                             }
 5039:                             my ($showstatus,$showemail,$pickstart);
 5040:                             my $numextras = 0;
 5041:                             my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 5042:                             if ((ref($types) eq 'ARRAY') && (@{$types} > 0)) {
 5043:                                 if (ref($usertypes) eq 'HASH') {
 5044:                                     if ($usertypes->{$usertype}) {
 5045:                                         $showstatus = $usertypes->{$usertype};
 5046:                                     } else {
 5047:                                         $showstatus = $othertitle;
 5048:                                     }
 5049:                                     if ($showstatus) {
 5050:                                         $numextras ++;
 5051:                                     }
 5052:                                 }
 5053:                             }
 5054:                             if (($info{$uname}{'email'} ne '') && ($info{$uname}{'email'} ne $uname)) {
 5055:                                 $showemail = $info{$uname}{'email'};
 5056:                                 $numextras ++;
 5057:                             }
 5058:                             if (ref($domconfig{'usercreation'}{'cancreate'}{'emailusername'}{$usertype}) eq 'HASH') {
 5059:                                 if ((ref($infofields) eq 'ARRAY') && (ref($infotitles) eq 'HASH')) {
 5060:                                     $pickstart = 1;
 5061:                                     $r->print('<div>'.&Apache::lonhtmlcommon::start_pick_box());
 5062:                                     my ($num,$count);
 5063:                                     $count = scalar(keys(%{$domconfig{'usercreation'}{'cancreate'}{'emailusername'}{$usertype}}));
 5064:                                     $count += $numextras;
 5065:                                     foreach my $field (@{$infofields}) {
 5066:                                         next unless ($domconfig{'usercreation'}{'cancreate'}{'emailusername'}{$usertype}{$field});
 5067:                                         next unless ($infotitles->{$field});
 5068:                                         $r->print(&Apache::lonhtmlcommon::row_title($infotitles->{$field}).
 5069:                                                   $info{$uname}{$field});
 5070:                                         $num ++;
 5071:                                         unless ($count == $num) {
 5072:                                             $r->print(&Apache::lonhtmlcommon::row_closure());
 5073:                                         }
 5074:                                     }
 5075:                                 }
 5076:                             }
 5077:                             if ($numextras) {
 5078:                                 unless ($pickstart) {
 5079:                                     $r->print('<div>'.&Apache::lonhtmlcommon::start_pick_box());
 5080:                                     $pickstart = 1;
 5081:                                 }
 5082:                                 if ($showemail) {
 5083:                                     my $closure = '';
 5084:                                     unless ($showstatus) {
 5085:                                         $closure = 1;
 5086:                                     }
 5087:                                     $r->print(&Apache::lonhtmlcommon::row_title(&mt('E-mail address')).
 5088:                                               $showemail.
 5089:                                               &Apache::lonhtmlcommon::row_closure($closure));
 5090:                                 }
 5091:                                 if ($showstatus) {
 5092:                                     $r->print(&Apache::lonhtmlcommon::row_title(&mt('Status type[_1](self-reported)','<br />')).
 5093:                                               $showstatus.
 5094:                                               &Apache::lonhtmlcommon::row_closure(1));
 5095:                                 }
 5096:                             }
 5097:                             if ($pickstart) {
 5098:                                 $r->print(&Apache::lonhtmlcommon::end_pick_box().'</div>');
 5099:                             } else {
 5100:                                 $r->print('<div>'.&mt('No information to display for this account request.').'</div>');
 5101:                             }
 5102:                         } else {
 5103:                             $r->print('<div>'.&mt('No information available for this account request.').'</div>');
 5104:                         }
 5105:                     }
 5106:                 }
 5107:             }
 5108:         }
 5109:         $r->print(&close_popup_form());
 5110:     } elsif (($env{'form.action'} eq 'listusers') && 
 5111:              ($permission->{'view'} || $permission->{'cusr'})) {
 5112:         my $helpitem = 'Course_View_Class_List';
 5113:         if ($context eq 'author') {
 5114:             $helpitem = 'Author_View_Coauthor_List';
 5115:         } elsif ($context eq 'domain') {
 5116:             $helpitem = 'Domain_View_Users_List';
 5117:         }
 5118:         if ($env{'form.phase'} eq 'bulkchange') {
 5119:             push(@{$brcrum},
 5120:                     {href => '/adm/createuser?action=listusers',
 5121:                      text => "List Users"},
 5122:                     {href => "/adm/createuser",
 5123:                      text => "Result",
 5124:                      help => $helpitem});
 5125:             $bread_crumbs_component = 'Update Users';
 5126:             $args = {bread_crumbs           => $brcrum,
 5127:                      bread_crumbs_component => $bread_crumbs_component};
 5128:             $r->print(&header(undef,$args));
 5129:             my $setting = $env{'form.roletype'};
 5130:             my $choice = $env{'form.bulkaction'};
 5131:             if ($permission->{'cusr'}) {
 5132:                 &Apache::lonuserutils::update_user_list($r,$context,$setting,$choice,$crstype);
 5133:             } else {
 5134:                 $r->print(&mt('You are not authorized to make bulk changes to user roles'));
 5135:                 $r->print('<p><a href="/adm/createuser?action=listusers">'.&mt('Display User Lists').'</a>');
 5136:             }
 5137:         } else {
 5138:             push(@{$brcrum},
 5139:                     {href => '/adm/createuser?action=listusers',
 5140:                      text => "List Users",
 5141:                      help => $helpitem});
 5142:             $bread_crumbs_component = 'List Users';
 5143:             $args = {bread_crumbs           => $brcrum,
 5144:                      bread_crumbs_component => $bread_crumbs_component};
 5145:             my ($cb_jscript,$jscript,$totcodes,$codetitles,$idlist,$idlist_titles);
 5146:             my $formname = 'studentform';
 5147:             my $hidecall = "hide_searching();";
 5148:             if (($context eq 'domain') && (($env{'form.roletype'} eq 'course') ||
 5149:                 ($env{'form.roletype'} eq 'community'))) {
 5150:                 if ($env{'form.roletype'} eq 'course') {
 5151:                     ($cb_jscript,$jscript,$totcodes,$codetitles,$idlist,$idlist_titles) = 
 5152:                         &Apache::lonuserutils::courses_selector($env{'request.role.domain'},
 5153:                                                                 $formname);
 5154:                 } elsif ($env{'form.roletype'} eq 'community') {
 5155:                     $cb_jscript = 
 5156:                         &Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'});
 5157:                     my %elements = (
 5158:                                       coursepick => 'radio',
 5159:                                       coursetotal => 'text',
 5160:                                       courselist => 'text',
 5161:                                    );
 5162:                     $jscript = &Apache::lonhtmlcommon::set_form_elements(\%elements);
 5163:                 }
 5164:                 $jscript .= &verify_user_display($context)."\n".
 5165:                             &Apache::loncommon::check_uncheck_jscript();
 5166:                 my $js = &add_script($jscript).$cb_jscript;
 5167:                 my $loadcode = 
 5168:                     &Apache::lonuserutils::course_selector_loadcode($formname);
 5169:                 if ($loadcode ne '') {
 5170:                     $args->{add_entries} = {onload => "$loadcode;$hidecall"};
 5171:                 } else {
 5172:                     $args->{add_entries} = {onload => $hidecall};
 5173:                 }
 5174:                 $r->print(&header($js,$args));
 5175:             } else {
 5176:                 $args->{add_entries} = {onload => $hidecall};
 5177:                 $jscript = &verify_user_display($context).
 5178:                            &Apache::loncommon::check_uncheck_jscript(); 
 5179:                 $r->print(&header(&add_script($jscript),$args));
 5180:             }
 5181:             &Apache::lonuserutils::print_userlist($r,undef,$permission,$context,
 5182:                          $formname,$totcodes,$codetitles,$idlist,$idlist_titles,
 5183:                          $showcredits);
 5184:         }
 5185:     } elsif ($env{'form.action'} eq 'drop' && $permission->{'cusr'}) {
 5186:         my $brtext;
 5187:         if ($crstype eq 'Community') {
 5188:             $brtext = 'Drop Members';
 5189:         } else {
 5190:             $brtext = 'Drop Students';
 5191:         }
 5192:         push(@{$brcrum},
 5193:                 {href => '/adm/createuser?action=drop',
 5194:                  text => $brtext,
 5195:                  help => 'Course_Drop_Student'});
 5196:         if ($env{'form.state'} eq 'done') {
 5197:             push(@{$brcrum},
 5198:                      {href=>'/adm/createuser?action=drop',
 5199:                       text=>"Result"});
 5200:         }
 5201:         $bread_crumbs_component = $brtext;
 5202:         $args = {bread_crumbs           => $brcrum,
 5203:                  bread_crumbs_component => $bread_crumbs_component}; 
 5204:         $r->print(&header(undef,$args));
 5205:         if (!exists($env{'form.state'})) {
 5206:             &Apache::lonuserutils::print_drop_menu($r,$context,$permission,$crstype);
 5207:         } elsif ($env{'form.state'} eq 'done') {
 5208:             &Apache::lonuserutils::update_user_list($r,$context,undef,
 5209:                                                     $env{'form.action'});
 5210:         }
 5211:     } elsif ($env{'form.action'} eq 'dateselect') {
 5212:         if ($permission->{'cusr'}) {
 5213:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 5214:                       &Apache::lonuserutils::date_section_selector($context,$permission,
 5215:                                                                    $crstype,$showcredits));
 5216:         } else {
 5217:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 5218:                      '<span class="LC_error">'.&mt('You do not have permission to modify dates or sections for users').'</span>'); 
 5219:         }
 5220:     } elsif ($env{'form.action'} eq 'selfenroll') {
 5221:         my %currsettings;
 5222:         if ($permission->{selfenrolladmin} || $permission->{selfenrollview}) {
 5223:             %currsettings = (
 5224:                 selfenroll_types              => $env{'course.'.$cid.'.internal.selfenroll_types'},
 5225:                 selfenroll_registered         => $env{'course.'.$cid.'.internal.selfenroll_registered'},
 5226:                 selfenroll_section            => $env{'course.'.$cid.'.internal.selfenroll_section'},
 5227:                 selfenroll_notifylist         => $env{'course.'.$cid.'.internal.selfenroll_notifylist'},
 5228:                 selfenroll_approval           => $env{'course.'.$cid.'.internal.selfenroll_approval'},
 5229:                 selfenroll_limit              => $env{'course.'.$cid.'.internal.selfenroll_limit'},
 5230:                 selfenroll_cap                => $env{'course.'.$cid.'.internal.selfenroll_cap'},
 5231:                 selfenroll_start_date         => $env{'course.'.$cid.'.internal.selfenroll_start_date'},
 5232:                 selfenroll_end_date           => $env{'course.'.$cid.'.internal.selfenroll_end_date'},
 5233:                 selfenroll_start_access       => $env{'course.'.$cid.'.internal.selfenroll_start_access'},
 5234:                 selfenroll_end_access         => $env{'course.'.$cid.'.internal.selfenroll_end_access'},
 5235:                 default_enrollment_start_date => $env{'course.'.$cid.'.default_enrollment_start_date'},
 5236:                 default_enrollment_end_date   => $env{'course.'.$cid.'.default_enrollment_end_date'},
 5237:                 uniquecode                    => $env{'course.'.$cid.'.internal.uniquecode'},
 5238:             );
 5239:         }
 5240:         if ($permission->{selfenrolladmin}) {
 5241:             push(@{$brcrum},
 5242:                     {href => '/adm/createuser?action=selfenroll',
 5243:                      text => "Configure Self-enrollment",
 5244:                      help => 'Course_Self_Enrollment'});
 5245:             if (!exists($env{'form.state'})) {
 5246:                 $args = { bread_crumbs           => $brcrum,
 5247:                           bread_crumbs_component => 'Configure Self-enrollment'};
 5248:                 $r->print(&header(undef,$args));
 5249:                 $r->print('<h3>'.&mt('Self-enrollment with a student role').'</h3>'."\n");
 5250:                 &print_selfenroll_menu($r,'course',$cid,$cdom,$cnum,\%currsettings);
 5251:             } elsif ($env{'form.state'} eq 'done') {
 5252:                 push (@{$brcrum},
 5253:                           {href=>'/adm/createuser?action=selfenroll',
 5254:                            text=>"Result"});
 5255:                 $args = { bread_crumbs           => $brcrum,
 5256:                           bread_crumbs_component => 'Self-enrollment result'};
 5257:                 $r->print(&header(undef,$args));
 5258:                 $r->print('<h3>'.&mt('Self-enrollment with a student role').'</h3>'."\n");
 5259:                 &update_selfenroll_config($r,$cid,$cdom,$cnum,$context,$crstype,\%currsettings);
 5260:             }
 5261:         } elsif ($permission->{selfenrollview}) {
 5262:             push(@{$brcrum},
 5263:                     {href => '/adm/createuser?action=selfenroll',
 5264:                      text => "View Self-enrollment configuration",
 5265:                      help => 'Course_Self_Enrollment'});
 5266:             $args = { bread_crumbs           => $brcrum,
 5267:                       bread_crumbs_component => 'Self-enrollment Settings'};
 5268:             $r->print(&header(undef,$args));
 5269:             $r->print('<h3>'.&mt('Self-enrollment with a student role').'</h3>'."\n");
 5270:             &print_selfenroll_menu($r,'course',$cid,$cdom,$cnum,\%currsettings,'',1);
 5271:         } else {
 5272:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 5273:                      '<span class="LC_error">'.&mt('You do not have permission to configure self-enrollment').'</span>');
 5274:         }
 5275:     } elsif ($env{'form.action'} eq 'selfenrollqueue') {
 5276:         if ($permission->{selfenrolladmin}) {
 5277:             push(@{$brcrum},
 5278:                      {href => '/adm/createuser?action=selfenrollqueue',
 5279:                       text => 'Enrollment requests',
 5280:                       help => 'Course_Approve_Selfenroll'});
 5281:             $bread_crumbs_component = 'Enrollment requests';
 5282:             if ($env{'form.state'} eq 'done') {
 5283:                 push(@{$brcrum},
 5284:                          {href => '/adm/createuser?action=selfenrollqueue',
 5285:                           text => 'Result',
 5286:                           help => 'Course_Approve_Selfenroll'});
 5287:                 $bread_crumbs_component = 'Enrollment result';
 5288:             }
 5289:             $args = { bread_crumbs           => $brcrum,
 5290:                       bread_crumbs_component => $bread_crumbs_component};
 5291:             $r->print(&header(undef,$args));
 5292:             my $coursedesc = $env{'course.'.$cid.'.description'};
 5293:             if (!exists($env{'form.state'})) {
 5294:                 $r->print('<h3>'.&mt('Pending enrollment requests').'</h3>'."\n");
 5295:                 $r->print(&Apache::loncoursequeueadmin::display_queued_requests($context,
 5296:                                                                                 $cdom,$cnum));
 5297:             } elsif ($env{'form.state'} eq 'done') {
 5298:                 $r->print('<h3>'.&mt('Enrollment request processing').'</h3>'."\n");
 5299:                 $r->print(&Apache::loncoursequeueadmin::update_request_queue($context,
 5300:                               $cdom,$cnum,$coursedesc));
 5301:             }
 5302:         } else {
 5303:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 5304:                      '<span class="LC_error">'.&mt('You do not have permission to manage self-enrollment').'</span>');
 5305:         }
 5306:     } elsif ($env{'form.action'} eq 'changelogs') {
 5307:         if ($permission->{cusr} || $permission->{view}) {
 5308:             &print_userchangelogs_display($r,$context,$permission,$brcrum);
 5309:         } else {
 5310:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 5311:                      '<span class="LC_error">'.&mt('You do not have permission to view change logs').'</span>');
 5312:         }
 5313:     } elsif ($env{'form.action'} eq 'helpdesk') {
 5314:         if (($permission->{'owner'} || $permission->{'co-owner'}) &&
 5315:             ($permission->{'cusr'} || $permission->{'view'})) {
 5316:             if ($env{'form.state'} eq 'process') {
 5317:                 if ($permission->{'owner'}) {
 5318:                     &update_helpdeskaccess($r,$permission,$brcrum);
 5319:                 } else {
 5320:                     &print_helpdeskaccess_display($r,$permission,$brcrum);
 5321:                 }
 5322:             } else {
 5323:                 &print_helpdeskaccess_display($r,$permission,$brcrum);
 5324:             }
 5325:         } else {
 5326:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 5327:                       '<span class="LC_error">'.&mt('You do not have permission to view helpdesk access').'</span>');
 5328:         }
 5329:     } else {
 5330:         $bread_crumbs_component = 'User Management';
 5331:         $args = { bread_crumbs           => $brcrum,
 5332:                   bread_crumbs_component => $bread_crumbs_component};
 5333:         $r->print(&header(undef,$args));
 5334:         $r->print(&print_main_menu($permission,$context,$crstype));
 5335:     }
 5336:     $r->print(&Apache::loncommon::end_page());
 5337:     return OK;
 5338: }
 5339: 
 5340: sub header {
 5341:     my ($jscript,$args) = @_;
 5342:     my $start_page;
 5343:     if (ref($args) eq 'HASH') {
 5344:         $start_page=&Apache::loncommon::start_page('User Management',$jscript,$args);
 5345:     } else {
 5346:         $start_page=&Apache::loncommon::start_page('User Management',$jscript);
 5347:     }
 5348:     return $start_page;
 5349: }
 5350: 
 5351: sub add_script {
 5352:     my ($js) = @_;
 5353:     return '<script type="text/javascript">'."\n"
 5354:           .'// <![CDATA['."\n"
 5355:           .$js."\n"
 5356:           .'// ]]>'."\n"
 5357:           .'</script>'."\n";
 5358: }
 5359: 
 5360: sub usernamerequest_javascript {
 5361:     my $js = <<ENDJS;
 5362: 
 5363: function openusernamereqdisplay(dom,uname,queue) {
 5364:     var url = '/adm/createuser?action=displayuserreq';
 5365:     url += '&domain='+dom+'&username='+uname+'&queue='+queue;
 5366:     var title = 'Account_Request_Browser';
 5367:     var options = 'scrollbars=1,resizable=1,menubar=0';
 5368:     options += ',width=700,height=600';
 5369:     var stdeditbrowser = open(url,title,options,'1');
 5370:     stdeditbrowser.focus();
 5371:     return;
 5372: }
 5373:  
 5374: ENDJS
 5375: }
 5376: 
 5377: sub close_popup_form {
 5378:     my $close= &mt('Close Window');
 5379:     return << "END";
 5380: <p><form name="displayreq" action="" method="post">
 5381: <input type="button" name="closeme" value="$close" onclick="javascript:self.close();" />
 5382: </form></p>
 5383: END
 5384: }
 5385: 
 5386: sub verify_user_display {
 5387:     my ($context) = @_;
 5388:     my %lt = &Apache::lonlocal::texthash (
 5389:         course    => 'course(s): description, section(s), status',
 5390:         community => 'community(s): description, section(s), status',
 5391:         author    => 'author',
 5392:     );
 5393:     my $photos;
 5394:     if (($context eq 'course') && $env{'request.course.id'}) {
 5395:         $photos = $env{'course.'.$env{'request.course.id'}.'.internal.showphoto'};
 5396:     }
 5397:     my $output = <<"END";
 5398: 
 5399: function hide_searching() {
 5400:     if (document.getElementById('searching')) {
 5401:         document.getElementById('searching').style.display = 'none';
 5402:     }
 5403:     return;
 5404: }
 5405: 
 5406: function display_update() {
 5407:     document.studentform.action.value = 'listusers';
 5408:     document.studentform.phase.value = 'display';
 5409:     document.studentform.submit();
 5410: }
 5411: 
 5412: function updateCols(caller) {
 5413:     var context = '$context';
 5414:     var photos = '$photos';
 5415:     if (caller == 'Status') {
 5416:         if ((context == 'domain') && 
 5417:             ((document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'course') ||
 5418:              (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'community'))) {
 5419:             document.getElementById('showcolstatus').checked = false;
 5420:             document.getElementById('showcolstatus').disabled = 'disabled';
 5421:             document.getElementById('showcolstart').checked = false;
 5422:             document.getElementById('showcolend').checked = false;
 5423:         } else {
 5424:             if (document.studentform.Status.options[document.studentform.Status.selectedIndex].value == 'Any') {
 5425:                 document.getElementById('showcolstatus').checked = true;
 5426:                 document.getElementById('showcolstatus').disabled = '';
 5427:                 document.getElementById('showcolstart').checked = true;
 5428:                 document.getElementById('showcolend').checked = true;
 5429:             } else {
 5430:                 document.getElementById('showcolstatus').checked = false;
 5431:                 document.getElementById('showcolstatus').disabled = 'disabled';
 5432:                 document.getElementById('showcolstart').checked = false;
 5433:                 document.getElementById('showcolend').checked = false;
 5434:             }
 5435:         }
 5436:     }
 5437:     if (caller == 'output') {
 5438:         if (photos == 1) {
 5439:             if (document.getElementById('showcolphoto')) {
 5440:                 var photoitem = document.getElementById('showcolphoto');
 5441:                 if (document.studentform.output.options[document.studentform.output.selectedIndex].value == 'html') {
 5442:                     photoitem.checked = true;
 5443:                     photoitem.disabled = '';
 5444:                 } else {
 5445:                     photoitem.checked = false;
 5446:                     photoitem.disabled = 'disabled';
 5447:                 }
 5448:             }
 5449:         }
 5450:     }
 5451:     if (caller == 'showrole') {
 5452:         if ((document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'Any') ||
 5453:             (document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'cr')) {
 5454:             document.getElementById('showcolrole').checked = true;
 5455:             document.getElementById('showcolrole').disabled = '';
 5456:         } else {
 5457:             document.getElementById('showcolrole').checked = false;
 5458:             document.getElementById('showcolrole').disabled = 'disabled';
 5459:         }
 5460:         if (context == 'domain') {
 5461:             var quotausageshow = 0;
 5462:             if ((document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'course') ||
 5463:                 (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'community')) {
 5464:                 document.getElementById('showcolstatus').checked = false;
 5465:                 document.getElementById('showcolstatus').disabled = 'disabled';
 5466:                 document.getElementById('showcolstart').checked = false;
 5467:                 document.getElementById('showcolend').checked = false;
 5468:             } else {
 5469:                 if (document.studentform.Status.options[document.studentform.Status.selectedIndex].value == 'Any') {
 5470:                     document.getElementById('showcolstatus').checked = true;
 5471:                     document.getElementById('showcolstatus').disabled = '';
 5472:                     document.getElementById('showcolstart').checked = true;
 5473:                     document.getElementById('showcolend').checked = true;
 5474:                 }
 5475:             }
 5476:             if (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'domain') {
 5477:                 document.getElementById('showcolextent').disabled = 'disabled';
 5478:                 document.getElementById('showcolextent').checked = 'false';
 5479:                 document.getElementById('showextent').style.display='none';
 5480:                 document.getElementById('showcoltextextent').innerHTML = '';
 5481:                 if ((document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'au') ||
 5482:                     (document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'Any')) {
 5483:                     if (document.getElementById('showcolauthorusage')) {
 5484:                         document.getElementById('showcolauthorusage').disabled = '';
 5485:                     }
 5486:                     if (document.getElementById('showcolauthorquota')) {
 5487:                         document.getElementById('showcolauthorquota').disabled = '';
 5488:                     }
 5489:                     quotausageshow = 1;
 5490:                 }
 5491:             } else {
 5492:                 document.getElementById('showextent').style.display='block';
 5493:                 document.getElementById('showextent').style.textAlign='left';
 5494:                 document.getElementById('showextent').style.textFace='normal';
 5495:                 if (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'author') {
 5496:                     document.getElementById('showcolextent').disabled = '';
 5497:                     document.getElementById('showcolextent').checked = 'true';
 5498:                     document.getElementById('showcoltextextent').innerHTML="$lt{'author'}";
 5499:                 } else {
 5500:                     document.getElementById('showcolextent').disabled = '';
 5501:                     document.getElementById('showcolextent').checked = 'true';
 5502:                     if (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'community') {
 5503:                         document.getElementById('showcoltextextent').innerHTML="$lt{'community'}";
 5504:                     } else {
 5505:                         document.getElementById('showcoltextextent').innerHTML="$lt{'course'}";
 5506:                     }
 5507:                 }
 5508:             }
 5509:             if (quotausageshow == 0)  {
 5510:                 if (document.getElementById('showcolauthorusage')) {
 5511:                     document.getElementById('showcolauthorusage').checked = false;
 5512:                     document.getElementById('showcolauthorusage').disabled = 'disabled';
 5513:                 }
 5514:                 if (document.getElementById('showcolauthorquota')) {
 5515:                     document.getElementById('showcolauthorquota').checked = false;
 5516:                     document.getElementById('showcolauthorquota').disabled = 'disabled';
 5517:                 }
 5518:             }
 5519:         }
 5520:     }
 5521:     return;
 5522: }
 5523: 
 5524: END
 5525:     return $output;
 5526: 
 5527: }
 5528: 
 5529: ###############################################################
 5530: ###############################################################
 5531: #  Menu Phase One
 5532: sub print_main_menu {
 5533:     my ($permission,$context,$crstype) = @_;
 5534:     my $linkcontext = $context;
 5535:     my $stuterm = lc(&Apache::lonnet::plaintext('st',$crstype));
 5536:     if (($context eq 'course') && ($crstype eq 'Community')) {
 5537:         $linkcontext = lc($crstype);
 5538:         $stuterm = 'Members';
 5539:     }
 5540:     my %links = (
 5541:                 domain => {
 5542:                             upload     => 'Upload a File of Users',
 5543:                             singleuser => 'Add/Modify a User',
 5544:                             listusers  => 'Manage Users',
 5545:                             },
 5546:                 author => {
 5547:                             upload     => 'Upload a File of Co-authors',
 5548:                             singleuser => 'Add/Modify a Co-author',
 5549:                             listusers  => 'Manage Co-authors',
 5550:                             },
 5551:                 course => {
 5552:                             upload     => 'Upload a File of Course Users',
 5553:                             singleuser => 'Add/Modify a Course User',
 5554:                             listusers  => 'List and Modify Multiple Course Users',
 5555:                             },
 5556:                 community => {
 5557:                             upload     => 'Upload a File of Community Users',
 5558:                             singleuser => 'Add/Modify a Community User',
 5559:                             listusers  => 'List and Modify Multiple Community Users',
 5560:                            },
 5561:                 );
 5562:      my %linktitles = (
 5563:                 domain => {
 5564:                             singleuser => 'Add a user to the domain, and/or a course or community in the domain.',
 5565:                             listusers  => 'Show and manage users in this domain.',
 5566:                             },
 5567:                 author => {
 5568:                             singleuser => 'Add a user with a co- or assistant author role.',
 5569:                             listusers  => 'Show and manage co- or assistant authors.',
 5570:                             },
 5571:                 course => {
 5572:                             singleuser => 'Add a user with a certain role to this course.',
 5573:                             listusers  => 'Show and manage users in this course.',
 5574:                             },
 5575:                 community => {
 5576:                             singleuser => 'Add a user with a certain role to this community.',
 5577:                             listusers  => 'Show and manage users in this community.',
 5578:                            },
 5579:                 );
 5580:   if ($linkcontext eq 'domain') {
 5581:       unless ($permission->{'cusr'}) {
 5582:           $links{'domain'}{'singleuser'} = 'View a User';
 5583:           $linktitles{'domain'}{'singleuser'} = 'View information about a user in the domain';
 5584:       }
 5585:   } elsif ($linkcontext eq 'course') {
 5586:       unless ($permission->{'cusr'}) {
 5587:           $links{'course'}{'singleuser'} = 'View a Course User';
 5588:           $linktitles{'course'}{'singleuser'} = 'View information about a user in this course';
 5589:           $links{'course'}{'listusers'} = 'List Course Users';
 5590:           $linktitles{'course'}{'listusers'} = 'Show information about users in this course';
 5591:       }
 5592:   } elsif ($linkcontext eq 'community') {
 5593:       unless ($permission->{'cusr'}) {
 5594:           $links{'community'}{'singleuser'} = 'View a Community User';
 5595:           $linktitles{'community'}{'singleuser'} = 'View information about a user in this community';
 5596:           $links{'community'}{'listusers'} = 'List Community Users';
 5597:           $linktitles{'community'}{'listusers'} = 'Show information about users in this community';
 5598:       }
 5599:   }
 5600:   my @menu = ( {categorytitle => 'Single Users', 
 5601:          items =>
 5602:          [
 5603:             {
 5604:              linktext => $links{$linkcontext}{'singleuser'},
 5605:              icon => 'edit-redo.png',
 5606:              #help => 'Course_Change_Privileges',
 5607:              url => '/adm/createuser?action=singleuser',
 5608:              permission => ($permission->{'view'} || $permission->{'cusr'}),
 5609:              linktitle => $linktitles{$linkcontext}{'singleuser'},
 5610:             },
 5611:          ]},
 5612: 
 5613:          {categorytitle => 'Multiple Users',
 5614:          items => 
 5615:          [
 5616:             {
 5617:              linktext => $links{$linkcontext}{'upload'},
 5618:              icon => 'uplusr.png',
 5619:              #help => 'Course_Create_Class_List',
 5620:              url => '/adm/createuser?action=upload',
 5621:              permission => $permission->{'cusr'},
 5622:              linktitle => 'Upload a CSV or a text file containing users.',
 5623:             },
 5624:             {
 5625:              linktext => $links{$linkcontext}{'listusers'},
 5626:              icon => 'mngcu.png',
 5627:              #help => 'Course_View_Class_List',
 5628:              url => '/adm/createuser?action=listusers',
 5629:              permission => ($permission->{'view'} || $permission->{'cusr'}),
 5630:              linktitle => $linktitles{$linkcontext}{'listusers'}, 
 5631:             },
 5632: 
 5633:          ]},
 5634: 
 5635:          {categorytitle => 'Administration',
 5636:          items => [ ]},
 5637:        );
 5638: 
 5639:     if ($context eq 'domain'){
 5640:         push(@{  $menu[0]->{items} }, # Single Users
 5641:             {
 5642:              linktext => 'User Access Log',
 5643:              icon => 'document-properties.png',
 5644:              #help => 'Domain_User_Access_Logs',
 5645:              url => '/adm/createuser?action=accesslogs',
 5646:              permission => $permission->{'activity'},
 5647:              linktitle => 'View user access log.',
 5648:             }
 5649:         );
 5650:         
 5651:         push(@{ $menu[2]->{items} }, #Category: Administration
 5652:             {
 5653:              linktext => 'Custom Roles',
 5654:              icon => 'emblem-photos.png',
 5655:              #help => 'Course_Editing_Custom_Roles',
 5656:              url => '/adm/createuser?action=custom',
 5657:              permission => $permission->{'custom'},
 5658:              linktitle => 'Configure a custom role.',
 5659:             },
 5660:             {
 5661:              linktext => 'Authoring Space Requests',
 5662:              icon => 'selfenrl-queue.png',
 5663:              #help => 'Domain_Role_Approvals',
 5664:              url => '/adm/createuser?action=processauthorreq',
 5665:              permission => $permission->{'cusr'},
 5666:              linktitle => 'Approve or reject author role requests',
 5667:             },
 5668:             {
 5669:              linktext => 'LON-CAPA Account Requests',
 5670:              icon => 'list-add.png',
 5671:              #help => 'Domain_Username_Approvals',
 5672:              url => '/adm/createuser?action=processusernamereq',
 5673:              permission => $permission->{'cusr'},
 5674:              linktitle => 'Approve or reject LON-CAPA account requests',
 5675:             },
 5676:             {
 5677:              linktext => 'Change Log',
 5678:              icon => 'document-properties.png',
 5679:              #help => 'Course_User_Logs',
 5680:              url => '/adm/createuser?action=changelogs',
 5681:              permission => ($permission->{'cusr'} || $permission->{'view'}),
 5682:              linktitle => 'View change log.',
 5683:             },
 5684:         );
 5685:         
 5686:     }elsif ($context eq 'course'){
 5687:         my ($cnum,$cdom) = &Apache::lonuserutils::get_course_identity();
 5688: 
 5689:         my %linktext = (
 5690:                          'Course'    => {
 5691:                                           single => 'Add/Modify a Student', 
 5692:                                           drop   => 'Drop Students',
 5693:                                           groups => 'Course Groups',
 5694:                                         },
 5695:                          'Community' => {
 5696:                                           single => 'Add/Modify a Member', 
 5697:                                           drop   => 'Drop Members',
 5698:                                           groups => 'Community Groups',
 5699:                                         },
 5700:                        );
 5701: 
 5702:         my %linktitle = (
 5703:             'Course' => {
 5704:                   single => 'Add a user with the role of student to this course',
 5705:                   drop   => 'Remove a student from this course.',
 5706:                   groups => 'Manage course groups',
 5707:                         },
 5708:             'Community' => {
 5709:                   single => 'Add a user with the role of member to this community',
 5710:                   drop   => 'Remove a member from this community.',
 5711:                   groups => 'Manage community groups',
 5712:                            },
 5713:         );
 5714: 
 5715:         push(@{ $menu[0]->{items} }, #Category: Single Users
 5716:             {   
 5717:              linktext => $linktext{$crstype}{'single'},
 5718:              #help => 'Course_Add_Student',
 5719:              icon => 'list-add.png',
 5720:              url => '/adm/createuser?action=singlestudent',
 5721:              permission => $permission->{'cusr'},
 5722:              linktitle => $linktitle{$crstype}{'single'},
 5723:             },
 5724:         );
 5725:         
 5726:         push(@{ $menu[1]->{items} }, #Category: Multiple Users 
 5727:             {
 5728:              linktext => $linktext{$crstype}{'drop'},
 5729:              icon => 'edit-undo.png',
 5730:              #help => 'Course_Drop_Student',
 5731:              url => '/adm/createuser?action=drop',
 5732:              permission => $permission->{'cusr'},
 5733:              linktitle => $linktitle{$crstype}{'drop'},
 5734:             },
 5735:         );
 5736:         push(@{ $menu[2]->{items} }, #Category: Administration
 5737:             {
 5738:              linktext => 'Helpdesk Access',
 5739:              icon => 'helpdesk-access.png',
 5740:              #help => 'Course_Helpdesk_Access',
 5741:              url => '/adm/createuser?action=helpdesk',
 5742:              permission => (($permission->{'owner'} || $permission->{'co-owner'}) &&
 5743:                             ($permission->{'view'} || $permission->{'cusr'})),
 5744:              linktitle => 'Helpdesk access options',
 5745:             },
 5746:             {
 5747:              linktext => 'Custom Roles',
 5748:              icon => 'emblem-photos.png',
 5749:              #help => 'Course_Editing_Custom_Roles',
 5750:              url => '/adm/createuser?action=custom',
 5751:              permission => $permission->{'custom'},
 5752:              linktitle => 'Configure a custom role.',
 5753:             },
 5754:             {
 5755:              linktext => $linktext{$crstype}{'groups'},
 5756:              icon => 'grps.png',
 5757:              #help => 'Course_Manage_Group',
 5758:              url => '/adm/coursegroups?refpage=cusr',
 5759:              permission => $permission->{'grp_manage'},
 5760:              linktitle => $linktitle{$crstype}{'groups'},
 5761:             },
 5762:             {
 5763:              linktext => 'Change Log',
 5764:              icon => 'document-properties.png',
 5765:              #help => 'Course_User_Logs',
 5766:              url => '/adm/createuser?action=changelogs',
 5767:              permission => ($permission->{'view'} || $permission->{'cusr'}),
 5768:              linktitle => 'View change log.',
 5769:             },
 5770:         );
 5771:         if ($env{'course.'.$env{'request.course.id'}.'.internal.selfenroll_approval'}) {
 5772:             push(@{ $menu[2]->{items} },
 5773:                     {
 5774:                      linktext => 'Enrollment Requests',
 5775:                      icon => 'selfenrl-queue.png',
 5776:                      #help => 'Course_Approve_Selfenroll',
 5777:                      url => '/adm/createuser?action=selfenrollqueue',
 5778:                      permission => $permission->{'selfenrolladmin'} || $permission->{'selfenrollview'},
 5779:                      linktitle =>'Approve or reject enrollment requests.',
 5780:                     },
 5781:             );
 5782:         }
 5783:         
 5784:         if (!exists($permission->{'cusr_section'})){
 5785:             if ($crstype ne 'Community') {
 5786:                 push(@{ $menu[2]->{items} },
 5787:                     {
 5788:                      linktext => 'Automated Enrollment',
 5789:                      icon => 'roles.png',
 5790:                      #help => 'Course_Automated_Enrollment',
 5791:                      permission => (&Apache::lonnet::auto_run($cnum,$cdom)
 5792:                                          && (($permission->{'cusr'}) ||
 5793:                                              ($permission->{'view'}))),
 5794:                      url  => '/adm/populate',
 5795:                      linktitle => 'Automated enrollment manager.',
 5796:                     }
 5797:                 );
 5798:             }
 5799:             push(@{ $menu[2]->{items} }, 
 5800:                 {
 5801:                  linktext => 'User Self-Enrollment',
 5802:                  icon => 'self_enroll.png',
 5803:                  #help => 'Course_Self_Enrollment',
 5804:                  url => '/adm/createuser?action=selfenroll',
 5805:                  permission => $permission->{'selfenrolladmin'} || $permission->{'selfenrollview'},
 5806:                  linktitle => 'Configure user self-enrollment.',
 5807:                 },
 5808:             );
 5809:         }
 5810:     } elsif ($context eq 'author') {
 5811:         push(@{ $menu[2]->{items} }, #Category: Administration
 5812:             {
 5813:              linktext => 'Change Log',
 5814:              icon => 'document-properties.png',
 5815:              #help => 'Course_User_Logs',
 5816:              url => '/adm/createuser?action=changelogs',
 5817:              permission => $permission->{'cusr'},
 5818:              linktitle => 'View change log.',
 5819:             },
 5820:         );
 5821:     }
 5822:     return Apache::lonhtmlcommon::generate_menu(@menu);
 5823: #               { text => 'View Log-in History',
 5824: #                 help => 'Course_User_Logins',
 5825: #                 action => 'logins',
 5826: #                 permission => $permission->{'cusr'},
 5827: #               });
 5828: }
 5829: 
 5830: sub restore_prev_selections {
 5831:     my %saveable_parameters = ('srchby'   => 'scalar',
 5832: 			       'srchin'   => 'scalar',
 5833: 			       'srchtype' => 'scalar',
 5834: 			       );
 5835:     &Apache::loncommon::store_settings('user','user_picker',
 5836: 				       \%saveable_parameters);
 5837:     &Apache::loncommon::restore_settings('user','user_picker',
 5838: 					 \%saveable_parameters);
 5839: }
 5840: 
 5841: sub print_selfenroll_menu {
 5842:     my ($r,$context,$cid,$cdom,$cnum,$currsettings,$additional,$readonly) = @_;
 5843:     my $crstype = &Apache::loncommon::course_type();
 5844:     my $formname = 'selfenroll';
 5845:     my $nolink = 1;
 5846:     my ($row,$lt) = &Apache::lonuserutils::get_selfenroll_titles();
 5847:     my $groupslist = &Apache::lonuserutils::get_groupslist();
 5848:     my $setsec_js = 
 5849:         &Apache::lonuserutils::setsections_javascript($formname,$groupslist);
 5850:     my %alerts = &Apache::lonlocal::texthash(
 5851:         acto => 'Activation of self-enrollment was selected for the following domain(s)',
 5852:         butn => 'but no user types have been checked.',
 5853:         wilf => "Please uncheck 'activate' or check at least one type.",
 5854:     );
 5855:     my $disabled;
 5856:     if ($readonly) {
 5857:        $disabled = ' disabled="disabled"';
 5858:     }
 5859:     &js_escape(\%alerts);
 5860:     my $selfenroll_js = <<"ENDSCRIPT";
 5861: function update_types(caller,num) {
 5862:     var delidx = getIndexByName('selfenroll_delete');
 5863:     var actidx = getIndexByName('selfenroll_activate');
 5864:     if (caller == 'selfenroll_all') {
 5865:         var selall;
 5866:         for (var i=0; i<document.$formname.selfenroll_all.length; i++) {
 5867:             if (document.$formname.selfenroll_all[i].checked) {
 5868:                 selall = document.$formname.selfenroll_all[i].value;
 5869:             }
 5870:         }
 5871:         if (selall == 1) {
 5872:             if (delidx != -1) {
 5873:                 if (document.$formname.selfenroll_delete.length) {
 5874:                     for (var j=0; j<document.$formname.selfenroll_delete.length; j++) {
 5875:                         document.$formname.selfenroll_delete[j].checked = true;
 5876:                     }
 5877:                 } else {
 5878:                     document.$formname.elements[delidx].checked = true;
 5879:                 }
 5880:             }
 5881:             if (actidx != -1) {
 5882:                 if (document.$formname.selfenroll_activate.length) {
 5883:                     for (var j=0; j<document.$formname.selfenroll_activate.length; j++) {
 5884:                         document.$formname.selfenroll_activate[j].checked = false;
 5885:                     }
 5886:                 } else {
 5887:                     document.$formname.elements[actidx].checked = false;
 5888:                 }
 5889:             }
 5890:             document.$formname.selfenroll_newdom.selectedIndex = 0; 
 5891:         }
 5892:     }
 5893:     if (caller == 'selfenroll_activate') {
 5894:         if (document.$formname.selfenroll_activate.length) {
 5895:             for (var j=0; j<document.$formname.selfenroll_activate.length; j++) {
 5896:                 if (document.$formname.selfenroll_activate[j].value == num) {
 5897:                     if (document.$formname.selfenroll_activate[j].checked) {
 5898:                         for (var i=0; i<document.$formname.selfenroll_all.length; i++) {
 5899:                             if (document.$formname.selfenroll_all[i].value == '1') {
 5900:                                 document.$formname.selfenroll_all[i].checked = false;
 5901:                             }
 5902:                             if (document.$formname.selfenroll_all[i].value == '0') {
 5903:                                 document.$formname.selfenroll_all[i].checked = true;
 5904:                             }
 5905:                         }
 5906:                     }
 5907:                 }
 5908:             }
 5909:         } else {
 5910:             for (var i=0; i<document.$formname.selfenroll_all.length; i++) {
 5911:                 if (document.$formname.selfenroll_all[i].value == '1') {
 5912:                     document.$formname.selfenroll_all[i].checked = false;
 5913:                 }
 5914:                 if (document.$formname.selfenroll_all[i].value == '0') {
 5915:                     document.$formname.selfenroll_all[i].checked = true;
 5916:                 }
 5917:             }
 5918:         }
 5919:     }
 5920:     if (caller == 'selfenroll_delete') {
 5921:         if (document.$formname.selfenroll_delete.length) {
 5922:             for (var j=0; j<document.$formname.selfenroll_delete.length; j++) {
 5923:                 if (document.$formname.selfenroll_delete[j].value == num) {
 5924:                     if (document.$formname.selfenroll_delete[j].checked) {
 5925:                         var delindex = getIndexByName('selfenroll_types_'+num);
 5926:                         if (delindex != -1) { 
 5927:                             if (document.$formname.elements[delindex].length) {
 5928:                                 for (var k=0; k<document.$formname.elements[delindex].length; k++) {
 5929:                                     document.$formname.elements[delindex][k].checked = false;
 5930:                                 }
 5931:                             } else {
 5932:                                 document.$formname.elements[delindex].checked = false;
 5933:                             }
 5934:                         }
 5935:                     }
 5936:                 }
 5937:             }
 5938:         } else {
 5939:             if (document.$formname.selfenroll_delete.checked) {
 5940:                 var delindex = getIndexByName('selfenroll_types_'+num);
 5941:                 if (delindex != -1) {
 5942:                     if (document.$formname.elements[delindex].length) {
 5943:                         for (var k=0; k<document.$formname.elements[delindex].length; k++) {
 5944:                             document.$formname.elements[delindex][k].checked = false;
 5945:                         }
 5946:                     } else {
 5947:                         document.$formname.elements[delindex].checked = false;
 5948:                     }
 5949:                 }
 5950:             }
 5951:         }
 5952:     }
 5953:     return;
 5954: }
 5955: 
 5956: function validate_types(form) {
 5957:     var needaction = new Array();
 5958:     var countfail = 0;
 5959:     var actidx = getIndexByName('selfenroll_activate');
 5960:     if (actidx != -1) {
 5961:         if (document.$formname.selfenroll_activate.length) {
 5962:             for (var j=0; j<document.$formname.selfenroll_activate.length; j++) {
 5963:                 var num = document.$formname.selfenroll_activate[j].value;
 5964:                 if (document.$formname.selfenroll_activate[j].checked) {
 5965:                     countfail = check_types(num,countfail,needaction)
 5966:                 }
 5967:             }
 5968:         } else {
 5969:             if (document.$formname.selfenroll_activate.checked) {
 5970:                 var num = document.$formname.selfenroll_activate.value;
 5971:                 countfail = check_types(num,countfail,needaction)
 5972:             }
 5973:         }
 5974:     }
 5975:     if (countfail > 0) {
 5976:         var msg = "$alerts{'acto'}\\n";
 5977:         var loopend = needaction.length -1;
 5978:         if (loopend > 0) {
 5979:             for (var m=0; m<loopend; m++) {
 5980:                 msg += needaction[m]+", ";
 5981:             }
 5982:         }
 5983:         msg += needaction[loopend]+"\\n$alerts{'butn'}\\n$alerts{'wilf'}";
 5984:         alert(msg);
 5985:         return; 
 5986:     }
 5987:     setSections(form);
 5988: }
 5989: 
 5990: function check_types(num,countfail,needaction) {
 5991:     var boxname = 'selfenroll_types_'+num;
 5992:     var typeidx = getIndexByName(boxname);
 5993:     var count = 0;
 5994:     if (typeidx != -1) {
 5995:         if (document.$formname.elements[boxname].length) {
 5996:             for (var k=0; k<document.$formname.elements[boxname].length; k++) {
 5997:                 if (document.$formname.elements[boxname][k].checked) {
 5998:                     count ++;
 5999:                 }
 6000:             }
 6001:         } else {
 6002:             if (document.$formname.elements[typeidx].checked) {
 6003:                 count ++;
 6004:             }
 6005:         }
 6006:         if (count == 0) {
 6007:             var domidx = getIndexByName('selfenroll_dom_'+num);
 6008:             if (domidx != -1) {
 6009:                 var domname = document.$formname.elements[domidx].value;
 6010:                 needaction[countfail] = domname;
 6011:                 countfail ++;
 6012:             }
 6013:         }
 6014:     }
 6015:     return countfail;
 6016: }
 6017: 
 6018: function toggleNotify() {
 6019:     var selfenrollApproval = 0;
 6020:     if (document.$formname.selfenroll_approval.length) {
 6021:         for (var i=0; i<document.$formname.selfenroll_approval.length; i++) {
 6022:             if (document.$formname.selfenroll_approval[i].checked) {
 6023:                 selfenrollApproval = document.$formname.selfenroll_approval[i].value;
 6024:                 break;        
 6025:             }
 6026:         }
 6027:     }
 6028:     if (document.getElementById('notified')) {
 6029:         if (selfenrollApproval == 0) {
 6030:             document.getElementById('notified').style.display='none';
 6031:         } else {
 6032:             document.getElementById('notified').style.display='block';
 6033:         }
 6034:     }
 6035:     return;
 6036: }
 6037: 
 6038: function getIndexByName(item) {
 6039:     for (var i=0;i<document.$formname.elements.length;i++) {
 6040:         if (document.$formname.elements[i].name == item) {
 6041:             return i;
 6042:         }
 6043:     }
 6044:     return -1;
 6045: }
 6046: ENDSCRIPT
 6047: 
 6048:     my $output = '<script type="text/javascript">'."\n".
 6049:                  '// <![CDATA['."\n".
 6050:                  $setsec_js."\n".$selfenroll_js."\n".
 6051:                  '// ]]>'."\n".
 6052:                  '</script>'."\n".
 6053:                  '<h3>'.$lt->{'selfenroll'}.'</h3>'."\n";
 6054:     my $visactions = &cat_visibility($cdom);
 6055:     my ($cathash,%cattype);
 6056:     my %domconfig = &Apache::lonnet::get_dom('configuration',['coursecategories'],$cdom);
 6057:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 6058:         $cathash = $domconfig{'coursecategories'}{'cats'};
 6059:         $cattype{'auth'} = $domconfig{'coursecategories'}{'auth'};
 6060:         $cattype{'unauth'} = $domconfig{'coursecategories'}{'unauth'};
 6061:         if ($cattype{'auth'} eq '') {
 6062:             $cattype{'auth'} = 'std';
 6063:         }
 6064:         if ($cattype{'unauth'} eq '') {
 6065:             $cattype{'unauth'} = 'std';
 6066:         }
 6067:     } else {
 6068:         $cathash = {};
 6069:         $cattype{'auth'} = 'std';
 6070:         $cattype{'unauth'} = 'std';
 6071:     }
 6072:     if (($cattype{'auth'} eq 'none') && ($cattype{'unauth'} eq 'none')) {
 6073:         $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
 6074:                   '<br />'.
 6075:                   '<br />'.$visactions->{'take'}.'<ul>'.
 6076:                   '<li>'.$visactions->{'dc_chgconf'}.'</li>'.
 6077:                   '</ul>');
 6078:     } elsif (($cattype{'auth'} !~ /^(std|domonly)$/) && ($cattype{'unauth'} !~ /^(std|domonly)$/)) {
 6079:         if ($currsettings->{'uniquecode'}) {
 6080:             $r->print('<span class="LC_info">'.$visactions->{'vis'}.'</span>');
 6081:         } else {
 6082:             $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
 6083:                   '<br />'.
 6084:                   '<br />'.$visactions->{'take'}.'<ul>'.
 6085:                   '<li>'.$visactions->{'dc_setcode'}.'</li>'.
 6086:                   '</ul><br />');
 6087:         }
 6088:     } else {
 6089:         my ($visible,$cansetvis,$vismsgs) = &visible_in_stdcat($cdom,$cnum,\%domconfig);
 6090:         if (ref($visactions) eq 'HASH') {
 6091:             if ($visible) {
 6092:                 $output .= '<p class="LC_info">'.$visactions->{'vis'}.'</p>';
 6093:            } else {
 6094:                 $output .= '<p class="LC_warning">'.$visactions->{'miss'}.'</p>'
 6095:                           .$visactions->{'yous'}.
 6096:                            '<p>'.$visactions->{'gen'}.'<br />'.$visactions->{'coca'};
 6097:                 if (ref($vismsgs) eq 'ARRAY') {
 6098:                     $output .= '<br />'.$visactions->{'make'}.'<ul>';
 6099:                     foreach my $item (@{$vismsgs}) {
 6100:                         $output .= '<li>'.$visactions->{$item}.'</li>';
 6101:                     }
 6102:                     $output .= '</ul>';
 6103:                 }
 6104:                 $output .= '</p>';
 6105:             }
 6106:         }
 6107:     }
 6108:     my $actionhref = '/adm/createuser';
 6109:     if ($context eq 'domain') {
 6110:         $actionhref = '/adm/modifycourse';
 6111:     }
 6112: 
 6113:     my %noedit;
 6114:     unless ($context eq 'domain') {
 6115:         %noedit = &get_noedit_fields($cdom,$cnum,$crstype,$row);
 6116:     }
 6117:     $output .= '<form name="'.$formname.'" method="post" action="'.$actionhref.'">'."\n".
 6118:                &Apache::lonhtmlcommon::start_pick_box();
 6119:     if (ref($row) eq 'ARRAY') {
 6120:         foreach my $item (@{$row}) {
 6121:             my $title = $item; 
 6122:             if (ref($lt) eq 'HASH') {
 6123:                 $title = $lt->{$item};
 6124:             }
 6125:             $output .= &Apache::lonhtmlcommon::row_title($title);
 6126:             if ($item eq 'types') {
 6127:                 my $curr_types;
 6128:                 if (ref($currsettings) eq 'HASH') {
 6129:                     $curr_types = $currsettings->{'selfenroll_types'};
 6130:                 }
 6131:                 if ($noedit{$item}) {
 6132:                     if ($curr_types eq '*') {
 6133:                         $output .= &mt('Any user in any domain');   
 6134:                     } else {
 6135:                         my @entries = split(/;/,$curr_types);
 6136:                         if (@entries > 0) {
 6137:                             $output .= '<ul>'; 
 6138:                             foreach my $entry (@entries) {
 6139:                                 my ($currdom,$typestr) = split(/:/,$entry);
 6140:                                 next if ($typestr eq '');
 6141:                                 my $domdesc = &Apache::lonnet::domain($currdom);
 6142:                                 my @currinsttypes = split(',',$typestr);
 6143:                                 my ($othertitle,$usertypes,$types) = 
 6144:                                     &Apache::loncommon::sorted_inst_types($currdom);
 6145:                                 if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 6146:                                     $usertypes->{'any'} = &mt('any user'); 
 6147:                                     if (keys(%{$usertypes}) > 0) {
 6148:                                         $usertypes->{'other'} = &mt('other users');
 6149:                                     }
 6150:                                     my @longinsttypes = map { $usertypes->{$_}; } @currinsttypes;
 6151:                                     $output .= '<li>'.$domdesc.':'.join(', ',@longinsttypes).'</li>';
 6152:                                  }
 6153:                             }
 6154:                             $output .= '</ul>';
 6155:                         } else {
 6156:                             $output .= &mt('None');
 6157:                         }
 6158:                     }
 6159:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 6160:                     next;
 6161:                 }
 6162:                 my $showdomdesc = 1;
 6163:                 my $includeempty = 1;
 6164:                 my $num = 0;
 6165:                 $output .= &Apache::loncommon::start_data_table().
 6166:                            &Apache::loncommon::start_data_table_row()
 6167:                            .'<td colspan="2"><span class="LC_nobreak"><label>'
 6168:                            .&mt('Any user in any domain:')
 6169:                            .'&nbsp;<input type="radio" name="selfenroll_all" value="1" ';
 6170:                 if ($curr_types eq '*') {
 6171:                     $output .= ' checked="checked" '; 
 6172:                 }
 6173:                 $output .= 'onchange="javascript:update_types('.
 6174:                            "'selfenroll_all'".');"'.$disabled.' />'.&mt('Yes').'</label>'.
 6175:                            '&nbsp;&nbsp;<input type="radio" name="selfenroll_all" value="0" ';
 6176:                 if ($curr_types ne '*') {
 6177:                     $output .= ' checked="checked" ';
 6178:                 }
 6179:                 $output .= ' onchange="javascript:update_types('.
 6180:                            "'selfenroll_all'".');"'.$disabled.' />'.&mt('No').'</label></td>'.
 6181:                            &Apache::loncommon::end_data_table_row().
 6182:                            &Apache::loncommon::end_data_table().
 6183:                            &mt('Or').'<br />'.
 6184:                            &Apache::loncommon::start_data_table();
 6185:                 my %currdoms;
 6186:                 if ($curr_types eq '') {
 6187:                     $output .= &new_selfenroll_dom_row($cdom,'0');
 6188:                 } elsif ($curr_types ne '*') {
 6189:                     my @entries = split(/;/,$curr_types);
 6190:                     if (@entries > 0) {
 6191:                         foreach my $entry (@entries) {
 6192:                             my ($currdom,$typestr) = split(/:/,$entry);
 6193:                             $currdoms{$currdom} = 1;
 6194:                             my $domdesc = &Apache::lonnet::domain($currdom);
 6195:                             my @currinsttypes = split(',',$typestr);
 6196:                             $output .= &Apache::loncommon::start_data_table_row()
 6197:                                        .'<td valign="top"><span class="LC_nobreak">'.&mt('Domain:').'<b>'
 6198:                                        .'&nbsp;'.$domdesc.' ('.$currdom.')'
 6199:                                        .'</b><input type="hidden" name="selfenroll_dom_'.$num
 6200:                                        .'" value="'.$currdom.'" /></span><br />'
 6201:                                        .'<span class="LC_nobreak"><label><input type="checkbox" '
 6202:                                        .'name="selfenroll_delete" value="'.$num.'" onchange="javascript:update_types('."'selfenroll_delete','$num'".');"'.$disabled.' />'
 6203:                                        .&mt('Delete').'</label></span></td>';
 6204:                             $output .= '<td valign="top">&nbsp;&nbsp;'.&mt('User types:').'<br />'
 6205:                                        .&selfenroll_inst_types($num,$currdom,\@currinsttypes,$readonly).'</td>'
 6206:                                        .&Apache::loncommon::end_data_table_row();
 6207:                             $num ++;
 6208:                         }
 6209:                     }
 6210:                 }
 6211:                 my $add_domtitle = &mt('Users in additional domain:');
 6212:                 if ($curr_types eq '*') { 
 6213:                     $add_domtitle = &mt('Users in specific domain:');
 6214:                 } elsif ($curr_types eq '') {
 6215:                     $add_domtitle = &mt('Users in other domain:');
 6216:                 }
 6217:                 $output .= &Apache::loncommon::start_data_table_row()
 6218:                            .'<td colspan="2"><span class="LC_nobreak">'.$add_domtitle.'</span><br />'
 6219:                            .&Apache::loncommon::select_dom_form('','selfenroll_newdom',
 6220:                                                                 $includeempty,$showdomdesc,'','','',$readonly)
 6221:                            .'<input type="hidden" name="selfenroll_types_total" value="'.$num.'" />'
 6222:                            .'</td>'.&Apache::loncommon::end_data_table_row()
 6223:                            .&Apache::loncommon::end_data_table();
 6224:             } elsif ($item eq 'registered') {
 6225:                 my ($regon,$regoff);
 6226:                 my $registered;
 6227:                 if (ref($currsettings) eq 'HASH') {
 6228:                     $registered = $currsettings->{'selfenroll_registered'};
 6229:                 }
 6230:                 if ($noedit{$item}) {
 6231:                     if ($registered) {
 6232:                         $output .= &mt('Must be registered in course');
 6233:                     } else {
 6234:                         $output .= &mt('No requirement');
 6235:                     }
 6236:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 6237:                     next;
 6238:                 }
 6239:                 if ($registered) {
 6240:                     $regon = ' checked="checked" ';
 6241:                     $regoff = '';
 6242:                 } else {
 6243:                     $regon = '';
 6244:                     $regoff = ' checked="checked" ';
 6245:                 }
 6246:                 $output .= '<label>'.
 6247:                            '<input type="radio" name="selfenroll_registered" value="1"'.$regon.$disabled.' />'.
 6248:                            &mt('Yes').'</label>&nbsp;&nbsp;<label>'.
 6249:                            '<input type="radio" name="selfenroll_registered" value="0"'.$regoff.$disabled.' />'.
 6250:                            &mt('No').'</label>';
 6251:             } elsif ($item eq 'enroll_dates') {
 6252:                 my ($starttime,$endtime);
 6253:                 if (ref($currsettings) eq 'HASH') {
 6254:                     $starttime = $currsettings->{'selfenroll_start_date'};
 6255:                     $endtime = $currsettings->{'selfenroll_end_date'};
 6256:                     if ($starttime eq '') {
 6257:                         $starttime = $currsettings->{'default_enrollment_start_date'};
 6258:                     }
 6259:                     if ($endtime eq '') {
 6260:                         $endtime = $currsettings->{'default_enrollment_end_date'};
 6261:                     }
 6262:                 }
 6263:                 if ($noedit{$item}) {
 6264:                     $output .= &mt('From: [_1], to: [_2]',&Apache::lonlocal::locallocaltime($starttime),
 6265:                                                           &Apache::lonlocal::locallocaltime($endtime));
 6266:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 6267:                     next;
 6268:                 }
 6269:                 my $startform =
 6270:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_start_date',$starttime,
 6271:                                       $disabled,undef,undef,undef,undef,undef,undef,$nolink);
 6272:                 my $endform =
 6273:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_end_date',$endtime,
 6274:                                       $disabled,undef,undef,undef,undef,undef,undef,$nolink);
 6275:                 $output .= &selfenroll_date_forms($startform,$endform);
 6276:             } elsif ($item eq 'access_dates') {
 6277:                 my ($starttime,$endtime);
 6278:                 if (ref($currsettings) eq 'HASH') {
 6279:                     $starttime = $currsettings->{'selfenroll_start_access'};
 6280:                     $endtime = $currsettings->{'selfenroll_end_access'};
 6281:                     if ($starttime eq '') {
 6282:                         $starttime = $currsettings->{'default_enrollment_start_date'};
 6283:                     }
 6284:                     if ($endtime eq '') {
 6285:                         $endtime = $currsettings->{'default_enrollment_end_date'};
 6286:                     }
 6287:                 }
 6288:                 if ($noedit{$item}) {
 6289:                     $output .= &mt('From: [_1], to: [_2]',&Apache::lonlocal::locallocaltime($starttime),
 6290:                                                           &Apache::lonlocal::locallocaltime($endtime));
 6291:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 6292:                     next;
 6293:                 }
 6294:                 my $startform =
 6295:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_start_access',$starttime,
 6296:                                       $disabled,undef,undef,undef,undef,undef,undef,$nolink);
 6297:                 my $endform =
 6298:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_end_access',$endtime,
 6299:                                       $disabled,undef,undef,undef,undef,undef,undef,$nolink);
 6300:                 $output .= &selfenroll_date_forms($startform,$endform);
 6301:             } elsif ($item eq 'section') {
 6302:                 my $currsec;
 6303:                 if (ref($currsettings) eq 'HASH') {
 6304:                     $currsec = $currsettings->{'selfenroll_section'};
 6305:                 }
 6306:                 my %sections_count = &Apache::loncommon::get_sections($cdom,$cnum);
 6307:                 my $newsecval;
 6308:                 if ($currsec ne 'none' && $currsec ne '') {
 6309:                     if (!defined($sections_count{$currsec})) {
 6310:                         $newsecval = $currsec;
 6311:                     }
 6312:                 }
 6313:                 if ($noedit{$item}) {
 6314:                     if ($currsec ne '') {
 6315:                         $output .= $currsec;
 6316:                     } else {
 6317:                         $output .= &mt('No specific section');
 6318:                     }
 6319:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 6320:                     next;
 6321:                 }
 6322:                 my $sections_select = 
 6323:                     &Apache::lonuserutils::course_sections(\%sections_count,'st',$currsec,$disabled);
 6324:                 $output .= '<table class="LC_createuser">'."\n".
 6325:                            '<tr class="LC_section_row">'."\n".
 6326:                            '<td align="center">'.&mt('Existing sections')."\n".
 6327:                            '<br />'.$sections_select.'</td><td align="center">'.
 6328:                            &mt('New section').'<br />'."\n".
 6329:                            '<input type="text" name="newsec" size="15" value="'.$newsecval.'"'.$disabled.' />'."\n".
 6330:                            '<input type="hidden" name="sections" value="" />'."\n".
 6331:                            '</td></tr></table>'."\n";
 6332:             } elsif ($item eq 'approval') {
 6333:                 my ($currnotified,$currapproval,%appchecked);
 6334:                 my %selfdescs = &Apache::lonuserutils::selfenroll_default_descs();
 6335:                 if (ref($currsettings) eq 'HASH') {
 6336:                     $currnotified = $currsettings->{'selfenroll_notifylist'};
 6337:                     $currapproval = $currsettings->{'selfenroll_approval'};
 6338:                 }
 6339:                 if ($currapproval !~ /^[012]$/) {
 6340:                     $currapproval = 0;
 6341:                 }
 6342:                 if ($noedit{$item}) {
 6343:                     $output .=  $selfdescs{'approval'}{$currapproval}.
 6344:                                 '<br />'.&mt('(Set by Domain Coordinator)');
 6345:                     next;
 6346:                 }
 6347:                 $appchecked{$currapproval} = ' checked="checked"';
 6348:                 for my $i (0..2) {
 6349:                     $output .= '<label>'.
 6350:                                '<input type="radio" name="selfenroll_approval" value="'.$i.'"'.
 6351:                                $appchecked{$i}.' onclick="toggleNotify();"'.$disabled.' />'.
 6352:                                $selfdescs{'approval'}{$i}.'</label>'.('&nbsp;'x2);
 6353:                 }
 6354:                 my %advhash = &Apache::lonnet::get_course_adv_roles($cid,1);
 6355:                 my (@ccs,%notified);
 6356:                 my $ccrole = 'cc';
 6357:                 if ($crstype eq 'Community') {
 6358:                     $ccrole = 'co';
 6359:                 }
 6360:                 if ($advhash{$ccrole}) {
 6361:                     @ccs = split(/,/,$advhash{$ccrole});
 6362:                 }
 6363:                 if ($currnotified) {
 6364:                     foreach my $current (split(/,/,$currnotified)) {
 6365:                         $notified{$current} = 1;
 6366:                         if (!grep(/^\Q$current\E$/,@ccs)) {
 6367:                             push(@ccs,$current);
 6368:                         }
 6369:                     }
 6370:                 }
 6371:                 if (@ccs) {
 6372:                     my $style;
 6373:                     unless ($currapproval) {
 6374:                         $style = ' style="display: none;"'; 
 6375:                     }
 6376:                     $output .= '<br /><div id="notified"'.$style.'>'.
 6377:                                &mt('Personnel to be notified when an enrollment request needs approval, or has been approved:').'&nbsp;'.
 6378:                                &Apache::loncommon::start_data_table().
 6379:                                &Apache::loncommon::start_data_table_row();
 6380:                     my $count = 0;
 6381:                     my $numcols = 4;
 6382:                     foreach my $cc (sort(@ccs)) {
 6383:                         my $notifyon;
 6384:                         my ($ccuname,$ccudom) = split(/:/,$cc);
 6385:                         if ($notified{$cc}) {
 6386:                             $notifyon = ' checked="checked" ';
 6387:                         }
 6388:                         if ($count && !$count%$numcols) {
 6389:                             $output .= &Apache::loncommon::end_data_table_row().
 6390:                                        &Apache::loncommon::start_data_table_row()
 6391:                         }
 6392:                         $output .= '<td><span class="LC_nobreak"><label>'.
 6393:                                    '<input type="checkbox" name="selfenroll_notify"'.$notifyon.' value="'.$cc.'"'.$disabled.' />'.
 6394:                                    &Apache::loncommon::plainname($ccuname,$ccudom).
 6395:                                    '</label></span></td>';
 6396:                         $count ++;
 6397:                     }
 6398:                     my $rem = $count%$numcols;
 6399:                     if ($rem) {
 6400:                         my $emptycols = $numcols - $rem;
 6401:                         for (my $i=0; $i<$emptycols; $i++) { 
 6402:                             $output .= '<td>&nbsp;</td>';
 6403:                         }
 6404:                     }
 6405:                     $output .= &Apache::loncommon::end_data_table_row().
 6406:                                &Apache::loncommon::end_data_table().
 6407:                                '</div>';
 6408:                 }
 6409:             } elsif ($item eq 'limit') {
 6410:                 my ($crslimit,$selflimit,$nolimit,$currlim,$currcap);
 6411:                 if (ref($currsettings) eq 'HASH') {
 6412:                     $currlim = $currsettings->{'selfenroll_limit'};
 6413:                     $currcap = $currsettings->{'selfenroll_cap'};
 6414:                 }
 6415:                 if ($noedit{$item}) {
 6416:                     if (($currlim eq 'allstudents') || ($currlim eq 'selfenrolled')) {
 6417:                         if ($currlim eq 'allstudents') {
 6418:                             $output .= &mt('Limit by total students');
 6419:                         } elsif ($currlim eq 'selfenrolled') {
 6420:                             $output .= &mt('Limit by total self-enrolled students');
 6421:                         }
 6422:                         $output .= ' '.&mt('Maximum: [_1]',$currcap).
 6423:                                    '<br />'.&mt('(Set by Domain Coordinator)');
 6424:                     } else {
 6425:                         $output .= &mt('No limit').'<br />'.&mt('(Set by Domain Coordinator)');
 6426:                     }
 6427:                     next;
 6428:                 }
 6429:                 if ($currlim eq 'allstudents') {
 6430:                     $crslimit = ' checked="checked" ';
 6431:                     $selflimit = ' ';
 6432:                     $nolimit = ' ';
 6433:                 } elsif ($currlim eq 'selfenrolled') {
 6434:                     $crslimit = ' ';
 6435:                     $selflimit = ' checked="checked" ';
 6436:                     $nolimit = ' '; 
 6437:                 } else {
 6438:                     $crslimit = ' ';
 6439:                     $selflimit = ' ';
 6440:                     $nolimit = ' checked="checked" ';
 6441:                 }
 6442:                 $output .= '<table><tr><td><label>'.
 6443:                            '<input type="radio" name="selfenroll_limit" value="none"'.$nolimit.$disabled.'/>'.
 6444:                            &mt('No limit').'</label></td><td><label>'.
 6445:                            '<input type="radio" name="selfenroll_limit" value="allstudents"'.$crslimit.$disabled.'/>'.
 6446:                            &mt('Limit by total students').'</label></td><td><label>'.
 6447:                            '<input type="radio" name="selfenroll_limit" value="selfenrolled"'.$selflimit.$disabled.'/>'.
 6448:                            &mt('Limit by total self-enrolled students').
 6449:                            '</td></tr><tr>'.
 6450:                            '<td>&nbsp;</td><td colspan="2"><span class="LC_nobreak">'.
 6451:                            ('&nbsp;'x3).&mt('Maximum number allowed: ').
 6452:                            '<input type="text" name="selfenroll_cap" size = "5" value="'.$currcap.'"'.$disabled.' /></td></tr></table>';
 6453:             }
 6454:             $output .= &Apache::lonhtmlcommon::row_closure(1);
 6455:         }
 6456:     }
 6457:     $output .= &Apache::lonhtmlcommon::end_pick_box().'<br />';
 6458:     unless ($readonly) {
 6459:         $output .= '<input type="button" name="selfenrollconf" value="'
 6460:                    .&mt('Save').'" onclick="validate_types(this.form);" />';
 6461:     }
 6462:     $output .= '<input type="hidden" name="action" value="selfenroll" />'
 6463:               .'<input type="hidden" name="state" value="done" />'."\n"
 6464:               .$additional.'</form>';
 6465:     $r->print($output);
 6466:     return;
 6467: }
 6468: 
 6469: sub get_noedit_fields {
 6470:     my ($cdom,$cnum,$crstype,$row) = @_;
 6471:     my %noedit;
 6472:     if (ref($row) eq 'ARRAY') {
 6473:         my %settings = &Apache::lonnet::get('environment',['internal.coursecode','internal.textbook',
 6474:                                                            'internal.selfenrollmgrdc',
 6475:                                                            'internal.selfenrollmgrcc'],$cdom,$cnum);
 6476:         my $type = &Apache::lonuserutils::get_extended_type($cdom,$cnum,$crstype,\%settings);
 6477:         my (%specific_managebydc,%specific_managebycc,%default_managebydc);
 6478:         map { $specific_managebydc{$_} = 1; } (split(/,/,$settings{'internal.selfenrollmgrdc'}));
 6479:         map { $specific_managebycc{$_} = 1; } (split(/,/,$settings{'internal.selfenrollmgrcc'}));
 6480:         my %domdefaults = &Apache::lonnet::get_domain_defaults($cdom);
 6481:         map { $default_managebydc{$_} = 1; } (split(/,/,$domdefaults{$type.'selfenrolladmdc'}));
 6482: 
 6483:         foreach my $item (@{$row}) {
 6484:             next if ($specific_managebycc{$item});
 6485:             if (($specific_managebydc{$item}) || ($default_managebydc{$item})) {
 6486:                 $noedit{$item} = 1;
 6487:             }
 6488:         }
 6489:     }
 6490:     return %noedit;
 6491: } 
 6492: 
 6493: sub visible_in_stdcat {
 6494:     my ($cdom,$cnum,$domconf) = @_;
 6495:     my ($cathash,%settable,@vismsgs,$cansetvis,$visible);
 6496:     unless (ref($domconf) eq 'HASH') {
 6497:         return ($visible,$cansetvis,\@vismsgs);
 6498:     }
 6499:     if (ref($domconf->{'coursecategories'}) eq 'HASH') {
 6500:         if ($domconf->{'coursecategories'}{'togglecats'} eq 'crs') {
 6501:             $settable{'togglecats'} = 1;
 6502:         }
 6503:         if ($domconf->{'coursecategories'}{'categorize'} eq 'crs') {
 6504:             $settable{'categorize'} = 1;
 6505:         }
 6506:         $cathash = $domconf->{'coursecategories'}{'cats'};
 6507:     }
 6508:     if ($settable{'togglecats'} && $settable{'categorize'}) {
 6509:         $cansetvis = &mt('You are able to both assign a course category and choose to exclude this course from the catalog.');   
 6510:     } elsif ($settable{'togglecats'}) {
 6511:         $cansetvis = &mt('You are able to choose to exclude this course from the catalog, but only a Domain Coordinator may assign a course category.'); 
 6512:     } elsif ($settable{'categorize'}) {
 6513:         $cansetvis = &mt('You may assign a course category, but only a Domain Coordinator may choose to exclude this course from the catalog.');  
 6514:     } else {
 6515:         $cansetvis = &mt('Only a Domain Coordinator may assign a course category or choose to exclude this course from the catalog.'); 
 6516:     }
 6517:      
 6518:     my %currsettings =
 6519:         &Apache::lonnet::get('environment',['hidefromcat','categories','internal.coursecode'],
 6520:                              $cdom,$cnum);
 6521:     $visible = 0;
 6522:     if ($currsettings{'internal.coursecode'} ne '') {
 6523:         if (ref($domconf->{'coursecategories'}) eq 'HASH') {
 6524:             $cathash = $domconf->{'coursecategories'}{'cats'};
 6525:             if (ref($cathash) eq 'HASH') {
 6526:                 if ($cathash->{'instcode::0'} eq '') {
 6527:                     push(@vismsgs,'dc_addinst'); 
 6528:                 } else {
 6529:                     $visible = 1;
 6530:                 }
 6531:             } else {
 6532:                 $visible = 1;
 6533:             }
 6534:         } else {
 6535:             $visible = 1;
 6536:         }
 6537:     } else {
 6538:         if (ref($cathash) eq 'HASH') {
 6539:             if ($cathash->{'instcode::0'} ne '') {
 6540:                 push(@vismsgs,'dc_instcode');
 6541:             }
 6542:         } else {
 6543:             push(@vismsgs,'dc_instcode');
 6544:         }
 6545:     }
 6546:     if ($currsettings{'categories'} ne '') {
 6547:         my $cathash;
 6548:         if (ref($domconf->{'coursecategories'}) eq 'HASH') {
 6549:             $cathash = $domconf->{'coursecategories'}{'cats'};
 6550:             if (ref($cathash) eq 'HASH') {
 6551:                 if (keys(%{$cathash}) == 0) {
 6552:                     push(@vismsgs,'dc_catalog');
 6553:                 } elsif ((keys(%{$cathash}) == 1) && ($cathash->{'instcode::0'} ne '')) {
 6554:                     push(@vismsgs,'dc_categories');
 6555:                 } else {
 6556:                     my @currcategories = split('&',$currsettings{'categories'});
 6557:                     my $matched = 0;
 6558:                     foreach my $cat (@currcategories) {
 6559:                         if ($cathash->{$cat} ne '') {
 6560:                             $visible = 1;
 6561:                             $matched = 1;
 6562:                             last;
 6563:                         }
 6564:                     }
 6565:                     if (!$matched) {
 6566:                         if ($settable{'categorize'}) { 
 6567:                             push(@vismsgs,'chgcat');
 6568:                         } else {
 6569:                             push(@vismsgs,'dc_chgcat');
 6570:                         }
 6571:                     }
 6572:                 }
 6573:             }
 6574:         }
 6575:     } else {
 6576:         if (ref($cathash) eq 'HASH') {
 6577:             if ((keys(%{$cathash}) > 1) || 
 6578:                 (keys(%{$cathash}) == 1) && ($cathash->{'instcode::0'} eq '')) {
 6579:                 if ($settable{'categorize'}) {
 6580:                     push(@vismsgs,'addcat');
 6581:                 } else {
 6582:                     push(@vismsgs,'dc_addcat');
 6583:                 }
 6584:             }
 6585:         }
 6586:     }
 6587:     if ($currsettings{'hidefromcat'} eq 'yes') {
 6588:         $visible = 0;
 6589:         if ($settable{'togglecats'}) {
 6590:             unshift(@vismsgs,'unhide');
 6591:         } else {
 6592:             unshift(@vismsgs,'dc_unhide')
 6593:         }
 6594:     }
 6595:     return ($visible,$cansetvis,\@vismsgs);
 6596: }
 6597: 
 6598: sub cat_visibility {
 6599:     my ($cdom) = @_;
 6600:     my %visactions = &Apache::lonlocal::texthash(
 6601:                    vis => 'This course/community currently appears in the Course/Community Catalog for this domain.',
 6602:                    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.',
 6603:                    miss => 'This course/community does not currently appear in the Course/Community Catalog for this domain.',
 6604:                    none => 'Display of a course catalog is disabled for this domain.',
 6605:                    yous => 'You should remedy this if you plan to allow self-enrollment, otherwise students will have difficulty finding this course.',
 6606:                    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.',
 6607:                    make => 'Make any changes to self-enrollment settings below, click "Save", then take action to include the course in the Catalog:',
 6608:                    take => 'Take the following action to ensure the course appears in the Catalog:',
 6609:                    dc_chgconf => 'Ask a domain coordinator to change the Catalog type for this domain.',
 6610:                    dc_setcode => 'Ask a domain coordinator to assign a six character code to the course',
 6611:                    dc_unhide  => 'Ask a domain coordinator to change the "Exclude from course catalog" setting.',
 6612:                    dc_addinst => 'Ask a domain coordinator to enable catalog display of "Official courses (with institutional codes)".',
 6613:                    dc_instcode => 'Ask a domain coordinator to assign an institutional code (if this is an official course).',
 6614:                    dc_catalog  => 'Ask a domain coordinator to enable or create at least one course category in the domain.',
 6615:                    dc_categories => 'Ask a domain coordinator to create a hierarchy of categories and sub categories for courses in the domain.',
 6616:                    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',
 6617:                    dc_addcat => 'Ask a domain coordinator to assign a category to the course.',
 6618:     );
 6619:     if ($env{'request.role'} eq "dc./$cdom/") {
 6620:         $visactions{'dc_chgconf'} = &mt('Use: "Main menu" [_1] "Set domain configuration" [_1] "Cataloging of courses/communities" to change the Catalog type for this domain.','&raquo;');
 6621:         $visactions{'dc_setcode'} = &mt('Use: "Main menu" [_1] "Set domain configuration" [_1] "Cataloging of courses/communities" to assign a six character code to the course.','&raquo;');
 6622:         $visactions{'dc_unhide'} = &mt('Use: "Main menu" [_1] "Set domain configuration" [_1] "Cataloging of courses/communities" to change the "Exclude from course catalog" setting.','&raquo;');
 6623:         $visactions{'dc_addinst'} = &mt('Use: "Main menu" [_1] "Set domain configuration" [_1] "Cataloging of courses/communities" to enable catalog display of "Official courses (with institutional codes)".','&raquo;');
 6624:         $visactions{'dc_instcode'} = &mt('Use: "Main menu" [_1] "View or modify a course or community" [_1] "View/Modify course owner, institutional code ... " to assign an institutional code (if this is an official course).','&raquo;');
 6625:         $visactions{'dc_catalog'} = &mt('Use: "Main menu" [_1] "Set domain configuration" [_1] "Cataloging of courses/communities" to enable or create at least one course category in the domain.','&raquo;');
 6626:         $visactions{'dc_categories'} = &mt('Use: "Main menu" [_1] "Set domain configuration" [_1] "Cataloging of courses/communities" to create a hierarchy of categories and sub categories for courses in the domain.','&raquo;');
 6627:         $visactions{'dc_chgcat'} = &mt('Use: "Main menu" [_1] "View or modify a course or community" [_1] "View/Modify catalog settings for course" to change the category assigned to the course, as the one currently assigned is no longer used in the domain.','&raquo;');
 6628:         $visactions{'dc_addcat'} = &mt('Use: "Main menu" [_1] "View or modify a course or community" [_1] "View/Modify catalog settings for course" to assign a category to the course.','&raquo;');
 6629:     }
 6630:     $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>"');
 6631:     $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>"');
 6632:     $visactions{'addcat'} = &mt('Use [_1]Categorize course[_2] to assign a category to the course.','"<a href="/adm/courseprefs?phase=display&actions=courseinfo">','</a>"');
 6633:     return \%visactions;
 6634: }
 6635: 
 6636: sub new_selfenroll_dom_row {
 6637:     my ($newdom,$num) = @_;
 6638:     my $domdesc = &Apache::lonnet::domain($newdom);
 6639:     my $output;
 6640:     if ($domdesc ne '') {
 6641:         $output .= &Apache::loncommon::start_data_table_row()
 6642:                    .'<td valign="top"><span class="LC_nobreak">'.&mt('Domain:').'&nbsp;<b>'.$domdesc
 6643:                    .' ('.$newdom.')</b><input type="hidden" name="selfenroll_dom_'.$num
 6644:                    .'" value="'.$newdom.'" /></span><br />'
 6645:                    .'<span class="LC_nobreak"><label><input type="checkbox" '
 6646:                    .'name="selfenroll_activate" value="'.$num.'" '
 6647:                    .'onchange="javascript:update_types('
 6648:                    ."'selfenroll_activate','$num'".');" />'
 6649:                    .&mt('Activate').'</label></span></td>';
 6650:         my @currinsttypes;
 6651:         $output .= '<td>'.&mt('User types:').'<br />'
 6652:                    .&selfenroll_inst_types($num,$newdom,\@currinsttypes).'</td>'
 6653:                    .&Apache::loncommon::end_data_table_row();
 6654:     }
 6655:     return $output;
 6656: }
 6657: 
 6658: sub selfenroll_inst_types {
 6659:     my ($num,$currdom,$currinsttypes,$readonly) = @_;
 6660:     my $output;
 6661:     my $numinrow = 4;
 6662:     my $count = 0;
 6663:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($currdom);
 6664:     my $othervalue = 'any';
 6665:     my $disabled;
 6666:     if ($readonly) {
 6667:         $disabled = ' disabled="disabled"';
 6668:     }
 6669:     if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 6670:         if (keys(%{$usertypes}) > 0) {
 6671:             $othervalue = 'other';
 6672:         }
 6673:         $output .= '<table><tr>';
 6674:         foreach my $type (@{$types}) {
 6675:             if (($count > 0) && ($count%$numinrow == 0)) {
 6676:                 $output .= '</tr><tr>';
 6677:             }
 6678:             if (defined($usertypes->{$type})) {
 6679:                 my $esc_type = &escape($type);
 6680:                 $output .= '<td><span class="LC_nobreak"><label><input type = "checkbox" value="'.
 6681:                            $esc_type.'" ';
 6682:                 if (ref($currinsttypes) eq 'ARRAY') {
 6683:                     if (@{$currinsttypes} > 0) {
 6684:                         if (grep(/^any$/,@{$currinsttypes})) {
 6685:                             $output .= 'checked="checked"';
 6686:                         } elsif (grep(/^\Q$esc_type\E$/,@{$currinsttypes})) {
 6687:                             $output .= 'checked="checked"';
 6688:                         }
 6689:                     } else {
 6690:                         $output .= 'checked="checked"';
 6691:                     }
 6692:                 }
 6693:                 $output .= ' name="selfenroll_types_'.$num.'"'.$disabled.' />'.$usertypes->{$type}.'</label></span></td>';
 6694:             }
 6695:             $count ++;
 6696:         }
 6697:         if (($count > 0) && ($count%$numinrow == 0)) {
 6698:             $output .= '</tr><tr>';
 6699:         }
 6700:         $output .= '<td><span class="LC_nobreak"><label><input type = "checkbox" value="'.$othervalue.'"';
 6701:         if (ref($currinsttypes) eq 'ARRAY') {
 6702:             if (@{$currinsttypes} > 0) {
 6703:                 if (grep(/^any$/,@{$currinsttypes})) { 
 6704:                     $output .= ' checked="checked"';
 6705:                 } elsif ($othervalue eq 'other') {
 6706:                     if (grep(/^\Q$othervalue\E$/,@{$currinsttypes})) {
 6707:                         $output .= ' checked="checked"';
 6708:                     }
 6709:                 }
 6710:             } else {
 6711:                 $output .= ' checked="checked"';
 6712:             }
 6713:         } else {
 6714:             $output .= ' checked="checked"';
 6715:         }
 6716:         $output .= ' name="selfenroll_types_'.$num.'"'.$disabled.' />'.$othertitle.'</label></span></td></tr></table>';
 6717:     }
 6718:     return $output;
 6719: }
 6720: 
 6721: sub selfenroll_date_forms {
 6722:     my ($startform,$endform) = @_;
 6723:     my $output .= &Apache::lonhtmlcommon::start_pick_box()."\n".
 6724:                   &Apache::lonhtmlcommon::row_title(&mt('Start date'),
 6725:                                                     'LC_oddrow_value')."\n".
 6726:                   $startform."\n".
 6727:                   &Apache::lonhtmlcommon::row_closure(1).
 6728:                   &Apache::lonhtmlcommon::row_title(&mt('End date'),
 6729:                                                    'LC_oddrow_value')."\n".
 6730:                   $endform."\n".
 6731:                   &Apache::lonhtmlcommon::row_closure(1).
 6732:                   &Apache::lonhtmlcommon::end_pick_box();
 6733:     return $output;
 6734: }
 6735: 
 6736: sub print_userchangelogs_display {
 6737:     my ($r,$context,$permission,$brcrum) = @_;
 6738:     my $formname = 'rolelog';
 6739:     my ($username,$domain,$crstype,$viewablesec,%roleslog);
 6740:     if ($context eq 'domain') {
 6741:         $domain = $env{'request.role.domain'};
 6742:         %roleslog=&Apache::lonnet::dump_dom('nohist_rolelog',$domain);
 6743:     } else {
 6744:         if ($context eq 'course') { 
 6745:             $domain = $env{'course.'.$env{'request.course.id'}.'.domain'};
 6746:             $username = $env{'course.'.$env{'request.course.id'}.'.num'};
 6747:             $crstype = &Apache::loncommon::course_type();
 6748:             $viewablesec = &Apache::lonuserutils::viewable_section($permission);
 6749:             my %saveable_parameters = ('show' => 'scalar',);
 6750:             &Apache::loncommon::store_course_settings('roles_log',
 6751:                                                       \%saveable_parameters);
 6752:             &Apache::loncommon::restore_course_settings('roles_log',
 6753:                                                         \%saveable_parameters);
 6754:         } elsif ($context eq 'author') {
 6755:             $domain = $env{'user.domain'}; 
 6756:             if ($env{'request.role'} =~ m{^au\./\Q$domain\E/$}) {
 6757:                 $username = $env{'user.name'};
 6758:             } else {
 6759:                 undef($domain);
 6760:             }
 6761:         }
 6762:         if ($domain ne '' && $username ne '') { 
 6763:             %roleslog=&Apache::lonnet::dump('nohist_rolelog',$domain,$username);
 6764:         }
 6765:     }
 6766:     if ((keys(%roleslog))[0]=~/^error\:/) { undef(%roleslog); }
 6767: 
 6768:     my $helpitem;
 6769:     if ($context eq 'course') {
 6770:         $helpitem = 'Course_User_Logs';
 6771:     } elsif ($context eq 'domain') {
 6772:         $helpitem = 'Domain_Role_Logs';
 6773:     } elsif ($context eq 'author') {
 6774:         $helpitem = 'Author_User_Logs';
 6775:     }
 6776:     push (@{$brcrum},
 6777:              {href => '/adm/createuser?action=changelogs',
 6778:               text => 'User Management Logs',
 6779:               help => $helpitem});
 6780:     my $bread_crumbs_component = 'User Changes';
 6781:     my $args = { bread_crumbs           => $brcrum,
 6782:                  bread_crumbs_component => $bread_crumbs_component};
 6783: 
 6784:     # Create navigation javascript
 6785:     my $jsnav = &userlogdisplay_js($formname);
 6786: 
 6787:     my $jscript = (<<ENDSCRIPT);
 6788: <script type="text/javascript">
 6789: // <![CDATA[
 6790: $jsnav
 6791: // ]]>
 6792: </script>
 6793: ENDSCRIPT
 6794: 
 6795:     # print page header
 6796:     $r->print(&header($jscript,$args));
 6797: 
 6798:     # set defaults
 6799:     my $now = time();
 6800:     my $defstart = $now - (7*24*3600); #7 days ago 
 6801:     my %defaults = (
 6802:                      page               => '1',
 6803:                      show               => '10',
 6804:                      role               => 'any',
 6805:                      chgcontext         => 'any',
 6806:                      rolelog_start_date => $defstart,
 6807:                      rolelog_end_date   => $now,
 6808:                    );
 6809:     my $more_records = 0;
 6810: 
 6811:     # set current
 6812:     my %curr;
 6813:     foreach my $item ('show','page','role','chgcontext') {
 6814:         $curr{$item} = $env{'form.'.$item};
 6815:     }
 6816:     my ($startdate,$enddate) = 
 6817:         &Apache::lonuserutils::get_dates_from_form('rolelog_start_date','rolelog_end_date');
 6818:     $curr{'rolelog_start_date'} = $startdate;
 6819:     $curr{'rolelog_end_date'} = $enddate;
 6820:     foreach my $key (keys(%defaults)) {
 6821:         if ($curr{$key} eq '') {
 6822:             $curr{$key} = $defaults{$key};
 6823:         }
 6824:     }
 6825:     my (%whodunit,%changed,$version);
 6826:     ($version) = ($r->dir_config('lonVersion') =~ /^([\d\.]+)\-/);
 6827:     my ($minshown,$maxshown);
 6828:     $minshown = 1;
 6829:     my $count = 0;
 6830:     if ($curr{'show'} =~ /\D/) {
 6831:         $curr{'page'} = 1;
 6832:     } else {
 6833:         $maxshown = $curr{'page'} * $curr{'show'};
 6834:         if ($curr{'page'} > 1) {
 6835:             $minshown = 1 + ($curr{'page'} - 1) * $curr{'show'};
 6836:         }
 6837:     }
 6838: 
 6839:     # Form Header
 6840:     $r->print('<form action="/adm/createuser" method="post" name="'.$formname.'">'.
 6841:               &role_display_filter($context,$formname,$domain,$username,\%curr,
 6842:                                    $version,$crstype));
 6843: 
 6844:     my $showntableheader = 0;
 6845: 
 6846:     # Table Header
 6847:     my $tableheader = 
 6848:         &Apache::loncommon::start_data_table_header_row()
 6849:        .'<th>&nbsp;</th>'
 6850:        .'<th>'.&mt('When').'</th>'
 6851:        .'<th>'.&mt('Who made the change').'</th>'
 6852:        .'<th>'.&mt('Changed User').'</th>'
 6853:        .'<th>'.&mt('Role').'</th>';
 6854: 
 6855:     if ($context eq 'course') {
 6856:         $tableheader .= '<th>'.&mt('Section').'</th>';
 6857:     }
 6858:     $tableheader .=
 6859:         '<th>'.&mt('Context').'</th>'
 6860:        .'<th>'.&mt('Start').'</th>'
 6861:        .'<th>'.&mt('End').'</th>'
 6862:        .&Apache::loncommon::end_data_table_header_row();
 6863: 
 6864:     # Display user change log data
 6865:     foreach my $id (sort { $roleslog{$b}{'exe_time'}<=>$roleslog{$a}{'exe_time'} } (keys(%roleslog))) {
 6866:         next if (($roleslog{$id}{'exe_time'} < $curr{'rolelog_start_date'}) ||
 6867:                  ($roleslog{$id}{'exe_time'} > $curr{'rolelog_end_date'}));
 6868:         if ($curr{'show'} !~ /\D/) {
 6869:             if ($count >= $curr{'page'} * $curr{'show'}) {
 6870:                 $more_records = 1;
 6871:                 last;
 6872:             }
 6873:         }
 6874:         if ($curr{'role'} ne 'any') {
 6875:             next if ($roleslog{$id}{'logentry'}{'role'} ne $curr{'role'}); 
 6876:         }
 6877:         if ($curr{'chgcontext'} ne 'any') {
 6878:             if ($curr{'chgcontext'} eq 'selfenroll') {
 6879:                 next if (!$roleslog{$id}{'logentry'}{'selfenroll'});
 6880:             } else {
 6881:                 next if ($roleslog{$id}{'logentry'}{'context'} ne $curr{'chgcontext'});
 6882:             }
 6883:         }
 6884:         if (($context eq 'course') && ($viewablesec ne '')) {
 6885:             next if ($roleslog{$id}{'logentry'}{'section'} ne $viewablesec);
 6886:         }
 6887:         $count ++;
 6888:         next if ($count < $minshown);
 6889:         unless ($showntableheader) {
 6890:             $r->print(&Apache::loncommon::start_data_table()
 6891:                      .$tableheader);
 6892:             $r->rflush();
 6893:             $showntableheader = 1;
 6894:         }
 6895:         if ($whodunit{$roleslog{$id}{'exe_uname'}.':'.$roleslog{$id}{'exe_udom'}} eq '') {
 6896:             $whodunit{$roleslog{$id}{'exe_uname'}.':'.$roleslog{$id}{'exe_udom'}} =
 6897:                 &Apache::loncommon::plainname($roleslog{$id}{'exe_uname'},$roleslog{$id}{'exe_udom'});
 6898:         }
 6899:         if ($changed{$roleslog{$id}{'uname'}.':'.$roleslog{$id}{'udom'}} eq '') {
 6900:             $changed{$roleslog{$id}{'uname'}.':'.$roleslog{$id}{'udom'}} =
 6901:                 &Apache::loncommon::plainname($roleslog{$id}{'uname'},$roleslog{$id}{'udom'});
 6902:         }
 6903:         my $sec = $roleslog{$id}{'logentry'}{'section'};
 6904:         if ($sec eq '') {
 6905:             $sec = &mt('None');
 6906:         }
 6907:         my ($rolestart,$roleend);
 6908:         if ($roleslog{$id}{'delflag'}) {
 6909:             $rolestart = &mt('deleted');
 6910:             $roleend = &mt('deleted');
 6911:         } else {
 6912:             $rolestart = $roleslog{$id}{'logentry'}{'start'};
 6913:             $roleend = $roleslog{$id}{'logentry'}{'end'};
 6914:             if ($rolestart eq '' || $rolestart == 0) {
 6915:                 $rolestart = &mt('No start date'); 
 6916:             } else {
 6917:                 $rolestart = &Apache::lonlocal::locallocaltime($rolestart);
 6918:             }
 6919:             if ($roleend eq '' || $roleend == 0) { 
 6920:                 $roleend = &mt('No end date');
 6921:             } else {
 6922:                 $roleend = &Apache::lonlocal::locallocaltime($roleend);
 6923:             }
 6924:         }
 6925:         my $chgcontext = $roleslog{$id}{'logentry'}{'context'};
 6926:         if ($roleslog{$id}{'logentry'}{'selfenroll'}) {
 6927:             $chgcontext = 'selfenroll';
 6928:         }
 6929:         my %lt = &rolechg_contexts($context,$crstype);
 6930:         if ($chgcontext ne '' && $lt{$chgcontext} ne '') {
 6931:             $chgcontext = $lt{$chgcontext};
 6932:         }
 6933:         $r->print(
 6934:             &Apache::loncommon::start_data_table_row()
 6935:            .'<td>'.$count.'</td>'
 6936:            .'<td>'.&Apache::lonlocal::locallocaltime($roleslog{$id}{'exe_time'}).'</td>'
 6937:            .'<td>'.$whodunit{$roleslog{$id}{'exe_uname'}.':'.$roleslog{$id}{'exe_udom'}}.'</td>'
 6938:            .'<td>'.$changed{$roleslog{$id}{'uname'}.':'.$roleslog{$id}{'udom'}}.'</td>'
 6939:            .'<td>'.&Apache::lonnet::plaintext($roleslog{$id}{'logentry'}{'role'},$crstype).'</td>');
 6940:         if ($context eq 'course') { 
 6941:             $r->print('<td>'.$sec.'</td>');
 6942:         }
 6943:         $r->print(
 6944:             '<td>'.$chgcontext.'</td>'
 6945:            .'<td>'.$rolestart.'</td>'
 6946:            .'<td>'.$roleend.'</td>'
 6947:            .&Apache::loncommon::end_data_table_row()."\n");
 6948:     }
 6949: 
 6950:     if ($showntableheader) { # Table footer, if content displayed above
 6951:         $r->print(&Apache::loncommon::end_data_table().
 6952:                   &userlogdisplay_navlinks(\%curr,$more_records));
 6953:     } else { # No content displayed above
 6954:         $r->print('<p class="LC_info">'
 6955:                  .&mt('There are no records to display.')
 6956:                  .'</p>'
 6957:         );
 6958:     }
 6959: 
 6960:     # Form Footer
 6961:     $r->print( 
 6962:         '<input type="hidden" name="page" value="'.$curr{'page'}.'" />'
 6963:        .'<input type="hidden" name="action" value="changelogs" />'
 6964:        .'</form>');
 6965:     return;
 6966: }
 6967: 
 6968: sub print_useraccesslogs_display {
 6969:     my ($r,$uname,$udom,$permission,$brcrum) = @_;
 6970:     my $formname = 'accesslog';
 6971:     my $form = 'document.accesslog';
 6972: 
 6973: # set breadcrumbs
 6974:     my %breadcrumb_text = &singleuser_breadcrumb('','domain',$udom);
 6975:     my $prevphasestr;
 6976:     if ($env{'form.popup'}) {
 6977:         $brcrum = [];
 6978:     } else {
 6979:         push (@{$brcrum},
 6980:             {href => "javascript:backPage($form)",
 6981:              text => $breadcrumb_text{'search'}});
 6982:         my @prevphases;
 6983:         if ($env{'form.prevphases'}) {
 6984:             @prevphases = split(/,/,$env{'form.prevphases'});
 6985:             $prevphasestr = $env{'form.prevphases'};
 6986:         }
 6987:         if (($env{'form.phase'} eq 'userpicked') || (grep(/^userpicked$/,@prevphases))) {
 6988:             push(@{$brcrum},
 6989:                   {href => "javascript:backPage($form,'get_user_info','select')",
 6990:                    text => $breadcrumb_text{'userpicked'}});
 6991:             if ($env{'form.phase'} eq 'userpicked') {
 6992:                 $prevphasestr = 'userpicked';
 6993:             }
 6994:         }
 6995:     }
 6996:     push(@{$brcrum},
 6997:              {href => '/adm/createuser?action=accesslogs',
 6998:               text => 'User access logs',
 6999:               help => 'Domain_User_Access_Logs'});
 7000:     my $bread_crumbs_component = 'User Access Logs';
 7001:     my $args = { bread_crumbs           => $brcrum,
 7002:                  bread_crumbs_component => 'User Management'};
 7003:     if ($env{'form.popup'}) {
 7004:         $args->{'no_nav_bar'} = 1;
 7005:         $args->{'bread_crumbs_nomenu'} = 1;
 7006:     }
 7007: 
 7008: # set javascript
 7009:     my ($jsback,$elements) = &crumb_utilities();
 7010:     my $jsnav = &userlogdisplay_js($formname);
 7011: 
 7012:     my $jscript = (<<ENDSCRIPT);
 7013: <script type="text/javascript">
 7014: // <![CDATA[
 7015: 
 7016: $jsback
 7017: $jsnav
 7018: 
 7019: // ]]>
 7020: </script>
 7021: 
 7022: ENDSCRIPT
 7023: 
 7024: # print page header
 7025:     $r->print(&header($jscript,$args));
 7026: 
 7027: # early out unless log data can be displayed.
 7028:     unless ($permission->{'activity'}) {
 7029:         $r->print('<p class="LC_warning">'
 7030:                  .&mt('You do not have rights to display user access logs.')
 7031:                  .'</p>');
 7032:         if ($env{'form.popup'}) {
 7033:             $r->print('<p><a href="javascript:window.close()">'.&mt('Close window').'</a></p>');
 7034:         } else {
 7035:             $r->print(&earlyout_accesslog_form($formname,$prevphasestr,$udom));
 7036:         }
 7037:         return;
 7038:     }
 7039: 
 7040:     unless ($udom eq $env{'request.role.domain'}) {
 7041:         $r->print('<p class="LC_warning">'
 7042:                  .&mt("User's domain must match role's domain")
 7043:                  .'</p>'
 7044:                  .&earlyout_accesslog_form($formname,$prevphasestr,$udom));
 7045:         return;
 7046:     }
 7047: 
 7048:     if (($uname eq '') || ($udom eq '')) {
 7049:         $r->print('<p class="LC_warning">'
 7050:                  .&mt('Invalid username or domain')
 7051:                  .'</p>'
 7052:                  .&earlyout_accesslog_form($formname,$prevphasestr,$udom));
 7053:         return;
 7054:     }
 7055: 
 7056:     if (&Apache::lonnet::privileged($uname,$udom,
 7057:                                     [$env{'request.role.domain'}],['dc','su'])) {
 7058:         unless (&Apache::lonnet::privileged($env{'user.name'},$env{'user.domain'},
 7059:                                             [$env{'request.role.domain'}],['dc','su'])) {
 7060:             $r->print('<p class="LC_warning">'
 7061:                  .&mt('You need to be a privileged user to display user access logs for [_1]',
 7062:                       &Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($uname,$udom),
 7063:                                                          $uname,$udom))
 7064:                  .'</p>');
 7065:             if ($env{'form.popup'}) {
 7066:                 $r->print('<p><a href="javascript:window.close()">'.&mt('Close window').'</a></p>');
 7067:             } else {
 7068:                 $r->print(&earlyout_accesslog_form($formname,$prevphasestr,$udom));
 7069:             }
 7070:             return;
 7071:         }
 7072:     }
 7073: 
 7074: # set defaults
 7075:     my $now = time();
 7076:     my $defstart = $now - (7*24*3600);
 7077:     my %defaults = (
 7078:                      page                 => '1',
 7079:                      show                 => '10',
 7080:                      activity             => 'any',
 7081:                      accesslog_start_date => $defstart,
 7082:                      accesslog_end_date   => $now,
 7083:                    );
 7084:     my $more_records = 0;
 7085: 
 7086: # set current
 7087:     my %curr;
 7088:     foreach my $item ('show','page','activity') {
 7089:         $curr{$item} = $env{'form.'.$item};
 7090:     }
 7091:     my ($startdate,$enddate) =
 7092:         &Apache::lonuserutils::get_dates_from_form('accesslog_start_date','accesslog_end_date');
 7093:     $curr{'accesslog_start_date'} = $startdate;
 7094:     $curr{'accesslog_end_date'} = $enddate;
 7095:     foreach my $key (keys(%defaults)) {
 7096:         if ($curr{$key} eq '') {
 7097:             $curr{$key} = $defaults{$key};
 7098:         }
 7099:     }
 7100:     my ($minshown,$maxshown);
 7101:     $minshown = 1;
 7102:     my $count = 0;
 7103:     if ($curr{'show'} =~ /\D/) {
 7104:         $curr{'page'} = 1;
 7105:     } else {
 7106:         $maxshown = $curr{'page'} * $curr{'show'};
 7107:         if ($curr{'page'} > 1) {
 7108:             $minshown = 1 + ($curr{'page'} - 1) * $curr{'show'};
 7109:         }
 7110:     }
 7111: 
 7112: # form header
 7113:     $r->print('<form action="/adm/createuser" method="post" name="'.$formname.'">'.
 7114:               &activity_display_filter($formname,\%curr));
 7115: 
 7116:     my $showntableheader = 0;
 7117:     my ($nav_script,$nav_links);
 7118: 
 7119: # table header
 7120:     my $heading = '<h3>'.
 7121:         &mt('User access logs for: [_1]',
 7122:             &Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($uname,$udom),$uname,$udom)).'</h3>';
 7123:     my $tableheader = $heading
 7124:        .&Apache::loncommon::start_data_table_header_row()
 7125:        .'<th>&nbsp;</th>'
 7126:        .'<th>'.&mt('When').'</th>'
 7127:        .'<th>'.&mt('HostID').'</th>'
 7128:        .'<th>'.&mt('Event').'</th>'
 7129:        .'<th>'.&mt('Other data').'</th>'
 7130:        .&Apache::loncommon::end_data_table_header_row();
 7131: 
 7132:     my %filters=(
 7133:         start  => $curr{'accesslog_start_date'},
 7134:         end    => $curr{'accesslog_end_date'},
 7135:         action => $curr{'activity'},
 7136:     );
 7137: 
 7138:     my $reply = &Apache::lonnet::userlog_query($uname,$udom,%filters);
 7139:     unless ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 7140:         my (%courses,%missing);
 7141:         my @results = split(/\&/,$reply);
 7142:         foreach my $item (reverse(@results)) {
 7143:             my ($timestamp,$host,$event) = split(/:/,$item);
 7144:             next unless ($event =~ /^(Log|Role)/);
 7145:             if ($curr{'show'} !~ /\D/) {
 7146:                 if ($count >= $curr{'page'} * $curr{'show'}) {
 7147:                     $more_records = 1;
 7148:                     last;
 7149:                 }
 7150:             }
 7151:             $count ++;
 7152:             next if ($count < $minshown);
 7153:             unless ($showntableheader) {
 7154:                 $r->print($nav_script
 7155:                          .&Apache::loncommon::start_data_table()
 7156:                          .$tableheader);
 7157:                 $r->rflush();
 7158:                 $showntableheader = 1;
 7159:             }
 7160:             my ($shown,$extra);
 7161:             my ($event,$data) = split(/\s+/,&unescape($event),2);
 7162:             if ($event eq 'Role') {
 7163:                 my ($rolecode,$extent) = split(/\./,$data,2);
 7164:                 next if ($extent eq '');
 7165:                 my ($crstype,$desc,$info);
 7166:                 if ($extent =~ m{^/($match_domain)/($match_courseid)(?:/(\w+)|)$}) {
 7167:                     my ($cdom,$cnum,$sec) = ($1,$2,$3);
 7168:                     my $cid = $cdom.'_'.$cnum;
 7169:                     if (exists($courses{$cid})) {
 7170:                         $crstype = $courses{$cid}{'type'};
 7171:                         $desc = $courses{$cid}{'description'};
 7172:                     } elsif ($missing{$cid}) {
 7173:                         $crstype = 'Course';
 7174:                         $desc = 'Course/Community';
 7175:                     } else {
 7176:                         my %crsinfo = &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 7177:                         if (ref($crsinfo{$cdom.'_'.$cnum}) eq 'HASH') {
 7178:                             $courses{$cid} = $crsinfo{$cid};
 7179:                             $crstype = $crsinfo{$cid}{'type'};
 7180:                             $desc = $crsinfo{$cid}{'description'};
 7181:                         } else {
 7182:                             $missing{$cid} = 1;
 7183:                         }
 7184:                     }
 7185:                     $extra = &mt($crstype).': <a href="/public/'.$cdom.'/'.$cnum.'/syllabus">'.$desc.'</a>';
 7186:                     if ($sec ne '') {
 7187:                        $extra .= ' ('.&mt('Section: [_1]',$sec).')';
 7188:                     }
 7189:                 } elsif ($extent =~ m{^/($match_domain)/($match_username|$)}) {
 7190:                     my ($dom,$name) = ($1,$2);
 7191:                     if ($rolecode eq 'au') {
 7192:                         $extra = '';
 7193:                     } elsif ($rolecode =~ /^(ca|aa)$/) {
 7194:                         $extra = &mt('Authoring Space: [_1]',$name.':'.$dom);
 7195:                     } elsif ($rolecode =~ /^(li|dg|dh|dc|sc)$/) {
 7196:                         $extra = &mt('Domain: [_1]',$dom);
 7197:                     }
 7198:                 }
 7199:                 my $rolename;
 7200:                 if ($rolecode =~ m{^cr/($match_domain)/($match_username)/(\w+)}) {
 7201:                     my $role = $3;
 7202:                     my $owner = "($2:$1)";
 7203:                     if ($2 eq $1.'-domainconfig') {
 7204:                         $owner = '(ad hoc)';
 7205:                     }
 7206:                     $rolename = &mt('Custom role: [_1]',$role.' '.$owner);
 7207:                 } else {
 7208:                     $rolename = &Apache::lonnet::plaintext($rolecode,$crstype);
 7209:                 }
 7210:                 $shown = &mt('Role selection: [_1]',$rolename);
 7211:             } else {
 7212:                 $shown = &mt($event);
 7213:                 if ($data =~ /^webdav/) {
 7214:                     my ($path,$clientip) = split(/\s+/,$data,2);
 7215:                     $path =~ s/^webdav//;
 7216:                     if ($clientip ne '') {
 7217:                         $extra = &mt('Client IP address: [_1]',$clientip);
 7218:                     }
 7219:                     if ($path ne '') {
 7220:                         $shown .= ' '.&mt('(WebDAV access to [_1])',$path);
 7221:                     }
 7222:                 } elsif ($data ne '') {
 7223:                     $extra = &mt('Client IP address: [_1]',$data);
 7224:                 }
 7225:             }
 7226:             $r->print(
 7227:             &Apache::loncommon::start_data_table_row()
 7228:            .'<td>'.$count.'</td>'
 7229:            .'<td>'.&Apache::lonlocal::locallocaltime($timestamp).'</td>'
 7230:            .'<td>'.$host.'</td>'
 7231:            .'<td>'.$shown.'</td>'
 7232:            .'<td>'.$extra.'</td>'
 7233:            .&Apache::loncommon::end_data_table_row()."\n");
 7234:         }
 7235:     }
 7236: 
 7237:     if ($showntableheader) { # Table footer, if content displayed above
 7238:         $r->print(&Apache::loncommon::end_data_table().
 7239:                   &userlogdisplay_navlinks(\%curr,$more_records));
 7240:     } else { # No content displayed above
 7241:         $r->print($heading.'<p class="LC_info">'
 7242:                  .&mt('There are no records to display.')
 7243:                  .'</p>');
 7244:     }
 7245: 
 7246:     if ($env{'form.popup'} == 1) {
 7247:         $r->print('<input type="hidden" name="popup" value="1" />'."\n");
 7248:     }
 7249: 
 7250:     # Form Footer
 7251:     $r->print(
 7252:         '<input type="hidden" name="currstate" value="" />'
 7253:        .'<input type="hidden" name="accessuname" value="'.$uname.'" />'
 7254:        .'<input type="hidden" name="accessudom" value="'.$udom.'" />'
 7255:        .'<input type="hidden" name="page" value="'.$curr{'page'}.'" />'
 7256:        .'<input type="hidden" name="prevphases" value="'.$prevphasestr.'" />'
 7257:        .'<input type="hidden" name="phase" value="activity" />'
 7258:        .'<input type="hidden" name="action" value="accesslogs" />'
 7259:        .'<input type="hidden" name="srchdomain" value="'.$udom.'" />'
 7260:        .'<input type="hidden" name="srchby" value="'.$env{'form.srchby'}.'" />'
 7261:        .'<input type="hidden" name="srchtype" value="'.$env{'form.srchtype'}.'" />'
 7262:        .'<input type="hidden" name="srchterm" value="'.&HTML::Entities::encode($env{'form.srchterm'},'<>"&').'" />'
 7263:        .'<input type="hidden" name="srchin" value="'.$env{'form.srchin'}.'" />'
 7264:        .'</form>');
 7265:     return;
 7266: }
 7267: 
 7268: sub earlyout_accesslog_form {
 7269:     my ($formname,$prevphasestr,$udom) = @_;
 7270:     my $srchterm = &HTML::Entities::encode($env{'form.srchterm'},'<>"&');
 7271:    return <<"END";
 7272: <form action="/adm/createuser" method="post" name="$formname">
 7273: <input type="hidden" name="currstate" value="" />
 7274: <input type="hidden" name="prevphases" value="$prevphasestr" />
 7275: <input type="hidden" name="phase" value="activity" />
 7276: <input type="hidden" name="action" value="accesslogs" />
 7277: <input type="hidden" name="srchdomain" value="$udom" />
 7278: <input type="hidden" name="srchby" value="$env{'form.srchby'}" />
 7279: <input type="hidden" name="srchtype" value="$env{'form.srchtype'}" />
 7280: <input type="hidden" name="srchterm" value="$srchterm" />
 7281: <input type="hidden" name="srchin" value="$env{'form.srchin'}" />
 7282: </form>
 7283: END
 7284: }
 7285: 
 7286: sub activity_display_filter {
 7287:     my ($formname,$curr) = @_;
 7288:     my $nolink = 1;
 7289:     my $output = '<table><tr><td valign="top">'.
 7290:                  '<span class="LC_nobreak"><b>'.&mt('Actions/page:').'</b></span><br />'.
 7291:                  &Apache::lonmeta::selectbox('show',$curr->{'show'},undef,
 7292:                                               (&mt('all'),5,10,20,50,100,1000,10000)).
 7293:                  '</td><td>&nbsp;&nbsp;</td>';
 7294:     my $startform =
 7295:         &Apache::lonhtmlcommon::date_setter($formname,'accesslog_start_date',
 7296:                                             $curr->{'accesslog_start_date'},undef,
 7297:                                             undef,undef,undef,undef,undef,undef,$nolink);
 7298:     my $endform =
 7299:         &Apache::lonhtmlcommon::date_setter($formname,'accesslog_end_date',
 7300:                                             $curr->{'accesslog_end_date'},undef,
 7301:                                             undef,undef,undef,undef,undef,undef,$nolink);
 7302:     my %lt = &Apache::lonlocal::texthash (
 7303:                                           activity => 'Activity',
 7304:                                           Role     => 'Role selection',
 7305:                                           log      => 'Log-in or Logout',
 7306:     );
 7307:     $output .= '<td valign="top"><b>'.&mt('Window during which actions occurred:').'</b><br />'.
 7308:                '<table><tr><td>'.&mt('After:').
 7309:                '</td><td>'.$startform.'</td></tr>'.
 7310:                '<tr><td>'.&mt('Before:').'</td>'.
 7311:                '<td>'.$endform.'</td></tr></table>'.
 7312:                '</td>'.
 7313:                '<td>&nbsp;&nbsp;</td>'.
 7314:                '<td valign="top"><b>'.&mt('Activities').'</b><br />'.
 7315:                '<select name="activity"><option value="any"';
 7316:     if ($curr->{'activity'} eq 'any') {
 7317:         $output .= ' selected="selected"';
 7318:     }
 7319:     $output .= '>'.&mt('Any').'</option>'."\n";
 7320:     foreach my $activity ('Role','log') {
 7321:         my $selstr = '';
 7322:         if ($activity eq $curr->{'activity'}) {
 7323:             $selstr = ' selected="selected"';
 7324:         }
 7325:         $output .= '<option value="'.$activity.'"'.$selstr.'>'.$lt{$activity}.'</option>';
 7326:     }
 7327:     $output .= '</select></td>'.
 7328:                '</tr></table>';
 7329:     # Update Display button
 7330:     $output .= '<p>'
 7331:               .'<input type="submit" value="'.&mt('Update Display').'" />'
 7332:               .'</p><hr />';
 7333:     return $output;
 7334: }
 7335: 
 7336: sub userlogdisplay_js {
 7337:     my ($formname) = @_;
 7338:     return <<"ENDSCRIPT";
 7339: 
 7340: function chgPage(caller) {
 7341:     if (caller == 'previous') {
 7342:         document.$formname.page.value --;
 7343:     }
 7344:     if (caller == 'next') {
 7345:         document.$formname.page.value ++;
 7346:     }
 7347:     document.$formname.submit();
 7348:     return;
 7349: }
 7350: ENDSCRIPT
 7351: }
 7352: 
 7353: sub userlogdisplay_navlinks {
 7354:     my ($curr,$more_records) = @_;
 7355:     return unless(ref($curr) eq 'HASH');
 7356:     # Navigation Buttons
 7357:     my $nav_links = '<p>';
 7358:     if (($curr->{'page'} > 1) || ($more_records)) {
 7359:         if (($curr->{'page'} > 1) && ($curr->{'show'} !~ /\D/)) {
 7360:             $nav_links .= '<input type="button"'
 7361:                          .' onclick="javascript:chgPage('."'previous'".');"'
 7362:                          .' value="'.&mt('Previous [_1] changes',$curr->{'show'})
 7363:                          .'" /> ';
 7364:         }
 7365:         if ($more_records) {
 7366:             $nav_links .= '<input type="button"'
 7367:                          .' onclick="javascript:chgPage('."'next'".');"'
 7368:                          .' value="'.&mt('Next [_1] changes',$curr->{'show'})
 7369:                          .'" />';
 7370:         }
 7371:     }
 7372:     $nav_links .= '</p>';
 7373:     return $nav_links;
 7374: }
 7375: 
 7376: sub role_display_filter {
 7377:     my ($context,$formname,$cdom,$cnum,$curr,$version,$crstype) = @_;
 7378:     my $lctype;
 7379:     if ($context eq 'course') {
 7380:         $lctype = lc($crstype);
 7381:     }
 7382:     my $nolink = 1;
 7383:     my $output = '<table><tr><td valign="top">'.
 7384:                  '<span class="LC_nobreak"><b>'.&mt('Changes/page:').'</b></span><br />'.
 7385:                  &Apache::lonmeta::selectbox('show',$curr->{'show'},undef,
 7386:                                               (&mt('all'),5,10,20,50,100,1000,10000)).
 7387:                  '</td><td>&nbsp;&nbsp;</td>';
 7388:     my $startform =
 7389:         &Apache::lonhtmlcommon::date_setter($formname,'rolelog_start_date',
 7390:                                             $curr->{'rolelog_start_date'},undef,
 7391:                                             undef,undef,undef,undef,undef,undef,$nolink);
 7392:     my $endform =
 7393:         &Apache::lonhtmlcommon::date_setter($formname,'rolelog_end_date',
 7394:                                             $curr->{'rolelog_end_date'},undef,
 7395:                                             undef,undef,undef,undef,undef,undef,$nolink);
 7396:     my %lt = &rolechg_contexts($context,$crstype);
 7397:     $output .= '<td valign="top"><b>'.&mt('Window during which changes occurred:').'</b><br />'.
 7398:                '<table><tr><td>'.&mt('After:').
 7399:                '</td><td>'.$startform.'</td></tr>'.
 7400:                '<tr><td>'.&mt('Before:').'</td>'.
 7401:                '<td>'.$endform.'</td></tr></table>'.
 7402:                '</td>'.
 7403:                '<td>&nbsp;&nbsp;</td>'.
 7404:                '<td valign="top"><b>'.&mt('Role:').'</b><br />'.
 7405:                '<select name="role"><option value="any"';
 7406:     if ($curr->{'role'} eq 'any') {
 7407:         $output .= ' selected="selected"';
 7408:     }
 7409:     $output .=  '>'.&mt('Any').'</option>'."\n";
 7410:     my @roles = &Apache::lonuserutils::roles_by_context($context,1,$crstype);
 7411:     foreach my $role (@roles) {
 7412:         my $plrole;
 7413:         if ($role eq 'cr') {
 7414:             $plrole = &mt('Custom Role');
 7415:         } else {
 7416:             $plrole=&Apache::lonnet::plaintext($role,$crstype);
 7417:         }
 7418:         my $selstr = '';
 7419:         if ($role eq $curr->{'role'}) {
 7420:             $selstr = ' selected="selected"';
 7421:         }
 7422:         $output .= '  <option value="'.$role.'"'.$selstr.'>'.$plrole.'</option>';
 7423:     }
 7424:     $output .= '</select></td>'.
 7425:                '<td>&nbsp;&nbsp;</td>'.
 7426:                '<td valign="top"><b>'.
 7427:                &mt('Context:').'</b><br /><select name="chgcontext">';
 7428:     my @posscontexts;
 7429:     if ($context eq 'course') {
 7430:         @posscontexts = ('any','automated','updatenow','createcourse','course','domain','selfenroll','requestcourses','chgtype');
 7431:     } elsif ($context eq 'domain') {
 7432:         @posscontexts = ('any','domain','requestauthor','domconfig','server');
 7433:     } else {
 7434:         @posscontexts = ('any','author','domain');
 7435:     }
 7436:     foreach my $chgtype (@posscontexts) {
 7437:         my $selstr = '';
 7438:         if ($curr->{'chgcontext'} eq $chgtype) {
 7439:             $selstr = ' selected="selected"';
 7440:         }
 7441:         if ($context eq 'course') {
 7442:             if (($chgtype eq 'automated') || ($chgtype eq 'updatenow')) {
 7443:                 next if (!&Apache::lonnet::auto_run($cnum,$cdom));
 7444:             }
 7445:         }
 7446:         $output .= '<option value="'.$chgtype.'"'.$selstr.'>'.$lt{$chgtype}.'</option>'."\n";
 7447:     }
 7448:     $output .= '</select></td>'
 7449:               .'</tr></table>';
 7450: 
 7451:     # Update Display button
 7452:     $output .= '<p>'
 7453:               .'<input type="submit" value="'.&mt('Update Display').'" />'
 7454:               .'</p>';
 7455: 
 7456:     # Server version info
 7457:     my $needsrev = '2.11.0';
 7458:     if ($context eq 'course') {
 7459:         $needsrev = '2.7.0';
 7460:     }
 7461:     
 7462:     $output .= '<p class="LC_info">'
 7463:               .&mt('Only changes made from servers running LON-CAPA [_1] or later are displayed.'
 7464:                   ,$needsrev);
 7465:     if ($version) {
 7466:         $output .= ' '.&mt('This LON-CAPA server is version [_1]',$version);
 7467:     }
 7468:     $output .= '</p><hr />';
 7469:     return $output;
 7470: }
 7471: 
 7472: sub rolechg_contexts {
 7473:     my ($context,$crstype) = @_;
 7474:     my %lt;
 7475:     if ($context eq 'course') {
 7476:         %lt = &Apache::lonlocal::texthash (
 7477:                                              any          => 'Any',
 7478:                                              automated    => 'Automated Enrollment',
 7479:                                              chgtype      => 'Enrollment Type/Lock Change',
 7480:                                              updatenow    => 'Roster Update',
 7481:                                              createcourse => 'Course Creation',
 7482:                                              course       => 'User Management in course',
 7483:                                              domain       => 'User Management in domain',
 7484:                                              selfenroll   => 'Self-enrolled',
 7485:                                              requestcourses => 'Course Request',
 7486:                                          );
 7487:         if ($crstype eq 'Community') {
 7488:             $lt{'createcourse'} = &mt('Community Creation');
 7489:             $lt{'course'} = &mt('User Management in community');
 7490:             $lt{'requestcourses'} = &mt('Community Request');
 7491:         }
 7492:     } elsif ($context eq 'domain') {
 7493:         %lt = &Apache::lonlocal::texthash (
 7494:                                              any           => 'Any',
 7495:                                              domain        => 'User Management in domain',
 7496:                                              requestauthor => 'Authoring Request',
 7497:                                              server        => 'Command line script (DC role)',
 7498:                                              domconfig     => 'Self-enrolled',
 7499:                                          );
 7500:     } else {
 7501:         %lt = &Apache::lonlocal::texthash (
 7502:                                              any    => 'Any',
 7503:                                              domain => 'User Management in domain',
 7504:                                              author => 'User Management by author',
 7505:                                          );
 7506:     } 
 7507:     return %lt;
 7508: }
 7509: 
 7510: sub print_helpdeskaccess_display {
 7511:     my ($r,$permission,$brcrum) = @_;
 7512:     my $formname = 'helpdeskaccess';
 7513:     my $helpitem = 'Course_Helpdesk_Access';
 7514:     push (@{$brcrum},
 7515:              {href => '/adm/createuser?action=helpdesk',
 7516:               text => 'Helpdesk Access',
 7517:               help => $helpitem});
 7518:     my $bread_crumbs_component = 'Helpdesk Staff Access';
 7519:     my $args = { bread_crumbs           => $brcrum,
 7520:                  bread_crumbs_component => $bread_crumbs_component};
 7521: 
 7522:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7523:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7524:     my $confname = $cdom.'-domainconfig';
 7525:     my $crstype = &Apache::loncommon::course_type();
 7526: 
 7527:     my @accesstypes = ('all','dh','da','none');
 7528:     my ($numstatustypes,@jsarray);
 7529:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($cdom);
 7530:     if (ref($types) eq 'ARRAY') {
 7531:         if (@{$types} > 0) {
 7532:             $numstatustypes = scalar(@{$types});
 7533:             push(@accesstypes,'status');
 7534:             @jsarray = ('bystatus');
 7535:         }
 7536:     }
 7537:     my %customroles = &get_domain_customroles($cdom,$confname);
 7538:     my %domhelpdesk = &Apache::lonnet::get_active_domroles($cdom,['dh','da']);
 7539:     if (keys(%domhelpdesk)) {
 7540:        push(@accesstypes,('inc','exc'));
 7541:        push(@jsarray,('notinc','notexc'));
 7542:     }
 7543:     push(@jsarray,'privs');
 7544:     my $hiddenstr = join("','",@jsarray);
 7545:     my $rolestr = join("','",sort(keys(%customroles)));
 7546: 
 7547:     my $jscript;
 7548:     my (%settings,%overridden);
 7549:     if (keys(%customroles)) {
 7550:         &get_adhocrole_settings($env{'request.course.id'},\@accesstypes,
 7551:                                 $types,\%customroles,\%settings,\%overridden);
 7552:         my %jsfull=();
 7553:         my %jslevels= (
 7554:                      course => {},
 7555:                      domain => {},
 7556:                      system => {},
 7557:                     );
 7558:         my %jslevelscurrent=(
 7559:                            course => {},
 7560:                            domain => {},
 7561:                            system => {},
 7562:                           );
 7563:         my (%privs,%jsprivs);
 7564:         &Apache::lonuserutils::custom_role_privs(\%privs,\%jsfull,\%jslevels,\%jslevelscurrent);
 7565:         foreach my $priv (keys(%jsfull)) {
 7566:             if ($jslevels{'course'}{$priv}) {
 7567:                 $jsprivs{$priv} = 1;
 7568:             }
 7569:         }
 7570:         my (%elements,%stored);
 7571:         foreach my $role (keys(%customroles)) {
 7572:             $elements{$role.'_access'} = 'radio';
 7573:             $elements{$role.'_incrs'} = 'radio';
 7574:             if ($numstatustypes) {
 7575:                 $elements{$role.'_status'} = 'checkbox';
 7576:             }
 7577:             if (keys(%domhelpdesk) > 0) {
 7578:                 $elements{$role.'_staff_inc'} = 'checkbox';
 7579:                 $elements{$role.'_staff_exc'} = 'checkbox';
 7580:             }
 7581:             $elements{$role.'_override'} = 'checkbox';
 7582:             if (ref($settings{$role}) eq 'HASH') {
 7583:                 if ($settings{$role}{'access'} ne '') {
 7584:                     my $curraccess = $settings{$role}{'access'};
 7585:                     $stored{$role.'_access'} = $curraccess;
 7586:                     $stored{$role.'_incrs'} = 1;
 7587:                     if ($curraccess eq 'status') {
 7588:                         if (ref($settings{$role}{'status'}) eq 'ARRAY') {
 7589:                             $stored{$role.'_status'} = $settings{$role}{'status'};
 7590:                         }
 7591:                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 7592:                         if (ref($settings{$role}{$curraccess}) eq 'ARRAY') {
 7593:                             $stored{$role.'_staff_'.$curraccess} = $settings{$role}{$curraccess};
 7594:                         }
 7595:                     }
 7596:                 } else {
 7597:                     $stored{$role.'_incrs'} = 0;
 7598:                 }
 7599:                 $stored{$role.'_override'} = [];
 7600:                 if ($env{'course.'.$env{'request.course.id'}.'.internal.adhocpriv.'.$role}) {
 7601:                     if (ref($settings{$role}{'off'}) eq 'ARRAY') {
 7602:                         foreach my $priv (@{$settings{$role}{'off'}}) {
 7603:                             push(@{$stored{$role.'_override'}},$priv);
 7604:                         }
 7605:                     }
 7606:                     if (ref($settings{$role}{'on'}) eq 'ARRAY') {
 7607:                         foreach my $priv (@{$settings{$role}{'on'}}) {
 7608:                             unless (grep(/^$priv$/,@{$stored{$role.'_override'}})) {
 7609:                                 push(@{$stored{$role.'_override'}},$priv);
 7610:                             }
 7611:                         }
 7612:                     }
 7613:                 }
 7614:             } else {
 7615:                 $stored{$role.'_incrs'} = 0;
 7616:             }
 7617:         }
 7618:         $jscript = &Apache::lonhtmlcommon::set_form_elements(\%elements,\%stored);
 7619:     }
 7620: 
 7621:     my $js = <<"ENDJS";
 7622: <script type="text/javascript">
 7623: // <![CDATA[
 7624: $jscript;
 7625: 
 7626: function switchRoleTab(caller,role) {
 7627:     if (document.getElementById(role+'_maindiv')) {
 7628:         if (caller.id != 'LC_current_minitab') {
 7629:             if (document.getElementById('LC_current_minitab')) {
 7630:                 document.getElementById('LC_current_minitab').id=null;
 7631:             }
 7632:             var roledivs = Array('$rolestr');
 7633:             if (roledivs.length > 0) {
 7634:                 for (var i=0; i<roledivs.length; i++) {
 7635:                     if (document.getElementById(roledivs[i]+'_maindiv')) {
 7636:                         document.getElementById(roledivs[i]+'_maindiv').style.display='none';
 7637:                     }
 7638:                 }
 7639:             }
 7640:             caller.id = 'LC_current_minitab';
 7641:             document.getElementById(role+'_maindiv').style.display='block';
 7642:         }
 7643:     }
 7644:     return false;
 7645: }
 7646: 
 7647: function helpdeskAccess(role) {
 7648:     var curraccess = null;
 7649:     if (document.$formname.elements[role+'_access'].length) {
 7650:         for (var i=0; i<document.$formname.elements[role+'_access'].length; i++) {
 7651:             if (document.$formname.elements[role+'_access'][i].checked) {
 7652:                 curraccess = document.$formname.elements[role+'_access'][i].value;
 7653:             }
 7654:         }
 7655:     }
 7656:     var shown = Array();
 7657:     var hidden = Array();
 7658:     if (curraccess == 'none') {
 7659:         hidden = Array ('$hiddenstr');
 7660:     } else {
 7661:         if (curraccess == 'status') {
 7662:             shown = Array ('bystatus','privs');
 7663:             hidden = Array ('notinc','notexc');
 7664:         } else {
 7665:             if (curraccess == 'exc') {
 7666:                 shown = Array ('notexc','privs');
 7667:                 hidden = Array ('notinc','bystatus');
 7668:             }
 7669:             if (curraccess == 'inc') {
 7670:                 shown = Array ('notinc','privs');
 7671:                 hidden = Array ('notexc','bystatus');
 7672:             }
 7673:             if (curraccess == 'all') {
 7674:                 shown = Array ('privs');
 7675:                 hidden = Array ('notinc','notexc','bystatus');
 7676:             }
 7677:         }
 7678:     }
 7679:     if (hidden.length > 0) {
 7680:         for (var i=0; i<hidden.length; i++) {
 7681:             if (document.getElementById(role+'_'+hidden[i])) {
 7682:                 document.getElementById(role+'_'+hidden[i]).style.display = 'none';
 7683:             }
 7684:         }
 7685:     }
 7686:     if (shown.length > 0) {
 7687:         for (var i=0; i<shown.length; i++) {
 7688:             if (document.getElementById(role+'_'+shown[i])) {
 7689:                 if (shown[i] == 'privs') {
 7690:                     document.getElementById(role+'_'+shown[i]).style.display = 'block';
 7691:                 } else {
 7692:                     document.getElementById(role+'_'+shown[i]).style.display = 'inline';
 7693:                 }
 7694:             }
 7695:         }
 7696:     }
 7697:     return;
 7698: }
 7699: 
 7700: function toggleAccess(role) {
 7701:     if ((document.getElementById(role+'_setincrs')) &&
 7702:         (document.getElementById(role+'_setindom'))) {
 7703:         for (var i=0; i<document.$formname.elements[role+'_incrs'].length; i++) {
 7704:             if (document.$formname.elements[role+'_incrs'][i].checked) {
 7705:                 if (document.$formname.elements[role+'_incrs'][i].value == 1) {
 7706:                     document.getElementById(role+'_setindom').style.display = 'none';
 7707:                     document.getElementById(role+'_setincrs').style.display = 'block';
 7708:                 } else {
 7709:                     document.getElementById(role+'_setincrs').style.display = 'none';
 7710:                     document.getElementById(role+'_setindom').style.display = 'block';
 7711:                 }
 7712:                 break;
 7713:             }
 7714:         }
 7715:     }
 7716:     return;
 7717: }
 7718: 
 7719: // ]]>
 7720: </script>
 7721: ENDJS
 7722: 
 7723:     $args->{add_entries} = {onload => "javascript:setFormElements(document.$formname)"};
 7724: 
 7725:     # print page header
 7726:     $r->print(&header($js,$args));
 7727:     # print form header
 7728:     $r->print('<form action="/adm/createuser" method="post" name="'.$formname.'">');
 7729: 
 7730:     if (keys(%customroles)) {
 7731:         my %lt = &Apache::lonlocal::texthash(
 7732:                     'aco'    => 'As course owner you may override the defaults set in the domain for role usage and/or privileges.',
 7733:                     'rou'    => 'Role usage',
 7734:                     'whi'    => 'Which helpdesk personnel may use this role?',
 7735:                     'udd'    => 'Use domain default',
 7736:                     'all'    => 'All with domain helpdesk or helpdesk assistant role',
 7737:                     'dh'     => 'All with domain helpdesk role',
 7738:                     'da'     => 'All with domain helpdesk assistant role',
 7739:                     'none'   => 'None',
 7740:                     'status' => 'Determined based on institutional status',
 7741:                     'inc'    => 'Include all, but exclude specific personnel',
 7742:                     'exc'    => 'Exclude all, but include specific personnel',
 7743:                     'hel'    => 'Helpdesk',
 7744:                     'rpr'    => 'Role privileges',
 7745:                  );
 7746:         $lt{'tfh'} = &mt("Custom [_1]ad hoc[_2] course roles available for use by the domain's helpdesk are as follows",'<i>','</i>');
 7747:         my %domconfig = &Apache::lonnet::get_dom('configuration',['helpsettings'],$cdom);
 7748:         my (%domcurrent,%ordered,%description,%domusage,$disabled);
 7749:         if (ref($domconfig{'helpsettings'}) eq 'HASH') {
 7750:             if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
 7751:                 %domcurrent = %{$domconfig{'helpsettings'}{'adhoc'}};
 7752:             }
 7753:         }
 7754:         my $count = 0;
 7755:         foreach my $role (sort(keys(%customroles))) {
 7756:             my ($order,$desc,$access_in_dom);
 7757:             if (ref($domcurrent{$role}) eq 'HASH') {
 7758:                 $order = $domcurrent{$role}{'order'};
 7759:                 $desc = $domcurrent{$role}{'desc'};
 7760:                 $access_in_dom = $domcurrent{$role}{'access'};
 7761:             }
 7762:             if ($order eq '') {
 7763:                 $order = $count;
 7764:             }
 7765:             $ordered{$order} = $role;
 7766:             if ($desc ne '') {
 7767:                 $description{$role} = $desc;
 7768:             } else {
 7769:                 $description{$role}= $role;
 7770:             }
 7771:             $count++;
 7772:         }
 7773:         %domusage = &domain_adhoc_access(\%customroles,\%domcurrent,\@accesstypes,$usertypes,$othertitle);
 7774:         my @roles_by_num = ();
 7775:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 7776:             push(@roles_by_num,$ordered{$item});
 7777:         }
 7778:         $r->print('<p>'.$lt{'tfh'}.': <i>'.join('</i>, <i>',map { $description{$_}; } @roles_by_num).'</i>.');
 7779:         if ($permission->{'owner'}) {
 7780:             $r->print('<br />'.$lt{'aco'}.'</p><p>');
 7781:             $r->print('<input type="hidden" name="state" value="process" />'.
 7782:                       '<input type="submit" value="'.&mt('Save changes').'" />');
 7783:         } else {
 7784:             if ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'}) {
 7785:                 my ($ownername,$ownerdom) = split(/:/,$env{'course.'.$env{'request.course.id'}.'.internal.courseowner'});
 7786:                 $r->print('<br />'.&mt('The course owner -- [_1] -- can override the default access and/or privileges for these ad hoc roles.',
 7787:                                     &Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($ownername,$ownerdom),$ownername,$ownerdom)));
 7788:             }
 7789:             $disabled = ' disabled="disabled"';
 7790:         }
 7791:         $r->print('</p>');
 7792: 
 7793:         $r->print('<div id="LC_minitab_header"><ul>');
 7794:         my $count = 0;
 7795:         my %visibility;
 7796:         foreach my $role (@roles_by_num) {
 7797:             my $id;
 7798:             if ($count == 0) {
 7799:                 $id=' id="LC_current_minitab"';
 7800:                 $visibility{$role} = ' style="display:block"';
 7801:             } else {
 7802:                 $visibility{$role} = ' style="display:none"';
 7803:             }
 7804:             $count ++;
 7805:             $r->print('<li'.$id.'><a href="#" onclick="javascript:switchRoleTab(this.parentNode,'."'$role'".');">'.$description{$role}.'</a></li>');
 7806:         }
 7807:         $r->print('</ul></div>');
 7808: 
 7809:         foreach my $role (@roles_by_num) {
 7810:             my %usecheck = (
 7811:                              all => ' checked="checked"',
 7812:                            );
 7813:             my %displaydiv = (
 7814:                                 status => 'none',
 7815:                                 inc    => 'none',
 7816:                                 exc    => 'none',
 7817:                                 priv   => 'block',
 7818:                              );
 7819:             my (%selected,$overridden,$incrscheck,$indomcheck,$indomvis,$incrsvis);
 7820:             if (ref($settings{$role}) eq 'HASH') {
 7821:                 if ($settings{$role}{'access'} ne '') {
 7822:                     $indomvis = ' style="display:none"';
 7823:                     $incrsvis = ' style="display:block"';
 7824:                     $incrscheck = ' checked="checked"';
 7825:                     if ($settings{$role}{'access'} ne 'all') {
 7826:                         $usecheck{$settings{$role}{'access'}} = $usecheck{'all'};
 7827:                         delete($usecheck{'all'});
 7828:                         if ($settings{$role}{'access'} eq 'status') {
 7829:                             my $access = 'status';
 7830:                             $displaydiv{$access} = 'inline';
 7831:                             if (ref($settings{$role}{$access}) eq 'ARRAY') {
 7832:                                 $selected{$access} = $settings{$role}{$access};
 7833:                             }
 7834:                         } elsif ($settings{$role}{'access'} =~ /^(inc|exc)$/) {
 7835:                             my $access = $1;
 7836:                             $displaydiv{$access} = 'inline';
 7837:                             if (ref($settings{$role}{$access}) eq 'ARRAY') {
 7838:                                 $selected{$access} = $settings{$role}{$access};
 7839:                             }
 7840:                         } elsif ($settings{$role}{'access'} eq 'none') {
 7841:                             $displaydiv{'priv'} = 'none';
 7842:                         }
 7843:                     }
 7844:                 } else {
 7845:                     $indomcheck = ' checked="checked"';
 7846:                     $indomvis = ' style="display:block"';
 7847:                     $incrsvis = ' style="display:none"';
 7848:                 }
 7849:             } else {
 7850:                 $indomcheck = ' checked="checked"';
 7851:                 $indomvis = ' style="display:block"';
 7852:                 $incrsvis = ' style="display:none"';
 7853:             }
 7854:             $r->print('<div class="LC_left_float" id="'.$role.'_maindiv"'.$visibility{$role}.'>'.
 7855:                       '<fieldset><legend>'.$lt{'rou'}.'</legend>'.
 7856:                       '<p>'.$lt{'whi'}.' <span class="LC_nobreak">'.
 7857:                       '<label><input type="radio" name="'.$role.'_incrs" value="1"'.$incrscheck.' onclick="toggleAccess('."'$role'".');"'.$disabled.'>'.
 7858:                       &mt('Set here in [_1]',lc($crstype)).'</label>'.
 7859:                       '<span>'.('&nbsp;'x2).
 7860:                       '<label><input type="radio" name="'.$role.'_incrs" value="0"'.$indomcheck.' onclick="toggleAccess('."'$role'".');"'.$disabled.'>'.
 7861:                       $lt{'udd'}.'</label><span></p>'.
 7862:                       '<div id="'.$role.'_setindom"'.$indomvis.'>'.
 7863:                       '<span class="LC_cusr_emph">'.$domusage{$role}.'</span></div>'.
 7864:                       '<div id="'.$role.'_setincrs"'.$incrsvis.'>');
 7865:             foreach my $access (@accesstypes) {
 7866:                 $r->print('<p><label><input type="radio" name="'.$role.'_access" value="'.$access.'" '.$usecheck{$access}.
 7867:                           ' onclick="helpdeskAccess('."'$role'".');"'.$disabled.' />'.$lt{$access}.'</label>');
 7868:                 if ($access eq 'status') {
 7869:                     $r->print('<div id="'.$role.'_bystatus" style="display:'.$displaydiv{$access}.'">'.
 7870:                               &Apache::lonuserutils::adhoc_status_types($cdom,undef,$role,$selected{$access},
 7871:                                                                         $othertitle,$usertypes,$types,$disabled).
 7872:                               '</div>');
 7873:                 } elsif (($access eq 'inc') && (keys(%domhelpdesk) > 0)) {
 7874:                     $r->print('<div id="'.$role.'_notinc" style="display:'.$displaydiv{$access}.'">'.
 7875:                               &Apache::lonuserutils::adhoc_staff($access,undef,$role,$selected{$access},
 7876:                                                                  \%domhelpdesk,$disabled).
 7877:                               '</div>');
 7878:                 } elsif (($access eq 'exc') && (keys(%domhelpdesk) > 0)) {
 7879:                     $r->print('<div id="'.$role.'_notexc" style="display:'.$displaydiv{$access}.'">'.
 7880:                               &Apache::lonuserutils::adhoc_staff($access,undef,$role,$selected{$access},
 7881:                                                                  \%domhelpdesk,$disabled).
 7882:                               '</div>');
 7883:                 }
 7884:                 $r->print('</p>');
 7885:             }
 7886:             $r->print('</div></fieldset>');
 7887:             my %full=();
 7888:             my %levels= (
 7889:                          course => {},
 7890:                          domain => {},
 7891:                          system => {},
 7892:                         );
 7893:             my %levelscurrent=(
 7894:                                course => {},
 7895:                                domain => {},
 7896:                                system => {},
 7897:                               );
 7898:             &Apache::lonuserutils::custom_role_privs($customroles{$role},\%full,\%levels,\%levelscurrent);
 7899:             $r->print('<fieldset id="'.$role.'_privs" style="display:'.$displaydiv{'priv'}.'">'.
 7900:                       '<legend>'.$lt{'rpr'}.'</legend>'.
 7901:                       &role_priv_table($role,$permission,$crstype,\%full,\%levels,\%levelscurrent,$overridden{$role}).
 7902:                       '</fieldset></div><div style="padding:0;clear:both;margin:0;border:0"></div>');
 7903:         }
 7904:         if ($permission->{'owner'}) {
 7905:             $r->print('<p><input type="submit" value="'.&mt('Save changes').'" /></p>');
 7906:         }
 7907:     } else {
 7908:         $r->print(&mt('Helpdesk roles have not yet been created in this domain.'));
 7909:     }
 7910:     # Form Footer
 7911:     $r->print('<input type="hidden" name="action" value="helpdesk" />'
 7912:              .'</form>');
 7913:     return;
 7914: }
 7915: 
 7916: sub domain_adhoc_access {
 7917:     my ($roles,$domcurrent,$accesstypes,$usertypes,$othertitle) = @_;
 7918:     my %domusage;
 7919:     return unless ((ref($roles) eq 'HASH') && (ref($domcurrent) eq 'HASH') && (ref($accesstypes) eq 'ARRAY'));
 7920:     foreach my $role (keys(%{$roles})) {
 7921:         if (ref($domcurrent->{$role}) eq 'HASH') {
 7922:             my $access = $domcurrent->{$role}{'access'};
 7923:             if (($access eq '') || (!grep(/^\Q$access\E$/,@{$accesstypes}))) {
 7924:                 $access = 'all';
 7925:                 $domusage{$role} = &mt('Any user in domain with active [_1] or [_2] role',&Apache::lonnet::plaintext('dh'),
 7926:                                                                                           &Apache::lonnet::plaintext('da'));
 7927:             } elsif ($access eq 'status') {
 7928:                 if (ref($domcurrent->{$role}{$access}) eq 'ARRAY') {
 7929:                     my @shown;
 7930:                     foreach my $type (@{$domcurrent->{$role}{$access}}) {
 7931:                         unless ($type eq 'default') {
 7932:                             if ($usertypes->{$type}) {
 7933:                                 push(@shown,$usertypes->{$type});
 7934:                             }
 7935:                         }
 7936:                     }
 7937:                     if (grep(/^default$/,@{$domcurrent->{$role}{$access}})) {
 7938:                         push(@shown,$othertitle);
 7939:                     }
 7940:                     if (@shown) {
 7941:                         my $shownstatus = join(' '.&mt('or').' ',@shown);
 7942:                         $domusage{$role} = &mt('Any user in domain with active [_1] or [_2] role, and institutional status: [_3]',
 7943:                                                &Apache::lonnet::plaintext('dh'),&Apache::lonnet::plaintext('da'),$shownstatus);
 7944:                     } else {
 7945:                         $domusage{$role} = &mt('No one in the domain');
 7946:                     }
 7947:                 }
 7948:             } elsif ($access eq 'inc') {
 7949:                 my @dominc = ();
 7950:                 if (ref($domcurrent->{$role}{'inc'}) eq 'ARRAY') {
 7951:                     foreach my $user (@{$domcurrent->{$role}{'inc'}}) {
 7952:                         my ($uname,$udom) = split(/:/,$user);
 7953:                         push(@dominc,&Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($uname,$udom),$uname,$udom));
 7954:                     }
 7955:                     my $showninc = join(', ',@dominc);
 7956:                     if ($showninc ne '') {
 7957:                         $domusage{$role} = &mt('Include any user in domain with active [_1] or [_2] role, except: [_3]',
 7958:                                                &Apache::lonnet::plaintext('dh'),&Apache::lonnet::plaintext('da'),$showninc);
 7959:                     } else {
 7960:                         $domusage{$role} = &mt('Any user in domain with active [_1] or [_2] role',
 7961:                                                &Apache::lonnet::plaintext('dh'),&Apache::lonnet::plaintext('da'));
 7962:                     }
 7963:                 }
 7964:             } elsif ($access eq 'exc') {
 7965:                 my @domexc = ();
 7966:                 if (ref($domcurrent->{$role}{'exc'}) eq 'ARRAY') {
 7967:                     foreach my $user (@{$domcurrent->{$role}{'exc'}}) {
 7968:                         my ($uname,$udom) = split(/:/,$user);
 7969:                         push(@domexc,&Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($uname,$udom),$uname,$udom));
 7970:                     }
 7971:                 }
 7972:                 my $shownexc = join(', ',@domexc);
 7973:                 if ($shownexc ne '') {
 7974:                     $domusage{$role} = &mt('Only the following in the domain with active [_1] or [_2] role: [_3]',
 7975:                                            &Apache::lonnet::plaintext('dh'),&Apache::lonnet::plaintext('da'),$shownexc);
 7976:                 } else {
 7977:                     $domusage{$role} = &mt('No one in the domain');
 7978:                 }
 7979:             } elsif ($access eq 'none') {
 7980:                 $domusage{$role} = &mt('No one in the domain');
 7981:             } elsif ($access eq 'dh') {
 7982:                 $domusage{$role} = &mt('Any user in domain with active [_1] role',&Apache::lonnet::plaintext('dh'));
 7983:             } elsif ($access eq 'da') {
 7984:                 $domusage{$role} = &mt('Any user in domain with active [_1] role',&Apache::lonnet::plaintext('da'));
 7985:             } elsif ($access eq 'all') {
 7986:                 $domusage{$role} = &mt('Any user in domain with active [_1] or [_2] role',
 7987:                                        &Apache::lonnet::plaintext('dh'),&Apache::lonnet::plaintext('da'));
 7988:             }
 7989:         } else {
 7990:             $domusage{$role} = &mt('Any user in domain with active [_1] or [_2] role',
 7991:                                    &Apache::lonnet::plaintext('dh'),&Apache::lonnet::plaintext('da'));
 7992:         }
 7993:     }
 7994:     return %domusage;
 7995: }
 7996: 
 7997: sub get_domain_customroles {
 7998:     my ($cdom,$confname) = @_;
 7999:     my %existing=&Apache::lonnet::dump('roles',$cdom,$confname,'rolesdef_');
 8000:     my %customroles;
 8001:     foreach my $key (keys(%existing)) {
 8002:         if ($key=~/^rolesdef\_(\w+)$/) {
 8003:             my $rolename = $1;
 8004:             my %privs;
 8005:             ($privs{'system'},$privs{'domain'},$privs{'course'}) = split(/\_/,$existing{$key});
 8006:             $customroles{$rolename} = \%privs;
 8007:         }
 8008:     }
 8009:     return %customroles;
 8010: }
 8011: 
 8012: sub role_priv_table {
 8013:     my ($role,$permission,$crstype,$full,$levels,$levelscurrent,$overridden) = @_;
 8014:     return unless ((ref($full) eq 'HASH') && (ref($levels) eq 'HASH') &&
 8015:                    (ref($levelscurrent) eq 'HASH'));
 8016:     my %lt=&Apache::lonlocal::texthash (
 8017:                     'crl'  => 'Course Level Privilege',
 8018:                     'def'  => 'Domain Defaults',
 8019:                     'ove'  => 'Override in Course',
 8020:                     'ine'  => 'In effect',
 8021:                     'dis'  => 'Disabled',
 8022:                     'ena'  => 'Enabled',
 8023:                    );
 8024:     if ($crstype eq 'Community') {
 8025:         $lt{'ove'} = 'Override in Community',
 8026:     }
 8027:     my @status = ('Disabled','Enabled');
 8028:     my (%on,%off);
 8029:     if (ref($overridden) eq 'HASH') {
 8030:         if (ref($overridden->{'on'}) eq 'ARRAY') {
 8031:             map { $on{$_} = 1; } (@{$overridden->{'on'}});
 8032:         }
 8033:         if (ref($overridden->{'off'}) eq 'ARRAY') {
 8034:             map { $off{$_} = 1; } (@{$overridden->{'off'}});
 8035:         }
 8036:     }
 8037:     my $output=&Apache::loncommon::start_data_table().
 8038:                &Apache::loncommon::start_data_table_header_row().
 8039:                '<th>'.$lt{'crl'}.'</th><th>'.$lt{'def'}.'</th><th>'.$lt{'ove'}.
 8040:                '</th><th>'.$lt{'ine'}.'</th>'.
 8041:                &Apache::loncommon::end_data_table_header_row();
 8042:     foreach my $priv (sort(keys(%{$full}))) {
 8043:         next unless ($levels->{'course'}{$priv});
 8044:         my $privtext = &Apache::lonnet::plaintext($priv,$crstype);
 8045:         my ($default,$ineffect);
 8046:         if ($levelscurrent->{'course'}{$priv}) {
 8047:             $default = '<img src="/adm/lonIcons/navmap.correct.gif" alt="'.$lt{'ena'}.'" />';
 8048:             $ineffect = $default;
 8049:         }
 8050:         my ($customstatus,$checked);
 8051:         $output .= &Apache::loncommon::start_data_table_row().
 8052:                    '<td>'.$privtext.'</td>'.
 8053:                    '<td>'.$default.'</td><td>';
 8054:         if (($levelscurrent->{'course'}{$priv}) && ($off{$priv})) {
 8055:             if ($permission->{'owner'}) {
 8056:                 $checked = ' checked="checked"';
 8057:             }
 8058:             $customstatus = '<img src="/adm/lonIcons/navmap.wrong.gif" alt="'.$lt{'dis'}.'" />';
 8059:             $ineffect = $customstatus;
 8060:         } elsif ((!$levelscurrent->{'course'}{$priv}) && ($on{$priv})) {
 8061:             if ($permission->{'owner'}) {
 8062:                 $checked = ' checked="checked"';
 8063:             }
 8064:             $customstatus = '<img src="/adm/lonIcons/navmap.correct.gif" alt="'.$lt{'ena'}.'" />';
 8065:             $ineffect = $customstatus;
 8066:         }
 8067:         if ($permission->{'owner'}) {
 8068:             $output .= '<input type="checkbox" name="'.$role.'_override" value="'.$priv.'"'.$checked.' />';
 8069:         } else {
 8070:             $output .= $customstatus;
 8071:         }
 8072:         $output .= '</td><td>'.$ineffect.'</td>'.
 8073:                    &Apache::loncommon::end_data_table_row();
 8074:     }
 8075:     $output .= &Apache::loncommon::end_data_table();
 8076:     return $output;
 8077: }
 8078: 
 8079: sub get_adhocrole_settings {
 8080:     my ($cid,$accesstypes,$types,$customroles,$settings,$overridden) = @_;
 8081:     return unless ((ref($accesstypes) eq 'ARRAY') && (ref($customroles) eq 'HASH') &&
 8082:                    (ref($settings) eq 'HASH') && (ref($overridden) eq 'HASH'));
 8083:     foreach my $role (split(/,/,$env{'course.'.$cid.'.internal.adhocaccess'})) {
 8084:         my ($curraccess,$rest) = split(/=/,$env{'course.'.$cid.'.internal.adhoc.'.$role});
 8085:         if (($curraccess ne '') && (grep(/^\Q$curraccess\E$/,@{$accesstypes}))) {
 8086:             $settings->{$role}{'access'} = $curraccess;
 8087:             if (($curraccess eq 'status') && (ref($types) eq 'ARRAY')) {
 8088:                 my @status = split(/,/,$rest);
 8089:                 my @currstatus;
 8090:                 foreach my $type (@status) {
 8091:                     if ($type eq 'default') {
 8092:                         push(@currstatus,$type);
 8093:                     } elsif (grep(/^\Q$type\E$/,@{$types})) {
 8094:                         push(@currstatus,$type);
 8095:                     }
 8096:                 }
 8097:                 if (@currstatus) {
 8098:                     $settings->{$role}{$curraccess} = \@currstatus;
 8099:                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 8100:                     my @personnel = split(/,/,$rest);
 8101:                     $settings->{$role}{$curraccess} = \@personnel;
 8102:                 }
 8103:             }
 8104:         }
 8105:     }
 8106:     foreach my $role (keys(%{$customroles})) {
 8107:         if ($env{'course.'.$cid.'.internal.adhocpriv.'.$role}) {
 8108:             my %currentprivs;
 8109:             if (ref($customroles->{$role}) eq 'HASH') {
 8110:                 if (exists($customroles->{$role}{'course'})) {
 8111:                     my %full=();
 8112:                     my %levels= (
 8113:                                   course => {},
 8114:                                   domain => {},
 8115:                                   system => {},
 8116:                                 );
 8117:                     my %levelscurrent=(
 8118:                                         course => {},
 8119:                                         domain => {},
 8120:                                         system => {},
 8121:                                       );
 8122:                     &Apache::lonuserutils::custom_role_privs($customroles->{$role},\%full,\%levels,\%levelscurrent);
 8123:                     %currentprivs = %{$levelscurrent{'course'}};
 8124:                 }
 8125:             }
 8126:             foreach my $item (split(/,/,$env{'course.'.$cid.'.internal.adhocpriv.'.$role})) {
 8127:                 next if ($item eq '');
 8128:                 my ($rule,$rest) = split(/=/,$item);
 8129:                 next unless (($rule eq 'off') || ($rule eq 'on'));
 8130:                 foreach my $priv (split(/:/,$rest)) {
 8131:                     if ($priv ne '') {
 8132:                         if ($rule eq 'off') {
 8133:                             push(@{$overridden->{$role}{'off'}},$priv);
 8134:                             if ($currentprivs{$priv}) {
 8135:                                 push(@{$settings->{$role}{'off'}},$priv);
 8136:                             }
 8137:                         } else {
 8138:                             push(@{$overridden->{$role}{'on'}},$priv);
 8139:                             unless ($currentprivs{$priv}) {
 8140:                                 push(@{$settings->{$role}{'on'}},$priv);
 8141:                             }
 8142:                         }
 8143:                     }
 8144:                 }
 8145:             }
 8146:         }
 8147:     }
 8148:     return;
 8149: }
 8150: 
 8151: sub update_helpdeskaccess {
 8152:     my ($r,$permission,$brcrum) = @_;
 8153:     my $helpitem = 'Course_Helpdesk_Access';
 8154:     push (@{$brcrum},
 8155:              {href => '/adm/createuser?action=helpdesk',
 8156:               text => 'Helpdesk Access',
 8157:               help => $helpitem},
 8158:              {href => '/adm/createuser?action=helpdesk',
 8159:               text => 'Result',
 8160:               help => $helpitem}
 8161:          );
 8162:     my $bread_crumbs_component = 'Helpdesk Staff Access';
 8163:     my $args = { bread_crumbs           => $brcrum,
 8164:                  bread_crumbs_component => $bread_crumbs_component};
 8165: 
 8166:     # print page header
 8167:     $r->print(&header('',$args));
 8168:     unless ((ref($permission) eq 'HASH') && ($permission->{'owner'})) {
 8169:         $r->print('<p class="LC_error">'.&mt('You do not have permission to change helpdesk access.').'</p>');
 8170:         return;
 8171:     }
 8172:     my @accesstypes = ('all','dh','da','none','status','inc','exc');
 8173:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8174:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 8175:     my $confname = $cdom.'-domainconfig';
 8176:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($cdom);
 8177:     my $crstype = &Apache::loncommon::course_type();
 8178:     my %customroles = &get_domain_customroles($cdom,$confname);
 8179:     my (%settings,%overridden);
 8180:     &get_adhocrole_settings($env{'request.course.id'},\@accesstypes,
 8181:                             $types,\%customroles,\%settings,\%overridden);
 8182:     my %domhelpdesk = &Apache::lonnet::get_active_domroles($cdom,['dh','da']);
 8183:     my (%changed,%storehash,@todelete);
 8184: 
 8185:     if (keys(%customroles)) {
 8186:         my (%newsettings,@incrs);
 8187:         foreach my $role (keys(%customroles)) {
 8188:             $newsettings{$role} = {
 8189:                                     access => '',
 8190:                                     status => '',
 8191:                                     exc    => '',
 8192:                                     inc    => '',
 8193:                                     on     => '',
 8194:                                     off    => '',
 8195:                                   };
 8196:             my %current;
 8197:             if (ref($settings{$role}) eq 'HASH') {
 8198:                 %current = %{$settings{$role}};
 8199:             }
 8200:             if (ref($overridden{$role}) eq 'HASH') {
 8201:                 $current{'overridden'} = $overridden{$role};
 8202:             }
 8203:             if ($env{'form.'.$role.'_incrs'}) {
 8204:                 my $access = $env{'form.'.$role.'_access'};
 8205:                 if (grep(/^\Q$access\E$/,@accesstypes)) {
 8206:                     push(@incrs,$role);
 8207:                     unless ($current{'access'} eq $access) {
 8208:                         $changed{$role}{'access'} = 1;
 8209:                         $storehash{'internal.adhoc.'.$role} = $access;
 8210:                     }
 8211:                     if ($access eq 'status') {
 8212:                         my @statuses = &Apache::loncommon::get_env_multiple('form.'.$role.'_status');
 8213:                         my @stored;
 8214:                         my @shownstatus;
 8215:                         if (ref($types) eq 'ARRAY') {
 8216:                             foreach my $type (sort(@statuses)) {
 8217:                                 if ($type eq 'default') {
 8218:                                     push(@stored,$type);
 8219:                                 } elsif (grep(/^\Q$type\E$/,@{$types})) {
 8220:                                     push(@stored,$type);
 8221:                                     push(@shownstatus,$usertypes->{$type});
 8222:                                 }
 8223:                             }
 8224:                             if (grep(/^default$/,@statuses)) {
 8225:                                 push(@shownstatus,$othertitle);
 8226:                             }
 8227:                             $storehash{'internal.adhoc.'.$role} .= '='.join(',',@stored);
 8228:                         }
 8229:                         $newsettings{$role}{'status'} = join(' '.&mt('or').' ',@shownstatus);
 8230:                         if (ref($current{'status'}) eq 'ARRAY') {
 8231:                             my @diffs = &Apache::loncommon::compare_arrays(\@stored,$current{'status'});
 8232:                             if (@diffs) {
 8233:                                 $changed{$role}{'status'} = 1;
 8234:                             }
 8235:                         } elsif (@stored) {
 8236:                             $changed{$role}{'status'} = 1;
 8237:                         }
 8238:                     } elsif (($access eq 'inc') || ($access eq 'exc')) {
 8239:                         my @personnel = &Apache::loncommon::get_env_multiple('form.'.$role.'_staff_'.$access);
 8240:                         my @newspecstaff;
 8241:                         my @stored;
 8242:                         my @currstaff;
 8243:                         foreach my $person (sort(@personnel)) {
 8244:                             if ($domhelpdesk{$person}) {
 8245:                                 push(@stored,$person);
 8246:                             }
 8247:                         }
 8248:                         if (ref($current{$access}) eq 'ARRAY') {
 8249:                             my @diffs = &Apache::loncommon::compare_arrays(\@stored,$current{$access});
 8250:                             if (@diffs) {
 8251:                                 $changed{$role}{$access} = 1;
 8252:                             }
 8253:                         } elsif (@stored) {
 8254:                             $changed{$role}{$access} = 1;
 8255:                         }
 8256:                         $storehash{'internal.adhoc.'.$role} .= '='.join(',',@stored);
 8257:                         foreach my $person (@stored) {
 8258:                             my ($uname,$udom) = split(/:/,$person);
 8259:                             push(@newspecstaff,&Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($uname,$udom,'lastname'),$uname,$udom));
 8260:                         }
 8261:                         $newsettings{$role}{$access} = join(', ',sort(@newspecstaff));
 8262:                     }
 8263:                     $newsettings{$role}{'access'} = $access;
 8264:                 }
 8265:             } else {
 8266:                 if (($current{'access'} ne '') && (grep(/^\Q$current{'access'}\E$/,@accesstypes))) {
 8267:                     $changed{$role}{'access'} = 1;
 8268:                     $newsettings{$role} = {};
 8269:                     push(@todelete,'internal.adhoc.'.$role);
 8270:                 }
 8271:             }
 8272:             if (($env{'form.'.$role.'_incrs'}) && ($env{'form.'.$role.'_access'} eq 'none')) {
 8273:                 if (ref($current{'overridden'}) eq 'HASH') {
 8274:                     push(@todelete,'internal.adhocpriv.'.$role);
 8275:                 }
 8276:             } else {
 8277:                 my %full=();
 8278:                 my %levels= (
 8279:                              course => {},
 8280:                              domain => {},
 8281:                              system => {},
 8282:                             );
 8283:                 my %levelscurrent=(
 8284:                                    course => {},
 8285:                                    domain => {},
 8286:                                    system => {},
 8287:                                   );
 8288:                 &Apache::lonuserutils::custom_role_privs($customroles{$role},\%full,\%levels,\%levelscurrent);
 8289:                 my (@updatedon,@updatedoff,@override);
 8290:                 @override = &Apache::loncommon::get_env_multiple('form.'.$role.'_override');
 8291:                 if (@override) {
 8292:                     foreach my $priv (sort(keys(%full))) {
 8293:                         next unless ($levels{'course'}{$priv});
 8294:                         if (grep(/^\Q$priv\E$/,@override)) {
 8295:                             if ($levelscurrent{'course'}{$priv}) {
 8296:                                 push(@updatedoff,$priv);
 8297:                             } else {
 8298:                                 push(@updatedon,$priv);
 8299:                             }
 8300:                         }
 8301:                     }
 8302:                 }
 8303:                 if (@updatedon) {
 8304:                     $newsettings{$role}{'on'} = join('</li><li>', map { &Apache::lonnet::plaintext($_,$crstype) } (@updatedon));
 8305:                 }
 8306:                 if (@updatedoff) {
 8307:                     $newsettings{$role}{'off'} = join('</li><li>', map { &Apache::lonnet::plaintext($_,$crstype) } (@updatedoff));
 8308:                 }
 8309:                 if (ref($current{'overridden'}) eq 'HASH') {
 8310:                     if (ref($current{'overridden'}{'on'}) eq 'ARRAY') {
 8311:                         if (@updatedon) {
 8312:                             my @diffs = &Apache::loncommon::compare_arrays(\@updatedon,$current{'overridden'}{'on'});
 8313:                             if (@diffs) {
 8314:                                 $changed{$role}{'on'} = 1;
 8315:                             }
 8316:                         } else {
 8317:                             $changed{$role}{'on'} = 1;
 8318:                         }
 8319:                     } elsif (@updatedon) {
 8320:                         $changed{$role}{'on'} = 1;
 8321:                     }
 8322:                     if (ref($current{'overridden'}{'off'}) eq 'ARRAY') {
 8323:                         if (@updatedoff) {
 8324:                             my @diffs = &Apache::loncommon::compare_arrays(\@updatedoff,$current{'overridden'}{'off'});
 8325:                             if (@diffs) {
 8326:                                 $changed{$role}{'off'} = 1;
 8327:                             }
 8328:                         } else {
 8329:                             $changed{$role}{'off'} = 1;
 8330:                         }
 8331:                     } elsif (@updatedoff) {
 8332:                         $changed{$role}{'off'} = 1;
 8333:                     }
 8334:                 } else {
 8335:                     if (@updatedon) {
 8336:                         $changed{$role}{'on'} = 1;
 8337:                     }
 8338:                     if (@updatedoff) {
 8339:                         $changed{$role}{'off'} = 1;
 8340:                     }
 8341:                 }
 8342:                 if (ref($changed{$role}) eq 'HASH') {
 8343:                     if (($changed{$role}{'on'} || $changed{$role}{'off'})) {
 8344:                         my $newpriv;
 8345:                         if (@updatedon) {
 8346:                             $newpriv = 'on='.join(':',@updatedon);
 8347:                         }
 8348:                         if (@updatedoff) {
 8349:                             $newpriv .= ($newpriv ? ',' : '' ).'off='.join(':',@updatedoff);
 8350:                         }
 8351:                         if ($newpriv eq '') {
 8352:                             push(@todelete,'internal.adhocpriv.'.$role);
 8353:                         } else {
 8354:                             $storehash{'internal.adhocpriv.'.$role} = $newpriv;
 8355:                         }
 8356:                     }
 8357:                 }
 8358:             }
 8359:         }
 8360:         if (@incrs) {
 8361:             $storehash{'internal.adhocaccess'} = join(',',@incrs);
 8362:         } elsif (@todelete) {
 8363:             push(@todelete,'internal.adhocaccess');
 8364:         }
 8365:         if (keys(%changed)) {
 8366:             my ($putres,$delres);
 8367:             if (keys(%storehash)) {
 8368:                 $putres = &Apache::lonnet::put('environment',\%storehash,$cdom,$cnum);
 8369:                 my %newenvhash;
 8370:                 foreach my $key (keys(%storehash)) {
 8371:                     $newenvhash{'course.'.$env{'request.course.id'}.'.'.$key} = $storehash{$key};
 8372:                 }
 8373:                 &Apache::lonnet::appenv(\%newenvhash);
 8374:             }
 8375:             if (@todelete) {
 8376:                 $delres = &Apache::lonnet::del('environment',\@todelete,$cdom,$cnum);
 8377:                 foreach my $key (@todelete) {
 8378:                     &Apache::lonnet::delenv('course.'.$env{'request.course.id'}.'.'.$key);
 8379:                 }
 8380:             }
 8381:             if (($putres eq 'ok') || ($delres eq 'ok')) {
 8382:                 my %domconfig = &Apache::lonnet::get_dom('configuration',['helpsettings'],$cdom);
 8383:                 my (%domcurrent,%ordered,%description,%domusage);
 8384:                 if (ref($domconfig{'helpsettings'}) eq 'HASH') {
 8385:                     if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
 8386:                         %domcurrent = %{$domconfig{'helpsettings'}{'adhoc'}};
 8387:                     }
 8388:                 }
 8389:                 my $count = 0;
 8390:                 foreach my $role (sort(keys(%customroles))) {
 8391:                     my ($order,$desc);
 8392:                     if (ref($domcurrent{$role}) eq 'HASH') {
 8393:                         $order = $domcurrent{$role}{'order'};
 8394:                         $desc = $domcurrent{$role}{'desc'};
 8395:                     }
 8396:                     if ($order eq '') {
 8397:                         $order = $count;
 8398:                     }
 8399:                     $ordered{$order} = $role;
 8400:                     if ($desc ne '') {
 8401:                         $description{$role} = $desc;
 8402:                     } else {
 8403:                         $description{$role}= $role;
 8404:                     }
 8405:                     $count++;
 8406:                 }
 8407:                 my @roles_by_num = ();
 8408:                 foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 8409:                     push(@roles_by_num,$ordered{$item});
 8410:                 }
 8411:                 %domusage = &domain_adhoc_access(\%changed,\%domcurrent,\@accesstypes,$usertypes,$othertitle);
 8412:                 $r->print(&mt('Helpdesk access settings have been changed as follows').'<br />');
 8413:                 $r->print('<ul>');
 8414:                 foreach my $role (@roles_by_num) {
 8415:                     next unless (ref($changed{$role}) eq 'HASH');
 8416:                     $r->print('<li>'.&mt('Ad hoc role').': <b>'.$description{$role}.'</b>'.
 8417:                               '<ul>');
 8418:                     if ($changed{$role}{'access'} || $changed{$role}{'status'} || $changed{$role}{'inc'} || $changed{$role}{'exc'}) {
 8419:                         $r->print('<li>');
 8420:                         if ($env{'form.'.$role.'_incrs'}) {
 8421:                             if ($newsettings{$role}{'access'} eq 'all') {
 8422:                                 $r->print(&mt('All helpdesk staff can access '.lc($crstype).' with this role.'));
 8423:                             } elsif ($newsettings{$role}{'access'} eq 'dh') {
 8424:                                 $r->print(&mt('Helpdesk staff can use this role if they have an active [_1] role',
 8425:                                               &Apache::lonnet::plaintext('dh')));
 8426:                             } elsif ($newsettings{$role}{'access'} eq 'da') {
 8427:                                 $r->print(&mt('Helpdesk staff can use this role if they have an active [_1] role',
 8428:                                               &Apache::lonnet::plaintext('da')));
 8429:                             } elsif ($newsettings{$role}{'access'} eq 'none') {
 8430:                                 $r->print(&mt('No helpdesk staff can access '.lc($crstype).' with this role.'));
 8431:                             } elsif ($newsettings{$role}{'access'} eq 'status') {
 8432:                                 if ($newsettings{$role}{'status'}) {
 8433:                                     my ($access,$rest) = split(/=/,$storehash{'internal.adhoc.'.$role});
 8434:                                     if (split(/,/,$rest) > 1) {
 8435:                                         $r->print(&mt('Helpdesk staff can use this role if their institutional type is one of: [_1].',
 8436:                                                       $newsettings{$role}{'status'}));
 8437:                                     } else {
 8438:                                         $r->print(&mt('Helpdesk staff can use this role if their institutional type is: [_1].',
 8439:                                                       $newsettings{$role}{'status'}));
 8440:                                     }
 8441:                                 } else {
 8442:                                     $r->print(&mt('No helpdesk staff can access '.lc($crstype).' with this role.'));
 8443:                                 }
 8444:                             } elsif ($newsettings{$role}{'access'} eq 'exc') {
 8445:                                 if ($newsettings{$role}{'exc'}) {
 8446:                                     $r->print(&mt('Helpdesk staff who can use this role are as follows:').' '.$newsettings{$role}{'exc'}.'.');
 8447:                                 } else {
 8448:                                     $r->print(&mt('No helpdesk staff can access '.lc($crstype).' with this role.'));
 8449:                                 }
 8450:                             } elsif ($newsettings{$role}{'access'} eq 'inc') {
 8451:                                 if ($newsettings{$role}{'inc'}) {
 8452:                                     $r->print(&mt('All helpdesk staff may use this role except the following:').' '.$newsettings{$role}{'inc'}.'.');
 8453:                                 } else {
 8454:                                     $r->print(&mt('All helpdesk staff may use this role.'));
 8455:                                 }
 8456:                             }
 8457:                         } else {
 8458:                             $r->print(&mt('Default access set in the domain now applies.').'<br />'.
 8459:                                       '<span class="LC_cusr_emph">'.$domusage{$role}.'</span>');
 8460:                         }
 8461:                         $r->print('</li>');
 8462:                     }
 8463:                     unless ($newsettings{$role}{'access'} eq 'none') {
 8464:                         if ($changed{$role}{'off'}) {
 8465:                             if ($newsettings{$role}{'off'}) {
 8466:                                 $r->print('<li>'.&mt('Privileges which are available by default for this ad hoc role, but are disabled for this specific '.lc($crstype).':').
 8467:                                           '<ul><li>'.$newsettings{$role}{'off'}.'</li></ul></li>');
 8468:                             } else {
 8469:                                 $r->print('<li>'.&mt('All privileges available by default for this ad hoc role are enabled.').'</li>');
 8470:                             }
 8471:                         }
 8472:                         if ($changed{$role}{'on'}) {
 8473:                             if ($newsettings{$role}{'on'}) {
 8474:                                 $r->print('<li>'.&mt('Privileges which are not available by default for this ad hoc role, but are enabled for this specific '.lc($crstype).':').
 8475:                                           '<ul><li>'.$newsettings{$role}{'on'}.'</li></ul></li>');
 8476:                             } else {
 8477:                                 $r->print('<li>'.&mt('None of the privileges unavailable by default for this ad hoc role are enabled.').'</li>');
 8478:                             }
 8479:                         }
 8480:                     }
 8481:                     $r->print('</ul></li>');
 8482:                 }
 8483:                 $r->print('</ul>');
 8484:             }
 8485:         } else {
 8486:             $r->print(&mt('No changes made to helpdesk access settings.'));
 8487:         }
 8488:     }
 8489:     return;
 8490: }
 8491: 
 8492: #-------------------------------------------------- functions for &phase_two
 8493: sub user_search_result {
 8494:     my ($context,$srch) = @_;
 8495:     my %allhomes;
 8496:     my %inst_matches;
 8497:     my %srch_results;
 8498:     my ($response,$currstate,$forcenewuser,$dirsrchres);
 8499:     $srch->{'srchterm'} =~ s/\s+/ /g;
 8500:     if ($srch->{'srchby'} !~ /^(uname|lastname|lastfirst)$/) {
 8501:         $response = &mt('Invalid search.');
 8502:     }
 8503:     if ($srch->{'srchin'} !~ /^(crs|dom|alc|instd)$/) {
 8504:         $response = &mt('Invalid search.');
 8505:     }
 8506:     if ($srch->{'srchtype'} !~ /^(exact|contains|begins)$/) {
 8507:         $response = &mt('Invalid search.');
 8508:     }
 8509:     if ($srch->{'srchterm'} eq '') {
 8510:         $response = &mt('You must enter a search term.');
 8511:     }
 8512:     if ($srch->{'srchterm'} =~ /^\s+$/) {
 8513:         $response = &mt('Your search term must contain more than just spaces.');
 8514:     }
 8515:     if (($srch->{'srchin'} eq 'dom') || ($srch->{'srchin'} eq 'instd')) {
 8516:         if (($srch->{'srchdomain'} eq '') || 
 8517: 	    ! (&Apache::lonnet::domain($srch->{'srchdomain'}))) {
 8518:             $response = &mt('You must specify a valid domain when searching in a domain or institutional directory.')
 8519:         }
 8520:     }
 8521:     if (($srch->{'srchin'} eq 'dom') || ($srch->{'srchin'} eq 'crs') ||
 8522:         ($srch->{'srchin'} eq 'alc')) {
 8523:         if ($srch->{'srchby'} eq 'uname') {
 8524:             my $unamecheck = $srch->{'srchterm'};
 8525:             if ($srch->{'srchtype'} eq 'contains') {
 8526:                 if ($unamecheck !~ /^\w/) {
 8527:                     $unamecheck = 'a'.$unamecheck; 
 8528:                 }
 8529:             }
 8530:             if ($unamecheck !~ /^$match_username$/) {
 8531:                 $response = &mt('You must specify a valid username. Only the following are allowed: letters numbers - . @');
 8532:             }
 8533:         }
 8534:     }
 8535:     if ($response ne '') {
 8536:         $response = '<span class="LC_warning">'.$response.'</span><br />';
 8537:     }
 8538:     if ($srch->{'srchin'} eq 'instd') {
 8539:         my $instd_chk = &instdirectorysrch_check($srch);
 8540:         if ($instd_chk ne 'ok') {
 8541:             my $domd_chk = &domdirectorysrch_check($srch);
 8542:             $response .= '<span class="LC_warning">'.$instd_chk.'</span><br />';
 8543:             if ($domd_chk eq 'ok') {
 8544:                 $response .= &mt('You may want to search in the LON-CAPA domain instead of the institutional directory.');
 8545:             }
 8546:             $response .= '<br />';
 8547:         }
 8548:     } else {
 8549:         unless (($context eq 'requestcrs') && ($srch->{'srchtype'} eq 'exact')) {
 8550:             my $domd_chk = &domdirectorysrch_check($srch);
 8551:             if (($domd_chk ne 'ok') && ($env{'form.action'} ne 'accesslogs')) {
 8552:                 my $instd_chk = &instdirectorysrch_check($srch);
 8553:                 $response .= '<span class="LC_warning">'.$domd_chk.'</span><br />';
 8554:                 if ($instd_chk eq 'ok') {
 8555:                     $response .= &mt('You may want to search in the institutional directory instead of the LON-CAPA domain.');
 8556:                 }
 8557:                 $response .= '<br />';
 8558:             }
 8559:         }
 8560:     }
 8561:     if ($response ne '') {
 8562:         return ($currstate,$response);
 8563:     }
 8564:     if ($srch->{'srchby'} eq 'uname') {
 8565:         if (($srch->{'srchin'} eq 'dom') || ($srch->{'srchin'} eq 'crs')) {
 8566:             if ($env{'form.forcenew'}) {
 8567:                 if ($srch->{'srchdomain'} ne $env{'request.role.domain'}) {
 8568:                     my $uhome=&Apache::lonnet::homeserver($srch->{'srchterm'},$srch->{'srchdomain'});
 8569:                     if ($uhome eq 'no_host') {
 8570:                         my $domdesc = &Apache::lonnet::domain($env{'request.role.domain'},'description');
 8571:                         my $showdom = &display_domain_info($env{'request.role.domain'});
 8572:                         $response = &mt('New users can only be created in the domain to which your current role belongs - [_1].',$showdom);
 8573:                     } else {
 8574:                         $currstate = 'modify';
 8575:                     }
 8576:                 } else {
 8577:                     $currstate = 'modify';
 8578:                 }
 8579:             } else {
 8580:                 if ($srch->{'srchin'} eq 'dom') {
 8581:                     if ($srch->{'srchtype'} eq 'exact') {
 8582:                         my $uhome=&Apache::lonnet::homeserver($srch->{'srchterm'},$srch->{'srchdomain'});
 8583:                         if ($uhome eq 'no_host') {
 8584:                             ($currstate,$response,$forcenewuser) =
 8585:                                 &build_search_response($context,$srch,%srch_results);
 8586:                         } else {
 8587:                             $currstate = 'modify';
 8588:                             if ($env{'form.action'} eq 'accesslogs') {
 8589:                                 $currstate = 'activity';
 8590:                             }
 8591:                             my $uname = $srch->{'srchterm'};
 8592:                             my $udom = $srch->{'srchdomain'};
 8593:                             $srch_results{$uname.':'.$udom} =
 8594:                                 { &Apache::lonnet::get('environment',
 8595:                                                        ['firstname',
 8596:                                                         'lastname',
 8597:                                                         'permanentemail'],
 8598:                                                          $udom,$uname)
 8599:                                 };
 8600:                         }
 8601:                     } else {
 8602:                         %srch_results = &Apache::lonnet::usersearch($srch);
 8603:                         ($currstate,$response,$forcenewuser) =
 8604:                             &build_search_response($context,$srch,%srch_results);
 8605:                     }
 8606:                 } else {
 8607:                     my $courseusers = &get_courseusers();
 8608:                     if ($srch->{'srchtype'} eq 'exact') {
 8609:                         if (exists($courseusers->{$srch->{'srchterm'}.':'.$srch->{'srchdomain'}})) {
 8610:                             $currstate = 'modify';
 8611:                         } else {
 8612:                             ($currstate,$response,$forcenewuser) =
 8613:                                 &build_search_response($context,$srch,%srch_results);
 8614:                         }
 8615:                     } else {
 8616:                         foreach my $user (keys(%$courseusers)) {
 8617:                             my ($cuname,$cudomain) = split(/:/,$user);
 8618:                             if ($cudomain eq $srch->{'srchdomain'}) {
 8619:                                 my $matched = 0;
 8620:                                 if ($srch->{'srchtype'} eq 'begins') {
 8621:                                     if ($cuname =~ /^\Q$srch->{'srchterm'}\E/i) {
 8622:                                         $matched = 1;
 8623:                                     }
 8624:                                 } else {
 8625:                                     if ($cuname =~ /\Q$srch->{'srchterm'}\E/i) {
 8626:                                         $matched = 1;
 8627:                                     }
 8628:                                 }
 8629:                                 if ($matched) {
 8630:                                     $srch_results{$user} = 
 8631: 					{&Apache::lonnet::get('environment',
 8632: 							     ['firstname',
 8633: 							      'lastname',
 8634: 							      'permanentemail'],
 8635: 							      $cudomain,$cuname)};
 8636:                                 }
 8637:                             }
 8638:                         }
 8639:                         ($currstate,$response,$forcenewuser) =
 8640:                             &build_search_response($context,$srch,%srch_results);
 8641:                     }
 8642:                 }
 8643:             }
 8644:         } elsif ($srch->{'srchin'} eq 'alc') {
 8645:             $currstate = 'query';
 8646:         } elsif ($srch->{'srchin'} eq 'instd') {
 8647:             ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query($srch);
 8648:             if ($dirsrchres eq 'ok') {
 8649:                 ($currstate,$response,$forcenewuser) = 
 8650:                     &build_search_response($context,$srch,%srch_results);
 8651:             } else {
 8652:                 my $showdom = &display_domain_info($srch->{'srchdomain'});
 8653:                 $response = '<span class="LC_warning">'.
 8654:                     &mt('Institutional directory search is not available in domain: [_1]',$showdom).
 8655:                     '</span><br />'.
 8656:                     &mt('You may want to search in the LON-CAPA domain instead of the institutional directory.').
 8657:                     '<br />'; 
 8658:             }
 8659:         }
 8660:     } else {
 8661:         if ($srch->{'srchin'} eq 'dom') {
 8662:             %srch_results = &Apache::lonnet::usersearch($srch);
 8663:             ($currstate,$response,$forcenewuser) = 
 8664:                 &build_search_response($context,$srch,%srch_results); 
 8665:         } elsif ($srch->{'srchin'} eq 'crs') {
 8666:             my $courseusers = &get_courseusers(); 
 8667:             foreach my $user (keys(%$courseusers)) {
 8668:                 my ($uname,$udom) = split(/:/,$user);
 8669:                 my %names = &Apache::loncommon::getnames($uname,$udom);
 8670:                 my %emails = &Apache::loncommon::getemails($uname,$udom);
 8671:                 if ($srch->{'srchby'} eq 'lastname') {
 8672:                     if ((($srch->{'srchtype'} eq 'exact') && 
 8673:                          ($names{'lastname'} eq $srch->{'srchterm'})) || 
 8674:                         (($srch->{'srchtype'} eq 'begins') &&
 8675:                          ($names{'lastname'} =~ /^\Q$srch->{'srchterm'}\E/i)) ||
 8676:                         (($srch->{'srchtype'} eq 'contains') &&
 8677:                          ($names{'lastname'} =~ /\Q$srch->{'srchterm'}\E/i))) {
 8678:                         $srch_results{$user} = {firstname => $names{'firstname'},
 8679:                                             lastname => $names{'lastname'},
 8680:                                             permanentemail => $emails{'permanentemail'},
 8681:                                            };
 8682:                     }
 8683:                 } elsif ($srch->{'srchby'} eq 'lastfirst') {
 8684:                     my ($srchlast,$srchfirst) = split(/,/,$srch->{'srchterm'});
 8685:                     $srchlast =~ s/\s+$//;
 8686:                     $srchfirst =~ s/^\s+//;
 8687:                     if ($srch->{'srchtype'} eq 'exact') {
 8688:                         if (($names{'lastname'} eq $srchlast) &&
 8689:                             ($names{'firstname'} eq $srchfirst)) {
 8690:                             $srch_results{$user} = {firstname => $names{'firstname'},
 8691:                                                 lastname => $names{'lastname'},
 8692:                                                 permanentemail => $emails{'permanentemail'},
 8693: 
 8694:                                            };
 8695:                         }
 8696:                     } elsif ($srch->{'srchtype'} eq 'begins') {
 8697:                         if (($names{'lastname'} =~ /^\Q$srchlast\E/i) &&
 8698:                             ($names{'firstname'} =~ /^\Q$srchfirst\E/i)) {
 8699:                             $srch_results{$user} = {firstname => $names{'firstname'},
 8700:                                                 lastname => $names{'lastname'},
 8701:                                                 permanentemail => $emails{'permanentemail'},
 8702:                                                };
 8703:                         }
 8704:                     } else {
 8705:                         if (($names{'lastname'} =~ /\Q$srchlast\E/i) && 
 8706:                             ($names{'firstname'} =~ /\Q$srchfirst\E/i)) {
 8707:                             $srch_results{$user} = {firstname => $names{'firstname'},
 8708:                                                 lastname => $names{'lastname'},
 8709:                                                 permanentemail => $emails{'permanentemail'},
 8710:                                                };
 8711:                         }
 8712:                     }
 8713:                 }
 8714:             }
 8715:             ($currstate,$response,$forcenewuser) = 
 8716:                 &build_search_response($context,$srch,%srch_results); 
 8717:         } elsif ($srch->{'srchin'} eq 'alc') {
 8718:             $currstate = 'query';
 8719:         } elsif ($srch->{'srchin'} eq 'instd') {
 8720:             ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query($srch); 
 8721:             if ($dirsrchres eq 'ok') {
 8722:                 ($currstate,$response,$forcenewuser) = 
 8723:                     &build_search_response($context,$srch,%srch_results);
 8724:             } else {
 8725:                 my $showdom = &display_domain_info($srch->{'srchdomain'});
 8726:                 $response = '<span class="LC_warning">'.
 8727:                     &mt('Institutional directory search is not available in domain: [_1]',$showdom).
 8728:                     '</span><br />'.
 8729:                     &mt('You may want to search in the LON-CAPA domain instead of the institutional directory.').
 8730:                     '<br />';
 8731:             }
 8732:         }
 8733:     }
 8734:     return ($currstate,$response,$forcenewuser,\%srch_results);
 8735: }
 8736: 
 8737: sub domdirectorysrch_check {
 8738:     my ($srch) = @_;
 8739:     my $response;
 8740:     my %dom_inst_srch = &Apache::lonnet::get_dom('configuration',
 8741:                                              ['directorysrch'],$srch->{'srchdomain'});
 8742:     my $showdom = &display_domain_info($srch->{'srchdomain'});
 8743:     if (ref($dom_inst_srch{'directorysrch'}) eq 'HASH') {
 8744:         if ($dom_inst_srch{'directorysrch'}{'lcavailable'} eq '0') {
 8745:             return &mt('LON-CAPA directory search is not available in domain: [_1]',$showdom);
 8746:         }
 8747:         if ($dom_inst_srch{'directorysrch'}{'lclocalonly'}) {
 8748:             if ($env{'request.role.domain'} ne $srch->{'srchdomain'}) {
 8749:                 return &mt('LON-CAPA directory search in domain: [_1] is only allowed for users with a current role in the domain.',$showdom);
 8750:             }
 8751:         }
 8752:     }
 8753:     return 'ok';
 8754: }
 8755: 
 8756: sub instdirectorysrch_check {
 8757:     my ($srch) = @_;
 8758:     my $can_search = 0;
 8759:     my $response;
 8760:     my %dom_inst_srch = &Apache::lonnet::get_dom('configuration',
 8761:                                              ['directorysrch'],$srch->{'srchdomain'});
 8762:     my $showdom = &display_domain_info($srch->{'srchdomain'});
 8763:     if (ref($dom_inst_srch{'directorysrch'}) eq 'HASH') {
 8764:         if (!$dom_inst_srch{'directorysrch'}{'available'}) {
 8765:             return &mt('Institutional directory search is not available in domain: [_1]',$showdom); 
 8766:         }
 8767:         if ($dom_inst_srch{'directorysrch'}{'localonly'}) {
 8768:             if ($env{'request.role.domain'} ne $srch->{'srchdomain'}) {
 8769:                 return &mt('Institutional directory search in domain: [_1] is only allowed for users with a current role in the domain.',$showdom); 
 8770:             }
 8771:             my @usertypes = split(/:/,$env{'environment.inststatus'});
 8772:             if (!@usertypes) {
 8773:                 push(@usertypes,'default');
 8774:             }
 8775:             if (ref($dom_inst_srch{'directorysrch'}{'cansearch'}) eq 'ARRAY') {
 8776:                 foreach my $type (@usertypes) {
 8777:                     if (grep(/^\Q$type\E$/,@{$dom_inst_srch{'directorysrch'}{'cansearch'}})) {
 8778:                         $can_search = 1;
 8779:                         last;
 8780:                     }
 8781:                 }
 8782:             }
 8783:             if (!$can_search) {
 8784:                 my ($insttypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($srch->{'srchdomain'});
 8785:                 my @longtypes; 
 8786:                 foreach my $item (@usertypes) {
 8787:                     if (defined($insttypes->{$item})) { 
 8788:                         push (@longtypes,$insttypes->{$item});
 8789:                     } elsif ($item eq 'default') {
 8790:                         push (@longtypes,&mt('other')); 
 8791:                     }
 8792:                 }
 8793:                 my $insttype_str = join(', ',@longtypes); 
 8794:                 return &mt('Institutional directory search in domain: [_1] is not available to your user type: ',$showdom).$insttype_str;
 8795:             }
 8796:         } else {
 8797:             $can_search = 1;
 8798:         }
 8799:     } else {
 8800:         return &mt('Institutional directory search has not been configured for domain: [_1]',$showdom);
 8801:     }
 8802:     my %longtext = &Apache::lonlocal::texthash (
 8803:                        uname     => 'username',
 8804:                        lastfirst => 'last name, first name',
 8805:                        lastname  => 'last name',
 8806:                        contains  => 'contains',
 8807:                        exact     => 'as exact match to',
 8808:                        begins    => 'begins with',
 8809:                    );
 8810:     if ($can_search) {
 8811:         if (ref($dom_inst_srch{'directorysrch'}{'searchby'}) eq 'ARRAY') {
 8812:             if (!grep(/^\Q$srch->{'srchby'}\E$/,@{$dom_inst_srch{'directorysrch'}{'searchby'}})) {
 8813:                 return &mt('Institutional directory search in domain: [_1] is not available for searching by "[_2]"',$showdom,$longtext{$srch->{'srchby'}});
 8814:             }
 8815:         } else {
 8816:             return &mt('Institutional directory search in domain: [_1] is not available.', $showdom);
 8817:         }
 8818:     }
 8819:     if ($can_search) {
 8820:         if (ref($dom_inst_srch{'directorysrch'}{'searchtypes'}) eq 'ARRAY') {
 8821:             if (grep(/^\Q$srch->{'srchtype'}\E/,@{$dom_inst_srch{'directorysrch'}{'searchtypes'}})) {
 8822:                 return 'ok';
 8823:             } else {
 8824:                 return &mt('Institutional directory search in domain [_1] is not available for the requested search type: "[_2]"',$showdom,$longtext{$srch->{'srchtype'}});
 8825:             }
 8826:         } else {
 8827:             if ((($dom_inst_srch{'directorysrch'}{'searchtypes'} eq 'specify') &&
 8828:                  ($srch->{'srchtype'} eq 'exact' || $srch->{'srchtype'} eq 'contains')) ||
 8829:                 ($dom_inst_srch{'directorysrch'}{'searchtypes'} eq $srch->{'srchtype'})) {
 8830:                 return 'ok';
 8831:             } else {
 8832:                 return &mt('Institutional directory search in domain [_1] is not available for the requested search type: "[_2]"',$showdom,$longtext{$srch->{'srchtype'}});
 8833:             }
 8834:         }
 8835:     }
 8836: }
 8837: 
 8838: sub get_courseusers {
 8839:     my %advhash;
 8840:     my $classlist = &Apache::loncoursedata::get_classlist();
 8841:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles();
 8842:     foreach my $role (sort(keys(%coursepersonnel))) {
 8843:         foreach my $user (split(/\,/,$coursepersonnel{$role})) {
 8844: 	    if (!exists($classlist->{$user})) {
 8845: 		$classlist->{$user} = [];
 8846: 	    }
 8847:         }
 8848:     }
 8849:     return $classlist;
 8850: }
 8851: 
 8852: sub build_search_response {
 8853:     my ($context,$srch,%srch_results) = @_;
 8854:     my ($currstate,$response,$forcenewuser);
 8855:     my %names = (
 8856:           'uname'     => 'username',
 8857:           'lastname'  => 'last name',
 8858:           'lastfirst' => 'last name, first name',
 8859:           'crs'       => 'this course',
 8860:           'dom'       => 'LON-CAPA domain',
 8861:           'instd'     => 'the institutional directory for domain',
 8862:     );
 8863: 
 8864:     my %single = (
 8865:                    begins   => 'A match',
 8866:                    contains => 'A match',
 8867:                    exact    => 'An exact match',
 8868:                  );
 8869:     my %nomatch = (
 8870:                    begins   => 'No match',
 8871:                    contains => 'No match',
 8872:                    exact    => 'No exact match',
 8873:                   );
 8874:     if (keys(%srch_results) > 1) {
 8875:         $currstate = 'select';
 8876:     } else {
 8877:         if (keys(%srch_results) == 1) {
 8878:             if ($env{'form.action'} eq 'accesslogs') {
 8879:                 $currstate = 'activity';
 8880:             } else {
 8881:                 $currstate = 'modify';
 8882:             }
 8883:             $response = &mt("$single{$srch->{'srchtype'}} was found for the $names{$srch->{'srchby'}} ([_1]) in $names{$srch->{'srchin'}}.",$srch->{'srchterm'});
 8884:             if ($srch->{'srchin'} eq 'dom' || $srch->{'srchin'} eq 'instd') {
 8885:                 $response .= ': '.&display_domain_info($srch->{'srchdomain'});
 8886:             }
 8887:         } else { # Search has nothing found. Prepare message to user.
 8888:             $response = '<span class="LC_warning">';
 8889:             if ($srch->{'srchin'} eq 'dom' || $srch->{'srchin'} eq 'instd') {
 8890:                 $response .= &mt("$nomatch{$srch->{'srchtype'}} found for the $names{$srch->{'srchby'}} [_1] in $names{$srch->{'srchin'}}: [_2]",
 8891:                                  '<b>'.$srch->{'srchterm'}.'</b>',
 8892:                                  &display_domain_info($srch->{'srchdomain'}));
 8893:             } else {
 8894:                 $response .= &mt("$nomatch{$srch->{'srchtype'}} found for the $names{$srch->{'srchby'}} [_1] in $names{$srch->{'srchin'}}.",
 8895:                                  '<b>'.$srch->{'srchterm'}.'</b>');
 8896:             }
 8897:             $response .= '</span>';
 8898: 
 8899:             if ($srch->{'srchin'} ne 'alc') {
 8900:                 $forcenewuser = 1;
 8901:                 my $cansrchinst = 0; 
 8902:                 if (($srch->{'srchdomain'}) && ($env{'form.action'} ne 'accesslogs')) {
 8903:                     my %domconfig = &Apache::lonnet::get_dom('configuration',['directorysrch'],$srch->{'srchdomain'});
 8904:                     if (ref($domconfig{'directorysrch'}) eq 'HASH') {
 8905:                         if ($domconfig{'directorysrch'}{'available'}) {
 8906:                             $cansrchinst = 1;
 8907:                         } 
 8908:                     }
 8909:                 }
 8910:                 if ((($srch->{'srchby'} eq 'lastfirst') || 
 8911:                      ($srch->{'srchby'} eq 'lastname')) &&
 8912:                     ($srch->{'srchin'} eq 'dom')) {
 8913:                     if ($cansrchinst) {
 8914:                         $response .= '<br />'.&mt('You may want to broaden your search to a search of the institutional directory for the domain.');
 8915:                     }
 8916:                 }
 8917:                 if ($srch->{'srchin'} eq 'crs') {
 8918:                     $response .= '<br />'.&mt('You may want to broaden your search to the selected LON-CAPA domain.');
 8919:                 }
 8920:             }
 8921:             my $createdom = $env{'request.role.domain'};
 8922:             if ($context eq 'requestcrs') {
 8923:                 if ($env{'form.coursedom'} ne '') {
 8924:                     $createdom = $env{'form.coursedom'};
 8925:                 }
 8926:             }
 8927:             unless (($env{'form.action'} eq 'accesslogs') || (($srch->{'srchby'} eq 'uname') && ($srch->{'srchin'} eq 'dom') &&
 8928:                     ($srch->{'srchtype'} eq 'exact') && ($srch->{'srchdomain'} eq $createdom))) {
 8929:                 my $cancreate =
 8930:                     &Apache::lonuserutils::can_create_user($createdom,$context);
 8931:                 my $targetdom = '<span class="LC_cusr_emph">'.$createdom.'</span>';
 8932:                 if ($cancreate) {
 8933:                     my $showdom = &display_domain_info($createdom); 
 8934:                     $response .= '<br /><br />'
 8935:                                 .'<b>'.&mt('To add a new user:').'</b>'
 8936:                                 .'<br />';
 8937:                     if ($context eq 'requestcrs') {
 8938:                         $response .= &mt("(You can only define new users in the new course's domain - [_1])",$targetdom);
 8939:                     } else {
 8940:                         $response .= &mt("(You can only create new users in your current role's domain - [_1])",$targetdom);
 8941:                     }
 8942:                     $response .='<ul><li>'
 8943:                                 .&mt("Set 'Domain/institution to search' to: [_1]",'<span class="LC_cusr_emph">'.$showdom.'</span>')
 8944:                                 .'</li><li>'
 8945:                                 .&mt("Set 'Search criteria' to: [_1]username is ..... in selected LON-CAPA domain[_2]",'<span class="LC_cusr_emph">','</span>')
 8946:                                 .'</li><li>'
 8947:                                 .&mt('Provide the proposed username')
 8948:                                 .'</li><li>'
 8949:                                 .&mt("Click 'Search'")
 8950:                                 .'</li></ul><br />';
 8951:                 } else {
 8952:                     unless (($context eq 'domain') && ($env{'form.action'} eq 'singleuser')) {
 8953:                         my $helplink = ' href="javascript:helpMenu('."'display'".')"';
 8954:                         $response .= '<br /><br />';
 8955:                         if ($context eq 'requestcrs') {
 8956:                             $response .= &mt("You are not authorized to define new users in the new course's domain - [_1].",$targetdom);
 8957:                         } else {
 8958:                             $response .= &mt("You are not authorized to create new users in your current role's domain - [_1].",$targetdom);
 8959:                         }
 8960:                         $response .= '<br />'
 8961:                                      .&mt('Please contact the [_1]helpdesk[_2] if you need to create a new user.'
 8962:                                         ,' <a'.$helplink.'>'
 8963:                                         ,'</a>')
 8964:                                      .'<br />';
 8965:                     }
 8966:                 }
 8967:             }
 8968:         }
 8969:     }
 8970:     return ($currstate,$response,$forcenewuser);
 8971: }
 8972: 
 8973: sub display_domain_info {
 8974:     my ($dom) = @_;
 8975:     my $output = $dom;
 8976:     if ($dom ne '') { 
 8977:         my $domdesc = &Apache::lonnet::domain($dom,'description');
 8978:         if ($domdesc ne '') {
 8979:             $output .= ' <span class="LC_cusr_emph">('.$domdesc.')</span>';
 8980:         }
 8981:     }
 8982:     return $output;
 8983: }
 8984: 
 8985: sub crumb_utilities {
 8986:     my %elements = (
 8987:        crtuser => {
 8988:            srchterm => 'text',
 8989:            srchin => 'selectbox',
 8990:            srchby => 'selectbox',
 8991:            srchtype => 'selectbox',
 8992:            srchdomain => 'selectbox',
 8993:        },
 8994:        crtusername => {
 8995:            srchterm => 'text',
 8996:            srchdomain => 'selectbox',
 8997:        },
 8998:        docustom => {
 8999:            rolename => 'selectbox',
 9000:            newrolename => 'textbox',
 9001:        },
 9002:        studentform => {
 9003:            srchterm => 'text',
 9004:            srchin => 'selectbox',
 9005:            srchby => 'selectbox',
 9006:            srchtype => 'selectbox',
 9007:            srchdomain => 'selectbox',
 9008:        },
 9009:     );
 9010: 
 9011:     my $jsback .= qq|
 9012: function backPage(formname,prevphase,prevstate) {
 9013:     if (typeof prevphase == 'undefined') {
 9014:         formname.phase.value = '';
 9015:     }
 9016:     else {  
 9017:         formname.phase.value = prevphase;
 9018:     }
 9019:     if (typeof prevstate == 'undefined') {
 9020:         formname.currstate.value = '';
 9021:     }
 9022:     else {
 9023:         formname.currstate.value = prevstate;
 9024:     }
 9025:     formname.submit();
 9026: }
 9027: |;
 9028:     return ($jsback,\%elements);
 9029: }
 9030: 
 9031: sub course_level_table {
 9032:     my ($inccourses,$showcredits,$defaultcredits) = @_;
 9033:     return unless (ref($inccourses) eq 'HASH');
 9034:     my $table = '';
 9035: # Custom Roles?
 9036: 
 9037:     my %customroles=&Apache::lonuserutils::my_custom_roles();
 9038:     my %lt=&Apache::lonlocal::texthash(
 9039:             'exs'  => "Existing sections",
 9040:             'new'  => "Define new section",
 9041:             'ssd'  => "Set Start Date",
 9042:             'sed'  => "Set End Date",
 9043:             'crl'  => "Course Level",
 9044:             'act'  => "Activate",
 9045:             'rol'  => "Role",
 9046:             'ext'  => "Extent",
 9047:             'grs'  => "Section",
 9048:             'crd'  => "Credits",
 9049:             'sta'  => "Start",
 9050:             'end'  => "End"
 9051:     );
 9052: 
 9053:     foreach my $protectedcourse (sort(keys(%{$inccourses}))) {
 9054: 	my $thiscourse=$protectedcourse;
 9055: 	$thiscourse=~s:_:/:g;
 9056: 	my %coursedata=&Apache::lonnet::coursedescription($thiscourse);
 9057:         my $isowner = &Apache::lonuserutils::is_courseowner($protectedcourse,$coursedata{'internal.courseowner'});
 9058: 	my $area=$coursedata{'description'};
 9059:         my $crstype=$coursedata{'type'};
 9060: 	if (!defined($area)) { $area=&mt('Unavailable course').': '.$protectedcourse; }
 9061: 	my ($domain,$cnum)=split(/\//,$thiscourse);
 9062:         my %sections_count;
 9063:         if (defined($env{'request.course.id'})) {
 9064:             if ($env{'request.course.id'} eq $domain.'_'.$cnum) {
 9065:                 %sections_count = 
 9066: 		    &Apache::loncommon::get_sections($domain,$cnum);
 9067:             }
 9068:         }
 9069:         my @roles = &Apache::lonuserutils::roles_by_context('course','',$crstype);
 9070: 	foreach my $role (@roles) {
 9071:             my $plrole=&Apache::lonnet::plaintext($role,$crstype);
 9072: 	    if ((&Apache::lonnet::allowed('c'.$role,$thiscourse)) ||
 9073:                 ((($role eq 'cc') || ($role eq 'co')) && ($isowner))) {
 9074:                 $table .= &course_level_row($protectedcourse,$role,$area,$domain,
 9075:                                             $plrole,\%sections_count,\%lt,
 9076:                                             $showcredits,$defaultcredits,$crstype);
 9077:             } elsif ($env{'request.course.sec'} ne '') {
 9078:                 if (&Apache::lonnet::allowed('c'.$role,$thiscourse.'/'.
 9079:                                              $env{'request.course.sec'})) {
 9080:                     $table .= &course_level_row($protectedcourse,$role,$area,$domain,
 9081:                                                 $plrole,\%sections_count,\%lt,
 9082:                                                 $showcredits,$defaultcredits,$crstype);
 9083:                 }
 9084:             }
 9085:         }
 9086:         if (&Apache::lonnet::allowed('ccr',$thiscourse)) {
 9087:             foreach my $cust (sort(keys(%customroles))) {
 9088:                 next if ($crstype eq 'Community' && $customroles{$cust} =~ /bre\&S/);
 9089:                 my $role = 'cr_cr_'.$env{'user.domain'}.'_'.$env{'user.name'}.'_'.$cust;
 9090:                 $table .= &course_level_row($protectedcourse,$role,$area,$domain,
 9091:                                             $cust,\%sections_count,\%lt,
 9092:                                             $showcredits,$defaultcredits,$crstype);
 9093:             }
 9094: 	}
 9095:     }
 9096:     return '' if ($table eq ''); # return nothing if there is nothing 
 9097:                                  # in the table
 9098:     my $result;
 9099:     if (!$env{'request.course.id'}) {
 9100:         $result = '<h4>'.$lt{'crl'}.'</h4>'."\n";
 9101:     }
 9102:     $result .= 
 9103: &Apache::loncommon::start_data_table().
 9104: &Apache::loncommon::start_data_table_header_row().
 9105: '<th>'.$lt{'act'}.'</th><th>'.$lt{'rol'}.'</th>'."\n".
 9106: '<th>'.$lt{'ext'}.'</th><th>'."\n";
 9107:     if ($showcredits) {
 9108:         $result .= $lt{'crd'}.'</th>';
 9109:     }
 9110:     $result .=
 9111: '<th>'.$lt{'grs'}.'</th><th>'.$lt{'sta'}.'</th>'."\n".
 9112: '<th>'.$lt{'end'}.'</th>'.
 9113: &Apache::loncommon::end_data_table_header_row().
 9114: $table.
 9115: &Apache::loncommon::end_data_table();
 9116:     return $result;
 9117: }
 9118: 
 9119: sub course_level_row {
 9120:     my ($protectedcourse,$role,$area,$domain,$plrole,$sections_count,
 9121:         $lt,$showcredits,$defaultcredits,$crstype) = @_;
 9122:     my $creditem;
 9123:     my $row = &Apache::loncommon::start_data_table_row().
 9124:               ' <td><input type="checkbox" name="act_'.
 9125:               $protectedcourse.'_'.$role.'" /></td>'."\n".
 9126:               ' <td>'.$plrole.'</td>'."\n".
 9127:               ' <td>'.$area.'<br />Domain: '.$domain.'</td>'."\n";
 9128:     if (($showcredits) && ($role eq 'st') && ($crstype eq 'Course')) {
 9129:         $row .= 
 9130:             '<td><input type="text" name="credits_'.$protectedcourse.'_'.
 9131:             $role.'" size="3" value="'.$defaultcredits.'" /></td>';
 9132:     } else {
 9133:         $row .= '<td>&nbsp;</td>';
 9134:     }
 9135:     if (($role eq 'cc') || ($role eq 'co')) {
 9136:         $row .= '<td>&nbsp;</td>';
 9137:     } elsif ($env{'request.course.sec'} ne '') {
 9138:         $row .= ' <td><input type="hidden" value="'.
 9139:                 $env{'request.course.sec'}.'" '.
 9140:                 'name="sec_'.$protectedcourse.'_'.$role.'" />'.
 9141:                 $env{'request.course.sec'}.'</td>';
 9142:     } else {
 9143:         if (ref($sections_count) eq 'HASH') {
 9144:             my $currsec = 
 9145:                 &Apache::lonuserutils::course_sections($sections_count,
 9146:                                                        $protectedcourse.'_'.$role);
 9147:             $row .= '<td><table class="LC_createuser">'."\n".
 9148:                     '<tr class="LC_section_row">'."\n".
 9149:                     ' <td valign="top">'.$lt->{'exs'}.'<br />'.
 9150:                        $currsec.'</td>'."\n".
 9151:                      ' <td>&nbsp;&nbsp;</td>'."\n".
 9152:                      ' <td valign="top">&nbsp;'.$lt->{'new'}.'<br />'.
 9153:                      '<input type="text" name="newsec_'.$protectedcourse.'_'.$role.
 9154:                      '" value="" />'.
 9155:                      '<input type="hidden" '.
 9156:                      'name="sec_'.$protectedcourse.'_'.$role.'" /></td>'."\n".
 9157:                      '</tr></table></td>'."\n";
 9158:         } else {
 9159:             $row .= '<td><input type="text" size="10" '.
 9160:                     'name="sec_'.$protectedcourse.'_'.$role.'" /></td>'."\n";
 9161:         }
 9162:     }
 9163:     $row .= <<ENDTIMEENTRY;
 9164: <td><input type="hidden" name="start_$protectedcourse\_$role" value="" />
 9165: <a href=
 9166: "javascript:pjump('date_start','Start Date $plrole',document.cu.start_$protectedcourse\_$role.value,'start_$protectedcourse\_$role','cu.pres','dateset')">$lt->{'ssd'}</a></td>
 9167: <td><input type="hidden" name="end_$protectedcourse\_$role" value="" />
 9168: <a href=
 9169: "javascript:pjump('date_end','End Date $plrole',document.cu.end_$protectedcourse\_$role.value,'end_$protectedcourse\_$role','cu.pres','dateset')">$lt->{'sed'}</a></td>
 9170: ENDTIMEENTRY
 9171:     $row .= &Apache::loncommon::end_data_table_row();
 9172:     return $row;
 9173: }
 9174: 
 9175: sub course_level_dc {
 9176:     my ($dcdom,$showcredits) = @_;
 9177:     my %customroles=&Apache::lonuserutils::my_custom_roles();
 9178:     my @roles = &Apache::lonuserutils::roles_by_context('course');
 9179:     my $hiddenitems = '<input type="hidden" name="dcdomain" value="'.$dcdom.'" />'.
 9180:                       '<input type="hidden" name="origdom" value="'.$dcdom.'" />'.
 9181:                       '<input type="hidden" name="dccourse" value="" />';
 9182:     my $courseform=&Apache::loncommon::selectcourse_link
 9183:             ('cu','dccourse','dcdomain','coursedesc',undef,undef,'Select','crstype');
 9184:     my $credit_elem;
 9185:     if ($showcredits) {
 9186:         $credit_elem = 'credits';
 9187:     }
 9188:     my $cb_jscript = &Apache::loncommon::coursebrowser_javascript($dcdom,'currsec','cu','role','Course/Community Browser',$credit_elem);
 9189:     my %lt=&Apache::lonlocal::texthash(
 9190:                     'rol'  => "Role",
 9191:                     'grs'  => "Section",
 9192:                     'exs'  => "Existing sections",
 9193:                     'new'  => "Define new section", 
 9194:                     'sta'  => "Start",
 9195:                     'end'  => "End",
 9196:                     'ssd'  => "Set Start Date",
 9197:                     'sed'  => "Set End Date",
 9198:                     'scc'  => "Course/Community",
 9199:                     'crd'  => "Credits",
 9200:                   );
 9201:     my $header = '<h4>'.&mt('Course/Community Level').'</h4>'.
 9202:                  &Apache::loncommon::start_data_table().
 9203:                  &Apache::loncommon::start_data_table_header_row().
 9204:                  '<th>'.$lt{'scc'}.'</th><th>'.$lt{'rol'}.'</th>'."\n".
 9205:                  '<th>'.$lt{'grs'}.'</th>'."\n";
 9206:     $header .=   '<th>'.$lt{'crd'}.'</th>'."\n" if ($showcredits);
 9207:     $header .=   '<th>'.$lt{'sta'}.'</th><th>'.$lt{'end'}.'</th>'."\n".
 9208:                  &Apache::loncommon::end_data_table_header_row();
 9209:     my $otheritems = &Apache::loncommon::start_data_table_row()."\n".
 9210:                      '<td><br /><span class="LC_nobreak"><input type="text" name="coursedesc" value="" onfocus="this.blur();opencrsbrowser('."'cu','dccourse','dcdomain','coursedesc','','','','crstype'".')" />'.
 9211:                      $courseform.('&nbsp;' x4).'</span></td>'."\n".
 9212:                      '<td valign="top"><br /><select name="role">'."\n";
 9213:     foreach my $role (@roles) {
 9214:         my $plrole=&Apache::lonnet::plaintext($role);
 9215:         $otheritems .= '  <option value="'.$role.'">'.$plrole.'</option>';
 9216:     }
 9217:     if ( keys(%customroles) > 0) {
 9218:         foreach my $cust (sort(keys(%customroles))) {
 9219:             my $custrole='cr_cr_'.$env{'user.domain'}.
 9220:                     '_'.$env{'user.name'}.'_'.$cust;
 9221:             $otheritems .= '  <option value="'.$custrole.'">'.$cust.'</option>';
 9222:         }
 9223:     }
 9224:     $otheritems .= '</select></td><td>'.
 9225:                      '<table border="0" cellspacing="0" cellpadding="0">'.
 9226:                      '<tr><td valign="top"><b>'.$lt{'exs'}.'</b><br /><select name="currsec">'.
 9227:                      ' <option value="">&lt;--'.&mt('Pick course first').'</option></select></td>'.
 9228:                      '<td>&nbsp;&nbsp;</td>'.
 9229:                      '<td valign="top">&nbsp;<b>'.$lt{'new'}.'</b><br />'.
 9230:                      '<input type="text" name="newsec" value="" />'.
 9231:                      '<input type="hidden" name="section" value="" />'.
 9232:                      '<input type="hidden" name="groups" value="" />'.
 9233:                      '<input type="hidden" name="crstype" value="" /></td>'.
 9234:                      '</tr></table></td>'."\n";
 9235:     if ($showcredits) {
 9236:         $otheritems .= '<td><br />'."\n".
 9237:                        '<input type="text" size="3" name="credits" value="" /></td>'."\n";
 9238:     }
 9239:     $otheritems .= <<ENDTIMEENTRY;
 9240: <td><br /><input type="hidden" name="start" value='' />
 9241: <a href=
 9242: "javascript:pjump('date_start','Start Date',document.cu.start.value,'start','cu.pres','dateset')">$lt{'ssd'}</a></td>
 9243: <td><br /><input type="hidden" name="end" value='' />
 9244: <a href=
 9245: "javascript:pjump('date_end','End Date',document.cu.end.value,'end','cu.pres','dateset')">$lt{'sed'}</a></td>
 9246: ENDTIMEENTRY
 9247:     $otheritems .= &Apache::loncommon::end_data_table_row().
 9248:                    &Apache::loncommon::end_data_table()."\n";
 9249:     return $cb_jscript.$header.$hiddenitems.$otheritems;
 9250: }
 9251: 
 9252: sub update_selfenroll_config {
 9253:     my ($r,$cid,$cdom,$cnum,$context,$crstype,$currsettings) = @_;
 9254:     return unless (ref($currsettings) eq 'HASH');
 9255:     my ($row,$lt) = &Apache::lonuserutils::get_selfenroll_titles();
 9256:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
 9257:     my (%changes,%warning);
 9258:     my $curr_types;
 9259:     my %noedit;
 9260:     unless ($context eq 'domain') {
 9261:         %noedit = &get_noedit_fields($cdom,$cnum,$crstype,$row);
 9262:     }
 9263:     if (ref($row) eq 'ARRAY') {
 9264:         foreach my $item (@{$row}) {
 9265:             next if ($noedit{$item});
 9266:             if ($item eq 'enroll_dates') {
 9267:                 my (%currenrolldate,%newenrolldate);
 9268:                 foreach my $type ('start','end') {
 9269:                     $currenrolldate{$type} = $currsettings->{'selfenroll_'.$type.'_date'};
 9270:                     $newenrolldate{$type} = &Apache::lonhtmlcommon::get_date_from_form('selfenroll_'.$type.'_date');
 9271:                     if ($newenrolldate{$type} ne $currenrolldate{$type}) {
 9272:                         $changes{'internal.selfenroll_'.$type.'_date'} = $newenrolldate{$type};
 9273:                     }
 9274:                 }
 9275:             } elsif ($item eq 'access_dates') {
 9276:                 my (%currdate,%newdate);
 9277:                 foreach my $type ('start','end') {
 9278:                     $currdate{$type} = $currsettings->{'selfenroll_'.$type.'_access'};
 9279:                     $newdate{$type} = &Apache::lonhtmlcommon::get_date_from_form('selfenroll_'.$type.'_access');
 9280:                     if ($newdate{$type} ne $currdate{$type}) {
 9281:                         $changes{'internal.selfenroll_'.$type.'_access'} = $newdate{$type};
 9282:                     }
 9283:                 }
 9284:             } elsif ($item eq 'types') {
 9285:                 $curr_types = $currsettings->{'selfenroll_'.$item};
 9286:                 if ($env{'form.selfenroll_all'}) {
 9287:                     if ($curr_types ne '*') {
 9288:                         $changes{'internal.selfenroll_types'} = '*';
 9289:                     } else {
 9290:                         next;
 9291:                     }
 9292:                 } else {
 9293:                     my %currdoms;
 9294:                     my @entries = split(/;/,$curr_types);
 9295:                     my @deletedoms = &Apache::loncommon::get_env_multiple('form.selfenroll_delete');
 9296:                     my @activations = &Apache::loncommon::get_env_multiple('form.selfenroll_activate');
 9297:                     my $newnum = 0;
 9298:                     my @latesttypes;
 9299:                     foreach my $num (@activations) {
 9300:                         my @types = &Apache::loncommon::get_env_multiple('form.selfenroll_types_'.$num);
 9301:                         if (@types > 0) {
 9302:                             @types = sort(@types);
 9303:                             my $typestr = join(',',@types);
 9304:                             my $typedom = $env{'form.selfenroll_dom_'.$num};
 9305:                             $latesttypes[$newnum] = $typedom.':'.$typestr;
 9306:                             $currdoms{$typedom} = 1;
 9307:                             $newnum ++;
 9308:                         }
 9309:                     }
 9310:                     for (my $j=0; $j<$env{'form.selfenroll_types_total'}; $j++) {
 9311:                         if ((!grep(/^$j$/,@deletedoms)) && (!grep(/^$j$/,@activations))) {
 9312:                             my @types = &Apache::loncommon::get_env_multiple('form.selfenroll_types_'.$j);
 9313:                             if (@types > 0) {
 9314:                                 @types = sort(@types);
 9315:                                 my $typestr = join(',',@types);
 9316:                                 my $typedom = $env{'form.selfenroll_dom_'.$j};
 9317:                                 $latesttypes[$newnum] = $typedom.':'.$typestr;
 9318:                                 $currdoms{$typedom} = 1;
 9319:                                 $newnum ++;
 9320:                             }
 9321:                         }
 9322:                     }
 9323:                     if ($env{'form.selfenroll_newdom'} ne '') {
 9324:                         my $typedom = $env{'form.selfenroll_newdom'};
 9325:                         if ((!defined($currdoms{$typedom})) && 
 9326:                             (&Apache::lonnet::domain($typedom) ne '')) {
 9327:                             my $typestr;
 9328:                             my ($othertitle,$usertypes,$types) = 
 9329:                                 &Apache::loncommon::sorted_inst_types($typedom);
 9330:                             my $othervalue = 'any';
 9331:                             if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 9332:                                 if (@{$types} > 0) {
 9333:                                     my @esc_types = map { &escape($_); } @{$types};
 9334:                                     $othervalue = 'other';
 9335:                                     $typestr = join(',',(@esc_types,$othervalue));
 9336:                                 }
 9337:                                 $typestr = $othervalue;
 9338:                             } else {
 9339:                                 $typestr = $othervalue;
 9340:                             } 
 9341:                             $latesttypes[$newnum] = $typedom.':'.$typestr;
 9342:                             $newnum ++ ;
 9343:                         }
 9344:                     }
 9345:                     my $selfenroll_types = join(';',@latesttypes);
 9346:                     if ($selfenroll_types ne $curr_types) {
 9347:                         $changes{'internal.selfenroll_types'} = $selfenroll_types;
 9348:                     }
 9349:                 }
 9350:             } elsif ($item eq 'limit') {
 9351:                 my $newlimit = $env{'form.selfenroll_limit'};
 9352:                 my $newcap = $env{'form.selfenroll_cap'};
 9353:                 $newcap =~s/\s+//g;
 9354:                 my $currlimit =  $currsettings->{'selfenroll_limit'};
 9355:                 $currlimit = 'none' if ($currlimit eq '');
 9356:                 my $currcap = $currsettings->{'selfenroll_cap'};
 9357:                 if ($newlimit ne $currlimit) {
 9358:                     if ($newlimit ne 'none') {
 9359:                         if ($newcap =~ /^\d+$/) {
 9360:                             if ($newcap ne $currcap) {
 9361:                                 $changes{'internal.selfenroll_cap'} = $newcap;
 9362:                             }
 9363:                             $changes{'internal.selfenroll_limit'} = $newlimit;
 9364:                         } else {
 9365:                             $warning{$item} = &mt('Maximum enrollment setting unchanged.').'<br />'.
 9366:                                 &mt('The value provided was invalid - it must be a positive integer if enrollment is being limited.'); 
 9367:                         }
 9368:                     } elsif ($currcap ne '') {
 9369:                         $changes{'internal.selfenroll_cap'} = '';
 9370:                         $changes{'internal.selfenroll_limit'} = $newlimit; 
 9371:                     }
 9372:                 } elsif ($currlimit ne 'none') {
 9373:                     if ($newcap =~ /^\d+$/) {
 9374:                         if ($newcap ne $currcap) {
 9375:                             $changes{'internal.selfenroll_cap'} = $newcap;
 9376:                         }
 9377:                     } else {
 9378:                         $warning{$item} = &mt('Maximum enrollment setting unchanged.').'<br />'.
 9379:                             &mt('The value provided was invalid - it must be a positive integer if enrollment is being limited.');
 9380:                     }
 9381:                 }
 9382:             } elsif ($item eq 'approval') {
 9383:                 my (@currnotified,@newnotified);
 9384:                 my $currapproval = $currsettings->{'selfenroll_approval'};
 9385:                 my $currnotifylist = $currsettings->{'selfenroll_notifylist'};
 9386:                 if ($currnotifylist ne '') {
 9387:                     @currnotified = split(/,/,$currnotifylist);
 9388:                     @currnotified = sort(@currnotified);
 9389:                 }
 9390:                 my $newapproval = $env{'form.selfenroll_approval'};
 9391:                 @newnotified = &Apache::loncommon::get_env_multiple('form.selfenroll_notify');
 9392:                 @newnotified = sort(@newnotified);
 9393:                 if ($newapproval ne $currapproval) {
 9394:                     $changes{'internal.selfenroll_approval'} = $newapproval;
 9395:                     if (!$newapproval) {
 9396:                         if ($currnotifylist ne '') {
 9397:                             $changes{'internal.selfenroll_notifylist'} = '';
 9398:                         }
 9399:                     } else {
 9400:                         my @differences =  
 9401:                             &Apache::loncommon::compare_arrays(\@currnotified,\@newnotified);
 9402:                         if (@differences > 0) {
 9403:                             if (@newnotified > 0) {
 9404:                                 $changes{'internal.selfenroll_notifylist'} = join(',',@newnotified);
 9405:                             } else {
 9406:                                 $changes{'internal.selfenroll_notifylist'} = join(',',@newnotified);
 9407:                             }
 9408:                         }
 9409:                     }
 9410:                 } else {
 9411:                     my @differences = &Apache::loncommon::compare_arrays(\@currnotified,\@newnotified);
 9412:                     if (@differences > 0) {
 9413:                         if (@newnotified > 0) {
 9414:                             $changes{'internal.selfenroll_notifylist'} = join(',',@newnotified);
 9415:                         } else {
 9416:                             $changes{'internal.selfenroll_notifylist'} = '';
 9417:                         }
 9418:                     }
 9419:                 }
 9420:             } else {
 9421:                 my $curr_val = $currsettings->{'selfenroll_'.$item};
 9422:                 my $newval = $env{'form.selfenroll_'.$item};
 9423:                 if ($item eq 'section') {
 9424:                     $newval = $env{'form.sections'};
 9425:                     if (defined($curr_groups{$newval})) {
 9426:                         $newval = $curr_val;
 9427:                         $warning{$item} = &mt('Section for self-enrolled users unchanged as the proposed section is a group').'<br />'.
 9428:                                           &mt('Group names and section names must be distinct');
 9429:                     } elsif ($newval eq 'all') {
 9430:                         $newval = $curr_val;
 9431:                         $warning{$item} = &mt('Section for self-enrolled users unchanged, as "all" is a reserved section name.');
 9432:                     }
 9433:                     if ($newval eq '') {
 9434:                         $newval = 'none';
 9435:                     }
 9436:                 }
 9437:                 if ($newval ne $curr_val) {
 9438:                     $changes{'internal.selfenroll_'.$item} = $newval;
 9439:                 }
 9440:             }
 9441:         }
 9442:         if (keys(%warning) > 0) {
 9443:             foreach my $item (@{$row}) {
 9444:                 if (exists($warning{$item})) {
 9445:                     $r->print($warning{$item}.'<br />');
 9446:                 }
 9447:             } 
 9448:         }
 9449:         if (keys(%changes) > 0) {
 9450:             my $putresult = &Apache::lonnet::put('environment',\%changes,$cdom,$cnum);
 9451:             if ($putresult eq 'ok') {
 9452:                 if ((exists($changes{'internal.selfenroll_types'})) ||
 9453:                     (exists($changes{'internal.selfenroll_start_date'}))  ||
 9454:                     (exists($changes{'internal.selfenroll_end_date'}))) {
 9455:                     my %crsinfo = &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',
 9456:                                                                 $cnum,undef,undef,'Course');
 9457:                     my $chome = &Apache::lonnet::homeserver($cnum,$cdom);
 9458:                     if (ref($crsinfo{$cid}) eq 'HASH') {
 9459:                         foreach my $item ('selfenroll_types','selfenroll_start_date','selfenroll_end_date') {
 9460:                             if (exists($changes{'internal.'.$item})) {
 9461:                                 $crsinfo{$cid}{$item} = $changes{'internal.'.$item};
 9462:                             }
 9463:                         }
 9464:                         my $crsputresult =
 9465:                             &Apache::lonnet::courseidput($cdom,\%crsinfo,
 9466:                                                          $chome,'notime');
 9467:                     }
 9468:                 }
 9469:                 $r->print(&mt('The following changes were made to self-enrollment settings:').'<ul>');
 9470:                 foreach my $item (@{$row}) {
 9471:                     my $title = $item;
 9472:                     if (ref($lt) eq 'HASH') {
 9473:                         $title = $lt->{$item};
 9474:                     }
 9475:                     if ($item eq 'enroll_dates') {
 9476:                         foreach my $type ('start','end') {
 9477:                             if (exists($changes{'internal.selfenroll_'.$type.'_date'})) {
 9478:                                 my $newdate = &Apache::lonlocal::locallocaltime($changes{'internal.selfenroll_'.$type.'_date'});
 9479:                                 $r->print('<li>'.&mt('[_1]: "[_2]" set to "[_3]".',
 9480:                                           $title,$type,$newdate).'</li>');
 9481:                             }
 9482:                         }
 9483:                     } elsif ($item eq 'access_dates') {
 9484:                         foreach my $type ('start','end') {
 9485:                             if (exists($changes{'internal.selfenroll_'.$type.'_access'})) {
 9486:                                 my $newdate = &Apache::lonlocal::locallocaltime($changes{'internal.selfenroll_'.$type.'_access'});
 9487:                                 $r->print('<li>'.&mt('[_1]: "[_2]" set to "[_3]".',
 9488:                                           $title,$type,$newdate).'</li>');
 9489:                             }
 9490:                         }
 9491:                     } elsif ($item eq 'limit') {
 9492:                         if ((exists($changes{'internal.selfenroll_limit'})) ||
 9493:                             (exists($changes{'internal.selfenroll_cap'}))) {
 9494:                             my ($newval,$newcap);
 9495:                             if ($changes{'internal.selfenroll_cap'} ne '') {
 9496:                                 $newcap = $changes{'internal.selfenroll_cap'}
 9497:                             } else {
 9498:                                 $newcap = $currsettings->{'selfenroll_cap'};
 9499:                             }
 9500:                             if ($changes{'internal.selfenroll_limit'} eq 'none') {
 9501:                                 $newval = &mt('No limit');
 9502:                             } elsif ($changes{'internal.selfenroll_limit'} eq 
 9503:                                      'allstudents') {
 9504:                                 $newval = &mt('New self-enrollment no longer allowed when total (all students) reaches [_1].',$newcap);
 9505:                             } elsif ($changes{'internal.selfenroll_limit'} eq 'selfenrolled') {
 9506:                                 $newval = &mt('New self-enrollment no longer allowed when total number of self-enrolled students reaches [_1].',$newcap);
 9507:                             } else {
 9508:                                 my $currlimit =  $currsettings->{'selfenroll_limit'};
 9509:                                 if ($currlimit eq 'allstudents') {
 9510:                                     $newval = &mt('New self-enrollment no longer allowed when total (all students) reaches [_1].',$newcap);
 9511:                                 } elsif ($changes{'internal.selfenroll_limit'} eq 'selfenrolled') {
 9512:                                     $newval =  &mt('New self-enrollment no longer allowed when total number of self-enrolled students reaches [_1].',$newcap);
 9513:                                 }
 9514:                             }
 9515:                             $r->print('<li>'.&mt('"[_1]" set to "[_2]".',$title,$newval).'</li>'."\n");
 9516:                         }
 9517:                     } elsif ($item eq 'approval') {
 9518:                         if ((exists($changes{'internal.selfenroll_approval'})) ||
 9519:                             (exists($changes{'internal.selfenroll_notifylist'}))) {
 9520:                             my %selfdescs = &Apache::lonuserutils::selfenroll_default_descs();
 9521:                             my ($newval,$newnotify);
 9522:                             if (exists($changes{'internal.selfenroll_notifylist'})) {
 9523:                                 $newnotify = $changes{'internal.selfenroll_notifylist'};
 9524:                             } else {   
 9525:                                 $newnotify = $currsettings->{'selfenroll_notifylist'};
 9526:                             }
 9527:                             if (exists($changes{'internal.selfenroll_approval'})) {
 9528:                                 if ($changes{'internal.selfenroll_approval'} !~ /^[012]$/) {
 9529:                                     $changes{'internal.selfenroll_approval'} = '0';
 9530:                                 }
 9531:                                 $newval = $selfdescs{'approval'}{$changes{'internal.selfenroll_approval'}};
 9532:                             } else {
 9533:                                 my $currapproval = $currsettings->{'selfenroll_approval'}; 
 9534:                                 if ($currapproval !~ /^[012]$/) {
 9535:                                     $currapproval = 0;
 9536:                                 }
 9537:                                 $newval = $selfdescs{'approval'}{$currapproval};
 9538:                             }
 9539:                             $r->print('<li>'.&mt('"[_1]" set to "[_2]".',$title,$newval));
 9540:                             if ($newnotify) {
 9541:                                 $r->print('<br />'.&mt('The following will be notified when an enrollment request needs approval, or has been approved: [_1].',$newnotify));
 9542:                             } else {
 9543:                                 $r->print('<br />'.&mt('No notifications sent when an enrollment request needs approval, or has been approved.'));
 9544:                             }
 9545:                             $r->print('</li>'."\n");
 9546:                         }
 9547:                     } else {
 9548:                         if (exists($changes{'internal.selfenroll_'.$item})) {
 9549:                             my $newval = $changes{'internal.selfenroll_'.$item};
 9550:                             if ($item eq 'types') {
 9551:                                 if ($newval eq '') {
 9552:                                     $newval = &mt('None');
 9553:                                 } elsif ($newval eq '*') {
 9554:                                     $newval = &mt('Any user in any domain');
 9555:                                 }
 9556:                             } elsif ($item eq 'registered') {
 9557:                                 if ($newval eq '1') {
 9558:                                     $newval = &mt('Yes');
 9559:                                 } elsif ($newval eq '0') {
 9560:                                     $newval = &mt('No');
 9561:                                 }
 9562:                             }
 9563:                             $r->print('<li>'.&mt('"[_1]" set to "[_2]".',$title,$newval).'</li>'."\n");
 9564:                         }
 9565:                     }
 9566:                 }
 9567:                 $r->print('</ul>');
 9568:                 if ($env{'course.'.$cid.'.description'} ne '') {
 9569:                     my %newenvhash;
 9570:                     foreach my $key (keys(%changes)) {
 9571:                         $newenvhash{'course.'.$cid.'.'.$key} = $changes{$key};
 9572:                     }
 9573:                     &Apache::lonnet::appenv(\%newenvhash);
 9574:                 }
 9575:             } else {
 9576:                 $r->print(&mt('An error occurred when saving changes to self-enrollment settings in this course.').'<br />'.
 9577:                           &mt('The error was: [_1].',$putresult));
 9578:             }
 9579:         } else {
 9580:             $r->print(&mt('No changes were made to the existing self-enrollment settings in this course.'));
 9581:         }
 9582:     } else {
 9583:         $r->print(&mt('No changes were made to the existing self-enrollment settings in this course.'));
 9584:     }
 9585:     my $visactions = &cat_visibility($cdom);
 9586:     my ($cathash,%cattype);
 9587:     my %domconfig = &Apache::lonnet::get_dom('configuration',['coursecategories'],$cdom);
 9588:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 9589:         $cathash = $domconfig{'coursecategories'}{'cats'};
 9590:         $cattype{'auth'} = $domconfig{'coursecategories'}{'auth'};
 9591:         $cattype{'unauth'} = $domconfig{'coursecategories'}{'unauth'};
 9592:     } else {
 9593:         $cathash = {};
 9594:         $cattype{'auth'} = 'std';
 9595:         $cattype{'unauth'} = 'std';
 9596:     }
 9597:     if (($cattype{'auth'} eq 'none') && ($cattype{'unauth'} eq 'none')) {
 9598:         $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
 9599:                   '<br />'.
 9600:                   '<br />'.$visactions->{'take'}.'<ul>'.
 9601:                   '<li>'.$visactions->{'dc_chgconf'}.'</li>'.
 9602:                   '</ul>');
 9603:     } elsif (($cattype{'auth'} !~ /^(std|domonly)$/) && ($cattype{'unauth'} !~ /^(std|domonly)$/)) {
 9604:         if ($currsettings->{'uniquecode'}) {
 9605:             $r->print('<span class="LC_info">'.$visactions->{'vis'}.'</span>');
 9606:         } else {
 9607:             $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
 9608:                   '<br />'.
 9609:                   '<br />'.$visactions->{'take'}.'<ul>'.
 9610:                   '<li>'.$visactions->{'dc_setcode'}.'</li>'.
 9611:                   '</ul><br />');
 9612:         }
 9613:     } else {
 9614:         my ($visible,$cansetvis,$vismsgs) = &visible_in_stdcat($cdom,$cnum,\%domconfig);
 9615:         if (ref($visactions) eq 'HASH') {
 9616:             if (!$visible) {
 9617:                 $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
 9618:                           '<br />');
 9619:                 if (ref($vismsgs) eq 'ARRAY') {
 9620:                     $r->print('<br />'.$visactions->{'take'}.'<ul>');
 9621:                     foreach my $item (@{$vismsgs}) {
 9622:                         $r->print('<li>'.$visactions->{$item}.'</li>');
 9623:                     }
 9624:                     $r->print('</ul>');
 9625:                 }
 9626:                 $r->print($cansetvis);
 9627:             }
 9628:         }
 9629:     } 
 9630:     return;
 9631: }
 9632: 
 9633: #---------------------------------------------- end functions for &phase_two
 9634: 
 9635: #--------------------------------- functions for &phase_two and &phase_three
 9636: 
 9637: #--------------------------end of functions for &phase_two and &phase_three
 9638: 
 9639: 1;
 9640: __END__
 9641: 
 9642: 

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