File:  [LON-CAPA] / loncom / interface / loncreateuser.pm
Revision 1.406.2.20: download - view: text, annotated - select for diffs
Mon Dec 13 20:53:06 2021 UTC (2 years, 5 months ago) by raeburn
Branches: version_2_11_X
CVS tags: version_2_11_4_uiuc, version_2_11_4_msu, version_2_11_4
- For 2.11
  Backport 1.455, 1.456, 1.457

    1: # The LearningOnline Network with CAPA
    2: # Create a user
    3: #
    4: # $Id: loncreateuser.pm,v 1.406.2.20 2021/12/13 20:53:06 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: ###
   29: 
   30: package Apache::loncreateuser;
   31: 
   32: =pod
   33: 
   34: =head1 NAME
   35: 
   36: Apache::loncreateuser.pm
   37: 
   38: =head1 SYNOPSIS
   39: 
   40:     Handler to create users and custom roles
   41: 
   42:     Provides an Apache handler for creating users,
   43:     editing their login parameters, roles, and removing roles, and
   44:     also creating and assigning custom roles.
   45: 
   46: =head1 OVERVIEW
   47: 
   48: =head2 Custom Roles
   49: 
   50: In LON-CAPA, roles are actually collections of privileges. "Teaching
   51: Assistant", "Course Coordinator", and other such roles are really just
   52: collection of privileges that are useful in many circumstances.
   53: 
   54: Custom roles can be defined by a Domain Coordinator, Course Coordinator
   55: or Community Coordinator via the Manage User functionality.
   56: The custom role editor screen will show all privileges which can be
   57: assigned to users. For a complete list of privileges, please see 
   58: C</home/httpd/lonTabs/rolesplain.tab>.
   59: 
   60: Custom role definitions are stored in the C<roles.db> file of the creator
   61: of the role.
   62: 
   63: =cut
   64: 
   65: use strict;
   66: use Apache::Constants qw(:common :http);
   67: use Apache::lonnet;
   68: use Apache::loncommon;
   69: use Apache::lonlocal;
   70: use Apache::longroup;
   71: use Apache::lonuserutils;
   72: use Apache::loncoursequeueadmin;
   73: use LONCAPA qw(:DEFAULT :match);
   74: use HTML::Entities;
   75: 
   76: my $loginscript; # piece of javascript used in two separate instances
   77: my $authformnop;
   78: my $authformkrb;
   79: my $authformint;
   80: my $authformfsys;
   81: my $authformloc;
   82: 
   83: sub initialize_authen_forms {
   84:     my ($dom,$formname,$curr_authtype,$mode) = @_;
   85:     my ($krbdef,$krbdefdom) = &Apache::loncommon::get_kerberos_defaults($dom);
   86:     my %param = ( formname => $formname,
   87:                   kerb_def_dom => $krbdefdom,
   88:                   kerb_def_auth => $krbdef,
   89:                   domain => $dom,
   90:                 );
   91:     my %abv_auth = &auth_abbrev();
   92:     if ($curr_authtype =~ /^(krb4|krb5|internal|localauth|unix):(.*)$/) {
   93:         my $long_auth = $1;
   94:         my $curr_autharg = $2;
   95:         my %abv_auth = &auth_abbrev();
   96:         $param{'curr_authtype'} = $abv_auth{$long_auth};
   97:         if ($long_auth =~ /^krb(4|5)$/) {
   98:             $param{'curr_kerb_ver'} = $1;
   99:             $param{'curr_autharg'} = $curr_autharg;
  100:         }
  101:         if ($mode eq 'modifyuser') {
  102:             $param{'mode'} = $mode;
  103:         }
  104:     }
  105:     $loginscript  = &Apache::loncommon::authform_header(%param);
  106:     $authformkrb  = &Apache::loncommon::authform_kerberos(%param);
  107:     $authformnop  = &Apache::loncommon::authform_nochange(%param);
  108:     $authformint  = &Apache::loncommon::authform_internal(%param);
  109:     $authformfsys = &Apache::loncommon::authform_filesystem(%param);
  110:     $authformloc  = &Apache::loncommon::authform_local(%param);
  111: }
  112: 
  113: sub auth_abbrev {
  114:     my %abv_auth = (
  115:                      krb5      => 'krb',
  116:                      krb4      => 'krb',
  117:                      internal  => 'int',
  118:                      localauth => 'loc',
  119:                      unix      => 'fsys',
  120:                    );
  121:     return %abv_auth;
  122: }
  123: 
  124: # ====================================================
  125: 
  126: sub user_quotas {
  127:     my ($ccuname,$ccdomain) = @_;
  128:     my %lt = &Apache::lonlocal::texthash(
  129:                    'usrt'      => "User Tools",
  130:                    'cust'      => "Custom quota",
  131:                    'chqu'      => "Change quota",
  132:     );
  133:    
  134:     my $quota_javascript = <<"END_SCRIPT";
  135: <script type="text/javascript">
  136: // <![CDATA[
  137: function quota_changes(caller,context) {
  138:     var customoff = document.getElementById('custom_'+context+'quota_off');
  139:     var customon = document.getElementById('custom_'+context+'quota_on');
  140:     var number = document.getElementById(context+'quota');
  141:     if (caller == "custom") {
  142:         if (customoff) {
  143:             if (customoff.checked) {
  144:                 number.value = "";
  145:             }
  146:         }
  147:     }
  148:     if (caller == "quota") {
  149:         if (customon) {
  150:             customon.checked = true;
  151:         }
  152:     }
  153:     return;
  154: }
  155: // ]]>
  156: </script>
  157: END_SCRIPT
  158:     my $longinsttype;
  159:     my ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($ccdomain);
  160:     my $output = $quota_javascript."\n".
  161:                  '<h3>'.$lt{'usrt'}.'</h3>'."\n".
  162:                  &Apache::loncommon::start_data_table();
  163: 
  164:     if ((&Apache::lonnet::allowed('mut',$ccdomain)) ||
  165:         (&Apache::lonnet::allowed('udp',$ccdomain))) {
  166:         $output .= &build_tools_display($ccuname,$ccdomain,'tools');
  167:     }
  168: 
  169:     my %titles = &Apache::lonlocal::texthash (
  170:                     portfolio => "Disk space allocated to user's portfolio files",
  171:                     author    => "Disk space allocated to user's Authoring Space (if role assigned)",
  172:                  );
  173:     foreach my $name ('portfolio','author') {
  174:         my ($currquota,$quotatype,$inststatus,$defquota) =
  175:             &Apache::loncommon::get_user_quota($ccuname,$ccdomain,$name);
  176:         if ($longinsttype eq '') { 
  177:             if ($inststatus ne '') {
  178:                 if ($usertypes->{$inststatus} ne '') {
  179:                     $longinsttype = $usertypes->{$inststatus};
  180:                 }
  181:             }
  182:         }
  183:         my ($showquota,$custom_on,$custom_off,$defaultinfo);
  184:         $custom_on = ' ';
  185:         $custom_off = ' checked="checked" ';
  186:         if ($quotatype eq 'custom') {
  187:             $custom_on = $custom_off;
  188:             $custom_off = ' ';
  189:             $showquota = $currquota;
  190:             if ($longinsttype eq '') {
  191:                 $defaultinfo = &mt('For this user, the default quota would be [_1]'
  192:                               .' MB.',$defquota);
  193:             } else {
  194:                 $defaultinfo = &mt("For this user, the default quota would be [_1]".
  195:                                    " MB, as determined by the user's institutional".
  196:                                    " affiliation ([_2]).",$defquota,$longinsttype);
  197:             }
  198:         } else {
  199:             if ($longinsttype eq '') {
  200:                 $defaultinfo = &mt('For this user, the default quota is [_1]'
  201:                               .' MB.',$defquota);
  202:             } else {
  203:                 $defaultinfo = &mt("For this user, the default quota of [_1]".
  204:                                    " MB, is determined by the user's institutional".
  205:                                    " affiliation ([_2]).",$defquota,$longinsttype);
  206:             }
  207:         }
  208: 
  209:         if (&Apache::lonnet::allowed('mpq',$ccdomain)) {
  210:             $output .= '<tr class="LC_info_row">'."\n".
  211:                        '    <td>'.$titles{$name}.'</td>'."\n".
  212:                        '  </tr>'."\n".
  213:                        &Apache::loncommon::start_data_table_row()."\n".
  214:                        '  <td><span class="LC_nobreak">'.
  215:                        &mt('Current quota: [_1] MB',$currquota).'</span>&nbsp;&nbsp;'.
  216:                        $defaultinfo.'</td>'."\n".
  217:                        &Apache::loncommon::end_data_table_row()."\n".
  218:                        &Apache::loncommon::start_data_table_row()."\n".
  219:                        '  <td><span class="LC_nobreak">'.$lt{'chqu'}.
  220:                        ': <label>'.
  221:                        '<input type="radio" name="custom_'.$name.'quota" id="custom_'.$name.'quota_off" '.
  222:                        'value="0" '.$custom_off.' onchange="javascript:quota_changes('."'custom','$name'".');"'.
  223:                        ' /><span class="LC_nobreak">'.
  224:                        &mt('Default ([_1] MB)',$defquota).'</span></label>&nbsp;'.
  225:                        '&nbsp;<label><input type="radio" name="custom_'.$name.'quota" id="custom_'.$name.'quota_on" '.
  226:                        'value="1" '.$custom_on.'  onchange="javascript:quota_changes('."'custom','$name'".');"'.
  227:                        ' />'.$lt{'cust'}.':</label>&nbsp;'.
  228:                        '<input type="text" name="'.$name.'quota" id="'.$name.'quota" size ="5" '.
  229:                        'value="'.$showquota.'" onfocus="javascript:quota_changes('."'quota','$name'".');"'.
  230:                        ' />&nbsp;'.&mt('MB').'</span></td>'."\n".
  231:                        &Apache::loncommon::end_data_table_row()."\n";
  232:         }
  233:     }
  234:     $output .= &Apache::loncommon::end_data_table();
  235:     return $output;
  236: }
  237: 
  238: sub build_tools_display {
  239:     my ($ccuname,$ccdomain,$context) = @_;
  240:     my (@usertools,%userenv,$output,@options,%validations,%reqtitles,%reqdisplay,
  241:         $colspan,$isadv,%domconfig);
  242:     my %lt = &Apache::lonlocal::texthash (
  243:                    'blog'       => "Personal User Blog",
  244:                    'aboutme'    => "Personal Information Page",
  245:                    'webdav'     => "WebDAV access to Authoring Spaces (if SSL and author/co-author)",
  246:                    'portfolio'  => "Personal User Portfolio",
  247:                    'avai'       => "Available",
  248:                    'cusa'       => "availability",
  249:                    'chse'       => "Change setting",
  250:                    'usde'       => "Use default",
  251:                    'uscu'       => "Use custom",
  252:                    'official'   => 'Can request creation of official courses',
  253:                    'unofficial' => 'Can request creation of unofficial courses',
  254:                    'community'  => 'Can request creation of communities',
  255:                    'textbook'   => 'Can request creation of textbook courses',
  256:                    'requestauthor'  => 'Can request author space',
  257:     );
  258:     if ($context eq 'requestcourses') {
  259:         %userenv = &Apache::lonnet::userenvironment($ccdomain,$ccuname,
  260:                       'requestcourses.official','requestcourses.unofficial',
  261:                       'requestcourses.community','requestcourses.textbook');
  262:         @usertools = ('official','unofficial','community','textbook');
  263:         @options =('norequest','approval','autolimit','validate');
  264:         %validations = &Apache::lonnet::auto_courserequest_checks($ccdomain);
  265:         %reqtitles = &courserequest_titles();
  266:         %reqdisplay = &courserequest_display();
  267:         $colspan = ' colspan="2"';
  268:         %domconfig =
  269:             &Apache::lonnet::get_dom('configuration',['requestcourses'],$ccdomain);
  270:         $isadv = &Apache::lonnet::is_advanced_user($ccdomain,$ccuname);
  271:     } elsif ($context eq 'requestauthor') {
  272:         %userenv = &Apache::lonnet::userenvironment($ccdomain,$ccuname,
  273:                                                     'requestauthor');
  274:         @usertools = ('requestauthor');
  275:         @options =('norequest','approval','automatic');
  276:         %reqtitles = &requestauthor_titles();
  277:         %reqdisplay = &requestauthor_display();
  278:         $colspan = ' colspan="2"';
  279:         %domconfig =
  280:             &Apache::lonnet::get_dom('configuration',['requestauthor'],$ccdomain);
  281:     } else {
  282:         %userenv = &Apache::lonnet::userenvironment($ccdomain,$ccuname,
  283:                           'tools.aboutme','tools.portfolio','tools.blog',
  284:                           'tools.webdav');
  285:         @usertools = ('aboutme','blog','webdav','portfolio');
  286:     }
  287:     foreach my $item (@usertools) {
  288:         my ($custom_access,$curr_access,$cust_on,$cust_off,$tool_on,$tool_off,
  289:             $currdisp,$custdisp,$custradio);
  290:         $cust_off = 'checked="checked" ';
  291:         $tool_on = 'checked="checked" ';
  292:         $curr_access =  
  293:             &Apache::lonnet::usertools_access($ccuname,$ccdomain,$item,undef,
  294:                                               $context);
  295:         if ($context eq 'requestauthor') {
  296:             if ($userenv{$context} ne '') {
  297:                 $cust_on = ' checked="checked" ';
  298:                 $cust_off = '';
  299:             }  
  300:         } elsif ($userenv{$context.'.'.$item} ne '') {
  301:             $cust_on = ' checked="checked" ';
  302:             $cust_off = '';
  303:         }
  304:         if ($context eq 'requestcourses') {
  305:             if ($userenv{$context.'.'.$item} eq '') {
  306:                 $custom_access = &mt('Currently from default setting.');
  307:             } else {
  308:                 $custom_access = &mt('Currently from custom setting.');
  309:             }
  310:         } elsif ($context eq 'requestauthor') {
  311:             if ($userenv{$context} eq '') {
  312:                 $custom_access = &mt('Currently from default setting.');
  313:             } else {
  314:                 $custom_access = &mt('Currently from custom setting.');
  315:             }
  316:         } else {
  317:             if ($userenv{$context.'.'.$item} eq '') {
  318:                 $custom_access =
  319:                     &mt('Availability determined currently from default setting.');
  320:                 if (!$curr_access) {
  321:                     $tool_off = 'checked="checked" ';
  322:                     $tool_on = '';
  323:                 }
  324:             } else {
  325:                 $custom_access =
  326:                     &mt('Availability determined currently from custom setting.');
  327:                 if ($userenv{$context.'.'.$item} == 0) {
  328:                     $tool_off = 'checked="checked" ';
  329:                     $tool_on = '';
  330:                 }
  331:             }
  332:         }
  333:         $output .= '  <tr class="LC_info_row">'."\n".
  334:                    '   <td'.$colspan.'>'.$lt{$item}.'</td>'."\n".
  335:                    '  </tr>'."\n".
  336:                    &Apache::loncommon::start_data_table_row()."\n";
  337:         if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
  338:             my ($curroption,$currlimit);
  339:             my $envkey = $context.'.'.$item;
  340:             if ($context eq 'requestauthor') {
  341:                 $envkey = $context;
  342:             }
  343:             if ($userenv{$envkey} ne '') {
  344:                 $curroption = $userenv{$envkey};
  345:             } else {
  346:                 my (@inststatuses);
  347:                 if ($context eq 'requestcourses') {
  348:                     $curroption =
  349:                         &Apache::loncoursequeueadmin::get_processtype('course',$ccuname,$ccdomain,
  350:                                                                       $isadv,$ccdomain,$item,
  351:                                                                       \@inststatuses,\%domconfig);
  352:                 } else {
  353:                      $curroption = 
  354:                          &Apache::loncoursequeueadmin::get_processtype('requestauthor',$ccuname,$ccdomain,
  355:                                                                        $isadv,$ccdomain,undef,
  356:                                                                        \@inststatuses,\%domconfig);
  357:                 }
  358:             }
  359:             if (!$curroption) {
  360:                 $curroption = 'norequest';
  361:             }
  362:             if ($curroption =~ /^autolimit=(\d*)$/) {
  363:                 $currlimit = $1;
  364:                 if ($currlimit eq '') {
  365:                     $currdisp = &mt('Yes, automatic creation');
  366:                 } else {
  367:                     $currdisp = &mt('Yes, up to [quant,_1,request]/user',$currlimit);
  368:                 }
  369:             } else {
  370:                 $currdisp = $reqdisplay{$curroption};
  371:             }
  372:             $custdisp = '<table>';
  373:             foreach my $option (@options) {
  374:                 my $val = $option;
  375:                 if ($option eq 'norequest') {
  376:                     $val = 0;
  377:                 }
  378:                 if ($option eq 'validate') {
  379:                     my $canvalidate = 0;
  380:                     if (ref($validations{$item}) eq 'HASH') {
  381:                         if ($validations{$item}{'_custom_'}) {
  382:                             $canvalidate = 1;
  383:                         }
  384:                     }
  385:                     next if (!$canvalidate);
  386:                 }
  387:                 my $checked = '';
  388:                 if ($option eq $curroption) {
  389:                     $checked = ' checked="checked"';
  390:                 } elsif ($option eq 'autolimit') {
  391:                     if ($curroption =~ /^autolimit/) {
  392:                         $checked = ' checked="checked"';
  393:                     }
  394:                 }
  395:                 my $name = 'crsreq_'.$item;
  396:                 if ($context eq 'requestauthor') {
  397:                     $name = $item;
  398:                 }
  399:                 $custdisp .= '<tr><td><span class="LC_nobreak"><label>'.
  400:                              '<input type="radio" name="'.$name.'" '.
  401:                              'value="'.$val.'"'.$checked.' />'.
  402:                              $reqtitles{$option}.'</label>&nbsp;';
  403:                 if ($option eq 'autolimit') {
  404:                     $custdisp .= '<input type="text" name="'.$name.
  405:                                  '_limit" size="1" '.
  406:                                  'value="'.$currlimit.'" /></span><br />'.
  407:                                  $reqtitles{'unlimited'};
  408:                 } else {
  409:                     $custdisp .= '</span>';
  410:                 }
  411:                 $custdisp .= '</td></tr>';
  412:             }
  413:             $custdisp .= '</table>';
  414:             $custradio = '</span></td><td>'.&mt('Custom setting').'<br />'.$custdisp;
  415:         } else {
  416:             $currdisp = ($curr_access?&mt('Yes'):&mt('No'));
  417:             my $name = $context.'_'.$item;
  418:             if ($context eq 'requestauthor') {
  419:                 $name = $context;
  420:             }
  421:             $custdisp = '<span class="LC_nobreak"><label>'.
  422:                         '<input type="radio" name="'.$name.'"'.
  423:                         ' value="1" '.$tool_on.'/>'.&mt('On').'</label>&nbsp;<label>'.
  424:                         '<input type="radio" name="'.$name.'" value="0" '.
  425:                         $tool_off.'/>'.&mt('Off').'</label></span>';
  426:             $custradio = ('&nbsp;'x2).'--'.$lt{'cusa'}.':&nbsp;'.$custdisp.
  427:                           '</span>';
  428:         }
  429:         $output .= '  <td'.$colspan.'>'.$custom_access.('&nbsp;'x4).
  430:                    $lt{'avai'}.': '.$currdisp.'</td>'."\n".
  431:                    &Apache::loncommon::end_data_table_row()."\n";
  432:         unless (&Apache::lonnet::allowed('udp',$ccdomain)) {
  433:             $output .=
  434:                    &Apache::loncommon::start_data_table_row()."\n".
  435:                    '  <td style="vertical-align:top;"><span class="LC_nobreak">'.
  436:                    $lt{'chse'}.': <label>'.
  437:                    '<input type="radio" name="custom'.$item.'" value="0" '.
  438:                    $cust_off.'/>'.$lt{'usde'}.'</label>'.('&nbsp;' x3).
  439:                    '<label><input type="radio" name="custom'.$item.'" value="1" '.
  440:                    $cust_on.'/>'.$lt{'uscu'}.'</label>'.$custradio.'</td>'.
  441:                    &Apache::loncommon::end_data_table_row()."\n";
  442:         }
  443:     }
  444:     return $output;
  445: }
  446: 
  447: sub coursereq_externaluser {
  448:     my ($ccuname,$ccdomain,$cdom) = @_;
  449:     my (@usertools,@options,%validations,%userenv,$output);
  450:     my %lt = &Apache::lonlocal::texthash (
  451:                    'official'   => 'Can request creation of official courses',
  452:                    'unofficial' => 'Can request creation of unofficial courses',
  453:                    'community'  => 'Can request creation of communities',
  454:                    'textbook'   => 'Can request creation of textbook courses',
  455:     );
  456: 
  457:     %userenv = &Apache::lonnet::userenvironment($ccdomain,$ccuname,
  458:                       'reqcrsotherdom.official','reqcrsotherdom.unofficial',
  459:                       'reqcrsotherdom.community','reqcrsotherdom.textbook');
  460:     @usertools = ('official','unofficial','community','textbook');
  461:     @options = ('approval','validate','autolimit');
  462:     %validations = &Apache::lonnet::auto_courserequest_checks($cdom);
  463:     my $optregex = join('|',@options);
  464:     my %reqtitles = &courserequest_titles();
  465:     foreach my $item (@usertools) {
  466:         my ($curroption,$currlimit,$tooloff);
  467:         if ($userenv{'reqcrsotherdom.'.$item} ne '') {
  468:             my @curr = split(',',$userenv{'reqcrsotherdom.'.$item});
  469:             foreach my $req (@curr) {
  470:                 if ($req =~ /^\Q$cdom\E\:($optregex)=?(\d*)$/) {
  471:                     $curroption = $1;
  472:                     $currlimit = $2;
  473:                     last;
  474:                 }
  475:             }
  476:             if (!$curroption) {
  477:                 $curroption = 'norequest';
  478:                 $tooloff = ' checked="checked"';
  479:             }
  480:         } else {
  481:             $curroption = 'norequest';
  482:             $tooloff = ' checked="checked"';
  483:         }
  484:         $output.= &Apache::loncommon::start_data_table_row()."\n".
  485:                   '  <td><span class="LC_nobreak">'.$lt{$item}.': </span></td><td>'.
  486:                   '<table><tr><td valign="top">'."\n".
  487:                   '<label><input type="radio" name="reqcrsotherdom_'.$item.
  488:                   '" value=""'.$tooloff.' />'.$reqtitles{'norequest'}.
  489:                   '</label></td>';
  490:         foreach my $option (@options) {
  491:             if ($option eq 'validate') {
  492:                 my $canvalidate = 0;
  493:                 if (ref($validations{$item}) eq 'HASH') {
  494:                     if ($validations{$item}{'_external_'}) {
  495:                         $canvalidate = 1;
  496:                     }
  497:                 }
  498:                 next if (!$canvalidate);
  499:             }
  500:             my $checked = '';
  501:             if ($option eq $curroption) {
  502:                 $checked = ' checked="checked"';
  503:             }
  504:             $output .= '<td valign="top"><span class="LC_nobreak"><label>'.
  505:                        '<input type="radio" name="reqcrsotherdom_'.$item.
  506:                        '" value="'.$option.'"'.$checked.' />'.
  507:                        $reqtitles{$option}.'</label>';
  508:             if ($option eq 'autolimit') {
  509:                 $output .= '&nbsp;<input type="text" name="reqcrsotherdom_'.
  510:                            $item.'_limit" size="1" '.
  511:                            'value="'.$currlimit.'" /></span>'.
  512:                            '<br />'.$reqtitles{'unlimited'};
  513:             } else {
  514:                 $output .= '</span>';
  515:             }
  516:             $output .= '</td>';
  517:         }
  518:         $output .= '</td></tr></table></td>'."\n".
  519:                    &Apache::loncommon::end_data_table_row()."\n";
  520:     }
  521:     return $output;
  522: }
  523: 
  524: sub domainrole_req {
  525:     my ($ccuname,$ccdomain) = @_;
  526:     return '<br /><h3>'.
  527:            &mt('User Can Request Assignment of Domain Roles?').
  528:            '</h3>'."\n".
  529:            &Apache::loncommon::start_data_table().
  530:            &build_tools_display($ccuname,$ccdomain,
  531:                                 'requestauthor').
  532:            &Apache::loncommon::end_data_table();
  533: }
  534: 
  535: sub courserequest_titles {
  536:     my %titles = &Apache::lonlocal::texthash (
  537:                                    official   => 'Official',
  538:                                    unofficial => 'Unofficial',
  539:                                    community  => 'Communities',
  540:                                    textbook   => 'Textbook',
  541:                                    norequest  => 'Not allowed',
  542:                                    approval   => 'Approval by Dom. Coord.',
  543:                                    validate   => 'With validation',
  544:                                    autolimit  => 'Numerical limit',
  545:                                    unlimited  => '(blank for unlimited)',
  546:                  );
  547:     return %titles;
  548: }
  549: 
  550: sub courserequest_display {
  551:     my %titles = &Apache::lonlocal::texthash (
  552:                                    approval   => 'Yes, need approval',
  553:                                    validate   => 'Yes, with validation',
  554:                                    norequest  => 'No',
  555:    );
  556:    return %titles;
  557: }
  558: 
  559: sub requestauthor_titles {
  560:     my %titles = &Apache::lonlocal::texthash (
  561:                                    norequest  => 'Not allowed',
  562:                                    approval   => 'Approval by Dom. Coord.',
  563:                                    automatic  => 'Automatic approval',
  564:                  );
  565:     return %titles;
  566: 
  567: }
  568: 
  569: sub requestauthor_display {
  570:     my %titles = &Apache::lonlocal::texthash (
  571:                                    approval   => 'Yes, need approval',
  572:                                    automatic  => 'Yes, automatic approval',
  573:                                    norequest  => 'No',
  574:    );
  575:    return %titles;
  576: }
  577: 
  578: sub requestchange_display {
  579:     my %titles = &Apache::lonlocal::texthash (
  580:                                    approval   => "availability set to 'on' (approval required)", 
  581:                                    automatic  => "availability set to 'on' (automatic approval)",
  582:                                    norequest  => "availability set to 'off'",
  583:    );
  584:    return %titles;
  585: }
  586: 
  587: sub curr_requestauthor {
  588:     my ($uname,$udom,$isadv,$inststatuses,$domconfig) = @_;
  589:     return unless ((ref($inststatuses) eq 'ARRAY') && (ref($domconfig) eq 'HASH'));
  590:     if ($uname eq '' || $udom eq '') {
  591:         $uname = $env{'user.name'};
  592:         $udom = $env{'user.domain'};
  593:         $isadv = $env{'user.adv'};
  594:     }
  595:     my (%userenv,%settings,$val);
  596:     my @options = ('automatic','approval');
  597:     %userenv =
  598:         &Apache::lonnet::userenvironment($udom,$uname,'requestauthor','inststatus');
  599:     if ($userenv{'requestauthor'}) {
  600:         $val = $userenv{'requestauthor'};
  601:         @{$inststatuses} = ('_custom_');
  602:     } else {
  603:         my %alltasks;
  604:         if (ref($domconfig->{'requestauthor'}) eq 'HASH') {
  605:             %settings = %{$domconfig->{'requestauthor'}};
  606:             if (($isadv) && ($settings{'_LC_adv'} ne '')) {
  607:                 $val = $settings{'_LC_adv'};
  608:                 @{$inststatuses} = ('_LC_adv_');
  609:             } else {
  610:                 if ($userenv{'inststatus'} ne '') {
  611:                     @{$inststatuses} = split(',',$userenv{'inststatus'});
  612:                 } else {
  613:                     @{$inststatuses} = ('default');
  614:                 }
  615:                 foreach my $status (@{$inststatuses}) {
  616:                     if (exists($settings{$status})) {
  617:                         my $value = $settings{$status};
  618:                         next unless ($value);
  619:                         unless (exists($alltasks{$value})) {
  620:                             if (ref($alltasks{$value}) eq 'ARRAY') {
  621:                                 unless(grep(/^\Q$status\E$/,@{$alltasks{$value}})) {
  622:                                     push(@{$alltasks{$value}},$status);
  623:                                 }
  624:                             } else {
  625:                                 @{$alltasks{$value}} = ($status);
  626:                             }
  627:                         }
  628:                     }
  629:                 }
  630:                 foreach my $option (@options) {
  631:                     if ($alltasks{$option}) {
  632:                         $val = $option;
  633:                         last;
  634:                     }
  635:                 }
  636:             }
  637:         }
  638:     }
  639:     return $val;
  640: }
  641: 
  642: # =================================================================== Phase one
  643: 
  644: sub print_username_entry_form {
  645:     my ($r,$context,$response,$srch,$forcenewuser,$crstype,$brcrum,
  646:         $permission) = @_;
  647:     my $defdom=$env{'request.role.domain'};
  648:     my $formtoset = 'crtuser';
  649:     if (exists($env{'form.startrolename'})) {
  650:         $formtoset = 'docustom';
  651:         $env{'form.rolename'} = $env{'form.startrolename'};
  652:     } elsif ($env{'form.origform'} eq 'crtusername') {
  653:         $formtoset =  $env{'form.origform'};
  654:     }
  655: 
  656:     my ($jsback,$elements) = &crumb_utilities();
  657: 
  658:     my $jscript = &Apache::loncommon::studentbrowser_javascript()."\n".
  659:         '<script type="text/javascript">'."\n".
  660:         '// <![CDATA['."\n".
  661:         &Apache::lonhtmlcommon::set_form_elements($elements->{$formtoset})."\n".
  662:         '// ]]>'."\n".
  663:         '</script>'."\n";
  664: 
  665:     my %existingroles=&Apache::lonuserutils::my_custom_roles($crstype);
  666:     if (($env{'form.action'} eq 'custom') && (keys(%existingroles) > 0)
  667:         && (&Apache::lonnet::allowed('mcr','/'))) {
  668:         $jscript .= &customrole_javascript();
  669:     }
  670:     my $helpitem = 'Course_Change_Privileges';
  671:     if ($env{'form.action'} eq 'custom') {
  672:         if ($context eq 'course') {
  673:             $helpitem = 'Course_Editing_Custom_Roles';
  674:         } elsif ($context eq 'domain') {
  675:             $helpitem = 'Domain_Editing_Custom_Roles';
  676:         }
  677:     } elsif ($env{'form.action'} eq 'singlestudent') {
  678:         $helpitem = 'Course_Add_Student';
  679:     } elsif ($env{'form.action'} eq 'accesslogs') {
  680:         $helpitem = 'Domain_User_Access_Logs';
  681:     } elsif ($context eq 'author') {
  682:         $helpitem = 'Author_Change_Privileges';
  683:     } elsif ($context eq 'domain') {
  684:         if ($permission->{'cusr'}) {
  685:             $helpitem = 'Domain_Change_Privileges';
  686:         } elsif ($permission->{'view'}) {
  687:             $helpitem = 'Domain_View_Privileges';
  688:         } else {
  689:             undef($helpitem);
  690:         }
  691:     }
  692:     my %breadcrumb_text = &singleuser_breadcrumb($crstype,$context,$defdom);
  693:     if ($env{'form.action'} eq 'custom') {
  694:         push(@{$brcrum},
  695:                  {href=>"javascript:backPage(document.crtuser)",       
  696:                   text=>"Pick custom role",
  697:                   help => $helpitem,}
  698:                  );
  699:     } else {
  700:         push (@{$brcrum},
  701:                   {href => "javascript:backPage(document.crtuser)",
  702:                    text => $breadcrumb_text{'search'},
  703:                    help => $helpitem,
  704:                    faq  => 282,
  705:                    bug  => 'Instructor Interface',}
  706:                   );
  707:     }
  708:     my %loaditems = (
  709:                 'onload' => "javascript:setFormElements(document.$formtoset)",
  710:                     );
  711:     my $args = {bread_crumbs           => $brcrum,
  712:                 bread_crumbs_component => 'User Management',
  713:                 add_entries            => \%loaditems,};
  714:     $r->print(&Apache::loncommon::start_page('User Management',$jscript,$args));
  715: 
  716:     my %lt=&Apache::lonlocal::texthash(
  717:                     'srst' => 'Search for a user and enroll as a student',
  718:                     'srme' => 'Search for a user and enroll as a member',
  719:                     'srad' => 'Search for a user and modify/add user information or roles',
  720:                     'srvu' => 'Search for a user and view user information and roles',
  721:                     'srva' => 'Search for a user and view access log information',
  722: 		    'usr'  => "Username",
  723:                     'dom'  => "Domain",
  724:                     'ecrp' => "Define or Edit Custom Role",
  725:                     'nr'   => "role name",
  726:                     'cre'  => "Next",
  727: 				       );
  728: 
  729:     if ($env{'form.action'} eq 'custom') {
  730:         if (&Apache::lonnet::allowed('mcr','/')) {
  731:             my $newroletext = &mt('Define new custom role:');
  732:             $r->print('<form action="/adm/createuser" method="post" name="docustom">'.
  733:                       '<input type="hidden" name="action" value="'.$env{'form.action'}.'" />'.
  734:                       '<input type="hidden" name="phase" value="selected_custom_edit" />'.
  735:                       '<h3>'.$lt{'ecrp'}.'</h3>'.
  736:                       &Apache::loncommon::start_data_table().
  737:                       &Apache::loncommon::start_data_table_row().
  738:                       '<td>');
  739:             if (keys(%existingroles) > 0) {
  740:                 $r->print('<br /><label><input type="radio" name="customroleaction" value="new" checked="checked" onclick="setCustomFields();" /><b>'.$newroletext.'</b></label>');
  741:             } else {
  742:                 $r->print('<br /><input type="hidden" name="customroleaction" value="new" /><b>'.$newroletext.'</b>');
  743:             }
  744:             $r->print('</td><td align="center">'.$lt{'nr'}.'<br /><input type="text" size="15" name="newrolename" onfocus="setCustomAction('."'new'".');" /></td>'.
  745:                       &Apache::loncommon::end_data_table_row());
  746:             if (keys(%existingroles) > 0) {
  747:                 $r->print(&Apache::loncommon::start_data_table_row().'<td><br />'.
  748:                           '<label><input type="radio" name="customroleaction" value="edit" onclick="setCustomFields();"/><b>'.
  749:                           &mt('View/Modify existing role:').'</b></label></td>'.
  750:                           '<td align="center"><br />'.
  751:                           '<select name="rolename" onchange="setCustomAction('."'edit'".');">'.
  752:                           '<option value="" selected="selected">'.
  753:                           &mt('Select'));
  754:                 foreach my $role (sort(keys(%existingroles))) {
  755:                     $r->print('<option value="'.$role.'">'.$role.'</option>');
  756:                 }
  757:                 $r->print('</select>'.
  758:                           '</td>'.
  759:                           &Apache::loncommon::end_data_table_row());
  760:             }
  761:             $r->print(&Apache::loncommon::end_data_table().'<p>'.
  762:                       '<input name="customeditor" type="submit" value="'.
  763:                       $lt{'cre'}.'" /></p>'.
  764:                       '</form>');
  765:         }
  766:     } else {
  767:         my $actiontext = $lt{'srad'};
  768:         my $fixeddom;
  769:         if ($env{'form.action'} eq 'singlestudent') {
  770:             if ($crstype eq 'Community') {
  771:                 $actiontext = $lt{'srme'};
  772:             } else {
  773:                 $actiontext = $lt{'srst'};
  774:             }
  775:         } elsif ($env{'form.action'} eq 'accesslogs') {
  776:             $actiontext = $lt{'srva'};
  777:             $fixeddom = 1;
  778:         } elsif (($env{'form.action'} eq 'singleuser') &&
  779:                  ($context eq 'domain') && (!&Apache::lonnet::allowed('mau',$defdom))) {
  780:             $actiontext = $lt{'srvu'};
  781:             $fixeddom = 1;
  782:         }
  783:         $r->print("<h3>$actiontext</h3>");
  784:         if ($env{'form.origform'} ne 'crtusername') {
  785:             if ($response) {
  786:                $r->print("\n<div>$response</div>".
  787:                          '<br clear="all" />');
  788:             }
  789:         }
  790:         $r->print(&entry_form($defdom,$srch,$forcenewuser,$context,$response,$crstype,$fixeddom));
  791:     }
  792: }
  793: 
  794: sub customrole_javascript {
  795:     my $js = <<"END";
  796: <script type="text/javascript">
  797: // <![CDATA[
  798: 
  799: function setCustomFields() {
  800:     if (document.docustom.customroleaction.length > 0) {
  801:         for (var i=0; i<document.docustom.customroleaction.length; i++) {
  802:             if (document.docustom.customroleaction[i].checked) {
  803:                 if (document.docustom.customroleaction[i].value == 'new') {
  804:                     document.docustom.rolename.selectedIndex = 0;
  805:                 } else {
  806:                     document.docustom.newrolename.value = '';
  807:                 }
  808:             }
  809:         }
  810:     }
  811:     return;
  812: }
  813: 
  814: function setCustomAction(caller) {
  815:     if (document.docustom.customroleaction.length > 0) {
  816:         for (var i=0; i<document.docustom.customroleaction.length; i++) {
  817:             if (document.docustom.customroleaction[i].value == caller) {
  818:                 document.docustom.customroleaction[i].checked = true;
  819:             }
  820:         }
  821:     }
  822:     setCustomFields();
  823:     return;
  824: }
  825: 
  826: // ]]>
  827: </script>
  828: END
  829:     return $js;
  830: }
  831: 
  832: sub entry_form {
  833:     my ($dom,$srch,$forcenewuser,$context,$responsemsg,$crstype,$fixeddom) = @_;
  834:     my ($usertype,$inexact);
  835:     if (ref($srch) eq 'HASH') {
  836:         if (($srch->{'srchin'} eq 'dom') &&
  837:             ($srch->{'srchby'} eq 'uname') &&
  838:             ($srch->{'srchtype'} eq 'exact') &&
  839:             ($srch->{'srchdomain'} ne '') &&
  840:             ($srch->{'srchterm'} ne '')) {
  841:             my (%curr_rules,%got_rules);
  842:             my ($rules,$ruleorder) =
  843:                 &Apache::lonnet::inst_userrules($srch->{'srchdomain'},'username');
  844:             $usertype = &Apache::lonuserutils::check_usertype($srch->{'srchdomain'},$srch->{'srchterm'},$rules,\%curr_rules,\%got_rules);
  845:         } else {
  846:             $inexact = 1;
  847:         }
  848:     }
  849:     my ($cancreate,$noinstd);
  850:     if ($env{'form.action'} eq 'accesslogs') {
  851:         $noinstd = 1;
  852:     } else {
  853:         $cancreate =
  854:             &Apache::lonuserutils::can_create_user($dom,$context,$usertype);
  855:     }
  856:     my ($userpicker,$cansearch) = 
  857:        &Apache::loncommon::user_picker($dom,$srch,$forcenewuser,
  858:                                        'document.crtuser',$cancreate,$usertype,$context,$fixeddom,$noinstd);
  859:     my $srchbutton = &mt('Search');
  860:     if ($env{'form.action'} eq 'singlestudent') {
  861:         $srchbutton = &mt('Search and Enroll');
  862:     } elsif ($env{'form.action'} eq 'accesslogs') {
  863:         $srchbutton = &mt('Search');
  864:     } elsif ($cancreate && $responsemsg ne '' && $inexact) {
  865:         $srchbutton = &mt('Search or Add New User');
  866:     }
  867:     my $output;
  868:     if ($cansearch) {
  869:         $output = <<"ENDBLOCK";
  870: <form action="/adm/createuser" method="post" name="crtuser">
  871: <input type="hidden" name="action" value="$env{'form.action'}" />
  872: <input type="hidden" name="phase" value="get_user_info" />
  873: $userpicker
  874: <input name="userrole" type="button" value="$srchbutton" onclick="javascript:validateEntry(document.crtuser)" />
  875: </form>
  876: ENDBLOCK
  877:     } else {
  878:         $output = '<p>'.$userpicker.'</p>';
  879:     }
  880:     if (($env{'form.phase'} eq '') && ($env{'form.action'} ne 'accesslogs') &&
  881:         (!(($env{'form.action'} eq 'singleuser') && ($context eq 'domain') &&
  882:         (!&Apache::lonnet::allowed('mau',$env{'request.role.domain'}))))) {
  883:         my $defdom=$env{'request.role.domain'};
  884:         my $domform = &Apache::loncommon::select_dom_form($defdom,'srchdomain');
  885:         my %lt=&Apache::lonlocal::texthash(
  886:                   'enro' => 'Enroll one student',
  887:                   'enrm' => 'Enroll one member',
  888:                   'admo' => 'Add/modify a single user',
  889:                   'crea' => 'create new user if required',
  890:                   'uskn' => "username is known",
  891:                   'crnu' => 'Create a new user',
  892:                   'usr'  => 'Username',
  893:                   'dom'  => 'in domain',
  894:                   'enrl' => 'Enroll',
  895:                   'cram'  => 'Create/Modify user',
  896:         );
  897:         my $sellink=&Apache::loncommon::selectstudent_link('crtusername','srchterm','srchdomain');
  898:         my ($title,$buttontext,$showresponse);
  899:         if ($env{'form.action'} eq 'singlestudent') {
  900:             if ($crstype eq 'Community') {
  901:                 $title = $lt{'enrm'};
  902:             } else {
  903:                 $title = $lt{'enro'};
  904:             }
  905:             $buttontext = $lt{'enrl'};
  906:         } else {
  907:             $title = $lt{'admo'};
  908:             $buttontext = $lt{'cram'};
  909:         }
  910:         if ($cancreate) {
  911:             $title .= ' <span class="LC_cusr_subheading">('.$lt{'crea'}.')</span>';
  912:         } else {
  913:             $title .= ' <span class="LC_cusr_subheading">('.$lt{'uskn'}.')</span>';
  914:         }
  915:         if ($env{'form.origform'} eq 'crtusername') {
  916:             $showresponse = $responsemsg;
  917:         }
  918:         $output .= <<"ENDDOCUMENT";
  919: <br />
  920: <form action="/adm/createuser" method="post" name="crtusername">
  921: <input type="hidden" name="action" value="$env{'form.action'}" />
  922: <input type="hidden" name="phase" value="createnewuser" />
  923: <input type="hidden" name="srchtype" value="exact" />
  924: <input type="hidden" name="srchby" value="uname" />
  925: <input type="hidden" name="srchin" value="dom" />
  926: <input type="hidden" name="forcenewuser" value="1" />
  927: <input type="hidden" name="origform" value="crtusername" />
  928: <h3>$title</h3>
  929: $showresponse
  930: <table>
  931:  <tr>
  932:   <td>$lt{'usr'}:</td>
  933:   <td><input type="text" size="15" name="srchterm" /></td>
  934:   <td>&nbsp;$lt{'dom'}:</td><td>$domform</td>
  935:   <td>&nbsp;$sellink&nbsp;</td>
  936:   <td>&nbsp;<input name="userrole" type="submit" value="$buttontext" /></td>
  937:  </tr>
  938: </table>
  939: </form>
  940: ENDDOCUMENT
  941:     }
  942:     return $output;
  943: }
  944: 
  945: sub user_modification_js {
  946:     my ($pjump_def,$dc_setcourse_code,$nondc_setsection_code,$groupslist)=@_;
  947:     
  948:     return <<END;
  949: <script type="text/javascript" language="Javascript">
  950: // <![CDATA[
  951: 
  952:     $pjump_def
  953:     $dc_setcourse_code
  954: 
  955:     function dateset() {
  956:         eval("document.cu."+document.cu.pres_marker.value+
  957:             ".value=document.cu.pres_value.value");
  958:         modalWindow.close();
  959:     }
  960: 
  961:     $nondc_setsection_code
  962: // ]]>
  963: </script>
  964: END
  965: }
  966: 
  967: # =================================================================== Phase two
  968: sub print_user_selection_page {
  969:     my ($r,$response,$srch,$srch_results,$srcharray,$context,$opener_elements,$crstype,$brcrum) = @_;
  970:     my @fields = ('username','domain','lastname','firstname','permanentemail');
  971:     my $sortby = $env{'form.sortby'};
  972: 
  973:     if (!grep(/^\Q$sortby\E$/,@fields)) {
  974:         $sortby = 'lastname';
  975:     }
  976: 
  977:     my ($jsback,$elements) = &crumb_utilities();
  978: 
  979:     my $jscript = (<<ENDSCRIPT);
  980: <script type="text/javascript">
  981: // <![CDATA[
  982: function pickuser(uname,udom) {
  983:     document.usersrchform.seluname.value=uname;
  984:     document.usersrchform.seludom.value=udom;
  985:     document.usersrchform.phase.value="userpicked";
  986:     document.usersrchform.submit();
  987: }
  988: 
  989: $jsback
  990: // ]]>
  991: </script>
  992: ENDSCRIPT
  993: 
  994:     my %lt=&Apache::lonlocal::texthash(
  995:                                        'usrch'          => "User Search to add/modify roles",
  996:                                        'stusrch'        => "User Search to enroll student",
  997:                                        'memsrch'        => "User Search to enroll member",
  998:                                        'srcva'          => "Search for a user and view access log information",
  999:                                        'usrvu'          => "User Search to view user roles",
 1000:                                        'usel'           => "Select a user to add/modify roles",
 1001:                                        'suvr'           => "Select a user to view roles",
 1002:                                        'stusel'         => "Select a user to enroll as a student",
 1003:                                        'memsel'         => "Select a user to enroll as a member",
 1004:                                        'vacsel'         => "Select a user to view access log",
 1005:                                        'username'       => "username",
 1006:                                        'domain'         => "domain",
 1007:                                        'lastname'       => "last name",
 1008:                                        'firstname'      => "first name",
 1009:                                        'permanentemail' => "permanent e-mail",
 1010:                                       );
 1011:     if ($context eq 'requestcrs') {
 1012:         $r->print('<div>');
 1013:     } else {
 1014:         my %breadcrumb_text = &singleuser_breadcrumb($crstype,$context,$srch->{'srchdomain'});
 1015:         my $helpitem;
 1016:         if ($env{'form.action'} eq 'singleuser') {
 1017:             $helpitem = 'Course_Change_Privileges';
 1018:         } elsif ($env{'form.action'} eq 'singlestudent') {
 1019:             $helpitem = 'Course_Add_Student';
 1020:         } elsif ($context eq 'author') {
 1021:             $helpitem = 'Author_Change_Privileges';
 1022:         } elsif ($context eq 'domain') {
 1023:             $helpitem = 'Domain_Change_Privileges';
 1024:         }
 1025:         push (@{$brcrum},
 1026:                   {href => "javascript:backPage(document.usersrchform,'','')",
 1027:                    text => $breadcrumb_text{'search'},
 1028:                    faq  => 282,
 1029:                    bug  => 'Instructor Interface',},
 1030:                   {href => "javascript:backPage(document.usersrchform,'get_user_info','select')",
 1031:                    text => $breadcrumb_text{'userpicked'},
 1032:                    faq  => 282,
 1033:                    bug  => 'Instructor Interface',
 1034:                    help => $helpitem}
 1035:                   );
 1036:         $r->print(&Apache::loncommon::start_page('User Management',$jscript,{bread_crumbs => $brcrum}));
 1037:         if ($env{'form.action'} eq 'singleuser') {
 1038:             my $readonly;
 1039:             if (($context eq 'domain') && (!&Apache::lonnet::allowed('mau',$srch->{'srchdomain'}))) {
 1040:                 $readonly = 1;
 1041:                 $r->print("<b>$lt{'usrvu'}</b><br />");
 1042:             } else {
 1043:                 $r->print("<b>$lt{'usrch'}</b><br />");
 1044:             }
 1045:             $r->print(&entry_form($srch->{'srchdomain'},$srch,undef,$context,undef,$crstype));
 1046:             if ($readonly) {
 1047:                 $r->print('<h3>'.$lt{'suvr'}.'</h3>');
 1048:             } else {
 1049:                 $r->print('<h3>'.$lt{'usel'}.'</h3>');
 1050:             }
 1051:         } elsif ($env{'form.action'} eq 'singlestudent') {
 1052:             $r->print($jscript."<b>");
 1053:             if ($crstype eq 'Community') {
 1054:                 $r->print($lt{'memsrch'});
 1055:             } else {
 1056:                 $r->print($lt{'stusrch'});
 1057:             }
 1058:             $r->print("</b><br />");
 1059:             $r->print(&entry_form($srch->{'srchdomain'},$srch,undef,$context,undef,$crstype));
 1060:             $r->print('</form><h3>');
 1061:             if ($crstype eq 'Community') {
 1062:                 $r->print($lt{'memsel'});
 1063:             } else {
 1064:                 $r->print($lt{'stusel'});
 1065:             }
 1066:             $r->print('</h3>');
 1067:         } elsif ($env{'form.action'} eq 'accesslogs') {
 1068:             $r->print("<b>$lt{'srcva'}</b><br />");
 1069:             $r->print(&entry_form($srch->{'srchdomain'},$srch,undef,$context,undef,undef,1));
 1070:             $r->print('<h3>'.$lt{'vacsel'}.'</h3>');
 1071:         }
 1072:     }
 1073:     $r->print('<form name="usersrchform" method="post" action="">'.
 1074:               &Apache::loncommon::start_data_table()."\n".
 1075:               &Apache::loncommon::start_data_table_header_row()."\n".
 1076:               ' <th> </th>'."\n");
 1077:     foreach my $field (@fields) {
 1078:         $r->print(' <th><a href="javascript:document.usersrchform.sortby.value='.
 1079:                   "'".$field."'".';document.usersrchform.submit();">'.
 1080:                   $lt{$field}.'</a></th>'."\n");
 1081:     }
 1082:     $r->print(&Apache::loncommon::end_data_table_header_row());
 1083: 
 1084:     my @sorted_users = sort {
 1085:         lc($srch_results->{$a}->{$sortby})   cmp lc($srch_results->{$b}->{$sortby})
 1086:             ||
 1087:         lc($srch_results->{$a}->{lastname})  cmp lc($srch_results->{$b}->{lastname})
 1088:             ||
 1089:         lc($srch_results->{$a}->{firstname}) cmp lc($srch_results->{$b}->{firstname})
 1090: 	    ||
 1091: 	lc($a) cmp lc($b)
 1092:         } (keys(%$srch_results));
 1093: 
 1094:     foreach my $user (@sorted_users) {
 1095:         my ($uname,$udom) = split(/:/,$user);
 1096:         my $onclick;
 1097:         if ($context eq 'requestcrs') {
 1098:             $onclick =
 1099:                 'onclick="javascript:gochoose('."'$uname','$udom',".
 1100:                                                "'$srch_results->{$user}->{firstname}',".
 1101:                                                "'$srch_results->{$user}->{lastname}',".
 1102:                                                "'$srch_results->{$user}->{permanentemail}'".');"';
 1103:         } else {
 1104:             $onclick =
 1105:                 ' onclick="javascript:pickuser('."'".$uname."'".','."'".$udom."'".');"';
 1106:         }
 1107:         $r->print(&Apache::loncommon::start_data_table_row().
 1108:                   '<td><input type="button" name="seluser" value="'.&mt('Select').'" '.
 1109:                   $onclick.' /></td>'.
 1110:                   '<td><tt>'.$uname.'</tt></td>'.
 1111:                   '<td><tt>'.$udom.'</tt></td>');
 1112:         foreach my $field ('lastname','firstname','permanentemail') {
 1113:             $r->print('<td>'.$srch_results->{$user}->{$field}.'</td>');
 1114:         }
 1115:         $r->print(&Apache::loncommon::end_data_table_row());
 1116:     }
 1117:     $r->print(&Apache::loncommon::end_data_table().'<br /><br />');
 1118:     if (ref($srcharray) eq 'ARRAY') {
 1119:         foreach my $item (@{$srcharray}) {
 1120:             $r->print('<input type="hidden" name="'.$item.'" value="'.$env{'form.'.$item}.'" />'."\n");
 1121:         }
 1122:     }
 1123:     $r->print(' <input type="hidden" name="sortby" value="'.$sortby.'" />'."\n".
 1124:               ' <input type="hidden" name="seluname" value="" />'."\n".
 1125:               ' <input type="hidden" name="seludom" value="" />'."\n".
 1126:               ' <input type="hidden" name="currstate" value="select" />'."\n".
 1127:               ' <input type="hidden" name="phase" value="get_user_info" />'."\n".
 1128:               ' <input type="hidden" name="action" value="'.$env{'form.action'}.'" />'."\n");
 1129:     if ($context eq 'requestcrs') {
 1130:         $r->print($opener_elements.'</form></div>');
 1131:     } else {
 1132:         $r->print($response.'</form>');
 1133:     }
 1134: }
 1135: 
 1136: sub print_user_query_page {
 1137:     my ($r,$caller,$brcrum) = @_;
 1138: # FIXME - this is for a network-wide name search (similar to catalog search)
 1139: # To use frames with similar behavior to catalog/portfolio search.
 1140: # To be implemented. 
 1141:     return;
 1142: }
 1143: 
 1144: sub print_user_modification_page {
 1145:     my ($r,$ccuname,$ccdomain,$srch,$response,$context,$permission,$crstype,
 1146:         $brcrum,$showcredits) = @_;
 1147:     if (($ccuname eq '') || ($ccdomain eq '')) {
 1148:         my $usermsg = &mt('No username and/or domain provided.');
 1149:         $env{'form.phase'} = '';
 1150: 	&print_username_entry_form($r,$context,$usermsg,'','',$crstype,$brcrum,
 1151:                                    $permission);
 1152:         return;
 1153:     }
 1154:     my ($form,$formname);
 1155:     if ($env{'form.action'} eq 'singlestudent') {
 1156:         $form = 'document.enrollstudent';
 1157:         $formname = 'enrollstudent';
 1158:     } else {
 1159:         $form = 'document.cu';
 1160:         $formname = 'cu';
 1161:     }
 1162:     my %abv_auth = &auth_abbrev();
 1163:     my (%rulematch,%inst_results,$newuser,%alerts,%curr_rules,%got_rules);
 1164:     my $uhome=&Apache::lonnet::homeserver($ccuname,$ccdomain);
 1165:     if ($uhome eq 'no_host') {
 1166:         my $usertype;
 1167:         my ($rules,$ruleorder) =
 1168:             &Apache::lonnet::inst_userrules($ccdomain,'username');
 1169:             $usertype =
 1170:                 &Apache::lonuserutils::check_usertype($ccdomain,$ccuname,$rules,
 1171:                                                       \%curr_rules,\%got_rules);
 1172:         my $cancreate =
 1173:             &Apache::lonuserutils::can_create_user($ccdomain,$context,
 1174:                                                    $usertype);
 1175:         if (!$cancreate) {
 1176:             my $helplink = 'javascript:helpMenu('."'display'".')';
 1177:             my %usertypetext = (
 1178:                 official   => 'institutional',
 1179:                 unofficial => 'non-institutional',
 1180:             );
 1181:             my $response;
 1182:             if ($env{'form.origform'} eq 'crtusername') {
 1183:                 $response = '<span class="LC_warning">'.
 1184:                             &mt('No match found for the username [_1] in LON-CAPA domain: [_2]',
 1185:                                 '<b>'.$ccuname.'</b>',$ccdomain).
 1186:                             '</span><br />';
 1187:             }
 1188:             $response .= '<p class="LC_warning">'
 1189:                         .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
 1190:                         .' ';
 1191:             if ($context eq 'domain') {
 1192:                 $response .= &mt('Please contact a [_1] for assistance.',
 1193:                                  &Apache::lonnet::plaintext('dc'));
 1194:             } else {
 1195:                 $response .= &mt('Please contact the [_1]helpdesk[_2] for assistance.'
 1196:                                 ,'<a href="'.$helplink.'">','</a>');
 1197:             }
 1198:             $response .= '</p><br />';
 1199:             $env{'form.phase'} = '';
 1200:             &print_username_entry_form($r,$context,$response,undef,undef,$crstype,$brcrum,
 1201:                                        $permission);
 1202:             return;
 1203:         }
 1204:         $newuser = 1;
 1205:         my $checkhash;
 1206:         my $checks = { 'username' => 1 };
 1207:         $checkhash->{$ccuname.':'.$ccdomain} = { 'newuser' => $newuser };
 1208:         &Apache::loncommon::user_rule_check($checkhash,$checks,
 1209:             \%alerts,\%rulematch,\%inst_results,\%curr_rules,\%got_rules);
 1210:         if (ref($alerts{'username'}) eq 'HASH') {
 1211:             if (ref($alerts{'username'}{$ccdomain}) eq 'HASH') {
 1212:                 my $domdesc =
 1213:                     &Apache::lonnet::domain($ccdomain,'description');
 1214:                 if ($alerts{'username'}{$ccdomain}{$ccuname}) {
 1215:                     my $userchkmsg;
 1216:                     if (ref($curr_rules{$ccdomain}) eq 'HASH') {  
 1217:                         $userchkmsg = 
 1218:                             &Apache::loncommon::instrule_disallow_msg('username',
 1219:                                                                  $domdesc,1).
 1220:                         &Apache::loncommon::user_rule_formats($ccdomain,
 1221:                             $domdesc,$curr_rules{$ccdomain}{'username'},
 1222:                             'username');
 1223:                     }
 1224:                     $env{'form.phase'} = '';
 1225:                     &print_username_entry_form($r,$context,$userchkmsg,undef,undef,$crstype,$brcrum,
 1226:                                                $permission);
 1227:                     return;
 1228:                 }
 1229:             }
 1230:         }
 1231:     } else {
 1232:         $newuser = 0;
 1233:     }
 1234:     if ($response) {
 1235:         $response = '<br />'.$response;
 1236:     }
 1237: 
 1238:     my $pjump_def = &Apache::lonhtmlcommon::pjump_javascript_definition();
 1239:     my $dc_setcourse_code = '';
 1240:     my $nondc_setsection_code = '';                                        
 1241:     my %loaditem;
 1242: 
 1243:     my $groupslist = &Apache::lonuserutils::get_groupslist();
 1244: 
 1245:     my $js = &validation_javascript($context,$ccdomain,$pjump_def,$crstype,
 1246:                                $groupslist,$newuser,$formname,\%loaditem);
 1247:     my %breadcrumb_text = &singleuser_breadcrumb($crstype,$context,$ccdomain);
 1248:     my $helpitem = 'Course_Change_Privileges';
 1249:     if ($env{'form.action'} eq 'singlestudent') {
 1250:         $helpitem = 'Course_Add_Student';
 1251:     } elsif ($context eq 'author') {
 1252:         $helpitem = 'Author_Change_Privileges';
 1253:     } elsif ($context eq 'domain') {
 1254:         $helpitem = 'Domain_Change_Privileges';
 1255:     }
 1256:     push (@{$brcrum},
 1257:         {href => "javascript:backPage($form)",
 1258:          text => $breadcrumb_text{'search'},
 1259:          faq  => 282,
 1260:          bug  => 'Instructor Interface',});
 1261:     if ($env{'form.phase'} eq 'userpicked') {
 1262:        push(@{$brcrum},
 1263:               {href => "javascript:backPage($form,'get_user_info','select')",
 1264:                text => $breadcrumb_text{'userpicked'},
 1265:                faq  => 282,
 1266:                bug  => 'Instructor Interface',});
 1267:     }
 1268:     push(@{$brcrum},
 1269:             {href => "javascript:backPage($form,'$env{'form.phase'}','modify')",
 1270:              text => $breadcrumb_text{'modify'},
 1271:              faq  => 282,
 1272:              bug  => 'Instructor Interface',
 1273:              help => $helpitem});
 1274:     my $args = {'add_entries'           => \%loaditem,
 1275:                 'bread_crumbs'          => $brcrum,
 1276:                 'bread_crumbs_component' => 'User Management'};
 1277:     if ($env{'form.popup'}) {
 1278:         $args->{'no_nav_bar'} = 1;
 1279:     }
 1280:     my $start_page =
 1281:         &Apache::loncommon::start_page('User Management',$js,$args);
 1282: 
 1283:     my $forminfo =<<"ENDFORMINFO";
 1284: <form action="/adm/createuser" method="post" name="$formname">
 1285: <input type="hidden" name="phase" value="update_user_data" />
 1286: <input type="hidden" name="ccuname" value="$ccuname" />
 1287: <input type="hidden" name="ccdomain" value="$ccdomain" />
 1288: <input type="hidden" name="pres_value"  value="" />
 1289: <input type="hidden" name="pres_type"   value="" />
 1290: <input type="hidden" name="pres_marker" value="" />
 1291: ENDFORMINFO
 1292:     my (%inccourses,$roledom,$defaultcredits);
 1293:     if ($context eq 'course') {
 1294:         $inccourses{$env{'request.course.id'}}=1;
 1295:         $roledom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 1296:         if ($showcredits) {
 1297:             $defaultcredits = &Apache::lonuserutils::get_defaultcredits();
 1298:         }
 1299:     } elsif ($context eq 'author') {
 1300:         $roledom = $env{'request.role.domain'};
 1301:     } elsif ($context eq 'domain') {
 1302:         foreach my $key (keys(%env)) {
 1303:             $roledom = $env{'request.role.domain'};
 1304:             if ($key=~/^user\.priv\.cm\.\/($roledom)\/($match_username)/) {
 1305:                 $inccourses{$1.'_'.$2}=1;
 1306:             }
 1307:         }
 1308:     } else {
 1309:         foreach my $key (keys(%env)) {
 1310: 	    if ($key=~/^user\.priv\.cm\.\/($match_domain)\/($match_username)/) {
 1311: 	        $inccourses{$1.'_'.$2}=1;
 1312:             }
 1313:         }
 1314:     }
 1315:     my $title = '';
 1316:     if ($newuser) {
 1317:         my ($portfolioform,$domroleform);
 1318:         if ((&Apache::lonnet::allowed('mpq',$env{'request.role.domain'})) ||
 1319:             (&Apache::lonnet::allowed('mut',$env{'request.role.domain'}))) {
 1320:             # Current user has quota or user tools modification privileges
 1321:             $portfolioform = '<br />'.&user_quotas($ccuname,$ccdomain);
 1322:         }
 1323:         if ((&Apache::lonnet::allowed('cau',$env{'request.role.domain'})) &&
 1324:             ($ccdomain eq $env{'request.role.domain'})) {
 1325:             $domroleform = '<br />'.&domainrole_req($ccuname,$ccdomain);
 1326:         }
 1327:         &initialize_authen_forms($ccdomain,$formname);
 1328:         my %lt=&Apache::lonlocal::texthash(
 1329:                 'lg'             => 'Login Data',
 1330:                 'hs'             => "Home Server",
 1331:         );
 1332: 	$r->print(<<ENDTITLE);
 1333: $start_page
 1334: $response
 1335: $forminfo
 1336: <script type="text/javascript" language="Javascript">
 1337: // <![CDATA[
 1338: $loginscript
 1339: // ]]>
 1340: </script>
 1341: <input type='hidden' name='makeuser' value='1' />
 1342: ENDTITLE
 1343:         if ($env{'form.action'} eq 'singlestudent') {
 1344:             if ($crstype eq 'Community') {
 1345:                 $title = &mt('Create New User [_1] in domain [_2] as a member',
 1346:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1347:             } else {
 1348:                 $title = &mt('Create New User [_1] in domain [_2] as a student',
 1349:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1350:             }
 1351:         } else {
 1352:                 $title = &mt('Create New User [_1] in domain [_2]',
 1353:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1354:         }
 1355:         $r->print('<h2>'.$title.'</h2>'."\n");
 1356:         $r->print('<div class="LC_left_float">');
 1357:         $r->print(&personal_data_display($ccuname,$ccdomain,$newuser,$context,
 1358:                                          $inst_results{$ccuname.':'.$ccdomain}));
 1359:         # Option to disable student/employee ID conflict checking not offerred for new users.
 1360:         my ($home_server_pick,$numlib) = 
 1361:             &Apache::loncommon::home_server_form_item($ccdomain,'hserver',
 1362:                                                       'default','hide');
 1363:         if ($numlib > 1) {
 1364:             $r->print("
 1365: <br />
 1366: $lt{'hs'}: $home_server_pick
 1367: <br />");
 1368:         } else {
 1369:             $r->print($home_server_pick);
 1370:         }
 1371:         if (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) {
 1372:             $r->print('<br /><h3>'.
 1373:                       &mt('User Can Request Creation of Courses/Communities in this Domain?').'</h3>'.
 1374:                       &Apache::loncommon::start_data_table().
 1375:                       &build_tools_display($ccuname,$ccdomain,
 1376:                                            'requestcourses').
 1377:                       &Apache::loncommon::end_data_table());
 1378:         }
 1379:         $r->print('</div>'."\n".'<div class="LC_left_float"><h3>'.
 1380:                   $lt{'lg'}.'</h3>');
 1381:         my ($fixedauth,$varauth,$authmsg); 
 1382:         if (ref($rulematch{$ccuname.':'.$ccdomain}) eq 'HASH') {
 1383:             my $matchedrule = $rulematch{$ccuname.':'.$ccdomain}{'username'};
 1384:             my ($rules,$ruleorder) = 
 1385:                 &Apache::lonnet::inst_userrules($ccdomain,'username');
 1386:             if (ref($rules) eq 'HASH') {
 1387:                 if (ref($rules->{$matchedrule}) eq 'HASH') {
 1388:                     my $authtype = $rules->{$matchedrule}{'authtype'};
 1389:                     if ($authtype !~ /^(krb4|krb5|int|fsys|loc)$/) {
 1390:                         $r->print(&Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc));
 1391:                     } else { 
 1392:                         my $authparm = $rules->{$matchedrule}{'authparm'};
 1393:                         $authmsg = $rules->{$matchedrule}{'authmsg'};
 1394:                         if ($authtype =~ /^krb(4|5)$/) {
 1395:                             my $ver = $1;
 1396:                             if ($authparm ne '') {
 1397:                                 $fixedauth = <<"KERB"; 
 1398: <input type="hidden" name="login" value="krb" />
 1399: <input type="hidden" name="krbver" value="$ver" />
 1400: <input type="hidden" name="krbarg" value="$authparm" />
 1401: KERB
 1402:                             }
 1403:                         } else {
 1404:                             $fixedauth = 
 1405: '<input type="hidden" name="login" value="'.$authtype.'" />'."\n";
 1406:                             if ($rules->{$matchedrule}{'authparmfixed'}) {
 1407:                                 $fixedauth .=    
 1408: '<input type="hidden" name="'.$authtype.'arg" value="'.$authparm.'" />'."\n";
 1409:                             } else {
 1410:                                 if ($authtype eq 'int') {
 1411:                                     $varauth = '<br />'.
 1412: &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>';
 1413:                                 } elsif ($authtype eq 'loc') {
 1414:                                     $varauth = '<br />'.
 1415: &mt('[_1] Local Authentication with argument [_2]','','<input type="text" name="'.$authtype.'arg" value="" />')."\n";
 1416:                                 } else {
 1417:                                     $varauth =
 1418: '<input type="text" name="'.$authtype.'arg" value="" />'."\n";
 1419:                                 }
 1420:                             }
 1421:                         }
 1422:                     }
 1423:                 } else {
 1424:                     $r->print(&Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc));
 1425:                 }
 1426:             }
 1427:             if ($authmsg) {
 1428:                 $r->print(<<ENDAUTH);
 1429: $fixedauth
 1430: $authmsg
 1431: $varauth
 1432: ENDAUTH
 1433:             }
 1434:         } else {
 1435:             $r->print(&Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc)); 
 1436:         }
 1437:         $r->print($portfolioform.$domroleform);
 1438:         if ($env{'form.action'} eq 'singlestudent') {
 1439:             $r->print(&date_sections_select($context,$newuser,$formname,
 1440:                                             $permission,$crstype,$ccuname,
 1441:                                             $ccdomain,$showcredits));
 1442:         }
 1443:         $r->print('</div><div class="LC_clear_float_footer"></div>');
 1444:     } else { # user already exists
 1445: 	$r->print($start_page.$forminfo);
 1446:         if ($env{'form.action'} eq 'singlestudent') {
 1447:             if ($crstype eq 'Community') {
 1448:                 $title = &mt('Enroll one member: [_1] in domain [_2]',
 1449:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1450:             } else {
 1451:                 $title = &mt('Enroll one student: [_1] in domain [_2]',
 1452:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1453:             }
 1454:         } else {
 1455:             if ($permission->{'cusr'}) {
 1456:                 $title = &mt('Modify existing user: [_1] in domain [_2]',
 1457:                              '"'.$ccuname.'"','"'.$ccdomain.'"');
 1458:             } else {
 1459:                 $title = &mt('Existing user: [_1] in domain [_2]',
 1460:                              '"'.$ccuname.'"','"'.$ccdomain.'"');
 1461:             }
 1462:         }
 1463:         $r->print('<h2>'.$title.'</h2>'."\n");
 1464:         $r->print('<div class="LC_left_float">');
 1465:         $r->print(&personal_data_display($ccuname,$ccdomain,$newuser,$context,
 1466:                                          $inst_results{$ccuname.':'.$ccdomain}));
 1467:         if ((&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) ||
 1468:             (&Apache::lonnet::allowed('udp',$env{'request.role.domain'}))) {
 1469:             $r->print('<br /><h3>'.&mt('User Can Request Creation of Courses/Communities in this Domain?').'</h3>'.
 1470:                       &Apache::loncommon::start_data_table());
 1471:             if ($env{'request.role.domain'} eq $ccdomain) {
 1472:                 $r->print(&build_tools_display($ccuname,$ccdomain,'requestcourses'));
 1473:             } else {
 1474:                 $r->print(&coursereq_externaluser($ccuname,$ccdomain,
 1475:                                                   $env{'request.role.domain'}));
 1476:             }
 1477:             $r->print(&Apache::loncommon::end_data_table());
 1478:         }
 1479:         $r->print('</div>');
 1480:         my @order = ('auth','quota','tools','requestauthor');
 1481:         my %user_text;
 1482:         my ($isadv,$isauthor) = 
 1483:             &Apache::lonnet::is_advanced_user($ccdomain,$ccuname);
 1484:         if ((!$isauthor) && 
 1485:             ((&Apache::lonnet::allowed('cau',$env{'request.role.domain'})) ||
 1486:              (&Apache::lonnet::allowed('udp',$env{'request.role.domain'}))) &&
 1487:              ($env{'request.role.domain'} eq $ccdomain)) {
 1488:             $user_text{'requestauthor'} = &domainrole_req($ccuname,$ccdomain);
 1489:         }
 1490:         $user_text{'auth'} =  &user_authentication($ccuname,$ccdomain,$formname,$crstype,$permission);
 1491:         if ((&Apache::lonnet::allowed('mpq',$ccdomain)) ||
 1492:             (&Apache::lonnet::allowed('mut',$ccdomain)) ||
 1493:             (&Apache::lonnet::allowed('udp',$ccdomain))) {
 1494:             # Current user has quota modification privileges
 1495:             $user_text{'quota'} = &user_quotas($ccuname,$ccdomain);
 1496:         }
 1497:         if (!&Apache::lonnet::allowed('mpq',$ccdomain)) {
 1498:             if (&Apache::lonnet::allowed('mpq',$env{'request.role.domain'})) {
 1499:                 my %lt=&Apache::lonlocal::texthash(
 1500:                     'dska'  => "Disk quotas for user's portfolio and Authoring Space",
 1501:                     'youd'  => "You do not have privileges to modify the portfolio and/or Authoring Space quotas for this user.",
 1502:                     'ichr'  => "If a change is required, contact a domain coordinator for the domain",
 1503:                 );
 1504:                 $user_text{'quota'} = <<ENDNOPORTPRIV;
 1505: <h3>$lt{'dska'}</h3>
 1506: $lt{'youd'} $lt{'ichr'}: $ccdomain
 1507: ENDNOPORTPRIV
 1508:             }
 1509:         }
 1510:         if (!&Apache::lonnet::allowed('mut',$ccdomain)) {
 1511:             if (&Apache::lonnet::allowed('mut',$env{'request.role.domain'})) {
 1512:                 my %lt=&Apache::lonlocal::texthash(
 1513:                     'utav'  => "User Tools Availability",
 1514:                     'yodo'  => "You do not have privileges to modify Portfolio, Blog, WebDAV, or Personal Information Page settings for this user.",
 1515:                     'ifch'  => "If a change is required, contact a domain coordinator for the domain",
 1516:                 );
 1517:                 $user_text{'tools'} = <<ENDNOTOOLSPRIV;
 1518: <h3>$lt{'utav'}</h3>
 1519: $lt{'yodo'} $lt{'ifch'}: $ccdomain
 1520: ENDNOTOOLSPRIV
 1521:             }
 1522:         }
 1523:         my $gotdiv = 0; 
 1524:         foreach my $item (@order) {
 1525:             if ($user_text{$item} ne '') {
 1526:                 unless ($gotdiv) {
 1527:                     $r->print('<div class="LC_left_float">');
 1528:                     $gotdiv = 1;
 1529:                 }
 1530:                 $r->print('<br />'.$user_text{$item});
 1531:             }
 1532:         }
 1533:         if ($env{'form.action'} eq 'singlestudent') {
 1534:             unless ($gotdiv) {
 1535:                 $r->print('<div class="LC_left_float">');
 1536:             }
 1537:             my $credits;
 1538:             if ($showcredits) {
 1539:                 $credits = &get_user_credits($ccuname,$ccdomain,$defaultcredits);
 1540:                 if ($credits eq '') {
 1541:                     $credits = $defaultcredits;
 1542:                 }
 1543:             }
 1544:             $r->print(&date_sections_select($context,$newuser,$formname,
 1545:                                             $permission,$crstype,$ccuname,
 1546:                                             $ccdomain,$showcredits));
 1547:         }
 1548:         if ($gotdiv) {
 1549:             $r->print('</div><div class="LC_clear_float_footer"></div>');
 1550:         }
 1551:         my $statuses;
 1552:         if (($context eq 'domain') && (&Apache::lonnet::allowed('udp',$ccdomain)) &&
 1553:             (!&Apache::lonnet::allowed('mau',$ccdomain))) {
 1554:             $statuses = ['active'];
 1555:         } elsif (($context eq 'course') && ((&Apache::lonnet::allowed('vcl',$env{'request.course.id'})) ||
 1556:                  ($env{'request.course.sec'} &&
 1557:                   &Apache::lonnet::allowed('vcl',$env{'request.course.id'}.'/'.$env{'request.course.sec'})))) {
 1558:             $statuses = ['active'];
 1559:         }
 1560:         if ($env{'form.action'} ne 'singlestudent') {
 1561:             &display_existing_roles($r,$ccuname,$ccdomain,\%inccourses,$context,
 1562:                                     $roledom,$crstype,$showcredits,$statuses);
 1563:         }
 1564:     } ## End of new user/old user logic
 1565:     if ($env{'form.action'} eq 'singlestudent') {
 1566:         my $btntxt;
 1567:         if ($crstype eq 'Community') {
 1568:             $btntxt = &mt('Enroll Member');
 1569:         } else {
 1570:             $btntxt = &mt('Enroll Student');
 1571:         }
 1572:         $r->print('<br /><input type="button" value="'.$btntxt.'" onclick="setSections(this.form)" />'."\n");
 1573:     } elsif ($permission->{'cusr'}) {
 1574:         $r->print('<div class="LC_left_float">'.
 1575:                   '<fieldset><legend>'.&mt('Add Roles').'</legend>');
 1576:         my $addrolesdisplay = 0;
 1577:         if ($context eq 'domain' || $context eq 'author') {
 1578:             $addrolesdisplay = &new_coauthor_roles($r,$ccuname,$ccdomain);
 1579:         }
 1580:         if ($context eq 'domain') {
 1581:             my $add_domainroles = &new_domain_roles($r,$ccdomain);
 1582:             if (!$addrolesdisplay) {
 1583:                 $addrolesdisplay = $add_domainroles;
 1584:             }
 1585:             $r->print(&course_level_dc($env{'request.role.domain'},$showcredits));
 1586:             $r->print('</fieldset></div><div class="LC_clear_float_footer"></div>'.
 1587:                       '<br /><input type="button" value="'.&mt('Save').'" onclick="setCourse()" />'."\n");
 1588:         } elsif ($context eq 'author') {
 1589:             if ($addrolesdisplay) {
 1590:                 $r->print('</fieldset></div><div class="LC_clear_float_footer"></div>'.
 1591:                           '<br /><input type="button" value="'.&mt('Save').'"');
 1592:                 if ($newuser) {
 1593:                     $r->print(' onclick="auth_check()" \>'."\n");
 1594:                 } else {
 1595:                     $r->print('onclick="this.form.submit()" \>'."\n");
 1596:                 }
 1597:             } else {
 1598:                 $r->print('</fieldset></div>'.
 1599:                           '<div class="LC_clear_float_footer"></div>'.
 1600:                           '<br /><a href="javascript:backPage(document.cu)">'.
 1601:                           &mt('Back to previous page').'</a>');
 1602:             }
 1603:         } else {
 1604:             $r->print(&course_level_table(\%inccourses,$showcredits,$defaultcredits));
 1605:             $r->print('</fieldset></div><div class="LC_clear_float_footer"></div>'.
 1606:                       '<br /><input type="button" value="'.&mt('Save').'" onclick="setSections(this.form)" />'."\n");
 1607:         }
 1608:     }
 1609:     $r->print(&Apache::lonhtmlcommon::echo_form_input(['phase','userrole','ccdomain','prevphase','currstate','ccuname','ccdomain']));
 1610:     $r->print('<input type="hidden" name="currstate" value="" />');
 1611:     $r->print('<input type="hidden" name="prevphase" value="'.$env{'form.phase'}.'" /></form><br /><br />');
 1612:     return;
 1613: }
 1614: 
 1615: sub singleuser_breadcrumb {
 1616:     my ($crstype,$context,$domain) = @_;
 1617:     my %breadcrumb_text;
 1618:     if ($env{'form.action'} eq 'singlestudent') {
 1619:         if ($crstype eq 'Community') {
 1620:             $breadcrumb_text{'search'} = 'Enroll a member';
 1621:         } else {
 1622:             $breadcrumb_text{'search'} = 'Enroll a student';
 1623:         }
 1624:         $breadcrumb_text{'userpicked'} = 'Select a user';
 1625:         $breadcrumb_text{'modify'} = 'Set section/dates';
 1626:     } elsif ($env{'form.action'} eq 'accesslogs') {
 1627:         $breadcrumb_text{'search'} = 'View access logs for a user';
 1628:         $breadcrumb_text{'userpicked'} = 'Select a user';
 1629:         $breadcrumb_text{'activity'} = 'Activity';
 1630:     } elsif (($env{'form.action'} eq 'singleuser') && ($context eq 'domain') &&
 1631:              (!&Apache::lonnet::allowed('mau',$domain))) {
 1632:         $breadcrumb_text{'search'} = "View user's roles";
 1633:         $breadcrumb_text{'userpicked'} = 'Select a user';
 1634:         $breadcrumb_text{'modify'} = 'User roles';
 1635:     } else {
 1636:         $breadcrumb_text{'search'} = 'Create/modify a user';
 1637:         $breadcrumb_text{'userpicked'} = 'Select a user';
 1638:         $breadcrumb_text{'modify'} = 'Set user role';
 1639:     }
 1640:     return %breadcrumb_text;
 1641: }
 1642: 
 1643: sub date_sections_select {
 1644:     my ($context,$newuser,$formname,$permission,$crstype,$ccuname,$ccdomain,
 1645:         $showcredits) = @_;
 1646:     my $credits;
 1647:     if ($showcredits) {
 1648:         my $defaultcredits = &Apache::lonuserutils::get_defaultcredits();
 1649:         $credits = &get_user_credits($ccuname,$ccdomain,$defaultcredits);
 1650:         if ($credits eq '') {
 1651:             $credits = $defaultcredits;
 1652:         }
 1653:     }
 1654:     my $cid = $env{'request.course.id'};
 1655:     my ($cnum,$cdom) = &Apache::lonuserutils::get_course_identity($cid);
 1656:     my $date_table = '<h3>'.&mt('Starting and Ending Dates').'</h3>'."\n".
 1657:         &Apache::lonuserutils::date_setting_table(undef,undef,$context,
 1658:                                                   undef,$formname,$permission);
 1659:     my $rowtitle = 'Section';
 1660:     my $secbox = '<h3>'.&mt('Section and Credits').'</h3>'."\n".
 1661:         &Apache::lonuserutils::section_picker($cdom,$cnum,'st',$rowtitle,
 1662:                                               $permission,$context,'',$crstype,
 1663:                                               $showcredits,$credits);
 1664:     my $output = $date_table.$secbox;
 1665:     return $output;
 1666: }
 1667: 
 1668: sub validation_javascript {
 1669:     my ($context,$ccdomain,$pjump_def,$crstype,$groupslist,$newuser,$formname,
 1670:         $loaditem) = @_;
 1671:     my $dc_setcourse_code = '';
 1672:     my $nondc_setsection_code = '';
 1673:     if ($context eq 'domain') {
 1674:         my $dcdom = $env{'request.role.domain'};
 1675:         $loaditem->{'onload'} = "document.cu.coursedesc.value='';";
 1676:         $dc_setcourse_code = 
 1677:             &Apache::lonuserutils::dc_setcourse_js('cu','singleuser',$context);
 1678:     } else {
 1679:         my $checkauth; 
 1680:         if (($newuser) || (&Apache::lonnet::allowed('mau',$ccdomain))) {
 1681:             $checkauth = 1;
 1682:         }
 1683:         if ($context eq 'course') {
 1684:             $nondc_setsection_code =
 1685:                 &Apache::lonuserutils::setsections_javascript($formname,$groupslist,
 1686:                                                               undef,$checkauth,
 1687:                                                               $crstype);
 1688:         }
 1689:         if ($checkauth) {
 1690:             $nondc_setsection_code .= 
 1691:                 &Apache::lonuserutils::verify_authen($formname,$context);
 1692:         }
 1693:     }
 1694:     my $js = &user_modification_js($pjump_def,$dc_setcourse_code,
 1695:                                    $nondc_setsection_code,$groupslist);
 1696:     my ($jsback,$elements) = &crumb_utilities();
 1697:     $js .= "\n".
 1698:            '<script type="text/javascript">'."\n".
 1699:            '// <![CDATA['."\n".
 1700:            $jsback."\n".
 1701:            '// ]]>'."\n".
 1702:            '</script>'."\n";
 1703:     return $js;
 1704: }
 1705: 
 1706: sub display_existing_roles {
 1707:     my ($r,$ccuname,$ccdomain,$inccourses,$context,$roledom,$crstype,
 1708:         $showcredits,$statuses) = @_;
 1709:     my $now=time;
 1710:     my $showall = 1;
 1711:     my ($showexpired,$showactive);
 1712:     if ((ref($statuses) eq 'ARRAY') && (@{$statuses} > 0)) {
 1713:         $showall = 0;
 1714:         if (grep(/^expired$/,@{$statuses})) {
 1715:             $showexpired = 1;
 1716:         }
 1717:         if (grep(/^active$/,@{$statuses})) {
 1718:             $showactive = 1;
 1719:         }
 1720:         if ($showexpired && $showactive) {
 1721:             $showall = 1;
 1722:         }
 1723:     }
 1724:     my %lt=&Apache::lonlocal::texthash(
 1725:                     'rer'  => "Existing Roles",
 1726:                     'rev'  => "Revoke",
 1727:                     'del'  => "Delete",
 1728:                     'ren'  => "Re-Enable",
 1729:                     'rol'  => "Role",
 1730:                     'ext'  => "Extent",
 1731:                     'crd'  => "Credits",
 1732:                     'sta'  => "Start",
 1733:                     'end'  => "End",
 1734:                                        );
 1735:     my (%rolesdump,%roletext,%sortrole,%roleclass,%rolepriv);
 1736:     if ($context eq 'course' || $context eq 'author') {
 1737:         my @roles = &Apache::lonuserutils::roles_by_context($context,1,$crstype);
 1738:         my %roleshash = 
 1739:             &Apache::lonnet::get_my_roles($ccuname,$ccdomain,'userroles',
 1740:                               ['active','previous','future'],\@roles,$roledom,1);
 1741:         foreach my $key (keys(%roleshash)) {
 1742:             my ($start,$end) = split(':',$roleshash{$key});
 1743:             next if ($start eq '-1' || $end eq '-1');
 1744:             my ($rnum,$rdom,$role,$sec) = split(':',$key);
 1745:             if ($context eq 'course') {
 1746:                 next unless (($rnum eq $env{'course.'.$env{'request.course.id'}.'.num'})
 1747:                              && ($rdom eq $env{'course.'.$env{'request.course.id'}.'.domain'}));
 1748:             } elsif ($context eq 'author') {
 1749:                 next unless (($rnum eq $env{'user.name'}) && ($rdom eq $env{'request.role.domain'}));
 1750:             }
 1751:             my ($newkey,$newvalue,$newrole);
 1752:             $newkey = '/'.$rdom.'/'.$rnum;
 1753:             if ($sec ne '') {
 1754:                 $newkey .= '/'.$sec;
 1755:             }
 1756:             $newvalue = $role;
 1757:             if ($role =~ /^cr/) {
 1758:                 $newrole = 'cr';
 1759:             } else {
 1760:                 $newrole = $role;
 1761:             }
 1762:             $newkey .= '_'.$newrole;
 1763:             if ($start ne '' && $end ne '') {
 1764:                 $newvalue .= '_'.$end.'_'.$start;
 1765:             } elsif ($end ne '') {
 1766:                 $newvalue .= '_'.$end;
 1767:             }
 1768:             $rolesdump{$newkey} = $newvalue;
 1769:         }
 1770:     } else {
 1771:         %rolesdump=&Apache::lonnet::dump('roles',$ccdomain,$ccuname);
 1772:     }
 1773:     # Build up table of user roles to allow revocation and re-enabling of roles.
 1774:     my ($tmp) = keys(%rolesdump);
 1775:     return if ($tmp =~ /^(con_lost|error)/i);
 1776:     foreach my $area (sort { my $a1=join('_',(split('_',$a))[1,0]);
 1777:                                 my $b1=join('_',(split('_',$b))[1,0]);
 1778:                                 return $a1 cmp $b1;
 1779:                             } keys(%rolesdump)) {
 1780:         next if ($area =~ /^rolesdef/);
 1781:         my $envkey=$area;
 1782:         my $role = $rolesdump{$area};
 1783:         my $thisrole=$area;
 1784:         $area =~ s/\_\w\w$//;
 1785:         my ($role_code,$role_end_time,$role_start_time) =
 1786:             split(/_/,$role);
 1787:         my $active=1;
 1788:         $active=0 if (($role_end_time) && ($now>$role_end_time));
 1789:         if ($active) {
 1790:             next unless($showall || $showactive);
 1791:         } else {
 1792:             next unless($showall || $showexpired);
 1793:         }
 1794: # Is this a custom role? Get role owner and title.
 1795:         my ($croleudom,$croleuname,$croletitle)=
 1796:             ($role_code=~m{^cr/($match_domain)/($match_username)/(\w+)$});
 1797:         my $allowed=0;
 1798:         my $delallowed=0;
 1799:         my $sortkey=$role_code;
 1800:         my $class='Unknown';
 1801:         my $credits='';
 1802:         my $csec;
 1803:         if ($area =~ m{^/($match_domain)/($match_courseid)}) {
 1804:             $class='Course';
 1805:             my ($coursedom,$coursedir) = ($1,$2);
 1806:             my $cid = $1.'_'.$2;
 1807:             # $1.'_'.$2 is the course id (eg. 103_12345abcef103l3).
 1808:             next if ($envkey =~ m{^/$match_domain/$match_courseid/[A-Za-z0-9]+_gr$});
 1809:             my %coursedata=
 1810:                 &Apache::lonnet::coursedescription($cid);
 1811:             if ($coursedir =~ /^$match_community$/) {
 1812:                 $class='Community';
 1813:             }
 1814:             $sortkey.="\0$coursedom";
 1815:             my $carea;
 1816:             if (defined($coursedata{'description'})) {
 1817:                 $carea=$coursedata{'description'}.
 1818:                     '<br />'.&mt('Domain').': '.$coursedom.('&nbsp;'x8).
 1819:     &Apache::loncommon::syllabuswrapper(&mt('Syllabus'),$coursedir,$coursedom);
 1820:                 $sortkey.="\0".$coursedata{'description'};
 1821:             } else {
 1822:                 if ($class eq 'Community') {
 1823:                     $carea=&mt('Unavailable community').': '.$area;
 1824:                     $sortkey.="\0".&mt('Unavailable community').': '.$area;
 1825:                 } else {
 1826:                     $carea=&mt('Unavailable course').': '.$area;
 1827:                     $sortkey.="\0".&mt('Unavailable course').': '.$area;
 1828:                 }
 1829:             }
 1830:             $sortkey.="\0$coursedir";
 1831:             $inccourses->{$cid}=1;
 1832:             if (($showcredits) && ($class eq 'Course') && ($role_code eq 'st')) {
 1833:                 my $defaultcredits = $coursedata{'internal.defaultcredits'};
 1834:                 $credits =
 1835:                     &get_user_credits($ccuname,$ccdomain,$defaultcredits,
 1836:                                       $coursedom,$coursedir);
 1837:                 if ($credits eq '') {
 1838:                     $credits = $defaultcredits;
 1839:                 }
 1840:             }
 1841:             if ((&Apache::lonnet::allowed('c'.$role_code,$coursedom.'/'.$coursedir)) ||
 1842:                 (&Apache::lonnet::allowed('c'.$role_code,$ccdomain))) {
 1843:                 $allowed=1;
 1844:             }
 1845:             unless ($allowed) {
 1846:                 my $isowner = &Apache::lonuserutils::is_courseowner($cid,$coursedata{'internal.courseowner'});
 1847:                 if ($isowner) {
 1848:                     if (($role_code eq 'co') && ($class eq 'Community')) {
 1849:                         $allowed = 1;
 1850:                     } elsif (($role_code eq 'cc') && ($class eq 'Course')) {
 1851:                         $allowed = 1;
 1852:                     }
 1853:                 }
 1854:             } 
 1855:             if ((&Apache::lonnet::allowed('dro',$coursedom)) ||
 1856:                 (&Apache::lonnet::allowed('dro',$ccdomain))) {
 1857:                 $delallowed=1;
 1858:             }
 1859: # - custom role. Needs more info, too
 1860:             if ($croletitle) {
 1861:                 if (&Apache::lonnet::allowed('ccr',$coursedom.'/'.$coursedir)) {
 1862:                     $allowed=1;
 1863:                     $thisrole.='.'.$role_code;
 1864:                 }
 1865:             }
 1866:             if ($area=~m{^/($match_domain/$match_courseid/(\w+))}) {
 1867:                 $csec = $2;
 1868:                 $carea.='<br />'.&mt('Section: [_1]',$csec);
 1869:                 $sortkey.="\0$csec";
 1870:                 if (!$allowed) {
 1871:                     if ($env{'request.course.sec'} eq $csec) {
 1872:                         if (&Apache::lonnet::allowed('c'.$role_code,$1)) {
 1873:                             $allowed = 1;
 1874:                         }
 1875:                     }
 1876:                 }
 1877:             }
 1878:             $area=$carea;
 1879:         } else {
 1880:             $sortkey.="\0".$area;
 1881:             # Determine if current user is able to revoke privileges
 1882:             if ($area=~m{^/($match_domain)/}) {
 1883:                 if ((&Apache::lonnet::allowed('c'.$role_code,$1)) ||
 1884:                    (&Apache::lonnet::allowed('c'.$role_code,$ccdomain))) {
 1885:                    $allowed=1;
 1886:                 }
 1887:                 if (((&Apache::lonnet::allowed('dro',$1))  ||
 1888:                     (&Apache::lonnet::allowed('dro',$ccdomain))) &&
 1889:                     ($role_code ne 'dc')) {
 1890:                     $delallowed=1;
 1891:                 }
 1892:             } else {
 1893:                 if (&Apache::lonnet::allowed('c'.$role_code,'/')) {
 1894:                     $allowed=1;
 1895:                 }
 1896:             }
 1897:             if ($role_code eq 'ca' || $role_code eq 'au' || $role_code eq 'aa') {
 1898:                 $class='Authoring Space';
 1899:             } elsif ($role_code eq 'su') {
 1900:                 $class='System';
 1901:             } else {
 1902:                 $class='Domain';
 1903:             }
 1904:         }
 1905:         if (($role_code eq 'ca') || ($role_code eq 'aa')) {
 1906:             $area=~m{/($match_domain)/($match_username)};
 1907:             if (&Apache::lonuserutils::authorpriv($2,$1)) {
 1908:                 $allowed=1;
 1909:             } else {
 1910:                 $allowed=0;
 1911:             }
 1912:         }
 1913:         my $row = '';
 1914:         if ($showall) {
 1915:             $row.= '<td>';
 1916:             if (($active) && ($allowed)) {
 1917:                 $row.= '<input type="checkbox" name="rev:'.$thisrole.'" />';
 1918:             } else {
 1919:                 if ($active) {
 1920:                     $row.='&nbsp;';
 1921:                 } else {
 1922:                     $row.=&mt('expired or revoked');
 1923:                 }
 1924:             }
 1925:             $row.='</td><td>';
 1926:             if ($allowed && !$active) {
 1927:                 $row.= '<input type="checkbox" name="ren:'.$thisrole.'" />';
 1928:             } else {
 1929:                 $row.='&nbsp;';
 1930:             }
 1931:             $row.='</td><td>';
 1932:             if ($delallowed) {
 1933:                 $row.= '<input type="checkbox" name="del:'.$thisrole.'" />';
 1934:             } else {
 1935:                 $row.='&nbsp;';
 1936:             }
 1937:             $row.= '</td>';
 1938:         }
 1939:         my $plaintext='';
 1940:         if (!$croletitle) {
 1941:             $plaintext=&Apache::lonnet::plaintext($role_code,$class);
 1942:             if (($showcredits) && ($credits ne '')) {
 1943:                 $plaintext .= '<br/ ><span class="LC_nobreak">'.
 1944:                               '<span class="LC_fontsize_small">'.
 1945:                               &mt('Credits: [_1]',$credits).
 1946:                               '</span></span>';
 1947:             }
 1948:         } else {
 1949:             $plaintext=
 1950:                 &mt('Custom role [_1][_2]defined by [_3]',
 1951:                         '"'.$croletitle.'"',
 1952:                         '<br />',
 1953:                         $croleuname.':'.$croleudom);
 1954:         }
 1955:         $row.= '<td>'.$plaintext.'</td>'.
 1956:                '<td>'.$area.'</td>'.
 1957:                '<td>'.($role_start_time?&Apache::lonlocal::locallocaltime($role_start_time)
 1958:                                             : '&nbsp;' ).'</td>'.
 1959:                '<td>'.($role_end_time  ?&Apache::lonlocal::locallocaltime($role_end_time)
 1960:                                             : '&nbsp;' ).'</td>';
 1961:         $sortrole{$sortkey}=$envkey;
 1962:         $roletext{$envkey}=$row;
 1963:         $roleclass{$envkey}=$class;
 1964:         if ($allowed) {
 1965:             $rolepriv{$envkey}='edit';
 1966:         } else {
 1967:             if ($context eq 'domain') {
 1968:                 if ((&Apache::lonnet::allowed('vur',$ccdomain)) &&
 1969:                     ($envkey=~m{^/$ccdomain/})) {
 1970:                     $rolepriv{$envkey}='view';
 1971:                 }
 1972:             } elsif ($context eq 'course') {
 1973:                 if ((&Apache::lonnet::allowed('vcl',$env{'request.course.id'})) ||
 1974:                     ($env{'request.course.sec'} && ($env{'request.course.sec'} eq $csec) &&
 1975:                      &Apache::lonnet::allowed('vcl',$env{'request.course.id'}.'/'.$env{'request.course.sec'}))) {
 1976:                     $rolepriv{$envkey}='view';
 1977:                 }
 1978:             }
 1979:         }
 1980:     } # end of foreach        (table building loop)
 1981: 
 1982:     my $rolesdisplay = 0;
 1983:     my %output = ();
 1984:     foreach my $type ('Authoring Space','Course','Community','Domain','System','Unknown') {
 1985:         $output{$type} = '';
 1986:         foreach my $which (sort {uc($a) cmp uc($b)} (keys(%sortrole))) {
 1987:             if ( ($roleclass{$sortrole{$which}} =~ /^\Q$type\E/ ) && ($rolepriv{$sortrole{$which}}) ) {
 1988:                  $output{$type}.=
 1989:                       &Apache::loncommon::start_data_table_row().
 1990:                       $roletext{$sortrole{$which}}.
 1991:                       &Apache::loncommon::end_data_table_row();
 1992:             }
 1993:         }
 1994:         unless($output{$type} eq '') {
 1995:             $output{$type} = '<tr class="LC_info_row">'.
 1996:                       "<td align='center' colspan='7'>".&mt($type)."</td></tr>".
 1997:                       $output{$type};
 1998:             $rolesdisplay = 1;
 1999:         }
 2000:     }
 2001:     if ($rolesdisplay == 1) {
 2002:         my $contextrole='';
 2003:         if ($env{'request.course.id'}) {
 2004:             if (&Apache::loncommon::course_type() eq 'Community') {
 2005:                 $contextrole = &mt('Existing Roles in this Community');
 2006:             } else {
 2007:                 $contextrole = &mt('Existing Roles in this Course');
 2008:             }
 2009:         } elsif ($env{'request.role'} =~ /^au\./) {
 2010:             $contextrole = &mt('Existing Co-Author Roles in your Authoring Space');
 2011:         } else {
 2012:             if ($showall) {
 2013:                 $contextrole = &mt('Existing Roles in this Domain');
 2014:             } elsif ($showactive) {
 2015:                 $contextrole = &mt('Unexpired Roles in this Domain');
 2016:             } elsif ($showexpired) {
 2017:                 $contextrole = &mt('Expired or Revoked Roles in this Domain');
 2018:             }
 2019:         }
 2020:         $r->print('<div class="LC_left_float">'.
 2021: '<fieldset><legend>'.$contextrole.'</legend>'.
 2022: &Apache::loncommon::start_data_table("LC_createuser").
 2023: &Apache::loncommon::start_data_table_header_row());
 2024:         if ($showall) {
 2025:             $r->print(
 2026: '<th>'.$lt{'rev'}.'</th><th>'.$lt{'ren'}.'</th><th>'.$lt{'del'}.'</th>'
 2027:             );
 2028:         } elsif ($showexpired) {
 2029:             $r->print('<th>'.$lt{'rev'}.'</th>');
 2030:         }
 2031:         $r->print(
 2032: '<th>'.$lt{'rol'}.'</th><th>'.$lt{'ext'}.'</th>'.
 2033: '<th>'.$lt{'sta'}.'</th><th>'.$lt{'end'}.'</th>'.
 2034: &Apache::loncommon::end_data_table_header_row());
 2035:         foreach my $type ('Authoring Space','Course','Community','Domain','System','Unknown') {
 2036:             if ($output{$type}) {
 2037:                 $r->print($output{$type}."\n");
 2038:             }
 2039:         }
 2040:         $r->print(&Apache::loncommon::end_data_table().
 2041:                   '</fieldset></div>');
 2042:     }
 2043:     return;
 2044: }
 2045: 
 2046: sub new_coauthor_roles {
 2047:     my ($r,$ccuname,$ccdomain) = @_;
 2048:     my $addrolesdisplay = 0;
 2049:     #
 2050:     # Co-Author
 2051:     #
 2052:     if (&Apache::lonuserutils::authorpriv($env{'user.name'},
 2053:                                           $env{'request.role.domain'}) &&
 2054:         ($env{'user.name'} ne $ccuname || $env{'user.domain'} ne $ccdomain)) {
 2055:         # No sense in assigning co-author role to yourself
 2056:         $addrolesdisplay = 1;
 2057:         my $cuname=$env{'user.name'};
 2058:         my $cudom=$env{'request.role.domain'};
 2059:         my %lt=&Apache::lonlocal::texthash(
 2060:                     'cs'   => "Authoring Space",
 2061:                     'act'  => "Activate",
 2062:                     'rol'  => "Role",
 2063:                     'ext'  => "Extent",
 2064:                     'sta'  => "Start",
 2065:                     'end'  => "End",
 2066:                     'cau'  => "Co-Author",
 2067:                     'caa'  => "Assistant Co-Author",
 2068:                     'ssd'  => "Set Start Date",
 2069:                     'sed'  => "Set End Date"
 2070:                                        );
 2071:         $r->print('<h4>'.$lt{'cs'}.'</h4>'."\n".
 2072:                   &Apache::loncommon::start_data_table()."\n".
 2073:                   &Apache::loncommon::start_data_table_header_row()."\n".
 2074:                   '<th>'.$lt{'act'}.'</th><th>'.$lt{'rol'}.'</th>'.
 2075:                   '<th>'.$lt{'ext'}.'</th><th>'.$lt{'sta'}.'</th>'.
 2076:                   '<th>'.$lt{'end'}.'</th>'."\n".
 2077:                   &Apache::loncommon::end_data_table_header_row()."\n".
 2078:                   &Apache::loncommon::start_data_table_row().'
 2079:            <td>
 2080:             <input type="checkbox" name="act_'.$cudom.'_'.$cuname.'_ca" />
 2081:            </td>
 2082:            <td>'.$lt{'cau'}.'</td>
 2083:            <td>'.$cudom.'_'.$cuname.'</td>
 2084:            <td><input type="hidden" name="start_'.$cudom.'_'.$cuname.'_ca" value="" />
 2085:              <a href=
 2086: "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>
 2087: <td><input type="hidden" name="end_'.$cudom.'_'.$cuname.'_ca" value="" />
 2088: <a href=
 2089: "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".
 2090:               &Apache::loncommon::end_data_table_row()."\n".
 2091:               &Apache::loncommon::start_data_table_row()."\n".
 2092: '<td><input type="checkbox" name="act_'.$cudom.'_'.$cuname.'_aa" /></td>
 2093: <td>'.$lt{'caa'}.'</td>
 2094: <td>'.$cudom.'_'.$cuname.'</td>
 2095: <td><input type="hidden" name="start_'.$cudom.'_'.$cuname.'_aa" value="" />
 2096: <a href=
 2097: "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>
 2098: <td><input type="hidden" name="end_'.$cudom.'_'.$cuname.'_aa" value="" />
 2099: <a href=
 2100: "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".
 2101:              &Apache::loncommon::end_data_table_row()."\n".
 2102:              &Apache::loncommon::end_data_table());
 2103:     } elsif ($env{'request.role'} =~ /^au\./) {
 2104:         if (!(&Apache::lonuserutils::authorpriv($env{'user.name'},
 2105:                                                 $env{'request.role.domain'}))) {
 2106:             $r->print('<span class="LC_error">'.
 2107:                       &mt('You do not have privileges to assign co-author roles.').
 2108:                       '</span>');
 2109:         } elsif (($env{'user.name'} eq $ccuname) &&
 2110:              ($env{'user.domain'} eq $ccdomain)) {
 2111:             $r->print(&mt('Assigning yourself a co-author or assistant co-author role in your own author area in Authoring Space is not permitted'));
 2112:         }
 2113:     }
 2114:     return $addrolesdisplay;;
 2115: }
 2116: 
 2117: sub new_domain_roles {
 2118:     my ($r,$ccdomain) = @_;
 2119:     my $addrolesdisplay = 0;
 2120:     #
 2121:     # Domain level
 2122:     #
 2123:     my $num_domain_level = 0;
 2124:     my $domaintext =
 2125:     '<h4>'.&mt('Domain Level').'</h4>'.
 2126:     &Apache::loncommon::start_data_table().
 2127:     &Apache::loncommon::start_data_table_header_row().
 2128:     '<th>'.&mt('Activate').'</th><th>'.&mt('Role').'</th><th>'.
 2129:     &mt('Extent').'</th>'.
 2130:     '<th>'.&mt('Start').'</th><th>'.&mt('End').'</th>'.
 2131:     &Apache::loncommon::end_data_table_header_row();
 2132:     my @allroles = &Apache::lonuserutils::roles_by_context('domain');
 2133:     foreach my $thisdomain (sort(&Apache::lonnet::all_domains())) {
 2134:         foreach my $role (@allroles) {
 2135:             next if ($role eq 'ad');
 2136:             next if (($role eq 'au') && ($ccdomain ne $thisdomain));
 2137:             if (&Apache::lonnet::allowed('c'.$role,$thisdomain)) {
 2138:                my $plrole=&Apache::lonnet::plaintext($role);
 2139:                my %lt=&Apache::lonlocal::texthash(
 2140:                     'ssd'  => "Set Start Date",
 2141:                     'sed'  => "Set End Date"
 2142:                                        );
 2143:                $num_domain_level ++;
 2144:                $domaintext .=
 2145: &Apache::loncommon::start_data_table_row().
 2146: '<td><input type="checkbox" name="act_'.$thisdomain.'_'.$role.'" /></td>
 2147: <td>'.$plrole.'</td>
 2148: <td>'.$thisdomain.'</td>
 2149: <td><input type="hidden" name="start_'.$thisdomain.'_'.$role.'" value="" />
 2150: <a href=
 2151: "javascript:pjump('."'date_start','Start Date $plrole',document.cu.start_$thisdomain\_$role.value,'start_$thisdomain\_$role','cu.pres','dateset'".')">'.$lt{'ssd'}.'</a></td>
 2152: <td><input type="hidden" name="end_'.$thisdomain.'_'.$role.'" value="" />
 2153: <a href=
 2154: "javascript:pjump('."'date_end','End Date $plrole',document.cu.end_$thisdomain\_$role.value,'end_$thisdomain\_$role','cu.pres','dateset'".')">'.$lt{'sed'}.'</a></td>'.
 2155: &Apache::loncommon::end_data_table_row();
 2156:             }
 2157:         }
 2158:     }
 2159:     $domaintext.= &Apache::loncommon::end_data_table();
 2160:     if ($num_domain_level > 0) {
 2161:         $r->print($domaintext);
 2162:         $addrolesdisplay = 1;
 2163:     }
 2164:     return $addrolesdisplay;
 2165: }
 2166: 
 2167: sub user_authentication {
 2168:     my ($ccuname,$ccdomain,$formname,$crstype,$permission) = @_;
 2169:     my $currentauth=&Apache::lonnet::queryauthenticate($ccuname,$ccdomain);
 2170:     my $outcome;
 2171:     my %lt=&Apache::lonlocal::texthash(
 2172:                    'err'   => "ERROR",
 2173:                    'uuas'  => "This user has an unrecognized authentication scheme",
 2174:                    'adcs'  => "Please alert a domain coordinator of this situation",
 2175:                    'sldb'  => "Please specify login data below",
 2176:                    'ld'    => "Login Data"
 2177:     );
 2178:     # Check for a bad authentication type
 2179:     if ($currentauth !~ /^(krb4|krb5|unix|internal|localauth):/) {
 2180:         # bad authentication scheme
 2181:         if (&Apache::lonnet::allowed('mau',$ccdomain)) {
 2182:             &initialize_authen_forms($ccdomain,$formname);
 2183: 
 2184:             my $choices = &Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc);
 2185:             $outcome = <<ENDBADAUTH;
 2186: <script type="text/javascript" language="Javascript">
 2187: // <![CDATA[
 2188: $loginscript
 2189: // ]]>
 2190: </script>
 2191: <span class="LC_error">$lt{'err'}:
 2192: $lt{'uuas'} ($currentauth). $lt{'sldb'}.</span>
 2193: <h3>$lt{'ld'}</h3>
 2194: $choices
 2195: ENDBADAUTH
 2196:         } else {
 2197:             # This user is not allowed to modify the user's
 2198:             # authentication scheme, so just notify them of the problem
 2199:             $outcome = <<ENDBADAUTH;
 2200: <span class="LC_error"> $lt{'err'}: 
 2201: $lt{'uuas'} ($currentauth). $lt{'adcs'}.
 2202: </span>
 2203: ENDBADAUTH
 2204:         }
 2205:     } else { # Authentication type is valid
 2206:         &initialize_authen_forms($ccdomain,$formname,$currentauth,'modifyuser');
 2207:         my ($authformcurrent,$can_modify,@authform_others) =
 2208:             &modify_login_block($ccdomain,$currentauth);
 2209:         if (&Apache::lonnet::allowed('mau',$ccdomain)) {
 2210:             # Current user has login modification privileges
 2211:             $outcome =
 2212:                        '<script type="text/javascript" language="Javascript">'."\n".
 2213:                        '// <![CDATA['."\n".
 2214:                        $loginscript."\n".
 2215:                        '// ]]>'."\n".
 2216:                        '</script>'."\n".
 2217:                        '<h3>'.$lt{'ld'}.'</h3>'.
 2218:                        &Apache::loncommon::start_data_table().
 2219:                        &Apache::loncommon::start_data_table_row().
 2220:                        '<td>'.$authformnop;
 2221:             if (($can_modify) && (&Apache::lonnet::allowed('mau',$ccdomain))) {
 2222:                 $outcome .= '</td>'."\n".
 2223:                             &Apache::loncommon::end_data_table_row().
 2224:                             &Apache::loncommon::start_data_table_row().
 2225:                             '<td>'.$authformcurrent.'</td>'.
 2226:                             &Apache::loncommon::end_data_table_row()."\n";
 2227:             } else {
 2228:                 $outcome .= '&nbsp;('.$authformcurrent.')</td>'.
 2229:                             &Apache::loncommon::end_data_table_row()."\n";
 2230:             }
 2231:             if (&Apache::lonnet::allowed('mau',$ccdomain)) {
 2232:                 foreach my $item (@authform_others) { 
 2233:                     $outcome .= &Apache::loncommon::start_data_table_row().
 2234:                                 '<td>'.$item.'</td>'.
 2235:                                 &Apache::loncommon::end_data_table_row()."\n";
 2236:                 }
 2237:             }
 2238:             $outcome .= &Apache::loncommon::end_data_table();
 2239:         } else {
 2240:             if (($currentauth =~ /^internal:/) &&
 2241:                 (&Apache::lonuserutils::can_change_internalpass($ccuname,$ccdomain,$crstype,$permission))) {
 2242:                 $outcome = <<"ENDJS";
 2243: <script type="text/javascript">
 2244: // <![CDATA[
 2245: function togglePwd(form) {
 2246:     if (form.newintpwd.length) {
 2247:         if (document.getElementById('LC_ownersetpwd')) {
 2248:             for (var i=0; i<form.newintpwd.length; i++) {
 2249:                 if (form.newintpwd[i].checked) {
 2250:                     if (form.newintpwd[i].value == 1) {
 2251:                         document.getElementById('LC_ownersetpwd').style.display = 'inline-block';
 2252:                     } else {
 2253:                         document.getElementById('LC_ownersetpwd').style.display = 'none';
 2254:                     }
 2255:                 }
 2256:             }
 2257:         }
 2258:     }
 2259: }
 2260: // ]]>
 2261: </script>
 2262: ENDJS
 2263: 
 2264:                 $outcome .= '<h3>'.$lt{'ld'}.'</h3>'.
 2265:                             &Apache::loncommon::start_data_table().
 2266:                             &Apache::loncommon::start_data_table_row().
 2267:                             '<td>'.&mt('Internally authenticated').'<br />'.&mt("Change user's password?").
 2268:                             '<label><input type="radio" name="newintpwd" value="0" checked="checked" onclick="togglePwd(this.form);" />'.
 2269:                             &mt('No').'</label>'.('&nbsp;'x2).
 2270:                             '<label><input type="radio" name="newintpwd" value="1" onclick="togglePwd(this.form);" />'.&mt('Yes').'</label>'.
 2271:                             '<div id="LC_ownersetpwd" style="display:none">'.
 2272:                             '&nbsp;&nbsp;'.&mt('Password').' <input type="password" size="15" name="intarg" value="" />'.
 2273:                             '<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>'.
 2274:                             &Apache::loncommon::end_data_table_row().
 2275:                             &Apache::loncommon::end_data_table();
 2276:             }
 2277:             if (&Apache::lonnet::allowed('udp',$ccdomain)) {
 2278:                 # Current user has rights to view domain preferences for user's domain
 2279:                 my $result;
 2280:                 if ($currentauth =~ /^krb(4|5):([^:]*)$/) {
 2281:                     my ($krbver,$krbrealm) = ($1,$2);
 2282:                     if ($krbrealm eq '') {
 2283:                         $result = &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
 2284:                     } else {
 2285:                         $result = &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
 2286:                                       $krbrealm,$krbver);
 2287:                     }
 2288:                 } elsif ($currentauth =~ /^internal:/) {
 2289:                     $result = &mt('Currently internally authenticated.');
 2290:                 } elsif ($currentauth =~ /^localauth:/) {
 2291:                     $result = &mt('Currently using local (institutional) authentication.');
 2292:                 } elsif ($currentauth =~ /^unix:/) {
 2293:                     $result = &mt('Currently Filesystem Authenticated.');
 2294:                 }
 2295:                 $outcome = '<h3>'.$lt{'ld'}.'</h3>'.
 2296:                            &Apache::loncommon::start_data_table().
 2297:                            &Apache::loncommon::start_data_table_row().
 2298:                            '<td>'.$result.'</td>'.
 2299:                            &Apache::loncommon::end_data_table_row()."\n".
 2300:                            &Apache::loncommon::end_data_table();
 2301:             } elsif (&Apache::lonnet::allowed('mau',$env{'request.role.domain'})) {
 2302:                 my %lt=&Apache::lonlocal::texthash(
 2303:                            'ccld'  => "Change Current Login Data",
 2304:                            'yodo'  => "You do not have privileges to modify the authentication configuration for this user.",
 2305:                            'ifch'  => "If a change is required, contact a domain coordinator for the domain",
 2306:                 );
 2307:                 $outcome .= <<ENDNOPRIV;
 2308: <h3>$lt{'ccld'}</h3>
 2309: $lt{'yodo'} $lt{'ifch'}: $ccdomain
 2310: <input type="hidden" name="login" value="nochange" />
 2311: ENDNOPRIV
 2312:             }
 2313:         }
 2314:     }  ## End of "check for bad authentication type" logic
 2315:     return $outcome;
 2316: }
 2317: 
 2318: sub modify_login_block {
 2319:     my ($dom,$currentauth) = @_;
 2320:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 2321:     my ($authnum,%can_assign) =
 2322:         &Apache::loncommon::get_assignable_auth($dom);
 2323:     my ($authformcurrent,@authform_others,$show_override_msg);
 2324:     if ($currentauth=~/^krb(4|5):/) {
 2325:         $authformcurrent=$authformkrb;
 2326:         if ($can_assign{'int'}) {
 2327:             push(@authform_others,$authformint);
 2328:         }
 2329:         if ($can_assign{'loc'}) {
 2330:             push(@authform_others,$authformloc);
 2331:         }
 2332:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2333:             $show_override_msg = 1;
 2334:         }
 2335:     } elsif ($currentauth=~/^internal:/) {
 2336:         $authformcurrent=$authformint;
 2337:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2338:             push(@authform_others,$authformkrb);
 2339:         }
 2340:         if ($can_assign{'loc'}) {
 2341:             push(@authform_others,$authformloc);
 2342:         }
 2343:         if ($can_assign{'int'}) {
 2344:             $show_override_msg = 1;
 2345:         }
 2346:     } elsif ($currentauth=~/^unix:/) {
 2347:         $authformcurrent=$authformfsys;
 2348:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2349:             push(@authform_others,$authformkrb);
 2350:         }
 2351:         if ($can_assign{'int'}) {
 2352:             push(@authform_others,$authformint);
 2353:         }
 2354:         if ($can_assign{'loc'}) {
 2355:             push(@authform_others,$authformloc);
 2356:         }
 2357:         if ($can_assign{'fsys'}) {
 2358:             $show_override_msg = 1;
 2359:         }
 2360:     } elsif ($currentauth=~/^localauth:/) {
 2361:         $authformcurrent=$authformloc;
 2362:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2363:             push(@authform_others,$authformkrb);
 2364:         }
 2365:         if ($can_assign{'int'}) {
 2366:             push(@authform_others,$authformint);
 2367:         }
 2368:         if ($can_assign{'loc'}) {
 2369:             $show_override_msg = 1;
 2370:         }
 2371:     }
 2372:     if ($show_override_msg) {
 2373:         $authformcurrent = '<table><tr><td colspan="3">'.$authformcurrent.
 2374:                            '</td></tr>'."\n".
 2375:                            '<tr><td>&nbsp;&nbsp;&nbsp;</td>'.
 2376:                            '<td><b>'.&mt('Currently in use').'</b></td>'.
 2377:                            '<td align="right"><span class="LC_cusr_emph">'.
 2378:                             &mt('will override current values').
 2379:                             '</span></td></tr></table>';
 2380:     }
 2381:     return ($authformcurrent,$show_override_msg,@authform_others); 
 2382: }
 2383: 
 2384: sub personal_data_display {
 2385:     my ($ccuname,$ccdomain,$newuser,$context,$inst_results,$rolesarray,$now,
 2386:         $captchaform,$emailusername,$usertype,$usernameset,$condition,$excluded,$showsubmit) = @_;
 2387:     my ($output,%userenv,%canmodify,%canmodify_status);
 2388:     my @userinfo = ('firstname','middlename','lastname','generation',
 2389:                     'permanentemail','id');
 2390:     my $rowcount = 0;
 2391:     my $editable = 0;
 2392:     my %textboxsize = (
 2393:                        firstname      => '15',
 2394:                        middlename     => '15',
 2395:                        lastname       => '15',
 2396:                        generation     => '5',
 2397:                        permanentemail => '25',
 2398:                        id             => '15',
 2399:                       );
 2400: 
 2401:     my %lt=&Apache::lonlocal::texthash(
 2402:                 'pd'             => "Personal Data",
 2403:                 'firstname'      => "First Name",
 2404:                 'middlename'     => "Middle Name",
 2405:                 'lastname'       => "Last Name",
 2406:                 'generation'     => "Generation",
 2407:                 'permanentemail' => "Permanent e-mail address",
 2408:                 'id'             => "Student/Employee ID",
 2409:                 'lg'             => "Login Data",
 2410:                 'inststatus'     => "Affiliation",
 2411:                 'email'          => 'E-mail address',
 2412:                 'valid'          => 'Validation',
 2413:                 'username'       => 'Username',
 2414:     );
 2415: 
 2416:     %canmodify_status =
 2417:         &Apache::lonuserutils::can_modify_userinfo($context,$ccdomain,
 2418:                                                    ['inststatus'],$rolesarray);
 2419:     if (!$newuser) {
 2420:         # Get the users information
 2421:         %userenv = &Apache::lonnet::get('environment',
 2422:                    ['firstname','middlename','lastname','generation',
 2423:                     'permanentemail','id','inststatus'],$ccdomain,$ccuname);
 2424:         %canmodify =
 2425:             &Apache::lonuserutils::can_modify_userinfo($context,$ccdomain,
 2426:                                                        \@userinfo,$rolesarray);
 2427:     } elsif ($context eq 'selfcreate') {
 2428:         if ($newuser eq 'email') {
 2429:             if (ref($emailusername) eq 'HASH') {
 2430:                 if (ref($emailusername->{$usertype}) eq 'HASH') {
 2431:                     my ($infofields,$infotitles) = &Apache::loncommon::emailusername_info();
 2432:                     @userinfo = ();
 2433:                     if ((ref($infofields) eq 'ARRAY') && (ref($infotitles) eq 'HASH')) {
 2434:                         foreach my $field (@{$infofields}) { 
 2435:                             if ($emailusername->{$usertype}->{$field}) {
 2436:                                 push(@userinfo,$field);
 2437:                                 $canmodify{$field} = 1;
 2438:                                 unless ($textboxsize{$field}) {
 2439:                                     $textboxsize{$field} = 25;
 2440:                                 }
 2441:                                 unless ($lt{$field}) {
 2442:                                     $lt{$field} = $infotitles->{$field};
 2443:                                 }
 2444:                                 if ($emailusername->{$usertype}->{$field} eq 'required') {
 2445:                                     $lt{$field} .= '<b>*</b>';
 2446:                                 }
 2447:                             }
 2448:                         }
 2449:                     }
 2450:                 }
 2451:             }
 2452:         } else {
 2453:             %canmodify = &selfcreate_canmodify($context,$ccdomain,\@userinfo,
 2454:                                                $inst_results,$rolesarray);
 2455:         }
 2456:     }
 2457: 
 2458:     my $genhelp=&Apache::loncommon::help_open_topic('Generation');
 2459:     $output = '<h3>'.$lt{'pd'}.'</h3>'.
 2460:               &Apache::lonhtmlcommon::start_pick_box();
 2461:     if (($context eq 'selfcreate') && ($newuser eq 'email')) {
 2462:         my $size = 25;
 2463:         if ($condition) {
 2464:             if ($condition =~ /^\@[^\@]+$/) {
 2465:                 $size = 10;
 2466:             } else {
 2467:                 undef($condition);
 2468:             }
 2469:         }
 2470:         if ($excluded) {
 2471:             unless ($excluded =~ /^\@[^\@]+$/) {
 2472:                 undef($condition);
 2473:             }
 2474:         }
 2475:         $output .= &Apache::lonhtmlcommon::row_title($lt{'email'}.'<b>*</b>',undef,
 2476:                                                      'LC_oddrow_value')."\n".
 2477:                    '<input type="text" name="uname" size="'.$size.'" value="" autocomplete="off" />';
 2478:         if ($condition) {
 2479:             $output .= $condition;
 2480:         } elsif ($excluded) {
 2481:             $output .= '<br /><span style="font-size: smaller">'.&mt('You must use an e-mail address that does not end with [_1]',
 2482:                                                                      $excluded).'</span>';
 2483:         }
 2484:         if ($usernameset eq 'first') {
 2485:             $output .= '<br /><span style="font-size: smaller">';
 2486:             if ($condition) {
 2487:                 $output .= &mt('Your username in LON-CAPA will be the part of your e-mail address before [_1]',
 2488:                                       $condition);
 2489:             } else {
 2490:                 $output .= &mt('Your username in LON-CAPA will be the part of your e-mail address before the @');
 2491:             }
 2492:             $output .= '</span>';
 2493:         }
 2494:         $rowcount ++;
 2495:         $output .= &Apache::lonhtmlcommon::row_closure(1);
 2496:         my $upassone = '<input type="password" name="upass'.$now.'" size="20" autocomplete="off" />';
 2497:         my $upasstwo = '<input type="password" name="upasscheck'.$now.'" size="20" autocomplete="off" />';
 2498:         $output .= &Apache::lonhtmlcommon::row_title(&mt('Password').'<b>*</b>',
 2499:                                                     'LC_pick_box_title',
 2500:                                                     'LC_oddrow_value')."\n".
 2501:                    $upassone."\n".
 2502:                    &Apache::lonhtmlcommon::row_closure(1)."\n".
 2503:                    &Apache::lonhtmlcommon::row_title(&mt('Confirm password').'<b>*</b>',
 2504:                                                      'LC_pick_box_title',
 2505:                                                      'LC_oddrow_value')."\n".
 2506:                    $upasstwo.
 2507:                    &Apache::lonhtmlcommon::row_closure()."\n";
 2508:         if ($usernameset eq 'free') {
 2509:             my $onclick = "toggleUsernameDisp(this,'selfcreateusername');";
 2510:             $output .= &Apache::lonhtmlcommon::row_title($lt{'username'},undef,'LC_oddrow_value')."\n".
 2511:                        '<span class="LC_nobreak">'.&mt('Use e-mail address: ').
 2512:                        '<label><input type="radio" name="emailused" value="1" checked="checked" onclick="'.$onclick.'" />'.
 2513:                        &mt('Yes').'</label>'.('&nbsp;'x2).
 2514:                        '<label><input type="radio" name="emailused" value="0" onclick="'.$onclick.'" />'.
 2515:                        &mt('No').'</label></span>'."\n".
 2516:                        '<div id="selfcreateusername" style="display: none; font-size: smaller">'.
 2517:                        '<br /><span class="LC_nobreak">'.&mt('Preferred username').
 2518:                        '&nbsp;<input type="text" name="username" value="" size="20" autocomplete="off"/>'.
 2519:                        '</span></div>'."\n".&Apache::lonhtmlcommon::row_closure(1);
 2520:             $rowcount ++;
 2521:         }
 2522:     }
 2523:     foreach my $item (@userinfo) {
 2524:         my $rowtitle = $lt{$item};
 2525:         my $hiderow = 0;
 2526:         if ($item eq 'generation') {
 2527:             $rowtitle = $genhelp.$rowtitle;
 2528:         }
 2529:         my $row = &Apache::lonhtmlcommon::row_title($rowtitle,undef,'LC_oddrow_value')."\n";
 2530:         if ($newuser) {
 2531:             if (ref($inst_results) eq 'HASH') {
 2532:                 if ($inst_results->{$item} ne '') {
 2533:                     $row .= '<input type="hidden" name="c'.$item.'" value="'.$inst_results->{$item}.'" />'.$inst_results->{$item};
 2534:                 } else {
 2535:                     if ($context eq 'selfcreate') {
 2536:                         if ($canmodify{$item}) {
 2537:                             $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="" autocomplete="off" />';
 2538:                             $editable ++;
 2539:                         } else {
 2540:                             $hiderow = 1;
 2541:                         }
 2542:                     } else {
 2543:                         $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="" />';
 2544:                     }
 2545:                 }
 2546:             } else {
 2547:                 if ($context eq 'selfcreate') {
 2548:                     if ($canmodify{$item}) {
 2549:                         if ($newuser eq 'email') {
 2550:                             $row .= '<input type="text" name="'.$item.'" size="'.$textboxsize{$item}.'" value="" autocomplete="off" />';
 2551:                         } else {
 2552:                             $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="" autocomplete="off" />';
 2553:                         }
 2554:                         $editable ++;
 2555:                     } else {
 2556:                         $hiderow = 1;
 2557:                     }
 2558:                 } else {
 2559:                     $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="" />';
 2560:                 }
 2561:             }
 2562:         } else {
 2563:             if ($canmodify{$item}) {
 2564:                 $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="'.$userenv{$item}.'" />';
 2565:                 if (($item eq 'id') && (!$newuser)) {
 2566:                     $row .= '<br />'.&Apache::lonuserutils::forceid_change($context);
 2567:                 }
 2568:             } else {
 2569:                 $row .= $userenv{$item};
 2570:             }
 2571:         }
 2572:         $row .= &Apache::lonhtmlcommon::row_closure(1);
 2573:         if (!$hiderow) {
 2574:             $output .= $row;
 2575:             $rowcount ++;
 2576:         }
 2577:     }
 2578:     if (($canmodify_status{'inststatus'}) || ($context ne 'selfcreate')) {
 2579:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($ccdomain);
 2580:         if (ref($types) eq 'ARRAY') {
 2581:             if (@{$types} > 0) {
 2582:                 my ($hiderow,$shown);
 2583:                 if ($canmodify_status{'inststatus'}) {
 2584:                     $shown = &pick_inst_statuses($userenv{'inststatus'},$usertypes,$types);
 2585:                 } else {
 2586:                     if ($userenv{'inststatus'} eq '') {
 2587:                         $hiderow = 1;
 2588:                     } else {
 2589:                         my @showitems;
 2590:                         foreach my $item ( map { &unescape($_); } split(':',$userenv{'inststatus'})) {
 2591:                             if (exists($usertypes->{$item})) {
 2592:                                 push(@showitems,$usertypes->{$item});
 2593:                             } else {
 2594:                                 push(@showitems,$item);
 2595:                             }
 2596:                         }
 2597:                         if (@showitems) {
 2598:                             $shown = join(', ',@showitems);
 2599:                         } else {
 2600:                             $hiderow = 1;
 2601:                         }
 2602:                     }
 2603:                 }
 2604:                 if (!$hiderow) {
 2605:                     my $row = &Apache::lonhtmlcommon::row_title(&mt('Affiliations'),undef,'LC_oddrow_value')."\n".
 2606:                               $shown.&Apache::lonhtmlcommon::row_closure(1); 
 2607:                     if ($context eq 'selfcreate') {
 2608:                         $rowcount ++;
 2609:                     }
 2610:                     $output .= $row;
 2611:                 }
 2612:             }
 2613:         }
 2614:     }
 2615:     if (($context eq 'selfcreate') && ($newuser eq 'email')) {
 2616:         if ($captchaform) {
 2617:             $output .= &Apache::lonhtmlcommon::row_title($lt{'valid'}.'*',
 2618:                                                          'LC_pick_box_title')."\n".
 2619:                        $captchaform."\n".'<br /><br />'.
 2620:                        &Apache::lonhtmlcommon::row_closure(1); 
 2621:             $rowcount ++;
 2622:         }
 2623:         if ($showsubmit) {
 2624:             my $submit_text = &mt('Create account');
 2625:             $output .= &Apache::lonhtmlcommon::row_title()."\n".
 2626:                        '<br /><input type="submit" name="createaccount" value="'.
 2627:                        $submit_text.'" />';
 2628:             if ($usertype ne '') {
 2629:                 $output .= '<input type="hidden" name="type" value="'.$usertype.'" />'.
 2630:                            &Apache::lonhtmlcommon::row_closure(1);
 2631:             }
 2632:         }
 2633:     }
 2634:     $output .= &Apache::lonhtmlcommon::end_pick_box();
 2635:     if (wantarray) {
 2636:         if ($context eq 'selfcreate') {
 2637:             return($output,$rowcount,$editable);
 2638:         } else {
 2639:             return $output;
 2640:         }
 2641:     } else {
 2642:         return $output;
 2643:     }
 2644: }
 2645: 
 2646: sub pick_inst_statuses {
 2647:     my ($curr,$usertypes,$types) = @_;
 2648:     my ($output,$rem,@currtypes);
 2649:     if ($curr ne '') {
 2650:         @currtypes = map { &unescape($_); } split(/:/,$curr);
 2651:     }
 2652:     my $numinrow = 2;
 2653:     if (ref($types) eq 'ARRAY') {
 2654:         $output = '<table>';
 2655:         my $lastcolspan; 
 2656:         for (my $i=0; $i<@{$types}; $i++) {
 2657:             if (defined($usertypes->{$types->[$i]})) {
 2658:                 my $rem = $i%($numinrow);
 2659:                 if ($rem == 0) {
 2660:                     if ($i<@{$types}-1) {
 2661:                         if ($i > 0) { 
 2662:                             $output .= '</tr>';
 2663:                         }
 2664:                         $output .= '<tr>';
 2665:                     }
 2666:                 } elsif ($i==@{$types}-1) {
 2667:                     my $colsleft = $numinrow - $rem;
 2668:                     if ($colsleft > 1) {
 2669:                         $lastcolspan = ' colspan="'.$colsleft.'"';
 2670:                     }
 2671:                 }
 2672:                 my $check = ' ';
 2673:                 if (grep(/^\Q$types->[$i]\E$/,@currtypes)) {
 2674:                     $check = ' checked="checked" ';
 2675:                 }
 2676:                 $output .= '<td class="LC_left_item"'.$lastcolspan.'>'.
 2677:                            '<span class="LC_nobreak"><label>'.
 2678:                            '<input type="checkbox" name="inststatus" '.
 2679:                            'value="'.$types->[$i].'"'.$check.'/>'.
 2680:                            $usertypes->{$types->[$i]}.'</label></span></td>';
 2681:             }
 2682:         }
 2683:         $output .= '</tr></table>';
 2684:     }
 2685:     return $output;
 2686: }
 2687: 
 2688: sub selfcreate_canmodify {
 2689:     my ($context,$dom,$userinfo,$inst_results,$rolesarray) = @_;
 2690:     if (ref($inst_results) eq 'HASH') {
 2691:         my @inststatuses = &get_inststatuses($inst_results);
 2692:         if (@inststatuses == 0) {
 2693:             @inststatuses = ('default');
 2694:         }
 2695:         $rolesarray = \@inststatuses;
 2696:     }
 2697:     my %canmodify =
 2698:         &Apache::lonuserutils::can_modify_userinfo($context,$dom,$userinfo,
 2699:                                                    $rolesarray);
 2700:     return %canmodify;
 2701: }
 2702: 
 2703: sub get_inststatuses {
 2704:     my ($insthashref) = @_;
 2705:     my @inststatuses = ();
 2706:     if (ref($insthashref) eq 'HASH') {
 2707:         if (ref($insthashref->{'inststatus'}) eq 'ARRAY') {
 2708:             @inststatuses = @{$insthashref->{'inststatus'}};
 2709:         }
 2710:     }
 2711:     return @inststatuses;
 2712: }
 2713: 
 2714: # ================================================================= Phase Three
 2715: sub update_user_data {
 2716:     my ($r,$context,$crstype,$brcrum,$showcredits,$permission) = @_; 
 2717:     my $uhome=&Apache::lonnet::homeserver($env{'form.ccuname'},
 2718:                                           $env{'form.ccdomain'});
 2719:     # Error messages
 2720:     my $error     = '<span class="LC_error">'.&mt('Error').': ';
 2721:     my $end       = '</span><br /><br />';
 2722:     my $rtnlink   = '<a href="javascript:backPage(document.userupdate,'.
 2723:                     "'$env{'form.prevphase'}','modify')".'" />'.
 2724:                     &mt('Return to previous page').'</a>'.
 2725:                     &Apache::loncommon::end_page();
 2726:     my $now = time;
 2727:     my $title;
 2728:     if (exists($env{'form.makeuser'})) {
 2729: 	$title='Set Privileges for New User';
 2730:     } else {
 2731:         $title='Modify User Privileges';
 2732:     }
 2733:     my $newuser = 0;
 2734:     my ($jsback,$elements) = &crumb_utilities();
 2735:     my $jscript = '<script type="text/javascript">'."\n".
 2736:                   '// <![CDATA['."\n".
 2737:                   $jsback."\n".
 2738:                   '// ]]>'."\n".
 2739:                   '</script>'."\n";
 2740:     my %breadcrumb_text = &singleuser_breadcrumb($crstype,$context,$env{'form.ccdomain'});
 2741:     push (@{$brcrum},
 2742:              {href => "javascript:backPage(document.userupdate)",
 2743:               text => $breadcrumb_text{'search'},
 2744:               faq  => 282,
 2745:               bug  => 'Instructor Interface',}
 2746:              );
 2747:     if ($env{'form.prevphase'} eq 'userpicked') {
 2748:         push(@{$brcrum},
 2749:                {href => "javascript:backPage(document.userupdate,'get_user_info','select')",
 2750:                 text => $breadcrumb_text{'userpicked'},
 2751:                 faq  => 282,
 2752:                 bug  => 'Instructor Interface',});
 2753:     }
 2754:     my $helpitem = 'Course_Change_Privileges';
 2755:     if ($env{'form.action'} eq 'singlestudent') {
 2756:         $helpitem = 'Course_Add_Student';
 2757:     } elsif ($context eq 'author') {
 2758:         $helpitem = 'Author_Change_Privileges';
 2759:     } elsif ($context eq 'domain') {
 2760:         $helpitem = 'Domain_Change_Privileges';
 2761:     }
 2762:     push(@{$brcrum}, 
 2763:             {href => "javascript:backPage(document.userupdate,'$env{'form.prevphase'}','modify')",
 2764:              text => $breadcrumb_text{'modify'},
 2765:              faq  => 282,
 2766:              bug  => 'Instructor Interface',},
 2767:             {href => "/adm/createuser",
 2768:              text => "Result",
 2769:              faq  => 282,
 2770:              bug  => 'Instructor Interface',
 2771:              help => $helpitem});
 2772:     my $args = {bread_crumbs          => $brcrum,
 2773:                 bread_crumbs_component => 'User Management'};
 2774:     if ($env{'form.popup'}) {
 2775:         $args->{'no_nav_bar'} = 1;
 2776:     }
 2777:     $r->print(&Apache::loncommon::start_page($title,$jscript,$args));
 2778:     $r->print(&update_result_form($uhome));
 2779:     # Check Inputs
 2780:     if (! $env{'form.ccuname'} ) {
 2781: 	$r->print($error.&mt('No login name specified').'.'.$end.$rtnlink);
 2782: 	return;
 2783:     }
 2784:     if (  $env{'form.ccuname'} ne 
 2785: 	  &LONCAPA::clean_username($env{'form.ccuname'}) ) {
 2786: 	$r->print($error.&mt('Invalid login name.').'  '.
 2787: 		  &mt('Only letters, numbers, periods, dashes, @, and underscores are valid.').
 2788: 		  $end.$rtnlink);
 2789: 	return;
 2790:     }
 2791:     if (! $env{'form.ccdomain'}       ) {
 2792: 	$r->print($error.&mt('No domain specified').'.'.$end.$rtnlink);
 2793: 	return;
 2794:     }
 2795:     if (  $env{'form.ccdomain'} ne
 2796: 	  &LONCAPA::clean_domain($env{'form.ccdomain'}) ) {
 2797: 	$r->print($error.&mt('Invalid domain name.').'  '.
 2798: 		  &mt('Only letters, numbers, periods, dashes, and underscores are valid.').
 2799: 		  $end.$rtnlink);
 2800: 	return;
 2801:     }
 2802:     if ($uhome eq 'no_host') {
 2803:         $newuser = 1;
 2804:     }
 2805:     if (! exists($env{'form.makeuser'})) {
 2806:         # Modifying an existing user, so check the validity of the name
 2807:         if ($uhome eq 'no_host') {
 2808:             $r->print(
 2809:                 $error
 2810:                .'<p class="LC_error">'
 2811:                .&mt('Unable to determine home server for [_1] in domain [_2].',
 2812:                         '"'.$env{'form.ccuname'}.'"','"'.$env{'form.ccdomain'}.'"')
 2813:                .'</p>');
 2814:             return;
 2815:         }
 2816:     }
 2817:     # Determine authentication method and password for the user being modified
 2818:     my $amode='';
 2819:     my $genpwd='';
 2820:     if ($env{'form.login'} eq 'krb') {
 2821: 	$amode='krb';
 2822: 	$amode.=$env{'form.krbver'};
 2823: 	$genpwd=$env{'form.krbarg'};
 2824:     } elsif ($env{'form.login'} eq 'int') {
 2825: 	$amode='internal';
 2826: 	$genpwd=$env{'form.intarg'};
 2827:     } elsif ($env{'form.login'} eq 'fsys') {
 2828: 	$amode='unix';
 2829: 	$genpwd=$env{'form.fsysarg'};
 2830:     } elsif ($env{'form.login'} eq 'loc') {
 2831: 	$amode='localauth';
 2832: 	$genpwd=$env{'form.locarg'};
 2833: 	$genpwd=" " if (!$genpwd);
 2834:     } elsif (($env{'form.login'} eq 'nochange') ||
 2835:              ($env{'form.login'} eq ''        )) { 
 2836:         # There is no need to tell the user we did not change what they
 2837:         # did not ask us to change.
 2838:         # If they are creating a new user but have not specified login
 2839:         # information this will be caught below.
 2840:     } else {
 2841:             $r->print($error.&mt('Invalid login mode or password').$end.$rtnlink);
 2842:             return;
 2843:     }
 2844: 
 2845:     $r->print('<h3>'.&mt('User [_1] in domain [_2]',
 2846:                         $env{'form.ccuname'}.' ('.&Apache::loncommon::plainname($env{'form.ccuname'},
 2847:                         $env{'form.ccdomain'}).')', $env{'form.ccdomain'}).'</h3>');
 2848:     my %prog_state = &Apache::lonhtmlcommon::Create_PrgWin($r,2);
 2849: 
 2850:     my (%alerts,%rulematch,%inst_results,%curr_rules);
 2851:     my @userinfo = ('firstname','middlename','lastname','generation','permanentemail','id');
 2852:     my @usertools = ('aboutme','blog','webdav','portfolio');
 2853:     my @requestcourses = ('official','unofficial','community','textbook');
 2854:     my @requestauthor = ('requestauthor');
 2855:     my ($othertitle,$usertypes,$types) = 
 2856:         &Apache::loncommon::sorted_inst_types($env{'form.ccdomain'});
 2857:     my %canmodify_status =
 2858:         &Apache::lonuserutils::can_modify_userinfo($context,$env{'form.ccdomain'},
 2859:                                                    ['inststatus']);
 2860:     if ($env{'form.makeuser'}) {
 2861: 	$r->print('<h3>'.&mt('Creating new account.').'</h3>');
 2862:         # Check for the authentication mode and password
 2863:         if (! $amode || ! $genpwd) {
 2864: 	    $r->print($error.&mt('Invalid login mode or password').$end.$rtnlink);    
 2865: 	    return;
 2866: 	}
 2867:         # Determine desired host
 2868:         my $desiredhost = $env{'form.hserver'};
 2869:         if (lc($desiredhost) eq 'default') {
 2870:             $desiredhost = undef;
 2871:         } else {
 2872:             my %home_servers = 
 2873: 		&Apache::lonnet::get_servers($env{'form.ccdomain'},'library');
 2874:             if (! exists($home_servers{$desiredhost})) {
 2875:                 $r->print($error.&mt('Invalid home server specified').$end.$rtnlink);
 2876:                 return;
 2877:             }
 2878:         }
 2879:         # Check ID format
 2880:         my %checkhash;
 2881:         my %checks = ('id' => 1);
 2882:         %{$checkhash{$env{'form.ccuname'}.':'.$env{'form.ccdomain'}}} = (
 2883:             'newuser' => $newuser, 
 2884:             'id' => $env{'form.cid'},
 2885:         );
 2886:         if ($env{'form.cid'} ne '') {
 2887:             &Apache::loncommon::user_rule_check(\%checkhash,\%checks,\%alerts,
 2888:                                           \%rulematch,\%inst_results,\%curr_rules);
 2889:             if (ref($alerts{'id'}) eq 'HASH') {
 2890:                 if (ref($alerts{'id'}{$env{'form.ccdomain'}}) eq 'HASH') {
 2891:                     my $domdesc =
 2892:                         &Apache::lonnet::domain($env{'form.ccdomain'},'description');
 2893:                     if ($alerts{'id'}{$env{'form.ccdomain'}}{$env{'form.cid'}}) {
 2894:                         my $userchkmsg;
 2895:                         if (ref($curr_rules{$env{'form.ccdomain'}}) eq 'HASH') {
 2896:                             $userchkmsg  = 
 2897:                                 &Apache::loncommon::instrule_disallow_msg('id',
 2898:                                                                     $domdesc,1).
 2899:                                 &Apache::loncommon::user_rule_formats($env{'form.ccdomain'},
 2900:                                     $domdesc,$curr_rules{$env{'form.ccdomain'}}{'id'},'id');
 2901:                         }
 2902:                         $r->print($error.&mt('Invalid ID format').$end.
 2903:                                   $userchkmsg.$rtnlink);
 2904:                         return;
 2905:                     }
 2906:                 }
 2907:             }
 2908:         }
 2909:         &Apache::lonhtmlcommon::Increment_PrgWin($r, \%prog_state);
 2910: 	# Call modifyuser
 2911: 	my $result = &Apache::lonnet::modifyuser
 2912: 	    ($env{'form.ccdomain'},$env{'form.ccuname'},$env{'form.cid'},
 2913:              $amode,$genpwd,$env{'form.cfirstname'},
 2914:              $env{'form.cmiddlename'},$env{'form.clastname'},
 2915:              $env{'form.cgeneration'},undef,$desiredhost,
 2916:              $env{'form.cpermanentemail'});
 2917: 	$r->print(&mt('Generating user').': '.$result);
 2918:         $uhome = &Apache::lonnet::homeserver($env{'form.ccuname'},
 2919:                                                $env{'form.ccdomain'});
 2920:         my (%changeHash,%newcustom,%changed,%changedinfo);
 2921:         if ($uhome ne 'no_host') {
 2922:             if ($context eq 'domain') {
 2923:                 foreach my $name ('portfolio','author') {
 2924:                     if ($env{'form.custom_'.$name.'quota'} == 1) {
 2925:                         if ($env{'form.'.$name.'quota'} eq '') {
 2926:                             $newcustom{$name.'quota'} = 0;
 2927:                         } else {
 2928:                             $newcustom{$name.'quota'} = $env{'form.'.$name.'quota'};
 2929:                             $newcustom{$name.'quota'} =~ s/[^\d\.]//g;
 2930:                         }
 2931:                         if (&quota_admin($newcustom{$name.'quota'},\%changeHash,$name)) {
 2932:                             $changed{$name.'quota'} = 1;
 2933:                         }
 2934:                     }
 2935:                 }
 2936:                 foreach my $item (@usertools) {
 2937:                     if ($env{'form.custom'.$item} == 1) {
 2938:                         $newcustom{$item} = $env{'form.tools_'.$item};
 2939:                         $changed{$item} = &tool_admin($item,$newcustom{$item},
 2940:                                                      \%changeHash,'tools');
 2941:                     }
 2942:                 }
 2943:                 foreach my $item (@requestcourses) {
 2944:                     if ($env{'form.custom'.$item} == 1) {
 2945:                         $newcustom{$item} = $env{'form.crsreq_'.$item};
 2946:                         if ($env{'form.crsreq_'.$item} eq 'autolimit') {
 2947:                             $newcustom{$item} .= '=';
 2948:                             $env{'form.crsreq_'.$item.'_limit'} =~ s/\D+//g;
 2949:                             if ($env{'form.crsreq_'.$item.'_limit'}) {
 2950:                                 $newcustom{$item} .= $env{'form.crsreq_'.$item.'_limit'};
 2951:                             }
 2952:                         }
 2953:                         $changed{$item} = &tool_admin($item,$newcustom{$item},
 2954:                                                       \%changeHash,'requestcourses');
 2955:                     }
 2956:                 }
 2957:                 if ($env{'form.customrequestauthor'} == 1) {
 2958:                     $newcustom{'requestauthor'} = $env{'form.requestauthor'};
 2959:                     $changed{'requestauthor'} = &tool_admin('requestauthor',
 2960:                                                     $newcustom{'requestauthor'},
 2961:                                                     \%changeHash,'requestauthor');
 2962:                 }
 2963:             }
 2964:             if ($canmodify_status{'inststatus'}) {
 2965:                 if (exists($env{'form.inststatus'})) {
 2966:                     my @inststatuses = &Apache::loncommon::get_env_multiple('form.inststatus');
 2967:                     if (@inststatuses > 0) {
 2968:                         $changeHash{'inststatus'} = join(',',@inststatuses);
 2969:                         $changed{'inststatus'} = $changeHash{'inststatus'};
 2970:                     }
 2971:                 }
 2972:             }
 2973:             if (keys(%changed)) {
 2974:                 foreach my $item (@userinfo) {
 2975:                     $changeHash{$item}  = $env{'form.c'.$item};
 2976:                 }
 2977:                 my $chgresult =
 2978:                      &Apache::lonnet::put('environment',\%changeHash,
 2979:                                           $env{'form.ccdomain'},$env{'form.ccuname'});
 2980:             } 
 2981:         }
 2982:         $r->print('<br />'.&mt('Home Server').': '.$uhome.' '.
 2983:                   &Apache::lonnet::hostname($uhome));
 2984:     } elsif (($env{'form.login'} ne 'nochange') &&
 2985:              ($env{'form.login'} ne ''        )) {
 2986: 	# Modify user privileges
 2987:         if (! $amode || ! $genpwd) {
 2988: 	    $r->print($error.'Invalid login mode or password'.$end.$rtnlink);    
 2989: 	    return;
 2990: 	}
 2991: 	# Only allow authentication modification if the person has authority
 2992: 	if (&Apache::lonnet::allowed('mau',$env{'form.ccdomain'})) {
 2993: 	    $r->print('Modifying authentication: '.
 2994:                       &Apache::lonnet::modifyuserauth(
 2995: 		       $env{'form.ccdomain'},$env{'form.ccuname'},
 2996:                        $amode,$genpwd));
 2997:             $r->print('<br />'.&mt('Home Server').': '.&Apache::lonnet::homeserver
 2998: 		  ($env{'form.ccuname'},$env{'form.ccdomain'}));
 2999: 	} else {
 3000: 	    # Okay, this is a non-fatal error.
 3001: 	    $r->print($error.&mt('You do not have privileges to modify the authentication configuration for this user.').$end);    
 3002: 	}
 3003:     } elsif (($env{'form.intarg'} ne '') &&
 3004:              (&Apache::lonnet::queryauthenticate($env{'form.ccuname'},$env{'form.ccdomain'}) =~ /^internal:/) &&
 3005:              (&Apache::lonuserutils::can_change_internalpass($env{'form.ccuname'},$env{'form.ccdomain'},$crstype,$permission))) {
 3006:         $r->print('Modifying authentication: '.
 3007:                   &Apache::lonnet::modifyuserauth(
 3008:                   $env{'form.ccdomain'},$env{'form.ccuname'},
 3009:                   'internal',$env{'form.intarg'}));
 3010:     }
 3011:     $r->rflush(); # Finish display of header before time consuming actions start
 3012:     &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state);
 3013:     ##
 3014:     my (@userroles,%userupdate,$cnum,$cdom,$defaultcredits,%namechanged);
 3015:     if ($context eq 'course') {
 3016:         ($cnum,$cdom) =
 3017:             &Apache::lonuserutils::get_course_identity();
 3018:         $crstype = &Apache::loncommon::course_type($cdom.'_'.$cnum);
 3019:         if ($showcredits) {
 3020:            $defaultcredits = &Apache::lonuserutils::get_defaultcredits($cdom,$cnum);
 3021:         }
 3022:     }
 3023:     if (! $env{'form.makeuser'} ) {
 3024:         # Check for need to change
 3025:         my %userenv = &Apache::lonnet::get
 3026:             ('environment',['firstname','middlename','lastname','generation',
 3027:              'id','permanentemail','portfolioquota','authorquota','inststatus',
 3028:              'tools.aboutme','tools.blog','tools.webdav','tools.portfolio',
 3029:              'requestcourses.official','requestcourses.unofficial',
 3030:              'requestcourses.community','requestcourses.textbook',
 3031:              'reqcrsotherdom.official','reqcrsotherdom.unofficial',
 3032:              'reqcrsotherdom.community','reqcrsotherdom.textbook',
 3033:              'requestauthor'],
 3034:               $env{'form.ccdomain'},$env{'form.ccuname'});
 3035:         my ($tmp) = keys(%userenv);
 3036:         if ($tmp =~ /^(con_lost|error)/i) { 
 3037:             %userenv = ();
 3038:         }
 3039:         my $no_forceid_alert;
 3040:         # Check to see if user information can be changed
 3041:         my %domconfig =
 3042:             &Apache::lonnet::get_dom('configuration',['usermodification'],
 3043:                                      $env{'form.ccdomain'});
 3044:         my @statuses = ('active','future');
 3045:         my %roles = &Apache::lonnet::get_my_roles($env{'form.ccuname'},$env{'form.ccdomain'},'userroles',\@statuses,undef,$env{'request.role.domain'});
 3046:         my ($auname,$audom);
 3047:         if ($context eq 'author') {
 3048:             $auname = $env{'user.name'};
 3049:             $audom = $env{'user.domain'};     
 3050:         }
 3051:         foreach my $item (keys(%roles)) {
 3052:             my ($rolenum,$roledom,$role) = split(/:/,$item,-1);
 3053:             if ($context eq 'course') {
 3054:                 if ($cnum ne '' && $cdom ne '') {
 3055:                     if ($rolenum eq $cnum && $roledom eq $cdom) {
 3056:                         if (!grep(/^\Q$role\E$/,@userroles)) {
 3057:                             push(@userroles,$role);
 3058:                         }
 3059:                     }
 3060:                 }
 3061:             } elsif ($context eq 'author') {
 3062:                 if ($rolenum eq $auname && $roledom eq $audom) {
 3063:                     if (!grep(/^\Q$role\E$/,@userroles)) { 
 3064:                         push(@userroles,$role);
 3065:                     }
 3066:                 }
 3067:             }
 3068:         }
 3069:         if ($env{'form.action'} eq 'singlestudent') {
 3070:             if (!grep(/^st$/,@userroles)) {
 3071:                 push(@userroles,'st');
 3072:             }
 3073:         } else {
 3074:             # Check for course or co-author roles being activated or re-enabled
 3075:             if ($context eq 'author' || $context eq 'course') {
 3076:                 foreach my $key (keys(%env)) {
 3077:                     if ($context eq 'author') {
 3078:                         if ($key=~/^form\.act_\Q$audom\E_\Q$auname\E_([^_]+)/) {
 3079:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 3080:                                 push(@userroles,$1);
 3081:                             }
 3082:                         } elsif ($key =~/^form\.ren\:\Q$audom\E\/\Q$auname\E_([^_]+)/) {
 3083:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 3084:                                 push(@userroles,$1);
 3085:                             }
 3086:                         }
 3087:                     } elsif ($context eq 'course') {
 3088:                         if ($key=~/^form\.act_\Q$cdom\E_\Q$cnum\E_([^_]+)/) {
 3089:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 3090:                                 push(@userroles,$1);
 3091:                             }
 3092:                         } elsif ($key =~/^form\.ren\:\Q$cdom\E\/\Q$cnum\E(\/?\w*)_([^_]+)/) {
 3093:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 3094:                                 push(@userroles,$1);
 3095:                             }
 3096:                         }
 3097:                     }
 3098:                 }
 3099:             }
 3100:         }
 3101:         #Check to see if we can change personal data for the user 
 3102:         my (@mod_disallowed,@longroles);
 3103:         foreach my $role (@userroles) {
 3104:             if ($role eq 'cr') {
 3105:                 push(@longroles,'Custom');
 3106:             } else {
 3107:                 push(@longroles,&Apache::lonnet::plaintext($role,$crstype)); 
 3108:             }
 3109:         }
 3110:         my %canmodify = &Apache::lonuserutils::can_modify_userinfo($context,$env{'form.ccdomain'},\@userinfo,\@userroles);
 3111:         foreach my $item (@userinfo) {
 3112:             # Strip leading and trailing whitespace
 3113:             $env{'form.c'.$item} =~ s/(\s+$|^\s+)//g;
 3114:             if (!$canmodify{$item}) {
 3115:                 if (defined($env{'form.c'.$item})) {
 3116:                     if ($env{'form.c'.$item} ne $userenv{$item}) {
 3117:                         push(@mod_disallowed,$item);
 3118:                     }
 3119:                 }
 3120:                 $env{'form.c'.$item} = $userenv{$item};
 3121:             }
 3122:         }
 3123:         # Check to see if we can change the Student/Employee ID
 3124:         my $forceid = $env{'form.forceid'};
 3125:         my $recurseid = $env{'form.recurseid'};
 3126:         my (%alerts,%rulematch,%idinst_results,%curr_rules,%got_rules);
 3127:         my %uidhash = &Apache::lonnet::idrget($env{'form.ccdomain'},
 3128:                                             $env{'form.ccuname'});
 3129:         if (($uidhash{$env{'form.ccuname'}}) && 
 3130:             ($uidhash{$env{'form.ccuname'}}!~/error\:/) && 
 3131:             (!$forceid)) {
 3132:             if ($env{'form.cid'} ne $uidhash{$env{'form.ccuname'}}) {
 3133:                 $env{'form.cid'} = $userenv{'id'};
 3134:                 $no_forceid_alert = &mt('New student/employee ID does not match existing ID for this user.')
 3135:                                    .'<br />'
 3136:                                    .&mt("Change is not permitted without checking the 'Force ID change' checkbox on the previous page.")
 3137:                                    .'<br />'."\n";
 3138:             }
 3139:         }
 3140:         if ($env{'form.cid'} ne $userenv{'id'}) {
 3141:             my $checkhash;
 3142:             my $checks = { 'id' => 1 };
 3143:             $checkhash->{$env{'form.ccuname'}.':'.$env{'form.ccdomain'}} = 
 3144:                    { 'newuser' => $newuser,
 3145:                      'id'  => $env{'form.cid'}, 
 3146:                    };
 3147:             &Apache::loncommon::user_rule_check($checkhash,$checks,
 3148:                 \%alerts,\%rulematch,\%idinst_results,\%curr_rules,\%got_rules);
 3149:             if (ref($alerts{'id'}) eq 'HASH') {
 3150:                 if (ref($alerts{'id'}{$env{'form.ccdomain'}}) eq 'HASH') {
 3151:                    $env{'form.cid'} = $userenv{'id'};
 3152:                 }
 3153:             }
 3154:         }
 3155:         my (%quotachanged,%oldquota,%newquota,%olddefquota,%newdefquota, 
 3156:             $oldinststatus,$newinststatus,%oldisdefault,%newisdefault,%oldsettings,
 3157:             %oldsettingstext,%newsettings,%newsettingstext,@disporder,
 3158:             %oldsettingstatus,%newsettingstatus);
 3159:         @disporder = ('inststatus');
 3160:         if ($env{'request.role.domain'} eq $env{'form.ccdomain'}) {
 3161:             push(@disporder,'requestcourses','requestauthor');
 3162:         } else {
 3163:             push(@disporder,'reqcrsotherdom');
 3164:         }
 3165:         push(@disporder,('quota','tools'));
 3166:         $oldinststatus = $userenv{'inststatus'};
 3167:         foreach my $name ('portfolio','author') {
 3168:             ($olddefquota{$name},$oldsettingstatus{$name}) = 
 3169:                 &Apache::loncommon::default_quota($env{'form.ccdomain'},$oldinststatus,$name);
 3170:             ($newdefquota{$name},$newsettingstatus{$name}) = ($olddefquota{$name},$oldsettingstatus{$name});
 3171:         }
 3172:         my %canshow;
 3173:         if (&Apache::lonnet::allowed('mpq',$env{'form.ccdomain'})) {
 3174:             $canshow{'quota'} = 1;
 3175:         }
 3176:         if (&Apache::lonnet::allowed('mut',$env{'form.ccdomain'})) {
 3177:             $canshow{'tools'} = 1;
 3178:         }
 3179:         if (&Apache::lonnet::allowed('ccc',$env{'form.ccdomain'})) {
 3180:             $canshow{'requestcourses'} = 1;
 3181:         } elsif (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) {
 3182:             $canshow{'reqcrsotherdom'} = 1;
 3183:         }
 3184:         if (&Apache::lonnet::allowed('mau',$env{'form.ccdomain'})) {
 3185:             $canshow{'inststatus'} = 1;
 3186:         }
 3187:         if (&Apache::lonnet::allowed('cau',$env{'form.ccdomain'})) {
 3188:             $canshow{'requestauthor'} = 1;
 3189:         }
 3190:         my (%changeHash,%changed);
 3191:         if ($oldinststatus eq '') {
 3192:             $oldsettings{'inststatus'} = $othertitle; 
 3193:         } else {
 3194:             if (ref($usertypes) eq 'HASH') {
 3195:                 $oldsettings{'inststatus'} = join(', ',map{ $usertypes->{ &unescape($_) }; } (split(/:/,$userenv{'inststatus'})));
 3196:             } else {
 3197:                 $oldsettings{'inststatus'} = join(', ',map{ &unescape($_); } (split(/:/,$userenv{'inststatus'})));
 3198:             }
 3199:         }
 3200:         $changeHash{'inststatus'} = $userenv{'inststatus'};
 3201:         if ($canmodify_status{'inststatus'}) {
 3202:             $canshow{'inststatus'} = 1;
 3203:             if (exists($env{'form.inststatus'})) {
 3204:                 my @inststatuses = &Apache::loncommon::get_env_multiple('form.inststatus');
 3205:                 if (@inststatuses > 0) {
 3206:                     $newinststatus = join(':',map { &escape($_); } @inststatuses);
 3207:                     $changeHash{'inststatus'} = $newinststatus;
 3208:                     if ($newinststatus ne $oldinststatus) {
 3209:                         $changed{'inststatus'} = $newinststatus;
 3210:                         foreach my $name ('portfolio','author') {
 3211:                             ($newdefquota{$name},$newsettingstatus{$name}) =
 3212:                                 &Apache::loncommon::default_quota($env{'form.ccdomain'},$newinststatus,$name);
 3213:                         }
 3214:                     }
 3215:                     if (ref($usertypes) eq 'HASH') {
 3216:                         $newsettings{'inststatus'} = join(', ',map{ $usertypes->{$_}; } (@inststatuses)); 
 3217:                     } else {
 3218:                         $newsettings{'inststatus'} = join(', ',@inststatuses);
 3219:                     }
 3220:                 }
 3221:             } else {
 3222:                 $newinststatus = '';
 3223:                 $changeHash{'inststatus'} = $newinststatus;
 3224:                 $newsettings{'inststatus'} = $othertitle;
 3225:                 if ($newinststatus ne $oldinststatus) {
 3226:                     $changed{'inststatus'} = $changeHash{'inststatus'};
 3227:                     foreach my $name ('portfolio','author') {
 3228:                         ($newdefquota{$name},$newsettingstatus{$name}) =
 3229:                             &Apache::loncommon::default_quota($env{'form.ccdomain'},$newinststatus,$name);
 3230:                     }
 3231:                 }
 3232:             }
 3233:         } elsif ($context ne 'selfcreate') {
 3234:             $canshow{'inststatus'} = 1;
 3235:             $newsettings{'inststatus'} = $oldsettings{'inststatus'};
 3236:         }
 3237:         foreach my $name ('portfolio','author') {
 3238:             $changeHash{$name.'quota'} = $userenv{$name.'quota'};
 3239:         }
 3240:         if ($context eq 'domain') {
 3241:             foreach my $name ('portfolio','author') {
 3242:                 if ($userenv{$name.'quota'} ne '') {
 3243:                     $oldquota{$name} = $userenv{$name.'quota'};
 3244:                     if ($env{'form.custom_'.$name.'quota'} == 1) {
 3245:                         if ($env{'form.'.$name.'quota'} eq '') {
 3246:                             $newquota{$name} = 0;
 3247:                         } else {
 3248:                             $newquota{$name} = $env{'form.'.$name.'quota'};
 3249:                             $newquota{$name} =~ s/[^\d\.]//g;
 3250:                         }
 3251:                         if ($newquota{$name} != $oldquota{$name}) {
 3252:                             if (&quota_admin($newquota{$name},\%changeHash,$name)) {
 3253:                                 $changed{$name.'quota'} = 1;
 3254:                             }
 3255:                         }
 3256:                     } else {
 3257:                         if (&quota_admin('',\%changeHash,$name)) {
 3258:                             $changed{$name.'quota'} = 1;
 3259:                             $newquota{$name} = $newdefquota{$name};
 3260:                             $newisdefault{$name} = 1;
 3261:                         }
 3262:                     }
 3263:                 } else {
 3264:                     $oldisdefault{$name} = 1;
 3265:                     $oldquota{$name} = $olddefquota{$name};
 3266:                     if ($env{'form.custom_'.$name.'quota'} == 1) {
 3267:                         if ($env{'form.'.$name.'quota'} eq '') {
 3268:                             $newquota{$name} = 0;
 3269:                         } else {
 3270:                             $newquota{$name} = $env{'form.'.$name.'quota'};
 3271:                             $newquota{$name} =~ s/[^\d\.]//g;
 3272:                         }
 3273:                         if (&quota_admin($newquota{$name},\%changeHash,$name)) {
 3274:                             $changed{$name.'quota'} = 1;
 3275:                         }
 3276:                     } else {
 3277:                         $newquota{$name} = $newdefquota{$name};
 3278:                         $newisdefault{$name} = 1;
 3279:                     }
 3280:                 }
 3281:                 if ($oldisdefault{$name}) {
 3282:                     $oldsettingstext{'quota'}{$name} = &get_defaultquota_text($oldsettingstatus{$name});
 3283:                 }  else {
 3284:                     $oldsettingstext{'quota'}{$name} = &mt('custom quota: [_1] MB',$oldquota{$name});
 3285:                 }
 3286:                 if ($newisdefault{$name}) {
 3287:                     $newsettingstext{'quota'}{$name} = &get_defaultquota_text($newsettingstatus{$name});
 3288:                 } else {
 3289:                     $newsettingstext{'quota'}{$name} = &mt('custom quota: [_1] MB',$newquota{$name});
 3290:                 }
 3291:             }
 3292:             &tool_changes('tools',\@usertools,\%oldsettings,\%oldsettingstext,\%userenv,
 3293:                           \%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3294:             if ($env{'form.ccdomain'} eq $env{'request.role.domain'}) {
 3295:                 &tool_changes('requestcourses',\@requestcourses,\%oldsettings,\%oldsettingstext,
 3296:                               \%userenv,\%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3297:                 &tool_changes('requestauthor',\@requestauthor,\%oldsettings,\%oldsettingstext,
 3298:                               \%userenv,\%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3299:             } else {
 3300:                 &tool_changes('reqcrsotherdom',\@requestcourses,\%oldsettings,\%oldsettingstext,
 3301:                               \%userenv,\%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3302:             }
 3303:         }
 3304:         foreach my $item (@userinfo) {
 3305:             if ($env{'form.c'.$item} ne $userenv{$item}) {
 3306:                 $namechanged{$item} = 1;
 3307:             }
 3308:         }
 3309:         foreach my $name ('portfolio','author') {
 3310:             $oldsettings{'quota'}{$name} = &mt('[_1] MB',$oldquota{$name});
 3311:             $newsettings{'quota'}{$name} = &mt('[_1] MB',$newquota{$name});
 3312:         }
 3313:         if ((keys(%namechanged) > 0) || (keys(%changed) > 0)) {
 3314:             my ($chgresult,$namechgresult);
 3315:             if (keys(%changed) > 0) {
 3316:                 $chgresult = 
 3317:                     &Apache::lonnet::put('environment',\%changeHash,
 3318:                                   $env{'form.ccdomain'},$env{'form.ccuname'});
 3319:                 if ($chgresult eq 'ok') {
 3320:                     if (($env{'user.name'} eq $env{'form.ccuname'}) &&
 3321:                         ($env{'user.domain'} eq $env{'form.ccdomain'})) {
 3322:                         my %newenvhash;
 3323:                         foreach my $key (keys(%changed)) {
 3324:                             if (($key eq 'official') || ($key eq 'unofficial')
 3325:                                 || ($key eq 'community') || ($key eq 'textbook')) {
 3326:                                 $newenvhash{'environment.requestcourses.'.$key} =
 3327:                                     $changeHash{'requestcourses.'.$key};
 3328:                                 if ($changeHash{'requestcourses.'.$key}) {
 3329:                                     $newenvhash{'environment.canrequest.'.$key} = 1;
 3330:                                 } else {
 3331:                                     $newenvhash{'environment.canrequest.'.$key} =
 3332:           &Apache::lonnet::usertools_access($env{'user.name'},$env{'user.domain'},
 3333:                                             $key,'reload','requestcourses');
 3334:                                 }
 3335:                             } elsif ($key eq 'requestauthor') {
 3336:                                 $newenvhash{'environment.'.$key} = $changeHash{$key};
 3337:                                 if ($changeHash{$key}) {
 3338:                                     $newenvhash{'environment.canrequest.author'} = 1;
 3339:                                 } else {
 3340:                                     $newenvhash{'environment.canrequest.author'} =
 3341:           &Apache::lonnet::usertools_access($env{'user.name'},$env{'user.domain'},
 3342:                                             $key,'reload','requestauthor');
 3343:                                 }
 3344:                             } elsif ($key ne 'quota') {
 3345:                                 $newenvhash{'environment.tools.'.$key} = 
 3346:                                     $changeHash{'tools.'.$key};
 3347:                                 if ($changeHash{'tools.'.$key} ne '') {
 3348:                                     $newenvhash{'environment.availabletools.'.$key} =
 3349:                                         $changeHash{'tools.'.$key};
 3350:                                 } else {
 3351:                                     $newenvhash{'environment.availabletools.'.$key} =
 3352:           &Apache::lonnet::usertools_access($env{'user.name'},$env{'user.domain'},
 3353:           $key,'reload','tools');
 3354:                                 }
 3355:                             }
 3356:                         }
 3357:                         if (keys(%newenvhash)) {
 3358:                             &Apache::lonnet::appenv(\%newenvhash);
 3359:                         }
 3360:                     }
 3361:                 }
 3362:             }
 3363:             if (keys(%namechanged) > 0) {
 3364:                 foreach my $field (@userinfo) {
 3365:                     $changeHash{$field}  = $env{'form.c'.$field};
 3366:                 }
 3367: # Make the change
 3368:                 $namechgresult =
 3369:                     &Apache::lonnet::modifyuser($env{'form.ccdomain'},
 3370:                         $env{'form.ccuname'},$changeHash{'id'},undef,undef,
 3371:                         $changeHash{'firstname'},$changeHash{'middlename'},
 3372:                         $changeHash{'lastname'},$changeHash{'generation'},
 3373:                         $changeHash{'id'},undef,$changeHash{'permanentemail'},undef,\@userinfo);
 3374:                 %userupdate = (
 3375:                                lastname   => $env{'form.clastname'},
 3376:                                middlename => $env{'form.cmiddlename'},
 3377:                                firstname  => $env{'form.cfirstname'},
 3378:                                generation => $env{'form.cgeneration'},
 3379:                                id         => $env{'form.cid'},
 3380:                              );
 3381:             }
 3382:             if (((keys(%namechanged) > 0) && $namechgresult eq 'ok') || 
 3383:                 ((keys(%changed) > 0) && $chgresult eq 'ok')) {
 3384:             # Tell the user we changed the name
 3385:                 &display_userinfo($r,1,\@disporder,\%canshow,\@requestcourses,
 3386:                                   \@usertools,\@requestauthor,\%userenv,\%changed,\%namechanged,
 3387:                                   \%oldsettings, \%oldsettingstext,\%newsettings,
 3388:                                   \%newsettingstext);
 3389:                 if ($env{'form.cid'} ne $userenv{'id'}) {
 3390:                     &Apache::lonnet::idput($env{'form.ccdomain'},
 3391:                          {$env{'form.ccuname'} => $env{'form.cid'}});
 3392:                     if (($recurseid) &&
 3393:                         (&Apache::lonnet::allowed('mau',$env{'form.ccdomain'}))) {
 3394:                         my $idresult = 
 3395:                             &Apache::lonuserutils::propagate_id_change(
 3396:                                 $env{'form.ccuname'},$env{'form.ccdomain'},
 3397:                                 \%userupdate);
 3398:                         $r->print('<br />'.$idresult.'<br />');
 3399:                     }
 3400:                 }
 3401:                 if (($env{'form.ccdomain'} eq $env{'user.domain'}) && 
 3402:                     ($env{'form.ccuname'} eq $env{'user.name'})) {
 3403:                     my %newenvhash;
 3404:                     foreach my $key (keys(%changeHash)) {
 3405:                         $newenvhash{'environment.'.$key} = $changeHash{$key};
 3406:                     }
 3407:                     &Apache::lonnet::appenv(\%newenvhash);
 3408:                 }
 3409:             } else { # error occurred
 3410:                 $r->print(
 3411:                     '<p class="LC_error">'
 3412:                    .&mt('Unable to successfully change environment for [_1] in domain [_2].',
 3413:                             '"'.$env{'form.ccuname'}.'"',
 3414:                             '"'.$env{'form.ccdomain'}.'"')
 3415:                    .'</p>');
 3416:             }
 3417:         } else { # End of if ($env ... ) logic
 3418:             # They did not want to change the users name, quota, tool availability,
 3419:             # or ability to request creation of courses, 
 3420:             # but we can still tell them what the name and quota and availabilities are  
 3421:             &display_userinfo($r,undef,\@disporder,\%canshow,\@requestcourses,
 3422:                               \@usertools,\@requestauthor,\%userenv,\%changed,\%namechanged,\%oldsettings,
 3423:                               \%oldsettingstext,\%newsettings,\%newsettingstext);
 3424:         }
 3425:         if (@mod_disallowed) {
 3426:             my ($rolestr,$contextname);
 3427:             if (@longroles > 0) {
 3428:                 $rolestr = join(', ',@longroles);
 3429:             } else {
 3430:                 $rolestr = &mt('No roles');
 3431:             }
 3432:             if ($context eq 'course') {
 3433:                 $contextname = 'course';
 3434:             } elsif ($context eq 'author') {
 3435:                 $contextname = 'co-author';
 3436:             }
 3437:             $r->print(&mt('The following fields were not updated: ').'<ul>');
 3438:             my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
 3439:             foreach my $field (@mod_disallowed) {
 3440:                 $r->print('<li>'.$fieldtitles{$field}.'</li>'."\n"); 
 3441:             }
 3442:             $r->print('</ul>');
 3443:             if (@mod_disallowed == 1) {
 3444:                 $r->print(&mt("You do not have the authority to change this field given the user's current set of active/future $contextname roles:"));
 3445:             } else {
 3446:                 $r->print(&mt("You do not have the authority to change these fields given the user's current set of active/future $contextname roles:"));
 3447:             }
 3448:             my $helplink = 'javascript:helpMenu('."'display'".')';
 3449:             $r->print('<span class="LC_cusr_emph">'.$rolestr.'</span><br />'
 3450:                      .&mt('Please contact your [_1]helpdesk[_2] for more information.'
 3451:                          ,'<a href="'.$helplink.'">','</a>')
 3452:                       .'<br />');
 3453:         }
 3454:         $r->print('<span class="LC_warning">'
 3455:                   .$no_forceid_alert
 3456:                   .&Apache::lonuserutils::print_namespacing_alerts($env{'form.ccdomain'},\%alerts,\%curr_rules)
 3457:                   .'</span>');
 3458:     }
 3459:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 3460:     if ($env{'form.action'} eq 'singlestudent') {
 3461:         &enroll_single_student($r,$uhome,$amode,$genpwd,$now,$newuser,$context,
 3462:                                $crstype,$showcredits,$defaultcredits);
 3463:         my $linktext = ($crstype eq 'Community' ?
 3464:             &mt('Enroll Another Member') : &mt('Enroll Another Student'));
 3465:         $r->print(
 3466:             &Apache::lonhtmlcommon::actionbox([
 3467:                 '<a href="javascript:backPage(document.userupdate)">'
 3468:                .($crstype eq 'Community' ? 
 3469:                     &mt('Enroll Another Member') : &mt('Enroll Another Student'))
 3470:                .'</a>']));
 3471:     } else {
 3472:         my @rolechanges = &update_roles($r,$context,$showcredits);
 3473:         if (keys(%namechanged) > 0) {
 3474:             if ($context eq 'course') {
 3475:                 if (@userroles > 0) {
 3476:                     if ((@rolechanges == 0) || 
 3477:                         (!(grep(/^st$/,@rolechanges)))) {
 3478:                         if (grep(/^st$/,@userroles)) {
 3479:                             my $classlistupdated =
 3480:                                 &Apache::lonuserutils::update_classlist($cdom,
 3481:                                               $cnum,$env{'form.ccdomain'},
 3482:                                        $env{'form.ccuname'},\%userupdate);
 3483:                         }
 3484:                     }
 3485:                 }
 3486:             }
 3487:         }
 3488:         my $userinfo = &Apache::loncommon::plainname($env{'form.ccuname'},
 3489:                                                      $env{'form.ccdomain'});
 3490:         if ($env{'form.popup'}) {
 3491:             $r->print('<p><a href="javascript:window.close()">'.&mt('Close window').'</a></p>');
 3492:         } else {
 3493:             $r->print('<br />'.&Apache::lonhtmlcommon::actionbox(['<a href="javascript:backPage(document.userupdate,'."'$env{'form.prevphase'}','modify'".')">'
 3494:                      .&mt('Modify this user: [_1]','<span class="LC_cusr_emph">'.$env{'form.ccuname'}.':'.$env{'form.ccdomain'}.' ('.$userinfo.')</span>').'</a>',
 3495:                      '<a href="javascript:backPage(document.userupdate)">'.&mt('Create/Modify Another User').'</a>']));
 3496:         }
 3497:     }
 3498: }
 3499: 
 3500: sub display_userinfo {
 3501:     my ($r,$changed,$order,$canshow,$requestcourses,$usertools,$requestauthor,
 3502:         $userenv,$changedhash,$namechangedhash,$oldsetting,$oldsettingtext,
 3503:         $newsetting,$newsettingtext) = @_;
 3504:     return unless (ref($order) eq 'ARRAY' &&
 3505:                    ref($canshow) eq 'HASH' && 
 3506:                    ref($requestcourses) eq 'ARRAY' && 
 3507:                    ref($requestauthor) eq 'ARRAY' &&
 3508:                    ref($usertools) eq 'ARRAY' && 
 3509:                    ref($userenv) eq 'HASH' &&
 3510:                    ref($changedhash) eq 'HASH' &&
 3511:                    ref($oldsetting) eq 'HASH' &&
 3512:                    ref($oldsettingtext) eq 'HASH' &&
 3513:                    ref($newsetting) eq 'HASH' &&
 3514:                    ref($newsettingtext) eq 'HASH');
 3515:     my %lt=&Apache::lonlocal::texthash(
 3516:          'ui'             => 'User Information',
 3517:          'uic'            => 'User Information Changed',
 3518:          'firstname'      => 'First Name',
 3519:          'middlename'     => 'Middle Name',
 3520:          'lastname'       => 'Last Name',
 3521:          'generation'     => 'Generation',
 3522:          'id'             => 'Student/Employee ID',
 3523:          'permanentemail' => 'Permanent e-mail address',
 3524:          'portfolioquota' => 'Disk space allocated to portfolio files',
 3525:          'authorquota'    => 'Disk space allocated to Authoring Space',
 3526:          'blog'           => 'Blog Availability',
 3527:          'webdav'         => 'WebDAV Availability',
 3528:          'aboutme'        => 'Personal Information Page Availability',
 3529:          'portfolio'      => 'Portfolio Availability',
 3530:          'official'       => 'Can Request Official Courses',
 3531:          'unofficial'     => 'Can Request Unofficial Courses',
 3532:          'community'      => 'Can Request Communities',
 3533:          'textbook'       => 'Can Request Textbook Courses',
 3534:          'requestauthor'  => 'Can Request Author Role',
 3535:          'inststatus'     => "Affiliation",
 3536:          'prvs'           => 'Previous Value:',
 3537:          'chto'           => 'Changed To:'
 3538:     );
 3539:     if ($changed) {
 3540:         $r->print('<h3>'.$lt{'uic'}.'</h3>'.
 3541:                 &Apache::loncommon::start_data_table().
 3542:                 &Apache::loncommon::start_data_table_header_row());
 3543:         $r->print("<th>&nbsp;</th>\n");
 3544:         $r->print('<th><b>'.$lt{'prvs'}.'</b></th>');
 3545:         $r->print('<th><span class="LC_nobreak"><b>'.$lt{'chto'}.'</b></span></th>');
 3546:         $r->print(&Apache::loncommon::end_data_table_header_row());
 3547:         my @userinfo = ('firstname','middlename','lastname','generation','permanentemail','id');
 3548: 
 3549:         foreach my $item (@userinfo) {
 3550:             my $value = $env{'form.c'.$item};
 3551:             #show changes only:
 3552:             unless ($value eq $userenv->{$item}){
 3553:                 $r->print(&Apache::loncommon::start_data_table_row());
 3554:                 $r->print("<td>$lt{$item}</td>\n");
 3555:                 $r->print("<td>".$userenv->{$item}."</td>\n");
 3556:                 $r->print("<td>$value </td>\n");
 3557:                 $r->print(&Apache::loncommon::end_data_table_row());
 3558:             }
 3559:         }
 3560:         foreach my $entry (@{$order}) {
 3561:             if ($canshow->{$entry}) {
 3562:                 if (($entry eq 'requestcourses') || ($entry eq 'reqcrsotherdom') || ($entry eq 'requestauthor')) {
 3563:                     my @items;
 3564:                     if ($entry eq 'requestauthor') {
 3565:                         @items = ($entry);
 3566:                     } else {
 3567:                         @items = @{$requestcourses};
 3568:                     }
 3569:                     foreach my $item (@items) {
 3570:                         if (($newsetting->{$item} ne $oldsetting->{$item}) || 
 3571:                             ($newsettingtext->{$item} ne $oldsettingtext->{$item})) {
 3572:                             $r->print(&Apache::loncommon::start_data_table_row()."\n");  
 3573:                             $r->print("<td>$lt{$item}</td>\n");
 3574:                             $r->print("<td>".$oldsetting->{$item});
 3575:                             if ($oldsettingtext->{$item}) {
 3576:                                 if ($oldsetting->{$item}) {
 3577:                                     $r->print(' -- ');
 3578:                                 }
 3579:                                 $r->print($oldsettingtext->{$item});
 3580:                             }
 3581:                             $r->print("</td>\n");
 3582:                             $r->print("<td>".$newsetting->{$item});
 3583:                             if ($newsettingtext->{$item}) {
 3584:                                 if ($newsetting->{$item}) {
 3585:                                     $r->print(' -- ');
 3586:                                 }
 3587:                                 $r->print($newsettingtext->{$item});
 3588:                             }
 3589:                             $r->print("</td>\n");
 3590:                             $r->print(&Apache::loncommon::end_data_table_row()."\n");
 3591:                         }
 3592:                     }
 3593:                 } elsif ($entry eq 'tools') {
 3594:                     foreach my $item (@{$usertools}) {
 3595:                         if ($newsetting->{$item} ne $oldsetting->{$item}) {
 3596:                             $r->print(&Apache::loncommon::start_data_table_row()."\n");
 3597:                             $r->print("<td>$lt{$item}</td>\n");
 3598:                             $r->print("<td>".$oldsetting->{$item}.' '.$oldsettingtext->{$item}."</td>\n");
 3599:                             $r->print("<td>".$newsetting->{$item}.' '.$newsettingtext->{$item}."</td>\n");
 3600:                             $r->print(&Apache::loncommon::end_data_table_row()."\n");
 3601:                         }
 3602:                     }
 3603:                 } elsif ($entry eq 'quota') {
 3604:                     if ((ref($oldsetting->{$entry}) eq 'HASH') && (ref($oldsettingtext->{$entry}) eq 'HASH') &&
 3605:                         (ref($newsetting->{$entry}) eq 'HASH') && (ref($newsettingtext->{$entry}) eq 'HASH')) {
 3606:                         foreach my $name ('portfolio','author') {
 3607:                             if ($newsetting->{$entry}->{$name} ne $oldsetting->{$entry}->{$name}) {
 3608:                                 $r->print(&Apache::loncommon::start_data_table_row()."\n");
 3609:                                 $r->print("<td>$lt{$name.$entry}</td>\n");
 3610:                                 $r->print("<td>".$oldsettingtext->{$entry}->{$name}."</td>\n");
 3611:                                 $r->print("<td>".$newsettingtext->{$entry}->{$name}."</td>\n");
 3612:                                 $r->print(&Apache::loncommon::end_data_table_row()."\n");
 3613:                             }
 3614:                         }
 3615:                     }
 3616:                 } else {
 3617:                     if ($newsetting->{$entry} ne $oldsetting->{$entry}) {
 3618:                         $r->print(&Apache::loncommon::start_data_table_row()."\n");
 3619:                         $r->print("<td>$lt{$entry}</td>\n");
 3620:                         $r->print("<td>".$oldsetting->{$entry}.' '.$oldsettingtext->{$entry}."</td>\n");
 3621:                         $r->print("<td>".$newsetting->{$entry}.' '.$newsettingtext->{$entry}."</td>\n");
 3622:                         $r->print(&Apache::loncommon::end_data_table_row()."\n");
 3623:                     }
 3624:                 }
 3625:             }
 3626:         }
 3627:         $r->print(&Apache::loncommon::end_data_table().'<br />');
 3628:     } else {
 3629:         $r->print('<h3>'.$lt{'ui'}.'</h3>'.
 3630:                   '<p>'.&mt('No changes made to user information').'</p>');
 3631:     }
 3632:     return;
 3633: }
 3634: 
 3635: sub tool_changes {
 3636:     my ($context,$usertools,$oldaccess,$oldaccesstext,$userenv,$changeHash,
 3637:         $changed,$newaccess,$newaccesstext) = @_;
 3638:     if (!((ref($usertools) eq 'ARRAY') && (ref($oldaccess) eq 'HASH') &&
 3639:           (ref($oldaccesstext) eq 'HASH') && (ref($userenv) eq 'HASH') &&
 3640:           (ref($changeHash) eq 'HASH') && (ref($changed) eq 'HASH') &&
 3641:           (ref($newaccess) eq 'HASH') && (ref($newaccesstext) eq 'HASH'))) {
 3642:         return;
 3643:     }
 3644:     my %reqdisplay = &requestchange_display();
 3645:     if ($context eq 'reqcrsotherdom') {
 3646:         my @options = ('approval','validate','autolimit');
 3647:         my $optregex = join('|',@options);
 3648:         my $cdom = $env{'request.role.domain'};
 3649:         foreach my $tool (@{$usertools}) {
 3650:             $oldaccesstext->{$tool} = &mt("availability set to 'off'");
 3651:             $newaccesstext->{$tool} = $oldaccesstext->{$tool};
 3652:             $changeHash->{$context.'.'.$tool} = $userenv->{$context.'.'.$tool};
 3653:             my ($newop,$limit);
 3654:             if ($env{'form.'.$context.'_'.$tool}) {
 3655:                 $newop = $env{'form.'.$context.'_'.$tool};
 3656:                 if ($newop eq 'autolimit') {
 3657:                     $limit = $env{'form.'.$context.'_'.$tool.'_limit'};
 3658:                     $limit =~ s/\D+//g;
 3659:                     $newop .= '='.$limit;
 3660:                 }
 3661:             }
 3662:             if ($userenv->{$context.'.'.$tool} eq '') {
 3663:                 if ($newop) {
 3664:                     $changed->{$tool}=&tool_admin($tool,$cdom.':'.$newop,
 3665:                                                   $changeHash,$context);
 3666:                     if ($changed->{$tool}) {
 3667:                         if ($newop =~ /^autolimit/) {
 3668:                             if ($limit) {
 3669:                                 $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3670:                             } else {
 3671:                                 $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3672:                             }
 3673:                         } else {
 3674:                             $newaccesstext->{$tool} = $reqdisplay{$newop};
 3675:                         }
 3676:                     } else {
 3677:                         $newaccesstext->{$tool} = $oldaccesstext->{$tool};
 3678:                     }
 3679:                 }
 3680:             } else {
 3681:                 my @curr = split(',',$userenv->{$context.'.'.$tool});
 3682:                 my @new;
 3683:                 my $changedoms;
 3684:                 foreach my $req (@curr) {
 3685:                     if ($req =~ /^\Q$cdom\E\:($optregex\=?\d*)$/) {
 3686:                         my $oldop = $1;
 3687:                         if ($oldop =~ /^autolimit=(\d*)/) {
 3688:                             my $limit = $1;
 3689:                             if ($limit) {
 3690:                                 $oldaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3691:                             } else {
 3692:                                 $oldaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3693:                             }
 3694:                         } else {
 3695:                             $oldaccesstext->{$tool} = $reqdisplay{$oldop};
 3696:                         }
 3697:                         if ($oldop ne $newop) {
 3698:                             $changedoms = 1;
 3699:                             foreach my $item (@curr) {
 3700:                                 my ($reqdom,$option) = split(':',$item);
 3701:                                 unless ($reqdom eq $cdom) {
 3702:                                     push(@new,$item);
 3703:                                 }
 3704:                             }
 3705:                             if ($newop) {
 3706:                                 push(@new,$cdom.':'.$newop);
 3707:                             }
 3708:                             @new = sort(@new);
 3709:                         }
 3710:                         last;
 3711:                     }
 3712:                 }
 3713:                 if ((!$changedoms) && ($newop)) {
 3714:                     $changedoms = 1;
 3715:                     @new = sort(@curr,$cdom.':'.$newop);
 3716:                 }
 3717:                 if ($changedoms) {
 3718:                     my $newdomstr;
 3719:                     if (@new) {
 3720:                         $newdomstr = join(',',@new);
 3721:                     }
 3722:                     $changed->{$tool}=&tool_admin($tool,$newdomstr,$changeHash,
 3723:                                                   $context);
 3724:                     if ($changed->{$tool}) {
 3725:                         if ($env{'form.'.$context.'_'.$tool}) {
 3726:                             if ($env{'form.'.$context.'_'.$tool} eq 'autolimit') {
 3727:                                 my $limit = $env{'form.'.$context.'_'.$tool.'_limit'};
 3728:                                 $limit =~ s/\D+//g;
 3729:                                 if ($limit) {
 3730:                                     $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3731:                                 } else {
 3732:                                     $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3733:                                 }
 3734:                             } else {
 3735:                                 $newaccesstext->{$tool} = $reqdisplay{$env{'form.'.$context.'_'.$tool}};
 3736:                             }
 3737:                         } else {
 3738:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3739:                         }
 3740:                     }
 3741:                 }
 3742:             }
 3743:         }
 3744:         return;
 3745:     }
 3746:     foreach my $tool (@{$usertools}) {
 3747:         my ($newval,$limit,$envkey);
 3748:         $envkey = $context.'.'.$tool;
 3749:         if ($context eq 'requestcourses') {
 3750:             $newval = $env{'form.crsreq_'.$tool};
 3751:             if ($newval eq 'autolimit') {
 3752:                 $limit = $env{'form.crsreq_'.$tool.'_limit'};
 3753:                 $limit =~ s/\D+//g;
 3754:                 $newval .= '='.$limit;
 3755:             }
 3756:         } elsif ($context eq 'requestauthor') {
 3757:             $newval = $env{'form.'.$context};
 3758:             $envkey = $context;
 3759:         } else {
 3760:             $newval = $env{'form.'.$context.'_'.$tool};
 3761:         }
 3762:         if ($userenv->{$envkey} ne '') {
 3763:             $oldaccess->{$tool} = &mt('custom');
 3764:             if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 3765:                 if ($userenv->{$envkey} =~ /^autolimit=(\d*)$/) {
 3766:                     my $currlimit = $1;
 3767:                     if ($currlimit eq '') {
 3768:                         $oldaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3769:                     } else {
 3770:                         $oldaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$currlimit);
 3771:                     }
 3772:                 } elsif ($userenv->{$envkey}) {
 3773:                     $oldaccesstext->{$tool} = $reqdisplay{$userenv->{$envkey}};
 3774:                 } else {
 3775:                     $oldaccesstext->{$tool} = &mt("availability set to 'off'");
 3776:                 }
 3777:             } else {
 3778:                 if ($userenv->{$envkey}) {
 3779:                     $oldaccesstext->{$tool} = &mt("availability set to 'on'");
 3780:                 } else {
 3781:                     $oldaccesstext->{$tool} = &mt("availability set to 'off'");
 3782:                 }
 3783:             }
 3784:             $changeHash->{$envkey} = $userenv->{$envkey};
 3785:             if ($env{'form.custom'.$tool} == 1) {
 3786:                 if ($newval ne $userenv->{$envkey}) {
 3787:                     $changed->{$tool} = &tool_admin($tool,$newval,$changeHash,
 3788:                                                     $context);
 3789:                     if ($changed->{$tool}) {
 3790:                         $newaccess->{$tool} = &mt('custom');
 3791:                         if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 3792:                             if ($newval =~ /^autolimit/) {
 3793:                                 if ($limit) {
 3794:                                     $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3795:                                 } else {
 3796:                                     $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3797:                                 }
 3798:                             } elsif ($newval) {
 3799:                                 $newaccesstext->{$tool} = $reqdisplay{$newval};
 3800:                             } else {
 3801:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3802:                             }
 3803:                         } else {
 3804:                             if ($newval) {
 3805:                                 $newaccesstext->{$tool} = &mt("availability set to 'on'");
 3806:                             } else {
 3807:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3808:                             }
 3809:                         }
 3810:                     } else {
 3811:                         $newaccess->{$tool} = $oldaccess->{$tool};
 3812:                         if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 3813:                             if ($newval =~ /^autolimit/) {
 3814:                                 if ($limit) {
 3815:                                     $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3816:                                 } else {
 3817:                                     $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3818:                                 }
 3819:                             } elsif ($newval) {
 3820:                                 $newaccesstext->{$tool} = $reqdisplay{$newval};
 3821:                             } else {
 3822:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3823:                             }
 3824:                         } else {
 3825:                             if ($userenv->{$context.'.'.$tool}) {
 3826:                                 $newaccesstext->{$tool} = &mt("availability set to 'on'");
 3827:                             } else {
 3828:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3829:                             }
 3830:                         }
 3831:                     }
 3832:                 } else {
 3833:                     $newaccess->{$tool} = $oldaccess->{$tool};
 3834:                     $newaccesstext->{$tool} = $oldaccesstext->{$tool};
 3835:                 }
 3836:             } else {
 3837:                 $changed->{$tool} = &tool_admin($tool,'',$changeHash,$context);
 3838:                 if ($changed->{$tool}) {
 3839:                     $newaccess->{$tool} = &mt('default');
 3840:                 } else {
 3841:                     $newaccess->{$tool} = $oldaccess->{$tool};
 3842:                     if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 3843:                         if ($newval =~ /^autolimit/) {
 3844:                             if ($limit) {
 3845:                                 $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3846:                             } else {
 3847:                                 $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3848:                             }
 3849:                         } elsif ($newval) {
 3850:                             $newaccesstext->{$tool} = $reqdisplay{$newval};
 3851:                         } else {
 3852:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3853:                         }
 3854:                     } else {
 3855:                         if ($userenv->{$context.'.'.$tool}) {
 3856:                             $newaccesstext->{$tool} = &mt("availability set to 'on'");
 3857:                         } else {
 3858:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3859:                         }
 3860:                     }
 3861:                 }
 3862:             }
 3863:         } else {
 3864:             $oldaccess->{$tool} = &mt('default');
 3865:             if ($env{'form.custom'.$tool} == 1) {
 3866:                 $changed->{$tool} = &tool_admin($tool,$newval,$changeHash,
 3867:                                                 $context);
 3868:                 if ($changed->{$tool}) {
 3869:                     $newaccess->{$tool} = &mt('custom');
 3870:                     if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 3871:                         if ($newval =~ /^autolimit/) {
 3872:                             if ($limit) {
 3873:                                 $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3874:                             } else {
 3875:                                 $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3876:                             }
 3877:                         } elsif ($newval) {
 3878:                             $newaccesstext->{$tool} = $reqdisplay{$newval};
 3879:                         } else {
 3880:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3881:                         }
 3882:                     } else {
 3883:                         if ($newval) {
 3884:                             $newaccesstext->{$tool} = &mt("availability set to 'on'");
 3885:                         } else {
 3886:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3887:                         }
 3888:                     }
 3889:                 } else {
 3890:                     $newaccess->{$tool} = $oldaccess->{$tool};
 3891:                 }
 3892:             } else {
 3893:                 $newaccess->{$tool} = $oldaccess->{$tool};
 3894:             }
 3895:         }
 3896:     }
 3897:     return;
 3898: }
 3899: 
 3900: sub update_roles {
 3901:     my ($r,$context,$showcredits) = @_;
 3902:     my $now=time;
 3903:     my @rolechanges;
 3904:     my %disallowed;
 3905:     $r->print('<h3>'.&mt('Modifying Roles').'</h3>');
 3906:     foreach my $key (keys(%env)) {
 3907: 	next if (! $env{$key});
 3908:         next if ($key eq 'form.action');
 3909: 	# Revoke roles
 3910: 	if ($key=~/^form\.rev/) {
 3911: 	    if ($key=~/^form\.rev\:([^\_]+)\_([^\_\.]+)$/) {
 3912: # Revoke standard role
 3913: 		my ($scope,$role) = ($1,$2);
 3914: 		my $result =
 3915: 		    &Apache::lonnet::revokerole($env{'form.ccdomain'},
 3916: 						$env{'form.ccuname'},
 3917: 						$scope,$role,'','',$context);
 3918:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
 3919:                             &mt('Revoking [_1] in [_2]',
 3920:                                 &Apache::lonnet::plaintext($role),
 3921:                                 &Apache::loncommon::show_role_extent($scope,$context,$role)),
 3922:                                 $result ne "ok").'<br />');
 3923:                 if ($result ne "ok") {
 3924:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 3925:                 }
 3926: 		if ($role eq 'st') {
 3927: 		    my $result = 
 3928:                         &Apache::lonuserutils::classlist_drop($scope,
 3929:                             $env{'form.ccuname'},$env{'form.ccdomain'},
 3930: 			    $now);
 3931:                     $r->print(&Apache::lonhtmlcommon::confirm_success($result));
 3932: 		}
 3933:                 if (!grep(/^\Q$role\E$/,@rolechanges)) {
 3934:                     push(@rolechanges,$role);
 3935:                 }
 3936: 	    }
 3937: 	    if ($key=~m{^form\.rev\:([^_]+)_cr\.cr/($match_domain)/($match_username)/(\w+)$}s) {
 3938: # Revoke custom role
 3939:                 my $result = &Apache::lonnet::revokecustomrole(
 3940:                     $env{'form.ccdomain'},$env{'form.ccuname'},$1,$2,$3,$4,'','',$context);
 3941:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
 3942:                             &mt('Revoking custom role [_1] by [_2] in [_3]',
 3943:                                 $4,$3.':'.$2,&Apache::loncommon::show_role_extent($1,$context,'cr')),
 3944:                             $result ne 'ok').'<br />');
 3945:                 if ($result ne "ok") {
 3946:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 3947:                 }
 3948:                 if (!grep(/^cr$/,@rolechanges)) {
 3949:                     push(@rolechanges,'cr');
 3950:                 }
 3951: 	    }
 3952: 	} elsif ($key=~/^form\.del/) {
 3953: 	    if ($key=~/^form\.del\:([^\_]+)\_([^\_\.]+)$/) {
 3954: # Delete standard role
 3955: 		my ($scope,$role) = ($1,$2);
 3956: 		my $result =
 3957: 		    &Apache::lonnet::assignrole($env{'form.ccdomain'},
 3958: 						$env{'form.ccuname'},
 3959: 						$scope,$role,$now,0,1,'',
 3960:                                                 $context);
 3961:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
 3962:                             &mt('Deleting [_1] in [_2]',
 3963:                                 &Apache::lonnet::plaintext($role),
 3964:                                 &Apache::loncommon::show_role_extent($scope,$context,$role)),
 3965:                             $result ne 'ok').'<br />');
 3966:                 if ($result ne "ok") {
 3967:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 3968:                 }
 3969: 
 3970: 		if ($role eq 'st') {
 3971: 		    my $result = 
 3972:                         &Apache::lonuserutils::classlist_drop($scope,
 3973:                             $env{'form.ccuname'},$env{'form.ccdomain'},
 3974: 			    $now);
 3975: 		    $r->print(&Apache::lonhtmlcommon::confirm_success($result));
 3976: 		}
 3977:                 if (!grep(/^\Q$role\E$/,@rolechanges)) {
 3978:                     push(@rolechanges,$role);
 3979:                 }
 3980:             }
 3981: 	    if ($key=~m{^form\.del\:([^_]+)_cr\.cr/($match_domain)/($match_username)/(\w+)$}) {
 3982:                 my ($url,$rdom,$rnam,$rolename) = ($1,$2,$3,$4);
 3983: # Delete custom role
 3984:                 my $result =
 3985:                     &Apache::lonnet::assigncustomrole($env{'form.ccdomain'},
 3986:                         $env{'form.ccuname'},$url,$rdom,$rnam,$rolename,$now,
 3987:                         0,1,$context);
 3988:                 $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('Deleting custom role [_1] by [_2] in [_3]',
 3989:                       $rolename,$rnam.':'.$rdom,&Apache::loncommon::show_role_extent($1,$context,'cr')),
 3990:                       $result ne "ok").'<br />');
 3991:                 if ($result ne "ok") {
 3992:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 3993:                 }
 3994: 
 3995:                 if (!grep(/^cr$/,@rolechanges)) {
 3996:                     push(@rolechanges,'cr');
 3997:                 }
 3998:             }
 3999: 	} elsif ($key=~/^form\.ren/) {
 4000:             my $udom = $env{'form.ccdomain'};
 4001:             my $uname = $env{'form.ccuname'};
 4002: # Re-enable standard role
 4003: 	    if ($key=~/^form\.ren\:([^\_]+)\_([^\_\.]+)$/) {
 4004:                 my $url = $1;
 4005:                 my $role = $2;
 4006:                 my $logmsg;
 4007:                 my $output;
 4008:                 if ($role eq 'st') {
 4009:                     if ($url =~ m-^/($match_domain)/($match_courseid)/?(\w*)$-) {
 4010:                         my ($cdom,$cnum,$csec) = ($1,$2,$3);
 4011:                         my $credits;
 4012:                         if ($showcredits) {
 4013:                             my $defaultcredits = 
 4014:                                 &Apache::lonuserutils::get_defaultcredits($cdom,$cnum);
 4015:                             $credits = &get_user_credits($defaultcredits,$cdom,$cnum);
 4016:                         }
 4017:                         my $result = &Apache::loncommon::commit_studentrole(\$logmsg,$udom,$uname,$url,$role,$now,0,$cdom,$cnum,$csec,$context,$credits);
 4018:                         if (($result =~ /^error/) || ($result eq 'not_in_class') || ($result eq 'unknown_course') || ($result eq 'refused')) {
 4019:                             if ($result eq 'refused' && $logmsg) {
 4020:                                 $output = $logmsg;
 4021:                             } else { 
 4022:                                 $output = &mt('Error: [_1]',$result)."\n";
 4023:                             }
 4024:                         } else {
 4025:                             $output = &Apache::lonhtmlcommon::confirm_success(&mt('Assigning [_1] in [_2] starting [_3]',
 4026:                                         &Apache::lonnet::plaintext($role),
 4027:                                         &Apache::loncommon::show_role_extent($url,$context,'st'),
 4028:                                         &Apache::lonlocal::locallocaltime($now))).'<br />'.$logmsg.'<br />';
 4029:                         }
 4030:                     }
 4031:                 } else {
 4032: 		    my $result=&Apache::lonnet::assignrole($env{'form.ccdomain'},
 4033:                                $env{'form.ccuname'},$url,$role,0,$now,'','',
 4034:                                $context);
 4035:                         $output = &Apache::lonhtmlcommon::confirm_success(&mt('Re-enabling [_1] in [_2]',
 4036:                                         &Apache::lonnet::plaintext($role),
 4037:                                         &Apache::loncommon::show_role_extent($url,$context,$role)),$result ne "ok").'<br />';
 4038:                     if ($result ne "ok") {
 4039:                         $output .= &mt('Error: [_1]',$result).'<br />';
 4040:                     }
 4041:                 }
 4042:                 $r->print($output);
 4043:                 if (!grep(/^\Q$role\E$/,@rolechanges)) {
 4044:                     push(@rolechanges,$role);
 4045:                 }
 4046: 	    }
 4047: # Re-enable custom role
 4048: 	    if ($key=~m{^form\.ren\:([^_]+)_cr\.cr/($match_domain)/($match_username)/(\w+)$}) {
 4049:                 my ($url,$rdom,$rnam,$rolename) = ($1,$2,$3,$4);
 4050:                 my $result = &Apache::lonnet::assigncustomrole(
 4051:                                $env{'form.ccdomain'}, $env{'form.ccuname'},
 4052:                                $url,$rdom,$rnam,$rolename,0,$now,undef,$context);
 4053:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
 4054:                     &mt('Re-enabling custom role [_1] by [_2] in [_3]',
 4055:                         $rolename,$rnam.':'.$rdom,&Apache::loncommon::show_role_extent($1,$context,'cr')),
 4056:                     $result ne "ok").'<br />');
 4057:                 if ($result ne "ok") {
 4058:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 4059:                 }
 4060:                 if (!grep(/^cr$/,@rolechanges)) {
 4061:                     push(@rolechanges,'cr');
 4062:                 }
 4063:             }
 4064: 	} elsif ($key=~/^form\.act/) {
 4065:             my $udom = $env{'form.ccdomain'};
 4066:             my $uname = $env{'form.ccuname'};
 4067: 	    if ($key=~/^form\.act\_($match_domain)\_($match_courseid)\_cr_cr_($match_domain)_($match_username)_([^\_]+)$/) {
 4068:                 # Activate a custom role
 4069: 		my ($one,$two,$three,$four,$five)=($1,$2,$3,$4,$5);
 4070: 		my $url='/'.$one.'/'.$two;
 4071: 		my $full=$one.'_'.$two.'_cr_cr_'.$three.'_'.$four.'_'.$five;
 4072: 
 4073:                 my $start = ( $env{'form.start_'.$full} ?
 4074:                               $env{'form.start_'.$full} :
 4075:                               $now );
 4076:                 my $end   = ( $env{'form.end_'.$full} ?
 4077:                               $env{'form.end_'.$full} :
 4078:                               0 );
 4079:                                                                                      
 4080:                 # split multiple sections
 4081:                 my %sections = ();
 4082:                 my $num_sections = &build_roles($env{'form.sec_'.$full},\%sections,$5);
 4083:                 if ($num_sections == 0) {
 4084:                     $r->print(&Apache::loncommon::commit_customrole($udom,$uname,$url,$three,$four,$five,$start,$end,$context));
 4085:                 } else {
 4086: 		    my %curr_groups =
 4087: 			&Apache::longroup::coursegroups($one,$two);
 4088:                     foreach my $sec (sort {$a cmp $b} keys(%sections)) {
 4089:                         if (($sec eq 'none') || ($sec eq 'all') || 
 4090:                             exists($curr_groups{$sec})) {
 4091:                             $disallowed{$sec} = $url;
 4092:                             next;
 4093:                         }
 4094:                         my $securl = $url.'/'.$sec;
 4095: 		        $r->print(&Apache::loncommon::commit_customrole($udom,$uname,$securl,$three,$four,$five,$start,$end,$context));
 4096:                     }
 4097:                 }
 4098:                 if (!grep(/^cr$/,@rolechanges)) {
 4099:                     push(@rolechanges,'cr');
 4100:                 }
 4101: 	    } elsif ($key=~/^form\.act\_($match_domain)\_($match_name)\_([^\_]+)$/) {
 4102: 		# Activate roles for sections with 3 id numbers
 4103: 		# set start, end times, and the url for the class
 4104: 		my ($one,$two,$three)=($1,$2,$3);
 4105: 		my $start = ( $env{'form.start_'.$one.'_'.$two.'_'.$three} ? 
 4106: 			      $env{'form.start_'.$one.'_'.$two.'_'.$three} : 
 4107: 			      $now );
 4108: 		my $end   = ( $env{'form.end_'.$one.'_'.$two.'_'.$three} ? 
 4109: 			      $env{'form.end_'.$one.'_'.$two.'_'.$three} :
 4110: 			      0 );
 4111: 		my $url='/'.$one.'/'.$two;
 4112:                 my $type = 'three';
 4113:                 # split multiple sections
 4114:                 my %sections = ();
 4115:                 my $num_sections = &build_roles($env{'form.sec_'.$one.'_'.$two.'_'.$three},\%sections,$three);
 4116:                 my $credits;
 4117:                 if ($three eq 'st') {
 4118:                     if ($showcredits) { 
 4119:                         my $defaultcredits = 
 4120:                             &Apache::lonuserutils::get_defaultcredits($one,$two);
 4121:                         $credits = $env{'form.credits_'.$one.'_'.$two.'_'.$three};
 4122:                         $credits =~ s/[^\d\.]//g;
 4123:                         if ($credits eq $defaultcredits) {
 4124:                             undef($credits);
 4125:                         }
 4126:                     }
 4127:                 }
 4128:                 if ($num_sections == 0) {
 4129:                     $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$three,$start,$end,$one,$two,'',$context,$credits));
 4130:                 } else {
 4131:                     my %curr_groups = 
 4132: 			&Apache::longroup::coursegroups($one,$two);
 4133:                     my $emptysec = 0;
 4134:                     foreach my $sec (sort {$a cmp $b} keys(%sections)) {
 4135:                         $sec =~ s/\W//g;
 4136:                         if ($sec ne '') {
 4137:                             if (($sec eq 'none') || ($sec eq 'all') || 
 4138:                                 exists($curr_groups{$sec})) {
 4139:                                 $disallowed{$sec} = $url;
 4140:                                 next;
 4141:                             }
 4142:                             my $securl = $url.'/'.$sec;
 4143:                             $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$securl,$three,$start,$end,$one,$two,$sec,$context,$credits));
 4144:                         } else {
 4145:                             $emptysec = 1;
 4146:                         }
 4147:                     }
 4148:                     if ($emptysec) {
 4149:                         $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$three,$start,$end,$one,$two,'',$context,$credits));
 4150:                     }
 4151:                 }
 4152:                 if (!grep(/^\Q$three\E$/,@rolechanges)) {
 4153:                     push(@rolechanges,$three);
 4154:                 }
 4155: 	    } elsif ($key=~/^form\.act\_([^\_]+)\_([^\_]+)$/) {
 4156: 		# Activate roles for sections with two id numbers
 4157: 		# set start, end times, and the url for the class
 4158: 		my $start = ( $env{'form.start_'.$1.'_'.$2} ? 
 4159: 			      $env{'form.start_'.$1.'_'.$2} : 
 4160: 			      $now );
 4161: 		my $end   = ( $env{'form.end_'.$1.'_'.$2} ? 
 4162: 			      $env{'form.end_'.$1.'_'.$2} :
 4163: 			      0 );
 4164:                 my $one = $1;
 4165:                 my $two = $2;
 4166: 		my $url='/'.$one.'/';
 4167:                 # split multiple sections
 4168:                 my %sections = ();
 4169:                 my $num_sections = &build_roles($env{'form.sec_'.$one.'_'.$two},\%sections,$two);
 4170:                 if ($num_sections == 0) {
 4171:                     $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$two,$start,$end,$one,undef,'',$context));
 4172:                 } else {
 4173:                     my $emptysec = 0;
 4174:                     foreach my $sec (sort {$a cmp $b} keys(%sections)) {
 4175:                         if ($sec ne '') {
 4176:                             my $securl = $url.'/'.$sec;
 4177:                             $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$securl,$two,$start,$end,$one,undef,$sec,$context));
 4178:                         } else {
 4179:                             $emptysec = 1;
 4180:                         }
 4181:                     }
 4182:                     if ($emptysec) {
 4183:                         $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$two,$start,$end,$one,undef,'',$context));
 4184:                     }
 4185:                 }
 4186:                 if (!grep(/^\Q$two\E$/,@rolechanges)) {
 4187:                     push(@rolechanges,$two);
 4188:                 }
 4189: 	    } else {
 4190: 		$r->print('<p><span class="LC_error">'.&mt('ERROR').': '.&mt('Unknown command').' <tt>'.$key.'</tt></span></p><br />');
 4191:             }
 4192:             foreach my $key (sort(keys(%disallowed))) {
 4193:                 $r->print('<p class="LC_warning">');
 4194:                 if (($key eq 'none') || ($key eq 'all')) {  
 4195:                     $r->print(&mt('[_1] may not be used as the name for a section, as it is a reserved word.','<tt>'.$key.'</tt>'));
 4196:                 } else {
 4197:                     $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>'));
 4198:                 }
 4199:                 $r->print('</p><p>'
 4200:                          .&mt('Please [_1]go back[_2] and choose a different section name.'
 4201:                              ,'<a href="javascript:history.go(-1)'
 4202:                              ,'</a>')
 4203:                          .'</p><br />'
 4204:                 );
 4205:             }
 4206: 	}
 4207:     } # End of foreach (keys(%env))
 4208: # Flush the course logs so reverse user roles immediately updated
 4209:     $r->register_cleanup(\&Apache::lonnet::flushcourselogs);
 4210:     if (@rolechanges == 0) {
 4211:         $r->print('<p>'.&mt('No roles to modify').'</p>');
 4212:     }
 4213:     return @rolechanges;
 4214: }
 4215: 
 4216: sub get_user_credits {
 4217:     my ($uname,$udom,$defaultcredits,$cdom,$cnum) = @_;
 4218:     if ($cdom eq '' || $cnum eq '') {
 4219:         return unless ($env{'request.course.id'});
 4220:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4221:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4222:     }
 4223:     my $credits;
 4224:     my %currhash =
 4225:         &Apache::lonnet::get('classlist',[$uname.':'.$udom],$cdom,$cnum);
 4226:     if (keys(%currhash) > 0) {
 4227:         my @items = split(/:/,$currhash{$uname.':'.$udom});
 4228:         my $crdidx = &Apache::loncoursedata::CL_CREDITS() - 3;
 4229:         $credits = $items[$crdidx];
 4230:         $credits =~ s/[^\d\.]//g;
 4231:     }
 4232:     if ($credits eq $defaultcredits) {
 4233:         undef($credits);
 4234:     }
 4235:     return $credits;
 4236: }
 4237: 
 4238: sub enroll_single_student {
 4239:     my ($r,$uhome,$amode,$genpwd,$now,$newuser,$context,$crstype,
 4240:         $showcredits,$defaultcredits) = @_;
 4241:     $r->print('<h3>');
 4242:     if ($crstype eq 'Community') {
 4243:         $r->print(&mt('Enrolling Member'));
 4244:     } else {
 4245:         $r->print(&mt('Enrolling Student'));
 4246:     }
 4247:     $r->print('</h3>');
 4248: 
 4249:     # Remove non alphanumeric values from section
 4250:     $env{'form.sections'}=~s/\W//g;
 4251: 
 4252:     my $credits;
 4253:     if (($showcredits) && ($env{'form.credits'} ne '')) {
 4254:         $credits = $env{'form.credits'};
 4255:         $credits =~ s/[^\d\.]//g;
 4256:         if ($credits ne '') {
 4257:             if ($credits eq $defaultcredits) {
 4258:                 undef($credits);
 4259:             }
 4260:         }
 4261:     }
 4262: 
 4263:     # Clean out any old student roles the user has in this class.
 4264:     &Apache::lonuserutils::modifystudent($env{'form.ccdomain'},
 4265:          $env{'form.ccuname'},$env{'request.course.id'},undef,$uhome);
 4266:     my ($startdate,$enddate) = &Apache::lonuserutils::get_dates_from_form();
 4267:     my $enroll_result =
 4268:         &Apache::lonnet::modify_student_enrollment($env{'form.ccdomain'},
 4269:             $env{'form.ccuname'},$env{'form.cid'},$env{'form.cfirstname'},
 4270:             $env{'form.cmiddlename'},$env{'form.clastname'},
 4271:             $env{'form.generation'},$env{'form.sections'},$enddate,
 4272:             $startdate,'manual',undef,$env{'request.course.id'},'',$context,
 4273:             $credits);
 4274:     if ($enroll_result =~ /^ok/) {
 4275:         $r->print(&mt('[_1] enrolled','<b>'.$env{'form.ccuname'}.':'.$env{'form.ccdomain'}.'</b>'));
 4276:         if ($env{'form.sections'} ne '') {
 4277:             $r->print(' '.&mt('in section [_1]',$env{'form.sections'}));
 4278:         }
 4279:         my ($showstart,$showend);
 4280:         if ($startdate <= $now) {
 4281:             $showstart = &mt('Access starts immediately');
 4282:         } else {
 4283:             $showstart = &mt('Access starts: ').&Apache::lonlocal::locallocaltime($startdate);
 4284:         }
 4285:         if ($enddate == 0) {
 4286:             $showend = &mt('ends: no ending date');
 4287:         } else {
 4288:             $showend = &mt('ends: ').&Apache::lonlocal::locallocaltime($enddate);
 4289:         }
 4290:         $r->print('.<br />'.$showstart.'; '.$showend);
 4291:         if ($startdate <= $now && !$newuser) {
 4292:             $r->print('<p class="LC_info">');
 4293:             if ($crstype eq 'Community') {
 4294:                 $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.'));
 4295:             } else {
 4296:                 $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.'));
 4297:            }
 4298:            $r->print('</p>');
 4299:         }
 4300:     } else {
 4301:         $r->print(&mt('unable to enroll').": ".$enroll_result);
 4302:     }
 4303:     return;
 4304: }
 4305: 
 4306: sub get_defaultquota_text {
 4307:     my ($settingstatus) = @_;
 4308:     my $defquotatext; 
 4309:     if ($settingstatus eq '') {
 4310:         $defquotatext = &mt('default');
 4311:     } else {
 4312:         my ($usertypes,$order) =
 4313:             &Apache::lonnet::retrieve_inst_usertypes($env{'form.ccdomain'});
 4314:         if ($usertypes->{$settingstatus} eq '') {
 4315:             $defquotatext = &mt('default');
 4316:         } else {
 4317:             $defquotatext = &mt('default for [_1]',$usertypes->{$settingstatus});
 4318:         }
 4319:     }
 4320:     return $defquotatext;
 4321: }
 4322: 
 4323: sub update_result_form {
 4324:     my ($uhome) = @_;
 4325:     my $outcome = 
 4326:     '<form name="userupdate" method="post" action="">'."\n";
 4327:     foreach my $item ('srchby','srchin','srchtype','srchterm','srchdomain','ccuname','ccdomain') {
 4328:         $outcome .= '<input type="hidden" name="'.$item.'" value="'.$env{'form.'.$item}.'" />'."\n";
 4329:     }
 4330:     if ($env{'form.origname'} ne '') {
 4331:         $outcome .= '<input type="hidden" name="origname" value="'.$env{'form.origname'}.'" />'."\n";
 4332:     }
 4333:     foreach my $item ('sortby','seluname','seludom') {
 4334:         if (exists($env{'form.'.$item})) {
 4335:             $outcome .= '<input type="hidden" name="'.$item.'" value="'.$env{'form.'.$item}.'" />'."\n";
 4336:         }
 4337:     }
 4338:     if ($uhome eq 'no_host') {
 4339:         $outcome .= '<input type="hidden" name="forcenewuser" value="1" />'."\n";
 4340:     }
 4341:     $outcome .= '<input type="hidden" name="phase" value="" />'."\n".
 4342:                 '<input type="hidden" name="currstate" value="" />'."\n".
 4343:                 '<input type="hidden" name="action" value="'.$env{'form.action'}.'" />'."\n".
 4344:                 '</form>';
 4345:     return $outcome;
 4346: }
 4347: 
 4348: sub quota_admin {
 4349:     my ($setquota,$changeHash,$name) = @_;
 4350:     my $quotachanged;
 4351:     if (&Apache::lonnet::allowed('mpq',$env{'form.ccdomain'})) {
 4352:         # Current user has quota modification privileges
 4353:         if (ref($changeHash) eq 'HASH') {
 4354:             $quotachanged = 1;
 4355:             $changeHash->{$name.'quota'} = $setquota;
 4356:         }
 4357:     }
 4358:     return $quotachanged;
 4359: }
 4360: 
 4361: sub tool_admin {
 4362:     my ($tool,$settool,$changeHash,$context) = @_;
 4363:     my $canchange = 0; 
 4364:     if ($context eq 'requestcourses') {
 4365:         if (&Apache::lonnet::allowed('ccc',$env{'form.ccdomain'})) {
 4366:             $canchange = 1;
 4367:         }
 4368:     } elsif ($context eq 'reqcrsotherdom') {
 4369:         if (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) {
 4370:             $canchange = 1;
 4371:         }
 4372:     } elsif ($context eq 'requestauthor') {
 4373:         if (&Apache::lonnet::allowed('cau',$env{'request.role.domain'})) {
 4374:             $canchange = 1;
 4375:         }
 4376:     } elsif (&Apache::lonnet::allowed('mut',$env{'form.ccdomain'})) {
 4377:         # Current user has quota modification privileges
 4378:         $canchange = 1;
 4379:     }
 4380:     my $toolchanged;
 4381:     if ($canchange) {
 4382:         if (ref($changeHash) eq 'HASH') {
 4383:             $toolchanged = 1;
 4384:             if ($tool eq 'requestauthor') {
 4385:                 $changeHash->{$context} = $settool;
 4386:             } else {
 4387:                 $changeHash->{$context.'.'.$tool} = $settool;
 4388:             }
 4389:         }
 4390:     }
 4391:     return $toolchanged;
 4392: }
 4393: 
 4394: sub build_roles {
 4395:     my ($sectionstr,$sections,$role) = @_;
 4396:     my $num_sections = 0;
 4397:     if ($sectionstr=~ /,/) {
 4398:         my @secnums = split/,/,$sectionstr;
 4399:         if ($role eq 'st') {
 4400:             $secnums[0] =~ s/\W//g;
 4401:             $$sections{$secnums[0]} = 1;
 4402:             $num_sections = 1;
 4403:         } else {
 4404:             foreach my $sec (@secnums) {
 4405:                 $sec =~ ~s/\W//g;
 4406:                 if (!($sec eq "")) {
 4407:                     if (exists($$sections{$sec})) {
 4408:                         $$sections{$sec} ++;
 4409:                     } else {
 4410:                         $$sections{$sec} = 1;
 4411:                         $num_sections ++;
 4412:                     }
 4413:                 }
 4414:             }
 4415:         }
 4416:     } else {
 4417:         $sectionstr=~s/\W//g;
 4418:         unless ($sectionstr eq '') {
 4419:             $$sections{$sectionstr} = 1;
 4420:             $num_sections ++;
 4421:         }
 4422:     }
 4423: 
 4424:     return $num_sections;
 4425: }
 4426: 
 4427: # ========================================================== Custom Role Editor
 4428: 
 4429: sub custom_role_editor {
 4430:     my ($r,$context,$brcrum,$prefix,$permission) = @_;
 4431:     my $action = $env{'form.customroleaction'};
 4432:     my ($rolename,$helpitem);
 4433:     if ($action eq 'new') {
 4434:         $rolename=$env{'form.newrolename'};
 4435:     } else {
 4436:         $rolename=$env{'form.rolename'};
 4437:     }
 4438: 
 4439:     my ($crstype,$context);
 4440:     if ($env{'request.course.id'}) {
 4441:         $crstype = &Apache::loncommon::course_type();
 4442:         $context = 'course';
 4443:         $helpitem = 'Course_Editing_Custom_Roles';
 4444:     } else {
 4445:         $context = 'domain';
 4446:         $crstype = 'course';
 4447:         $helpitem = 'Domain_Editing_Custom_Roles';
 4448:     }
 4449: 
 4450:     $rolename=~s/[^A-Za-z0-9]//gs;
 4451:     if (!$rolename || $env{'form.phase'} eq 'pickrole') {
 4452: 	&print_username_entry_form($r,$context,undef,undef,undef,$crstype,$brcrum,
 4453:                                    $permission);
 4454:         return;
 4455:     }
 4456: 
 4457:     my $formname = 'form1';
 4458:     my %privs=();
 4459:     my $body_top = '<h2>';
 4460: # ------------------------------------------------------- Does this role exist?
 4461:     my ($rdummy,$roledef)=
 4462: 			 &Apache::lonnet::get('roles',["rolesdef_$rolename"]);
 4463:     if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 4464:         $body_top .= &mt('Existing Role').' "';
 4465: # ------------------------------------------------- Get current role privileges
 4466:         ($privs{'system'},$privs{'domain'},$privs{'course'})=split(/\_/,$roledef);
 4467:         if ($privs{'system'} =~ /bre\&S/) {
 4468:             if ($context eq 'domain') {
 4469:                 $crstype = 'Course';
 4470:             } elsif ($crstype eq 'Community') {
 4471:                 $privs{'system'} =~ s/bre\&S//;
 4472:             }
 4473:         } elsif ($context eq 'domain') {
 4474:             $crstype = 'Course';
 4475:         }
 4476:     } else {
 4477:         $body_top .= &mt('New Role').' "';
 4478:         $roledef='';
 4479:     }
 4480:     $body_top .= $rolename.'"</h2>';
 4481: 
 4482: # ------------------------------------------------------- What can be assigned?
 4483:     my %full=();
 4484:     my %levels=(
 4485:                  course => {},
 4486:                  domain => {},
 4487:                  system => {},
 4488:                );
 4489:     my %levelscurrent=(
 4490:                         course => {},
 4491:                         domain => {},
 4492:                         system => {},
 4493:                       );
 4494:     &Apache::lonuserutils::custom_role_privs(\%privs,\%full,\%levels,\%levelscurrent);
 4495:     my ($jsback,$elements) = &crumb_utilities();
 4496:     my @templateroles = &Apache::lonuserutils::custom_template_roles($context,$crstype);
 4497:     my $head_script =
 4498:         &Apache::lonuserutils::custom_roledefs_js($context,$crstype,$formname,
 4499:                                                   \%full,\@templateroles,$jsback);
 4500:     push (@{$brcrum},
 4501:               {href => "javascript:backPage(document.$formname,'pickrole','')",
 4502:                text => "Pick custom role",
 4503:                faq  => 282,bug=>'Instructor Interface',},
 4504:               {href => "javascript:backPage(document.$formname,'','')",
 4505:                text => "Edit custom role",
 4506:                faq  => 282,
 4507:                bug  => 'Instructor Interface',
 4508:                help => $helpitem}
 4509:               );
 4510:     my $args = { bread_crumbs          => $brcrum,
 4511:                  bread_crumbs_component => 'User Management'};
 4512:     $r->print(&Apache::loncommon::start_page('Custom Role Editor',
 4513:                                              $head_script,$args).
 4514:               $body_top);
 4515:     $r->print('<form name="'.$formname.'" method="post" action="">'."\n".
 4516:               &Apache::lonuserutils::custom_role_header($context,$crstype,
 4517:                                                         \@templateroles,$prefix));
 4518: 
 4519:     $r->print(<<ENDCCF);
 4520: <input type="hidden" name="phase" value="set_custom_roles" />
 4521: <input type="hidden" name="rolename" value="$rolename" />
 4522: ENDCCF
 4523:     $r->print(&Apache::lonuserutils::custom_role_table($crstype,\%full,\%levels,
 4524:                                                        \%levelscurrent,$prefix));
 4525:     $r->print(&Apache::loncommon::end_data_table().
 4526:    '<input type="hidden" name="action" value="'.$env{'form.action'}.'" />'.
 4527:    '<input type="hidden" name="startrolename" value="'.$env{'form.rolename'}.
 4528:    '" />'."\n".'<input type="hidden" name="currstate" value="" />'."\n".
 4529:    '<input type="reset" value="'.&mt("Reset").'" />'."\n".
 4530:    '<input type="submit" value="'.&mt('Save').'" /></form>');
 4531: }
 4532: 
 4533: # ---------------------------------------------------------- Call to definerole
 4534: sub set_custom_role {
 4535:     my ($r,$context,$brcrum,$prefix,$permission) = @_;
 4536:     my $rolename=$env{'form.rolename'};
 4537:     $rolename=~s/[^A-Za-z0-9]//gs;
 4538:     if (!$rolename) {
 4539: 	&custom_role_editor($r,$context,$brcrum,$prefix,$permission);
 4540:         return;
 4541:     }
 4542:     my ($jsback,$elements) = &crumb_utilities();
 4543:     my $jscript = '<script type="text/javascript">'
 4544:                  .'// <![CDATA['."\n"
 4545:                  .$jsback."\n"
 4546:                  .'// ]]>'."\n"
 4547:                  .'</script>'."\n";
 4548:     my $helpitem = 'Course_Editing_Custom_Roles';
 4549:     if ($context eq 'domain') {
 4550:         $helpitem = 'Domain_Editing_Custom_Roles';
 4551:     }
 4552:     push(@{$brcrum},
 4553:         {href => "javascript:backPage(document.customresult,'pickrole','')",
 4554:          text => "Pick custom role",
 4555:          faq  => 282,
 4556:          bug  => 'Instructor Interface',},
 4557:         {href => "javascript:backPage(document.customresult,'selected_custom_edit','')",
 4558:          text => "Edit custom role",
 4559:          faq  => 282,
 4560:          bug  => 'Instructor Interface',},
 4561:         {href => "javascript:backPage(document.customresult,'set_custom_roles','')",
 4562:          text => "Result",
 4563:          faq  => 282,
 4564:          bug  => 'Instructor Interface',
 4565:          help => $helpitem,}
 4566:         );
 4567:     my $args = { bread_crumbs           => $brcrum,
 4568:                  bread_crumbs_component => 'User Management'};
 4569:     $r->print(&Apache::loncommon::start_page('Save Custom Role',$jscript,$args));
 4570: 
 4571:     my $newrole;
 4572:     my ($rdummy,$roledef)=
 4573: 	&Apache::lonnet::get('roles',["rolesdef_$rolename"]);
 4574: 
 4575: # ------------------------------------------------------- Does this role exist?
 4576:     $r->print('<h3>');
 4577:     if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 4578: 	$r->print(&mt('Existing Role').' "');
 4579:     } else {
 4580: 	$r->print(&mt('New Role').' "');
 4581: 	$roledef='';
 4582:         $newrole = 1;
 4583:     }
 4584:     $r->print($rolename.'"</h3>');
 4585: # ------------------------------------------------- Assign role and show result
 4586: 
 4587:     my $errmsg;
 4588:     my %newprivs = &Apache::lonuserutils::custom_role_update($rolename,$prefix);
 4589:     # Assign role and return result
 4590:     my $result = &Apache::lonnet::definerole($rolename,$newprivs{'s'},$newprivs{'d'},
 4591:                                              $newprivs{'c'});
 4592:     if ($result ne 'ok') {
 4593:         $errmsg = ': '.$result;
 4594:     }
 4595:     my $message =
 4596:         &Apache::lonhtmlcommon::confirm_success(
 4597:             &mt('Defining Role').$errmsg, ($result eq 'ok' ? 0 : 1));
 4598:     if ($env{'request.course.id'}) {
 4599:         my $url='/'.$env{'request.course.id'};
 4600:         $url=~s/\_/\//g;
 4601:         $result =
 4602:             &Apache::lonnet::assigncustomrole(
 4603:                 $env{'user.domain'},$env{'user.name'},
 4604:                 $url,
 4605:                 $env{'user.domain'},$env{'user.name'},
 4606:                 $rolename,undef,undef,undef,$context);
 4607:         if ($result ne 'ok') {
 4608:             $errmsg = ': '.$result;
 4609:         }
 4610:         $message .=
 4611:             '<br />'
 4612:            .&Apache::lonhtmlcommon::confirm_success(
 4613:                 &mt('Assigning Role to Self').$errmsg, ($result eq 'ok' ? 0 : 1));
 4614:     }
 4615:     $r->print(
 4616:         &Apache::loncommon::confirmwrapper($message)
 4617:        .'<br />'
 4618:        .&Apache::lonhtmlcommon::actionbox([
 4619:             '<a href="javascript:backPage(document.customresult,'."'pickrole'".')">'
 4620:            .&mt('Create or edit another custom role')
 4621:            .'</a>'])
 4622:        .'<form name="customresult" method="post" action="">'
 4623:        .&Apache::lonhtmlcommon::echo_form_input([])
 4624:        .'</form>'
 4625:     );
 4626: }
 4627: 
 4628: # ================================================================ Main Handler
 4629: sub handler {
 4630:     my $r = shift;
 4631:     if ($r->header_only) {
 4632:        &Apache::loncommon::content_type($r,'text/html');
 4633:        $r->send_http_header;
 4634:        return OK;
 4635:     }
 4636:     my ($context,$crstype,$cid,$cnum,$cdom,$allhelpitems);
 4637: 
 4638:     if ($env{'request.course.id'}) {
 4639:         $context = 'course';
 4640:         $crstype = &Apache::loncommon::course_type();
 4641:     } elsif ($env{'request.role'} =~ /^au\./) {
 4642:         $context = 'author';
 4643:     } else {
 4644:         $context = 'domain';
 4645:     }
 4646: 
 4647:     my ($permission,$allowed) =
 4648:         &Apache::lonuserutils::get_permission($context,$crstype);
 4649: 
 4650:     if ($allowed) {
 4651:         my @allhelp;
 4652:         if ($context eq 'course') {
 4653:             $cid = $env{'request.course.id'};
 4654:             $cdom = $env{'course.'.$cid.'.domain'};
 4655:             $cnum = $env{'course.'.$cid.'.num'};
 4656: 
 4657:             if ($permission->{'cusr'}) {
 4658:                 push(@allhelp,'Course_Create_Class_List');
 4659:             }
 4660:             if ($permission->{'view'} || $permission->{'cusr'}) {
 4661:                 push(@allhelp,('Course_Change_Privileges','Course_View_Class_List'));
 4662:             }
 4663:             if ($permission->{'custom'}) {
 4664:                 push(@allhelp,'Course_Editing_Custom_Roles');
 4665:             }
 4666:             if ($permission->{'cusr'}) {
 4667:                 push(@allhelp,('Course_Add_Student','Course_Drop_Student'));
 4668:             }
 4669:             unless ($permission->{'cusr_section'}) {
 4670:                 if (&Apache::lonnet::auto_run($cnum,$cdom) && (($permission->{'cusr'}) || ($permission->{'view'}))) {
 4671:                     push(@allhelp,'Course_Automated_Enrollment');
 4672:                 }
 4673:                 if ($permission->{'selfenrolladmin'}) {
 4674:                     push(@allhelp,'Course_Approve_Selfenroll');
 4675:                 }
 4676:             }
 4677:             if ($permission->{'grp_manage'}) {
 4678:                 push(@allhelp,'Course_Manage_Group');
 4679:             }
 4680:             if ($permission->{'view'} || $permission->{'cusr'}) {
 4681:                 push(@allhelp,'Course_User_Logs');
 4682:             }
 4683:         } elsif ($context eq 'author') {
 4684:             push(@allhelp,('Author_Change_Privileges','Author_Create_Coauthor_List',
 4685:                            'Author_View_Coauthor_List','Author_User_Logs'));
 4686:         } else {
 4687:             if ($permission->{'cusr'}) {
 4688:                 push(@allhelp,'Domain_Change_Privileges');
 4689:                 if ($permission->{'activity'}) {
 4690:                     push(@allhelp,'Domain_User_Access_Logs');
 4691:                 }
 4692:                 push(@allhelp,('Domain_Create_Users','Domain_View_Users_List'));
 4693:                 if ($permission->{'custom'}) {
 4694:                     push(@allhelp,'Domain_Editing_Custom_Roles');
 4695:                 }
 4696:                 push(@allhelp,('Domain_Role_Approvals','Domain_Username_Approvals','Domain_Change_Logs'));
 4697:             } elsif ($permission->{'view'}) {
 4698:                 push(@allhelp,'Domain_View_Privileges');
 4699:                 if ($permission->{'activity'}) {
 4700:                     push(@allhelp,'Domain_User_Access_Logs');
 4701:                 }
 4702:                 push(@allhelp,('Domain_View_Users_List','Domain_Change_Logs'));
 4703:             }
 4704:         }
 4705:         if (@allhelp) {
 4706:             $allhelpitems = join(',',@allhelp);
 4707:         }
 4708:     }
 4709: 
 4710:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 4711:         ['action','state','callingform','roletype','showrole','bulkaction','popup','phase',
 4712:          'username','domain','srchterm','srchdomain','srchin','srchby','srchtype','queue']);
 4713:     &Apache::lonhtmlcommon::clear_breadcrumbs();
 4714:     my $args;
 4715:     my $brcrum = [];
 4716:     my $bread_crumbs_component = 'User Management';
 4717:     if (($env{'form.action'} ne 'dateselect') && ($env{'form.action'} ne 'displayuserreq')) {
 4718:         $brcrum = [{href=>"/adm/createuser",
 4719:                     text=>"User Management",
 4720:                     help=>$allhelpitems}
 4721:                   ];
 4722:     }
 4723:     if (!$allowed) {
 4724:         if ($context eq 'course') {
 4725:             $r->internal_redirect('/adm/viewclasslist');
 4726:             return OK;
 4727:         }
 4728:         $env{'user.error.msg'}=
 4729:             "/adm/createuser:cst:0:0:Cannot create/modify user data ".
 4730:                                  "or view user status.";
 4731:         return HTTP_NOT_ACCEPTABLE;
 4732:     }
 4733: 
 4734:     &Apache::loncommon::content_type($r,'text/html');
 4735:     $r->send_http_header;
 4736: 
 4737:     my $showcredits;
 4738:     if ((($context eq 'course') && ($crstype eq 'Course')) || 
 4739:          ($context eq 'domain')) {
 4740:         my %domdefaults = 
 4741:             &Apache::lonnet::get_domain_defaults($env{'request.role.domain'});
 4742:         if ($domdefaults{'officialcredits'} || $domdefaults{'unofficialcredits'}) {
 4743:             $showcredits = 1;
 4744:         }
 4745:     }
 4746: 
 4747:     # Main switch on form.action and form.state, as appropriate
 4748:     if (! exists($env{'form.action'})) {
 4749:         $args = {bread_crumbs => $brcrum,
 4750:                  bread_crumbs_component => $bread_crumbs_component}; 
 4751:         $r->print(&header(undef,$args));
 4752:         $r->print(&print_main_menu($permission,$context,$crstype));
 4753:     } elsif ($env{'form.action'} eq 'upload' && $permission->{'cusr'}) {
 4754:         my $helpitem = 'Course_Create_Class_List';
 4755:         if ($context eq 'author') {
 4756:             $helpitem = 'Author_Create_Coauthor_List';
 4757:         } elsif ($context eq 'domain') {
 4758:             $helpitem = 'Domain_Create_Users';
 4759:         }
 4760:         push(@{$brcrum},
 4761:               { href => '/adm/createuser?action=upload&state=',
 4762:                 text => 'Upload Users List',
 4763:                 help => $helpitem,
 4764:               });
 4765:         $bread_crumbs_component = 'Upload Users List';
 4766:         $args = {bread_crumbs           => $brcrum,
 4767:                  bread_crumbs_component => $bread_crumbs_component};
 4768:         $r->print(&header(undef,$args));
 4769:         $r->print('<form name="studentform" method="post" '.
 4770:                   'enctype="multipart/form-data" '.
 4771:                   ' action="/adm/createuser">'."\n");
 4772:         if (! exists($env{'form.state'})) {
 4773:             &Apache::lonuserutils::print_first_users_upload_form($r,$context);
 4774:         } elsif ($env{'form.state'} eq 'got_file') {
 4775:             my $result =
 4776:                 &Apache::lonuserutils::print_upload_manager_form($r,$context,
 4777:                                                                  $permission,
 4778:                                                                  $crstype,$showcredits);
 4779:             if ($result eq 'missingdata') {
 4780:                 delete($env{'form.state'});
 4781:                 &Apache::lonuserutils::print_first_users_upload_form($r,$context);
 4782:             }
 4783:         } elsif ($env{'form.state'} eq 'enrolling') {
 4784:             if ($env{'form.datatoken'}) {
 4785:                 my $result = &Apache::lonuserutils::upfile_drop_add($r,$context,
 4786:                                                                     $permission,
 4787:                                                                     $showcredits);
 4788:                 if ($result eq 'missingdata') {
 4789:                     delete($env{'form.state'});
 4790:                     &Apache::lonuserutils::print_first_users_upload_form($r,$context);
 4791:                 } elsif ($result eq 'invalidhome') {
 4792:                     $env{'form.state'} = 'got_file';
 4793:                     delete($env{'form.lcserver'});
 4794:                     my $result =
 4795:                         &Apache::lonuserutils::print_upload_manager_form($r,$context,$permission,
 4796:                                                                          $crstype,$showcredits);
 4797:                     if ($result eq 'missingdata') {
 4798:                         delete($env{'form.state'});
 4799:                         &Apache::lonuserutils::print_first_users_upload_form($r,$context);
 4800:                     }
 4801:                 }
 4802:             } else {
 4803:                 delete($env{'form.state'});
 4804:                 &Apache::lonuserutils::print_first_users_upload_form($r,$context);
 4805:             }
 4806:         } else {
 4807:             &Apache::lonuserutils::print_first_users_upload_form($r,$context);
 4808:         }
 4809:         $r->print('</form>');
 4810:     } elsif (((($env{'form.action'} eq 'singleuser') || ($env{'form.action'}
 4811:               eq 'singlestudent')) && ($permission->{'cusr'})) ||
 4812:              (($env{'form.action'} eq 'singleuser') && ($permission->{'view'})) ||
 4813:              (($env{'form.action'} eq 'accesslogs') && ($permission->{'activity'}))) {
 4814:         my $phase = $env{'form.phase'};
 4815:         my @search = ('srchterm','srchby','srchin','srchtype','srchdomain');
 4816: 	&Apache::loncreateuser::restore_prev_selections();
 4817: 	my $srch;
 4818: 	foreach my $item (@search) {
 4819: 	    $srch->{$item} = $env{'form.'.$item};
 4820: 	}
 4821:         if (($phase eq 'get_user_info') || ($phase eq 'userpicked') ||
 4822:             ($phase eq 'createnewuser') || ($phase eq 'activity')) {
 4823:             if ($env{'form.phase'} eq 'createnewuser') {
 4824:                 my $response;
 4825:                 if ($env{'form.srchterm'} !~ /^$match_username$/) {
 4826:                     my $response =
 4827:                         '<span class="LC_warning">'
 4828:                        .&mt('You must specify a valid username. Only the following are allowed:'
 4829:                            .' letters numbers - . @')
 4830:                        .'</span>';
 4831:                     $env{'form.phase'} = '';
 4832:                     &print_username_entry_form($r,$context,$response,$srch,undef,
 4833:                                                $crstype,$brcrum,$permission);
 4834:                 } else {
 4835:                     my $ccuname =&LONCAPA::clean_username($srch->{'srchterm'});
 4836:                     my $ccdomain=&LONCAPA::clean_domain($srch->{'srchdomain'});
 4837:                     &print_user_modification_page($r,$ccuname,$ccdomain,
 4838:                                                   $srch,$response,$context,
 4839:                                                   $permission,$crstype,$brcrum,
 4840:                                                   $showcredits);
 4841:                 }
 4842:             } elsif ($env{'form.phase'} eq 'get_user_info') {
 4843:                 my ($currstate,$response,$forcenewuser,$results) = 
 4844:                     &user_search_result($context,$srch);
 4845:                 if ($env{'form.currstate'} eq 'modify') {
 4846:                     $currstate = $env{'form.currstate'};
 4847:                 }
 4848:                 if ($currstate eq 'select') {
 4849:                     &print_user_selection_page($r,$response,$srch,$results,
 4850:                                                \@search,$context,undef,$crstype,
 4851:                                                $brcrum);
 4852:                 } elsif (($currstate eq 'modify') || ($env{'form.action'} eq 'accesslogs')) {
 4853:                     my ($ccuname,$ccdomain,$uhome);
 4854:                     if (($srch->{'srchby'} eq 'uname') && 
 4855:                         ($srch->{'srchtype'} eq 'exact')) {
 4856:                         $ccuname = $srch->{'srchterm'};
 4857:                         $ccdomain= $srch->{'srchdomain'};
 4858:                     } else {
 4859:                         my @matchedunames = keys(%{$results});
 4860:                         ($ccuname,$ccdomain) = split(/:/,$matchedunames[0]);
 4861:                     }
 4862:                     $ccuname =&LONCAPA::clean_username($ccuname);
 4863:                     $ccdomain=&LONCAPA::clean_domain($ccdomain);
 4864:                     if ($env{'form.action'} eq 'accesslogs') {
 4865:                         my $uhome;
 4866:                         if (($ccuname ne '') && ($ccdomain ne '')) {
 4867:                            $uhome = &Apache::lonnet::homeserver($ccuname,$ccdomain);
 4868:                         }
 4869:                         if (($uhome eq '') || ($uhome eq 'no_host')) {
 4870:                             $env{'form.phase'} = '';
 4871:                             undef($forcenewuser);
 4872:                             #if ($response) {
 4873:                             #    unless ($response =~ m{\Q<br /><br />\E$}) {
 4874:                             #        $response .= '<br /><br />';
 4875:                             #    }
 4876:                             #}
 4877:                             &print_username_entry_form($r,$context,$response,$srch,
 4878:                                                        $forcenewuser,$crstype,$brcrum,
 4879:                                                        $permission);
 4880:                         } else {
 4881:                             &print_useraccesslogs_display($r,$ccuname,$ccdomain,$permission,$brcrum);
 4882:                         }
 4883:                     } else {
 4884:                         if ($env{'form.forcenewuser'}) {
 4885:                             $response = '';
 4886:                         }
 4887:                         &print_user_modification_page($r,$ccuname,$ccdomain,
 4888:                                                       $srch,$response,$context,
 4889:                                                       $permission,$crstype,$brcrum);
 4890:                     }
 4891:                 } elsif ($currstate eq 'query') {
 4892:                     &print_user_query_page($r,'createuser',$brcrum);
 4893:                 } else {
 4894:                     $env{'form.phase'} = '';
 4895:                     &print_username_entry_form($r,$context,$response,$srch,
 4896:                                                $forcenewuser,$crstype,$brcrum,
 4897:                                                $permission);
 4898:                 }
 4899:             } elsif ($env{'form.phase'} eq 'userpicked') {
 4900:                 my $ccuname = &LONCAPA::clean_username($env{'form.seluname'});
 4901:                 my $ccdomain = &LONCAPA::clean_domain($env{'form.seludom'});
 4902:                 if ($env{'form.action'} eq 'accesslogs') {
 4903:                     &print_useraccesslogs_display($r,$ccuname,$ccdomain,$permission,$brcrum);
 4904:                 } else {
 4905:                     &print_user_modification_page($r,$ccuname,$ccdomain,$srch,'',
 4906:                                                   $context,$permission,$crstype,
 4907:                                                   $brcrum);
 4908:                 }
 4909:             } elsif ($env{'form.action'} eq 'accesslogs') {
 4910:                 my $ccuname = &LONCAPA::clean_username($env{'form.accessuname'});
 4911:                 my $ccdomain = &LONCAPA::clean_domain($env{'form.accessudom'});
 4912:                 &print_useraccesslogs_display($r,$ccuname,$ccdomain,$permission,$brcrum);
 4913:             }
 4914:         } elsif ($env{'form.phase'} eq 'update_user_data') {
 4915:             &update_user_data($r,$context,$crstype,$brcrum,$showcredits,$permission);
 4916:         } else {
 4917:             &print_username_entry_form($r,$context,undef,$srch,undef,$crstype,
 4918:                                        $brcrum,$permission);
 4919:         }
 4920:     } elsif ($env{'form.action'} eq 'custom' && $permission->{'custom'}) {
 4921:         my $prefix;
 4922:         if ($env{'form.phase'} eq 'set_custom_roles') {
 4923:             &set_custom_role($r,$context,$brcrum,$prefix,$permission);
 4924:         } else {
 4925:             &custom_role_editor($r,$context,$brcrum,$prefix,$permission);
 4926:         }
 4927:     } elsif (($env{'form.action'} eq 'processauthorreq') &&
 4928:              ($permission->{'cusr'}) && 
 4929:              (&Apache::lonnet::allowed('cau',$env{'request.role.domain'}))) {
 4930:         push(@{$brcrum},
 4931:                  {href => '/adm/createuser?action=processauthorreq',
 4932:                   text => 'Authoring Space requests',
 4933:                   help => 'Domain_Role_Approvals'});
 4934:         $bread_crumbs_component = 'Authoring requests';
 4935:         if ($env{'form.state'} eq 'done') {
 4936:             push(@{$brcrum},
 4937:                      {href => '/adm/createuser?action=authorreqqueue',
 4938:                       text => 'Result',
 4939:                       help => 'Domain_Role_Approvals'});
 4940:             $bread_crumbs_component = 'Authoring request result';
 4941:         }
 4942:         $args = { bread_crumbs           => $brcrum,
 4943:                   bread_crumbs_component => $bread_crumbs_component};
 4944:         my $js = &usernamerequest_javascript();
 4945:         $r->print(&header(&add_script($js),$args));
 4946:         if (!exists($env{'form.state'})) {
 4947:             $r->print(&Apache::loncoursequeueadmin::display_queued_requests('requestauthor',
 4948:                                                                             $env{'request.role.domain'}));
 4949:         } elsif ($env{'form.state'} eq 'done') {
 4950:             $r->print('<h3>'.&mt('Authoring request processing').'</h3>'."\n");
 4951:             $r->print(&Apache::loncoursequeueadmin::update_request_queue('requestauthor',
 4952:                                                                          $env{'request.role.domain'}));
 4953:         }
 4954:     } elsif (($env{'form.action'} eq 'processusernamereq') &&
 4955:              ($permission->{'cusr'}) &&
 4956:              (&Apache::lonnet::allowed('cau',$env{'request.role.domain'}))) {
 4957:         push(@{$brcrum},
 4958:                  {href => '/adm/createuser?action=processusernamereq',
 4959:                   text => 'LON-CAPA account requests',
 4960:                   help => 'Domain_Username_Approvals'});
 4961:         $bread_crumbs_component = 'Account requests';
 4962:         if ($env{'form.state'} eq 'done') {
 4963:             push(@{$brcrum},
 4964:                      {href => '/adm/createuser?action=usernamereqqueue',
 4965:                       text => 'Result',
 4966:                       help => 'Domain_Username_Approvals'});
 4967:             $bread_crumbs_component = 'LON-CAPA account request result';
 4968:         }
 4969:         $args = { bread_crumbs           => $brcrum,
 4970:                   bread_crumbs_component => $bread_crumbs_component};
 4971:         my $js = &usernamerequest_javascript();
 4972:         $r->print(&header(&add_script($js),$args));
 4973:         if (!exists($env{'form.state'})) {
 4974:             $r->print(&Apache::loncoursequeueadmin::display_queued_requests('requestusername',
 4975:                                                                             $env{'request.role.domain'}));
 4976:         } elsif ($env{'form.state'} eq 'done') {
 4977:             $r->print('<h3>'.&mt('LON-CAPA account request processing').'</h3>'."\n");
 4978:             $r->print(&Apache::loncoursequeueadmin::update_request_queue('requestusername',
 4979:                                                                          $env{'request.role.domain'}));
 4980:         }
 4981:     } elsif (($env{'form.action'} eq 'displayuserreq') &&
 4982:              ($permission->{'cusr'})) {
 4983:         my $dom = $env{'form.domain'};
 4984:         my $uname = $env{'form.username'};
 4985:         my $warning;
 4986:         if (($dom =~ /^$match_domain$/) && (&Apache::lonnet::domain($dom) ne '')) {
 4987:             if (($dom eq $env{'request.role.domain'}) && (&Apache::lonnet::allowed('ccc',$dom))) {
 4988:                 if (($uname =~ /^$match_username$/) && ($env{'form.queue'} eq 'approval')) {
 4989:                     my $uhome = &Apache::lonnet::homeserver($uname,$dom);
 4990:                     if ($uhome eq 'no_host') {
 4991:                         my $queue = $env{'form.queue'};
 4992:                         my $reqkey = &escape($uname).'_'.$queue; 
 4993:                         my $namespace = 'usernamequeue';
 4994:                         my $domconfig = &Apache::lonnet::get_domainconfiguser($dom);
 4995:                         my %queued =
 4996:                             &Apache::lonnet::get($namespace,[$reqkey],$dom,$domconfig);
 4997:                         unless ($queued{$reqkey}) {
 4998:                             $warning = &mt('No information was found for this LON-CAPA account request.');
 4999:                         }
 5000:                     } else {
 5001:                         $warning = &mt('A LON-CAPA account already exists for the requested username and domain.');
 5002:                     }
 5003:                 } else {
 5004:                     $warning = &mt('LON-CAPA account request status check is for an invalid username.');
 5005:                 }
 5006:             } else {
 5007:                 $warning = &mt('You do not have rights to view LON-CAPA account requests in the domain specified.');
 5008:             }
 5009:         } else {
 5010:             $warning = &mt('LON-CAPA account request status check is for an invalid domain.');
 5011:         }
 5012:         my $args = { only_body => 1 };
 5013:         $r->print(&header(undef,$args).
 5014:                   '<h3>'.&mt('LON-CAPA Account Request Details').'</h3>');
 5015:         if ($warning ne '') {
 5016:             $r->print('<div class="LC_warning">'.$warning.'</div>');
 5017:         } else {
 5018:             my ($infofields,$infotitles) = &Apache::loncommon::emailusername_info();
 5019:             my $domconfiguser = &Apache::lonnet::get_domainconfiguser($dom);
 5020:             my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 5021:             if (ref($domconfig{'usercreation'}) eq 'HASH') {
 5022:                 if (ref($domconfig{'usercreation'}{'cancreate'}) eq 'HASH') {
 5023:                     if (ref($domconfig{'usercreation'}{'cancreate'}{'emailusername'}) eq 'HASH') {
 5024:                         my %info =
 5025:                             &Apache::lonnet::get('nohist_requestedusernames',[$uname],$dom,$domconfiguser);
 5026:                         if (ref($info{$uname}) eq 'HASH') {
 5027:                             my $usertype = $info{$uname}{'inststatus'};
 5028:                             unless ($usertype) {
 5029:                                 $usertype = 'default';
 5030:                             }
 5031:                             my ($showstatus,$showemail,$pickstart);
 5032:                             my $numextras = 0;
 5033:                             my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 5034:                             if ((ref($types) eq 'ARRAY') && (@{$types} > 0)) {
 5035:                                 if (ref($usertypes) eq 'HASH') {
 5036:                                     if ($usertypes->{$usertype}) {
 5037:                                         $showstatus = $usertypes->{$usertype};
 5038:                                     } else {
 5039:                                         $showstatus = $othertitle;
 5040:                                     }
 5041:                                     if ($showstatus) {
 5042:                                         $numextras ++;
 5043:                                     }
 5044:                                 }
 5045:                             }
 5046:                             if (($info{$uname}{'email'} ne '') && ($info{$uname}{'email'} ne $uname)) {
 5047:                                 $showemail = $info{$uname}{'email'};
 5048:                                 $numextras ++;
 5049:                             }
 5050:                             if (ref($domconfig{'usercreation'}{'cancreate'}{'emailusername'}{$usertype}) eq 'HASH') {
 5051:                                 if ((ref($infofields) eq 'ARRAY') && (ref($infotitles) eq 'HASH')) {
 5052:                                     $pickstart = 1;
 5053:                                     $r->print('<div>'.&Apache::lonhtmlcommon::start_pick_box());
 5054:                                     my ($num,$count);
 5055:                                     $count = scalar(keys(%{$domconfig{'usercreation'}{'cancreate'}{'emailusername'}{$usertype}}));
 5056:                                     $count += $numextras;
 5057:                                     foreach my $field (@{$infofields}) {
 5058:                                         next unless ($domconfig{'usercreation'}{'cancreate'}{'emailusername'}{$usertype}{$field});
 5059:                                         next unless ($infotitles->{$field});
 5060:                                         $r->print(&Apache::lonhtmlcommon::row_title($infotitles->{$field}).
 5061:                                                   $info{$uname}{$field});
 5062:                                         $num ++;
 5063:                                         unless ($count == $num) {
 5064:                                             $r->print(&Apache::lonhtmlcommon::row_closure());
 5065:                                         }
 5066:                                     }
 5067:                                 }
 5068:                             }
 5069:                             if ($numextras) {
 5070:                                 unless ($pickstart) {
 5071:                                     $r->print('<div>'.&Apache::lonhtmlcommon::start_pick_box());
 5072:                                     $pickstart = 1;
 5073:                                 }
 5074:                                 if ($showemail) {
 5075:                                     my $closure = '';
 5076:                                     unless ($showstatus) {
 5077:                                         $closure = 1;
 5078:                                     }
 5079:                                     $r->print(&Apache::lonhtmlcommon::row_title(&mt('E-mail address')).
 5080:                                               $showemail.
 5081:                                               &Apache::lonhtmlcommon::row_closure($closure));
 5082:                                 }
 5083:                                 if ($showstatus) {
 5084:                                     $r->print(&Apache::lonhtmlcommon::row_title(&mt('Status type[_1](self-reported)','<br />')).
 5085:                                               $showstatus.
 5086:                                               &Apache::lonhtmlcommon::row_closure(1));
 5087:                                 }
 5088:                             }
 5089:                             if ($pickstart) {
 5090:                                 $r->print(&Apache::lonhtmlcommon::end_pick_box().'</div>');
 5091:                             } else {
 5092:                                 $r->print('<div>'.&mt('No information to display for this account request.').'</div>');
 5093:                             }
 5094:                         } else {
 5095:                             $r->print('<div>'.&mt('No information available for this account request.').'</div>');
 5096:                         }
 5097:                     }
 5098:                 }
 5099:             }
 5100:         }
 5101:         $r->print(&close_popup_form());
 5102:     } elsif (($env{'form.action'} eq 'listusers') && 
 5103:              ($permission->{'view'} || $permission->{'cusr'})) {
 5104:         my $helpitem = 'Course_View_Class_List';
 5105:         if ($context eq 'author') {
 5106:             $helpitem = 'Author_View_Coauthor_List';
 5107:         } elsif ($context eq 'domain') {
 5108:             $helpitem = 'Domain_View_Users_List';
 5109:         }
 5110:         if ($env{'form.phase'} eq 'bulkchange') {
 5111:             push(@{$brcrum},
 5112:                     {href => '/adm/createuser?action=listusers',
 5113:                      text => "List Users"},
 5114:                     {href => "/adm/createuser",
 5115:                      text => "Result",
 5116:                      help => $helpitem});
 5117:             $bread_crumbs_component = 'Update Users';
 5118:             $args = {bread_crumbs           => $brcrum,
 5119:                      bread_crumbs_component => $bread_crumbs_component};
 5120:             $r->print(&header(undef,$args));
 5121:             my $setting = $env{'form.roletype'};
 5122:             my $choice = $env{'form.bulkaction'};
 5123:             if ($permission->{'cusr'}) {
 5124:                 &Apache::lonuserutils::update_user_list($r,$context,$setting,$choice,$crstype);
 5125:             } else {
 5126:                 $r->print(&mt('You are not authorized to make bulk changes to user roles'));
 5127:                 $r->print('<p><a href="/adm/createuser?action=listusers">'.&mt('Display User Lists').'</a>');
 5128:             }
 5129:         } else {
 5130:             push(@{$brcrum},
 5131:                     {href => '/adm/createuser?action=listusers',
 5132:                      text => "List Users",
 5133:                      help => $helpitem});
 5134:             $bread_crumbs_component = 'List Users';
 5135:             $args = {bread_crumbs           => $brcrum,
 5136:                      bread_crumbs_component => $bread_crumbs_component};
 5137:             my ($cb_jscript,$jscript,$totcodes,$codetitles,$idlist,$idlist_titles);
 5138:             my $formname = 'studentform';
 5139:             my $hidecall = "hide_searching();";
 5140:             if (($context eq 'domain') && (($env{'form.roletype'} eq 'course') ||
 5141:                 ($env{'form.roletype'} eq 'community'))) {
 5142:                 if ($env{'form.roletype'} eq 'course') {
 5143:                     ($cb_jscript,$jscript,$totcodes,$codetitles,$idlist,$idlist_titles) = 
 5144:                         &Apache::lonuserutils::courses_selector($env{'request.role.domain'},
 5145:                                                                 $formname);
 5146:                 } elsif ($env{'form.roletype'} eq 'community') {
 5147:                     $cb_jscript = 
 5148:                         &Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'});
 5149:                     my %elements = (
 5150:                                       coursepick => 'radio',
 5151:                                       coursetotal => 'text',
 5152:                                       courselist => 'text',
 5153:                                    );
 5154:                     $jscript = &Apache::lonhtmlcommon::set_form_elements(\%elements);
 5155:                 }
 5156:                 $jscript .= &verify_user_display($context)."\n".
 5157:                             &Apache::loncommon::check_uncheck_jscript();
 5158:                 my $js = &add_script($jscript).$cb_jscript;
 5159:                 my $loadcode = 
 5160:                     &Apache::lonuserutils::course_selector_loadcode($formname);
 5161:                 if ($loadcode ne '') {
 5162:                     $args->{add_entries} = {onload => "$loadcode;$hidecall"};
 5163:                 } else {
 5164:                     $args->{add_entries} = {onload => $hidecall};
 5165:                 }
 5166:                 $r->print(&header($js,$args));
 5167:             } else {
 5168:                 $args->{add_entries} = {onload => $hidecall};
 5169:                 $jscript = &verify_user_display($context).
 5170:                            &Apache::loncommon::check_uncheck_jscript(); 
 5171:                 $r->print(&header(&add_script($jscript),$args));
 5172:             }
 5173:             &Apache::lonuserutils::print_userlist($r,undef,$permission,$context,
 5174:                          $formname,$totcodes,$codetitles,$idlist,$idlist_titles,
 5175:                          $showcredits);
 5176:         }
 5177:     } elsif ($env{'form.action'} eq 'drop' && $permission->{'cusr'}) {
 5178:         my $brtext;
 5179:         if ($crstype eq 'Community') {
 5180:             $brtext = 'Drop Members';
 5181:         } else {
 5182:             $brtext = 'Drop Students';
 5183:         }
 5184:         push(@{$brcrum},
 5185:                 {href => '/adm/createuser?action=drop',
 5186:                  text => $brtext,
 5187:                  help => 'Course_Drop_Student'});
 5188:         if ($env{'form.state'} eq 'done') {
 5189:             push(@{$brcrum},
 5190:                      {href=>'/adm/createuser?action=drop',
 5191:                       text=>"Result"});
 5192:         }
 5193:         $bread_crumbs_component = $brtext;
 5194:         $args = {bread_crumbs           => $brcrum,
 5195:                  bread_crumbs_component => $bread_crumbs_component}; 
 5196:         $r->print(&header(undef,$args));
 5197:         if (!exists($env{'form.state'})) {
 5198:             &Apache::lonuserutils::print_drop_menu($r,$context,$permission,$crstype);
 5199:         } elsif ($env{'form.state'} eq 'done') {
 5200:             &Apache::lonuserutils::update_user_list($r,$context,undef,
 5201:                                                     $env{'form.action'});
 5202:         }
 5203:     } elsif ($env{'form.action'} eq 'dateselect') {
 5204:         if ($permission->{'cusr'}) {
 5205:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 5206:                       &Apache::lonuserutils::date_section_selector($context,$permission,
 5207:                                                                    $crstype,$showcredits));
 5208:         } else {
 5209:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 5210:                      '<span class="LC_error">'.&mt('You do not have permission to modify dates or sections for users').'</span>'); 
 5211:         }
 5212:     } elsif ($env{'form.action'} eq 'selfenroll') {
 5213:         if ($permission->{selfenrolladmin}) {
 5214:             my %currsettings = (
 5215:                 selfenroll_types              => $env{'course.'.$cid.'.internal.selfenroll_types'},
 5216:                 selfenroll_registered         => $env{'course.'.$cid.'.internal.selfenroll_registered'},
 5217:                 selfenroll_section            => $env{'course.'.$cid.'.internal.selfenroll_section'},
 5218:                 selfenroll_notifylist         => $env{'course.'.$cid.'.internal.selfenroll_notifylist'},
 5219:                 selfenroll_approval           => $env{'course.'.$cid.'.internal.selfenroll_approval'},
 5220:                 selfenroll_limit              => $env{'course.'.$cid.'.internal.selfenroll_limit'},
 5221:                 selfenroll_cap                => $env{'course.'.$cid.'.internal.selfenroll_cap'},
 5222:                 selfenroll_start_date         => $env{'course.'.$cid.'.internal.selfenroll_start_date'},
 5223:                 selfenroll_end_date           => $env{'course.'.$cid.'.internal.selfenroll_end_date'},
 5224:                 selfenroll_start_access       => $env{'course.'.$cid.'.internal.selfenroll_start_access'},
 5225:                 selfenroll_end_access         => $env{'course.'.$cid.'.internal.selfenroll_end_access'},
 5226:                 default_enrollment_start_date => $env{'course.'.$cid.'.default_enrollment_start_date'},
 5227:                 default_enrollment_end_date   => $env{'course.'.$cid.'.default_enrollment_end_date'},
 5228:                 uniquecode                    => $env{'course.'.$cid.'.internal.uniquecode'},
 5229:             );
 5230:             push(@{$brcrum},
 5231:                     {href => '/adm/createuser?action=selfenroll',
 5232:                      text => "Configure Self-enrollment",
 5233:                      help => 'Course_Self_Enrollment'});
 5234:             if (!exists($env{'form.state'})) {
 5235:                 $args = { bread_crumbs           => $brcrum,
 5236:                           bread_crumbs_component => 'Configure Self-enrollment'};
 5237:                 $r->print(&header(undef,$args));
 5238:                 $r->print('<h3>'.&mt('Self-enrollment with a student role').'</h3>'."\n");
 5239:                 &print_selfenroll_menu($r,'course',$cid,$cdom,$cnum,\%currsettings);
 5240:             } elsif ($env{'form.state'} eq 'done') {
 5241:                 push (@{$brcrum},
 5242:                           {href=>'/adm/createuser?action=selfenroll',
 5243:                            text=>"Result"});
 5244:                 $args = { bread_crumbs           => $brcrum,
 5245:                           bread_crumbs_component => 'Self-enrollment result'};
 5246:                 $r->print(&header(undef,$args));
 5247:                 $r->print('<h3>'.&mt('Self-enrollment with a student role').'</h3>'."\n");
 5248:                 &update_selfenroll_config($r,$cid,$cdom,$cnum,$context,$crstype,\%currsettings);
 5249:             }
 5250:         } else {
 5251:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 5252:                      '<span class="LC_error">'.&mt('You do not have permission to configure self-enrollment').'</span>');
 5253:         }
 5254:     } elsif ($env{'form.action'} eq 'selfenrollqueue') {
 5255:         if ($permission->{selfenrolladmin}) {
 5256:             push(@{$brcrum},
 5257:                      {href => '/adm/createuser?action=selfenrollqueue',
 5258:                       text => 'Enrollment requests',
 5259:                       help => 'Course_Approve_Selfenroll'});
 5260:             $bread_crumbs_component = 'Enrollment requests';
 5261:             if ($env{'form.state'} eq 'done') {
 5262:                 push(@{$brcrum},
 5263:                          {href => '/adm/createuser?action=selfenrollqueue',
 5264:                           text => 'Result',
 5265:                           help => 'Course_Approve_Selfenroll'});
 5266:                 $bread_crumbs_component = 'Enrollment result';
 5267:             }
 5268:             $args = { bread_crumbs           => $brcrum,
 5269:                       bread_crumbs_component => $bread_crumbs_component};
 5270:             $r->print(&header(undef,$args));
 5271:             my $coursedesc = $env{'course.'.$cid.'.description'};
 5272:             if (!exists($env{'form.state'})) {
 5273:                 $r->print('<h3>'.&mt('Pending enrollment requests').'</h3>'."\n");
 5274:                 $r->print(&Apache::loncoursequeueadmin::display_queued_requests($context,
 5275:                                                                                 $cdom,$cnum));
 5276:             } elsif ($env{'form.state'} eq 'done') {
 5277:                 $r->print('<h3>'.&mt('Enrollment request processing').'</h3>'."\n");
 5278:                 $r->print(&Apache::loncoursequeueadmin::update_request_queue($context,
 5279:                               $cdom,$cnum,$coursedesc));
 5280:             }
 5281:         } else {
 5282:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 5283:                      '<span class="LC_error">'.&mt('You do not have permission to manage self-enrollment').'</span>');
 5284:         }
 5285:     } elsif ($env{'form.action'} eq 'changelogs') {
 5286:         if ($permission->{cusr} || $permission->{view}) {
 5287:             &print_userchangelogs_display($r,$context,$permission,$brcrum);
 5288:         } else {
 5289:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 5290:                      '<span class="LC_error">'.&mt('You do not have permission to view change logs').'</span>');
 5291:         }
 5292:     } elsif ($env{'form.action'} eq 'helpdesk') {
 5293:         if (($permission->{'owner'}) || ($permission->{'co-owner'})) {
 5294:             if ($env{'form.state'} eq 'process') {
 5295:                 if ($permission->{'owner'}) {
 5296:                     &update_helpdeskaccess($r,$permission,$brcrum);
 5297:                 } else {
 5298:                     &print_helpdeskaccess_display($r,$permission,$brcrum);
 5299:                 }
 5300:             } else {
 5301:                 &print_helpdeskaccess_display($r,$permission,$brcrum);
 5302:             }
 5303:         } else {
 5304:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 5305:                       '<span class="LC_error">'.&mt('You do not have permission to view helpdesk access').'</span>');
 5306:         }
 5307:     } else {
 5308:         $bread_crumbs_component = 'User Management';
 5309:         $args = { bread_crumbs           => $brcrum,
 5310:                   bread_crumbs_component => $bread_crumbs_component};
 5311:         $r->print(&header(undef,$args));
 5312:         $r->print(&print_main_menu($permission,$context,$crstype));
 5313:     }
 5314:     $r->print(&Apache::loncommon::end_page());
 5315:     return OK;
 5316: }
 5317: 
 5318: sub header {
 5319:     my ($jscript,$args) = @_;
 5320:     my $start_page;
 5321:     if (ref($args) eq 'HASH') {
 5322:         $start_page=&Apache::loncommon::start_page('User Management',$jscript,$args);
 5323:     } else {
 5324:         $start_page=&Apache::loncommon::start_page('User Management',$jscript);
 5325:     }
 5326:     return $start_page;
 5327: }
 5328: 
 5329: sub add_script {
 5330:     my ($js) = @_;
 5331:     return '<script type="text/javascript">'."\n"
 5332:           .'// <![CDATA['."\n"
 5333:           .$js."\n"
 5334:           .'// ]]>'."\n"
 5335:           .'</script>'."\n";
 5336: }
 5337: 
 5338: sub usernamerequest_javascript {
 5339:     my $js = <<ENDJS;
 5340: 
 5341: function openusernamereqdisplay(dom,uname,queue) {
 5342:     var url = '/adm/createuser?action=displayuserreq';
 5343:     url += '&domain='+dom+'&username='+uname+'&queue='+queue;
 5344:     var title = 'Account_Request_Browser';
 5345:     var options = 'scrollbars=1,resizable=1,menubar=0';
 5346:     options += ',width=700,height=600';
 5347:     var stdeditbrowser = open(url,title,options,'1');
 5348:     stdeditbrowser.focus();
 5349:     return;
 5350: }
 5351:  
 5352: ENDJS
 5353: }
 5354: 
 5355: sub close_popup_form {
 5356:     my $close= &mt('Close Window');
 5357:     return << "END";
 5358: <p><form name="displayreq" action="" method="post">
 5359: <input type="button" name="closeme" value="$close" onclick="javascript:self.close();" />
 5360: </form></p>
 5361: END
 5362: }
 5363: 
 5364: sub verify_user_display {
 5365:     my ($context) = @_;
 5366:     my %lt = &Apache::lonlocal::texthash (
 5367:         course    => 'course(s): description, section(s), status',
 5368:         community => 'community(s): description, section(s), status',
 5369:         author    => 'author',
 5370:     );
 5371:     my $photos;
 5372:     if (($context eq 'course') && $env{'request.course.id'}) {
 5373:         $photos = $env{'course.'.$env{'request.course.id'}.'.internal.showphoto'};
 5374:     }
 5375:     my $output = <<"END";
 5376: 
 5377: function hide_searching() {
 5378:     if (document.getElementById('searching')) {
 5379:         document.getElementById('searching').style.display = 'none';
 5380:     }
 5381:     return;
 5382: }
 5383: 
 5384: function display_update() {
 5385:     document.studentform.action.value = 'listusers';
 5386:     document.studentform.phase.value = 'display';
 5387:     document.studentform.submit();
 5388: }
 5389: 
 5390: function updateCols(caller) {
 5391:     var context = '$context';
 5392:     var photos = '$photos';
 5393:     if (caller == 'Status') {
 5394:         if ((context == 'domain') && 
 5395:             ((document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'course') ||
 5396:              (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'community'))) {
 5397:             document.getElementById('showcolstatus').checked = false;
 5398:             document.getElementById('showcolstatus').disabled = 'disabled';
 5399:             document.getElementById('showcolstart').checked = false;
 5400:             document.getElementById('showcolend').checked = false;
 5401:         } else {
 5402:             if (document.studentform.Status.options[document.studentform.Status.selectedIndex].value == 'Any') {
 5403:                 document.getElementById('showcolstatus').checked = true;
 5404:                 document.getElementById('showcolstatus').disabled = '';
 5405:                 document.getElementById('showcolstart').checked = true;
 5406:                 document.getElementById('showcolend').checked = true;
 5407:             } else {
 5408:                 document.getElementById('showcolstatus').checked = false;
 5409:                 document.getElementById('showcolstatus').disabled = 'disabled';
 5410:                 document.getElementById('showcolstart').checked = false;
 5411:                 document.getElementById('showcolend').checked = false;
 5412:             }
 5413:         }
 5414:     }
 5415:     if (caller == 'output') {
 5416:         if (photos == 1) {
 5417:             if (document.getElementById('showcolphoto')) {
 5418:                 var photoitem = document.getElementById('showcolphoto');
 5419:                 if (document.studentform.output.options[document.studentform.output.selectedIndex].value == 'html') {
 5420:                     photoitem.checked = true;
 5421:                     photoitem.disabled = '';
 5422:                 } else {
 5423:                     photoitem.checked = false;
 5424:                     photoitem.disabled = 'disabled';
 5425:                 }
 5426:             }
 5427:         }
 5428:     }
 5429:     if (caller == 'showrole') {
 5430:         if ((document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'Any') ||
 5431:             (document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'cr')) {
 5432:             document.getElementById('showcolrole').checked = true;
 5433:             document.getElementById('showcolrole').disabled = '';
 5434:         } else {
 5435:             document.getElementById('showcolrole').checked = false;
 5436:             document.getElementById('showcolrole').disabled = 'disabled';
 5437:         }
 5438:         if (context == 'domain') {
 5439:             var quotausageshow = 0;
 5440:             if ((document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'course') ||
 5441:                 (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'community')) {
 5442:                 document.getElementById('showcolstatus').checked = false;
 5443:                 document.getElementById('showcolstatus').disabled = 'disabled';
 5444:                 document.getElementById('showcolstart').checked = false;
 5445:                 document.getElementById('showcolend').checked = false;
 5446:             } else {
 5447:                 if (document.studentform.Status.options[document.studentform.Status.selectedIndex].value == 'Any') {
 5448:                     document.getElementById('showcolstatus').checked = true;
 5449:                     document.getElementById('showcolstatus').disabled = '';
 5450:                     document.getElementById('showcolstart').checked = true;
 5451:                     document.getElementById('showcolend').checked = true;
 5452:                 }
 5453:             }
 5454:             if (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'domain') {
 5455:                 document.getElementById('showcolextent').disabled = 'disabled';
 5456:                 document.getElementById('showcolextent').checked = 'false';
 5457:                 document.getElementById('showextent').style.display='none';
 5458:                 document.getElementById('showcoltextextent').innerHTML = '';
 5459:                 if ((document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'au') ||
 5460:                     (document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'Any')) {
 5461:                     if (document.getElementById('showcolauthorusage')) {
 5462:                         document.getElementById('showcolauthorusage').disabled = '';
 5463:                     }
 5464:                     if (document.getElementById('showcolauthorquota')) {
 5465:                         document.getElementById('showcolauthorquota').disabled = '';
 5466:                     }
 5467:                     quotausageshow = 1;
 5468:                 }
 5469:             } else {
 5470:                 document.getElementById('showextent').style.display='block';
 5471:                 document.getElementById('showextent').style.textAlign='left';
 5472:                 document.getElementById('showextent').style.textFace='normal';
 5473:                 if (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'author') {
 5474:                     document.getElementById('showcolextent').disabled = '';
 5475:                     document.getElementById('showcolextent').checked = 'true';
 5476:                     document.getElementById('showcoltextextent').innerHTML="$lt{'author'}";
 5477:                 } else {
 5478:                     document.getElementById('showcolextent').disabled = '';
 5479:                     document.getElementById('showcolextent').checked = 'true';
 5480:                     if (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'community') {
 5481:                         document.getElementById('showcoltextextent').innerHTML="$lt{'community'}";
 5482:                     } else {
 5483:                         document.getElementById('showcoltextextent').innerHTML="$lt{'course'}";
 5484:                     }
 5485:                 }
 5486:             }
 5487:             if (quotausageshow == 0)  {
 5488:                 if (document.getElementById('showcolauthorusage')) {
 5489:                     document.getElementById('showcolauthorusage').checked = false;
 5490:                     document.getElementById('showcolauthorusage').disabled = 'disabled';
 5491:                 }
 5492:                 if (document.getElementById('showcolauthorquota')) {
 5493:                     document.getElementById('showcolauthorquota').checked = false;
 5494:                     document.getElementById('showcolauthorquota').disabled = 'disabled';
 5495:                 }
 5496:             }
 5497:         }
 5498:     }
 5499:     return;
 5500: }
 5501: 
 5502: END
 5503:     return $output;
 5504: 
 5505: }
 5506: 
 5507: ###############################################################
 5508: ###############################################################
 5509: #  Menu Phase One
 5510: sub print_main_menu {
 5511:     my ($permission,$context,$crstype) = @_;
 5512:     my $linkcontext = $context;
 5513:     my $stuterm = lc(&Apache::lonnet::plaintext('st',$crstype));
 5514:     if (($context eq 'course') && ($crstype eq 'Community')) {
 5515:         $linkcontext = lc($crstype);
 5516:         $stuterm = 'Members';
 5517:     }
 5518:     my %links = (
 5519:                 domain => {
 5520:                             upload     => 'Upload a File of Users',
 5521:                             singleuser => 'Add/Modify a User',
 5522:                             listusers  => 'Manage Users',
 5523:                             },
 5524:                 author => {
 5525:                             upload     => 'Upload a File of Co-authors',
 5526:                             singleuser => 'Add/Modify a Co-author',
 5527:                             listusers  => 'Manage Co-authors',
 5528:                             },
 5529:                 course => {
 5530:                             upload     => 'Upload a File of Course Users',
 5531:                             singleuser => 'Add/Modify a Course User',
 5532:                             listusers  => 'List and Modify Multiple Course Users',
 5533:                             },
 5534:                 community => {
 5535:                             upload     => 'Upload a File of Community Users',
 5536:                             singleuser => 'Add/Modify a Community User',
 5537:                             listusers  => 'List and Modify Multiple Community Users',
 5538:                            },
 5539:                 );
 5540:      my %linktitles = (
 5541:                 domain => {
 5542:                             singleuser => 'Add a user to the domain, and/or a course or community in the domain.',
 5543:                             listusers  => 'Show and manage users in this domain.',
 5544:                             },
 5545:                 author => {
 5546:                             singleuser => 'Add a user with a co- or assistant author role.',
 5547:                             listusers  => 'Show and manage co- or assistant authors.',
 5548:                             },
 5549:                 course => {
 5550:                             singleuser => 'Add a user with a certain role to this course.',
 5551:                             listusers  => 'Show and manage users in this course.',
 5552:                             },
 5553:                 community => {
 5554:                             singleuser => 'Add a user with a certain role to this community.',
 5555:                             listusers  => 'Show and manage users in this community.',
 5556:                            },
 5557:                 );
 5558:   if ($linkcontext eq 'domain') {
 5559:       unless ($permission->{'cusr'}) {
 5560:           $links{'domain'}{'singleuser'} = 'View a User';
 5561:           $linktitles{'domain'}{'singleuser'} = 'View information about a user in the domain';
 5562:       }
 5563:   } elsif ($linkcontext eq 'course') {
 5564:       unless ($permission->{'cusr'}) {
 5565:           $links{'course'}{'singleuser'} = 'View a Course User';
 5566:           $linktitles{'course'}{'singleuser'} = 'View information about a user in this course';
 5567:           $links{'course'}{'listusers'} = 'List Course Users';
 5568:           $linktitles{'course'}{'listusers'} = 'Show information about users in this course';
 5569:       }
 5570:   } elsif ($linkcontext eq 'community') {
 5571:       unless ($permission->{'cusr'}) {
 5572:           $links{'community'}{'singleuser'} = 'View a Community User';
 5573:           $linktitles{'community'}{'singleuser'} = 'View information about a user in this community';
 5574:           $links{'community'}{'listusers'} = 'List Community Users';
 5575:           $linktitles{'community'}{'listusers'} = 'Show information about users in this community';
 5576:       }
 5577:   }
 5578:   my @menu = ( {categorytitle => 'Single Users', 
 5579:          items =>
 5580:          [
 5581:             {
 5582:              linktext => $links{$linkcontext}{'singleuser'},
 5583:              icon => 'edit-redo.png',
 5584:              #help => 'Course_Change_Privileges',
 5585:              url => '/adm/createuser?action=singleuser',
 5586:              permission => ($permission->{'view'} || $permission->{'cusr'}),
 5587:              linktitle => $linktitles{$linkcontext}{'singleuser'},
 5588:             },
 5589:          ]},
 5590: 
 5591:          {categorytitle => 'Multiple Users',
 5592:          items => 
 5593:          [
 5594:             {
 5595:              linktext => $links{$linkcontext}{'upload'},
 5596:              icon => 'uplusr.png',
 5597:              #help => 'Course_Create_Class_List',
 5598:              url => '/adm/createuser?action=upload',
 5599:              permission => $permission->{'cusr'},
 5600:              linktitle => 'Upload a CSV or a text file containing users.',
 5601:             },
 5602:             {
 5603:              linktext => $links{$linkcontext}{'listusers'},
 5604:              icon => 'mngcu.png',
 5605:              #help => 'Course_View_Class_List',
 5606:              url => '/adm/createuser?action=listusers',
 5607:              permission => ($permission->{'view'} || $permission->{'cusr'}),
 5608:              linktitle => $linktitles{$linkcontext}{'listusers'}, 
 5609:             },
 5610: 
 5611:          ]},
 5612: 
 5613:          {categorytitle => 'Administration',
 5614:          items => [ ]},
 5615:        );
 5616: 
 5617:     if ($context eq 'domain'){
 5618:         push(@{  $menu[0]->{items} }, # Single Users
 5619:             {
 5620:              linktext => 'User Access Log',
 5621:              icon => 'document-properties.png',
 5622:              #help => 'Domain_User_Access_Logs',
 5623:              url => '/adm/createuser?action=accesslogs',
 5624:              permission => $permission->{'activity'},
 5625:              linktitle => 'View user access log.',
 5626:             }
 5627:         );
 5628:         
 5629:         push(@{ $menu[2]->{items} }, #Category: Administration
 5630:             {
 5631:              linktext => 'Custom Roles',
 5632:              icon => 'emblem-photos.png',
 5633:              #help => 'Course_Editing_Custom_Roles',
 5634:              url => '/adm/createuser?action=custom',
 5635:              permission => $permission->{'custom'},
 5636:              linktitle => 'Configure a custom role.',
 5637:             },
 5638:             {
 5639:              linktext => 'Authoring Space Requests',
 5640:              icon => 'selfenrl-queue.png',
 5641:              #help => 'Domain_Role_Approvals',
 5642:              url => '/adm/createuser?action=processauthorreq',
 5643:              permission => $permission->{'cusr'},
 5644:              linktitle => 'Approve or reject author role requests',
 5645:             },
 5646:             {
 5647:              linktext => 'LON-CAPA Account Requests',
 5648:              icon => 'list-add.png',
 5649:              #help => 'Domain_Username_Approvals',
 5650:              url => '/adm/createuser?action=processusernamereq',
 5651:              permission => $permission->{'cusr'},
 5652:              linktitle => 'Approve or reject LON-CAPA account requests',
 5653:             },
 5654:             {
 5655:              linktext => 'Change Log',
 5656:              icon => 'document-properties.png',
 5657:              #help => 'Course_User_Logs',
 5658:              url => '/adm/createuser?action=changelogs',
 5659:              permission => ($permission->{'cusr'} || $permission->{'view'}),
 5660:              linktitle => 'View change log.',
 5661:             },
 5662:         );
 5663:         
 5664:     }elsif ($context eq 'course'){
 5665:         my ($cnum,$cdom) = &Apache::lonuserutils::get_course_identity();
 5666: 
 5667:         my %linktext = (
 5668:                          'Course'    => {
 5669:                                           single => 'Add/Modify a Student', 
 5670:                                           drop   => 'Drop Students',
 5671:                                           groups => 'Course Groups',
 5672:                                         },
 5673:                          'Community' => {
 5674:                                           single => 'Add/Modify a Member', 
 5675:                                           drop   => 'Drop Members',
 5676:                                           groups => 'Community Groups',
 5677:                                         },
 5678:                        );
 5679: 
 5680:         my %linktitle = (
 5681:             'Course' => {
 5682:                   single => 'Add a user with the role of student to this course',
 5683:                   drop   => 'Remove a student from this course.',
 5684:                   groups => 'Manage course groups',
 5685:                         },
 5686:             'Community' => {
 5687:                   single => 'Add a user with the role of member to this community',
 5688:                   drop   => 'Remove a member from this community.',
 5689:                   groups => 'Manage community groups',
 5690:                            },
 5691:         );
 5692: 
 5693:         push(@{ $menu[0]->{items} }, #Category: Single Users
 5694:             {   
 5695:              linktext => $linktext{$crstype}{'single'},
 5696:              #help => 'Course_Add_Student',
 5697:              icon => 'list-add.png',
 5698:              url => '/adm/createuser?action=singlestudent',
 5699:              permission => $permission->{'cusr'},
 5700:              linktitle => $linktitle{$crstype}{'single'},
 5701:             },
 5702:         );
 5703:         
 5704:         push(@{ $menu[1]->{items} }, #Category: Multiple Users 
 5705:             {
 5706:              linktext => $linktext{$crstype}{'drop'},
 5707:              icon => 'edit-undo.png',
 5708:              #help => 'Course_Drop_Student',
 5709:              url => '/adm/createuser?action=drop',
 5710:              permission => $permission->{'cusr'},
 5711:              linktitle => $linktitle{$crstype}{'drop'},
 5712:             },
 5713:         );
 5714:         push(@{ $menu[2]->{items} }, #Category: Administration
 5715:             {
 5716:              linktext => 'Helpdesk Access',
 5717:              icon => 'helpdesk-access.png',
 5718:              #help => 'Course_Helpdesk_Access',
 5719:              url => '/adm/createuser?action=helpdesk',
 5720:              permission => ($permission->{'owner'} || $permission->{'co-owner'}),
 5721:              linktitle => 'Helpdesk access options',
 5722:             },
 5723:             {
 5724:              linktext => 'Custom Roles',
 5725:              icon => 'emblem-photos.png',
 5726:              #help => 'Course_Editing_Custom_Roles',
 5727:              url => '/adm/createuser?action=custom',
 5728:              permission => $permission->{'custom'},
 5729:              linktitle => 'Configure a custom role.',
 5730:             },
 5731:             {
 5732:              linktext => $linktext{$crstype}{'groups'},
 5733:              icon => 'grps.png',
 5734:              #help => 'Course_Manage_Group',
 5735:              url => '/adm/coursegroups?refpage=cusr',
 5736:              permission => $permission->{'grp_manage'},
 5737:              linktitle => $linktitle{$crstype}{'groups'},
 5738:             },
 5739:             {
 5740:              linktext => 'Change Log',
 5741:              icon => 'document-properties.png',
 5742:              #help => 'Course_User_Logs',
 5743:              url => '/adm/createuser?action=changelogs',
 5744:              permission => ($permission->{'view'} || $permission->{'cusr'}),
 5745:              linktitle => 'View change log.',
 5746:             },
 5747:         );
 5748:         if ($env{'course.'.$env{'request.course.id'}.'.internal.selfenroll_approval'}) {
 5749:             push(@{ $menu[2]->{items} },
 5750:                     {
 5751:                      linktext => 'Enrollment Requests',
 5752:                      icon => 'selfenrl-queue.png',
 5753:                      #help => 'Course_Approve_Selfenroll',
 5754:                      url => '/adm/createuser?action=selfenrollqueue',
 5755:                      permission => $permission->{'selfenrolladmin'},
 5756:                      linktitle =>'Approve or reject enrollment requests.',
 5757:                     },
 5758:             );
 5759:         }
 5760:         
 5761:         if (!exists($permission->{'cusr_section'})){
 5762:             if ($crstype ne 'Community') {
 5763:                 push(@{ $menu[2]->{items} },
 5764:                     {
 5765:                      linktext => 'Automated Enrollment',
 5766:                      icon => 'roles.png',
 5767:                      #help => 'Course_Automated_Enrollment',
 5768:                      permission => (&Apache::lonnet::auto_run($cnum,$cdom)
 5769:                                          && (($permission->{'cusr'}) ||
 5770:                                              ($permission->{'view'}))),
 5771:                      url  => '/adm/populate',
 5772:                      linktitle => 'Automated enrollment manager.',
 5773:                     }
 5774:                 );
 5775:             }
 5776:             push(@{ $menu[2]->{items} }, 
 5777:                 {
 5778:                  linktext => 'User Self-Enrollment',
 5779:                  icon => 'self_enroll.png',
 5780:                  #help => 'Course_Self_Enrollment',
 5781:                  url => '/adm/createuser?action=selfenroll',
 5782:                  permission => $permission->{'selfenrolladmin'},
 5783:                  linktitle => 'Configure user self-enrollment.',
 5784:                 },
 5785:             );
 5786:         }
 5787:     } elsif ($context eq 'author') {
 5788:         push(@{ $menu[2]->{items} }, #Category: Administration
 5789:             {
 5790:              linktext => 'Change Log',
 5791:              icon => 'document-properties.png',
 5792:              #help => 'Course_User_Logs',
 5793:              url => '/adm/createuser?action=changelogs',
 5794:              permission => $permission->{'cusr'},
 5795:              linktitle => 'View change log.',
 5796:             },
 5797:         );
 5798:     }
 5799:     return Apache::lonhtmlcommon::generate_menu(@menu);
 5800: #               { text => 'View Log-in History',
 5801: #                 help => 'Course_User_Logins',
 5802: #                 action => 'logins',
 5803: #                 permission => $permission->{'cusr'},
 5804: #               });
 5805: }
 5806: 
 5807: sub restore_prev_selections {
 5808:     my %saveable_parameters = ('srchby'   => 'scalar',
 5809: 			       'srchin'   => 'scalar',
 5810: 			       'srchtype' => 'scalar',
 5811: 			       );
 5812:     &Apache::loncommon::store_settings('user','user_picker',
 5813: 				       \%saveable_parameters);
 5814:     &Apache::loncommon::restore_settings('user','user_picker',
 5815: 					 \%saveable_parameters);
 5816: }
 5817: 
 5818: sub print_selfenroll_menu {
 5819:     my ($r,$context,$cid,$cdom,$cnum,$currsettings,$additional,$readonly) = @_;
 5820:     my $crstype = &Apache::loncommon::course_type();
 5821:     my $formname = 'selfenroll';
 5822:     my $nolink = 1;
 5823:     my ($row,$lt) = &Apache::lonuserutils::get_selfenroll_titles();
 5824:     my $groupslist = &Apache::lonuserutils::get_groupslist();
 5825:     my $setsec_js = 
 5826:         &Apache::lonuserutils::setsections_javascript($formname,$groupslist);
 5827:     my %alerts = &Apache::lonlocal::texthash(
 5828:         acto => 'Activation of self-enrollment was selected for the following domain(s)',
 5829:         butn => 'but no user types have been checked.',
 5830:         wilf => "Please uncheck 'activate' or check at least one type.",
 5831:     );
 5832:     my $disabled;
 5833:     if ($readonly) {
 5834:        $disabled = ' disabled="disabled"';
 5835:     }
 5836:     &js_escape(\%alerts);
 5837:     my $selfenroll_js = <<"ENDSCRIPT";
 5838: function update_types(caller,num) {
 5839:     var delidx = getIndexByName('selfenroll_delete');
 5840:     var actidx = getIndexByName('selfenroll_activate');
 5841:     if (caller == 'selfenroll_all') {
 5842:         var selall;
 5843:         for (var i=0; i<document.$formname.selfenroll_all.length; i++) {
 5844:             if (document.$formname.selfenroll_all[i].checked) {
 5845:                 selall = document.$formname.selfenroll_all[i].value;
 5846:             }
 5847:         }
 5848:         if (selall == 1) {
 5849:             if (delidx != -1) {
 5850:                 if (document.$formname.selfenroll_delete.length) {
 5851:                     for (var j=0; j<document.$formname.selfenroll_delete.length; j++) {
 5852:                         document.$formname.selfenroll_delete[j].checked = true;
 5853:                     }
 5854:                 } else {
 5855:                     document.$formname.elements[delidx].checked = true;
 5856:                 }
 5857:             }
 5858:             if (actidx != -1) {
 5859:                 if (document.$formname.selfenroll_activate.length) {
 5860:                     for (var j=0; j<document.$formname.selfenroll_activate.length; j++) {
 5861:                         document.$formname.selfenroll_activate[j].checked = false;
 5862:                     }
 5863:                 } else {
 5864:                     document.$formname.elements[actidx].checked = false;
 5865:                 }
 5866:             }
 5867:             document.$formname.selfenroll_newdom.selectedIndex = 0; 
 5868:         }
 5869:     }
 5870:     if (caller == 'selfenroll_activate') {
 5871:         if (document.$formname.selfenroll_activate.length) {
 5872:             for (var j=0; j<document.$formname.selfenroll_activate.length; j++) {
 5873:                 if (document.$formname.selfenroll_activate[j].value == num) {
 5874:                     if (document.$formname.selfenroll_activate[j].checked) {
 5875:                         for (var i=0; i<document.$formname.selfenroll_all.length; i++) {
 5876:                             if (document.$formname.selfenroll_all[i].value == '1') {
 5877:                                 document.$formname.selfenroll_all[i].checked = false;
 5878:                             }
 5879:                             if (document.$formname.selfenroll_all[i].value == '0') {
 5880:                                 document.$formname.selfenroll_all[i].checked = true;
 5881:                             }
 5882:                         }
 5883:                     }
 5884:                 }
 5885:             }
 5886:         } else {
 5887:             for (var i=0; i<document.$formname.selfenroll_all.length; i++) {
 5888:                 if (document.$formname.selfenroll_all[i].value == '1') {
 5889:                     document.$formname.selfenroll_all[i].checked = false;
 5890:                 }
 5891:                 if (document.$formname.selfenroll_all[i].value == '0') {
 5892:                     document.$formname.selfenroll_all[i].checked = true;
 5893:                 }
 5894:             }
 5895:         }
 5896:     }
 5897:     if (caller == 'selfenroll_delete') {
 5898:         if (document.$formname.selfenroll_delete.length) {
 5899:             for (var j=0; j<document.$formname.selfenroll_delete.length; j++) {
 5900:                 if (document.$formname.selfenroll_delete[j].value == num) {
 5901:                     if (document.$formname.selfenroll_delete[j].checked) {
 5902:                         var delindex = getIndexByName('selfenroll_types_'+num);
 5903:                         if (delindex != -1) { 
 5904:                             if (document.$formname.elements[delindex].length) {
 5905:                                 for (var k=0; k<document.$formname.elements[delindex].length; k++) {
 5906:                                     document.$formname.elements[delindex][k].checked = false;
 5907:                                 }
 5908:                             } else {
 5909:                                 document.$formname.elements[delindex].checked = false;
 5910:                             }
 5911:                         }
 5912:                     }
 5913:                 }
 5914:             }
 5915:         } else {
 5916:             if (document.$formname.selfenroll_delete.checked) {
 5917:                 var delindex = getIndexByName('selfenroll_types_'+num);
 5918:                 if (delindex != -1) {
 5919:                     if (document.$formname.elements[delindex].length) {
 5920:                         for (var k=0; k<document.$formname.elements[delindex].length; k++) {
 5921:                             document.$formname.elements[delindex][k].checked = false;
 5922:                         }
 5923:                     } else {
 5924:                         document.$formname.elements[delindex].checked = false;
 5925:                     }
 5926:                 }
 5927:             }
 5928:         }
 5929:     }
 5930:     return;
 5931: }
 5932: 
 5933: function validate_types(form) {
 5934:     var needaction = new Array();
 5935:     var countfail = 0;
 5936:     var actidx = getIndexByName('selfenroll_activate');
 5937:     if (actidx != -1) {
 5938:         if (document.$formname.selfenroll_activate.length) {
 5939:             for (var j=0; j<document.$formname.selfenroll_activate.length; j++) {
 5940:                 var num = document.$formname.selfenroll_activate[j].value;
 5941:                 if (document.$formname.selfenroll_activate[j].checked) {
 5942:                     countfail = check_types(num,countfail,needaction)
 5943:                 }
 5944:             }
 5945:         } else {
 5946:             if (document.$formname.selfenroll_activate.checked) {
 5947:                 var num = document.$formname.selfenroll_activate.value;
 5948:                 countfail = check_types(num,countfail,needaction)
 5949:             }
 5950:         }
 5951:     }
 5952:     if (countfail > 0) {
 5953:         var msg = "$alerts{'acto'}\\n";
 5954:         var loopend = needaction.length -1;
 5955:         if (loopend > 0) {
 5956:             for (var m=0; m<loopend; m++) {
 5957:                 msg += needaction[m]+", ";
 5958:             }
 5959:         }
 5960:         msg += needaction[loopend]+"\\n$alerts{'butn'}\\n$alerts{'wilf'}";
 5961:         alert(msg);
 5962:         return; 
 5963:     }
 5964:     setSections(form);
 5965: }
 5966: 
 5967: function check_types(num,countfail,needaction) {
 5968:     var boxname = 'selfenroll_types_'+num;
 5969:     var typeidx = getIndexByName(boxname);
 5970:     var count = 0;
 5971:     if (typeidx != -1) {
 5972:         if (document.$formname.elements[boxname].length) {
 5973:             for (var k=0; k<document.$formname.elements[boxname].length; k++) {
 5974:                 if (document.$formname.elements[boxname][k].checked) {
 5975:                     count ++;
 5976:                 }
 5977:             }
 5978:         } else {
 5979:             if (document.$formname.elements[typeidx].checked) {
 5980:                 count ++;
 5981:             }
 5982:         }
 5983:         if (count == 0) {
 5984:             var domidx = getIndexByName('selfenroll_dom_'+num);
 5985:             if (domidx != -1) {
 5986:                 var domname = document.$formname.elements[domidx].value;
 5987:                 needaction[countfail] = domname;
 5988:                 countfail ++;
 5989:             }
 5990:         }
 5991:     }
 5992:     return countfail;
 5993: }
 5994: 
 5995: function toggleNotify() {
 5996:     var selfenrollApproval = 0;
 5997:     if (document.$formname.selfenroll_approval.length) {
 5998:         for (var i=0; i<document.$formname.selfenroll_approval.length; i++) {
 5999:             if (document.$formname.selfenroll_approval[i].checked) {
 6000:                 selfenrollApproval = document.$formname.selfenroll_approval[i].value;
 6001:                 break;        
 6002:             }
 6003:         }
 6004:     }
 6005:     if (document.getElementById('notified')) {
 6006:         if (selfenrollApproval == 0) {
 6007:             document.getElementById('notified').style.display='none';
 6008:         } else {
 6009:             document.getElementById('notified').style.display='block';
 6010:         }
 6011:     }
 6012:     return;
 6013: }
 6014: 
 6015: function getIndexByName(item) {
 6016:     for (var i=0;i<document.$formname.elements.length;i++) {
 6017:         if (document.$formname.elements[i].name == item) {
 6018:             return i;
 6019:         }
 6020:     }
 6021:     return -1;
 6022: }
 6023: ENDSCRIPT
 6024: 
 6025:     my $output = '<script type="text/javascript">'."\n".
 6026:                  '// <![CDATA['."\n".
 6027:                  $setsec_js."\n".$selfenroll_js."\n".
 6028:                  '// ]]>'."\n".
 6029:                  '</script>'."\n".
 6030:                  '<h3>'.$lt->{'selfenroll'}.'</h3>'."\n";
 6031:  
 6032:     my $visactions = &cat_visibility();
 6033:     my ($cathash,%cattype);
 6034:     my %domconfig = &Apache::lonnet::get_dom('configuration',['coursecategories'],$cdom);
 6035:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 6036:         $cathash = $domconfig{'coursecategories'}{'cats'};
 6037:         $cattype{'auth'} = $domconfig{'coursecategories'}{'auth'};
 6038:         $cattype{'unauth'} = $domconfig{'coursecategories'}{'unauth'};
 6039:         if ($cattype{'auth'} eq '') {
 6040:             $cattype{'auth'} = 'std';
 6041:         }
 6042:         if ($cattype{'unauth'} eq '') {
 6043:             $cattype{'unauth'} = 'std';
 6044:         }
 6045:     } else {
 6046:         $cathash = {};
 6047:         $cattype{'auth'} = 'std';
 6048:         $cattype{'unauth'} = 'std';
 6049:     }
 6050:     if (($cattype{'auth'} eq 'none') && ($cattype{'unauth'} eq 'none')) {
 6051:         $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
 6052:                   '<br />'.
 6053:                   '<br />'.$visactions->{'take'}.'<ul>'.
 6054:                   '<li>'.$visactions->{'dc_chgconf'}.'</li>'.
 6055:                   '</ul>');
 6056:     } elsif (($cattype{'auth'} !~ /^(std|domonly)$/) && ($cattype{'unauth'} !~ /^(std|domonly)$/)) {
 6057:         if ($currsettings->{'uniquecode'}) {
 6058:             $r->print('<span class="LC_info">'.$visactions->{'vis'}.'</span>');
 6059:         } else {
 6060:             $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
 6061:                   '<br />'.
 6062:                   '<br />'.$visactions->{'take'}.'<ul>'.
 6063:                   '<li>'.$visactions->{'dc_setcode'}.'</li>'.
 6064:                   '</ul><br />');
 6065:         }
 6066:     } else {
 6067:         my ($visible,$cansetvis,$vismsgs) = &visible_in_stdcat($cdom,$cnum,\%domconfig);
 6068:         if (ref($visactions) eq 'HASH') {
 6069:             if ($visible) {
 6070:                 $output .= '<p class="LC_info">'.$visactions->{'vis'}.'</p>';
 6071:            } else {
 6072:                 $output .= '<p class="LC_warning">'.$visactions->{'miss'}.'</p>'
 6073:                           .$visactions->{'yous'}.
 6074:                            '<p>'.$visactions->{'gen'}.'<br />'.$visactions->{'coca'};
 6075:                 if (ref($vismsgs) eq 'ARRAY') {
 6076:                     $output .= '<br />'.$visactions->{'make'}.'<ul>';
 6077:                     foreach my $item (@{$vismsgs}) {
 6078:                         $output .= '<li>'.$visactions->{$item}.'</li>';
 6079:                     }
 6080:                     $output .= '</ul>';
 6081:                 }
 6082:                 $output .= '</p>';
 6083:             }
 6084:         }
 6085:     }
 6086:     my $actionhref = '/adm/createuser';
 6087:     if ($context eq 'domain') {
 6088:         $actionhref = '/adm/modifycourse';
 6089:     }
 6090: 
 6091:     my %noedit;
 6092:     unless ($context eq 'domain') {
 6093:         %noedit = &get_noedit_fields($cdom,$cnum,$crstype,$row);
 6094:     }
 6095:     $output .= '<form name="'.$formname.'" method="post" action="'.$actionhref.'">'."\n".
 6096:                &Apache::lonhtmlcommon::start_pick_box();
 6097:     if (ref($row) eq 'ARRAY') {
 6098:         foreach my $item (@{$row}) {
 6099:             my $title = $item; 
 6100:             if (ref($lt) eq 'HASH') {
 6101:                 $title = $lt->{$item};
 6102:             }
 6103:             $output .= &Apache::lonhtmlcommon::row_title($title);
 6104:             if ($item eq 'types') {
 6105:                 my $curr_types;
 6106:                 if (ref($currsettings) eq 'HASH') {
 6107:                     $curr_types = $currsettings->{'selfenroll_types'};
 6108:                 }
 6109:                 if ($noedit{$item}) {
 6110:                     if ($curr_types eq '*') {
 6111:                         $output .= &mt('Any user in any domain');   
 6112:                     } else {
 6113:                         my @entries = split(/;/,$curr_types);
 6114:                         if (@entries > 0) {
 6115:                             $output .= '<ul>'; 
 6116:                             foreach my $entry (@entries) {
 6117:                                 my ($currdom,$typestr) = split(/:/,$entry);
 6118:                                 next if ($typestr eq '');
 6119:                                 my $domdesc = &Apache::lonnet::domain($currdom);
 6120:                                 my @currinsttypes = split(',',$typestr);
 6121:                                 my ($othertitle,$usertypes,$types) = 
 6122:                                     &Apache::loncommon::sorted_inst_types($currdom);
 6123:                                 if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 6124:                                     $usertypes->{'any'} = &mt('any user'); 
 6125:                                     if (keys(%{$usertypes}) > 0) {
 6126:                                         $usertypes->{'other'} = &mt('other users');
 6127:                                     }
 6128:                                     my @longinsttypes = map { $usertypes->{$_}; } @currinsttypes;
 6129:                                     $output .= '<li>'.$domdesc.':'.join(', ',@longinsttypes).'</li>';
 6130:                                  }
 6131:                             }
 6132:                             $output .= '</ul>';
 6133:                         } else {
 6134:                             $output .= &mt('None');
 6135:                         }
 6136:                     }
 6137:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 6138:                     next;
 6139:                 }
 6140:                 my $showdomdesc = 1;
 6141:                 my $includeempty = 1;
 6142:                 my $num = 0;
 6143:                 $output .= &Apache::loncommon::start_data_table().
 6144:                            &Apache::loncommon::start_data_table_row()
 6145:                            .'<td colspan="2"><span class="LC_nobreak"><label>'
 6146:                            .&mt('Any user in any domain:')
 6147:                            .'&nbsp;<input type="radio" name="selfenroll_all" value="1" ';
 6148:                 if ($curr_types eq '*') {
 6149:                     $output .= ' checked="checked" '; 
 6150:                 }
 6151:                 $output .= 'onchange="javascript:update_types('.
 6152:                            "'selfenroll_all'".');"'.$disabled.' />'.&mt('Yes').'</label>'.
 6153:                            '&nbsp;&nbsp;<input type="radio" name="selfenroll_all" value="0" ';
 6154:                 if ($curr_types ne '*') {
 6155:                     $output .= ' checked="checked" ';
 6156:                 }
 6157:                 $output .= ' onchange="javascript:update_types('.
 6158:                            "'selfenroll_all'".');"'.$disabled.' />'.&mt('No').'</label></td>'.
 6159:                            &Apache::loncommon::end_data_table_row().
 6160:                            &Apache::loncommon::end_data_table().
 6161:                            &mt('Or').'<br />'.
 6162:                            &Apache::loncommon::start_data_table();
 6163:                 my %currdoms;
 6164:                 if ($curr_types eq '') {
 6165:                     $output .= &new_selfenroll_dom_row($cdom,'0');
 6166:                 } elsif ($curr_types ne '*') {
 6167:                     my @entries = split(/;/,$curr_types);
 6168:                     if (@entries > 0) {
 6169:                         foreach my $entry (@entries) {
 6170:                             my ($currdom,$typestr) = split(/:/,$entry);
 6171:                             $currdoms{$currdom} = 1;
 6172:                             my $domdesc = &Apache::lonnet::domain($currdom);
 6173:                             my @currinsttypes = split(',',$typestr);
 6174:                             $output .= &Apache::loncommon::start_data_table_row()
 6175:                                        .'<td valign="top"><span class="LC_nobreak">'.&mt('Domain:').'<b>'
 6176:                                        .'&nbsp;'.$domdesc.' ('.$currdom.')'
 6177:                                        .'</b><input type="hidden" name="selfenroll_dom_'.$num
 6178:                                        .'" value="'.$currdom.'" /></span><br />'
 6179:                                        .'<span class="LC_nobreak"><label><input type="checkbox" '
 6180:                                        .'name="selfenroll_delete" value="'.$num.'" onchange="javascript:update_types('."'selfenroll_delete','$num'".');"'.$disabled.' />'
 6181:                                        .&mt('Delete').'</label></span></td>';
 6182:                             $output .= '<td valign="top">&nbsp;&nbsp;'.&mt('User types:').'<br />'
 6183:                                        .&selfenroll_inst_types($num,$currdom,\@currinsttypes,$readonly).'</td>'
 6184:                                        .&Apache::loncommon::end_data_table_row();
 6185:                             $num ++;
 6186:                         }
 6187:                     }
 6188:                 }
 6189:                 my $add_domtitle = &mt('Users in additional domain:');
 6190:                 if ($curr_types eq '*') { 
 6191:                     $add_domtitle = &mt('Users in specific domain:');
 6192:                 } elsif ($curr_types eq '') {
 6193:                     $add_domtitle = &mt('Users in other domain:');
 6194:                 }
 6195:                 $output .= &Apache::loncommon::start_data_table_row()
 6196:                            .'<td colspan="2"><span class="LC_nobreak">'.$add_domtitle.'</span><br />'
 6197:                            .&Apache::loncommon::select_dom_form('','selfenroll_newdom',
 6198:                                                                 $includeempty,$showdomdesc,'','','',$readonly)
 6199:                            .'<input type="hidden" name="selfenroll_types_total" value="'.$num.'" />'
 6200:                            .'</td>'.&Apache::loncommon::end_data_table_row()
 6201:                            .&Apache::loncommon::end_data_table();
 6202:             } elsif ($item eq 'registered') {
 6203:                 my ($regon,$regoff);
 6204:                 my $registered;
 6205:                 if (ref($currsettings) eq 'HASH') {
 6206:                     $registered = $currsettings->{'selfenroll_registered'};
 6207:                 }
 6208:                 if ($noedit{$item}) {
 6209:                     if ($registered) {
 6210:                         $output .= &mt('Must be registered in course');
 6211:                     } else {
 6212:                         $output .= &mt('No requirement');
 6213:                     }
 6214:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 6215:                     next;
 6216:                 }
 6217:                 if ($registered) {
 6218:                     $regon = ' checked="checked" ';
 6219:                     $regoff = '';
 6220:                 } else {
 6221:                     $regon = '';
 6222:                     $regoff = ' checked="checked" ';
 6223:                 }
 6224:                 $output .= '<label>'.
 6225:                            '<input type="radio" name="selfenroll_registered" value="1"'.$regon.$disabled.' />'.
 6226:                            &mt('Yes').'</label>&nbsp;&nbsp;<label>'.
 6227:                            '<input type="radio" name="selfenroll_registered" value="0"'.$regoff.$disabled.' />'.
 6228:                            &mt('No').'</label>';
 6229:             } elsif ($item eq 'enroll_dates') {
 6230:                 my ($starttime,$endtime);
 6231:                 if (ref($currsettings) eq 'HASH') {
 6232:                     $starttime = $currsettings->{'selfenroll_start_date'};
 6233:                     $endtime = $currsettings->{'selfenroll_end_date'};
 6234:                     if ($starttime eq '') {
 6235:                         $starttime = $currsettings->{'default_enrollment_start_date'};
 6236:                     }
 6237:                     if ($endtime eq '') {
 6238:                         $endtime = $currsettings->{'default_enrollment_end_date'};
 6239:                     }
 6240:                 }
 6241:                 if ($noedit{$item}) {
 6242:                     $output .= &mt('From: [_1], to: [_2]',&Apache::lonlocal::locallocaltime($starttime),
 6243:                                                           &Apache::lonlocal::locallocaltime($endtime));
 6244:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 6245:                     next;
 6246:                 }
 6247:                 my $startform =
 6248:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_start_date',$starttime,
 6249:                                       $disabled,undef,undef,undef,undef,undef,undef,$nolink);
 6250:                 my $endform =
 6251:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_end_date',$endtime,
 6252:                                       $disabled,undef,undef,undef,undef,undef,undef,$nolink);
 6253:                 $output .= &selfenroll_date_forms($startform,$endform);
 6254:             } elsif ($item eq 'access_dates') {
 6255:                 my ($starttime,$endtime);
 6256:                 if (ref($currsettings) eq 'HASH') {
 6257:                     $starttime = $currsettings->{'selfenroll_start_access'};
 6258:                     $endtime = $currsettings->{'selfenroll_end_access'};
 6259:                     if ($starttime eq '') {
 6260:                         $starttime = $currsettings->{'default_enrollment_start_date'};
 6261:                     }
 6262:                     if ($endtime eq '') {
 6263:                         $endtime = $currsettings->{'default_enrollment_end_date'};
 6264:                     }
 6265:                 }
 6266:                 if ($noedit{$item}) {
 6267:                     $output .= &mt('From: [_1], to: [_2]',&Apache::lonlocal::locallocaltime($starttime),
 6268:                                                           &Apache::lonlocal::locallocaltime($endtime));
 6269:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 6270:                     next;
 6271:                 }
 6272:                 my $startform =
 6273:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_start_access',$starttime,
 6274:                                       $disabled,undef,undef,undef,undef,undef,undef,$nolink);
 6275:                 my $endform =
 6276:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_end_access',$endtime,
 6277:                                       $disabled,undef,undef,undef,undef,undef,undef,$nolink);
 6278:                 $output .= &selfenroll_date_forms($startform,$endform);
 6279:             } elsif ($item eq 'section') {
 6280:                 my $currsec;
 6281:                 if (ref($currsettings) eq 'HASH') {
 6282:                     $currsec = $currsettings->{'selfenroll_section'};
 6283:                 }
 6284:                 my %sections_count = &Apache::loncommon::get_sections($cdom,$cnum);
 6285:                 my $newsecval;
 6286:                 if ($currsec ne 'none' && $currsec ne '') {
 6287:                     if (!defined($sections_count{$currsec})) {
 6288:                         $newsecval = $currsec;
 6289:                     }
 6290:                 }
 6291:                 if ($noedit{$item}) {
 6292:                     if ($currsec ne '') {
 6293:                         $output .= $currsec;
 6294:                     } else {
 6295:                         $output .= &mt('No specific section');
 6296:                     }
 6297:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 6298:                     next;
 6299:                 }
 6300:                 my $sections_select = 
 6301:                     &Apache::lonuserutils::course_sections(\%sections_count,'st',$currsec,$disabled);
 6302:                 $output .= '<table class="LC_createuser">'."\n".
 6303:                            '<tr class="LC_section_row">'."\n".
 6304:                            '<td align="center">'.&mt('Existing sections')."\n".
 6305:                            '<br />'.$sections_select.'</td><td align="center">'.
 6306:                            &mt('New section').'<br />'."\n".
 6307:                            '<input type="text" name="newsec" size="15" value="'.$newsecval.'"'.$disabled.' />'."\n".
 6308:                            '<input type="hidden" name="sections" value="" />'."\n".
 6309:                            '</td></tr></table>'."\n";
 6310:             } elsif ($item eq 'approval') {
 6311:                 my ($currnotified,$currapproval,%appchecked);
 6312:                 my %selfdescs = &Apache::lonuserutils::selfenroll_default_descs();
 6313:                 if (ref($currsettings) eq 'HASH') {
 6314:                     $currnotified = $currsettings->{'selfenroll_notifylist'};
 6315:                     $currapproval = $currsettings->{'selfenroll_approval'};
 6316:                 }
 6317:                 if ($currapproval !~ /^[012]$/) {
 6318:                     $currapproval = 0;
 6319:                 }
 6320:                 if ($noedit{$item}) {
 6321:                     $output .=  $selfdescs{'approval'}{$currapproval}.
 6322:                                 '<br />'.&mt('(Set by Domain Coordinator)');
 6323:                     next;
 6324:                 }
 6325:                 $appchecked{$currapproval} = ' checked="checked"';
 6326:                 for my $i (0..2) {
 6327:                     $output .= '<label>'.
 6328:                                '<input type="radio" name="selfenroll_approval" value="'.$i.'"'.
 6329:                                $appchecked{$i}.' onclick="toggleNotify();"'.$disabled.' />'.
 6330:                                $selfdescs{'approval'}{$i}.'</label>'.('&nbsp;'x2);
 6331:                 }
 6332:                 my %advhash = &Apache::lonnet::get_course_adv_roles($cid,1);
 6333:                 my (@ccs,%notified);
 6334:                 my $ccrole = 'cc';
 6335:                 if ($crstype eq 'Community') {
 6336:                     $ccrole = 'co';
 6337:                 }
 6338:                 if ($advhash{$ccrole}) {
 6339:                     @ccs = split(/,/,$advhash{$ccrole});
 6340:                 }
 6341:                 if ($currnotified) {
 6342:                     foreach my $current (split(/,/,$currnotified)) {
 6343:                         $notified{$current} = 1;
 6344:                         if (!grep(/^\Q$current\E$/,@ccs)) {
 6345:                             push(@ccs,$current);
 6346:                         }
 6347:                     }
 6348:                 }
 6349:                 if (@ccs) {
 6350:                     my $style;
 6351:                     unless ($currapproval) {
 6352:                         $style = ' style="display: none;"'; 
 6353:                     }
 6354:                     $output .= '<br /><div id="notified"'.$style.'>'.
 6355:                                &mt('Personnel to be notified when an enrollment request needs approval, or has been approved:').'&nbsp;'.
 6356:                                &Apache::loncommon::start_data_table().
 6357:                                &Apache::loncommon::start_data_table_row();
 6358:                     my $count = 0;
 6359:                     my $numcols = 4;
 6360:                     foreach my $cc (sort(@ccs)) {
 6361:                         my $notifyon;
 6362:                         my ($ccuname,$ccudom) = split(/:/,$cc);
 6363:                         if ($notified{$cc}) {
 6364:                             $notifyon = ' checked="checked" ';
 6365:                         }
 6366:                         if ($count && !$count%$numcols) {
 6367:                             $output .= &Apache::loncommon::end_data_table_row().
 6368:                                        &Apache::loncommon::start_data_table_row()
 6369:                         }
 6370:                         $output .= '<td><span class="LC_nobreak"><label>'.
 6371:                                    '<input type="checkbox" name="selfenroll_notify"'.$notifyon.' value="'.$cc.'"'.$disabled.' />'.
 6372:                                    &Apache::loncommon::plainname($ccuname,$ccudom).
 6373:                                    '</label></span></td>';
 6374:                         $count ++;
 6375:                     }
 6376:                     my $rem = $count%$numcols;
 6377:                     if ($rem) {
 6378:                         my $emptycols = $numcols - $rem;
 6379:                         for (my $i=0; $i<$emptycols; $i++) { 
 6380:                             $output .= '<td>&nbsp;</td>';
 6381:                         }
 6382:                     }
 6383:                     $output .= &Apache::loncommon::end_data_table_row().
 6384:                                &Apache::loncommon::end_data_table().
 6385:                                '</div>';
 6386:                 }
 6387:             } elsif ($item eq 'limit') {
 6388:                 my ($crslimit,$selflimit,$nolimit,$currlim,$currcap);
 6389:                 if (ref($currsettings) eq 'HASH') {
 6390:                     $currlim = $currsettings->{'selfenroll_limit'};
 6391:                     $currcap = $currsettings->{'selfenroll_cap'};
 6392:                 }
 6393:                 if ($noedit{$item}) {
 6394:                     if (($currlim eq 'allstudents') || ($currlim eq 'selfenrolled')) {
 6395:                         if ($currlim eq 'allstudents') {
 6396:                             $output .= &mt('Limit by total students');
 6397:                         } elsif ($currlim eq 'selfenrolled') {
 6398:                             $output .= &mt('Limit by total self-enrolled students');
 6399:                         }
 6400:                         $output .= ' '.&mt('Maximum: [_1]',$currcap).
 6401:                                    '<br />'.&mt('(Set by Domain Coordinator)');
 6402:                     } else {
 6403:                         $output .= &mt('No limit').'<br />'.&mt('(Set by Domain Coordinator)');
 6404:                     }
 6405:                     next;
 6406:                 }
 6407:                 if ($currlim eq 'allstudents') {
 6408:                     $crslimit = ' checked="checked" ';
 6409:                     $selflimit = ' ';
 6410:                     $nolimit = ' ';
 6411:                 } elsif ($currlim eq 'selfenrolled') {
 6412:                     $crslimit = ' ';
 6413:                     $selflimit = ' checked="checked" ';
 6414:                     $nolimit = ' '; 
 6415:                 } else {
 6416:                     $crslimit = ' ';
 6417:                     $selflimit = ' ';
 6418:                     $nolimit = ' checked="checked" ';
 6419:                 }
 6420:                 $output .= '<table><tr><td><label>'.
 6421:                            '<input type="radio" name="selfenroll_limit" value="none"'.$nolimit.$disabled.'/>'.
 6422:                            &mt('No limit').'</label></td><td><label>'.
 6423:                            '<input type="radio" name="selfenroll_limit" value="allstudents"'.$crslimit.$disabled.'/>'.
 6424:                            &mt('Limit by total students').'</label></td><td><label>'.
 6425:                            '<input type="radio" name="selfenroll_limit" value="selfenrolled"'.$selflimit.$disabled.'/>'.
 6426:                            &mt('Limit by total self-enrolled students').
 6427:                            '</td></tr><tr>'.
 6428:                            '<td>&nbsp;</td><td colspan="2"><span class="LC_nobreak">'.
 6429:                            ('&nbsp;'x3).&mt('Maximum number allowed: ').
 6430:                            '<input type="text" name="selfenroll_cap" size = "5" value="'.$currcap.'"'.$disabled.' /></td></tr></table>';
 6431:             }
 6432:             $output .= &Apache::lonhtmlcommon::row_closure(1);
 6433:         }
 6434:     }
 6435:     $output .= &Apache::lonhtmlcommon::end_pick_box().'<br />';
 6436:     unless ($readonly) {
 6437:         $output .= '<input type="button" name="selfenrollconf" value="'
 6438:                    .&mt('Save').'" onclick="validate_types(this.form);" />';
 6439:     }
 6440:     $output .= '<input type="hidden" name="action" value="selfenroll" />'
 6441:               .'<input type="hidden" name="state" value="done" />'."\n"
 6442:               .$additional.'</form>';
 6443:     $r->print($output);
 6444:     return;
 6445: }
 6446: 
 6447: sub get_noedit_fields {
 6448:     my ($cdom,$cnum,$crstype,$row) = @_;
 6449:     my %noedit;
 6450:     if (ref($row) eq 'ARRAY') {
 6451:         my %settings = &Apache::lonnet::get('environment',['internal.coursecode','internal.textbook',
 6452:                                                            'internal.selfenrollmgrdc',
 6453:                                                            'internal.selfenrollmgrcc'],$cdom,$cnum);
 6454:         my $type = &Apache::lonuserutils::get_extended_type($cdom,$cnum,$crstype,\%settings);
 6455:         my (%specific_managebydc,%specific_managebycc,%default_managebydc);
 6456:         map { $specific_managebydc{$_} = 1; } (split(/,/,$settings{'internal.selfenrollmgrdc'}));
 6457:         map { $specific_managebycc{$_} = 1; } (split(/,/,$settings{'internal.selfenrollmgrcc'}));
 6458:         my %domdefaults = &Apache::lonnet::get_domain_defaults($cdom);
 6459:         map { $default_managebydc{$_} = 1; } (split(/,/,$domdefaults{$type.'selfenrolladmdc'}));
 6460: 
 6461:         foreach my $item (@{$row}) {
 6462:             next if ($specific_managebycc{$item});
 6463:             if (($specific_managebydc{$item}) || ($default_managebydc{$item})) {
 6464:                 $noedit{$item} = 1;
 6465:             }
 6466:         }
 6467:     }
 6468:     return %noedit;
 6469: } 
 6470: 
 6471: sub visible_in_stdcat {
 6472:     my ($cdom,$cnum,$domconf) = @_;
 6473:     my ($cathash,%settable,@vismsgs,$cansetvis,$visible);
 6474:     unless (ref($domconf) eq 'HASH') {
 6475:         return ($visible,$cansetvis,\@vismsgs);
 6476:     }
 6477:     if (ref($domconf->{'coursecategories'}) eq 'HASH') {
 6478:         if ($domconf->{'coursecategories'}{'togglecats'} eq 'crs') {
 6479:             $settable{'togglecats'} = 1;
 6480:         }
 6481:         if ($domconf->{'coursecategories'}{'categorize'} eq 'crs') {
 6482:             $settable{'categorize'} = 1;
 6483:         }
 6484:         $cathash = $domconf->{'coursecategories'}{'cats'};
 6485:     }
 6486:     if ($settable{'togglecats'} && $settable{'categorize'}) {
 6487:         $cansetvis = &mt('You are able to both assign a course category and choose to exclude this course from the catalog.');   
 6488:     } elsif ($settable{'togglecats'}) {
 6489:         $cansetvis = &mt('You are able to choose to exclude this course from the catalog, but only a Domain Coordinator may assign a course category.'); 
 6490:     } elsif ($settable{'categorize'}) {
 6491:         $cansetvis = &mt('You may assign a course category, but only a Domain Coordinator may choose to exclude this course from the catalog.');  
 6492:     } else {
 6493:         $cansetvis = &mt('Only a Domain Coordinator may assign a course category or choose to exclude this course from the catalog.'); 
 6494:     }
 6495:      
 6496:     my %currsettings =
 6497:         &Apache::lonnet::get('environment',['hidefromcat','categories','internal.coursecode'],
 6498:                              $cdom,$cnum);
 6499:     $visible = 0;
 6500:     if ($currsettings{'internal.coursecode'} ne '') {
 6501:         if (ref($domconf->{'coursecategories'}) eq 'HASH') {
 6502:             $cathash = $domconf->{'coursecategories'}{'cats'};
 6503:             if (ref($cathash) eq 'HASH') {
 6504:                 if ($cathash->{'instcode::0'} eq '') {
 6505:                     push(@vismsgs,'dc_addinst'); 
 6506:                 } else {
 6507:                     $visible = 1;
 6508:                 }
 6509:             } else {
 6510:                 $visible = 1;
 6511:             }
 6512:         } else {
 6513:             $visible = 1;
 6514:         }
 6515:     } else {
 6516:         if (ref($cathash) eq 'HASH') {
 6517:             if ($cathash->{'instcode::0'} ne '') {
 6518:                 push(@vismsgs,'dc_instcode');
 6519:             }
 6520:         } else {
 6521:             push(@vismsgs,'dc_instcode');
 6522:         }
 6523:     }
 6524:     if ($currsettings{'categories'} ne '') {
 6525:         my $cathash;
 6526:         if (ref($domconf->{'coursecategories'}) eq 'HASH') {
 6527:             $cathash = $domconf->{'coursecategories'}{'cats'};
 6528:             if (ref($cathash) eq 'HASH') {
 6529:                 if (keys(%{$cathash}) == 0) {
 6530:                     push(@vismsgs,'dc_catalog');
 6531:                 } elsif ((keys(%{$cathash}) == 1) && ($cathash->{'instcode::0'} ne '')) {
 6532:                     push(@vismsgs,'dc_categories');
 6533:                 } else {
 6534:                     my @currcategories = split('&',$currsettings{'categories'});
 6535:                     my $matched = 0;
 6536:                     foreach my $cat (@currcategories) {
 6537:                         if ($cathash->{$cat} ne '') {
 6538:                             $visible = 1;
 6539:                             $matched = 1;
 6540:                             last;
 6541:                         }
 6542:                     }
 6543:                     if (!$matched) {
 6544:                         if ($settable{'categorize'}) { 
 6545:                             push(@vismsgs,'chgcat');
 6546:                         } else {
 6547:                             push(@vismsgs,'dc_chgcat');
 6548:                         }
 6549:                     }
 6550:                 }
 6551:             }
 6552:         }
 6553:     } else {
 6554:         if (ref($cathash) eq 'HASH') {
 6555:             if ((keys(%{$cathash}) > 1) || 
 6556:                 (keys(%{$cathash}) == 1) && ($cathash->{'instcode::0'} eq '')) {
 6557:                 if ($settable{'categorize'}) {
 6558:                     push(@vismsgs,'addcat');
 6559:                 } else {
 6560:                     push(@vismsgs,'dc_addcat');
 6561:                 }
 6562:             }
 6563:         }
 6564:     }
 6565:     if ($currsettings{'hidefromcat'} eq 'yes') {
 6566:         $visible = 0;
 6567:         if ($settable{'togglecats'}) {
 6568:             unshift(@vismsgs,'unhide');
 6569:         } else {
 6570:             unshift(@vismsgs,'dc_unhide')
 6571:         }
 6572:     }
 6573:     return ($visible,$cansetvis,\@vismsgs);
 6574: }
 6575: 
 6576: sub cat_visibility {
 6577:     my %visactions = &Apache::lonlocal::texthash(
 6578:                    vis => 'This course/community currently appears in the Course/Community Catalog for this domain.',
 6579:                    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.',
 6580:                    miss => 'This course/community does not currently appear in the Course/Community Catalog for this domain.',
 6581:                    none => 'Display of a course catalog is disabled for this domain.',
 6582:                    yous => 'You should remedy this if you plan to allow self-enrollment, otherwise students will have difficulty finding this course.',
 6583:                    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.',
 6584:                    make => 'Make any changes to self-enrollment settings below, click "Save", then take action to include the course in the Catalog:',
 6585:                    take => 'Take the following action to ensure the course appears in the Catalog:',
 6586:                    dc_chgconf => 'Ask a domain coordinator to change the Catalog type for this domain.',
 6587:                    dc_setcode => 'Ask a domain coordinator to assign a six character code to the course',
 6588:                    dc_unhide  => 'Ask a domain coordinator to change the "Exclude from course catalog" setting.',
 6589:                    dc_addinst => 'Ask a domain coordinator to enable display the catalog of "Official courses (with institutional codes)".',
 6590:                    dc_instcode => 'Ask a domain coordinator to assign an institutional code (if this is an official course).',
 6591:                    dc_catalog  => 'Ask a domain coordinator to enable or create at least one course category in the domain.',
 6592:                    dc_categories => 'Ask a domain coordinator to create a hierarchy of categories and sub categories for courses in the domain.',
 6593:                    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',
 6594:                    dc_addcat => 'Ask a domain coordinator to assign a category to the course.',
 6595:     );
 6596:     $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>"');
 6597:     $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>"');
 6598:     $visactions{'addcat'} = &mt('Use [_1]Categorize course[_2] to assign a category to the course.','"<a href="/adm/courseprefs?phase=display&actions=courseinfo">','</a>"');
 6599:     return \%visactions;
 6600: }
 6601: 
 6602: sub new_selfenroll_dom_row {
 6603:     my ($newdom,$num) = @_;
 6604:     my $domdesc = &Apache::lonnet::domain($newdom);
 6605:     my $output;
 6606:     if ($domdesc ne '') {
 6607:         $output .= &Apache::loncommon::start_data_table_row()
 6608:                    .'<td valign="top"><span class="LC_nobreak">'.&mt('Domain:').'&nbsp;<b>'.$domdesc
 6609:                    .' ('.$newdom.')</b><input type="hidden" name="selfenroll_dom_'.$num
 6610:                    .'" value="'.$newdom.'" /></span><br />'
 6611:                    .'<span class="LC_nobreak"><label><input type="checkbox" '
 6612:                    .'name="selfenroll_activate" value="'.$num.'" '
 6613:                    .'onchange="javascript:update_types('
 6614:                    ."'selfenroll_activate','$num'".');" />'
 6615:                    .&mt('Activate').'</label></span></td>';
 6616:         my @currinsttypes;
 6617:         $output .= '<td>'.&mt('User types:').'<br />'
 6618:                    .&selfenroll_inst_types($num,$newdom,\@currinsttypes).'</td>'
 6619:                    .&Apache::loncommon::end_data_table_row();
 6620:     }
 6621:     return $output;
 6622: }
 6623: 
 6624: sub selfenroll_inst_types {
 6625:     my ($num,$currdom,$currinsttypes,$readonly) = @_;
 6626:     my $output;
 6627:     my $numinrow = 4;
 6628:     my $count = 0;
 6629:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($currdom);
 6630:     my $othervalue = 'any';
 6631:     my $disabled;
 6632:     if ($readonly) {
 6633:         $disabled = ' disabled="disabled"';
 6634:     }
 6635:     if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 6636:         if (keys(%{$usertypes}) > 0) {
 6637:             $othervalue = 'other';
 6638:         }
 6639:         $output .= '<table><tr>';
 6640:         foreach my $type (@{$types}) {
 6641:             if (($count > 0) && ($count%$numinrow == 0)) {
 6642:                 $output .= '</tr><tr>';
 6643:             }
 6644:             if (defined($usertypes->{$type})) {
 6645:                 my $esc_type = &escape($type);
 6646:                 $output .= '<td><span class="LC_nobreak"><label><input type = "checkbox" value="'.
 6647:                            $esc_type.'" ';
 6648:                 if (ref($currinsttypes) eq 'ARRAY') {
 6649:                     if (@{$currinsttypes} > 0) {
 6650:                         if (grep(/^any$/,@{$currinsttypes})) {
 6651:                             $output .= 'checked="checked"';
 6652:                         } elsif (grep(/^\Q$esc_type\E$/,@{$currinsttypes})) {
 6653:                             $output .= 'checked="checked"';
 6654:                         }
 6655:                     } else {
 6656:                         $output .= 'checked="checked"';
 6657:                     }
 6658:                 }
 6659:                 $output .= ' name="selfenroll_types_'.$num.'"'.$disabled.' />'.$usertypes->{$type}.'</label></span></td>';
 6660:             }
 6661:             $count ++;
 6662:         }
 6663:         if (($count > 0) && ($count%$numinrow == 0)) {
 6664:             $output .= '</tr><tr>';
 6665:         }
 6666:         $output .= '<td><span class="LC_nobreak"><label><input type = "checkbox" value="'.$othervalue.'"';
 6667:         if (ref($currinsttypes) eq 'ARRAY') {
 6668:             if (@{$currinsttypes} > 0) {
 6669:                 if (grep(/^any$/,@{$currinsttypes})) { 
 6670:                     $output .= ' checked="checked"';
 6671:                 } elsif ($othervalue eq 'other') {
 6672:                     if (grep(/^\Q$othervalue\E$/,@{$currinsttypes})) {
 6673:                         $output .= ' checked="checked"';
 6674:                     }
 6675:                 }
 6676:             } else {
 6677:                 $output .= ' checked="checked"';
 6678:             }
 6679:         } else {
 6680:             $output .= ' checked="checked"';
 6681:         }
 6682:         $output .= ' name="selfenroll_types_'.$num.'"'.$disabled.' />'.$othertitle.'</label></span></td></tr></table>';
 6683:     }
 6684:     return $output;
 6685: }
 6686: 
 6687: sub selfenroll_date_forms {
 6688:     my ($startform,$endform) = @_;
 6689:     my $output .= &Apache::lonhtmlcommon::start_pick_box()."\n".
 6690:                   &Apache::lonhtmlcommon::row_title(&mt('Start date'),
 6691:                                                     'LC_oddrow_value')."\n".
 6692:                   $startform."\n".
 6693:                   &Apache::lonhtmlcommon::row_closure(1).
 6694:                   &Apache::lonhtmlcommon::row_title(&mt('End date'),
 6695:                                                    'LC_oddrow_value')."\n".
 6696:                   $endform."\n".
 6697:                   &Apache::lonhtmlcommon::row_closure(1).
 6698:                   &Apache::lonhtmlcommon::end_pick_box();
 6699:     return $output;
 6700: }
 6701: 
 6702: sub print_userchangelogs_display {
 6703:     my ($r,$context,$permission,$brcrum) = @_;
 6704:     my $formname = 'rolelog';
 6705:     my ($username,$domain,$crstype,$viewablesec,%roleslog);
 6706:     if ($context eq 'domain') {
 6707:         $domain = $env{'request.role.domain'};
 6708:         %roleslog=&Apache::lonnet::dump_dom('nohist_rolelog',$domain);
 6709:     } else {
 6710:         if ($context eq 'course') { 
 6711:             $domain = $env{'course.'.$env{'request.course.id'}.'.domain'};
 6712:             $username = $env{'course.'.$env{'request.course.id'}.'.num'};
 6713:             $crstype = &Apache::loncommon::course_type();
 6714:             $viewablesec = &Apache::lonuserutils::viewable_section($permission);
 6715:             my %saveable_parameters = ('show' => 'scalar',);
 6716:             &Apache::loncommon::store_course_settings('roles_log',
 6717:                                                       \%saveable_parameters);
 6718:             &Apache::loncommon::restore_course_settings('roles_log',
 6719:                                                         \%saveable_parameters);
 6720:         } elsif ($context eq 'author') {
 6721:             $domain = $env{'user.domain'}; 
 6722:             if ($env{'request.role'} =~ m{^au\./\Q$domain\E/$}) {
 6723:                 $username = $env{'user.name'};
 6724:             } else {
 6725:                 undef($domain);
 6726:             }
 6727:         }
 6728:         if ($domain ne '' && $username ne '') { 
 6729:             %roleslog=&Apache::lonnet::dump('nohist_rolelog',$domain,$username);
 6730:         }
 6731:     }
 6732:     if ((keys(%roleslog))[0]=~/^error\:/) { undef(%roleslog); }
 6733: 
 6734:     my $helpitem;
 6735:     if ($context eq 'course') {
 6736:         $helpitem = 'Course_User_Logs';
 6737:     } elsif ($context eq 'domain') {
 6738:         $helpitem = 'Domain_Role_Logs';
 6739:     } elsif ($context eq 'author') {
 6740:         $helpitem = 'Author_User_Logs';
 6741:     }
 6742:     push (@{$brcrum},
 6743:              {href => '/adm/createuser?action=changelogs',
 6744:               text => 'User Management Logs',
 6745:               help => $helpitem});
 6746:     my $bread_crumbs_component = 'User Changes';
 6747:     my $args = { bread_crumbs           => $brcrum,
 6748:                  bread_crumbs_component => $bread_crumbs_component};
 6749: 
 6750:     # Create navigation javascript
 6751:     my $jsnav = &userlogdisplay_js($formname);
 6752: 
 6753:     my $jscript = (<<ENDSCRIPT);
 6754: <script type="text/javascript">
 6755: // <![CDATA[
 6756: $jsnav
 6757: // ]]>
 6758: </script>
 6759: ENDSCRIPT
 6760: 
 6761:     # print page header
 6762:     $r->print(&header($jscript,$args));
 6763: 
 6764:     # set defaults
 6765:     my $now = time();
 6766:     my $defstart = $now - (7*24*3600); #7 days ago 
 6767:     my %defaults = (
 6768:                      page               => '1',
 6769:                      show               => '10',
 6770:                      role               => 'any',
 6771:                      chgcontext         => 'any',
 6772:                      rolelog_start_date => $defstart,
 6773:                      rolelog_end_date   => $now,
 6774:                    );
 6775:     my $more_records = 0;
 6776: 
 6777:     # set current
 6778:     my %curr;
 6779:     foreach my $item ('show','page','role','chgcontext') {
 6780:         $curr{$item} = $env{'form.'.$item};
 6781:     }
 6782:     my ($startdate,$enddate) = 
 6783:         &Apache::lonuserutils::get_dates_from_form('rolelog_start_date','rolelog_end_date');
 6784:     $curr{'rolelog_start_date'} = $startdate;
 6785:     $curr{'rolelog_end_date'} = $enddate;
 6786:     foreach my $key (keys(%defaults)) {
 6787:         if ($curr{$key} eq '') {
 6788:             $curr{$key} = $defaults{$key};
 6789:         }
 6790:     }
 6791:     my (%whodunit,%changed,$version);
 6792:     ($version) = ($r->dir_config('lonVersion') =~ /^([\d\.]+)\-/);
 6793:     my ($minshown,$maxshown);
 6794:     $minshown = 1;
 6795:     my $count = 0;
 6796:     if ($curr{'show'} =~ /\D/) {
 6797:         $curr{'page'} = 1;
 6798:     } else {
 6799:         $maxshown = $curr{'page'} * $curr{'show'};
 6800:         if ($curr{'page'} > 1) {
 6801:             $minshown = 1 + ($curr{'page'} - 1) * $curr{'show'};
 6802:         }
 6803:     }
 6804: 
 6805:     # Form Header
 6806:     $r->print('<form action="/adm/createuser" method="post" name="'.$formname.'">'.
 6807:               &role_display_filter($context,$formname,$domain,$username,\%curr,
 6808:                                    $version,$crstype));
 6809: 
 6810:     my $showntableheader = 0;
 6811: 
 6812:     # Table Header
 6813:     my $tableheader = 
 6814:         &Apache::loncommon::start_data_table_header_row()
 6815:        .'<th>&nbsp;</th>'
 6816:        .'<th>'.&mt('When').'</th>'
 6817:        .'<th>'.&mt('Who made the change').'</th>'
 6818:        .'<th>'.&mt('Changed User').'</th>'
 6819:        .'<th>'.&mt('Role').'</th>';
 6820: 
 6821:     if ($context eq 'course') {
 6822:         $tableheader .= '<th>'.&mt('Section').'</th>';
 6823:     }
 6824:     $tableheader .=
 6825:         '<th>'.&mt('Context').'</th>'
 6826:        .'<th>'.&mt('Start').'</th>'
 6827:        .'<th>'.&mt('End').'</th>'
 6828:        .&Apache::loncommon::end_data_table_header_row();
 6829: 
 6830:     # Display user change log data
 6831:     foreach my $id (sort { $roleslog{$b}{'exe_time'}<=>$roleslog{$a}{'exe_time'} } (keys(%roleslog))) {
 6832:         next if (($roleslog{$id}{'exe_time'} < $curr{'rolelog_start_date'}) ||
 6833:                  ($roleslog{$id}{'exe_time'} > $curr{'rolelog_end_date'}));
 6834:         if ($curr{'show'} !~ /\D/) {
 6835:             if ($count >= $curr{'page'} * $curr{'show'}) {
 6836:                 $more_records = 1;
 6837:                 last;
 6838:             }
 6839:         }
 6840:         if ($curr{'role'} ne 'any') {
 6841:             next if ($roleslog{$id}{'logentry'}{'role'} ne $curr{'role'}); 
 6842:         }
 6843:         if ($curr{'chgcontext'} ne 'any') {
 6844:             if ($curr{'chgcontext'} eq 'selfenroll') {
 6845:                 next if (!$roleslog{$id}{'logentry'}{'selfenroll'});
 6846:             } else {
 6847:                 next if ($roleslog{$id}{'logentry'}{'context'} ne $curr{'chgcontext'});
 6848:             }
 6849:         }
 6850:         if (($context eq 'course') && ($viewablesec ne '')) {
 6851:             next if ($roleslog{$id}{'logentry'}{'section'} ne $viewablesec);
 6852:         }
 6853:         $count ++;
 6854:         next if ($count < $minshown);
 6855:         unless ($showntableheader) {
 6856:             $r->print(&Apache::loncommon::start_data_table()
 6857:                      .$tableheader);
 6858:             $r->rflush();
 6859:             $showntableheader = 1;
 6860:         }
 6861:         if ($whodunit{$roleslog{$id}{'exe_uname'}.':'.$roleslog{$id}{'exe_udom'}} eq '') {
 6862:             $whodunit{$roleslog{$id}{'exe_uname'}.':'.$roleslog{$id}{'exe_udom'}} =
 6863:                 &Apache::loncommon::plainname($roleslog{$id}{'exe_uname'},$roleslog{$id}{'exe_udom'});
 6864:         }
 6865:         if ($changed{$roleslog{$id}{'uname'}.':'.$roleslog{$id}{'udom'}} eq '') {
 6866:             $changed{$roleslog{$id}{'uname'}.':'.$roleslog{$id}{'udom'}} =
 6867:                 &Apache::loncommon::plainname($roleslog{$id}{'uname'},$roleslog{$id}{'udom'});
 6868:         }
 6869:         my $sec = $roleslog{$id}{'logentry'}{'section'};
 6870:         if ($sec eq '') {
 6871:             $sec = &mt('None');
 6872:         }
 6873:         my ($rolestart,$roleend);
 6874:         if ($roleslog{$id}{'delflag'}) {
 6875:             $rolestart = &mt('deleted');
 6876:             $roleend = &mt('deleted');
 6877:         } else {
 6878:             $rolestart = $roleslog{$id}{'logentry'}{'start'};
 6879:             $roleend = $roleslog{$id}{'logentry'}{'end'};
 6880:             if ($rolestart eq '' || $rolestart == 0) {
 6881:                 $rolestart = &mt('No start date'); 
 6882:             } else {
 6883:                 $rolestart = &Apache::lonlocal::locallocaltime($rolestart);
 6884:             }
 6885:             if ($roleend eq '' || $roleend == 0) { 
 6886:                 $roleend = &mt('No end date');
 6887:             } else {
 6888:                 $roleend = &Apache::lonlocal::locallocaltime($roleend);
 6889:             }
 6890:         }
 6891:         my $chgcontext = $roleslog{$id}{'logentry'}{'context'};
 6892:         if ($roleslog{$id}{'logentry'}{'selfenroll'}) {
 6893:             $chgcontext = 'selfenroll';
 6894:         }
 6895:         my %lt = &rolechg_contexts($context,$crstype);
 6896:         if ($chgcontext ne '' && $lt{$chgcontext} ne '') {
 6897:             $chgcontext = $lt{$chgcontext};
 6898:         }
 6899:         $r->print(
 6900:             &Apache::loncommon::start_data_table_row()
 6901:            .'<td>'.$count.'</td>'
 6902:            .'<td>'.&Apache::lonlocal::locallocaltime($roleslog{$id}{'exe_time'}).'</td>'
 6903:            .'<td>'.$whodunit{$roleslog{$id}{'exe_uname'}.':'.$roleslog{$id}{'exe_udom'}}.'</td>'
 6904:            .'<td>'.$changed{$roleslog{$id}{'uname'}.':'.$roleslog{$id}{'udom'}}.'</td>'
 6905:            .'<td>'.&Apache::lonnet::plaintext($roleslog{$id}{'logentry'}{'role'},$crstype).'</td>');
 6906:         if ($context eq 'course') { 
 6907:             $r->print('<td>'.$sec.'</td>');
 6908:         }
 6909:         $r->print(
 6910:             '<td>'.$chgcontext.'</td>'
 6911:            .'<td>'.$rolestart.'</td>'
 6912:            .'<td>'.$roleend.'</td>'
 6913:            .&Apache::loncommon::end_data_table_row()."\n");
 6914:     }
 6915: 
 6916:     if ($showntableheader) { # Table footer, if content displayed above
 6917:         $r->print(&Apache::loncommon::end_data_table().
 6918:                   &userlogdisplay_navlinks(\%curr,$more_records));
 6919:     } else { # No content displayed above
 6920:         $r->print('<p class="LC_info">'
 6921:                  .&mt('There are no records to display.')
 6922:                  .'</p>'
 6923:         );
 6924:     }
 6925: 
 6926:     # Form Footer
 6927:     $r->print( 
 6928:         '<input type="hidden" name="page" value="'.$curr{'page'}.'" />'
 6929:        .'<input type="hidden" name="action" value="changelogs" />'
 6930:        .'</form>');
 6931:     return;
 6932: }
 6933: 
 6934: sub print_useraccesslogs_display {
 6935:     my ($r,$uname,$udom,$permission,$brcrum) = @_;
 6936:     my $formname = 'accesslog';
 6937:     my $form = 'document.accesslog';
 6938: 
 6939: # set breadcrumbs
 6940:     my %breadcrumb_text = &singleuser_breadcrumb('','domain',$udom);
 6941:     my $prevphasestr;
 6942:     if ($env{'form.popup'}) {
 6943:         $brcrum = [];
 6944:     } else {
 6945:         push (@{$brcrum},
 6946:             {href => "javascript:backPage($form)",
 6947:              text => $breadcrumb_text{'search'}});
 6948:         my @prevphases;
 6949:         if ($env{'form.prevphases'}) {
 6950:             @prevphases = split(/,/,$env{'form.prevphases'});
 6951:             $prevphasestr = $env{'form.prevphases'};
 6952:         }
 6953:         if (($env{'form.phase'} eq 'userpicked') || (grep(/^userpicked$/,@prevphases))) {
 6954:             push(@{$brcrum},
 6955:                   {href => "javascript:backPage($form,'get_user_info','select')",
 6956:                    text => $breadcrumb_text{'userpicked'}});
 6957:             if ($env{'form.phase'} eq 'userpicked') {
 6958:                 $prevphasestr = 'userpicked';
 6959:             }
 6960:         }
 6961:     }
 6962:     push(@{$brcrum},
 6963:              {href => '/adm/createuser?action=accesslogs',
 6964:               text => 'User access logs',
 6965:               help => 'Domain_User_Access_Logs'});
 6966:     my $bread_crumbs_component = 'User Access Logs';
 6967:     my $args = { bread_crumbs           => $brcrum,
 6968:                  bread_crumbs_component => 'User Management'};
 6969:     if ($env{'form.popup'}) {
 6970:         $args->{'no_nav_bar'} = 1;
 6971:         $args->{'bread_crumbs_nomenu'} = 1;
 6972:     }
 6973: 
 6974: # set javascript
 6975:     my ($jsback,$elements) = &crumb_utilities();
 6976:     my $jsnav = &userlogdisplay_js($formname);
 6977: 
 6978:     my $jscript = (<<ENDSCRIPT);
 6979: <script type="text/javascript">
 6980: // <![CDATA[
 6981: 
 6982: $jsback
 6983: $jsnav
 6984: 
 6985: // ]]>
 6986: </script>
 6987: 
 6988: ENDSCRIPT
 6989: 
 6990: # print page header
 6991:     $r->print(&header($jscript,$args));
 6992: 
 6993: # early out unless log data can be displayed.
 6994:     unless ($permission->{'activity'}) {
 6995:         $r->print('<p class="LC_warning">'
 6996:                  .&mt('You do not have rights to display user access logs.')
 6997:                  .'</p>');
 6998:         if ($env{'form.popup'}) {
 6999:             $r->print('<p><a href="javascript:window.close()">'.&mt('Close window').'</a></p>');
 7000:         } else {
 7001:             $r->print(&earlyout_accesslog_form($formname,$prevphasestr,$udom));
 7002:         }
 7003:         return;
 7004:     }
 7005: 
 7006:     unless ($udom eq $env{'request.role.domain'}) {
 7007:         $r->print('<p class="LC_warning">'
 7008:                  .&mt("User's domain must match role's domain")
 7009:                  .'</p>'
 7010:                  .&earlyout_accesslog_form($formname,$prevphasestr,$udom));
 7011:         return;
 7012:     }
 7013: 
 7014:     if (($uname eq '') || ($udom eq '')) {
 7015:         $r->print('<p class="LC_warning">'
 7016:                  .&mt('Invalid username or domain')
 7017:                  .'</p>'
 7018:                  .&earlyout_accesslog_form($formname,$prevphasestr,$udom));
 7019:         return;
 7020:     }
 7021: 
 7022:     if (&Apache::lonnet::privileged($uname,$udom,
 7023:                                     [$env{'request.role.domain'}],['dc','su'])) {
 7024:         unless (&Apache::lonnet::privileged($env{'user.name'},$env{'user.domain'},
 7025:                                             [$env{'request.role.domain'}],['dc','su'])) {
 7026:             $r->print('<p class="LC_warning">'
 7027:                  .&mt('You need to be a privileged user to display user access logs for [_1]',
 7028:                       &Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($uname,$udom),
 7029:                                                          $uname,$udom))
 7030:                  .'</p>');
 7031:             if ($env{'form.popup'}) {
 7032:                 $r->print('<p><a href="javascript:window.close()">'.&mt('Close window').'</a></p>');
 7033:             } else {
 7034:                 $r->print(&earlyout_accesslog_form($formname,$prevphasestr,$udom));
 7035:             }
 7036:             return;
 7037:         }
 7038:     }
 7039: 
 7040: # set defaults
 7041:     my $now = time();
 7042:     my $defstart = $now - (7*24*3600);
 7043:     my %defaults = (
 7044:                      page                 => '1',
 7045:                      show                 => '10',
 7046:                      activity             => 'any',
 7047:                      accesslog_start_date => $defstart,
 7048:                      accesslog_end_date   => $now,
 7049:                    );
 7050:     my $more_records = 0;
 7051: 
 7052: # set current
 7053:     my %curr;
 7054:     foreach my $item ('show','page','activity') {
 7055:         $curr{$item} = $env{'form.'.$item};
 7056:     }
 7057:     my ($startdate,$enddate) =
 7058:         &Apache::lonuserutils::get_dates_from_form('accesslog_start_date','accesslog_end_date');
 7059:     $curr{'accesslog_start_date'} = $startdate;
 7060:     $curr{'accesslog_end_date'} = $enddate;
 7061:     foreach my $key (keys(%defaults)) {
 7062:         if ($curr{$key} eq '') {
 7063:             $curr{$key} = $defaults{$key};
 7064:         }
 7065:     }
 7066:     my ($minshown,$maxshown);
 7067:     $minshown = 1;
 7068:     my $count = 0;
 7069:     if ($curr{'show'} =~ /\D/) {
 7070:         $curr{'page'} = 1;
 7071:     } else {
 7072:         $maxshown = $curr{'page'} * $curr{'show'};
 7073:         if ($curr{'page'} > 1) {
 7074:             $minshown = 1 + ($curr{'page'} - 1) * $curr{'show'};
 7075:         }
 7076:     }
 7077: 
 7078: # form header
 7079:     $r->print('<form action="/adm/createuser" method="post" name="'.$formname.'">'.
 7080:               &activity_display_filter($formname,\%curr));
 7081: 
 7082:     my $showntableheader = 0;
 7083:     my ($nav_script,$nav_links);
 7084: 
 7085: # table header
 7086:     my $heading = '<h3>'.
 7087:         &mt('User access logs for: [_1]',
 7088:             &Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($uname,$udom),$uname,$udom)).'</h3>';
 7089:     my $tableheader = $heading
 7090:        .&Apache::loncommon::start_data_table_header_row()
 7091:        .'<th>&nbsp;</th>'
 7092:        .'<th>'.&mt('When').'</th>'
 7093:        .'<th>'.&mt('HostID').'</th>'
 7094:        .'<th>'.&mt('Event').'</th>'
 7095:        .'<th>'.&mt('Other data').'</th>'
 7096:        .&Apache::loncommon::end_data_table_header_row();
 7097: 
 7098:     my %filters=(
 7099:         start  => $curr{'accesslog_start_date'},
 7100:         end    => $curr{'accesslog_end_date'},
 7101:         action => $curr{'activity'},
 7102:     );
 7103: 
 7104:     my $reply = &Apache::lonnet::userlog_query($uname,$udom,%filters);
 7105:     unless ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 7106:         my (%courses,%missing);
 7107:         my @results = split(/\&/,$reply);
 7108:         foreach my $item (reverse(@results)) {
 7109:             my ($timestamp,$host,$event) = split(/:/,$item);
 7110:             next unless ($event =~ /^(Log|Role)/);
 7111:             if ($curr{'show'} !~ /\D/) {
 7112:                 if ($count >= $curr{'page'} * $curr{'show'}) {
 7113:                     $more_records = 1;
 7114:                     last;
 7115:                 }
 7116:             }
 7117:             $count ++;
 7118:             next if ($count < $minshown);
 7119:             unless ($showntableheader) {
 7120:                 $r->print($nav_script
 7121:                          .&Apache::loncommon::start_data_table()
 7122:                          .$tableheader);
 7123:                 $r->rflush();
 7124:                 $showntableheader = 1;
 7125:             }
 7126:             my ($shown,$extra);
 7127:             my ($event,$data) = split(/\s+/,&unescape($event),2);
 7128:             if ($event eq 'Role') {
 7129:                 my ($rolecode,$extent) = split(/\./,$data,2);
 7130:                 next if ($extent eq '');
 7131:                 my ($crstype,$desc,$info);
 7132:                 if ($extent =~ m{^/($match_domain)/($match_courseid)(?:/(\w+)|)$}) {
 7133:                     my ($cdom,$cnum,$sec) = ($1,$2,$3);
 7134:                     my $cid = $cdom.'_'.$cnum;
 7135:                     if (exists($courses{$cid})) {
 7136:                         $crstype = $courses{$cid}{'type'};
 7137:                         $desc = $courses{$cid}{'description'};
 7138:                     } elsif ($missing{$cid}) {
 7139:                         $crstype = 'Course';
 7140:                         $desc = 'Course/Community';
 7141:                     } else {
 7142:                         my %crsinfo = &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 7143:                         if (ref($crsinfo{$cdom.'_'.$cnum}) eq 'HASH') {
 7144:                             $courses{$cid} = $crsinfo{$cid};
 7145:                             $crstype = $crsinfo{$cid}{'type'};
 7146:                             $desc = $crsinfo{$cid}{'description'};
 7147:                         } else {
 7148:                             $missing{$cid} = 1;
 7149:                         }
 7150:                     }
 7151:                     $extra = &mt($crstype).': <a href="/public/'.$cdom.'/'.$cnum.'/syllabus">'.$desc.'</a>';
 7152:                     if ($sec ne '') {
 7153:                        $extra .= ' ('.&mt('Section: [_1]',$sec).')';
 7154:                     }
 7155:                 } elsif ($extent =~ m{^/($match_domain)/($match_username|$)}) {
 7156:                     my ($dom,$name) = ($1,$2);
 7157:                     if ($rolecode eq 'au') {
 7158:                         $extra = '';
 7159:                     } elsif ($rolecode =~ /^(ca|aa)$/) {
 7160:                         $extra = &mt('Authoring Space: [_1]',$name.':'.$dom);
 7161:                     } elsif ($rolecode =~ /^(li|dg|dh|dc|sc)$/) {
 7162:                         $extra = &mt('Domain: [_1]',$dom);
 7163:                     }
 7164:                 }
 7165:                 my $rolename;
 7166:                 if ($rolecode =~ m{^cr/($match_domain)/($match_username)/(\w+)}) {
 7167:                     my $role = $3;
 7168:                     my $owner = "($2:$1)";
 7169:                     if ($2 eq $1.'-domainconfig') {
 7170:                         $owner = '(ad hoc)';
 7171:                     }
 7172:                     $rolename = &mt('Custom role: [_1]',$role.' '.$owner);
 7173:                 } else {
 7174:                     $rolename = &Apache::lonnet::plaintext($rolecode,$crstype);
 7175:                 }
 7176:                 $shown = &mt('Role selection: [_1]',$rolename);
 7177:             } else {
 7178:                 $shown = &mt($event);
 7179:                 if ($data =~ /^webdav/) {
 7180:                     my ($path,$clientip) = split(/\s+/,$data,2);
 7181:                     $path =~ s/^webdav//;
 7182:                     if ($clientip ne '') {
 7183:                         $extra = &mt('Client IP address: [_1]',$clientip);
 7184:                     }
 7185:                     if ($path ne '') {
 7186:                         $shown .= ' '.&mt('(WebDAV access to [_1])',$path);
 7187:                     }
 7188:                 } elsif ($data ne '') {
 7189:                     $extra = &mt('Client IP address: [_1]',$data);
 7190:                 }
 7191:             }
 7192:             $r->print(
 7193:             &Apache::loncommon::start_data_table_row()
 7194:            .'<td>'.$count.'</td>'
 7195:            .'<td>'.&Apache::lonlocal::locallocaltime($timestamp).'</td>'
 7196:            .'<td>'.$host.'</td>'
 7197:            .'<td>'.$shown.'</td>'
 7198:            .'<td>'.$extra.'</td>'
 7199:            .&Apache::loncommon::end_data_table_row()."\n");
 7200:         }
 7201:     }
 7202: 
 7203:     if ($showntableheader) { # Table footer, if content displayed above
 7204:         $r->print(&Apache::loncommon::end_data_table().
 7205:                   &userlogdisplay_navlinks(\%curr,$more_records));
 7206:     } else { # No content displayed above
 7207:         $r->print($heading.'<p class="LC_info">'
 7208:                  .&mt('There are no records to display.')
 7209:                  .'</p>');
 7210:     }
 7211: 
 7212:     if ($env{'form.popup'} == 1) {
 7213:         $r->print('<input type="hidden" name="popup" value="1" />'."\n");
 7214:     }
 7215: 
 7216:     # Form Footer
 7217:     $r->print(
 7218:         '<input type="hidden" name="currstate" value="" />'
 7219:        .'<input type="hidden" name="accessuname" value="'.$uname.'" />'
 7220:        .'<input type="hidden" name="accessudom" value="'.$udom.'" />'
 7221:        .'<input type="hidden" name="page" value="'.$curr{'page'}.'" />'
 7222:        .'<input type="hidden" name="prevphases" value="'.$prevphasestr.'" />'
 7223:        .'<input type="hidden" name="phase" value="activity" />'
 7224:        .'<input type="hidden" name="action" value="accesslogs" />'
 7225:        .'<input type="hidden" name="srchdomain" value="'.$udom.'" />'
 7226:        .'<input type="hidden" name="srchby" value="'.$env{'form.srchby'}.'" />'
 7227:        .'<input type="hidden" name="srchtype" value="'.$env{'form.srchtype'}.'" />'
 7228:        .'<input type="hidden" name="srchterm" value="'.&HTML::Entities::encode($env{'form.srchterm'},'<>"&').'" />'
 7229:        .'<input type="hidden" name="srchin" value="'.$env{'form.srchin'}.'" />'
 7230:        .'</form>');
 7231:     return;
 7232: }
 7233: 
 7234: sub earlyout_accesslog_form {
 7235:     my ($formname,$prevphasestr,$udom) = @_;
 7236:     my $srchterm = &HTML::Entities::encode($env{'form.srchterm'},'<>"&');
 7237:    return <<"END";
 7238: <form action="/adm/createuser" method="post" name="$formname">
 7239: <input type="hidden" name="currstate" value="" />
 7240: <input type="hidden" name="prevphases" value="$prevphasestr" />
 7241: <input type="hidden" name="phase" value="activity" />
 7242: <input type="hidden" name="action" value="accesslogs" />
 7243: <input type="hidden" name="srchdomain" value="$udom" />
 7244: <input type="hidden" name="srchby" value="$env{'form.srchby'}" />
 7245: <input type="hidden" name="srchtype" value="$env{'form.srchtype'}" />
 7246: <input type="hidden" name="srchterm" value="$srchterm" />
 7247: <input type="hidden" name="srchin" value="$env{'form.srchin'}" />
 7248: </form>
 7249: END
 7250: }
 7251: 
 7252: sub activity_display_filter {
 7253:     my ($formname,$curr) = @_;
 7254:     my $nolink = 1;
 7255:     my $output = '<table><tr><td valign="top">'.
 7256:                  '<span class="LC_nobreak"><b>'.&mt('Actions/page:').'</b></span><br />'.
 7257:                  &Apache::lonmeta::selectbox('show',$curr->{'show'},undef,
 7258:                                               (&mt('all'),5,10,20,50,100,1000,10000)).
 7259:                  '</td><td>&nbsp;&nbsp;</td>';
 7260:     my $startform =
 7261:         &Apache::lonhtmlcommon::date_setter($formname,'accesslog_start_date',
 7262:                                             $curr->{'accesslog_start_date'},undef,
 7263:                                             undef,undef,undef,undef,undef,undef,$nolink);
 7264:     my $endform =
 7265:         &Apache::lonhtmlcommon::date_setter($formname,'accesslog_end_date',
 7266:                                             $curr->{'accesslog_end_date'},undef,
 7267:                                             undef,undef,undef,undef,undef,undef,$nolink);
 7268:     my %lt = &Apache::lonlocal::texthash (
 7269:                                           activity => 'Activity',
 7270:                                           Role     => 'Role selection',
 7271:                                           log      => 'Log-in or Logout',
 7272:     );
 7273:     $output .= '<td valign="top"><b>'.&mt('Window during which actions occurred:').'</b><br />'.
 7274:                '<table><tr><td>'.&mt('After:').
 7275:                '</td><td>'.$startform.'</td></tr>'.
 7276:                '<tr><td>'.&mt('Before:').'</td>'.
 7277:                '<td>'.$endform.'</td></tr></table>'.
 7278:                '</td>'.
 7279:                '<td>&nbsp;&nbsp;</td>'.
 7280:                '<td valign="top"><b>'.&mt('Activities').'</b><br />'.
 7281:                '<select name="activity"><option value="any"';
 7282:     if ($curr->{'activity'} eq 'any') {
 7283:         $output .= ' selected="selected"';
 7284:     }
 7285:     $output .= '>'.&mt('Any').'</option>'."\n";
 7286:     foreach my $activity ('Role','log') {
 7287:         my $selstr = '';
 7288:         if ($activity eq $curr->{'activity'}) {
 7289:             $selstr = ' selected="selected"';
 7290:         }
 7291:         $output .= '<option value="'.$activity.'"'.$selstr.'>'.$lt{$activity}.'</option>';
 7292:     }
 7293:     $output .= '</select></td>'.
 7294:                '</tr></table>';
 7295:     # Update Display button
 7296:     $output .= '<p>'
 7297:               .'<input type="submit" value="'.&mt('Update Display').'" />'
 7298:               .'</p><hr />';
 7299:     return $output;
 7300: }
 7301: 
 7302: sub userlogdisplay_js {
 7303:     my ($formname) = @_;
 7304:     return <<"ENDSCRIPT";
 7305: 
 7306: function chgPage(caller) {
 7307:     if (caller == 'previous') {
 7308:         document.$formname.page.value --;
 7309:     }
 7310:     if (caller == 'next') {
 7311:         document.$formname.page.value ++;
 7312:     }
 7313:     document.$formname.submit();
 7314:     return;
 7315: }
 7316: ENDSCRIPT
 7317: }
 7318: 
 7319: sub userlogdisplay_navlinks {
 7320:     my ($curr,$more_records) = @_;
 7321:     return unless(ref($curr) eq 'HASH');
 7322:     # Navigation Buttons
 7323:     my $nav_links = '<p>';
 7324:     if (($curr->{'page'} > 1) || ($more_records)) {
 7325:         if (($curr->{'page'} > 1) && ($curr->{'show'} !~ /\D/)) {
 7326:             $nav_links .= '<input type="button"'
 7327:                          .' onclick="javascript:chgPage('."'previous'".');"'
 7328:                          .' value="'.&mt('Previous [_1] changes',$curr->{'show'})
 7329:                          .'" /> ';
 7330:         }
 7331:         if ($more_records) {
 7332:             $nav_links .= '<input type="button"'
 7333:                          .' onclick="javascript:chgPage('."'next'".');"'
 7334:                          .' value="'.&mt('Next [_1] changes',$curr->{'show'})
 7335:                          .'" />';
 7336:         }
 7337:     }
 7338:     $nav_links .= '</p>';
 7339:     return $nav_links;
 7340: }
 7341: 
 7342: sub role_display_filter {
 7343:     my ($context,$formname,$cdom,$cnum,$curr,$version,$crstype) = @_;
 7344:     my $lctype;
 7345:     if ($context eq 'course') {
 7346:         $lctype = lc($crstype);
 7347:     }
 7348:     my $nolink = 1;
 7349:     my $output = '<table><tr><td valign="top">'.
 7350:                  '<span class="LC_nobreak"><b>'.&mt('Changes/page:').'</b></span><br />'.
 7351:                  &Apache::lonmeta::selectbox('show',$curr->{'show'},undef,
 7352:                                               (&mt('all'),5,10,20,50,100,1000,10000)).
 7353:                  '</td><td>&nbsp;&nbsp;</td>';
 7354:     my $startform =
 7355:         &Apache::lonhtmlcommon::date_setter($formname,'rolelog_start_date',
 7356:                                             $curr->{'rolelog_start_date'},undef,
 7357:                                             undef,undef,undef,undef,undef,undef,$nolink);
 7358:     my $endform =
 7359:         &Apache::lonhtmlcommon::date_setter($formname,'rolelog_end_date',
 7360:                                             $curr->{'rolelog_end_date'},undef,
 7361:                                             undef,undef,undef,undef,undef,undef,$nolink);
 7362:     my %lt = &rolechg_contexts($context,$crstype);
 7363:     $output .= '<td valign="top"><b>'.&mt('Window during which changes occurred:').'</b><br />'.
 7364:                '<table><tr><td>'.&mt('After:').
 7365:                '</td><td>'.$startform.'</td></tr>'.
 7366:                '<tr><td>'.&mt('Before:').'</td>'.
 7367:                '<td>'.$endform.'</td></tr></table>'.
 7368:                '</td>'.
 7369:                '<td>&nbsp;&nbsp;</td>'.
 7370:                '<td valign="top"><b>'.&mt('Role:').'</b><br />'.
 7371:                '<select name="role"><option value="any"';
 7372:     if ($curr->{'role'} eq 'any') {
 7373:         $output .= ' selected="selected"';
 7374:     }
 7375:     $output .=  '>'.&mt('Any').'</option>'."\n";
 7376:     my @roles = &Apache::lonuserutils::roles_by_context($context,1,$crstype);
 7377:     foreach my $role (@roles) {
 7378:         my $plrole;
 7379:         if ($role eq 'cr') {
 7380:             $plrole = &mt('Custom Role');
 7381:         } else {
 7382:             $plrole=&Apache::lonnet::plaintext($role,$crstype);
 7383:         }
 7384:         my $selstr = '';
 7385:         if ($role eq $curr->{'role'}) {
 7386:             $selstr = ' selected="selected"';
 7387:         }
 7388:         $output .= '  <option value="'.$role.'"'.$selstr.'>'.$plrole.'</option>';
 7389:     }
 7390:     $output .= '</select></td>'.
 7391:                '<td>&nbsp;&nbsp;</td>'.
 7392:                '<td valign="top"><b>'.
 7393:                &mt('Context:').'</b><br /><select name="chgcontext">';
 7394:     my @posscontexts;
 7395:     if ($context eq 'course') {
 7396:         @posscontexts = ('any','automated','updatenow','createcourse','course','domain','selfenroll','requestcourses','chgtype');
 7397:     } elsif ($context eq 'domain') {
 7398:         @posscontexts = ('any','domain','requestauthor','domconfig','server');
 7399:     } else {
 7400:         @posscontexts = ('any','author','domain');
 7401:     }
 7402:     foreach my $chgtype (@posscontexts) {
 7403:         my $selstr = '';
 7404:         if ($curr->{'chgcontext'} eq $chgtype) {
 7405:             $selstr = ' selected="selected"';
 7406:         }
 7407:         if ($context eq 'course') {
 7408:             if (($chgtype eq 'automated') || ($chgtype eq 'updatenow')) {
 7409:                 next if (!&Apache::lonnet::auto_run($cnum,$cdom));
 7410:             }
 7411:         }
 7412:         $output .= '<option value="'.$chgtype.'"'.$selstr.'>'.$lt{$chgtype}.'</option>'."\n";
 7413:     }
 7414:     $output .= '</select></td>'
 7415:               .'</tr></table>';
 7416: 
 7417:     # Update Display button
 7418:     $output .= '<p>'
 7419:               .'<input type="submit" value="'.&mt('Update Display').'" />'
 7420:               .'</p>';
 7421: 
 7422:     # Server version info
 7423:     my $needsrev = '2.11.0';
 7424:     if ($context eq 'course') {
 7425:         $needsrev = '2.7.0';
 7426:     }
 7427:     
 7428:     $output .= '<p class="LC_info">'
 7429:               .&mt('Only changes made from servers running LON-CAPA [_1] or later are displayed.'
 7430:                   ,$needsrev);
 7431:     if ($version) {
 7432:         $output .= ' '.&mt('This LON-CAPA server is version [_1]',$version);
 7433:     }
 7434:     $output .= '</p><hr />';
 7435:     return $output;
 7436: }
 7437: 
 7438: sub rolechg_contexts {
 7439:     my ($context,$crstype) = @_;
 7440:     my %lt;
 7441:     if ($context eq 'course') {
 7442:         %lt = &Apache::lonlocal::texthash (
 7443:                                              any          => 'Any',
 7444:                                              automated    => 'Automated Enrollment',
 7445:                                              chgtype      => 'Enrollment Type/Lock Change',
 7446:                                              updatenow    => 'Roster Update',
 7447:                                              createcourse => 'Course Creation',
 7448:                                              course       => 'User Management in course',
 7449:                                              domain       => 'User Management in domain',
 7450:                                              selfenroll   => 'Self-enrolled',
 7451:                                              requestcourses => 'Course Request',
 7452:                                          );
 7453:         if ($crstype eq 'Community') {
 7454:             $lt{'createcourse'} = &mt('Community Creation');
 7455:             $lt{'course'} = &mt('User Management in community');
 7456:             $lt{'requestcourses'} = &mt('Community Request');
 7457:         }
 7458:     } elsif ($context eq 'domain') {
 7459:         %lt = &Apache::lonlocal::texthash (
 7460:                                              any           => 'Any',
 7461:                                              domain        => 'User Management in domain',
 7462:                                              requestauthor => 'Authoring Request',
 7463:                                              server        => 'Command line script (DC role)',
 7464:                                              domconfig     => 'Self-enrolled',
 7465:                                          );
 7466:     } else {
 7467:         %lt = &Apache::lonlocal::texthash (
 7468:                                              any    => 'Any',
 7469:                                              domain => 'User Management in domain',
 7470:                                              author => 'User Management by author',
 7471:                                          );
 7472:     } 
 7473:     return %lt;
 7474: }
 7475: 
 7476: sub print_helpdeskaccess_display {
 7477:     my ($r,$permission,$brcrum) = @_;
 7478:     my $formname = 'helpdeskaccess';
 7479:     my $helpitem = 'Course_Helpdesk_Access';
 7480:     push (@{$brcrum},
 7481:              {href => '/adm/createuser?action=helpdesk',
 7482:               text => 'Helpdesk Access',
 7483:               help => $helpitem});
 7484:     my $bread_crumbs_component = 'Helpdesk Staff Access';
 7485:     my $args = { bread_crumbs           => $brcrum,
 7486:                  bread_crumbs_component => $bread_crumbs_component};
 7487: 
 7488:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7489:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7490:     my $confname = $cdom.'-domainconfig';
 7491:     my $crstype = &Apache::loncommon::course_type();
 7492: 
 7493:     my @accesstypes = ('all','dh','da','none');
 7494:     my ($numstatustypes,@jsarray);
 7495:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($cdom);
 7496:     if (ref($types) eq 'ARRAY') {
 7497:         if (@{$types} > 0) {
 7498:             $numstatustypes = scalar(@{$types});
 7499:             push(@accesstypes,'status');
 7500:             @jsarray = ('bystatus');
 7501:         }
 7502:     }
 7503:     my %customroles = &get_domain_customroles($cdom,$confname);
 7504:     my %domhelpdesk = &Apache::lonnet::get_active_domroles($cdom,['dh','da']);
 7505:     if (keys(%domhelpdesk)) {
 7506:        push(@accesstypes,('inc','exc'));
 7507:        push(@jsarray,('notinc','notexc'));
 7508:     }
 7509:     push(@jsarray,'privs');
 7510:     my $hiddenstr = join("','",@jsarray);
 7511:     my $rolestr = join("','",sort(keys(%customroles)));
 7512: 
 7513:     my $jscript;
 7514:     my (%settings,%overridden);
 7515:     if (keys(%customroles)) {
 7516:         &get_adhocrole_settings($env{'request.course.id'},\@accesstypes,
 7517:                                 $types,\%customroles,\%settings,\%overridden);
 7518:         my %jsfull=();
 7519:         my %jslevels= (
 7520:                      course => {},
 7521:                      domain => {},
 7522:                      system => {},
 7523:                     );
 7524:         my %jslevelscurrent=(
 7525:                            course => {},
 7526:                            domain => {},
 7527:                            system => {},
 7528:                           );
 7529:         my (%privs,%jsprivs);
 7530:         &Apache::lonuserutils::custom_role_privs(\%privs,\%jsfull,\%jslevels,\%jslevelscurrent);
 7531:         foreach my $priv (keys(%jsfull)) {
 7532:             if ($jslevels{'course'}{$priv}) {
 7533:                 $jsprivs{$priv} = 1;
 7534:             }
 7535:         }
 7536:         my (%elements,%stored);
 7537:         foreach my $role (keys(%customroles)) {
 7538:             $elements{$role.'_access'} = 'radio';
 7539:             $elements{$role.'_incrs'} = 'radio';
 7540:             if ($numstatustypes) {
 7541:                 $elements{$role.'_status'} = 'checkbox';
 7542:             }
 7543:             if (keys(%domhelpdesk) > 0) {
 7544:                 $elements{$role.'_staff_inc'} = 'checkbox';
 7545:                 $elements{$role.'_staff_exc'} = 'checkbox';
 7546:             }
 7547:             $elements{$role.'_override'} = 'checkbox';
 7548:             if (ref($settings{$role}) eq 'HASH') {
 7549:                 if ($settings{$role}{'access'} ne '') {
 7550:                     my $curraccess = $settings{$role}{'access'};
 7551:                     $stored{$role.'_access'} = $curraccess;
 7552:                     $stored{$role.'_incrs'} = 1;
 7553:                     if ($curraccess eq 'status') {
 7554:                         if (ref($settings{$role}{'status'}) eq 'ARRAY') {
 7555:                             $stored{$role.'_status'} = $settings{$role}{'status'};
 7556:                         }
 7557:                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 7558:                         if (ref($settings{$role}{$curraccess}) eq 'ARRAY') {
 7559:                             $stored{$role.'_staff_'.$curraccess} = $settings{$role}{$curraccess};
 7560:                         }
 7561:                     }
 7562:                 } else {
 7563:                     $stored{$role.'_incrs'} = 0;
 7564:                 }
 7565:                 $stored{$role.'_override'} = [];
 7566:                 if ($env{'course.'.$env{'request.course.id'}.'.internal.adhocpriv.'.$role}) {
 7567:                     if (ref($settings{$role}{'off'}) eq 'ARRAY') {
 7568:                         foreach my $priv (@{$settings{$role}{'off'}}) {
 7569:                             push(@{$stored{$role.'_override'}},$priv);
 7570:                         }
 7571:                     }
 7572:                     if (ref($settings{$role}{'on'}) eq 'ARRAY') {
 7573:                         foreach my $priv (@{$settings{$role}{'on'}}) {
 7574:                             unless (grep(/^$priv$/,@{$stored{$role.'_override'}})) {
 7575:                                 push(@{$stored{$role.'_override'}},$priv);
 7576:                             }
 7577:                         }
 7578:                     }
 7579:                 }
 7580:             } else {
 7581:                 $stored{$role.'_incrs'} = 0;
 7582:             }
 7583:         }
 7584:         $jscript = &Apache::lonhtmlcommon::set_form_elements(\%elements,\%stored);
 7585:     }
 7586: 
 7587:     my $js = <<"ENDJS";
 7588: <script type="text/javascript">
 7589: // <![CDATA[
 7590: $jscript;
 7591: 
 7592: function switchRoleTab(caller,role) {
 7593:     if (document.getElementById(role+'_maindiv')) {
 7594:         if (caller.id != 'LC_current_minitab') {
 7595:             if (document.getElementById('LC_current_minitab')) {
 7596:                 document.getElementById('LC_current_minitab').id=null;
 7597:             }
 7598:             var roledivs = Array('$rolestr');
 7599:             if (roledivs.length > 0) {
 7600:                 for (var i=0; i<roledivs.length; i++) {
 7601:                     if (document.getElementById(roledivs[i]+'_maindiv')) {
 7602:                         document.getElementById(roledivs[i]+'_maindiv').style.display='none';
 7603:                     }
 7604:                 }
 7605:             }
 7606:             caller.id = 'LC_current_minitab';
 7607:             document.getElementById(role+'_maindiv').style.display='block';
 7608:         }
 7609:     }
 7610:     return false;
 7611: }
 7612: 
 7613: function helpdeskAccess(role) {
 7614:     var curraccess = null;
 7615:     if (document.$formname.elements[role+'_access'].length) {
 7616:         for (var i=0; i<document.$formname.elements[role+'_access'].length; i++) {
 7617:             if (document.$formname.elements[role+'_access'][i].checked) {
 7618:                 curraccess = document.$formname.elements[role+'_access'][i].value;
 7619:             }
 7620:         }
 7621:     }
 7622:     var shown = Array();
 7623:     var hidden = Array();
 7624:     if (curraccess == 'none') {
 7625:         hidden = Array ('$hiddenstr');
 7626:     } else {
 7627:         if (curraccess == 'status') {
 7628:             shown = Array ('bystatus','privs');
 7629:             hidden = Array ('notinc','notexc');
 7630:         } else {
 7631:             if (curraccess == 'exc') {
 7632:                 shown = Array ('notexc','privs');
 7633:                 hidden = Array ('notinc','bystatus');
 7634:             }
 7635:             if (curraccess == 'inc') {
 7636:                 shown = Array ('notinc','privs');
 7637:                 hidden = Array ('notexc','bystatus');
 7638:             }
 7639:             if (curraccess == 'all') {
 7640:                 shown = Array ('privs');
 7641:                 hidden = Array ('notinc','notexc','bystatus');
 7642:             }
 7643:         }
 7644:     }
 7645:     if (hidden.length > 0) {
 7646:         for (var i=0; i<hidden.length; i++) {
 7647:             if (document.getElementById(role+'_'+hidden[i])) {
 7648:                 document.getElementById(role+'_'+hidden[i]).style.display = 'none';
 7649:             }
 7650:         }
 7651:     }
 7652:     if (shown.length > 0) {
 7653:         for (var i=0; i<shown.length; i++) {
 7654:             if (document.getElementById(role+'_'+shown[i])) {
 7655:                 if (shown[i] == 'privs') {
 7656:                     document.getElementById(role+'_'+shown[i]).style.display = 'block';
 7657:                 } else {
 7658:                     document.getElementById(role+'_'+shown[i]).style.display = 'inline';
 7659:                 }
 7660:             }
 7661:         }
 7662:     }
 7663:     return;
 7664: }
 7665: 
 7666: function toggleAccess(role) {
 7667:     if ((document.getElementById(role+'_setincrs')) &&
 7668:         (document.getElementById(role+'_setindom'))) {
 7669:         for (var i=0; i<document.$formname.elements[role+'_incrs'].length; i++) {
 7670:             if (document.$formname.elements[role+'_incrs'][i].checked) {
 7671:                 if (document.$formname.elements[role+'_incrs'][i].value == 1) {
 7672:                     document.getElementById(role+'_setindom').style.display = 'none';
 7673:                     document.getElementById(role+'_setincrs').style.display = 'block';
 7674:                 } else {
 7675:                     document.getElementById(role+'_setincrs').style.display = 'none';
 7676:                     document.getElementById(role+'_setindom').style.display = 'block';
 7677:                 }
 7678:                 break;
 7679:             }
 7680:         }
 7681:     }
 7682:     return;
 7683: }
 7684: 
 7685: // ]]>
 7686: </script>
 7687: ENDJS
 7688: 
 7689:     $args->{add_entries} = {onload => "javascript:setFormElements(document.$formname)"};
 7690: 
 7691:     # print page header
 7692:     $r->print(&header($js,$args));
 7693:     # print form header
 7694:     $r->print('<form action="/adm/createuser" method="post" name="'.$formname.'">');
 7695: 
 7696:     if (keys(%customroles)) {
 7697:         my %lt = &Apache::lonlocal::texthash(
 7698:                     'aco'    => 'As course owner you may override the defaults set in the domain for role usage and/or privileges.',
 7699:                     'rou'    => 'Role usage',
 7700:                     'whi'    => 'Which helpdesk personnel may use this role?',
 7701:                     'udd'    => 'Use domain default',
 7702:                     'all'    => 'All with domain helpdesk or helpdesk assistant role',
 7703:                     'dh'     => 'All with domain helpdesk role',
 7704:                     'da'     => 'All with domain helpdesk assistant role',
 7705:                     'none'   => 'None',
 7706:                     'status' => 'Determined based on institutional status',
 7707:                     'inc'    => 'Include all, but exclude specific personnel',
 7708:                     'exc'    => 'Exclude all, but include specific personnel',
 7709:                     'hel'    => 'Helpdesk',
 7710:                     'rpr'    => 'Role privileges',
 7711:                  );
 7712:         $lt{'tfh'} = &mt("Custom [_1]ad hoc[_2] course roles available for use by the domain's helpdesk are as follows",'<i>','</i>');
 7713:         my %domconfig = &Apache::lonnet::get_dom('configuration',['helpsettings'],$cdom);
 7714:         my (%domcurrent,%ordered,%description,%domusage,$disabled);
 7715:         if (ref($domconfig{'helpsettings'}) eq 'HASH') {
 7716:             if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
 7717:                 %domcurrent = %{$domconfig{'helpsettings'}{'adhoc'}};
 7718:             }
 7719:         }
 7720:         my $count = 0;
 7721:         foreach my $role (sort(keys(%customroles))) {
 7722:             my ($order,$desc,$access_in_dom);
 7723:             if (ref($domcurrent{$role}) eq 'HASH') {
 7724:                 $order = $domcurrent{$role}{'order'};
 7725:                 $desc = $domcurrent{$role}{'desc'};
 7726:                 $access_in_dom = $domcurrent{$role}{'access'};
 7727:             }
 7728:             if ($order eq '') {
 7729:                 $order = $count;
 7730:             }
 7731:             $ordered{$order} = $role;
 7732:             if ($desc ne '') {
 7733:                 $description{$role} = $desc;
 7734:             } else {
 7735:                 $description{$role}= $role;
 7736:             }
 7737:             $count++;
 7738:         }
 7739:         %domusage = &domain_adhoc_access(\%customroles,\%domcurrent,\@accesstypes,$usertypes,$othertitle);
 7740:         my @roles_by_num = ();
 7741:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 7742:             push(@roles_by_num,$ordered{$item});
 7743:         }
 7744:         $r->print('<p>'.$lt{'tfh'}.': <i>'.join('</i>, <i>',map { $description{$_}; } @roles_by_num).'</i>.');
 7745:         if ($permission->{'owner'}) {
 7746:             $r->print('<br />'.$lt{'aco'}.'</p><p>');
 7747:             $r->print('<input type="hidden" name="state" value="process" />'.
 7748:                       '<input type="submit" value="'.&mt('Save changes').'" />');
 7749:         } else {
 7750:             if ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'}) {
 7751:                 my ($ownername,$ownerdom) = split(/:/,$env{'course.'.$env{'request.course.id'}.'.internal.courseowner'});
 7752:                 $r->print('<br />'.&mt('The course owner -- [_1] -- can override the default access and/or privileges for these ad hoc roles.',
 7753:                                     &Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($ownername,$ownerdom),$ownername,$ownerdom)));
 7754:             }
 7755:             $disabled = ' disabled="disabled"';
 7756:         }
 7757:         $r->print('</p>');
 7758: 
 7759:         $r->print('<div id="LC_minitab_header"><ul>');
 7760:         my $count = 0;
 7761:         my %visibility;
 7762:         foreach my $role (@roles_by_num) {
 7763:             my $id;
 7764:             if ($count == 0) {
 7765:                 $id=' id="LC_current_minitab"';
 7766:                 $visibility{$role} = ' style="display:block"';
 7767:             } else {
 7768:                 $visibility{$role} = ' style="display:none"';
 7769:             }
 7770:             $count ++;
 7771:             $r->print('<li'.$id.'><a href="#" onclick="javascript:switchRoleTab(this.parentNode,'."'$role'".');">'.$description{$role}.'</a></li>');
 7772:         }
 7773:         $r->print('</ul></div>');
 7774: 
 7775:         foreach my $role (@roles_by_num) {
 7776:             my %usecheck = (
 7777:                              all => ' checked="checked"',
 7778:                            );
 7779:             my %displaydiv = (
 7780:                                 status => 'none',
 7781:                                 inc    => 'none',
 7782:                                 exc    => 'none',
 7783:                                 priv   => 'block',
 7784:                              );
 7785:             my (%selected,$overridden,$incrscheck,$indomcheck,$indomvis,$incrsvis);
 7786:             if (ref($settings{$role}) eq 'HASH') {
 7787:                 if ($settings{$role}{'access'} ne '') {
 7788:                     $indomvis = ' style="display:none"';
 7789:                     $incrsvis = ' style="display:block"';
 7790:                     $incrscheck = ' checked="checked"';
 7791:                     if ($settings{$role}{'access'} ne 'all') {
 7792:                         $usecheck{$settings{$role}{'access'}} = $usecheck{'all'};
 7793:                         delete($usecheck{'all'});
 7794:                         if ($settings{$role}{'access'} eq 'status') {
 7795:                             my $access = 'status';
 7796:                             $displaydiv{$access} = 'inline';
 7797:                             if (ref($settings{$role}{$access}) eq 'ARRAY') {
 7798:                                 $selected{$access} = $settings{$role}{$access};
 7799:                             }
 7800:                         } elsif ($settings{$role}{'access'} =~ /^(inc|exc)$/) {
 7801:                             my $access = $1;
 7802:                             $displaydiv{$access} = 'inline';
 7803:                             if (ref($settings{$role}{$access}) eq 'ARRAY') {
 7804:                                 $selected{$access} = $settings{$role}{$access};
 7805:                             }
 7806:                         } elsif ($settings{$role}{'access'} eq 'none') {
 7807:                             $displaydiv{'priv'} = 'none';
 7808:                         }
 7809:                     }
 7810:                 } else {
 7811:                     $indomcheck = ' checked="checked"';
 7812:                     $indomvis = ' style="display:block"';
 7813:                     $incrsvis = ' style="display:none"';
 7814:                 }
 7815:             } else {
 7816:                 $indomcheck = ' checked="checked"';
 7817:                 $indomvis = ' style="display:block"';
 7818:                 $incrsvis = ' style="display:none"';
 7819:             }
 7820:             $r->print('<div class="LC_left_float" id="'.$role.'_maindiv"'.$visibility{$role}.'>'.
 7821:                       '<fieldset><legend>'.$lt{'rou'}.'</legend>'.
 7822:                       '<p>'.$lt{'whi'}.' <span class="LC_nobreak">'.
 7823:                       '<label><input type="radio" name="'.$role.'_incrs" value="1"'.$incrscheck.' onclick="toggleAccess('."'$role'".');"'.$disabled.'>'.
 7824:                       &mt('Set here in [_1]',lc($crstype)).'</label>'.
 7825:                       '<span>'.('&nbsp;'x2).
 7826:                       '<label><input type="radio" name="'.$role.'_incrs" value="0"'.$indomcheck.' onclick="toggleAccess('."'$role'".');"'.$disabled.'>'.
 7827:                       $lt{'udd'}.'</label><span></p>'.
 7828:                       '<div id="'.$role.'_setindom"'.$indomvis.'>'.
 7829:                       '<span class="LC_cusr_emph">'.$domusage{$role}.'</span></div>'.
 7830:                       '<div id="'.$role.'_setincrs"'.$incrsvis.'>');
 7831:             foreach my $access (@accesstypes) {
 7832:                 $r->print('<p><label><input type="radio" name="'.$role.'_access" value="'.$access.'" '.$usecheck{$access}.
 7833:                           ' onclick="helpdeskAccess('."'$role'".');"'.$disabled.' />'.$lt{$access}.'</label>');
 7834:                 if ($access eq 'status') {
 7835:                     $r->print('<div id="'.$role.'_bystatus" style="display:'.$displaydiv{$access}.'">'.
 7836:                               &Apache::lonuserutils::adhoc_status_types($cdom,undef,$role,$selected{$access},
 7837:                                                                         $othertitle,$usertypes,$types,$disabled).
 7838:                               '</div>');
 7839:                 } elsif (($access eq 'inc') && (keys(%domhelpdesk) > 0)) {
 7840:                     $r->print('<div id="'.$role.'_notinc" style="display:'.$displaydiv{$access}.'">'.
 7841:                               &Apache::lonuserutils::adhoc_staff($access,undef,$role,$selected{$access},
 7842:                                                                  \%domhelpdesk,$disabled).
 7843:                               '</div>');
 7844:                 } elsif (($access eq 'exc') && (keys(%domhelpdesk) > 0)) {
 7845:                     $r->print('<div id="'.$role.'_notexc" style="display:'.$displaydiv{$access}.'">'.
 7846:                               &Apache::lonuserutils::adhoc_staff($access,undef,$role,$selected{$access},
 7847:                                                                  \%domhelpdesk,$disabled).
 7848:                               '</div>');
 7849:                 }
 7850:                 $r->print('</p>');
 7851:             }
 7852:             $r->print('</div></fieldset>');
 7853:             my %full=();
 7854:             my %levels= (
 7855:                          course => {},
 7856:                          domain => {},
 7857:                          system => {},
 7858:                         );
 7859:             my %levelscurrent=(
 7860:                                course => {},
 7861:                                domain => {},
 7862:                                system => {},
 7863:                               );
 7864:             &Apache::lonuserutils::custom_role_privs($customroles{$role},\%full,\%levels,\%levelscurrent);
 7865:             $r->print('<fieldset id="'.$role.'_privs" style="display:'.$displaydiv{'priv'}.'">'.
 7866:                       '<legend>'.$lt{'rpr'}.'</legend>'.
 7867:                       &role_priv_table($role,$permission,$crstype,\%full,\%levels,\%levelscurrent,$overridden{$role}).
 7868:                       '</fieldset></div><div style="padding:0;clear:both;margin:0;border:0"></div>');
 7869:         }
 7870:         if ($permission->{'owner'}) {
 7871:             $r->print('<p><input type="submit" value="'.&mt('Save changes').'" /></p>');
 7872:         }
 7873:     } else {
 7874:         $r->print(&mt('Helpdesk roles have not yet been created in this domain.'));
 7875:     }
 7876:     # Form Footer
 7877:     $r->print('<input type="hidden" name="action" value="helpdesk" />'
 7878:              .'</form>');
 7879:     return;
 7880: }
 7881: 
 7882: sub domain_adhoc_access {
 7883:     my ($roles,$domcurrent,$accesstypes,$usertypes,$othertitle) = @_;
 7884:     my %domusage;
 7885:     return unless ((ref($roles) eq 'HASH') && (ref($domcurrent) eq 'HASH') && (ref($accesstypes) eq 'ARRAY'));
 7886:     foreach my $role (keys(%{$roles})) {
 7887:         if (ref($domcurrent->{$role}) eq 'HASH') {
 7888:             my $access = $domcurrent->{$role}{'access'};
 7889:             if (($access eq '') || (!grep(/^\Q$access\E$/,@{$accesstypes}))) {
 7890:                 $access = 'all';
 7891:                 $domusage{$role} = &mt('Any user in domain with active [_1] or [_2] role',&Apache::lonnet::plaintext('dh'),
 7892:                                                                                           &Apache::lonnet::plaintext('da'));
 7893:             } elsif ($access eq 'status') {
 7894:                 if (ref($domcurrent->{$role}{$access}) eq 'ARRAY') {
 7895:                     my @shown;
 7896:                     foreach my $type (@{$domcurrent->{$role}{$access}}) {
 7897:                         unless ($type eq 'default') {
 7898:                             if ($usertypes->{$type}) {
 7899:                                 push(@shown,$usertypes->{$type});
 7900:                             }
 7901:                         }
 7902:                     }
 7903:                     if (grep(/^default$/,@{$domcurrent->{$role}{$access}})) {
 7904:                         push(@shown,$othertitle);
 7905:                     }
 7906:                     if (@shown) {
 7907:                         my $shownstatus = join(' '.&mt('or').' ',@shown);
 7908:                         $domusage{$role} = &mt('Any user in domain with active [_1] or [_2] role, and institutional status: [_3]',
 7909:                                                &Apache::lonnet::plaintext('dh'),&Apache::lonnet::plaintext('da'),$shownstatus);
 7910:                     } else {
 7911:                         $domusage{$role} = &mt('No one in the domain');
 7912:                     }
 7913:                 }
 7914:             } elsif ($access eq 'inc') {
 7915:                 my @dominc = ();
 7916:                 if (ref($domcurrent->{$role}{'inc'}) eq 'ARRAY') {
 7917:                     foreach my $user (@{$domcurrent->{$role}{'inc'}}) {
 7918:                         my ($uname,$udom) = split(/:/,$user);
 7919:                         push(@dominc,&Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($uname,$udom),$uname,$udom));
 7920:                     }
 7921:                     my $showninc = join(', ',@dominc);
 7922:                     if ($showninc ne '') {
 7923:                         $domusage{$role} = &mt('Include any user in domain with active [_1] or [_2] role, except: [_3]',
 7924:                                                &Apache::lonnet::plaintext('dh'),&Apache::lonnet::plaintext('da'),$showninc);
 7925:                     } else {
 7926:                         $domusage{$role} = &mt('Any user in domain with active [_1] or [_2] role',
 7927:                                                &Apache::lonnet::plaintext('dh'),&Apache::lonnet::plaintext('da'));
 7928:                     }
 7929:                 }
 7930:             } elsif ($access eq 'exc') {
 7931:                 my @domexc = ();
 7932:                 if (ref($domcurrent->{$role}{'exc'}) eq 'ARRAY') {
 7933:                     foreach my $user (@{$domcurrent->{$role}{'exc'}}) {
 7934:                         my ($uname,$udom) = split(/:/,$user);
 7935:                         push(@domexc,&Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($uname,$udom),$uname,$udom));
 7936:                     }
 7937:                 }
 7938:                 my $shownexc = join(', ',@domexc);
 7939:                 if ($shownexc ne '') {
 7940:                     $domusage{$role} = &mt('Only the following in the domain with active [_1] or [_2] role: [_3]',
 7941:                                            &Apache::lonnet::plaintext('dh'),&Apache::lonnet::plaintext('da'),$shownexc);
 7942:                 } else {
 7943:                     $domusage{$role} = &mt('No one in the domain');
 7944:                 }
 7945:             } elsif ($access eq 'none') {
 7946:                 $domusage{$role} = &mt('No one in the domain');
 7947:             } elsif ($access eq 'dh') {
 7948:                 $domusage{$role} = &mt('Any user in domain with active [_1] role',&Apache::lonnet::plaintext('dh'));
 7949:             } elsif ($access eq 'da') {
 7950:                 $domusage{$role} = &mt('Any user in domain with active [_1] role',&Apache::lonnet::plaintext('da'));
 7951:             } elsif ($access eq 'all') {
 7952:                 $domusage{$role} = &mt('Any user in domain with active [_1] or [_2] role',
 7953:                                        &Apache::lonnet::plaintext('dh'),&Apache::lonnet::plaintext('da'));
 7954:             }
 7955:         } else {
 7956:             $domusage{$role} = &mt('Any user in domain with active [_1] or [_2] role',
 7957:                                    &Apache::lonnet::plaintext('dh'),&Apache::lonnet::plaintext('da'));
 7958:         }
 7959:     }
 7960:     return %domusage;
 7961: }
 7962: 
 7963: sub get_domain_customroles {
 7964:     my ($cdom,$confname) = @_;
 7965:     my %existing=&Apache::lonnet::dump('roles',$cdom,$confname,'rolesdef_');
 7966:     my %customroles;
 7967:     foreach my $key (keys(%existing)) {
 7968:         if ($key=~/^rolesdef\_(\w+)$/) {
 7969:             my $rolename = $1;
 7970:             my %privs;
 7971:             ($privs{'system'},$privs{'domain'},$privs{'course'}) = split(/\_/,$existing{$key});
 7972:             $customroles{$rolename} = \%privs;
 7973:         }
 7974:     }
 7975:     return %customroles;
 7976: }
 7977: 
 7978: sub role_priv_table {
 7979:     my ($role,$permission,$crstype,$full,$levels,$levelscurrent,$overridden) = @_;
 7980:     return unless ((ref($full) eq 'HASH') && (ref($levels) eq 'HASH') &&
 7981:                    (ref($levelscurrent) eq 'HASH'));
 7982:     my %lt=&Apache::lonlocal::texthash (
 7983:                     'crl'  => 'Course Level Privilege',
 7984:                     'def'  => 'Domain Defaults',
 7985:                     'ove'  => 'Override in Course',
 7986:                     'ine'  => 'In effect',
 7987:                     'dis'  => 'Disabled',
 7988:                     'ena'  => 'Enabled',
 7989:                    );
 7990:     if ($crstype eq 'Community') {
 7991:         $lt{'ove'} = 'Override in Community',
 7992:     }
 7993:     my @status = ('Disabled','Enabled');
 7994:     my (%on,%off);
 7995:     if (ref($overridden) eq 'HASH') {
 7996:         if (ref($overridden->{'on'}) eq 'ARRAY') {
 7997:             map { $on{$_} = 1; } (@{$overridden->{'on'}});
 7998:         }
 7999:         if (ref($overridden->{'off'}) eq 'ARRAY') {
 8000:             map { $off{$_} = 1; } (@{$overridden->{'off'}});
 8001:         }
 8002:     }
 8003:     my $output=&Apache::loncommon::start_data_table().
 8004:                &Apache::loncommon::start_data_table_header_row().
 8005:                '<th>'.$lt{'crl'}.'</th><th>'.$lt{'def'}.'</th><th>'.$lt{'ove'}.
 8006:                '</th><th>'.$lt{'ine'}.'</th>'.
 8007:                &Apache::loncommon::end_data_table_header_row();
 8008:     foreach my $priv (sort(keys(%{$full}))) {
 8009:         next unless ($levels->{'course'}{$priv});
 8010:         my $privtext = &Apache::lonnet::plaintext($priv,$crstype);
 8011:         my ($default,$ineffect);
 8012:         if ($levelscurrent->{'course'}{$priv}) {
 8013:             $default = '<img src="/adm/lonIcons/navmap.correct.gif" alt="'.$lt{'ena'}.'" />';
 8014:             $ineffect = $default;
 8015:         }
 8016:         my ($customstatus,$checked);
 8017:         $output .= &Apache::loncommon::start_data_table_row().
 8018:                    '<td>'.$privtext.'</td>'.
 8019:                    '<td>'.$default.'</td><td>';
 8020:         if (($levelscurrent->{'course'}{$priv}) && ($off{$priv})) {
 8021:             if ($permission->{'owner'}) {
 8022:                 $checked = ' checked="checked"';
 8023:             }
 8024:             $customstatus = '<img src="/adm/lonIcons/navmap.wrong.gif" alt="'.$lt{'dis'}.'" />';
 8025:             $ineffect = $customstatus;
 8026:         } elsif ((!$levelscurrent->{'course'}{$priv}) && ($on{$priv})) {
 8027:             if ($permission->{'owner'}) {
 8028:                 $checked = ' checked="checked"';
 8029:             }
 8030:             $customstatus = '<img src="/adm/lonIcons/navmap.correct.gif" alt="'.$lt{'ena'}.'" />';
 8031:             $ineffect = $customstatus;
 8032:         }
 8033:         if ($permission->{'owner'}) {
 8034:             $output .= '<input type="checkbox" name="'.$role.'_override" value="'.$priv.'"'.$checked.' />';
 8035:         } else {
 8036:             $output .= $customstatus;
 8037:         }
 8038:         $output .= '</td><td>'.$ineffect.'</td>'.
 8039:                    &Apache::loncommon::end_data_table_row();
 8040:     }
 8041:     $output .= &Apache::loncommon::end_data_table();
 8042:     return $output;
 8043: }
 8044: 
 8045: sub get_adhocrole_settings {
 8046:     my ($cid,$accesstypes,$types,$customroles,$settings,$overridden) = @_;
 8047:     return unless ((ref($accesstypes) eq 'ARRAY') && (ref($customroles) eq 'HASH') &&
 8048:                    (ref($settings) eq 'HASH') && (ref($overridden) eq 'HASH'));
 8049:     foreach my $role (split(/,/,$env{'course.'.$cid.'.internal.adhocaccess'})) {
 8050:         my ($curraccess,$rest) = split(/=/,$env{'course.'.$cid.'.internal.adhoc.'.$role});
 8051:         if (($curraccess ne '') && (grep(/^\Q$curraccess\E$/,@{$accesstypes}))) {
 8052:             $settings->{$role}{'access'} = $curraccess;
 8053:             if (($curraccess eq 'status') && (ref($types) eq 'ARRAY')) {
 8054:                 my @status = split(/,/,$rest);
 8055:                 my @currstatus;
 8056:                 foreach my $type (@status) {
 8057:                     if ($type eq 'default') {
 8058:                         push(@currstatus,$type);
 8059:                     } elsif (grep(/^\Q$type\E$/,@{$types})) {
 8060:                         push(@currstatus,$type);
 8061:                     }
 8062:                 }
 8063:                 if (@currstatus) {
 8064:                     $settings->{$role}{$curraccess} = \@currstatus;
 8065:                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 8066:                     my @personnel = split(/,/,$rest);
 8067:                     $settings->{$role}{$curraccess} = \@personnel;
 8068:                 }
 8069:             }
 8070:         }
 8071:     }
 8072:     foreach my $role (keys(%{$customroles})) {
 8073:         if ($env{'course.'.$cid.'.internal.adhocpriv.'.$role}) {
 8074:             my %currentprivs;
 8075:             if (ref($customroles->{$role}) eq 'HASH') {
 8076:                 if (exists($customroles->{$role}{'course'})) {
 8077:                     my %full=();
 8078:                     my %levels= (
 8079:                                   course => {},
 8080:                                   domain => {},
 8081:                                   system => {},
 8082:                                 );
 8083:                     my %levelscurrent=(
 8084:                                         course => {},
 8085:                                         domain => {},
 8086:                                         system => {},
 8087:                                       );
 8088:                     &Apache::lonuserutils::custom_role_privs($customroles->{$role},\%full,\%levels,\%levelscurrent);
 8089:                     %currentprivs = %{$levelscurrent{'course'}};
 8090:                 }
 8091:             }
 8092:             foreach my $item (split(/,/,$env{'course.'.$cid.'.internal.adhocpriv.'.$role})) {
 8093:                 next if ($item eq '');
 8094:                 my ($rule,$rest) = split(/=/,$item);
 8095:                 next unless (($rule eq 'off') || ($rule eq 'on'));
 8096:                 foreach my $priv (split(/:/,$rest)) {
 8097:                     if ($priv ne '') {
 8098:                         if ($rule eq 'off') {
 8099:                             push(@{$overridden->{$role}{'off'}},$priv);
 8100:                             if ($currentprivs{$priv}) {
 8101:                                 push(@{$settings->{$role}{'off'}},$priv);
 8102:                             }
 8103:                         } else {
 8104:                             push(@{$overridden->{$role}{'on'}},$priv);
 8105:                             unless ($currentprivs{$priv}) {
 8106:                                 push(@{$settings->{$role}{'on'}},$priv);
 8107:                             }
 8108:                         }
 8109:                     }
 8110:                 }
 8111:             }
 8112:         }
 8113:     }
 8114:     return;
 8115: }
 8116: 
 8117: sub update_helpdeskaccess {
 8118:     my ($r,$permission,$brcrum) = @_;
 8119:     my $helpitem = 'Course_Helpdesk_Access';
 8120:     push (@{$brcrum},
 8121:              {href => '/adm/createuser?action=helpdesk',
 8122:               text => 'Helpdesk Access',
 8123:               help => $helpitem},
 8124:              {href => '/adm/createuser?action=helpdesk',
 8125:               text => 'Result',
 8126:               help => $helpitem}
 8127:          );
 8128:     my $bread_crumbs_component = 'Helpdesk Staff Access';
 8129:     my $args = { bread_crumbs           => $brcrum,
 8130:                  bread_crumbs_component => $bread_crumbs_component};
 8131: 
 8132:     # print page header
 8133:     $r->print(&header('',$args));
 8134:     unless ((ref($permission) eq 'HASH') && ($permission->{'owner'})) {
 8135:         $r->print('<p class="LC_error">'.&mt('You do not have permission to change helpdesk access.').'</p>');
 8136:         return;
 8137:     }
 8138:     my @accesstypes = ('all','dh','da','none','status','inc','exc');
 8139:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8140:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 8141:     my $confname = $cdom.'-domainconfig';
 8142:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($cdom);
 8143:     my $crstype = &Apache::loncommon::course_type();
 8144:     my %customroles = &get_domain_customroles($cdom,$confname);
 8145:     my (%settings,%overridden);
 8146:     &get_adhocrole_settings($env{'request.course.id'},\@accesstypes,
 8147:                             $types,\%customroles,\%settings,\%overridden);
 8148:     my %domhelpdesk = &Apache::lonnet::get_active_domroles($cdom,['dh','da']);
 8149:     my (%changed,%storehash,@todelete);
 8150: 
 8151:     if (keys(%customroles)) {
 8152:         my (%newsettings,@incrs);
 8153:         foreach my $role (keys(%customroles)) {
 8154:             $newsettings{$role} = {
 8155:                                     access => '',
 8156:                                     status => '',
 8157:                                     exc    => '',
 8158:                                     inc    => '',
 8159:                                     on     => '',
 8160:                                     off    => '',
 8161:                                   };
 8162:             my %current;
 8163:             if (ref($settings{$role}) eq 'HASH') {
 8164:                 %current = %{$settings{$role}};
 8165:             }
 8166:             if (ref($overridden{$role}) eq 'HASH') {
 8167:                 $current{'overridden'} = $overridden{$role};
 8168:             }
 8169:             if ($env{'form.'.$role.'_incrs'}) {
 8170:                 my $access = $env{'form.'.$role.'_access'};
 8171:                 if (grep(/^\Q$access\E$/,@accesstypes)) {
 8172:                     push(@incrs,$role);
 8173:                     unless ($current{'access'} eq $access) {
 8174:                         $changed{$role}{'access'} = 1;
 8175:                         $storehash{'internal.adhoc.'.$role} = $access;
 8176:                     }
 8177:                     if ($access eq 'status') {
 8178:                         my @statuses = &Apache::loncommon::get_env_multiple('form.'.$role.'_status');
 8179:                         my @stored;
 8180:                         my @shownstatus;
 8181:                         if (ref($types) eq 'ARRAY') {
 8182:                             foreach my $type (sort(@statuses)) {
 8183:                                 if ($type eq 'default') {
 8184:                                     push(@stored,$type);
 8185:                                 } elsif (grep(/^\Q$type\E$/,@{$types})) {
 8186:                                     push(@stored,$type);
 8187:                                     push(@shownstatus,$usertypes->{$type});
 8188:                                 }
 8189:                             }
 8190:                             if (grep(/^default$/,@statuses)) {
 8191:                                 push(@shownstatus,$othertitle);
 8192:                             }
 8193:                             $storehash{'internal.adhoc.'.$role} .= '='.join(',',@stored);
 8194:                         }
 8195:                         $newsettings{$role}{'status'} = join(' '.&mt('or').' ',@shownstatus);
 8196:                         if (ref($current{'status'}) eq 'ARRAY') {
 8197:                             my @diffs = &Apache::loncommon::compare_arrays(\@stored,$current{'status'});
 8198:                             if (@diffs) {
 8199:                                 $changed{$role}{'status'} = 1;
 8200:                             }
 8201:                         } elsif (@stored) {
 8202:                             $changed{$role}{'status'} = 1;
 8203:                         }
 8204:                     } elsif (($access eq 'inc') || ($access eq 'exc')) {
 8205:                         my @personnel = &Apache::loncommon::get_env_multiple('form.'.$role.'_staff_'.$access);
 8206:                         my @newspecstaff;
 8207:                         my @stored;
 8208:                         my @currstaff;
 8209:                         foreach my $person (sort(@personnel)) {
 8210:                             if ($domhelpdesk{$person}) {
 8211:                                 push(@stored,$person);
 8212:                             }
 8213:                         }
 8214:                         if (ref($current{$access}) eq 'ARRAY') {
 8215:                             my @diffs = &Apache::loncommon::compare_arrays(\@stored,$current{$access});
 8216:                             if (@diffs) {
 8217:                                 $changed{$role}{$access} = 1;
 8218:                             }
 8219:                         } elsif (@stored) {
 8220:                             $changed{$role}{$access} = 1;
 8221:                         }
 8222:                         $storehash{'internal.adhoc.'.$role} .= '='.join(',',@stored);
 8223:                         foreach my $person (@stored) {
 8224:                             my ($uname,$udom) = split(/:/,$person);
 8225:                             push(@newspecstaff,&Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($uname,$udom,'lastname'),$uname,$udom));
 8226:                         }
 8227:                         $newsettings{$role}{$access} = join(', ',sort(@newspecstaff));
 8228:                     }
 8229:                     $newsettings{$role}{'access'} = $access;
 8230:                 }
 8231:             } else {
 8232:                 if (($current{'access'} ne '') && (grep(/^\Q$current{'access'}\E$/,@accesstypes))) {
 8233:                     $changed{$role}{'access'} = 1;
 8234:                     $newsettings{$role} = {};
 8235:                     push(@todelete,'internal.adhoc.'.$role);
 8236:                 }
 8237:             }
 8238:             if (($env{'form.'.$role.'_incrs'}) && ($env{'form.'.$role.'_access'} eq 'none')) {
 8239:                 if (ref($current{'overridden'}) eq 'HASH') {
 8240:                     push(@todelete,'internal.adhocpriv.'.$role);
 8241:                 }
 8242:             } else {
 8243:                 my %full=();
 8244:                 my %levels= (
 8245:                              course => {},
 8246:                              domain => {},
 8247:                              system => {},
 8248:                             );
 8249:                 my %levelscurrent=(
 8250:                                    course => {},
 8251:                                    domain => {},
 8252:                                    system => {},
 8253:                                   );
 8254:                 &Apache::lonuserutils::custom_role_privs($customroles{$role},\%full,\%levels,\%levelscurrent);
 8255:                 my (@updatedon,@updatedoff,@override);
 8256:                 @override = &Apache::loncommon::get_env_multiple('form.'.$role.'_override');
 8257:                 if (@override) {
 8258:                     foreach my $priv (sort(keys(%full))) {
 8259:                         next unless ($levels{'course'}{$priv});
 8260:                         if (grep(/^\Q$priv\E$/,@override)) {
 8261:                             if ($levelscurrent{'course'}{$priv}) {
 8262:                                 push(@updatedoff,$priv);
 8263:                             } else {
 8264:                                 push(@updatedon,$priv);
 8265:                             }
 8266:                         }
 8267:                     }
 8268:                 }
 8269:                 if (@updatedon) {
 8270:                     $newsettings{$role}{'on'} = join('</li><li>', map { &Apache::lonnet::plaintext($_,$crstype) } (@updatedon));
 8271:                 }
 8272:                 if (@updatedoff) {
 8273:                     $newsettings{$role}{'off'} = join('</li><li>', map { &Apache::lonnet::plaintext($_,$crstype) } (@updatedoff));
 8274:                 }
 8275:                 if (ref($current{'overridden'}) eq 'HASH') {
 8276:                     if (ref($current{'overridden'}{'on'}) eq 'ARRAY') {
 8277:                         if (@updatedon) {
 8278:                             my @diffs = &Apache::loncommon::compare_arrays(\@updatedon,$current{'overridden'}{'on'});
 8279:                             if (@diffs) {
 8280:                                 $changed{$role}{'on'} = 1;
 8281:                             }
 8282:                         } else {
 8283:                             $changed{$role}{'on'} = 1;
 8284:                         }
 8285:                     } elsif (@updatedon) {
 8286:                         $changed{$role}{'on'} = 1;
 8287:                     }
 8288:                     if (ref($current{'overridden'}{'off'}) eq 'ARRAY') {
 8289:                         if (@updatedoff) {
 8290:                             my @diffs = &Apache::loncommon::compare_arrays(\@updatedoff,$current{'overridden'}{'off'});
 8291:                             if (@diffs) {
 8292:                                 $changed{$role}{'off'} = 1;
 8293:                             }
 8294:                         } else {
 8295:                             $changed{$role}{'off'} = 1;
 8296:                         }
 8297:                     } elsif (@updatedoff) {
 8298:                         $changed{$role}{'off'} = 1;
 8299:                     }
 8300:                 } else {
 8301:                     if (@updatedon) {
 8302:                         $changed{$role}{'on'} = 1;
 8303:                     }
 8304:                     if (@updatedoff) {
 8305:                         $changed{$role}{'off'} = 1;
 8306:                     }
 8307:                 }
 8308:                 if (ref($changed{$role}) eq 'HASH') {
 8309:                     if (($changed{$role}{'on'} || $changed{$role}{'off'})) {
 8310:                         my $newpriv;
 8311:                         if (@updatedon) {
 8312:                             $newpriv = 'on='.join(':',@updatedon);
 8313:                         }
 8314:                         if (@updatedoff) {
 8315:                             $newpriv .= ($newpriv ? ',' : '' ).'off='.join(':',@updatedoff);
 8316:                         }
 8317:                         if ($newpriv eq '') {
 8318:                             push(@todelete,'internal.adhocpriv.'.$role);
 8319:                         } else {
 8320:                             $storehash{'internal.adhocpriv.'.$role} = $newpriv;
 8321:                         }
 8322:                     }
 8323:                 }
 8324:             }
 8325:         }
 8326:         if (@incrs) {
 8327:             $storehash{'internal.adhocaccess'} = join(',',@incrs);
 8328:         } elsif (@todelete) {
 8329:             push(@todelete,'internal.adhocaccess');
 8330:         }
 8331:         if (keys(%changed)) {
 8332:             my ($putres,$delres);
 8333:             if (keys(%storehash)) {
 8334:                 $putres = &Apache::lonnet::put('environment',\%storehash,$cdom,$cnum);
 8335:                 my %newenvhash;
 8336:                 foreach my $key (keys(%storehash)) {
 8337:                     $newenvhash{'course.'.$env{'request.course.id'}.'.'.$key} = $storehash{$key};
 8338:                 }
 8339:                 &Apache::lonnet::appenv(\%newenvhash);
 8340:             }
 8341:             if (@todelete) {
 8342:                 $delres = &Apache::lonnet::del('environment',\@todelete,$cdom,$cnum);
 8343:                 foreach my $key (@todelete) {
 8344:                     &Apache::lonnet::delenv('course.'.$env{'request.course.id'}.'.'.$key);
 8345:                 }
 8346:             }
 8347:             if (($putres eq 'ok') || ($delres eq 'ok')) {
 8348:                 my %domconfig = &Apache::lonnet::get_dom('configuration',['helpsettings'],$cdom);
 8349:                 my (%domcurrent,%ordered,%description,%domusage);
 8350:                 if (ref($domconfig{'helpsettings'}) eq 'HASH') {
 8351:                     if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
 8352:                         %domcurrent = %{$domconfig{'helpsettings'}{'adhoc'}};
 8353:                     }
 8354:                 }
 8355:                 my $count = 0;
 8356:                 foreach my $role (sort(keys(%customroles))) {
 8357:                     my ($order,$desc);
 8358:                     if (ref($domcurrent{$role}) eq 'HASH') {
 8359:                         $order = $domcurrent{$role}{'order'};
 8360:                         $desc = $domcurrent{$role}{'desc'};
 8361:                     }
 8362:                     if ($order eq '') {
 8363:                         $order = $count;
 8364:                     }
 8365:                     $ordered{$order} = $role;
 8366:                     if ($desc ne '') {
 8367:                         $description{$role} = $desc;
 8368:                     } else {
 8369:                         $description{$role}= $role;
 8370:                     }
 8371:                     $count++;
 8372:                 }
 8373:                 my @roles_by_num = ();
 8374:                 foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 8375:                     push(@roles_by_num,$ordered{$item});
 8376:                 }
 8377:                 %domusage = &domain_adhoc_access(\%changed,\%domcurrent,\@accesstypes,$usertypes,$othertitle);
 8378:                 $r->print(&mt('Helpdesk access settings have been changed as follows').'<br />');
 8379:                 $r->print('<ul>');
 8380:                 foreach my $role (@roles_by_num) {
 8381:                     next unless (ref($changed{$role}) eq 'HASH');
 8382:                     $r->print('<li>'.&mt('Ad hoc role').': <b>'.$description{$role}.'</b>'.
 8383:                               '<ul>');
 8384:                     if ($changed{$role}{'access'} || $changed{$role}{'status'} || $changed{$role}{'inc'} || $changed{$role}{'exc'}) {
 8385:                         $r->print('<li>');
 8386:                         if ($env{'form.'.$role.'_incrs'}) {
 8387:                             if ($newsettings{$role}{'access'} eq 'all') {
 8388:                                 $r->print(&mt('All helpdesk staff can access '.lc($crstype).' with this role.'));
 8389:                             } elsif ($newsettings{$role}{'access'} eq 'dh') {
 8390:                                 $r->print(&mt('Helpdesk staff can use this role if they have an active [_1] role',
 8391:                                               &Apache::lonnet::plaintext('dh')));
 8392:                             } elsif ($newsettings{$role}{'access'} eq 'da') {
 8393:                                 $r->print(&mt('Helpdesk staff can use this role if they have an active [_1] role',
 8394:                                               &Apache::lonnet::plaintext('da')));
 8395:                             } elsif ($newsettings{$role}{'access'} eq 'none') {
 8396:                                 $r->print(&mt('No helpdesk staff can access '.lc($crstype).' with this role.'));
 8397:                             } elsif ($newsettings{$role}{'access'} eq 'status') {
 8398:                                 if ($newsettings{$role}{'status'}) {
 8399:                                     my ($access,$rest) = split(/=/,$storehash{'internal.adhoc.'.$role});
 8400:                                     if (split(/,/,$rest) > 1) {
 8401:                                         $r->print(&mt('Helpdesk staff can use this role if their institutional type is one of: [_1].',
 8402:                                                       $newsettings{$role}{'status'}));
 8403:                                     } else {
 8404:                                         $r->print(&mt('Helpdesk staff can use this role if their institutional type is: [_1].',
 8405:                                                       $newsettings{$role}{'status'}));
 8406:                                     }
 8407:                                 } else {
 8408:                                     $r->print(&mt('No helpdesk staff can access '.lc($crstype).' with this role.'));
 8409:                                 }
 8410:                             } elsif ($newsettings{$role}{'access'} eq 'exc') {
 8411:                                 if ($newsettings{$role}{'exc'}) {
 8412:                                     $r->print(&mt('Helpdesk staff who can use this role are as follows:').' '.$newsettings{$role}{'exc'}.'.');
 8413:                                 } else {
 8414:                                     $r->print(&mt('No helpdesk staff can access '.lc($crstype).' with this role.'));
 8415:                                 }
 8416:                             } elsif ($newsettings{$role}{'access'} eq 'inc') {
 8417:                                 if ($newsettings{$role}{'inc'}) {
 8418:                                     $r->print(&mt('All helpdesk staff may use this role except the following:').' '.$newsettings{$role}{'inc'}.'.');
 8419:                                 } else {
 8420:                                     $r->print(&mt('All helpdesk staff may use this role.'));
 8421:                                 }
 8422:                             }
 8423:                         } else {
 8424:                             $r->print(&mt('Default access set in the domain now applies.').'<br />'.
 8425:                                       '<span class="LC_cusr_emph">'.$domusage{$role}.'</span>');
 8426:                         }
 8427:                         $r->print('</li>');
 8428:                     }
 8429:                     unless ($newsettings{$role}{'access'} eq 'none') {
 8430:                         if ($changed{$role}{'off'}) {
 8431:                             if ($newsettings{$role}{'off'}) {
 8432:                                 $r->print('<li>'.&mt('Privileges which are available by default for this ad hoc role, but are disabled for this specific '.lc($crstype).':').
 8433:                                           '<ul><li>'.$newsettings{$role}{'off'}.'</li></ul></li>');
 8434:                             } else {
 8435:                                 $r->print('<li>'.&mt('All privileges available by default for this ad hoc role are enabled.').'</li>');
 8436:                             }
 8437:                         }
 8438:                         if ($changed{$role}{'on'}) {
 8439:                             if ($newsettings{$role}{'on'}) {
 8440:                                 $r->print('<li>'.&mt('Privileges which are not available by default for this ad hoc role, but are enabled for this specific '.lc($crstype).':').
 8441:                                           '<ul><li>'.$newsettings{$role}{'on'}.'</li></ul></li>');
 8442:                             } else {
 8443:                                 $r->print('<li>'.&mt('None of the privileges unavailable by default for this ad hoc role are enabled.').'</li>');
 8444:                             }
 8445:                         }
 8446:                     }
 8447:                     $r->print('</ul></li>');
 8448:                 }
 8449:                 $r->print('</ul>');
 8450:             }
 8451:         } else {
 8452:             $r->print(&mt('No changes made to helpdesk access settings.'));
 8453:         }
 8454:     }
 8455:     return;
 8456: }
 8457: 
 8458: #-------------------------------------------------- functions for &phase_two
 8459: sub user_search_result {
 8460:     my ($context,$srch) = @_;
 8461:     my %allhomes;
 8462:     my %inst_matches;
 8463:     my %srch_results;
 8464:     my ($response,$currstate,$forcenewuser,$dirsrchres);
 8465:     $srch->{'srchterm'} =~ s/\s+/ /g;
 8466:     if ($srch->{'srchby'} !~ /^(uname|lastname|lastfirst)$/) {
 8467:         $response = &mt('Invalid search.');
 8468:     }
 8469:     if ($srch->{'srchin'} !~ /^(crs|dom|alc|instd)$/) {
 8470:         $response = &mt('Invalid search.');
 8471:     }
 8472:     if ($srch->{'srchtype'} !~ /^(exact|contains|begins)$/) {
 8473:         $response = &mt('Invalid search.');
 8474:     }
 8475:     if ($srch->{'srchterm'} eq '') {
 8476:         $response = &mt('You must enter a search term.');
 8477:     }
 8478:     if ($srch->{'srchterm'} =~ /^\s+$/) {
 8479:         $response = &mt('Your search term must contain more than just spaces.');
 8480:     }
 8481:     if (($srch->{'srchin'} eq 'dom') || ($srch->{'srchin'} eq 'instd')) {
 8482:         if (($srch->{'srchdomain'} eq '') || 
 8483: 	    ! (&Apache::lonnet::domain($srch->{'srchdomain'}))) {
 8484:             $response = &mt('You must specify a valid domain when searching in a domain or institutional directory.')
 8485:         }
 8486:     }
 8487:     if (($srch->{'srchin'} eq 'dom') || ($srch->{'srchin'} eq 'crs') ||
 8488:         ($srch->{'srchin'} eq 'alc')) {
 8489:         if ($srch->{'srchby'} eq 'uname') {
 8490:             my $unamecheck = $srch->{'srchterm'};
 8491:             if ($srch->{'srchtype'} eq 'contains') {
 8492:                 if ($unamecheck !~ /^\w/) {
 8493:                     $unamecheck = 'a'.$unamecheck; 
 8494:                 }
 8495:             }
 8496:             if ($unamecheck !~ /^$match_username$/) {
 8497:                 $response = &mt('You must specify a valid username. Only the following are allowed: letters numbers - . @');
 8498:             }
 8499:         }
 8500:     }
 8501:     if ($response ne '') {
 8502:         $response = '<span class="LC_warning">'.$response.'</span><br />';
 8503:     }
 8504:     if ($srch->{'srchin'} eq 'instd') {
 8505:         my $instd_chk = &instdirectorysrch_check($srch);
 8506:         if ($instd_chk ne 'ok') {
 8507:             my $domd_chk = &domdirectorysrch_check($srch);
 8508:             $response .= '<span class="LC_warning">'.$instd_chk.'</span><br />';
 8509:             if ($domd_chk eq 'ok') {
 8510:                 $response .= &mt('You may want to search in the LON-CAPA domain instead of the institutional directory.');
 8511:             }
 8512:             $response .= '<br />';
 8513:         }
 8514:     } else {
 8515:         unless (($context eq 'requestcrs') && ($srch->{'srchtype'} eq 'exact')) {
 8516:             my $domd_chk = &domdirectorysrch_check($srch);
 8517:             if (($domd_chk ne 'ok') && ($env{'form.action'} ne 'accesslogs')) {
 8518:                 my $instd_chk = &instdirectorysrch_check($srch);
 8519:                 $response .= '<span class="LC_warning">'.$domd_chk.'</span><br />';
 8520:                 if ($instd_chk eq 'ok') {
 8521:                     $response .= &mt('You may want to search in the institutional directory instead of the LON-CAPA domain.');
 8522:                 }
 8523:                 $response .= '<br />';
 8524:             }
 8525:         }
 8526:     }
 8527:     if ($response ne '') {
 8528:         return ($currstate,$response);
 8529:     }
 8530:     if ($srch->{'srchby'} eq 'uname') {
 8531:         if (($srch->{'srchin'} eq 'dom') || ($srch->{'srchin'} eq 'crs')) {
 8532:             if ($env{'form.forcenew'}) {
 8533:                 if ($srch->{'srchdomain'} ne $env{'request.role.domain'}) {
 8534:                     my $uhome=&Apache::lonnet::homeserver($srch->{'srchterm'},$srch->{'srchdomain'});
 8535:                     if ($uhome eq 'no_host') {
 8536:                         my $domdesc = &Apache::lonnet::domain($env{'request.role.domain'},'description');
 8537:                         my $showdom = &display_domain_info($env{'request.role.domain'});
 8538:                         $response = &mt('New users can only be created in the domain to which your current role belongs - [_1].',$showdom);
 8539:                     } else {
 8540:                         $currstate = 'modify';
 8541:                     }
 8542:                 } else {
 8543:                     $currstate = 'modify';
 8544:                 }
 8545:             } else {
 8546:                 if ($srch->{'srchin'} eq 'dom') {
 8547:                     if ($srch->{'srchtype'} eq 'exact') {
 8548:                         my $uhome=&Apache::lonnet::homeserver($srch->{'srchterm'},$srch->{'srchdomain'});
 8549:                         if ($uhome eq 'no_host') {
 8550:                             ($currstate,$response,$forcenewuser) =
 8551:                                 &build_search_response($context,$srch,%srch_results);
 8552:                         } else {
 8553:                             $currstate = 'modify';
 8554:                             if ($env{'form.action'} eq 'accesslogs') {
 8555:                                 $currstate = 'activity';
 8556:                             }
 8557:                             my $uname = $srch->{'srchterm'};
 8558:                             my $udom = $srch->{'srchdomain'};
 8559:                             $srch_results{$uname.':'.$udom} =
 8560:                                 { &Apache::lonnet::get('environment',
 8561:                                                        ['firstname',
 8562:                                                         'lastname',
 8563:                                                         'permanentemail'],
 8564:                                                          $udom,$uname)
 8565:                                 };
 8566:                         }
 8567:                     } else {
 8568:                         %srch_results = &Apache::lonnet::usersearch($srch);
 8569:                         ($currstate,$response,$forcenewuser) =
 8570:                             &build_search_response($context,$srch,%srch_results);
 8571:                     }
 8572:                 } else {
 8573:                     my $courseusers = &get_courseusers();
 8574:                     if ($srch->{'srchtype'} eq 'exact') {
 8575:                         if (exists($courseusers->{$srch->{'srchterm'}.':'.$srch->{'srchdomain'}})) {
 8576:                             $currstate = 'modify';
 8577:                         } else {
 8578:                             ($currstate,$response,$forcenewuser) =
 8579:                                 &build_search_response($context,$srch,%srch_results);
 8580:                         }
 8581:                     } else {
 8582:                         foreach my $user (keys(%$courseusers)) {
 8583:                             my ($cuname,$cudomain) = split(/:/,$user);
 8584:                             if ($cudomain eq $srch->{'srchdomain'}) {
 8585:                                 my $matched = 0;
 8586:                                 if ($srch->{'srchtype'} eq 'begins') {
 8587:                                     if ($cuname =~ /^\Q$srch->{'srchterm'}\E/i) {
 8588:                                         $matched = 1;
 8589:                                     }
 8590:                                 } else {
 8591:                                     if ($cuname =~ /\Q$srch->{'srchterm'}\E/i) {
 8592:                                         $matched = 1;
 8593:                                     }
 8594:                                 }
 8595:                                 if ($matched) {
 8596:                                     $srch_results{$user} = 
 8597: 					{&Apache::lonnet::get('environment',
 8598: 							     ['firstname',
 8599: 							      'lastname',
 8600: 							      'permanentemail'],
 8601: 							      $cudomain,$cuname)};
 8602:                                 }
 8603:                             }
 8604:                         }
 8605:                         ($currstate,$response,$forcenewuser) =
 8606:                             &build_search_response($context,$srch,%srch_results);
 8607:                     }
 8608:                 }
 8609:             }
 8610:         } elsif ($srch->{'srchin'} eq 'alc') {
 8611:             $currstate = 'query';
 8612:         } elsif ($srch->{'srchin'} eq 'instd') {
 8613:             ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query($srch);
 8614:             if ($dirsrchres eq 'ok') {
 8615:                 ($currstate,$response,$forcenewuser) = 
 8616:                     &build_search_response($context,$srch,%srch_results);
 8617:             } else {
 8618:                 my $showdom = &display_domain_info($srch->{'srchdomain'});
 8619:                 $response = '<span class="LC_warning">'.
 8620:                     &mt('Institutional directory search is not available in domain: [_1]',$showdom).
 8621:                     '</span><br />'.
 8622:                     &mt('You may want to search in the LON-CAPA domain instead of the institutional directory.').
 8623:                     '<br />'; 
 8624:             }
 8625:         }
 8626:     } else {
 8627:         if ($srch->{'srchin'} eq 'dom') {
 8628:             %srch_results = &Apache::lonnet::usersearch($srch);
 8629:             ($currstate,$response,$forcenewuser) = 
 8630:                 &build_search_response($context,$srch,%srch_results); 
 8631:         } elsif ($srch->{'srchin'} eq 'crs') {
 8632:             my $courseusers = &get_courseusers(); 
 8633:             foreach my $user (keys(%$courseusers)) {
 8634:                 my ($uname,$udom) = split(/:/,$user);
 8635:                 my %names = &Apache::loncommon::getnames($uname,$udom);
 8636:                 my %emails = &Apache::loncommon::getemails($uname,$udom);
 8637:                 if ($srch->{'srchby'} eq 'lastname') {
 8638:                     if ((($srch->{'srchtype'} eq 'exact') && 
 8639:                          ($names{'lastname'} eq $srch->{'srchterm'})) || 
 8640:                         (($srch->{'srchtype'} eq 'begins') &&
 8641:                          ($names{'lastname'} =~ /^\Q$srch->{'srchterm'}\E/i)) ||
 8642:                         (($srch->{'srchtype'} eq 'contains') &&
 8643:                          ($names{'lastname'} =~ /\Q$srch->{'srchterm'}\E/i))) {
 8644:                         $srch_results{$user} = {firstname => $names{'firstname'},
 8645:                                             lastname => $names{'lastname'},
 8646:                                             permanentemail => $emails{'permanentemail'},
 8647:                                            };
 8648:                     }
 8649:                 } elsif ($srch->{'srchby'} eq 'lastfirst') {
 8650:                     my ($srchlast,$srchfirst) = split(/,/,$srch->{'srchterm'});
 8651:                     $srchlast =~ s/\s+$//;
 8652:                     $srchfirst =~ s/^\s+//;
 8653:                     if ($srch->{'srchtype'} eq 'exact') {
 8654:                         if (($names{'lastname'} eq $srchlast) &&
 8655:                             ($names{'firstname'} eq $srchfirst)) {
 8656:                             $srch_results{$user} = {firstname => $names{'firstname'},
 8657:                                                 lastname => $names{'lastname'},
 8658:                                                 permanentemail => $emails{'permanentemail'},
 8659: 
 8660:                                            };
 8661:                         }
 8662:                     } elsif ($srch->{'srchtype'} eq 'begins') {
 8663:                         if (($names{'lastname'} =~ /^\Q$srchlast\E/i) &&
 8664:                             ($names{'firstname'} =~ /^\Q$srchfirst\E/i)) {
 8665:                             $srch_results{$user} = {firstname => $names{'firstname'},
 8666:                                                 lastname => $names{'lastname'},
 8667:                                                 permanentemail => $emails{'permanentemail'},
 8668:                                                };
 8669:                         }
 8670:                     } else {
 8671:                         if (($names{'lastname'} =~ /\Q$srchlast\E/i) && 
 8672:                             ($names{'firstname'} =~ /\Q$srchfirst\E/i)) {
 8673:                             $srch_results{$user} = {firstname => $names{'firstname'},
 8674:                                                 lastname => $names{'lastname'},
 8675:                                                 permanentemail => $emails{'permanentemail'},
 8676:                                                };
 8677:                         }
 8678:                     }
 8679:                 }
 8680:             }
 8681:             ($currstate,$response,$forcenewuser) = 
 8682:                 &build_search_response($context,$srch,%srch_results); 
 8683:         } elsif ($srch->{'srchin'} eq 'alc') {
 8684:             $currstate = 'query';
 8685:         } elsif ($srch->{'srchin'} eq 'instd') {
 8686:             ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query($srch); 
 8687:             if ($dirsrchres eq 'ok') {
 8688:                 ($currstate,$response,$forcenewuser) = 
 8689:                     &build_search_response($context,$srch,%srch_results);
 8690:             } else {
 8691:                 my $showdom = &display_domain_info($srch->{'srchdomain'});
 8692:                 $response = '<span class="LC_warning">'.
 8693:                     &mt('Institutional directory search is not available in domain: [_1]',$showdom).
 8694:                     '</span><br />'.
 8695:                     &mt('You may want to search in the LON-CAPA domain instead of the institutional directory.').
 8696:                     '<br />';
 8697:             }
 8698:         }
 8699:     }
 8700:     return ($currstate,$response,$forcenewuser,\%srch_results);
 8701: }
 8702: 
 8703: sub domdirectorysrch_check {
 8704:     my ($srch) = @_;
 8705:     my $response;
 8706:     my %dom_inst_srch = &Apache::lonnet::get_dom('configuration',
 8707:                                              ['directorysrch'],$srch->{'srchdomain'});
 8708:     my $showdom = &display_domain_info($srch->{'srchdomain'});
 8709:     if (ref($dom_inst_srch{'directorysrch'}) eq 'HASH') {
 8710:         if ($dom_inst_srch{'directorysrch'}{'lcavailable'} eq '0') {
 8711:             return &mt('LON-CAPA directory search is not available in domain: [_1]',$showdom);
 8712:         }
 8713:         if ($dom_inst_srch{'directorysrch'}{'lclocalonly'}) {
 8714:             if ($env{'request.role.domain'} ne $srch->{'srchdomain'}) {
 8715:                 return &mt('LON-CAPA directory search in domain: [_1] is only allowed for users with a current role in the domain.',$showdom);
 8716:             }
 8717:         }
 8718:     }
 8719:     return 'ok';
 8720: }
 8721: 
 8722: sub instdirectorysrch_check {
 8723:     my ($srch) = @_;
 8724:     my $can_search = 0;
 8725:     my $response;
 8726:     my %dom_inst_srch = &Apache::lonnet::get_dom('configuration',
 8727:                                              ['directorysrch'],$srch->{'srchdomain'});
 8728:     my $showdom = &display_domain_info($srch->{'srchdomain'});
 8729:     if (ref($dom_inst_srch{'directorysrch'}) eq 'HASH') {
 8730:         if (!$dom_inst_srch{'directorysrch'}{'available'}) {
 8731:             return &mt('Institutional directory search is not available in domain: [_1]',$showdom); 
 8732:         }
 8733:         if ($dom_inst_srch{'directorysrch'}{'localonly'}) {
 8734:             if ($env{'request.role.domain'} ne $srch->{'srchdomain'}) {
 8735:                 return &mt('Institutional directory search in domain: [_1] is only allowed for users with a current role in the domain.',$showdom); 
 8736:             }
 8737:             my @usertypes = split(/:/,$env{'environment.inststatus'});
 8738:             if (!@usertypes) {
 8739:                 push(@usertypes,'default');
 8740:             }
 8741:             if (ref($dom_inst_srch{'directorysrch'}{'cansearch'}) eq 'ARRAY') {
 8742:                 foreach my $type (@usertypes) {
 8743:                     if (grep(/^\Q$type\E$/,@{$dom_inst_srch{'directorysrch'}{'cansearch'}})) {
 8744:                         $can_search = 1;
 8745:                         last;
 8746:                     }
 8747:                 }
 8748:             }
 8749:             if (!$can_search) {
 8750:                 my ($insttypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($srch->{'srchdomain'});
 8751:                 my @longtypes; 
 8752:                 foreach my $item (@usertypes) {
 8753:                     if (defined($insttypes->{$item})) { 
 8754:                         push (@longtypes,$insttypes->{$item});
 8755:                     } elsif ($item eq 'default') {
 8756:                         push (@longtypes,&mt('other')); 
 8757:                     }
 8758:                 }
 8759:                 my $insttype_str = join(', ',@longtypes); 
 8760:                 return &mt('Institutional directory search in domain: [_1] is not available to your user type: ',$showdom).$insttype_str;
 8761:             }
 8762:         } else {
 8763:             $can_search = 1;
 8764:         }
 8765:     } else {
 8766:         return &mt('Institutional directory search has not been configured for domain: [_1]',$showdom);
 8767:     }
 8768:     my %longtext = &Apache::lonlocal::texthash (
 8769:                        uname     => 'username',
 8770:                        lastfirst => 'last name, first name',
 8771:                        lastname  => 'last name',
 8772:                        contains  => 'contains',
 8773:                        exact     => 'as exact match to',
 8774:                        begins    => 'begins with',
 8775:                    );
 8776:     if ($can_search) {
 8777:         if (ref($dom_inst_srch{'directorysrch'}{'searchby'}) eq 'ARRAY') {
 8778:             if (!grep(/^\Q$srch->{'srchby'}\E$/,@{$dom_inst_srch{'directorysrch'}{'searchby'}})) {
 8779:                 return &mt('Institutional directory search in domain: [_1] is not available for searching by "[_2]"',$showdom,$longtext{$srch->{'srchby'}});
 8780:             }
 8781:         } else {
 8782:             return &mt('Institutional directory search in domain: [_1] is not available.', $showdom);
 8783:         }
 8784:     }
 8785:     if ($can_search) {
 8786:         if (ref($dom_inst_srch{'directorysrch'}{'searchtypes'}) eq 'ARRAY') {
 8787:             if (grep(/^\Q$srch->{'srchtype'}\E/,@{$dom_inst_srch{'directorysrch'}{'searchtypes'}})) {
 8788:                 return 'ok';
 8789:             } else {
 8790:                 return &mt('Institutional directory search in domain [_1] is not available for the requested search type: "[_2]"',$showdom,$longtext{$srch->{'srchtype'}});
 8791:             }
 8792:         } else {
 8793:             if ((($dom_inst_srch{'directorysrch'}{'searchtypes'} eq 'specify') &&
 8794:                  ($srch->{'srchtype'} eq 'exact' || $srch->{'srchtype'} eq 'contains')) ||
 8795:                 ($dom_inst_srch{'directorysrch'}{'searchtypes'} eq $srch->{'srchtype'})) {
 8796:                 return 'ok';
 8797:             } else {
 8798:                 return &mt('Institutional directory search in domain [_1] is not available for the requested search type: "[_2]"',$showdom,$longtext{$srch->{'srchtype'}});
 8799:             }
 8800:         }
 8801:     }
 8802: }
 8803: 
 8804: sub get_courseusers {
 8805:     my %advhash;
 8806:     my $classlist = &Apache::loncoursedata::get_classlist();
 8807:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles();
 8808:     foreach my $role (sort(keys(%coursepersonnel))) {
 8809:         foreach my $user (split(/\,/,$coursepersonnel{$role})) {
 8810: 	    if (!exists($classlist->{$user})) {
 8811: 		$classlist->{$user} = [];
 8812: 	    }
 8813:         }
 8814:     }
 8815:     return $classlist;
 8816: }
 8817: 
 8818: sub build_search_response {
 8819:     my ($context,$srch,%srch_results) = @_;
 8820:     my ($currstate,$response,$forcenewuser);
 8821:     my %names = (
 8822:           'uname'     => 'username',
 8823:           'lastname'  => 'last name',
 8824:           'lastfirst' => 'last name, first name',
 8825:           'crs'       => 'this course',
 8826:           'dom'       => 'LON-CAPA domain',
 8827:           'instd'     => 'the institutional directory for domain',
 8828:     );
 8829: 
 8830:     my %single = (
 8831:                    begins   => 'A match',
 8832:                    contains => 'A match',
 8833:                    exact    => 'An exact match',
 8834:                  );
 8835:     my %nomatch = (
 8836:                    begins   => 'No match',
 8837:                    contains => 'No match',
 8838:                    exact    => 'No exact match',
 8839:                   );
 8840:     if (keys(%srch_results) > 1) {
 8841:         $currstate = 'select';
 8842:     } else {
 8843:         if (keys(%srch_results) == 1) {
 8844:             if ($env{'form.action'} eq 'accesslogs') {
 8845:                 $currstate = 'activity';
 8846:             } else {
 8847:                 $currstate = 'modify';
 8848:             }
 8849:             $response = &mt("$single{$srch->{'srchtype'}} was found for the $names{$srch->{'srchby'}} ([_1]) in $names{$srch->{'srchin'}}.",$srch->{'srchterm'});
 8850:             if ($srch->{'srchin'} eq 'dom' || $srch->{'srchin'} eq 'instd') {
 8851:                 $response .= ': '.&display_domain_info($srch->{'srchdomain'});
 8852:             }
 8853:         } else { # Search has nothing found. Prepare message to user.
 8854:             $response = '<span class="LC_warning">';
 8855:             if ($srch->{'srchin'} eq 'dom' || $srch->{'srchin'} eq 'instd') {
 8856:                 $response .= &mt("$nomatch{$srch->{'srchtype'}} found for the $names{$srch->{'srchby'}} [_1] in $names{$srch->{'srchin'}}: [_2]",
 8857:                                  '<b>'.$srch->{'srchterm'}.'</b>',
 8858:                                  &display_domain_info($srch->{'srchdomain'}));
 8859:             } else {
 8860:                 $response .= &mt("$nomatch{$srch->{'srchtype'}} found for the $names{$srch->{'srchby'}} [_1] in $names{$srch->{'srchin'}}.",
 8861:                                  '<b>'.$srch->{'srchterm'}.'</b>');
 8862:             }
 8863:             $response .= '</span>';
 8864: 
 8865:             if ($srch->{'srchin'} ne 'alc') {
 8866:                 $forcenewuser = 1;
 8867:                 my $cansrchinst = 0; 
 8868:                 if (($srch->{'srchdomain'}) && ($env{'form.action'} ne 'accesslogs')) {
 8869:                     my %domconfig = &Apache::lonnet::get_dom('configuration',['directorysrch'],$srch->{'srchdomain'});
 8870:                     if (ref($domconfig{'directorysrch'}) eq 'HASH') {
 8871:                         if ($domconfig{'directorysrch'}{'available'}) {
 8872:                             $cansrchinst = 1;
 8873:                         } 
 8874:                     }
 8875:                 }
 8876:                 if ((($srch->{'srchby'} eq 'lastfirst') || 
 8877:                      ($srch->{'srchby'} eq 'lastname')) &&
 8878:                     ($srch->{'srchin'} eq 'dom')) {
 8879:                     if ($cansrchinst) {
 8880:                         $response .= '<br />'.&mt('You may want to broaden your search to a search of the institutional directory for the domain.');
 8881:                     }
 8882:                 }
 8883:                 if ($srch->{'srchin'} eq 'crs') {
 8884:                     $response .= '<br />'.&mt('You may want to broaden your search to the selected LON-CAPA domain.');
 8885:                 }
 8886:             }
 8887:             my $createdom = $env{'request.role.domain'};
 8888:             if ($context eq 'requestcrs') {
 8889:                 if ($env{'form.coursedom'} ne '') {
 8890:                     $createdom = $env{'form.coursedom'};
 8891:                 }
 8892:             }
 8893:             unless (($env{'form.action'} eq 'accesslogs') || (($srch->{'srchby'} eq 'uname') && ($srch->{'srchin'} eq 'dom') &&
 8894:                     ($srch->{'srchtype'} eq 'exact') && ($srch->{'srchdomain'} eq $createdom))) {
 8895:                 my $cancreate =
 8896:                     &Apache::lonuserutils::can_create_user($createdom,$context);
 8897:                 my $targetdom = '<span class="LC_cusr_emph">'.$createdom.'</span>';
 8898:                 if ($cancreate) {
 8899:                     my $showdom = &display_domain_info($createdom); 
 8900:                     $response .= '<br /><br />'
 8901:                                 .'<b>'.&mt('To add a new user:').'</b>'
 8902:                                 .'<br />';
 8903:                     if ($context eq 'requestcrs') {
 8904:                         $response .= &mt("(You can only define new users in the new course's domain - [_1])",$targetdom);
 8905:                     } else {
 8906:                         $response .= &mt("(You can only create new users in your current role's domain - [_1])",$targetdom);
 8907:                     }
 8908:                     $response .='<ul><li>'
 8909:                                 .&mt("Set 'Domain/institution to search' to: [_1]",'<span class="LC_cusr_emph">'.$showdom.'</span>')
 8910:                                 .'</li><li>'
 8911:                                 .&mt("Set 'Search criteria' to: [_1]username is ..... in selected LON-CAPA domain[_2]",'<span class="LC_cusr_emph">','</span>')
 8912:                                 .'</li><li>'
 8913:                                 .&mt('Provide the proposed username')
 8914:                                 .'</li><li>'
 8915:                                 .&mt("Click 'Search'")
 8916:                                 .'</li></ul><br />';
 8917:                 } else {
 8918:                     unless (($context eq 'domain') && ($env{'form.action'} eq 'singleuser')) {
 8919:                         my $helplink = ' href="javascript:helpMenu('."'display'".')"';
 8920:                         $response .= '<br /><br />';
 8921:                         if ($context eq 'requestcrs') {
 8922:                             $response .= &mt("You are not authorized to define new users in the new course's domain - [_1].",$targetdom);
 8923:                         } else {
 8924:                             $response .= &mt("You are not authorized to create new users in your current role's domain - [_1].",$targetdom);
 8925:                         }
 8926:                         $response .= '<br />'
 8927:                                      .&mt('Please contact the [_1]helpdesk[_2] if you need to create a new user.'
 8928:                                         ,' <a'.$helplink.'>'
 8929:                                         ,'</a>')
 8930:                                      .'<br />';
 8931:                     }
 8932:                 }
 8933:             }
 8934:         }
 8935:     }
 8936:     return ($currstate,$response,$forcenewuser);
 8937: }
 8938: 
 8939: sub display_domain_info {
 8940:     my ($dom) = @_;
 8941:     my $output = $dom;
 8942:     if ($dom ne '') { 
 8943:         my $domdesc = &Apache::lonnet::domain($dom,'description');
 8944:         if ($domdesc ne '') {
 8945:             $output .= ' <span class="LC_cusr_emph">('.$domdesc.')</span>';
 8946:         }
 8947:     }
 8948:     return $output;
 8949: }
 8950: 
 8951: sub crumb_utilities {
 8952:     my %elements = (
 8953:        crtuser => {
 8954:            srchterm => 'text',
 8955:            srchin => 'selectbox',
 8956:            srchby => 'selectbox',
 8957:            srchtype => 'selectbox',
 8958:            srchdomain => 'selectbox',
 8959:        },
 8960:        crtusername => {
 8961:            srchterm => 'text',
 8962:            srchdomain => 'selectbox',
 8963:        },
 8964:        docustom => {
 8965:            rolename => 'selectbox',
 8966:            newrolename => 'textbox',
 8967:        },
 8968:        studentform => {
 8969:            srchterm => 'text',
 8970:            srchin => 'selectbox',
 8971:            srchby => 'selectbox',
 8972:            srchtype => 'selectbox',
 8973:            srchdomain => 'selectbox',
 8974:        },
 8975:     );
 8976: 
 8977:     my $jsback .= qq|
 8978: function backPage(formname,prevphase,prevstate) {
 8979:     if (typeof prevphase == 'undefined') {
 8980:         formname.phase.value = '';
 8981:     }
 8982:     else {  
 8983:         formname.phase.value = prevphase;
 8984:     }
 8985:     if (typeof prevstate == 'undefined') {
 8986:         formname.currstate.value = '';
 8987:     }
 8988:     else {
 8989:         formname.currstate.value = prevstate;
 8990:     }
 8991:     formname.submit();
 8992: }
 8993: |;
 8994:     return ($jsback,\%elements);
 8995: }
 8996: 
 8997: sub course_level_table {
 8998:     my ($inccourses,$showcredits,$defaultcredits) = @_;
 8999:     return unless (ref($inccourses) eq 'HASH');
 9000:     my $table = '';
 9001: # Custom Roles?
 9002: 
 9003:     my %customroles=&Apache::lonuserutils::my_custom_roles();
 9004:     my %lt=&Apache::lonlocal::texthash(
 9005:             'exs'  => "Existing sections",
 9006:             'new'  => "Define new section",
 9007:             'ssd'  => "Set Start Date",
 9008:             'sed'  => "Set End Date",
 9009:             'crl'  => "Course Level",
 9010:             'act'  => "Activate",
 9011:             'rol'  => "Role",
 9012:             'ext'  => "Extent",
 9013:             'grs'  => "Section",
 9014:             'crd'  => "Credits",
 9015:             'sta'  => "Start",
 9016:             'end'  => "End"
 9017:     );
 9018: 
 9019:     foreach my $protectedcourse (sort(keys(%{$inccourses}))) {
 9020: 	my $thiscourse=$protectedcourse;
 9021: 	$thiscourse=~s:_:/:g;
 9022: 	my %coursedata=&Apache::lonnet::coursedescription($thiscourse);
 9023:         my $isowner = &Apache::lonuserutils::is_courseowner($protectedcourse,$coursedata{'internal.courseowner'});
 9024: 	my $area=$coursedata{'description'};
 9025:         my $crstype=$coursedata{'type'};
 9026: 	if (!defined($area)) { $area=&mt('Unavailable course').': '.$protectedcourse; }
 9027: 	my ($domain,$cnum)=split(/\//,$thiscourse);
 9028:         my %sections_count;
 9029:         if (defined($env{'request.course.id'})) {
 9030:             if ($env{'request.course.id'} eq $domain.'_'.$cnum) {
 9031:                 %sections_count = 
 9032: 		    &Apache::loncommon::get_sections($domain,$cnum);
 9033:             }
 9034:         }
 9035:         my @roles = &Apache::lonuserutils::roles_by_context('course','',$crstype);
 9036: 	foreach my $role (@roles) {
 9037:             my $plrole=&Apache::lonnet::plaintext($role,$crstype);
 9038: 	    if ((&Apache::lonnet::allowed('c'.$role,$thiscourse)) ||
 9039:                 ((($role eq 'cc') || ($role eq 'co')) && ($isowner))) {
 9040:                 $table .= &course_level_row($protectedcourse,$role,$area,$domain,
 9041:                                             $plrole,\%sections_count,\%lt,
 9042:                                             $showcredits,$defaultcredits,$crstype);
 9043:             } elsif ($env{'request.course.sec'} ne '') {
 9044:                 if (&Apache::lonnet::allowed('c'.$role,$thiscourse.'/'.
 9045:                                              $env{'request.course.sec'})) {
 9046:                     $table .= &course_level_row($protectedcourse,$role,$area,$domain,
 9047:                                                 $plrole,\%sections_count,\%lt,
 9048:                                                 $showcredits,$defaultcredits,$crstype);
 9049:                 }
 9050:             }
 9051:         }
 9052:         if (&Apache::lonnet::allowed('ccr',$thiscourse)) {
 9053:             foreach my $cust (sort(keys(%customroles))) {
 9054:                 next if ($crstype eq 'Community' && $customroles{$cust} =~ /bre\&S/);
 9055:                 my $role = 'cr_cr_'.$env{'user.domain'}.'_'.$env{'user.name'}.'_'.$cust;
 9056:                 $table .= &course_level_row($protectedcourse,$role,$area,$domain,
 9057:                                             $cust,\%sections_count,\%lt,
 9058:                                             $showcredits,$defaultcredits,$crstype);
 9059:             }
 9060: 	}
 9061:     }
 9062:     return '' if ($table eq ''); # return nothing if there is nothing 
 9063:                                  # in the table
 9064:     my $result;
 9065:     if (!$env{'request.course.id'}) {
 9066:         $result = '<h4>'.$lt{'crl'}.'</h4>'."\n";
 9067:     }
 9068:     $result .= 
 9069: &Apache::loncommon::start_data_table().
 9070: &Apache::loncommon::start_data_table_header_row().
 9071: '<th>'.$lt{'act'}.'</th><th>'.$lt{'rol'}.'</th>'."\n".
 9072: '<th>'.$lt{'ext'}.'</th><th>'."\n";
 9073:     if ($showcredits) {
 9074:         $result .= $lt{'crd'}.'</th>';
 9075:     }
 9076:     $result .=
 9077: '<th>'.$lt{'grs'}.'</th><th>'.$lt{'sta'}.'</th>'."\n".
 9078: '<th>'.$lt{'end'}.'</th>'.
 9079: &Apache::loncommon::end_data_table_header_row().
 9080: $table.
 9081: &Apache::loncommon::end_data_table();
 9082:     return $result;
 9083: }
 9084: 
 9085: sub course_level_row {
 9086:     my ($protectedcourse,$role,$area,$domain,$plrole,$sections_count,
 9087:         $lt,$showcredits,$defaultcredits,$crstype) = @_;
 9088:     my $creditem;
 9089:     my $row = &Apache::loncommon::start_data_table_row().
 9090:               ' <td><input type="checkbox" name="act_'.
 9091:               $protectedcourse.'_'.$role.'" /></td>'."\n".
 9092:               ' <td>'.$plrole.'</td>'."\n".
 9093:               ' <td>'.$area.'<br />Domain: '.$domain.'</td>'."\n";
 9094:     if (($showcredits) && ($role eq 'st') && ($crstype eq 'Course')) {
 9095:         $row .= 
 9096:             '<td><input type="text" name="credits_'.$protectedcourse.'_'.
 9097:             $role.'" size="3" value="'.$defaultcredits.'" /></td>';
 9098:     } else {
 9099:         $row .= '<td>&nbsp;</td>';
 9100:     }
 9101:     if (($role eq 'cc') || ($role eq 'co')) {
 9102:         $row .= '<td>&nbsp;</td>';
 9103:     } elsif ($env{'request.course.sec'} ne '') {
 9104:         $row .= ' <td><input type="hidden" value="'.
 9105:                 $env{'request.course.sec'}.'" '.
 9106:                 'name="sec_'.$protectedcourse.'_'.$role.'" />'.
 9107:                 $env{'request.course.sec'}.'</td>';
 9108:     } else {
 9109:         if (ref($sections_count) eq 'HASH') {
 9110:             my $currsec = 
 9111:                 &Apache::lonuserutils::course_sections($sections_count,
 9112:                                                        $protectedcourse.'_'.$role);
 9113:             $row .= '<td><table class="LC_createuser">'."\n".
 9114:                     '<tr class="LC_section_row">'."\n".
 9115:                     ' <td valign="top">'.$lt->{'exs'}.'<br />'.
 9116:                        $currsec.'</td>'."\n".
 9117:                      ' <td>&nbsp;&nbsp;</td>'."\n".
 9118:                      ' <td valign="top">&nbsp;'.$lt->{'new'}.'<br />'.
 9119:                      '<input type="text" name="newsec_'.$protectedcourse.'_'.$role.
 9120:                      '" value="" />'.
 9121:                      '<input type="hidden" '.
 9122:                      'name="sec_'.$protectedcourse.'_'.$role.'" /></td>'."\n".
 9123:                      '</tr></table></td>'."\n";
 9124:         } else {
 9125:             $row .= '<td><input type="text" size="10" '.
 9126:                     'name="sec_'.$protectedcourse.'_'.$role.'" /></td>'."\n";
 9127:         }
 9128:     }
 9129:     $row .= <<ENDTIMEENTRY;
 9130: <td><input type="hidden" name="start_$protectedcourse\_$role" value="" />
 9131: <a href=
 9132: "javascript:pjump('date_start','Start Date $plrole',document.cu.start_$protectedcourse\_$role.value,'start_$protectedcourse\_$role','cu.pres','dateset')">$lt->{'ssd'}</a></td>
 9133: <td><input type="hidden" name="end_$protectedcourse\_$role" value="" />
 9134: <a href=
 9135: "javascript:pjump('date_end','End Date $plrole',document.cu.end_$protectedcourse\_$role.value,'end_$protectedcourse\_$role','cu.pres','dateset')">$lt->{'sed'}</a></td>
 9136: ENDTIMEENTRY
 9137:     $row .= &Apache::loncommon::end_data_table_row();
 9138:     return $row;
 9139: }
 9140: 
 9141: sub course_level_dc {
 9142:     my ($dcdom,$showcredits) = @_;
 9143:     my %customroles=&Apache::lonuserutils::my_custom_roles();
 9144:     my @roles = &Apache::lonuserutils::roles_by_context('course');
 9145:     my $hiddenitems = '<input type="hidden" name="dcdomain" value="'.$dcdom.'" />'.
 9146:                       '<input type="hidden" name="origdom" value="'.$dcdom.'" />'.
 9147:                       '<input type="hidden" name="dccourse" value="" />';
 9148:     my $courseform=&Apache::loncommon::selectcourse_link
 9149:             ('cu','dccourse','dcdomain','coursedesc',undef,undef,'Select','crstype');
 9150:     my $credit_elem;
 9151:     if ($showcredits) {
 9152:         $credit_elem = 'credits';
 9153:     }
 9154:     my $cb_jscript = &Apache::loncommon::coursebrowser_javascript($dcdom,'currsec','cu','role','Course/Community Browser',$credit_elem);
 9155:     my %lt=&Apache::lonlocal::texthash(
 9156:                     'rol'  => "Role",
 9157:                     'grs'  => "Section",
 9158:                     'exs'  => "Existing sections",
 9159:                     'new'  => "Define new section", 
 9160:                     'sta'  => "Start",
 9161:                     'end'  => "End",
 9162:                     'ssd'  => "Set Start Date",
 9163:                     'sed'  => "Set End Date",
 9164:                     'scc'  => "Course/Community",
 9165:                     'crd'  => "Credits",
 9166:                   );
 9167:     my $header = '<h4>'.&mt('Course/Community Level').'</h4>'.
 9168:                  &Apache::loncommon::start_data_table().
 9169:                  &Apache::loncommon::start_data_table_header_row().
 9170:                  '<th>'.$lt{'scc'}.'</th><th>'.$lt{'rol'}.'</th>'."\n".
 9171:                  '<th>'.$lt{'grs'}.'</th>'."\n";
 9172:     $header .=   '<th>'.$lt{'crd'}.'</th>'."\n" if ($showcredits);
 9173:     $header .=   '<th>'.$lt{'sta'}.'</th><th>'.$lt{'end'}.'</th>'."\n".
 9174:                  &Apache::loncommon::end_data_table_header_row();
 9175:     my $otheritems = &Apache::loncommon::start_data_table_row()."\n".
 9176:                      '<td><br /><span class="LC_nobreak"><input type="text" name="coursedesc" value="" onfocus="this.blur();opencrsbrowser('."'cu','dccourse','dcdomain','coursedesc','','','','crstype'".')" />'.
 9177:                      $courseform.('&nbsp;' x4).'</span></td>'."\n".
 9178:                      '<td valign="top"><br /><select name="role">'."\n";
 9179:     foreach my $role (@roles) {
 9180:         my $plrole=&Apache::lonnet::plaintext($role);
 9181:         $otheritems .= '  <option value="'.$role.'">'.$plrole.'</option>';
 9182:     }
 9183:     if ( keys(%customroles) > 0) {
 9184:         foreach my $cust (sort(keys(%customroles))) {
 9185:             my $custrole='cr_cr_'.$env{'user.domain'}.
 9186:                     '_'.$env{'user.name'}.'_'.$cust;
 9187:             $otheritems .= '  <option value="'.$custrole.'">'.$cust.'</option>';
 9188:         }
 9189:     }
 9190:     $otheritems .= '</select></td><td>'.
 9191:                      '<table border="0" cellspacing="0" cellpadding="0">'.
 9192:                      '<tr><td valign="top"><b>'.$lt{'exs'}.'</b><br /><select name="currsec">'.
 9193:                      ' <option value="">&lt;--'.&mt('Pick course first').'</option></select></td>'.
 9194:                      '<td>&nbsp;&nbsp;</td>'.
 9195:                      '<td valign="top">&nbsp;<b>'.$lt{'new'}.'</b><br />'.
 9196:                      '<input type="text" name="newsec" value="" />'.
 9197:                      '<input type="hidden" name="section" value="" />'.
 9198:                      '<input type="hidden" name="groups" value="" />'.
 9199:                      '<input type="hidden" name="crstype" value="" /></td>'.
 9200:                      '</tr></table></td>'."\n";
 9201:     if ($showcredits) {
 9202:         $otheritems .= '<td><br />'."\n".
 9203:                        '<input type="text" size="3" name="credits" value="" /></td>'."\n";
 9204:     }
 9205:     $otheritems .= <<ENDTIMEENTRY;
 9206: <td><br /><input type="hidden" name="start" value='' />
 9207: <a href=
 9208: "javascript:pjump('date_start','Start Date',document.cu.start.value,'start','cu.pres','dateset')">$lt{'ssd'}</a></td>
 9209: <td><br /><input type="hidden" name="end" value='' />
 9210: <a href=
 9211: "javascript:pjump('date_end','End Date',document.cu.end.value,'end','cu.pres','dateset')">$lt{'sed'}</a></td>
 9212: ENDTIMEENTRY
 9213:     $otheritems .= &Apache::loncommon::end_data_table_row().
 9214:                    &Apache::loncommon::end_data_table()."\n";
 9215:     return $cb_jscript.$header.$hiddenitems.$otheritems;
 9216: }
 9217: 
 9218: sub update_selfenroll_config {
 9219:     my ($r,$cid,$cdom,$cnum,$context,$crstype,$currsettings) = @_;
 9220:     return unless (ref($currsettings) eq 'HASH');
 9221:     my ($row,$lt) = &Apache::lonuserutils::get_selfenroll_titles();
 9222:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
 9223:     my (%changes,%warning);
 9224:     my $curr_types;
 9225:     my %noedit;
 9226:     unless ($context eq 'domain') {
 9227:         %noedit = &get_noedit_fields($cdom,$cnum,$crstype,$row);
 9228:     }
 9229:     if (ref($row) eq 'ARRAY') {
 9230:         foreach my $item (@{$row}) {
 9231:             next if ($noedit{$item});
 9232:             if ($item eq 'enroll_dates') {
 9233:                 my (%currenrolldate,%newenrolldate);
 9234:                 foreach my $type ('start','end') {
 9235:                     $currenrolldate{$type} = $currsettings->{'selfenroll_'.$type.'_date'};
 9236:                     $newenrolldate{$type} = &Apache::lonhtmlcommon::get_date_from_form('selfenroll_'.$type.'_date');
 9237:                     if ($newenrolldate{$type} ne $currenrolldate{$type}) {
 9238:                         $changes{'internal.selfenroll_'.$type.'_date'} = $newenrolldate{$type};
 9239:                     }
 9240:                 }
 9241:             } elsif ($item eq 'access_dates') {
 9242:                 my (%currdate,%newdate);
 9243:                 foreach my $type ('start','end') {
 9244:                     $currdate{$type} = $currsettings->{'selfenroll_'.$type.'_access'};
 9245:                     $newdate{$type} = &Apache::lonhtmlcommon::get_date_from_form('selfenroll_'.$type.'_access');
 9246:                     if ($newdate{$type} ne $currdate{$type}) {
 9247:                         $changes{'internal.selfenroll_'.$type.'_access'} = $newdate{$type};
 9248:                     }
 9249:                 }
 9250:             } elsif ($item eq 'types') {
 9251:                 $curr_types = $currsettings->{'selfenroll_'.$item};
 9252:                 if ($env{'form.selfenroll_all'}) {
 9253:                     if ($curr_types ne '*') {
 9254:                         $changes{'internal.selfenroll_types'} = '*';
 9255:                     } else {
 9256:                         next;
 9257:                     }
 9258:                 } else {
 9259:                     my %currdoms;
 9260:                     my @entries = split(/;/,$curr_types);
 9261:                     my @deletedoms = &Apache::loncommon::get_env_multiple('form.selfenroll_delete');
 9262:                     my @activations = &Apache::loncommon::get_env_multiple('form.selfenroll_activate');
 9263:                     my $newnum = 0;
 9264:                     my @latesttypes;
 9265:                     foreach my $num (@activations) {
 9266:                         my @types = &Apache::loncommon::get_env_multiple('form.selfenroll_types_'.$num);
 9267:                         if (@types > 0) {
 9268:                             @types = sort(@types);
 9269:                             my $typestr = join(',',@types);
 9270:                             my $typedom = $env{'form.selfenroll_dom_'.$num};
 9271:                             $latesttypes[$newnum] = $typedom.':'.$typestr;
 9272:                             $currdoms{$typedom} = 1;
 9273:                             $newnum ++;
 9274:                         }
 9275:                     }
 9276:                     for (my $j=0; $j<$env{'form.selfenroll_types_total'}; $j++) {
 9277:                         if ((!grep(/^$j$/,@deletedoms)) && (!grep(/^$j$/,@activations))) {
 9278:                             my @types = &Apache::loncommon::get_env_multiple('form.selfenroll_types_'.$j);
 9279:                             if (@types > 0) {
 9280:                                 @types = sort(@types);
 9281:                                 my $typestr = join(',',@types);
 9282:                                 my $typedom = $env{'form.selfenroll_dom_'.$j};
 9283:                                 $latesttypes[$newnum] = $typedom.':'.$typestr;
 9284:                                 $currdoms{$typedom} = 1;
 9285:                                 $newnum ++;
 9286:                             }
 9287:                         }
 9288:                     }
 9289:                     if ($env{'form.selfenroll_newdom'} ne '') {
 9290:                         my $typedom = $env{'form.selfenroll_newdom'};
 9291:                         if ((!defined($currdoms{$typedom})) && 
 9292:                             (&Apache::lonnet::domain($typedom) ne '')) {
 9293:                             my $typestr;
 9294:                             my ($othertitle,$usertypes,$types) = 
 9295:                                 &Apache::loncommon::sorted_inst_types($typedom);
 9296:                             my $othervalue = 'any';
 9297:                             if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 9298:                                 if (@{$types} > 0) {
 9299:                                     my @esc_types = map { &escape($_); } @{$types};
 9300:                                     $othervalue = 'other';
 9301:                                     $typestr = join(',',(@esc_types,$othervalue));
 9302:                                 }
 9303:                                 $typestr = $othervalue;
 9304:                             } else {
 9305:                                 $typestr = $othervalue;
 9306:                             } 
 9307:                             $latesttypes[$newnum] = $typedom.':'.$typestr;
 9308:                             $newnum ++ ;
 9309:                         }
 9310:                     }
 9311:                     my $selfenroll_types = join(';',@latesttypes);
 9312:                     if ($selfenroll_types ne $curr_types) {
 9313:                         $changes{'internal.selfenroll_types'} = $selfenroll_types;
 9314:                     }
 9315:                 }
 9316:             } elsif ($item eq 'limit') {
 9317:                 my $newlimit = $env{'form.selfenroll_limit'};
 9318:                 my $newcap = $env{'form.selfenroll_cap'};
 9319:                 $newcap =~s/\s+//g;
 9320:                 my $currlimit =  $currsettings->{'selfenroll_limit'};
 9321:                 $currlimit = 'none' if ($currlimit eq '');
 9322:                 my $currcap = $currsettings->{'selfenroll_cap'};
 9323:                 if ($newlimit ne $currlimit) {
 9324:                     if ($newlimit ne 'none') {
 9325:                         if ($newcap =~ /^\d+$/) {
 9326:                             if ($newcap ne $currcap) {
 9327:                                 $changes{'internal.selfenroll_cap'} = $newcap;
 9328:                             }
 9329:                             $changes{'internal.selfenroll_limit'} = $newlimit;
 9330:                         } else {
 9331:                             $warning{$item} = &mt('Maximum enrollment setting unchanged.').'<br />'.
 9332:                                 &mt('The value provided was invalid - it must be a positive integer if enrollment is being limited.'); 
 9333:                         }
 9334:                     } elsif ($currcap ne '') {
 9335:                         $changes{'internal.selfenroll_cap'} = '';
 9336:                         $changes{'internal.selfenroll_limit'} = $newlimit; 
 9337:                     }
 9338:                 } elsif ($currlimit ne 'none') {
 9339:                     if ($newcap =~ /^\d+$/) {
 9340:                         if ($newcap ne $currcap) {
 9341:                             $changes{'internal.selfenroll_cap'} = $newcap;
 9342:                         }
 9343:                     } else {
 9344:                         $warning{$item} = &mt('Maximum enrollment setting unchanged.').'<br />'.
 9345:                             &mt('The value provided was invalid - it must be a positive integer if enrollment is being limited.');
 9346:                     }
 9347:                 }
 9348:             } elsif ($item eq 'approval') {
 9349:                 my (@currnotified,@newnotified);
 9350:                 my $currapproval = $currsettings->{'selfenroll_approval'};
 9351:                 my $currnotifylist = $currsettings->{'selfenroll_notifylist'};
 9352:                 if ($currnotifylist ne '') {
 9353:                     @currnotified = split(/,/,$currnotifylist);
 9354:                     @currnotified = sort(@currnotified);
 9355:                 }
 9356:                 my $newapproval = $env{'form.selfenroll_approval'};
 9357:                 @newnotified = &Apache::loncommon::get_env_multiple('form.selfenroll_notify');
 9358:                 @newnotified = sort(@newnotified);
 9359:                 if ($newapproval ne $currapproval) {
 9360:                     $changes{'internal.selfenroll_approval'} = $newapproval;
 9361:                     if (!$newapproval) {
 9362:                         if ($currnotifylist ne '') {
 9363:                             $changes{'internal.selfenroll_notifylist'} = '';
 9364:                         }
 9365:                     } else {
 9366:                         my @differences =  
 9367:                             &Apache::loncommon::compare_arrays(\@currnotified,\@newnotified);
 9368:                         if (@differences > 0) {
 9369:                             if (@newnotified > 0) {
 9370:                                 $changes{'internal.selfenroll_notifylist'} = join(',',@newnotified);
 9371:                             } else {
 9372:                                 $changes{'internal.selfenroll_notifylist'} = join(',',@newnotified);
 9373:                             }
 9374:                         }
 9375:                     }
 9376:                 } else {
 9377:                     my @differences = &Apache::loncommon::compare_arrays(\@currnotified,\@newnotified);
 9378:                     if (@differences > 0) {
 9379:                         if (@newnotified > 0) {
 9380:                             $changes{'internal.selfenroll_notifylist'} = join(',',@newnotified);
 9381:                         } else {
 9382:                             $changes{'internal.selfenroll_notifylist'} = '';
 9383:                         }
 9384:                     }
 9385:                 }
 9386:             } else {
 9387:                 my $curr_val = $currsettings->{'selfenroll_'.$item};
 9388:                 my $newval = $env{'form.selfenroll_'.$item};
 9389:                 if ($item eq 'section') {
 9390:                     $newval = $env{'form.sections'};
 9391:                     if (defined($curr_groups{$newval})) {
 9392:                         $newval = $curr_val;
 9393:                         $warning{$item} = &mt('Section for self-enrolled users unchanged as the proposed section is a group').'<br />'.
 9394:                                           &mt('Group names and section names must be distinct');
 9395:                     } elsif ($newval eq 'all') {
 9396:                         $newval = $curr_val;
 9397:                         $warning{$item} = &mt('Section for self-enrolled users unchanged, as "all" is a reserved section name.');
 9398:                     }
 9399:                     if ($newval eq '') {
 9400:                         $newval = 'none';
 9401:                     }
 9402:                 }
 9403:                 if ($newval ne $curr_val) {
 9404:                     $changes{'internal.selfenroll_'.$item} = $newval;
 9405:                 }
 9406:             }
 9407:         }
 9408:         if (keys(%warning) > 0) {
 9409:             foreach my $item (@{$row}) {
 9410:                 if (exists($warning{$item})) {
 9411:                     $r->print($warning{$item}.'<br />');
 9412:                 }
 9413:             } 
 9414:         }
 9415:         if (keys(%changes) > 0) {
 9416:             my $putresult = &Apache::lonnet::put('environment',\%changes,$cdom,$cnum);
 9417:             if ($putresult eq 'ok') {
 9418:                 if ((exists($changes{'internal.selfenroll_types'})) ||
 9419:                     (exists($changes{'internal.selfenroll_start_date'}))  ||
 9420:                     (exists($changes{'internal.selfenroll_end_date'}))) {
 9421:                     my %crsinfo = &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',
 9422:                                                                 $cnum,undef,undef,'Course');
 9423:                     my $chome = &Apache::lonnet::homeserver($cnum,$cdom);
 9424:                     if (ref($crsinfo{$cid}) eq 'HASH') {
 9425:                         foreach my $item ('selfenroll_types','selfenroll_start_date','selfenroll_end_date') {
 9426:                             if (exists($changes{'internal.'.$item})) {
 9427:                                 $crsinfo{$cid}{$item} = $changes{'internal.'.$item};
 9428:                             }
 9429:                         }
 9430:                         my $crsputresult =
 9431:                             &Apache::lonnet::courseidput($cdom,\%crsinfo,
 9432:                                                          $chome,'notime');
 9433:                     }
 9434:                 }
 9435:                 $r->print(&mt('The following changes were made to self-enrollment settings:').'<ul>');
 9436:                 foreach my $item (@{$row}) {
 9437:                     my $title = $item;
 9438:                     if (ref($lt) eq 'HASH') {
 9439:                         $title = $lt->{$item};
 9440:                     }
 9441:                     if ($item eq 'enroll_dates') {
 9442:                         foreach my $type ('start','end') {
 9443:                             if (exists($changes{'internal.selfenroll_'.$type.'_date'})) {
 9444:                                 my $newdate = &Apache::lonlocal::locallocaltime($changes{'internal.selfenroll_'.$type.'_date'});
 9445:                                 $r->print('<li>'.&mt('[_1]: "[_2]" set to "[_3]".',
 9446:                                           $title,$type,$newdate).'</li>');
 9447:                             }
 9448:                         }
 9449:                     } elsif ($item eq 'access_dates') {
 9450:                         foreach my $type ('start','end') {
 9451:                             if (exists($changes{'internal.selfenroll_'.$type.'_access'})) {
 9452:                                 my $newdate = &Apache::lonlocal::locallocaltime($changes{'internal.selfenroll_'.$type.'_access'});
 9453:                                 $r->print('<li>'.&mt('[_1]: "[_2]" set to "[_3]".',
 9454:                                           $title,$type,$newdate).'</li>');
 9455:                             }
 9456:                         }
 9457:                     } elsif ($item eq 'limit') {
 9458:                         if ((exists($changes{'internal.selfenroll_limit'})) ||
 9459:                             (exists($changes{'internal.selfenroll_cap'}))) {
 9460:                             my ($newval,$newcap);
 9461:                             if ($changes{'internal.selfenroll_cap'} ne '') {
 9462:                                 $newcap = $changes{'internal.selfenroll_cap'}
 9463:                             } else {
 9464:                                 $newcap = $currsettings->{'selfenroll_cap'};
 9465:                             }
 9466:                             if ($changes{'internal.selfenroll_limit'} eq 'none') {
 9467:                                 $newval = &mt('No limit');
 9468:                             } elsif ($changes{'internal.selfenroll_limit'} eq 
 9469:                                      'allstudents') {
 9470:                                 $newval = &mt('New self-enrollment no longer allowed when total (all students) reaches [_1].',$newcap);
 9471:                             } elsif ($changes{'internal.selfenroll_limit'} eq 'selfenrolled') {
 9472:                                 $newval = &mt('New self-enrollment no longer allowed when total number of self-enrolled students reaches [_1].',$newcap);
 9473:                             } else {
 9474:                                 my $currlimit =  $currsettings->{'selfenroll_limit'};
 9475:                                 if ($currlimit eq 'allstudents') {
 9476:                                     $newval = &mt('New self-enrollment no longer allowed when total (all students) reaches [_1].',$newcap);
 9477:                                 } elsif ($changes{'internal.selfenroll_limit'} eq 'selfenrolled') {
 9478:                                     $newval =  &mt('New self-enrollment no longer allowed when total number of self-enrolled students reaches [_1].',$newcap);
 9479:                                 }
 9480:                             }
 9481:                             $r->print('<li>'.&mt('"[_1]" set to "[_2]".',$title,$newval).'</li>'."\n");
 9482:                         }
 9483:                     } elsif ($item eq 'approval') {
 9484:                         if ((exists($changes{'internal.selfenroll_approval'})) ||
 9485:                             (exists($changes{'internal.selfenroll_notifylist'}))) {
 9486:                             my %selfdescs = &Apache::lonuserutils::selfenroll_default_descs();
 9487:                             my ($newval,$newnotify);
 9488:                             if (exists($changes{'internal.selfenroll_notifylist'})) {
 9489:                                 $newnotify = $changes{'internal.selfenroll_notifylist'};
 9490:                             } else {   
 9491:                                 $newnotify = $currsettings->{'selfenroll_notifylist'};
 9492:                             }
 9493:                             if (exists($changes{'internal.selfenroll_approval'})) {
 9494:                                 if ($changes{'internal.selfenroll_approval'} !~ /^[012]$/) {
 9495:                                     $changes{'internal.selfenroll_approval'} = '0';
 9496:                                 }
 9497:                                 $newval = $selfdescs{'approval'}{$changes{'internal.selfenroll_approval'}};
 9498:                             } else {
 9499:                                 my $currapproval = $currsettings->{'selfenroll_approval'}; 
 9500:                                 if ($currapproval !~ /^[012]$/) {
 9501:                                     $currapproval = 0;
 9502:                                 }
 9503:                                 $newval = $selfdescs{'approval'}{$currapproval};
 9504:                             }
 9505:                             $r->print('<li>'.&mt('"[_1]" set to "[_2]".',$title,$newval));
 9506:                             if ($newnotify) {
 9507:                                 $r->print('<br />'.&mt('The following will be notified when an enrollment request needs approval, or has been approved: [_1].',$newnotify));
 9508:                             } else {
 9509:                                 $r->print('<br />'.&mt('No notifications sent when an enrollment request needs approval, or has been approved.'));
 9510:                             }
 9511:                             $r->print('</li>'."\n");
 9512:                         }
 9513:                     } else {
 9514:                         if (exists($changes{'internal.selfenroll_'.$item})) {
 9515:                             my $newval = $changes{'internal.selfenroll_'.$item};
 9516:                             if ($item eq 'types') {
 9517:                                 if ($newval eq '') {
 9518:                                     $newval = &mt('None');
 9519:                                 } elsif ($newval eq '*') {
 9520:                                     $newval = &mt('Any user in any domain');
 9521:                                 }
 9522:                             } elsif ($item eq 'registered') {
 9523:                                 if ($newval eq '1') {
 9524:                                     $newval = &mt('Yes');
 9525:                                 } elsif ($newval eq '0') {
 9526:                                     $newval = &mt('No');
 9527:                                 }
 9528:                             }
 9529:                             $r->print('<li>'.&mt('"[_1]" set to "[_2]".',$title,$newval).'</li>'."\n");
 9530:                         }
 9531:                     }
 9532:                 }
 9533:                 $r->print('</ul>');
 9534:                 if ($env{'course.'.$cid.'.description'} ne '') {
 9535:                     my %newenvhash;
 9536:                     foreach my $key (keys(%changes)) {
 9537:                         $newenvhash{'course.'.$cid.'.'.$key} = $changes{$key};
 9538:                     }
 9539:                     &Apache::lonnet::appenv(\%newenvhash);
 9540:                 }
 9541:             } else {
 9542:                 $r->print(&mt('An error occurred when saving changes to self-enrollment settings in this course.').'<br />'.
 9543:                           &mt('The error was: [_1].',$putresult));
 9544:             }
 9545:         } else {
 9546:             $r->print(&mt('No changes were made to the existing self-enrollment settings in this course.'));
 9547:         }
 9548:     } else {
 9549:         $r->print(&mt('No changes were made to the existing self-enrollment settings in this course.'));
 9550:     }
 9551:     my $visactions = &cat_visibility();
 9552:     my ($cathash,%cattype);
 9553:     my %domconfig = &Apache::lonnet::get_dom('configuration',['coursecategories'],$cdom);
 9554:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 9555:         $cathash = $domconfig{'coursecategories'}{'cats'};
 9556:         $cattype{'auth'} = $domconfig{'coursecategories'}{'auth'};
 9557:         $cattype{'unauth'} = $domconfig{'coursecategories'}{'unauth'};
 9558:     } else {
 9559:         $cathash = {};
 9560:         $cattype{'auth'} = 'std';
 9561:         $cattype{'unauth'} = 'std';
 9562:     }
 9563:     if (($cattype{'auth'} eq 'none') && ($cattype{'unauth'} eq 'none')) {
 9564:         $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
 9565:                   '<br />'.
 9566:                   '<br />'.$visactions->{'take'}.'<ul>'.
 9567:                   '<li>'.$visactions->{'dc_chgconf'}.'</li>'.
 9568:                   '</ul>');
 9569:     } elsif (($cattype{'auth'} !~ /^(std|domonly)$/) && ($cattype{'unauth'} !~ /^(std|domonly)$/)) {
 9570:         if ($currsettings->{'uniquecode'}) {
 9571:             $r->print('<span class="LC_info">'.$visactions->{'vis'}.'</span>');
 9572:         } else {
 9573:             $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
 9574:                   '<br />'.
 9575:                   '<br />'.$visactions->{'take'}.'<ul>'.
 9576:                   '<li>'.$visactions->{'dc_setcode'}.'</li>'.
 9577:                   '</ul><br />');
 9578:         }
 9579:     } else {
 9580:         my ($visible,$cansetvis,$vismsgs) = &visible_in_stdcat($cdom,$cnum,\%domconfig);
 9581:         if (ref($visactions) eq 'HASH') {
 9582:             if (!$visible) {
 9583:                 $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
 9584:                           '<br />');
 9585:                 if (ref($vismsgs) eq 'ARRAY') {
 9586:                     $r->print('<br />'.$visactions->{'take'}.'<ul>');
 9587:                     foreach my $item (@{$vismsgs}) {
 9588:                         $r->print('<li>'.$visactions->{$item}.'</li>');
 9589:                     }
 9590:                     $r->print('</ul>');
 9591:                 }
 9592:                 $r->print($cansetvis);
 9593:             }
 9594:         }
 9595:     } 
 9596:     return;
 9597: }
 9598: 
 9599: #---------------------------------------------- end functions for &phase_two
 9600: 
 9601: #--------------------------------- functions for &phase_two and &phase_three
 9602: 
 9603: #--------------------------end of functions for &phase_two and &phase_three
 9604: 
 9605: 1;
 9606: __END__
 9607: 
 9608: 

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