File:  [LON-CAPA] / loncom / interface / loncreateuser.pm
Revision 1.460: download - view: text, annotated - select for diffs
Tue Oct 18 23:28:00 2022 UTC (19 months, 1 week ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Hint to browsers to not autofill password fields.

    1: # The LearningOnline Network with CAPA
    2: # Create a user
    3: #
    4: # $Id: loncreateuser.pm,v 1.460 2022/10/18 23:28:00 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: my $authformlti;
   83: 
   84: sub initialize_authen_forms {
   85:     my ($dom,$formname,$curr_authtype,$mode) = @_;
   86:     my ($krbdef,$krbdefdom) = &Apache::loncommon::get_kerberos_defaults($dom);
   87:     my %param = ( formname => $formname,
   88:                   kerb_def_dom => $krbdefdom,
   89:                   kerb_def_auth => $krbdef,
   90:                   domain => $dom,
   91:                 );
   92:     my %abv_auth = &auth_abbrev();
   93:     if ($curr_authtype =~ /^(krb4|krb5|internal|localauth|unix|lti):(.*)$/) {
   94:         my $long_auth = $1;
   95:         my $curr_autharg = $2;
   96:         my %abv_auth = &auth_abbrev();
   97:         $param{'curr_authtype'} = $abv_auth{$long_auth};
   98:         if ($long_auth =~ /^krb(4|5)$/) {
   99:             $param{'curr_kerb_ver'} = $1;
  100:             $param{'curr_autharg'} = $curr_autharg;
  101:         }
  102:         if ($mode eq 'modifyuser') {
  103:             $param{'mode'} = $mode;
  104:         }
  105:     }
  106:     $loginscript  = &Apache::loncommon::authform_header(%param);
  107:     $authformkrb  = &Apache::loncommon::authform_kerberos(%param);
  108:     $authformnop  = &Apache::loncommon::authform_nochange(%param);
  109:     $authformint  = &Apache::loncommon::authform_internal(%param);
  110:     $authformfsys = &Apache::loncommon::authform_filesystem(%param);
  111:     $authformloc  = &Apache::loncommon::authform_local(%param);
  112:     $authformlti  = &Apache::loncommon::authform_lti(%param);
  113: }
  114: 
  115: sub auth_abbrev {
  116:     my %abv_auth = (
  117:                      krb5      => 'krb',
  118:                      krb4      => 'krb',
  119:                      internal  => 'int',
  120:                      localauth => 'loc',
  121:                      unix      => 'fsys',
  122:                      lti       => 'lti',
  123:                    );
  124:     return %abv_auth;
  125: }
  126: 
  127: # ====================================================
  128: 
  129: sub user_quotas {
  130:     my ($ccuname,$ccdomain) = @_;
  131:     my %lt = &Apache::lonlocal::texthash(
  132:                    'usrt'      => "User Tools",
  133:                    'cust'      => "Custom quota",
  134:                    'chqu'      => "Change quota",
  135:     );
  136:    
  137:     my $quota_javascript = <<"END_SCRIPT";
  138: <script type="text/javascript">
  139: // <![CDATA[
  140: function quota_changes(caller,context) {
  141:     var customoff = document.getElementById('custom_'+context+'quota_off');
  142:     var customon = document.getElementById('custom_'+context+'quota_on');
  143:     var number = document.getElementById(context+'quota');
  144:     if (caller == "custom") {
  145:         if (customoff) {
  146:             if (customoff.checked) {
  147:                 number.value = "";
  148:             }
  149:         }
  150:     }
  151:     if (caller == "quota") {
  152:         if (customon) {
  153:             customon.checked = true;
  154:         }
  155:     }
  156:     return;
  157: }
  158: // ]]>
  159: </script>
  160: END_SCRIPT
  161:     my $longinsttype;
  162:     my ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($ccdomain);
  163:     my $output = $quota_javascript."\n".
  164:                  '<h3>'.$lt{'usrt'}.'</h3>'."\n".
  165:                  &Apache::loncommon::start_data_table();
  166: 
  167:     if ((&Apache::lonnet::allowed('mut',$ccdomain)) ||
  168:         (&Apache::lonnet::allowed('udp',$ccdomain))) {
  169:         $output .= &build_tools_display($ccuname,$ccdomain,'tools');
  170:     }
  171: 
  172:     my %titles = &Apache::lonlocal::texthash (
  173:                     portfolio => "Disk space allocated to user's portfolio files",
  174:                     author    => "Disk space allocated to user's Authoring Space (if role assigned)",
  175:                  );
  176:     foreach my $name ('portfolio','author') {
  177:         my ($currquota,$quotatype,$inststatus,$defquota) =
  178:             &Apache::loncommon::get_user_quota($ccuname,$ccdomain,$name);
  179:         if ($longinsttype eq '') { 
  180:             if ($inststatus ne '') {
  181:                 if ($usertypes->{$inststatus} ne '') {
  182:                     $longinsttype = $usertypes->{$inststatus};
  183:                 }
  184:             }
  185:         }
  186:         my ($showquota,$custom_on,$custom_off,$defaultinfo);
  187:         $custom_on = ' ';
  188:         $custom_off = ' checked="checked" ';
  189:         if ($quotatype eq 'custom') {
  190:             $custom_on = $custom_off;
  191:             $custom_off = ' ';
  192:             $showquota = $currquota;
  193:             if ($longinsttype eq '') {
  194:                 $defaultinfo = &mt('For this user, the default quota would be [_1]'
  195:                               .' MB.',$defquota);
  196:             } else {
  197:                 $defaultinfo = &mt("For this user, the default quota would be [_1]".
  198:                                    " MB, as determined by the user's institutional".
  199:                                    " affiliation ([_2]).",$defquota,$longinsttype);
  200:             }
  201:         } else {
  202:             if ($longinsttype eq '') {
  203:                 $defaultinfo = &mt('For this user, the default quota is [_1]'
  204:                               .' MB.',$defquota);
  205:             } else {
  206:                 $defaultinfo = &mt("For this user, the default quota of [_1]".
  207:                                    " MB, is determined by the user's institutional".
  208:                                    " affiliation ([_2]).",$defquota,$longinsttype);
  209:             }
  210:         }
  211: 
  212:         if (&Apache::lonnet::allowed('mpq',$ccdomain)) {
  213:             $output .= '<tr class="LC_info_row">'."\n".
  214:                        '    <td>'.$titles{$name}.'</td>'."\n".
  215:                        '  </tr>'."\n".
  216:                        &Apache::loncommon::start_data_table_row()."\n".
  217:                        '  <td><span class="LC_nobreak">'.
  218:                        &mt('Current quota: [_1] MB',$currquota).'</span>&nbsp;&nbsp;'.
  219:                        $defaultinfo.'</td>'."\n".
  220:                        &Apache::loncommon::end_data_table_row()."\n".
  221:                        &Apache::loncommon::start_data_table_row()."\n".
  222:                        '  <td><span class="LC_nobreak">'.$lt{'chqu'}.
  223:                        ': <label>'.
  224:                        '<input type="radio" name="custom_'.$name.'quota" id="custom_'.$name.'quota_off" '.
  225:                        'value="0" '.$custom_off.' onchange="javascript:quota_changes('."'custom','$name'".');"'.
  226:                        ' /><span class="LC_nobreak">'.
  227:                        &mt('Default ([_1] MB)',$defquota).'</span></label>&nbsp;'.
  228:                        '&nbsp;<label><input type="radio" name="custom_'.$name.'quota" id="custom_'.$name.'quota_on" '.
  229:                        'value="1" '.$custom_on.'  onchange="javascript:quota_changes('."'custom','$name'".');"'.
  230:                        ' />'.$lt{'cust'}.':</label>&nbsp;'.
  231:                        '<input type="text" name="'.$name.'quota" id="'.$name.'quota" size ="5" '.
  232:                        'value="'.$showquota.'" onfocus="javascript:quota_changes('."'quota','$name'".');"'.
  233:                        ' />&nbsp;'.&mt('MB').'</span></td>'."\n".
  234:                        &Apache::loncommon::end_data_table_row()."\n";
  235:         }
  236:     }
  237:     $output .= &Apache::loncommon::end_data_table();
  238:     return $output;
  239: }
  240: 
  241: sub build_tools_display {
  242:     my ($ccuname,$ccdomain,$context) = @_;
  243:     my (@usertools,%userenv,$output,@options,%validations,%reqtitles,%reqdisplay,
  244:         $colspan,$isadv,%domconfig);
  245:     my %lt = &Apache::lonlocal::texthash (
  246:                    'blog'       => "Personal User Blog",
  247:                    'aboutme'    => "Personal Information Page",
  248:                    'webdav'     => "WebDAV access to Authoring Spaces (if SSL and author/co-author)",
  249:                    'portfolio'  => "Personal User Portfolio",
  250:                    'timezone'   => "Can set Time Zone",
  251:                    'avai'       => "Available",
  252:                    'cusa'       => "availability",
  253:                    'chse'       => "Change setting",
  254:                    'usde'       => "Use default",
  255:                    'uscu'       => "Use custom",
  256:                    'official'   => 'Can request creation of official courses',
  257:                    'unofficial' => 'Can request creation of unofficial courses',
  258:                    'community'  => 'Can request creation of communities',
  259:                    'textbook'   => 'Can request creation of textbook courses',
  260:                    'placement'  => 'Can request creation of placement tests',
  261:                    'lti'        => 'Can request creation of LTI courses',
  262:                    'requestauthor'  => 'Can request author space',
  263:     );
  264:     if ($context eq 'requestcourses') {
  265:         %userenv = &Apache::lonnet::userenvironment($ccdomain,$ccuname,
  266:                       'requestcourses.official','requestcourses.unofficial',
  267:                       'requestcourses.community','requestcourses.textbook',
  268:                       'requestcourses.placement','requestcourses.lti');
  269:         @usertools = ('official','unofficial','community','textbook','placement','lti');
  270:         @options =('norequest','approval','autolimit','validate');
  271:         %validations = &Apache::lonnet::auto_courserequest_checks($ccdomain);
  272:         %reqtitles = &courserequest_titles();
  273:         %reqdisplay = &courserequest_display();
  274:         $colspan = ' colspan="2"';
  275:         %domconfig =
  276:             &Apache::lonnet::get_dom('configuration',['requestcourses'],$ccdomain);
  277:         $isadv = &Apache::lonnet::is_advanced_user($ccdomain,$ccuname);
  278:     } elsif ($context eq 'requestauthor') {
  279:         %userenv = &Apache::lonnet::userenvironment($ccdomain,$ccuname,
  280:                                                     'requestauthor');
  281:         @usertools = ('requestauthor');
  282:         @options =('norequest','approval','automatic');
  283:         %reqtitles = &requestauthor_titles();
  284:         %reqdisplay = &requestauthor_display();
  285:         $colspan = ' colspan="2"';
  286:         %domconfig =
  287:             &Apache::lonnet::get_dom('configuration',['requestauthor'],$ccdomain);
  288:     } else {
  289:         %userenv = &Apache::lonnet::userenvironment($ccdomain,$ccuname,
  290:                           'tools.aboutme','tools.portfolio','tools.blog',
  291:                           'tools.webdav','tools.timezone');
  292:         @usertools = ('aboutme','blog','webdav','portfolio','timezone');
  293:     }
  294:     foreach my $item (@usertools) {
  295:         my ($custom_access,$curr_access,$cust_on,$cust_off,$tool_on,$tool_off,
  296:             $currdisp,$custdisp,$custradio);
  297:         $cust_off = 'checked="checked" ';
  298:         $tool_on = 'checked="checked" ';
  299:         $curr_access =  
  300:             &Apache::lonnet::usertools_access($ccuname,$ccdomain,$item,undef,
  301:                                               $context);
  302:         if ($context eq 'requestauthor') {
  303:             if ($userenv{$context} ne '') {
  304:                 $cust_on = ' checked="checked" ';
  305:                 $cust_off = '';
  306:             }  
  307:         } elsif ($userenv{$context.'.'.$item} ne '') {
  308:             $cust_on = ' checked="checked" ';
  309:             $cust_off = '';
  310:         }
  311:         if ($context eq 'requestcourses') {
  312:             if ($userenv{$context.'.'.$item} eq '') {
  313:                 $custom_access = &mt('Currently from default setting.');
  314:             } else {
  315:                 $custom_access = &mt('Currently from custom setting.');
  316:             }
  317:         } elsif ($context eq 'requestauthor') {
  318:             if ($userenv{$context} eq '') {
  319:                 $custom_access = &mt('Currently from default setting.');
  320:             } else {
  321:                 $custom_access = &mt('Currently from custom setting.');
  322:             }
  323:         } else {
  324:             if ($userenv{$context.'.'.$item} eq '') {
  325:                 $custom_access =
  326:                     &mt('Availability determined currently from default setting.');
  327:                 if (!$curr_access) {
  328:                     $tool_off = 'checked="checked" ';
  329:                     $tool_on = '';
  330:                 }
  331:             } else {
  332:                 $custom_access =
  333:                     &mt('Availability determined currently from custom setting.');
  334:                 if ($userenv{$context.'.'.$item} == 0) {
  335:                     $tool_off = 'checked="checked" ';
  336:                     $tool_on = '';
  337:                 }
  338:             }
  339:         }
  340:         $output .= '  <tr class="LC_info_row">'."\n".
  341:                    '   <td'.$colspan.'>'.$lt{$item}.'</td>'."\n".
  342:                    '  </tr>'."\n".
  343:                    &Apache::loncommon::start_data_table_row()."\n";
  344:   
  345:         if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
  346:             my ($curroption,$currlimit);
  347:             my $envkey = $context.'.'.$item;
  348:             if ($context eq 'requestauthor') {
  349:                 $envkey = $context;
  350:             }
  351:             if ($userenv{$envkey} ne '') {
  352:                 $curroption = $userenv{$envkey};
  353:             } else {
  354:                 my (@inststatuses);
  355:                 if ($context eq 'requestcourses') {
  356:                     $curroption =
  357:                         &Apache::loncoursequeueadmin::get_processtype('course',$ccuname,$ccdomain,
  358:                                                                       $isadv,$ccdomain,$item,
  359:                                                                       \@inststatuses,\%domconfig);
  360:                 } else {
  361:                      $curroption = 
  362:                          &Apache::loncoursequeueadmin::get_processtype('requestauthor',$ccuname,$ccdomain,
  363:                                                                        $isadv,$ccdomain,undef,
  364:                                                                        \@inststatuses,\%domconfig);
  365:                 }
  366:             }
  367:             if (!$curroption) {
  368:                 $curroption = 'norequest';
  369:             }
  370:             if ($curroption =~ /^autolimit=(\d*)$/) {
  371:                 $currlimit = $1;
  372:                 if ($currlimit eq '') {
  373:                     $currdisp = &mt('Yes, automatic creation');
  374:                 } else {
  375:                     $currdisp = &mt('Yes, up to [quant,_1,request]/user',$currlimit);
  376:                 }
  377:             } else {
  378:                 $currdisp = $reqdisplay{$curroption};
  379:             }
  380:             $custdisp = '<table>';
  381:             foreach my $option (@options) {
  382:                 my $val = $option;
  383:                 if ($option eq 'norequest') {
  384:                     $val = 0;
  385:                 }
  386:                 if ($option eq 'validate') {
  387:                     my $canvalidate = 0;
  388:                     if (ref($validations{$item}) eq 'HASH') {
  389:                         if ($validations{$item}{'_custom_'}) {
  390:                             $canvalidate = 1;
  391:                         }
  392:                     }
  393:                     next if (!$canvalidate);
  394:                 }
  395:                 my $checked = '';
  396:                 if ($option eq $curroption) {
  397:                     $checked = ' checked="checked"';
  398:                 } elsif ($option eq 'autolimit') {
  399:                     if ($curroption =~ /^autolimit/) {
  400:                         $checked = ' checked="checked"';
  401:                     }
  402:                 }
  403:                 my $name = 'crsreq_'.$item;
  404:                 if ($context eq 'requestauthor') {
  405:                     $name = $item;
  406:                 }
  407:                 $custdisp .= '<tr><td><span class="LC_nobreak"><label>'.
  408:                              '<input type="radio" name="'.$name.'" '.
  409:                              'value="'.$val.'"'.$checked.' />'.
  410:                              $reqtitles{$option}.'</label>&nbsp;';
  411:                 if ($option eq 'autolimit') {
  412:                     $custdisp .= '<input type="text" name="'.$name.
  413:                                  '_limit" size="1" '.
  414:                                  'value="'.$currlimit.'" /></span><br />'.
  415:                                  $reqtitles{'unlimited'};
  416:                 } else {
  417:                     $custdisp .= '</span>';
  418:                 }
  419:                 $custdisp .= '</td></tr>';
  420:             }
  421:             $custdisp .= '</table>';
  422:             $custradio = '</span></td><td>'.&mt('Custom setting').'<br />'.$custdisp;
  423:         } else {
  424:             $currdisp = ($curr_access?&mt('Yes'):&mt('No'));
  425:             my $name = $context.'_'.$item;
  426:             if ($context eq 'requestauthor') {
  427:                 $name = $context;
  428:             }
  429:             $custdisp = '<span class="LC_nobreak"><label>'.
  430:                         '<input type="radio" name="'.$name.'"'.
  431:                         ' value="1" '.$tool_on.'/>'.&mt('On').'</label>&nbsp;<label>'.
  432:                         '<input type="radio" name="'.$name.'" value="0" '.
  433:                         $tool_off.'/>'.&mt('Off').'</label></span>';
  434:             $custradio = ('&nbsp;'x2).'--'.$lt{'cusa'}.':&nbsp;'.$custdisp.
  435:                           '</span>';
  436:         }
  437:         $output .= '  <td'.$colspan.'>'.$custom_access.('&nbsp;'x4).
  438:                    $lt{'avai'}.': '.$currdisp.'</td>'."\n".
  439:                    &Apache::loncommon::end_data_table_row()."\n";
  440:         unless (&Apache::lonnet::allowed('udp',$ccdomain)) {
  441:             $output .=
  442:                    &Apache::loncommon::start_data_table_row()."\n".
  443:                    '  <td style="vertical-align:top;"><span class="LC_nobreak">'.
  444:                    $lt{'chse'}.': <label>'.
  445:                    '<input type="radio" name="custom'.$item.'" value="0" '.
  446:                    $cust_off.'/>'.$lt{'usde'}.'</label>'.('&nbsp;' x3).
  447:                    '<label><input type="radio" name="custom'.$item.'" value="1" '.
  448:                    $cust_on.'/>'.$lt{'uscu'}.'</label>'.$custradio.'</td>'.
  449:                    &Apache::loncommon::end_data_table_row()."\n";
  450:         }
  451:     }
  452:     return $output;
  453: }
  454: 
  455: sub coursereq_externaluser {
  456:     my ($ccuname,$ccdomain,$cdom) = @_;
  457:     my (@usertools,@options,%validations,%userenv,$output);
  458:     my %lt = &Apache::lonlocal::texthash (
  459:                    'official'   => 'Can request creation of official courses',
  460:                    'unofficial' => 'Can request creation of unofficial courses',
  461:                    'community'  => 'Can request creation of communities',
  462:                    'textbook'   => 'Can request creation of textbook courses',
  463:                    'placement'  => 'Can request creation of placement tests',
  464:     );
  465: 
  466:     %userenv = &Apache::lonnet::userenvironment($ccdomain,$ccuname,
  467:                       'reqcrsotherdom.official','reqcrsotherdom.unofficial',
  468:                       'reqcrsotherdom.community','reqcrsotherdom.textbook',
  469:                       'reqcrsotherdom.placement');
  470:     @usertools = ('official','unofficial','community','textbook','placement');
  471:     @options = ('approval','validate','autolimit');
  472:     %validations = &Apache::lonnet::auto_courserequest_checks($cdom);
  473:     my $optregex = join('|',@options);
  474:     my %reqtitles = &courserequest_titles();
  475:     foreach my $item (@usertools) {
  476:         my ($curroption,$currlimit,$tooloff);
  477:         if ($userenv{'reqcrsotherdom.'.$item} ne '') {
  478:             my @curr = split(',',$userenv{'reqcrsotherdom.'.$item});
  479:             foreach my $req (@curr) {
  480:                 if ($req =~ /^\Q$cdom\E\:($optregex)=?(\d*)$/) {
  481:                     $curroption = $1;
  482:                     $currlimit = $2;
  483:                     last;
  484:                 }
  485:             }
  486:             if (!$curroption) {
  487:                 $curroption = 'norequest';
  488:                 $tooloff = ' checked="checked"';
  489:             }
  490:         } else {
  491:             $curroption = 'norequest';
  492:             $tooloff = ' checked="checked"';
  493:         }
  494:         $output.= &Apache::loncommon::start_data_table_row()."\n".
  495:                   '  <td><span class="LC_nobreak">'.$lt{$item}.': </span></td><td>'.
  496:                   '<table><tr><td valign="top">'."\n".
  497:                   '<label><input type="radio" name="reqcrsotherdom_'.$item.
  498:                   '" value=""'.$tooloff.' />'.$reqtitles{'norequest'}.
  499:                   '</label></td>';
  500:         foreach my $option (@options) {
  501:             if ($option eq 'validate') {
  502:                 my $canvalidate = 0;
  503:                 if (ref($validations{$item}) eq 'HASH') {
  504:                     if ($validations{$item}{'_external_'}) {
  505:                         $canvalidate = 1;
  506:                     }
  507:                 }
  508:                 next if (!$canvalidate);
  509:             }
  510:             my $checked = '';
  511:             if ($option eq $curroption) {
  512:                 $checked = ' checked="checked"';
  513:             }
  514:             $output .= '<td valign="top"><span class="LC_nobreak"><label>'.
  515:                        '<input type="radio" name="reqcrsotherdom_'.$item.
  516:                        '" value="'.$option.'"'.$checked.' />'.
  517:                        $reqtitles{$option}.'</label>';
  518:             if ($option eq 'autolimit') {
  519:                 $output .= '&nbsp;<input type="text" name="reqcrsotherdom_'.
  520:                            $item.'_limit" size="1" '.
  521:                            'value="'.$currlimit.'" /></span>'.
  522:                            '<br />'.$reqtitles{'unlimited'};
  523:             } else {
  524:                 $output .= '</span>';
  525:             }
  526:             $output .= '</td>';
  527:         }
  528:         $output .= '</td></tr></table></td>'."\n".
  529:                    &Apache::loncommon::end_data_table_row()."\n";
  530:     }
  531:     return $output;
  532: }
  533: 
  534: sub domainrole_req {
  535:     my ($ccuname,$ccdomain) = @_;
  536:     return '<br /><h3>'.
  537:            &mt('User Can Request Assignment of Domain Roles?').
  538:            '</h3>'."\n".
  539:            &Apache::loncommon::start_data_table().
  540:            &build_tools_display($ccuname,$ccdomain,
  541:                                 'requestauthor').
  542:            &Apache::loncommon::end_data_table();
  543: }
  544: 
  545: sub courserequest_titles {
  546:     my %titles = &Apache::lonlocal::texthash (
  547:                                    official   => 'Official',
  548:                                    unofficial => 'Unofficial',
  549:                                    community  => 'Communities',
  550:                                    textbook   => 'Textbook',
  551:                                    placement  => 'Placement Tests',
  552:                                    lti        => 'LTI Provider',
  553:                                    norequest  => 'Not allowed',
  554:                                    approval   => 'Approval by Dom. Coord.',
  555:                                    validate   => 'With validation',
  556:                                    autolimit  => 'Numerical limit',
  557:                                    unlimited  => '(blank for unlimited)',
  558:                  );
  559:     return %titles;
  560: }
  561: 
  562: sub courserequest_display {
  563:     my %titles = &Apache::lonlocal::texthash (
  564:                                    approval   => 'Yes, need approval',
  565:                                    validate   => 'Yes, with validation',
  566:                                    norequest  => 'No',
  567:    );
  568:    return %titles;
  569: }
  570: 
  571: sub requestauthor_titles {
  572:     my %titles = &Apache::lonlocal::texthash (
  573:                                    norequest  => 'Not allowed',
  574:                                    approval   => 'Approval by Dom. Coord.',
  575:                                    automatic  => 'Automatic approval',
  576:                  );
  577:     return %titles;
  578: 
  579: }
  580: 
  581: sub requestauthor_display {
  582:     my %titles = &Apache::lonlocal::texthash (
  583:                                    approval   => 'Yes, need approval',
  584:                                    automatic  => 'Yes, automatic approval',
  585:                                    norequest  => 'No',
  586:    );
  587:    return %titles;
  588: }
  589: 
  590: sub requestchange_display {
  591:     my %titles = &Apache::lonlocal::texthash (
  592:                                    approval   => "availability set to 'on' (approval required)", 
  593:                                    automatic  => "availability set to 'on' (automatic approval)",
  594:                                    norequest  => "availability set to 'off'",
  595:    );
  596:    return %titles;
  597: }
  598: 
  599: sub curr_requestauthor {
  600:     my ($uname,$udom,$isadv,$inststatuses,$domconfig) = @_;
  601:     return unless ((ref($inststatuses) eq 'ARRAY') && (ref($domconfig) eq 'HASH'));
  602:     if ($uname eq '' || $udom eq '') {
  603:         $uname = $env{'user.name'};
  604:         $udom = $env{'user.domain'};
  605:         $isadv = $env{'user.adv'};
  606:     }
  607:     my (%userenv,%settings,$val);
  608:     my @options = ('automatic','approval');
  609:     %userenv =
  610:         &Apache::lonnet::userenvironment($udom,$uname,'requestauthor','inststatus');
  611:     if ($userenv{'requestauthor'}) {
  612:         $val = $userenv{'requestauthor'};
  613:         @{$inststatuses} = ('_custom_');
  614:     } else {
  615:         my %alltasks;
  616:         if (ref($domconfig->{'requestauthor'}) eq 'HASH') {
  617:             %settings = %{$domconfig->{'requestauthor'}};
  618:             if (($isadv) && ($settings{'_LC_adv'} ne '')) {
  619:                 $val = $settings{'_LC_adv'};
  620:                 @{$inststatuses} = ('_LC_adv_');
  621:             } else {
  622:                 if ($userenv{'inststatus'} ne '') {
  623:                     @{$inststatuses} = split(',',$userenv{'inststatus'});
  624:                 } else {
  625:                     @{$inststatuses} = ('default');
  626:                 }
  627:                 foreach my $status (@{$inststatuses}) {
  628:                     if (exists($settings{$status})) {
  629:                         my $value = $settings{$status};
  630:                         next unless ($value);
  631:                         unless (exists($alltasks{$value})) {
  632:                             if (ref($alltasks{$value}) eq 'ARRAY') {
  633:                                 unless(grep(/^\Q$status\E$/,@{$alltasks{$value}})) {
  634:                                     push(@{$alltasks{$value}},$status);
  635:                                 }
  636:                             } else {
  637:                                 @{$alltasks{$value}} = ($status);
  638:                             }
  639:                         }
  640:                     }
  641:                 }
  642:                 foreach my $option (@options) {
  643:                     if ($alltasks{$option}) {
  644:                         $val = $option;
  645:                         last;
  646:                     }
  647:                 }
  648:             }
  649:         }
  650:     }
  651:     return $val;
  652: }
  653: 
  654: # =================================================================== Phase one
  655: 
  656: sub print_username_entry_form {
  657:     my ($r,$context,$response,$srch,$forcenewuser,$crstype,$brcrum,
  658:         $permission) = @_;
  659:     my $defdom=$env{'request.role.domain'};
  660:     my $formtoset = 'crtuser';
  661:     if (exists($env{'form.startrolename'})) {
  662:         $formtoset = 'docustom';
  663:         $env{'form.rolename'} = $env{'form.startrolename'};
  664:     } elsif ($env{'form.origform'} eq 'crtusername') {
  665:         $formtoset =  $env{'form.origform'};
  666:     }
  667: 
  668:     my ($jsback,$elements) = &crumb_utilities();
  669: 
  670:     my $jscript = &Apache::loncommon::studentbrowser_javascript()."\n".
  671:         '<script type="text/javascript">'."\n".
  672:         '// <![CDATA['."\n".
  673:         &Apache::lonhtmlcommon::set_form_elements($elements->{$formtoset})."\n".
  674:         '// ]]>'."\n".
  675:         '</script>'."\n";
  676: 
  677:     my %existingroles=&Apache::lonuserutils::my_custom_roles($crstype);
  678:     if (($env{'form.action'} eq 'custom') && (keys(%existingroles) > 0)
  679:         && (&Apache::lonnet::allowed('mcr','/'))) {
  680:         $jscript .= &customrole_javascript();
  681:     }
  682:     my $helpitem = 'Course_Change_Privileges';
  683:     if ($env{'form.action'} eq 'custom') {
  684:         if ($context eq 'course') {
  685:             $helpitem = 'Course_Editing_Custom_Roles';
  686:         } elsif ($context eq 'domain') {
  687:             $helpitem = 'Domain_Editing_Custom_Roles';
  688:         }
  689:     } elsif ($env{'form.action'} eq 'singlestudent') {
  690:         $helpitem = 'Course_Add_Student';
  691:     } elsif ($env{'form.action'} eq 'accesslogs') {
  692:         $helpitem = 'Domain_User_Access_Logs';
  693:     } elsif ($context eq 'author') {
  694:         $helpitem = 'Author_Change_Privileges';
  695:     } elsif ($context eq 'domain') {
  696:         if ($permission->{'cusr'}) {
  697:             $helpitem = 'Domain_Change_Privileges';
  698:         } elsif ($permission->{'view'}) {
  699:             $helpitem = 'Domain_View_Privileges';
  700:         } else {
  701:             undef($helpitem);
  702:         }
  703:     }
  704:     my %breadcrumb_text = &singleuser_breadcrumb($crstype,$context,$defdom);
  705:     if ($env{'form.action'} eq 'custom') {
  706:         push(@{$brcrum},
  707:                  {href=>"javascript:backPage(document.crtuser)",       
  708:                   text=>"Pick custom role",
  709:                   help => $helpitem,}
  710:                  );
  711:     } else {
  712:         push (@{$brcrum},
  713:                   {href => "javascript:backPage(document.crtuser)",
  714:                    text => $breadcrumb_text{'search'},
  715:                    help => $helpitem,
  716:                    faq  => 282,
  717:                    bug  => 'Instructor Interface',}
  718:                   );
  719:     }
  720:     my %loaditems = (
  721:                 'onload' => "javascript:setFormElements(document.$formtoset)",
  722:                     );
  723:     my $args = {bread_crumbs           => $brcrum,
  724:                 bread_crumbs_component => 'User Management',
  725:                 add_entries            => \%loaditems,};
  726:     $r->print(&Apache::loncommon::start_page('User Management',$jscript,$args));
  727: 
  728:     my %lt=&Apache::lonlocal::texthash(
  729:                     'srst' => 'Search for a user and enroll as a student',
  730:                     'srme' => 'Search for a user and enroll as a member',
  731:                     'srad' => 'Search for a user and modify/add user information or roles',
  732:                     'srvu' => 'Search for a user and view user information and roles',
  733:                     'srva' => 'Search for a user and view access log information',
  734: 		    'usr'  => "Username",
  735:                     'dom'  => "Domain",
  736:                     'ecrp' => "Define or Edit Custom Role",
  737:                     'nr'   => "role name",
  738:                     'cre'  => "Next",
  739: 				       );
  740: 
  741:     if ($env{'form.action'} eq 'custom') {
  742:         if (&Apache::lonnet::allowed('mcr','/')) {
  743:             my $newroletext = &mt('Define new custom role:');
  744:             $r->print('<form action="/adm/createuser" method="post" name="docustom">'.
  745:                       '<input type="hidden" name="action" value="'.$env{'form.action'}.'" />'.
  746:                       '<input type="hidden" name="phase" value="selected_custom_edit" />'.
  747:                       '<h3>'.$lt{'ecrp'}.'</h3>'.
  748:                       &Apache::loncommon::start_data_table().
  749:                       &Apache::loncommon::start_data_table_row().
  750:                       '<td>');
  751:             if (keys(%existingroles) > 0) {
  752:                 $r->print('<br /><label><input type="radio" name="customroleaction" value="new" checked="checked" onclick="setCustomFields();" /><b>'.$newroletext.'</b></label>');
  753:             } else {
  754:                 $r->print('<br /><input type="hidden" name="customroleaction" value="new" /><b>'.$newroletext.'</b>');
  755:             }
  756:             $r->print('</td><td align="center">'.$lt{'nr'}.'<br /><input type="text" size="15" name="newrolename" onfocus="setCustomAction('."'new'".');" /></td>'.
  757:                       &Apache::loncommon::end_data_table_row());
  758:             if (keys(%existingroles) > 0) {
  759:                 $r->print(&Apache::loncommon::start_data_table_row().'<td><br />'.
  760:                           '<label><input type="radio" name="customroleaction" value="edit" onclick="setCustomFields();"/><b>'.
  761:                           &mt('View/Modify existing role:').'</b></label></td>'.
  762:                           '<td align="center"><br />'.
  763:                           '<select name="rolename" onchange="setCustomAction('."'edit'".');">'.
  764:                           '<option value="" selected="selected">'.
  765:                           &mt('Select'));
  766:                 foreach my $role (sort(keys(%existingroles))) {
  767:                     $r->print('<option value="'.$role.'">'.$role.'</option>');
  768:                 }
  769:                 $r->print('</select>'.
  770:                           '</td>'.
  771:                           &Apache::loncommon::end_data_table_row());
  772:             }
  773:             $r->print(&Apache::loncommon::end_data_table().'<p>'.
  774:                       '<input name="customeditor" type="submit" value="'.
  775:                       $lt{'cre'}.'" /></p>'.
  776:                       '</form>');
  777:         }
  778:     } else {
  779:         my $actiontext = $lt{'srad'};
  780:         my $fixeddom;
  781:         if ($env{'form.action'} eq 'singlestudent') {
  782:             if ($crstype eq 'Community') {
  783:                 $actiontext = $lt{'srme'};
  784:             } else {
  785:                 $actiontext = $lt{'srst'};
  786:             }
  787:         } elsif ($env{'form.action'} eq 'accesslogs') {
  788:             $actiontext = $lt{'srva'};
  789:             $fixeddom = 1;
  790:         } elsif (($env{'form.action'} eq 'singleuser') &&
  791:                  ($context eq 'domain') && (!&Apache::lonnet::allowed('mau',$defdom))) {
  792:             $actiontext = $lt{'srvu'};
  793:             $fixeddom = 1;
  794:         }
  795:         $r->print("<h3>$actiontext</h3>");
  796:         if ($env{'form.origform'} ne 'crtusername') {
  797:             if ($response) {
  798:                $r->print("\n<div>$response</div>".
  799:                          '<br clear="all" />');
  800:             }
  801:         }
  802:         $r->print(&entry_form($defdom,$srch,$forcenewuser,$context,$response,$crstype,$fixeddom));
  803:     }
  804: }
  805: 
  806: sub customrole_javascript {
  807:     my $js = <<"END";
  808: <script type="text/javascript">
  809: // <![CDATA[
  810: 
  811: function setCustomFields() {
  812:     if (document.docustom.customroleaction.length > 0) {
  813:         for (var i=0; i<document.docustom.customroleaction.length; i++) {
  814:             if (document.docustom.customroleaction[i].checked) {
  815:                 if (document.docustom.customroleaction[i].value == 'new') {
  816:                     document.docustom.rolename.selectedIndex = 0;
  817:                 } else {
  818:                     document.docustom.newrolename.value = '';
  819:                 }
  820:             }
  821:         }
  822:     }
  823:     return;
  824: }
  825: 
  826: function setCustomAction(caller) {
  827:     if (document.docustom.customroleaction.length > 0) {
  828:         for (var i=0; i<document.docustom.customroleaction.length; i++) {
  829:             if (document.docustom.customroleaction[i].value == caller) {
  830:                 document.docustom.customroleaction[i].checked = true;
  831:             }
  832:         }
  833:     }
  834:     setCustomFields();
  835:     return;
  836: }
  837: 
  838: // ]]>
  839: </script>
  840: END
  841:     return $js;
  842: }
  843: 
  844: sub entry_form {
  845:     my ($dom,$srch,$forcenewuser,$context,$responsemsg,$crstype,$fixeddom) = @_;
  846:     my ($usertype,$inexact);
  847:     if (ref($srch) eq 'HASH') {
  848:         if (($srch->{'srchin'} eq 'dom') &&
  849:             ($srch->{'srchby'} eq 'uname') &&
  850:             ($srch->{'srchtype'} eq 'exact') &&
  851:             ($srch->{'srchdomain'} ne '') &&
  852:             ($srch->{'srchterm'} ne '')) {
  853:             my (%curr_rules,%got_rules);
  854:             my ($rules,$ruleorder) =
  855:                 &Apache::lonnet::inst_userrules($srch->{'srchdomain'},'username');
  856:             $usertype = &Apache::lonuserutils::check_usertype($srch->{'srchdomain'},$srch->{'srchterm'},$rules,\%curr_rules,\%got_rules);
  857:         } else {
  858:             $inexact = 1;
  859:         }
  860:     }
  861:     my ($cancreate,$noinstd);
  862:     if ($env{'form.action'} eq 'accesslogs') {
  863:         $noinstd = 1;
  864:     } else {
  865:         $cancreate =
  866:             &Apache::lonuserutils::can_create_user($dom,$context,$usertype);
  867:     }
  868:     my ($userpicker,$cansearch) = 
  869:        &Apache::loncommon::user_picker($dom,$srch,$forcenewuser,
  870:                                        'document.crtuser',$cancreate,$usertype,$context,$fixeddom,$noinstd);
  871:     my $srchbutton = &mt('Search');
  872:     if ($env{'form.action'} eq 'singlestudent') {
  873:         $srchbutton = &mt('Search and Enroll');
  874:     } elsif ($env{'form.action'} eq 'accesslogs') {
  875:         $srchbutton = &mt('Search');
  876:     } elsif ($cancreate && $responsemsg ne '' && $inexact) {
  877:         $srchbutton = &mt('Search or Add New User');
  878:     }
  879:     my $output;
  880:     if ($cansearch) {
  881:         $output = <<"ENDBLOCK";
  882: <form action="/adm/createuser" method="post" name="crtuser">
  883: <input type="hidden" name="action" value="$env{'form.action'}" />
  884: <input type="hidden" name="phase" value="get_user_info" />
  885: $userpicker
  886: <input name="userrole" type="button" value="$srchbutton" onclick="javascript:validateEntry(document.crtuser)" />
  887: </form>
  888: ENDBLOCK
  889:     } else {
  890:         $output = '<p>'.$userpicker.'</p>';
  891:     }
  892:     if (($env{'form.phase'} eq '') && ($env{'form.action'} ne 'accesslogs') &&
  893:         (!(($env{'form.action'} eq 'singleuser') && ($context eq 'domain') &&
  894:         (!&Apache::lonnet::allowed('mau',$env{'request.role.domain'}))))) {
  895:         my $defdom=$env{'request.role.domain'};
  896:         my ($trusted,$untrusted);
  897:         if ($context eq 'course') {
  898:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('enroll',$defdom);
  899:         } elsif ($context eq 'author') {
  900:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('othcoau',$defdom);
  901:         } elsif ($context eq 'domain') {
  902:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('domroles',$defdom); 
  903:         }
  904:         my $domform = &Apache::loncommon::select_dom_form($defdom,'srchdomain',undef,undef,undef,$trusted,$untrusted);
  905:         my %lt=&Apache::lonlocal::texthash(
  906:                   'enro' => 'Enroll one student',
  907:                   'enrm' => 'Enroll one member',
  908:                   'admo' => 'Add/modify a single user',
  909:                   'crea' => 'create new user if required',
  910:                   'uskn' => "username is known",
  911:                   'crnu' => 'Create a new user',
  912:                   'usr'  => 'Username',
  913:                   'dom'  => 'in domain',
  914:                   'enrl' => 'Enroll',
  915:                   'cram'  => 'Create/Modify user',
  916:         );
  917:         my $sellink=&Apache::loncommon::selectstudent_link('crtusername','srchterm','srchdomain');
  918:         my ($title,$buttontext,$showresponse);
  919:         if ($env{'form.action'} eq 'singlestudent') {
  920:             if ($crstype eq 'Community') {
  921:                 $title = $lt{'enrm'};
  922:             } else {
  923:                 $title = $lt{'enro'};
  924:             }
  925:             $buttontext = $lt{'enrl'};
  926:         } else {
  927:             $title = $lt{'admo'};
  928:             $buttontext = $lt{'cram'};
  929:         }
  930:         if ($cancreate) {
  931:             $title .= ' <span class="LC_cusr_subheading">('.$lt{'crea'}.')</span>';
  932:         } else {
  933:             $title .= ' <span class="LC_cusr_subheading">('.$lt{'uskn'}.')</span>';
  934:         }
  935:         if ($env{'form.origform'} eq 'crtusername') {
  936:             $showresponse = $responsemsg;
  937:         }
  938:         $output .= <<"ENDDOCUMENT";
  939: <br />
  940: <form action="/adm/createuser" method="post" name="crtusername">
  941: <input type="hidden" name="action" value="$env{'form.action'}" />
  942: <input type="hidden" name="phase" value="createnewuser" />
  943: <input type="hidden" name="srchtype" value="exact" />
  944: <input type="hidden" name="srchby" value="uname" />
  945: <input type="hidden" name="srchin" value="dom" />
  946: <input type="hidden" name="forcenewuser" value="1" />
  947: <input type="hidden" name="origform" value="crtusername" />
  948: <h3>$title</h3>
  949: $showresponse
  950: <table>
  951:  <tr>
  952:   <td>$lt{'usr'}:</td>
  953:   <td><input type="text" size="15" name="srchterm" /></td>
  954:   <td>&nbsp;$lt{'dom'}:</td><td>$domform</td>
  955:   <td>&nbsp;$sellink&nbsp;</td>
  956:   <td>&nbsp;<input name="userrole" type="submit" value="$buttontext" /></td>
  957:  </tr>
  958: </table>
  959: </form>
  960: ENDDOCUMENT
  961:     }
  962:     return $output;
  963: }
  964: 
  965: sub user_modification_js {
  966:     my ($pjump_def,$dc_setcourse_code,$nondc_setsection_code,$groupslist)=@_;
  967:     
  968:     return <<END;
  969: <script type="text/javascript" language="Javascript">
  970: // <![CDATA[
  971: 
  972:     $pjump_def
  973:     $dc_setcourse_code
  974: 
  975:     function dateset() {
  976:         eval("document.cu."+document.cu.pres_marker.value+
  977:             ".value=document.cu.pres_value.value");
  978:         modalWindow.close();
  979:     }
  980: 
  981:     $nondc_setsection_code
  982: // ]]>
  983: </script>
  984: END
  985: }
  986: 
  987: # =================================================================== Phase two
  988: sub print_user_selection_page {
  989:     my ($r,$response,$srch,$srch_results,$srcharray,$context,$opener_elements,$crstype,$brcrum) = @_;
  990:     my @fields = ('username','domain','lastname','firstname','permanentemail');
  991:     my $sortby = $env{'form.sortby'};
  992: 
  993:     if (!grep(/^\Q$sortby\E$/,@fields)) {
  994:         $sortby = 'lastname';
  995:     }
  996: 
  997:     my ($jsback,$elements) = &crumb_utilities();
  998: 
  999:     my $jscript = (<<ENDSCRIPT);
 1000: <script type="text/javascript">
 1001: // <![CDATA[
 1002: function pickuser(uname,udom) {
 1003:     document.usersrchform.seluname.value=uname;
 1004:     document.usersrchform.seludom.value=udom;
 1005:     document.usersrchform.phase.value="userpicked";
 1006:     document.usersrchform.submit();
 1007: }
 1008: 
 1009: $jsback
 1010: // ]]>
 1011: </script>
 1012: ENDSCRIPT
 1013: 
 1014:     my %lt=&Apache::lonlocal::texthash(
 1015:                                        'usrch'          => "User Search to add/modify roles",
 1016:                                        'stusrch'        => "User Search to enroll student",
 1017:                                        'memsrch'        => "User Search to enroll member",
 1018:                                        'srcva'          => "Search for a user and view access log information",
 1019:                                        'usrvu'          => "User Search to view user roles",
 1020:                                        'usel'           => "Select a user to add/modify roles",
 1021:                                        'suvr'           => "Select a user to view roles",
 1022:                                        'stusel'         => "Select a user to enroll as a student",
 1023:                                        'memsel'         => "Select a user to enroll as a member",
 1024:                                        'vacsel'         => "Select a user to view access log",
 1025:                                        'username'       => "username",
 1026:                                        'domain'         => "domain",
 1027:                                        'lastname'       => "last name",
 1028:                                        'firstname'      => "first name",
 1029:                                        'permanentemail' => "permanent e-mail",
 1030:                                       );
 1031:     if ($context eq 'requestcrs') {
 1032:         $r->print('<div>');
 1033:     } else {
 1034:         my %breadcrumb_text = &singleuser_breadcrumb($crstype,$context,$srch->{'srchdomain'});
 1035:         my $helpitem;
 1036:         if ($env{'form.action'} eq 'singleuser') {
 1037:             $helpitem = 'Course_Change_Privileges';
 1038:         } elsif ($env{'form.action'} eq 'singlestudent') {
 1039:             $helpitem = 'Course_Add_Student';
 1040:         } elsif ($context eq 'author') {
 1041:             $helpitem = 'Author_Change_Privileges';
 1042:         } elsif ($context eq 'domain') {
 1043:             $helpitem = 'Domain_Change_Privileges';
 1044:         }
 1045:         push (@{$brcrum},
 1046:                   {href => "javascript:backPage(document.usersrchform,'','')",
 1047:                    text => $breadcrumb_text{'search'},
 1048:                    faq  => 282,
 1049:                    bug  => 'Instructor Interface',},
 1050:                   {href => "javascript:backPage(document.usersrchform,'get_user_info','select')",
 1051:                    text => $breadcrumb_text{'userpicked'},
 1052:                    faq  => 282,
 1053:                    bug  => 'Instructor Interface',
 1054:                    help => $helpitem}
 1055:                   );
 1056:         $r->print(&Apache::loncommon::start_page('User Management',$jscript,{bread_crumbs => $brcrum}));
 1057:         if ($env{'form.action'} eq 'singleuser') {
 1058:             my $readonly;
 1059:             if (($context eq 'domain') && (!&Apache::lonnet::allowed('mau',$srch->{'srchdomain'}))) {
 1060:                 $readonly = 1;
 1061:                 $r->print("<b>$lt{'usrvu'}</b><br />");
 1062:             } else {
 1063:                 $r->print("<b>$lt{'usrch'}</b><br />");
 1064:             }
 1065:             $r->print(&entry_form($srch->{'srchdomain'},$srch,undef,$context,undef,$crstype));
 1066:             if ($readonly) {
 1067:                 $r->print('<h3>'.$lt{'suvr'}.'</h3>');
 1068:             } else {
 1069:                 $r->print('<h3>'.$lt{'usel'}.'</h3>');
 1070:             }
 1071:         } elsif ($env{'form.action'} eq 'singlestudent') {
 1072:             $r->print($jscript."<b>");
 1073:             if ($crstype eq 'Community') {
 1074:                 $r->print($lt{'memsrch'});
 1075:             } else {
 1076:                 $r->print($lt{'stusrch'});
 1077:             }
 1078:             $r->print("</b><br />");
 1079:             $r->print(&entry_form($srch->{'srchdomain'},$srch,undef,$context,undef,$crstype));
 1080:             $r->print('</form><h3>');
 1081:             if ($crstype eq 'Community') {
 1082:                 $r->print($lt{'memsel'});
 1083:             } else {
 1084:                 $r->print($lt{'stusel'});
 1085:             }
 1086:             $r->print('</h3>');
 1087:         } elsif ($env{'form.action'} eq 'accesslogs') {
 1088:             $r->print("<b>$lt{'srcva'}</b><br />");
 1089:             $r->print(&entry_form($srch->{'srchdomain'},$srch,undef,$context,undef,undef,1));
 1090:             $r->print('<h3>'.$lt{'vacsel'}.'</h3>');
 1091:         }
 1092:     }
 1093:     $r->print('<form name="usersrchform" method="post" action="">'.
 1094:               &Apache::loncommon::start_data_table()."\n".
 1095:               &Apache::loncommon::start_data_table_header_row()."\n".
 1096:               ' <th> </th>'."\n");
 1097:     foreach my $field (@fields) {
 1098:         $r->print(' <th><a href="javascript:document.usersrchform.sortby.value='.
 1099:                   "'".$field."'".';document.usersrchform.submit();">'.
 1100:                   $lt{$field}.'</a></th>'."\n");
 1101:     }
 1102:     $r->print(&Apache::loncommon::end_data_table_header_row());
 1103: 
 1104:     my @sorted_users = sort {
 1105:         lc($srch_results->{$a}->{$sortby})   cmp lc($srch_results->{$b}->{$sortby})
 1106:             ||
 1107:         lc($srch_results->{$a}->{lastname})  cmp lc($srch_results->{$b}->{lastname})
 1108:             ||
 1109:         lc($srch_results->{$a}->{firstname}) cmp lc($srch_results->{$b}->{firstname})
 1110: 	    ||
 1111: 	lc($a) cmp lc($b)
 1112:         } (keys(%$srch_results));
 1113: 
 1114:     foreach my $user (@sorted_users) {
 1115:         my ($uname,$udom) = split(/:/,$user);
 1116:         my $onclick;
 1117:         if ($context eq 'requestcrs') {
 1118:             $onclick =
 1119:                 'onclick="javascript:gochoose('."'$uname','$udom',".
 1120:                                                "'$srch_results->{$user}->{firstname}',".
 1121:                                                "'$srch_results->{$user}->{lastname}',".
 1122:                                                "'$srch_results->{$user}->{permanentemail}'".');"';
 1123:         } else {
 1124:             $onclick =
 1125:                 ' onclick="javascript:pickuser('."'".$uname."'".','."'".$udom."'".');"';
 1126:         }
 1127:         $r->print(&Apache::loncommon::start_data_table_row().
 1128:                   '<td><input type="button" name="seluser" value="'.&mt('Select').'" '.
 1129:                   $onclick.' /></td>'.
 1130:                   '<td><tt>'.$uname.'</tt></td>'.
 1131:                   '<td><tt>'.$udom.'</tt></td>');
 1132:         foreach my $field ('lastname','firstname','permanentemail') {
 1133:             $r->print('<td>'.$srch_results->{$user}->{$field}.'</td>');
 1134:         }
 1135:         $r->print(&Apache::loncommon::end_data_table_row());
 1136:     }
 1137:     $r->print(&Apache::loncommon::end_data_table().'<br /><br />');
 1138:     if (ref($srcharray) eq 'ARRAY') {
 1139:         foreach my $item (@{$srcharray}) {
 1140:             $r->print('<input type="hidden" name="'.$item.'" value="'.$env{'form.'.$item}.'" />'."\n");
 1141:         }
 1142:     }
 1143:     $r->print(' <input type="hidden" name="sortby" value="'.$sortby.'" />'."\n".
 1144:               ' <input type="hidden" name="seluname" value="" />'."\n".
 1145:               ' <input type="hidden" name="seludom" value="" />'."\n".
 1146:               ' <input type="hidden" name="currstate" value="select" />'."\n".
 1147:               ' <input type="hidden" name="phase" value="get_user_info" />'."\n".
 1148:               ' <input type="hidden" name="action" value="'.$env{'form.action'}.'" />'."\n");
 1149:     if ($context eq 'requestcrs') {
 1150:         $r->print($opener_elements.'</form></div>');
 1151:     } else {
 1152:         $r->print($response.'</form>');
 1153:     }
 1154: }
 1155: 
 1156: sub print_user_query_page {
 1157:     my ($r,$caller,$brcrum) = @_;
 1158: # FIXME - this is for a network-wide name search (similar to catalog search)
 1159: # To use frames with similar behavior to catalog/portfolio search.
 1160: # To be implemented. 
 1161:     return;
 1162: }
 1163: 
 1164: sub print_user_modification_page {
 1165:     my ($r,$ccuname,$ccdomain,$srch,$response,$context,$permission,$crstype,
 1166:         $brcrum,$showcredits) = @_;
 1167:     if (($ccuname eq '') || ($ccdomain eq '')) {
 1168:         my $usermsg = &mt('No username and/or domain provided.');
 1169:         $env{'form.phase'} = '';
 1170: 	&print_username_entry_form($r,$context,$usermsg,'','',$crstype,$brcrum,
 1171:                                    $permission);
 1172:         return;
 1173:     }
 1174:     my ($form,$formname);
 1175:     if ($env{'form.action'} eq 'singlestudent') {
 1176:         $form = 'document.enrollstudent';
 1177:         $formname = 'enrollstudent';
 1178:     } else {
 1179:         $form = 'document.cu';
 1180:         $formname = 'cu';
 1181:     }
 1182:     my %abv_auth = &auth_abbrev();
 1183:     my (%rulematch,%inst_results,$newuser,%alerts,%curr_rules,%got_rules);
 1184:     my $uhome=&Apache::lonnet::homeserver($ccuname,$ccdomain);
 1185:     if ($uhome eq 'no_host') {
 1186:         my $usertype;
 1187:         my ($rules,$ruleorder) =
 1188:             &Apache::lonnet::inst_userrules($ccdomain,'username');
 1189:             $usertype =
 1190:                 &Apache::lonuserutils::check_usertype($ccdomain,$ccuname,$rules,
 1191:                                                       \%curr_rules,\%got_rules);
 1192:         my $cancreate =
 1193:             &Apache::lonuserutils::can_create_user($ccdomain,$context,
 1194:                                                    $usertype);
 1195:         if (!$cancreate) {
 1196:             my $helplink = 'javascript:helpMenu('."'display'".')';
 1197:             my %usertypetext = (
 1198:                 official   => 'institutional',
 1199:                 unofficial => 'non-institutional',
 1200:             );
 1201:             my $response;
 1202:             if ($env{'form.origform'} eq 'crtusername') {
 1203:                 $response = '<span class="LC_warning">'.
 1204:                             &mt('No match found for the username [_1] in LON-CAPA domain: [_2]',
 1205:                                 '<b>'.$ccuname.'</b>',$ccdomain).
 1206:                             '</span><br />';
 1207:             }
 1208:             $response .= '<p class="LC_warning">'
 1209:                         .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
 1210:                         .' ';
 1211:             if ($context eq 'domain') {
 1212:                 $response .= &mt('Please contact a [_1] for assistance.',
 1213:                                  &Apache::lonnet::plaintext('dc'));
 1214:             } else {
 1215:                 $response .= &mt('Please contact the [_1]helpdesk[_2] for assistance.'
 1216:                                 ,'<a href="'.$helplink.'">','</a>');
 1217:             }
 1218:             $response .= '</p><br />';
 1219:             $env{'form.phase'} = '';
 1220:             &print_username_entry_form($r,$context,$response,undef,undef,$crstype,$brcrum,
 1221:                                        $permission);
 1222:             return;
 1223:         }
 1224:         $newuser = 1;
 1225:         my $checkhash;
 1226:         my $checks = { 'username' => 1 };
 1227:         $checkhash->{$ccuname.':'.$ccdomain} = { 'newuser' => $newuser };
 1228:         &Apache::loncommon::user_rule_check($checkhash,$checks,
 1229:             \%alerts,\%rulematch,\%inst_results,\%curr_rules,\%got_rules);
 1230:         if (ref($alerts{'username'}) eq 'HASH') {
 1231:             if (ref($alerts{'username'}{$ccdomain}) eq 'HASH') {
 1232:                 my $domdesc =
 1233:                     &Apache::lonnet::domain($ccdomain,'description');
 1234:                 if ($alerts{'username'}{$ccdomain}{$ccuname}) {
 1235:                     my $userchkmsg;
 1236:                     if (ref($curr_rules{$ccdomain}) eq 'HASH') {  
 1237:                         $userchkmsg = 
 1238:                             &Apache::loncommon::instrule_disallow_msg('username',
 1239:                                                                  $domdesc,1).
 1240:                         &Apache::loncommon::user_rule_formats($ccdomain,
 1241:                             $domdesc,$curr_rules{$ccdomain}{'username'},
 1242:                             'username');
 1243:                     }
 1244:                     $env{'form.phase'} = '';
 1245:                     &print_username_entry_form($r,$context,$userchkmsg,undef,undef,$crstype,$brcrum,
 1246:                                                $permission);
 1247:                     return;
 1248:                 }
 1249:             }
 1250:         }
 1251:     } else {
 1252:         $newuser = 0;
 1253:     }
 1254:     if ($response) {
 1255:         $response = '<br />'.$response;
 1256:     }
 1257: 
 1258:     my $pjump_def = &Apache::lonhtmlcommon::pjump_javascript_definition();
 1259:     my $dc_setcourse_code = '';
 1260:     my $nondc_setsection_code = '';                                        
 1261:     my %loaditem;
 1262: 
 1263:     my $groupslist = &Apache::lonuserutils::get_groupslist();
 1264: 
 1265:     my $js = &validation_javascript($context,$ccdomain,$pjump_def,$crstype,
 1266:                                $groupslist,$newuser,$formname,\%loaditem);
 1267:     my %breadcrumb_text = &singleuser_breadcrumb($crstype,$context,$ccdomain);
 1268:     my $helpitem = 'Course_Change_Privileges';
 1269:     if ($env{'form.action'} eq 'singlestudent') {
 1270:         $helpitem = 'Course_Add_Student';
 1271:     } elsif ($context eq 'author') {
 1272:         $helpitem = 'Author_Change_Privileges';
 1273:     } elsif ($context eq 'domain') {
 1274:         $helpitem = 'Domain_Change_Privileges';
 1275:     }
 1276:     push (@{$brcrum},
 1277:         {href => "javascript:backPage($form)",
 1278:          text => $breadcrumb_text{'search'},
 1279:          faq  => 282,
 1280:          bug  => 'Instructor Interface',});
 1281:     if ($env{'form.phase'} eq 'userpicked') {
 1282:        push(@{$brcrum},
 1283:               {href => "javascript:backPage($form,'get_user_info','select')",
 1284:                text => $breadcrumb_text{'userpicked'},
 1285:                faq  => 282,
 1286:                bug  => 'Instructor Interface',});
 1287:     }
 1288:     push(@{$brcrum},
 1289:             {href => "javascript:backPage($form,'$env{'form.phase'}','modify')",
 1290:              text => $breadcrumb_text{'modify'},
 1291:              faq  => 282,
 1292:              bug  => 'Instructor Interface',
 1293:              help => $helpitem});
 1294:     my $args = {'add_entries'           => \%loaditem,
 1295:                 'bread_crumbs'          => $brcrum,
 1296:                 'bread_crumbs_component' => 'User Management'};
 1297:     if ($env{'form.popup'}) {
 1298:         $args->{'no_nav_bar'} = 1;
 1299:     }
 1300:     my $start_page =
 1301:         &Apache::loncommon::start_page('User Management',$js,$args);
 1302: 
 1303:     my $forminfo =<<"ENDFORMINFO";
 1304: <form action="/adm/createuser" method="post" name="$formname">
 1305: <input type="hidden" name="phase" value="update_user_data" />
 1306: <input type="hidden" name="ccuname" value="$ccuname" />
 1307: <input type="hidden" name="ccdomain" value="$ccdomain" />
 1308: <input type="hidden" name="pres_value"  value="" />
 1309: <input type="hidden" name="pres_type"   value="" />
 1310: <input type="hidden" name="pres_marker" value="" />
 1311: ENDFORMINFO
 1312:     my (%inccourses,$roledom,$defaultcredits);
 1313:     if ($context eq 'course') {
 1314:         $inccourses{$env{'request.course.id'}}=1;
 1315:         $roledom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 1316:         if ($showcredits) {
 1317:             $defaultcredits = &Apache::lonuserutils::get_defaultcredits();
 1318:         }
 1319:     } elsif ($context eq 'author') {
 1320:         $roledom = $env{'request.role.domain'};
 1321:     } elsif ($context eq 'domain') {
 1322:         foreach my $key (keys(%env)) {
 1323:             $roledom = $env{'request.role.domain'};
 1324:             if ($key=~/^user\.priv\.cm\.\/($roledom)\/($match_username)/) {
 1325:                 $inccourses{$1.'_'.$2}=1;
 1326:             }
 1327:         }
 1328:     } else {
 1329:         foreach my $key (keys(%env)) {
 1330: 	    if ($key=~/^user\.priv\.cm\.\/($match_domain)\/($match_username)/) {
 1331: 	        $inccourses{$1.'_'.$2}=1;
 1332:             }
 1333:         }
 1334:     }
 1335:     my $title = '';
 1336:     if ($newuser) {
 1337:         my ($portfolioform,$domroleform);
 1338:         if ((&Apache::lonnet::allowed('mpq',$env{'request.role.domain'})) ||
 1339:             (&Apache::lonnet::allowed('mut',$env{'request.role.domain'}))) {
 1340:             # Current user has quota or user tools modification privileges
 1341:             $portfolioform = '<br />'.&user_quotas($ccuname,$ccdomain);
 1342:         }
 1343:         if ((&Apache::lonnet::allowed('cau',$env{'request.role.domain'})) &&
 1344:             ($ccdomain eq $env{'request.role.domain'})) {
 1345:             $domroleform = '<br />'.&domainrole_req($ccuname,$ccdomain);
 1346:         }
 1347:         &initialize_authen_forms($ccdomain,$formname);
 1348:         my %lt=&Apache::lonlocal::texthash(
 1349:                 'lg'             => 'Login Data',
 1350:                 'hs'             => "Home Server",
 1351:         );
 1352: 	$r->print(<<ENDTITLE);
 1353: $start_page
 1354: $response
 1355: $forminfo
 1356: <script type="text/javascript" language="Javascript">
 1357: // <![CDATA[
 1358: $loginscript
 1359: // ]]>
 1360: </script>
 1361: <input type='hidden' name='makeuser' value='1' />
 1362: ENDTITLE
 1363:         if ($env{'form.action'} eq 'singlestudent') {
 1364:             if ($crstype eq 'Community') {
 1365:                 $title = &mt('Create New User [_1] in domain [_2] as a member',
 1366:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1367:             } else {
 1368:                 $title = &mt('Create New User [_1] in domain [_2] as a student',
 1369:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1370:             }
 1371:         } else {
 1372:                 $title = &mt('Create New User [_1] in domain [_2]',
 1373:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1374:         }
 1375:         $r->print('<h2>'.$title.'</h2>'."\n");
 1376:         $r->print('<div class="LC_left_float">');
 1377:         $r->print(&personal_data_display($ccuname,$ccdomain,$newuser,$context,
 1378:                                          $inst_results{$ccuname.':'.$ccdomain}));
 1379:         # Option to disable student/employee ID conflict checking not offerred for new users.
 1380:         my ($home_server_pick,$numlib) = 
 1381:             &Apache::loncommon::home_server_form_item($ccdomain,'hserver',
 1382:                                                       'default','hide');
 1383:         if ($numlib > 1) {
 1384:             $r->print("
 1385: <br />
 1386: $lt{'hs'}: $home_server_pick
 1387: <br />");
 1388:         } else {
 1389:             $r->print($home_server_pick);
 1390:         }
 1391:         if (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) {
 1392:             $r->print('<br /><h3>'.
 1393:                       &mt('User Can Request Creation of Courses/Communities in this Domain?').'</h3>'.
 1394:                       &Apache::loncommon::start_data_table().
 1395:                       &build_tools_display($ccuname,$ccdomain,
 1396:                                            'requestcourses').
 1397:                       &Apache::loncommon::end_data_table());
 1398:         }
 1399:         $r->print('</div>'."\n".'<div class="LC_left_float"><h3>'.
 1400:                   $lt{'lg'}.'</h3>');
 1401:         my ($fixedauth,$varauth,$authmsg); 
 1402:         if (ref($rulematch{$ccuname.':'.$ccdomain}) eq 'HASH') {
 1403:             my $matchedrule = $rulematch{$ccuname.':'.$ccdomain}{'username'};
 1404:             my ($rules,$ruleorder) = 
 1405:                 &Apache::lonnet::inst_userrules($ccdomain,'username');
 1406:             if (ref($rules) eq 'HASH') {
 1407:                 if (ref($rules->{$matchedrule}) eq 'HASH') {
 1408:                     my $authtype = $rules->{$matchedrule}{'authtype'};
 1409:                     if ($authtype !~ /^(krb4|krb5|int|fsys|loc)$/) {
 1410:                         $r->print(&Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc));
 1411:                     } else { 
 1412:                         my $authparm = $rules->{$matchedrule}{'authparm'};
 1413:                         $authmsg = $rules->{$matchedrule}{'authmsg'};
 1414:                         if ($authtype =~ /^krb(4|5)$/) {
 1415:                             my $ver = $1;
 1416:                             if ($authparm ne '') {
 1417:                                 $fixedauth = <<"KERB"; 
 1418: <input type="hidden" name="login" value="krb" />
 1419: <input type="hidden" name="krbver" value="$ver" />
 1420: <input type="hidden" name="krbarg" value="$authparm" />
 1421: KERB
 1422:                             }
 1423:                         } else {
 1424:                             $fixedauth = 
 1425: '<input type="hidden" name="login" value="'.$authtype.'" />'."\n";
 1426:                             if ($rules->{$matchedrule}{'authparmfixed'}) {
 1427:                                 $fixedauth .=    
 1428: '<input type="hidden" name="'.$authtype.'arg" value="'.$authparm.'" />'."\n";
 1429:                             } else {
 1430:                                 if ($authtype eq 'int') {
 1431:                                     $varauth = '<br />'.
 1432: &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>';
 1433:                                 } elsif ($authtype eq 'loc') {
 1434:                                     $varauth = '<br />'.
 1435: &mt('[_1] Local Authentication with argument [_2]','','<input type="text" name="'.$authtype.'arg" value="" />')."\n";
 1436:                                 } else {
 1437:                                     $varauth =
 1438: '<input type="text" name="'.$authtype.'arg" value="" />'."\n";
 1439:                                 }
 1440:                             }
 1441:                         }
 1442:                     }
 1443:                 } else {
 1444:                     $r->print(&Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc));
 1445:                 }
 1446:             }
 1447:             if ($authmsg) {
 1448:                 $r->print(<<ENDAUTH);
 1449: $fixedauth
 1450: $authmsg
 1451: $varauth
 1452: ENDAUTH
 1453:             }
 1454:         } else {
 1455:             $r->print(&Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc)); 
 1456:         }
 1457:         $r->print($portfolioform.$domroleform);
 1458:         if ($env{'form.action'} eq 'singlestudent') {
 1459:             $r->print(&date_sections_select($context,$newuser,$formname,
 1460:                                             $permission,$crstype,$ccuname,
 1461:                                             $ccdomain,$showcredits));
 1462:         }
 1463:         $r->print('</div><div class="LC_clear_float_footer"></div>');
 1464:     } else { # user already exists
 1465: 	$r->print($start_page.$forminfo);
 1466:         if ($env{'form.action'} eq 'singlestudent') {
 1467:             if ($crstype eq 'Community') {
 1468:                 $title = &mt('Enroll one member: [_1] in domain [_2]',
 1469:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1470:             } else {
 1471:                 $title = &mt('Enroll one student: [_1] in domain [_2]',
 1472:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1473:             }
 1474:         } else {
 1475:             if ($permission->{'cusr'}) {
 1476:                 $title = &mt('Modify existing user: [_1] in domain [_2]',
 1477:                              '"'.$ccuname.'"','"'.$ccdomain.'"');
 1478:             } else {
 1479:                 $title = &mt('Existing user: [_1] in domain [_2]',
 1480:                              '"'.$ccuname.'"','"'.$ccdomain.'"');
 1481:             }
 1482:         }
 1483:         $r->print('<h2>'.$title.'</h2>'."\n");
 1484:         $r->print('<div class="LC_left_float">');
 1485:         $r->print(&personal_data_display($ccuname,$ccdomain,$newuser,$context,
 1486:                                          $inst_results{$ccuname.':'.$ccdomain}));
 1487:         if ((&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) ||
 1488:             (&Apache::lonnet::allowed('udp',$env{'request.role.domain'}))) {
 1489:             $r->print('<br /><h3>'.&mt('User Can Request Creation of Courses/Communities in this Domain?').'</h3>'."\n");
 1490:             if (($env{'request.role.domain'} eq $ccdomain) ||
 1491:                 (&Apache::lonnet::will_trust('reqcrs',$ccdomain,$env{'request.role.domain'}))) {
 1492:                 $r->print(&Apache::loncommon::start_data_table());
 1493:                 if ($env{'request.role.domain'} eq $ccdomain) {
 1494:                     $r->print(&build_tools_display($ccuname,$ccdomain,'requestcourses'));
 1495:                 } else {
 1496:                     $r->print(&coursereq_externaluser($ccuname,$ccdomain,
 1497:                                                       $env{'request.role.domain'}));
 1498:                 }
 1499:                 $r->print(&Apache::loncommon::end_data_table());
 1500:             } else {
 1501:                 $r->print(&mt('Domain configuration for this domain prohibits course creation by users from domain: "[_1]"',
 1502:                               &Apache::lonnet::domain($ccdomain,'description')));
 1503:             }
 1504:         }
 1505:         $r->print('</div>');
 1506:         my @order = ('auth','quota','tools','requestauthor');
 1507:         my %user_text;
 1508:         my ($isadv,$isauthor) = 
 1509:             &Apache::lonnet::is_advanced_user($ccdomain,$ccuname);
 1510:         if ((!$isauthor) && 
 1511:             ((&Apache::lonnet::allowed('cau',$env{'request.role.domain'})) ||
 1512:              (&Apache::lonnet::allowed('udp',$env{'request.role.domain'}))) &&
 1513:              ($env{'request.role.domain'} eq $ccdomain)) {
 1514:             $user_text{'requestauthor'} = &domainrole_req($ccuname,$ccdomain);
 1515:         }
 1516:         $user_text{'auth'} =  &user_authentication($ccuname,$ccdomain,$formname,$crstype,$permission);
 1517:         if ((&Apache::lonnet::allowed('mpq',$ccdomain)) ||
 1518:             (&Apache::lonnet::allowed('mut',$ccdomain)) ||
 1519:             (&Apache::lonnet::allowed('udp',$ccdomain))) {
 1520:             # Current user has quota modification privileges
 1521:             $user_text{'quota'} = &user_quotas($ccuname,$ccdomain);
 1522:         }
 1523:         if (!&Apache::lonnet::allowed('mpq',$ccdomain)) {
 1524:             if (&Apache::lonnet::allowed('mpq',$env{'request.role.domain'})) {
 1525:                 my %lt=&Apache::lonlocal::texthash(
 1526:                     'dska'  => "Disk quotas for user's portfolio and Authoring Space",
 1527:                     'youd'  => "You do not have privileges to modify the portfolio and/or Authoring Space quotas for this user.",
 1528:                     'ichr'  => "If a change is required, contact a domain coordinator for the domain",
 1529:                 );
 1530:                 $user_text{'quota'} = <<ENDNOPORTPRIV;
 1531: <h3>$lt{'dska'}</h3>
 1532: $lt{'youd'} $lt{'ichr'}: $ccdomain
 1533: ENDNOPORTPRIV
 1534:             }
 1535:         }
 1536:         if (!&Apache::lonnet::allowed('mut',$ccdomain)) {
 1537:             if (&Apache::lonnet::allowed('mut',$env{'request.role.domain'})) {
 1538:                 my %lt=&Apache::lonlocal::texthash(
 1539:                     'utav'  => "User Tools Availability",
 1540:                     'yodo'  => "You do not have privileges to modify Portfolio, Blog, WebDAV, or Personal Information Page settings for this user.",
 1541:                     'ifch'  => "If a change is required, contact a domain coordinator for the domain",
 1542:                 );
 1543:                 $user_text{'tools'} = <<ENDNOTOOLSPRIV;
 1544: <h3>$lt{'utav'}</h3>
 1545: $lt{'yodo'} $lt{'ifch'}: $ccdomain
 1546: ENDNOTOOLSPRIV
 1547:             }
 1548:         }
 1549:         my $gotdiv = 0; 
 1550:         foreach my $item (@order) {
 1551:             if ($user_text{$item} ne '') {
 1552:                 unless ($gotdiv) {
 1553:                     $r->print('<div class="LC_left_float">');
 1554:                     $gotdiv = 1;
 1555:                 }
 1556:                 $r->print('<br />'.$user_text{$item});
 1557:             }
 1558:         }
 1559:         if ($env{'form.action'} eq 'singlestudent') {
 1560:             unless ($gotdiv) {
 1561:                 $r->print('<div class="LC_left_float">');
 1562:             }
 1563:             my $credits;
 1564:             if ($showcredits) {
 1565:                 $credits = &get_user_credits($ccuname,$ccdomain,$defaultcredits);
 1566:                 if ($credits eq '') {
 1567:                     $credits = $defaultcredits;
 1568:                 }
 1569:             }
 1570:             $r->print(&date_sections_select($context,$newuser,$formname,
 1571:                                             $permission,$crstype,$ccuname,
 1572:                                             $ccdomain,$showcredits));
 1573:         }
 1574:         if ($gotdiv) {
 1575:             $r->print('</div><div class="LC_clear_float_footer"></div>');
 1576:         }
 1577:         my $statuses;
 1578:         if (($context eq 'domain') && (&Apache::lonnet::allowed('udp',$ccdomain)) &&
 1579:             (!&Apache::lonnet::allowed('mau',$ccdomain))) {
 1580:             $statuses = ['active'];
 1581:         } elsif (($context eq 'course') && ((&Apache::lonnet::allowed('vcl',$env{'request.course.id'})) ||
 1582:                  ($env{'request.course.sec'} &&
 1583:                   &Apache::lonnet::allowed('vcl',$env{'request.course.id'}.'/'.$env{'request.course.sec'})))) {
 1584:             $statuses = ['active'];
 1585:         }
 1586:         if ($env{'form.action'} ne 'singlestudent') {
 1587:             &display_existing_roles($r,$ccuname,$ccdomain,\%inccourses,$context,
 1588:                                     $roledom,$crstype,$showcredits,$statuses);
 1589:         }
 1590:     } ## End of new user/old user logic
 1591:     if ($env{'form.action'} eq 'singlestudent') {
 1592:         my $btntxt;
 1593:         if ($crstype eq 'Community') {
 1594:             $btntxt = &mt('Enroll Member');
 1595:         } else {
 1596:             $btntxt = &mt('Enroll Student');
 1597:         }
 1598:         $r->print('<br /><input type="button" value="'.$btntxt.'" onclick="setSections(this.form)" />'."\n");
 1599:     } elsif ($permission->{'cusr'}) {
 1600:         $r->print('<div class="LC_left_float">'.
 1601:                   '<fieldset><legend>'.&mt('Add Roles').'</legend>');
 1602:         my $addrolesdisplay = 0;
 1603:         if ($context eq 'domain' || $context eq 'author') {
 1604:             $addrolesdisplay = &new_coauthor_roles($r,$ccuname,$ccdomain);
 1605:         }
 1606:         if ($context eq 'domain') {
 1607:             my $add_domainroles = &new_domain_roles($r,$ccdomain);
 1608:             if (!$addrolesdisplay) {
 1609:                 $addrolesdisplay = $add_domainroles;
 1610:             }
 1611:             $r->print(&course_level_dc($env{'request.role.domain'},$showcredits));
 1612:             $r->print('</fieldset></div><div class="LC_clear_float_footer"></div>'.
 1613:                       '<br /><input type="button" value="'.&mt('Save').'" onclick="setCourse()" />'."\n");
 1614:         } elsif ($context eq 'author') {
 1615:             if ($addrolesdisplay) {
 1616:                 $r->print('</fieldset></div><div class="LC_clear_float_footer"></div>'.
 1617:                           '<br /><input type="button" value="'.&mt('Save').'"');
 1618:                 if ($newuser) {
 1619:                     $r->print(' onclick="auth_check()" \>'."\n");
 1620:                 } else {
 1621:                     $r->print('onclick="this.form.submit()" \>'."\n");
 1622:                 }
 1623:             } else {
 1624:                 $r->print('</fieldset></div>'.
 1625:                           '<div class="LC_clear_float_footer"></div>'.
 1626:                           '<br /><a href="javascript:backPage(document.cu)">'.
 1627:                           &mt('Back to previous page').'</a>');
 1628:             }
 1629:         } else {
 1630:             $r->print(&course_level_table(\%inccourses,$showcredits,$defaultcredits));
 1631:             $r->print('</fieldset></div><div class="LC_clear_float_footer"></div>'.
 1632:                       '<br /><input type="button" value="'.&mt('Save').'" onclick="setSections(this.form)" />'."\n");
 1633:         }
 1634:     }
 1635:     $r->print(&Apache::lonhtmlcommon::echo_form_input(['phase','userrole','ccdomain','prevphase','currstate','ccuname','ccdomain']));
 1636:     $r->print('<input type="hidden" name="currstate" value="" />');
 1637:     $r->print('<input type="hidden" name="prevphase" value="'.$env{'form.phase'}.'" /></form><br /><br />');
 1638:     return;
 1639: }
 1640: 
 1641: sub singleuser_breadcrumb {
 1642:     my ($crstype,$context,$domain) = @_;
 1643:     my %breadcrumb_text;
 1644:     if ($env{'form.action'} eq 'singlestudent') {
 1645:         if ($crstype eq 'Community') {
 1646:             $breadcrumb_text{'search'} = 'Enroll a member';
 1647:         } else {
 1648:             $breadcrumb_text{'search'} = 'Enroll a student';
 1649:         }
 1650:         $breadcrumb_text{'userpicked'} = 'Select a user';
 1651:         $breadcrumb_text{'modify'} = 'Set section/dates';
 1652:     } elsif ($env{'form.action'} eq 'accesslogs') {
 1653:         $breadcrumb_text{'search'} = 'View access logs for a user';
 1654:         $breadcrumb_text{'userpicked'} = 'Select a user';
 1655:         $breadcrumb_text{'activity'} = 'Activity';
 1656:     } elsif (($env{'form.action'} eq 'singleuser') && ($context eq 'domain') &&
 1657:              (!&Apache::lonnet::allowed('mau',$domain))) {
 1658:         $breadcrumb_text{'search'} = "View user's roles";
 1659:         $breadcrumb_text{'userpicked'} = 'Select a user';
 1660:         $breadcrumb_text{'modify'} = 'User roles';
 1661:     } else {
 1662:         $breadcrumb_text{'search'} = 'Create/modify a user';
 1663:         $breadcrumb_text{'userpicked'} = 'Select a user';
 1664:         $breadcrumb_text{'modify'} = 'Set user role';
 1665:     }
 1666:     return %breadcrumb_text;
 1667: }
 1668: 
 1669: sub date_sections_select {
 1670:     my ($context,$newuser,$formname,$permission,$crstype,$ccuname,$ccdomain,
 1671:         $showcredits) = @_;
 1672:     my $credits;
 1673:     if ($showcredits) {
 1674:         my $defaultcredits = &Apache::lonuserutils::get_defaultcredits();
 1675:         $credits = &get_user_credits($ccuname,$ccdomain,$defaultcredits);
 1676:         if ($credits eq '') {
 1677:             $credits = $defaultcredits;
 1678:         }
 1679:     }
 1680:     my $cid = $env{'request.course.id'};
 1681:     my ($cnum,$cdom) = &Apache::lonuserutils::get_course_identity($cid);
 1682:     my $date_table = '<h3>'.&mt('Starting and Ending Dates').'</h3>'."\n".
 1683:         &Apache::lonuserutils::date_setting_table(undef,undef,$context,
 1684:                                                   undef,$formname,$permission);
 1685:     my $rowtitle = 'Section';
 1686:     my $secbox = '<h3>'.&mt('Section and Credits').'</h3>'."\n".
 1687:         &Apache::lonuserutils::section_picker($cdom,$cnum,'st',$rowtitle,
 1688:                                               $permission,$context,'',$crstype,
 1689:                                               $showcredits,$credits);
 1690:     my $output = $date_table.$secbox;
 1691:     return $output;
 1692: }
 1693: 
 1694: sub validation_javascript {
 1695:     my ($context,$ccdomain,$pjump_def,$crstype,$groupslist,$newuser,$formname,
 1696:         $loaditem) = @_;
 1697:     my $dc_setcourse_code = '';
 1698:     my $nondc_setsection_code = '';
 1699:     if ($context eq 'domain') {
 1700:         my $dcdom = $env{'request.role.domain'};
 1701:         $loaditem->{'onload'} = "document.cu.coursedesc.value='';";
 1702:         $dc_setcourse_code = 
 1703:             &Apache::lonuserutils::dc_setcourse_js('cu','singleuser',$context);
 1704:     } else {
 1705:         my $checkauth; 
 1706:         if (($newuser) || (&Apache::lonnet::allowed('mau',$ccdomain))) {
 1707:             $checkauth = 1;
 1708:         }
 1709:         if ($context eq 'course') {
 1710:             $nondc_setsection_code =
 1711:                 &Apache::lonuserutils::setsections_javascript($formname,$groupslist,
 1712:                                                               undef,$checkauth,
 1713:                                                               $crstype);
 1714:         }
 1715:         if ($checkauth) {
 1716:             $nondc_setsection_code .= 
 1717:                 &Apache::lonuserutils::verify_authen($formname,$context);
 1718:         }
 1719:     }
 1720:     my $js = &user_modification_js($pjump_def,$dc_setcourse_code,
 1721:                                    $nondc_setsection_code,$groupslist);
 1722:     my ($jsback,$elements) = &crumb_utilities();
 1723:     $js .= "\n".
 1724:            '<script type="text/javascript">'."\n".
 1725:            '// <![CDATA['."\n".
 1726:            $jsback."\n".
 1727:            '// ]]>'."\n".
 1728:            '</script>'."\n";
 1729:     return $js;
 1730: }
 1731: 
 1732: sub display_existing_roles {
 1733:     my ($r,$ccuname,$ccdomain,$inccourses,$context,$roledom,$crstype,
 1734:         $showcredits,$statuses) = @_;
 1735:     my $now=time;
 1736:     my $showall = 1;
 1737:     my ($showexpired,$showactive);
 1738:     if ((ref($statuses) eq 'ARRAY') && (@{$statuses} > 0)) {
 1739:         $showall = 0;
 1740:         if (grep(/^expired$/,@{$statuses})) {
 1741:             $showexpired = 1;
 1742:         }
 1743:         if (grep(/^active$/,@{$statuses})) {
 1744:             $showactive = 1;
 1745:         }
 1746:         if ($showexpired && $showactive) {
 1747:             $showall = 1;
 1748:         }
 1749:     }
 1750:     my %lt=&Apache::lonlocal::texthash(
 1751:                     'rer'  => "Existing Roles",
 1752:                     'rev'  => "Revoke",
 1753:                     'del'  => "Delete",
 1754:                     'ren'  => "Re-Enable",
 1755:                     'rol'  => "Role",
 1756:                     'ext'  => "Extent",
 1757:                     'crd'  => "Credits",
 1758:                     'sta'  => "Start",
 1759:                     'end'  => "End",
 1760:                                        );
 1761:     my (%rolesdump,%roletext,%sortrole,%roleclass,%rolepriv);
 1762:     if ($context eq 'course' || $context eq 'author') {
 1763:         my @roles = &Apache::lonuserutils::roles_by_context($context,1,$crstype);
 1764:         my %roleshash = 
 1765:             &Apache::lonnet::get_my_roles($ccuname,$ccdomain,'userroles',
 1766:                               ['active','previous','future'],\@roles,$roledom,1);
 1767:         foreach my $key (keys(%roleshash)) {
 1768:             my ($start,$end) = split(':',$roleshash{$key});
 1769:             next if ($start eq '-1' || $end eq '-1');
 1770:             my ($rnum,$rdom,$role,$sec) = split(':',$key);
 1771:             if ($context eq 'course') {
 1772:                 next unless (($rnum eq $env{'course.'.$env{'request.course.id'}.'.num'})
 1773:                              && ($rdom eq $env{'course.'.$env{'request.course.id'}.'.domain'}));
 1774:             } elsif ($context eq 'author') {
 1775:                 next unless (($rnum eq $env{'user.name'}) && ($rdom eq $env{'request.role.domain'}));
 1776:             }
 1777:             my ($newkey,$newvalue,$newrole);
 1778:             $newkey = '/'.$rdom.'/'.$rnum;
 1779:             if ($sec ne '') {
 1780:                 $newkey .= '/'.$sec;
 1781:             }
 1782:             $newvalue = $role;
 1783:             if ($role =~ /^cr/) {
 1784:                 $newrole = 'cr';
 1785:             } else {
 1786:                 $newrole = $role;
 1787:             }
 1788:             $newkey .= '_'.$newrole;
 1789:             if ($start ne '' && $end ne '') {
 1790:                 $newvalue .= '_'.$end.'_'.$start;
 1791:             } elsif ($end ne '') {
 1792:                 $newvalue .= '_'.$end;
 1793:             }
 1794:             $rolesdump{$newkey} = $newvalue;
 1795:         }
 1796:     } else {
 1797:         %rolesdump=&Apache::lonnet::dump('roles',$ccdomain,$ccuname);
 1798:     }
 1799:     # Build up table of user roles to allow revocation and re-enabling of roles.
 1800:     my ($tmp) = keys(%rolesdump);
 1801:     return if ($tmp =~ /^(con_lost|error)/i);
 1802:     foreach my $area (sort { my $a1=join('_',(split('_',$a))[1,0]);
 1803:                                 my $b1=join('_',(split('_',$b))[1,0]);
 1804:                                 return $a1 cmp $b1;
 1805:                             } keys(%rolesdump)) {
 1806:         next if ($area =~ /^rolesdef/);
 1807:         my $envkey=$area;
 1808:         my $role = $rolesdump{$area};
 1809:         my $thisrole=$area;
 1810:         $area =~ s/\_\w\w$//;
 1811:         my ($role_code,$role_end_time,$role_start_time) =
 1812:             split(/_/,$role);
 1813:         my $active=1;
 1814:         $active=0 if (($role_end_time) && ($now>$role_end_time));
 1815:         if ($active) {
 1816:             next unless($showall || $showactive);
 1817:         } else {
 1818:             next unless($showall || $showexpired);
 1819:         }
 1820: # Is this a custom role? Get role owner and title.
 1821:         my ($croleudom,$croleuname,$croletitle)=
 1822:             ($role_code=~m{^cr/($match_domain)/($match_username)/(\w+)$});
 1823:         my $allowed=0;
 1824:         my $delallowed=0;
 1825:         my $sortkey=$role_code;
 1826:         my $class='Unknown';
 1827:         my $credits='';
 1828:         my $csec;
 1829:         if ($area =~ m{^/($match_domain)/($match_courseid)}) {
 1830:             $class='Course';
 1831:             my ($coursedom,$coursedir) = ($1,$2);
 1832:             my $cid = $1.'_'.$2;
 1833:             # $1.'_'.$2 is the course id (eg. 103_12345abcef103l3).
 1834:             next if ($envkey =~ m{^/$match_domain/$match_courseid/[A-Za-z0-9]+_gr$});
 1835:             my %coursedata=
 1836:                 &Apache::lonnet::coursedescription($cid);
 1837:             if ($coursedir =~ /^$match_community$/) {
 1838:                 $class='Community';
 1839:             }
 1840:             $sortkey.="\0$coursedom";
 1841:             my $carea;
 1842:             if (defined($coursedata{'description'})) {
 1843:                 $carea=$coursedata{'description'}.
 1844:                     '<br />'.&mt('Domain').': '.$coursedom.('&nbsp;'x8).
 1845:     &Apache::loncommon::syllabuswrapper(&mt('Syllabus'),$coursedir,$coursedom);
 1846:                 $sortkey.="\0".$coursedata{'description'};
 1847:             } else {
 1848:                 if ($class eq 'Community') {
 1849:                     $carea=&mt('Unavailable community').': '.$area;
 1850:                     $sortkey.="\0".&mt('Unavailable community').': '.$area;
 1851:                 } else {
 1852:                     $carea=&mt('Unavailable course').': '.$area;
 1853:                     $sortkey.="\0".&mt('Unavailable course').': '.$area;
 1854:                 }
 1855:             }
 1856:             $sortkey.="\0$coursedir";
 1857:             $inccourses->{$cid}=1;
 1858:             if (($showcredits) && ($class eq 'Course') && ($role_code eq 'st')) {
 1859:                 my $defaultcredits = $coursedata{'internal.defaultcredits'};
 1860:                 $credits =
 1861:                     &get_user_credits($ccuname,$ccdomain,$defaultcredits,
 1862:                                       $coursedom,$coursedir);
 1863:                 if ($credits eq '') {
 1864:                     $credits = $defaultcredits;
 1865:                 }
 1866:             }
 1867:             if ((&Apache::lonnet::allowed('c'.$role_code,$coursedom.'/'.$coursedir)) ||
 1868:                 (&Apache::lonnet::allowed('c'.$role_code,$ccdomain))) {
 1869:                 $allowed=1;
 1870:             }
 1871:             unless ($allowed) {
 1872:                 my $isowner = &Apache::lonuserutils::is_courseowner($cid,$coursedata{'internal.courseowner'});
 1873:                 if ($isowner) {
 1874:                     if (($role_code eq 'co') && ($class eq 'Community')) {
 1875:                         $allowed = 1;
 1876:                     } elsif (($role_code eq 'cc') && ($class eq 'Course')) {
 1877:                         $allowed = 1;
 1878:                     }
 1879:                 }
 1880:             } 
 1881:             if ((&Apache::lonnet::allowed('dro',$coursedom)) ||
 1882:                 (&Apache::lonnet::allowed('dro',$ccdomain))) {
 1883:                 $delallowed=1;
 1884:             }
 1885: # - custom role. Needs more info, too
 1886:             if ($croletitle) {
 1887:                 if (&Apache::lonnet::allowed('ccr',$coursedom.'/'.$coursedir)) {
 1888:                     $allowed=1;
 1889:                     $thisrole.='.'.$role_code;
 1890:                 }
 1891:             }
 1892:             if ($area=~m{^/($match_domain/$match_courseid/(\w+))}) {
 1893:                 $csec = $2;
 1894:                 $carea.='<br />'.&mt('Section: [_1]',$csec);
 1895:                 $sortkey.="\0$csec";
 1896:                 if (!$allowed) {
 1897:                     if ($env{'request.course.sec'} eq $csec) {
 1898:                         if (&Apache::lonnet::allowed('c'.$role_code,$1)) {
 1899:                             $allowed = 1;
 1900:                         }
 1901:                     }
 1902:                 }
 1903:             }
 1904:             $area=$carea;
 1905:         } else {
 1906:             $sortkey.="\0".$area;
 1907:             # Determine if current user is able to revoke privileges
 1908:             if ($area=~m{^/($match_domain)/}) {
 1909:                 if ((&Apache::lonnet::allowed('c'.$role_code,$1)) ||
 1910:                    (&Apache::lonnet::allowed('c'.$role_code,$ccdomain))) {
 1911:                    $allowed=1;
 1912:                 }
 1913:                 if (((&Apache::lonnet::allowed('dro',$1))  ||
 1914:                     (&Apache::lonnet::allowed('dro',$ccdomain))) &&
 1915:                     ($role_code ne 'dc')) {
 1916:                     $delallowed=1;
 1917:                 }
 1918:             } else {
 1919:                 if (&Apache::lonnet::allowed('c'.$role_code,'/')) {
 1920:                     $allowed=1;
 1921:                 }
 1922:             }
 1923:             if ($role_code eq 'ca' || $role_code eq 'au' || $role_code eq 'aa') {
 1924:                 $class='Authoring Space';
 1925:             } elsif ($role_code eq 'su') {
 1926:                 $class='System';
 1927:             } else {
 1928:                 $class='Domain';
 1929:             }
 1930:         }
 1931:         if (($role_code eq 'ca') || ($role_code eq 'aa')) {
 1932:             $area=~m{/($match_domain)/($match_username)};
 1933:             if (&Apache::lonuserutils::authorpriv($2,$1)) {
 1934:                 $allowed=1;
 1935:             } else {
 1936:                 $allowed=0;
 1937:             }
 1938:         }
 1939:         my $row = '';
 1940:         if ($showall) {
 1941:             $row.= '<td>';
 1942:             if (($active) && ($allowed)) {
 1943:                 $row.= '<input type="checkbox" name="rev:'.$thisrole.'" />';
 1944:             } else {
 1945:                 if ($active) {
 1946:                     $row.='&nbsp;';
 1947:                 } else {
 1948:                     $row.=&mt('expired or revoked');
 1949:                 }
 1950:             }
 1951:             $row.='</td><td>';
 1952:             if ($allowed && !$active) {
 1953:                 $row.= '<input type="checkbox" name="ren:'.$thisrole.'" />';
 1954:             } else {
 1955:                 $row.='&nbsp;';
 1956:             }
 1957:             $row.='</td><td>';
 1958:             if ($delallowed) {
 1959:                 $row.= '<input type="checkbox" name="del:'.$thisrole.'" />';
 1960:             } else {
 1961:                 $row.='&nbsp;';
 1962:             }
 1963:             $row.= '</td>';
 1964:         }
 1965:         my $plaintext='';
 1966:         if (!$croletitle) {
 1967:             $plaintext=&Apache::lonnet::plaintext($role_code,$class);
 1968:             if (($showcredits) && ($credits ne '')) {
 1969:                 $plaintext .= '<br/ ><span class="LC_nobreak">'.
 1970:                               '<span class="LC_fontsize_small">'.
 1971:                               &mt('Credits: [_1]',$credits).
 1972:                               '</span></span>';
 1973:             }
 1974:         } else {
 1975:             $plaintext=
 1976:                 &mt('Custom role [_1][_2]defined by [_3]',
 1977:                         '"'.$croletitle.'"',
 1978:                         '<br />',
 1979:                         $croleuname.':'.$croleudom);
 1980:         }
 1981:         $row.= '<td>'.$plaintext.'</td>'.
 1982:                '<td>'.$area.'</td>'.
 1983:                '<td>'.($role_start_time?&Apache::lonlocal::locallocaltime($role_start_time)
 1984:                                             : '&nbsp;' ).'</td>'.
 1985:                '<td>'.($role_end_time  ?&Apache::lonlocal::locallocaltime($role_end_time)
 1986:                                             : '&nbsp;' ).'</td>';
 1987:         $sortrole{$sortkey}=$envkey;
 1988:         $roletext{$envkey}=$row;
 1989:         $roleclass{$envkey}=$class;
 1990:         if ($allowed) {
 1991:             $rolepriv{$envkey}='edit';
 1992:         } else {
 1993:             if ($context eq 'domain') {
 1994:                 if ((&Apache::lonnet::allowed('vur',$ccdomain)) &&
 1995:                     ($envkey=~m{^/$ccdomain/})) {
 1996:                     $rolepriv{$envkey}='view';
 1997:                 }
 1998:             } elsif ($context eq 'course') {
 1999:                 if ((&Apache::lonnet::allowed('vcl',$env{'request.course.id'})) ||
 2000:                     ($env{'request.course.sec'} && ($env{'request.course.sec'} eq $csec) &&
 2001:                      &Apache::lonnet::allowed('vcl',$env{'request.course.id'}.'/'.$env{'request.course.sec'}))) {
 2002:                     $rolepriv{$envkey}='view';
 2003:                 }
 2004:             }
 2005:         }
 2006:     } # end of foreach        (table building loop)
 2007: 
 2008:     my $rolesdisplay = 0;
 2009:     my %output = ();
 2010:     foreach my $type ('Authoring Space','Course','Community','Domain','System','Unknown') {
 2011:         $output{$type} = '';
 2012:         foreach my $which (sort {uc($a) cmp uc($b)} (keys(%sortrole))) {
 2013:             if ( ($roleclass{$sortrole{$which}} =~ /^\Q$type\E/ ) && ($rolepriv{$sortrole{$which}}) ) {
 2014:                  $output{$type}.=
 2015:                       &Apache::loncommon::start_data_table_row().
 2016:                       $roletext{$sortrole{$which}}.
 2017:                       &Apache::loncommon::end_data_table_row();
 2018:             }
 2019:         }
 2020:         unless($output{$type} eq '') {
 2021:             $output{$type} = '<tr class="LC_info_row">'.
 2022:                       "<td align='center' colspan='7'>".&mt($type)."</td></tr>".
 2023:                       $output{$type};
 2024:             $rolesdisplay = 1;
 2025:         }
 2026:     }
 2027:     if ($rolesdisplay == 1) {
 2028:         my $contextrole='';
 2029:         if ($env{'request.course.id'}) {
 2030:             if (&Apache::loncommon::course_type() eq 'Community') {
 2031:                 $contextrole = &mt('Existing Roles in this Community');
 2032:             } else {
 2033:                 $contextrole = &mt('Existing Roles in this Course');
 2034:             }
 2035:         } elsif ($env{'request.role'} =~ /^au\./) {
 2036:             $contextrole = &mt('Existing Co-Author Roles in your Authoring Space');
 2037:         } else {
 2038:             if ($showall) {
 2039:                 $contextrole = &mt('Existing Roles in this Domain');
 2040:             } elsif ($showactive) {
 2041:                 $contextrole = &mt('Unexpired Roles in this Domain');
 2042:             } elsif ($showexpired) {
 2043:                 $contextrole = &mt('Expired or Revoked Roles in this Domain');
 2044:             }
 2045:         }
 2046:         $r->print('<div class="LC_left_float">'.
 2047: '<fieldset><legend>'.$contextrole.'</legend>'.
 2048: &Apache::loncommon::start_data_table("LC_createuser").
 2049: &Apache::loncommon::start_data_table_header_row());
 2050:         if ($showall) {
 2051:             $r->print(
 2052: '<th>'.$lt{'rev'}.'</th><th>'.$lt{'ren'}.'</th><th>'.$lt{'del'}.'</th>'
 2053:             );
 2054:         } elsif ($showexpired) {
 2055:             $r->print('<th>'.$lt{'rev'}.'</th>');
 2056:         }
 2057:         $r->print(
 2058: '<th>'.$lt{'rol'}.'</th><th>'.$lt{'ext'}.'</th>'.
 2059: '<th>'.$lt{'sta'}.'</th><th>'.$lt{'end'}.'</th>'.
 2060: &Apache::loncommon::end_data_table_header_row());
 2061:         foreach my $type ('Authoring Space','Course','Community','Domain','System','Unknown') {
 2062:             if ($output{$type}) {
 2063:                 $r->print($output{$type}."\n");
 2064:             }
 2065:         }
 2066:         $r->print(&Apache::loncommon::end_data_table().
 2067:                   '</fieldset></div>');
 2068:     }
 2069:     return;
 2070: }
 2071: 
 2072: sub new_coauthor_roles {
 2073:     my ($r,$ccuname,$ccdomain) = @_;
 2074:     my $addrolesdisplay = 0;
 2075:     #
 2076:     # Co-Author
 2077:     #
 2078:     if (&Apache::lonuserutils::authorpriv($env{'user.name'},
 2079:                                           $env{'request.role.domain'}) &&
 2080:         ($env{'user.name'} ne $ccuname || $env{'user.domain'} ne $ccdomain)) {
 2081:         # No sense in assigning co-author role to yourself
 2082:         $addrolesdisplay = 1;
 2083:         my $cuname=$env{'user.name'};
 2084:         my $cudom=$env{'request.role.domain'};
 2085:         my %lt=&Apache::lonlocal::texthash(
 2086:                     'cs'   => "Authoring Space",
 2087:                     'act'  => "Activate",
 2088:                     'rol'  => "Role",
 2089:                     'ext'  => "Extent",
 2090:                     'sta'  => "Start",
 2091:                     'end'  => "End",
 2092:                     'cau'  => "Co-Author",
 2093:                     'caa'  => "Assistant Co-Author",
 2094:                     'ssd'  => "Set Start Date",
 2095:                     'sed'  => "Set End Date"
 2096:                                        );
 2097:         $r->print('<h4>'.$lt{'cs'}.'</h4>'."\n".
 2098:                   &Apache::loncommon::start_data_table()."\n".
 2099:                   &Apache::loncommon::start_data_table_header_row()."\n".
 2100:                   '<th>'.$lt{'act'}.'</th><th>'.$lt{'rol'}.'</th>'.
 2101:                   '<th>'.$lt{'ext'}.'</th><th>'.$lt{'sta'}.'</th>'.
 2102:                   '<th>'.$lt{'end'}.'</th>'."\n".
 2103:                   &Apache::loncommon::end_data_table_header_row()."\n".
 2104:                   &Apache::loncommon::start_data_table_row().'
 2105:            <td>
 2106:             <input type="checkbox" name="act_'.$cudom.'_'.$cuname.'_ca" />
 2107:            </td>
 2108:            <td>'.$lt{'cau'}.'</td>
 2109:            <td>'.$cudom.'_'.$cuname.'</td>
 2110:            <td><input type="hidden" name="start_'.$cudom.'_'.$cuname.'_ca" value="" />
 2111:              <a href=
 2112: "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>
 2113: <td><input type="hidden" name="end_'.$cudom.'_'.$cuname.'_ca" value="" />
 2114: <a href=
 2115: "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".
 2116:               &Apache::loncommon::end_data_table_row()."\n".
 2117:               &Apache::loncommon::start_data_table_row()."\n".
 2118: '<td><input type="checkbox" name="act_'.$cudom.'_'.$cuname.'_aa" /></td>
 2119: <td>'.$lt{'caa'}.'</td>
 2120: <td>'.$cudom.'_'.$cuname.'</td>
 2121: <td><input type="hidden" name="start_'.$cudom.'_'.$cuname.'_aa" value="" />
 2122: <a href=
 2123: "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>
 2124: <td><input type="hidden" name="end_'.$cudom.'_'.$cuname.'_aa" value="" />
 2125: <a href=
 2126: "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".
 2127:              &Apache::loncommon::end_data_table_row()."\n".
 2128:              &Apache::loncommon::end_data_table());
 2129:     } elsif ($env{'request.role'} =~ /^au\./) {
 2130:         if (!(&Apache::lonuserutils::authorpriv($env{'user.name'},
 2131:                                                 $env{'request.role.domain'}))) {
 2132:             $r->print('<span class="LC_error">'.
 2133:                       &mt('You do not have privileges to assign co-author roles.').
 2134:                       '</span>');
 2135:         } elsif (($env{'user.name'} eq $ccuname) &&
 2136:              ($env{'user.domain'} eq $ccdomain)) {
 2137:             $r->print(&mt('Assigning yourself a co-author or assistant co-author role in your own author area in Authoring Space is not permitted'));
 2138:         }
 2139:     }
 2140:     return $addrolesdisplay;;
 2141: }
 2142: 
 2143: sub new_domain_roles {
 2144:     my ($r,$ccdomain) = @_;
 2145:     my $addrolesdisplay = 0;
 2146:     #
 2147:     # Domain level
 2148:     #
 2149:     my $num_domain_level = 0;
 2150:     my $domaintext =
 2151:     '<h4>'.&mt('Domain Level').'</h4>'.
 2152:     &Apache::loncommon::start_data_table().
 2153:     &Apache::loncommon::start_data_table_header_row().
 2154:     '<th>'.&mt('Activate').'</th><th>'.&mt('Role').'</th><th>'.
 2155:     &mt('Extent').'</th>'.
 2156:     '<th>'.&mt('Start').'</th><th>'.&mt('End').'</th>'.
 2157:     &Apache::loncommon::end_data_table_header_row();
 2158:     my @allroles = &Apache::lonuserutils::roles_by_context('domain');
 2159:     my $uprimary = &Apache::lonnet::domain($env{'request.role.domain'},'primary');
 2160:     my $uintdom = &Apache::lonnet::internet_dom($uprimary);
 2161:     foreach my $thisdomain (sort(&Apache::lonnet::all_domains())) {
 2162:         foreach my $role (@allroles) {
 2163:             next if ($role eq 'ad');
 2164:             next if (($role eq 'au') && ($ccdomain ne $thisdomain));
 2165:             if (&Apache::lonnet::allowed('c'.$role,$thisdomain)) {
 2166:                if ($role eq 'dc') {
 2167:                    unless ($thisdomain eq $env{'request.role.domain'}) {
 2168:                        my $domprim = &Apache::lonnet::domain($thisdomain,'primary');
 2169:                        my $intdom = &Apache::lonnet::internet_dom($domprim);
 2170:                        next unless ($uintdom eq $intdom);
 2171:                    }
 2172:                }
 2173:                my $plrole=&Apache::lonnet::plaintext($role);
 2174:                my %lt=&Apache::lonlocal::texthash(
 2175:                     'ssd'  => "Set Start Date",
 2176:                     'sed'  => "Set End Date"
 2177:                                        );
 2178:                $num_domain_level ++;
 2179:                $domaintext .=
 2180: &Apache::loncommon::start_data_table_row().
 2181: '<td><input type="checkbox" name="act_'.$thisdomain.'_'.$role.'" /></td>
 2182: <td>'.$plrole.'</td>
 2183: <td>'.$thisdomain.'</td>
 2184: <td><input type="hidden" name="start_'.$thisdomain.'_'.$role.'" value="" />
 2185: <a href=
 2186: "javascript:pjump('."'date_start','Start Date $plrole',document.cu.start_$thisdomain\_$role.value,'start_$thisdomain\_$role','cu.pres','dateset'".')">'.$lt{'ssd'}.'</a></td>
 2187: <td><input type="hidden" name="end_'.$thisdomain.'_'.$role.'" value="" />
 2188: <a href=
 2189: "javascript:pjump('."'date_end','End Date $plrole',document.cu.end_$thisdomain\_$role.value,'end_$thisdomain\_$role','cu.pres','dateset'".')">'.$lt{'sed'}.'</a></td>'.
 2190: &Apache::loncommon::end_data_table_row();
 2191:             }
 2192:         }
 2193:     }
 2194:     $domaintext.= &Apache::loncommon::end_data_table();
 2195:     if ($num_domain_level > 0) {
 2196:         $r->print($domaintext);
 2197:         $addrolesdisplay = 1;
 2198:     }
 2199:     return $addrolesdisplay;
 2200: }
 2201: 
 2202: sub user_authentication {
 2203:     my ($ccuname,$ccdomain,$formname,$crstype,$permission) = @_;
 2204:     my $currentauth=&Apache::lonnet::queryauthenticate($ccuname,$ccdomain);
 2205:     my $outcome;
 2206:     my %lt=&Apache::lonlocal::texthash(
 2207:                    'err'   => "ERROR",
 2208:                    'uuas'  => "This user has an unrecognized authentication scheme",
 2209:                    'adcs'  => "Please alert a domain coordinator of this situation",
 2210:                    'sldb'  => "Please specify login data below",
 2211:                    'ld'    => "Login Data"
 2212:     );
 2213:     # Check for a bad authentication type
 2214:     if ($currentauth !~ /^(krb4|krb5|unix|internal|localauth|lti):/) {
 2215:         # bad authentication scheme
 2216:         if (&Apache::lonnet::allowed('mau',$ccdomain)) {
 2217:             &initialize_authen_forms($ccdomain,$formname);
 2218: 
 2219:             my $choices = &Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc);
 2220:             $outcome = <<ENDBADAUTH;
 2221: <script type="text/javascript" language="Javascript">
 2222: // <![CDATA[
 2223: $loginscript
 2224: // ]]>
 2225: </script>
 2226: <span class="LC_error">$lt{'err'}:
 2227: $lt{'uuas'} ($currentauth). $lt{'sldb'}.</span>
 2228: <h3>$lt{'ld'}</h3>
 2229: $choices
 2230: ENDBADAUTH
 2231:         } else {
 2232:             # This user is not allowed to modify the user's
 2233:             # authentication scheme, so just notify them of the problem
 2234:             $outcome = <<ENDBADAUTH;
 2235: <span class="LC_error"> $lt{'err'}: 
 2236: $lt{'uuas'} ($currentauth). $lt{'adcs'}.
 2237: </span>
 2238: ENDBADAUTH
 2239:         }
 2240:     } else { # Authentication type is valid
 2241:         
 2242:         &initialize_authen_forms($ccdomain,$formname,$currentauth,'modifyuser');
 2243:         my ($authformcurrent,$can_modify,@authform_others) =
 2244:             &modify_login_block($ccdomain,$currentauth);
 2245:         if (&Apache::lonnet::allowed('mau',$ccdomain)) {
 2246:             # Current user has login modification privileges
 2247:             $outcome =
 2248:                        '<script type="text/javascript" language="Javascript">'."\n".
 2249:                        '// <![CDATA['."\n".
 2250:                        $loginscript."\n".
 2251:                        '// ]]>'."\n".
 2252:                        '</script>'."\n".
 2253:                        '<h3>'.$lt{'ld'}.'</h3>'.
 2254:                        &Apache::loncommon::start_data_table().
 2255:                        &Apache::loncommon::start_data_table_row().
 2256:                        '<td>'.$authformnop;
 2257:             if (($can_modify) && (&Apache::lonnet::allowed('mau',$ccdomain))) {
 2258:                 $outcome .= '</td>'."\n".
 2259:                             &Apache::loncommon::end_data_table_row().
 2260:                             &Apache::loncommon::start_data_table_row().
 2261:                             '<td>'.$authformcurrent.'</td>'.
 2262:                             &Apache::loncommon::end_data_table_row()."\n";
 2263:             } else {
 2264:                 $outcome .= '&nbsp;('.$authformcurrent.')</td>'.
 2265:                             &Apache::loncommon::end_data_table_row()."\n";
 2266:             }
 2267:             if (&Apache::lonnet::allowed('mau',$ccdomain)) {
 2268:                 foreach my $item (@authform_others) { 
 2269:                     $outcome .= &Apache::loncommon::start_data_table_row().
 2270:                                 '<td>'.$item.'</td>'.
 2271:                                 &Apache::loncommon::end_data_table_row()."\n";
 2272:                 }
 2273:             }
 2274:             $outcome .= &Apache::loncommon::end_data_table();
 2275:         } else {
 2276:             if (($currentauth =~ /^internal:/) &&
 2277:                 (&Apache::lonuserutils::can_change_internalpass($ccuname,$ccdomain,$crstype,$permission))) {
 2278:                 $outcome = <<"ENDJS";
 2279: <script type="text/javascript">
 2280: // <![CDATA[
 2281: function togglePwd(form) {
 2282:     if (form.newintpwd.length) {
 2283:         if (document.getElementById('LC_ownersetpwd')) {
 2284:             for (var i=0; i<form.newintpwd.length; i++) {
 2285:                 if (form.newintpwd[i].checked) {
 2286:                     if (form.newintpwd[i].value == 1) {
 2287:                         document.getElementById('LC_ownersetpwd').style.display = 'inline-block';
 2288:                     } else {
 2289:                         document.getElementById('LC_ownersetpwd').style.display = 'none';
 2290:                     }
 2291:                 }
 2292:             }
 2293:         }
 2294:     }
 2295: }
 2296: // ]]>
 2297: </script>
 2298: ENDJS
 2299: 
 2300:                 $outcome .= '<h3>'.$lt{'ld'}.'</h3>'.
 2301:                             &Apache::loncommon::start_data_table().
 2302:                             &Apache::loncommon::start_data_table_row().
 2303:                             '<td>'.&mt('Internally authenticated').'<br />'.&mt("Change user's password?").
 2304:                             '<label><input type="radio" name="newintpwd" value="0" checked="checked" onclick="togglePwd(this.form);" />'.
 2305:                             &mt('No').'</label>'.('&nbsp;'x2).
 2306:                             '<label><input type="radio" name="newintpwd" value="1" onclick="togglePwd(this.form);" />'.&mt('Yes').'</label>'.
 2307:                             '<div id="LC_ownersetpwd" style="display:none">'.
 2308:                             '&nbsp;&nbsp;'.&mt('Password').' <input type="password" size="15" name="intarg" value="" />'.
 2309:                             '<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>'.
 2310:                             &Apache::loncommon::end_data_table_row().
 2311:                             &Apache::loncommon::end_data_table();
 2312:             }
 2313:             if (&Apache::lonnet::allowed('udp',$ccdomain)) {
 2314:                 # Current user has rights to view domain preferences for user's domain
 2315:                 my $result;
 2316:                 if ($currentauth =~ /^krb(4|5):([^:]*)$/) {
 2317:                     my ($krbver,$krbrealm) = ($1,$2);
 2318:                     if ($krbrealm eq '') {
 2319:                         $result = &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
 2320:                     } else {
 2321:                         $result = &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
 2322:                                       $krbrealm,$krbver);
 2323:                     }
 2324:                 } elsif ($currentauth =~ /^internal:/) {
 2325:                     $result = &mt('Currently internally authenticated.');
 2326:                 } elsif ($currentauth =~ /^localauth:/) {
 2327:                     $result = &mt('Currently using local (institutional) authentication.');
 2328:                 } elsif ($currentauth =~ /^unix:/) {
 2329:                     $result = &mt('Currently Filesystem Authenticated.');
 2330:                 } elsif ($currentauth =~ /^lti:/) {
 2331:                     $result = &mt('Currently LTI authenticated.');
 2332:                 }
 2333:                 $outcome = '<h3>'.$lt{'ld'}.'</h3>'.
 2334:                            &Apache::loncommon::start_data_table().
 2335:                            &Apache::loncommon::start_data_table_row().
 2336:                            '<td>'.$result.'</td>'.
 2337:                            &Apache::loncommon::end_data_table_row()."\n".
 2338:                            &Apache::loncommon::end_data_table();
 2339:             } elsif (&Apache::lonnet::allowed('mau',$env{'request.role.domain'})) {
 2340:                 my %lt=&Apache::lonlocal::texthash(
 2341:                            'ccld'  => "Change Current Login Data",
 2342:                            'yodo'  => "You do not have privileges to modify the authentication configuration for this user.",
 2343:                            'ifch'  => "If a change is required, contact a domain coordinator for the domain",
 2344:                 );
 2345:                 $outcome .= <<ENDNOPRIV;
 2346: <h3>$lt{'ccld'}</h3>
 2347: $lt{'yodo'} $lt{'ifch'}: $ccdomain
 2348: <input type="hidden" name="login" value="nochange" />
 2349: ENDNOPRIV
 2350:             }
 2351:         }
 2352:     }  ## End of "check for bad authentication type" logic
 2353:     return $outcome;
 2354: }
 2355: 
 2356: sub modify_login_block {
 2357:     my ($dom,$currentauth) = @_;
 2358:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 2359:     my ($authnum,%can_assign) =
 2360:         &Apache::loncommon::get_assignable_auth($dom);
 2361:     my ($authformcurrent,@authform_others,$show_override_msg);
 2362:     if ($currentauth=~/^krb(4|5):/) {
 2363:         $authformcurrent=$authformkrb;
 2364:         if ($can_assign{'int'}) {
 2365:             push(@authform_others,$authformint);
 2366:         }
 2367:         if ($can_assign{'loc'}) {
 2368:             push(@authform_others,$authformloc);
 2369:         }
 2370:         if ($can_assign{'lti'}) {
 2371:             push(@authform_others,$authformlti);
 2372:         }
 2373:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2374:             $show_override_msg = 1;
 2375:         }
 2376:     } elsif ($currentauth=~/^internal:/) {
 2377:         $authformcurrent=$authformint;
 2378:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2379:             push(@authform_others,$authformkrb);
 2380:         }
 2381:         if ($can_assign{'loc'}) {
 2382:             push(@authform_others,$authformloc);
 2383:         }
 2384:         if ($can_assign{'lti'}) {
 2385:             push(@authform_others,$authformlti);
 2386:         }
 2387:         if ($can_assign{'int'}) {
 2388:             $show_override_msg = 1;
 2389:         }
 2390:     } elsif ($currentauth=~/^unix:/) {
 2391:         $authformcurrent=$authformfsys;
 2392:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2393:             push(@authform_others,$authformkrb);
 2394:         }
 2395:         if ($can_assign{'int'}) {
 2396:             push(@authform_others,$authformint);
 2397:         }
 2398:         if ($can_assign{'loc'}) {
 2399:             push(@authform_others,$authformloc);
 2400:         }
 2401:         if ($can_assign{'lti'}) {
 2402:             push(@authform_others,$authformlti);
 2403:         }
 2404:         if ($can_assign{'fsys'}) {
 2405:             $show_override_msg = 1;
 2406:         }
 2407:     } elsif ($currentauth=~/^localauth:/) {
 2408:         $authformcurrent=$authformloc;
 2409:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2410:             push(@authform_others,$authformkrb);
 2411:         }
 2412:         if ($can_assign{'int'}) {
 2413:             push(@authform_others,$authformint);
 2414:         }
 2415:         if ($can_assign{'lti'}) {
 2416:             push(@authform_others,$authformlti);
 2417:         }
 2418:         if ($can_assign{'loc'}) {
 2419:             $show_override_msg = 1;
 2420:         }
 2421:     } elsif ($currentauth=~/^lti:/) {
 2422:         $authformcurrent=$authformlti;
 2423:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2424:             push(@authform_others,$authformkrb);
 2425:         }
 2426:         if ($can_assign{'int'}) {
 2427:             push(@authform_others,$authformint);
 2428:         }
 2429:         if ($can_assign{'loc'}) {
 2430:             push(@authform_others,$authformloc);
 2431:         }
 2432:     }
 2433:     if ($show_override_msg) {
 2434:         $authformcurrent = '<table><tr><td colspan="3">'.$authformcurrent.
 2435:                            '</td></tr>'."\n".
 2436:                            '<tr><td>&nbsp;&nbsp;&nbsp;</td>'.
 2437:                            '<td><b>'.&mt('Currently in use').'</b></td>'.
 2438:                            '<td align="right"><span class="LC_cusr_emph">'.
 2439:                             &mt('will override current values').
 2440:                             '</span></td></tr></table>';
 2441:     }
 2442:     return ($authformcurrent,$show_override_msg,@authform_others); 
 2443: }
 2444: 
 2445: sub personal_data_display {
 2446:     my ($ccuname,$ccdomain,$newuser,$context,$inst_results,$rolesarray,$now,
 2447:         $captchaform,$emailusername,$usertype,$usernameset,$condition,$excluded,$showsubmit) = @_;
 2448:     my ($output,%userenv,%canmodify,%canmodify_status);
 2449:     my @userinfo = ('firstname','middlename','lastname','generation',
 2450:                     'permanentemail','id');
 2451:     my $rowcount = 0;
 2452:     my $editable = 0;
 2453:     my %textboxsize = (
 2454:                        firstname      => '15',
 2455:                        middlename     => '15',
 2456:                        lastname       => '15',
 2457:                        generation     => '5',
 2458:                        permanentemail => '25',
 2459:                        id             => '15',
 2460:                       );
 2461: 
 2462:     my %lt=&Apache::lonlocal::texthash(
 2463:                 'pd'             => "Personal Data",
 2464:                 'firstname'      => "First Name",
 2465:                 'middlename'     => "Middle Name",
 2466:                 'lastname'       => "Last Name",
 2467:                 'generation'     => "Generation",
 2468:                 'permanentemail' => "Permanent e-mail address",
 2469:                 'id'             => "Student/Employee ID",
 2470:                 'lg'             => "Login Data",
 2471:                 'inststatus'     => "Affiliation",
 2472:                 'email'          => 'E-mail address',
 2473:                 'valid'          => 'Validation',
 2474:                 'username'       => 'Username',
 2475:     );
 2476: 
 2477:     %canmodify_status =
 2478:         &Apache::lonuserutils::can_modify_userinfo($context,$ccdomain,
 2479:                                                    ['inststatus'],$rolesarray);
 2480:     if (!$newuser) {
 2481:         # Get the users information
 2482:         %userenv = &Apache::lonnet::get('environment',
 2483:                    ['firstname','middlename','lastname','generation',
 2484:                     'permanentemail','id','inststatus'],$ccdomain,$ccuname);
 2485:         %canmodify =
 2486:             &Apache::lonuserutils::can_modify_userinfo($context,$ccdomain,
 2487:                                                        \@userinfo,$rolesarray);
 2488:     } elsif ($context eq 'selfcreate') {
 2489:         if ($newuser eq 'email') {
 2490:             if (ref($emailusername) eq 'HASH') {
 2491:                 if (ref($emailusername->{$usertype}) eq 'HASH') {
 2492:                     my ($infofields,$infotitles) = &Apache::loncommon::emailusername_info();
 2493:                     @userinfo = ();
 2494:                     if ((ref($infofields) eq 'ARRAY') && (ref($infotitles) eq 'HASH')) {
 2495:                         foreach my $field (@{$infofields}) { 
 2496:                             if ($emailusername->{$usertype}->{$field}) {
 2497:                                 push(@userinfo,$field);
 2498:                                 $canmodify{$field} = 1;
 2499:                                 unless ($textboxsize{$field}) {
 2500:                                     $textboxsize{$field} = 25;
 2501:                                 }
 2502:                                 unless ($lt{$field}) {
 2503:                                     $lt{$field} = $infotitles->{$field};
 2504:                                 }
 2505:                                 if ($emailusername->{$usertype}->{$field} eq 'required') {
 2506:                                     $lt{$field} .= '<b>*</b>';
 2507:                                 }
 2508:                             }
 2509:                         }
 2510:                     }
 2511:                 }
 2512:             }
 2513:         } else {
 2514:             %canmodify = &selfcreate_canmodify($context,$ccdomain,\@userinfo,
 2515:                                                $inst_results,$rolesarray);
 2516:         }
 2517:     }
 2518: 
 2519:     my $genhelp=&Apache::loncommon::help_open_topic('Generation');
 2520:     $output = '<h3>'.$lt{'pd'}.'</h3>'.
 2521:               &Apache::lonhtmlcommon::start_pick_box();
 2522:     if (($context eq 'selfcreate') && ($newuser eq 'email')) {
 2523:         my $size = 25;
 2524:         if ($condition) {
 2525:             if ($condition =~ /^\@[^\@]+$/) {
 2526:                 $size = 10;
 2527:             } else {
 2528:                 undef($condition);
 2529:             }
 2530:         } 
 2531:         if ($excluded) {
 2532:             unless ($excluded =~ /^\@[^\@]+$/) {
 2533:                 undef($condition);
 2534:             }
 2535:         }
 2536:         $output .= &Apache::lonhtmlcommon::row_title($lt{'email'}.'<b>*</b>',undef,
 2537:                                                      'LC_oddrow_value')."\n".
 2538:                    '<input type="text" name="uname" size="'.$size.'" value="" autocomplete="off" />';
 2539:         if ($condition) {
 2540:             $output .= $condition;
 2541:         } elsif ($excluded) {
 2542:             $output .= '<br /><span style="font-size: smaller">'.&mt('You must use an e-mail address that does not end with [_1]',
 2543:                                                                      $excluded).'</span>';
 2544:         }
 2545:         if ($usernameset eq 'first') {
 2546:             $output .= '<br /><span style="font-size: smaller">';
 2547:             if ($condition) {
 2548:                 $output .= &mt('Your username in LON-CAPA will be the part of your e-mail address before [_1]',
 2549:                                       $condition);
 2550:             } else {
 2551:                 $output .= &mt('Your username in LON-CAPA will be the part of your e-mail address before the @');
 2552:             }
 2553:             $output .= '</span>';
 2554:         }
 2555:         $rowcount ++;
 2556:         $output .= &Apache::lonhtmlcommon::row_closure(1);
 2557:         my $upassone = '<input type="password" name="upass'.$now.'" size="20" autocomplete="new-password" />';
 2558:         my $upasstwo = '<input type="password" name="upasscheck'.$now.'" size="20" autocomplete="new-password" />';
 2559:         $output .= &Apache::lonhtmlcommon::row_title(&mt('Password').'<b>*</b>',
 2560:                                                     'LC_pick_box_title',
 2561:                                                     'LC_oddrow_value')."\n".
 2562:                    $upassone."\n".
 2563:                    &Apache::lonhtmlcommon::row_closure(1)."\n".
 2564:                    &Apache::lonhtmlcommon::row_title(&mt('Confirm password').'<b>*</b>',
 2565:                                                      'LC_pick_box_title',
 2566:                                                      'LC_oddrow_value')."\n".
 2567:                    $upasstwo.
 2568:                    &Apache::lonhtmlcommon::row_closure()."\n";
 2569:         if ($usernameset eq 'free') {
 2570:             my $onclick = "toggleUsernameDisp(this,'selfcreateusername');"; 
 2571:             $output .= &Apache::lonhtmlcommon::row_title($lt{'username'},undef,'LC_oddrow_value')."\n".
 2572:                        '<span class="LC_nobreak">'.&mt('Use e-mail address: ').
 2573:                        '<label><input type="radio" name="emailused" value="1" checked="checked" onclick="'.$onclick.'" />'.
 2574:                        &mt('Yes').'</label>'.('&nbsp;'x2).
 2575:                        '<label><input type="radio" name="emailused" value="0" onclick="'.$onclick.'" />'.
 2576:                        &mt('No').'</label></span>'."\n".
 2577:                        '<div id="selfcreateusername" style="display: none; font-size: smaller">'.
 2578:                        '<br /><span class="LC_nobreak">'.&mt('Preferred username').
 2579:                        '&nbsp;<input type="text" name="username" value="" size="20" autocomplete="off"/>'.
 2580:                        '</span></div>'."\n".&Apache::lonhtmlcommon::row_closure(1);
 2581:             $rowcount ++;
 2582:         }
 2583:     }
 2584:     foreach my $item (@userinfo) {
 2585:         my $rowtitle = $lt{$item};
 2586:         my $hiderow = 0;
 2587:         if ($item eq 'generation') {
 2588:             $rowtitle = $genhelp.$rowtitle;
 2589:         }
 2590:         my $row = &Apache::lonhtmlcommon::row_title($rowtitle,undef,'LC_oddrow_value')."\n";
 2591:         if ($newuser) {
 2592:             if (ref($inst_results) eq 'HASH') {
 2593:                 if ($inst_results->{$item} ne '') {
 2594:                     $row .= '<input type="hidden" name="c'.$item.'" value="'.$inst_results->{$item}.'" />'.$inst_results->{$item};
 2595:                 } else {
 2596:                     if ($context eq 'selfcreate') {
 2597:                         if ($canmodify{$item}) {
 2598:                             $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="" autocomplete="off" />';
 2599:                             $editable ++;
 2600:                         } else {
 2601:                             $hiderow = 1;
 2602:                         }
 2603:                     } else {
 2604:                         $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="" />';
 2605:                     }
 2606:                 }
 2607:             } else {
 2608:                 if ($context eq 'selfcreate') {
 2609:                     if ($canmodify{$item}) {
 2610:                         if ($newuser eq 'email') {
 2611:                             $row .= '<input type="text" name="'.$item.'" size="'.$textboxsize{$item}.'" value="" autocomplete="off" />';
 2612:                         } else {
 2613:                             $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="" autocomplete="off" />';
 2614:                         }
 2615:                         $editable ++;
 2616:                     } else {
 2617:                         $hiderow = 1;
 2618:                     }
 2619:                 } else {
 2620:                     $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="" />';
 2621:                 }
 2622:             }
 2623:         } else {
 2624:             if ($canmodify{$item}) {
 2625:                 $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="'.$userenv{$item}.'" />';
 2626:                 if (($item eq 'id') && (!$newuser)) {
 2627:                     $row .= '<br />'.&Apache::lonuserutils::forceid_change($context);
 2628:                 }
 2629:             } else {
 2630:                 $row .= $userenv{$item};
 2631:             }
 2632:         }
 2633:         $row .= &Apache::lonhtmlcommon::row_closure(1);
 2634:         if (!$hiderow) {
 2635:             $output .= $row;
 2636:             $rowcount ++;
 2637:         }
 2638:     }
 2639:     if (($canmodify_status{'inststatus'}) || ($context ne 'selfcreate')) {
 2640:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($ccdomain);
 2641:         if (ref($types) eq 'ARRAY') {
 2642:             if (@{$types} > 0) {
 2643:                 my ($hiderow,$shown);
 2644:                 if ($canmodify_status{'inststatus'}) {
 2645:                     $shown = &pick_inst_statuses($userenv{'inststatus'},$usertypes,$types);
 2646:                 } else {
 2647:                     if ($userenv{'inststatus'} eq '') {
 2648:                         $hiderow = 1;
 2649:                     } else {
 2650:                         my @showitems;
 2651:                         foreach my $item ( map { &unescape($_); } split(':',$userenv{'inststatus'})) {
 2652:                             if (exists($usertypes->{$item})) {
 2653:                                 push(@showitems,$usertypes->{$item});
 2654:                             } else {
 2655:                                 push(@showitems,$item);
 2656:                             }
 2657:                         }
 2658:                         if (@showitems) {
 2659:                             $shown = join(', ',@showitems);
 2660:                         } else {
 2661:                             $hiderow = 1;
 2662:                         }
 2663:                     }
 2664:                 }
 2665:                 if (!$hiderow) {
 2666:                     my $row = &Apache::lonhtmlcommon::row_title(&mt('Affiliations'),undef,'LC_oddrow_value')."\n".
 2667:                               $shown.&Apache::lonhtmlcommon::row_closure(1); 
 2668:                     if ($context eq 'selfcreate') {
 2669:                         $rowcount ++;
 2670:                     }
 2671:                     $output .= $row;
 2672:                 }
 2673:             }
 2674:         }
 2675:     }
 2676:     if (($context eq 'selfcreate') && ($newuser eq 'email')) {
 2677:         if ($captchaform) {
 2678:             $output .= &Apache::lonhtmlcommon::row_title($lt{'valid'}.'*',
 2679:                                                          'LC_pick_box_title')."\n".
 2680:                        $captchaform."\n".'<br /><br />'.
 2681:                        &Apache::lonhtmlcommon::row_closure(1); 
 2682:             $rowcount ++;
 2683:         }
 2684:         if ($showsubmit) {
 2685:             my $submit_text = &mt('Create account');
 2686:             $output .= &Apache::lonhtmlcommon::row_title()."\n".
 2687:                        '<br /><input type="submit" name="createaccount" value="'.
 2688:                        $submit_text.'" />';
 2689:             if ($usertype ne '') {
 2690:                 $output .= '<input type="hidden" name="type" value="'.
 2691:                            &HTML::Entities::encode($usertype,'\'<>"&').'" />';
 2692:             }
 2693:             $output .= &Apache::lonhtmlcommon::row_closure(1);
 2694:         }
 2695:     }
 2696:     $output .= &Apache::lonhtmlcommon::end_pick_box();
 2697:     if (wantarray) {
 2698:         if ($context eq 'selfcreate') {
 2699:             return($output,$rowcount,$editable);
 2700:         } else {
 2701:             return $output;
 2702:         }
 2703:     } else {
 2704:         return $output;
 2705:     }
 2706: }
 2707: 
 2708: sub pick_inst_statuses {
 2709:     my ($curr,$usertypes,$types) = @_;
 2710:     my ($output,$rem,@currtypes);
 2711:     if ($curr ne '') {
 2712:         @currtypes = map { &unescape($_); } split(/:/,$curr);
 2713:     }
 2714:     my $numinrow = 2;
 2715:     if (ref($types) eq 'ARRAY') {
 2716:         $output = '<table>';
 2717:         my $lastcolspan; 
 2718:         for (my $i=0; $i<@{$types}; $i++) {
 2719:             if (defined($usertypes->{$types->[$i]})) {
 2720:                 my $rem = $i%($numinrow);
 2721:                 if ($rem == 0) {
 2722:                     if ($i<@{$types}-1) {
 2723:                         if ($i > 0) { 
 2724:                             $output .= '</tr>';
 2725:                         }
 2726:                         $output .= '<tr>';
 2727:                     }
 2728:                 } elsif ($i==@{$types}-1) {
 2729:                     my $colsleft = $numinrow - $rem;
 2730:                     if ($colsleft > 1) {
 2731:                         $lastcolspan = ' colspan="'.$colsleft.'"';
 2732:                     }
 2733:                 }
 2734:                 my $check = ' ';
 2735:                 if (grep(/^\Q$types->[$i]\E$/,@currtypes)) {
 2736:                     $check = ' checked="checked" ';
 2737:                 }
 2738:                 $output .= '<td class="LC_left_item"'.$lastcolspan.'>'.
 2739:                            '<span class="LC_nobreak"><label>'.
 2740:                            '<input type="checkbox" name="inststatus" '.
 2741:                            'value="'.$types->[$i].'"'.$check.'/>'.
 2742:                            $usertypes->{$types->[$i]}.'</label></span></td>';
 2743:             }
 2744:         }
 2745:         $output .= '</tr></table>';
 2746:     }
 2747:     return $output;
 2748: }
 2749: 
 2750: sub selfcreate_canmodify {
 2751:     my ($context,$dom,$userinfo,$inst_results,$rolesarray) = @_;
 2752:     if (ref($inst_results) eq 'HASH') {
 2753:         my @inststatuses = &get_inststatuses($inst_results);
 2754:         if (@inststatuses == 0) {
 2755:             @inststatuses = ('default');
 2756:         }
 2757:         $rolesarray = \@inststatuses;
 2758:     }
 2759:     my %canmodify =
 2760:         &Apache::lonuserutils::can_modify_userinfo($context,$dom,$userinfo,
 2761:                                                    $rolesarray);
 2762:     return %canmodify;
 2763: }
 2764: 
 2765: sub get_inststatuses {
 2766:     my ($insthashref) = @_;
 2767:     my @inststatuses = ();
 2768:     if (ref($insthashref) eq 'HASH') {
 2769:         if (ref($insthashref->{'inststatus'}) eq 'ARRAY') {
 2770:             @inststatuses = @{$insthashref->{'inststatus'}};
 2771:         }
 2772:     }
 2773:     return @inststatuses;
 2774: }
 2775: 
 2776: # ================================================================= Phase Three
 2777: sub update_user_data {
 2778:     my ($r,$context,$crstype,$brcrum,$showcredits,$permission) = @_; 
 2779:     my $uhome=&Apache::lonnet::homeserver($env{'form.ccuname'},
 2780:                                           $env{'form.ccdomain'});
 2781:     # Error messages
 2782:     my $error     = '<span class="LC_error">'.&mt('Error').': ';
 2783:     my $end       = '</span><br /><br />';
 2784:     my $rtnlink   = '<a href="javascript:backPage(document.userupdate,'.
 2785:                     "'$env{'form.prevphase'}','modify')".'" />'.
 2786:                     &mt('Return to previous page').'</a>'.
 2787:                     &Apache::loncommon::end_page();
 2788:     my $now = time;
 2789:     my $title;
 2790:     if (exists($env{'form.makeuser'})) {
 2791: 	$title='Set Privileges for New User';
 2792:     } else {
 2793:         $title='Modify User Privileges';
 2794:     }
 2795:     my $newuser = 0;
 2796:     my ($jsback,$elements) = &crumb_utilities();
 2797:     my $jscript = '<script type="text/javascript">'."\n".
 2798:                   '// <![CDATA['."\n".
 2799:                   $jsback."\n".
 2800:                   '// ]]>'."\n".
 2801:                   '</script>'."\n";
 2802:     my %breadcrumb_text = &singleuser_breadcrumb($crstype,$context,$env{'form.ccdomain'});
 2803:     push (@{$brcrum},
 2804:              {href => "javascript:backPage(document.userupdate)",
 2805:               text => $breadcrumb_text{'search'},
 2806:               faq  => 282,
 2807:               bug  => 'Instructor Interface',}
 2808:              );
 2809:     if ($env{'form.prevphase'} eq 'userpicked') {
 2810:         push(@{$brcrum},
 2811:                {href => "javascript:backPage(document.userupdate,'get_user_info','select')",
 2812:                 text => $breadcrumb_text{'userpicked'},
 2813:                 faq  => 282,
 2814:                 bug  => 'Instructor Interface',});
 2815:     }
 2816:     my $helpitem = 'Course_Change_Privileges';
 2817:     if ($env{'form.action'} eq 'singlestudent') {
 2818:         $helpitem = 'Course_Add_Student';
 2819:     } elsif ($context eq 'author') {
 2820:         $helpitem = 'Author_Change_Privileges';
 2821:     } elsif ($context eq 'domain') {
 2822:         $helpitem = 'Domain_Change_Privileges';
 2823:     }
 2824:     push(@{$brcrum}, 
 2825:             {href => "javascript:backPage(document.userupdate,'$env{'form.prevphase'}','modify')",
 2826:              text => $breadcrumb_text{'modify'},
 2827:              faq  => 282,
 2828:              bug  => 'Instructor Interface',},
 2829:             {href => "/adm/createuser",
 2830:              text => "Result",
 2831:              faq  => 282,
 2832:              bug  => 'Instructor Interface',
 2833:              help => $helpitem});
 2834:     my $args = {bread_crumbs          => $brcrum,
 2835:                 bread_crumbs_component => 'User Management'};
 2836:     if ($env{'form.popup'}) {
 2837:         $args->{'no_nav_bar'} = 1;
 2838:     }
 2839:     $r->print(&Apache::loncommon::start_page($title,$jscript,$args));
 2840:     $r->print(&update_result_form($uhome));
 2841:     # Check Inputs
 2842:     if (! $env{'form.ccuname'} ) {
 2843: 	$r->print($error.&mt('No login name specified').'.'.$end.$rtnlink);
 2844: 	return;
 2845:     }
 2846:     if (  $env{'form.ccuname'} ne 
 2847: 	  &LONCAPA::clean_username($env{'form.ccuname'}) ) {
 2848: 	$r->print($error.&mt('Invalid login name.').'  '.
 2849: 		  &mt('Only letters, numbers, periods, dashes, @, and underscores are valid.').
 2850: 		  $end.$rtnlink);
 2851: 	return;
 2852:     }
 2853:     if (! $env{'form.ccdomain'}       ) {
 2854: 	$r->print($error.&mt('No domain specified').'.'.$end.$rtnlink);
 2855: 	return;
 2856:     }
 2857:     if (  $env{'form.ccdomain'} ne
 2858: 	  &LONCAPA::clean_domain($env{'form.ccdomain'}) ) {
 2859: 	$r->print($error.&mt('Invalid domain name.').'  '.
 2860: 		  &mt('Only letters, numbers, periods, dashes, and underscores are valid.').
 2861: 		  $end.$rtnlink);
 2862: 	return;
 2863:     }
 2864:     if ($uhome eq 'no_host') {
 2865:         $newuser = 1;
 2866:     }
 2867:     if (! exists($env{'form.makeuser'})) {
 2868:         # Modifying an existing user, so check the validity of the name
 2869:         if ($uhome eq 'no_host') {
 2870:             $r->print(
 2871:                 $error
 2872:                .'<p class="LC_error">'
 2873:                .&mt('Unable to determine home server for [_1] in domain [_2].',
 2874:                         '"'.$env{'form.ccuname'}.'"','"'.$env{'form.ccdomain'}.'"')
 2875:                .'</p>');
 2876:             return;
 2877:         }
 2878:     }
 2879:     # Determine authentication method and password for the user being modified
 2880:     my $amode='';
 2881:     my $genpwd='';
 2882:     if ($env{'form.login'} eq 'krb') {
 2883: 	$amode='krb';
 2884: 	$amode.=$env{'form.krbver'};
 2885: 	$genpwd=$env{'form.krbarg'};
 2886:     } elsif ($env{'form.login'} eq 'int') {
 2887: 	$amode='internal';
 2888: 	$genpwd=$env{'form.intarg'};
 2889:     } elsif ($env{'form.login'} eq 'fsys') {
 2890: 	$amode='unix';
 2891: 	$genpwd=$env{'form.fsysarg'};
 2892:     } elsif ($env{'form.login'} eq 'loc') {
 2893: 	$amode='localauth';
 2894: 	$genpwd=$env{'form.locarg'};
 2895: 	$genpwd=" " if (!$genpwd);
 2896:     } elsif ($env{'form.login'} eq 'lti') {
 2897:         $amode='lti';
 2898:         $genpwd=" ";
 2899:     } elsif (($env{'form.login'} eq 'nochange') ||
 2900:              ($env{'form.login'} eq ''        )) { 
 2901:         # There is no need to tell the user we did not change what they
 2902:         # did not ask us to change.
 2903:         # If they are creating a new user but have not specified login
 2904:         # information this will be caught below.
 2905:     } else {
 2906:             $r->print($error.&mt('Invalid login mode or password').$end.$rtnlink);
 2907:             return;
 2908:     }
 2909: 
 2910:     $r->print('<h3>'.&mt('User [_1] in domain [_2]',
 2911:                         $env{'form.ccuname'}.' ('.&Apache::loncommon::plainname($env{'form.ccuname'},
 2912:                         $env{'form.ccdomain'}).')', $env{'form.ccdomain'}).'</h3>');
 2913:     my %prog_state = &Apache::lonhtmlcommon::Create_PrgWin($r,2);
 2914: 
 2915:     my (%alerts,%rulematch,%inst_results,%curr_rules);
 2916:     my @userinfo = ('firstname','middlename','lastname','generation','permanentemail','id');
 2917:     my @usertools = ('aboutme','blog','webdav','portfolio','timezone');
 2918:     my @requestcourses = ('official','unofficial','community','textbook','placement','lti');
 2919:     my @requestauthor = ('requestauthor');
 2920:     my ($othertitle,$usertypes,$types) = 
 2921:         &Apache::loncommon::sorted_inst_types($env{'form.ccdomain'});
 2922:     my %canmodify_status =
 2923:         &Apache::lonuserutils::can_modify_userinfo($context,$env{'form.ccdomain'},
 2924:                                                    ['inststatus']);
 2925:     if ($env{'form.makeuser'}) {
 2926: 	$r->print('<h3>'.&mt('Creating new account.').'</h3>');
 2927:         # Check for the authentication mode and password
 2928:         if (! $amode || ! $genpwd) {
 2929: 	    $r->print($error.&mt('Invalid login mode or password').$end.$rtnlink);    
 2930: 	    return;
 2931: 	}
 2932:         # Determine desired host
 2933:         my $desiredhost = $env{'form.hserver'};
 2934:         if (lc($desiredhost) eq 'default') {
 2935:             $desiredhost = undef;
 2936:         } else {
 2937:             my %home_servers = 
 2938: 		&Apache::lonnet::get_servers($env{'form.ccdomain'},'library');
 2939:             if (! exists($home_servers{$desiredhost})) {
 2940:                 $r->print($error.&mt('Invalid home server specified').$end.$rtnlink);
 2941:                 return;
 2942:             }
 2943:         }
 2944:         # Check ID format
 2945:         my %checkhash;
 2946:         my %checks = ('id' => 1);
 2947:         %{$checkhash{$env{'form.ccuname'}.':'.$env{'form.ccdomain'}}} = (
 2948:             'newuser' => $newuser, 
 2949:             'id' => $env{'form.cid'},
 2950:         );
 2951:         if ($env{'form.cid'} ne '') {
 2952:             &Apache::loncommon::user_rule_check(\%checkhash,\%checks,\%alerts,
 2953:                                           \%rulematch,\%inst_results,\%curr_rules);
 2954:             if (ref($alerts{'id'}) eq 'HASH') {
 2955:                 if (ref($alerts{'id'}{$env{'form.ccdomain'}}) eq 'HASH') {
 2956:                     my $domdesc =
 2957:                         &Apache::lonnet::domain($env{'form.ccdomain'},'description');
 2958:                     if ($alerts{'id'}{$env{'form.ccdomain'}}{$env{'form.cid'}}) {
 2959:                         my $userchkmsg;
 2960:                         if (ref($curr_rules{$env{'form.ccdomain'}}) eq 'HASH') {
 2961:                             $userchkmsg  = 
 2962:                                 &Apache::loncommon::instrule_disallow_msg('id',
 2963:                                                                     $domdesc,1).
 2964:                                 &Apache::loncommon::user_rule_formats($env{'form.ccdomain'},
 2965:                                     $domdesc,$curr_rules{$env{'form.ccdomain'}}{'id'},'id');
 2966:                         }
 2967:                         $r->print($error.&mt('Invalid ID format').$end.
 2968:                                   $userchkmsg.$rtnlink);
 2969:                         return;
 2970:                     }
 2971:                 }
 2972:             }
 2973:         }
 2974:         &Apache::lonhtmlcommon::Increment_PrgWin($r, \%prog_state);
 2975: 	# Call modifyuser
 2976: 	my $result = &Apache::lonnet::modifyuser
 2977: 	    ($env{'form.ccdomain'},$env{'form.ccuname'},$env{'form.cid'},
 2978:              $amode,$genpwd,$env{'form.cfirstname'},
 2979:              $env{'form.cmiddlename'},$env{'form.clastname'},
 2980:              $env{'form.cgeneration'},undef,$desiredhost,
 2981:              $env{'form.cpermanentemail'});
 2982: 	$r->print(&mt('Generating user').': '.$result);
 2983:         $uhome = &Apache::lonnet::homeserver($env{'form.ccuname'},
 2984:                                                $env{'form.ccdomain'});
 2985:         my (%changeHash,%newcustom,%changed,%changedinfo);
 2986:         if ($uhome ne 'no_host') {
 2987:             if ($context eq 'domain') {
 2988:                 foreach my $name ('portfolio','author') {
 2989:                     if ($env{'form.custom_'.$name.'quota'} == 1) {
 2990:                         if ($env{'form.'.$name.'quota'} eq '') {
 2991:                             $newcustom{$name.'quota'} = 0;
 2992:                         } else {
 2993:                             $newcustom{$name.'quota'} = $env{'form.'.$name.'quota'};
 2994:                             $newcustom{$name.'quota'} =~ s/[^\d\.]//g;
 2995:                         }
 2996:                         if (&quota_admin($newcustom{$name.'quota'},\%changeHash,$name)) {
 2997:                             $changed{$name.'quota'} = 1;
 2998:                         }
 2999:                     }
 3000:                 }
 3001:                 foreach my $item (@usertools) {
 3002:                     if ($env{'form.custom'.$item} == 1) {
 3003:                         $newcustom{$item} = $env{'form.tools_'.$item};
 3004:                         $changed{$item} = &tool_admin($item,$newcustom{$item},
 3005:                                                      \%changeHash,'tools');
 3006:                     }
 3007:                 }
 3008:                 foreach my $item (@requestcourses) {
 3009:                     if ($env{'form.custom'.$item} == 1) {
 3010:                         $newcustom{$item} = $env{'form.crsreq_'.$item};
 3011:                         if ($env{'form.crsreq_'.$item} eq 'autolimit') {
 3012:                             $newcustom{$item} .= '=';
 3013:                             $env{'form.crsreq_'.$item.'_limit'} =~ s/\D+//g;
 3014:                             if ($env{'form.crsreq_'.$item.'_limit'}) {
 3015:                                 $newcustom{$item} .= $env{'form.crsreq_'.$item.'_limit'};
 3016:                             }
 3017:                         }
 3018:                         $changed{$item} = &tool_admin($item,$newcustom{$item},
 3019:                                                       \%changeHash,'requestcourses');
 3020:                     }
 3021:                 }
 3022:                 if ($env{'form.customrequestauthor'} == 1) {
 3023:                     $newcustom{'requestauthor'} = $env{'form.requestauthor'};
 3024:                     $changed{'requestauthor'} = &tool_admin('requestauthor',
 3025:                                                     $newcustom{'requestauthor'},
 3026:                                                     \%changeHash,'requestauthor');
 3027:                 }
 3028:             }
 3029:             if ($canmodify_status{'inststatus'}) {
 3030:                 if (exists($env{'form.inststatus'})) {
 3031:                     my @inststatuses = &Apache::loncommon::get_env_multiple('form.inststatus');
 3032:                     if (@inststatuses > 0) {
 3033:                         $changeHash{'inststatus'} = join(',',@inststatuses);
 3034:                         $changed{'inststatus'} = $changeHash{'inststatus'};
 3035:                     }
 3036:                 }
 3037:             }
 3038:             if (keys(%changed)) {
 3039:                 foreach my $item (@userinfo) {
 3040:                     $changeHash{$item}  = $env{'form.c'.$item};
 3041:                 }
 3042:                 my $chgresult =
 3043:                      &Apache::lonnet::put('environment',\%changeHash,
 3044:                                           $env{'form.ccdomain'},$env{'form.ccuname'});
 3045:             } 
 3046:         }
 3047:         $r->print('<br />'.&mt('Home Server').': '.$uhome.' '.
 3048:                   &Apache::lonnet::hostname($uhome));
 3049:     } elsif (($env{'form.login'} ne 'nochange') &&
 3050:              ($env{'form.login'} ne ''        )) {
 3051: 	# Modify user privileges
 3052:         if (! $amode || ! $genpwd) {
 3053: 	    $r->print($error.'Invalid login mode or password'.$end.$rtnlink);    
 3054: 	    return;
 3055: 	}
 3056: 	# Only allow authentication modification if the person has authority
 3057: 	if (&Apache::lonnet::allowed('mau',$env{'form.ccdomain'})) {
 3058: 	    $r->print('Modifying authentication: '.
 3059:                       &Apache::lonnet::modifyuserauth(
 3060: 		       $env{'form.ccdomain'},$env{'form.ccuname'},
 3061:                        $amode,$genpwd));
 3062:             $r->print('<br />'.&mt('Home Server').': '.&Apache::lonnet::homeserver
 3063: 		  ($env{'form.ccuname'},$env{'form.ccdomain'}));
 3064: 	} else {
 3065: 	    # Okay, this is a non-fatal error.
 3066: 	    $r->print($error.&mt('You do not have privileges to modify the authentication configuration for this user.').$end);
 3067: 	}
 3068:     } elsif (($env{'form.intarg'} ne '') &&
 3069:              (&Apache::lonnet::queryauthenticate($env{'form.ccuname'},$env{'form.ccdomain'}) =~ /^internal:/) &&
 3070:              (&Apache::lonuserutils::can_change_internalpass($env{'form.ccuname'},$env{'form.ccdomain'},$crstype,$permission))) {
 3071:         $r->print('Modifying authentication: '.
 3072:                   &Apache::lonnet::modifyuserauth(
 3073:                   $env{'form.ccdomain'},$env{'form.ccuname'},
 3074:                   'internal',$env{'form.intarg'}));
 3075:     }
 3076:     $r->rflush(); # Finish display of header before time consuming actions start
 3077:     &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state);
 3078:     ##
 3079:     my (@userroles,%userupdate,$cnum,$cdom,$defaultcredits,%namechanged);
 3080:     if ($context eq 'course') {
 3081:         ($cnum,$cdom) =
 3082:             &Apache::lonuserutils::get_course_identity();
 3083:         $crstype = &Apache::loncommon::course_type($cdom.'_'.$cnum);
 3084:         if ($showcredits) {
 3085:            $defaultcredits = &Apache::lonuserutils::get_defaultcredits($cdom,$cnum);
 3086:         }
 3087:     }
 3088:     if (! $env{'form.makeuser'} ) {
 3089:         # Check for need to change
 3090:         my %userenv = &Apache::lonnet::get
 3091:             ('environment',['firstname','middlename','lastname','generation',
 3092:              'id','permanentemail','portfolioquota','authorquota','inststatus',
 3093:              'tools.aboutme','tools.blog','tools.webdav',
 3094:              'tools.portfolio','tools.timezone',
 3095:              'requestcourses.official','requestcourses.unofficial',
 3096:              'requestcourses.community','requestcourses.textbook',
 3097:              'requestcourses.lti','requestauthor',
 3098:              'reqcrsotherdom.official','reqcrsotherdom.unofficial',
 3099:              'reqcrsotherdom.community','reqcrsotherdom.textbook',
 3100:              'reqcrsotherdom.placement'],
 3101:               $env{'form.ccdomain'},$env{'form.ccuname'});
 3102:         my ($tmp) = keys(%userenv);
 3103:         if ($tmp =~ /^(con_lost|error)/i) { 
 3104:             %userenv = ();
 3105:         }
 3106:         my $no_forceid_alert;
 3107:         # Check to see if user information can be changed
 3108:         my %domconfig =
 3109:             &Apache::lonnet::get_dom('configuration',['usermodification'],
 3110:                                      $env{'form.ccdomain'});
 3111:         my @statuses = ('active','future');
 3112:         my %roles = &Apache::lonnet::get_my_roles($env{'form.ccuname'},$env{'form.ccdomain'},'userroles',\@statuses,undef,$env{'request.role.domain'});
 3113:         my ($auname,$audom);
 3114:         if ($context eq 'author') {
 3115:             $auname = $env{'user.name'};
 3116:             $audom = $env{'user.domain'};     
 3117:         }
 3118:         foreach my $item (keys(%roles)) {
 3119:             my ($rolenum,$roledom,$role) = split(/:/,$item,-1);
 3120:             if ($context eq 'course') {
 3121:                 if ($cnum ne '' && $cdom ne '') {
 3122:                     if ($rolenum eq $cnum && $roledom eq $cdom) {
 3123:                         if (!grep(/^\Q$role\E$/,@userroles)) {
 3124:                             push(@userroles,$role);
 3125:                         }
 3126:                     }
 3127:                 }
 3128:             } elsif ($context eq 'author') {
 3129:                 if ($rolenum eq $auname && $roledom eq $audom) {
 3130:                     if (!grep(/^\Q$role\E$/,@userroles)) { 
 3131:                         push(@userroles,$role);
 3132:                     }
 3133:                 }
 3134:             }
 3135:         }
 3136:         if ($env{'form.action'} eq 'singlestudent') {
 3137:             if (!grep(/^st$/,@userroles)) {
 3138:                 push(@userroles,'st');
 3139:             }
 3140:         } else {
 3141:             # Check for course or co-author roles being activated or re-enabled
 3142:             if ($context eq 'author' || $context eq 'course') {
 3143:                 foreach my $key (keys(%env)) {
 3144:                     if ($context eq 'author') {
 3145:                         if ($key=~/^form\.act_\Q$audom\E_\Q$auname\E_([^_]+)/) {
 3146:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 3147:                                 push(@userroles,$1);
 3148:                             }
 3149:                         } elsif ($key =~/^form\.ren\:\Q$audom\E\/\Q$auname\E_([^_]+)/) {
 3150:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 3151:                                 push(@userroles,$1);
 3152:                             }
 3153:                         }
 3154:                     } elsif ($context eq 'course') {
 3155:                         if ($key=~/^form\.act_\Q$cdom\E_\Q$cnum\E_([^_]+)/) {
 3156:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 3157:                                 push(@userroles,$1);
 3158:                             }
 3159:                         } elsif ($key =~/^form\.ren\:\Q$cdom\E\/\Q$cnum\E(\/?\w*)_([^_]+)/) {
 3160:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 3161:                                 push(@userroles,$1);
 3162:                             }
 3163:                         }
 3164:                     }
 3165:                 }
 3166:             }
 3167:         }
 3168:         #Check to see if we can change personal data for the user 
 3169:         my (@mod_disallowed,@longroles);
 3170:         foreach my $role (@userroles) {
 3171:             if ($role eq 'cr') {
 3172:                 push(@longroles,'Custom');
 3173:             } else {
 3174:                 push(@longroles,&Apache::lonnet::plaintext($role,$crstype)); 
 3175:             }
 3176:         }
 3177:         my %canmodify = &Apache::lonuserutils::can_modify_userinfo($context,$env{'form.ccdomain'},\@userinfo,\@userroles);
 3178:         foreach my $item (@userinfo) {
 3179:             # Strip leading and trailing whitespace
 3180:             $env{'form.c'.$item} =~ s/(\s+$|^\s+)//g;
 3181:             if (!$canmodify{$item}) {
 3182:                 if (defined($env{'form.c'.$item})) {
 3183:                     if ($env{'form.c'.$item} ne $userenv{$item}) {
 3184:                         push(@mod_disallowed,$item);
 3185:                     }
 3186:                 }
 3187:                 $env{'form.c'.$item} = $userenv{$item};
 3188:             }
 3189:         }
 3190:         # Check to see if we can change the Student/Employee ID
 3191:         my $forceid = $env{'form.forceid'};
 3192:         my $recurseid = $env{'form.recurseid'};
 3193:         my (%alerts,%rulematch,%idinst_results,%curr_rules,%got_rules);
 3194:         my %uidhash = &Apache::lonnet::idrget($env{'form.ccdomain'},
 3195:                                             $env{'form.ccuname'});
 3196:         if (($uidhash{$env{'form.ccuname'}}) && 
 3197:             ($uidhash{$env{'form.ccuname'}}!~/error\:/) && 
 3198:             (!$forceid)) {
 3199:             if ($env{'form.cid'} ne $uidhash{$env{'form.ccuname'}}) {
 3200:                 $env{'form.cid'} = $userenv{'id'};
 3201:                 $no_forceid_alert = &mt('New student/employee ID does not match existing ID for this user.')
 3202:                                    .'<br />'
 3203:                                    .&mt("Change is not permitted without checking the 'Force ID change' checkbox on the previous page.")
 3204:                                    .'<br />'."\n";
 3205:             }
 3206:         }
 3207:         if ($env{'form.cid'} ne $userenv{'id'}) {
 3208:             my $checkhash;
 3209:             my $checks = { 'id' => 1 };
 3210:             $checkhash->{$env{'form.ccuname'}.':'.$env{'form.ccdomain'}} = 
 3211:                    { 'newuser' => $newuser,
 3212:                      'id'  => $env{'form.cid'}, 
 3213:                    };
 3214:             &Apache::loncommon::user_rule_check($checkhash,$checks,
 3215:                 \%alerts,\%rulematch,\%idinst_results,\%curr_rules,\%got_rules);
 3216:             if (ref($alerts{'id'}) eq 'HASH') {
 3217:                 if (ref($alerts{'id'}{$env{'form.ccdomain'}}) eq 'HASH') {
 3218:                    $env{'form.cid'} = $userenv{'id'};
 3219:                 }
 3220:             }
 3221:         }
 3222:         my (%quotachanged,%oldquota,%newquota,%olddefquota,%newdefquota, 
 3223:             $oldinststatus,$newinststatus,%oldisdefault,%newisdefault,%oldsettings,
 3224:             %oldsettingstext,%newsettings,%newsettingstext,@disporder,
 3225:             %oldsettingstatus,%newsettingstatus);
 3226:         @disporder = ('inststatus');
 3227:         if ($env{'request.role.domain'} eq $env{'form.ccdomain'}) {
 3228:             push(@disporder,'requestcourses','requestauthor');
 3229:         } else {
 3230:             push(@disporder,'reqcrsotherdom');
 3231:         }
 3232:         push(@disporder,('quota','tools'));
 3233:         $oldinststatus = $userenv{'inststatus'};
 3234:         foreach my $name ('portfolio','author') {
 3235:             ($olddefquota{$name},$oldsettingstatus{$name}) = 
 3236:                 &Apache::loncommon::default_quota($env{'form.ccdomain'},$oldinststatus,$name);
 3237:             ($newdefquota{$name},$newsettingstatus{$name}) = ($olddefquota{$name},$oldsettingstatus{$name});
 3238:         }
 3239:         my %canshow;
 3240:         if (&Apache::lonnet::allowed('mpq',$env{'form.ccdomain'})) {
 3241:             $canshow{'quota'} = 1;
 3242:         }
 3243:         if (&Apache::lonnet::allowed('mut',$env{'form.ccdomain'})) {
 3244:             $canshow{'tools'} = 1;
 3245:         }
 3246:         if (&Apache::lonnet::allowed('ccc',$env{'form.ccdomain'})) {
 3247:             $canshow{'requestcourses'} = 1;
 3248:         } elsif (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) {
 3249:             $canshow{'reqcrsotherdom'} = 1;
 3250:         }
 3251:         if (&Apache::lonnet::allowed('mau',$env{'form.ccdomain'})) {
 3252:             $canshow{'inststatus'} = 1;
 3253:         }
 3254:         if (&Apache::lonnet::allowed('cau',$env{'form.ccdomain'})) {
 3255:             $canshow{'requestauthor'} = 1;
 3256:         }
 3257:         my (%changeHash,%changed);
 3258:         if ($oldinststatus eq '') {
 3259:             $oldsettings{'inststatus'} = $othertitle; 
 3260:         } else {
 3261:             if (ref($usertypes) eq 'HASH') {
 3262:                 $oldsettings{'inststatus'} = join(', ',map{ $usertypes->{ &unescape($_) }; } (split(/:/,$userenv{'inststatus'})));
 3263:             } else {
 3264:                 $oldsettings{'inststatus'} = join(', ',map{ &unescape($_); } (split(/:/,$userenv{'inststatus'})));
 3265:             }
 3266:         }
 3267:         $changeHash{'inststatus'} = $userenv{'inststatus'};
 3268:         if ($canmodify_status{'inststatus'}) {
 3269:             $canshow{'inststatus'} = 1;
 3270:             if (exists($env{'form.inststatus'})) {
 3271:                 my @inststatuses = &Apache::loncommon::get_env_multiple('form.inststatus');
 3272:                 if (@inststatuses > 0) {
 3273:                     $newinststatus = join(':',map { &escape($_); } @inststatuses);
 3274:                     $changeHash{'inststatus'} = $newinststatus;
 3275:                     if ($newinststatus ne $oldinststatus) {
 3276:                         $changed{'inststatus'} = $newinststatus;
 3277:                         foreach my $name ('portfolio','author') {
 3278:                             ($newdefquota{$name},$newsettingstatus{$name}) =
 3279:                                 &Apache::loncommon::default_quota($env{'form.ccdomain'},$newinststatus,$name);
 3280:                         }
 3281:                     }
 3282:                     if (ref($usertypes) eq 'HASH') {
 3283:                         $newsettings{'inststatus'} = join(', ',map{ $usertypes->{$_}; } (@inststatuses)); 
 3284:                     } else {
 3285:                         $newsettings{'inststatus'} = join(', ',@inststatuses);
 3286:                     }
 3287:                 }
 3288:             } else {
 3289:                 $newinststatus = '';
 3290:                 $changeHash{'inststatus'} = $newinststatus;
 3291:                 $newsettings{'inststatus'} = $othertitle;
 3292:                 if ($newinststatus ne $oldinststatus) {
 3293:                     $changed{'inststatus'} = $changeHash{'inststatus'};
 3294:                     foreach my $name ('portfolio','author') {
 3295:                         ($newdefquota{$name},$newsettingstatus{$name}) =
 3296:                             &Apache::loncommon::default_quota($env{'form.ccdomain'},$newinststatus,$name);
 3297:                     }
 3298:                 }
 3299:             }
 3300:         } elsif ($context ne 'selfcreate') {
 3301:             $canshow{'inststatus'} = 1;
 3302:             $newsettings{'inststatus'} = $oldsettings{'inststatus'};
 3303:         }
 3304:         foreach my $name ('portfolio','author') {
 3305:             $changeHash{$name.'quota'} = $userenv{$name.'quota'};
 3306:         }
 3307:         if ($context eq 'domain') {
 3308:             foreach my $name ('portfolio','author') {
 3309:                 if ($userenv{$name.'quota'} ne '') {
 3310:                     $oldquota{$name} = $userenv{$name.'quota'};
 3311:                     if ($env{'form.custom_'.$name.'quota'} == 1) {
 3312:                         if ($env{'form.'.$name.'quota'} eq '') {
 3313:                             $newquota{$name} = 0;
 3314:                         } else {
 3315:                             $newquota{$name} = $env{'form.'.$name.'quota'};
 3316:                             $newquota{$name} =~ s/[^\d\.]//g;
 3317:                         }
 3318:                         if ($newquota{$name} != $oldquota{$name}) {
 3319:                             if (&quota_admin($newquota{$name},\%changeHash,$name)) {
 3320:                                 $changed{$name.'quota'} = 1;
 3321:                             }
 3322:                         }
 3323:                     } else {
 3324:                         if (&quota_admin('',\%changeHash,$name)) {
 3325:                             $changed{$name.'quota'} = 1;
 3326:                             $newquota{$name} = $newdefquota{$name};
 3327:                             $newisdefault{$name} = 1;
 3328:                         }
 3329:                     }
 3330:                 } else {
 3331:                     $oldisdefault{$name} = 1;
 3332:                     $oldquota{$name} = $olddefquota{$name};
 3333:                     if ($env{'form.custom_'.$name.'quota'} == 1) {
 3334:                         if ($env{'form.'.$name.'quota'} eq '') {
 3335:                             $newquota{$name} = 0;
 3336:                         } else {
 3337:                             $newquota{$name} = $env{'form.'.$name.'quota'};
 3338:                             $newquota{$name} =~ s/[^\d\.]//g;
 3339:                         }
 3340:                         if (&quota_admin($newquota{$name},\%changeHash,$name)) {
 3341:                             $changed{$name.'quota'} = 1;
 3342:                         }
 3343:                     } else {
 3344:                         $newquota{$name} = $newdefquota{$name};
 3345:                         $newisdefault{$name} = 1;
 3346:                     }
 3347:                 }
 3348:                 if ($oldisdefault{$name}) {
 3349:                     $oldsettingstext{'quota'}{$name} = &get_defaultquota_text($oldsettingstatus{$name});
 3350:                 }  else {
 3351:                     $oldsettingstext{'quota'}{$name} = &mt('custom quota: [_1] MB',$oldquota{$name});
 3352:                 }
 3353:                 if ($newisdefault{$name}) {
 3354:                     $newsettingstext{'quota'}{$name} = &get_defaultquota_text($newsettingstatus{$name});
 3355:                 } else {
 3356:                     $newsettingstext{'quota'}{$name} = &mt('custom quota: [_1] MB',$newquota{$name});
 3357:                 }
 3358:             }
 3359:             &tool_changes('tools',\@usertools,\%oldsettings,\%oldsettingstext,\%userenv,
 3360:                           \%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3361:             if ($env{'form.ccdomain'} eq $env{'request.role.domain'}) {
 3362:                 &tool_changes('requestcourses',\@requestcourses,\%oldsettings,\%oldsettingstext,
 3363:                               \%userenv,\%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3364:                 &tool_changes('requestauthor',\@requestauthor,\%oldsettings,\%oldsettingstext,
 3365:                               \%userenv,\%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3366:             } else {
 3367:                 &tool_changes('reqcrsotherdom',\@requestcourses,\%oldsettings,\%oldsettingstext,
 3368:                               \%userenv,\%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3369:             }
 3370:         }
 3371:         foreach my $item (@userinfo) {
 3372:             if ($env{'form.c'.$item} ne $userenv{$item}) {
 3373:                 $namechanged{$item} = 1;
 3374:             }
 3375:         }
 3376:         foreach my $name ('portfolio','author') {
 3377:             $oldsettings{'quota'}{$name} = &mt('[_1] MB',$oldquota{$name});
 3378:             $newsettings{'quota'}{$name} = &mt('[_1] MB',$newquota{$name});
 3379:         }
 3380:         if ((keys(%namechanged) > 0) || (keys(%changed) > 0)) {
 3381:             my ($chgresult,$namechgresult);
 3382:             if (keys(%changed) > 0) {
 3383:                 $chgresult = 
 3384:                     &Apache::lonnet::put('environment',\%changeHash,
 3385:                                   $env{'form.ccdomain'},$env{'form.ccuname'});
 3386:                 if ($chgresult eq 'ok') {
 3387:                     if (($env{'user.name'} eq $env{'form.ccuname'}) &&
 3388:                         ($env{'user.domain'} eq $env{'form.ccdomain'})) {
 3389:                         my %newenvhash;
 3390:                         foreach my $key (keys(%changed)) {
 3391:                             if (($key eq 'official') || ($key eq 'unofficial') ||
 3392:                                 ($key eq 'community') || ($key eq 'textbook') ||
 3393:                                 ($key eq 'placement') || ($key eq 'lti')) {
 3394:                                 $newenvhash{'environment.requestcourses.'.$key} =
 3395:                                     $changeHash{'requestcourses.'.$key};
 3396:                                 if ($changeHash{'requestcourses.'.$key}) {
 3397:                                     $newenvhash{'environment.canrequest.'.$key} = 1;
 3398:                                 } else {
 3399:                                     $newenvhash{'environment.canrequest.'.$key} =
 3400:           &Apache::lonnet::usertools_access($env{'user.name'},$env{'user.domain'},
 3401:                                             $key,'reload','requestcourses');
 3402:                                 }
 3403:                             } elsif ($key eq 'requestauthor') {
 3404:                                 $newenvhash{'environment.'.$key} = $changeHash{$key};
 3405:                                 if ($changeHash{$key}) {
 3406:                                     $newenvhash{'environment.canrequest.author'} = 1;
 3407:                                 } else {
 3408:                                     $newenvhash{'environment.canrequest.author'} =
 3409:           &Apache::lonnet::usertools_access($env{'user.name'},$env{'user.domain'},
 3410:                                             $key,'reload','requestauthor');
 3411:                                 }
 3412:                             } elsif ($key ne 'quota') {
 3413:                                 $newenvhash{'environment.tools.'.$key} = 
 3414:                                     $changeHash{'tools.'.$key};
 3415:                                 if ($changeHash{'tools.'.$key} ne '') {
 3416:                                     $newenvhash{'environment.availabletools.'.$key} =
 3417:                                         $changeHash{'tools.'.$key};
 3418:                                 } else {
 3419:                                     $newenvhash{'environment.availabletools.'.$key} =
 3420:           &Apache::lonnet::usertools_access($env{'user.name'},$env{'user.domain'},
 3421:           $key,'reload','tools');
 3422:                                 }
 3423:                             }
 3424:                         }
 3425:                         if (keys(%newenvhash)) {
 3426:                             &Apache::lonnet::appenv(\%newenvhash);
 3427:                         }
 3428:                     }
 3429:                 }
 3430:             }
 3431:             if (keys(%namechanged) > 0) {
 3432:                 foreach my $field (@userinfo) {
 3433:                     $changeHash{$field}  = $env{'form.c'.$field};
 3434:                 }
 3435: # Make the change
 3436:                 $namechgresult =
 3437:                     &Apache::lonnet::modifyuser($env{'form.ccdomain'},
 3438:                         $env{'form.ccuname'},$changeHash{'id'},undef,undef,
 3439:                         $changeHash{'firstname'},$changeHash{'middlename'},
 3440:                         $changeHash{'lastname'},$changeHash{'generation'},
 3441:                         $changeHash{'id'},undef,$changeHash{'permanentemail'},undef,\@userinfo);
 3442:                 %userupdate = (
 3443:                                lastname   => $env{'form.clastname'},
 3444:                                middlename => $env{'form.cmiddlename'},
 3445:                                firstname  => $env{'form.cfirstname'},
 3446:                                generation => $env{'form.cgeneration'},
 3447:                                id         => $env{'form.cid'},
 3448:                              );
 3449:             }
 3450:             if (((keys(%namechanged) > 0) && $namechgresult eq 'ok') || 
 3451:                 ((keys(%changed) > 0) && $chgresult eq 'ok')) {
 3452:             # Tell the user we changed the name
 3453:                 &display_userinfo($r,1,\@disporder,\%canshow,\@requestcourses,
 3454:                                   \@usertools,\@requestauthor,\%userenv,\%changed,\%namechanged,
 3455:                                   \%oldsettings, \%oldsettingstext,\%newsettings,
 3456:                                   \%newsettingstext);
 3457:                 if ($env{'form.cid'} ne $userenv{'id'}) {
 3458:                     &Apache::lonnet::idput($env{'form.ccdomain'},
 3459:                          {$env{'form.ccuname'} => $env{'form.cid'}},$uhome,'ids');
 3460:                     if (($recurseid) &&
 3461:                         (&Apache::lonnet::allowed('mau',$env{'form.ccdomain'}))) {
 3462:                         my $idresult = 
 3463:                             &Apache::lonuserutils::propagate_id_change(
 3464:                                 $env{'form.ccuname'},$env{'form.ccdomain'},
 3465:                                 \%userupdate);
 3466:                         $r->print('<br />'.$idresult.'<br />');
 3467:                     }
 3468:                 }
 3469:                 if (($env{'form.ccdomain'} eq $env{'user.domain'}) && 
 3470:                     ($env{'form.ccuname'} eq $env{'user.name'})) {
 3471:                     my %newenvhash;
 3472:                     foreach my $key (keys(%changeHash)) {
 3473:                         $newenvhash{'environment.'.$key} = $changeHash{$key};
 3474:                     }
 3475:                     &Apache::lonnet::appenv(\%newenvhash);
 3476:                 }
 3477:             } else { # error occurred
 3478:                 $r->print(
 3479:                     '<p class="LC_error">'
 3480:                    .&mt('Unable to successfully change environment for [_1] in domain [_2].',
 3481:                             '"'.$env{'form.ccuname'}.'"',
 3482:                             '"'.$env{'form.ccdomain'}.'"')
 3483:                    .'</p>');
 3484:             }
 3485:         } else { # End of if ($env ... ) logic
 3486:             # They did not want to change the users name, quota, tool availability,
 3487:             # or ability to request creation of courses, 
 3488:             # but we can still tell them what the name and quota and availabilities are  
 3489:             &display_userinfo($r,undef,\@disporder,\%canshow,\@requestcourses,
 3490:                               \@usertools,\@requestauthor,\%userenv,\%changed,\%namechanged,\%oldsettings,
 3491:                               \%oldsettingstext,\%newsettings,\%newsettingstext);
 3492:         }
 3493:         if (@mod_disallowed) {
 3494:             my ($rolestr,$contextname);
 3495:             if (@longroles > 0) {
 3496:                 $rolestr = join(', ',@longroles);
 3497:             } else {
 3498:                 $rolestr = &mt('No roles');
 3499:             }
 3500:             if ($context eq 'course') {
 3501:                 $contextname = 'course';
 3502:             } elsif ($context eq 'author') {
 3503:                 $contextname = 'co-author';
 3504:             }
 3505:             $r->print(&mt('The following fields were not updated: ').'<ul>');
 3506:             my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
 3507:             foreach my $field (@mod_disallowed) {
 3508:                 $r->print('<li>'.$fieldtitles{$field}.'</li>'."\n"); 
 3509:             }
 3510:             $r->print('</ul>');
 3511:             if (@mod_disallowed == 1) {
 3512:                 $r->print(&mt("You do not have the authority to change this field given the user's current set of active/future $contextname roles:"));
 3513:             } else {
 3514:                 $r->print(&mt("You do not have the authority to change these fields given the user's current set of active/future $contextname roles:"));
 3515:             }
 3516:             my $helplink = 'javascript:helpMenu('."'display'".')';
 3517:             $r->print('<span class="LC_cusr_emph">'.$rolestr.'</span><br />'
 3518:                      .&mt('Please contact your [_1]helpdesk[_2] for more information.'
 3519:                          ,'<a href="'.$helplink.'">','</a>')
 3520:                       .'<br />');
 3521:         }
 3522:         $r->print('<span class="LC_warning">'
 3523:                   .$no_forceid_alert
 3524:                   .&Apache::lonuserutils::print_namespacing_alerts($env{'form.ccdomain'},\%alerts,\%curr_rules)
 3525:                   .'</span>');
 3526:     }
 3527:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 3528:     if ($env{'form.action'} eq 'singlestudent') {
 3529:         &enroll_single_student($r,$uhome,$amode,$genpwd,$now,$newuser,$context,
 3530:                                $crstype,$showcredits,$defaultcredits);
 3531:         my $linktext = ($crstype eq 'Community' ?
 3532:             &mt('Enroll Another Member') : &mt('Enroll Another Student'));
 3533:         $r->print(
 3534:             &Apache::lonhtmlcommon::actionbox([
 3535:                 '<a href="javascript:backPage(document.userupdate)">'
 3536:                .($crstype eq 'Community' ? 
 3537:                     &mt('Enroll Another Member') : &mt('Enroll Another Student'))
 3538:                .'</a>']));
 3539:     } else {
 3540:         my @rolechanges = &update_roles($r,$context,$showcredits);
 3541:         if (keys(%namechanged) > 0) {
 3542:             if ($context eq 'course') {
 3543:                 if (@userroles > 0) {
 3544:                     if ((@rolechanges == 0) || 
 3545:                         (!(grep(/^st$/,@rolechanges)))) {
 3546:                         if (grep(/^st$/,@userroles)) {
 3547:                             my $classlistupdated =
 3548:                                 &Apache::lonuserutils::update_classlist($cdom,
 3549:                                               $cnum,$env{'form.ccdomain'},
 3550:                                        $env{'form.ccuname'},\%userupdate);
 3551:                         }
 3552:                     }
 3553:                 }
 3554:             }
 3555:         }
 3556:         my $userinfo = &Apache::loncommon::plainname($env{'form.ccuname'},
 3557:                                                      $env{'form.ccdomain'});
 3558:         if ($env{'form.popup'}) {
 3559:             $r->print('<p><a href="javascript:window.close()">'.&mt('Close window').'</a></p>');
 3560:         } else {
 3561:             $r->print('<br />'.&Apache::lonhtmlcommon::actionbox(['<a href="javascript:backPage(document.userupdate,'."'$env{'form.prevphase'}','modify'".')">'
 3562:                      .&mt('Modify this user: [_1]','<span class="LC_cusr_emph">'.$env{'form.ccuname'}.':'.$env{'form.ccdomain'}.' ('.$userinfo.')</span>').'</a>',
 3563:                      '<a href="javascript:backPage(document.userupdate)">'.&mt('Create/Modify Another User').'</a>']));
 3564:         }
 3565:     }
 3566: }
 3567: 
 3568: sub display_userinfo {
 3569:     my ($r,$changed,$order,$canshow,$requestcourses,$usertools,$requestauthor,
 3570:         $userenv,$changedhash,$namechangedhash,$oldsetting,$oldsettingtext,
 3571:         $newsetting,$newsettingtext) = @_;
 3572:     return unless (ref($order) eq 'ARRAY' &&
 3573:                    ref($canshow) eq 'HASH' && 
 3574:                    ref($requestcourses) eq 'ARRAY' && 
 3575:                    ref($requestauthor) eq 'ARRAY' &&
 3576:                    ref($usertools) eq 'ARRAY' && 
 3577:                    ref($userenv) eq 'HASH' &&
 3578:                    ref($changedhash) eq 'HASH' &&
 3579:                    ref($oldsetting) eq 'HASH' &&
 3580:                    ref($oldsettingtext) eq 'HASH' &&
 3581:                    ref($newsetting) eq 'HASH' &&
 3582:                    ref($newsettingtext) eq 'HASH');
 3583:     my %lt=&Apache::lonlocal::texthash(
 3584:          'ui'             => 'User Information',
 3585:          'uic'            => 'User Information Changed',
 3586:          'firstname'      => 'First Name',
 3587:          'middlename'     => 'Middle Name',
 3588:          'lastname'       => 'Last Name',
 3589:          'generation'     => 'Generation',
 3590:          'id'             => 'Student/Employee ID',
 3591:          'permanentemail' => 'Permanent e-mail address',
 3592:          'portfolioquota' => 'Disk space allocated to portfolio files',
 3593:          'authorquota'    => 'Disk space allocated to Authoring Space',
 3594:          'blog'           => 'Blog Availability',
 3595:          'webdav'         => 'WebDAV Availability',
 3596:          'aboutme'        => 'Personal Information Page Availability',
 3597:          'portfolio'      => 'Portfolio Availability',
 3598:          'timezone'       => 'Can set own Time Zone',
 3599:          'official'       => 'Can Request Official Courses',
 3600:          'unofficial'     => 'Can Request Unofficial Courses',
 3601:          'community'      => 'Can Request Communities',
 3602:          'textbook'       => 'Can Request Textbook Courses',
 3603:          'placement'      => 'Can Request Placement Tests',
 3604:          'lti'            => 'Can Request LTI Courses',
 3605:          'requestauthor'  => 'Can Request Author Role',
 3606:          'inststatus'     => "Affiliation",
 3607:          'prvs'           => 'Previous Value:',
 3608:          'chto'           => 'Changed To:'
 3609:     );
 3610:     if ($changed) {
 3611:         $r->print('<h3>'.$lt{'uic'}.'</h3>'.
 3612:                 &Apache::loncommon::start_data_table().
 3613:                 &Apache::loncommon::start_data_table_header_row());
 3614:         $r->print("<th>&nbsp;</th>\n");
 3615:         $r->print('<th><b>'.$lt{'prvs'}.'</b></th>');
 3616:         $r->print('<th><span class="LC_nobreak"><b>'.$lt{'chto'}.'</b></span></th>');
 3617:         $r->print(&Apache::loncommon::end_data_table_header_row());
 3618:         my @userinfo = ('firstname','middlename','lastname','generation','permanentemail','id');
 3619: 
 3620:         foreach my $item (@userinfo) {
 3621:             my $value = $env{'form.c'.$item};
 3622:             #show changes only:
 3623:             unless ($value eq $userenv->{$item}){
 3624:                 $r->print(&Apache::loncommon::start_data_table_row());
 3625:                 $r->print("<td>$lt{$item}</td>\n");
 3626:                 $r->print("<td>".$userenv->{$item}."</td>\n");
 3627:                 $r->print("<td>$value </td>\n");
 3628:                 $r->print(&Apache::loncommon::end_data_table_row());
 3629:             }
 3630:         }
 3631:         foreach my $entry (@{$order}) {
 3632:             if ($canshow->{$entry}) {
 3633:                 if (($entry eq 'requestcourses') || ($entry eq 'reqcrsotherdom') || ($entry eq 'requestauthor')) {
 3634:                     my @items;
 3635:                     if ($entry eq 'requestauthor') {
 3636:                         @items = ($entry);
 3637:                     } else {
 3638:                         @items = @{$requestcourses};
 3639:                     }
 3640:                     foreach my $item (@items) {
 3641:                         if (($newsetting->{$item} ne $oldsetting->{$item}) || 
 3642:                             ($newsettingtext->{$item} ne $oldsettingtext->{$item})) {
 3643:                             $r->print(&Apache::loncommon::start_data_table_row()."\n");  
 3644:                             $r->print("<td>$lt{$item}</td>\n");
 3645:                             $r->print("<td>".$oldsetting->{$item});
 3646:                             if ($oldsettingtext->{$item}) {
 3647:                                 if ($oldsetting->{$item}) {
 3648:                                     $r->print(' -- ');
 3649:                                 }
 3650:                                 $r->print($oldsettingtext->{$item});
 3651:                             }
 3652:                             $r->print("</td>\n");
 3653:                             $r->print("<td>".$newsetting->{$item});
 3654:                             if ($newsettingtext->{$item}) {
 3655:                                 if ($newsetting->{$item}) {
 3656:                                     $r->print(' -- ');
 3657:                                 }
 3658:                                 $r->print($newsettingtext->{$item});
 3659:                             }
 3660:                             $r->print("</td>\n");
 3661:                             $r->print(&Apache::loncommon::end_data_table_row()."\n");
 3662:                         }
 3663:                     }
 3664:                 } elsif ($entry eq 'tools') {
 3665:                     foreach my $item (@{$usertools}) {
 3666:                         if ($newsetting->{$item} ne $oldsetting->{$item}) {
 3667:                             $r->print(&Apache::loncommon::start_data_table_row()."\n");
 3668:                             $r->print("<td>$lt{$item}</td>\n");
 3669:                             $r->print("<td>".$oldsetting->{$item}.' '.$oldsettingtext->{$item}."</td>\n");
 3670:                             $r->print("<td>".$newsetting->{$item}.' '.$newsettingtext->{$item}."</td>\n");
 3671:                             $r->print(&Apache::loncommon::end_data_table_row()."\n");
 3672:                         }
 3673:                     }
 3674:                 } elsif ($entry eq 'quota') {
 3675:                     if ((ref($oldsetting->{$entry}) eq 'HASH') && (ref($oldsettingtext->{$entry}) eq 'HASH') &&
 3676:                         (ref($newsetting->{$entry}) eq 'HASH') && (ref($newsettingtext->{$entry}) eq 'HASH')) {
 3677:                         foreach my $name ('portfolio','author') {
 3678:                             if ($newsetting->{$entry}->{$name} ne $oldsetting->{$entry}->{$name}) {
 3679:                                 $r->print(&Apache::loncommon::start_data_table_row()."\n");
 3680:                                 $r->print("<td>$lt{$name.$entry}</td>\n");
 3681:                                 $r->print("<td>".$oldsettingtext->{$entry}->{$name}."</td>\n");
 3682:                                 $r->print("<td>".$newsettingtext->{$entry}->{$name}."</td>\n");
 3683:                                 $r->print(&Apache::loncommon::end_data_table_row()."\n");
 3684:                             }
 3685:                         }
 3686:                     }
 3687:                 } else {
 3688:                     if ($newsetting->{$entry} ne $oldsetting->{$entry}) {
 3689:                         $r->print(&Apache::loncommon::start_data_table_row()."\n");
 3690:                         $r->print("<td>$lt{$entry}</td>\n");
 3691:                         $r->print("<td>".$oldsetting->{$entry}.' '.$oldsettingtext->{$entry}."</td>\n");
 3692:                         $r->print("<td>".$newsetting->{$entry}.' '.$newsettingtext->{$entry}."</td>\n");
 3693:                         $r->print(&Apache::loncommon::end_data_table_row()."\n");
 3694:                     }
 3695:                 }
 3696:             }
 3697:         }
 3698:         $r->print(&Apache::loncommon::end_data_table().'<br />');
 3699:     } else {
 3700:         $r->print('<h3>'.$lt{'ui'}.'</h3>'.
 3701:                   '<p>'.&mt('No changes made to user information').'</p>');
 3702:     }
 3703:     return;
 3704: }
 3705: 
 3706: sub tool_changes {
 3707:     my ($context,$usertools,$oldaccess,$oldaccesstext,$userenv,$changeHash,
 3708:         $changed,$newaccess,$newaccesstext) = @_;
 3709:     if (!((ref($usertools) eq 'ARRAY') && (ref($oldaccess) eq 'HASH') &&
 3710:           (ref($oldaccesstext) eq 'HASH') && (ref($userenv) eq 'HASH') &&
 3711:           (ref($changeHash) eq 'HASH') && (ref($changed) eq 'HASH') &&
 3712:           (ref($newaccess) eq 'HASH') && (ref($newaccesstext) eq 'HASH'))) {
 3713:         return;
 3714:     }
 3715:     my %reqdisplay = &requestchange_display();
 3716:     if ($context eq 'reqcrsotherdom') {
 3717:         my @options = ('approval','validate','autolimit');
 3718:         my $optregex = join('|',@options);
 3719:         my $cdom = $env{'request.role.domain'};
 3720:         foreach my $tool (@{$usertools}) {
 3721:             $oldaccesstext->{$tool} = &mt("availability set to 'off'");
 3722:             $newaccesstext->{$tool} = $oldaccesstext->{$tool};
 3723:             $changeHash->{$context.'.'.$tool} = $userenv->{$context.'.'.$tool};
 3724:             my ($newop,$limit);
 3725:             if ($env{'form.'.$context.'_'.$tool}) {
 3726:                 $newop = $env{'form.'.$context.'_'.$tool};
 3727:                 if ($newop eq 'autolimit') {
 3728:                     $limit = $env{'form.'.$context.'_'.$tool.'_limit'};
 3729:                     $limit =~ s/\D+//g;
 3730:                     $newop .= '='.$limit;
 3731:                 }
 3732:             }
 3733:             if ($userenv->{$context.'.'.$tool} eq '') {
 3734:                 if ($newop) {
 3735:                     $changed->{$tool}=&tool_admin($tool,$cdom.':'.$newop,
 3736:                                                   $changeHash,$context);
 3737:                     if ($changed->{$tool}) {
 3738:                         if ($newop =~ /^autolimit/) {
 3739:                             if ($limit) {
 3740:                                 $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3741:                             } else {
 3742:                                 $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3743:                             }
 3744:                         } else {
 3745:                             $newaccesstext->{$tool} = $reqdisplay{$newop};
 3746:                         }
 3747:                     } else {
 3748:                         $newaccesstext->{$tool} = $oldaccesstext->{$tool};
 3749:                     }
 3750:                 }
 3751:             } else {
 3752:                 my @curr = split(',',$userenv->{$context.'.'.$tool});
 3753:                 my @new;
 3754:                 my $changedoms;
 3755:                 foreach my $req (@curr) {
 3756:                     if ($req =~ /^\Q$cdom\E\:($optregex\=?\d*)$/) {
 3757:                         my $oldop = $1;
 3758:                         if ($oldop =~ /^autolimit=(\d*)/) {
 3759:                             my $limit = $1;
 3760:                             if ($limit) {
 3761:                                 $oldaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3762:                             } else {
 3763:                                 $oldaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3764:                             }
 3765:                         } else {
 3766:                             $oldaccesstext->{$tool} = $reqdisplay{$oldop};
 3767:                         }
 3768:                         if ($oldop ne $newop) {
 3769:                             $changedoms = 1;
 3770:                             foreach my $item (@curr) {
 3771:                                 my ($reqdom,$option) = split(':',$item);
 3772:                                 unless ($reqdom eq $cdom) {
 3773:                                     push(@new,$item);
 3774:                                 }
 3775:                             }
 3776:                             if ($newop) {
 3777:                                 push(@new,$cdom.':'.$newop);
 3778:                             }
 3779:                             @new = sort(@new);
 3780:                         }
 3781:                         last;
 3782:                     }
 3783:                 }
 3784:                 if ((!$changedoms) && ($newop)) {
 3785:                     $changedoms = 1;
 3786:                     @new = sort(@curr,$cdom.':'.$newop);
 3787:                 }
 3788:                 if ($changedoms) {
 3789:                     my $newdomstr;
 3790:                     if (@new) {
 3791:                         $newdomstr = join(',',@new);
 3792:                     }
 3793:                     $changed->{$tool}=&tool_admin($tool,$newdomstr,$changeHash,
 3794:                                                   $context);
 3795:                     if ($changed->{$tool}) {
 3796:                         if ($env{'form.'.$context.'_'.$tool}) {
 3797:                             if ($env{'form.'.$context.'_'.$tool} eq 'autolimit') {
 3798:                                 my $limit = $env{'form.'.$context.'_'.$tool.'_limit'};
 3799:                                 $limit =~ s/\D+//g;
 3800:                                 if ($limit) {
 3801:                                     $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3802:                                 } else {
 3803:                                     $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3804:                                 }
 3805:                             } else {
 3806:                                 $newaccesstext->{$tool} = $reqdisplay{$env{'form.'.$context.'_'.$tool}};
 3807:                             }
 3808:                         } else {
 3809:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3810:                         }
 3811:                     }
 3812:                 }
 3813:             }
 3814:         }
 3815:         return;
 3816:     }
 3817:     foreach my $tool (@{$usertools}) {
 3818:         my ($newval,$limit,$envkey);
 3819:         $envkey = $context.'.'.$tool;
 3820:         if ($context eq 'requestcourses') {
 3821:             $newval = $env{'form.crsreq_'.$tool};
 3822:             if ($newval eq 'autolimit') {
 3823:                 $limit = $env{'form.crsreq_'.$tool.'_limit'};
 3824:                 $limit =~ s/\D+//g;
 3825:                 $newval .= '='.$limit;
 3826:             }
 3827:         } elsif ($context eq 'requestauthor') {
 3828:             $newval = $env{'form.'.$context};
 3829:             $envkey = $context;
 3830:         } else {
 3831:             $newval = $env{'form.'.$context.'_'.$tool};
 3832:         }
 3833:         if ($userenv->{$envkey} ne '') {
 3834:             $oldaccess->{$tool} = &mt('custom');
 3835:             if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 3836:                 if ($userenv->{$envkey} =~ /^autolimit=(\d*)$/) {
 3837:                     my $currlimit = $1;
 3838:                     if ($currlimit eq '') {
 3839:                         $oldaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3840:                     } else {
 3841:                         $oldaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$currlimit);
 3842:                     }
 3843:                 } elsif ($userenv->{$envkey}) {
 3844:                     $oldaccesstext->{$tool} = $reqdisplay{$userenv->{$envkey}};
 3845:                 } else {
 3846:                     $oldaccesstext->{$tool} = &mt("availability set to 'off'");
 3847:                 }
 3848:             } else {
 3849:                 if ($userenv->{$envkey}) {
 3850:                     $oldaccesstext->{$tool} = &mt("availability set to 'on'");
 3851:                 } else {
 3852:                     $oldaccesstext->{$tool} = &mt("availability set to 'off'");
 3853:                 }
 3854:             }
 3855:             $changeHash->{$envkey} = $userenv->{$envkey};
 3856:             if ($env{'form.custom'.$tool} == 1) {
 3857:                 if ($newval ne $userenv->{$envkey}) {
 3858:                     $changed->{$tool} = &tool_admin($tool,$newval,$changeHash,
 3859:                                                     $context);
 3860:                     if ($changed->{$tool}) {
 3861:                         $newaccess->{$tool} = &mt('custom');
 3862:                         if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 3863:                             if ($newval =~ /^autolimit/) {
 3864:                                 if ($limit) {
 3865:                                     $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3866:                                 } else {
 3867:                                     $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3868:                                 }
 3869:                             } elsif ($newval) {
 3870:                                 $newaccesstext->{$tool} = $reqdisplay{$newval};
 3871:                             } else {
 3872:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3873:                             }
 3874:                         } else {
 3875:                             if ($newval) {
 3876:                                 $newaccesstext->{$tool} = &mt("availability set to 'on'");
 3877:                             } else {
 3878:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3879:                             }
 3880:                         }
 3881:                     } else {
 3882:                         $newaccess->{$tool} = $oldaccess->{$tool};
 3883:                         if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 3884:                             if ($newval =~ /^autolimit/) {
 3885:                                 if ($limit) {
 3886:                                     $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3887:                                 } else {
 3888:                                     $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3889:                                 }
 3890:                             } elsif ($newval) {
 3891:                                 $newaccesstext->{$tool} = $reqdisplay{$newval};
 3892:                             } else {
 3893:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3894:                             }
 3895:                         } else {
 3896:                             if ($userenv->{$context.'.'.$tool}) {
 3897:                                 $newaccesstext->{$tool} = &mt("availability set to 'on'");
 3898:                             } else {
 3899:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3900:                             }
 3901:                         }
 3902:                     }
 3903:                 } else {
 3904:                     $newaccess->{$tool} = $oldaccess->{$tool};
 3905:                     $newaccesstext->{$tool} = $oldaccesstext->{$tool};
 3906:                 }
 3907:             } else {
 3908:                 $changed->{$tool} = &tool_admin($tool,'',$changeHash,$context);
 3909:                 if ($changed->{$tool}) {
 3910:                     $newaccess->{$tool} = &mt('default');
 3911:                 } else {
 3912:                     $newaccess->{$tool} = $oldaccess->{$tool};
 3913:                     if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 3914:                         if ($newval =~ /^autolimit/) {
 3915:                             if ($limit) {
 3916:                                 $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3917:                             } else {
 3918:                                 $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3919:                             }
 3920:                         } elsif ($newval) {
 3921:                             $newaccesstext->{$tool} = $reqdisplay{$newval};
 3922:                         } else {
 3923:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3924:                         }
 3925:                     } else {
 3926:                         if ($userenv->{$context.'.'.$tool}) {
 3927:                             $newaccesstext->{$tool} = &mt("availability set to 'on'");
 3928:                         } else {
 3929:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3930:                         }
 3931:                     }
 3932:                 }
 3933:             }
 3934:         } else {
 3935:             $oldaccess->{$tool} = &mt('default');
 3936:             if ($env{'form.custom'.$tool} == 1) {
 3937:                 $changed->{$tool} = &tool_admin($tool,$newval,$changeHash,
 3938:                                                 $context);
 3939:                 if ($changed->{$tool}) {
 3940:                     $newaccess->{$tool} = &mt('custom');
 3941:                     if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 3942:                         if ($newval =~ /^autolimit/) {
 3943:                             if ($limit) {
 3944:                                 $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3945:                             } else {
 3946:                                 $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3947:                             }
 3948:                         } elsif ($newval) {
 3949:                             $newaccesstext->{$tool} = $reqdisplay{$newval};
 3950:                         } else {
 3951:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3952:                         }
 3953:                     } else {
 3954:                         if ($newval) {
 3955:                             $newaccesstext->{$tool} = &mt("availability set to 'on'");
 3956:                         } else {
 3957:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3958:                         }
 3959:                     }
 3960:                 } else {
 3961:                     $newaccess->{$tool} = $oldaccess->{$tool};
 3962:                 }
 3963:             } else {
 3964:                 $newaccess->{$tool} = $oldaccess->{$tool};
 3965:             }
 3966:         }
 3967:     }
 3968:     return;
 3969: }
 3970: 
 3971: sub update_roles {
 3972:     my ($r,$context,$showcredits) = @_;
 3973:     my $now=time;
 3974:     my @rolechanges;
 3975:     my %disallowed;
 3976:     $r->print('<h3>'.&mt('Modifying Roles').'</h3>');
 3977:     foreach my $key (keys(%env)) {
 3978: 	next if (! $env{$key});
 3979:         next if ($key eq 'form.action');
 3980: 	# Revoke roles
 3981: 	if ($key=~/^form\.rev/) {
 3982: 	    if ($key=~/^form\.rev\:([^\_]+)\_([^\_\.]+)$/) {
 3983: # Revoke standard role
 3984: 		my ($scope,$role) = ($1,$2);
 3985: 		my $result =
 3986: 		    &Apache::lonnet::revokerole($env{'form.ccdomain'},
 3987: 						$env{'form.ccuname'},
 3988: 						$scope,$role,'','',$context);
 3989:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
 3990:                             &mt('Revoking [_1] in [_2]',
 3991:                                 &Apache::lonnet::plaintext($role),
 3992:                                 &Apache::loncommon::show_role_extent($scope,$context,$role)),
 3993:                                 $result ne "ok").'<br />');
 3994:                 if ($result ne "ok") {
 3995:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 3996:                 }
 3997: 		if ($role eq 'st') {
 3998: 		    my $result = 
 3999:                         &Apache::lonuserutils::classlist_drop($scope,
 4000:                             $env{'form.ccuname'},$env{'form.ccdomain'},
 4001: 			    $now);
 4002:                     $r->print(&Apache::lonhtmlcommon::confirm_success($result));
 4003: 		}
 4004:                 if (!grep(/^\Q$role\E$/,@rolechanges)) {
 4005:                     push(@rolechanges,$role);
 4006:                 }
 4007: 	    }
 4008: 	    if ($key=~m{^form\.rev\:([^_]+)_cr\.cr/($match_domain)/($match_username)/(\w+)$}s) {
 4009: # Revoke custom role
 4010:                 my $result = &Apache::lonnet::revokecustomrole(
 4011:                     $env{'form.ccdomain'},$env{'form.ccuname'},$1,$2,$3,$4,'','',$context);
 4012:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
 4013:                             &mt('Revoking custom role [_1] by [_2] in [_3]',
 4014:                                 $4,$3.':'.$2,&Apache::loncommon::show_role_extent($1,$context,'cr')),
 4015:                             $result ne 'ok').'<br />');
 4016:                 if ($result ne "ok") {
 4017:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 4018:                 }
 4019:                 if (!grep(/^cr$/,@rolechanges)) {
 4020:                     push(@rolechanges,'cr');
 4021:                 }
 4022: 	    }
 4023: 	} elsif ($key=~/^form\.del/) {
 4024: 	    if ($key=~/^form\.del\:([^\_]+)\_([^\_\.]+)$/) {
 4025: # Delete standard role
 4026: 		my ($scope,$role) = ($1,$2);
 4027: 		my $result =
 4028: 		    &Apache::lonnet::assignrole($env{'form.ccdomain'},
 4029: 						$env{'form.ccuname'},
 4030: 						$scope,$role,$now,0,1,'',
 4031:                                                 $context);
 4032:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
 4033:                             &mt('Deleting [_1] in [_2]',
 4034:                                 &Apache::lonnet::plaintext($role),
 4035:                                 &Apache::loncommon::show_role_extent($scope,$context,$role)),
 4036:                             $result ne 'ok').'<br />');
 4037:                 if ($result ne "ok") {
 4038:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 4039:                 }
 4040: 
 4041: 		if ($role eq 'st') {
 4042: 		    my $result = 
 4043:                         &Apache::lonuserutils::classlist_drop($scope,
 4044:                             $env{'form.ccuname'},$env{'form.ccdomain'},
 4045: 			    $now);
 4046: 		    $r->print(&Apache::lonhtmlcommon::confirm_success($result));
 4047: 		}
 4048:                 if (!grep(/^\Q$role\E$/,@rolechanges)) {
 4049:                     push(@rolechanges,$role);
 4050:                 }
 4051:             }
 4052: 	    if ($key=~m{^form\.del\:([^_]+)_cr\.cr/($match_domain)/($match_username)/(\w+)$}) {
 4053:                 my ($url,$rdom,$rnam,$rolename) = ($1,$2,$3,$4);
 4054: # Delete custom role
 4055:                 my $result =
 4056:                     &Apache::lonnet::assigncustomrole($env{'form.ccdomain'},
 4057:                         $env{'form.ccuname'},$url,$rdom,$rnam,$rolename,$now,
 4058:                         0,1,$context);
 4059:                 $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('Deleting custom role [_1] by [_2] in [_3]',
 4060:                       $rolename,$rnam.':'.$rdom,&Apache::loncommon::show_role_extent($1,$context,'cr')),
 4061:                       $result ne "ok").'<br />');
 4062:                 if ($result ne "ok") {
 4063:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 4064:                 }
 4065: 
 4066:                 if (!grep(/^cr$/,@rolechanges)) {
 4067:                     push(@rolechanges,'cr');
 4068:                 }
 4069:             }
 4070: 	} elsif ($key=~/^form\.ren/) {
 4071:             my $udom = $env{'form.ccdomain'};
 4072:             my $uname = $env{'form.ccuname'};
 4073: # Re-enable standard role
 4074: 	    if ($key=~/^form\.ren\:([^\_]+)\_([^\_\.]+)$/) {
 4075:                 my $url = $1;
 4076:                 my $role = $2;
 4077:                 my $logmsg;
 4078:                 my $output;
 4079:                 if ($role eq 'st') {
 4080:                     if ($url =~ m-^/($match_domain)/($match_courseid)/?(\w*)$-) {
 4081:                         my ($cdom,$cnum,$csec) = ($1,$2,$3);
 4082:                         my $credits;
 4083:                         if ($showcredits) {
 4084:                             my $defaultcredits = 
 4085:                                 &Apache::lonuserutils::get_defaultcredits($cdom,$cnum);
 4086:                             $credits = &get_user_credits($defaultcredits,$cdom,$cnum);
 4087:                         }
 4088:                         my $result = &Apache::loncommon::commit_studentrole(\$logmsg,$udom,$uname,$url,$role,$now,0,$cdom,$cnum,$csec,$context,$credits);
 4089:                         if (($result =~ /^error/) || ($result eq 'not_in_class') || ($result eq 'unknown_course') || ($result eq 'refused')) {
 4090:                             if ($result eq 'refused' && $logmsg) {
 4091:                                 $output = $logmsg;
 4092:                             } else { 
 4093:                                 $output = &mt('Error: [_1]',$result)."\n";
 4094:                             }
 4095:                         } else {
 4096:                             $output = &Apache::lonhtmlcommon::confirm_success(&mt('Assigning [_1] in [_2] starting [_3]',
 4097:                                         &Apache::lonnet::plaintext($role),
 4098:                                         &Apache::loncommon::show_role_extent($url,$context,'st'),
 4099:                                         &Apache::lonlocal::locallocaltime($now))).'<br />'.$logmsg.'<br />';
 4100:                         }
 4101:                     }
 4102:                 } else {
 4103: 		    my $result=&Apache::lonnet::assignrole($env{'form.ccdomain'},
 4104:                                $env{'form.ccuname'},$url,$role,0,$now,'','',
 4105:                                $context);
 4106:                         $output = &Apache::lonhtmlcommon::confirm_success(&mt('Re-enabling [_1] in [_2]',
 4107:                                         &Apache::lonnet::plaintext($role),
 4108:                                         &Apache::loncommon::show_role_extent($url,$context,$role)),$result ne "ok").'<br />';
 4109:                     if ($result ne "ok") {
 4110:                         $output .= &mt('Error: [_1]',$result).'<br />';
 4111:                     }
 4112:                 }
 4113:                 $r->print($output);
 4114:                 if (!grep(/^\Q$role\E$/,@rolechanges)) {
 4115:                     push(@rolechanges,$role);
 4116:                 }
 4117: 	    }
 4118: # Re-enable custom role
 4119: 	    if ($key=~m{^form\.ren\:([^_]+)_cr\.cr/($match_domain)/($match_username)/(\w+)$}) {
 4120:                 my ($url,$rdom,$rnam,$rolename) = ($1,$2,$3,$4);
 4121:                 my $result = &Apache::lonnet::assigncustomrole(
 4122:                                $env{'form.ccdomain'}, $env{'form.ccuname'},
 4123:                                $url,$rdom,$rnam,$rolename,0,$now,undef,$context);
 4124:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
 4125:                     &mt('Re-enabling custom role [_1] by [_2] in [_3]',
 4126:                         $rolename,$rnam.':'.$rdom,&Apache::loncommon::show_role_extent($1,$context,'cr')),
 4127:                     $result ne "ok").'<br />');
 4128:                 if ($result ne "ok") {
 4129:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 4130:                 }
 4131:                 if (!grep(/^cr$/,@rolechanges)) {
 4132:                     push(@rolechanges,'cr');
 4133:                 }
 4134:             }
 4135: 	} elsif ($key=~/^form\.act/) {
 4136:             my $udom = $env{'form.ccdomain'};
 4137:             my $uname = $env{'form.ccuname'};
 4138: 	    if ($key=~/^form\.act\_($match_domain)\_($match_courseid)\_cr_cr_($match_domain)_($match_username)_([^\_]+)$/) {
 4139:                 # Activate a custom role
 4140: 		my ($one,$two,$three,$four,$five)=($1,$2,$3,$4,$5);
 4141: 		my $url='/'.$one.'/'.$two;
 4142: 		my $full=$one.'_'.$two.'_cr_cr_'.$three.'_'.$four.'_'.$five;
 4143: 
 4144:                 my $start = ( $env{'form.start_'.$full} ?
 4145:                               $env{'form.start_'.$full} :
 4146:                               $now );
 4147:                 my $end   = ( $env{'form.end_'.$full} ?
 4148:                               $env{'form.end_'.$full} :
 4149:                               0 );
 4150:                                                                                      
 4151:                 # split multiple sections
 4152:                 my %sections = ();
 4153:                 my $num_sections = &build_roles($env{'form.sec_'.$full},\%sections,$5);
 4154:                 if ($num_sections == 0) {
 4155:                     $r->print(&Apache::loncommon::commit_customrole($udom,$uname,$url,$three,$four,$five,$start,$end,$context));
 4156:                 } else {
 4157: 		    my %curr_groups =
 4158: 			&Apache::longroup::coursegroups($one,$two);
 4159:                     foreach my $sec (sort {$a cmp $b} keys(%sections)) {
 4160:                         if (($sec eq 'none') || ($sec eq 'all') || 
 4161:                             exists($curr_groups{$sec})) {
 4162:                             $disallowed{$sec} = $url;
 4163:                             next;
 4164:                         }
 4165:                         my $securl = $url.'/'.$sec;
 4166: 		        $r->print(&Apache::loncommon::commit_customrole($udom,$uname,$securl,$three,$four,$five,$start,$end,$context));
 4167:                     }
 4168:                 }
 4169:                 if (!grep(/^cr$/,@rolechanges)) {
 4170:                     push(@rolechanges,'cr');
 4171:                 }
 4172: 	    } elsif ($key=~/^form\.act\_($match_domain)\_($match_name)\_([^\_]+)$/) {
 4173: 		# Activate roles for sections with 3 id numbers
 4174: 		# set start, end times, and the url for the class
 4175: 		my ($one,$two,$three)=($1,$2,$3);
 4176: 		my $start = ( $env{'form.start_'.$one.'_'.$two.'_'.$three} ? 
 4177: 			      $env{'form.start_'.$one.'_'.$two.'_'.$three} : 
 4178: 			      $now );
 4179: 		my $end   = ( $env{'form.end_'.$one.'_'.$two.'_'.$three} ? 
 4180: 			      $env{'form.end_'.$one.'_'.$two.'_'.$three} :
 4181: 			      0 );
 4182: 		my $url='/'.$one.'/'.$two;
 4183:                 my $type = 'three';
 4184:                 # split multiple sections
 4185:                 my %sections = ();
 4186:                 my $num_sections = &build_roles($env{'form.sec_'.$one.'_'.$two.'_'.$three},\%sections,$three);
 4187:                 my $credits;
 4188:                 if ($three eq 'st') {
 4189:                     if ($showcredits) { 
 4190:                         my $defaultcredits = 
 4191:                             &Apache::lonuserutils::get_defaultcredits($one,$two);
 4192:                         $credits = $env{'form.credits_'.$one.'_'.$two.'_'.$three};
 4193:                         $credits =~ s/[^\d\.]//g;
 4194:                         if ($credits eq $defaultcredits) {
 4195:                             undef($credits);
 4196:                         }
 4197:                     }
 4198:                 }
 4199:                 if ($num_sections == 0) {
 4200:                     $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$three,$start,$end,$one,$two,'',$context,$credits));
 4201:                 } else {
 4202:                     my %curr_groups = 
 4203: 			&Apache::longroup::coursegroups($one,$two);
 4204:                     my $emptysec = 0;
 4205:                     foreach my $sec (sort {$a cmp $b} keys(%sections)) {
 4206:                         $sec =~ s/\W//g;
 4207:                         if ($sec ne '') {
 4208:                             if (($sec eq 'none') || ($sec eq 'all') || 
 4209:                                 exists($curr_groups{$sec})) {
 4210:                                 $disallowed{$sec} = $url;
 4211:                                 next;
 4212:                             }
 4213:                             my $securl = $url.'/'.$sec;
 4214:                             $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$securl,$three,$start,$end,$one,$two,$sec,$context,$credits));
 4215:                         } else {
 4216:                             $emptysec = 1;
 4217:                         }
 4218:                     }
 4219:                     if ($emptysec) {
 4220:                         $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$three,$start,$end,$one,$two,'',$context,$credits));
 4221:                     }
 4222:                 }
 4223:                 if (!grep(/^\Q$three\E$/,@rolechanges)) {
 4224:                     push(@rolechanges,$three);
 4225:                 }
 4226: 	    } elsif ($key=~/^form\.act\_([^\_]+)\_([^\_]+)$/) {
 4227: 		# Activate roles for sections with two id numbers
 4228: 		# set start, end times, and the url for the class
 4229: 		my $start = ( $env{'form.start_'.$1.'_'.$2} ? 
 4230: 			      $env{'form.start_'.$1.'_'.$2} : 
 4231: 			      $now );
 4232: 		my $end   = ( $env{'form.end_'.$1.'_'.$2} ? 
 4233: 			      $env{'form.end_'.$1.'_'.$2} :
 4234: 			      0 );
 4235:                 my $one = $1;
 4236:                 my $two = $2;
 4237: 		my $url='/'.$one.'/';
 4238:                 # split multiple sections
 4239:                 my %sections = ();
 4240:                 my $num_sections = &build_roles($env{'form.sec_'.$one.'_'.$two},\%sections,$two);
 4241:                 if ($num_sections == 0) {
 4242:                     $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$two,$start,$end,$one,undef,'',$context));
 4243:                 } else {
 4244:                     my $emptysec = 0;
 4245:                     foreach my $sec (sort {$a cmp $b} keys(%sections)) {
 4246:                         if ($sec ne '') {
 4247:                             my $securl = $url.'/'.$sec;
 4248:                             $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$securl,$two,$start,$end,$one,undef,$sec,$context));
 4249:                         } else {
 4250:                             $emptysec = 1;
 4251:                         }
 4252:                     }
 4253:                     if ($emptysec) {
 4254:                         $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$two,$start,$end,$one,undef,'',$context));
 4255:                     }
 4256:                 }
 4257:                 if (!grep(/^\Q$two\E$/,@rolechanges)) {
 4258:                     push(@rolechanges,$two);
 4259:                 }
 4260: 	    } else {
 4261: 		$r->print('<p><span class="LC_error">'.&mt('ERROR').': '.&mt('Unknown command').' <tt>'.$key.'</tt></span></p><br />');
 4262:             }
 4263:             foreach my $key (sort(keys(%disallowed))) {
 4264:                 $r->print('<p class="LC_warning">');
 4265:                 if (($key eq 'none') || ($key eq 'all')) {  
 4266:                     $r->print(&mt('[_1] may not be used as the name for a section, as it is a reserved word.','<tt>'.$key.'</tt>'));
 4267:                 } else {
 4268:                     $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>'));
 4269:                 }
 4270:                 $r->print('</p><p>'
 4271:                          .&mt('Please [_1]go back[_2] and choose a different section name.'
 4272:                              ,'<a href="javascript:history.go(-1)'
 4273:                              ,'</a>')
 4274:                          .'</p><br />'
 4275:                 );
 4276:             }
 4277: 	}
 4278:     } # End of foreach (keys(%env))
 4279: # Flush the course logs so reverse user roles immediately updated
 4280:     $r->register_cleanup(\&Apache::lonnet::flushcourselogs);
 4281:     if (@rolechanges == 0) {
 4282:         $r->print('<p>'.&mt('No roles to modify').'</p>');
 4283:     }
 4284:     return @rolechanges;
 4285: }
 4286: 
 4287: sub get_user_credits {
 4288:     my ($uname,$udom,$defaultcredits,$cdom,$cnum) = @_;
 4289:     if ($cdom eq '' || $cnum eq '') {
 4290:         return unless ($env{'request.course.id'});
 4291:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4292:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4293:     }
 4294:     my $credits;
 4295:     my %currhash =
 4296:         &Apache::lonnet::get('classlist',[$uname.':'.$udom],$cdom,$cnum);
 4297:     if (keys(%currhash) > 0) {
 4298:         my @items = split(/:/,$currhash{$uname.':'.$udom});
 4299:         my $crdidx = &Apache::loncoursedata::CL_CREDITS() - 3;
 4300:         $credits = $items[$crdidx];
 4301:         $credits =~ s/[^\d\.]//g;
 4302:     }
 4303:     if ($credits eq $defaultcredits) {
 4304:         undef($credits);
 4305:     }
 4306:     return $credits;
 4307: }
 4308: 
 4309: sub enroll_single_student {
 4310:     my ($r,$uhome,$amode,$genpwd,$now,$newuser,$context,$crstype,
 4311:         $showcredits,$defaultcredits) = @_;
 4312:     $r->print('<h3>');
 4313:     if ($crstype eq 'Community') {
 4314:         $r->print(&mt('Enrolling Member'));
 4315:     } else {
 4316:         $r->print(&mt('Enrolling Student'));
 4317:     }
 4318:     $r->print('</h3>');
 4319: 
 4320:     # Remove non alphanumeric values from section
 4321:     $env{'form.sections'}=~s/\W//g;
 4322: 
 4323:     my $credits;
 4324:     if (($showcredits) && ($env{'form.credits'} ne '')) {
 4325:         $credits = $env{'form.credits'};
 4326:         $credits =~ s/[^\d\.]//g;
 4327:         if ($credits ne '') {
 4328:             if ($credits eq $defaultcredits) {
 4329:                 undef($credits);
 4330:             }
 4331:         }
 4332:     }
 4333: 
 4334:     # Clean out any old student roles the user has in this class.
 4335:     &Apache::lonuserutils::modifystudent($env{'form.ccdomain'},
 4336:          $env{'form.ccuname'},$env{'request.course.id'},undef,$uhome);
 4337:     my ($startdate,$enddate) = &Apache::lonuserutils::get_dates_from_form();
 4338:     my $enroll_result =
 4339:         &Apache::lonnet::modify_student_enrollment($env{'form.ccdomain'},
 4340:             $env{'form.ccuname'},$env{'form.cid'},$env{'form.cfirstname'},
 4341:             $env{'form.cmiddlename'},$env{'form.clastname'},
 4342:             $env{'form.generation'},$env{'form.sections'},$enddate,
 4343:             $startdate,'manual',undef,$env{'request.course.id'},'',$context,
 4344:             $credits);
 4345:     if ($enroll_result =~ /^ok/) {
 4346:         $r->print(&mt('[_1] enrolled','<b>'.$env{'form.ccuname'}.':'.$env{'form.ccdomain'}.'</b>'));
 4347:         if ($env{'form.sections'} ne '') {
 4348:             $r->print(' '.&mt('in section [_1]',$env{'form.sections'}));
 4349:         }
 4350:         my ($showstart,$showend);
 4351:         if ($startdate <= $now) {
 4352:             $showstart = &mt('Access starts immediately');
 4353:         } else {
 4354:             $showstart = &mt('Access starts: ').&Apache::lonlocal::locallocaltime($startdate);
 4355:         }
 4356:         if ($enddate == 0) {
 4357:             $showend = &mt('ends: no ending date');
 4358:         } else {
 4359:             $showend = &mt('ends: ').&Apache::lonlocal::locallocaltime($enddate);
 4360:         }
 4361:         $r->print('.<br />'.$showstart.'; '.$showend);
 4362:         if ($startdate <= $now && !$newuser) {
 4363:             $r->print('<p class="LC_info">');
 4364:             if ($crstype eq 'Community') {
 4365:                 $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.'));
 4366:             } else {
 4367:                 $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.'));
 4368:            }
 4369:            $r->print('</p>');
 4370:         }
 4371:     } else {
 4372:         $r->print(&mt('unable to enroll').": ".$enroll_result);
 4373:     }
 4374:     return;
 4375: }
 4376: 
 4377: sub get_defaultquota_text {
 4378:     my ($settingstatus) = @_;
 4379:     my $defquotatext; 
 4380:     if ($settingstatus eq '') {
 4381:         $defquotatext = &mt('default');
 4382:     } else {
 4383:         my ($usertypes,$order) =
 4384:             &Apache::lonnet::retrieve_inst_usertypes($env{'form.ccdomain'});
 4385:         if ($usertypes->{$settingstatus} eq '') {
 4386:             $defquotatext = &mt('default');
 4387:         } else {
 4388:             $defquotatext = &mt('default for [_1]',$usertypes->{$settingstatus});
 4389:         }
 4390:     }
 4391:     return $defquotatext;
 4392: }
 4393: 
 4394: sub update_result_form {
 4395:     my ($uhome) = @_;
 4396:     my $outcome = 
 4397:     '<form name="userupdate" method="post" action="">'."\n";
 4398:     foreach my $item ('srchby','srchin','srchtype','srchterm','srchdomain','ccuname','ccdomain') {
 4399:         $outcome .= '<input type="hidden" name="'.$item.'" value="'.$env{'form.'.$item}.'" />'."\n";
 4400:     }
 4401:     if ($env{'form.origname'} ne '') {
 4402:         $outcome .= '<input type="hidden" name="origname" value="'.$env{'form.origname'}.'" />'."\n";
 4403:     }
 4404:     foreach my $item ('sortby','seluname','seludom') {
 4405:         if (exists($env{'form.'.$item})) {
 4406:             $outcome .= '<input type="hidden" name="'.$item.'" value="'.$env{'form.'.$item}.'" />'."\n";
 4407:         }
 4408:     }
 4409:     if ($uhome eq 'no_host') {
 4410:         $outcome .= '<input type="hidden" name="forcenewuser" value="1" />'."\n";
 4411:     }
 4412:     $outcome .= '<input type="hidden" name="phase" value="" />'."\n".
 4413:                 '<input type="hidden" name="currstate" value="" />'."\n".
 4414:                 '<input type="hidden" name="action" value="'.$env{'form.action'}.'" />'."\n".
 4415:                 '</form>';
 4416:     return $outcome;
 4417: }
 4418: 
 4419: sub quota_admin {
 4420:     my ($setquota,$changeHash,$name) = @_;
 4421:     my $quotachanged;
 4422:     if (&Apache::lonnet::allowed('mpq',$env{'form.ccdomain'})) {
 4423:         # Current user has quota modification privileges
 4424:         if (ref($changeHash) eq 'HASH') {
 4425:             $quotachanged = 1;
 4426:             $changeHash->{$name.'quota'} = $setquota;
 4427:         }
 4428:     }
 4429:     return $quotachanged;
 4430: }
 4431: 
 4432: sub tool_admin {
 4433:     my ($tool,$settool,$changeHash,$context) = @_;
 4434:     my $canchange = 0; 
 4435:     if ($context eq 'requestcourses') {
 4436:         if (&Apache::lonnet::allowed('ccc',$env{'form.ccdomain'})) {
 4437:             $canchange = 1;
 4438:         }
 4439:     } elsif ($context eq 'reqcrsotherdom') {
 4440:         if (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) {
 4441:             $canchange = 1;
 4442:         }
 4443:     } elsif ($context eq 'requestauthor') {
 4444:         if (&Apache::lonnet::allowed('cau',$env{'request.role.domain'})) {
 4445:             $canchange = 1;
 4446:         }
 4447:     } elsif (&Apache::lonnet::allowed('mut',$env{'form.ccdomain'})) {
 4448:         # Current user has quota modification privileges
 4449:         $canchange = 1;
 4450:     }
 4451:     my $toolchanged;
 4452:     if ($canchange) {
 4453:         if (ref($changeHash) eq 'HASH') {
 4454:             $toolchanged = 1;
 4455:             if ($tool eq 'requestauthor') {
 4456:                 $changeHash->{$context} = $settool;
 4457:             } else {
 4458:                 $changeHash->{$context.'.'.$tool} = $settool;
 4459:             }
 4460:         }
 4461:     }
 4462:     return $toolchanged;
 4463: }
 4464: 
 4465: sub build_roles {
 4466:     my ($sectionstr,$sections,$role) = @_;
 4467:     my $num_sections = 0;
 4468:     if ($sectionstr=~ /,/) {
 4469:         my @secnums = split/,/,$sectionstr;
 4470:         if ($role eq 'st') {
 4471:             $secnums[0] =~ s/\W//g;
 4472:             $$sections{$secnums[0]} = 1;
 4473:             $num_sections = 1;
 4474:         } else {
 4475:             foreach my $sec (@secnums) {
 4476:                 $sec =~ ~s/\W//g;
 4477:                 if (!($sec eq "")) {
 4478:                     if (exists($$sections{$sec})) {
 4479:                         $$sections{$sec} ++;
 4480:                     } else {
 4481:                         $$sections{$sec} = 1;
 4482:                         $num_sections ++;
 4483:                     }
 4484:                 }
 4485:             }
 4486:         }
 4487:     } else {
 4488:         $sectionstr=~s/\W//g;
 4489:         unless ($sectionstr eq '') {
 4490:             $$sections{$sectionstr} = 1;
 4491:             $num_sections ++;
 4492:         }
 4493:     }
 4494: 
 4495:     return $num_sections;
 4496: }
 4497: 
 4498: # ========================================================== Custom Role Editor
 4499: 
 4500: sub custom_role_editor {
 4501:     my ($r,$context,$brcrum,$prefix,$permission) = @_;
 4502:     my $action = $env{'form.customroleaction'};
 4503:     my ($rolename,$helpitem);
 4504:     if ($action eq 'new') {
 4505:         $rolename=$env{'form.newrolename'};
 4506:     } else {
 4507:         $rolename=$env{'form.rolename'};
 4508:     }
 4509: 
 4510:     my ($crstype,$context);
 4511:     if ($env{'request.course.id'}) {
 4512:         $crstype = &Apache::loncommon::course_type();
 4513:         $context = 'course';
 4514:         $helpitem = 'Course_Editing_Custom_Roles';
 4515:     } else {
 4516:         $context = 'domain';
 4517:         $crstype = 'course';
 4518:         $helpitem = 'Domain_Editing_Custom_Roles';
 4519:     }
 4520: 
 4521:     $rolename=~s/[^A-Za-z0-9]//gs;
 4522:     if (!$rolename || $env{'form.phase'} eq 'pickrole') {
 4523: 	&print_username_entry_form($r,$context,undef,undef,undef,$crstype,$brcrum,
 4524:                                    $permission);
 4525:         return;
 4526:     }
 4527: 
 4528:     my $formname = 'form1';
 4529:     my %privs=();
 4530:     my $body_top = '<h2>';
 4531: # ------------------------------------------------------- Does this role exist?
 4532:     my ($rdummy,$roledef)=
 4533: 			 &Apache::lonnet::get('roles',["rolesdef_$rolename"]);
 4534:     if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 4535:         $body_top .= &mt('Existing Role').' "';
 4536: # ------------------------------------------------- Get current role privileges
 4537:         ($privs{'system'},$privs{'domain'},$privs{'course'})=split(/\_/,$roledef);
 4538:         if ($privs{'system'} =~ /bre\&S/) {
 4539:             if ($context eq 'domain') {
 4540:                 $crstype = 'Course';
 4541:             } elsif ($crstype eq 'Community') {
 4542:                 $privs{'system'} =~ s/bre\&S//;
 4543:             }
 4544:         } elsif ($context eq 'domain') {
 4545:             $crstype = 'Course';
 4546:         }
 4547:     } else {
 4548:         $body_top .= &mt('New Role').' "';
 4549:         $roledef='';
 4550:     }
 4551:     $body_top .= $rolename.'"</h2>';
 4552: 
 4553: # ------------------------------------------------------- What can be assigned?
 4554:     my %full=();
 4555:     my %levels=(
 4556:                  course => {},
 4557:                  domain => {},
 4558:                  system => {},
 4559:                );
 4560:     my %levelscurrent=(
 4561:                         course => {},
 4562:                         domain => {},
 4563:                         system => {},
 4564:                       );
 4565:     &Apache::lonuserutils::custom_role_privs(\%privs,\%full,\%levels,\%levelscurrent);
 4566:     my ($jsback,$elements) = &crumb_utilities();
 4567:     my @templateroles = &Apache::lonuserutils::custom_template_roles($context,$crstype);
 4568:     my $head_script =
 4569:         &Apache::lonuserutils::custom_roledefs_js($context,$crstype,$formname,
 4570:                                                   \%full,\@templateroles,$jsback);
 4571:     push (@{$brcrum},
 4572:               {href => "javascript:backPage(document.$formname,'pickrole','')",
 4573:                text => "Pick custom role",
 4574:                faq  => 282,bug=>'Instructor Interface',},
 4575:               {href => "javascript:backPage(document.$formname,'','')",
 4576:                text => "Edit custom role",
 4577:                faq  => 282,
 4578:                bug  => 'Instructor Interface',
 4579:                help => $helpitem}
 4580:               );
 4581:     my $args = { bread_crumbs          => $brcrum,
 4582:                  bread_crumbs_component => 'User Management'};
 4583:     $r->print(&Apache::loncommon::start_page('Custom Role Editor',
 4584:                                              $head_script,$args).
 4585:               $body_top);
 4586:     $r->print('<form name="'.$formname.'" method="post" action="">'."\n".
 4587:               &Apache::lonuserutils::custom_role_header($context,$crstype,
 4588:                                                         \@templateroles,$prefix));
 4589: 
 4590:     $r->print(<<ENDCCF);
 4591: <input type="hidden" name="phase" value="set_custom_roles" />
 4592: <input type="hidden" name="rolename" value="$rolename" />
 4593: ENDCCF
 4594:     $r->print(&Apache::lonuserutils::custom_role_table($crstype,\%full,\%levels,
 4595:                                                        \%levelscurrent,$prefix));
 4596:     $r->print(&Apache::loncommon::end_data_table().
 4597:    '<input type="hidden" name="action" value="'.$env{'form.action'}.'" />'.
 4598:    '<input type="hidden" name="startrolename" value="'.$env{'form.rolename'}.
 4599:    '" />'."\n".'<input type="hidden" name="currstate" value="" />'."\n".
 4600:    '<input type="reset" value="'.&mt("Reset").'" />'."\n".
 4601:    '<input type="submit" value="'.&mt('Save').'" /></form>');
 4602: }
 4603: 
 4604: # ---------------------------------------------------------- Call to definerole
 4605: sub set_custom_role {
 4606:     my ($r,$context,$brcrum,$prefix,$permission) = @_;
 4607:     my $rolename=$env{'form.rolename'};
 4608:     $rolename=~s/[^A-Za-z0-9]//gs;
 4609:     if (!$rolename) {
 4610: 	&custom_role_editor($r,$context,$brcrum,$prefix,$permission);
 4611:         return;
 4612:     }
 4613:     my ($jsback,$elements) = &crumb_utilities();
 4614:     my $jscript = '<script type="text/javascript">'
 4615:                  .'// <![CDATA['."\n"
 4616:                  .$jsback."\n"
 4617:                  .'// ]]>'."\n"
 4618:                  .'</script>'."\n";
 4619:     my $helpitem = 'Course_Editing_Custom_Roles';
 4620:     if ($context eq 'domain') {
 4621:         $helpitem = 'Domain_Editing_Custom_Roles';
 4622:     }
 4623:     push(@{$brcrum},
 4624:         {href => "javascript:backPage(document.customresult,'pickrole','')",
 4625:          text => "Pick custom role",
 4626:          faq  => 282,
 4627:          bug  => 'Instructor Interface',},
 4628:         {href => "javascript:backPage(document.customresult,'selected_custom_edit','')",
 4629:          text => "Edit custom role",
 4630:          faq  => 282,
 4631:          bug  => 'Instructor Interface',},
 4632:         {href => "javascript:backPage(document.customresult,'set_custom_roles','')",
 4633:          text => "Result",
 4634:          faq  => 282,
 4635:          bug  => 'Instructor Interface',
 4636:          help => $helpitem,}
 4637:         );
 4638:     my $args = { bread_crumbs           => $brcrum,
 4639:                  bread_crumbs_component => 'User Management'};
 4640:     $r->print(&Apache::loncommon::start_page('Save Custom Role',$jscript,$args));
 4641: 
 4642:     my $newrole;
 4643:     my ($rdummy,$roledef)=
 4644: 	&Apache::lonnet::get('roles',["rolesdef_$rolename"]);
 4645: 
 4646: # ------------------------------------------------------- Does this role exist?
 4647:     $r->print('<h3>');
 4648:     if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 4649: 	$r->print(&mt('Existing Role').' "');
 4650:     } else {
 4651: 	$r->print(&mt('New Role').' "');
 4652: 	$roledef='';
 4653:         $newrole = 1;
 4654:     }
 4655:     $r->print($rolename.'"</h3>');
 4656: # ------------------------------------------------- Assign role and show result
 4657: 
 4658:     my $errmsg;
 4659:     my %newprivs = &Apache::lonuserutils::custom_role_update($rolename,$prefix);
 4660:     # Assign role and return result
 4661:     my $result = &Apache::lonnet::definerole($rolename,$newprivs{'s'},$newprivs{'d'},
 4662:                                              $newprivs{'c'});
 4663:     if ($result ne 'ok') {
 4664:         $errmsg = ': '.$result;
 4665:     }
 4666:     my $message =
 4667:         &Apache::lonhtmlcommon::confirm_success(
 4668:             &mt('Defining Role').$errmsg, ($result eq 'ok' ? 0 : 1));
 4669:     if ($env{'request.course.id'}) {
 4670:         my $url='/'.$env{'request.course.id'};
 4671:         $url=~s/\_/\//g;
 4672:         $result =
 4673:             &Apache::lonnet::assigncustomrole(
 4674:                 $env{'user.domain'},$env{'user.name'},
 4675:                 $url,
 4676:                 $env{'user.domain'},$env{'user.name'},
 4677:                 $rolename,undef,undef,undef,$context);
 4678:         if ($result ne 'ok') {
 4679:             $errmsg = ': '.$result;
 4680:         }
 4681:         $message .=
 4682:             '<br />'
 4683:            .&Apache::lonhtmlcommon::confirm_success(
 4684:                 &mt('Assigning Role to Self').$errmsg, ($result eq 'ok' ? 0 : 1));
 4685:     }
 4686:     $r->print(
 4687:         &Apache::loncommon::confirmwrapper($message)
 4688:        .'<br />'
 4689:        .&Apache::lonhtmlcommon::actionbox([
 4690:             '<a href="javascript:backPage(document.customresult,'."'pickrole'".')">'
 4691:            .&mt('Create or edit another custom role')
 4692:            .'</a>'])
 4693:        .'<form name="customresult" method="post" action="">'
 4694:        .&Apache::lonhtmlcommon::echo_form_input([])
 4695:        .'</form>'
 4696:     );
 4697: }
 4698: 
 4699: # ================================================================ Main Handler
 4700: sub handler {
 4701:     my $r = shift;
 4702:     if ($r->header_only) {
 4703:        &Apache::loncommon::content_type($r,'text/html');
 4704:        $r->send_http_header;
 4705:        return OK;
 4706:     }
 4707:     my ($context,$crstype,$cid,$cnum,$cdom,$allhelpitems);
 4708: 
 4709:     if ($env{'request.course.id'}) {
 4710:         $context = 'course';
 4711:         $crstype = &Apache::loncommon::course_type();
 4712:     } elsif ($env{'request.role'} =~ /^au\./) {
 4713:         $context = 'author';
 4714:     } else {
 4715:         $context = 'domain';
 4716:     }
 4717: 
 4718:     my ($permission,$allowed) =
 4719:         &Apache::lonuserutils::get_permission($context,$crstype);
 4720: 
 4721:     if ($allowed) {
 4722:         my @allhelp;
 4723:         if ($context eq 'course') {
 4724:             $cid = $env{'request.course.id'};
 4725:             $cdom = $env{'course.'.$cid.'.domain'};
 4726:             $cnum = $env{'course.'.$cid.'.num'};
 4727: 
 4728:             if ($permission->{'cusr'}) {
 4729:                 push(@allhelp,'Course_Create_Class_List');
 4730:             }
 4731:             if ($permission->{'view'} || $permission->{'cusr'}) {
 4732:                 push(@allhelp,('Course_Change_Privileges','Course_View_Class_List'));
 4733:             }
 4734:             if ($permission->{'custom'}) {
 4735:                 push(@allhelp,'Course_Editing_Custom_Roles');
 4736:             }
 4737:             if ($permission->{'cusr'}) {
 4738:                 push(@allhelp,('Course_Add_Student','Course_Drop_Student'));
 4739:             }
 4740:             unless ($permission->{'cusr_section'}) {
 4741:                 if (&Apache::lonnet::auto_run($cnum,$cdom) && (($permission->{'cusr'}) || ($permission->{'view'}))) {
 4742:                     push(@allhelp,'Course_Automated_Enrollment');
 4743:                 }
 4744:                 if ($permission->{'selfenrolladmin'}) {
 4745:                     push(@allhelp,'Course_Approve_Selfenroll');
 4746:                 }
 4747:             }
 4748:             if ($permission->{'grp_manage'}) {
 4749:                 push(@allhelp,'Course_Manage_Group');
 4750:             }
 4751:             if ($permission->{'view'} || $permission->{'cusr'}) {
 4752:                 push(@allhelp,'Course_User_Logs');
 4753:             }
 4754:         } elsif ($context eq 'author') {
 4755:             push(@allhelp,('Author_Change_Privileges','Author_Create_Coauthor_List',
 4756:                            'Author_View_Coauthor_List','Author_User_Logs'));
 4757:         } else {
 4758:             if ($permission->{'cusr'}) {
 4759:                 push(@allhelp,'Domain_Change_Privileges');
 4760:                 if ($permission->{'activity'}) {
 4761:                     push(@allhelp,'Domain_User_Access_Logs');
 4762:                 }
 4763:                 push(@allhelp,('Domain_Create_Users','Domain_View_Users_List'));
 4764:                 if ($permission->{'custom'}) {
 4765:                     push(@allhelp,'Domain_Editing_Custom_Roles');
 4766:                 }
 4767:                 push(@allhelp,('Domain_Role_Approvals','Domain_Username_Approvals','Domain_Change_Logs'));
 4768:             } elsif ($permission->{'view'}) {
 4769:                 push(@allhelp,'Domain_View_Privileges');
 4770:                 if ($permission->{'activity'}) {
 4771:                     push(@allhelp,'Domain_User_Access_Logs');
 4772:                 }
 4773:                 push(@allhelp,('Domain_View_Users_List','Domain_Change_Logs'));
 4774:             }
 4775:         }
 4776:         if (@allhelp) {
 4777:             $allhelpitems = join(',',@allhelp);
 4778:         }
 4779:     }
 4780: 
 4781:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 4782:         ['action','state','callingform','roletype','showrole','bulkaction','popup','phase',
 4783:          'username','domain','srchterm','srchdomain','srchin','srchby','srchtype','queue']);
 4784:     &Apache::lonhtmlcommon::clear_breadcrumbs();
 4785:     my $args;
 4786:     my $brcrum = [];
 4787:     my $bread_crumbs_component = 'User Management';
 4788:     if (($env{'form.action'} ne 'dateselect') && ($env{'form.action'} ne 'displayuserreq')) {
 4789:         $brcrum = [{href=>"/adm/createuser",
 4790:                     text=>"User Management",
 4791:                     help=>$allhelpitems}
 4792:                   ];
 4793:     }
 4794:     if (!$allowed) {
 4795:         if ($context eq 'course') {
 4796:             $r->internal_redirect('/adm/viewclasslist');
 4797:             return OK;
 4798:         }
 4799:         $env{'user.error.msg'}=
 4800:             "/adm/createuser:cst:0:0:Cannot create/modify user data ".
 4801:                                  "or view user status.";
 4802:         return HTTP_NOT_ACCEPTABLE;
 4803:     }
 4804: 
 4805:     &Apache::loncommon::content_type($r,'text/html');
 4806:     $r->send_http_header;
 4807: 
 4808:     my $showcredits;
 4809:     if ((($context eq 'course') && ($crstype eq 'Course')) || 
 4810:          ($context eq 'domain')) {
 4811:         my %domdefaults = 
 4812:             &Apache::lonnet::get_domain_defaults($env{'request.role.domain'});
 4813:         if ($domdefaults{'officialcredits'} || $domdefaults{'unofficialcredits'}) {
 4814:             $showcredits = 1;
 4815:         }
 4816:     }
 4817: 
 4818:     # Main switch on form.action and form.state, as appropriate
 4819:     if (! exists($env{'form.action'})) {
 4820:         $args = {bread_crumbs => $brcrum,
 4821:                  bread_crumbs_component => $bread_crumbs_component}; 
 4822:         $r->print(&header(undef,$args));
 4823:         $r->print(&print_main_menu($permission,$context,$crstype));
 4824:     } elsif ($env{'form.action'} eq 'upload' && $permission->{'cusr'}) {
 4825:         my $helpitem = 'Course_Create_Class_List';
 4826:         if ($context eq 'author') {
 4827:             $helpitem = 'Author_Create_Coauthor_List';
 4828:         } elsif ($context eq 'domain') {
 4829:             $helpitem = 'Domain_Create_Users';
 4830:         }
 4831:         push(@{$brcrum},
 4832:               { href => '/adm/createuser?action=upload&state=',
 4833:                 text => 'Upload Users List',
 4834:                 help => $helpitem,
 4835:               });
 4836:         $bread_crumbs_component = 'Upload Users List';
 4837:         $args = {bread_crumbs           => $brcrum,
 4838:                  bread_crumbs_component => $bread_crumbs_component};
 4839:         $r->print(&header(undef,$args));
 4840:         $r->print('<form name="studentform" method="post" '.
 4841:                   'enctype="multipart/form-data" '.
 4842:                   ' action="/adm/createuser">'."\n");
 4843:         if (! exists($env{'form.state'})) {
 4844:             &Apache::lonuserutils::print_first_users_upload_form($r,$context);
 4845:         } elsif ($env{'form.state'} eq 'got_file') {
 4846:             my $result = 
 4847:                 &Apache::lonuserutils::print_upload_manager_form($r,$context,
 4848:                                                                  $permission,
 4849:                                                                  $crstype,$showcredits);
 4850:             if ($result eq 'missingdata') {
 4851:                 delete($env{'form.state'});
 4852:                 &Apache::lonuserutils::print_first_users_upload_form($r,$context);
 4853:             }
 4854:         } elsif ($env{'form.state'} eq 'enrolling') {
 4855:             if ($env{'form.datatoken'}) {
 4856:                 my $result = &Apache::lonuserutils::upfile_drop_add($r,$context,
 4857:                                                                     $permission,
 4858:                                                                     $showcredits);
 4859:                 if ($result eq 'missingdata') {
 4860:                     delete($env{'form.state'});
 4861:                     &Apache::lonuserutils::print_first_users_upload_form($r,$context);
 4862:                 } elsif ($result eq 'invalidhome') {
 4863:                     $env{'form.state'} = 'got_file';
 4864:                     delete($env{'form.lcserver'});
 4865:                     my $result =
 4866:                         &Apache::lonuserutils::print_upload_manager_form($r,$context,$permission,
 4867:                                                                          $crstype,$showcredits);
 4868:                     if ($result eq 'missingdata') {
 4869:                         delete($env{'form.state'});
 4870:                         &Apache::lonuserutils::print_first_users_upload_form($r,$context);
 4871:                     }
 4872:                 }
 4873:             } else {
 4874:                 delete($env{'form.state'});
 4875:                 &Apache::lonuserutils::print_first_users_upload_form($r,$context);
 4876:             }
 4877:         } else {
 4878:             &Apache::lonuserutils::print_first_users_upload_form($r,$context);
 4879:         }
 4880:         $r->print('</form>');
 4881:     } elsif (((($env{'form.action'} eq 'singleuser') || ($env{'form.action'}
 4882:               eq 'singlestudent')) && ($permission->{'cusr'})) ||
 4883:              (($env{'form.action'} eq 'singleuser') && ($permission->{'view'})) ||
 4884:              (($env{'form.action'} eq 'accesslogs') && ($permission->{'activity'}))) {
 4885:         my $phase = $env{'form.phase'};
 4886:         my @search = ('srchterm','srchby','srchin','srchtype','srchdomain');
 4887: 	&Apache::loncreateuser::restore_prev_selections();
 4888: 	my $srch;
 4889: 	foreach my $item (@search) {
 4890: 	    $srch->{$item} = $env{'form.'.$item};
 4891: 	}
 4892:         if (($phase eq 'get_user_info') || ($phase eq 'userpicked') ||
 4893:             ($phase eq 'createnewuser') || ($phase eq 'activity')) {
 4894:             if ($env{'form.phase'} eq 'createnewuser') {
 4895:                 my $response;
 4896:                 if ($env{'form.srchterm'} !~ /^$match_username$/) {
 4897:                     my $response =
 4898:                         '<span class="LC_warning">'
 4899:                        .&mt('You must specify a valid username. Only the following are allowed:'
 4900:                            .' letters numbers - . @')
 4901:                        .'</span>';
 4902:                     $env{'form.phase'} = '';
 4903:                     &print_username_entry_form($r,$context,$response,$srch,undef,
 4904:                                                $crstype,$brcrum,$permission);
 4905:                 } else {
 4906:                     my $ccuname =&LONCAPA::clean_username($srch->{'srchterm'});
 4907:                     my $ccdomain=&LONCAPA::clean_domain($srch->{'srchdomain'});
 4908:                     &print_user_modification_page($r,$ccuname,$ccdomain,
 4909:                                                   $srch,$response,$context,
 4910:                                                   $permission,$crstype,$brcrum,
 4911:                                                   $showcredits);
 4912:                 }
 4913:             } elsif ($env{'form.phase'} eq 'get_user_info') {
 4914:                 my ($currstate,$response,$forcenewuser,$results) = 
 4915:                     &user_search_result($context,$srch);
 4916:                 if ($env{'form.currstate'} eq 'modify') {
 4917:                     $currstate = $env{'form.currstate'};
 4918:                 }
 4919:                 if ($currstate eq 'select') {
 4920:                     &print_user_selection_page($r,$response,$srch,$results,
 4921:                                                \@search,$context,undef,$crstype,
 4922:                                                $brcrum);
 4923:                 } elsif (($currstate eq 'modify') || ($env{'form.action'} eq 'accesslogs')) {
 4924:                     my ($ccuname,$ccdomain,$uhome);
 4925:                     if (($srch->{'srchby'} eq 'uname') && 
 4926:                         ($srch->{'srchtype'} eq 'exact')) {
 4927:                         $ccuname = $srch->{'srchterm'};
 4928:                         $ccdomain= $srch->{'srchdomain'};
 4929:                     } else {
 4930:                         my @matchedunames = keys(%{$results});
 4931:                         ($ccuname,$ccdomain) = split(/:/,$matchedunames[0]);
 4932:                     }
 4933:                     $ccuname =&LONCAPA::clean_username($ccuname);
 4934:                     $ccdomain=&LONCAPA::clean_domain($ccdomain);
 4935:                     if ($env{'form.action'} eq 'accesslogs') {
 4936:                         my $uhome;
 4937:                         if (($ccuname ne '') && ($ccdomain ne '')) {
 4938:                            $uhome = &Apache::lonnet::homeserver($ccuname,$ccdomain);
 4939:                         }
 4940:                         if (($uhome eq '') || ($uhome eq 'no_host')) {
 4941:                             $env{'form.phase'} = '';
 4942:                             undef($forcenewuser);
 4943:                             #if ($response) {
 4944:                             #    unless ($response =~ m{\Q<br /><br />\E$}) {
 4945:                             #        $response .= '<br /><br />';
 4946:                             #    }
 4947:                             #}
 4948:                             &print_username_entry_form($r,$context,$response,$srch,
 4949:                                                        $forcenewuser,$crstype,$brcrum,
 4950:                                                        $permission);
 4951:                         } else {
 4952:                             &print_useraccesslogs_display($r,$ccuname,$ccdomain,$permission,$brcrum);
 4953:                         }
 4954:                     } else {
 4955:                         if ($env{'form.forcenewuser'}) {
 4956:                             $response = '';
 4957:                         }
 4958:                         &print_user_modification_page($r,$ccuname,$ccdomain,
 4959:                                                       $srch,$response,$context,
 4960:                                                       $permission,$crstype,$brcrum);
 4961:                     }
 4962:                 } elsif ($currstate eq 'query') {
 4963:                     &print_user_query_page($r,'createuser',$brcrum);
 4964:                 } else {
 4965:                     $env{'form.phase'} = '';
 4966:                     &print_username_entry_form($r,$context,$response,$srch,
 4967:                                                $forcenewuser,$crstype,$brcrum,
 4968:                                                $permission);
 4969:                 }
 4970:             } elsif ($env{'form.phase'} eq 'userpicked') {
 4971:                 my $ccuname = &LONCAPA::clean_username($env{'form.seluname'});
 4972:                 my $ccdomain = &LONCAPA::clean_domain($env{'form.seludom'});
 4973:                 if ($env{'form.action'} eq 'accesslogs') {
 4974:                     &print_useraccesslogs_display($r,$ccuname,$ccdomain,$permission,$brcrum);
 4975:                 } else {
 4976:                     &print_user_modification_page($r,$ccuname,$ccdomain,$srch,'',
 4977:                                                   $context,$permission,$crstype,
 4978:                                                   $brcrum);
 4979:                 }
 4980:             } elsif ($env{'form.action'} eq 'accesslogs') {
 4981:                 my $ccuname = &LONCAPA::clean_username($env{'form.accessuname'});
 4982:                 my $ccdomain = &LONCAPA::clean_domain($env{'form.accessudom'});
 4983:                 &print_useraccesslogs_display($r,$ccuname,$ccdomain,$permission,$brcrum);
 4984:             }
 4985:         } elsif ($env{'form.phase'} eq 'update_user_data') {
 4986:             &update_user_data($r,$context,$crstype,$brcrum,$showcredits,$permission);
 4987:         } else {
 4988:             &print_username_entry_form($r,$context,undef,$srch,undef,$crstype,
 4989:                                        $brcrum,$permission);
 4990:         }
 4991:     } elsif ($env{'form.action'} eq 'custom' && $permission->{'custom'}) {
 4992:         my $prefix;
 4993:         if ($env{'form.phase'} eq 'set_custom_roles') {
 4994:             &set_custom_role($r,$context,$brcrum,$prefix,$permission);
 4995:         } else {
 4996:             &custom_role_editor($r,$context,$brcrum,$prefix,$permission);
 4997:         }
 4998:     } elsif (($env{'form.action'} eq 'processauthorreq') &&
 4999:              ($permission->{'cusr'}) && 
 5000:              (&Apache::lonnet::allowed('cau',$env{'request.role.domain'}))) {
 5001:         push(@{$brcrum},
 5002:                  {href => '/adm/createuser?action=processauthorreq',
 5003:                   text => 'Authoring Space requests',
 5004:                   help => 'Domain_Role_Approvals'});
 5005:         $bread_crumbs_component = 'Authoring requests';
 5006:         if ($env{'form.state'} eq 'done') {
 5007:             push(@{$brcrum},
 5008:                      {href => '/adm/createuser?action=authorreqqueue',
 5009:                       text => 'Result',
 5010:                       help => 'Domain_Role_Approvals'});
 5011:             $bread_crumbs_component = 'Authoring request result';
 5012:         }
 5013:         $args = { bread_crumbs           => $brcrum,
 5014:                   bread_crumbs_component => $bread_crumbs_component};
 5015:         my $js = &usernamerequest_javascript();
 5016:         $r->print(&header(&add_script($js),$args));
 5017:         if (!exists($env{'form.state'})) {
 5018:             $r->print(&Apache::loncoursequeueadmin::display_queued_requests('requestauthor',
 5019:                                                                             $env{'request.role.domain'}));
 5020:         } elsif ($env{'form.state'} eq 'done') {
 5021:             $r->print('<h3>'.&mt('Authoring request processing').'</h3>'."\n");
 5022:             $r->print(&Apache::loncoursequeueadmin::update_request_queue('requestauthor',
 5023:                                                                          $env{'request.role.domain'}));
 5024:         }
 5025:     } elsif (($env{'form.action'} eq 'processusernamereq') &&
 5026:              ($permission->{'cusr'}) &&
 5027:              (&Apache::lonnet::allowed('cau',$env{'request.role.domain'}))) {
 5028:         push(@{$brcrum},
 5029:                  {href => '/adm/createuser?action=processusernamereq',
 5030:                   text => 'LON-CAPA account requests',
 5031:                   help => 'Domain_Username_Approvals'});
 5032:         $bread_crumbs_component = 'Account requests';
 5033:         if ($env{'form.state'} eq 'done') {
 5034:             push(@{$brcrum},
 5035:                      {href => '/adm/createuser?action=usernamereqqueue',
 5036:                       text => 'Result',
 5037:                       help => 'Domain_Username_Approvals'});
 5038:             $bread_crumbs_component = 'LON-CAPA account request result';
 5039:         }
 5040:         $args = { bread_crumbs           => $brcrum,
 5041:                   bread_crumbs_component => $bread_crumbs_component};
 5042:         my $js = &usernamerequest_javascript();
 5043:         $r->print(&header(&add_script($js),$args));
 5044:         if (!exists($env{'form.state'})) {
 5045:             $r->print(&Apache::loncoursequeueadmin::display_queued_requests('requestusername',
 5046:                                                                             $env{'request.role.domain'}));
 5047:         } elsif ($env{'form.state'} eq 'done') {
 5048:             $r->print('<h3>'.&mt('LON-CAPA account request processing').'</h3>'."\n");
 5049:             $r->print(&Apache::loncoursequeueadmin::update_request_queue('requestusername',
 5050:                                                                          $env{'request.role.domain'}));
 5051:         }
 5052:     } elsif (($env{'form.action'} eq 'displayuserreq') &&
 5053:              ($permission->{'cusr'})) {
 5054:         my $dom = $env{'form.domain'};
 5055:         my $uname = $env{'form.username'};
 5056:         my $warning;
 5057:         if (($dom =~ /^$match_domain$/) && (&Apache::lonnet::domain($dom) ne '')) {
 5058:             if (($dom eq $env{'request.role.domain'}) && (&Apache::lonnet::allowed('ccc',$dom))) {
 5059:                 if (($uname =~ /^$match_username$/) && ($env{'form.queue'} eq 'approval')) {
 5060:                     my $uhome = &Apache::lonnet::homeserver($uname,$dom);
 5061:                     if ($uhome eq 'no_host') {
 5062:                         my $queue = $env{'form.queue'};
 5063:                         my $reqkey = &escape($uname).'_'.$queue; 
 5064:                         my $namespace = 'usernamequeue';
 5065:                         my $domconfig = &Apache::lonnet::get_domainconfiguser($dom);
 5066:                         my %queued =
 5067:                             &Apache::lonnet::get($namespace,[$reqkey],$dom,$domconfig);
 5068:                         unless ($queued{$reqkey}) {
 5069:                             $warning = &mt('No information was found for this LON-CAPA account request.');
 5070:                         }
 5071:                     } else {
 5072:                         $warning = &mt('A LON-CAPA account already exists for the requested username and domain.');
 5073:                     }
 5074:                 } else {
 5075:                     $warning = &mt('LON-CAPA account request status check is for an invalid username.');
 5076:                 }
 5077:             } else {
 5078:                 $warning = &mt('You do not have rights to view LON-CAPA account requests in the domain specified.');
 5079:             }
 5080:         } else {
 5081:             $warning = &mt('LON-CAPA account request status check is for an invalid domain.');
 5082:         }
 5083:         my $args = { only_body => 1 };
 5084:         $r->print(&header(undef,$args).
 5085:                   '<h3>'.&mt('LON-CAPA Account Request Details').'</h3>');
 5086:         if ($warning ne '') {
 5087:             $r->print('<div class="LC_warning">'.$warning.'</div>');
 5088:         } else {
 5089:             my ($infofields,$infotitles) = &Apache::loncommon::emailusername_info();
 5090:             my $domconfiguser = &Apache::lonnet::get_domainconfiguser($dom);
 5091:             my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 5092:             if (ref($domconfig{'usercreation'}) eq 'HASH') {
 5093:                 if (ref($domconfig{'usercreation'}{'cancreate'}) eq 'HASH') {
 5094:                     if (ref($domconfig{'usercreation'}{'cancreate'}{'emailusername'}) eq 'HASH') {
 5095:                         my %info =
 5096:                             &Apache::lonnet::get('nohist_requestedusernames',[$uname],$dom,$domconfiguser);
 5097:                         if (ref($info{$uname}) eq 'HASH') {
 5098:                             my $usertype = $info{$uname}{'inststatus'};
 5099:                             unless ($usertype) {
 5100:                                 $usertype = 'default';
 5101:                             }
 5102:                             my ($showstatus,$showemail,$pickstart);
 5103:                             my $numextras = 0;
 5104:                             my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 5105:                             if ((ref($types) eq 'ARRAY') && (@{$types} > 0)) {
 5106:                                 if (ref($usertypes) eq 'HASH') {
 5107:                                     if ($usertypes->{$usertype}) {
 5108:                                         $showstatus = $usertypes->{$usertype};
 5109:                                     } else {
 5110:                                         $showstatus = $othertitle;
 5111:                                     }
 5112:                                     if ($showstatus) {
 5113:                                         $numextras ++;
 5114:                                     }
 5115:                                 }
 5116:                             }
 5117:                             if (($info{$uname}{'email'} ne '') && ($info{$uname}{'email'} ne $uname)) {
 5118:                                 $showemail = $info{$uname}{'email'};
 5119:                                 $numextras ++;
 5120:                             }
 5121:                             if (ref($domconfig{'usercreation'}{'cancreate'}{'emailusername'}{$usertype}) eq 'HASH') {
 5122:                                 if ((ref($infofields) eq 'ARRAY') && (ref($infotitles) eq 'HASH')) {
 5123:                                     $pickstart = 1;
 5124:                                     $r->print('<div>'.&Apache::lonhtmlcommon::start_pick_box());
 5125:                                     my ($num,$count);
 5126:                                     $count = scalar(keys(%{$domconfig{'usercreation'}{'cancreate'}{'emailusername'}{$usertype}}));
 5127:                                     $count += $numextras;
 5128:                                     foreach my $field (@{$infofields}) {
 5129:                                         next unless ($domconfig{'usercreation'}{'cancreate'}{'emailusername'}{$usertype}{$field});
 5130:                                         next unless ($infotitles->{$field});
 5131:                                         $r->print(&Apache::lonhtmlcommon::row_title($infotitles->{$field}).
 5132:                                                   $info{$uname}{$field});
 5133:                                         $num ++;
 5134:                                         unless ($count == $num) {
 5135:                                             $r->print(&Apache::lonhtmlcommon::row_closure());
 5136:                                         }
 5137:                                     }
 5138:                                 }
 5139:                             }
 5140:                             if ($numextras) {
 5141:                                 unless ($pickstart) {
 5142:                                     $r->print('<div>'.&Apache::lonhtmlcommon::start_pick_box());
 5143:                                     $pickstart = 1;
 5144:                                 }
 5145:                                 if ($showemail) {
 5146:                                     my $closure = '';
 5147:                                     unless ($showstatus) {
 5148:                                         $closure = 1;
 5149:                                     }
 5150:                                     $r->print(&Apache::lonhtmlcommon::row_title(&mt('E-mail address')).
 5151:                                               $showemail.
 5152:                                               &Apache::lonhtmlcommon::row_closure($closure));
 5153:                                 }
 5154:                                 if ($showstatus) {
 5155:                                     $r->print(&Apache::lonhtmlcommon::row_title(&mt('Status type[_1](self-reported)','<br />')).
 5156:                                               $showstatus.
 5157:                                               &Apache::lonhtmlcommon::row_closure(1));
 5158:                                 }
 5159:                             }
 5160:                             if ($pickstart) { 
 5161:                                 $r->print(&Apache::lonhtmlcommon::end_pick_box().'</div>');
 5162:                             } else {
 5163:                                 $r->print('<div>'.&mt('No information to display for this account request.').'</div>');
 5164:                             }
 5165:                         } else {
 5166:                             $r->print('<div>'.&mt('No information available for this account request.').'</div>');
 5167:                         }
 5168:                     }
 5169:                 }
 5170:             }
 5171:         }
 5172:         $r->print(&close_popup_form());
 5173:     } elsif (($env{'form.action'} eq 'listusers') && 
 5174:              ($permission->{'view'} || $permission->{'cusr'})) {
 5175:         my $helpitem = 'Course_View_Class_List';
 5176:         if ($context eq 'author') {
 5177:             $helpitem = 'Author_View_Coauthor_List';
 5178:         } elsif ($context eq 'domain') {
 5179:             $helpitem = 'Domain_View_Users_List';
 5180:         }
 5181:         if ($env{'form.phase'} eq 'bulkchange') {
 5182:             push(@{$brcrum},
 5183:                     {href => '/adm/createuser?action=listusers',
 5184:                      text => "List Users"},
 5185:                     {href => "/adm/createuser",
 5186:                      text => "Result",
 5187:                      help => $helpitem});
 5188:             $bread_crumbs_component = 'Update Users';
 5189:             $args = {bread_crumbs           => $brcrum,
 5190:                      bread_crumbs_component => $bread_crumbs_component};
 5191:             $r->print(&header(undef,$args));
 5192:             my $setting = $env{'form.roletype'};
 5193:             my $choice = $env{'form.bulkaction'};
 5194:             if ($permission->{'cusr'}) {
 5195:                 &Apache::lonuserutils::update_user_list($r,$context,$setting,$choice,$crstype);
 5196:             } else {
 5197:                 $r->print(&mt('You are not authorized to make bulk changes to user roles'));
 5198:                 $r->print('<p><a href="/adm/createuser?action=listusers">'.&mt('Display User Lists').'</a>');
 5199:             }
 5200:         } else {
 5201:             push(@{$brcrum},
 5202:                     {href => '/adm/createuser?action=listusers',
 5203:                      text => "List Users",
 5204:                      help => $helpitem});
 5205:             $bread_crumbs_component = 'List Users';
 5206:             $args = {bread_crumbs           => $brcrum,
 5207:                      bread_crumbs_component => $bread_crumbs_component};
 5208:             my ($cb_jscript,$jscript,$totcodes,$codetitles,$idlist,$idlist_titles);
 5209:             my $formname = 'studentform';
 5210:             my $hidecall = "hide_searching();";
 5211:             if (($context eq 'domain') && (($env{'form.roletype'} eq 'course') ||
 5212:                 ($env{'form.roletype'} eq 'community'))) {
 5213:                 if ($env{'form.roletype'} eq 'course') {
 5214:                     ($cb_jscript,$jscript,$totcodes,$codetitles,$idlist,$idlist_titles) = 
 5215:                         &Apache::lonuserutils::courses_selector($env{'request.role.domain'},
 5216:                                                                 $formname);
 5217:                 } elsif ($env{'form.roletype'} eq 'community') {
 5218:                     $cb_jscript = 
 5219:                         &Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'});
 5220:                     my %elements = (
 5221:                                       coursepick => 'radio',
 5222:                                       coursetotal => 'text',
 5223:                                       courselist => 'text',
 5224:                                    );
 5225:                     $jscript = &Apache::lonhtmlcommon::set_form_elements(\%elements);
 5226:                 }
 5227:                 $jscript .= &verify_user_display($context)."\n".
 5228:                             &Apache::loncommon::check_uncheck_jscript();
 5229:                 my $js = &add_script($jscript).$cb_jscript;
 5230:                 my $loadcode = 
 5231:                     &Apache::lonuserutils::course_selector_loadcode($formname);
 5232:                 if ($loadcode ne '') {
 5233:                     $args->{add_entries} = {onload => "$loadcode;$hidecall"};
 5234:                 } else {
 5235:                     $args->{add_entries} = {onload => $hidecall};
 5236:                 }
 5237:                 $r->print(&header($js,$args));
 5238:             } else {
 5239:                 $args->{add_entries} = {onload => $hidecall};
 5240:                 $jscript = &verify_user_display($context).
 5241:                            &Apache::loncommon::check_uncheck_jscript(); 
 5242:                 $r->print(&header(&add_script($jscript),$args));
 5243:             }
 5244:             &Apache::lonuserutils::print_userlist($r,undef,$permission,$context,
 5245:                          $formname,$totcodes,$codetitles,$idlist,$idlist_titles,
 5246:                          $showcredits);
 5247:         }
 5248:     } elsif ($env{'form.action'} eq 'drop' && $permission->{'cusr'}) {
 5249:         my $brtext;
 5250:         if ($crstype eq 'Community') {
 5251:             $brtext = 'Drop Members';
 5252:         } else {
 5253:             $brtext = 'Drop Students';
 5254:         }
 5255:         push(@{$brcrum},
 5256:                 {href => '/adm/createuser?action=drop',
 5257:                  text => $brtext,
 5258:                  help => 'Course_Drop_Student'});
 5259:         if ($env{'form.state'} eq 'done') {
 5260:             push(@{$brcrum},
 5261:                      {href=>'/adm/createuser?action=drop',
 5262:                       text=>"Result"});
 5263:         }
 5264:         $bread_crumbs_component = $brtext;
 5265:         $args = {bread_crumbs           => $brcrum,
 5266:                  bread_crumbs_component => $bread_crumbs_component}; 
 5267:         $r->print(&header(undef,$args));
 5268:         if (!exists($env{'form.state'})) {
 5269:             &Apache::lonuserutils::print_drop_menu($r,$context,$permission,$crstype);
 5270:         } elsif ($env{'form.state'} eq 'done') {
 5271:             &Apache::lonuserutils::update_user_list($r,$context,undef,
 5272:                                                     $env{'form.action'});
 5273:         }
 5274:     } elsif ($env{'form.action'} eq 'dateselect') {
 5275:         if ($permission->{'cusr'}) {
 5276:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 5277:                       &Apache::lonuserutils::date_section_selector($context,$permission,
 5278:                                                                    $crstype,$showcredits));
 5279:         } else {
 5280:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 5281:                      '<span class="LC_error">'.&mt('You do not have permission to modify dates or sections for users').'</span>'); 
 5282:         }
 5283:     } elsif ($env{'form.action'} eq 'selfenroll') {
 5284:         if ($permission->{selfenrolladmin}) {
 5285:             my %currsettings = (
 5286:                 selfenroll_types              => $env{'course.'.$cid.'.internal.selfenroll_types'},
 5287:                 selfenroll_registered         => $env{'course.'.$cid.'.internal.selfenroll_registered'},
 5288:                 selfenroll_section            => $env{'course.'.$cid.'.internal.selfenroll_section'},
 5289:                 selfenroll_notifylist         => $env{'course.'.$cid.'.internal.selfenroll_notifylist'},
 5290:                 selfenroll_approval           => $env{'course.'.$cid.'.internal.selfenroll_approval'},
 5291:                 selfenroll_limit              => $env{'course.'.$cid.'.internal.selfenroll_limit'},
 5292:                 selfenroll_cap                => $env{'course.'.$cid.'.internal.selfenroll_cap'},
 5293:                 selfenroll_start_date         => $env{'course.'.$cid.'.internal.selfenroll_start_date'},
 5294:                 selfenroll_end_date           => $env{'course.'.$cid.'.internal.selfenroll_end_date'},
 5295:                 selfenroll_start_access       => $env{'course.'.$cid.'.internal.selfenroll_start_access'},
 5296:                 selfenroll_end_access         => $env{'course.'.$cid.'.internal.selfenroll_end_access'},
 5297:                 default_enrollment_start_date => $env{'course.'.$cid.'.default_enrollment_start_date'},
 5298:                 default_enrollment_end_date   => $env{'course.'.$cid.'.default_enrollment_end_date'},
 5299:                 uniquecode                    => $env{'course.'.$cid.'.internal.uniquecode'},
 5300:             );
 5301:             push(@{$brcrum},
 5302:                     {href => '/adm/createuser?action=selfenroll',
 5303:                      text => "Configure Self-enrollment",
 5304:                      help => 'Course_Self_Enrollment'});
 5305:             if (!exists($env{'form.state'})) {
 5306:                 $args = { bread_crumbs           => $brcrum,
 5307:                           bread_crumbs_component => 'Configure Self-enrollment'};
 5308:                 $r->print(&header(undef,$args));
 5309:                 $r->print('<h3>'.&mt('Self-enrollment with a student role').'</h3>'."\n");
 5310:                 &print_selfenroll_menu($r,'course',$cid,$cdom,$cnum,\%currsettings);
 5311:             } elsif ($env{'form.state'} eq 'done') {
 5312:                 push (@{$brcrum},
 5313:                           {href=>'/adm/createuser?action=selfenroll',
 5314:                            text=>"Result"});
 5315:                 $args = { bread_crumbs           => $brcrum,
 5316:                           bread_crumbs_component => 'Self-enrollment result'};
 5317:                 $r->print(&header(undef,$args));
 5318:                 $r->print('<h3>'.&mt('Self-enrollment with a student role').'</h3>'."\n");
 5319:                 &update_selfenroll_config($r,$cid,$cdom,$cnum,$context,$crstype,\%currsettings);
 5320:             }
 5321:         } else {
 5322:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 5323:                      '<span class="LC_error">'.&mt('You do not have permission to configure self-enrollment').'</span>');
 5324:         }
 5325:     } elsif ($env{'form.action'} eq 'selfenrollqueue') {
 5326:         if ($permission->{selfenrolladmin}) {
 5327:             push(@{$brcrum},
 5328:                      {href => '/adm/createuser?action=selfenrollqueue',
 5329:                       text => 'Enrollment requests',
 5330:                       help => 'Course_Approve_Selfenroll'});
 5331:             $bread_crumbs_component = 'Enrollment requests';
 5332:             if ($env{'form.state'} eq 'done') {
 5333:                 push(@{$brcrum},
 5334:                          {href => '/adm/createuser?action=selfenrollqueue',
 5335:                           text => 'Result',
 5336:                           help => 'Course_Approve_Selfenroll'});
 5337:                 $bread_crumbs_component = 'Enrollment result';
 5338:             }
 5339:             $args = { bread_crumbs           => $brcrum,
 5340:                       bread_crumbs_component => $bread_crumbs_component};
 5341:             $r->print(&header(undef,$args));
 5342:             my $coursedesc = $env{'course.'.$cid.'.description'};
 5343:             if (!exists($env{'form.state'})) {
 5344:                 $r->print('<h3>'.&mt('Pending enrollment requests').'</h3>'."\n");
 5345:                 $r->print(&Apache::loncoursequeueadmin::display_queued_requests($context,
 5346:                                                                                 $cdom,$cnum));
 5347:             } elsif ($env{'form.state'} eq 'done') {
 5348:                 $r->print('<h3>'.&mt('Enrollment request processing').'</h3>'."\n");
 5349:                 $r->print(&Apache::loncoursequeueadmin::update_request_queue($context,
 5350:                               $cdom,$cnum,$coursedesc));
 5351:             }
 5352:         } else {
 5353:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 5354:                      '<span class="LC_error">'.&mt('You do not have permission to manage self-enrollment').'</span>');
 5355:         }
 5356:     } elsif ($env{'form.action'} eq 'changelogs') {
 5357:         if ($permission->{cusr} || $permission->{view}) {
 5358:             &print_userchangelogs_display($r,$context,$permission,$brcrum);
 5359:         } else {
 5360:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 5361:                      '<span class="LC_error">'.&mt('You do not have permission to view change logs').'</span>');
 5362:         }
 5363:     } elsif ($env{'form.action'} eq 'helpdesk') {
 5364:         if (($permission->{'owner'}) || ($permission->{'co-owner'})) {
 5365:             if ($env{'form.state'} eq 'process') {
 5366:                 if ($permission->{'owner'}) {
 5367:                     &update_helpdeskaccess($r,$permission,$brcrum);
 5368:                 } else {
 5369:                     &print_helpdeskaccess_display($r,$permission,$brcrum);
 5370:                 }
 5371:             } else {
 5372:                 &print_helpdeskaccess_display($r,$permission,$brcrum);
 5373:             }
 5374:         } else {
 5375:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 5376:                       '<span class="LC_error">'.&mt('You do not have permission to view helpdesk access').'</span>');
 5377:         }
 5378:     } else {
 5379:         $bread_crumbs_component = 'User Management';
 5380:         $args = { bread_crumbs           => $brcrum,
 5381:                   bread_crumbs_component => $bread_crumbs_component};
 5382:         $r->print(&header(undef,$args));
 5383:         $r->print(&print_main_menu($permission,$context,$crstype));
 5384:     }
 5385:     $r->print(&Apache::loncommon::end_page());
 5386:     return OK;
 5387: }
 5388: 
 5389: sub header {
 5390:     my ($jscript,$args) = @_;
 5391:     my $start_page;
 5392:     if (ref($args) eq 'HASH') {
 5393:         $start_page=&Apache::loncommon::start_page('User Management',$jscript,$args);
 5394:     } else {
 5395:         $start_page=&Apache::loncommon::start_page('User Management',$jscript);
 5396:     }
 5397:     return $start_page;
 5398: }
 5399: 
 5400: sub add_script {
 5401:     my ($js) = @_;
 5402:     return '<script type="text/javascript">'."\n"
 5403:           .'// <![CDATA['."\n"
 5404:           .$js."\n"
 5405:           .'// ]]>'."\n"
 5406:           .'</script>'."\n";
 5407: }
 5408: 
 5409: sub usernamerequest_javascript {
 5410:     my $js = <<ENDJS;
 5411: 
 5412: function openusernamereqdisplay(dom,uname,queue) {
 5413:     var url = '/adm/createuser?action=displayuserreq';
 5414:     url += '&domain='+dom+'&username='+uname+'&queue='+queue;
 5415:     var title = 'Account_Request_Browser';
 5416:     var options = 'scrollbars=1,resizable=1,menubar=0';
 5417:     options += ',width=700,height=600';
 5418:     var stdeditbrowser = open(url,title,options,'1');
 5419:     stdeditbrowser.focus();
 5420:     return;
 5421: }
 5422:  
 5423: ENDJS
 5424: }
 5425: 
 5426: sub close_popup_form {
 5427:     my $close= &mt('Close Window');
 5428:     return << "END";
 5429: <p><form name="displayreq" action="" method="post">
 5430: <input type="button" name="closeme" value="$close" onclick="javascript:self.close();" />
 5431: </form></p>
 5432: END
 5433: }
 5434: 
 5435: sub verify_user_display {
 5436:     my ($context) = @_;
 5437:     my %lt = &Apache::lonlocal::texthash (
 5438:         course    => 'course(s): description, section(s), status',
 5439:         community => 'community(s): description, section(s), status',
 5440:         author    => 'author',
 5441:     );
 5442:     my $photos;
 5443:     if (($context eq 'course') && $env{'request.course.id'}) {
 5444:         $photos = $env{'course.'.$env{'request.course.id'}.'.internal.showphoto'};
 5445:     }
 5446:     my $output = <<"END";
 5447: 
 5448: function hide_searching() {
 5449:     if (document.getElementById('searching')) {
 5450:         document.getElementById('searching').style.display = 'none';
 5451:     }
 5452:     return;
 5453: }
 5454: 
 5455: function display_update() {
 5456:     document.studentform.action.value = 'listusers';
 5457:     document.studentform.phase.value = 'display';
 5458:     document.studentform.submit();
 5459: }
 5460: 
 5461: function updateCols(caller) {
 5462:     var context = '$context';
 5463:     var photos = '$photos';
 5464:     if (caller == 'Status') {
 5465:         if ((context == 'domain') && 
 5466:             ((document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'course') ||
 5467:              (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'community'))) {
 5468:             document.getElementById('showcolstatus').checked = false;
 5469:             document.getElementById('showcolstatus').disabled = 'disabled';
 5470:             document.getElementById('showcolstart').checked = false;
 5471:             document.getElementById('showcolend').checked = false;
 5472:         } else {
 5473:             if (document.studentform.Status.options[document.studentform.Status.selectedIndex].value == 'Any') {
 5474:                 document.getElementById('showcolstatus').checked = true;
 5475:                 document.getElementById('showcolstatus').disabled = '';
 5476:                 document.getElementById('showcolstart').checked = true;
 5477:                 document.getElementById('showcolend').checked = true;
 5478:             } else {
 5479:                 document.getElementById('showcolstatus').checked = false;
 5480:                 document.getElementById('showcolstatus').disabled = 'disabled';
 5481:                 document.getElementById('showcolstart').checked = false;
 5482:                 document.getElementById('showcolend').checked = false;
 5483:             }
 5484:         }
 5485:     }
 5486:     if (caller == 'output') {
 5487:         if (photos == 1) {
 5488:             if (document.getElementById('showcolphoto')) {
 5489:                 var photoitem = document.getElementById('showcolphoto');
 5490:                 if (document.studentform.output.options[document.studentform.output.selectedIndex].value == 'html') {
 5491:                     photoitem.checked = true;
 5492:                     photoitem.disabled = '';
 5493:                 } else {
 5494:                     photoitem.checked = false;
 5495:                     photoitem.disabled = 'disabled';
 5496:                 }
 5497:             }
 5498:         }
 5499:     }
 5500:     if (caller == 'showrole') {
 5501:         if ((document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'Any') ||
 5502:             (document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'cr')) {
 5503:             document.getElementById('showcolrole').checked = true;
 5504:             document.getElementById('showcolrole').disabled = '';
 5505:         } else {
 5506:             document.getElementById('showcolrole').checked = false;
 5507:             document.getElementById('showcolrole').disabled = 'disabled';
 5508:         }
 5509:         if (context == 'domain') {
 5510:             var quotausageshow = 0;
 5511:             if ((document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'course') ||
 5512:                 (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'community')) {
 5513:                 document.getElementById('showcolstatus').checked = false;
 5514:                 document.getElementById('showcolstatus').disabled = 'disabled';
 5515:                 document.getElementById('showcolstart').checked = false;
 5516:                 document.getElementById('showcolend').checked = false;
 5517:             } else {
 5518:                 if (document.studentform.Status.options[document.studentform.Status.selectedIndex].value == 'Any') {
 5519:                     document.getElementById('showcolstatus').checked = true;
 5520:                     document.getElementById('showcolstatus').disabled = '';
 5521:                     document.getElementById('showcolstart').checked = true;
 5522:                     document.getElementById('showcolend').checked = true;
 5523:                 }
 5524:             }
 5525:             if (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'domain') {
 5526:                 document.getElementById('showcolextent').disabled = 'disabled';
 5527:                 document.getElementById('showcolextent').checked = 'false';
 5528:                 document.getElementById('showextent').style.display='none';
 5529:                 document.getElementById('showcoltextextent').innerHTML = '';
 5530:                 if ((document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'au') ||
 5531:                     (document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'Any')) {
 5532:                     if (document.getElementById('showcolauthorusage')) {
 5533:                         document.getElementById('showcolauthorusage').disabled = '';
 5534:                     }
 5535:                     if (document.getElementById('showcolauthorquota')) {
 5536:                         document.getElementById('showcolauthorquota').disabled = '';
 5537:                     }
 5538:                     quotausageshow = 1;
 5539:                 }
 5540:             } else {
 5541:                 document.getElementById('showextent').style.display='block';
 5542:                 document.getElementById('showextent').style.textAlign='left';
 5543:                 document.getElementById('showextent').style.textFace='normal';
 5544:                 if (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'author') {
 5545:                     document.getElementById('showcolextent').disabled = '';
 5546:                     document.getElementById('showcolextent').checked = 'true';
 5547:                     document.getElementById('showcoltextextent').innerHTML="$lt{'author'}";
 5548:                 } else {
 5549:                     document.getElementById('showcolextent').disabled = '';
 5550:                     document.getElementById('showcolextent').checked = 'true';
 5551:                     if (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'community') {
 5552:                         document.getElementById('showcoltextextent').innerHTML="$lt{'community'}";
 5553:                     } else {
 5554:                         document.getElementById('showcoltextextent').innerHTML="$lt{'course'}";
 5555:                     }
 5556:                 }
 5557:             }
 5558:             if (quotausageshow == 0)  {
 5559:                 if (document.getElementById('showcolauthorusage')) {
 5560:                     document.getElementById('showcolauthorusage').checked = false;
 5561:                     document.getElementById('showcolauthorusage').disabled = 'disabled';
 5562:                 }
 5563:                 if (document.getElementById('showcolauthorquota')) {
 5564:                     document.getElementById('showcolauthorquota').checked = false;
 5565:                     document.getElementById('showcolauthorquota').disabled = 'disabled';
 5566:                 }
 5567:             }
 5568:         }
 5569:     }
 5570:     return;
 5571: }
 5572: 
 5573: END
 5574:     return $output;
 5575: 
 5576: }
 5577: 
 5578: ###############################################################
 5579: ###############################################################
 5580: #  Menu Phase One
 5581: sub print_main_menu {
 5582:     my ($permission,$context,$crstype) = @_;
 5583:     my $linkcontext = $context;
 5584:     my $stuterm = lc(&Apache::lonnet::plaintext('st',$crstype));
 5585:     if (($context eq 'course') && ($crstype eq 'Community')) {
 5586:         $linkcontext = lc($crstype);
 5587:         $stuterm = 'Members';
 5588:     }
 5589:     my %links = (
 5590:                 domain => {
 5591:                             upload     => 'Upload a File of Users',
 5592:                             singleuser => 'Add/Modify a User',
 5593:                             listusers  => 'Manage Users',
 5594:                             },
 5595:                 author => {
 5596:                             upload     => 'Upload a File of Co-authors',
 5597:                             singleuser => 'Add/Modify a Co-author',
 5598:                             listusers  => 'Manage Co-authors',
 5599:                             },
 5600:                 course => {
 5601:                             upload     => 'Upload a File of Course Users',
 5602:                             singleuser => 'Add/Modify a Course User',
 5603:                             listusers  => 'List and Modify Multiple Course Users',
 5604:                             },
 5605:                 community => {
 5606:                             upload     => 'Upload a File of Community Users',
 5607:                             singleuser => 'Add/Modify a Community User',
 5608:                             listusers  => 'List and Modify Multiple Community Users',
 5609:                            },
 5610:                 );
 5611:      my %linktitles = (
 5612:                 domain => {
 5613:                             singleuser => 'Add a user to the domain, and/or a course or community in the domain.',
 5614:                             listusers  => 'Show and manage users in this domain.',
 5615:                             },
 5616:                 author => {
 5617:                             singleuser => 'Add a user with a co- or assistant author role.',
 5618:                             listusers  => 'Show and manage co- or assistant authors.',
 5619:                             },
 5620:                 course => {
 5621:                             singleuser => 'Add a user with a certain role to this course.',
 5622:                             listusers  => 'Show and manage users in this course.',
 5623:                             },
 5624:                 community => {
 5625:                             singleuser => 'Add a user with a certain role to this community.',
 5626:                             listusers  => 'Show and manage users in this community.',
 5627:                            },
 5628:                 );
 5629:   if ($linkcontext eq 'domain') {
 5630:       unless ($permission->{'cusr'}) {
 5631:           $links{'domain'}{'singleuser'} = 'View a User';
 5632:           $linktitles{'domain'}{'singleuser'} = 'View information about a user in the domain';
 5633:       }
 5634:   } elsif ($linkcontext eq 'course') {
 5635:       unless ($permission->{'cusr'}) {
 5636:           $links{'course'}{'singleuser'} = 'View a Course User';
 5637:           $linktitles{'course'}{'singleuser'} = 'View information about a user in this course';
 5638:           $links{'course'}{'listusers'} = 'List Course Users';
 5639:           $linktitles{'course'}{'listusers'} = 'Show information about users in this course';
 5640:       }
 5641:   } elsif ($linkcontext eq 'community') {
 5642:       unless ($permission->{'cusr'}) {
 5643:           $links{'community'}{'singleuser'} = 'View a Community User';
 5644:           $linktitles{'community'}{'singleuser'} = 'View information about a user in this community';
 5645:           $links{'community'}{'listusers'} = 'List Community Users';
 5646:           $linktitles{'community'}{'listusers'} = 'Show information about users in this community';
 5647:       }
 5648:   }
 5649:   my @menu = ( {categorytitle => 'Single Users', 
 5650:          items =>
 5651:          [
 5652:             {
 5653:              linktext => $links{$linkcontext}{'singleuser'},
 5654:              icon => 'edit-redo.png',
 5655:              #help => 'Course_Change_Privileges',
 5656:              url => '/adm/createuser?action=singleuser',
 5657:              permission => ($permission->{'view'} || $permission->{'cusr'}),
 5658:              linktitle => $linktitles{$linkcontext}{'singleuser'},
 5659:             },
 5660:          ]},
 5661: 
 5662:          {categorytitle => 'Multiple Users',
 5663:          items => 
 5664:          [
 5665:             {
 5666:              linktext => $links{$linkcontext}{'upload'},
 5667:              icon => 'uplusr.png',
 5668:              #help => 'Course_Create_Class_List',
 5669:              url => '/adm/createuser?action=upload',
 5670:              permission => $permission->{'cusr'},
 5671:              linktitle => 'Upload a CSV or a text file containing users.',
 5672:             },
 5673:             {
 5674:              linktext => $links{$linkcontext}{'listusers'},
 5675:              icon => 'mngcu.png',
 5676:              #help => 'Course_View_Class_List',
 5677:              url => '/adm/createuser?action=listusers',
 5678:              permission => ($permission->{'view'} || $permission->{'cusr'}),
 5679:              linktitle => $linktitles{$linkcontext}{'listusers'}, 
 5680:             },
 5681: 
 5682:          ]},
 5683: 
 5684:          {categorytitle => 'Administration',
 5685:          items => [ ]},
 5686:        );
 5687: 
 5688:     if ($context eq 'domain'){
 5689:         push(@{  $menu[0]->{items} }, # Single Users
 5690:             {
 5691:              linktext => 'User Access Log',
 5692:              icon => 'document-properties.png',
 5693:              #help => 'Domain_User_Access_Logs',
 5694:              url => '/adm/createuser?action=accesslogs',
 5695:              permission => $permission->{'activity'},
 5696:              linktitle => 'View user access log.',
 5697:             }
 5698:         );
 5699:         
 5700:         push(@{ $menu[2]->{items} }, #Category: Administration
 5701:             {
 5702:              linktext => 'Custom Roles',
 5703:              icon => 'emblem-photos.png',
 5704:              #help => 'Course_Editing_Custom_Roles',
 5705:              url => '/adm/createuser?action=custom',
 5706:              permission => $permission->{'custom'},
 5707:              linktitle => 'Configure a custom role.',
 5708:             },
 5709:             {
 5710:              linktext => 'Authoring Space Requests',
 5711:              icon => 'selfenrl-queue.png',
 5712:              #help => 'Domain_Role_Approvals',
 5713:              url => '/adm/createuser?action=processauthorreq',
 5714:              permission => $permission->{'cusr'},
 5715:              linktitle => 'Approve or reject author role requests',
 5716:             },
 5717:             {
 5718:              linktext => 'LON-CAPA Account Requests',
 5719:              icon => 'list-add.png',
 5720:              #help => 'Domain_Username_Approvals',
 5721:              url => '/adm/createuser?action=processusernamereq',
 5722:              permission => $permission->{'cusr'},
 5723:              linktitle => 'Approve or reject LON-CAPA account requests',
 5724:             },
 5725:             {
 5726:              linktext => 'Change Log',
 5727:              icon => 'document-properties.png',
 5728:              #help => 'Course_User_Logs',
 5729:              url => '/adm/createuser?action=changelogs',
 5730:              permission => ($permission->{'cusr'} || $permission->{'view'}),
 5731:              linktitle => 'View change log.',
 5732:             },
 5733:         );
 5734:         
 5735:     }elsif ($context eq 'course'){
 5736:         my ($cnum,$cdom) = &Apache::lonuserutils::get_course_identity();
 5737: 
 5738:         my %linktext = (
 5739:                          'Course'    => {
 5740:                                           single => 'Add/Modify a Student', 
 5741:                                           drop   => 'Drop Students',
 5742:                                           groups => 'Course Groups',
 5743:                                         },
 5744:                          'Community' => {
 5745:                                           single => 'Add/Modify a Member', 
 5746:                                           drop   => 'Drop Members',
 5747:                                           groups => 'Community Groups',
 5748:                                         },
 5749:                        );
 5750:         $linktext{'Placement'} = $linktext{'Course'};
 5751: 
 5752:         my %linktitle = (
 5753:             'Course' => {
 5754:                   single => 'Add a user with the role of student to this course',
 5755:                   drop   => 'Remove a student from this course.',
 5756:                   groups => 'Manage course groups',
 5757:                         },
 5758:             'Community' => {
 5759:                   single => 'Add a user with the role of member to this community',
 5760:                   drop   => 'Remove a member from this community.',
 5761:                   groups => 'Manage community groups',
 5762:                            },
 5763:         );
 5764: 
 5765:         $linktitle{'Placement'} = $linktitle{'Course'};
 5766: 
 5767:         push(@{ $menu[0]->{items} }, #Category: Single Users
 5768:             {   
 5769:              linktext => $linktext{$crstype}{'single'},
 5770:              #help => 'Course_Add_Student',
 5771:              icon => 'list-add.png',
 5772:              url => '/adm/createuser?action=singlestudent',
 5773:              permission => $permission->{'cusr'},
 5774:              linktitle => $linktitle{$crstype}{'single'},
 5775:             },
 5776:         );
 5777:         
 5778:         push(@{ $menu[1]->{items} }, #Category: Multiple Users 
 5779:             {
 5780:              linktext => $linktext{$crstype}{'drop'},
 5781:              icon => 'edit-undo.png',
 5782:              #help => 'Course_Drop_Student',
 5783:              url => '/adm/createuser?action=drop',
 5784:              permission => $permission->{'cusr'},
 5785:              linktitle => $linktitle{$crstype}{'drop'},
 5786:             },
 5787:         );
 5788:         push(@{ $menu[2]->{items} }, #Category: Administration
 5789:             {
 5790:              linktext => 'Helpdesk Access',
 5791:              icon => 'helpdesk-access.png',
 5792:              #help => 'Course_Helpdesk_Access',
 5793:              url => '/adm/createuser?action=helpdesk',
 5794:              permission => ($permission->{'owner'} || $permission->{'co-owner'}),
 5795:              linktitle => 'Helpdesk access options',
 5796:             },
 5797:             {
 5798:              linktext => 'Custom Roles',
 5799:              icon => 'emblem-photos.png',
 5800:              #help => 'Course_Editing_Custom_Roles',
 5801:              url => '/adm/createuser?action=custom',
 5802:              permission => $permission->{'custom'},
 5803:              linktitle => 'Configure a custom role.',
 5804:             },
 5805:             {
 5806:              linktext => $linktext{$crstype}{'groups'},
 5807:              icon => 'grps.png',
 5808:              #help => 'Course_Manage_Group',
 5809:              url => '/adm/coursegroups?refpage=cusr',
 5810:              permission => $permission->{'grp_manage'},
 5811:              linktitle => $linktitle{$crstype}{'groups'},
 5812:             },
 5813:             {
 5814:              linktext => 'Change Log',
 5815:              icon => 'document-properties.png',
 5816:              #help => 'Course_User_Logs',
 5817:              url => '/adm/createuser?action=changelogs',
 5818:              permission => ($permission->{'view'} || $permission->{'cusr'}),
 5819:              linktitle => 'View change log.',
 5820:             },
 5821:         );
 5822:         if ($env{'course.'.$env{'request.course.id'}.'.internal.selfenroll_approval'}) {
 5823:             push(@{ $menu[2]->{items} },
 5824:                     {
 5825:                      linktext => 'Enrollment Requests',
 5826:                      icon => 'selfenrl-queue.png',
 5827:                      #help => 'Course_Approve_Selfenroll',
 5828:                      url => '/adm/createuser?action=selfenrollqueue',
 5829:                      permission => $permission->{'selfenrolladmin'},
 5830:                      linktitle =>'Approve or reject enrollment requests.',
 5831:                     },
 5832:             );
 5833:         }
 5834:         
 5835:         if (!exists($permission->{'cusr_section'})){
 5836:             if ($crstype ne 'Community') {
 5837:                 push(@{ $menu[2]->{items} },
 5838:                     {
 5839:                      linktext => 'Automated Enrollment',
 5840:                      icon => 'roles.png',
 5841:                      #help => 'Course_Automated_Enrollment',
 5842:                      permission => (&Apache::lonnet::auto_run($cnum,$cdom)
 5843:                                          && (($permission->{'cusr'}) ||
 5844:                                              ($permission->{'view'}))),
 5845:                      url  => '/adm/populate',
 5846:                      linktitle => 'Automated enrollment manager.',
 5847:                     }
 5848:                 );
 5849:             }
 5850:             push(@{ $menu[2]->{items} }, 
 5851:                 {
 5852:                  linktext => 'User Self-Enrollment',
 5853:                  icon => 'self_enroll.png',
 5854:                  #help => 'Course_Self_Enrollment',
 5855:                  url => '/adm/createuser?action=selfenroll',
 5856:                  permission => $permission->{'selfenrolladmin'},
 5857:                  linktitle => 'Configure user self-enrollment.',
 5858:                 },
 5859:             );
 5860:         }
 5861:     } elsif ($context eq 'author') {
 5862:         push(@{ $menu[2]->{items} }, #Category: Administration
 5863:             {
 5864:              linktext => 'Change Log',
 5865:              icon => 'document-properties.png',
 5866:              #help => 'Course_User_Logs',
 5867:              url => '/adm/createuser?action=changelogs',
 5868:              permission => $permission->{'cusr'},
 5869:              linktitle => 'View change log.',
 5870:             },
 5871:         );
 5872:     }
 5873:     return Apache::lonhtmlcommon::generate_menu(@menu);
 5874: #               { text => 'View Log-in History',
 5875: #                 help => 'Course_User_Logins',
 5876: #                 action => 'logins',
 5877: #                 permission => $permission->{'cusr'},
 5878: #               });
 5879: }
 5880: 
 5881: sub restore_prev_selections {
 5882:     my %saveable_parameters = ('srchby'   => 'scalar',
 5883: 			       'srchin'   => 'scalar',
 5884: 			       'srchtype' => 'scalar',
 5885: 			       );
 5886:     &Apache::loncommon::store_settings('user','user_picker',
 5887: 				       \%saveable_parameters);
 5888:     &Apache::loncommon::restore_settings('user','user_picker',
 5889: 					 \%saveable_parameters);
 5890: }
 5891: 
 5892: sub print_selfenroll_menu {
 5893:     my ($r,$context,$cid,$cdom,$cnum,$currsettings,$additional,$readonly) = @_;
 5894:     my $crstype = &Apache::loncommon::course_type();
 5895:     my $formname = 'selfenroll';
 5896:     my $nolink = 1;
 5897:     my ($row,$lt) = &Apache::lonuserutils::get_selfenroll_titles();
 5898:     my $groupslist = &Apache::lonuserutils::get_groupslist();
 5899:     my $setsec_js = 
 5900:         &Apache::lonuserutils::setsections_javascript($formname,$groupslist);
 5901:     my %alerts = &Apache::lonlocal::texthash(
 5902:         acto => 'Activation of self-enrollment was selected for the following domain(s)',
 5903:         butn => 'but no user types have been checked.',
 5904:         wilf => "Please uncheck 'activate' or check at least one type.",
 5905:     );
 5906:     my $disabled;
 5907:     if ($readonly) {
 5908:        $disabled = ' disabled="disabled"';
 5909:     }
 5910:     &js_escape(\%alerts);
 5911:     my $selfenroll_js = <<"ENDSCRIPT";
 5912: function update_types(caller,num) {
 5913:     var delidx = getIndexByName('selfenroll_delete');
 5914:     var actidx = getIndexByName('selfenroll_activate');
 5915:     if (caller == 'selfenroll_all') {
 5916:         var selall;
 5917:         for (var i=0; i<document.$formname.selfenroll_all.length; i++) {
 5918:             if (document.$formname.selfenroll_all[i].checked) {
 5919:                 selall = document.$formname.selfenroll_all[i].value;
 5920:             }
 5921:         }
 5922:         if (selall == 1) {
 5923:             if (delidx != -1) {
 5924:                 if (document.$formname.selfenroll_delete.length) {
 5925:                     for (var j=0; j<document.$formname.selfenroll_delete.length; j++) {
 5926:                         document.$formname.selfenroll_delete[j].checked = true;
 5927:                     }
 5928:                 } else {
 5929:                     document.$formname.elements[delidx].checked = true;
 5930:                 }
 5931:             }
 5932:             if (actidx != -1) {
 5933:                 if (document.$formname.selfenroll_activate.length) {
 5934:                     for (var j=0; j<document.$formname.selfenroll_activate.length; j++) {
 5935:                         document.$formname.selfenroll_activate[j].checked = false;
 5936:                     }
 5937:                 } else {
 5938:                     document.$formname.elements[actidx].checked = false;
 5939:                 }
 5940:             }
 5941:             document.$formname.selfenroll_newdom.selectedIndex = 0; 
 5942:         }
 5943:     }
 5944:     if (caller == 'selfenroll_activate') {
 5945:         if (document.$formname.selfenroll_activate.length) {
 5946:             for (var j=0; j<document.$formname.selfenroll_activate.length; j++) {
 5947:                 if (document.$formname.selfenroll_activate[j].value == num) {
 5948:                     if (document.$formname.selfenroll_activate[j].checked) {
 5949:                         for (var i=0; i<document.$formname.selfenroll_all.length; i++) {
 5950:                             if (document.$formname.selfenroll_all[i].value == '1') {
 5951:                                 document.$formname.selfenroll_all[i].checked = false;
 5952:                             }
 5953:                             if (document.$formname.selfenroll_all[i].value == '0') {
 5954:                                 document.$formname.selfenroll_all[i].checked = true;
 5955:                             }
 5956:                         }
 5957:                     }
 5958:                 }
 5959:             }
 5960:         } else {
 5961:             for (var i=0; i<document.$formname.selfenroll_all.length; i++) {
 5962:                 if (document.$formname.selfenroll_all[i].value == '1') {
 5963:                     document.$formname.selfenroll_all[i].checked = false;
 5964:                 }
 5965:                 if (document.$formname.selfenroll_all[i].value == '0') {
 5966:                     document.$formname.selfenroll_all[i].checked = true;
 5967:                 }
 5968:             }
 5969:         }
 5970:     }
 5971:     if (caller == 'selfenroll_delete') {
 5972:         if (document.$formname.selfenroll_delete.length) {
 5973:             for (var j=0; j<document.$formname.selfenroll_delete.length; j++) {
 5974:                 if (document.$formname.selfenroll_delete[j].value == num) {
 5975:                     if (document.$formname.selfenroll_delete[j].checked) {
 5976:                         var delindex = getIndexByName('selfenroll_types_'+num);
 5977:                         if (delindex != -1) { 
 5978:                             if (document.$formname.elements[delindex].length) {
 5979:                                 for (var k=0; k<document.$formname.elements[delindex].length; k++) {
 5980:                                     document.$formname.elements[delindex][k].checked = false;
 5981:                                 }
 5982:                             } else {
 5983:                                 document.$formname.elements[delindex].checked = false;
 5984:                             }
 5985:                         }
 5986:                     }
 5987:                 }
 5988:             }
 5989:         } else {
 5990:             if (document.$formname.selfenroll_delete.checked) {
 5991:                 var delindex = getIndexByName('selfenroll_types_'+num);
 5992:                 if (delindex != -1) {
 5993:                     if (document.$formname.elements[delindex].length) {
 5994:                         for (var k=0; k<document.$formname.elements[delindex].length; k++) {
 5995:                             document.$formname.elements[delindex][k].checked = false;
 5996:                         }
 5997:                     } else {
 5998:                         document.$formname.elements[delindex].checked = false;
 5999:                     }
 6000:                 }
 6001:             }
 6002:         }
 6003:     }
 6004:     return;
 6005: }
 6006: 
 6007: function validate_types(form) {
 6008:     var needaction = new Array();
 6009:     var countfail = 0;
 6010:     var actidx = getIndexByName('selfenroll_activate');
 6011:     if (actidx != -1) {
 6012:         if (document.$formname.selfenroll_activate.length) {
 6013:             for (var j=0; j<document.$formname.selfenroll_activate.length; j++) {
 6014:                 var num = document.$formname.selfenroll_activate[j].value;
 6015:                 if (document.$formname.selfenroll_activate[j].checked) {
 6016:                     countfail = check_types(num,countfail,needaction)
 6017:                 }
 6018:             }
 6019:         } else {
 6020:             if (document.$formname.selfenroll_activate.checked) {
 6021:                 var num = document.$formname.selfenroll_activate.value;
 6022:                 countfail = check_types(num,countfail,needaction)
 6023:             }
 6024:         }
 6025:     }
 6026:     if (countfail > 0) {
 6027:         var msg = "$alerts{'acto'}\\n";
 6028:         var loopend = needaction.length -1;
 6029:         if (loopend > 0) {
 6030:             for (var m=0; m<loopend; m++) {
 6031:                 msg += needaction[m]+", ";
 6032:             }
 6033:         }
 6034:         msg += needaction[loopend]+"\\n$alerts{'butn'}\\n$alerts{'wilf'}";
 6035:         alert(msg);
 6036:         return; 
 6037:     }
 6038:     setSections(form);
 6039: }
 6040: 
 6041: function check_types(num,countfail,needaction) {
 6042:     var boxname = 'selfenroll_types_'+num;
 6043:     var typeidx = getIndexByName(boxname);
 6044:     var count = 0;
 6045:     if (typeidx != -1) {
 6046:         if (document.$formname.elements[boxname].length) {
 6047:             for (var k=0; k<document.$formname.elements[boxname].length; k++) {
 6048:                 if (document.$formname.elements[boxname][k].checked) {
 6049:                     count ++;
 6050:                 }
 6051:             }
 6052:         } else {
 6053:             if (document.$formname.elements[typeidx].checked) {
 6054:                 count ++;
 6055:             }
 6056:         }
 6057:         if (count == 0) {
 6058:             var domidx = getIndexByName('selfenroll_dom_'+num);
 6059:             if (domidx != -1) {
 6060:                 var domname = document.$formname.elements[domidx].value;
 6061:                 needaction[countfail] = domname;
 6062:                 countfail ++;
 6063:             }
 6064:         }
 6065:     }
 6066:     return countfail;
 6067: }
 6068: 
 6069: function toggleNotify() {
 6070:     var selfenrollApproval = 0;
 6071:     if (document.$formname.selfenroll_approval.length) {
 6072:         for (var i=0; i<document.$formname.selfenroll_approval.length; i++) {
 6073:             if (document.$formname.selfenroll_approval[i].checked) {
 6074:                 selfenrollApproval = document.$formname.selfenroll_approval[i].value;
 6075:                 break;        
 6076:             }
 6077:         }
 6078:     }
 6079:     if (document.getElementById('notified')) {
 6080:         if (selfenrollApproval == 0) {
 6081:             document.getElementById('notified').style.display='none';
 6082:         } else {
 6083:             document.getElementById('notified').style.display='block';
 6084:         }
 6085:     }
 6086:     return;
 6087: }
 6088: 
 6089: function getIndexByName(item) {
 6090:     for (var i=0;i<document.$formname.elements.length;i++) {
 6091:         if (document.$formname.elements[i].name == item) {
 6092:             return i;
 6093:         }
 6094:     }
 6095:     return -1;
 6096: }
 6097: ENDSCRIPT
 6098: 
 6099:     my $output = '<script type="text/javascript">'."\n".
 6100:                  '// <![CDATA['."\n".
 6101:                  $setsec_js."\n".$selfenroll_js."\n".
 6102:                  '// ]]>'."\n".
 6103:                  '</script>'."\n".
 6104:                  '<h3>'.$lt->{'selfenroll'}.'</h3>'."\n";
 6105:  
 6106:     my $visactions = &cat_visibility();
 6107:     my ($cathash,%cattype);
 6108:     my %domconfig = &Apache::lonnet::get_dom('configuration',['coursecategories'],$cdom);
 6109:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 6110:         $cathash = $domconfig{'coursecategories'}{'cats'};
 6111:         $cattype{'auth'} = $domconfig{'coursecategories'}{'auth'};
 6112:         $cattype{'unauth'} = $domconfig{'coursecategories'}{'unauth'};
 6113:         if ($cattype{'auth'} eq '') {
 6114:             $cattype{'auth'} = 'std';
 6115:         }
 6116:         if ($cattype{'unauth'} eq '') {
 6117:             $cattype{'unauth'} = 'std';
 6118:         }
 6119:     } else {
 6120:         $cathash = {};
 6121:         $cattype{'auth'} = 'std';
 6122:         $cattype{'unauth'} = 'std';
 6123:     }
 6124:     if (($cattype{'auth'} eq 'none') && ($cattype{'unauth'} eq 'none')) {
 6125:         $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
 6126:                   '<br />'.
 6127:                   '<br />'.$visactions->{'take'}.'<ul>'.
 6128:                   '<li>'.$visactions->{'dc_chgconf'}.'</li>'.
 6129:                   '</ul>');
 6130:     } elsif (($cattype{'auth'} !~ /^(std|domonly)$/) && ($cattype{'unauth'} !~ /^(std|domonly)$/)) {
 6131:         if ($currsettings->{'uniquecode'}) {
 6132:             $r->print('<span class="LC_info">'.$visactions->{'vis'}.'</span>');
 6133:         } else {
 6134:             $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
 6135:                   '<br />'.
 6136:                   '<br />'.$visactions->{'take'}.'<ul>'.
 6137:                   '<li>'.$visactions->{'dc_setcode'}.'</li>'.
 6138:                   '</ul><br />');
 6139:         }
 6140:     } else {
 6141:         my ($visible,$cansetvis,$vismsgs) = &visible_in_stdcat($cdom,$cnum,\%domconfig);
 6142:         if (ref($visactions) eq 'HASH') {
 6143:             if ($visible) {
 6144:                 $output .= '<p class="LC_info">'.$visactions->{'vis'}.'</p>';
 6145:            } else {
 6146:                 $output .= '<p class="LC_warning">'.$visactions->{'miss'}.'</p>'
 6147:                           .$visactions->{'yous'}.
 6148:                            '<p>'.$visactions->{'gen'}.'<br />'.$visactions->{'coca'};
 6149:                 if (ref($vismsgs) eq 'ARRAY') {
 6150:                     $output .= '<br />'.$visactions->{'make'}.'<ul>';
 6151:                     foreach my $item (@{$vismsgs}) {
 6152:                         $output .= '<li>'.$visactions->{$item}.'</li>';
 6153:                     }
 6154:                     $output .= '</ul>';
 6155:                 }
 6156:                 $output .= '</p>';
 6157:             }
 6158:         }
 6159:     }
 6160:     my $actionhref = '/adm/createuser';
 6161:     if ($context eq 'domain') {
 6162:         $actionhref = '/adm/modifycourse';
 6163:     }
 6164: 
 6165:     my %noedit;
 6166:     unless ($context eq 'domain') {
 6167:         %noedit = &get_noedit_fields($cdom,$cnum,$crstype,$row);
 6168:     }
 6169:     $output .= '<form name="'.$formname.'" method="post" action="'.$actionhref.'">'."\n".
 6170:                &Apache::lonhtmlcommon::start_pick_box();
 6171:     if (ref($row) eq 'ARRAY') {
 6172:         foreach my $item (@{$row}) {
 6173:             my $title = $item; 
 6174:             if (ref($lt) eq 'HASH') {
 6175:                 $title = $lt->{$item};
 6176:             }
 6177:             $output .= &Apache::lonhtmlcommon::row_title($title);
 6178:             if ($item eq 'types') {
 6179:                 my $curr_types;
 6180:                 if (ref($currsettings) eq 'HASH') {
 6181:                     $curr_types = $currsettings->{'selfenroll_types'};
 6182:                 }
 6183:                 if ($noedit{$item}) {
 6184:                     if ($curr_types eq '*') {
 6185:                         $output .= &mt('Any user in any domain');   
 6186:                     } else {
 6187:                         my @entries = split(/;/,$curr_types);
 6188:                         if (@entries > 0) {
 6189:                             $output .= '<ul>'; 
 6190:                             foreach my $entry (@entries) {
 6191:                                 my ($currdom,$typestr) = split(/:/,$entry);
 6192:                                 next if ($typestr eq '');
 6193:                                 my $domdesc = &Apache::lonnet::domain($currdom);
 6194:                                 my @currinsttypes = split(',',$typestr);
 6195:                                 my ($othertitle,$usertypes,$types) = 
 6196:                                     &Apache::loncommon::sorted_inst_types($currdom);
 6197:                                 if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 6198:                                     $usertypes->{'any'} = &mt('any user'); 
 6199:                                     if (keys(%{$usertypes}) > 0) {
 6200:                                         $usertypes->{'other'} = &mt('other users');
 6201:                                     }
 6202:                                     my @longinsttypes = map { $usertypes->{$_}; } @currinsttypes;
 6203:                                     $output .= '<li>'.$domdesc.':'.join(', ',@longinsttypes).'</li>';
 6204:                                  }
 6205:                             }
 6206:                             $output .= '</ul>';
 6207:                         } else {
 6208:                             $output .= &mt('None');
 6209:                         }
 6210:                     }
 6211:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 6212:                     next;
 6213:                 }
 6214:                 my $showdomdesc = 1;
 6215:                 my $includeempty = 1;
 6216:                 my $num = 0;
 6217:                 $output .= &Apache::loncommon::start_data_table().
 6218:                            &Apache::loncommon::start_data_table_row()
 6219:                            .'<td colspan="2"><span class="LC_nobreak"><label>'
 6220:                            .&mt('Any user in any domain:')
 6221:                            .'&nbsp;<input type="radio" name="selfenroll_all" value="1" ';
 6222:                 if ($curr_types eq '*') {
 6223:                     $output .= ' checked="checked" '; 
 6224:                 }
 6225:                 $output .= 'onchange="javascript:update_types('.
 6226:                            "'selfenroll_all'".');"'.$disabled.' />'.&mt('Yes').'</label>'.
 6227:                            '&nbsp;&nbsp;<input type="radio" name="selfenroll_all" value="0" ';
 6228:                 if ($curr_types ne '*') {
 6229:                     $output .= ' checked="checked" ';
 6230:                 }
 6231:                 $output .= ' onchange="javascript:update_types('.
 6232:                            "'selfenroll_all'".');"'.$disabled.' />'.&mt('No').'</label></td>'.
 6233:                            &Apache::loncommon::end_data_table_row().
 6234:                            &Apache::loncommon::end_data_table().
 6235:                            &mt('Or').'<br />'.
 6236:                            &Apache::loncommon::start_data_table();
 6237:                 my %currdoms;
 6238:                 if ($curr_types eq '') {
 6239:                     $output .= &new_selfenroll_dom_row($cdom,'0');
 6240:                 } elsif ($curr_types ne '*') {
 6241:                     my @entries = split(/;/,$curr_types);
 6242:                     if (@entries > 0) {
 6243:                         foreach my $entry (@entries) {
 6244:                             my ($currdom,$typestr) = split(/:/,$entry);
 6245:                             $currdoms{$currdom} = 1;
 6246:                             my $domdesc = &Apache::lonnet::domain($currdom);
 6247:                             my @currinsttypes = split(',',$typestr);
 6248:                             $output .= &Apache::loncommon::start_data_table_row()
 6249:                                        .'<td valign="top"><span class="LC_nobreak">'.&mt('Domain:').'<b>'
 6250:                                        .'&nbsp;'.$domdesc.' ('.$currdom.')'
 6251:                                        .'</b><input type="hidden" name="selfenroll_dom_'.$num
 6252:                                        .'" value="'.$currdom.'" /></span><br />'
 6253:                                        .'<span class="LC_nobreak"><label><input type="checkbox" '
 6254:                                        .'name="selfenroll_delete" value="'.$num.'" onchange="javascript:update_types('."'selfenroll_delete','$num'".');"'.$disabled.' />'
 6255:                                        .&mt('Delete').'</label></span></td>';
 6256:                             $output .= '<td valign="top">&nbsp;&nbsp;'.&mt('User types:').'<br />'
 6257:                                        .&selfenroll_inst_types($num,$currdom,\@currinsttypes,$readonly).'</td>'
 6258:                                        .&Apache::loncommon::end_data_table_row();
 6259:                             $num ++;
 6260:                         }
 6261:                     }
 6262:                 }
 6263:                 my $add_domtitle = &mt('Users in additional domain:');
 6264:                 if ($curr_types eq '*') { 
 6265:                     $add_domtitle = &mt('Users in specific domain:');
 6266:                 } elsif ($curr_types eq '') {
 6267:                     $add_domtitle = &mt('Users in other domain:');
 6268:                 }
 6269:                 my ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('enroll',$cdom);
 6270:                 $output .= &Apache::loncommon::start_data_table_row()
 6271:                            .'<td colspan="2"><span class="LC_nobreak">'.$add_domtitle.'</span><br />'
 6272:                            .&Apache::loncommon::select_dom_form('','selfenroll_newdom',
 6273:                                                                 $includeempty,$showdomdesc,'',$trusted,$untrusted,$readonly)
 6274:                            .'<input type="hidden" name="selfenroll_types_total" value="'.$num.'" />'
 6275:                            .'</td>'.&Apache::loncommon::end_data_table_row()
 6276:                            .&Apache::loncommon::end_data_table();
 6277:             } elsif ($item eq 'registered') {
 6278:                 my ($regon,$regoff);
 6279:                 my $registered;
 6280:                 if (ref($currsettings) eq 'HASH') {
 6281:                     $registered = $currsettings->{'selfenroll_registered'};
 6282:                 }
 6283:                 if ($noedit{$item}) {
 6284:                     if ($registered) {
 6285:                         $output .= &mt('Must be registered in course');
 6286:                     } else {
 6287:                         $output .= &mt('No requirement');
 6288:                     }
 6289:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 6290:                     next;
 6291:                 }
 6292:                 if ($registered) {
 6293:                     $regon = ' checked="checked" ';
 6294:                     $regoff = '';
 6295:                 } else {
 6296:                     $regon = '';
 6297:                     $regoff = ' checked="checked" ';
 6298:                 }
 6299:                 $output .= '<label>'.
 6300:                            '<input type="radio" name="selfenroll_registered" value="1"'.$regon.$disabled.' />'.
 6301:                            &mt('Yes').'</label>&nbsp;&nbsp;<label>'.
 6302:                            '<input type="radio" name="selfenroll_registered" value="0"'.$regoff.$disabled.' />'.
 6303:                            &mt('No').'</label>';
 6304:             } elsif ($item eq 'enroll_dates') {
 6305:                 my ($starttime,$endtime);
 6306:                 if (ref($currsettings) eq 'HASH') {
 6307:                     $starttime = $currsettings->{'selfenroll_start_date'};
 6308:                     $endtime = $currsettings->{'selfenroll_end_date'};
 6309:                     if ($starttime eq '') {
 6310:                         $starttime = $currsettings->{'default_enrollment_start_date'};
 6311:                     }
 6312:                     if ($endtime eq '') {
 6313:                         $endtime = $currsettings->{'default_enrollment_end_date'};
 6314:                     }
 6315:                 }
 6316:                 if ($noedit{$item}) {
 6317:                     $output .= &mt('From: [_1], to: [_2]',&Apache::lonlocal::locallocaltime($starttime),
 6318:                                                           &Apache::lonlocal::locallocaltime($endtime));
 6319:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 6320:                     next;
 6321:                 }
 6322:                 my $startform =
 6323:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_start_date',$starttime,
 6324:                                       $disabled,undef,undef,undef,undef,undef,undef,$nolink);
 6325:                 my $endform =
 6326:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_end_date',$endtime,
 6327:                                       $disabled,undef,undef,undef,undef,undef,undef,$nolink);
 6328:                 $output .= &selfenroll_date_forms($startform,$endform);
 6329:             } elsif ($item eq 'access_dates') {
 6330:                 my ($starttime,$endtime);
 6331:                 if (ref($currsettings) eq 'HASH') {
 6332:                     $starttime = $currsettings->{'selfenroll_start_access'};
 6333:                     $endtime = $currsettings->{'selfenroll_end_access'};
 6334:                     if ($starttime eq '') {
 6335:                         $starttime = $currsettings->{'default_enrollment_start_date'};
 6336:                     }
 6337:                     if ($endtime eq '') {
 6338:                         $endtime = $currsettings->{'default_enrollment_end_date'};
 6339:                     }
 6340:                 }
 6341:                 if ($noedit{$item}) {
 6342:                     $output .= &mt('From: [_1], to: [_2]',&Apache::lonlocal::locallocaltime($starttime),
 6343:                                                           &Apache::lonlocal::locallocaltime($endtime));
 6344:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 6345:                     next;
 6346:                 }
 6347:                 my $startform =
 6348:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_start_access',$starttime,
 6349:                                       $disabled,undef,undef,undef,undef,undef,undef,$nolink);
 6350:                 my $endform =
 6351:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_end_access',$endtime,
 6352:                                       $disabled,undef,undef,undef,undef,undef,undef,$nolink);
 6353:                 $output .= &selfenroll_date_forms($startform,$endform);
 6354:             } elsif ($item eq 'section') {
 6355:                 my $currsec;
 6356:                 if (ref($currsettings) eq 'HASH') {
 6357:                     $currsec = $currsettings->{'selfenroll_section'};
 6358:                 }
 6359:                 my %sections_count = &Apache::loncommon::get_sections($cdom,$cnum);
 6360:                 my $newsecval;
 6361:                 if ($currsec ne 'none' && $currsec ne '') {
 6362:                     if (!defined($sections_count{$currsec})) {
 6363:                         $newsecval = $currsec;
 6364:                     }
 6365:                 }
 6366:                 if ($noedit{$item}) {
 6367:                     if ($currsec ne '') {
 6368:                         $output .= $currsec;
 6369:                     } else {
 6370:                         $output .= &mt('No specific section');
 6371:                     }
 6372:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 6373:                     next;
 6374:                 }
 6375:                 my $sections_select = 
 6376:                     &Apache::lonuserutils::course_sections(\%sections_count,'st',$currsec,$disabled);
 6377:                 $output .= '<table class="LC_createuser">'."\n".
 6378:                            '<tr class="LC_section_row">'."\n".
 6379:                            '<td align="center">'.&mt('Existing sections')."\n".
 6380:                            '<br />'.$sections_select.'</td><td align="center">'.
 6381:                            &mt('New section').'<br />'."\n".
 6382:                            '<input type="text" name="newsec" size="15" value="'.$newsecval.'"'.$disabled.' />'."\n".
 6383:                            '<input type="hidden" name="sections" value="" />'."\n".
 6384:                            '</td></tr></table>'."\n";
 6385:             } elsif ($item eq 'approval') {
 6386:                 my ($currnotified,$currapproval,%appchecked);
 6387:                 my %selfdescs = &Apache::lonuserutils::selfenroll_default_descs();
 6388:                 if (ref($currsettings) eq 'HASH') {
 6389:                     $currnotified = $currsettings->{'selfenroll_notifylist'};
 6390:                     $currapproval = $currsettings->{'selfenroll_approval'};
 6391:                 }
 6392:                 if ($currapproval !~ /^[012]$/) {
 6393:                     $currapproval = 0;
 6394:                 }
 6395:                 if ($noedit{$item}) {
 6396:                     $output .=  $selfdescs{'approval'}{$currapproval}.
 6397:                                 '<br />'.&mt('(Set by Domain Coordinator)');
 6398:                     next;
 6399:                 }
 6400:                 $appchecked{$currapproval} = ' checked="checked"';
 6401:                 for my $i (0..2) {
 6402:                     $output .= '<label>'.
 6403:                                '<input type="radio" name="selfenroll_approval" value="'.$i.'"'.
 6404:                                $appchecked{$i}.' onclick="toggleNotify();"'.$disabled.' />'.
 6405:                                $selfdescs{'approval'}{$i}.'</label>'.('&nbsp;'x2);
 6406:                 }
 6407:                 my %advhash = &Apache::lonnet::get_course_adv_roles($cid,1);
 6408:                 my (@ccs,%notified);
 6409:                 my $ccrole = 'cc';
 6410:                 if ($crstype eq 'Community') {
 6411:                     $ccrole = 'co';
 6412:                 }
 6413:                 if ($advhash{$ccrole}) {
 6414:                     @ccs = split(/,/,$advhash{$ccrole});
 6415:                 }
 6416:                 if ($currnotified) {
 6417:                     foreach my $current (split(/,/,$currnotified)) {
 6418:                         $notified{$current} = 1;
 6419:                         if (!grep(/^\Q$current\E$/,@ccs)) {
 6420:                             push(@ccs,$current);
 6421:                         }
 6422:                     }
 6423:                 }
 6424:                 if (@ccs) {
 6425:                     my $style;
 6426:                     unless ($currapproval) {
 6427:                         $style = ' style="display: none;"'; 
 6428:                     }
 6429:                     $output .= '<br /><div id="notified"'.$style.'>'.
 6430:                                &mt('Personnel to be notified when an enrollment request needs approval, or has been approved:').'&nbsp;'.
 6431:                                &Apache::loncommon::start_data_table().
 6432:                                &Apache::loncommon::start_data_table_row();
 6433:                     my $count = 0;
 6434:                     my $numcols = 4;
 6435:                     foreach my $cc (sort(@ccs)) {
 6436:                         my $notifyon;
 6437:                         my ($ccuname,$ccudom) = split(/:/,$cc);
 6438:                         if ($notified{$cc}) {
 6439:                             $notifyon = ' checked="checked" ';
 6440:                         }
 6441:                         if ($count && !$count%$numcols) {
 6442:                             $output .= &Apache::loncommon::end_data_table_row().
 6443:                                        &Apache::loncommon::start_data_table_row()
 6444:                         }
 6445:                         $output .= '<td><span class="LC_nobreak"><label>'.
 6446:                                    '<input type="checkbox" name="selfenroll_notify"'.$notifyon.' value="'.$cc.'"'.$disabled.' />'.
 6447:                                    &Apache::loncommon::plainname($ccuname,$ccudom).
 6448:                                    '</label></span></td>';
 6449:                         $count ++;
 6450:                     }
 6451:                     my $rem = $count%$numcols;
 6452:                     if ($rem) {
 6453:                         my $emptycols = $numcols - $rem;
 6454:                         for (my $i=0; $i<$emptycols; $i++) { 
 6455:                             $output .= '<td>&nbsp;</td>';
 6456:                         }
 6457:                     }
 6458:                     $output .= &Apache::loncommon::end_data_table_row().
 6459:                                &Apache::loncommon::end_data_table().
 6460:                                '</div>';
 6461:                 }
 6462:             } elsif ($item eq 'limit') {
 6463:                 my ($crslimit,$selflimit,$nolimit,$currlim,$currcap);
 6464:                 if (ref($currsettings) eq 'HASH') {
 6465:                     $currlim = $currsettings->{'selfenroll_limit'};
 6466:                     $currcap = $currsettings->{'selfenroll_cap'};
 6467:                 }
 6468:                 if ($noedit{$item}) {
 6469:                     if (($currlim eq 'allstudents') || ($currlim eq 'selfenrolled')) {
 6470:                         if ($currlim eq 'allstudents') {
 6471:                             $output .= &mt('Limit by total students');
 6472:                         } elsif ($currlim eq 'selfenrolled') {
 6473:                             $output .= &mt('Limit by total self-enrolled students');
 6474:                         }
 6475:                         $output .= ' '.&mt('Maximum: [_1]',$currcap).
 6476:                                    '<br />'.&mt('(Set by Domain Coordinator)');
 6477:                     } else {
 6478:                         $output .= &mt('No limit').'<br />'.&mt('(Set by Domain Coordinator)');
 6479:                     }
 6480:                     next;
 6481:                 }
 6482:                 if ($currlim eq 'allstudents') {
 6483:                     $crslimit = ' checked="checked" ';
 6484:                     $selflimit = ' ';
 6485:                     $nolimit = ' ';
 6486:                 } elsif ($currlim eq 'selfenrolled') {
 6487:                     $crslimit = ' ';
 6488:                     $selflimit = ' checked="checked" ';
 6489:                     $nolimit = ' '; 
 6490:                 } else {
 6491:                     $crslimit = ' ';
 6492:                     $selflimit = ' ';
 6493:                     $nolimit = ' checked="checked" ';
 6494:                 }
 6495:                 $output .= '<table><tr><td><label>'.
 6496:                            '<input type="radio" name="selfenroll_limit" value="none"'.$nolimit.$disabled.'/>'.
 6497:                            &mt('No limit').'</label></td><td><label>'.
 6498:                            '<input type="radio" name="selfenroll_limit" value="allstudents"'.$crslimit.$disabled.'/>'.
 6499:                            &mt('Limit by total students').'</label></td><td><label>'.
 6500:                            '<input type="radio" name="selfenroll_limit" value="selfenrolled"'.$selflimit.$disabled.'/>'.
 6501:                            &mt('Limit by total self-enrolled students').
 6502:                            '</td></tr><tr>'.
 6503:                            '<td>&nbsp;</td><td colspan="2"><span class="LC_nobreak">'.
 6504:                            ('&nbsp;'x3).&mt('Maximum number allowed: ').
 6505:                            '<input type="text" name="selfenroll_cap" size = "5" value="'.$currcap.'"'.$disabled.' /></td></tr></table>';
 6506:             }
 6507:             $output .= &Apache::lonhtmlcommon::row_closure(1);
 6508:         }
 6509:     }
 6510:     $output .= &Apache::lonhtmlcommon::end_pick_box().'<br />';
 6511:     unless ($readonly) {
 6512:         $output .= '<input type="button" name="selfenrollconf" value="'
 6513:                    .&mt('Save').'" onclick="validate_types(this.form);" />';
 6514:     }
 6515:     $output .= '<input type="hidden" name="action" value="selfenroll" />'
 6516:               .'<input type="hidden" name="state" value="done" />'."\n"
 6517:               .$additional.'</form>';
 6518:     $r->print($output);
 6519:     return;
 6520: }
 6521: 
 6522: sub get_noedit_fields {
 6523:     my ($cdom,$cnum,$crstype,$row) = @_;
 6524:     my %noedit;
 6525:     if (ref($row) eq 'ARRAY') {
 6526:         my %settings = &Apache::lonnet::get('environment',['internal.coursecode','internal.textbook',
 6527:                                                            'internal.selfenrollmgrdc',
 6528:                                                            'internal.selfenrollmgrcc'],$cdom,$cnum);
 6529:         my $type = &Apache::lonuserutils::get_extended_type($cdom,$cnum,$crstype,\%settings);
 6530:         my (%specific_managebydc,%specific_managebycc,%default_managebydc);
 6531:         map { $specific_managebydc{$_} = 1; } (split(/,/,$settings{'internal.selfenrollmgrdc'}));
 6532:         map { $specific_managebycc{$_} = 1; } (split(/,/,$settings{'internal.selfenrollmgrcc'}));
 6533:         my %domdefaults = &Apache::lonnet::get_domain_defaults($cdom);
 6534:         map { $default_managebydc{$_} = 1; } (split(/,/,$domdefaults{$type.'selfenrolladmdc'}));
 6535: 
 6536:         foreach my $item (@{$row}) {
 6537:             next if ($specific_managebycc{$item});
 6538:             if (($specific_managebydc{$item}) || ($default_managebydc{$item})) {
 6539:                 $noedit{$item} = 1;
 6540:             }
 6541:         }
 6542:     }
 6543:     return %noedit;
 6544: } 
 6545: 
 6546: sub visible_in_stdcat {
 6547:     my ($cdom,$cnum,$domconf) = @_;
 6548:     my ($cathash,%settable,@vismsgs,$cansetvis,$visible);
 6549:     unless (ref($domconf) eq 'HASH') {
 6550:         return ($visible,$cansetvis,\@vismsgs);
 6551:     }
 6552:     if (ref($domconf->{'coursecategories'}) eq 'HASH') {
 6553:         if ($domconf->{'coursecategories'}{'togglecats'} eq 'crs') {
 6554:             $settable{'togglecats'} = 1;
 6555:         }
 6556:         if ($domconf->{'coursecategories'}{'categorize'} eq 'crs') {
 6557:             $settable{'categorize'} = 1;
 6558:         }
 6559:         $cathash = $domconf->{'coursecategories'}{'cats'};
 6560:     }
 6561:     if ($settable{'togglecats'} && $settable{'categorize'}) {
 6562:         $cansetvis = &mt('You are able to both assign a course category and choose to exclude this course from the catalog.');   
 6563:     } elsif ($settable{'togglecats'}) {
 6564:         $cansetvis = &mt('You are able to choose to exclude this course from the catalog, but only a Domain Coordinator may assign a course category.'); 
 6565:     } elsif ($settable{'categorize'}) {
 6566:         $cansetvis = &mt('You may assign a course category, but only a Domain Coordinator may choose to exclude this course from the catalog.');  
 6567:     } else {
 6568:         $cansetvis = &mt('Only a Domain Coordinator may assign a course category or choose to exclude this course from the catalog.'); 
 6569:     }
 6570:      
 6571:     my %currsettings =
 6572:         &Apache::lonnet::get('environment',['hidefromcat','categories','internal.coursecode'],
 6573:                              $cdom,$cnum);
 6574:     $visible = 0;
 6575:     if ($currsettings{'internal.coursecode'} ne '') {
 6576:         if (ref($domconf->{'coursecategories'}) eq 'HASH') {
 6577:             $cathash = $domconf->{'coursecategories'}{'cats'};
 6578:             if (ref($cathash) eq 'HASH') {
 6579:                 if ($cathash->{'instcode::0'} eq '') {
 6580:                     push(@vismsgs,'dc_addinst'); 
 6581:                 } else {
 6582:                     $visible = 1;
 6583:                 }
 6584:             } else {
 6585:                 $visible = 1;
 6586:             }
 6587:         } else {
 6588:             $visible = 1;
 6589:         }
 6590:     } else {
 6591:         if (ref($cathash) eq 'HASH') {
 6592:             if ($cathash->{'instcode::0'} ne '') {
 6593:                 push(@vismsgs,'dc_instcode');
 6594:             }
 6595:         } else {
 6596:             push(@vismsgs,'dc_instcode');
 6597:         }
 6598:     }
 6599:     if ($currsettings{'categories'} ne '') {
 6600:         my $cathash;
 6601:         if (ref($domconf->{'coursecategories'}) eq 'HASH') {
 6602:             $cathash = $domconf->{'coursecategories'}{'cats'};
 6603:             if (ref($cathash) eq 'HASH') {
 6604:                 if (keys(%{$cathash}) == 0) {
 6605:                     push(@vismsgs,'dc_catalog');
 6606:                 } elsif ((keys(%{$cathash}) == 1) && ($cathash->{'instcode::0'} ne '')) {
 6607:                     push(@vismsgs,'dc_categories');
 6608:                 } else {
 6609:                     my @currcategories = split('&',$currsettings{'categories'});
 6610:                     my $matched = 0;
 6611:                     foreach my $cat (@currcategories) {
 6612:                         if ($cathash->{$cat} ne '') {
 6613:                             $visible = 1;
 6614:                             $matched = 1;
 6615:                             last;
 6616:                         }
 6617:                     }
 6618:                     if (!$matched) {
 6619:                         if ($settable{'categorize'}) { 
 6620:                             push(@vismsgs,'chgcat');
 6621:                         } else {
 6622:                             push(@vismsgs,'dc_chgcat');
 6623:                         }
 6624:                     }
 6625:                 }
 6626:             }
 6627:         }
 6628:     } else {
 6629:         if (ref($cathash) eq 'HASH') {
 6630:             if ((keys(%{$cathash}) > 1) || 
 6631:                 (keys(%{$cathash}) == 1) && ($cathash->{'instcode::0'} eq '')) {
 6632:                 if ($settable{'categorize'}) {
 6633:                     push(@vismsgs,'addcat');
 6634:                 } else {
 6635:                     push(@vismsgs,'dc_addcat');
 6636:                 }
 6637:             }
 6638:         }
 6639:     }
 6640:     if ($currsettings{'hidefromcat'} eq 'yes') {
 6641:         $visible = 0;
 6642:         if ($settable{'togglecats'}) {
 6643:             unshift(@vismsgs,'unhide');
 6644:         } else {
 6645:             unshift(@vismsgs,'dc_unhide')
 6646:         }
 6647:     }
 6648:     return ($visible,$cansetvis,\@vismsgs);
 6649: }
 6650: 
 6651: sub cat_visibility {
 6652:     my %visactions = &Apache::lonlocal::texthash(
 6653:                    vis => 'This course/community currently appears in the Course/Community Catalog for this domain.',
 6654:                    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.',
 6655:                    miss => 'This course/community does not currently appear in the Course/Community Catalog for this domain.',
 6656:                    none => 'Display of a course catalog is disabled for this domain.',
 6657:                    yous => 'You should remedy this if you plan to allow self-enrollment, otherwise students will have difficulty finding this course.',
 6658:                    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.',
 6659:                    make => 'Make any changes to self-enrollment settings below, click "Save", then take action to include the course in the Catalog:',
 6660:                    take => 'Take the following action to ensure the course appears in the Catalog:',
 6661:                    dc_chgconf => 'Ask a domain coordinator to change the Catalog type for this domain.',
 6662:                    dc_setcode => 'Ask a domain coordinator to assign a six character code to the course',
 6663:                    dc_unhide  => 'Ask a domain coordinator to change the "Exclude from course catalog" setting.',
 6664:                    dc_addinst => 'Ask a domain coordinator to enable display the catalog of "Official courses (with institutional codes)".',
 6665:                    dc_instcode => 'Ask a domain coordinator to assign an institutional code (if this is an official course).',
 6666:                    dc_catalog  => 'Ask a domain coordinator to enable or create at least one course category in the domain.',
 6667:                    dc_categories => 'Ask a domain coordinator to create a hierarchy of categories and sub categories for courses in the domain.',
 6668:                    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',
 6669:                    dc_addcat => 'Ask a domain coordinator to assign a category to the course.',
 6670:     );
 6671:     $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>"');
 6672:     $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>"');
 6673:     $visactions{'addcat'} = &mt('Use [_1]Categorize course[_2] to assign a category to the course.','"<a href="/adm/courseprefs?phase=display&actions=courseinfo">','</a>"');
 6674:     return \%visactions;
 6675: }
 6676: 
 6677: sub new_selfenroll_dom_row {
 6678:     my ($newdom,$num) = @_;
 6679:     my $domdesc = &Apache::lonnet::domain($newdom);
 6680:     my $output;
 6681:     if ($domdesc ne '') {
 6682:         $output .= &Apache::loncommon::start_data_table_row()
 6683:                    .'<td valign="top"><span class="LC_nobreak">'.&mt('Domain:').'&nbsp;<b>'.$domdesc
 6684:                    .' ('.$newdom.')</b><input type="hidden" name="selfenroll_dom_'.$num
 6685:                    .'" value="'.$newdom.'" /></span><br />'
 6686:                    .'<span class="LC_nobreak"><label><input type="checkbox" '
 6687:                    .'name="selfenroll_activate" value="'.$num.'" '
 6688:                    .'onchange="javascript:update_types('
 6689:                    ."'selfenroll_activate','$num'".');" />'
 6690:                    .&mt('Activate').'</label></span></td>';
 6691:         my @currinsttypes;
 6692:         $output .= '<td>'.&mt('User types:').'<br />'
 6693:                    .&selfenroll_inst_types($num,$newdom,\@currinsttypes).'</td>'
 6694:                    .&Apache::loncommon::end_data_table_row();
 6695:     }
 6696:     return $output;
 6697: }
 6698: 
 6699: sub selfenroll_inst_types {
 6700:     my ($num,$currdom,$currinsttypes,$readonly) = @_;
 6701:     my $output;
 6702:     my $numinrow = 4;
 6703:     my $count = 0;
 6704:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($currdom);
 6705:     my $othervalue = 'any';
 6706:     my $disabled;
 6707:     if ($readonly) {
 6708:         $disabled = ' disabled="disabled"';
 6709:     }
 6710:     if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 6711:         if (keys(%{$usertypes}) > 0) {
 6712:             $othervalue = 'other';
 6713:         }
 6714:         $output .= '<table><tr>';
 6715:         foreach my $type (@{$types}) {
 6716:             if (($count > 0) && ($count%$numinrow == 0)) {
 6717:                 $output .= '</tr><tr>';
 6718:             }
 6719:             if (defined($usertypes->{$type})) {
 6720:                 my $esc_type = &escape($type);
 6721:                 $output .= '<td><span class="LC_nobreak"><label><input type = "checkbox" value="'.
 6722:                            $esc_type.'" ';
 6723:                 if (ref($currinsttypes) eq 'ARRAY') {
 6724:                     if (@{$currinsttypes} > 0) {
 6725:                         if (grep(/^any$/,@{$currinsttypes})) {
 6726:                             $output .= 'checked="checked"';
 6727:                         } elsif (grep(/^\Q$esc_type\E$/,@{$currinsttypes})) {
 6728:                             $output .= 'checked="checked"';
 6729:                         }
 6730:                     } else {
 6731:                         $output .= 'checked="checked"';
 6732:                     }
 6733:                 }
 6734:                 $output .= ' name="selfenroll_types_'.$num.'"'.$disabled.' />'.$usertypes->{$type}.'</label></span></td>';
 6735:             }
 6736:             $count ++;
 6737:         }
 6738:         if (($count > 0) && ($count%$numinrow == 0)) {
 6739:             $output .= '</tr><tr>';
 6740:         }
 6741:         $output .= '<td><span class="LC_nobreak"><label><input type = "checkbox" value="'.$othervalue.'"';
 6742:         if (ref($currinsttypes) eq 'ARRAY') {
 6743:             if (@{$currinsttypes} > 0) {
 6744:                 if (grep(/^any$/,@{$currinsttypes})) { 
 6745:                     $output .= ' checked="checked"';
 6746:                 } elsif ($othervalue eq 'other') {
 6747:                     if (grep(/^\Q$othervalue\E$/,@{$currinsttypes})) {
 6748:                         $output .= ' checked="checked"';
 6749:                     }
 6750:                 }
 6751:             } else {
 6752:                 $output .= ' checked="checked"';
 6753:             }
 6754:         } else {
 6755:             $output .= ' checked="checked"';
 6756:         }
 6757:         $output .= ' name="selfenroll_types_'.$num.'"'.$disabled.' />'.$othertitle.'</label></span></td></tr></table>';
 6758:     }
 6759:     return $output;
 6760: }
 6761: 
 6762: sub selfenroll_date_forms {
 6763:     my ($startform,$endform) = @_;
 6764:     my $output .= &Apache::lonhtmlcommon::start_pick_box()."\n".
 6765:                   &Apache::lonhtmlcommon::row_title(&mt('Start date'),
 6766:                                                     'LC_oddrow_value')."\n".
 6767:                   $startform."\n".
 6768:                   &Apache::lonhtmlcommon::row_closure(1).
 6769:                   &Apache::lonhtmlcommon::row_title(&mt('End date'),
 6770:                                                    'LC_oddrow_value')."\n".
 6771:                   $endform."\n".
 6772:                   &Apache::lonhtmlcommon::row_closure(1).
 6773:                   &Apache::lonhtmlcommon::end_pick_box();
 6774:     return $output;
 6775: }
 6776: 
 6777: sub print_userchangelogs_display {
 6778:     my ($r,$context,$permission,$brcrum) = @_;
 6779:     my $formname = 'rolelog';
 6780:     my ($username,$domain,$crstype,$viewablesec,%roleslog);
 6781:     if ($context eq 'domain') {
 6782:         $domain = $env{'request.role.domain'};
 6783:         %roleslog=&Apache::lonnet::dump_dom('nohist_rolelog',$domain);
 6784:     } else {
 6785:         if ($context eq 'course') { 
 6786:             $domain = $env{'course.'.$env{'request.course.id'}.'.domain'};
 6787:             $username = $env{'course.'.$env{'request.course.id'}.'.num'};
 6788:             $crstype = &Apache::loncommon::course_type();
 6789:             $viewablesec = &Apache::lonuserutils::viewable_section($permission);
 6790:             my %saveable_parameters = ('show' => 'scalar',);
 6791:             &Apache::loncommon::store_course_settings('roles_log',
 6792:                                                       \%saveable_parameters);
 6793:             &Apache::loncommon::restore_course_settings('roles_log',
 6794:                                                         \%saveable_parameters);
 6795:         } elsif ($context eq 'author') {
 6796:             $domain = $env{'user.domain'}; 
 6797:             if ($env{'request.role'} =~ m{^au\./\Q$domain\E/$}) {
 6798:                 $username = $env{'user.name'};
 6799:             } else {
 6800:                 undef($domain);
 6801:             }
 6802:         }
 6803:         if ($domain ne '' && $username ne '') { 
 6804:             %roleslog=&Apache::lonnet::dump('nohist_rolelog',$domain,$username);
 6805:         }
 6806:     }
 6807:     if ((keys(%roleslog))[0]=~/^error\:/) { undef(%roleslog); }
 6808: 
 6809:     my $helpitem;
 6810:     if ($context eq 'course') {
 6811:         $helpitem = 'Course_User_Logs';
 6812:     } elsif ($context eq 'domain') {
 6813:         $helpitem = 'Domain_Role_Logs';
 6814:     } elsif ($context eq 'author') {
 6815:         $helpitem = 'Author_User_Logs';
 6816:     }
 6817:     push (@{$brcrum},
 6818:              {href => '/adm/createuser?action=changelogs',
 6819:               text => 'User Management Logs',
 6820:               help => $helpitem});
 6821:     my $bread_crumbs_component = 'User Changes';
 6822:     my $args = { bread_crumbs           => $brcrum,
 6823:                  bread_crumbs_component => $bread_crumbs_component};
 6824: 
 6825:     # Create navigation javascript
 6826:     my $jsnav = &userlogdisplay_js($formname);
 6827: 
 6828:     my $jscript = (<<ENDSCRIPT);
 6829: <script type="text/javascript">
 6830: // <![CDATA[
 6831: $jsnav
 6832: // ]]>
 6833: </script>
 6834: ENDSCRIPT
 6835: 
 6836:     # print page header
 6837:     $r->print(&header($jscript,$args));
 6838: 
 6839:     # set defaults
 6840:     my $now = time();
 6841:     my $defstart = $now - (7*24*3600); #7 days ago 
 6842:     my %defaults = (
 6843:                      page               => '1',
 6844:                      show               => '10',
 6845:                      role               => 'any',
 6846:                      chgcontext         => 'any',
 6847:                      rolelog_start_date => $defstart,
 6848:                      rolelog_end_date   => $now,
 6849:                    );
 6850:     my $more_records = 0;
 6851: 
 6852:     # set current
 6853:     my %curr;
 6854:     foreach my $item ('show','page','role','chgcontext') {
 6855:         $curr{$item} = $env{'form.'.$item};
 6856:     }
 6857:     my ($startdate,$enddate) = 
 6858:         &Apache::lonuserutils::get_dates_from_form('rolelog_start_date','rolelog_end_date');
 6859:     $curr{'rolelog_start_date'} = $startdate;
 6860:     $curr{'rolelog_end_date'} = $enddate;
 6861:     foreach my $key (keys(%defaults)) {
 6862:         if ($curr{$key} eq '') {
 6863:             $curr{$key} = $defaults{$key};
 6864:         }
 6865:     }
 6866:     my (%whodunit,%changed,$version);
 6867:     ($version) = ($r->dir_config('lonVersion') =~ /^([\d\.]+)\-/);
 6868:     my ($minshown,$maxshown);
 6869:     $minshown = 1;
 6870:     my $count = 0;
 6871:     if ($curr{'show'} =~ /\D/) {
 6872:         $curr{'page'} = 1;
 6873:     } else {
 6874:         $maxshown = $curr{'page'} * $curr{'show'};
 6875:         if ($curr{'page'} > 1) {
 6876:             $minshown = 1 + ($curr{'page'} - 1) * $curr{'show'};
 6877:         }
 6878:     }
 6879: 
 6880:     # Form Header
 6881:     $r->print('<form action="/adm/createuser" method="post" name="'.$formname.'">'.
 6882:               &role_display_filter($context,$formname,$domain,$username,\%curr,
 6883:                                    $version,$crstype));
 6884: 
 6885:     my $showntableheader = 0;
 6886: 
 6887:     # Table Header
 6888:     my $tableheader = 
 6889:         &Apache::loncommon::start_data_table_header_row()
 6890:        .'<th>&nbsp;</th>'
 6891:        .'<th>'.&mt('When').'</th>'
 6892:        .'<th>'.&mt('Who made the change').'</th>'
 6893:        .'<th>'.&mt('Changed User').'</th>'
 6894:        .'<th>'.&mt('Role').'</th>';
 6895: 
 6896:     if ($context eq 'course') {
 6897:         $tableheader .= '<th>'.&mt('Section').'</th>';
 6898:     }
 6899:     $tableheader .=
 6900:         '<th>'.&mt('Context').'</th>'
 6901:        .'<th>'.&mt('Start').'</th>'
 6902:        .'<th>'.&mt('End').'</th>'
 6903:        .&Apache::loncommon::end_data_table_header_row();
 6904: 
 6905:     # Display user change log data
 6906:     foreach my $id (sort { $roleslog{$b}{'exe_time'}<=>$roleslog{$a}{'exe_time'} } (keys(%roleslog))) {
 6907:         next if (($roleslog{$id}{'exe_time'} < $curr{'rolelog_start_date'}) ||
 6908:                  ($roleslog{$id}{'exe_time'} > $curr{'rolelog_end_date'}));
 6909:         if ($curr{'show'} !~ /\D/) {
 6910:             if ($count >= $curr{'page'} * $curr{'show'}) {
 6911:                 $more_records = 1;
 6912:                 last;
 6913:             }
 6914:         }
 6915:         if ($curr{'role'} ne 'any') {
 6916:             next if ($roleslog{$id}{'logentry'}{'role'} ne $curr{'role'}); 
 6917:         }
 6918:         if ($curr{'chgcontext'} ne 'any') {
 6919:             if ($curr{'chgcontext'} eq 'selfenroll') {
 6920:                 next if (!$roleslog{$id}{'logentry'}{'selfenroll'});
 6921:             } else {
 6922:                 next if ($roleslog{$id}{'logentry'}{'context'} ne $curr{'chgcontext'});
 6923:             }
 6924:         }
 6925:         if (($context eq 'course') && ($viewablesec ne '')) {
 6926:             next if ($roleslog{$id}{'logentry'}{'section'} ne $viewablesec);
 6927:         }
 6928:         $count ++;
 6929:         next if ($count < $minshown);
 6930:         unless ($showntableheader) {
 6931:             $r->print(&Apache::loncommon::start_data_table()
 6932:                      .$tableheader);
 6933:             $r->rflush();
 6934:             $showntableheader = 1;
 6935:         }
 6936:         if ($whodunit{$roleslog{$id}{'exe_uname'}.':'.$roleslog{$id}{'exe_udom'}} eq '') {
 6937:             $whodunit{$roleslog{$id}{'exe_uname'}.':'.$roleslog{$id}{'exe_udom'}} =
 6938:                 &Apache::loncommon::plainname($roleslog{$id}{'exe_uname'},$roleslog{$id}{'exe_udom'});
 6939:         }
 6940:         if ($changed{$roleslog{$id}{'uname'}.':'.$roleslog{$id}{'udom'}} eq '') {
 6941:             $changed{$roleslog{$id}{'uname'}.':'.$roleslog{$id}{'udom'}} =
 6942:                 &Apache::loncommon::plainname($roleslog{$id}{'uname'},$roleslog{$id}{'udom'});
 6943:         }
 6944:         my $sec = $roleslog{$id}{'logentry'}{'section'};
 6945:         if ($sec eq '') {
 6946:             $sec = &mt('None');
 6947:         }
 6948:         my ($rolestart,$roleend);
 6949:         if ($roleslog{$id}{'delflag'}) {
 6950:             $rolestart = &mt('deleted');
 6951:             $roleend = &mt('deleted');
 6952:         } else {
 6953:             $rolestart = $roleslog{$id}{'logentry'}{'start'};
 6954:             $roleend = $roleslog{$id}{'logentry'}{'end'};
 6955:             if ($rolestart eq '' || $rolestart == 0) {
 6956:                 $rolestart = &mt('No start date'); 
 6957:             } else {
 6958:                 $rolestart = &Apache::lonlocal::locallocaltime($rolestart);
 6959:             }
 6960:             if ($roleend eq '' || $roleend == 0) { 
 6961:                 $roleend = &mt('No end date');
 6962:             } else {
 6963:                 $roleend = &Apache::lonlocal::locallocaltime($roleend);
 6964:             }
 6965:         }
 6966:         my $chgcontext = $roleslog{$id}{'logentry'}{'context'};
 6967:         if ($roleslog{$id}{'logentry'}{'selfenroll'}) {
 6968:             $chgcontext = 'selfenroll';
 6969:         }
 6970:         my %lt = &rolechg_contexts($context,$crstype);
 6971:         if ($chgcontext ne '' && $lt{$chgcontext} ne '') {
 6972:             $chgcontext = $lt{$chgcontext};
 6973:         }
 6974:         $r->print(
 6975:             &Apache::loncommon::start_data_table_row()
 6976:            .'<td>'.$count.'</td>'
 6977:            .'<td>'.&Apache::lonlocal::locallocaltime($roleslog{$id}{'exe_time'}).'</td>'
 6978:            .'<td>'.$whodunit{$roleslog{$id}{'exe_uname'}.':'.$roleslog{$id}{'exe_udom'}}.'</td>'
 6979:            .'<td>'.$changed{$roleslog{$id}{'uname'}.':'.$roleslog{$id}{'udom'}}.'</td>'
 6980:            .'<td>'.&Apache::lonnet::plaintext($roleslog{$id}{'logentry'}{'role'},$crstype).'</td>');
 6981:         if ($context eq 'course') { 
 6982:             $r->print('<td>'.$sec.'</td>');
 6983:         }
 6984:         $r->print(
 6985:             '<td>'.$chgcontext.'</td>'
 6986:            .'<td>'.$rolestart.'</td>'
 6987:            .'<td>'.$roleend.'</td>'
 6988:            .&Apache::loncommon::end_data_table_row()."\n");
 6989:     }
 6990: 
 6991:     if ($showntableheader) { # Table footer, if content displayed above
 6992:         $r->print(&Apache::loncommon::end_data_table().
 6993:                   &userlogdisplay_navlinks(\%curr,$more_records));
 6994:     } else { # No content displayed above
 6995:         $r->print('<p class="LC_info">'
 6996:                  .&mt('There are no records to display.')
 6997:                  .'</p>'
 6998:         );
 6999:     }
 7000: 
 7001:     # Form Footer
 7002:     $r->print( 
 7003:         '<input type="hidden" name="page" value="'.$curr{'page'}.'" />'
 7004:        .'<input type="hidden" name="action" value="changelogs" />'
 7005:        .'</form>');
 7006:     return;
 7007: }
 7008: 
 7009: sub print_useraccesslogs_display {
 7010:     my ($r,$uname,$udom,$permission,$brcrum) = @_;
 7011:     my $formname = 'accesslog';
 7012:     my $form = 'document.accesslog';
 7013: 
 7014: # set breadcrumbs
 7015:     my %breadcrumb_text = &singleuser_breadcrumb('','domain',$udom);
 7016:     my $prevphasestr;
 7017:     if ($env{'form.popup'}) {
 7018:         $brcrum = [];
 7019:     } else {
 7020:         push (@{$brcrum},
 7021:             {href => "javascript:backPage($form)",
 7022:              text => $breadcrumb_text{'search'}});
 7023:         my @prevphases;
 7024:         if ($env{'form.prevphases'}) {
 7025:             @prevphases = split(/,/,$env{'form.prevphases'});
 7026:             $prevphasestr = $env{'form.prevphases'};
 7027:         }
 7028:         if (($env{'form.phase'} eq 'userpicked') || (grep(/^userpicked$/,@prevphases))) {
 7029:             push(@{$brcrum},
 7030:                   {href => "javascript:backPage($form,'get_user_info','select')",
 7031:                    text => $breadcrumb_text{'userpicked'}});
 7032:             if ($env{'form.phase'} eq 'userpicked') {
 7033:                 $prevphasestr = 'userpicked';
 7034:             }
 7035:         }
 7036:     }
 7037:     push(@{$brcrum},
 7038:              {href => '/adm/createuser?action=accesslogs',
 7039:               text => 'User access logs',
 7040:               help => 'Domain_User_Access_Logs'});
 7041:     my $bread_crumbs_component = 'User Access Logs';
 7042:     my $args = { bread_crumbs           => $brcrum,
 7043:                  bread_crumbs_component => 'User Management'};
 7044:     if ($env{'form.popup'}) {
 7045:         $args->{'no_nav_bar'} = 1;
 7046:         $args->{'bread_crumbs_nomenu'} = 1;
 7047:     }
 7048: 
 7049: # set javascript
 7050:     my ($jsback,$elements) = &crumb_utilities();
 7051:     my $jsnav = &userlogdisplay_js($formname);
 7052: 
 7053:     my $jscript = (<<ENDSCRIPT);
 7054: <script type="text/javascript">
 7055: // <![CDATA[
 7056: 
 7057: $jsback
 7058: $jsnav
 7059: 
 7060: // ]]>
 7061: </script>
 7062: 
 7063: ENDSCRIPT
 7064: 
 7065: # print page header
 7066:     $r->print(&header($jscript,$args));
 7067: 
 7068: # early out unless log data can be displayed.
 7069:     unless ($permission->{'activity'}) {
 7070:         $r->print('<p class="LC_warning">'
 7071:                  .&mt('You do not have rights to display user access logs.')
 7072:                  .'</p>');
 7073:         if ($env{'form.popup'}) {
 7074:             $r->print('<p><a href="javascript:window.close()">'.&mt('Close window').'</a></p>');
 7075:         } else {
 7076:             $r->print(&earlyout_accesslog_form($formname,$prevphasestr,$udom));
 7077:         }
 7078:         return;
 7079:     }
 7080: 
 7081:     unless ($udom eq $env{'request.role.domain'}) {
 7082:         $r->print('<p class="LC_warning">'
 7083:                  .&mt("User's domain must match role's domain")
 7084:                  .'</p>'
 7085:                  .&earlyout_accesslog_form($formname,$prevphasestr,$udom));
 7086:         return;
 7087:     }
 7088: 
 7089:     if (($uname eq '') || ($udom eq '')) {
 7090:         $r->print('<p class="LC_warning">'
 7091:                  .&mt('Invalid username or domain')
 7092:                  .'</p>'
 7093:                  .&earlyout_accesslog_form($formname,$prevphasestr,$udom));
 7094:         return;
 7095:     }
 7096: 
 7097:     if (&Apache::lonnet::privileged($uname,$udom,
 7098:                                     [$env{'request.role.domain'}],['dc','su'])) {
 7099:         unless (&Apache::lonnet::privileged($env{'user.name'},$env{'user.domain'},
 7100:                                             [$env{'request.role.domain'}],['dc','su'])) {
 7101:             $r->print('<p class="LC_warning">'
 7102:                  .&mt('You need to be a privileged user to display user access logs for [_1]',
 7103:                       &Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($uname,$udom),
 7104:                                                          $uname,$udom))
 7105:                  .'</p>');
 7106:             if ($env{'form.popup'}) {
 7107:                 $r->print('<p><a href="javascript:window.close()">'.&mt('Close window').'</a></p>');
 7108:             } else {
 7109:                 $r->print(&earlyout_accesslog_form($formname,$prevphasestr,$udom));
 7110:             }
 7111:             return;
 7112:         }
 7113:     }
 7114: 
 7115: # set defaults
 7116:     my $now = time();
 7117:     my $defstart = $now - (7*24*3600);
 7118:     my %defaults = (
 7119:                      page                 => '1',
 7120:                      show                 => '10',
 7121:                      activity             => 'any',
 7122:                      accesslog_start_date => $defstart,
 7123:                      accesslog_end_date   => $now,
 7124:                    );
 7125:     my $more_records = 0;
 7126: 
 7127: # set current
 7128:     my %curr;
 7129:     foreach my $item ('show','page','activity') {
 7130:         $curr{$item} = $env{'form.'.$item};
 7131:     }
 7132:     my ($startdate,$enddate) =
 7133:         &Apache::lonuserutils::get_dates_from_form('accesslog_start_date','accesslog_end_date');
 7134:     $curr{'accesslog_start_date'} = $startdate;
 7135:     $curr{'accesslog_end_date'} = $enddate;
 7136:     foreach my $key (keys(%defaults)) {
 7137:         if ($curr{$key} eq '') {
 7138:             $curr{$key} = $defaults{$key};
 7139:         }
 7140:     }
 7141:     my ($minshown,$maxshown);
 7142:     $minshown = 1;
 7143:     my $count = 0;
 7144:     if ($curr{'show'} =~ /\D/) {
 7145:         $curr{'page'} = 1;
 7146:     } else {
 7147:         $maxshown = $curr{'page'} * $curr{'show'};
 7148:         if ($curr{'page'} > 1) {
 7149:             $minshown = 1 + ($curr{'page'} - 1) * $curr{'show'};
 7150:         }
 7151:     }
 7152: 
 7153: # form header
 7154:     $r->print('<form action="/adm/createuser" method="post" name="'.$formname.'">'.
 7155:               &activity_display_filter($formname,\%curr));
 7156: 
 7157:     my $showntableheader = 0;
 7158:     my ($nav_script,$nav_links);
 7159: 
 7160: # table header
 7161:     my $heading = '<h3>'.
 7162:         &mt('User access logs for: [_1]',
 7163:             &Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($uname,$udom),$uname,$udom)).'</h3>';
 7164:     my $tableheader = $heading
 7165:        .&Apache::loncommon::start_data_table_header_row()
 7166:        .'<th>&nbsp;</th>'
 7167:        .'<th>'.&mt('When').'</th>'
 7168:        .'<th>'.&mt('HostID').'</th>'
 7169:        .'<th>'.&mt('Event').'</th>'
 7170:        .'<th>'.&mt('Other data').'</th>'
 7171:        .&Apache::loncommon::end_data_table_header_row();
 7172: 
 7173:     my %filters=(
 7174:         start  => $curr{'accesslog_start_date'},
 7175:         end    => $curr{'accesslog_end_date'},
 7176:         action => $curr{'activity'},
 7177:     );
 7178: 
 7179:     my $reply = &Apache::lonnet::userlog_query($uname,$udom,%filters);
 7180:     unless ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 7181:         my (%courses,%missing);
 7182:         my @results = split(/\&/,$reply);
 7183:         foreach my $item (reverse(@results)) {
 7184:             my ($timestamp,$host,$event) = split(/:/,$item);
 7185:             next unless ($event =~ /^(Log|Role)/);
 7186:             if ($curr{'show'} !~ /\D/) {
 7187:                 if ($count >= $curr{'page'} * $curr{'show'}) {
 7188:                     $more_records = 1;
 7189:                     last;
 7190:                 }
 7191:             }
 7192:             $count ++;
 7193:             next if ($count < $minshown);
 7194:             unless ($showntableheader) {
 7195:                 $r->print($nav_script
 7196:                          .&Apache::loncommon::start_data_table()
 7197:                          .$tableheader);
 7198:                 $r->rflush();
 7199:                 $showntableheader = 1;
 7200:             }
 7201:             my ($shown,$extra);
 7202:             my ($event,$data) = split(/\s+/,&unescape($event),2);
 7203:             if ($event eq 'Role') {
 7204:                 my ($rolecode,$extent) = split(/\./,$data,2);
 7205:                 next if ($extent eq '');
 7206:                 my ($crstype,$desc,$info);
 7207:                 if ($extent =~ m{^/($match_domain)/($match_courseid)(?:/(\w+)|)$}) {
 7208:                     my ($cdom,$cnum,$sec) = ($1,$2,$3);
 7209:                     my $cid = $cdom.'_'.$cnum;
 7210:                     if (exists($courses{$cid})) {
 7211:                         $crstype = $courses{$cid}{'type'};
 7212:                         $desc = $courses{$cid}{'description'};
 7213:                     } elsif ($missing{$cid}) {
 7214:                         $crstype = 'Course';
 7215:                         $desc = 'Course/Community';
 7216:                     } else {
 7217:                         my %crsinfo = &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 7218:                         if (ref($crsinfo{$cdom.'_'.$cnum}) eq 'HASH') {
 7219:                             $courses{$cid} = $crsinfo{$cid};
 7220:                             $crstype = $crsinfo{$cid}{'type'};
 7221:                             $desc = $crsinfo{$cid}{'description'};
 7222:                         } else {
 7223:                             $missing{$cid} = 1;
 7224:                         }
 7225:                     }
 7226:                     $extra = &mt($crstype).': <a href="/public/'.$cdom.'/'.$cnum.'/syllabus">'.$desc.'</a>';
 7227:                     if ($sec ne '') {
 7228:                        $extra .= ' ('.&mt('Section: [_1]',$sec).')';
 7229:                     }
 7230:                 } elsif ($extent =~ m{^/($match_domain)/($match_username|$)}) {
 7231:                     my ($dom,$name) = ($1,$2);
 7232:                     if ($rolecode eq 'au') {
 7233:                         $extra = '';
 7234:                     } elsif ($rolecode =~ /^(ca|aa)$/) {
 7235:                         $extra = &mt('Authoring Space: [_1]',$name.':'.$dom);
 7236:                     } elsif ($rolecode =~ /^(li|dg|dh|dc|sc)$/) {
 7237:                         $extra = &mt('Domain: [_1]',$dom);
 7238:                     }
 7239:                 }
 7240:                 my $rolename;
 7241:                 if ($rolecode =~ m{^cr/($match_domain)/($match_username)/(\w+)}) {
 7242:                     my $role = $3;
 7243:                     my $owner = "($2:$1)";
 7244:                     if ($2 eq $1.'-domainconfig') {
 7245:                         $owner = '(ad hoc)';
 7246:                     }
 7247:                     $rolename = &mt('Custom role: [_1]',$role.' '.$owner);
 7248:                 } else {
 7249:                     $rolename = &Apache::lonnet::plaintext($rolecode,$crstype);
 7250:                 }
 7251:                 $shown = &mt('Role selection: [_1]',$rolename);
 7252:             } else {
 7253:                 $shown = &mt($event);
 7254:                 if ($data =~ /^webdav/) {
 7255:                     my ($path,$clientip) = split(/\s+/,$data,2);
 7256:                     $path =~ s/^webdav//;
 7257:                     if ($clientip ne '') {
 7258:                         $extra = &mt('Client IP address: [_1]',$clientip);
 7259:                     }
 7260:                     if ($path ne '') {
 7261:                         $shown .= ' '.&mt('(WebDAV access to [_1])',$path);
 7262:                     }
 7263:                 } elsif ($data ne '') {
 7264:                     $extra = &mt('Client IP address: [_1]',$data);
 7265:                 }
 7266:             }
 7267:             $r->print(
 7268:             &Apache::loncommon::start_data_table_row()
 7269:            .'<td>'.$count.'</td>'
 7270:            .'<td>'.&Apache::lonlocal::locallocaltime($timestamp).'</td>'
 7271:            .'<td>'.$host.'</td>'
 7272:            .'<td>'.$shown.'</td>'
 7273:            .'<td>'.$extra.'</td>'
 7274:            .&Apache::loncommon::end_data_table_row()."\n");
 7275:         }
 7276:     }
 7277: 
 7278:     if ($showntableheader) { # Table footer, if content displayed above
 7279:         $r->print(&Apache::loncommon::end_data_table().
 7280:                   &userlogdisplay_navlinks(\%curr,$more_records));
 7281:     } else { # No content displayed above
 7282:         $r->print($heading.'<p class="LC_info">'
 7283:                  .&mt('There are no records to display.')
 7284:                  .'</p>');
 7285:     }
 7286: 
 7287:     if ($env{'form.popup'} == 1) {
 7288:         $r->print('<input type="hidden" name="popup" value="1" />'."\n");
 7289:     }
 7290: 
 7291:     # Form Footer
 7292:     $r->print(
 7293:         '<input type="hidden" name="currstate" value="" />'
 7294:        .'<input type="hidden" name="accessuname" value="'.$uname.'" />'
 7295:        .'<input type="hidden" name="accessudom" value="'.$udom.'" />'
 7296:        .'<input type="hidden" name="page" value="'.$curr{'page'}.'" />'
 7297:        .'<input type="hidden" name="prevphases" value="'.$prevphasestr.'" />'
 7298:        .'<input type="hidden" name="phase" value="activity" />'
 7299:        .'<input type="hidden" name="action" value="accesslogs" />'
 7300:        .'<input type="hidden" name="srchdomain" value="'.$udom.'" />'
 7301:        .'<input type="hidden" name="srchby" value="'.$env{'form.srchby'}.'" />'
 7302:        .'<input type="hidden" name="srchtype" value="'.$env{'form.srchtype'}.'" />'
 7303:        .'<input type="hidden" name="srchterm" value="'.&HTML::Entities::encode($env{'form.srchterm'},'<>"&').'" />'
 7304:        .'<input type="hidden" name="srchin" value="'.$env{'form.srchin'}.'" />'
 7305:        .'</form>');
 7306:     return;
 7307: }
 7308: 
 7309: sub earlyout_accesslog_form {
 7310:     my ($formname,$prevphasestr,$udom) = @_;
 7311:     my $srchterm = &HTML::Entities::encode($env{'form.srchterm'},'<>"&');
 7312:    return <<"END";
 7313: <form action="/adm/createuser" method="post" name="$formname">
 7314: <input type="hidden" name="currstate" value="" />
 7315: <input type="hidden" name="prevphases" value="$prevphasestr" />
 7316: <input type="hidden" name="phase" value="activity" />
 7317: <input type="hidden" name="action" value="accesslogs" />
 7318: <input type="hidden" name="srchdomain" value="$udom" />
 7319: <input type="hidden" name="srchby" value="$env{'form.srchby'}" />
 7320: <input type="hidden" name="srchtype" value="$env{'form.srchtype'}" />
 7321: <input type="hidden" name="srchterm" value="$srchterm" />
 7322: <input type="hidden" name="srchin" value="$env{'form.srchin'}" />
 7323: </form>
 7324: END
 7325: }
 7326: 
 7327: sub activity_display_filter {
 7328:     my ($formname,$curr) = @_;
 7329:     my $nolink = 1;
 7330:     my $output = '<table><tr><td valign="top">'.
 7331:                  '<span class="LC_nobreak"><b>'.&mt('Actions/page:').'</b></span><br />'.
 7332:                  &Apache::lonmeta::selectbox('show',$curr->{'show'},undef,
 7333:                                               (&mt('all'),5,10,20,50,100,1000,10000)).
 7334:                  '</td><td>&nbsp;&nbsp;</td>';
 7335:     my $startform =
 7336:         &Apache::lonhtmlcommon::date_setter($formname,'accesslog_start_date',
 7337:                                             $curr->{'accesslog_start_date'},undef,
 7338:                                             undef,undef,undef,undef,undef,undef,$nolink);
 7339:     my $endform =
 7340:         &Apache::lonhtmlcommon::date_setter($formname,'accesslog_end_date',
 7341:                                             $curr->{'accesslog_end_date'},undef,
 7342:                                             undef,undef,undef,undef,undef,undef,$nolink);
 7343:     my %lt = &Apache::lonlocal::texthash (
 7344:                                           activity => 'Activity',
 7345:                                           Role     => 'Role selection',
 7346:                                           log      => 'Log-in or Logout',
 7347:     );
 7348:     $output .= '<td valign="top"><b>'.&mt('Window during which actions occurred:').'</b><br />'.
 7349:                '<table><tr><td>'.&mt('After:').
 7350:                '</td><td>'.$startform.'</td></tr>'.
 7351:                '<tr><td>'.&mt('Before:').'</td>'.
 7352:                '<td>'.$endform.'</td></tr></table>'.
 7353:                '</td>'.
 7354:                '<td>&nbsp;&nbsp;</td>'.
 7355:                '<td valign="top"><b>'.&mt('Activities').'</b><br />'.
 7356:                '<select name="activity"><option value="any"';
 7357:     if ($curr->{'activity'} eq 'any') {
 7358:         $output .= ' selected="selected"';
 7359:     }
 7360:     $output .= '>'.&mt('Any').'</option>'."\n";
 7361:     foreach my $activity ('Role','log') {
 7362:         my $selstr = '';
 7363:         if ($activity eq $curr->{'activity'}) {
 7364:             $selstr = ' selected="selected"';
 7365:         }
 7366:         $output .= '<option value="'.$activity.'"'.$selstr.'>'.$lt{$activity}.'</option>';
 7367:     }
 7368:     $output .= '</select></td>'.
 7369:                '</tr></table>';
 7370:     # Update Display button
 7371:     $output .= '<p>'
 7372:               .'<input type="submit" value="'.&mt('Update Display').'" />'
 7373:               .'</p><hr />';
 7374:     return $output;
 7375: }
 7376: 
 7377: sub userlogdisplay_js {
 7378:     my ($formname) = @_;
 7379:     return <<"ENDSCRIPT";
 7380: 
 7381: function chgPage(caller) {
 7382:     if (caller == 'previous') {
 7383:         document.$formname.page.value --;
 7384:     }
 7385:     if (caller == 'next') {
 7386:         document.$formname.page.value ++;
 7387:     }
 7388:     document.$formname.submit();
 7389:     return;
 7390: }
 7391: ENDSCRIPT
 7392: }
 7393: 
 7394: sub userlogdisplay_navlinks {
 7395:     my ($curr,$more_records) = @_;
 7396:     return unless(ref($curr) eq 'HASH');
 7397:     # Navigation Buttons
 7398:     my $nav_links = '<p>';
 7399:     if (($curr->{'page'} > 1) || ($more_records)) {
 7400:         if (($curr->{'page'} > 1) && ($curr->{'show'} !~ /\D/)) {
 7401:             $nav_links .= '<input type="button"'
 7402:                          .' onclick="javascript:chgPage('."'previous'".');"'
 7403:                          .' value="'.&mt('Previous [_1] changes',$curr->{'show'})
 7404:                          .'" /> ';
 7405:         }
 7406:         if ($more_records) {
 7407:             $nav_links .= '<input type="button"'
 7408:                          .' onclick="javascript:chgPage('."'next'".');"'
 7409:                          .' value="'.&mt('Next [_1] changes',$curr->{'show'})
 7410:                          .'" />';
 7411:         }
 7412:     }
 7413:     $nav_links .= '</p>';
 7414:     return $nav_links;
 7415: }
 7416: 
 7417: sub role_display_filter {
 7418:     my ($context,$formname,$cdom,$cnum,$curr,$version,$crstype) = @_;
 7419:     my $lctype;
 7420:     if ($context eq 'course') {
 7421:         $lctype = lc($crstype);
 7422:     }
 7423:     my $nolink = 1;
 7424:     my $output = '<table><tr><td valign="top">'.
 7425:                  '<span class="LC_nobreak"><b>'.&mt('Changes/page:').'</b></span><br />'.
 7426:                  &Apache::lonmeta::selectbox('show',$curr->{'show'},undef,
 7427:                                               (&mt('all'),5,10,20,50,100,1000,10000)).
 7428:                  '</td><td>&nbsp;&nbsp;</td>';
 7429:     my $startform =
 7430:         &Apache::lonhtmlcommon::date_setter($formname,'rolelog_start_date',
 7431:                                             $curr->{'rolelog_start_date'},undef,
 7432:                                             undef,undef,undef,undef,undef,undef,$nolink);
 7433:     my $endform =
 7434:         &Apache::lonhtmlcommon::date_setter($formname,'rolelog_end_date',
 7435:                                             $curr->{'rolelog_end_date'},undef,
 7436:                                             undef,undef,undef,undef,undef,undef,$nolink);
 7437:     my %lt = &rolechg_contexts($context,$crstype);
 7438:     $output .= '<td valign="top"><b>'.&mt('Window during which changes occurred:').'</b><br />'.
 7439:                '<table><tr><td>'.&mt('After:').
 7440:                '</td><td>'.$startform.'</td></tr>'.
 7441:                '<tr><td>'.&mt('Before:').'</td>'.
 7442:                '<td>'.$endform.'</td></tr></table>'.
 7443:                '</td>'.
 7444:                '<td>&nbsp;&nbsp;</td>'.
 7445:                '<td valign="top"><b>'.&mt('Role:').'</b><br />'.
 7446:                '<select name="role"><option value="any"';
 7447:     if ($curr->{'role'} eq 'any') {
 7448:         $output .= ' selected="selected"';
 7449:     }
 7450:     $output .=  '>'.&mt('Any').'</option>'."\n";
 7451:     my @roles = &Apache::lonuserutils::roles_by_context($context,1,$crstype);
 7452:     foreach my $role (@roles) {
 7453:         my $plrole;
 7454:         if ($role eq 'cr') {
 7455:             $plrole = &mt('Custom Role');
 7456:         } else {
 7457:             $plrole=&Apache::lonnet::plaintext($role,$crstype);
 7458:         }
 7459:         my $selstr = '';
 7460:         if ($role eq $curr->{'role'}) {
 7461:             $selstr = ' selected="selected"';
 7462:         }
 7463:         $output .= '  <option value="'.$role.'"'.$selstr.'>'.$plrole.'</option>';
 7464:     }
 7465:     $output .= '</select></td>'.
 7466:                '<td>&nbsp;&nbsp;</td>'.
 7467:                '<td valign="top"><b>'.
 7468:                &mt('Context:').'</b><br /><select name="chgcontext">';
 7469:     my @posscontexts;
 7470:     if ($context eq 'course') {
 7471:         @posscontexts = ('any','automated','updatenow','createcourse','course','domain','selfenroll','requestcourses','chgtype');
 7472:     } elsif ($context eq 'domain') {
 7473:         @posscontexts = ('any','domain','requestauthor','domconfig','server');
 7474:     } else {
 7475:         @posscontexts = ('any','author','domain');
 7476:     }
 7477:     foreach my $chgtype (@posscontexts) {
 7478:         my $selstr = '';
 7479:         if ($curr->{'chgcontext'} eq $chgtype) {
 7480:             $selstr = ' selected="selected"';
 7481:         }
 7482:         if ($context eq 'course') {
 7483:             if (($chgtype eq 'automated') || ($chgtype eq 'updatenow')) {
 7484:                 next if (!&Apache::lonnet::auto_run($cnum,$cdom));
 7485:             }
 7486:         }
 7487:         $output .= '<option value="'.$chgtype.'"'.$selstr.'>'.$lt{$chgtype}.'</option>'."\n";
 7488:     }
 7489:     $output .= '</select></td>'
 7490:               .'</tr></table>';
 7491: 
 7492:     # Update Display button
 7493:     $output .= '<p>'
 7494:               .'<input type="submit" value="'.&mt('Update Display').'" />'
 7495:               .'</p>';
 7496: 
 7497:     # Server version info
 7498:     my $needsrev = '2.11.0';
 7499:     if ($context eq 'course') {
 7500:         $needsrev = '2.7.0';
 7501:     }
 7502:     
 7503:     $output .= '<p class="LC_info">'
 7504:               .&mt('Only changes made from servers running LON-CAPA [_1] or later are displayed.'
 7505:                   ,$needsrev);
 7506:     if ($version) {
 7507:         $output .= ' '.&mt('This LON-CAPA server is version [_1]',$version);
 7508:     }
 7509:     $output .= '</p><hr />';
 7510:     return $output;
 7511: }
 7512: 
 7513: sub rolechg_contexts {
 7514:     my ($context,$crstype) = @_;
 7515:     my %lt;
 7516:     if ($context eq 'course') {
 7517:         %lt = &Apache::lonlocal::texthash (
 7518:                                              any          => 'Any',
 7519:                                              automated    => 'Automated Enrollment',
 7520:                                              chgtype      => 'Enrollment Type/Lock Change',
 7521:                                              updatenow    => 'Roster Update',
 7522:                                              createcourse => 'Course Creation',
 7523:                                              course       => 'User Management in course',
 7524:                                              domain       => 'User Management in domain',
 7525:                                              selfenroll   => 'Self-enrolled',
 7526:                                              requestcourses => 'Course Request',
 7527:                                          );
 7528:         if ($crstype eq 'Community') {
 7529:             $lt{'createcourse'} = &mt('Community Creation');
 7530:             $lt{'course'} = &mt('User Management in community');
 7531:             $lt{'requestcourses'} = &mt('Community Request');
 7532:         }
 7533:     } elsif ($context eq 'domain') {
 7534:         %lt = &Apache::lonlocal::texthash (
 7535:                                              any           => 'Any',
 7536:                                              domain        => 'User Management in domain',
 7537:                                              requestauthor => 'Authoring Request',
 7538:                                              server        => 'Command line script (DC role)',
 7539:                                              domconfig     => 'Self-enrolled',
 7540:                                          );
 7541:     } else {
 7542:         %lt = &Apache::lonlocal::texthash (
 7543:                                              any    => 'Any',
 7544:                                              domain => 'User Management in domain',
 7545:                                              author => 'User Management by author',
 7546:                                          );
 7547:     } 
 7548:     return %lt;
 7549: }
 7550: 
 7551: sub print_helpdeskaccess_display {
 7552:     my ($r,$permission,$brcrum) = @_;
 7553:     my $formname = 'helpdeskaccess';
 7554:     my $helpitem = 'Course_Helpdesk_Access';
 7555:     push (@{$brcrum},
 7556:              {href => '/adm/createuser?action=helpdesk',
 7557:               text => 'Helpdesk Access',
 7558:               help => $helpitem});
 7559:     my $bread_crumbs_component = 'Helpdesk Staff Access';
 7560:     my $args = { bread_crumbs           => $brcrum,
 7561:                  bread_crumbs_component => $bread_crumbs_component};
 7562: 
 7563:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7564:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7565:     my $confname = $cdom.'-domainconfig';
 7566:     my $crstype = &Apache::loncommon::course_type();
 7567: 
 7568:     my @accesstypes = ('all','dh','da','none');
 7569:     my ($numstatustypes,@jsarray);
 7570:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($cdom);
 7571:     if (ref($types) eq 'ARRAY') {
 7572:         if (@{$types} > 0) {
 7573:             $numstatustypes = scalar(@{$types});
 7574:             push(@accesstypes,'status');
 7575:             @jsarray = ('bystatus');
 7576:         }
 7577:     }
 7578:     my %customroles = &get_domain_customroles($cdom,$confname);
 7579:     my %domhelpdesk = &Apache::lonnet::get_active_domroles($cdom,['dh','da']);
 7580:     if (keys(%domhelpdesk)) {
 7581:        push(@accesstypes,('inc','exc'));
 7582:        push(@jsarray,('notinc','notexc'));
 7583:     }
 7584:     push(@jsarray,'privs');
 7585:     my $hiddenstr = join("','",@jsarray);
 7586:     my $rolestr = join("','",sort(keys(%customroles)));
 7587: 
 7588:     my $jscript;
 7589:     my (%settings,%overridden);
 7590:     if (keys(%customroles)) {
 7591:         &get_adhocrole_settings($env{'request.course.id'},\@accesstypes,
 7592:                                 $types,\%customroles,\%settings,\%overridden);
 7593:         my %jsfull=();
 7594:         my %jslevels= (
 7595:                      course => {},
 7596:                      domain => {},
 7597:                      system => {},
 7598:                     );
 7599:         my %jslevelscurrent=(
 7600:                            course => {},
 7601:                            domain => {},
 7602:                            system => {},
 7603:                           );
 7604:         my (%privs,%jsprivs);
 7605:         &Apache::lonuserutils::custom_role_privs(\%privs,\%jsfull,\%jslevels,\%jslevelscurrent);
 7606:         foreach my $priv (keys(%jsfull)) {
 7607:             if ($jslevels{'course'}{$priv}) {
 7608:                 $jsprivs{$priv} = 1;
 7609:             }
 7610:         }
 7611:         my (%elements,%stored);
 7612:         foreach my $role (keys(%customroles)) {
 7613:             $elements{$role.'_access'} = 'radio';
 7614:             $elements{$role.'_incrs'} = 'radio';
 7615:             if ($numstatustypes) {
 7616:                 $elements{$role.'_status'} = 'checkbox';
 7617:             }
 7618:             if (keys(%domhelpdesk) > 0) {
 7619:                 $elements{$role.'_staff_inc'} = 'checkbox';
 7620:                 $elements{$role.'_staff_exc'} = 'checkbox';
 7621:             }
 7622:             $elements{$role.'_override'} = 'checkbox';
 7623:             if (ref($settings{$role}) eq 'HASH') {
 7624:                 if ($settings{$role}{'access'} ne '') {
 7625:                     my $curraccess = $settings{$role}{'access'};
 7626:                     $stored{$role.'_access'} = $curraccess;
 7627:                     $stored{$role.'_incrs'} = 1;
 7628:                     if ($curraccess eq 'status') {
 7629:                         if (ref($settings{$role}{'status'}) eq 'ARRAY') {
 7630:                             $stored{$role.'_status'} = $settings{$role}{'status'};
 7631:                         }
 7632:                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 7633:                         if (ref($settings{$role}{$curraccess}) eq 'ARRAY') {
 7634:                             $stored{$role.'_staff_'.$curraccess} = $settings{$role}{$curraccess};
 7635:                         }
 7636:                     }
 7637:                 } else {
 7638:                     $stored{$role.'_incrs'} = 0;
 7639:                 }
 7640:                 $stored{$role.'_override'} = [];
 7641:                 if ($env{'course.'.$env{'request.course.id'}.'.internal.adhocpriv.'.$role}) {
 7642:                     if (ref($settings{$role}{'off'}) eq 'ARRAY') {
 7643:                         foreach my $priv (@{$settings{$role}{'off'}}) {
 7644:                             push(@{$stored{$role.'_override'}},$priv);
 7645:                         }
 7646:                     }
 7647:                     if (ref($settings{$role}{'on'}) eq 'ARRAY') {
 7648:                         foreach my $priv (@{$settings{$role}{'on'}}) {
 7649:                             unless (grep(/^$priv$/,@{$stored{$role.'_override'}})) {
 7650:                                 push(@{$stored{$role.'_override'}},$priv);
 7651:                             }
 7652:                         }
 7653:                     }
 7654:                 }
 7655:             } else {
 7656:                 $stored{$role.'_incrs'} = 0;
 7657:             }
 7658:         }
 7659:         $jscript = &Apache::lonhtmlcommon::set_form_elements(\%elements,\%stored);
 7660:     }
 7661: 
 7662:     my $js = <<"ENDJS";
 7663: <script type="text/javascript">
 7664: // <![CDATA[
 7665: $jscript;
 7666: 
 7667: function switchRoleTab(caller,role) {
 7668:     if (document.getElementById(role+'_maindiv')) {
 7669:         if (caller.id != 'LC_current_minitab') {
 7670:             if (document.getElementById('LC_current_minitab')) {
 7671:                 document.getElementById('LC_current_minitab').id=null;
 7672:             }
 7673:             var roledivs = Array('$rolestr');
 7674:             if (roledivs.length > 0) {
 7675:                 for (var i=0; i<roledivs.length; i++) {
 7676:                     if (document.getElementById(roledivs[i]+'_maindiv')) {
 7677:                         document.getElementById(roledivs[i]+'_maindiv').style.display='none';
 7678:                     }
 7679:                 }
 7680:             }
 7681:             caller.id = 'LC_current_minitab';
 7682:             document.getElementById(role+'_maindiv').style.display='block';
 7683:         }
 7684:     }
 7685:     return false;
 7686: }
 7687: 
 7688: function helpdeskAccess(role) {
 7689:     var curraccess = null;
 7690:     if (document.$formname.elements[role+'_access'].length) {
 7691:         for (var i=0; i<document.$formname.elements[role+'_access'].length; i++) {
 7692:             if (document.$formname.elements[role+'_access'][i].checked) {
 7693:                 curraccess = document.$formname.elements[role+'_access'][i].value;
 7694:             }
 7695:         }
 7696:     }
 7697:     var shown = Array();
 7698:     var hidden = Array();
 7699:     if (curraccess == 'none') {
 7700:         hidden = Array ('$hiddenstr');
 7701:     } else {
 7702:         if (curraccess == 'status') {
 7703:             shown = Array ('bystatus','privs');
 7704:             hidden = Array ('notinc','notexc');
 7705:         } else {
 7706:             if (curraccess == 'exc') {
 7707:                 shown = Array ('notexc','privs');
 7708:                 hidden = Array ('notinc','bystatus');
 7709:             }
 7710:             if (curraccess == 'inc') {
 7711:                 shown = Array ('notinc','privs');
 7712:                 hidden = Array ('notexc','bystatus');
 7713:             }
 7714:             if (curraccess == 'all') {
 7715:                 shown = Array ('privs');
 7716:                 hidden = Array ('notinc','notexc','bystatus');
 7717:             }
 7718:         }
 7719:     }
 7720:     if (hidden.length > 0) {
 7721:         for (var i=0; i<hidden.length; i++) {
 7722:             if (document.getElementById(role+'_'+hidden[i])) {
 7723:                 document.getElementById(role+'_'+hidden[i]).style.display = 'none';
 7724:             }
 7725:         }
 7726:     }
 7727:     if (shown.length > 0) {
 7728:         for (var i=0; i<shown.length; i++) {
 7729:             if (document.getElementById(role+'_'+shown[i])) {
 7730:                 if (shown[i] == 'privs') {
 7731:                     document.getElementById(role+'_'+shown[i]).style.display = 'block';
 7732:                 } else {
 7733:                     document.getElementById(role+'_'+shown[i]).style.display = 'inline';
 7734:                 }
 7735:             }
 7736:         }
 7737:     }
 7738:     return;
 7739: }
 7740: 
 7741: function toggleAccess(role) {
 7742:     if ((document.getElementById(role+'_setincrs')) &&
 7743:         (document.getElementById(role+'_setindom'))) {
 7744:         for (var i=0; i<document.$formname.elements[role+'_incrs'].length; i++) {
 7745:             if (document.$formname.elements[role+'_incrs'][i].checked) {
 7746:                 if (document.$formname.elements[role+'_incrs'][i].value == 1) {
 7747:                     document.getElementById(role+'_setindom').style.display = 'none';
 7748:                     document.getElementById(role+'_setincrs').style.display = 'block';
 7749:                 } else {
 7750:                     document.getElementById(role+'_setincrs').style.display = 'none';
 7751:                     document.getElementById(role+'_setindom').style.display = 'block';
 7752:                 }
 7753:                 break;
 7754:             }
 7755:         }
 7756:     }
 7757:     return;
 7758: }
 7759: 
 7760: // ]]>
 7761: </script>
 7762: ENDJS
 7763: 
 7764:     $args->{add_entries} = {onload => "javascript:setFormElements(document.$formname)"};
 7765: 
 7766:     # print page header
 7767:     $r->print(&header($js,$args));
 7768:     # print form header
 7769:     $r->print('<form action="/adm/createuser" method="post" name="'.$formname.'">');
 7770: 
 7771:     if (keys(%customroles)) {
 7772:         my %lt = &Apache::lonlocal::texthash(
 7773:                     'aco'    => 'As course owner you may override the defaults set in the domain for role usage and/or privileges.',
 7774:                     'rou'    => 'Role usage',
 7775:                     'whi'    => 'Which helpdesk personnel may use this role?',
 7776:                     'udd'    => 'Use domain default',
 7777:                     'all'    => 'All with domain helpdesk or helpdesk assistant role',
 7778:                     'dh'     => 'All with domain helpdesk role',
 7779:                     'da'     => 'All with domain helpdesk assistant role',
 7780:                     'none'   => 'None',
 7781:                     'status' => 'Determined based on institutional status',
 7782:                     'inc'    => 'Include all, but exclude specific personnel',
 7783:                     'exc'    => 'Exclude all, but include specific personnel',
 7784:                     'hel'    => 'Helpdesk',
 7785:                     'rpr'    => 'Role privileges',
 7786:                  );
 7787:         $lt{'tfh'} = &mt("Custom [_1]ad hoc[_2] course roles available for use by the domain's helpdesk are as follows",'<i>','</i>');
 7788:         my %domconfig = &Apache::lonnet::get_dom('configuration',['helpsettings'],$cdom);
 7789:         my (%domcurrent,%ordered,%description,%domusage,$disabled);
 7790:         if (ref($domconfig{'helpsettings'}) eq 'HASH') {
 7791:             if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
 7792:                 %domcurrent = %{$domconfig{'helpsettings'}{'adhoc'}};
 7793:             }
 7794:         }
 7795:         my $count = 0;
 7796:         foreach my $role (sort(keys(%customroles))) {
 7797:             my ($order,$desc,$access_in_dom);
 7798:             if (ref($domcurrent{$role}) eq 'HASH') {
 7799:                 $order = $domcurrent{$role}{'order'};
 7800:                 $desc = $domcurrent{$role}{'desc'};
 7801:                 $access_in_dom = $domcurrent{$role}{'access'};
 7802:             }
 7803:             if ($order eq '') {
 7804:                 $order = $count;
 7805:             }
 7806:             $ordered{$order} = $role;
 7807:             if ($desc ne '') {
 7808:                 $description{$role} = $desc;
 7809:             } else {
 7810:                 $description{$role}= $role;
 7811:             }
 7812:             $count++;
 7813:         }
 7814:         %domusage = &domain_adhoc_access(\%customroles,\%domcurrent,\@accesstypes,$usertypes,$othertitle);
 7815:         my @roles_by_num = ();
 7816:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 7817:             push(@roles_by_num,$ordered{$item});
 7818:         }
 7819:         $r->print('<p>'.$lt{'tfh'}.': <i>'.join('</i>, <i>',map { $description{$_}; } @roles_by_num).'</i>.');
 7820:         if ($permission->{'owner'}) {
 7821:             $r->print('<br />'.$lt{'aco'}.'</p><p>');
 7822:             $r->print('<input type="hidden" name="state" value="process" />'.
 7823:                       '<input type="submit" value="'.&mt('Save changes').'" />');
 7824:         } else {
 7825:             if ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'}) {
 7826:                 my ($ownername,$ownerdom) = split(/:/,$env{'course.'.$env{'request.course.id'}.'.internal.courseowner'});
 7827:                 $r->print('<br />'.&mt('The course owner -- [_1] -- can override the default access and/or privileges for these ad hoc roles.',
 7828:                                     &Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($ownername,$ownerdom),$ownername,$ownerdom)));
 7829:             }
 7830:             $disabled = ' disabled="disabled"';
 7831:         }
 7832:         $r->print('</p>');
 7833: 
 7834:         $r->print('<div id="LC_minitab_header"><ul>');
 7835:         my $count = 0;
 7836:         my %visibility;
 7837:         foreach my $role (@roles_by_num) {
 7838:             my $id;
 7839:             if ($count == 0) {
 7840:                 $id=' id="LC_current_minitab"';
 7841:                 $visibility{$role} = ' style="display:block"';
 7842:             } else {
 7843:                 $visibility{$role} = ' style="display:none"';
 7844:             }
 7845:             $count ++;
 7846:             $r->print('<li'.$id.'><a href="#" onclick="javascript:switchRoleTab(this.parentNode,'."'$role'".');">'.$description{$role}.'</a></li>');
 7847:         }
 7848:         $r->print('</ul></div>');
 7849: 
 7850:         foreach my $role (@roles_by_num) {
 7851:             my %usecheck = (
 7852:                              all => ' checked="checked"',
 7853:                            );
 7854:             my %displaydiv = (
 7855:                                 status => 'none',
 7856:                                 inc    => 'none',
 7857:                                 exc    => 'none',
 7858:                                 priv   => 'block',
 7859:                              );
 7860:             my (%selected,$overridden,$incrscheck,$indomcheck,$indomvis,$incrsvis);
 7861:             if (ref($settings{$role}) eq 'HASH') {
 7862:                 if ($settings{$role}{'access'} ne '') {
 7863:                     $indomvis = ' style="display:none"';
 7864:                     $incrsvis = ' style="display:block"';
 7865:                     $incrscheck = ' checked="checked"';
 7866:                     if ($settings{$role}{'access'} ne 'all') {
 7867:                         $usecheck{$settings{$role}{'access'}} = $usecheck{'all'};
 7868:                         delete($usecheck{'all'});
 7869:                         if ($settings{$role}{'access'} eq 'status') {
 7870:                             my $access = 'status';
 7871:                             $displaydiv{$access} = 'inline';
 7872:                             if (ref($settings{$role}{$access}) eq 'ARRAY') {
 7873:                                 $selected{$access} = $settings{$role}{$access};
 7874:                             }
 7875:                         } elsif ($settings{$role}{'access'} =~ /^(inc|exc)$/) {
 7876:                             my $access = $1;
 7877:                             $displaydiv{$access} = 'inline';
 7878:                             if (ref($settings{$role}{$access}) eq 'ARRAY') {
 7879:                                 $selected{$access} = $settings{$role}{$access};
 7880:                             }
 7881:                         } elsif ($settings{$role}{'access'} eq 'none') {
 7882:                             $displaydiv{'priv'} = 'none';
 7883:                         }
 7884:                     }
 7885:                 } else {
 7886:                     $indomcheck = ' checked="checked"';
 7887:                     $indomvis = ' style="display:block"';
 7888:                     $incrsvis = ' style="display:none"';
 7889:                 }
 7890:             } else {
 7891:                 $indomcheck = ' checked="checked"';
 7892:                 $indomvis = ' style="display:block"';
 7893:                 $incrsvis = ' style="display:none"';
 7894:             }
 7895:             $r->print('<div class="LC_left_float" id="'.$role.'_maindiv"'.$visibility{$role}.'>'.
 7896:                       '<fieldset><legend>'.$lt{'rou'}.'</legend>'.
 7897:                       '<p>'.$lt{'whi'}.' <span class="LC_nobreak">'.
 7898:                       '<label><input type="radio" name="'.$role.'_incrs" value="1"'.$incrscheck.' onclick="toggleAccess('."'$role'".');"'.$disabled.'>'.
 7899:                       &mt('Set here in [_1]',lc($crstype)).'</label>'.
 7900:                       '<span>'.('&nbsp;'x2).
 7901:                       '<label><input type="radio" name="'.$role.'_incrs" value="0"'.$indomcheck.' onclick="toggleAccess('."'$role'".');"'.$disabled.'>'.
 7902:                       $lt{'udd'}.'</label><span></p>'.
 7903:                       '<div id="'.$role.'_setindom"'.$indomvis.'>'.
 7904:                       '<span class="LC_cusr_emph">'.$domusage{$role}.'</span></div>'.
 7905:                       '<div id="'.$role.'_setincrs"'.$incrsvis.'>');
 7906:             foreach my $access (@accesstypes) {
 7907:                 $r->print('<p><label><input type="radio" name="'.$role.'_access" value="'.$access.'" '.$usecheck{$access}.
 7908:                           ' onclick="helpdeskAccess('."'$role'".');"'.$disabled.' />'.$lt{$access}.'</label>');
 7909:                 if ($access eq 'status') {
 7910:                     $r->print('<div id="'.$role.'_bystatus" style="display:'.$displaydiv{$access}.'">'.
 7911:                               &Apache::lonuserutils::adhoc_status_types($cdom,undef,$role,$selected{$access},
 7912:                                                                         $othertitle,$usertypes,$types,$disabled).
 7913:                               '</div>');
 7914:                 } elsif (($access eq 'inc') && (keys(%domhelpdesk) > 0)) {
 7915:                     $r->print('<div id="'.$role.'_notinc" style="display:'.$displaydiv{$access}.'">'.
 7916:                               &Apache::lonuserutils::adhoc_staff($access,undef,$role,$selected{$access},
 7917:                                                                  \%domhelpdesk,$disabled).
 7918:                               '</div>');
 7919:                 } elsif (($access eq 'exc') && (keys(%domhelpdesk) > 0)) {
 7920:                     $r->print('<div id="'.$role.'_notexc" style="display:'.$displaydiv{$access}.'">'.
 7921:                               &Apache::lonuserutils::adhoc_staff($access,undef,$role,$selected{$access},
 7922:                                                                  \%domhelpdesk,$disabled).
 7923:                               '</div>');
 7924:                 }
 7925:                 $r->print('</p>');
 7926:             }
 7927:             $r->print('</div></fieldset>');
 7928:             my %full=();
 7929:             my %levels= (
 7930:                          course => {},
 7931:                          domain => {},
 7932:                          system => {},
 7933:                         );
 7934:             my %levelscurrent=(
 7935:                                course => {},
 7936:                                domain => {},
 7937:                                system => {},
 7938:                               );
 7939:             &Apache::lonuserutils::custom_role_privs($customroles{$role},\%full,\%levels,\%levelscurrent);
 7940:             $r->print('<fieldset id="'.$role.'_privs" style="display:'.$displaydiv{'priv'}.'">'.
 7941:                       '<legend>'.$lt{'rpr'}.'</legend>'.
 7942:                       &role_priv_table($role,$permission,$crstype,\%full,\%levels,\%levelscurrent,$overridden{$role}).
 7943:                       '</fieldset></div><div style="padding:0;clear:both;margin:0;border:0"></div>');
 7944:         }
 7945:         if ($permission->{'owner'}) {
 7946:             $r->print('<p><input type="submit" value="'.&mt('Save changes').'" /></p>');
 7947:         }
 7948:     } else {
 7949:         $r->print(&mt('Helpdesk roles have not yet been created in this domain.'));
 7950:     }
 7951:     # Form Footer
 7952:     $r->print('<input type="hidden" name="action" value="helpdesk" />'
 7953:              .'</form>');
 7954:     return;
 7955: }
 7956: 
 7957: sub domain_adhoc_access {
 7958:     my ($roles,$domcurrent,$accesstypes,$usertypes,$othertitle) = @_;
 7959:     my %domusage;
 7960:     return unless ((ref($roles) eq 'HASH') && (ref($domcurrent) eq 'HASH') && (ref($accesstypes) eq 'ARRAY'));
 7961:     foreach my $role (keys(%{$roles})) {
 7962:         if (ref($domcurrent->{$role}) eq 'HASH') {
 7963:             my $access = $domcurrent->{$role}{'access'};
 7964:             if (($access eq '') || (!grep(/^\Q$access\E$/,@{$accesstypes}))) {
 7965:                 $access = 'all';
 7966:                 $domusage{$role} = &mt('Any user in domain with active [_1] or [_2] role',&Apache::lonnet::plaintext('dh'),
 7967:                                                                                           &Apache::lonnet::plaintext('da'));
 7968:             } elsif ($access eq 'status') {
 7969:                 if (ref($domcurrent->{$role}{$access}) eq 'ARRAY') {
 7970:                     my @shown;
 7971:                     foreach my $type (@{$domcurrent->{$role}{$access}}) {
 7972:                         unless ($type eq 'default') {
 7973:                             if ($usertypes->{$type}) {
 7974:                                 push(@shown,$usertypes->{$type});
 7975:                             }
 7976:                         }
 7977:                     }
 7978:                     if (grep(/^default$/,@{$domcurrent->{$role}{$access}})) {
 7979:                         push(@shown,$othertitle);
 7980:                     }
 7981:                     if (@shown) {
 7982:                         my $shownstatus = join(' '.&mt('or').' ',@shown);
 7983:                         $domusage{$role} = &mt('Any user in domain with active [_1] or [_2] role, and institutional status: [_3]',
 7984:                                                &Apache::lonnet::plaintext('dh'),&Apache::lonnet::plaintext('da'),$shownstatus);
 7985:                     } else {
 7986:                         $domusage{$role} = &mt('No one in the domain');
 7987:                     }
 7988:                 }
 7989:             } elsif ($access eq 'inc') {
 7990:                 my @dominc = ();
 7991:                 if (ref($domcurrent->{$role}{'inc'}) eq 'ARRAY') {
 7992:                     foreach my $user (@{$domcurrent->{$role}{'inc'}}) {
 7993:                         my ($uname,$udom) = split(/:/,$user);
 7994:                         push(@dominc,&Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($uname,$udom),$uname,$udom));
 7995:                     }
 7996:                     my $showninc = join(', ',@dominc);
 7997:                     if ($showninc ne '') {
 7998:                         $domusage{$role} = &mt('Include any user in domain with active [_1] or [_2] role, except: [_3]',
 7999:                                                &Apache::lonnet::plaintext('dh'),&Apache::lonnet::plaintext('da'),$showninc);
 8000:                     } else {
 8001:                         $domusage{$role} = &mt('Any user in domain with active [_1] or [_2] role',
 8002:                                                &Apache::lonnet::plaintext('dh'),&Apache::lonnet::plaintext('da'));
 8003:                     }
 8004:                 }
 8005:             } elsif ($access eq 'exc') {
 8006:                 my @domexc = ();
 8007:                 if (ref($domcurrent->{$role}{'exc'}) eq 'ARRAY') {
 8008:                     foreach my $user (@{$domcurrent->{$role}{'exc'}}) {
 8009:                         my ($uname,$udom) = split(/:/,$user);
 8010:                         push(@domexc,&Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($uname,$udom),$uname,$udom));
 8011:                     }
 8012:                 }
 8013:                 my $shownexc = join(', ',@domexc);
 8014:                 if ($shownexc ne '') {
 8015:                     $domusage{$role} = &mt('Only the following in the domain with active [_1] or [_2] role: [_3]',
 8016:                                            &Apache::lonnet::plaintext('dh'),&Apache::lonnet::plaintext('da'),$shownexc);
 8017:                 } else {
 8018:                     $domusage{$role} = &mt('No one in the domain');
 8019:                 }
 8020:             } elsif ($access eq 'none') {
 8021:                 $domusage{$role} = &mt('No one in the domain');
 8022:             } elsif ($access eq 'dh') {
 8023:                 $domusage{$role} = &mt('Any user in domain with active [_1] role',&Apache::lonnet::plaintext('dh'));
 8024:             } elsif ($access eq 'da') {
 8025:                 $domusage{$role} = &mt('Any user in domain with active [_1] role',&Apache::lonnet::plaintext('da'));
 8026:             } elsif ($access eq 'all') {
 8027:                 $domusage{$role} = &mt('Any user in domain with active [_1] or [_2] role',
 8028:                                        &Apache::lonnet::plaintext('dh'),&Apache::lonnet::plaintext('da'));
 8029:             }
 8030:         } else {
 8031:             $domusage{$role} = &mt('Any user in domain with active [_1] or [_2] role',
 8032:                                    &Apache::lonnet::plaintext('dh'),&Apache::lonnet::plaintext('da'));
 8033:         }
 8034:     }
 8035:     return %domusage;
 8036: }
 8037: 
 8038: sub get_domain_customroles {
 8039:     my ($cdom,$confname) = @_;
 8040:     my %existing=&Apache::lonnet::dump('roles',$cdom,$confname,'rolesdef_');
 8041:     my %customroles;
 8042:     foreach my $key (keys(%existing)) {
 8043:         if ($key=~/^rolesdef\_(\w+)$/) {
 8044:             my $rolename = $1;
 8045:             my %privs;
 8046:             ($privs{'system'},$privs{'domain'},$privs{'course'}) = split(/\_/,$existing{$key});
 8047:             $customroles{$rolename} = \%privs;
 8048:         }
 8049:     }
 8050:     return %customroles;
 8051: }
 8052: 
 8053: sub role_priv_table {
 8054:     my ($role,$permission,$crstype,$full,$levels,$levelscurrent,$overridden) = @_;
 8055:     return unless ((ref($full) eq 'HASH') && (ref($levels) eq 'HASH') &&
 8056:                    (ref($levelscurrent) eq 'HASH'));
 8057:     my %lt=&Apache::lonlocal::texthash (
 8058:                     'crl'  => 'Course Level Privilege',
 8059:                     'def'  => 'Domain Defaults',
 8060:                     'ove'  => 'Override in Course',
 8061:                     'ine'  => 'In effect',
 8062:                     'dis'  => 'Disabled',
 8063:                     'ena'  => 'Enabled',
 8064:                    );
 8065:     if ($crstype eq 'Community') {
 8066:         $lt{'ove'} = 'Override in Community',
 8067:     }
 8068:     my @status = ('Disabled','Enabled');
 8069:     my (%on,%off);
 8070:     if (ref($overridden) eq 'HASH') {
 8071:         if (ref($overridden->{'on'}) eq 'ARRAY') {
 8072:             map { $on{$_} = 1; } (@{$overridden->{'on'}});
 8073:         }
 8074:         if (ref($overridden->{'off'}) eq 'ARRAY') {
 8075:             map { $off{$_} = 1; } (@{$overridden->{'off'}});
 8076:         }
 8077:     }
 8078:     my $output=&Apache::loncommon::start_data_table().
 8079:                &Apache::loncommon::start_data_table_header_row().
 8080:                '<th>'.$lt{'crl'}.'</th><th>'.$lt{'def'}.'</th><th>'.$lt{'ove'}.
 8081:                '</th><th>'.$lt{'ine'}.'</th>'.
 8082:                &Apache::loncommon::end_data_table_header_row();
 8083:     foreach my $priv (sort(keys(%{$full}))) {
 8084:         next unless ($levels->{'course'}{$priv});
 8085:         my $privtext = &Apache::lonnet::plaintext($priv,$crstype);
 8086:         my ($default,$ineffect);
 8087:         if ($levelscurrent->{'course'}{$priv}) {
 8088:             $default = '<img src="/adm/lonIcons/navmap.correct.gif" alt="'.$lt{'ena'}.'" />';
 8089:             $ineffect = $default;
 8090:         }
 8091:         my ($customstatus,$checked);
 8092:         $output .= &Apache::loncommon::start_data_table_row().
 8093:                    '<td>'.$privtext.'</td>'.
 8094:                    '<td>'.$default.'</td><td>';
 8095:         if (($levelscurrent->{'course'}{$priv}) && ($off{$priv})) {
 8096:             if ($permission->{'owner'}) {
 8097:                 $checked = ' checked="checked"';
 8098:             }
 8099:             $customstatus = '<img src="/adm/lonIcons/navmap.wrong.gif" alt="'.$lt{'dis'}.'" />';
 8100:             $ineffect = $customstatus;
 8101:         } elsif ((!$levelscurrent->{'course'}{$priv}) && ($on{$priv})) {
 8102:             if ($permission->{'owner'}) {
 8103:                 $checked = ' checked="checked"';
 8104:             }
 8105:             $customstatus = '<img src="/adm/lonIcons/navmap.correct.gif" alt="'.$lt{'ena'}.'" />';
 8106:             $ineffect = $customstatus;
 8107:         }
 8108:         if ($permission->{'owner'}) {
 8109:             $output .= '<input type="checkbox" name="'.$role.'_override" value="'.$priv.'"'.$checked.' />';
 8110:         } else {
 8111:             $output .= $customstatus;
 8112:         }
 8113:         $output .= '</td><td>'.$ineffect.'</td>'.
 8114:                    &Apache::loncommon::end_data_table_row();
 8115:     }
 8116:     $output .= &Apache::loncommon::end_data_table();
 8117:     return $output;
 8118: }
 8119: 
 8120: sub get_adhocrole_settings {
 8121:     my ($cid,$accesstypes,$types,$customroles,$settings,$overridden) = @_;
 8122:     return unless ((ref($accesstypes) eq 'ARRAY') && (ref($customroles) eq 'HASH') &&
 8123:                    (ref($settings) eq 'HASH') && (ref($overridden) eq 'HASH'));
 8124:     foreach my $role (split(/,/,$env{'course.'.$cid.'.internal.adhocaccess'})) {
 8125:         my ($curraccess,$rest) = split(/=/,$env{'course.'.$cid.'.internal.adhoc.'.$role});
 8126:         if (($curraccess ne '') && (grep(/^\Q$curraccess\E$/,@{$accesstypes}))) {
 8127:             $settings->{$role}{'access'} = $curraccess;
 8128:             if (($curraccess eq 'status') && (ref($types) eq 'ARRAY')) {
 8129:                 my @status = split(/,/,$rest);
 8130:                 my @currstatus;
 8131:                 foreach my $type (@status) {
 8132:                     if ($type eq 'default') {
 8133:                         push(@currstatus,$type);
 8134:                     } elsif (grep(/^\Q$type\E$/,@{$types})) {
 8135:                         push(@currstatus,$type);
 8136:                     }
 8137:                 }
 8138:                 if (@currstatus) {
 8139:                     $settings->{$role}{$curraccess} = \@currstatus;
 8140:                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 8141:                     my @personnel = split(/,/,$rest);
 8142:                     $settings->{$role}{$curraccess} = \@personnel;
 8143:                 }
 8144:             }
 8145:         }
 8146:     }
 8147:     foreach my $role (keys(%{$customroles})) {
 8148:         if ($env{'course.'.$cid.'.internal.adhocpriv.'.$role}) {
 8149:             my %currentprivs;
 8150:             if (ref($customroles->{$role}) eq 'HASH') {
 8151:                 if (exists($customroles->{$role}{'course'})) {
 8152:                     my %full=();
 8153:                     my %levels= (
 8154:                                   course => {},
 8155:                                   domain => {},
 8156:                                   system => {},
 8157:                                 );
 8158:                     my %levelscurrent=(
 8159:                                         course => {},
 8160:                                         domain => {},
 8161:                                         system => {},
 8162:                                       );
 8163:                     &Apache::lonuserutils::custom_role_privs($customroles->{$role},\%full,\%levels,\%levelscurrent);
 8164:                     %currentprivs = %{$levelscurrent{'course'}};
 8165:                 }
 8166:             }
 8167:             foreach my $item (split(/,/,$env{'course.'.$cid.'.internal.adhocpriv.'.$role})) {
 8168:                 next if ($item eq '');
 8169:                 my ($rule,$rest) = split(/=/,$item);
 8170:                 next unless (($rule eq 'off') || ($rule eq 'on'));
 8171:                 foreach my $priv (split(/:/,$rest)) {
 8172:                     if ($priv ne '') {
 8173:                         if ($rule eq 'off') {
 8174:                             push(@{$overridden->{$role}{'off'}},$priv);
 8175:                             if ($currentprivs{$priv}) {
 8176:                                 push(@{$settings->{$role}{'off'}},$priv);
 8177:                             }
 8178:                         } else {
 8179:                             push(@{$overridden->{$role}{'on'}},$priv);
 8180:                             unless ($currentprivs{$priv}) {
 8181:                                 push(@{$settings->{$role}{'on'}},$priv);
 8182:                             }
 8183:                         }
 8184:                     }
 8185:                 }
 8186:             }
 8187:         }
 8188:     }
 8189:     return;
 8190: }
 8191: 
 8192: sub update_helpdeskaccess {
 8193:     my ($r,$permission,$brcrum) = @_;
 8194:     my $helpitem = 'Course_Helpdesk_Access';
 8195:     push (@{$brcrum},
 8196:              {href => '/adm/createuser?action=helpdesk',
 8197:               text => 'Helpdesk Access',
 8198:               help => $helpitem},
 8199:              {href => '/adm/createuser?action=helpdesk',
 8200:               text => 'Result',
 8201:               help => $helpitem}
 8202:          );
 8203:     my $bread_crumbs_component = 'Helpdesk Staff Access';
 8204:     my $args = { bread_crumbs           => $brcrum,
 8205:                  bread_crumbs_component => $bread_crumbs_component};
 8206: 
 8207:     # print page header
 8208:     $r->print(&header('',$args));
 8209:     unless ((ref($permission) eq 'HASH') && ($permission->{'owner'})) {
 8210:         $r->print('<p class="LC_error">'.&mt('You do not have permission to change helpdesk access.').'</p>');
 8211:         return;
 8212:     }
 8213:     my @accesstypes = ('all','dh','da','none','status','inc','exc');
 8214:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8215:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 8216:     my $confname = $cdom.'-domainconfig';
 8217:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($cdom);
 8218:     my $crstype = &Apache::loncommon::course_type();
 8219:     my %customroles = &get_domain_customroles($cdom,$confname);
 8220:     my (%settings,%overridden);
 8221:     &get_adhocrole_settings($env{'request.course.id'},\@accesstypes,
 8222:                             $types,\%customroles,\%settings,\%overridden);
 8223:     my %domhelpdesk = &Apache::lonnet::get_active_domroles($cdom,['dh','da']);
 8224:     my (%changed,%storehash,@todelete);
 8225: 
 8226:     if (keys(%customroles)) {
 8227:         my (%newsettings,@incrs);
 8228:         foreach my $role (keys(%customroles)) {
 8229:             $newsettings{$role} = {
 8230:                                     access => '',
 8231:                                     status => '',
 8232:                                     exc    => '',
 8233:                                     inc    => '',
 8234:                                     on     => '',
 8235:                                     off    => '',
 8236:                                   };
 8237:             my %current;
 8238:             if (ref($settings{$role}) eq 'HASH') {
 8239:                 %current = %{$settings{$role}};
 8240:             }
 8241:             if (ref($overridden{$role}) eq 'HASH') {
 8242:                 $current{'overridden'} = $overridden{$role};
 8243:             }
 8244:             if ($env{'form.'.$role.'_incrs'}) {
 8245:                 my $access = $env{'form.'.$role.'_access'};
 8246:                 if (grep(/^\Q$access\E$/,@accesstypes)) {
 8247:                     push(@incrs,$role);
 8248:                     unless ($current{'access'} eq $access) {
 8249:                         $changed{$role}{'access'} = 1;
 8250:                         $storehash{'internal.adhoc.'.$role} = $access;
 8251:                     }
 8252:                     if ($access eq 'status') {
 8253:                         my @statuses = &Apache::loncommon::get_env_multiple('form.'.$role.'_status');
 8254:                         my @stored;
 8255:                         my @shownstatus;
 8256:                         if (ref($types) eq 'ARRAY') {
 8257:                             foreach my $type (sort(@statuses)) {
 8258:                                 if ($type eq 'default') {
 8259:                                     push(@stored,$type);
 8260:                                 } elsif (grep(/^\Q$type\E$/,@{$types})) {
 8261:                                     push(@stored,$type);
 8262:                                     push(@shownstatus,$usertypes->{$type});
 8263:                                 }
 8264:                             }
 8265:                             if (grep(/^default$/,@statuses)) {
 8266:                                 push(@shownstatus,$othertitle);
 8267:                             }
 8268:                             $storehash{'internal.adhoc.'.$role} .= '='.join(',',@stored);
 8269:                         }
 8270:                         $newsettings{$role}{'status'} = join(' '.&mt('or').' ',@shownstatus);
 8271:                         if (ref($current{'status'}) eq 'ARRAY') {
 8272:                             my @diffs = &Apache::loncommon::compare_arrays(\@stored,$current{'status'});
 8273:                             if (@diffs) {
 8274:                                 $changed{$role}{'status'} = 1;
 8275:                             }
 8276:                         } elsif (@stored) {
 8277:                             $changed{$role}{'status'} = 1;
 8278:                         }
 8279:                     } elsif (($access eq 'inc') || ($access eq 'exc')) {
 8280:                         my @personnel = &Apache::loncommon::get_env_multiple('form.'.$role.'_staff_'.$access);
 8281:                         my @newspecstaff;
 8282:                         my @stored;
 8283:                         my @currstaff;
 8284:                         foreach my $person (sort(@personnel)) {
 8285:                             if ($domhelpdesk{$person}) {
 8286:                                 push(@stored,$person);
 8287:                             }
 8288:                         }
 8289:                         if (ref($current{$access}) eq 'ARRAY') {
 8290:                             my @diffs = &Apache::loncommon::compare_arrays(\@stored,$current{$access});
 8291:                             if (@diffs) {
 8292:                                 $changed{$role}{$access} = 1;
 8293:                             }
 8294:                         } elsif (@stored) {
 8295:                             $changed{$role}{$access} = 1;
 8296:                         }
 8297:                         $storehash{'internal.adhoc.'.$role} .= '='.join(',',@stored);
 8298:                         foreach my $person (@stored) {
 8299:                             my ($uname,$udom) = split(/:/,$person);
 8300:                             push(@newspecstaff,&Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($uname,$udom,'lastname'),$uname,$udom));
 8301:                         }
 8302:                         $newsettings{$role}{$access} = join(', ',sort(@newspecstaff));
 8303:                     }
 8304:                     $newsettings{$role}{'access'} = $access;
 8305:                 }
 8306:             } else {
 8307:                 if (($current{'access'} ne '') && (grep(/^\Q$current{'access'}\E$/,@accesstypes))) {
 8308:                     $changed{$role}{'access'} = 1;
 8309:                     $newsettings{$role} = {};
 8310:                     push(@todelete,'internal.adhoc.'.$role);
 8311:                 }
 8312:             }
 8313:             if (($env{'form.'.$role.'_incrs'}) && ($env{'form.'.$role.'_access'} eq 'none')) {
 8314:                 if (ref($current{'overridden'}) eq 'HASH') {
 8315:                     push(@todelete,'internal.adhocpriv.'.$role);
 8316:                 }
 8317:             } else {
 8318:                 my %full=();
 8319:                 my %levels= (
 8320:                              course => {},
 8321:                              domain => {},
 8322:                              system => {},
 8323:                             );
 8324:                 my %levelscurrent=(
 8325:                                    course => {},
 8326:                                    domain => {},
 8327:                                    system => {},
 8328:                                   );
 8329:                 &Apache::lonuserutils::custom_role_privs($customroles{$role},\%full,\%levels,\%levelscurrent);
 8330:                 my (@updatedon,@updatedoff,@override);
 8331:                 @override = &Apache::loncommon::get_env_multiple('form.'.$role.'_override');
 8332:                 if (@override) {
 8333:                     foreach my $priv (sort(keys(%full))) {
 8334:                         next unless ($levels{'course'}{$priv});
 8335:                         if (grep(/^\Q$priv\E$/,@override)) {
 8336:                             if ($levelscurrent{'course'}{$priv}) {
 8337:                                 push(@updatedoff,$priv);
 8338:                             } else {
 8339:                                 push(@updatedon,$priv);
 8340:                             }
 8341:                         }
 8342:                     }
 8343:                 }
 8344:                 if (@updatedon) {
 8345:                     $newsettings{$role}{'on'} = join('</li><li>', map { &Apache::lonnet::plaintext($_,$crstype) } (@updatedon));
 8346:                 }
 8347:                 if (@updatedoff) {
 8348:                     $newsettings{$role}{'off'} = join('</li><li>', map { &Apache::lonnet::plaintext($_,$crstype) } (@updatedoff));
 8349:                 }
 8350:                 if (ref($current{'overridden'}) eq 'HASH') {
 8351:                     if (ref($current{'overridden'}{'on'}) eq 'ARRAY') {
 8352:                         if (@updatedon) {
 8353:                             my @diffs = &Apache::loncommon::compare_arrays(\@updatedon,$current{'overridden'}{'on'});
 8354:                             if (@diffs) {
 8355:                                 $changed{$role}{'on'} = 1;
 8356:                             }
 8357:                         } else {
 8358:                             $changed{$role}{'on'} = 1;
 8359:                         }
 8360:                     } elsif (@updatedon) {
 8361:                         $changed{$role}{'on'} = 1;
 8362:                     }
 8363:                     if (ref($current{'overridden'}{'off'}) eq 'ARRAY') {
 8364:                         if (@updatedoff) {
 8365:                             my @diffs = &Apache::loncommon::compare_arrays(\@updatedoff,$current{'overridden'}{'off'});
 8366:                             if (@diffs) {
 8367:                                 $changed{$role}{'off'} = 1;
 8368:                             }
 8369:                         } else {
 8370:                             $changed{$role}{'off'} = 1;
 8371:                         }
 8372:                     } elsif (@updatedoff) {
 8373:                         $changed{$role}{'off'} = 1;
 8374:                     }
 8375:                 } else {
 8376:                     if (@updatedon) {
 8377:                         $changed{$role}{'on'} = 1;
 8378:                     }
 8379:                     if (@updatedoff) {
 8380:                         $changed{$role}{'off'} = 1;
 8381:                     }
 8382:                 }
 8383:                 if (ref($changed{$role}) eq 'HASH') {
 8384:                     if (($changed{$role}{'on'} || $changed{$role}{'off'})) {
 8385:                         my $newpriv;
 8386:                         if (@updatedon) {
 8387:                             $newpriv = 'on='.join(':',@updatedon);
 8388:                         }
 8389:                         if (@updatedoff) {
 8390:                             $newpriv .= ($newpriv ? ',' : '' ).'off='.join(':',@updatedoff);
 8391:                         }
 8392:                         if ($newpriv eq '') {
 8393:                             push(@todelete,'internal.adhocpriv.'.$role);
 8394:                         } else {
 8395:                             $storehash{'internal.adhocpriv.'.$role} = $newpriv;
 8396:                         }
 8397:                     }
 8398:                 }
 8399:             }
 8400:         }
 8401:         if (@incrs) {
 8402:             $storehash{'internal.adhocaccess'} = join(',',@incrs);
 8403:         } elsif (@todelete) {
 8404:             push(@todelete,'internal.adhocaccess');
 8405:         }
 8406:         if (keys(%changed)) {
 8407:             my ($putres,$delres);
 8408:             if (keys(%storehash)) {
 8409:                 $putres = &Apache::lonnet::put('environment',\%storehash,$cdom,$cnum);
 8410:                 my %newenvhash;
 8411:                 foreach my $key (keys(%storehash)) {
 8412:                     $newenvhash{'course.'.$env{'request.course.id'}.'.'.$key} = $storehash{$key};
 8413:                 }
 8414:                 &Apache::lonnet::appenv(\%newenvhash);
 8415:             }
 8416:             if (@todelete) {
 8417:                 $delres = &Apache::lonnet::del('environment',\@todelete,$cdom,$cnum);
 8418:                 foreach my $key (@todelete) {
 8419:                     &Apache::lonnet::delenv('course.'.$env{'request.course.id'}.'.'.$key);
 8420:                 }
 8421:             }
 8422:             if (($putres eq 'ok') || ($delres eq 'ok')) {
 8423:                 my %domconfig = &Apache::lonnet::get_dom('configuration',['helpsettings'],$cdom);
 8424:                 my (%domcurrent,%ordered,%description,%domusage);
 8425:                 if (ref($domconfig{'helpsettings'}) eq 'HASH') {
 8426:                     if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
 8427:                         %domcurrent = %{$domconfig{'helpsettings'}{'adhoc'}};
 8428:                     }
 8429:                 }
 8430:                 my $count = 0;
 8431:                 foreach my $role (sort(keys(%customroles))) {
 8432:                     my ($order,$desc);
 8433:                     if (ref($domcurrent{$role}) eq 'HASH') {
 8434:                         $order = $domcurrent{$role}{'order'};
 8435:                         $desc = $domcurrent{$role}{'desc'};
 8436:                     }
 8437:                     if ($order eq '') {
 8438:                         $order = $count;
 8439:                     }
 8440:                     $ordered{$order} = $role;
 8441:                     if ($desc ne '') {
 8442:                         $description{$role} = $desc;
 8443:                     } else {
 8444:                         $description{$role}= $role;
 8445:                     }
 8446:                     $count++;
 8447:                 }
 8448:                 my @roles_by_num = ();
 8449:                 foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 8450:                     push(@roles_by_num,$ordered{$item});
 8451:                 }
 8452:                 %domusage = &domain_adhoc_access(\%changed,\%domcurrent,\@accesstypes,$usertypes,$othertitle);
 8453:                 $r->print(&mt('Helpdesk access settings have been changed as follows').'<br />');
 8454:                 $r->print('<ul>');
 8455:                 foreach my $role (@roles_by_num) {
 8456:                     next unless (ref($changed{$role}) eq 'HASH');
 8457:                     $r->print('<li>'.&mt('Ad hoc role').': <b>'.$description{$role}.'</b>'.
 8458:                               '<ul>');
 8459:                     if ($changed{$role}{'access'} || $changed{$role}{'status'} || $changed{$role}{'inc'} || $changed{$role}{'exc'}) {
 8460:                         $r->print('<li>');
 8461:                         if ($env{'form.'.$role.'_incrs'}) {
 8462:                             if ($newsettings{$role}{'access'} eq 'all') {
 8463:                                 $r->print(&mt('All helpdesk staff can access '.lc($crstype).' with this role.'));
 8464:                             } elsif ($newsettings{$role}{'access'} eq 'dh') {
 8465:                                 $r->print(&mt('Helpdesk staff can use this role if they have an active [_1] role',
 8466:                                               &Apache::lonnet::plaintext('dh')));
 8467:                             } elsif ($newsettings{$role}{'access'} eq 'da') {
 8468:                                 $r->print(&mt('Helpdesk staff can use this role if they have an active [_1] role',
 8469:                                               &Apache::lonnet::plaintext('da')));
 8470:                             } elsif ($newsettings{$role}{'access'} eq 'none') {
 8471:                                 $r->print(&mt('No helpdesk staff can access '.lc($crstype).' with this role.'));
 8472:                             } elsif ($newsettings{$role}{'access'} eq 'status') {
 8473:                                 if ($newsettings{$role}{'status'}) {
 8474:                                     my ($access,$rest) = split(/=/,$storehash{'internal.adhoc.'.$role});
 8475:                                     if (split(/,/,$rest) > 1) {
 8476:                                         $r->print(&mt('Helpdesk staff can use this role if their institutional type is one of: [_1].',
 8477:                                                       $newsettings{$role}{'status'}));
 8478:                                     } else {
 8479:                                         $r->print(&mt('Helpdesk staff can use this role if their institutional type is: [_1].',
 8480:                                                       $newsettings{$role}{'status'}));
 8481:                                     }
 8482:                                 } else {
 8483:                                     $r->print(&mt('No helpdesk staff can access '.lc($crstype).' with this role.'));
 8484:                                 }
 8485:                             } elsif ($newsettings{$role}{'access'} eq 'exc') {
 8486:                                 if ($newsettings{$role}{'exc'}) {
 8487:                                     $r->print(&mt('Helpdesk staff who can use this role are as follows:').' '.$newsettings{$role}{'exc'}.'.');
 8488:                                 } else {
 8489:                                     $r->print(&mt('No helpdesk staff can access '.lc($crstype).' with this role.'));
 8490:                                 }
 8491:                             } elsif ($newsettings{$role}{'access'} eq 'inc') {
 8492:                                 if ($newsettings{$role}{'inc'}) {
 8493:                                     $r->print(&mt('All helpdesk staff may use this role except the following:').' '.$newsettings{$role}{'inc'}.'.');
 8494:                                 } else {
 8495:                                     $r->print(&mt('All helpdesk staff may use this role.'));
 8496:                                 }
 8497:                             }
 8498:                         } else {
 8499:                             $r->print(&mt('Default access set in the domain now applies.').'<br />'.
 8500:                                       '<span class="LC_cusr_emph">'.$domusage{$role}.'</span>');
 8501:                         }
 8502:                         $r->print('</li>');
 8503:                     }
 8504:                     unless ($newsettings{$role}{'access'} eq 'none') {
 8505:                         if ($changed{$role}{'off'}) {
 8506:                             if ($newsettings{$role}{'off'}) {
 8507:                                 $r->print('<li>'.&mt('Privileges which are available by default for this ad hoc role, but are disabled for this specific '.lc($crstype).':').
 8508:                                           '<ul><li>'.$newsettings{$role}{'off'}.'</li></ul></li>');
 8509:                             } else {
 8510:                                 $r->print('<li>'.&mt('All privileges available by default for this ad hoc role are enabled.').'</li>');
 8511:                             }
 8512:                         }
 8513:                         if ($changed{$role}{'on'}) {
 8514:                             if ($newsettings{$role}{'on'}) {
 8515:                                 $r->print('<li>'.&mt('Privileges which are not available by default for this ad hoc role, but are enabled for this specific '.lc($crstype).':').
 8516:                                           '<ul><li>'.$newsettings{$role}{'on'}.'</li></ul></li>');
 8517:                             } else {
 8518:                                 $r->print('<li>'.&mt('None of the privileges unavailable by default for this ad hoc role are enabled.').'</li>');
 8519:                             }
 8520:                         }
 8521:                     }
 8522:                     $r->print('</ul></li>');
 8523:                 }
 8524:                 $r->print('</ul>');
 8525:             }
 8526:         } else {
 8527:             $r->print(&mt('No changes made to helpdesk access settings.'));
 8528:         }
 8529:     }
 8530:     return;
 8531: }
 8532: 
 8533: #-------------------------------------------------- functions for &phase_two
 8534: sub user_search_result {
 8535:     my ($context,$srch) = @_;
 8536:     my %allhomes;
 8537:     my %inst_matches;
 8538:     my %srch_results;
 8539:     my ($response,$currstate,$forcenewuser,$dirsrchres);
 8540:     $srch->{'srchterm'} =~ s/\s+/ /g;
 8541:     if ($srch->{'srchby'} !~ /^(uname|lastname|lastfirst)$/) {
 8542:         $response = &mt('Invalid search.');
 8543:     }
 8544:     if ($srch->{'srchin'} !~ /^(crs|dom|alc|instd)$/) {
 8545:         $response = &mt('Invalid search.');
 8546:     }
 8547:     if ($srch->{'srchtype'} !~ /^(exact|contains|begins)$/) {
 8548:         $response = &mt('Invalid search.');
 8549:     }
 8550:     if ($srch->{'srchterm'} eq '') {
 8551:         $response = &mt('You must enter a search term.');
 8552:     }
 8553:     if ($srch->{'srchterm'} =~ /^\s+$/) {
 8554:         $response = &mt('Your search term must contain more than just spaces.');
 8555:     }
 8556:     if (($srch->{'srchin'} eq 'dom') || ($srch->{'srchin'} eq 'instd')) {
 8557:         if (($srch->{'srchdomain'} eq '') || 
 8558: 	    ! (&Apache::lonnet::domain($srch->{'srchdomain'}))) {
 8559:             $response = &mt('You must specify a valid domain when searching in a domain or institutional directory.')
 8560:         }
 8561:     }
 8562:     if (($srch->{'srchin'} eq 'dom') || ($srch->{'srchin'} eq 'crs') ||
 8563:         ($srch->{'srchin'} eq 'alc')) {
 8564:         if ($srch->{'srchby'} eq 'uname') {
 8565:             my $unamecheck = $srch->{'srchterm'};
 8566:             if ($srch->{'srchtype'} eq 'contains') {
 8567:                 if ($unamecheck !~ /^\w/) {
 8568:                     $unamecheck = 'a'.$unamecheck; 
 8569:                 }
 8570:             }
 8571:             if ($unamecheck !~ /^$match_username$/) {
 8572:                 $response = &mt('You must specify a valid username. Only the following are allowed: letters numbers - . @');
 8573:             }
 8574:         }
 8575:     }
 8576:     if ($response ne '') {
 8577:         $response = '<span class="LC_warning">'.$response.'</span><br />';
 8578:     }
 8579:     if ($srch->{'srchin'} eq 'instd') {
 8580:         my $instd_chk = &instdirectorysrch_check($srch);
 8581:         if ($instd_chk ne 'ok') {
 8582:             my $domd_chk = &domdirectorysrch_check($srch);
 8583:             $response .= '<span class="LC_warning">'.$instd_chk.'</span><br />';
 8584:             if ($domd_chk eq 'ok') {
 8585:                 $response .= &mt('You may want to search in the LON-CAPA domain instead of in the institutional directory.');
 8586:             }
 8587:             $response .= '<br />';
 8588:         }
 8589:     } else {
 8590:         unless (($context eq 'requestcrs') && ($srch->{'srchtype'} eq 'exact')) {
 8591:             my $domd_chk = &domdirectorysrch_check($srch);
 8592:             if (($domd_chk ne 'ok') && ($env{'form.action'} ne 'accesslogs')) {
 8593:                 my $instd_chk = &instdirectorysrch_check($srch);
 8594:                 $response .= '<span class="LC_warning">'.$domd_chk.'</span><br />';
 8595:                 if ($instd_chk eq 'ok') {
 8596:                     $response .= &mt('You may want to search in the institutional directory instead of in the LON-CAPA domain.');
 8597:                 }
 8598:                 $response .= '<br />';
 8599:             }
 8600:         }
 8601:     }
 8602:     if ($response ne '') {
 8603:         return ($currstate,$response);
 8604:     }
 8605:     if ($srch->{'srchby'} eq 'uname') {
 8606:         if (($srch->{'srchin'} eq 'dom') || ($srch->{'srchin'} eq 'crs')) {
 8607:             if ($env{'form.forcenew'}) {
 8608:                 if ($srch->{'srchdomain'} ne $env{'request.role.domain'}) {
 8609:                     my $uhome=&Apache::lonnet::homeserver($srch->{'srchterm'},$srch->{'srchdomain'});
 8610:                     if ($uhome eq 'no_host') {
 8611:                         my $domdesc = &Apache::lonnet::domain($env{'request.role.domain'},'description');
 8612:                         my $showdom = &display_domain_info($env{'request.role.domain'});
 8613:                         $response = &mt('New users can only be created in the domain to which your current role belongs - [_1].',$showdom);
 8614:                     } else {
 8615:                         $currstate = 'modify';
 8616:                     }
 8617:                 } else {
 8618:                     $currstate = 'modify';
 8619:                 }
 8620:             } else {
 8621:                 if ($srch->{'srchin'} eq 'dom') {
 8622:                     if ($srch->{'srchtype'} eq 'exact') {
 8623:                         my $uhome=&Apache::lonnet::homeserver($srch->{'srchterm'},$srch->{'srchdomain'});
 8624:                         if ($uhome eq 'no_host') {
 8625:                             ($currstate,$response,$forcenewuser) =
 8626:                                 &build_search_response($context,$srch,%srch_results);
 8627:                         } else {
 8628:                             $currstate = 'modify';
 8629:                             if ($env{'form.action'} eq 'accesslogs') {
 8630:                                 $currstate = 'activity';
 8631:                             }
 8632:                             my $uname = $srch->{'srchterm'};
 8633:                             my $udom = $srch->{'srchdomain'};
 8634:                             $srch_results{$uname.':'.$udom} =
 8635:                                 { &Apache::lonnet::get('environment',
 8636:                                                        ['firstname',
 8637:                                                         'lastname',
 8638:                                                         'permanentemail'],
 8639:                                                          $udom,$uname)
 8640:                                 };
 8641:                         }
 8642:                     } else {
 8643:                         %srch_results = &Apache::lonnet::usersearch($srch);
 8644:                         ($currstate,$response,$forcenewuser) =
 8645:                             &build_search_response($context,$srch,%srch_results);
 8646:                     }
 8647:                 } else {
 8648:                     my $courseusers = &get_courseusers();
 8649:                     if ($srch->{'srchtype'} eq 'exact') {
 8650:                         if (exists($courseusers->{$srch->{'srchterm'}.':'.$srch->{'srchdomain'}})) {
 8651:                             $currstate = 'modify';
 8652:                         } else {
 8653:                             ($currstate,$response,$forcenewuser) =
 8654:                                 &build_search_response($context,$srch,%srch_results);
 8655:                         }
 8656:                     } else {
 8657:                         foreach my $user (keys(%$courseusers)) {
 8658:                             my ($cuname,$cudomain) = split(/:/,$user);
 8659:                             if ($cudomain eq $srch->{'srchdomain'}) {
 8660:                                 my $matched = 0;
 8661:                                 if ($srch->{'srchtype'} eq 'begins') {
 8662:                                     if ($cuname =~ /^\Q$srch->{'srchterm'}\E/i) {
 8663:                                         $matched = 1;
 8664:                                     }
 8665:                                 } else {
 8666:                                     if ($cuname =~ /\Q$srch->{'srchterm'}\E/i) {
 8667:                                         $matched = 1;
 8668:                                     }
 8669:                                 }
 8670:                                 if ($matched) {
 8671:                                     $srch_results{$user} = 
 8672: 					{&Apache::lonnet::get('environment',
 8673: 							     ['firstname',
 8674: 							      'lastname',
 8675: 							      'permanentemail'],
 8676: 							      $cudomain,$cuname)};
 8677:                                 }
 8678:                             }
 8679:                         }
 8680:                         ($currstate,$response,$forcenewuser) =
 8681:                             &build_search_response($context,$srch,%srch_results);
 8682:                     }
 8683:                 }
 8684:             }
 8685:         } elsif ($srch->{'srchin'} eq 'alc') {
 8686:             $currstate = 'query';
 8687:         } elsif ($srch->{'srchin'} eq 'instd') {
 8688:             ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query($srch);
 8689:             if ($dirsrchres eq 'ok') {
 8690:                 ($currstate,$response,$forcenewuser) = 
 8691:                     &build_search_response($context,$srch,%srch_results);
 8692:             } else {
 8693:                 my $showdom = &display_domain_info($srch->{'srchdomain'});
 8694:                 $response = '<span class="LC_warning">'.
 8695:                     &mt('Institutional directory search is not available in domain: [_1]',$showdom).
 8696:                     '</span><br />'.
 8697:                     &mt('You may want to search in the LON-CAPA domain instead of in the institutional directory.').
 8698:                     '<br />'; 
 8699:             }
 8700:         }
 8701:     } else {
 8702:         if ($srch->{'srchin'} eq 'dom') {
 8703:             %srch_results = &Apache::lonnet::usersearch($srch);
 8704:             ($currstate,$response,$forcenewuser) = 
 8705:                 &build_search_response($context,$srch,%srch_results); 
 8706:         } elsif ($srch->{'srchin'} eq 'crs') {
 8707:             my $courseusers = &get_courseusers(); 
 8708:             foreach my $user (keys(%$courseusers)) {
 8709:                 my ($uname,$udom) = split(/:/,$user);
 8710:                 my %names = &Apache::loncommon::getnames($uname,$udom);
 8711:                 my %emails = &Apache::loncommon::getemails($uname,$udom);
 8712:                 if ($srch->{'srchby'} eq 'lastname') {
 8713:                     if ((($srch->{'srchtype'} eq 'exact') && 
 8714:                          ($names{'lastname'} eq $srch->{'srchterm'})) || 
 8715:                         (($srch->{'srchtype'} eq 'begins') &&
 8716:                          ($names{'lastname'} =~ /^\Q$srch->{'srchterm'}\E/i)) ||
 8717:                         (($srch->{'srchtype'} eq 'contains') &&
 8718:                          ($names{'lastname'} =~ /\Q$srch->{'srchterm'}\E/i))) {
 8719:                         $srch_results{$user} = {firstname => $names{'firstname'},
 8720:                                             lastname => $names{'lastname'},
 8721:                                             permanentemail => $emails{'permanentemail'},
 8722:                                            };
 8723:                     }
 8724:                 } elsif ($srch->{'srchby'} eq 'lastfirst') {
 8725:                     my ($srchlast,$srchfirst) = split(/,/,$srch->{'srchterm'});
 8726:                     $srchlast =~ s/\s+$//;
 8727:                     $srchfirst =~ s/^\s+//;
 8728:                     if ($srch->{'srchtype'} eq 'exact') {
 8729:                         if (($names{'lastname'} eq $srchlast) &&
 8730:                             ($names{'firstname'} eq $srchfirst)) {
 8731:                             $srch_results{$user} = {firstname => $names{'firstname'},
 8732:                                                 lastname => $names{'lastname'},
 8733:                                                 permanentemail => $emails{'permanentemail'},
 8734: 
 8735:                                            };
 8736:                         }
 8737:                     } elsif ($srch->{'srchtype'} eq 'begins') {
 8738:                         if (($names{'lastname'} =~ /^\Q$srchlast\E/i) &&
 8739:                             ($names{'firstname'} =~ /^\Q$srchfirst\E/i)) {
 8740:                             $srch_results{$user} = {firstname => $names{'firstname'},
 8741:                                                 lastname => $names{'lastname'},
 8742:                                                 permanentemail => $emails{'permanentemail'},
 8743:                                                };
 8744:                         }
 8745:                     } else {
 8746:                         if (($names{'lastname'} =~ /\Q$srchlast\E/i) && 
 8747:                             ($names{'firstname'} =~ /\Q$srchfirst\E/i)) {
 8748:                             $srch_results{$user} = {firstname => $names{'firstname'},
 8749:                                                 lastname => $names{'lastname'},
 8750:                                                 permanentemail => $emails{'permanentemail'},
 8751:                                                };
 8752:                         }
 8753:                     }
 8754:                 }
 8755:             }
 8756:             ($currstate,$response,$forcenewuser) = 
 8757:                 &build_search_response($context,$srch,%srch_results); 
 8758:         } elsif ($srch->{'srchin'} eq 'alc') {
 8759:             $currstate = 'query';
 8760:         } elsif ($srch->{'srchin'} eq 'instd') {
 8761:             ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query($srch); 
 8762:             if ($dirsrchres eq 'ok') {
 8763:                 ($currstate,$response,$forcenewuser) = 
 8764:                     &build_search_response($context,$srch,%srch_results);
 8765:             } else {
 8766:                 my $showdom = &display_domain_info($srch->{'srchdomain'});
 8767:                 $response = '<span class="LC_warning">'.
 8768:                     &mt('Institutional directory search is not available in domain: [_1]',$showdom).
 8769:                     '</span><br />'.
 8770:                     &mt('You may want to search in the LON-CAPA domain instead of in the institutional directory.').
 8771:                     '<br />';
 8772:             }
 8773:         }
 8774:     }
 8775:     return ($currstate,$response,$forcenewuser,\%srch_results);
 8776: }
 8777: 
 8778: sub domdirectorysrch_check {
 8779:     my ($srch) = @_;
 8780:     my $response;
 8781:     my %dom_inst_srch = &Apache::lonnet::get_dom('configuration',
 8782:                                              ['directorysrch'],$srch->{'srchdomain'});
 8783:     my $showdom = &display_domain_info($srch->{'srchdomain'});
 8784:     if (ref($dom_inst_srch{'directorysrch'}) eq 'HASH') {
 8785:         if ($dom_inst_srch{'directorysrch'}{'lcavailable'} eq '0') {
 8786:             return &mt('LON-CAPA directory search is not available in domain: [_1]',$showdom);
 8787:         }
 8788:         if ($dom_inst_srch{'directorysrch'}{'lclocalonly'}) {
 8789:             if ($env{'request.role.domain'} ne $srch->{'srchdomain'}) {
 8790:                 return &mt('LON-CAPA directory search in domain: [_1] is only allowed for users with a current role in the domain.',$showdom);
 8791:             }
 8792:         }
 8793:     }
 8794:     return 'ok';
 8795: }
 8796: 
 8797: sub instdirectorysrch_check {
 8798:     my ($srch) = @_;
 8799:     my $can_search = 0;
 8800:     my $response;
 8801:     my %dom_inst_srch = &Apache::lonnet::get_dom('configuration',
 8802:                                              ['directorysrch'],$srch->{'srchdomain'});
 8803:     my $showdom = &display_domain_info($srch->{'srchdomain'});
 8804:     if (ref($dom_inst_srch{'directorysrch'}) eq 'HASH') {
 8805:         if (!$dom_inst_srch{'directorysrch'}{'available'}) {
 8806:             return &mt('Institutional directory search is not available in domain: [_1]',$showdom); 
 8807:         }
 8808:         if ($dom_inst_srch{'directorysrch'}{'localonly'}) {
 8809:             if ($env{'request.role.domain'} ne $srch->{'srchdomain'}) {
 8810:                 return &mt('Institutional directory search in domain: [_1] is only allowed for users with a current role in the domain.',$showdom); 
 8811:             }
 8812:             my @usertypes = split(/:/,$env{'environment.inststatus'});
 8813:             if (!@usertypes) {
 8814:                 push(@usertypes,'default');
 8815:             }
 8816:             if (ref($dom_inst_srch{'directorysrch'}{'cansearch'}) eq 'ARRAY') {
 8817:                 foreach my $type (@usertypes) {
 8818:                     if (grep(/^\Q$type\E$/,@{$dom_inst_srch{'directorysrch'}{'cansearch'}})) {
 8819:                         $can_search = 1;
 8820:                         last;
 8821:                     }
 8822:                 }
 8823:             }
 8824:             if (!$can_search) {
 8825:                 my ($insttypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($srch->{'srchdomain'});
 8826:                 my @longtypes; 
 8827:                 foreach my $item (@usertypes) {
 8828:                     if (defined($insttypes->{$item})) { 
 8829:                         push (@longtypes,$insttypes->{$item});
 8830:                     } elsif ($item eq 'default') {
 8831:                         push (@longtypes,&mt('other')); 
 8832:                     }
 8833:                 }
 8834:                 my $insttype_str = join(', ',@longtypes); 
 8835:                 return &mt('Institutional directory search in domain: [_1] is not available to your user type: ',$showdom).$insttype_str;
 8836:             }
 8837:         } else {
 8838:             $can_search = 1;
 8839:         }
 8840:     } else {
 8841:         return &mt('Institutional directory search has not been configured for domain: [_1]',$showdom);
 8842:     }
 8843:     my %longtext = &Apache::lonlocal::texthash (
 8844:                        uname     => 'username',
 8845:                        lastfirst => 'last name, first name',
 8846:                        lastname  => 'last name',
 8847:                        contains  => 'contains',
 8848:                        exact     => 'as exact match to',
 8849:                        begins    => 'begins with',
 8850:                    );
 8851:     if ($can_search) {
 8852:         if (ref($dom_inst_srch{'directorysrch'}{'searchby'}) eq 'ARRAY') {
 8853:             if (!grep(/^\Q$srch->{'srchby'}\E$/,@{$dom_inst_srch{'directorysrch'}{'searchby'}})) {
 8854:                 return &mt('Institutional directory search in domain: [_1] is not available for searching by "[_2]"',$showdom,$longtext{$srch->{'srchby'}});
 8855:             }
 8856:         } else {
 8857:             return &mt('Institutional directory search in domain: [_1] is not available.', $showdom);
 8858:         }
 8859:     }
 8860:     if ($can_search) {
 8861:         if (ref($dom_inst_srch{'directorysrch'}{'searchtypes'}) eq 'ARRAY') {
 8862:             if (grep(/^\Q$srch->{'srchtype'}\E/,@{$dom_inst_srch{'directorysrch'}{'searchtypes'}})) {
 8863:                 return 'ok';
 8864:             } else {
 8865:                 return &mt('Institutional directory search in domain [_1] is not available for the requested search type: "[_2]"',$showdom,$longtext{$srch->{'srchtype'}});
 8866:             }
 8867:         } else {
 8868:             if ((($dom_inst_srch{'directorysrch'}{'searchtypes'} eq 'specify') &&
 8869:                  ($srch->{'srchtype'} eq 'exact' || $srch->{'srchtype'} eq 'contains')) ||
 8870:                 ($dom_inst_srch{'directorysrch'}{'searchtypes'} eq $srch->{'srchtype'})) {
 8871:                 return 'ok';
 8872:             } else {
 8873:                 return &mt('Institutional directory search in domain [_1] is not available for the requested search type: "[_2]"',$showdom,$longtext{$srch->{'srchtype'}});
 8874:             }
 8875:         }
 8876:     }
 8877: }
 8878: 
 8879: sub get_courseusers {
 8880:     my %advhash;
 8881:     my $classlist = &Apache::loncoursedata::get_classlist();
 8882:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles();
 8883:     foreach my $role (sort(keys(%coursepersonnel))) {
 8884:         foreach my $user (split(/\,/,$coursepersonnel{$role})) {
 8885: 	    if (!exists($classlist->{$user})) {
 8886: 		$classlist->{$user} = [];
 8887: 	    }
 8888:         }
 8889:     }
 8890:     return $classlist;
 8891: }
 8892: 
 8893: sub build_search_response {
 8894:     my ($context,$srch,%srch_results) = @_;
 8895:     my ($currstate,$response,$forcenewuser);
 8896:     my %names = (
 8897:           'uname'     => 'username',
 8898:           'lastname'  => 'last name',
 8899:           'lastfirst' => 'last name, first name',
 8900:           'crs'       => 'this course',
 8901:           'dom'       => 'LON-CAPA domain',
 8902:           'instd'     => 'the institutional directory for domain',
 8903:     );
 8904: 
 8905:     my %single = (
 8906:                    begins   => 'A match',
 8907:                    contains => 'A match',
 8908:                    exact    => 'An exact match',
 8909:                  );
 8910:     my %nomatch = (
 8911:                    begins   => 'No match',
 8912:                    contains => 'No match',
 8913:                    exact    => 'No exact match',
 8914:                   );
 8915:     if (keys(%srch_results) > 1) {
 8916:         $currstate = 'select';
 8917:     } else {
 8918:         if (keys(%srch_results) == 1) {
 8919:             if ($env{'form.action'} eq 'accesslogs') {
 8920:                 $currstate = 'activity';
 8921:             } else {
 8922:                 $currstate = 'modify';
 8923:             }
 8924:             $response = &mt("$single{$srch->{'srchtype'}} was found for the $names{$srch->{'srchby'}} ([_1]) in $names{$srch->{'srchin'}}.",$srch->{'srchterm'});
 8925:             if ($srch->{'srchin'} eq 'dom' || $srch->{'srchin'} eq 'instd') {
 8926:                 $response .= ': '.&display_domain_info($srch->{'srchdomain'});
 8927:             }
 8928:         } else { # Search has nothing found. Prepare message to user.
 8929:             $response = '<span class="LC_warning">';
 8930:             if ($srch->{'srchin'} eq 'dom' || $srch->{'srchin'} eq 'instd') {
 8931:                 $response .= &mt("$nomatch{$srch->{'srchtype'}} found for the $names{$srch->{'srchby'}} [_1] in $names{$srch->{'srchin'}}: [_2]",
 8932:                                  '<b>'.$srch->{'srchterm'}.'</b>',
 8933:                                  &display_domain_info($srch->{'srchdomain'}));
 8934:             } else {
 8935:                 $response .= &mt("$nomatch{$srch->{'srchtype'}} found for the $names{$srch->{'srchby'}} [_1] in $names{$srch->{'srchin'}}.",
 8936:                                  '<b>'.$srch->{'srchterm'}.'</b>');
 8937:             }
 8938:             $response .= '</span>';
 8939: 
 8940:             if ($srch->{'srchin'} ne 'alc') {
 8941:                 $forcenewuser = 1;
 8942:                 my $cansrchinst = 0; 
 8943:                 if (($srch->{'srchdomain'}) && ($env{'form.action'} ne 'accesslogs')) {
 8944:                     my %domconfig = &Apache::lonnet::get_dom('configuration',['directorysrch'],$srch->{'srchdomain'});
 8945:                     if (ref($domconfig{'directorysrch'}) eq 'HASH') {
 8946:                         if ($domconfig{'directorysrch'}{'available'}) {
 8947:                             $cansrchinst = 1;
 8948:                         } 
 8949:                     }
 8950:                 }
 8951:                 if ((($srch->{'srchby'} eq 'lastfirst') || 
 8952:                      ($srch->{'srchby'} eq 'lastname')) &&
 8953:                     ($srch->{'srchin'} eq 'dom')) {
 8954:                     if ($cansrchinst) {
 8955:                         $response .= '<br />'.&mt('You may want to broaden your search to a search of the institutional directory for the domain.');
 8956:                     }
 8957:                 }
 8958:                 if ($srch->{'srchin'} eq 'crs') {
 8959:                     $response .= '<br />'.&mt('You may want to broaden your search to the selected LON-CAPA domain.');
 8960:                 }
 8961:             }
 8962:             my $createdom = $env{'request.role.domain'};
 8963:             if ($context eq 'requestcrs') {
 8964:                 if ($env{'form.coursedom'} ne '') {
 8965:                     $createdom = $env{'form.coursedom'};
 8966:                 }
 8967:             }
 8968:             unless (($env{'form.action'} eq 'accesslogs') || (($srch->{'srchby'} eq 'uname') && ($srch->{'srchin'} eq 'dom') &&
 8969:                     ($srch->{'srchtype'} eq 'exact') && ($srch->{'srchdomain'} eq $createdom))) {
 8970:                 my $cancreate =
 8971:                     &Apache::lonuserutils::can_create_user($createdom,$context);
 8972:                 my $targetdom = '<span class="LC_cusr_emph">'.$createdom.'</span>';
 8973:                 if ($cancreate) {
 8974:                     my $showdom = &display_domain_info($createdom); 
 8975:                     $response .= '<br /><br />'
 8976:                                 .'<b>'.&mt('To add a new user:').'</b>'
 8977:                                 .'<br />';
 8978:                     if ($context eq 'requestcrs') {
 8979:                         $response .= &mt("(You can only define new users in the new course's domain - [_1])",$targetdom);
 8980:                     } else {
 8981:                         $response .= &mt("(You can only create new users in your current role's domain - [_1])",$targetdom);
 8982:                     }
 8983:                     $response .='<ul><li>'
 8984:                                 .&mt("Set 'Domain/institution to search' to: [_1]",'<span class="LC_cusr_emph">'.$showdom.'</span>')
 8985:                                 .'</li><li>'
 8986:                                 .&mt("Set 'Search criteria' to: [_1]username is ..... in selected LON-CAPA domain[_2]",'<span class="LC_cusr_emph">','</span>')
 8987:                                 .'</li><li>'
 8988:                                 .&mt('Provide the proposed username')
 8989:                                 .'</li><li>'
 8990:                                 .&mt("Click 'Search'")
 8991:                                 .'</li></ul><br />';
 8992:                 } else {
 8993:                     unless (($context eq 'domain') && ($env{'form.action'} eq 'singleuser')) {
 8994:                         my $helplink = ' href="javascript:helpMenu('."'display'".')"';
 8995:                         $response .= '<br /><br />';
 8996:                         if ($context eq 'requestcrs') {
 8997:                             $response .= &mt("You are not authorized to define new users in the new course's domain - [_1].",$targetdom);
 8998:                         } else {
 8999:                             $response .= &mt("You are not authorized to create new users in your current role's domain - [_1].",$targetdom);
 9000:                         }
 9001:                         $response .= '<br />'
 9002:                                      .&mt('Please contact the [_1]helpdesk[_2] if you need to create a new user.'
 9003:                                         ,' <a'.$helplink.'>'
 9004:                                         ,'</a>')
 9005:                                      .'<br />';
 9006:                     }
 9007:                 }
 9008:             }
 9009:         }
 9010:     }
 9011:     return ($currstate,$response,$forcenewuser);
 9012: }
 9013: 
 9014: sub display_domain_info {
 9015:     my ($dom) = @_;
 9016:     my $output = $dom;
 9017:     if ($dom ne '') { 
 9018:         my $domdesc = &Apache::lonnet::domain($dom,'description');
 9019:         if ($domdesc ne '') {
 9020:             $output .= ' <span class="LC_cusr_emph">('.$domdesc.')</span>';
 9021:         }
 9022:     }
 9023:     return $output;
 9024: }
 9025: 
 9026: sub crumb_utilities {
 9027:     my %elements = (
 9028:        crtuser => {
 9029:            srchterm => 'text',
 9030:            srchin => 'selectbox',
 9031:            srchby => 'selectbox',
 9032:            srchtype => 'selectbox',
 9033:            srchdomain => 'selectbox',
 9034:        },
 9035:        crtusername => {
 9036:            srchterm => 'text',
 9037:            srchdomain => 'selectbox',
 9038:        },
 9039:        docustom => {
 9040:            rolename => 'selectbox',
 9041:            newrolename => 'textbox',
 9042:        },
 9043:        studentform => {
 9044:            srchterm => 'text',
 9045:            srchin => 'selectbox',
 9046:            srchby => 'selectbox',
 9047:            srchtype => 'selectbox',
 9048:            srchdomain => 'selectbox',
 9049:        },
 9050:     );
 9051: 
 9052:     my $jsback .= qq|
 9053: function backPage(formname,prevphase,prevstate) {
 9054:     if (typeof prevphase == 'undefined') {
 9055:         formname.phase.value = '';
 9056:     }
 9057:     else {  
 9058:         formname.phase.value = prevphase;
 9059:     }
 9060:     if (typeof prevstate == 'undefined') {
 9061:         formname.currstate.value = '';
 9062:     }
 9063:     else {
 9064:         formname.currstate.value = prevstate;
 9065:     }
 9066:     formname.submit();
 9067: }
 9068: |;
 9069:     return ($jsback,\%elements);
 9070: }
 9071: 
 9072: sub course_level_table {
 9073:     my ($inccourses,$showcredits,$defaultcredits) = @_;
 9074:     return unless (ref($inccourses) eq 'HASH');
 9075:     my $table = '';
 9076: # Custom Roles?
 9077: 
 9078:     my %customroles=&Apache::lonuserutils::my_custom_roles();
 9079:     my %lt=&Apache::lonlocal::texthash(
 9080:             'exs'  => "Existing sections",
 9081:             'new'  => "Define new section",
 9082:             'ssd'  => "Set Start Date",
 9083:             'sed'  => "Set End Date",
 9084:             'crl'  => "Course Level",
 9085:             'act'  => "Activate",
 9086:             'rol'  => "Role",
 9087:             'ext'  => "Extent",
 9088:             'grs'  => "Section",
 9089:             'crd'  => "Credits",
 9090:             'sta'  => "Start",
 9091:             'end'  => "End"
 9092:     );
 9093: 
 9094:     foreach my $protectedcourse (sort(keys(%{$inccourses}))) {
 9095: 	my $thiscourse=$protectedcourse;
 9096: 	$thiscourse=~s:_:/:g;
 9097: 	my %coursedata=&Apache::lonnet::coursedescription($thiscourse);
 9098:         my $isowner = &Apache::lonuserutils::is_courseowner($protectedcourse,$coursedata{'internal.courseowner'});
 9099: 	my $area=$coursedata{'description'};
 9100:         my $crstype=$coursedata{'type'};
 9101: 	if (!defined($area)) { $area=&mt('Unavailable course').': '.$protectedcourse; }
 9102: 	my ($domain,$cnum)=split(/\//,$thiscourse);
 9103:         my %sections_count;
 9104:         if (defined($env{'request.course.id'})) {
 9105:             if ($env{'request.course.id'} eq $domain.'_'.$cnum) {
 9106:                 %sections_count = 
 9107: 		    &Apache::loncommon::get_sections($domain,$cnum);
 9108:             }
 9109:         }
 9110:         my @roles = &Apache::lonuserutils::roles_by_context('course','',$crstype);
 9111: 	foreach my $role (@roles) {
 9112:             my $plrole=&Apache::lonnet::plaintext($role,$crstype);
 9113: 	    if ((&Apache::lonnet::allowed('c'.$role,$thiscourse)) ||
 9114:                 ((($role eq 'cc') || ($role eq 'co')) && ($isowner))) {
 9115:                 $table .= &course_level_row($protectedcourse,$role,$area,$domain,
 9116:                                             $plrole,\%sections_count,\%lt,
 9117:                                             $showcredits,$defaultcredits,$crstype);
 9118:             } elsif ($env{'request.course.sec'} ne '') {
 9119:                 if (&Apache::lonnet::allowed('c'.$role,$thiscourse.'/'.
 9120:                                              $env{'request.course.sec'})) {
 9121:                     $table .= &course_level_row($protectedcourse,$role,$area,$domain,
 9122:                                                 $plrole,\%sections_count,\%lt,
 9123:                                                 $showcredits,$defaultcredits,$crstype);
 9124:                 }
 9125:             }
 9126:         }
 9127:         if (&Apache::lonnet::allowed('ccr',$thiscourse)) {
 9128:             foreach my $cust (sort(keys(%customroles))) {
 9129:                 next if ($crstype eq 'Community' && $customroles{$cust} =~ /bre\&S/);
 9130:                 my $role = 'cr_cr_'.$env{'user.domain'}.'_'.$env{'user.name'}.'_'.$cust;
 9131:                 $table .= &course_level_row($protectedcourse,$role,$area,$domain,
 9132:                                             $cust,\%sections_count,\%lt,
 9133:                                             $showcredits,$defaultcredits,$crstype);
 9134:             }
 9135: 	}
 9136:     }
 9137:     return '' if ($table eq ''); # return nothing if there is nothing 
 9138:                                  # in the table
 9139:     my $result;
 9140:     if (!$env{'request.course.id'}) {
 9141:         $result = '<h4>'.$lt{'crl'}.'</h4>'."\n";
 9142:     }
 9143:     $result .= 
 9144: &Apache::loncommon::start_data_table().
 9145: &Apache::loncommon::start_data_table_header_row().
 9146: '<th>'.$lt{'act'}.'</th><th>'.$lt{'rol'}.'</th>'."\n".
 9147: '<th>'.$lt{'ext'}.'</th><th>'."\n";
 9148:     if ($showcredits) {
 9149:         $result .= $lt{'crd'}.'</th>';
 9150:     }
 9151:     $result .=
 9152: '<th>'.$lt{'grs'}.'</th><th>'.$lt{'sta'}.'</th>'."\n".
 9153: '<th>'.$lt{'end'}.'</th>'.
 9154: &Apache::loncommon::end_data_table_header_row().
 9155: $table.
 9156: &Apache::loncommon::end_data_table();
 9157:     return $result;
 9158: }
 9159: 
 9160: sub course_level_row {
 9161:     my ($protectedcourse,$role,$area,$domain,$plrole,$sections_count,
 9162:         $lt,$showcredits,$defaultcredits,$crstype) = @_;
 9163:     my $creditem;
 9164:     my $row = &Apache::loncommon::start_data_table_row().
 9165:               ' <td><input type="checkbox" name="act_'.
 9166:               $protectedcourse.'_'.$role.'" /></td>'."\n".
 9167:               ' <td>'.$plrole.'</td>'."\n".
 9168:               ' <td>'.$area.'<br />Domain: '.$domain.'</td>'."\n";
 9169:     if (($showcredits) && ($role eq 'st') && ($crstype eq 'Course')) {
 9170:         $row .= 
 9171:             '<td><input type="text" name="credits_'.$protectedcourse.'_'.
 9172:             $role.'" size="3" value="'.$defaultcredits.'" /></td>';
 9173:     } else {
 9174:         $row .= '<td>&nbsp;</td>';
 9175:     }
 9176:     if (($role eq 'cc') || ($role eq 'co')) {
 9177:         $row .= '<td>&nbsp;</td>';
 9178:     } elsif ($env{'request.course.sec'} ne '') {
 9179:         $row .= ' <td><input type="hidden" value="'.
 9180:                 $env{'request.course.sec'}.'" '.
 9181:                 'name="sec_'.$protectedcourse.'_'.$role.'" />'.
 9182:                 $env{'request.course.sec'}.'</td>';
 9183:     } else {
 9184:         if (ref($sections_count) eq 'HASH') {
 9185:             my $currsec = 
 9186:                 &Apache::lonuserutils::course_sections($sections_count,
 9187:                                                        $protectedcourse.'_'.$role);
 9188:             $row .= '<td><table class="LC_createuser">'."\n".
 9189:                     '<tr class="LC_section_row">'."\n".
 9190:                     ' <td valign="top">'.$lt->{'exs'}.'<br />'.
 9191:                        $currsec.'</td>'."\n".
 9192:                      ' <td>&nbsp;&nbsp;</td>'."\n".
 9193:                      ' <td valign="top">&nbsp;'.$lt->{'new'}.'<br />'.
 9194:                      '<input type="text" name="newsec_'.$protectedcourse.'_'.$role.
 9195:                      '" value="" />'.
 9196:                      '<input type="hidden" '.
 9197:                      'name="sec_'.$protectedcourse.'_'.$role.'" /></td>'."\n".
 9198:                      '</tr></table></td>'."\n";
 9199:         } else {
 9200:             $row .= '<td><input type="text" size="10" '.
 9201:                     'name="sec_'.$protectedcourse.'_'.$role.'" /></td>'."\n";
 9202:         }
 9203:     }
 9204:     $row .= <<ENDTIMEENTRY;
 9205: <td><input type="hidden" name="start_$protectedcourse\_$role" value="" />
 9206: <a href=
 9207: "javascript:pjump('date_start','Start Date $plrole',document.cu.start_$protectedcourse\_$role.value,'start_$protectedcourse\_$role','cu.pres','dateset')">$lt->{'ssd'}</a></td>
 9208: <td><input type="hidden" name="end_$protectedcourse\_$role" value="" />
 9209: <a href=
 9210: "javascript:pjump('date_end','End Date $plrole',document.cu.end_$protectedcourse\_$role.value,'end_$protectedcourse\_$role','cu.pres','dateset')">$lt->{'sed'}</a></td>
 9211: ENDTIMEENTRY
 9212:     $row .= &Apache::loncommon::end_data_table_row();
 9213:     return $row;
 9214: }
 9215: 
 9216: sub course_level_dc {
 9217:     my ($dcdom,$showcredits) = @_;
 9218:     my %customroles=&Apache::lonuserutils::my_custom_roles();
 9219:     my @roles = &Apache::lonuserutils::roles_by_context('course');
 9220:     my $hiddenitems = '<input type="hidden" name="dcdomain" value="'.$dcdom.'" />'.
 9221:                       '<input type="hidden" name="origdom" value="'.$dcdom.'" />'.
 9222:                       '<input type="hidden" name="dccourse" value="" />';
 9223:     my $courseform=&Apache::loncommon::selectcourse_link
 9224:             ('cu','dccourse','dcdomain','coursedesc',undef,undef,'Select','crstype');
 9225:     my $credit_elem;
 9226:     if ($showcredits) {
 9227:         $credit_elem = 'credits';
 9228:     }
 9229:     my $cb_jscript = &Apache::loncommon::coursebrowser_javascript($dcdom,'currsec','cu','role','Course/Community Browser',$credit_elem);
 9230:     my %lt=&Apache::lonlocal::texthash(
 9231:                     'rol'  => "Role",
 9232:                     'grs'  => "Section",
 9233:                     'exs'  => "Existing sections",
 9234:                     'new'  => "Define new section", 
 9235:                     'sta'  => "Start",
 9236:                     'end'  => "End",
 9237:                     'ssd'  => "Set Start Date",
 9238:                     'sed'  => "Set End Date",
 9239:                     'scc'  => "Course/Community",
 9240:                     'crd'  => "Credits",
 9241:                   );
 9242:     my $header = '<h4>'.&mt('Course/Community Level').'</h4>'.
 9243:                  &Apache::loncommon::start_data_table().
 9244:                  &Apache::loncommon::start_data_table_header_row().
 9245:                  '<th>'.$lt{'scc'}.'</th><th>'.$lt{'rol'}.'</th>'."\n".
 9246:                  '<th>'.$lt{'grs'}.'</th>'."\n";
 9247:     $header .=   '<th>'.$lt{'crd'}.'</th>'."\n" if ($showcredits);
 9248:     $header .=   '<th>'.$lt{'sta'}.'</th><th>'.$lt{'end'}.'</th>'."\n".
 9249:                  &Apache::loncommon::end_data_table_header_row();
 9250:     my $otheritems = &Apache::loncommon::start_data_table_row()."\n".
 9251:                      '<td><br /><span class="LC_nobreak"><input type="text" name="coursedesc" value="" onfocus="this.blur();opencrsbrowser('."'cu','dccourse','dcdomain','coursedesc','','','','crstype'".')" />'.
 9252:                      $courseform.('&nbsp;' x4).'</span></td>'."\n".
 9253:                      '<td valign="top"><br /><select name="role">'."\n";
 9254:     foreach my $role (@roles) {
 9255:         my $plrole=&Apache::lonnet::plaintext($role);
 9256:         $otheritems .= '  <option value="'.$role.'">'.$plrole.'</option>';
 9257:     }
 9258:     if ( keys(%customroles) > 0) {
 9259:         foreach my $cust (sort(keys(%customroles))) {
 9260:             my $custrole='cr_cr_'.$env{'user.domain'}.
 9261:                     '_'.$env{'user.name'}.'_'.$cust;
 9262:             $otheritems .= '  <option value="'.$custrole.'">'.$cust.'</option>';
 9263:         }
 9264:     }
 9265:     $otheritems .= '</select></td><td>'.
 9266:                      '<table border="0" cellspacing="0" cellpadding="0">'.
 9267:                      '<tr><td valign="top"><b>'.$lt{'exs'}.'</b><br /><select name="currsec">'.
 9268:                      ' <option value="">&lt;--'.&mt('Pick course first').'</option></select></td>'.
 9269:                      '<td>&nbsp;&nbsp;</td>'.
 9270:                      '<td valign="top">&nbsp;<b>'.$lt{'new'}.'</b><br />'.
 9271:                      '<input type="text" name="newsec" value="" />'.
 9272:                      '<input type="hidden" name="section" value="" />'.
 9273:                      '<input type="hidden" name="groups" value="" />'.
 9274:                      '<input type="hidden" name="crstype" value="" /></td>'.
 9275:                      '</tr></table></td>'."\n";
 9276:     if ($showcredits) {
 9277:         $otheritems .= '<td><br />'."\n".
 9278:                        '<input type="text" size="3" name="credits" value="" /></td>'."\n";
 9279:     }
 9280:     $otheritems .= <<ENDTIMEENTRY;
 9281: <td><br /><input type="hidden" name="start" value='' />
 9282: <a href=
 9283: "javascript:pjump('date_start','Start Date',document.cu.start.value,'start','cu.pres','dateset')">$lt{'ssd'}</a></td>
 9284: <td><br /><input type="hidden" name="end" value='' />
 9285: <a href=
 9286: "javascript:pjump('date_end','End Date',document.cu.end.value,'end','cu.pres','dateset')">$lt{'sed'}</a></td>
 9287: ENDTIMEENTRY
 9288:     $otheritems .= &Apache::loncommon::end_data_table_row().
 9289:                    &Apache::loncommon::end_data_table()."\n";
 9290:     return $cb_jscript.$header.$hiddenitems.$otheritems;
 9291: }
 9292: 
 9293: sub update_selfenroll_config {
 9294:     my ($r,$cid,$cdom,$cnum,$context,$crstype,$currsettings) = @_;
 9295:     return unless (ref($currsettings) eq 'HASH');
 9296:     my ($row,$lt) = &Apache::lonuserutils::get_selfenroll_titles();
 9297:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
 9298:     my (%changes,%warning);
 9299:     my $curr_types;
 9300:     my %noedit;
 9301:     unless ($context eq 'domain') {
 9302:         %noedit = &get_noedit_fields($cdom,$cnum,$crstype,$row);
 9303:     }
 9304:     if (ref($row) eq 'ARRAY') {
 9305:         foreach my $item (@{$row}) {
 9306:             next if ($noedit{$item});
 9307:             if ($item eq 'enroll_dates') {
 9308:                 my (%currenrolldate,%newenrolldate);
 9309:                 foreach my $type ('start','end') {
 9310:                     $currenrolldate{$type} = $currsettings->{'selfenroll_'.$type.'_date'};
 9311:                     $newenrolldate{$type} = &Apache::lonhtmlcommon::get_date_from_form('selfenroll_'.$type.'_date');
 9312:                     if ($newenrolldate{$type} ne $currenrolldate{$type}) {
 9313:                         $changes{'internal.selfenroll_'.$type.'_date'} = $newenrolldate{$type};
 9314:                     }
 9315:                 }
 9316:             } elsif ($item eq 'access_dates') {
 9317:                 my (%currdate,%newdate);
 9318:                 foreach my $type ('start','end') {
 9319:                     $currdate{$type} = $currsettings->{'selfenroll_'.$type.'_access'};
 9320:                     $newdate{$type} = &Apache::lonhtmlcommon::get_date_from_form('selfenroll_'.$type.'_access');
 9321:                     if ($newdate{$type} ne $currdate{$type}) {
 9322:                         $changes{'internal.selfenroll_'.$type.'_access'} = $newdate{$type};
 9323:                     }
 9324:                 }
 9325:             } elsif ($item eq 'types') {
 9326:                 $curr_types = $currsettings->{'selfenroll_'.$item};
 9327:                 if ($env{'form.selfenroll_all'}) {
 9328:                     if ($curr_types ne '*') {
 9329:                         $changes{'internal.selfenroll_types'} = '*';
 9330:                     } else {
 9331:                         next;
 9332:                     }
 9333:                 } else {
 9334:                     my %currdoms;
 9335:                     my @entries = split(/;/,$curr_types);
 9336:                     my @deletedoms = &Apache::loncommon::get_env_multiple('form.selfenroll_delete');
 9337:                     my @activations = &Apache::loncommon::get_env_multiple('form.selfenroll_activate');
 9338:                     my $newnum = 0;
 9339:                     my @latesttypes;
 9340:                     foreach my $num (@activations) {
 9341:                         my @types = &Apache::loncommon::get_env_multiple('form.selfenroll_types_'.$num);
 9342:                         if (@types > 0) {
 9343:                             @types = sort(@types);
 9344:                             my $typestr = join(',',@types);
 9345:                             my $typedom = $env{'form.selfenroll_dom_'.$num};
 9346:                             $latesttypes[$newnum] = $typedom.':'.$typestr;
 9347:                             $currdoms{$typedom} = 1;
 9348:                             $newnum ++;
 9349:                         }
 9350:                     }
 9351:                     for (my $j=0; $j<$env{'form.selfenroll_types_total'}; $j++) {
 9352:                         if ((!grep(/^$j$/,@deletedoms)) && (!grep(/^$j$/,@activations))) {
 9353:                             my @types = &Apache::loncommon::get_env_multiple('form.selfenroll_types_'.$j);
 9354:                             if (@types > 0) {
 9355:                                 @types = sort(@types);
 9356:                                 my $typestr = join(',',@types);
 9357:                                 my $typedom = $env{'form.selfenroll_dom_'.$j};
 9358:                                 $latesttypes[$newnum] = $typedom.':'.$typestr;
 9359:                                 $currdoms{$typedom} = 1;
 9360:                                 $newnum ++;
 9361:                             }
 9362:                         }
 9363:                     }
 9364:                     if ($env{'form.selfenroll_newdom'} ne '') {
 9365:                         my $typedom = $env{'form.selfenroll_newdom'};
 9366:                         if ((!defined($currdoms{$typedom})) && 
 9367:                             (&Apache::lonnet::domain($typedom) ne '')) {
 9368:                             my $typestr;
 9369:                             my ($othertitle,$usertypes,$types) = 
 9370:                                 &Apache::loncommon::sorted_inst_types($typedom);
 9371:                             my $othervalue = 'any';
 9372:                             if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 9373:                                 if (@{$types} > 0) {
 9374:                                     my @esc_types = map { &escape($_); } @{$types};
 9375:                                     $othervalue = 'other';
 9376:                                     $typestr = join(',',(@esc_types,$othervalue));
 9377:                                 }
 9378:                                 $typestr = $othervalue;
 9379:                             } else {
 9380:                                 $typestr = $othervalue;
 9381:                             } 
 9382:                             $latesttypes[$newnum] = $typedom.':'.$typestr;
 9383:                             $newnum ++ ;
 9384:                         }
 9385:                     }
 9386:                     my $selfenroll_types = join(';',@latesttypes);
 9387:                     if ($selfenroll_types ne $curr_types) {
 9388:                         $changes{'internal.selfenroll_types'} = $selfenroll_types;
 9389:                     }
 9390:                 }
 9391:             } elsif ($item eq 'limit') {
 9392:                 my $newlimit = $env{'form.selfenroll_limit'};
 9393:                 my $newcap = $env{'form.selfenroll_cap'};
 9394:                 $newcap =~s/\s+//g;
 9395:                 my $currlimit =  $currsettings->{'selfenroll_limit'};
 9396:                 $currlimit = 'none' if ($currlimit eq '');
 9397:                 my $currcap = $currsettings->{'selfenroll_cap'};
 9398:                 if ($newlimit ne $currlimit) {
 9399:                     if ($newlimit ne 'none') {
 9400:                         if ($newcap =~ /^\d+$/) {
 9401:                             if ($newcap ne $currcap) {
 9402:                                 $changes{'internal.selfenroll_cap'} = $newcap;
 9403:                             }
 9404:                             $changes{'internal.selfenroll_limit'} = $newlimit;
 9405:                         } else {
 9406:                             $warning{$item} = &mt('Maximum enrollment setting unchanged.').'<br />'.
 9407:                                 &mt('The value provided was invalid - it must be a positive integer if enrollment is being limited.'); 
 9408:                         }
 9409:                     } elsif ($currcap ne '') {
 9410:                         $changes{'internal.selfenroll_cap'} = '';
 9411:                         $changes{'internal.selfenroll_limit'} = $newlimit; 
 9412:                     }
 9413:                 } elsif ($currlimit ne 'none') {
 9414:                     if ($newcap =~ /^\d+$/) {
 9415:                         if ($newcap ne $currcap) {
 9416:                             $changes{'internal.selfenroll_cap'} = $newcap;
 9417:                         }
 9418:                     } else {
 9419:                         $warning{$item} = &mt('Maximum enrollment setting unchanged.').'<br />'.
 9420:                             &mt('The value provided was invalid - it must be a positive integer if enrollment is being limited.');
 9421:                     }
 9422:                 }
 9423:             } elsif ($item eq 'approval') {
 9424:                 my (@currnotified,@newnotified);
 9425:                 my $currapproval = $currsettings->{'selfenroll_approval'};
 9426:                 my $currnotifylist = $currsettings->{'selfenroll_notifylist'};
 9427:                 if ($currnotifylist ne '') {
 9428:                     @currnotified = split(/,/,$currnotifylist);
 9429:                     @currnotified = sort(@currnotified);
 9430:                 }
 9431:                 my $newapproval = $env{'form.selfenroll_approval'};
 9432:                 @newnotified = &Apache::loncommon::get_env_multiple('form.selfenroll_notify');
 9433:                 @newnotified = sort(@newnotified);
 9434:                 if ($newapproval ne $currapproval) {
 9435:                     $changes{'internal.selfenroll_approval'} = $newapproval;
 9436:                     if (!$newapproval) {
 9437:                         if ($currnotifylist ne '') {
 9438:                             $changes{'internal.selfenroll_notifylist'} = '';
 9439:                         }
 9440:                     } else {
 9441:                         my @differences =  
 9442:                             &Apache::loncommon::compare_arrays(\@currnotified,\@newnotified);
 9443:                         if (@differences > 0) {
 9444:                             if (@newnotified > 0) {
 9445:                                 $changes{'internal.selfenroll_notifylist'} = join(',',@newnotified);
 9446:                             } else {
 9447:                                 $changes{'internal.selfenroll_notifylist'} = join(',',@newnotified);
 9448:                             }
 9449:                         }
 9450:                     }
 9451:                 } else {
 9452:                     my @differences = &Apache::loncommon::compare_arrays(\@currnotified,\@newnotified);
 9453:                     if (@differences > 0) {
 9454:                         if (@newnotified > 0) {
 9455:                             $changes{'internal.selfenroll_notifylist'} = join(',',@newnotified);
 9456:                         } else {
 9457:                             $changes{'internal.selfenroll_notifylist'} = '';
 9458:                         }
 9459:                     }
 9460:                 }
 9461:             } else {
 9462:                 my $curr_val = $currsettings->{'selfenroll_'.$item};
 9463:                 my $newval = $env{'form.selfenroll_'.$item};
 9464:                 if ($item eq 'section') {
 9465:                     $newval = $env{'form.sections'};
 9466:                     if (defined($curr_groups{$newval})) {
 9467:                         $newval = $curr_val;
 9468:                         $warning{$item} = &mt('Section for self-enrolled users unchanged as the proposed section is a group').'<br />'.
 9469:                                           &mt('Group names and section names must be distinct');
 9470:                     } elsif ($newval eq 'all') {
 9471:                         $newval = $curr_val;
 9472:                         $warning{$item} = &mt('Section for self-enrolled users unchanged, as "all" is a reserved section name.');
 9473:                     }
 9474:                     if ($newval eq '') {
 9475:                         $newval = 'none';
 9476:                     }
 9477:                 }
 9478:                 if ($newval ne $curr_val) {
 9479:                     $changes{'internal.selfenroll_'.$item} = $newval;
 9480:                 }
 9481:             }
 9482:         }
 9483:         if (keys(%warning) > 0) {
 9484:             foreach my $item (@{$row}) {
 9485:                 if (exists($warning{$item})) {
 9486:                     $r->print($warning{$item}.'<br />');
 9487:                 }
 9488:             } 
 9489:         }
 9490:         if (keys(%changes) > 0) {
 9491:             my $putresult = &Apache::lonnet::put('environment',\%changes,$cdom,$cnum);
 9492:             if ($putresult eq 'ok') {
 9493:                 if ((exists($changes{'internal.selfenroll_types'})) ||
 9494:                     (exists($changes{'internal.selfenroll_start_date'}))  ||
 9495:                     (exists($changes{'internal.selfenroll_end_date'}))) {
 9496:                     my %crsinfo = &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',
 9497:                                                                 $cnum,undef,undef,'Course');
 9498:                     my $chome = &Apache::lonnet::homeserver($cnum,$cdom);
 9499:                     if (ref($crsinfo{$cid}) eq 'HASH') {
 9500:                         foreach my $item ('selfenroll_types','selfenroll_start_date','selfenroll_end_date') {
 9501:                             if (exists($changes{'internal.'.$item})) {
 9502:                                 $crsinfo{$cid}{$item} = $changes{'internal.'.$item};
 9503:                             }
 9504:                         }
 9505:                         my $crsputresult =
 9506:                             &Apache::lonnet::courseidput($cdom,\%crsinfo,
 9507:                                                          $chome,'notime');
 9508:                     }
 9509:                 }
 9510:                 $r->print(&mt('The following changes were made to self-enrollment settings:').'<ul>');
 9511:                 foreach my $item (@{$row}) {
 9512:                     my $title = $item;
 9513:                     if (ref($lt) eq 'HASH') {
 9514:                         $title = $lt->{$item};
 9515:                     }
 9516:                     if ($item eq 'enroll_dates') {
 9517:                         foreach my $type ('start','end') {
 9518:                             if (exists($changes{'internal.selfenroll_'.$type.'_date'})) {
 9519:                                 my $newdate = &Apache::lonlocal::locallocaltime($changes{'internal.selfenroll_'.$type.'_date'});
 9520:                                 $r->print('<li>'.&mt('[_1]: "[_2]" set to "[_3]".',
 9521:                                           $title,$type,$newdate).'</li>');
 9522:                             }
 9523:                         }
 9524:                     } elsif ($item eq 'access_dates') {
 9525:                         foreach my $type ('start','end') {
 9526:                             if (exists($changes{'internal.selfenroll_'.$type.'_access'})) {
 9527:                                 my $newdate = &Apache::lonlocal::locallocaltime($changes{'internal.selfenroll_'.$type.'_access'});
 9528:                                 $r->print('<li>'.&mt('[_1]: "[_2]" set to "[_3]".',
 9529:                                           $title,$type,$newdate).'</li>');
 9530:                             }
 9531:                         }
 9532:                     } elsif ($item eq 'limit') {
 9533:                         if ((exists($changes{'internal.selfenroll_limit'})) ||
 9534:                             (exists($changes{'internal.selfenroll_cap'}))) {
 9535:                             my ($newval,$newcap);
 9536:                             if ($changes{'internal.selfenroll_cap'} ne '') {
 9537:                                 $newcap = $changes{'internal.selfenroll_cap'}
 9538:                             } else {
 9539:                                 $newcap = $currsettings->{'selfenroll_cap'};
 9540:                             }
 9541:                             if ($changes{'internal.selfenroll_limit'} eq 'none') {
 9542:                                 $newval = &mt('No limit');
 9543:                             } elsif ($changes{'internal.selfenroll_limit'} eq 
 9544:                                      'allstudents') {
 9545:                                 $newval = &mt('New self-enrollment no longer allowed when total (all students) reaches [_1].',$newcap);
 9546:                             } elsif ($changes{'internal.selfenroll_limit'} eq 'selfenrolled') {
 9547:                                 $newval = &mt('New self-enrollment no longer allowed when total number of self-enrolled students reaches [_1].',$newcap);
 9548:                             } else {
 9549:                                 my $currlimit =  $currsettings->{'selfenroll_limit'};
 9550:                                 if ($currlimit eq 'allstudents') {
 9551:                                     $newval = &mt('New self-enrollment no longer allowed when total (all students) reaches [_1].',$newcap);
 9552:                                 } elsif ($changes{'internal.selfenroll_limit'} eq 'selfenrolled') {
 9553:                                     $newval =  &mt('New self-enrollment no longer allowed when total number of self-enrolled students reaches [_1].',$newcap);
 9554:                                 }
 9555:                             }
 9556:                             $r->print('<li>'.&mt('"[_1]" set to "[_2]".',$title,$newval).'</li>'."\n");
 9557:                         }
 9558:                     } elsif ($item eq 'approval') {
 9559:                         if ((exists($changes{'internal.selfenroll_approval'})) ||
 9560:                             (exists($changes{'internal.selfenroll_notifylist'}))) {
 9561:                             my %selfdescs = &Apache::lonuserutils::selfenroll_default_descs();
 9562:                             my ($newval,$newnotify);
 9563:                             if (exists($changes{'internal.selfenroll_notifylist'})) {
 9564:                                 $newnotify = $changes{'internal.selfenroll_notifylist'};
 9565:                             } else {   
 9566:                                 $newnotify = $currsettings->{'selfenroll_notifylist'};
 9567:                             }
 9568:                             if (exists($changes{'internal.selfenroll_approval'})) {
 9569:                                 if ($changes{'internal.selfenroll_approval'} !~ /^[012]$/) {
 9570:                                     $changes{'internal.selfenroll_approval'} = '0';
 9571:                                 }
 9572:                                 $newval = $selfdescs{'approval'}{$changes{'internal.selfenroll_approval'}};
 9573:                             } else {
 9574:                                 my $currapproval = $currsettings->{'selfenroll_approval'}; 
 9575:                                 if ($currapproval !~ /^[012]$/) {
 9576:                                     $currapproval = 0;
 9577:                                 }
 9578:                                 $newval = $selfdescs{'approval'}{$currapproval};
 9579:                             }
 9580:                             $r->print('<li>'.&mt('"[_1]" set to "[_2]".',$title,$newval));
 9581:                             if ($newnotify) {
 9582:                                 $r->print('<br />'.&mt('The following will be notified when an enrollment request needs approval, or has been approved: [_1].',$newnotify));
 9583:                             } else {
 9584:                                 $r->print('<br />'.&mt('No notifications sent when an enrollment request needs approval, or has been approved.'));
 9585:                             }
 9586:                             $r->print('</li>'."\n");
 9587:                         }
 9588:                     } else {
 9589:                         if (exists($changes{'internal.selfenroll_'.$item})) {
 9590:                             my $newval = $changes{'internal.selfenroll_'.$item};
 9591:                             if ($item eq 'types') {
 9592:                                 if ($newval eq '') {
 9593:                                     $newval = &mt('None');
 9594:                                 } elsif ($newval eq '*') {
 9595:                                     $newval = &mt('Any user in any domain');
 9596:                                 }
 9597:                             } elsif ($item eq 'registered') {
 9598:                                 if ($newval eq '1') {
 9599:                                     $newval = &mt('Yes');
 9600:                                 } elsif ($newval eq '0') {
 9601:                                     $newval = &mt('No');
 9602:                                 }
 9603:                             }
 9604:                             $r->print('<li>'.&mt('"[_1]" set to "[_2]".',$title,$newval).'</li>'."\n");
 9605:                         }
 9606:                     }
 9607:                 }
 9608:                 $r->print('</ul>');
 9609:                 if ($env{'course.'.$cid.'.description'} ne '') {
 9610:                     my %newenvhash;
 9611:                     foreach my $key (keys(%changes)) {
 9612:                         $newenvhash{'course.'.$cid.'.'.$key} = $changes{$key};
 9613:                     }
 9614:                     &Apache::lonnet::appenv(\%newenvhash);
 9615:                 }
 9616:             } else {
 9617:                 $r->print(&mt('An error occurred when saving changes to self-enrollment settings in this course.').'<br />'.
 9618:                           &mt('The error was: [_1].',$putresult));
 9619:             }
 9620:         } else {
 9621:             $r->print(&mt('No changes were made to the existing self-enrollment settings in this course.'));
 9622:         }
 9623:     } else {
 9624:         $r->print(&mt('No changes were made to the existing self-enrollment settings in this course.'));
 9625:     }
 9626:     my $visactions = &cat_visibility();
 9627:     my ($cathash,%cattype);
 9628:     my %domconfig = &Apache::lonnet::get_dom('configuration',['coursecategories'],$cdom);
 9629:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 9630:         $cathash = $domconfig{'coursecategories'}{'cats'};
 9631:         $cattype{'auth'} = $domconfig{'coursecategories'}{'auth'};
 9632:         $cattype{'unauth'} = $domconfig{'coursecategories'}{'unauth'};
 9633:     } else {
 9634:         $cathash = {};
 9635:         $cattype{'auth'} = 'std';
 9636:         $cattype{'unauth'} = 'std';
 9637:     }
 9638:     if (($cattype{'auth'} eq 'none') && ($cattype{'unauth'} eq 'none')) {
 9639:         $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
 9640:                   '<br />'.
 9641:                   '<br />'.$visactions->{'take'}.'<ul>'.
 9642:                   '<li>'.$visactions->{'dc_chgconf'}.'</li>'.
 9643:                   '</ul>');
 9644:     } elsif (($cattype{'auth'} !~ /^(std|domonly)$/) && ($cattype{'unauth'} !~ /^(std|domonly)$/)) {
 9645:         if ($currsettings->{'uniquecode'}) {
 9646:             $r->print('<span class="LC_info">'.$visactions->{'vis'}.'</span>');
 9647:         } else {
 9648:             $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
 9649:                   '<br />'.
 9650:                   '<br />'.$visactions->{'take'}.'<ul>'.
 9651:                   '<li>'.$visactions->{'dc_setcode'}.'</li>'.
 9652:                   '</ul><br />');
 9653:         }
 9654:     } else {
 9655:         my ($visible,$cansetvis,$vismsgs) = &visible_in_stdcat($cdom,$cnum,\%domconfig);
 9656:         if (ref($visactions) eq 'HASH') {
 9657:             if (!$visible) {
 9658:                 $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
 9659:                           '<br />');
 9660:                 if (ref($vismsgs) eq 'ARRAY') {
 9661:                     $r->print('<br />'.$visactions->{'take'}.'<ul>');
 9662:                     foreach my $item (@{$vismsgs}) {
 9663:                         $r->print('<li>'.$visactions->{$item}.'</li>');
 9664:                     }
 9665:                     $r->print('</ul>');
 9666:                 }
 9667:                 $r->print($cansetvis);
 9668:             }
 9669:         }
 9670:     } 
 9671:     return;
 9672: }
 9673: 
 9674: #---------------------------------------------- end functions for &phase_two
 9675: 
 9676: #--------------------------------- functions for &phase_two and &phase_three
 9677: 
 9678: #--------------------------end of functions for &phase_two and &phase_three
 9679: 
 9680: 1;
 9681: __END__
 9682: 
 9683: 

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