File:  [LON-CAPA] / loncom / interface / loncreateuser.pm
Revision 1.393: download - view: text, annotated - select for diffs
Sun Feb 16 15:38:52 2014 UTC (10 years, 3 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Modify changes in lonuserutils.pm rev. 1.161, so "Force ID change" message
  is not shown to users self-creating accounts.
- Wording change to labels for "Force ID change" and "Update ID in courses"
  message, to make them shorter, so "Login Data" can still float into right
  column.
- Add help document to explain ramifications of forcing ID change.
  - eliminate unhelpful: "only do if you know what you are doing".

    1: # The LearningOnline Network with CAPA
    2: # Create a user
    3: #
    4: # $Id: loncreateuser.pm,v 1.393 2014/02/16 15:38:52 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: ###
   29: 
   30: package Apache::loncreateuser;
   31: 
   32: =pod
   33: 
   34: =head1 NAME
   35: 
   36: Apache::loncreateuser.pm
   37: 
   38: =head1 SYNOPSIS
   39: 
   40:     Handler to create users and custom roles
   41: 
   42:     Provides an Apache handler for creating users,
   43:     editing their login parameters, roles, and removing roles, and
   44:     also creating and assigning custom roles.
   45: 
   46: =head1 OVERVIEW
   47: 
   48: =head2 Custom Roles
   49: 
   50: In LON-CAPA, roles are actually collections of privileges. "Teaching
   51: Assistant", "Course Coordinator", and other such roles are really just
   52: collection of privileges that are useful in many circumstances.
   53: 
   54: Custom roles can be defined by a Domain Coordinator, Course Coordinator
   55: or Community Coordinator via the Manage User functionality.
   56: The custom role editor screen will show all privileges which can be
   57: assigned to users. For a complete list of privileges, please see 
   58: C</home/httpd/lonTabs/rolesplain.tab>.
   59: 
   60: Custom role definitions are stored in the C<roles.db> file of the creator
   61: of the role.
   62: 
   63: =cut
   64: 
   65: use strict;
   66: use Apache::Constants qw(:common :http);
   67: use Apache::lonnet;
   68: use Apache::loncommon;
   69: use Apache::lonlocal;
   70: use Apache::longroup;
   71: use Apache::lonuserutils;
   72: use Apache::loncoursequeueadmin;
   73: use LONCAPA qw(:DEFAULT :match);
   74: 
   75: my $loginscript; # piece of javascript used in two separate instances
   76: my $authformnop;
   77: my $authformkrb;
   78: my $authformint;
   79: my $authformfsys;
   80: my $authformloc;
   81: 
   82: sub initialize_authen_forms {
   83:     my ($dom,$formname,$curr_authtype,$mode) = @_;
   84:     my ($krbdef,$krbdefdom) = &Apache::loncommon::get_kerberos_defaults($dom);
   85:     my %param = ( formname => $formname,
   86:                   kerb_def_dom => $krbdefdom,
   87:                   kerb_def_auth => $krbdef,
   88:                   domain => $dom,
   89:                 );
   90:     my %abv_auth = &auth_abbrev();
   91:     if ($curr_authtype =~ /^(krb4|krb5|internal|localauth|unix):(.*)$/) {
   92:         my $long_auth = $1;
   93:         my $curr_autharg = $2;
   94:         my %abv_auth = &auth_abbrev();
   95:         $param{'curr_authtype'} = $abv_auth{$long_auth};
   96:         if ($long_auth =~ /^krb(4|5)$/) {
   97:             $param{'curr_kerb_ver'} = $1;
   98:             $param{'curr_autharg'} = $curr_autharg;
   99:         }
  100:         if ($mode eq 'modifyuser') {
  101:             $param{'mode'} = $mode;
  102:         }
  103:     }
  104:     $loginscript  = &Apache::loncommon::authform_header(%param);
  105:     $authformkrb  = &Apache::loncommon::authform_kerberos(%param);
  106:     $authformnop  = &Apache::loncommon::authform_nochange(%param);
  107:     $authformint  = &Apache::loncommon::authform_internal(%param);
  108:     $authformfsys = &Apache::loncommon::authform_filesystem(%param);
  109:     $authformloc  = &Apache::loncommon::authform_local(%param);
  110: }
  111: 
  112: sub auth_abbrev {
  113:     my %abv_auth = (
  114:                      krb5      => 'krb',
  115:                      krb4      => 'krb',
  116:                      internal  => 'int',
  117:                      localauth => 'loc',
  118:                      unix      => 'fsys',
  119:                    );
  120:     return %abv_auth;
  121: }
  122: 
  123: # ====================================================
  124: 
  125: sub user_quotas {
  126:     my ($ccuname,$ccdomain) = @_;
  127:     my %lt = &Apache::lonlocal::texthash(
  128:                    'usrt'      => "User Tools",
  129:                    'cust'      => "Custom quota",
  130:                    'chqu'      => "Change quota",
  131:     );
  132:    
  133:     my $quota_javascript = <<"END_SCRIPT";
  134: <script type="text/javascript">
  135: // <![CDATA[
  136: function quota_changes(caller,context) {
  137:     var customoff = document.getElementById('custom_'+context+'quota_off');
  138:     var customon = document.getElementById('custom_'+context+'quota_on');
  139:     var number = document.getElementById(context+'quota');
  140:     if (caller == "custom") {
  141:         if (customoff) {
  142:             if (customoff.checked) {
  143:                 number.value = "";
  144:             }
  145:         }
  146:     }
  147:     if (caller == "quota") {
  148:         if (customon) {
  149:             customon.checked = true;
  150:         }
  151:     }
  152:     return;
  153: }
  154: // ]]>
  155: </script>
  156: END_SCRIPT
  157:     my $longinsttype;
  158:     my ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($ccdomain);
  159:     my $output = $quota_javascript."\n".
  160:                  '<h3>'.$lt{'usrt'}.'</h3>'."\n".
  161:                  &Apache::loncommon::start_data_table();
  162: 
  163:     if (&Apache::lonnet::allowed('mut',$ccdomain)) {
  164:         $output .= &build_tools_display($ccuname,$ccdomain,'tools');
  165:     }
  166: 
  167:     my %titles = &Apache::lonlocal::texthash (
  168:                     portfolio => "Disk space allocated to user's portfolio files",
  169:                     author    => "Disk space allocated to user's Authoring Space (if role assigned)",
  170:                  );
  171:     foreach my $name ('portfolio','author') {
  172:         my ($currquota,$quotatype,$inststatus,$defquota) =
  173:             &Apache::loncommon::get_user_quota($ccuname,$ccdomain,$name);
  174:         if ($longinsttype eq '') { 
  175:             if ($inststatus ne '') {
  176:                 if ($usertypes->{$inststatus} ne '') {
  177:                     $longinsttype = $usertypes->{$inststatus};
  178:                 }
  179:             }
  180:         }
  181:         my ($showquota,$custom_on,$custom_off,$defaultinfo);
  182:         $custom_on = ' ';
  183:         $custom_off = ' checked="checked" ';
  184:         if ($quotatype eq 'custom') {
  185:             $custom_on = $custom_off;
  186:             $custom_off = ' ';
  187:             $showquota = $currquota;
  188:             if ($longinsttype eq '') {
  189:                 $defaultinfo = &mt('For this user, the default quota would be [_1]'
  190:                               .' MB.',$defquota);
  191:             } else {
  192:                 $defaultinfo = &mt("For this user, the default quota would be [_1]".
  193:                                    " MB, as determined by the user's institutional".
  194:                                    " affiliation ([_2]).",$defquota,$longinsttype);
  195:             }
  196:         } else {
  197:             if ($longinsttype eq '') {
  198:                 $defaultinfo = &mt('For this user, the default quota is [_1]'
  199:                               .' MB.',$defquota);
  200:             } else {
  201:                 $defaultinfo = &mt("For this user, the default quota of [_1]".
  202:                                    " MB, is determined by the user's institutional".
  203:                                    " affiliation ([_2]).",$defquota,$longinsttype);
  204:             }
  205:         }
  206: 
  207:         if (&Apache::lonnet::allowed('mpq',$ccdomain)) {
  208:             $output .= '<tr class="LC_info_row">'."\n".
  209:                        '    <td>'.$titles{$name}.'</td>'."\n".
  210:                        '  </tr>'."\n".
  211:                        &Apache::loncommon::start_data_table_row()."\n".
  212:                        '  <td><span class="LC_nobreak">'.
  213:                        &mt('Current quota: [_1] MB',$currquota).'</span>&nbsp;&nbsp;'.
  214:                        $defaultinfo.'</td>'."\n".
  215:                        &Apache::loncommon::end_data_table_row()."\n".
  216:                        &Apache::loncommon::start_data_table_row()."\n".
  217:                        '  <td><span class="LC_nobreak">'.$lt{'chqu'}.
  218:                        ': <label>'.
  219:                        '<input type="radio" name="custom_'.$name.'quota" id="custom_'.$name.'quota_off" '.
  220:                        'value="0" '.$custom_off.' onchange="javascript:quota_changes('."'custom','$name'".');"'.
  221:                        ' /><span class="LC_nobreak">'.
  222:                        &mt('Default ([_1] MB)',$defquota).'</span></label>&nbsp;'.
  223:                        '&nbsp;<label><input type="radio" name="custom_'.$name.'quota" id="custom_'.$name.'quota_on" '.
  224:                        'value="1" '.$custom_on.'  onchange="javascript:quota_changes('."'custom','$name'".');"'.
  225:                        ' />'.$lt{'cust'}.':</label>&nbsp;'.
  226:                        '<input type="text" name="'.$name.'quota" id="'.$name.'quota" size ="5" '.
  227:                        'value="'.$showquota.'" onfocus="javascript:quota_changes('."'quota','$name'".');"'.
  228:                        ' />&nbsp;'.&mt('MB').'</span></td>'."\n".
  229:                        &Apache::loncommon::end_data_table_row()."\n";
  230:         }
  231:     }
  232:     $output .= &Apache::loncommon::end_data_table();
  233:     return $output;
  234: }
  235: 
  236: sub build_tools_display {
  237:     my ($ccuname,$ccdomain,$context) = @_;
  238:     my (@usertools,%userenv,$output,@options,%validations,%reqtitles,%reqdisplay,
  239:         $colspan,$isadv,%domconfig);
  240:     my %lt = &Apache::lonlocal::texthash (
  241:                    'blog'       => "Personal User Blog",
  242:                    'aboutme'    => "Personal Information Page",
  243:                    'webdav'     => "WebDAV access to Authoring Spaces (if SSL and author/co-author)",
  244:                    'portfolio'  => "Personal User Portfolio",
  245:                    'avai'       => "Available",
  246:                    'cusa'       => "availability",
  247:                    'chse'       => "Change setting",
  248:                    'usde'       => "Use default",
  249:                    'uscu'       => "Use custom",
  250:                    'official'   => 'Can request creation of official courses',
  251:                    'unofficial' => 'Can request creation of unofficial courses',
  252:                    'community'  => 'Can request creation of communities',
  253:                    'textbook'   => 'Can request creation of textbook courses',
  254:                    'requestauthor'  => 'Can request author space',
  255:     );
  256:     if ($context eq 'requestcourses') {
  257:         %userenv = &Apache::lonnet::userenvironment($ccdomain,$ccuname,
  258:                       'requestcourses.official','requestcourses.unofficial',
  259:                       'requestcourses.community','requestcourses.textbook');
  260:         @usertools = ('official','unofficial','community','textbook');
  261:         @options =('norequest','approval','autolimit','validate');
  262:         %validations = &Apache::lonnet::auto_courserequest_checks($ccdomain);
  263:         %reqtitles = &courserequest_titles();
  264:         %reqdisplay = &courserequest_display();
  265:         $colspan = ' colspan="2"';
  266:         %domconfig =
  267:             &Apache::lonnet::get_dom('configuration',['requestcourses'],$ccdomain);
  268:         $isadv = &Apache::lonnet::is_advanced_user($ccuname,$ccdomain);
  269:     } elsif ($context eq 'requestauthor') {
  270:         %userenv = &Apache::lonnet::userenvironment($ccdomain,$ccuname,
  271:                                                     'requestauthor');
  272:         @usertools = ('requestauthor');
  273:         @options =('norequest','approval','automatic');
  274:         %reqtitles = &requestauthor_titles();
  275:         %reqdisplay = &requestauthor_display();
  276:         $colspan = ' colspan="2"';
  277:         %domconfig =
  278:             &Apache::lonnet::get_dom('configuration',['requestauthor'],$ccdomain);
  279:     } else {
  280:         %userenv = &Apache::lonnet::userenvironment($ccdomain,$ccuname,
  281:                           'tools.aboutme','tools.portfolio','tools.blog',
  282:                           'tools.webdav');
  283:         @usertools = ('aboutme','blog','webdav','portfolio');
  284:     }
  285:     foreach my $item (@usertools) {
  286:         my ($custom_access,$curr_access,$cust_on,$cust_off,$tool_on,$tool_off,
  287:             $currdisp,$custdisp,$custradio);
  288:         $cust_off = 'checked="checked" ';
  289:         $tool_on = 'checked="checked" ';
  290:         $curr_access =  
  291:             &Apache::lonnet::usertools_access($ccuname,$ccdomain,$item,undef,
  292:                                               $context);
  293:         if ($context eq 'requestauthor') {
  294:             if ($userenv{$context} ne '') {
  295:                 $cust_on = ' checked="checked" ';
  296:                 $cust_off = '';
  297:             }  
  298:         } elsif ($userenv{$context.'.'.$item} ne '') {
  299:             $cust_on = ' checked="checked" ';
  300:             $cust_off = '';
  301:         }
  302:         if ($context eq 'requestcourses') {
  303:             if ($userenv{$context.'.'.$item} eq '') {
  304:                 $custom_access = &mt('Currently from default setting.');
  305:             } else {
  306:                 $custom_access = &mt('Currently from custom setting.');
  307:             }
  308:         } elsif ($context eq 'requestauthor') {
  309:             if ($userenv{$context} eq '') {
  310:                 $custom_access = &mt('Currently from default setting.');
  311:             } else {
  312:                 $custom_access = &mt('Currently from custom setting.');
  313:             }
  314:         } else {
  315:             if ($userenv{$context.'.'.$item} eq '') {
  316:                 $custom_access =
  317:                     &mt('Availability determined currently from default setting.');
  318:                 if (!$curr_access) {
  319:                     $tool_off = 'checked="checked" ';
  320:                     $tool_on = '';
  321:                 }
  322:             } else {
  323:                 $custom_access =
  324:                     &mt('Availability determined currently from custom setting.');
  325:                 if ($userenv{$context.'.'.$item} == 0) {
  326:                     $tool_off = 'checked="checked" ';
  327:                     $tool_on = '';
  328:                 }
  329:             }
  330:         }
  331:         $output .= '  <tr class="LC_info_row">'."\n".
  332:                    '   <td'.$colspan.'>'.$lt{$item}.'</td>'."\n".
  333:                    '  </tr>'."\n".
  334:                    &Apache::loncommon::start_data_table_row()."\n";
  335:         if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
  336:             my ($curroption,$currlimit);
  337:             my $envkey = $context.'.'.$item;
  338:             if ($context eq 'requestauthor') {
  339:                 $envkey = $context;
  340:             }
  341:             if ($userenv{$envkey} ne '') {
  342:                 $curroption = $userenv{$envkey};
  343:             } else {
  344:                 my (@inststatuses);
  345:                 if ($context eq 'requestcourses') {
  346:                     $curroption =
  347:                         &Apache::loncoursequeueadmin::get_processtype('course',$ccuname,$ccdomain,
  348:                                                                       $isadv,$ccdomain,$item,
  349:                                                                       \@inststatuses,\%domconfig);
  350:                 } else {
  351:                      $curroption = 
  352:                          &Apache::loncoursequeueadmin::get_processtype('requestauthor',$ccuname,$ccdomain,
  353:                                                                        $isadv,$ccdomain,undef,
  354:                                                                        \@inststatuses,\%domconfig);
  355:                 }
  356:             }
  357:             if (!$curroption) {
  358:                 $curroption = 'norequest';
  359:             }
  360:             if ($curroption =~ /^autolimit=(\d*)$/) {
  361:                 $currlimit = $1;
  362:                 if ($currlimit eq '') {
  363:                     $currdisp = &mt('Yes, automatic creation');
  364:                 } else {
  365:                     $currdisp = &mt('Yes, up to [quant,_1,request]/user',$currlimit);
  366:                 }
  367:             } else {
  368:                 $currdisp = $reqdisplay{$curroption};
  369:             }
  370:             $custdisp = '<table>';
  371:             foreach my $option (@options) {
  372:                 my $val = $option;
  373:                 if ($option eq 'norequest') {
  374:                     $val = 0;
  375:                 }
  376:                 if ($option eq 'validate') {
  377:                     my $canvalidate = 0;
  378:                     if (ref($validations{$item}) eq 'HASH') {
  379:                         if ($validations{$item}{'_custom_'}) {
  380:                             $canvalidate = 1;
  381:                         }
  382:                     }
  383:                     next if (!$canvalidate);
  384:                 }
  385:                 my $checked = '';
  386:                 if ($option eq $curroption) {
  387:                     $checked = ' checked="checked"';
  388:                 } elsif ($option eq 'autolimit') {
  389:                     if ($curroption =~ /^autolimit/) {
  390:                         $checked = ' checked="checked"';
  391:                     }
  392:                 }
  393:                 my $name = 'crsreq_'.$item;
  394:                 if ($context eq 'requestauthor') {
  395:                     $name = $item;
  396:                 }
  397:                 $custdisp .= '<tr><td><span class="LC_nobreak"><label>'.
  398:                              '<input type="radio" name="'.$name.'" '.
  399:                              'value="'.$val.'"'.$checked.' />'.
  400:                              $reqtitles{$option}.'</label>&nbsp;';
  401:                 if ($option eq 'autolimit') {
  402:                     $custdisp .= '<input type="text" name="'.$name.
  403:                                  '_limit" size="1" '.
  404:                                  'value="'.$currlimit.'" /></span><br />'.
  405:                                  $reqtitles{'unlimited'};
  406:                 } else {
  407:                     $custdisp .= '</span>';
  408:                 }
  409:                 $custdisp .= '</td></tr>';
  410:             }
  411:             $custdisp .= '</table>';
  412:             $custradio = '</span></td><td>'.&mt('Custom setting').'<br />'.$custdisp;
  413:         } else {
  414:             $currdisp = ($curr_access?&mt('Yes'):&mt('No'));
  415:             my $name = $context.'_'.$item;
  416:             if ($context eq 'requestauthor') {
  417:                 $name = $context;
  418:             }
  419:             $custdisp = '<span class="LC_nobreak"><label>'.
  420:                         '<input type="radio" name="'.$name.'"'.
  421:                         ' value="1" '.$tool_on.'/>'.&mt('On').'</label>&nbsp;<label>'.
  422:                         '<input type="radio" name="'.$name.'" value="0" '.
  423:                         $tool_off.'/>'.&mt('Off').'</label></span>';
  424:             $custradio = ('&nbsp;'x2).'--'.$lt{'cusa'}.':&nbsp;'.$custdisp.
  425:                           '</span>';
  426:         }
  427:         $output .= '  <td'.$colspan.'>'.$custom_access.('&nbsp;'x4).
  428:                    $lt{'avai'}.': '.$currdisp.'</td>'."\n".
  429:                    &Apache::loncommon::end_data_table_row()."\n".
  430:                    &Apache::loncommon::start_data_table_row()."\n".
  431:                    '  <td style="vertical-align:top;"><span class="LC_nobreak">'.
  432:                    $lt{'chse'}.': <label>'.
  433:                    '<input type="radio" name="custom'.$item.'" value="0" '.
  434:                    $cust_off.'/>'.$lt{'usde'}.'</label>'.('&nbsp;' x3).
  435:                    '<label><input type="radio" name="custom'.$item.'" value="1" '.
  436:                    $cust_on.'/>'.$lt{'uscu'}.'</label>'.$custradio.'</td>'.
  437:                    &Apache::loncommon::end_data_table_row()."\n";
  438:     }
  439:     return $output;
  440: }
  441: 
  442: sub coursereq_externaluser {
  443:     my ($ccuname,$ccdomain,$cdom) = @_;
  444:     my (@usertools,@options,%validations,%userenv,$output);
  445:     my %lt = &Apache::lonlocal::texthash (
  446:                    'official'   => 'Can request creation of official courses',
  447:                    'unofficial' => 'Can request creation of unofficial courses',
  448:                    'community'  => 'Can request creation of communities',
  449:                    'textbook'   => 'Can request creation of textbook courses',
  450:     );
  451: 
  452:     %userenv = &Apache::lonnet::userenvironment($ccdomain,$ccuname,
  453:                       'reqcrsotherdom.official','reqcrsotherdom.unofficial',
  454:                       'reqcrsotherdom.community','reqcrsotherdom.textbook');
  455:     @usertools = ('official','unofficial','community','textbook');
  456:     @options = ('approval','validate','autolimit');
  457:     %validations = &Apache::lonnet::auto_courserequest_checks($cdom);
  458:     my $optregex = join('|',@options);
  459:     my %reqtitles = &courserequest_titles();
  460:     foreach my $item (@usertools) {
  461:         my ($curroption,$currlimit,$tooloff);
  462:         if ($userenv{'reqcrsotherdom.'.$item} ne '') {
  463:             my @curr = split(',',$userenv{'reqcrsotherdom.'.$item});
  464:             foreach my $req (@curr) {
  465:                 if ($req =~ /^\Q$cdom\E\:($optregex)=?(\d*)$/) {
  466:                     $curroption = $1;
  467:                     $currlimit = $2;
  468:                     last;
  469:                 }
  470:             }
  471:             if (!$curroption) {
  472:                 $curroption = 'norequest';
  473:                 $tooloff = ' checked="checked"';
  474:             }
  475:         } else {
  476:             $curroption = 'norequest';
  477:             $tooloff = ' checked="checked"';
  478:         }
  479:         $output.= &Apache::loncommon::start_data_table_row()."\n".
  480:                   '  <td><span class="LC_nobreak">'.$lt{$item}.': </span></td><td>'.
  481:                   '<table><tr><td valign="top">'."\n".
  482:                   '<label><input type="radio" name="reqcrsotherdom_'.$item.
  483:                   '" value=""'.$tooloff.' />'.$reqtitles{'norequest'}.
  484:                   '</label></td>';
  485:         foreach my $option (@options) {
  486:             if ($option eq 'validate') {
  487:                 my $canvalidate = 0;
  488:                 if (ref($validations{$item}) eq 'HASH') {
  489:                     if ($validations{$item}{'_external_'}) {
  490:                         $canvalidate = 1;
  491:                     }
  492:                 }
  493:                 next if (!$canvalidate);
  494:             }
  495:             my $checked = '';
  496:             if ($option eq $curroption) {
  497:                 $checked = ' checked="checked"';
  498:             }
  499:             $output .= '<td valign="top"><span class="LC_nobreak"><label>'.
  500:                        '<input type="radio" name="reqcrsotherdom_'.$item.
  501:                        '" value="'.$option.'"'.$checked.' />'.
  502:                        $reqtitles{$option}.'</label>';
  503:             if ($option eq 'autolimit') {
  504:                 $output .= '&nbsp;<input type="text" name="reqcrsotherdom_'.
  505:                            $item.'_limit" size="1" '.
  506:                            'value="'.$currlimit.'" /></span>'.
  507:                            '<br />'.$reqtitles{'unlimited'};
  508:             } else {
  509:                 $output .= '</span>';
  510:             }
  511:             $output .= '</td>';
  512:         }
  513:         $output .= '</td></tr></table></td>'."\n".
  514:                    &Apache::loncommon::end_data_table_row()."\n";
  515:     }
  516:     return $output;
  517: }
  518: 
  519: sub domainrole_req {
  520:     my ($ccuname,$ccdomain) = @_;
  521:     return '<br /><h3>'.
  522:            &mt('User Can Request Assignment of Domain Roles?').
  523:            '</h3>'."\n".
  524:            &Apache::loncommon::start_data_table().
  525:            &build_tools_display($ccuname,$ccdomain,
  526:                                 'requestauthor').
  527:            &Apache::loncommon::end_data_table();
  528: }
  529: 
  530: sub courserequest_titles {
  531:     my %titles = &Apache::lonlocal::texthash (
  532:                                    official   => 'Official',
  533:                                    unofficial => 'Unofficial',
  534:                                    community  => 'Communities',
  535:                                    textbook   => 'Textbook',
  536:                                    norequest  => 'Not allowed',
  537:                                    approval   => 'Approval by Dom. Coord.',
  538:                                    validate   => 'With validation',
  539:                                    autolimit  => 'Numerical limit',
  540:                                    unlimited  => '(blank for unlimited)',
  541:                  );
  542:     return %titles;
  543: }
  544: 
  545: sub courserequest_display {
  546:     my %titles = &Apache::lonlocal::texthash (
  547:                                    approval   => 'Yes, need approval',
  548:                                    validate   => 'Yes, with validation',
  549:                                    norequest  => 'No',
  550:    );
  551:    return %titles;
  552: }
  553: 
  554: sub requestauthor_titles {
  555:     my %titles = &Apache::lonlocal::texthash (
  556:                                    norequest  => 'Not allowed',
  557:                                    approval   => 'Approval by Dom. Coord.',
  558:                                    automatic  => 'Automatic approval',
  559:                  );
  560:     return %titles;
  561: 
  562: }
  563: 
  564: sub requestauthor_display {
  565:     my %titles = &Apache::lonlocal::texthash (
  566:                                    approval   => 'Yes, need approval',
  567:                                    automatic  => 'Yes, automatic approval',
  568:                                    norequest  => 'No',
  569:    );
  570:    return %titles;
  571: }
  572: 
  573: sub requestchange_display {
  574:     my %titles = &Apache::lonlocal::texthash (
  575:                                    approval   => "availability set to 'on' (approval required)", 
  576:                                    automatic  => "availability set to 'on' (automatic approval)",
  577:                                    norequest  => "availability set to 'off'",
  578:    );
  579:    return %titles;
  580: }
  581: 
  582: sub curr_requestauthor {
  583:     my ($uname,$udom,$isadv,$inststatuses,$domconfig) = @_;
  584:     return unless ((ref($inststatuses) eq 'ARRAY') && (ref($domconfig) eq 'HASH'));
  585:     if ($uname eq '' || $udom eq '') {
  586:         $uname = $env{'user.name'};
  587:         $udom = $env{'user.domain'};
  588:         $isadv = $env{'user.adv'};
  589:     }
  590:     my (%userenv,%settings,$val);
  591:     my @options = ('automatic','approval');
  592:     %userenv =
  593:         &Apache::lonnet::userenvironment($udom,$uname,'requestauthor','inststatus');
  594:     if ($userenv{'requestauthor'}) {
  595:         $val = $userenv{'requestauthor'};
  596:         @{$inststatuses} = ('_custom_');
  597:     } else {
  598:         my %alltasks;
  599:         if (ref($domconfig->{'requestauthor'}) eq 'HASH') {
  600:             %settings = %{$domconfig->{'requestauthor'}};
  601:             if (($isadv) && ($settings{'_LC_adv'} ne '')) {
  602:                 $val = $settings{'_LC_adv'};
  603:                 @{$inststatuses} = ('_LC_adv_');
  604:             } else {
  605:                 if ($userenv{'inststatus'} ne '') {
  606:                     @{$inststatuses} = split(',',$userenv{'inststatus'});
  607:                 } else {
  608:                     @{$inststatuses} = ('default');
  609:                 }
  610:                 foreach my $status (@{$inststatuses}) {
  611:                     if (exists($settings{$status})) {
  612:                         my $value = $settings{$status};
  613:                         next unless ($value);
  614:                         unless (exists($alltasks{$value})) {
  615:                             if (ref($alltasks{$value}) eq 'ARRAY') {
  616:                                 unless(grep(/^\Q$status\E$/,@{$alltasks{$value}})) {
  617:                                     push(@{$alltasks{$value}},$status);
  618:                                 }
  619:                             } else {
  620:                                 @{$alltasks{$value}} = ($status);
  621:                             }
  622:                         }
  623:                     }
  624:                 }
  625:                 foreach my $option (@options) {
  626:                     if ($alltasks{$option}) {
  627:                         $val = $option;
  628:                         last;
  629:                     }
  630:                 }
  631:             }
  632:         }
  633:     }
  634:     return $val;
  635: }
  636: 
  637: # =================================================================== Phase one
  638: 
  639: sub print_username_entry_form {
  640:     my ($r,$context,$response,$srch,$forcenewuser,$crstype,$brcrum) = @_;
  641:     my $defdom=$env{'request.role.domain'};
  642:     my $formtoset = 'crtuser';
  643:     if (exists($env{'form.startrolename'})) {
  644:         $formtoset = 'docustom';
  645:         $env{'form.rolename'} = $env{'form.startrolename'};
  646:     } elsif ($env{'form.origform'} eq 'crtusername') {
  647:         $formtoset =  $env{'form.origform'};
  648:     }
  649: 
  650:     my ($jsback,$elements) = &crumb_utilities();
  651: 
  652:     my $jscript = &Apache::loncommon::studentbrowser_javascript()."\n".
  653:         '<script type="text/javascript">'."\n".
  654:         '// <![CDATA['."\n".
  655:         &Apache::lonhtmlcommon::set_form_elements($elements->{$formtoset})."\n".
  656:         '// ]]>'."\n".
  657:         '</script>'."\n";
  658: 
  659:     my %existingroles=&Apache::lonuserutils::my_custom_roles($crstype);
  660:     if (($env{'form.action'} eq 'custom') && (keys(%existingroles) > 0)
  661:         && (&Apache::lonnet::allowed('mcr','/'))) {
  662:         $jscript .= &customrole_javascript();
  663:     }
  664:     my $helpitem = 'Course_Change_Privileges';
  665:     if ($env{'form.action'} eq 'custom') {
  666:         $helpitem = 'Course_Editing_Custom_Roles';
  667:     } elsif ($env{'form.action'} eq 'singlestudent') {
  668:         $helpitem = 'Course_Add_Student';
  669:     }
  670:     my %breadcrumb_text = &singleuser_breadcrumb($crstype);
  671:     if ($env{'form.action'} eq 'custom') {
  672:         push(@{$brcrum},
  673:                  {href=>"javascript:backPage(document.crtuser)",       
  674:                   text=>"Pick custom role",
  675:                   help => $helpitem,}
  676:                  );
  677:     } else {
  678:         push (@{$brcrum},
  679:                   {href => "javascript:backPage(document.crtuser)",
  680:                    text => $breadcrumb_text{'search'},
  681:                    help => $helpitem,
  682:                    faq  => 282,
  683:                    bug  => 'Instructor Interface',}
  684:                   );
  685:     }
  686:     my %loaditems = (
  687:                 'onload' => "javascript:setFormElements(document.$formtoset)",
  688:                     );
  689:     my $args = {bread_crumbs           => $brcrum,
  690:                 bread_crumbs_component => 'User Management',
  691:                 add_entries            => \%loaditems,};
  692:     $r->print(&Apache::loncommon::start_page('User Management',$jscript,$args));
  693: 
  694:     my %lt=&Apache::lonlocal::texthash(
  695:                     'srst' => 'Search for a user and enroll as a student',
  696:                     'srme' => 'Search for a user and enroll as a member',
  697:                     'srad' => 'Search for a user and modify/add user information or roles',
  698: 		    'usr'  => "Username",
  699:                     'dom'  => "Domain",
  700:                     'ecrp' => "Define or Edit Custom Role",
  701:                     'nr'   => "role name",
  702:                     'cre'  => "Next",
  703: 				       );
  704: 
  705:     if ($env{'form.action'} eq 'custom') {
  706:         if (&Apache::lonnet::allowed('mcr','/')) {
  707:             my $newroletext = &mt('Define new custom role:');
  708:             $r->print('<form action="/adm/createuser" method="post" name="docustom">'.
  709:                       '<input type="hidden" name="action" value="'.$env{'form.action'}.'" />'.
  710:                       '<input type="hidden" name="phase" value="selected_custom_edit" />'.
  711:                       '<h3>'.$lt{'ecrp'}.'</h3>'.
  712:                       &Apache::loncommon::start_data_table().
  713:                       &Apache::loncommon::start_data_table_row().
  714:                       '<td>');
  715:             if (keys(%existingroles) > 0) {
  716:                 $r->print('<br /><label><input type="radio" name="customroleaction" value="new" checked="checked" onclick="setCustomFields();" /><b>'.$newroletext.'</b></label>');
  717:             } else {
  718:                 $r->print('<br /><input type="hidden" name="customroleaction" value="new" /><b>'.$newroletext.'</b>');
  719:             }
  720:             $r->print('</td><td align="center">'.$lt{'nr'}.'<br /><input type="text" size="15" name="newrolename" onfocus="setCustomAction('."'new'".');" /></td>'.
  721:                       &Apache::loncommon::end_data_table_row());
  722:             if (keys(%existingroles) > 0) {
  723:                 $r->print(&Apache::loncommon::start_data_table_row().'<td><br />'.
  724:                           '<label><input type="radio" name="customroleaction" value="edit" onclick="setCustomFields();"/><b>'.
  725:                           &mt('View/Modify existing role:').'</b></label></td>'.
  726:                           '<td align="center"><br />'.
  727:                           '<select name="rolename" onchange="setCustomAction('."'edit'".');">'.
  728:                           '<option value="" selected="selected">'.
  729:                           &mt('Select'));
  730:                 foreach my $role (sort(keys(%existingroles))) {
  731:                     $r->print('<option value="'.$role.'">'.$role.'</option>');
  732:                 }
  733:                 $r->print('</select>'.
  734:                           '</td>'.
  735:                           &Apache::loncommon::end_data_table_row());
  736:             }
  737:             $r->print(&Apache::loncommon::end_data_table().'<p>'.
  738:                       '<input name="customeditor" type="submit" value="'.
  739:                       $lt{'cre'}.'" /></p>'.
  740:                       '</form>');
  741:         }
  742:     } else {
  743:         my $actiontext = $lt{'srad'};
  744:         if ($env{'form.action'} eq 'singlestudent') {
  745:             if ($crstype eq 'Community') {
  746:                 $actiontext = $lt{'srme'};
  747:             } else {
  748:                 $actiontext = $lt{'srst'};
  749:             }
  750:         }
  751:         $r->print("<h3>$actiontext</h3>");
  752:         if ($env{'form.origform'} ne 'crtusername') {
  753:             $r->print("\n".$response);
  754:         }
  755:         $r->print(&entry_form($defdom,$srch,$forcenewuser,$context,$response,$crstype));
  756:     }
  757: }
  758: 
  759: sub customrole_javascript {
  760:     my $js = <<"END";
  761: <script type="text/javascript">
  762: // <![CDATA[
  763: 
  764: function setCustomFields() {
  765:     if (document.docustom.customroleaction.length > 0) {
  766:         for (var i=0; i<document.docustom.customroleaction.length; i++) {
  767:             if (document.docustom.customroleaction[i].checked) {
  768:                 if (document.docustom.customroleaction[i].value == 'new') {
  769:                     document.docustom.rolename.selectedIndex = 0;
  770:                 } else {
  771:                     document.docustom.newrolename.value = '';
  772:                 }
  773:             }
  774:         }
  775:     }
  776:     return;
  777: }
  778: 
  779: function setCustomAction(caller) {
  780:     if (document.docustom.customroleaction.length > 0) {
  781:         for (var i=0; i<document.docustom.customroleaction.length; i++) {
  782:             if (document.docustom.customroleaction[i].value == caller) {
  783:                 document.docustom.customroleaction[i].checked = true;
  784:             }
  785:         }
  786:     }
  787:     setCustomFields();
  788:     return;
  789: }
  790: 
  791: // ]]>
  792: </script>
  793: END
  794:     return $js;
  795: }
  796: 
  797: sub entry_form {
  798:     my ($dom,$srch,$forcenewuser,$context,$responsemsg,$crstype) = @_;
  799:     my ($usertype,$inexact);
  800:     if (ref($srch) eq 'HASH') {
  801:         if (($srch->{'srchin'} eq 'dom') &&
  802:             ($srch->{'srchby'} eq 'uname') &&
  803:             ($srch->{'srchtype'} eq 'exact') &&
  804:             ($srch->{'srchdomain'} ne '') &&
  805:             ($srch->{'srchterm'} ne '')) {
  806:             my (%curr_rules,%got_rules);
  807:             my ($rules,$ruleorder) =
  808:                 &Apache::lonnet::inst_userrules($srch->{'srchdomain'},'username');
  809:             $usertype = &Apache::lonuserutils::check_usertype($srch->{'srchdomain'},$srch->{'srchterm'},$rules,\%curr_rules,\%got_rules);
  810:         } else {
  811:             $inexact = 1;
  812:         }
  813:     }
  814:     my $cancreate =
  815:         &Apache::lonuserutils::can_create_user($dom,$context,$usertype);
  816:     my $userpicker = 
  817:        &Apache::loncommon::user_picker($dom,$srch,$forcenewuser,
  818:                                        'document.crtuser',$cancreate,$usertype);
  819:     my $srchbutton = &mt('Search');
  820:     if ($env{'form.action'} eq 'singlestudent') {
  821:         $srchbutton = &mt('Search and Enroll');
  822:     } elsif ($cancreate && $responsemsg ne '' && $inexact) {
  823:         $srchbutton = &mt('Search or Add New User');
  824:     }
  825:     my $output = <<"ENDBLOCK";
  826: <form action="/adm/createuser" method="post" name="crtuser">
  827: <input type="hidden" name="action" value="$env{'form.action'}" />
  828: <input type="hidden" name="phase" value="get_user_info" />
  829: $userpicker
  830: <input name="userrole" type="button" value="$srchbutton" onclick="javascript:validateEntry(document.crtuser)" />
  831: </form>
  832: ENDBLOCK
  833:     if ($env{'form.phase'} eq '') {
  834:         my $defdom=$env{'request.role.domain'};
  835:         my $domform = &Apache::loncommon::select_dom_form($defdom,'srchdomain');
  836:         my %lt=&Apache::lonlocal::texthash(
  837:                   'enro' => 'Enroll one student',
  838:                   'enrm' => 'Enroll one member',
  839:                   'admo' => 'Add/modify a single user',
  840:                   'crea' => 'create new user if required',
  841:                   'uskn' => "username is known",
  842:                   'crnu' => 'Create a new user',
  843:                   'usr'  => 'Username',
  844:                   'dom'  => 'in domain',
  845:                   'enrl' => 'Enroll',
  846:                   'cram'  => 'Create/Modify user',
  847:         );
  848:         my $sellink=&Apache::loncommon::selectstudent_link('crtusername','srchterm','srchdomain');
  849:         my ($title,$buttontext,$showresponse);
  850:         if ($env{'form.action'} eq 'singlestudent') {
  851:             if ($crstype eq 'Community') {
  852:                 $title = $lt{'enrm'};
  853:             } else {
  854:                 $title = $lt{'enro'};
  855:             }
  856:             $buttontext = $lt{'enrl'};
  857:         } else {
  858:             $title = $lt{'admo'};
  859:             $buttontext = $lt{'cram'};
  860:         }
  861:         if ($cancreate) {
  862:             $title .= ' <span class="LC_cusr_subheading">('.$lt{'crea'}.')</span>';
  863:         } else {
  864:             $title .= ' <span class="LC_cusr_subheading">('.$lt{'uskn'}.')</span>';
  865:         }
  866:         if ($env{'form.origform'} eq 'crtusername') {
  867:             $showresponse = $responsemsg;
  868:         }
  869:         $output .= <<"ENDDOCUMENT";
  870: <br />
  871: <form action="/adm/createuser" method="post" name="crtusername">
  872: <input type="hidden" name="action" value="$env{'form.action'}" />
  873: <input type="hidden" name="phase" value="createnewuser" />
  874: <input type="hidden" name="srchtype" value="exact" />
  875: <input type="hidden" name="srchby" value="uname" />
  876: <input type="hidden" name="srchin" value="dom" />
  877: <input type="hidden" name="forcenewuser" value="1" />
  878: <input type="hidden" name="origform" value="crtusername" />
  879: <h3>$title</h3>
  880: $showresponse
  881: <table>
  882:  <tr>
  883:   <td>$lt{'usr'}:</td>
  884:   <td><input type="text" size="15" name="srchterm" /></td>
  885:   <td>&nbsp;$lt{'dom'}:</td><td>$domform</td>
  886:   <td>&nbsp;$sellink&nbsp;</td>
  887:   <td>&nbsp;<input name="userrole" type="submit" value="$buttontext" /></td>
  888:  </tr>
  889: </table>
  890: </form>
  891: ENDDOCUMENT
  892:     }
  893:     return $output;
  894: }
  895: 
  896: sub user_modification_js {
  897:     my ($pjump_def,$dc_setcourse_code,$nondc_setsection_code,$groupslist)=@_;
  898:     
  899:     return <<END;
  900: <script type="text/javascript" language="Javascript">
  901: // <![CDATA[
  902: 
  903:     $pjump_def
  904:     $dc_setcourse_code
  905: 
  906:     function dateset() {
  907:         eval("document.cu."+document.cu.pres_marker.value+
  908:             ".value=document.cu.pres_value.value");
  909:         modalWindow.close();
  910:     }
  911: 
  912:     $nondc_setsection_code
  913: // ]]>
  914: </script>
  915: END
  916: }
  917: 
  918: # =================================================================== Phase two
  919: sub print_user_selection_page {
  920:     my ($r,$response,$srch,$srch_results,$srcharray,$context,$opener_elements,$crstype,$brcrum) = @_;
  921:     my @fields = ('username','domain','lastname','firstname','permanentemail');
  922:     my $sortby = $env{'form.sortby'};
  923: 
  924:     if (!grep(/^\Q$sortby\E$/,@fields)) {
  925:         $sortby = 'lastname';
  926:     }
  927: 
  928:     my ($jsback,$elements) = &crumb_utilities();
  929: 
  930:     my $jscript = (<<ENDSCRIPT);
  931: <script type="text/javascript">
  932: // <![CDATA[
  933: function pickuser(uname,udom) {
  934:     document.usersrchform.seluname.value=uname;
  935:     document.usersrchform.seludom.value=udom;
  936:     document.usersrchform.phase.value="userpicked";
  937:     document.usersrchform.submit();
  938: }
  939: 
  940: $jsback
  941: // ]]>
  942: </script>
  943: ENDSCRIPT
  944: 
  945:     my %lt=&Apache::lonlocal::texthash(
  946:                                        'usrch'          => "User Search to add/modify roles",
  947:                                        'stusrch'        => "User Search to enroll student",
  948:                                        'memsrch'        => "User Search to enroll member",
  949:                                        'usel'           => "Select a user to add/modify roles",
  950:                                        'stusel'         => "Select a user to enroll as a student",
  951:                                        'memsel'         => "Select a user to enroll as a member",
  952:                                        'username'       => "username",
  953:                                        'domain'         => "domain",
  954:                                        'lastname'       => "last name",
  955:                                        'firstname'      => "first name",
  956:                                        'permanentemail' => "permanent e-mail",
  957:                                       );
  958:     if ($context eq 'requestcrs') {
  959:         $r->print('<div>');
  960:     } else {
  961:         my %breadcrumb_text = &singleuser_breadcrumb($crstype);
  962:         my $helpitem;
  963:         if ($env{'form.action'} eq 'singleuser') {
  964:             $helpitem = 'Course_Change_Privileges';
  965:         } elsif ($env{'form.action'} eq 'singlestudent') {
  966:             $helpitem = 'Course_Add_Student';
  967:         }
  968:         push (@{$brcrum},
  969:                   {href => "javascript:backPage(document.usersrchform,'','')",
  970:                    text => $breadcrumb_text{'search'},
  971:                    faq  => 282,
  972:                    bug  => 'Instructor Interface',},
  973:                   {href => "javascript:backPage(document.usersrchform,'get_user_info','select')",
  974:                    text => $breadcrumb_text{'userpicked'},
  975:                    faq  => 282,
  976:                    bug  => 'Instructor Interface',
  977:                    help => $helpitem}
  978:                   );
  979:         $r->print(&Apache::loncommon::start_page('User Management',$jscript,{bread_crumbs => $brcrum}));
  980:         if ($env{'form.action'} eq 'singleuser') {
  981:             $r->print("<b>$lt{'usrch'}</b><br />");
  982:             $r->print(&entry_form($srch->{'srchdomain'},$srch,undef,$context,undef,$crstype));
  983:             $r->print('<h3>'.$lt{'usel'}.'</h3>');
  984:         } elsif ($env{'form.action'} eq 'singlestudent') {
  985:             $r->print($jscript."<b>");
  986:             if ($crstype eq 'Community') {
  987:                 $r->print($lt{'memsrch'});
  988:             } else {
  989:                 $r->print($lt{'stusrch'});
  990:             }
  991:             $r->print("</b><br />");
  992:             $r->print(&entry_form($srch->{'srchdomain'},$srch,undef,$context,undef,$crstype));
  993:             $r->print('</form><h3>');
  994:             if ($crstype eq 'Community') {
  995:                 $r->print($lt{'memsel'});
  996:             } else {
  997:                 $r->print($lt{'stusel'});
  998:             }
  999:             $r->print('</h3>');
 1000:         }
 1001:     }
 1002:     $r->print('<form name="usersrchform" method="post" action="">'.
 1003:               &Apache::loncommon::start_data_table()."\n".
 1004:               &Apache::loncommon::start_data_table_header_row()."\n".
 1005:               ' <th> </th>'."\n");
 1006:     foreach my $field (@fields) {
 1007:         $r->print(' <th><a href="javascript:document.usersrchform.sortby.value='.
 1008:                   "'".$field."'".';document.usersrchform.submit();">'.
 1009:                   $lt{$field}.'</a></th>'."\n");
 1010:     }
 1011:     $r->print(&Apache::loncommon::end_data_table_header_row());
 1012: 
 1013:     my @sorted_users = sort {
 1014:         lc($srch_results->{$a}->{$sortby})   cmp lc($srch_results->{$b}->{$sortby})
 1015:             ||
 1016:         lc($srch_results->{$a}->{lastname})  cmp lc($srch_results->{$b}->{lastname})
 1017:             ||
 1018:         lc($srch_results->{$a}->{firstname}) cmp lc($srch_results->{$b}->{firstname})
 1019: 	    ||
 1020: 	lc($a) cmp lc($b)
 1021:         } (keys(%$srch_results));
 1022: 
 1023:     foreach my $user (@sorted_users) {
 1024:         my ($uname,$udom) = split(/:/,$user);
 1025:         my $onclick;
 1026:         if ($context eq 'requestcrs') {
 1027:             $onclick =
 1028:                 'onclick="javascript:gochoose('."'$uname','$udom',".
 1029:                                                "'$srch_results->{$user}->{firstname}',".
 1030:                                                "'$srch_results->{$user}->{lastname}',".
 1031:                                                "'$srch_results->{$user}->{permanentemail}'".');"';
 1032:         } else {
 1033:             $onclick =
 1034:                 ' onclick="javascript:pickuser('."'".$uname."'".','."'".$udom."'".');"';
 1035:         }
 1036:         $r->print(&Apache::loncommon::start_data_table_row().
 1037:                   '<td><input type="button" name="seluser" value="'.&mt('Select').'" '.
 1038:                   $onclick.' /></td>'.
 1039:                   '<td><tt>'.$uname.'</tt></td>'.
 1040:                   '<td><tt>'.$udom.'</tt></td>');
 1041:         foreach my $field ('lastname','firstname','permanentemail') {
 1042:             $r->print('<td>'.$srch_results->{$user}->{$field}.'</td>');
 1043:         }
 1044:         $r->print(&Apache::loncommon::end_data_table_row());
 1045:     }
 1046:     $r->print(&Apache::loncommon::end_data_table().'<br /><br />');
 1047:     if (ref($srcharray) eq 'ARRAY') {
 1048:         foreach my $item (@{$srcharray}) {
 1049:             $r->print('<input type="hidden" name="'.$item.'" value="'.$env{'form.'.$item}.'" />'."\n");
 1050:         }
 1051:     }
 1052:     $r->print(' <input type="hidden" name="sortby" value="'.$sortby.'" />'."\n".
 1053:               ' <input type="hidden" name="seluname" value="" />'."\n".
 1054:               ' <input type="hidden" name="seludom" value="" />'."\n".
 1055:               ' <input type="hidden" name="currstate" value="select" />'."\n".
 1056:               ' <input type="hidden" name="phase" value="get_user_info" />'."\n".
 1057:               ' <input type="hidden" name="action" value="'.$env{'form.action'}.'" />'."\n");
 1058:     if ($context eq 'requestcrs') {
 1059:         $r->print($opener_elements.'</form></div>');
 1060:     } else {
 1061:         $r->print($response.'</form>');
 1062:     }
 1063: }
 1064: 
 1065: sub print_user_query_page {
 1066:     my ($r,$caller,$brcrum) = @_;
 1067: # FIXME - this is for a network-wide name search (similar to catalog search)
 1068: # To use frames with similar behavior to catalog/portfolio search.
 1069: # To be implemented. 
 1070:     return;
 1071: }
 1072: 
 1073: sub print_user_modification_page {
 1074:     my ($r,$ccuname,$ccdomain,$srch,$response,$context,$permission,$crstype,
 1075:         $brcrum,$showcredits) = @_;
 1076:     if (($ccuname eq '') || ($ccdomain eq '')) {
 1077:         my $usermsg = &mt('No username and/or domain provided.');
 1078:         $env{'form.phase'} = '';
 1079: 	&print_username_entry_form($r,$context,$usermsg,'','',$crstype,$brcrum);
 1080:         return;
 1081:     }
 1082:     my ($form,$formname);
 1083:     if ($env{'form.action'} eq 'singlestudent') {
 1084:         $form = 'document.enrollstudent';
 1085:         $formname = 'enrollstudent';
 1086:     } else {
 1087:         $form = 'document.cu';
 1088:         $formname = 'cu';
 1089:     }
 1090:     my %abv_auth = &auth_abbrev();
 1091:     my (%rulematch,%inst_results,$newuser,%alerts,%curr_rules,%got_rules);
 1092:     my $uhome=&Apache::lonnet::homeserver($ccuname,$ccdomain);
 1093:     if ($uhome eq 'no_host') {
 1094:         my $usertype;
 1095:         my ($rules,$ruleorder) =
 1096:             &Apache::lonnet::inst_userrules($ccdomain,'username');
 1097:             $usertype =
 1098:                 &Apache::lonuserutils::check_usertype($ccdomain,$ccuname,$rules,
 1099:                                                       \%curr_rules,\%got_rules);
 1100:         my $cancreate =
 1101:             &Apache::lonuserutils::can_create_user($ccdomain,$context,
 1102:                                                    $usertype);
 1103:         if (!$cancreate) {
 1104:             my $helplink = 'javascript:helpMenu('."'display'".')';
 1105:             my %usertypetext = (
 1106:                 official   => 'institutional',
 1107:                 unofficial => 'non-institutional',
 1108:             );
 1109:             my $response;
 1110:             if ($env{'form.origform'} eq 'crtusername') {
 1111:                 $response = '<span class="LC_warning">'.
 1112:                             &mt('No match found for the username [_1] in LON-CAPA domain: [_2]',
 1113:                                 '<b>'.$ccuname.'</b>',$ccdomain).
 1114:                             '</span><br />';
 1115:             }
 1116:             $response .= '<p class="LC_warning">'
 1117:                         .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
 1118:                         .' '
 1119:                         .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
 1120:                             ,'<a href="'.$helplink.'">','</a>')
 1121:                         .'</p><br />';
 1122:             $env{'form.phase'} = '';
 1123:             &print_username_entry_form($r,$context,$response,undef,undef,$crstype,$brcrum);
 1124:             return;
 1125:         }
 1126:         $newuser = 1;
 1127:         my $checkhash;
 1128:         my $checks = { 'username' => 1 };
 1129:         $checkhash->{$ccuname.':'.$ccdomain} = { 'newuser' => $newuser };
 1130:         &Apache::loncommon::user_rule_check($checkhash,$checks,
 1131:             \%alerts,\%rulematch,\%inst_results,\%curr_rules,\%got_rules);
 1132:         if (ref($alerts{'username'}) eq 'HASH') {
 1133:             if (ref($alerts{'username'}{$ccdomain}) eq 'HASH') {
 1134:                 my $domdesc =
 1135:                     &Apache::lonnet::domain($ccdomain,'description');
 1136:                 if ($alerts{'username'}{$ccdomain}{$ccuname}) {
 1137:                     my $userchkmsg;
 1138:                     if (ref($curr_rules{$ccdomain}) eq 'HASH') {  
 1139:                         $userchkmsg = 
 1140:                             &Apache::loncommon::instrule_disallow_msg('username',
 1141:                                                                  $domdesc,1).
 1142:                         &Apache::loncommon::user_rule_formats($ccdomain,
 1143:                             $domdesc,$curr_rules{$ccdomain}{'username'},
 1144:                             'username');
 1145:                     }
 1146:                     $env{'form.phase'} = '';
 1147:                     &print_username_entry_form($r,$context,$userchkmsg,undef,undef,$crstype,$brcrum);
 1148:                     return;
 1149:                 }
 1150:             }
 1151:         }
 1152:     } else {
 1153:         $newuser = 0;
 1154:     }
 1155:     if ($response) {
 1156:         $response = '<br />'.$response;
 1157:     }
 1158: 
 1159:     my $pjump_def = &Apache::lonhtmlcommon::pjump_javascript_definition();
 1160:     my $dc_setcourse_code = '';
 1161:     my $nondc_setsection_code = '';                                        
 1162:     my %loaditem;
 1163: 
 1164:     my $groupslist = &Apache::lonuserutils::get_groupslist();
 1165: 
 1166:     my $js = &validation_javascript($context,$ccdomain,$pjump_def,$crstype,
 1167:                                $groupslist,$newuser,$formname,\%loaditem);
 1168:     my %breadcrumb_text = &singleuser_breadcrumb($crstype);
 1169:     my $helpitem = 'Course_Change_Privileges';
 1170:     if ($env{'form.action'} eq 'singlestudent') {
 1171:         $helpitem = 'Course_Add_Student';
 1172:     }
 1173:     push (@{$brcrum},
 1174:         {href => "javascript:backPage($form)",
 1175:          text => $breadcrumb_text{'search'},
 1176:          faq  => 282,
 1177:          bug  => 'Instructor Interface',});
 1178:     if ($env{'form.phase'} eq 'userpicked') {
 1179:        push(@{$brcrum},
 1180:               {href => "javascript:backPage($form,'get_user_info','select')",
 1181:                text => $breadcrumb_text{'userpicked'},
 1182:                faq  => 282,
 1183:                bug  => 'Instructor Interface',});
 1184:     }
 1185:     push(@{$brcrum},
 1186:             {href => "javascript:backPage($form,'$env{'form.phase'}','modify')",
 1187:              text => $breadcrumb_text{'modify'},
 1188:              faq  => 282,
 1189:              bug  => 'Instructor Interface',
 1190:              help => $helpitem});
 1191:     my $args = {'add_entries'           => \%loaditem,
 1192:                 'bread_crumbs'          => $brcrum,
 1193:                 'bread_crumbs_component' => 'User Management'};
 1194:     if ($env{'form.popup'}) {
 1195:         $args->{'no_nav_bar'} = 1;
 1196:     }
 1197:     my $start_page =
 1198:         &Apache::loncommon::start_page('User Management',$js,$args);
 1199: 
 1200:     my $forminfo =<<"ENDFORMINFO";
 1201: <form action="/adm/createuser" method="post" name="$formname">
 1202: <input type="hidden" name="phase" value="update_user_data" />
 1203: <input type="hidden" name="ccuname" value="$ccuname" />
 1204: <input type="hidden" name="ccdomain" value="$ccdomain" />
 1205: <input type="hidden" name="pres_value"  value="" />
 1206: <input type="hidden" name="pres_type"   value="" />
 1207: <input type="hidden" name="pres_marker" value="" />
 1208: ENDFORMINFO
 1209:     my (%inccourses,$roledom,$defaultcredits);
 1210:     if ($context eq 'course') {
 1211:         $inccourses{$env{'request.course.id'}}=1;
 1212:         $roledom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 1213:         if ($showcredits) {
 1214:             $defaultcredits = &Apache::lonuserutils::get_defaultcredits();
 1215:         }
 1216:     } elsif ($context eq 'author') {
 1217:         $roledom = $env{'request.role.domain'};
 1218:     } elsif ($context eq 'domain') {
 1219:         foreach my $key (keys(%env)) {
 1220:             $roledom = $env{'request.role.domain'};
 1221:             if ($key=~/^user\.priv\.cm\.\/($roledom)\/($match_username)/) {
 1222:                 $inccourses{$1.'_'.$2}=1;
 1223:             }
 1224:         }
 1225:     } else {
 1226:         foreach my $key (keys(%env)) {
 1227: 	    if ($key=~/^user\.priv\.cm\.\/($match_domain)\/($match_username)/) {
 1228: 	        $inccourses{$1.'_'.$2}=1;
 1229:             }
 1230:         }
 1231:     }
 1232:     my $title = '';
 1233:     if ($newuser) {
 1234:         my ($portfolioform,$domroleform);
 1235:         if ((&Apache::lonnet::allowed('mpq',$env{'request.role.domain'})) ||
 1236:             (&Apache::lonnet::allowed('mut',$env{'request.role.domain'}))) {
 1237:             # Current user has quota or user tools modification privileges
 1238:             $portfolioform = '<br />'.&user_quotas($ccuname,$ccdomain);
 1239:         }
 1240:         if ((&Apache::lonnet::allowed('cau',$env{'request.role.domain'})) &&
 1241:             ($ccdomain eq $env{'request.role.domain'})) {
 1242:             $domroleform = '<br />'.&domainrole_req($ccuname,$ccdomain);
 1243:         }
 1244:         &initialize_authen_forms($ccdomain,$formname);
 1245:         my %lt=&Apache::lonlocal::texthash(
 1246:                 'lg'             => 'Login Data',
 1247:                 'hs'             => "Home Server",
 1248:         );
 1249: 	$r->print(<<ENDTITLE);
 1250: $start_page
 1251: $response
 1252: $forminfo
 1253: <script type="text/javascript" language="Javascript">
 1254: // <![CDATA[
 1255: $loginscript
 1256: // ]]>
 1257: </script>
 1258: <input type='hidden' name='makeuser' value='1' />
 1259: ENDTITLE
 1260:         if ($env{'form.action'} eq 'singlestudent') {
 1261:             if ($crstype eq 'Community') {
 1262:                 $title = &mt('Create New User [_1] in domain [_2] as a member',
 1263:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1264:             } else {
 1265:                 $title = &mt('Create New User [_1] in domain [_2] as a student',
 1266:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1267:             }
 1268:         } else {
 1269:                 $title = &mt('Create New User [_1] in domain [_2]',
 1270:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1271:         }
 1272:         $r->print('<h2>'.$title.'</h2>'."\n");
 1273:         $r->print('<div class="LC_left_float">');
 1274:         $r->print(&personal_data_display($ccuname,$ccdomain,$newuser,$context,
 1275:                                          $inst_results{$ccuname.':'.$ccdomain}));
 1276:         # Option to disable student/employee ID conflict checking not offerred for new users.
 1277:         my ($home_server_pick,$numlib) = 
 1278:             &Apache::loncommon::home_server_form_item($ccdomain,'hserver',
 1279:                                                       'default','hide');
 1280:         if ($numlib > 1) {
 1281:             $r->print("
 1282: <br />
 1283: $lt{'hs'}: $home_server_pick
 1284: <br />");
 1285:         } else {
 1286:             $r->print($home_server_pick);
 1287:         }
 1288:         if (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) {
 1289:             $r->print('<br /><h3>'.
 1290:                       &mt('User Can Request Creation of Courses/Communities in this Domain?').'</h3>'.
 1291:                       &Apache::loncommon::start_data_table().
 1292:                       &build_tools_display($ccuname,$ccdomain,
 1293:                                            'requestcourses').
 1294:                       &Apache::loncommon::end_data_table());
 1295:         }
 1296:         $r->print('</div>'."\n".'<div class="LC_left_float"><h3>'.
 1297:                   $lt{'lg'}.'</h3>');
 1298:         my ($fixedauth,$varauth,$authmsg); 
 1299:         if (ref($rulematch{$ccuname.':'.$ccdomain}) eq 'HASH') {
 1300:             my $matchedrule = $rulematch{$ccuname.':'.$ccdomain}{'username'};
 1301:             my ($rules,$ruleorder) = 
 1302:                 &Apache::lonnet::inst_userrules($ccdomain,'username');
 1303:             if (ref($rules) eq 'HASH') {
 1304:                 if (ref($rules->{$matchedrule}) eq 'HASH') {
 1305:                     my $authtype = $rules->{$matchedrule}{'authtype'};
 1306:                     if ($authtype !~ /^(krb4|krb5|int|fsys|loc)$/) {
 1307:                         $r->print(&Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc));
 1308:                     } else { 
 1309:                         my $authparm = $rules->{$matchedrule}{'authparm'};
 1310:                         $authmsg = $rules->{$matchedrule}{'authmsg'};
 1311:                         if ($authtype =~ /^krb(4|5)$/) {
 1312:                             my $ver = $1;
 1313:                             if ($authparm ne '') {
 1314:                                 $fixedauth = <<"KERB"; 
 1315: <input type="hidden" name="login" value="krb" />
 1316: <input type="hidden" name="krbver" value="$ver" />
 1317: <input type="hidden" name="krbarg" value="$authparm" />
 1318: KERB
 1319:                             }
 1320:                         } else {
 1321:                             $fixedauth = 
 1322: '<input type="hidden" name="login" value="'.$authtype.'" />'."\n";
 1323:                             if ($rules->{$matchedrule}{'authparmfixed'}) {
 1324:                                 $fixedauth .=    
 1325: '<input type="hidden" name="'.$authtype.'arg" value="'.$authparm.'" />'."\n";
 1326:                             } else {
 1327:                                 if ($authtype eq 'int') {
 1328:                                     $varauth = '<br />'.
 1329: &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>';
 1330:                                 } elsif ($authtype eq 'loc') {
 1331:                                     $varauth = '<br />'.
 1332: &mt('[_1] Local Authentication with argument [_2]','','<input type="text" name="'.$authtype.'arg" value="" />')."\n";
 1333:                                 } else {
 1334:                                     $varauth =
 1335: '<input type="text" name="'.$authtype.'arg" value="" />'."\n";
 1336:                                 }
 1337:                             }
 1338:                         }
 1339:                     }
 1340:                 } else {
 1341:                     $r->print(&Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc));
 1342:                 }
 1343:             }
 1344:             if ($authmsg) {
 1345:                 $r->print(<<ENDAUTH);
 1346: $fixedauth
 1347: $authmsg
 1348: $varauth
 1349: ENDAUTH
 1350:             }
 1351:         } else {
 1352:             $r->print(&Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc)); 
 1353:         }
 1354:         $r->print($portfolioform.$domroleform);
 1355:         if ($env{'form.action'} eq 'singlestudent') {
 1356:             $r->print(&date_sections_select($context,$newuser,$formname,
 1357:                                             $permission,$crstype,$ccuname,
 1358:                                             $ccdomain,$showcredits));
 1359:         }
 1360:         $r->print('</div><div class="LC_clear_float_footer"></div>');
 1361:     } else { # user already exists
 1362: 	$r->print($start_page.$forminfo);
 1363:         if ($env{'form.action'} eq 'singlestudent') {
 1364:             if ($crstype eq 'Community') {
 1365:                 $title = &mt('Enroll one member: [_1] in domain [_2]',
 1366:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1367:             } else {
 1368:                 $title = &mt('Enroll one student: [_1] in domain [_2]',
 1369:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1370:             }
 1371:         } else {
 1372:             $title = &mt('Modify existing user: [_1] in domain [_2]',
 1373:                              '"'.$ccuname.'"','"'.$ccdomain.'"');
 1374:         }
 1375:         $r->print('<h2>'.$title.'</h2>'."\n");
 1376:         $r->print('<div class="LC_left_float">');
 1377:         $r->print(&personal_data_display($ccuname,$ccdomain,$newuser,$context,
 1378:                                          $inst_results{$ccuname.':'.$ccdomain}));
 1379:         if (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) {
 1380:             $r->print('<br /><h3>'.&mt('User Can Request Creation of Courses/Communities in this Domain?').'</h3>'.
 1381:                       &Apache::loncommon::start_data_table());
 1382:             if ($env{'request.role.domain'} eq $ccdomain) {
 1383:                 $r->print(&build_tools_display($ccuname,$ccdomain,'requestcourses'));
 1384:             } else {
 1385:                 $r->print(&coursereq_externaluser($ccuname,$ccdomain,
 1386:                                                   $env{'request.role.domain'}));
 1387:             }
 1388:             $r->print(&Apache::loncommon::end_data_table());
 1389:         }
 1390:         $r->print('</div>');
 1391:         my @order = ('auth','quota','tools','requestauthor');
 1392:         my %user_text;
 1393:         my ($isadv,$isauthor) = 
 1394:             &Apache::lonnet::is_advanced_user($ccuname,$ccdomain);
 1395:         if ((!$isauthor) && 
 1396:             (&Apache::lonnet::allowed('cau',$env{'request.role.domain'}))
 1397:             && ($env{'request.role.domain'} eq $ccdomain)) {
 1398:             $user_text{'requestauthor'} = &domainrole_req($ccuname,$ccdomain);
 1399:         }
 1400:         $user_text{'auth'} =  &user_authentication($ccuname,$ccdomain,$formname);
 1401:         if ((&Apache::lonnet::allowed('mpq',$ccdomain)) ||
 1402:             (&Apache::lonnet::allowed('mut',$ccdomain))) {
 1403:             # Current user has quota modification privileges
 1404:             $user_text{'quota'} = &user_quotas($ccuname,$ccdomain);
 1405:         }
 1406:         if (!&Apache::lonnet::allowed('mpq',$ccdomain)) {
 1407:             if (&Apache::lonnet::allowed('mpq',$env{'request.role.domain'})) {
 1408:                 my %lt=&Apache::lonlocal::texthash(
 1409:                     'dska'  => "Disk quotas for user's portfolio and Authoring Space",
 1410:                     'youd'  => "You do not have privileges to modify the portfolio and/or Authoring Space quotas for this user.",
 1411:                     'ichr'  => "If a change is required, contact a domain coordinator for the domain",
 1412:                 );
 1413:                 $user_text{'quota'} = <<ENDNOPORTPRIV;
 1414: <h3>$lt{'dska'}</h3>
 1415: $lt{'youd'} $lt{'ichr'}: $ccdomain
 1416: ENDNOPORTPRIV
 1417:             }
 1418:         }
 1419:         if (!&Apache::lonnet::allowed('mut',$ccdomain)) {
 1420:             if (&Apache::lonnet::allowed('mut',$env{'request.role.domain'})) {
 1421:                 my %lt=&Apache::lonlocal::texthash(
 1422:                     'utav'  => "User Tools Availability",
 1423:                     'yodo'  => "You do not have privileges to modify Portfolio, Blog, WebDAV, or Personal Information Page settings for this user.",
 1424:                     'ifch'  => "If a change is required, contact a domain coordinator for the domain",
 1425:                 );
 1426:                 $user_text{'tools'} = <<ENDNOTOOLSPRIV;
 1427: <h3>$lt{'utav'}</h3>
 1428: $lt{'yodo'} $lt{'ifch'}: $ccdomain
 1429: ENDNOTOOLSPRIV
 1430:             }
 1431:         }
 1432:         my $gotdiv = 0; 
 1433:         foreach my $item (@order) {
 1434:             if ($user_text{$item} ne '') {
 1435:                 unless ($gotdiv) {
 1436:                     $r->print('<div class="LC_left_float">');
 1437:                     $gotdiv = 1;
 1438:                 }
 1439:                 $r->print('<br />'.$user_text{$item});
 1440:             }
 1441:         }
 1442:         if ($env{'form.action'} eq 'singlestudent') {
 1443:             unless ($gotdiv) {
 1444:                 $r->print('<div class="LC_left_float">');
 1445:             }
 1446:             my $credits;
 1447:             if ($showcredits) {
 1448:                 $credits = &get_user_credits($ccuname,$ccdomain,$defaultcredits);
 1449:                 if ($credits eq '') {
 1450:                     $credits = $defaultcredits;
 1451:                 }
 1452:             }
 1453:             $r->print(&date_sections_select($context,$newuser,$formname,
 1454:                                             $permission,$crstype,$ccuname,
 1455:                                             $ccdomain,$showcredits));
 1456:         }
 1457:         if ($gotdiv) {
 1458:             $r->print('</div><div class="LC_clear_float_footer"></div>');
 1459:         }
 1460:         if ($env{'form.action'} ne 'singlestudent') {
 1461:             &display_existing_roles($r,$ccuname,$ccdomain,\%inccourses,$context,
 1462:                                     $roledom,$crstype);
 1463:         }
 1464:     } ## End of new user/old user logic
 1465:     if ($env{'form.action'} eq 'singlestudent') {
 1466:         my $btntxt;
 1467:         if ($crstype eq 'Community') {
 1468:             $btntxt = &mt('Enroll Member');
 1469:         } else {
 1470:             $btntxt = &mt('Enroll Student');
 1471:         }
 1472:         $r->print('<br /><input type="button" value="'.$btntxt.'" onclick="setSections(this.form)" />'."\n");
 1473:     } else {
 1474:         $r->print('<div class="LC_left_float">'.
 1475:                   '<fieldset><legend>'.&mt('Add Roles').'</legend>');
 1476:         my $addrolesdisplay = 0;
 1477:         if ($context eq 'domain' || $context eq 'author') {
 1478:             $addrolesdisplay = &new_coauthor_roles($r,$ccuname,$ccdomain);
 1479:         }
 1480:         if ($context eq 'domain') {
 1481:             my $add_domainroles = &new_domain_roles($r,$ccdomain);
 1482:             if (!$addrolesdisplay) {
 1483:                 $addrolesdisplay = $add_domainroles;
 1484:             }
 1485:             $r->print(&course_level_dc($env{'request.role.domain'},$showcredits));
 1486:             $r->print('</fieldset></div><div class="LC_clear_float_footer"></div>'.
 1487:                       '<br /><input type="button" value="'.&mt('Save').'" onclick="setCourse()" />'."\n");
 1488:         } elsif ($context eq 'author') {
 1489:             if ($addrolesdisplay) {
 1490:                 $r->print('</fieldset></div><div class="LC_clear_float_footer"></div>'.
 1491:                           '<br /><input type="button" value="'.&mt('Save').'"');
 1492:                 if ($newuser) {
 1493:                     $r->print(' onclick="auth_check()" \>'."\n");
 1494:                 } else {
 1495:                     $r->print('onclick="this.form.submit()" \>'."\n");
 1496:                 }
 1497:             } else {
 1498:                 $r->print('</fieldset></div>'.
 1499:                           '<div class="LC_clear_float_footer"></div>'.
 1500:                           '<br /><a href="javascript:backPage(document.cu)">'.
 1501:                           &mt('Back to previous page').'</a>');
 1502:             }
 1503:         } else {
 1504:             $r->print(&course_level_table(\%inccourses,$showcredits,$defaultcredits));
 1505:             $r->print('</fieldset></div><div class="LC_clear_float_footer"></div>'.
 1506:                       '<br /><input type="button" value="'.&mt('Save').'" onclick="setSections(this.form)" />'."\n");
 1507:         }
 1508:     }
 1509:     $r->print(&Apache::lonhtmlcommon::echo_form_input(['phase','userrole','ccdomain','prevphase','currstate','ccuname','ccdomain']));
 1510:     $r->print('<input type="hidden" name="currstate" value="" />');
 1511:     $r->print('<input type="hidden" name="prevphase" value="'.$env{'form.phase'}.'" /></form><br /><br />');
 1512:     return;
 1513: }
 1514: 
 1515: sub singleuser_breadcrumb {
 1516:     my ($crstype) = @_;
 1517:     my %breadcrumb_text;
 1518:     if ($env{'form.action'} eq 'singlestudent') {
 1519:         if ($crstype eq 'Community') {
 1520:             $breadcrumb_text{'search'} = 'Enroll a member';
 1521:         } else {
 1522:             $breadcrumb_text{'search'} = 'Enroll a student';
 1523:         }
 1524:         $breadcrumb_text{'userpicked'} = 'Select a user',
 1525:         $breadcrumb_text{'modify'} = 'Set section/dates',
 1526:     } else {
 1527:         $breadcrumb_text{'search'} = 'Create/modify a user';
 1528:         $breadcrumb_text{'userpicked'} = 'Select a user',
 1529:         $breadcrumb_text{'modify'} = 'Set user role',
 1530:     }
 1531:     return %breadcrumb_text;
 1532: }
 1533: 
 1534: sub date_sections_select {
 1535:     my ($context,$newuser,$formname,$permission,$crstype,$ccuname,$ccdomain,
 1536:         $showcredits) = @_;
 1537:     my $credits;
 1538:     if ($showcredits) {
 1539:         my $defaultcredits = &Apache::lonuserutils::get_defaultcredits();
 1540:         $credits = &get_user_credits($ccuname,$ccdomain,$defaultcredits);
 1541:         if ($credits eq '') {
 1542:             $credits = $defaultcredits;
 1543:         }
 1544:     }
 1545:     my $cid = $env{'request.course.id'};
 1546:     my ($cnum,$cdom) = &Apache::lonuserutils::get_course_identity($cid);
 1547:     my $date_table = '<h3>'.&mt('Starting and Ending Dates').'</h3>'."\n".
 1548:         &Apache::lonuserutils::date_setting_table(undef,undef,$context,
 1549:                                                   undef,$formname,$permission);
 1550:     my $rowtitle = 'Section';
 1551:     my $secbox = '<h3>'.&mt('Section and Credits').'</h3>'."\n".
 1552:         &Apache::lonuserutils::section_picker($cdom,$cnum,'st',$rowtitle,
 1553:                                               $permission,$context,'',$crstype,
 1554:                                               $showcredits,$credits);
 1555:     my $output = $date_table.$secbox;
 1556:     return $output;
 1557: }
 1558: 
 1559: sub validation_javascript {
 1560:     my ($context,$ccdomain,$pjump_def,$crstype,$groupslist,$newuser,$formname,
 1561:         $loaditem) = @_;
 1562:     my $dc_setcourse_code = '';
 1563:     my $nondc_setsection_code = '';
 1564:     if ($context eq 'domain') {
 1565:         my $dcdom = $env{'request.role.domain'};
 1566:         $loaditem->{'onload'} = "document.cu.coursedesc.value='';";
 1567:         $dc_setcourse_code = 
 1568:             &Apache::lonuserutils::dc_setcourse_js('cu','singleuser',$context);
 1569:     } else {
 1570:         my $checkauth; 
 1571:         if (($newuser) || (&Apache::lonnet::allowed('mau',$ccdomain))) {
 1572:             $checkauth = 1;
 1573:         }
 1574:         if ($context eq 'course') {
 1575:             $nondc_setsection_code =
 1576:                 &Apache::lonuserutils::setsections_javascript($formname,$groupslist,
 1577:                                                               undef,$checkauth,
 1578:                                                               $crstype);
 1579:         }
 1580:         if ($checkauth) {
 1581:             $nondc_setsection_code .= 
 1582:                 &Apache::lonuserutils::verify_authen($formname,$context);
 1583:         }
 1584:     }
 1585:     my $js = &user_modification_js($pjump_def,$dc_setcourse_code,
 1586:                                    $nondc_setsection_code,$groupslist);
 1587:     my ($jsback,$elements) = &crumb_utilities();
 1588:     $js .= "\n".
 1589:            '<script type="text/javascript">'."\n".
 1590:            '// <![CDATA['."\n".
 1591:            $jsback."\n".
 1592:            '// ]]>'."\n".
 1593:            '</script>'."\n";
 1594:     return $js;
 1595: }
 1596: 
 1597: sub display_existing_roles {
 1598:     my ($r,$ccuname,$ccdomain,$inccourses,$context,$roledom,$crstype,
 1599:         $showcredits) = @_;
 1600:     my $now=time;
 1601:     my %lt=&Apache::lonlocal::texthash(
 1602:                     'rer'  => "Existing Roles",
 1603:                     'rev'  => "Revoke",
 1604:                     'del'  => "Delete",
 1605:                     'ren'  => "Re-Enable",
 1606:                     'rol'  => "Role",
 1607:                     'ext'  => "Extent",
 1608:                     'crd'  => "Credits",
 1609:                     'sta'  => "Start",
 1610:                     'end'  => "End",
 1611:                                        );
 1612:     my (%rolesdump,%roletext,%sortrole,%roleclass,%rolepriv);
 1613:     if ($context eq 'course' || $context eq 'author') {
 1614:         my @roles = &Apache::lonuserutils::roles_by_context($context,1,$crstype);
 1615:         my %roleshash = 
 1616:             &Apache::lonnet::get_my_roles($ccuname,$ccdomain,'userroles',
 1617:                               ['active','previous','future'],\@roles,$roledom,1);
 1618:         foreach my $key (keys(%roleshash)) {
 1619:             my ($start,$end) = split(':',$roleshash{$key});
 1620:             next if ($start eq '-1' || $end eq '-1');
 1621:             my ($rnum,$rdom,$role,$sec) = split(':',$key);
 1622:             if ($context eq 'course') {
 1623:                 next unless (($rnum eq $env{'course.'.$env{'request.course.id'}.'.num'})
 1624:                              && ($rdom eq $env{'course.'.$env{'request.course.id'}.'.domain'}));
 1625:             } elsif ($context eq 'author') {
 1626:                 next unless (($rnum eq $env{'user.name'}) && ($rdom eq $env{'request.role.domain'}));
 1627:             }
 1628:             my ($newkey,$newvalue,$newrole);
 1629:             $newkey = '/'.$rdom.'/'.$rnum;
 1630:             if ($sec ne '') {
 1631:                 $newkey .= '/'.$sec;
 1632:             }
 1633:             $newvalue = $role;
 1634:             if ($role =~ /^cr/) {
 1635:                 $newrole = 'cr';
 1636:             } else {
 1637:                 $newrole = $role;
 1638:             }
 1639:             $newkey .= '_'.$newrole;
 1640:             if ($start ne '' && $end ne '') {
 1641:                 $newvalue .= '_'.$end.'_'.$start;
 1642:             } elsif ($end ne '') {
 1643:                 $newvalue .= '_'.$end;
 1644:             }
 1645:             $rolesdump{$newkey} = $newvalue;
 1646:         }
 1647:     } else {
 1648:         %rolesdump=&Apache::lonnet::dump('roles',$ccdomain,$ccuname);
 1649:     }
 1650:     # Build up table of user roles to allow revocation and re-enabling of roles.
 1651:     my ($tmp) = keys(%rolesdump);
 1652:     return if ($tmp =~ /^(con_lost|error)/i);
 1653:     foreach my $area (sort { my $a1=join('_',(split('_',$a))[1,0]);
 1654:                                 my $b1=join('_',(split('_',$b))[1,0]);
 1655:                                 return $a1 cmp $b1;
 1656:                             } keys(%rolesdump)) {
 1657:         next if ($area =~ /^rolesdef/);
 1658:         my $envkey=$area;
 1659:         my $role = $rolesdump{$area};
 1660:         my $thisrole=$area;
 1661:         $area =~ s/\_\w\w$//;
 1662:         my ($role_code,$role_end_time,$role_start_time) =
 1663:             split(/_/,$role);
 1664: # Is this a custom role? Get role owner and title.
 1665:         my ($croleudom,$croleuname,$croletitle)=
 1666:             ($role_code=~m{^cr/($match_domain)/($match_username)/(\w+)$});
 1667:         my $allowed=0;
 1668:         my $delallowed=0;
 1669:         my $sortkey=$role_code;
 1670:         my $class='Unknown';
 1671:         my $credits='';
 1672:         if ($area =~ m{^/($match_domain)/($match_courseid)} ) {
 1673:             $class='Course';
 1674:             my ($coursedom,$coursedir) = ($1,$2);
 1675:             my $cid = $1.'_'.$2;
 1676:             # $1.'_'.$2 is the course id (eg. 103_12345abcef103l3).
 1677:             my %coursedata=
 1678:                 &Apache::lonnet::coursedescription($cid);
 1679:             if ($coursedir =~ /^$match_community$/) {
 1680:                 $class='Community';
 1681:             }
 1682:             $sortkey.="\0$coursedom";
 1683:             my $carea;
 1684:             if (defined($coursedata{'description'})) {
 1685:                 $carea=$coursedata{'description'}.
 1686:                     '<br />'.&mt('Domain').': '.$coursedom.('&nbsp;'x8).
 1687:     &Apache::loncommon::syllabuswrapper(&mt('Syllabus'),$coursedir,$coursedom);
 1688:                 $sortkey.="\0".$coursedata{'description'};
 1689:             } else {
 1690:                 if ($class eq 'Community') {
 1691:                     $carea=&mt('Unavailable community').': '.$area;
 1692:                     $sortkey.="\0".&mt('Unavailable community').': '.$area;
 1693:                 } else {
 1694:                     $carea=&mt('Unavailable course').': '.$area;
 1695:                     $sortkey.="\0".&mt('Unavailable course').': '.$area;
 1696:                 }
 1697:             }
 1698:             $sortkey.="\0$coursedir";
 1699:             $inccourses->{$cid}=1;
 1700:             if (($showcredits) && ($class eq 'Course') && ($role_code eq 'st')) {
 1701:                 my $defaultcredits = $coursedata{'internal.defaultcredits'};
 1702:                 $credits =
 1703:                     &get_user_credits($ccuname,$ccdomain,$defaultcredits,
 1704:                                       $coursedom,$coursedir);
 1705:                 if ($credits eq '') {
 1706:                     $credits = $defaultcredits;
 1707:                 }
 1708:             }
 1709:             if ((&Apache::lonnet::allowed('c'.$role_code,$coursedom.'/'.$coursedir)) ||
 1710:                 (&Apache::lonnet::allowed('c'.$role_code,$ccdomain))) {
 1711:                 $allowed=1;
 1712:             }
 1713:             unless ($allowed) {
 1714:                 my $isowner = &Apache::lonuserutils::is_courseowner($cid,$coursedata{'internal.courseowner'});
 1715:                 if ($isowner) {
 1716:                     if (($role_code eq 'co') && ($class eq 'Community')) {
 1717:                         $allowed = 1;
 1718:                     } elsif (($role_code eq 'cc') && ($class eq 'Course')) {
 1719:                         $allowed = 1;
 1720:                     }
 1721:                 }
 1722:             } 
 1723:             if ((&Apache::lonnet::allowed('dro',$coursedom)) ||
 1724:                 (&Apache::lonnet::allowed('dro',$ccdomain))) {
 1725:                 $delallowed=1;
 1726:             }
 1727: # - custom role. Needs more info, too
 1728:             if ($croletitle) {
 1729:                 if (&Apache::lonnet::allowed('ccr',$coursedom.'/'.$coursedir)) {
 1730:                     $allowed=1;
 1731:                     $thisrole.='.'.$role_code;
 1732:                 }
 1733:             }
 1734:             if ($area=~m{^/($match_domain)/($match_courseid)/(\w+)}) {
 1735:                 $carea.='<br />'.&mt('Section: [_1]',$3);
 1736:                 $sortkey.="\0$3";
 1737:                 if (!$allowed) {
 1738:                     if ($env{'request.course.sec'} eq $3) {
 1739:                         if (&Apache::lonnet::allowed('c'.$role_code,$1.'/'.$2.'/'.$3)) {
 1740:                             $allowed = 1;
 1741:                         }
 1742:                     }
 1743:                 }
 1744:             }
 1745:             $area=$carea;
 1746:         } else {
 1747:             $sortkey.="\0".$area;
 1748:             # Determine if current user is able to revoke privileges
 1749:             if ($area=~m{^/($match_domain)/}) {
 1750:                 if ((&Apache::lonnet::allowed('c'.$role_code,$1)) ||
 1751:                    (&Apache::lonnet::allowed('c'.$role_code,$ccdomain))) {
 1752:                    $allowed=1;
 1753:                 }
 1754:                 if (((&Apache::lonnet::allowed('dro',$1))  ||
 1755:                     (&Apache::lonnet::allowed('dro',$ccdomain))) &&
 1756:                     ($role_code ne 'dc')) {
 1757:                     $delallowed=1;
 1758:                 }
 1759:             } else {
 1760:                 if (&Apache::lonnet::allowed('c'.$role_code,'/')) {
 1761:                     $allowed=1;
 1762:                 }
 1763:             }
 1764:             if ($role_code eq 'ca' || $role_code eq 'au' || $role_code eq 'aa') {
 1765:                 $class='Authoring Space';
 1766:             } elsif ($role_code eq 'su') {
 1767:                 $class='System';
 1768:             } else {
 1769:                 $class='Domain';
 1770:             }
 1771:         }
 1772:         if (($role_code eq 'ca') || ($role_code eq 'aa')) {
 1773:             $area=~m{/($match_domain)/($match_username)};
 1774:             if (&Apache::lonuserutils::authorpriv($2,$1)) {
 1775:                 $allowed=1;
 1776:             } else {
 1777:                 $allowed=0;
 1778:             }
 1779:         }
 1780:         my $row = '';
 1781:         $row.= '<td>';
 1782:         my $active=1;
 1783:         $active=0 if (($role_end_time) && ($now>$role_end_time));
 1784:         if (($active) && ($allowed)) {
 1785:             $row.= '<input type="checkbox" name="rev:'.$thisrole.'" />';
 1786:         } else {
 1787:             if ($active) {
 1788:                $row.='&nbsp;';
 1789:             } else {
 1790:                $row.=&mt('expired or revoked');
 1791:             }
 1792:         }
 1793:         $row.='</td><td>';
 1794:         if ($allowed && !$active) {
 1795:             $row.= '<input type="checkbox" name="ren:'.$thisrole.'" />';
 1796:         } else {
 1797:             $row.='&nbsp;';
 1798:         }
 1799:         $row.='</td><td>';
 1800:         if ($delallowed) {
 1801:             $row.= '<input type="checkbox" name="del:'.$thisrole.'" />';
 1802:         } else {
 1803:             $row.='&nbsp;';
 1804:         }
 1805:         my $plaintext='';
 1806:         if (!$croletitle) {
 1807:             $plaintext=&Apache::lonnet::plaintext($role_code,$class);
 1808:             if (($showcredits) && ($credits ne '')) {
 1809:                 $plaintext .= '<br/ ><span class="LC_nobreak">'.
 1810:                               '<span class="LC_fontsize_small">'.
 1811:                               &mt('Credits: [_1]',$credits).
 1812:                               '</span></span>';
 1813:             }
 1814:         } else {
 1815:             $plaintext=
 1816:                 &mt('Customrole [_1][_2]defined by [_3]',
 1817:                         '"'.$croletitle.'"',
 1818:                         '<br />',
 1819:                         $croleuname.':'.$croleudom);
 1820:         }
 1821:         $row.= '</td><td>'.$plaintext.
 1822:                '</td><td>'.$area.
 1823:                '</td><td>'.($role_start_time?&Apache::lonlocal::locallocaltime($role_start_time)
 1824:                                             : '&nbsp;' ).
 1825:                '</td><td>'.($role_end_time  ?&Apache::lonlocal::locallocaltime($role_end_time)
 1826:                                             : '&nbsp;' )
 1827:                ."</td>";
 1828:         $sortrole{$sortkey}=$envkey;
 1829:         $roletext{$envkey}=$row;
 1830:         $roleclass{$envkey}=$class;
 1831:         $rolepriv{$envkey}=$allowed;
 1832:     } # end of foreach        (table building loop)
 1833: 
 1834:     my $rolesdisplay = 0;
 1835:     my %output = ();
 1836:     foreach my $type ('Authoring Space','Course','Community','Domain','System','Unknown') {
 1837:         $output{$type} = '';
 1838:         foreach my $which (sort {uc($a) cmp uc($b)} (keys(%sortrole))) {
 1839:             if ( ($roleclass{$sortrole{$which}} =~ /^\Q$type\E/ ) && ($rolepriv{$sortrole{$which}}) ) {
 1840:                  $output{$type}.=
 1841:                       &Apache::loncommon::start_data_table_row().
 1842:                       $roletext{$sortrole{$which}}.
 1843:                       &Apache::loncommon::end_data_table_row();
 1844:             }
 1845:         }
 1846:         unless($output{$type} eq '') {
 1847:             $output{$type} = '<tr class="LC_info_row">'.
 1848:                       "<td align='center' colspan='7'>".&mt($type)."</td></tr>".
 1849:                       $output{$type};
 1850:             $rolesdisplay = 1;
 1851:         }
 1852:     }
 1853:     if ($rolesdisplay == 1) {
 1854:         my $contextrole='';
 1855:         if ($env{'request.course.id'}) {
 1856:             if (&Apache::loncommon::course_type() eq 'Community') {
 1857:                 $contextrole = &mt('Existing Roles in this Community');
 1858:             } else {
 1859:                 $contextrole = &mt('Existing Roles in this Course');
 1860:             }
 1861:         } elsif ($env{'request.role'} =~ /^au\./) {
 1862:             $contextrole = &mt('Existing Co-Author Roles in your Authoring Space');
 1863:         } else {
 1864:             $contextrole = &mt('Existing Roles in this Domain');
 1865:         }
 1866:         $r->print('<div class="LC_left_float">'.
 1867: '<fieldset><legend>'.$contextrole.'</legend>'.
 1868: &Apache::loncommon::start_data_table("LC_createuser").
 1869: &Apache::loncommon::start_data_table_header_row().
 1870: '<th>'.$lt{'rev'}.'</th><th>'.$lt{'ren'}.'</th><th>'.$lt{'del'}.
 1871: '</th><th>'.$lt{'rol'}.'</th><th>'.$lt{'ext'}.
 1872: '</th><th>'.$lt{'sta'}.'</th><th>'.$lt{'end'}.'</th>'.
 1873: &Apache::loncommon::end_data_table_header_row());
 1874:         foreach my $type ('Authoring Space','Course','Community','Domain','System','Unknown') {
 1875:             if ($output{$type}) {
 1876:                 $r->print($output{$type}."\n");
 1877:             }
 1878:         }
 1879:         $r->print(&Apache::loncommon::end_data_table().
 1880:                   '</fieldset></div>');
 1881:     }
 1882:     return;
 1883: }
 1884: 
 1885: sub new_coauthor_roles {
 1886:     my ($r,$ccuname,$ccdomain) = @_;
 1887:     my $addrolesdisplay = 0;
 1888:     #
 1889:     # Co-Author
 1890:     #
 1891:     if (&Apache::lonuserutils::authorpriv($env{'user.name'},
 1892:                                           $env{'request.role.domain'}) &&
 1893:         ($env{'user.name'} ne $ccuname || $env{'user.domain'} ne $ccdomain)) {
 1894:         # No sense in assigning co-author role to yourself
 1895:         $addrolesdisplay = 1;
 1896:         my $cuname=$env{'user.name'};
 1897:         my $cudom=$env{'request.role.domain'};
 1898:         my %lt=&Apache::lonlocal::texthash(
 1899:                     'cs'   => "Authoring Space",
 1900:                     'act'  => "Activate",
 1901:                     'rol'  => "Role",
 1902:                     'ext'  => "Extent",
 1903:                     'sta'  => "Start",
 1904:                     'end'  => "End",
 1905:                     'cau'  => "Co-Author",
 1906:                     'caa'  => "Assistant Co-Author",
 1907:                     'ssd'  => "Set Start Date",
 1908:                     'sed'  => "Set End Date"
 1909:                                        );
 1910:         $r->print('<h4>'.$lt{'cs'}.'</h4>'."\n".
 1911:                   &Apache::loncommon::start_data_table()."\n".
 1912:                   &Apache::loncommon::start_data_table_header_row()."\n".
 1913:                   '<th>'.$lt{'act'}.'</th><th>'.$lt{'rol'}.'</th>'.
 1914:                   '<th>'.$lt{'ext'}.'</th><th>'.$lt{'sta'}.'</th>'.
 1915:                   '<th>'.$lt{'end'}.'</th>'."\n".
 1916:                   &Apache::loncommon::end_data_table_header_row()."\n".
 1917:                   &Apache::loncommon::start_data_table_row().'
 1918:            <td>
 1919:             <input type="checkbox" name="act_'.$cudom.'_'.$cuname.'_ca" />
 1920:            </td>
 1921:            <td>'.$lt{'cau'}.'</td>
 1922:            <td>'.$cudom.'_'.$cuname.'</td>
 1923:            <td><input type="hidden" name="start_'.$cudom.'_'.$cuname.'_ca" value="" />
 1924:              <a href=
 1925: "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>
 1926: <td><input type="hidden" name="end_'.$cudom.'_'.$cuname.'_ca" value="" />
 1927: <a href=
 1928: "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".
 1929:               &Apache::loncommon::end_data_table_row()."\n".
 1930:               &Apache::loncommon::start_data_table_row()."\n".
 1931: '<td><input type="checkbox" name="act_'.$cudom.'_'.$cuname.'_aa" /></td>
 1932: <td>'.$lt{'caa'}.'</td>
 1933: <td>'.$cudom.'_'.$cuname.'</td>
 1934: <td><input type="hidden" name="start_'.$cudom.'_'.$cuname.'_aa" value="" />
 1935: <a href=
 1936: "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>
 1937: <td><input type="hidden" name="end_'.$cudom.'_'.$cuname.'_aa" value="" />
 1938: <a href=
 1939: "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".
 1940:              &Apache::loncommon::end_data_table_row()."\n".
 1941:              &Apache::loncommon::end_data_table());
 1942:     } elsif ($env{'request.role'} =~ /^au\./) {
 1943:         if (!(&Apache::lonuserutils::authorpriv($env{'user.name'},
 1944:                                                 $env{'request.role.domain'}))) {
 1945:             $r->print('<span class="LC_error">'.
 1946:                       &mt('You do not have privileges to assign co-author roles.').
 1947:                       '</span>');
 1948:         } elsif (($env{'user.name'} eq $ccuname) &&
 1949:              ($env{'user.domain'} eq $ccdomain)) {
 1950:             $r->print(&mt('Assigning yourself a co-author or assistant co-author role in your own author area in Authoring Space is not permitted'));
 1951:         }
 1952:     }
 1953:     return $addrolesdisplay;;
 1954: }
 1955: 
 1956: sub new_domain_roles {
 1957:     my ($r,$ccdomain) = @_;
 1958:     my $addrolesdisplay = 0;
 1959:     #
 1960:     # Domain level
 1961:     #
 1962:     my $num_domain_level = 0;
 1963:     my $domaintext =
 1964:     '<h4>'.&mt('Domain Level').'</h4>'.
 1965:     &Apache::loncommon::start_data_table().
 1966:     &Apache::loncommon::start_data_table_header_row().
 1967:     '<th>'.&mt('Activate').'</th><th>'.&mt('Role').'</th><th>'.
 1968:     &mt('Extent').'</th>'.
 1969:     '<th>'.&mt('Start').'</th><th>'.&mt('End').'</th>'.
 1970:     &Apache::loncommon::end_data_table_header_row();
 1971:     my @allroles = &Apache::lonuserutils::roles_by_context('domain');
 1972:     foreach my $thisdomain (sort(&Apache::lonnet::all_domains())) {
 1973:         foreach my $role (@allroles) {
 1974:             next if ($role eq 'ad');
 1975:             next if (($role eq 'au') && ($ccdomain ne $thisdomain));
 1976:             if (&Apache::lonnet::allowed('c'.$role,$thisdomain)) {
 1977:                my $plrole=&Apache::lonnet::plaintext($role);
 1978:                my %lt=&Apache::lonlocal::texthash(
 1979:                     'ssd'  => "Set Start Date",
 1980:                     'sed'  => "Set End Date"
 1981:                                        );
 1982:                $num_domain_level ++;
 1983:                $domaintext .=
 1984: &Apache::loncommon::start_data_table_row().
 1985: '<td><input type="checkbox" name="act_'.$thisdomain.'_'.$role.'" /></td>
 1986: <td>'.$plrole.'</td>
 1987: <td>'.$thisdomain.'</td>
 1988: <td><input type="hidden" name="start_'.$thisdomain.'_'.$role.'" value="" />
 1989: <a href=
 1990: "javascript:pjump('."'date_start','Start Date $plrole',document.cu.start_$thisdomain\_$role.value,'start_$thisdomain\_$role','cu.pres','dateset'".')">'.$lt{'ssd'}.'</a></td>
 1991: <td><input type="hidden" name="end_'.$thisdomain.'_'.$role.'" value="" />
 1992: <a href=
 1993: "javascript:pjump('."'date_end','End Date $plrole',document.cu.end_$thisdomain\_$role.value,'end_$thisdomain\_$role','cu.pres','dateset'".')">'.$lt{'sed'}.'</a></td>'.
 1994: &Apache::loncommon::end_data_table_row();
 1995:             }
 1996:         }
 1997:     }
 1998:     $domaintext.= &Apache::loncommon::end_data_table();
 1999:     if ($num_domain_level > 0) {
 2000:         $r->print($domaintext);
 2001:         $addrolesdisplay = 1;
 2002:     }
 2003:     return $addrolesdisplay;
 2004: }
 2005: 
 2006: sub user_authentication {
 2007:     my ($ccuname,$ccdomain,$formname) = @_;
 2008:     my $currentauth=&Apache::lonnet::queryauthenticate($ccuname,$ccdomain);
 2009:     my $outcome;
 2010:     # Check for a bad authentication type
 2011:     if ($currentauth !~ /^(krb4|krb5|unix|internal|localauth):/) {
 2012:         # bad authentication scheme
 2013:         my %lt=&Apache::lonlocal::texthash(
 2014:                        'err'   => "ERROR",
 2015:                        'uuas'  => "This user has an unrecognized authentication scheme",
 2016:                        'adcs'  => "Please alert a domain coordinator of this situation",
 2017:                        'sldb'  => "Please specify login data below",
 2018:                        'ld'    => "Login Data"
 2019:         );
 2020:         if (&Apache::lonnet::allowed('mau',$ccdomain)) {
 2021:             &initialize_authen_forms($ccdomain,$formname);
 2022: 
 2023:             my $choices = &Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc);
 2024:             $outcome = <<ENDBADAUTH;
 2025: <script type="text/javascript" language="Javascript">
 2026: // <![CDATA[
 2027: $loginscript
 2028: // ]]>
 2029: </script>
 2030: <span class="LC_error">$lt{'err'}:
 2031: $lt{'uuas'} ($currentauth). $lt{'sldb'}.</span>
 2032: <h3>$lt{'ld'}</h3>
 2033: $choices
 2034: ENDBADAUTH
 2035:         } else {
 2036:             # This user is not allowed to modify the user's
 2037:             # authentication scheme, so just notify them of the problem
 2038:             $outcome = <<ENDBADAUTH;
 2039: <span class="LC_error"> $lt{'err'}: 
 2040: $lt{'uuas'} ($currentauth). $lt{'adcs'}.
 2041: </span>
 2042: ENDBADAUTH
 2043:         }
 2044:     } else { # Authentication type is valid
 2045:         &initialize_authen_forms($ccdomain,$formname,$currentauth,'modifyuser');
 2046:         my ($authformcurrent,$can_modify,@authform_others) =
 2047:             &modify_login_block($ccdomain,$currentauth);
 2048:         if (&Apache::lonnet::allowed('mau',$ccdomain)) {
 2049:             # Current user has login modification privileges
 2050:             my %lt=&Apache::lonlocal::texthash (
 2051:                            'ld'    => "Login Data",
 2052:                            'ccld'  => "Change Current Login Data",
 2053:                            'enld'  => "Enter New Login Data"
 2054:                                                );
 2055:             $outcome =
 2056:                        '<script type="text/javascript" language="Javascript">'."\n".
 2057:                        '// <![CDATA['."\n".
 2058:                        $loginscript."\n".
 2059:                        '// ]]>'."\n".
 2060:                        '</script>'."\n".
 2061:                        '<h3>'.$lt{'ld'}.'</h3>'.
 2062:                        &Apache::loncommon::start_data_table().
 2063:                        &Apache::loncommon::start_data_table_row().
 2064:                        '<td>'.$authformnop;
 2065:             if ($can_modify) {
 2066:                 $outcome .= '</td>'."\n".
 2067:                             &Apache::loncommon::end_data_table_row().
 2068:                             &Apache::loncommon::start_data_table_row().
 2069:                             '<td>'.$authformcurrent.'</td>'.
 2070:                             &Apache::loncommon::end_data_table_row()."\n";
 2071:             } else {
 2072:                 $outcome .= '&nbsp;('.$authformcurrent.')</td>'.
 2073:                             &Apache::loncommon::end_data_table_row()."\n";
 2074:             }
 2075:             foreach my $item (@authform_others) { 
 2076:                 $outcome .= &Apache::loncommon::start_data_table_row().
 2077:                             '<td>'.$item.'</td>'.
 2078:                             &Apache::loncommon::end_data_table_row()."\n";
 2079:             }
 2080:             $outcome .= &Apache::loncommon::end_data_table();
 2081:         } else {
 2082:             if (&Apache::lonnet::allowed('mau',$env{'request.role.domain'})) {
 2083:                 my %lt=&Apache::lonlocal::texthash(
 2084:                            'ccld'  => "Change Current Login Data",
 2085:                            'yodo'  => "You do not have privileges to modify the authentication configuration for this user.",
 2086:                            'ifch'  => "If a change is required, contact a domain coordinator for the domain",
 2087:                 );
 2088:                 $outcome .= <<ENDNOPRIV;
 2089: <h3>$lt{'ccld'}</h3>
 2090: $lt{'yodo'} $lt{'ifch'}: $ccdomain
 2091: <input type="hidden" name="login" value="nochange" />
 2092: ENDNOPRIV
 2093:             }
 2094:         }
 2095:     }  ## End of "check for bad authentication type" logic
 2096:     return $outcome;
 2097: }
 2098: 
 2099: sub modify_login_block {
 2100:     my ($dom,$currentauth) = @_;
 2101:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 2102:     my ($authnum,%can_assign) =
 2103:         &Apache::loncommon::get_assignable_auth($dom);
 2104:     my ($authformcurrent,@authform_others,$show_override_msg);
 2105:     if ($currentauth=~/^krb(4|5):/) {
 2106:         $authformcurrent=$authformkrb;
 2107:         if ($can_assign{'int'}) {
 2108:             push(@authform_others,$authformint);
 2109:         }
 2110:         if ($can_assign{'loc'}) {
 2111:             push(@authform_others,$authformloc);
 2112:         }
 2113:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2114:             $show_override_msg = 1;
 2115:         }
 2116:     } elsif ($currentauth=~/^internal:/) {
 2117:         $authformcurrent=$authformint;
 2118:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2119:             push(@authform_others,$authformkrb);
 2120:         }
 2121:         if ($can_assign{'loc'}) {
 2122:             push(@authform_others,$authformloc);
 2123:         }
 2124:         if ($can_assign{'int'}) {
 2125:             $show_override_msg = 1;
 2126:         }
 2127:     } elsif ($currentauth=~/^unix:/) {
 2128:         $authformcurrent=$authformfsys;
 2129:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2130:             push(@authform_others,$authformkrb);
 2131:         }
 2132:         if ($can_assign{'int'}) {
 2133:             push(@authform_others,$authformint);
 2134:         }
 2135:         if ($can_assign{'loc'}) {
 2136:             push(@authform_others,$authformloc);
 2137:         }
 2138:         if ($can_assign{'fsys'}) {
 2139:             $show_override_msg = 1;
 2140:         }
 2141:     } elsif ($currentauth=~/^localauth:/) {
 2142:         $authformcurrent=$authformloc;
 2143:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2144:             push(@authform_others,$authformkrb);
 2145:         }
 2146:         if ($can_assign{'int'}) {
 2147:             push(@authform_others,$authformint);
 2148:         }
 2149:         if ($can_assign{'loc'}) {
 2150:             $show_override_msg = 1;
 2151:         }
 2152:     }
 2153:     if ($show_override_msg) {
 2154:         $authformcurrent = '<table><tr><td colspan="3">'.$authformcurrent.
 2155:                            '</td></tr>'."\n".
 2156:                            '<tr><td>&nbsp;&nbsp;&nbsp;</td>'.
 2157:                            '<td><b>'.&mt('Currently in use').'</b></td>'.
 2158:                            '<td align="right"><span class="LC_cusr_emph">'.
 2159:                             &mt('will override current values').
 2160:                             '</span></td></tr></table>';
 2161:     }
 2162:     return ($authformcurrent,$show_override_msg,@authform_others); 
 2163: }
 2164: 
 2165: sub personal_data_display {
 2166:     my ($ccuname,$ccdomain,$newuser,$context,$inst_results,$rolesarray,
 2167:         $now,$captchaform,$emailusername) = @_;
 2168:     my ($output,%userenv,%canmodify,%canmodify_status);
 2169:     my @userinfo = ('firstname','middlename','lastname','generation',
 2170:                     'permanentemail','id');
 2171:     my $rowcount = 0;
 2172:     my $editable = 0;
 2173:     my %textboxsize = (
 2174:                        firstname      => '15',
 2175:                        middlename     => '15',
 2176:                        lastname       => '15',
 2177:                        generation     => '5',
 2178:                        permanentemail => '25',
 2179:                        id             => '15',
 2180:                       );
 2181: 
 2182:     my %lt=&Apache::lonlocal::texthash(
 2183:                 'pd'             => "Personal Data",
 2184:                 'firstname'      => "First Name",
 2185:                 'middlename'     => "Middle Name",
 2186:                 'lastname'       => "Last Name",
 2187:                 'generation'     => "Generation",
 2188:                 'permanentemail' => "Permanent e-mail address",
 2189:                 'id'             => "Student/Employee ID",
 2190:                 'lg'             => "Login Data",
 2191:                 'inststatus'     => "Affiliation",
 2192:                 'email'          => 'E-mail address',
 2193:                 'valid'          => 'Validation',
 2194:     );
 2195: 
 2196:     %canmodify_status =
 2197:         &Apache::lonuserutils::can_modify_userinfo($context,$ccdomain,
 2198:                                                    ['inststatus'],$rolesarray);
 2199:     if (!$newuser) {
 2200:         # Get the users information
 2201:         %userenv = &Apache::lonnet::get('environment',
 2202:                    ['firstname','middlename','lastname','generation',
 2203:                     'permanentemail','id','inststatus'],$ccdomain,$ccuname);
 2204:         %canmodify =
 2205:             &Apache::lonuserutils::can_modify_userinfo($context,$ccdomain,
 2206:                                                        \@userinfo,$rolesarray);
 2207:     } elsif ($context eq 'selfcreate') {
 2208:         if ($newuser eq 'email') {
 2209:             if (ref($emailusername) eq 'HASH') { 
 2210:                 my ($infofields,$infotitles) = &Apache::loncommon::emailusername_info();
 2211:                 @userinfo = ();          
 2212:                 if ((ref($infofields) eq 'ARRAY') && (ref($infotitles) eq 'HASH')) {
 2213:                     foreach my $field (@{$infofields}) { 
 2214:                         if ($emailusername->{$field}) {
 2215:                             push(@userinfo,$field);
 2216:                             $canmodify{$field} = 1;
 2217:                             unless ($textboxsize{$field}) {
 2218:                                 $textboxsize{$field} = 25;
 2219:                             }
 2220:                             unless ($lt{$field}) {
 2221:                                 $lt{$field} = $infotitles->{$field};
 2222:                             }
 2223:                         }
 2224:                     }
 2225:                 }
 2226:             }
 2227:         } else {
 2228:             %canmodify = &selfcreate_canmodify($context,$ccdomain,\@userinfo,
 2229:                                                $inst_results,$rolesarray);
 2230:         }
 2231:     }
 2232: 
 2233:     my $genhelp=&Apache::loncommon::help_open_topic('Generation');
 2234:     $output = '<h3>'.$lt{'pd'}.'</h3>'.
 2235:               &Apache::lonhtmlcommon::start_pick_box();
 2236:     if (($context eq 'selfcreate') && ($newuser eq 'email')) {
 2237:         $output .= &Apache::lonhtmlcommon::row_title($lt{'email'},undef,
 2238:                                                      'LC_oddrow_value')."\n".
 2239:                    '<input type="text" name="uname" size="25" value="" />';
 2240:         $rowcount ++;
 2241:         $output .= &Apache::lonhtmlcommon::row_closure(1);
 2242:         my $upassone = '<input type="password" name="upass'.$now.'" size="10" />';
 2243:         my $upasstwo = '<input type="password" name="upasscheck'.$now.'" size="10" />';
 2244:         $output .= &Apache::lonhtmlcommon::row_title(&mt('Password'),
 2245:                                                     'LC_pick_box_title',
 2246:                                                     'LC_oddrow_value')."\n".
 2247:                    $upassone."\n".
 2248:                    &Apache::lonhtmlcommon::row_closure(1)."\n".
 2249:                    &Apache::lonhtmlcommon::row_title(&mt('Confirm password'),
 2250:                                                      'LC_pick_box_title',
 2251:                                                      'LC_oddrow_value')."\n".
 2252:                    $upasstwo.
 2253:                    &Apache::lonhtmlcommon::row_closure()."\n";
 2254:     }
 2255:     foreach my $item (@userinfo) {
 2256:         my $rowtitle = $lt{$item};
 2257:         my $hiderow = 0;
 2258:         if ($item eq 'generation') {
 2259:             $rowtitle = $genhelp.$rowtitle;
 2260:         }
 2261:         my $row = &Apache::lonhtmlcommon::row_title($rowtitle,undef,'LC_oddrow_value')."\n";
 2262:         if ($newuser) {
 2263:             if (ref($inst_results) eq 'HASH') {
 2264:                 if ($inst_results->{$item} ne '') {
 2265:                     $row .= '<input type="hidden" name="c'.$item.'" value="'.$inst_results->{$item}.'" />'.$inst_results->{$item};
 2266:                 } else {
 2267:                     if ($context eq 'selfcreate') {
 2268:                         if ($canmodify{$item}) {
 2269:                             $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="" />';
 2270:                             $editable ++;
 2271:                         } else {
 2272:                             $hiderow = 1;
 2273:                         }
 2274:                     } else {
 2275:                         $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="" />';
 2276:                     }
 2277:                 }
 2278:             } else {
 2279:                 if ($context eq 'selfcreate') {
 2280:                     if (($item eq 'permanentemail') && ($newuser eq 'email')) {
 2281:                         $row .= $ccuname;
 2282:                     } else {
 2283:                         if ($canmodify{$item}) {
 2284:                             if ($newuser eq 'email') {
 2285:                                 $row .= '<input type="text" name="'.$item.'" size="'.$textboxsize{$item}.'" value="" />';
 2286:                             } else {
 2287:                                 $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="" />';
 2288:                             }
 2289:                             $editable ++;
 2290:                         } else {
 2291:                             $hiderow = 1;
 2292:                         }
 2293:                     }
 2294:                 } else {
 2295:                     $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="" />';
 2296:                 }
 2297:             }
 2298:         } else {
 2299:             if ($canmodify{$item}) {
 2300:                 $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="'.$userenv{$item}.'" />';
 2301:                 if (($item eq 'id') && (!$newuser)) {
 2302:                     $row .= '<br />'.&Apache::lonuserutils::forceid_change($context);
 2303:                 }
 2304:             } else {
 2305:                 $row .= $userenv{$item};
 2306:             }
 2307:         }
 2308:         $row .= &Apache::lonhtmlcommon::row_closure(1);
 2309:         if (!$hiderow) {
 2310:             $output .= $row;
 2311:             $rowcount ++;
 2312:         }
 2313:     }
 2314:     if (($canmodify_status{'inststatus'}) || ($context ne 'selfcreate')) {
 2315:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($ccdomain);
 2316:         if (ref($types) eq 'ARRAY') {
 2317:             if (@{$types} > 0) {
 2318:                 my ($hiderow,$shown);
 2319:                 if ($canmodify_status{'inststatus'}) {
 2320:                     $shown = &pick_inst_statuses($userenv{'inststatus'},$usertypes,$types);
 2321:                 } else {
 2322:                     if ($userenv{'inststatus'} eq '') {
 2323:                         $hiderow = 1;
 2324:                     } else {
 2325:                         my @showitems;
 2326:                         foreach my $item ( map { &unescape($_); } split(':',$userenv{'inststatus'})) {
 2327:                             if (exists($usertypes->{$item})) {
 2328:                                 push(@showitems,$usertypes->{$item});
 2329:                             } else {
 2330:                                 push(@showitems,$item);
 2331:                             }
 2332:                         }
 2333:                         if (@showitems) {
 2334:                             $shown = join(', ',@showitems);
 2335:                         } else {
 2336:                             $hiderow = 1;
 2337:                         }
 2338:                     }
 2339:                 }
 2340:                 if (!$hiderow) {
 2341:                     my $row = &Apache::lonhtmlcommon::row_title(&mt('Affiliations'),undef,'LC_oddrow_value')."\n".
 2342:                               $shown.&Apache::lonhtmlcommon::row_closure(1); 
 2343:                     if ($context eq 'selfcreate') {
 2344:                         $rowcount ++;
 2345:                     }
 2346:                     $output .= $row;
 2347:                 }
 2348:             }
 2349:         }
 2350:     }
 2351:     if (($context eq 'selfcreate') && ($newuser eq 'email')) {
 2352:         if ($captchaform) {
 2353:             $output .= &Apache::lonhtmlcommon::row_title($lt{'valid'},
 2354:                                                          'LC_pick_box_title')."\n".
 2355:                        $captchaform."\n".'<br /><br />'.
 2356:                        &Apache::lonhtmlcommon::row_closure(1); 
 2357:             $rowcount ++;
 2358:         }
 2359:         my $submit_text = &mt('Create account');
 2360:         $output .= &Apache::lonhtmlcommon::row_title()."\n".
 2361:                    '<br /><input type="submit" name="createaccount" value="'.
 2362:                    $submit_text.'" />'.
 2363:                    &Apache::lonhtmlcommon::row_closure(1);
 2364:     }
 2365:     $output .= &Apache::lonhtmlcommon::end_pick_box();
 2366:     if (wantarray) {
 2367:         if ($context eq 'selfcreate') {
 2368:             return($output,$rowcount,$editable);
 2369:         } else {
 2370:             return $output;
 2371:         }
 2372:     } else {
 2373:         return $output;
 2374:     }
 2375: }
 2376: 
 2377: sub pick_inst_statuses {
 2378:     my ($curr,$usertypes,$types) = @_;
 2379:     my ($output,$rem,@currtypes);
 2380:     if ($curr ne '') {
 2381:         @currtypes = map { &unescape($_); } split(/:/,$curr);
 2382:     }
 2383:     my $numinrow = 2;
 2384:     if (ref($types) eq 'ARRAY') {
 2385:         $output = '<table>';
 2386:         my $lastcolspan; 
 2387:         for (my $i=0; $i<@{$types}; $i++) {
 2388:             if (defined($usertypes->{$types->[$i]})) {
 2389:                 my $rem = $i%($numinrow);
 2390:                 if ($rem == 0) {
 2391:                     if ($i<@{$types}-1) {
 2392:                         if ($i > 0) { 
 2393:                             $output .= '</tr>';
 2394:                         }
 2395:                         $output .= '<tr>';
 2396:                     }
 2397:                 } elsif ($i==@{$types}-1) {
 2398:                     my $colsleft = $numinrow - $rem;
 2399:                     if ($colsleft > 1) {
 2400:                         $lastcolspan = ' colspan="'.$colsleft.'"';
 2401:                     }
 2402:                 }
 2403:                 my $check = ' ';
 2404:                 if (grep(/^\Q$types->[$i]\E$/,@currtypes)) {
 2405:                     $check = ' checked="checked" ';
 2406:                 }
 2407:                 $output .= '<td class="LC_left_item"'.$lastcolspan.'>'.
 2408:                            '<span class="LC_nobreak"><label>'.
 2409:                            '<input type="checkbox" name="inststatus" '.
 2410:                            'value="'.$types->[$i].'"'.$check.'/>'.
 2411:                            $usertypes->{$types->[$i]}.'</label></span></td>';
 2412:             }
 2413:         }
 2414:         $output .= '</tr></table>';
 2415:     }
 2416:     return $output;
 2417: }
 2418: 
 2419: sub selfcreate_canmodify {
 2420:     my ($context,$dom,$userinfo,$inst_results,$rolesarray) = @_;
 2421:     if (ref($inst_results) eq 'HASH') {
 2422:         my @inststatuses = &get_inststatuses($inst_results);
 2423:         if (@inststatuses == 0) {
 2424:             @inststatuses = ('default');
 2425:         }
 2426:         $rolesarray = \@inststatuses;
 2427:     }
 2428:     my %canmodify =
 2429:         &Apache::lonuserutils::can_modify_userinfo($context,$dom,$userinfo,
 2430:                                                    $rolesarray);
 2431:     return %canmodify;
 2432: }
 2433: 
 2434: sub get_inststatuses {
 2435:     my ($insthashref) = @_;
 2436:     my @inststatuses = ();
 2437:     if (ref($insthashref) eq 'HASH') {
 2438:         if (ref($insthashref->{'inststatus'}) eq 'ARRAY') {
 2439:             @inststatuses = @{$insthashref->{'inststatus'}};
 2440:         }
 2441:     }
 2442:     return @inststatuses;
 2443: }
 2444: 
 2445: # ================================================================= Phase Three
 2446: sub update_user_data {
 2447:     my ($r,$context,$crstype,$brcrum,$showcredits) = @_; 
 2448:     my $uhome=&Apache::lonnet::homeserver($env{'form.ccuname'},
 2449:                                           $env{'form.ccdomain'});
 2450:     # Error messages
 2451:     my $error     = '<span class="LC_error">'.&mt('Error').': ';
 2452:     my $end       = '</span><br /><br />';
 2453:     my $rtnlink   = '<a href="javascript:backPage(document.userupdate,'.
 2454:                     "'$env{'form.prevphase'}','modify')".'" />'.
 2455:                     &mt('Return to previous page').'</a>'.
 2456:                     &Apache::loncommon::end_page();
 2457:     my $now = time;
 2458:     my $title;
 2459:     if (exists($env{'form.makeuser'})) {
 2460: 	$title='Set Privileges for New User';
 2461:     } else {
 2462:         $title='Modify User Privileges';
 2463:     }
 2464:     my $newuser = 0;
 2465:     my ($jsback,$elements) = &crumb_utilities();
 2466:     my $jscript = '<script type="text/javascript">'."\n".
 2467:                   '// <![CDATA['."\n".
 2468:                   $jsback."\n".
 2469:                   '// ]]>'."\n".
 2470:                   '</script>'."\n";
 2471:     my %breadcrumb_text = &singleuser_breadcrumb($crstype);
 2472:     push (@{$brcrum},
 2473:              {href => "javascript:backPage(document.userupdate)",
 2474:               text => $breadcrumb_text{'search'},
 2475:               faq  => 282,
 2476:               bug  => 'Instructor Interface',}
 2477:              );
 2478:     if ($env{'form.prevphase'} eq 'userpicked') {
 2479:         push(@{$brcrum},
 2480:                {href => "javascript:backPage(document.userupdate,'get_user_info','select')",
 2481:                 text => $breadcrumb_text{'userpicked'},
 2482:                 faq  => 282,
 2483:                 bug  => 'Instructor Interface',});
 2484:     }
 2485:     my $helpitem = 'Course_Change_Privileges';
 2486:     if ($env{'form.action'} eq 'singlestudent') {
 2487:         $helpitem = 'Course_Add_Student';
 2488:     }
 2489:     push(@{$brcrum}, 
 2490:             {href => "javascript:backPage(document.userupdate,'$env{'form.prevphase'}','modify')",
 2491:              text => $breadcrumb_text{'modify'},
 2492:              faq  => 282,
 2493:              bug  => 'Instructor Interface',},
 2494:             {href => "/adm/createuser",
 2495:              text => "Result",
 2496:              faq  => 282,
 2497:              bug  => 'Instructor Interface',
 2498:              help => $helpitem});
 2499:     my $args = {bread_crumbs          => $brcrum,
 2500:                 bread_crumbs_component => 'User Management'};
 2501:     if ($env{'form.popup'}) {
 2502:         $args->{'no_nav_bar'} = 1;
 2503:     }
 2504:     $r->print(&Apache::loncommon::start_page($title,$jscript,$args));
 2505:     $r->print(&update_result_form($uhome));
 2506:     # Check Inputs
 2507:     if (! $env{'form.ccuname'} ) {
 2508: 	$r->print($error.&mt('No login name specified').'.'.$end.$rtnlink);
 2509: 	return;
 2510:     }
 2511:     if (  $env{'form.ccuname'} ne 
 2512: 	  &LONCAPA::clean_username($env{'form.ccuname'}) ) {
 2513: 	$r->print($error.&mt('Invalid login name.').'  '.
 2514: 		  &mt('Only letters, numbers, periods, dashes, @, and underscores are valid.').
 2515: 		  $end.$rtnlink);
 2516: 	return;
 2517:     }
 2518:     if (! $env{'form.ccdomain'}       ) {
 2519: 	$r->print($error.&mt('No domain specified').'.'.$end.$rtnlink);
 2520: 	return;
 2521:     }
 2522:     if (  $env{'form.ccdomain'} ne
 2523: 	  &LONCAPA::clean_domain($env{'form.ccdomain'}) ) {
 2524: 	$r->print($error.&mt('Invalid domain name.').'  '.
 2525: 		  &mt('Only letters, numbers, periods, dashes, and underscores are valid.').
 2526: 		  $end.$rtnlink);
 2527: 	return;
 2528:     }
 2529:     if ($uhome eq 'no_host') {
 2530:         $newuser = 1;
 2531:     }
 2532:     if (! exists($env{'form.makeuser'})) {
 2533:         # Modifying an existing user, so check the validity of the name
 2534:         if ($uhome eq 'no_host') {
 2535:             $r->print(
 2536:                 $error
 2537:                .'<p class="LC_error">'
 2538:                .&mt('Unable to determine home server for [_1] in domain [_2].',
 2539:                         '"'.$env{'form.ccuname'}.'"','"'.$env{'form.ccdomain'}.'"')
 2540:                .'</p>');
 2541:             return;
 2542:         }
 2543:     }
 2544:     # Determine authentication method and password for the user being modified
 2545:     my $amode='';
 2546:     my $genpwd='';
 2547:     if ($env{'form.login'} eq 'krb') {
 2548: 	$amode='krb';
 2549: 	$amode.=$env{'form.krbver'};
 2550: 	$genpwd=$env{'form.krbarg'};
 2551:     } elsif ($env{'form.login'} eq 'int') {
 2552: 	$amode='internal';
 2553: 	$genpwd=$env{'form.intarg'};
 2554:     } elsif ($env{'form.login'} eq 'fsys') {
 2555: 	$amode='unix';
 2556: 	$genpwd=$env{'form.fsysarg'};
 2557:     } elsif ($env{'form.login'} eq 'loc') {
 2558: 	$amode='localauth';
 2559: 	$genpwd=$env{'form.locarg'};
 2560: 	$genpwd=" " if (!$genpwd);
 2561:     } elsif (($env{'form.login'} eq 'nochange') ||
 2562:              ($env{'form.login'} eq ''        )) { 
 2563:         # There is no need to tell the user we did not change what they
 2564:         # did not ask us to change.
 2565:         # If they are creating a new user but have not specified login
 2566:         # information this will be caught below.
 2567:     } else {
 2568:             $r->print($error.&mt('Invalid login mode or password').$end.$rtnlink);
 2569:             return;
 2570:     }
 2571: 
 2572:     $r->print('<h3>'.&mt('User [_1] in domain [_2]',
 2573:                         $env{'form.ccuname'}.' ('.&Apache::loncommon::plainname($env{'form.ccuname'},
 2574:                         $env{'form.ccdomain'}).')', $env{'form.ccdomain'}).'</h3>');
 2575:     my %prog_state = &Apache::lonhtmlcommon::Create_PrgWin($r,2);
 2576: 
 2577:     my (%alerts,%rulematch,%inst_results,%curr_rules);
 2578:     my @userinfo = ('firstname','middlename','lastname','generation','permanentemail','id');
 2579:     my @usertools = ('aboutme','blog','webdav','portfolio');
 2580:     my @requestcourses = ('official','unofficial','community','textbook');
 2581:     my @requestauthor = ('requestauthor');
 2582:     my ($othertitle,$usertypes,$types) = 
 2583:         &Apache::loncommon::sorted_inst_types($env{'form.ccdomain'});
 2584:     my %canmodify_status =
 2585:         &Apache::lonuserutils::can_modify_userinfo($context,$env{'form.ccdomain'},
 2586:                                                    ['inststatus']);
 2587:     if ($env{'form.makeuser'}) {
 2588: 	$r->print('<h3>'.&mt('Creating new account.').'</h3>');
 2589:         # Check for the authentication mode and password
 2590:         if (! $amode || ! $genpwd) {
 2591: 	    $r->print($error.&mt('Invalid login mode or password').$end.$rtnlink);    
 2592: 	    return;
 2593: 	}
 2594:         # Determine desired host
 2595:         my $desiredhost = $env{'form.hserver'};
 2596:         if (lc($desiredhost) eq 'default') {
 2597:             $desiredhost = undef;
 2598:         } else {
 2599:             my %home_servers = 
 2600: 		&Apache::lonnet::get_servers($env{'form.ccdomain'},'library');
 2601:             if (! exists($home_servers{$desiredhost})) {
 2602:                 $r->print($error.&mt('Invalid home server specified').$end.$rtnlink);
 2603:                 return;
 2604:             }
 2605:         }
 2606:         # Check ID format
 2607:         my %checkhash;
 2608:         my %checks = ('id' => 1);
 2609:         %{$checkhash{$env{'form.ccuname'}.':'.$env{'form.ccdomain'}}} = (
 2610:             'newuser' => $newuser, 
 2611:             'id' => $env{'form.cid'},
 2612:         );
 2613:         if ($env{'form.cid'} ne '') {
 2614:             &Apache::loncommon::user_rule_check(\%checkhash,\%checks,\%alerts,
 2615:                                           \%rulematch,\%inst_results,\%curr_rules);
 2616:             if (ref($alerts{'id'}) eq 'HASH') {
 2617:                 if (ref($alerts{'id'}{$env{'form.ccdomain'}}) eq 'HASH') {
 2618:                     my $domdesc =
 2619:                         &Apache::lonnet::domain($env{'form.ccdomain'},'description');
 2620:                     if ($alerts{'id'}{$env{'form.ccdomain'}}{$env{'form.cid'}}) {
 2621:                         my $userchkmsg;
 2622:                         if (ref($curr_rules{$env{'form.ccdomain'}}) eq 'HASH') {
 2623:                             $userchkmsg  = 
 2624:                                 &Apache::loncommon::instrule_disallow_msg('id',
 2625:                                                                     $domdesc,1).
 2626:                                 &Apache::loncommon::user_rule_formats($env{'form.ccdomain'},
 2627:                                     $domdesc,$curr_rules{$env{'form.ccdomain'}}{'id'},'id');
 2628:                         }
 2629:                         $r->print($error.&mt('Invalid ID format').$end.
 2630:                                   $userchkmsg.$rtnlink);
 2631:                         return;
 2632:                     }
 2633:                 }
 2634:             }
 2635:         }
 2636:         &Apache::lonhtmlcommon::Increment_PrgWin($r, \%prog_state);
 2637: 	# Call modifyuser
 2638: 	my $result = &Apache::lonnet::modifyuser
 2639: 	    ($env{'form.ccdomain'},$env{'form.ccuname'},$env{'form.cid'},
 2640:              $amode,$genpwd,$env{'form.cfirstname'},
 2641:              $env{'form.cmiddlename'},$env{'form.clastname'},
 2642:              $env{'form.cgeneration'},undef,$desiredhost,
 2643:              $env{'form.cpermanentemail'});
 2644: 	$r->print(&mt('Generating user').': '.$result);
 2645:         $uhome = &Apache::lonnet::homeserver($env{'form.ccuname'},
 2646:                                                $env{'form.ccdomain'});
 2647:         my (%changeHash,%newcustom,%changed,%changedinfo);
 2648:         if ($uhome ne 'no_host') {
 2649:             if ($context eq 'domain') {
 2650:                 foreach my $name ('portfolio','author') {
 2651:                     if ($env{'form.custom_'.$name.'quota'} == 1) {
 2652:                         if ($env{'form.'.$name.'quota'} eq '') {
 2653:                             $newcustom{$name.'quota'} = 0;
 2654:                         } else {
 2655:                             $newcustom{$name.'quota'} = $env{'form.'.$name.'quota'};
 2656:                             $newcustom{$name.'quota'} =~ s/[^\d\.]//g;
 2657:                         }
 2658:                         if (&quota_admin($newcustom{$name.'quota'},\%changeHash,$name)) {
 2659:                             $changed{$name.'quota'} = 1;
 2660:                         }
 2661:                     }
 2662:                 }
 2663:                 foreach my $item (@usertools) {
 2664:                     if ($env{'form.custom'.$item} == 1) {
 2665:                         $newcustom{$item} = $env{'form.tools_'.$item};
 2666:                         $changed{$item} = &tool_admin($item,$newcustom{$item},
 2667:                                                      \%changeHash,'tools');
 2668:                     }
 2669:                 }
 2670:                 foreach my $item (@requestcourses) {
 2671:                     if ($env{'form.custom'.$item} == 1) {
 2672:                         $newcustom{$item} = $env{'form.crsreq_'.$item};
 2673:                         if ($env{'form.crsreq_'.$item} eq 'autolimit') {
 2674:                             $newcustom{$item} .= '=';
 2675:                             $env{'form.crsreq_'.$item.'_limit'} =~ s/\D+//g;
 2676:                             if ($env{'form.crsreq_'.$item.'_limit'}) {
 2677:                                 $newcustom{$item} .= $env{'form.crsreq_'.$item.'_limit'};
 2678:                             }
 2679:                         }
 2680:                         $changed{$item} = &tool_admin($item,$newcustom{$item},
 2681:                                                       \%changeHash,'requestcourses');
 2682:                     }
 2683:                 }
 2684:                 if ($env{'form.customrequestauthor'} == 1) {
 2685:                     $newcustom{'requestauthor'} = $env{'form.requestauthor'};
 2686:                     $changed{'requestauthor'} = &tool_admin('requestauthor',
 2687:                                                     $newcustom{'requestauthor'},
 2688:                                                     \%changeHash,'requestauthor');
 2689:                 }
 2690:             }
 2691:             if ($canmodify_status{'inststatus'}) {
 2692:                 if (exists($env{'form.inststatus'})) {
 2693:                     my @inststatuses = &Apache::loncommon::get_env_multiple('form.inststatus');
 2694:                     if (@inststatuses > 0) {
 2695:                         $changeHash{'inststatus'} = join(',',@inststatuses);
 2696:                         $changed{'inststatus'} = $changeHash{'inststatus'};
 2697:                     }
 2698:                 }
 2699:             }
 2700:             if (keys(%changed)) {
 2701:                 foreach my $item (@userinfo) {
 2702:                     $changeHash{$item}  = $env{'form.c'.$item};
 2703:                 }
 2704:                 my $chgresult =
 2705:                      &Apache::lonnet::put('environment',\%changeHash,
 2706:                                           $env{'form.ccdomain'},$env{'form.ccuname'});
 2707:             } 
 2708:         }
 2709:         $r->print('<br />'.&mt('Home server').': '.$uhome.' '.
 2710:                   &Apache::lonnet::hostname($uhome));
 2711:     } elsif (($env{'form.login'} ne 'nochange') &&
 2712:              ($env{'form.login'} ne ''        )) {
 2713: 	# Modify user privileges
 2714:         if (! $amode || ! $genpwd) {
 2715: 	    $r->print($error.'Invalid login mode or password'.$end.$rtnlink);    
 2716: 	    return;
 2717: 	}
 2718: 	# Only allow authentification modification if the person has authority
 2719: 	if (&Apache::lonnet::allowed('mau',$env{'form.ccdomain'})) {
 2720: 	    $r->print('Modifying authentication: '.
 2721:                       &Apache::lonnet::modifyuserauth(
 2722: 		       $env{'form.ccdomain'},$env{'form.ccuname'},
 2723:                        $amode,$genpwd));
 2724:             $r->print('<br />'.&mt('Home server').': '.&Apache::lonnet::homeserver
 2725: 		  ($env{'form.ccuname'},$env{'form.ccdomain'}));
 2726: 	} else {
 2727: 	    # Okay, this is a non-fatal error.
 2728: 	    $r->print($error.&mt('You do not have the authority to modify this users authentification information').'.'.$end);    
 2729: 	}
 2730:     }
 2731:     $r->rflush(); # Finish display of header before time consuming actions start
 2732:     &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state);
 2733:     ##
 2734:     my (@userroles,%userupdate,$cnum,$cdom,$defaultcredits,%namechanged);
 2735:     if ($context eq 'course') {
 2736:         ($cnum,$cdom) =
 2737:             &Apache::lonuserutils::get_course_identity();
 2738:         $crstype = &Apache::loncommon::course_type($cdom.'_'.$cnum);
 2739:         if ($showcredits) {
 2740:            $defaultcredits = &Apache::lonuserutils::get_defaultcredits($cdom,$cnum);
 2741:         }
 2742:     }
 2743:     if (! $env{'form.makeuser'} ) {
 2744:         # Check for need to change
 2745:         my %userenv = &Apache::lonnet::get
 2746:             ('environment',['firstname','middlename','lastname','generation',
 2747:              'id','permanentemail','portfolioquota','authorquota','inststatus',
 2748:              'tools.aboutme','tools.blog','tools.webdav','tools.portfolio',
 2749:              'requestcourses.official','requestcourses.unofficial',
 2750:              'requestcourses.community','requestcourses.textbook',
 2751:              'reqcrsotherdom.official','reqcrsotherdom.unofficial',
 2752:              'reqcrsotherdom.community','reqcrsotherdom.textbook',
 2753:              'requestauthor'],
 2754:               $env{'form.ccdomain'},$env{'form.ccuname'});
 2755:         my ($tmp) = keys(%userenv);
 2756:         if ($tmp =~ /^(con_lost|error)/i) { 
 2757:             %userenv = ();
 2758:         }
 2759:         my $no_forceid_alert;
 2760:         # Check to see if user information can be changed
 2761:         my %domconfig =
 2762:             &Apache::lonnet::get_dom('configuration',['usermodification'],
 2763:                                      $env{'form.ccdomain'});
 2764:         my @statuses = ('active','future');
 2765:         my %roles = &Apache::lonnet::get_my_roles($env{'form.ccuname'},$env{'form.ccdomain'},'userroles',\@statuses,undef,$env{'request.role.domain'});
 2766:         my ($auname,$audom);
 2767:         if ($context eq 'author') {
 2768:             $auname = $env{'user.name'};
 2769:             $audom = $env{'user.domain'};     
 2770:         }
 2771:         foreach my $item (keys(%roles)) {
 2772:             my ($rolenum,$roledom,$role) = split(/:/,$item,-1);
 2773:             if ($context eq 'course') {
 2774:                 if ($cnum ne '' && $cdom ne '') {
 2775:                     if ($rolenum eq $cnum && $roledom eq $cdom) {
 2776:                         if (!grep(/^\Q$role\E$/,@userroles)) {
 2777:                             push(@userroles,$role);
 2778:                         }
 2779:                     }
 2780:                 }
 2781:             } elsif ($context eq 'author') {
 2782:                 if ($rolenum eq $auname && $roledom eq $audom) {
 2783:                     if (!grep(/^\Q$role\E$/,@userroles)) { 
 2784:                         push(@userroles,$role);
 2785:                     }
 2786:                 }
 2787:             }
 2788:         }
 2789:         if ($env{'form.action'} eq 'singlestudent') {
 2790:             if (!grep(/^st$/,@userroles)) {
 2791:                 push(@userroles,'st');
 2792:             }
 2793:         } else {
 2794:             # Check for course or co-author roles being activated or re-enabled
 2795:             if ($context eq 'author' || $context eq 'course') {
 2796:                 foreach my $key (keys(%env)) {
 2797:                     if ($context eq 'author') {
 2798:                         if ($key=~/^form\.act_\Q$audom\E_\Q$auname\E_([^_]+)/) {
 2799:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 2800:                                 push(@userroles,$1);
 2801:                             }
 2802:                         } elsif ($key =~/^form\.ren\:\Q$audom\E\/\Q$auname\E_([^_]+)/) {
 2803:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 2804:                                 push(@userroles,$1);
 2805:                             }
 2806:                         }
 2807:                     } elsif ($context eq 'course') {
 2808:                         if ($key=~/^form\.act_\Q$cdom\E_\Q$cnum\E_([^_]+)/) {
 2809:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 2810:                                 push(@userroles,$1);
 2811:                             }
 2812:                         } elsif ($key =~/^form\.ren\:\Q$cdom\E\/\Q$cnum\E(\/?\w*)_([^_]+)/) {
 2813:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 2814:                                 push(@userroles,$1);
 2815:                             }
 2816:                         }
 2817:                     }
 2818:                 }
 2819:             }
 2820:         }
 2821:         #Check to see if we can change personal data for the user 
 2822:         my (@mod_disallowed,@longroles);
 2823:         foreach my $role (@userroles) {
 2824:             if ($role eq 'cr') {
 2825:                 push(@longroles,'Custom');
 2826:             } else {
 2827:                 push(@longroles,&Apache::lonnet::plaintext($role,$crstype)); 
 2828:             }
 2829:         }
 2830:         my %canmodify = &Apache::lonuserutils::can_modify_userinfo($context,$env{'form.ccdomain'},\@userinfo,\@userroles);
 2831:         foreach my $item (@userinfo) {
 2832:             # Strip leading and trailing whitespace
 2833:             $env{'form.c'.$item} =~ s/(\s+$|^\s+)//g;
 2834:             if (!$canmodify{$item}) {
 2835:                 if (defined($env{'form.c'.$item})) {
 2836:                     if ($env{'form.c'.$item} ne $userenv{$item}) {
 2837:                         push(@mod_disallowed,$item);
 2838:                     }
 2839:                 }
 2840:                 $env{'form.c'.$item} = $userenv{$item};
 2841:             }
 2842:         }
 2843:         # Check to see if we can change the Student/Employee ID
 2844:         my $forceid = $env{'form.forceid'};
 2845:         my $recurseid = $env{'form.recurseid'};
 2846:         my (%alerts,%rulematch,%idinst_results,%curr_rules,%got_rules);
 2847:         my %uidhash = &Apache::lonnet::idrget($env{'form.ccdomain'},
 2848:                                             $env{'form.ccuname'});
 2849:         if (($uidhash{$env{'form.ccuname'}}) && 
 2850:             ($uidhash{$env{'form.ccuname'}}!~/error\:/) && 
 2851:             (!$forceid)) {
 2852:             if ($env{'form.cid'} ne $uidhash{$env{'form.ccuname'}}) {
 2853:                 $env{'form.cid'} = $userenv{'id'};
 2854:                 $no_forceid_alert = &mt('New student/employee ID does not match existing ID for this user.')
 2855:                                    .'<br />'
 2856:                                    .&mt("Change is not permitted without checking the 'Force ID change' checkbox on the previous page.")
 2857:                                    .'<br />'."\n";
 2858:             }
 2859:         }
 2860:         if ($env{'form.cid'} ne $userenv{'id'}) {
 2861:             my $checkhash;
 2862:             my $checks = { 'id' => 1 };
 2863:             $checkhash->{$env{'form.ccuname'}.':'.$env{'form.ccdomain'}} = 
 2864:                    { 'newuser' => $newuser,
 2865:                      'id'  => $env{'form.cid'}, 
 2866:                    };
 2867:             &Apache::loncommon::user_rule_check($checkhash,$checks,
 2868:                 \%alerts,\%rulematch,\%idinst_results,\%curr_rules,\%got_rules);
 2869:             if (ref($alerts{'id'}) eq 'HASH') {
 2870:                 if (ref($alerts{'id'}{$env{'form.ccdomain'}}) eq 'HASH') {
 2871:                    $env{'form.cid'} = $userenv{'id'};
 2872:                 }
 2873:             }
 2874:         }
 2875:         my (%quotachanged,%oldquota,%newquota,%olddefquota,%newdefquota, 
 2876:             $oldinststatus,$newinststatus,%oldisdefault,%newisdefault,%oldsettings,
 2877:             %oldsettingstext,%newsettings,%newsettingstext,@disporder,
 2878:             %oldsettingstatus,%newsettingstatus);
 2879:         @disporder = ('inststatus');
 2880:         if ($env{'request.role.domain'} eq $env{'form.ccdomain'}) {
 2881:             push(@disporder,'requestcourses','requestauthor');
 2882:         } else {
 2883:             push(@disporder,'reqcrsotherdom');
 2884:         }
 2885:         push(@disporder,('quota','tools'));
 2886:         $oldinststatus = $userenv{'inststatus'};
 2887:         foreach my $name ('portfolio','author') {
 2888:             ($olddefquota{$name},$oldsettingstatus{$name}) = 
 2889:                 &Apache::loncommon::default_quota($env{'form.ccdomain'},$oldinststatus,$name);
 2890:             ($newdefquota{$name},$newsettingstatus{$name}) = ($olddefquota{$name},$oldsettingstatus{$name});
 2891:         }
 2892:         my %canshow;
 2893:         if (&Apache::lonnet::allowed('mpq',$env{'form.ccdomain'})) {
 2894:             $canshow{'quota'} = 1;
 2895:         }
 2896:         if (&Apache::lonnet::allowed('mut',$env{'form.ccdomain'})) {
 2897:             $canshow{'tools'} = 1;
 2898:         }
 2899:         if (&Apache::lonnet::allowed('ccc',$env{'form.ccdomain'})) {
 2900:             $canshow{'requestcourses'} = 1;
 2901:         } elsif (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) {
 2902:             $canshow{'reqcrsotherdom'} = 1;
 2903:         }
 2904:         if (&Apache::lonnet::allowed('mau',$env{'form.ccdomain'})) {
 2905:             $canshow{'inststatus'} = 1;
 2906:         }
 2907:         if (&Apache::lonnet::allowed('cau',$env{'form.ccdomain'})) {
 2908:             $canshow{'requestauthor'} = 1;
 2909:         }
 2910:         my (%changeHash,%changed);
 2911:         if ($oldinststatus eq '') {
 2912:             $oldsettings{'inststatus'} = $othertitle; 
 2913:         } else {
 2914:             if (ref($usertypes) eq 'HASH') {
 2915:                 $oldsettings{'inststatus'} = join(', ',map{ $usertypes->{ &unescape($_) }; } (split(/:/,$userenv{'inststatus'})));
 2916:             } else {
 2917:                 $oldsettings{'inststatus'} = join(', ',map{ &unescape($_); } (split(/:/,$userenv{'inststatus'})));
 2918:             }
 2919:         }
 2920:         $changeHash{'inststatus'} = $userenv{'inststatus'};
 2921:         if ($canmodify_status{'inststatus'}) {
 2922:             $canshow{'inststatus'} = 1;
 2923:             if (exists($env{'form.inststatus'})) {
 2924:                 my @inststatuses = &Apache::loncommon::get_env_multiple('form.inststatus');
 2925:                 if (@inststatuses > 0) {
 2926:                     $newinststatus = join(':',map { &escape($_); } @inststatuses);
 2927:                     $changeHash{'inststatus'} = $newinststatus;
 2928:                     if ($newinststatus ne $oldinststatus) {
 2929:                         $changed{'inststatus'} = $newinststatus;
 2930:                         foreach my $name ('portfolio','author') {
 2931:                             ($newdefquota{$name},$newsettingstatus{$name}) =
 2932:                                 &Apache::loncommon::default_quota($env{'form.ccdomain'},$newinststatus,$name);
 2933:                         }
 2934:                     }
 2935:                     if (ref($usertypes) eq 'HASH') {
 2936:                         $newsettings{'inststatus'} = join(', ',map{ $usertypes->{$_}; } (@inststatuses)); 
 2937:                     } else {
 2938:                         $newsettings{'inststatus'} = join(', ',@inststatuses);
 2939:                     }
 2940:                 }
 2941:             } else {
 2942:                 $newinststatus = '';
 2943:                 $changeHash{'inststatus'} = $newinststatus;
 2944:                 $newsettings{'inststatus'} = $othertitle;
 2945:                 if ($newinststatus ne $oldinststatus) {
 2946:                     $changed{'inststatus'} = $changeHash{'inststatus'};
 2947:                     foreach my $name ('portfolio','author') {
 2948:                         ($newdefquota{$name},$newsettingstatus{$name}) =
 2949:                             &Apache::loncommon::default_quota($env{'form.ccdomain'},$newinststatus,$name);
 2950:                     }
 2951:                 }
 2952:             }
 2953:         } elsif ($context ne 'selfcreate') {
 2954:             $canshow{'inststatus'} = 1;
 2955:             $newsettings{'inststatus'} = $oldsettings{'inststatus'};
 2956:         }
 2957:         foreach my $name ('portfolio','author') {
 2958:             $changeHash{$name.'quota'} = $userenv{$name.'quota'};
 2959:         }
 2960:         if ($context eq 'domain') {
 2961:             foreach my $name ('portfolio','author') {
 2962:                 if ($userenv{$name.'quota'} ne '') {
 2963:                     $oldquota{$name} = $userenv{$name.'quota'};
 2964:                     if ($env{'form.custom_'.$name.'quota'} == 1) {
 2965:                         if ($env{'form.'.$name.'quota'} eq '') {
 2966:                             $newquota{$name} = 0;
 2967:                         } else {
 2968:                             $newquota{$name} = $env{'form.'.$name.'quota'};
 2969:                             $newquota{$name} =~ s/[^\d\.]//g;
 2970:                         }
 2971:                         if ($newquota{$name} != $oldquota{$name}) {
 2972:                             if (&quota_admin($newquota{$name},\%changeHash,$name)) {
 2973:                                 $changed{$name.'quota'} = 1;
 2974:                             }
 2975:                         }
 2976:                     } else {
 2977:                         if (&quota_admin('',\%changeHash,$name)) {
 2978:                             $changed{$name.'quota'} = 1;
 2979:                             $newquota{$name} = $newdefquota{$name};
 2980:                             $newisdefault{$name} = 1;
 2981:                         }
 2982:                     }
 2983:                 } else {
 2984:                     $oldisdefault{$name} = 1;
 2985:                     $oldquota{$name} = $olddefquota{$name};
 2986:                     if ($env{'form.custom_'.$name.'quota'} == 1) {
 2987:                         if ($env{'form.'.$name.'quota'} eq '') {
 2988:                             $newquota{$name} = 0;
 2989:                         } else {
 2990:                             $newquota{$name} = $env{'form.'.$name.'quota'};
 2991:                             $newquota{$name} =~ s/[^\d\.]//g;
 2992:                         }
 2993:                         if (&quota_admin($newquota{$name},\%changeHash,$name)) {
 2994:                             $changed{$name.'quota'} = 1;
 2995:                         }
 2996:                     } else {
 2997:                         $newquota{$name} = $newdefquota{$name};
 2998:                         $newisdefault{$name} = 1;
 2999:                     }
 3000:                 }
 3001:                 if ($oldisdefault{$name}) {
 3002:                     $oldsettingstext{'quota'}{$name} = &get_defaultquota_text($oldsettingstatus{$name});
 3003:                 }  else {
 3004:                     $oldsettingstext{'quota'}{$name} = &mt('custom quota: [_1] MB',$oldquota{$name});
 3005:                 }
 3006:                 if ($newisdefault{$name}) {
 3007:                     $newsettingstext{'quota'}{$name} = &get_defaultquota_text($newsettingstatus{$name});
 3008:                 } else {
 3009:                     $newsettingstext{'quota'}{$name} = &mt('custom quota: [_1] MB',$newquota{$name});
 3010:                 }
 3011:             }
 3012:             &tool_changes('tools',\@usertools,\%oldsettings,\%oldsettingstext,\%userenv,
 3013:                           \%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3014:             if ($env{'form.ccdomain'} eq $env{'request.role.domain'}) {
 3015:                 &tool_changes('requestcourses',\@requestcourses,\%oldsettings,\%oldsettingstext,
 3016:                               \%userenv,\%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3017:                 &tool_changes('requestauthor',\@requestauthor,\%oldsettings,\%oldsettingstext,
 3018:                               \%userenv,\%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3019:             } else {
 3020:                 &tool_changes('reqcrsotherdom',\@requestcourses,\%oldsettings,\%oldsettingstext,
 3021:                               \%userenv,\%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3022:             }
 3023:         }
 3024:         foreach my $item (@userinfo) {
 3025:             if ($env{'form.c'.$item} ne $userenv{$item}) {
 3026:                 $namechanged{$item} = 1;
 3027:             }
 3028:         }
 3029:         foreach my $name ('portfolio','author') {
 3030:             $oldsettings{'quota'}{$name} = &mt('[_1] MB',$oldquota{$name});
 3031:             $newsettings{'quota'}{$name} = &mt('[_1] MB',$newquota{$name});
 3032:         }
 3033:         if ((keys(%namechanged) > 0) || (keys(%changed) > 0)) {
 3034:             my ($chgresult,$namechgresult);
 3035:             if (keys(%changed) > 0) {
 3036:                 $chgresult = 
 3037:                     &Apache::lonnet::put('environment',\%changeHash,
 3038:                                   $env{'form.ccdomain'},$env{'form.ccuname'});
 3039:                 if ($chgresult eq 'ok') {
 3040:                     if (($env{'user.name'} eq $env{'form.ccuname'}) &&
 3041:                         ($env{'user.domain'} eq $env{'form.ccdomain'})) {
 3042:                         my %newenvhash;
 3043:                         foreach my $key (keys(%changed)) {
 3044:                             if (($key eq 'official') || ($key eq 'unofficial')
 3045:                                 || ($key eq 'community')) {
 3046:                                 $newenvhash{'environment.requestcourses.'.$key} =
 3047:                                     $changeHash{'requestcourses.'.$key};
 3048:                                 if ($changeHash{'requestcourses.'.$key}) {
 3049:                                     $newenvhash{'environment.canrequest.'.$key} = 1;
 3050:                                 } else {
 3051:                                     $newenvhash{'environment.canrequest.'.$key} =
 3052:           &Apache::lonnet::usertools_access($env{'user.name'},$env{'user.domain'},
 3053:                                             $key,'reload','requestcourses');
 3054:                                 }
 3055:                             } elsif ($key eq 'requestauthor') {
 3056:                                 $newenvhash{'environment.'.$key} = $changeHash{$key};
 3057:                                 if ($changeHash{$key}) {
 3058:                                     $newenvhash{'environment.canrequest.author'} = 1;
 3059:                                 } else {
 3060:                                     $newenvhash{'environment.canrequest.author'} =
 3061:           &Apache::lonnet::usertools_access($env{'user.name'},$env{'user.domain'},
 3062:                                             $key,'reload','requestauthor');
 3063:                                 }
 3064:                             } elsif ($key ne 'quota') {
 3065:                                 $newenvhash{'environment.tools.'.$key} = 
 3066:                                     $changeHash{'tools.'.$key};
 3067:                                 if ($changeHash{'tools.'.$key} ne '') {
 3068:                                     $newenvhash{'environment.availabletools.'.$key} =
 3069:                                         $changeHash{'tools.'.$key};
 3070:                                 } else {
 3071:                                     $newenvhash{'environment.availabletools.'.$key} =
 3072:           &Apache::lonnet::usertools_access($env{'user.name'},$env{'user.domain'},
 3073:           $key,'reload','tools');
 3074:                                 }
 3075:                             }
 3076:                         }
 3077:                         if (keys(%newenvhash)) {
 3078:                             &Apache::lonnet::appenv(\%newenvhash);
 3079:                         }
 3080:                     }
 3081:                 }
 3082:             }
 3083:             if (keys(%namechanged) > 0) {
 3084:                 foreach my $field (@userinfo) {
 3085:                     $changeHash{$field}  = $env{'form.c'.$field};
 3086:                 }
 3087: # Make the change
 3088:                 $namechgresult =
 3089:                     &Apache::lonnet::modifyuser($env{'form.ccdomain'},
 3090:                         $env{'form.ccuname'},$changeHash{'id'},undef,undef,
 3091:                         $changeHash{'firstname'},$changeHash{'middlename'},
 3092:                         $changeHash{'lastname'},$changeHash{'generation'},
 3093:                         $changeHash{'id'},undef,$changeHash{'permanentemail'},undef,\@userinfo);
 3094:                 %userupdate = (
 3095:                                lastname   => $env{'form.clastname'},
 3096:                                middlename => $env{'form.cmiddlename'},
 3097:                                firstname  => $env{'form.cfirstname'},
 3098:                                generation => $env{'form.cgeneration'},
 3099:                                id         => $env{'form.cid'},
 3100:                              );
 3101:             }
 3102:             if (((keys(%namechanged) > 0) && $namechgresult eq 'ok') || 
 3103:                 ((keys(%changed) > 0) && $chgresult eq 'ok')) {
 3104:             # Tell the user we changed the name
 3105:                 &display_userinfo($r,1,\@disporder,\%canshow,\@requestcourses,
 3106:                                   \@usertools,\@requestauthor,\%userenv,\%changed,\%namechanged,
 3107:                                   \%oldsettings, \%oldsettingstext,\%newsettings,
 3108:                                   \%newsettingstext);
 3109:                 if ($env{'form.cid'} ne $userenv{'id'}) {
 3110:                     &Apache::lonnet::idput($env{'form.ccdomain'},
 3111:                          ($env{'form.ccuname'} => $env{'form.cid'}));
 3112:                     if (($recurseid) &&
 3113:                         (&Apache::lonnet::allowed('mau',$env{'form.ccdomain'}))) {
 3114:                         my $idresult = 
 3115:                             &Apache::lonuserutils::propagate_id_change(
 3116:                                 $env{'form.ccuname'},$env{'form.ccdomain'},
 3117:                                 \%userupdate);
 3118:                         $r->print('<br />'.$idresult.'<br />');
 3119:                     }
 3120:                 }
 3121:                 if (($env{'form.ccdomain'} eq $env{'user.domain'}) && 
 3122:                     ($env{'form.ccuname'} eq $env{'user.name'})) {
 3123:                     my %newenvhash;
 3124:                     foreach my $key (keys(%changeHash)) {
 3125:                         $newenvhash{'environment.'.$key} = $changeHash{$key};
 3126:                     }
 3127:                     &Apache::lonnet::appenv(\%newenvhash);
 3128:                 }
 3129:             } else { # error occurred
 3130:                 $r->print(
 3131:                     '<p class="LC_error">'
 3132:                    .&mt('Unable to successfully change environment for [_1] in domain [_2].',
 3133:                             '"'.$env{'form.ccuname'}.'"',
 3134:                             '"'.$env{'form.ccdomain'}.'"')
 3135:                    .'</p>');
 3136:             }
 3137:         } else { # End of if ($env ... ) logic
 3138:             # They did not want to change the users name, quota, tool availability,
 3139:             # or ability to request creation of courses, 
 3140:             # but we can still tell them what the name and quota and availabilities are  
 3141:             &display_userinfo($r,undef,\@disporder,\%canshow,\@requestcourses,
 3142:                               \@usertools,\@requestauthor,\%userenv,\%changed,\%namechanged,\%oldsettings,
 3143:                               \%oldsettingstext,\%newsettings,\%newsettingstext);
 3144:         }
 3145:         if (@mod_disallowed) {
 3146:             my ($rolestr,$contextname);
 3147:             if (@longroles > 0) {
 3148:                 $rolestr = join(', ',@longroles);
 3149:             } else {
 3150:                 $rolestr = &mt('No roles');
 3151:             }
 3152:             if ($context eq 'course') {
 3153:                 $contextname = &mt('course');
 3154:             } elsif ($context eq 'author') {
 3155:                 $contextname = &mt('co-author');
 3156:             }
 3157:             $r->print(&mt('The following fields were not updated: ').'<ul>');
 3158:             my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
 3159:             foreach my $field (@mod_disallowed) {
 3160:                 $r->print('<li>'.$fieldtitles{$field}.'</li>'."\n"); 
 3161:             }
 3162:             $r->print('</ul>');
 3163:             if (@mod_disallowed == 1) {
 3164:                 $r->print(&mt("You do not have the authority to change this field given the user's current set of active/future [_1] roles:",$contextname));
 3165:             } else {
 3166:                 $r->print(&mt("You do not have the authority to change these fields given the user's current set of active/future [_1] roles:",$contextname));
 3167:             }
 3168:             my $helplink = 'javascript:helpMenu('."'display'".')';
 3169:             $r->print('<span class="LC_cusr_emph">'.$rolestr.'</span><br />'
 3170:                      .&mt('Please contact your [_1]helpdesk[_2] for more information.'
 3171:                          ,'<a href="'.$helplink.'">','</a>')
 3172:                       .'<br />');
 3173:         }
 3174:         $r->print('<span class="LC_warning">'
 3175:                   .$no_forceid_alert
 3176:                   .&Apache::lonuserutils::print_namespacing_alerts($env{'form.ccdomain'},\%alerts,\%curr_rules)
 3177:                   .'</span>');
 3178:     }
 3179:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 3180:     if ($env{'form.action'} eq 'singlestudent') {
 3181:         &enroll_single_student($r,$uhome,$amode,$genpwd,$now,$newuser,$context,
 3182:                                $crstype,$showcredits,$defaultcredits);
 3183:         my $linktext = ($crstype eq 'Community' ?
 3184:             &mt('Enroll Another Member') : &mt('Enroll Another Student'));
 3185:         $r->print(
 3186:             &Apache::lonhtmlcommon::actionbox([
 3187:                 '<a href="javascript:backPage(document.userupdate)">'
 3188:                .($crstype eq 'Community' ? 
 3189:                     &mt('Enroll Another Member') : &mt('Enroll Another Student'))
 3190:                .'</a>']));
 3191:     } else {
 3192:         my @rolechanges = &update_roles($r,$context,$showcredits);
 3193:         if (keys(%namechanged) > 0) {
 3194:             if ($context eq 'course') {
 3195:                 if (@userroles > 0) {
 3196:                     if ((@rolechanges == 0) || 
 3197:                         (!(grep(/^st$/,@rolechanges)))) {
 3198:                         if (grep(/^st$/,@userroles)) {
 3199:                             my $classlistupdated =
 3200:                                 &Apache::lonuserutils::update_classlist($cdom,
 3201:                                               $cnum,$env{'form.ccdomain'},
 3202:                                        $env{'form.ccuname'},\%userupdate);
 3203:                         }
 3204:                     }
 3205:                 }
 3206:             }
 3207:         }
 3208:         my $userinfo = &Apache::loncommon::plainname($env{'form.ccuname'},
 3209:                                                      $env{'form.ccdomain'});
 3210:         if ($env{'form.popup'}) {
 3211:             $r->print('<p><a href="javascript:window.close()">'.&mt('Close window').'</a></p>');
 3212:         } else {
 3213:             $r->print('<br />'.&Apache::lonhtmlcommon::actionbox(['<a href="javascript:backPage(document.userupdate,'."'$env{'form.prevphase'}','modify'".')">'
 3214:                      .&mt('Modify this user: [_1]','<span class="LC_cusr_emph">'.$env{'form.ccuname'}.':'.$env{'form.ccdomain'}.' ('.$userinfo.')</span>').'</a>',
 3215:                      '<a href="javascript:backPage(document.userupdate)">'.&mt('Create/Modify Another User').'</a>']));
 3216:         }
 3217:     }
 3218: }
 3219: 
 3220: sub display_userinfo {
 3221:     my ($r,$changed,$order,$canshow,$requestcourses,$usertools,$requestauthor,
 3222:         $userenv,$changedhash,$namechangedhash,$oldsetting,$oldsettingtext,
 3223:         $newsetting,$newsettingtext) = @_;
 3224:     return unless (ref($order) eq 'ARRAY' &&
 3225:                    ref($canshow) eq 'HASH' && 
 3226:                    ref($requestcourses) eq 'ARRAY' && 
 3227:                    ref($requestauthor) eq 'ARRAY' &&
 3228:                    ref($usertools) eq 'ARRAY' && 
 3229:                    ref($userenv) eq 'HASH' &&
 3230:                    ref($changedhash) eq 'HASH' &&
 3231:                    ref($oldsetting) eq 'HASH' &&
 3232:                    ref($oldsettingtext) eq 'HASH' &&
 3233:                    ref($newsetting) eq 'HASH' &&
 3234:                    ref($newsettingtext) eq 'HASH');
 3235:     my %lt=&Apache::lonlocal::texthash(
 3236:          'ui'             => 'User Information',
 3237:          'uic'            => 'User Information Changed',
 3238:          'firstname'      => 'First Name',
 3239:          'middlename'     => 'Middle Name',
 3240:          'lastname'       => 'Last Name',
 3241:          'generation'     => 'Generation',
 3242:          'id'             => 'Student/Employee ID',
 3243:          'permanentemail' => 'Permanent e-mail address',
 3244:          'portfolioquota' => 'Disk space allocated to portfolio files',
 3245:          'authorquota'    => 'Disk space allocated to Authoring Space',
 3246:          'blog'           => 'Blog Availability',
 3247:          'webdav'         => 'WebDAV Availability',
 3248:          'aboutme'        => 'Personal Information Page Availability',
 3249:          'portfolio'      => 'Portfolio Availability',
 3250:          'official'       => 'Can Request Official Courses',
 3251:          'unofficial'     => 'Can Request Unofficial Courses',
 3252:          'community'      => 'Can Request Communities',
 3253:          'textbook'       => 'Can Request Textbook Courses',
 3254:          'requestauthor'  => 'Can Request Author Role',
 3255:          'inststatus'     => "Affiliation",
 3256:          'prvs'           => 'Previous Value:',
 3257:          'chto'           => 'Changed To:'
 3258:     );
 3259:     if ($changed) {
 3260:         $r->print('<h3>'.$lt{'uic'}.'</h3>'.
 3261:                 &Apache::loncommon::start_data_table().
 3262:                 &Apache::loncommon::start_data_table_header_row());
 3263:         $r->print("<th>&nbsp;</th>\n");
 3264:         $r->print('<th><b>'.$lt{'prvs'}.'</b></th>');
 3265:         $r->print('<th><span class="LC_nobreak"><b>'.$lt{'chto'}.'</b></span></th>');
 3266:         $r->print(&Apache::loncommon::end_data_table_header_row());
 3267:         my @userinfo = ('firstname','middlename','lastname','generation','permanentemail','id');
 3268: 
 3269:         foreach my $item (@userinfo) {
 3270:             my $value = $env{'form.c'.$item};
 3271:             #show changes only:
 3272:             unless ($value eq $userenv->{$item}){
 3273:                 $r->print(&Apache::loncommon::start_data_table_row());
 3274:                 $r->print("<td>$lt{$item}</td>\n");
 3275:                 $r->print("<td>".$userenv->{$item}."</td>\n");
 3276:                 $r->print("<td>$value </td>\n");
 3277:                 $r->print(&Apache::loncommon::end_data_table_row());
 3278:             }
 3279:         }
 3280:         foreach my $entry (@{$order}) {
 3281:             if ($canshow->{$entry}) {
 3282:                 if (($entry eq 'requestcourses') || ($entry eq 'reqcrsotherdom') || ($entry eq 'requestauthor')) {
 3283:                     my @items;
 3284:                     if ($entry eq 'requestauthor') {
 3285:                         @items = ($entry);
 3286:                     } else {
 3287:                         @items = @{$requestcourses};
 3288:                     }
 3289:                     foreach my $item (@items) {
 3290:                         if (($newsetting->{$item} ne $oldsetting->{$item}) || 
 3291:                             ($newsettingtext->{$item} ne $oldsettingtext->{$item})) {
 3292:                             $r->print(&Apache::loncommon::start_data_table_row()."\n");  
 3293:                             $r->print("<td>$lt{$item}</td>\n");
 3294:                             $r->print("<td>".$oldsetting->{$item});
 3295:                             if ($oldsettingtext->{$item}) {
 3296:                                 if ($oldsetting->{$item}) {
 3297:                                     $r->print(' -- ');
 3298:                                 }
 3299:                                 $r->print($oldsettingtext->{$item});
 3300:                             }
 3301:                             $r->print("</td>\n");
 3302:                             $r->print("<td>".$newsetting->{$item});
 3303:                             if ($newsettingtext->{$item}) {
 3304:                                 if ($newsetting->{$item}) {
 3305:                                     $r->print(' -- ');
 3306:                                 }
 3307:                                 $r->print($newsettingtext->{$item});
 3308:                             }
 3309:                             $r->print("</td>\n");
 3310:                             $r->print(&Apache::loncommon::end_data_table_row()."\n");
 3311:                         }
 3312:                     }
 3313:                 } elsif ($entry eq 'tools') {
 3314:                     foreach my $item (@{$usertools}) {
 3315:                         if ($newsetting->{$item} ne $oldsetting->{$item}) {
 3316:                             $r->print(&Apache::loncommon::start_data_table_row()."\n");
 3317:                             $r->print("<td>$lt{$item}</td>\n");
 3318:                             $r->print("<td>".$oldsetting->{$item}.' '.$oldsettingtext->{$item}."</td>\n");
 3319:                             $r->print("<td>".$newsetting->{$item}.' '.$newsettingtext->{$item}."</td>\n");
 3320:                             $r->print(&Apache::loncommon::end_data_table_row()."\n");
 3321:                         }
 3322:                     }
 3323:                 } elsif ($entry eq 'quota') {
 3324:                     if ((ref($oldsetting->{$entry}) eq 'HASH') && (ref($oldsettingtext->{$entry}) eq 'HASH') &&
 3325:                         (ref($newsetting->{$entry}) eq 'HASH') && (ref($newsettingtext->{$entry}) eq 'HASH')) {
 3326:                         foreach my $name ('portfolio','author') {
 3327:                             if ($newsetting->{$entry}->{$name} ne $oldsetting->{$entry}->{$name}) {
 3328:                                 $r->print(&Apache::loncommon::start_data_table_row()."\n");
 3329:                                 $r->print("<td>$lt{$name.$entry}</td>\n");
 3330:                                 $r->print("<td>".$oldsettingtext->{$entry}->{$name}."</td>\n");
 3331:                                 $r->print("<td>".$newsettingtext->{$entry}->{$name}."</td>\n");
 3332:                                 $r->print(&Apache::loncommon::end_data_table_row()."\n");
 3333:                             }
 3334:                         }
 3335:                     }
 3336:                 } else {
 3337:                     if ($newsetting->{$entry} ne $oldsetting->{$entry}) {
 3338:                         $r->print(&Apache::loncommon::start_data_table_row()."\n");
 3339:                         $r->print("<td>$lt{$entry}</td>\n");
 3340:                         $r->print("<td>".$oldsetting->{$entry}.' '.$oldsettingtext->{$entry}."</td>\n");
 3341:                         $r->print("<td>".$newsetting->{$entry}.' '.$newsettingtext->{$entry}."</td>\n");
 3342:                         $r->print(&Apache::loncommon::end_data_table_row()."\n");
 3343:                     }
 3344:                 }
 3345:             }
 3346:         }
 3347:         $r->print(&Apache::loncommon::end_data_table().'<br />');
 3348:     } else {
 3349:         $r->print('<h3>'.$lt{'ui'}.'</h3>'.
 3350:                   '<p>'.&mt('No changes made to user information').'</p>');
 3351:     }
 3352:     return;
 3353: }
 3354: 
 3355: sub tool_changes {
 3356:     my ($context,$usertools,$oldaccess,$oldaccesstext,$userenv,$changeHash,
 3357:         $changed,$newaccess,$newaccesstext) = @_;
 3358:     if (!((ref($usertools) eq 'ARRAY') && (ref($oldaccess) eq 'HASH') &&
 3359:           (ref($oldaccesstext) eq 'HASH') && (ref($userenv) eq 'HASH') &&
 3360:           (ref($changeHash) eq 'HASH') && (ref($changed) eq 'HASH') &&
 3361:           (ref($newaccess) eq 'HASH') && (ref($newaccesstext) eq 'HASH'))) {
 3362:         return;
 3363:     }
 3364:     my %reqdisplay = &requestchange_display();
 3365:     if ($context eq 'reqcrsotherdom') {
 3366:         my @options = ('approval','validate','autolimit');
 3367:         my $optregex = join('|',@options);
 3368:         my $cdom = $env{'request.role.domain'};
 3369:         foreach my $tool (@{$usertools}) {
 3370:             $oldaccesstext->{$tool} = &mt("availability set to 'off'");
 3371:             $newaccesstext->{$tool} = $oldaccesstext->{$tool};
 3372:             $changeHash->{$context.'.'.$tool} = $userenv->{$context.'.'.$tool};
 3373:             my ($newop,$limit);
 3374:             if ($env{'form.'.$context.'_'.$tool}) {
 3375:                 $newop = $env{'form.'.$context.'_'.$tool};
 3376:                 if ($newop eq 'autolimit') {
 3377:                     $limit = $env{'form.'.$context.'_'.$tool.'_limit'};
 3378:                     $limit =~ s/\D+//g;
 3379:                     $newop .= '='.$limit;
 3380:                 }
 3381:             }
 3382:             if ($userenv->{$context.'.'.$tool} eq '') {
 3383:                 if ($newop) {
 3384:                     $changed->{$tool}=&tool_admin($tool,$cdom.':'.$newop,
 3385:                                                   $changeHash,$context);
 3386:                     if ($changed->{$tool}) {
 3387:                         if ($newop =~ /^autolimit/) {
 3388:                             if ($limit) {
 3389:                                 $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3390:                             } else {
 3391:                                 $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3392:                             }
 3393:                         } else {
 3394:                             $newaccesstext->{$tool} = $reqdisplay{$newop};
 3395:                         }
 3396:                     } else {
 3397:                         $newaccesstext->{$tool} = $oldaccesstext->{$tool};
 3398:                     }
 3399:                 }
 3400:             } else {
 3401:                 my @curr = split(',',$userenv->{$context.'.'.$tool});
 3402:                 my @new;
 3403:                 my $changedoms;
 3404:                 foreach my $req (@curr) {
 3405:                     if ($req =~ /^\Q$cdom\E\:($optregex\=?\d*)$/) {
 3406:                         my $oldop = $1;
 3407:                         if ($oldop =~ /^autolimit=(\d*)/) {
 3408:                             my $limit = $1;
 3409:                             if ($limit) {
 3410:                                 $oldaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3411:                             } else {
 3412:                                 $oldaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3413:                             }
 3414:                         } else {
 3415:                             $oldaccesstext->{$tool} = $reqdisplay{$oldop};
 3416:                         }
 3417:                         if ($oldop ne $newop) {
 3418:                             $changedoms = 1;
 3419:                             foreach my $item (@curr) {
 3420:                                 my ($reqdom,$option) = split(':',$item);
 3421:                                 unless ($reqdom eq $cdom) {
 3422:                                     push(@new,$item);
 3423:                                 }
 3424:                             }
 3425:                             if ($newop) {
 3426:                                 push(@new,$cdom.':'.$newop);
 3427:                             }
 3428:                             @new = sort(@new);
 3429:                         }
 3430:                         last;
 3431:                     }
 3432:                 }
 3433:                 if ((!$changedoms) && ($newop)) {
 3434:                     $changedoms = 1;
 3435:                     @new = sort(@curr,$cdom.':'.$newop);
 3436:                 }
 3437:                 if ($changedoms) {
 3438:                     my $newdomstr;
 3439:                     if (@new) {
 3440:                         $newdomstr = join(',',@new);
 3441:                     }
 3442:                     $changed->{$tool}=&tool_admin($tool,$newdomstr,$changeHash,
 3443:                                                   $context);
 3444:                     if ($changed->{$tool}) {
 3445:                         if ($env{'form.'.$context.'_'.$tool}) {
 3446:                             if ($env{'form.'.$context.'_'.$tool} eq 'autolimit') {
 3447:                                 my $limit = $env{'form.'.$context.'_'.$tool.'_limit'};
 3448:                                 $limit =~ s/\D+//g;
 3449:                                 if ($limit) {
 3450:                                     $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3451:                                 } else {
 3452:                                     $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3453:                                 }
 3454:                             } else {
 3455:                                 $newaccesstext->{$tool} = $reqdisplay{$env{'form.'.$context.'_'.$tool}};
 3456:                             }
 3457:                         } else {
 3458:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3459:                         }
 3460:                     }
 3461:                 }
 3462:             }
 3463:         }
 3464:         return;
 3465:     }
 3466:     foreach my $tool (@{$usertools}) {
 3467:         my ($newval,$limit,$envkey);
 3468:         $envkey = $context.'.'.$tool;
 3469:         if ($context eq 'requestcourses') {
 3470:             $newval = $env{'form.crsreq_'.$tool};
 3471:             if ($newval eq 'autolimit') {
 3472:                 $limit = $env{'form.crsreq_'.$tool.'_limit'};
 3473:                 $limit =~ s/\D+//g;
 3474:                 $newval .= '='.$limit;
 3475:             }
 3476:         } elsif ($context eq 'requestauthor') {
 3477:             $newval = $env{'form.'.$context};
 3478:             $envkey = $context;
 3479:         } else {
 3480:             $newval = $env{'form.'.$context.'_'.$tool};
 3481:         }
 3482:         if ($userenv->{$envkey} ne '') {
 3483:             $oldaccess->{$tool} = &mt('custom');
 3484:             if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 3485:                 if ($userenv->{$envkey} =~ /^autolimit=(\d*)$/) {
 3486:                     my $currlimit = $1;
 3487:                     if ($currlimit eq '') {
 3488:                         $oldaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3489:                     } else {
 3490:                         $oldaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$currlimit);
 3491:                     }
 3492:                 } elsif ($userenv->{$envkey}) {
 3493:                     $oldaccesstext->{$tool} = $reqdisplay{$userenv->{$envkey}};
 3494:                 } else {
 3495:                     $oldaccesstext->{$tool} = &mt("availability set to 'off'");
 3496:                 }
 3497:             } else {
 3498:                 if ($userenv->{$envkey}) {
 3499:                     $oldaccesstext->{$tool} = &mt("availability set to 'on'");
 3500:                 } else {
 3501:                     $oldaccesstext->{$tool} = &mt("availability set to 'off'");
 3502:                 }
 3503:             }
 3504:             $changeHash->{$envkey} = $userenv->{$envkey};
 3505:             if ($env{'form.custom'.$tool} == 1) {
 3506:                 if ($newval ne $userenv->{$envkey}) {
 3507:                     $changed->{$tool} = &tool_admin($tool,$newval,$changeHash,
 3508:                                                     $context);
 3509:                     if ($changed->{$tool}) {
 3510:                         $newaccess->{$tool} = &mt('custom');
 3511:                         if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 3512:                             if ($newval =~ /^autolimit/) {
 3513:                                 if ($limit) {
 3514:                                     $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3515:                                 } else {
 3516:                                     $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3517:                                 }
 3518:                             } elsif ($newval) {
 3519:                                 $newaccesstext->{$tool} = $reqdisplay{$newval};
 3520:                             } else {
 3521:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3522:                             }
 3523:                         } else {
 3524:                             if ($newval) {
 3525:                                 $newaccesstext->{$tool} = &mt("availability set to 'on'");
 3526:                             } else {
 3527:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3528:                             }
 3529:                         }
 3530:                     } else {
 3531:                         $newaccess->{$tool} = $oldaccess->{$tool};
 3532:                         if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 3533:                             if ($newval =~ /^autolimit/) {
 3534:                                 if ($limit) {
 3535:                                     $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3536:                                 } else {
 3537:                                     $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3538:                                 }
 3539:                             } elsif ($newval) {
 3540:                                 $newaccesstext->{$tool} = $reqdisplay{$newval};
 3541:                             } else {
 3542:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3543:                             }
 3544:                         } else {
 3545:                             if ($userenv->{$context.'.'.$tool}) {
 3546:                                 $newaccesstext->{$tool} = &mt("availability set to 'on'");
 3547:                             } else {
 3548:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3549:                             }
 3550:                         }
 3551:                     }
 3552:                 } else {
 3553:                     $newaccess->{$tool} = $oldaccess->{$tool};
 3554:                     $newaccesstext->{$tool} = $oldaccesstext->{$tool};
 3555:                 }
 3556:             } else {
 3557:                 $changed->{$tool} = &tool_admin($tool,'',$changeHash,$context);
 3558:                 if ($changed->{$tool}) {
 3559:                     $newaccess->{$tool} = &mt('default');
 3560:                 } else {
 3561:                     $newaccess->{$tool} = $oldaccess->{$tool};
 3562:                     if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 3563:                         if ($newval =~ /^autolimit/) {
 3564:                             if ($limit) {
 3565:                                 $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3566:                             } else {
 3567:                                 $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3568:                             }
 3569:                         } elsif ($newval) {
 3570:                             $newaccesstext->{$tool} = $reqdisplay{$newval};
 3571:                         } else {
 3572:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3573:                         }
 3574:                     } else {
 3575:                         if ($userenv->{$context.'.'.$tool}) {
 3576:                             $newaccesstext->{$tool} = &mt("availability set to 'on'");
 3577:                         } else {
 3578:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3579:                         }
 3580:                     }
 3581:                 }
 3582:             }
 3583:         } else {
 3584:             $oldaccess->{$tool} = &mt('default');
 3585:             if ($env{'form.custom'.$tool} == 1) {
 3586:                 $changed->{$tool} = &tool_admin($tool,$newval,$changeHash,
 3587:                                                 $context);
 3588:                 if ($changed->{$tool}) {
 3589:                     $newaccess->{$tool} = &mt('custom');
 3590:                     if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 3591:                         if ($newval =~ /^autolimit/) {
 3592:                             if ($limit) {
 3593:                                 $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3594:                             } else {
 3595:                                 $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3596:                             }
 3597:                         } elsif ($newval) {
 3598:                             $newaccesstext->{$tool} = $reqdisplay{$newval};
 3599:                         } else {
 3600:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3601:                         }
 3602:                     } else {
 3603:                         if ($newval) {
 3604:                             $newaccesstext->{$tool} = &mt("availability set to 'on'");
 3605:                         } else {
 3606:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3607:                         }
 3608:                     }
 3609:                 } else {
 3610:                     $newaccess->{$tool} = $oldaccess->{$tool};
 3611:                 }
 3612:             } else {
 3613:                 $newaccess->{$tool} = $oldaccess->{$tool};
 3614:             }
 3615:         }
 3616:     }
 3617:     return;
 3618: }
 3619: 
 3620: sub update_roles {
 3621:     my ($r,$context,$showcredits) = @_;
 3622:     my $now=time;
 3623:     my @rolechanges;
 3624:     my %disallowed;
 3625:     $r->print('<h3>'.&mt('Modifying Roles').'</h3>');
 3626:     foreach my $key (keys (%env)) {
 3627: 	next if (! $env{$key});
 3628:         next if ($key eq 'form.action');
 3629: 	# Revoke roles
 3630: 	if ($key=~/^form\.rev/) {
 3631: 	    if ($key=~/^form\.rev\:([^\_]+)\_([^\_\.]+)$/) {
 3632: # Revoke standard role
 3633: 		my ($scope,$role) = ($1,$2);
 3634: 		my $result =
 3635: 		    &Apache::lonnet::revokerole($env{'form.ccdomain'},
 3636: 						$env{'form.ccuname'},
 3637: 						$scope,$role,'','',$context);
 3638:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
 3639:                             &mt('Revoking [_1] in [_2]',
 3640:                                 &Apache::lonnet::plaintext($role),
 3641:                                 &Apache::loncommon::show_role_extent($scope,$context,$role)),
 3642:                                 $result ne "ok").'<br />');
 3643:                 if ($result ne "ok") {
 3644:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 3645:                 }
 3646: 		if ($role eq 'st') {
 3647: 		    my $result = 
 3648:                         &Apache::lonuserutils::classlist_drop($scope,
 3649:                             $env{'form.ccuname'},$env{'form.ccdomain'},
 3650: 			    $now);
 3651:                     $r->print(&Apache::lonhtmlcommon::confirm_success($result));
 3652: 		}
 3653:                 if (!grep(/^\Q$role\E$/,@rolechanges)) {
 3654:                     push(@rolechanges,$role);
 3655:                 }
 3656: 	    }
 3657: 	    if ($key=~m{^form\.rev\:([^_]+)_cr\.cr/($match_domain)/($match_username)/(\w+)$}s) {
 3658: # Revoke custom role
 3659:                 my $result = &Apache::lonnet::revokecustomrole(
 3660:                     $env{'form.ccdomain'},$env{'form.ccuname'},$1,$2,$3,$4,'','',$context);
 3661:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
 3662:                             &mt('Revoking custom role [_1] by [_2] in [_3]',
 3663:                                 $4,$3.':'.$2,&Apache::loncommon::show_role_extent($1,$context,'cr')),
 3664:                             $result ne 'ok').'<br />');
 3665:                 if ($result ne "ok") {
 3666:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 3667:                 }
 3668:                 if (!grep(/^cr$/,@rolechanges)) {
 3669:                     push(@rolechanges,'cr');
 3670:                 }
 3671: 	    }
 3672: 	} elsif ($key=~/^form\.del/) {
 3673: 	    if ($key=~/^form\.del\:([^\_]+)\_([^\_\.]+)$/) {
 3674: # Delete standard role
 3675: 		my ($scope,$role) = ($1,$2);
 3676: 		my $result =
 3677: 		    &Apache::lonnet::assignrole($env{'form.ccdomain'},
 3678: 						$env{'form.ccuname'},
 3679: 						$scope,$role,$now,0,1,'',
 3680:                                                 $context);
 3681:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
 3682:                             &mt('Deleting [_1] in [_2]',
 3683:                                 &Apache::lonnet::plaintext($role),
 3684:                                 &Apache::loncommon::show_role_extent($scope,$context,$role)),
 3685:                             $result ne 'ok').'<br />');
 3686:                 if ($result ne "ok") {
 3687:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 3688:                 }
 3689: 
 3690: 		if ($role eq 'st') {
 3691: 		    my $result = 
 3692:                         &Apache::lonuserutils::classlist_drop($scope,
 3693:                             $env{'form.ccuname'},$env{'form.ccdomain'},
 3694: 			    $now);
 3695: 		    $r->print(&Apache::lonhtmlcommon::confirm_success($result));
 3696: 		}
 3697:                 if (!grep(/^\Q$role\E$/,@rolechanges)) {
 3698:                     push(@rolechanges,$role);
 3699:                 }
 3700:             }
 3701: 	    if ($key=~m{^form\.del\:([^_]+)_cr\.cr/($match_domain)/($match_username)/(\w+)$}) {
 3702:                 my ($url,$rdom,$rnam,$rolename) = ($1,$2,$3,$4);
 3703: # Delete custom role
 3704:                 my $result =
 3705:                     &Apache::lonnet::assigncustomrole($env{'form.ccdomain'},
 3706:                         $env{'form.ccuname'},$url,$rdom,$rnam,$rolename,$now,
 3707:                         0,1,$context);
 3708:                 $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('Deleting custom role [_1] by [_2] in [_3]',
 3709:                       $rolename,$rnam.':'.$rdom,&Apache::loncommon::show_role_extent($1,$context,'cr')),
 3710:                       $result ne "ok").'<br />');
 3711:                 if ($result ne "ok") {
 3712:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 3713:                 }
 3714: 
 3715:                 if (!grep(/^cr$/,@rolechanges)) {
 3716:                     push(@rolechanges,'cr');
 3717:                 }
 3718:             }
 3719: 	} elsif ($key=~/^form\.ren/) {
 3720:             my $udom = $env{'form.ccdomain'};
 3721:             my $uname = $env{'form.ccuname'};
 3722: # Re-enable standard role
 3723: 	    if ($key=~/^form\.ren\:([^\_]+)\_([^\_\.]+)$/) {
 3724:                 my $url = $1;
 3725:                 my $role = $2;
 3726:                 my $logmsg;
 3727:                 my $output;
 3728:                 if ($role eq 'st') {
 3729:                     if ($url =~ m-^/($match_domain)/($match_courseid)/?(\w*)$-) {
 3730:                         my ($cdom,$cnum,$csec) = ($1,$2,$3);
 3731:                         my $credits;
 3732:                         if ($showcredits) {
 3733:                             my $defaultcredits = 
 3734:                                 &Apache::lonuserutils::get_defaultcredits($cdom,$cnum);
 3735:                             $credits = &get_user_credits($defaultcredits,$cdom,$cnum);
 3736:                         }
 3737:                         my $result = &Apache::loncommon::commit_studentrole(\$logmsg,$udom,$uname,$url,$role,$now,0,$cdom,$cnum,$csec,$context,$credits);
 3738:                         if (($result =~ /^error/) || ($result eq 'not_in_class') || ($result eq 'unknown_course') || ($result eq 'refused')) {
 3739:                             if ($result eq 'refused' && $logmsg) {
 3740:                                 $output = $logmsg;
 3741:                             } else { 
 3742:                                 $output = &mt('Error: [_1]',$result)."\n";
 3743:                             }
 3744:                         } else {
 3745:                             $output = &Apache::lonhtmlcommon::confirm_success(&mt('Assigning [_1] in [_2] starting [_3]',
 3746:                                         &Apache::lonnet::plaintext($role),
 3747:                                         &Apache::loncommon::show_role_extent($url,$context,'st'),
 3748:                                         &Apache::lonlocal::locallocaltime($now))).'<br />'.$logmsg.'<br />';
 3749:                         }
 3750:                     }
 3751:                 } else {
 3752: 		    my $result=&Apache::lonnet::assignrole($env{'form.ccdomain'},
 3753:                                $env{'form.ccuname'},$url,$role,0,$now,'','',
 3754:                                $context);
 3755:                         $output = &Apache::lonhtmlcommon::confirm_success(&mt('Re-enabling [_1] in [_2]',
 3756:                                         &Apache::lonnet::plaintext($role),
 3757:                                         &Apache::loncommon::show_role_extent($url,$context,$role)),$result ne "ok").'<br />';
 3758:                     if ($result ne "ok") {
 3759:                         $output .= &mt('Error: [_1]',$result).'<br />';
 3760:                     }
 3761:                 }
 3762:                 $r->print($output);
 3763:                 if (!grep(/^\Q$role\E$/,@rolechanges)) {
 3764:                     push(@rolechanges,$role);
 3765:                 }
 3766: 	    }
 3767: # Re-enable custom role
 3768: 	    if ($key=~m{^form\.ren\:([^_]+)_cr\.cr/($match_domain)/($match_username)/(\w+)$}) {
 3769:                 my ($url,$rdom,$rnam,$rolename) = ($1,$2,$3,$4);
 3770:                 my $result = &Apache::lonnet::assigncustomrole(
 3771:                                $env{'form.ccdomain'}, $env{'form.ccuname'},
 3772:                                $url,$rdom,$rnam,$rolename,0,$now,undef,$context);
 3773:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
 3774:                     &mt('Re-enabling custom role [_1] by [_2] in [_3]',
 3775:                         $rolename,$rnam.':'.$rdom,&Apache::loncommon::show_role_extent($1,$context,'cr')),
 3776:                     $result ne "ok").'<br />');
 3777:                 if ($result ne "ok") {
 3778:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 3779:                 }
 3780:                 if (!grep(/^cr$/,@rolechanges)) {
 3781:                     push(@rolechanges,'cr');
 3782:                 }
 3783:             }
 3784: 	} elsif ($key=~/^form\.act/) {
 3785:             my $udom = $env{'form.ccdomain'};
 3786:             my $uname = $env{'form.ccuname'};
 3787: 	    if ($key=~/^form\.act\_($match_domain)\_($match_courseid)\_cr_cr_($match_domain)_($match_username)_([^\_]+)$/) {
 3788:                 # Activate a custom role
 3789: 		my ($one,$two,$three,$four,$five)=($1,$2,$3,$4,$5);
 3790: 		my $url='/'.$one.'/'.$two;
 3791: 		my $full=$one.'_'.$two.'_cr_cr_'.$three.'_'.$four.'_'.$five;
 3792: 
 3793:                 my $start = ( $env{'form.start_'.$full} ?
 3794:                               $env{'form.start_'.$full} :
 3795:                               $now );
 3796:                 my $end   = ( $env{'form.end_'.$full} ?
 3797:                               $env{'form.end_'.$full} :
 3798:                               0 );
 3799:                                                                                      
 3800:                 # split multiple sections
 3801:                 my %sections = ();
 3802:                 my $num_sections = &build_roles($env{'form.sec_'.$full},\%sections,$5);
 3803:                 if ($num_sections == 0) {
 3804:                     $r->print(&Apache::loncommon::commit_customrole($udom,$uname,$url,$three,$four,$five,$start,$end,$context));
 3805:                 } else {
 3806: 		    my %curr_groups =
 3807: 			&Apache::longroup::coursegroups($one,$two);
 3808:                     foreach my $sec (sort {$a cmp $b} keys %sections) {
 3809:                         if (($sec eq 'none') || ($sec eq 'all') || 
 3810:                             exists($curr_groups{$sec})) {
 3811:                             $disallowed{$sec} = $url;
 3812:                             next;
 3813:                         }
 3814:                         my $securl = $url.'/'.$sec;
 3815: 		        $r->print(&Apache::loncommon::commit_customrole($udom,$uname,$securl,$three,$four,$five,$start,$end,$context));
 3816:                     }
 3817:                 }
 3818:                 if (!grep(/^cr$/,@rolechanges)) {
 3819:                     push(@rolechanges,'cr');
 3820:                 }
 3821: 	    } elsif ($key=~/^form\.act\_($match_domain)\_($match_name)\_([^\_]+)$/) {
 3822: 		# Activate roles for sections with 3 id numbers
 3823: 		# set start, end times, and the url for the class
 3824: 		my ($one,$two,$three)=($1,$2,$3);
 3825: 		my $start = ( $env{'form.start_'.$one.'_'.$two.'_'.$three} ? 
 3826: 			      $env{'form.start_'.$one.'_'.$two.'_'.$three} : 
 3827: 			      $now );
 3828: 		my $end   = ( $env{'form.end_'.$one.'_'.$two.'_'.$three} ? 
 3829: 			      $env{'form.end_'.$one.'_'.$two.'_'.$three} :
 3830: 			      0 );
 3831: 		my $url='/'.$one.'/'.$two;
 3832:                 my $type = 'three';
 3833:                 # split multiple sections
 3834:                 my %sections = ();
 3835:                 my $num_sections = &build_roles($env{'form.sec_'.$one.'_'.$two.'_'.$three},\%sections,$three);
 3836:                 my $credits;
 3837:                 if ($three eq 'st') {
 3838:                     if ($showcredits) { 
 3839:                         my $defaultcredits = 
 3840:                             &Apache::lonuserutils::get_defaultcredits($one,$two);
 3841:                         $credits = $env{'form.credits_'.$one.'_'.$two.'_'.$three};
 3842:                         $credits =~ s/[^\d\.]//g;
 3843:                         if ($credits eq $defaultcredits) {
 3844:                             undef($credits);
 3845:                         }
 3846:                     }
 3847:                 }
 3848:                 if ($num_sections == 0) {
 3849:                     $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$three,$start,$end,$one,$two,'',$context,$credits));
 3850:                 } else {
 3851:                     my %curr_groups = 
 3852: 			&Apache::longroup::coursegroups($one,$two);
 3853:                     my $emptysec = 0;
 3854:                     foreach my $sec (sort {$a cmp $b} keys %sections) {
 3855:                         $sec =~ s/\W//g;
 3856:                         if ($sec ne '') {
 3857:                             if (($sec eq 'none') || ($sec eq 'all') || 
 3858:                                 exists($curr_groups{$sec})) {
 3859:                                 $disallowed{$sec} = $url;
 3860:                                 next;
 3861:                             }
 3862:                             my $securl = $url.'/'.$sec;
 3863:                             $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$securl,$three,$start,$end,$one,$two,$sec,$context,$credits));
 3864:                         } else {
 3865:                             $emptysec = 1;
 3866:                         }
 3867:                     }
 3868:                     if ($emptysec) {
 3869:                         $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$three,$start,$end,$one,$two,'',$context,$credits));
 3870:                     }
 3871:                 }
 3872:                 if (!grep(/^\Q$three\E$/,@rolechanges)) {
 3873:                     push(@rolechanges,$three);
 3874:                 }
 3875: 	    } elsif ($key=~/^form\.act\_([^\_]+)\_([^\_]+)$/) {
 3876: 		# Activate roles for sections with two id numbers
 3877: 		# set start, end times, and the url for the class
 3878: 		my $start = ( $env{'form.start_'.$1.'_'.$2} ? 
 3879: 			      $env{'form.start_'.$1.'_'.$2} : 
 3880: 			      $now );
 3881: 		my $end   = ( $env{'form.end_'.$1.'_'.$2} ? 
 3882: 			      $env{'form.end_'.$1.'_'.$2} :
 3883: 			      0 );
 3884:                 my $one = $1;
 3885:                 my $two = $2;
 3886: 		my $url='/'.$one.'/';
 3887:                 # split multiple sections
 3888:                 my %sections = ();
 3889:                 my $num_sections = &build_roles($env{'form.sec_'.$one.'_'.$two},\%sections,$two);
 3890:                 if ($num_sections == 0) {
 3891:                     $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$two,$start,$end,$one,undef,'',$context));
 3892:                 } else {
 3893:                     my $emptysec = 0;
 3894:                     foreach my $sec (sort {$a cmp $b} keys %sections) {
 3895:                         if ($sec ne '') {
 3896:                             my $securl = $url.'/'.$sec;
 3897:                             $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$securl,$two,$start,$end,$one,undef,$sec,$context));
 3898:                         } else {
 3899:                             $emptysec = 1;
 3900:                         }
 3901:                     }
 3902:                     if ($emptysec) {
 3903:                         $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$two,$start,$end,$one,undef,'',$context));
 3904:                     }
 3905:                 }
 3906:                 if (!grep(/^\Q$two\E$/,@rolechanges)) {
 3907:                     push(@rolechanges,$two);
 3908:                 }
 3909: 	    } else {
 3910: 		$r->print('<p><span class="LC_error">'.&mt('ERROR').': '.&mt('Unknown command').' <tt>'.$key.'</tt></span></p><br />');
 3911:             }
 3912:             foreach my $key (sort(keys(%disallowed))) {
 3913:                 $r->print('<p class="LC_warning">');
 3914:                 if (($key eq 'none') || ($key eq 'all')) {  
 3915:                     $r->print(&mt('[_1] may not be used as the name for a section, as it is a reserved word.','<tt>'.$key.'</tt>'));
 3916:                 } else {
 3917:                     $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>'));
 3918:                 }
 3919:                 $r->print('</p><p>'
 3920:                          .&mt('Please [_1]go back[_2] and choose a different section name.'
 3921:                              ,'<a href="javascript:history.go(-1)'
 3922:                              ,'</a>')
 3923:                          .'</p><br />'
 3924:                 );
 3925:             }
 3926: 	}
 3927:     } # End of foreach (keys(%env))
 3928: # Flush the course logs so reverse user roles immediately updated
 3929:     $r->register_cleanup(\&Apache::lonnet::flushcourselogs);
 3930:     if (@rolechanges == 0) {
 3931:         $r->print('<p>'.&mt('No roles to modify').'</p>');
 3932:     }
 3933:     return @rolechanges;
 3934: }
 3935: 
 3936: sub get_user_credits {
 3937:     my ($uname,$udom,$defaultcredits,$cdom,$cnum) = @_;
 3938:     if ($cdom eq '' || $cnum eq '') {
 3939:         return unless ($env{'request.course.id'});
 3940:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3941:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3942:     }
 3943:     my $credits;
 3944:     my %currhash =
 3945:         &Apache::lonnet::get('classlist',[$uname.':'.$udom],$cdom,$cnum);
 3946:     if (keys(%currhash) > 0) {
 3947:         my @items = split(/:/,$currhash{$uname.':'.$udom});
 3948:         my $crdidx = &Apache::loncoursedata::CL_CREDITS() - 3;
 3949:         $credits = $items[$crdidx];
 3950:         $credits =~ s/[^\d\.]//g;
 3951:     }
 3952:     if ($credits eq $defaultcredits) {
 3953:         undef($credits);
 3954:     }
 3955:     return $credits;
 3956: }
 3957: 
 3958: sub enroll_single_student {
 3959:     my ($r,$uhome,$amode,$genpwd,$now,$newuser,$context,$crstype,
 3960:         $showcredits,$defaultcredits) = @_;
 3961:     $r->print('<h3>');
 3962:     if ($crstype eq 'Community') {
 3963:         $r->print(&mt('Enrolling Member'));
 3964:     } else {
 3965:         $r->print(&mt('Enrolling Student'));
 3966:     }
 3967:     $r->print('</h3>');
 3968: 
 3969:     # Remove non alphanumeric values from section
 3970:     $env{'form.sections'}=~s/\W//g;
 3971: 
 3972:     my $credits;
 3973:     if (($showcredits) && ($env{'form.credits'} ne '')) {
 3974:         $credits = $env{'form.credits'};
 3975:         $credits =~ s/[^\d\.]//g;
 3976:         if ($credits ne '') {
 3977:             if ($credits eq $defaultcredits) {
 3978:                 undef($credits);
 3979:             }
 3980:         }
 3981:     }
 3982: 
 3983:     # Clean out any old student roles the user has in this class.
 3984:     &Apache::lonuserutils::modifystudent($env{'form.ccdomain'},
 3985:          $env{'form.ccuname'},$env{'request.course.id'},undef,$uhome);
 3986:     my ($startdate,$enddate) = &Apache::lonuserutils::get_dates_from_form();
 3987:     my $enroll_result =
 3988:         &Apache::lonnet::modify_student_enrollment($env{'form.ccdomain'},
 3989:             $env{'form.ccuname'},$env{'form.cid'},$env{'form.cfirstname'},
 3990:             $env{'form.cmiddlename'},$env{'form.clastname'},
 3991:             $env{'form.generation'},$env{'form.sections'},$enddate,
 3992:             $startdate,'manual',undef,$env{'request.course.id'},'',$context,
 3993:             $credits);
 3994:     if ($enroll_result =~ /^ok/) {
 3995:         $r->print(&mt('[_1] enrolled','<b>'.$env{'form.ccuname'}.':'.$env{'form.ccdomain'}.'</b>'));
 3996:         if ($env{'form.sections'} ne '') {
 3997:             $r->print(' '.&mt('in section [_1]',$env{'form.sections'}));
 3998:         }
 3999:         my ($showstart,$showend);
 4000:         if ($startdate <= $now) {
 4001:             $showstart = &mt('Access starts immediately');
 4002:         } else {
 4003:             $showstart = &mt('Access starts: ').&Apache::lonlocal::locallocaltime($startdate);
 4004:         }
 4005:         if ($enddate == 0) {
 4006:             $showend = &mt('ends: no ending date');
 4007:         } else {
 4008:             $showend = &mt('ends: ').&Apache::lonlocal::locallocaltime($enddate);
 4009:         }
 4010:         $r->print('.<br />'.$showstart.'; '.$showend);
 4011:         if ($startdate <= $now && !$newuser) {
 4012:             $r->print('<p class="LC_info">');
 4013:             if ($crstype eq 'Community') {
 4014:                 $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.'));
 4015:             } else {
 4016:                 $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.'));
 4017:            }
 4018:            $r->print('</p>');
 4019:         }
 4020:     } else {
 4021:         $r->print(&mt('unable to enroll').": ".$enroll_result);
 4022:     }
 4023:     return;
 4024: }
 4025: 
 4026: sub get_defaultquota_text {
 4027:     my ($settingstatus) = @_;
 4028:     my $defquotatext; 
 4029:     if ($settingstatus eq '') {
 4030:         $defquotatext = &mt('default');
 4031:     } else {
 4032:         my ($usertypes,$order) =
 4033:             &Apache::lonnet::retrieve_inst_usertypes($env{'form.ccdomain'});
 4034:         if ($usertypes->{$settingstatus} eq '') {
 4035:             $defquotatext = &mt('default');
 4036:         } else {
 4037:             $defquotatext = &mt('default for [_1]',$usertypes->{$settingstatus});
 4038:         }
 4039:     }
 4040:     return $defquotatext;
 4041: }
 4042: 
 4043: sub update_result_form {
 4044:     my ($uhome) = @_;
 4045:     my $outcome = 
 4046:     '<form name="userupdate" method="post" action="">'."\n";
 4047:     foreach my $item ('srchby','srchin','srchtype','srchterm','srchdomain','ccuname','ccdomain') {
 4048:         $outcome .= '<input type="hidden" name="'.$item.'" value="'.$env{'form.'.$item}.'" />'."\n";
 4049:     }
 4050:     if ($env{'form.origname'} ne '') {
 4051:         $outcome .= '<input type="hidden" name="origname" value="'.$env{'form.origname'}.'" />'."\n";
 4052:     }
 4053:     foreach my $item ('sortby','seluname','seludom') {
 4054:         if (exists($env{'form.'.$item})) {
 4055:             $outcome .= '<input type="hidden" name="'.$item.'" value="'.$env{'form.'.$item}.'" />'."\n";
 4056:         }
 4057:     }
 4058:     if ($uhome eq 'no_host') {
 4059:         $outcome .= '<input type="hidden" name="forcenewuser" value="1" />'."\n";
 4060:     }
 4061:     $outcome .= '<input type="hidden" name="phase" value="" />'."\n".
 4062:                 '<input type="hidden" name="currstate" value="" />'."\n".
 4063:                 '<input type="hidden" name="action" value="'.$env{'form.action'}.'" />'."\n".
 4064:                 '</form>';
 4065:     return $outcome;
 4066: }
 4067: 
 4068: sub quota_admin {
 4069:     my ($setquota,$changeHash,$name) = @_;
 4070:     my $quotachanged;
 4071:     if (&Apache::lonnet::allowed('mpq',$env{'form.ccdomain'})) {
 4072:         # Current user has quota modification privileges
 4073:         if (ref($changeHash) eq 'HASH') {
 4074:             $quotachanged = 1;
 4075:             $changeHash->{$name.'quota'} = $setquota;
 4076:         }
 4077:     }
 4078:     return $quotachanged;
 4079: }
 4080: 
 4081: sub tool_admin {
 4082:     my ($tool,$settool,$changeHash,$context) = @_;
 4083:     my $canchange = 0; 
 4084:     if ($context eq 'requestcourses') {
 4085:         if (&Apache::lonnet::allowed('ccc',$env{'form.ccdomain'})) {
 4086:             $canchange = 1;
 4087:         }
 4088:     } elsif ($context eq 'reqcrsotherdom') {
 4089:         if (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) {
 4090:             $canchange = 1;
 4091:         }
 4092:     } elsif ($context eq 'requestauthor') {
 4093:         if (&Apache::lonnet::allowed('cau',$env{'request.role.domain'})) {
 4094:             $canchange = 1;
 4095:         }
 4096:     } elsif (&Apache::lonnet::allowed('mut',$env{'form.ccdomain'})) {
 4097:         # Current user has quota modification privileges
 4098:         $canchange = 1;
 4099:     }
 4100:     my $toolchanged;
 4101:     if ($canchange) {
 4102:         if (ref($changeHash) eq 'HASH') {
 4103:             $toolchanged = 1;
 4104:             if ($tool eq 'requestauthor') {
 4105:                 $changeHash->{$context} = $settool;
 4106:             } else {
 4107:                 $changeHash->{$context.'.'.$tool} = $settool;
 4108:             }
 4109:         }
 4110:     }
 4111:     return $toolchanged;
 4112: }
 4113: 
 4114: sub build_roles {
 4115:     my ($sectionstr,$sections,$role) = @_;
 4116:     my $num_sections = 0;
 4117:     if ($sectionstr=~ /,/) {
 4118:         my @secnums = split/,/,$sectionstr;
 4119:         if ($role eq 'st') {
 4120:             $secnums[0] =~ s/\W//g;
 4121:             $$sections{$secnums[0]} = 1;
 4122:             $num_sections = 1;
 4123:         } else {
 4124:             foreach my $sec (@secnums) {
 4125:                 $sec =~ ~s/\W//g;
 4126:                 if (!($sec eq "")) {
 4127:                     if (exists($$sections{$sec})) {
 4128:                         $$sections{$sec} ++;
 4129:                     } else {
 4130:                         $$sections{$sec} = 1;
 4131:                         $num_sections ++;
 4132:                     }
 4133:                 }
 4134:             }
 4135:         }
 4136:     } else {
 4137:         $sectionstr=~s/\W//g;
 4138:         unless ($sectionstr eq '') {
 4139:             $$sections{$sectionstr} = 1;
 4140:             $num_sections ++;
 4141:         }
 4142:     }
 4143: 
 4144:     return $num_sections;
 4145: }
 4146: 
 4147: # ========================================================== Custom Role Editor
 4148: 
 4149: sub custom_role_editor {
 4150:     my ($r,$brcrum) = @_;
 4151:     my $action = $env{'form.customroleaction'};
 4152:     my $rolename; 
 4153:     if ($action eq 'new') {
 4154:         $rolename=$env{'form.newrolename'};
 4155:     } else {
 4156:         $rolename=$env{'form.rolename'};
 4157:     }
 4158: 
 4159:     my ($crstype,$context);
 4160:     if ($env{'request.course.id'}) {
 4161:         $crstype = &Apache::loncommon::course_type();
 4162:         $context = 'course';
 4163:     } else {
 4164:         $context = 'domain';
 4165:         $crstype = $env{'form.templatecrstype'};
 4166:     }
 4167: 
 4168:     $rolename=~s/[^A-Za-z0-9]//gs;
 4169:     if (!$rolename || $env{'form.phase'} eq 'pickrole') {
 4170: 	&print_username_entry_form($r,undef,undef,undef,undef,$crstype,$brcrum);
 4171:         return;
 4172:     }
 4173: 
 4174: # ------------------------------------------------------- What can be assigned?
 4175:     my %full=();
 4176:     my %courselevel=();
 4177:     my %courselevelcurrent=();
 4178:     my $syspriv='';
 4179:     my $dompriv='';
 4180:     my $coursepriv='';
 4181:     my $body_top;
 4182:     my $newrole;
 4183:     my ($rdummy,$roledef)=
 4184: 			 &Apache::lonnet::get('roles',["rolesdef_$rolename"]);
 4185: # ------------------------------------------------------- Does this role exist?
 4186:     $body_top .= '<h2>';
 4187:     if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 4188: 	$body_top .= &mt('Existing Role').' "';
 4189: # ------------------------------------------------- Get current role privileges
 4190: 	($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 4191:         if ($crstype eq 'Community') {
 4192:             $syspriv =~ s/bre\&S//;   
 4193:         }
 4194:     } else {
 4195:         $newrole = 1;
 4196: 	$body_top .= &mt('New Role').' "';
 4197: 	$roledef='';
 4198:     }
 4199:     $body_top .= $rolename.'"</h2>';
 4200:     foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
 4201: 	my ($priv,$restrict)=split(/\&/,$item);
 4202:         if (!$restrict) { $restrict='F'; }
 4203:         $courselevel{$priv}=$restrict;
 4204:         if ($coursepriv=~/\:$priv/) {
 4205: 	    $courselevelcurrent{$priv}=1;
 4206: 	}
 4207: 	$full{$priv}=1;
 4208:     }
 4209:     my %domainlevel=();
 4210:     my %domainlevelcurrent=();
 4211:     foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:d'})) {
 4212: 	my ($priv,$restrict)=split(/\&/,$item);
 4213:         if (!$restrict) { $restrict='F'; }
 4214:         $domainlevel{$priv}=$restrict;
 4215:         if ($dompriv=~/\:$priv/) {
 4216: 	    $domainlevelcurrent{$priv}=1;
 4217: 	}
 4218: 	$full{$priv}=1;
 4219:     }
 4220:     my %systemlevel=();
 4221:     my %systemlevelcurrent=();
 4222:     foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:s'})) {
 4223: 	my ($priv,$restrict)=split(/\&/,$item);
 4224:         if (!$restrict) { $restrict='F'; }
 4225:         $systemlevel{$priv}=$restrict;
 4226:         if ($syspriv=~/\:$priv/) {
 4227: 	    $systemlevelcurrent{$priv}=1;
 4228: 	}
 4229: 	$full{$priv}=1;
 4230:     }
 4231:     my ($jsback,$elements) = &crumb_utilities();
 4232:     my $button_code = "\n";
 4233:     my $head_script = "\n";
 4234:     $head_script .= '<script type="text/javascript">'."\n"
 4235:                    .'// <![CDATA['."\n";
 4236:     my @template_roles = ("in","ta","ep");
 4237:     if ($context eq 'domain') {
 4238:         push(@template_roles,"ad");
 4239:     }
 4240:     push(@template_roles,"st");
 4241:     if ($crstype eq 'Community') {
 4242:         unshift(@template_roles,'co');
 4243:     } else {
 4244:         unshift(@template_roles,'cc');
 4245:     }
 4246:     foreach my $role (@template_roles) {
 4247:         $head_script .= &make_script_template($role,$crstype);
 4248:         $button_code .= &make_button_code($role,$crstype).' ';
 4249:     }
 4250:     my $context_code;
 4251:     if ($context eq 'domain') {
 4252:         my $checkedCommunity = '';
 4253:         my $checkedCourse = ' checked="checked"';
 4254:         if ($env{'form.templatecrstype'} eq 'Community') {
 4255:             $checkedCommunity = $checkedCourse;
 4256:             $checkedCourse = '';
 4257:         }
 4258:         $context_code = '<label>'.
 4259:                         '<input type="radio" name="templatecrstype" value="Course"'.$checkedCourse.' onclick="this.form.submit();">'.
 4260:                         &mt('Course').
 4261:                         '</label>'.('&nbsp;' x2).
 4262:                         '<label>'.
 4263:                         '<input type="radio" name="templatecrstype" value="Community"'.$checkedCommunity.' onclick="this.form.submit();">'.
 4264:                         &mt('Community').
 4265:                         '</label>'.
 4266:                         '</fieldset>'.
 4267:                         '<input type="hidden" name="customroleaction" value="'.
 4268:                         $action.'" />';
 4269:         if ($env{'form.customroleaction'} eq 'new') {
 4270:             $context_code .= '<input type="hidden" name="newrolename" value="'.
 4271:                              $rolename.'" />';
 4272:         } else {
 4273:             $context_code .= '<input type="hidden" name="rolename" value="'.
 4274:                              $rolename.'" />';
 4275:         }
 4276:         $context_code .= '<input type="hidden" name="action" value="custom" />'.
 4277:                          '<input type="hidden" name="phase" value="selected_custom_edit" />';
 4278:     }
 4279: 
 4280:     $head_script .= "\n".$jsback."\n"
 4281:                    .'// ]]>'."\n"
 4282:                    .'</script>'."\n";
 4283:     push (@{$brcrum},
 4284:               {href => "javascript:backPage(document.form1,'pickrole','')",
 4285:                text => "Pick custom role",
 4286:                faq  => 282,bug=>'Instructor Interface',},
 4287:               {href => "javascript:backPage(document.form1,'','')",
 4288:                text => "Edit custom role",
 4289:                faq  => 282,
 4290:                bug  => 'Instructor Interface',
 4291:                help => 'Course_Editing_Custom_Roles'}
 4292:               );
 4293:     my $args = { bread_crumbs          => $brcrum,
 4294:                  bread_crumbs_component => 'User Management'};
 4295:  
 4296:     $r->print(&Apache::loncommon::start_page('Custom Role Editor',
 4297:                                              $head_script,$args).
 4298:               $body_top);
 4299:     my %lt=&Apache::lonlocal::texthash(
 4300: 		    'prv'  => "Privilege",
 4301: 		    'crl'  => "Course Level",
 4302:                     'dml'  => "Domain Level",
 4303:                     'ssl'  => "System Level");
 4304: 
 4305:     $r->print('<div class="LC_left_float">'
 4306:              .'<form action=""><fieldset>'
 4307:              .'<legend>'.&mt('Select a Template').'</legend>'
 4308:              .$button_code
 4309:              .'</fieldset></form></div>');
 4310:     if ($context_code) {
 4311:         $r->print('<div class="LC_left_float">'
 4312:                  .'<form action="/adm/createuser" method="post"><fieldset>'
 4313:                  .'<legend>'.&mt('Context').'</legend>'
 4314:                  .$context_code
 4315:                  .'</form>'
 4316:                  .'</div>'
 4317:         );
 4318:     }
 4319:     $r->print('<br clear="all" />');
 4320: 
 4321:     $r->print(<<ENDCCF);
 4322: <form name="form1" method="post" action="">
 4323: <input type="hidden" name="phase" value="set_custom_roles" />
 4324: <input type="hidden" name="rolename" value="$rolename" />
 4325: ENDCCF
 4326:     $r->print(&Apache::loncommon::start_data_table().
 4327:               &Apache::loncommon::start_data_table_header_row(). 
 4328: '<th>'.$lt{'prv'}.'</th><th>'.$lt{'crl'}.'</th><th>'.$lt{'dml'}.
 4329: '</th><th>'.$lt{'ssl'}.'</th>'.
 4330:               &Apache::loncommon::end_data_table_header_row());
 4331:     foreach my $priv (sort(keys(%full))) {
 4332:         my $privtext = &Apache::lonnet::plaintext($priv,$crstype);
 4333:         $r->print(&Apache::loncommon::start_data_table_row().
 4334: 	          '<td>'.$privtext.'</td><td>'.
 4335:     ($courselevel{$priv}?'<input type="checkbox" name="'.$priv.'_c"'.
 4336:     ($courselevelcurrent{$priv}?' checked="checked"':'').' />':'&nbsp;').
 4337:     '</td><td>'.
 4338:     ($domainlevel{$priv}?'<input type="checkbox" name="'.$priv.'_d"'.
 4339:     ($domainlevelcurrent{$priv}?' checked="checked"':'').' />':'&nbsp;').
 4340:     '</td><td>');
 4341:         if ($priv eq 'bre' && $crstype eq 'Community') {
 4342:             $r->print('&nbsp;');  
 4343:         } else {
 4344:             $r->print($systemlevel{$priv}?'<input type="checkbox" name="'.$priv.'_s"'.
 4345:                       ($systemlevelcurrent{$priv}?' checked="checked"':'').' />':'&nbsp;');
 4346:         }
 4347:         $r->print('</td>'.
 4348:                   &Apache::loncommon::end_data_table_row());
 4349:     }
 4350:     $r->print(&Apache::loncommon::end_data_table().
 4351:    '<input type="hidden" name="action" value="'.$env{'form.action'}.'" />'.
 4352:    '<input type="hidden" name="startrolename" value="'.$env{'form.rolename'}.
 4353:    '" />'."\n".'<input type="hidden" name="currstate" value="" />'."\n".   
 4354:    '<input type="reset" value="'.&mt("Reset").'" />'."\n".
 4355:    '<input type="submit" value="'.&mt('Save').'" /></form>');
 4356: }
 4357: # --------------------------------------------------------
 4358: sub make_script_template {
 4359:     my ($role,$crstype) = @_;
 4360:     my %full_c=();
 4361:     my %full_d=();
 4362:     my %full_s=();
 4363:     my $return_script;
 4364:     foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
 4365:         my ($priv,$restrict)=split(/\&/,$item);
 4366:         $full_c{$priv}=1;
 4367:     }
 4368:     foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:d'})) {
 4369:         my ($priv,$restrict)=split(/\&/,$item);
 4370:         $full_d{$priv}=1;
 4371:     }
 4372:     foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:s'})) {
 4373:         next if (($crstype eq 'Community') && ($item eq 'bre&S'));
 4374:         my ($priv,$restrict)=split(/\&/,$item);
 4375:         $full_s{$priv}=1;
 4376:     }
 4377:     $return_script .= 'function set_'.$role.'() {'."\n";
 4378:     my @temp = split(/:/,$Apache::lonnet::pr{$role.':c'});
 4379:     my %role_c;
 4380:     foreach my $priv (@temp) {
 4381:         my ($priv_item, $dummy) = split(/\&/,$priv);
 4382:         $role_c{$priv_item} = 1;
 4383:     }
 4384:     my %role_d;
 4385:     @temp = split(/:/,$Apache::lonnet::pr{$role.':d'});
 4386:     foreach my $priv(@temp) {
 4387:         my ($priv_item, $dummy) = split(/\&/,$priv);
 4388:         $role_d{$priv_item} = 1;
 4389:     }
 4390:     my %role_s;
 4391:     @temp = split(/:/,$Apache::lonnet::pr{$role.':s'});
 4392:     foreach my $priv(@temp) {
 4393:         my ($priv_item, $dummy) = split(/\&/,$priv);
 4394:         $role_s{$priv_item} = 1;
 4395:     }
 4396:     foreach my $priv_item (keys(%full_c)) {
 4397:         my ($priv, $dummy) = split(/\&/,$priv_item);
 4398:         if ((exists($role_c{$priv})) || (exists($role_d{$priv})) || 
 4399:             (exists($role_s{$priv}))) {
 4400:             $return_script .= "document.form1.$priv"."_c.checked = true;\n";
 4401:         } else {
 4402:             $return_script .= "document.form1.$priv"."_c.checked = false;\n";
 4403:         }
 4404:     }
 4405:     foreach my $priv_item (keys(%full_d)) {
 4406:         my ($priv, $dummy) = split(/\&/,$priv_item);
 4407:         if ((exists($role_d{$priv})) || (exists($role_s{$priv}))) {
 4408:             $return_script .= "document.form1.$priv"."_d.checked = true;\n";
 4409:         } else {
 4410:             $return_script .= "document.form1.$priv"."_d.checked = false;\n";
 4411:         }
 4412:     }
 4413:     foreach my $priv_item (keys(%full_s)) {
 4414:         my ($priv, $dummy) = split(/\&/,$priv_item);
 4415:         if (exists($role_s{$priv})) {
 4416:             $return_script .= "document.form1.$priv"."_s.checked = true;\n";
 4417:         } else {
 4418:             $return_script .= "document.form1.$priv"."_s.checked = false;\n";
 4419:         }
 4420:     }
 4421:     $return_script .= '}'."\n";
 4422:     return ($return_script);
 4423: }
 4424: # ----------------------------------------------------------
 4425: sub make_button_code {
 4426:     my ($role,$crstype) = @_;
 4427:     my $label = &Apache::lonnet::plaintext($role,$crstype);
 4428:     my $button_code = '<input type="button" onclick="set_'.$role.'()" value="'.$label.'" />';
 4429:     return ($button_code);
 4430: }
 4431: # ---------------------------------------------------------- Call to definerole
 4432: sub set_custom_role {
 4433:     my ($r,$context,$brcrum) = @_;
 4434:     my $rolename=$env{'form.rolename'};
 4435:     $rolename=~s/[^A-Za-z0-9]//gs;
 4436:     if (!$rolename) {
 4437: 	&custom_role_editor($r,$brcrum);
 4438:         return;
 4439:     }
 4440:     my ($jsback,$elements) = &crumb_utilities();
 4441:     my $jscript = '<script type="text/javascript">'
 4442:                  .'// <![CDATA['."\n"
 4443:                  .$jsback."\n"
 4444:                  .'// ]]>'."\n"
 4445:                  .'</script>'."\n";
 4446:     push(@{$brcrum},
 4447:         {href => "javascript:backPage(document.customresult,'pickrole','')",
 4448:          text => "Pick custom role",
 4449:          faq  => 282,
 4450:          bug  => 'Instructor Interface',},
 4451:         {href => "javascript:backPage(document.customresult,'selected_custom_edit','')",
 4452:          text => "Edit custom role",
 4453:          faq  => 282,
 4454:          bug  => 'Instructor Interface',},
 4455:         {href => "javascript:backPage(document.customresult,'set_custom_roles','')",
 4456:          text => "Result",
 4457:          faq  => 282,
 4458:          bug  => 'Instructor Interface',
 4459:          help => 'Course_Editing_Custom_Roles'},
 4460:         );
 4461:     my $args = { bread_crumbs           => $brcrum,
 4462:                  bread_crumbs_component => 'User Management'}; 
 4463:     $r->print(&Apache::loncommon::start_page('Save Custom Role',$jscript,$args));
 4464: 
 4465:     my $newrole;
 4466:     my ($rdummy,$roledef)=
 4467: 	&Apache::lonnet::get('roles',["rolesdef_$rolename"]);
 4468: 
 4469: # ------------------------------------------------------- Does this role exist?
 4470:     $r->print('<h3>');
 4471:     if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 4472: 	$r->print(&mt('Existing Role').' "');
 4473:     } else {
 4474: 	$r->print(&mt('New Role').' "');
 4475: 	$roledef='';
 4476:         $newrole = 1;
 4477:     }
 4478:     $r->print($rolename.'"</h3>');
 4479: # ------------------------------------------------------- What can be assigned?
 4480:     my $sysrole='';
 4481:     my $domrole='';
 4482:     my $courole='';
 4483: 
 4484:     foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
 4485: 	my ($priv,$restrict)=split(/\&/,$item);
 4486:         if (!$restrict) { $restrict=''; }
 4487:         if ($env{'form.'.$priv.'_c'}) {
 4488: 	    $courole.=':'.$item;
 4489: 	}
 4490:     }
 4491: 
 4492:     foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:d'})) {
 4493: 	my ($priv,$restrict)=split(/\&/,$item);
 4494:         if (!$restrict) { $restrict=''; }
 4495:         if ($env{'form.'.$priv.'_d'}) {
 4496: 	    $domrole.=':'.$item;
 4497: 	}
 4498:     }
 4499: 
 4500:     foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:s'})) {
 4501: 	my ($priv,$restrict)=split(/\&/,$item);
 4502:         if (!$restrict) { $restrict=''; }
 4503:         if ($env{'form.'.$priv.'_s'}) {
 4504: 	    $sysrole.=':'.$item;
 4505: 	}
 4506:     }
 4507:     # Assign role; Compile and show result
 4508:     my $errmsg;
 4509:     my $result =
 4510:         &Apache::lonnet::definerole($rolename,$sysrole,$domrole,$courole);
 4511:     if ($result ne 'ok') {
 4512:         $errmsg = ': '.$result;
 4513:     }
 4514:     my $message =
 4515:         &Apache::lonhtmlcommon::confirm_success(
 4516:             &mt('Defining Role').$errmsg, ($result eq 'ok' ? 0 : 1));
 4517:     if ($env{'request.course.id'}) {
 4518:         my $url='/'.$env{'request.course.id'};
 4519:         $url=~s/\_/\//g;
 4520:         $result =
 4521:             &Apache::lonnet::assigncustomrole(
 4522:                 $env{'user.domain'},$env{'user.name'},
 4523:                 $url,
 4524:                 $env{'user.domain'},$env{'user.name'},
 4525:                 $rolename,undef,undef,undef,$context);
 4526:         if ($result ne 'ok') {
 4527:             $errmsg = ': '.$result;
 4528:         }
 4529:         $message .=
 4530:             '<br />'
 4531:            .&Apache::lonhtmlcommon::confirm_success(
 4532:                 &mt('Assigning Role to Self').$errmsg, ($result eq 'ok' ? 0 : 1));
 4533:     }
 4534:     $r->print(
 4535:         &Apache::loncommon::confirmwrapper($message)
 4536:        .'<br />'
 4537:        .&Apache::lonhtmlcommon::actionbox([
 4538:             '<a href="javascript:backPage(document.customresult,'."'pickrole'".')">'
 4539:            .&mt('Create or edit another custom role')
 4540:            .'</a>'])
 4541:        .'<form name="customresult" method="post" action="">'
 4542:        .&Apache::lonhtmlcommon::echo_form_input([])
 4543:        .'</form>'
 4544:     );
 4545: }
 4546: 
 4547: # ================================================================ Main Handler
 4548: sub handler {
 4549:     my $r = shift;
 4550:     if ($r->header_only) {
 4551:        &Apache::loncommon::content_type($r,'text/html');
 4552:        $r->send_http_header;
 4553:        return OK;
 4554:     }
 4555:     my ($context,$crstype);
 4556:     if ($env{'request.course.id'}) {
 4557:         $context = 'course';
 4558:         $crstype = &Apache::loncommon::course_type();
 4559:     } elsif ($env{'request.role'} =~ /^au\./) {
 4560:         $context = 'author';
 4561:     } else {
 4562:         $context = 'domain';
 4563:     }
 4564: 
 4565:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 4566:         ['action','state','callingform','roletype','showrole','bulkaction','popup','phase',
 4567:          'username','domain','srchterm','srchdomain','srchin','srchby','srchtype','queue']);
 4568:     &Apache::lonhtmlcommon::clear_breadcrumbs();
 4569:     my $args;
 4570:     my $brcrum = [];
 4571:     my $bread_crumbs_component = 'User Management';
 4572:     if (($env{'form.action'} ne 'dateselect') && ($env{'form.action'} ne 'displayuserreq')) {
 4573:         $brcrum = [{href=>"/adm/createuser",
 4574:                     text=>"User Management",
 4575:                     help=>'Course_Create_Class_List,Course_Change_Privileges,Course_View_Class_List,Course_Editing_Custom_Roles,Course_Add_Student,Course_Drop_Student,Course_Automated_Enrollment,Course_Self_Enrollment,Course_Manage_Group'}
 4576:                   ];
 4577:     }
 4578:     #SD Following files not added to help, because the corresponding .tex-files seem to
 4579:     #be missing: Course_Approve_Selfenroll,Course_User_Logs,
 4580:     my ($permission,$allowed) = 
 4581:         &Apache::lonuserutils::get_permission($context,$crstype);
 4582:     if (!$allowed) {
 4583:         if ($context eq 'course') {
 4584:             $r->internal_redirect('/adm/viewclasslist');
 4585:             return OK;
 4586:         }
 4587:         $env{'user.error.msg'}=
 4588:             "/adm/createuser:cst:0:0:Cannot create/modify user data ".
 4589:                                  "or view user status.";
 4590:         return HTTP_NOT_ACCEPTABLE;
 4591:     }
 4592: 
 4593:     &Apache::loncommon::content_type($r,'text/html');
 4594:     $r->send_http_header;
 4595: 
 4596:     my $showcredits;
 4597:     if ((($context eq 'course') && ($crstype eq 'Course')) || 
 4598:          ($context eq 'domain')) {
 4599:         my %domdefaults = 
 4600:             &Apache::lonnet::get_domain_defaults($env{'request.role.domain'});
 4601:         if ($domdefaults{'officialcredits'} || $domdefaults{'unofficialcredits'}) {
 4602:             $showcredits = 1;
 4603:         }
 4604:     }
 4605: 
 4606:     # Main switch on form.action and form.state, as appropriate
 4607:     if (! exists($env{'form.action'})) {
 4608:         $args = {bread_crumbs => $brcrum,
 4609:                  bread_crumbs_component => $bread_crumbs_component}; 
 4610:         $r->print(&header(undef,$args));
 4611:         $r->print(&print_main_menu($permission,$context,$crstype));
 4612:     } elsif ($env{'form.action'} eq 'upload' && $permission->{'cusr'}) {
 4613:         push(@{$brcrum},
 4614:               { href => '/adm/createuser?action=upload&state=',
 4615:                 text => 'Upload Users List',
 4616:                 help => 'Course_Create_Class_List',
 4617:               });
 4618:         $bread_crumbs_component = 'Upload Users List';
 4619:         $args = {bread_crumbs           => $brcrum,
 4620:                  bread_crumbs_component => $bread_crumbs_component};
 4621:         $r->print(&header(undef,$args));
 4622:         $r->print('<form name="studentform" method="post" '.
 4623:                   'enctype="multipart/form-data" '.
 4624:                   ' action="/adm/createuser">'."\n");
 4625:         if (! exists($env{'form.state'})) {
 4626:             &Apache::lonuserutils::print_first_users_upload_form($r,$context);
 4627:         } elsif ($env{'form.state'} eq 'got_file') {
 4628:             &Apache::lonuserutils::print_upload_manager_form($r,$context,$permission,
 4629:                                                              $crstype,$showcredits);
 4630:         } elsif ($env{'form.state'} eq 'enrolling') {
 4631:             if ($env{'form.datatoken'}) {
 4632:                 &Apache::lonuserutils::upfile_drop_add($r,$context,$permission,
 4633:                                                        $showcredits);
 4634:             }
 4635:         } else {
 4636:             &Apache::lonuserutils::print_first_users_upload_form($r,$context);
 4637:         }
 4638:     } elsif ((($env{'form.action'} eq 'singleuser') || ($env{'form.action'}
 4639:              eq 'singlestudent')) && ($permission->{'cusr'})) {
 4640:         my $phase = $env{'form.phase'};
 4641:         my @search = ('srchterm','srchby','srchin','srchtype','srchdomain');
 4642: 	&Apache::loncreateuser::restore_prev_selections();
 4643: 	my $srch;
 4644: 	foreach my $item (@search) {
 4645: 	    $srch->{$item} = $env{'form.'.$item};
 4646: 	}
 4647:         if (($phase eq 'get_user_info') || ($phase eq 'userpicked') ||
 4648:             ($phase eq 'createnewuser')) {
 4649:             if ($env{'form.phase'} eq 'createnewuser') {
 4650:                 my $response;
 4651:                 if ($env{'form.srchterm'} !~ /^$match_username$/) {
 4652:                     my $response =
 4653:                         '<span class="LC_warning">'
 4654:                        .&mt('You must specify a valid username. Only the following are allowed:'
 4655:                            .' letters numbers - . @')
 4656:                        .'</span>';
 4657:                     $env{'form.phase'} = '';
 4658:                     &print_username_entry_form($r,$context,$response,$srch,undef,
 4659:                                                $crstype,$brcrum,$showcredits);
 4660:                 } else {
 4661:                     my $ccuname =&LONCAPA::clean_username($srch->{'srchterm'});
 4662:                     my $ccdomain=&LONCAPA::clean_domain($srch->{'srchdomain'});
 4663:                     &print_user_modification_page($r,$ccuname,$ccdomain,
 4664:                                                   $srch,$response,$context,
 4665:                                                   $permission,$crstype,$brcrum,
 4666:                                                   $showcredits);
 4667:                 }
 4668:             } elsif ($env{'form.phase'} eq 'get_user_info') {
 4669:                 my ($currstate,$response,$forcenewuser,$results) = 
 4670:                     &user_search_result($context,$srch);
 4671:                 if ($env{'form.currstate'} eq 'modify') {
 4672:                     $currstate = $env{'form.currstate'};
 4673:                 }
 4674:                 if ($currstate eq 'select') {
 4675:                     &print_user_selection_page($r,$response,$srch,$results,
 4676:                                                \@search,$context,undef,$crstype,
 4677:                                                $brcrum);
 4678:                 } elsif ($currstate eq 'modify') {
 4679:                     my ($ccuname,$ccdomain);
 4680:                     if (($srch->{'srchby'} eq 'uname') && 
 4681:                         ($srch->{'srchtype'} eq 'exact')) {
 4682:                         $ccuname = $srch->{'srchterm'};
 4683:                         $ccdomain= $srch->{'srchdomain'};
 4684:                     } else {
 4685:                         my @matchedunames = keys(%{$results});
 4686:                         ($ccuname,$ccdomain) = split(/:/,$matchedunames[0]);
 4687:                     }
 4688:                     $ccuname =&LONCAPA::clean_username($ccuname);
 4689:                     $ccdomain=&LONCAPA::clean_domain($ccdomain);
 4690:                     if ($env{'form.forcenewuser'}) {
 4691:                         $response = '';
 4692:                     }
 4693:                     &print_user_modification_page($r,$ccuname,$ccdomain,
 4694:                                                   $srch,$response,$context,
 4695:                                                   $permission,$crstype,$brcrum);
 4696:                 } elsif ($currstate eq 'query') {
 4697:                     &print_user_query_page($r,'createuser',$brcrum);
 4698:                 } else {
 4699:                     $env{'form.phase'} = '';
 4700:                     &print_username_entry_form($r,$context,$response,$srch,
 4701:                                                $forcenewuser,$crstype,$brcrum);
 4702:                 }
 4703:             } elsif ($env{'form.phase'} eq 'userpicked') {
 4704:                 my $ccuname = &LONCAPA::clean_username($env{'form.seluname'});
 4705:                 my $ccdomain = &LONCAPA::clean_domain($env{'form.seludom'});
 4706:                 &print_user_modification_page($r,$ccuname,$ccdomain,$srch,'',
 4707:                                               $context,$permission,$crstype,
 4708:                                               $brcrum);
 4709:             }
 4710:         } elsif ($env{'form.phase'} eq 'update_user_data') {
 4711:             &update_user_data($r,$context,$crstype,$brcrum,$showcredits);
 4712:         } else {
 4713:             &print_username_entry_form($r,$context,undef,$srch,undef,$crstype,
 4714:                                        $brcrum);
 4715:         }
 4716:     } elsif ($env{'form.action'} eq 'custom' && $permission->{'custom'}) {
 4717:         if ($env{'form.phase'} eq 'set_custom_roles') {
 4718:             &set_custom_role($r,$context,$brcrum);
 4719:         } else {
 4720:             &custom_role_editor($r,$brcrum);
 4721:         }
 4722:     } elsif (($env{'form.action'} eq 'processauthorreq') &&
 4723:              ($permission->{'cusr'}) && 
 4724:              (&Apache::lonnet::allowed('cau',$env{'request.role.domain'}))) {
 4725:         push(@{$brcrum},
 4726:                  {href => '/adm/createuser?action=processauthorreq',
 4727:                   text => 'Authoring Space requests',
 4728:                   help => 'Domain_Role_Approvals'});
 4729:         $bread_crumbs_component = 'Authoring requests';
 4730:         if ($env{'form.state'} eq 'done') {
 4731:             push(@{$brcrum},
 4732:                      {href => '/adm/createuser?action=authorreqqueue',
 4733:                       text => 'Result',
 4734:                       help => 'Domain_Role_Approvals'});
 4735:             $bread_crumbs_component = 'Authoring request result';
 4736:         }
 4737:         $args = { bread_crumbs           => $brcrum,
 4738:                   bread_crumbs_component => $bread_crumbs_component};
 4739:         my $js = &usernamerequest_javascript();
 4740:         $r->print(&header(&add_script($js),$args));
 4741:         if (!exists($env{'form.state'})) {
 4742:             $r->print(&Apache::loncoursequeueadmin::display_queued_requests('requestauthor',
 4743:                                                                             $env{'request.role.domain'}));
 4744:         } elsif ($env{'form.state'} eq 'done') {
 4745:             $r->print('<h3>'.&mt('Authoring request processing').'</h3>'."\n");
 4746:             $r->print(&Apache::loncoursequeueadmin::update_request_queue('requestauthor',
 4747:                                                                          $env{'request.role.domain'}));
 4748:         }
 4749:     } elsif (($env{'form.action'} eq 'processusernamereq') &&
 4750:              ($permission->{'cusr'}) &&
 4751:              (&Apache::lonnet::allowed('cau',$env{'request.role.domain'}))) {
 4752:         push(@{$brcrum},
 4753:                  {href => '/adm/createuser?action=processusernamereq',
 4754:                   text => 'LON-CAPA account requests',
 4755:                   help => 'Domain_Username_Approvals'});
 4756:         $bread_crumbs_component = 'Account requests';
 4757:         if ($env{'form.state'} eq 'done') {
 4758:             push(@{$brcrum},
 4759:                      {href => '/adm/createuser?action=usernamereqqueue',
 4760:                       text => 'Result',
 4761:                       help => 'Domain_Username_Approvals'});
 4762:             $bread_crumbs_component = 'LON-CAPA account request result';
 4763:         }
 4764:         $args = { bread_crumbs           => $brcrum,
 4765:                   bread_crumbs_component => $bread_crumbs_component};
 4766:         my $js = &usernamerequest_javascript();
 4767:         $r->print(&header(&add_script($js),$args));
 4768:         if (!exists($env{'form.state'})) {
 4769:             $r->print(&Apache::loncoursequeueadmin::display_queued_requests('requestusername',
 4770:                                                                             $env{'request.role.domain'}));
 4771:         } elsif ($env{'form.state'} eq 'done') {
 4772:             $r->print('<h3>'.&mt('LON-CAPA account request processing').'</h3>'."\n");
 4773:             $r->print(&Apache::loncoursequeueadmin::update_request_queue('requestusername',
 4774:                                                                          $env{'request.role.domain'}));
 4775:         }
 4776:     } elsif (($env{'form.action'} eq 'displayuserreq') &&
 4777:              ($permission->{'cusr'})) {
 4778:         my $dom = $env{'form.domain'};
 4779:         my $uname = $env{'form.username'};
 4780:         my $warning;
 4781:         if (($dom =~ /^$match_domain$/) && (&Apache::lonnet::domain($dom) ne '')) {
 4782:             if (($dom eq $env{'request.role.domain'}) && (&Apache::lonnet::allowed('ccc',$dom))) {
 4783:                 if (($uname =~ /^$match_username$/) && ($env{'form.queue'} eq 'approval')) {
 4784:                     my $uhome = &Apache::lonnet::homeserver($uname,$dom);
 4785:                     if ($uhome eq 'no_host') {
 4786:                         my $queue = $env{'form.queue'};
 4787:                         my $reqkey = &escape($uname).'_'.$queue; 
 4788:                         my $namespace = 'usernamequeue';
 4789:                         my $domconfig = &Apache::lonnet::get_domainconfiguser($dom);
 4790:                         my %queued =
 4791:                             &Apache::lonnet::get($namespace,[$reqkey],$dom,$domconfig);
 4792:                         unless ($queued{$reqkey}) {
 4793:                             $warning = &mt('No information was found for this LON-CAPA account request.');
 4794:                         }
 4795:                     } else {
 4796:                         $warning = &mt('A LON-CAPA account already exists for the requested username and domain.');
 4797:                     }
 4798:                 } else {
 4799:                     $warning = &mt('LON-CAPA account request status check is for an invalid username.');
 4800:                 }
 4801:             } else {
 4802:                 $warning = &mt('You do not have rights to view LON-CAPA account requests in the domain specified.');
 4803:             }
 4804:         } else {
 4805:             $warning = &mt('LON-CAPA account request status check is for an invalid domain.');
 4806:         }
 4807:         my $args = { only_body => 1 };
 4808:         $r->print(&header(undef,$args).
 4809:                   '<h3>'.&mt('LON-CAPA Account Request Details').'</h3>');
 4810:         if ($warning ne '') {
 4811:             $r->print('<div class="LC_warning">'.$warning.'</div>');
 4812:         } else {
 4813:             my ($infofields,$infotitles) = &Apache::loncommon::emailusername_info();
 4814:             my $domconfiguser = &Apache::lonnet::get_domainconfiguser($dom);
 4815:             my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 4816:             if (ref($domconfig{'usercreation'}) eq 'HASH') {
 4817:                 if (ref($domconfig{'usercreation'}{'cancreate'}) eq 'HASH') {
 4818:                     if (ref($domconfig{'usercreation'}{'cancreate'}{'emailusername'}) eq 'HASH') {
 4819:                         my $count = scalar(keys(%{$domconfig{'usercreation'}{'cancreate'}{'emailusername'}}));
 4820:                         my %info =
 4821:                             &Apache::lonnet::get('nohist_requestedusernames',[$uname],$dom,$domconfiguser);
 4822:                         if (ref($info{$uname}) eq 'HASH') {
 4823:                             if ((ref($infofields) eq 'ARRAY') && (ref($infotitles) eq 'HASH')) {
 4824:                                 $r->print('<div>'.&Apache::lonhtmlcommon::start_pick_box());
 4825:                                 my $num;
 4826:                                 foreach my $field (@{$infofields}) {
 4827:                                     next unless ($domconfig{'usercreation'}{'cancreate'}{'emailusername'}{$field});
 4828:                                     next unless ($infotitles->{$field});
 4829:                                     $r->print(&Apache::lonhtmlcommon::row_title($infotitles->{$field}).
 4830:                                               $info{$uname}{$field});
 4831:                                     $num ++;
 4832:                                     if ($count == $num) {
 4833:                                         $r->print(&Apache::lonhtmlcommon::row_closure(1));
 4834:                                     } else {
 4835:                                         $r->print(&Apache::lonhtmlcommon::row_closure());
 4836:                                     }
 4837:                                 }
 4838:                                 $r->print(&Apache::lonhtmlcommon::end_pick_box().'</div>');
 4839:                             }
 4840:                         }
 4841:                     }
 4842:                 }
 4843:             }
 4844:             $r->print(&close_popup_form());
 4845:         }
 4846:     } elsif (($env{'form.action'} eq 'listusers') && 
 4847:              ($permission->{'view'} || $permission->{'cusr'})) {
 4848:         if ($env{'form.phase'} eq 'bulkchange') {
 4849:             push(@{$brcrum},
 4850:                     {href => '/adm/createuser?action=listusers',
 4851:                      text => "List Users"},
 4852:                     {href => "/adm/createuser",
 4853:                      text => "Result",
 4854:                      help => 'Course_View_Class_List'});
 4855:             $bread_crumbs_component = 'Update Users';
 4856:             $args = {bread_crumbs           => $brcrum,
 4857:                      bread_crumbs_component => $bread_crumbs_component};
 4858:             $r->print(&header(undef,$args));
 4859:             my $setting = $env{'form.roletype'};
 4860:             my $choice = $env{'form.bulkaction'};
 4861:             if ($permission->{'cusr'}) {
 4862:                 &Apache::lonuserutils::update_user_list($r,$context,$setting,$choice,$crstype);
 4863:             } else {
 4864:                 $r->print(&mt('You are not authorized to make bulk changes to user roles'));
 4865:                 $r->print('<p><a href="/adm/createuser?action=listusers">'.&mt('Display User Lists').'</a>');
 4866:             }
 4867:         } else {
 4868:             push(@{$brcrum},
 4869:                     {href => '/adm/createuser?action=listusers',
 4870:                      text => "List Users",
 4871:                      help => 'Course_View_Class_List'});
 4872:             $bread_crumbs_component = 'List Users';
 4873:             $args = {bread_crumbs           => $brcrum,
 4874:                      bread_crumbs_component => $bread_crumbs_component};
 4875:             my ($cb_jscript,$jscript,$totcodes,$codetitles,$idlist,$idlist_titles);
 4876:             my $formname = 'studentform';
 4877:             my $hidecall = "hide_searching();";
 4878:             if (($context eq 'domain') && (($env{'form.roletype'} eq 'course') ||
 4879:                 ($env{'form.roletype'} eq 'community'))) {
 4880:                 if ($env{'form.roletype'} eq 'course') {
 4881:                     ($cb_jscript,$jscript,$totcodes,$codetitles,$idlist,$idlist_titles) = 
 4882:                         &Apache::lonuserutils::courses_selector($env{'request.role.domain'},
 4883:                                                                 $formname);
 4884:                 } elsif ($env{'form.roletype'} eq 'community') {
 4885:                     $cb_jscript = 
 4886:                         &Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'});
 4887:                     my %elements = (
 4888:                                       coursepick => 'radio',
 4889:                                       coursetotal => 'text',
 4890:                                       courselist => 'text',
 4891:                                    );
 4892:                     $jscript = &Apache::lonhtmlcommon::set_form_elements(\%elements);
 4893:                 }
 4894:                 $jscript .= &verify_user_display($context)."\n".
 4895:                             &Apache::loncommon::check_uncheck_jscript();
 4896:                 my $js = &add_script($jscript).$cb_jscript;
 4897:                 my $loadcode = 
 4898:                     &Apache::lonuserutils::course_selector_loadcode($formname);
 4899:                 if ($loadcode ne '') {
 4900:                     $args->{add_entries} = {onload => "$loadcode;$hidecall"};
 4901:                 } else {
 4902:                     $args->{add_entries} = {onload => $hidecall};
 4903:                 }
 4904:                 $r->print(&header($js,$args));
 4905:             } else {
 4906:                 $args->{add_entries} = {onload => $hidecall};
 4907:                 $jscript = &verify_user_display($context).
 4908:                            &Apache::loncommon::check_uncheck_jscript(); 
 4909:                 $r->print(&header(&add_script($jscript),$args));
 4910:             }
 4911:             &Apache::lonuserutils::print_userlist($r,undef,$permission,$context,
 4912:                          $formname,$totcodes,$codetitles,$idlist,$idlist_titles,
 4913:                          $showcredits);
 4914:         }
 4915:     } elsif ($env{'form.action'} eq 'drop' && $permission->{'cusr'}) {
 4916:         my $brtext;
 4917:         if ($crstype eq 'Community') {
 4918:             $brtext = 'Drop Members';
 4919:         } else {
 4920:             $brtext = 'Drop Students';
 4921:         }
 4922:         push(@{$brcrum},
 4923:                 {href => '/adm/createuser?action=drop',
 4924:                  text => $brtext,
 4925:                  help => 'Course_Drop_Student'});
 4926:         if ($env{'form.state'} eq 'done') {
 4927:             push(@{$brcrum},
 4928:                      {href=>'/adm/createuser?action=drop',
 4929:                       text=>"Result"});
 4930:         }
 4931:         $bread_crumbs_component = $brtext;
 4932:         $args = {bread_crumbs           => $brcrum,
 4933:                  bread_crumbs_component => $bread_crumbs_component}; 
 4934:         $r->print(&header(undef,$args));
 4935:         if (!exists($env{'form.state'})) {
 4936:             &Apache::lonuserutils::print_drop_menu($r,$context,$permission,$crstype);
 4937:         } elsif ($env{'form.state'} eq 'done') {
 4938:             &Apache::lonuserutils::update_user_list($r,$context,undef,
 4939:                                                     $env{'form.action'});
 4940:         }
 4941:     } elsif ($env{'form.action'} eq 'dateselect') {
 4942:         if ($permission->{'cusr'}) {
 4943:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 4944:                       &Apache::lonuserutils::date_section_selector($context,$permission,
 4945:                                                                    $crstype,$showcredits));
 4946:         } else {
 4947:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 4948:                      '<span class="LC_error">'.&mt('You do not have permission to modify dates or sections for users').'</span>'); 
 4949:         }
 4950:     } elsif ($env{'form.action'} eq 'selfenroll') {
 4951:         push(@{$brcrum},
 4952:                 {href => '/adm/createuser?action=selfenroll',
 4953:                  text => "Configure Self-enrollment",
 4954:                  help => 'Course_Self_Enrollment'});
 4955:         if (!exists($env{'form.state'})) {
 4956:             $args = { bread_crumbs           => $brcrum,
 4957:                       bread_crumbs_component => 'Configure Self-enrollment'};
 4958:             $r->print(&header(undef,$args));
 4959:             $r->print('<h3>'.&mt('Self-enrollment with a student role').'</h3>'."\n");
 4960:             &print_selfenroll_menu($r,$context,$permission);
 4961:         } elsif ($env{'form.state'} eq 'done') {
 4962:             push (@{$brcrum},
 4963:                       {href=>'/adm/createuser?action=selfenroll',
 4964:                        text=>"Result"});
 4965:             $args = { bread_crumbs           => $brcrum,
 4966:                       bread_crumbs_component => 'Self-enrollment result'};
 4967:             $r->print(&header(undef,$args));
 4968:             $r->print('<h3>'.&mt('Self-enrollment with a student role').'</h3>'."\n");
 4969:             &update_selfenroll_config($r,$context,$permission);
 4970:         }
 4971:     } elsif ($env{'form.action'} eq 'selfenrollqueue') {
 4972:         push(@{$brcrum},
 4973:                  {href => '/adm/createuser?action=selfenrollqueue',
 4974:                   text => 'Enrollment requests',
 4975:                   help => 'Course_Self_Enrollment'});
 4976:         $bread_crumbs_component = 'Enrollment requests';
 4977:         if ($env{'form.state'} eq 'done') {
 4978:             push(@{$brcrum},
 4979:                      {href => '/adm/createuser?action=selfenrollqueue',
 4980:                       text => 'Result',
 4981:                       help => 'Course_Self_Enrollment'});
 4982:             $bread_crumbs_component = 'Enrollment result';
 4983:         }
 4984:         $args = { bread_crumbs           => $brcrum,
 4985:                   bread_crumbs_component => $bread_crumbs_component};
 4986:         $r->print(&header(undef,$args));
 4987:         my $cid = $env{'request.course.id'};
 4988:         my $cdom = $env{'course.'.$cid.'.domain'};
 4989:         my $cnum = $env{'course.'.$cid.'.num'};
 4990:         my $coursedesc = $env{'course.'.$cid.'.description'};
 4991:         if (!exists($env{'form.state'})) {
 4992:             $r->print('<h3>'.&mt('Pending enrollment requests').'</h3>'."\n");
 4993:             $r->print(&Apache::loncoursequeueadmin::display_queued_requests($context,
 4994:                                                                        $cdom,$cnum));
 4995:         } elsif ($env{'form.state'} eq 'done') {
 4996:             $r->print('<h3>'.&mt('Enrollment request processing').'</h3>'."\n");
 4997:             $r->print(&Apache::loncoursequeueadmin::update_request_queue($context,
 4998:                           $cdom,$cnum,$coursedesc));
 4999:         }
 5000:     } elsif ($env{'form.action'} eq 'changelogs') {
 5001:         my $helpitem;
 5002:         if ($context eq 'course') {
 5003:             $helpitem = 'Course_User_Logs';
 5004:         }
 5005:         push (@{$brcrum},
 5006:                  {href => '/adm/createuser?action=changelogs',
 5007:                   text => 'User Management Logs',
 5008:                   help => $helpitem});
 5009:         $bread_crumbs_component = 'User Changes';
 5010:         $args = { bread_crumbs           => $brcrum,
 5011:                   bread_crumbs_component => $bread_crumbs_component};
 5012:         $r->print(&header(undef,$args));
 5013:         &print_userchangelogs_display($r,$context,$permission);
 5014:     } else {
 5015:         $bread_crumbs_component = 'User Management';
 5016:         $args = { bread_crumbs           => $brcrum,
 5017:                   bread_crumbs_component => $bread_crumbs_component};
 5018:         $r->print(&header(undef,$args));
 5019:         $r->print(&print_main_menu($permission,$context,$crstype));
 5020:     }
 5021:     $r->print(&Apache::loncommon::end_page());
 5022:     return OK;
 5023: }
 5024: 
 5025: sub header {
 5026:     my ($jscript,$args) = @_;
 5027:     my $start_page;
 5028:     if (ref($args) eq 'HASH') {
 5029:         $start_page=&Apache::loncommon::start_page('User Management',$jscript,$args);
 5030:     } else {
 5031:         $start_page=&Apache::loncommon::start_page('User Management',$jscript);
 5032:     }
 5033:     return $start_page;
 5034: }
 5035: 
 5036: sub add_script {
 5037:     my ($js) = @_;
 5038:     return '<script type="text/javascript">'."\n"
 5039:           .'// <![CDATA['."\n"
 5040:           .$js."\n"
 5041:           .'// ]]>'."\n"
 5042:           .'</script>'."\n";
 5043: }
 5044: 
 5045: sub usernamerequest_javascript {
 5046:     my $js = <<ENDJS;
 5047: 
 5048: function openusernamereqdisplay(dom,uname,queue) {
 5049:     var url = '/adm/createuser?action=displayuserreq';
 5050:     url += '&domain='+dom+'&username='+uname+'&queue='+queue;
 5051:     var title = 'Account_Request_Browser';
 5052:     var options = 'scrollbars=1,resizable=1,menubar=0';
 5053:     options += ',width=700,height=600';
 5054:     var stdeditbrowser = open(url,title,options,'1');
 5055:     stdeditbrowser.focus();
 5056:     return;
 5057: }
 5058:  
 5059: ENDJS
 5060: }
 5061: 
 5062: sub close_popup_form {
 5063:     my $close= &mt('Close Window');
 5064:     return << "END";
 5065: <p><form name="displayreq" action="" method="post">
 5066: <input type="button" name="closeme" value="$close" onclick="javascript:self.close();" />
 5067: </form></p>
 5068: END
 5069: }
 5070: 
 5071: sub verify_user_display {
 5072:     my ($context) = @_;
 5073:     my %lt = &Apache::lonlocal::texthash (
 5074:         course    => 'course(s): description, section(s), status',
 5075:         community => 'community(s): description, section(s), status',
 5076:         author    => 'author',
 5077:     );
 5078:     my $photos;
 5079:     if (($context eq 'course') && $env{'request.course.id'}) {
 5080:         $photos = $env{'course.'.$env{'request.course.id'}.'.internal.showphoto'};
 5081:     }
 5082:     my $output = <<"END";
 5083: 
 5084: function hide_searching() {
 5085:     if (document.getElementById('searching')) {
 5086:         document.getElementById('searching').style.display = 'none';
 5087:     }
 5088:     return;
 5089: }
 5090: 
 5091: function display_update() {
 5092:     document.studentform.action.value = 'listusers';
 5093:     document.studentform.phase.value = 'display';
 5094:     document.studentform.submit();
 5095: }
 5096: 
 5097: function updateCols(caller) {
 5098:     var context = '$context';
 5099:     var photos = '$photos';
 5100:     if (caller == 'Status') {
 5101:         if ((context == 'domain') && 
 5102:             ((document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'course') ||
 5103:              (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'community'))) {
 5104:             document.getElementById('showcolstatus').checked = false;
 5105:             document.getElementById('showcolstatus').disabled = 'disabled';
 5106:             document.getElementById('showcolstart').checked = false;
 5107:             document.getElementById('showcolend').checked = false;
 5108:         } else {
 5109:             if (document.studentform.Status.options[document.studentform.Status.selectedIndex].value == 'Any') {
 5110:                 document.getElementById('showcolstatus').checked = true;
 5111:                 document.getElementById('showcolstatus').disabled = '';
 5112:                 document.getElementById('showcolstart').checked = true;
 5113:                 document.getElementById('showcolend').checked = true;
 5114:             } else {
 5115:                 document.getElementById('showcolstatus').checked = false;
 5116:                 document.getElementById('showcolstatus').disabled = 'disabled';
 5117:                 document.getElementById('showcolstart').checked = false;
 5118:                 document.getElementById('showcolend').checked = false;
 5119:             }
 5120:         }
 5121:     }
 5122:     if (caller == 'output') {
 5123:         if (photos == 1) {
 5124:             if (document.getElementById('showcolphoto')) {
 5125:                 var photoitem = document.getElementById('showcolphoto');
 5126:                 if (document.studentform.output.options[document.studentform.output.selectedIndex].value == 'html') {
 5127:                     photoitem.checked = true;
 5128:                     photoitem.disabled = '';
 5129:                 } else {
 5130:                     photoitem.checked = false;
 5131:                     photoitem.disabled = 'disabled';
 5132:                 }
 5133:             }
 5134:         }
 5135:     }
 5136:     if (caller == 'showrole') {
 5137:         if ((document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'Any') ||
 5138:             (document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'cr')) {
 5139:             document.getElementById('showcolrole').checked = true;
 5140:             document.getElementById('showcolrole').disabled = '';
 5141:         } else {
 5142:             document.getElementById('showcolrole').checked = false;
 5143:             document.getElementById('showcolrole').disabled = 'disabled';
 5144:         }
 5145:         if (context == 'domain') {
 5146:             var quotausageshow = 0;
 5147:             if ((document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'course') ||
 5148:                 (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'community')) {
 5149:                 document.getElementById('showcolstatus').checked = false;
 5150:                 document.getElementById('showcolstatus').disabled = 'disabled';
 5151:                 document.getElementById('showcolstart').checked = false;
 5152:                 document.getElementById('showcolend').checked = false;
 5153:             } else {
 5154:                 if (document.studentform.Status.options[document.studentform.Status.selectedIndex].value == 'Any') {
 5155:                     document.getElementById('showcolstatus').checked = true;
 5156:                     document.getElementById('showcolstatus').disabled = '';
 5157:                     document.getElementById('showcolstart').checked = true;
 5158:                     document.getElementById('showcolend').checked = true;
 5159:                 }
 5160:             }
 5161:             if (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'domain') {
 5162:                 document.getElementById('showcolextent').disabled = 'disabled';
 5163:                 document.getElementById('showcolextent').checked = 'false';
 5164:                 document.getElementById('showextent').style.display='none';
 5165:                 document.getElementById('showcoltextextent').innerHTML = '';
 5166:                 if ((document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'au') ||
 5167:                     (document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'Any')) {
 5168:                     if (document.getElementById('showcolauthorusage')) {
 5169:                         document.getElementById('showcolauthorusage').disabled = '';
 5170:                     }
 5171:                     if (document.getElementById('showcolauthorquota')) {
 5172:                         document.getElementById('showcolauthorquota').disabled = '';
 5173:                     }
 5174:                     quotausageshow = 1;
 5175:                 }
 5176:             } else {
 5177:                 document.getElementById('showextent').style.display='block';
 5178:                 document.getElementById('showextent').style.textAlign='left';
 5179:                 document.getElementById('showextent').style.textFace='normal';
 5180:                 if (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'author') {
 5181:                     document.getElementById('showcolextent').disabled = '';
 5182:                     document.getElementById('showcolextent').checked = 'true';
 5183:                     document.getElementById('showcoltextextent').innerHTML="$lt{'author'}";
 5184:                 } else {
 5185:                     document.getElementById('showcolextent').disabled = '';
 5186:                     document.getElementById('showcolextent').checked = 'true';
 5187:                     if (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'community') {
 5188:                         document.getElementById('showcoltextextent').innerHTML="$lt{'community'}";
 5189:                     } else {
 5190:                         document.getElementById('showcoltextextent').innerHTML="$lt{'course'}";
 5191:                     }
 5192:                 }
 5193:             }
 5194:             if (quotausageshow == 0)  {
 5195:                 if (document.getElementById('showcolauthorusage')) {
 5196:                     document.getElementById('showcolauthorusage').checked = false;
 5197:                     document.getElementById('showcolauthorusage').disabled = 'disabled';
 5198:                 }
 5199:                 if (document.getElementById('showcolauthorquota')) {
 5200:                     document.getElementById('showcolauthorquota').checked = false;
 5201:                     document.getElementById('showcolauthorquota').disabled = 'disabled';
 5202:                 }
 5203:             }
 5204:         }
 5205:     }
 5206:     return;
 5207: }
 5208: 
 5209: END
 5210:     return $output;
 5211: 
 5212: }
 5213: 
 5214: ###############################################################
 5215: ###############################################################
 5216: #  Menu Phase One
 5217: sub print_main_menu {
 5218:     my ($permission,$context,$crstype) = @_;
 5219:     my $linkcontext = $context;
 5220:     my $stuterm = lc(&Apache::lonnet::plaintext('st',$crstype));
 5221:     if (($context eq 'course') && ($crstype eq 'Community')) {
 5222:         $linkcontext = lc($crstype);
 5223:         $stuterm = 'Members';
 5224:     }
 5225:     my %links = (
 5226:                 domain => {
 5227:                             upload     => 'Upload a File of Users',
 5228:                             singleuser => 'Add/Modify a User',
 5229:                             listusers  => 'Manage Users',
 5230:                             },
 5231:                 author => {
 5232:                             upload     => 'Upload a File of Co-authors',
 5233:                             singleuser => 'Add/Modify a Co-author',
 5234:                             listusers  => 'Manage Co-authors',
 5235:                             },
 5236:                 course => {
 5237:                             upload     => 'Upload a File of Course Users',
 5238:                             singleuser => 'Add/Modify a Course User',
 5239:                             listusers  => 'List and Modify Multiple Course Users',
 5240:                             },
 5241:                 community => {
 5242:                             upload     => 'Upload a File of Community Users',
 5243:                             singleuser => 'Add/Modify a Community User',
 5244:                             listusers  => 'List and Modify Multiple Community Users',
 5245:                            },
 5246:                 );
 5247:      my %linktitles = (
 5248:                 domain => {
 5249:                             singleuser => 'Add a user to the domain, and/or a course or community in the domain.',
 5250:                             listusers  => 'Show and manage users in this domain.',
 5251:                             },
 5252:                 author => {
 5253:                             singleuser => 'Add a user with a co- or assistant author role.',
 5254:                             listusers  => 'Show and manage co- or assistant authors.',
 5255:                             },
 5256:                 course => {
 5257:                             singleuser => 'Add a user with a certain role to this course.',
 5258:                             listusers  => 'Show and manage users in this course.',
 5259:                             },
 5260:                 community => {
 5261:                             singleuser => 'Add a user with a certain role to this community.',
 5262:                             listusers  => 'Show and manage users in this community.',
 5263:                            },
 5264:                 );
 5265:   my @menu = ( {categorytitle => 'Single Users', 
 5266:          items =>
 5267:          [
 5268:             {
 5269:              linktext => $links{$linkcontext}{'singleuser'},
 5270:              icon => 'edit-redo.png',
 5271:              #help => 'Course_Change_Privileges',
 5272:              url => '/adm/createuser?action=singleuser',
 5273:              permission => $permission->{'cusr'},
 5274:              linktitle => $linktitles{$linkcontext}{'singleuser'},
 5275:             },
 5276:          ]},
 5277: 
 5278:          {categorytitle => 'Multiple Users',
 5279:          items => 
 5280:          [
 5281:             {
 5282:              linktext => $links{$linkcontext}{'upload'},
 5283:              icon => 'uplusr.png',
 5284:              #help => 'Course_Create_Class_List',
 5285:              url => '/adm/createuser?action=upload',
 5286:              permission => $permission->{'cusr'},
 5287:              linktitle => 'Upload a CSV or a text file containing users.',
 5288:             },
 5289:             {
 5290:              linktext => $links{$linkcontext}{'listusers'},
 5291:              icon => 'mngcu.png',
 5292:              #help => 'Course_View_Class_List',
 5293:              url => '/adm/createuser?action=listusers',
 5294:              permission => ($permission->{'view'} || $permission->{'cusr'}),
 5295:              linktitle => $linktitles{$linkcontext}{'listusers'}, 
 5296:             },
 5297: 
 5298:          ]},
 5299: 
 5300:          {categorytitle => 'Administration',
 5301:          items => [ ]},
 5302:        );
 5303:             
 5304:     if ($context eq 'domain'){
 5305:         
 5306:         push(@{ $menu[2]->{items} }, #Category: Administration
 5307:             {
 5308:              linktext => 'Custom Roles',
 5309:              icon => 'emblem-photos.png',
 5310:              #help => 'Course_Editing_Custom_Roles',
 5311:              url => '/adm/createuser?action=custom',
 5312:              permission => $permission->{'custom'},
 5313:              linktitle => 'Configure a custom role.',
 5314:             },
 5315:             {
 5316:              linktext => 'Authoring Space Requests',
 5317:              icon => 'selfenrl-queue.png',
 5318:              #help => 'Domain_Role_Approvals',
 5319:              url => '/adm/createuser?action=processauthorreq',
 5320:              permission => $permission->{'cusr'},
 5321:              linktitle => 'Approve or reject author role requests',
 5322:             },
 5323:             {
 5324:              linktext => 'LON-CAPA Account Requests',
 5325:              icon => 'list-add.png',
 5326:              #help => 'Domain_Username_Approvals',
 5327:              url => '/adm/createuser?action=processusernamereq',
 5328:              permission => $permission->{'cusr'},
 5329:              linktitle => 'Approve or reject LON-CAPA account requests',
 5330:             },
 5331:             {
 5332:              linktext => 'Change Log',
 5333:              icon => 'document-properties.png',
 5334:              #help => 'Course_User_Logs',
 5335:              url => '/adm/createuser?action=changelogs',
 5336:              permission => $permission->{'cusr'},
 5337:              linktitle => 'View change log.',
 5338:             },
 5339:         );
 5340:         
 5341:     }elsif ($context eq 'course'){
 5342:         my ($cnum,$cdom) = &Apache::lonuserutils::get_course_identity();
 5343: 
 5344:         my %linktext = (
 5345:                          'Course'    => {
 5346:                                           single => 'Add/Modify a Student', 
 5347:                                           drop   => 'Drop Students',
 5348:                                           groups => 'Course Groups',
 5349:                                         },
 5350:                          'Community' => {
 5351:                                           single => 'Add/Modify a Member', 
 5352:                                           drop   => 'Drop Members',
 5353:                                           groups => 'Community Groups',
 5354:                                         },
 5355:                        );
 5356: 
 5357:         my %linktitle = (
 5358:             'Course' => {
 5359:                   single => 'Add a user with the role of student to this course',
 5360:                   drop   => 'Remove a student from this course.',
 5361:                   groups => 'Manage course groups',
 5362:                         },
 5363:             'Community' => {
 5364:                   single => 'Add a user with the role of member to this community',
 5365:                   drop   => 'Remove a member from this community.',
 5366:                   groups => 'Manage community groups',
 5367:                            },
 5368:         );
 5369: 
 5370:         push(@{ $menu[0]->{items} }, #Category: Single Users
 5371:             {   
 5372:              linktext => $linktext{$crstype}{'single'},
 5373:              #help => 'Course_Add_Student',
 5374:              icon => 'list-add.png',
 5375:              url => '/adm/createuser?action=singlestudent',
 5376:              permission => $permission->{'cusr'},
 5377:              linktitle => $linktitle{$crstype}{'single'},
 5378:             },
 5379:         );
 5380:         
 5381:         push(@{ $menu[1]->{items} }, #Category: Multiple Users 
 5382:             {
 5383:              linktext => $linktext{$crstype}{'drop'},
 5384:              icon => 'edit-undo.png',
 5385:              #help => 'Course_Drop_Student',
 5386:              url => '/adm/createuser?action=drop',
 5387:              permission => $permission->{'cusr'},
 5388:              linktitle => $linktitle{$crstype}{'drop'},
 5389:             },
 5390:         );
 5391:         push(@{ $menu[2]->{items} }, #Category: Administration
 5392:             {    
 5393:              linktext => 'Custom Roles',
 5394:              icon => 'emblem-photos.png',
 5395:              #help => 'Course_Editing_Custom_Roles',
 5396:              url => '/adm/createuser?action=custom',
 5397:              permission => $permission->{'custom'},
 5398:              linktitle => 'Configure a custom role.',
 5399:             },
 5400:             {
 5401:              linktext => $linktext{$crstype}{'groups'},
 5402:              icon => 'grps.png',
 5403:              #help => 'Course_Manage_Group',
 5404:              url => '/adm/coursegroups?refpage=cusr',
 5405:              permission => $permission->{'grp_manage'},
 5406:              linktitle => $linktitle{$crstype}{'groups'},
 5407:             },
 5408:             {
 5409:              linktext => 'Change Log',
 5410:              icon => 'document-properties.png',
 5411:              #help => 'Course_User_Logs',
 5412:              url => '/adm/createuser?action=changelogs',
 5413:              permission => $permission->{'cusr'},
 5414:              linktitle => 'View change log.',
 5415:             },
 5416:         );
 5417:         if ($env{'course.'.$env{'request.course.id'}.'.internal.selfenroll_approval'}) {
 5418:             push(@{ $menu[2]->{items} },
 5419:                     {   
 5420:                      linktext => 'Enrollment Requests',
 5421:                      icon => 'selfenrl-queue.png',
 5422:                      #help => 'Course_Approve_Selfenroll',
 5423:                      url => '/adm/createuser?action=selfenrollqueue',
 5424:                      permission => $permission->{'cusr'},
 5425:                      linktitle =>'Approve or reject enrollment requests.',
 5426:                     },
 5427:             );
 5428:         }
 5429:         
 5430:         if (!exists($permission->{'cusr_section'})){
 5431:             if ($crstype ne 'Community') {
 5432:                 push(@{ $menu[2]->{items} },
 5433:                     {
 5434:                      linktext => 'Automated Enrollment',
 5435:                      icon => 'roles.png',
 5436:                      #help => 'Course_Automated_Enrollment',
 5437:                      permission => (&Apache::lonnet::auto_run($cnum,$cdom)
 5438:                                          && $permission->{'cusr'}),
 5439:                      url  => '/adm/populate',
 5440:                      linktitle => 'Automated enrollment manager.',
 5441:                     }
 5442:                 );
 5443:             }
 5444:             push(@{ $menu[2]->{items} }, 
 5445:                 {
 5446:                  linktext => 'User Self-Enrollment',
 5447:                  icon => 'self_enroll.png',
 5448:                  #help => 'Course_Self_Enrollment',
 5449:                  url => '/adm/createuser?action=selfenroll',
 5450:                  permission => $permission->{'cusr'},
 5451:                  linktitle => 'Configure user self-enrollment.',
 5452:                 },
 5453:             );
 5454:         }
 5455:     } elsif ($context eq 'author') {
 5456:         push(@{ $menu[2]->{items} }, #Category: Administration
 5457:             {
 5458:              linktext => 'Change Log',
 5459:              icon => 'document-properties.png',
 5460:              #help => 'Course_User_Logs',
 5461:              url => '/adm/createuser?action=changelogs',
 5462:              permission => $permission->{'cusr'},
 5463:              linktitle => 'View change log.',
 5464:             },
 5465:         );
 5466:     }
 5467:     return Apache::lonhtmlcommon::generate_menu(@menu);
 5468: #               { text => 'View Log-in History',
 5469: #                 help => 'Course_User_Logins',
 5470: #                 action => 'logins',
 5471: #                 permission => $permission->{'cusr'},
 5472: #               });
 5473: }
 5474: 
 5475: sub restore_prev_selections {
 5476:     my %saveable_parameters = ('srchby'   => 'scalar',
 5477: 			       'srchin'   => 'scalar',
 5478: 			       'srchtype' => 'scalar',
 5479: 			       );
 5480:     &Apache::loncommon::store_settings('user','user_picker',
 5481: 				       \%saveable_parameters);
 5482:     &Apache::loncommon::restore_settings('user','user_picker',
 5483: 					 \%saveable_parameters);
 5484: }
 5485: 
 5486: sub print_selfenroll_menu {
 5487:     my ($r,$context,$permission) = @_;
 5488:     my $crstype = &Apache::loncommon::course_type();
 5489:     my $formname = 'enrollstudent';
 5490:     my $nolink = 1;
 5491:     my ($row,$lt) = &get_selfenroll_titles();
 5492:     my $groupslist = &Apache::lonuserutils::get_groupslist();
 5493:     my $setsec_js = 
 5494:         &Apache::lonuserutils::setsections_javascript($formname,$groupslist);
 5495:     my %alerts = &Apache::lonlocal::texthash(
 5496:         acto => 'Activation of self-enrollment was selected for the following domain(s)',
 5497:         butn => 'but no user types have been checked.',
 5498:         wilf => "Please uncheck 'activate' or check at least one type.",
 5499:     );
 5500:     my $selfenroll_js = <<"ENDSCRIPT";
 5501: function update_types(caller,num) {
 5502:     var delidx = getIndexByName('selfenroll_delete');
 5503:     var actidx = getIndexByName('selfenroll_activate');
 5504:     if (caller == 'selfenroll_all') {
 5505:         var selall;
 5506:         for (var i=0; i<document.$formname.selfenroll_all.length; i++) {
 5507:             if (document.$formname.selfenroll_all[i].checked) {
 5508:                 selall = document.$formname.selfenroll_all[i].value;
 5509:             }
 5510:         }
 5511:         if (selall == 1) {
 5512:             if (delidx != -1) {
 5513:                 if (document.$formname.selfenroll_delete.length) {
 5514:                     for (var j=0; j<document.$formname.selfenroll_delete.length; j++) {
 5515:                         document.$formname.selfenroll_delete[j].checked = true;
 5516:                     }
 5517:                 } else {
 5518:                     document.$formname.elements[delidx].checked = true;
 5519:                 }
 5520:             }
 5521:             if (actidx != -1) {
 5522:                 if (document.$formname.selfenroll_activate.length) {
 5523:                     for (var j=0; j<document.$formname.selfenroll_activate.length; j++) {
 5524:                         document.$formname.selfenroll_activate[j].checked = false;
 5525:                     }
 5526:                 } else {
 5527:                     document.$formname.elements[actidx].checked = false;
 5528:                 }
 5529:             }
 5530:             document.$formname.selfenroll_newdom.selectedIndex = 0; 
 5531:         }
 5532:     }
 5533:     if (caller == 'selfenroll_activate') {
 5534:         if (document.$formname.selfenroll_activate.length) {
 5535:             for (var j=0; j<document.$formname.selfenroll_activate.length; j++) {
 5536:                 if (document.$formname.selfenroll_activate[j].value == num) {
 5537:                     if (document.$formname.selfenroll_activate[j].checked) {
 5538:                         for (var i=0; i<document.$formname.selfenroll_all.length; i++) {
 5539:                             if (document.$formname.selfenroll_all[i].value == '1') {
 5540:                                 document.$formname.selfenroll_all[i].checked = false;
 5541:                             }
 5542:                             if (document.$formname.selfenroll_all[i].value == '0') {
 5543:                                 document.$formname.selfenroll_all[i].checked = true;
 5544:                             }
 5545:                         }
 5546:                     }
 5547:                 }
 5548:             }
 5549:         } else {
 5550:             for (var i=0; i<document.$formname.selfenroll_all.length; i++) {
 5551:                 if (document.$formname.selfenroll_all[i].value == '1') {
 5552:                     document.$formname.selfenroll_all[i].checked = false;
 5553:                 }
 5554:                 if (document.$formname.selfenroll_all[i].value == '0') {
 5555:                     document.$formname.selfenroll_all[i].checked = true;
 5556:                 }
 5557:             }
 5558:         }
 5559:     }
 5560:     if (caller == 'selfenroll_delete') {
 5561:         if (document.$formname.selfenroll_delete.length) {
 5562:             for (var j=0; j<document.$formname.selfenroll_delete.length; j++) {
 5563:                 if (document.$formname.selfenroll_delete[j].value == num) {
 5564:                     if (document.$formname.selfenroll_delete[j].checked) {
 5565:                         var delindex = getIndexByName('selfenroll_types_'+num);
 5566:                         if (delindex != -1) { 
 5567:                             if (document.$formname.elements[delindex].length) {
 5568:                                 for (var k=0; k<document.$formname.elements[delindex].length; k++) {
 5569:                                     document.$formname.elements[delindex][k].checked = false;
 5570:                                 }
 5571:                             } else {
 5572:                                 document.$formname.elements[delindex].checked = false;
 5573:                             }
 5574:                         }
 5575:                     }
 5576:                 }
 5577:             }
 5578:         } else {
 5579:             if (document.$formname.selfenroll_delete.checked) {
 5580:                 var delindex = getIndexByName('selfenroll_types_'+num);
 5581:                 if (delindex != -1) {
 5582:                     if (document.$formname.elements[delindex].length) {
 5583:                         for (var k=0; k<document.$formname.elements[delindex].length; k++) {
 5584:                             document.$formname.elements[delindex][k].checked = false;
 5585:                         }
 5586:                     } else {
 5587:                         document.$formname.elements[delindex].checked = false;
 5588:                     }
 5589:                 }
 5590:             }
 5591:         }
 5592:     }
 5593:     return;
 5594: }
 5595: 
 5596: function validate_types(form) {
 5597:     var needaction = new Array();
 5598:     var countfail = 0;
 5599:     var actidx = getIndexByName('selfenroll_activate');
 5600:     if (actidx != -1) {
 5601:         if (document.$formname.selfenroll_activate.length) {
 5602:             for (var j=0; j<document.$formname.selfenroll_activate.length; j++) {
 5603:                 var num = document.$formname.selfenroll_activate[j].value;
 5604:                 if (document.$formname.selfenroll_activate[j].checked) {
 5605:                     countfail = check_types(num,countfail,needaction)
 5606:                 }
 5607:             }
 5608:         } else {
 5609:             if (document.$formname.selfenroll_activate.checked) {
 5610:                 var num = document.enrollstudent.selfenroll_activate.value;
 5611:                 countfail = check_types(num,countfail,needaction)
 5612:             }
 5613:         }
 5614:     }
 5615:     if (countfail > 0) {
 5616:         var msg = "$alerts{'acto'}\\n";
 5617:         var loopend = needaction.length -1;
 5618:         if (loopend > 0) {
 5619:             for (var m=0; m<loopend; m++) {
 5620:                 msg += needaction[m]+", ";
 5621:             }
 5622:         }
 5623:         msg += needaction[loopend]+"\\n$alerts{'butn'}\\n$alerts{'wilf'}";
 5624:         alert(msg);
 5625:         return; 
 5626:     }
 5627:     setSections(form);
 5628: }
 5629: 
 5630: function check_types(num,countfail,needaction) {
 5631:     var typeidx = getIndexByName('selfenroll_types_'+num);
 5632:     var count = 0;
 5633:     if (typeidx != -1) {
 5634:         if (document.$formname.elements[typeidx].length) {
 5635:             for (var k=0; k<document.$formname.elements[typeidx].length; k++) {
 5636:                 if (document.$formname.elements[typeidx][k].checked) {
 5637:                     count ++;
 5638:                 }
 5639:             }
 5640:         } else {
 5641:             if (document.$formname.elements[typeidx].checked) {
 5642:                 count ++;
 5643:             }
 5644:         }
 5645:         if (count == 0) {
 5646:             var domidx = getIndexByName('selfenroll_dom_'+num);
 5647:             if (domidx != -1) {
 5648:                 var domname = document.$formname.elements[domidx].value;
 5649:                 needaction[countfail] = domname;
 5650:                 countfail ++;
 5651:             }
 5652:         }
 5653:     }
 5654:     return countfail;
 5655: }
 5656: 
 5657: function getIndexByName(item) {
 5658:     for (var i=0;i<document.$formname.elements.length;i++) {
 5659:         if (document.$formname.elements[i].name == item) {
 5660:             return i;
 5661:         }
 5662:     }
 5663:     return -1;
 5664: }
 5665: ENDSCRIPT
 5666:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5667:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 5668: 
 5669:     my $output = '<script type="text/javascript">'."\n".
 5670:                  '// <![CDATA['."\n".
 5671:                  $setsec_js."\n".$selfenroll_js."\n".
 5672:                  '// ]]>'."\n".
 5673:                  '</script>'."\n".
 5674:                  '<h3>'.$lt->{'selfenroll'}.'</h3>'."\n";
 5675:     my ($visible,$cansetvis,$vismsgs,$visactions) = &visible_in_cat($cdom,$cnum);
 5676:     if (ref($visactions) eq 'HASH') {
 5677:         if ($visible) {
 5678:             $output .= '<p class="LC_info">'.$visactions->{'vis'}.'</p>';
 5679:         } else {
 5680:             $output .= '<p class="LC_warning">'.$visactions->{'miss'}.'</p>'
 5681:                       .$visactions->{'yous'}.
 5682:                        '<p>'.$visactions->{'gen'}.'<br />'.$visactions->{'coca'};
 5683:             if (ref($vismsgs) eq 'ARRAY') {
 5684:                 $output .= '<br />'.$visactions->{'make'}.'<ul>';
 5685:                 foreach my $item (@{$vismsgs}) {
 5686:                     $output .= '<li>'.$visactions->{$item}.'</li>';
 5687:                 }
 5688:                 $output .= '</ul>';
 5689:             }
 5690:             $output .= '</p>';
 5691:         }
 5692:     }
 5693:     $output .= '<form name="'.$formname.'" method="post" action="/adm/createuser">'."\n".
 5694:                &Apache::lonhtmlcommon::start_pick_box();
 5695:     if (ref($row) eq 'ARRAY') {
 5696:         foreach my $item (@{$row}) {
 5697:             my $title = $item; 
 5698:             if (ref($lt) eq 'HASH') {
 5699:                 $title = $lt->{$item};
 5700:             }
 5701:             $output .= &Apache::lonhtmlcommon::row_title($title);
 5702:             if ($item eq 'types') {
 5703:                 my $curr_types = $env{'course.'.$env{'request.course.id'}.'.internal.selfenroll_types'};
 5704:                 my $showdomdesc = 1;
 5705:                 my $includeempty = 1;
 5706:                 my $num = 0;
 5707:                 $output .= &Apache::loncommon::start_data_table().
 5708:                            &Apache::loncommon::start_data_table_row()
 5709:                            .'<td colspan="2"><span class="LC_nobreak"><label>'
 5710:                            .&mt('Any user in any domain:')
 5711:                            .'&nbsp;<input type="radio" name="selfenroll_all" value="1" ';
 5712:                 if ($curr_types eq '*') {
 5713:                     $output .= ' checked="checked" '; 
 5714:                 }
 5715:                 $output .= 'onchange="javascript:update_types('.
 5716:                            "'selfenroll_all'".');" />'.&mt('Yes').'</label>'.
 5717:                            '&nbsp;&nbsp;<input type="radio" name="selfenroll_all" value="0" ';
 5718:                 if ($curr_types ne '*') {
 5719:                     $output .= ' checked="checked" ';
 5720:                 }
 5721:                 $output .= ' onchange="javascript:update_types('.
 5722:                            "'selfenroll_all'".');"/>'.&mt('No').'</label></td>'.
 5723:                            &Apache::loncommon::end_data_table_row().
 5724:                            &Apache::loncommon::end_data_table().
 5725:                            &mt('Or').'<br />'.
 5726:                            &Apache::loncommon::start_data_table();
 5727:                 my %currdoms;
 5728:                 if ($curr_types eq '') {
 5729:                     $output .= &new_selfenroll_dom_row($cdom,'0');
 5730:                 } elsif ($curr_types ne '*') {
 5731:                     my @entries = split(/;/,$curr_types);
 5732:                     if (@entries > 0) {
 5733:                         foreach my $entry (@entries) {
 5734:                             my ($currdom,$typestr) = split(/:/,$entry);
 5735:                             $currdoms{$currdom} = 1;
 5736:                             my $domdesc = &Apache::lonnet::domain($currdom);
 5737:                             my @currinsttypes = split(',',$typestr);
 5738:                             $output .= &Apache::loncommon::start_data_table_row()
 5739:                                        .'<td valign="top"><span class="LC_nobreak">'.&mt('Domain:').'<b>'
 5740:                                        .'&nbsp;'.$domdesc.' ('.$currdom.')'
 5741:                                        .'</b><input type="hidden" name="selfenroll_dom_'.$num
 5742:                                        .'" value="'.$currdom.'" /></span><br />'
 5743:                                        .'<span class="LC_nobreak"><label><input type="checkbox" '
 5744:                                        .'name="selfenroll_delete" value="'.$num.'" onchange="javascript:update_types('."'selfenroll_delete','$num'".');" />'
 5745:                                        .&mt('Delete').'</label></span></td>';
 5746:                             $output .= '<td valign="top">&nbsp;&nbsp;'.&mt('User types:').'<br />'
 5747:                                        .&selfenroll_inst_types($num,$currdom,\@currinsttypes).'</td>'
 5748:                                        .&Apache::loncommon::end_data_table_row();
 5749:                             $num ++;
 5750:                         }
 5751:                     }
 5752:                 }
 5753:                 my $add_domtitle = &mt('Users in additional domain:');
 5754:                 if ($curr_types eq '*') { 
 5755:                     $add_domtitle = &mt('Users in specific domain:');
 5756:                 } elsif ($curr_types eq '') {
 5757:                     $add_domtitle = &mt('Users in other domain:');
 5758:                 }
 5759:                 $output .= &Apache::loncommon::start_data_table_row()
 5760:                            .'<td colspan="2"><span class="LC_nobreak">'.$add_domtitle.'</span><br />'
 5761:                            .&Apache::loncommon::select_dom_form('','selfenroll_newdom',
 5762:                                                                 $includeempty,$showdomdesc)
 5763:                            .'<input type="hidden" name="selfenroll_types_total" value="'.$num.'" />'
 5764:                            .'</td>'.&Apache::loncommon::end_data_table_row()
 5765:                            .&Apache::loncommon::end_data_table();
 5766:             } elsif ($item eq 'registered') {
 5767:                 my ($regon,$regoff);
 5768:                 if ($env{'course.'.$env{'request.course.id'}.'.internal.selfenroll_registered'}) {
 5769:                     $regon = ' checked="checked" ';
 5770:                     $regoff = ' ';
 5771:                 } else {
 5772:                     $regon = ' ';
 5773:                     $regoff = ' checked="checked" ';
 5774:                 }
 5775:                 $output .= '<label>'.
 5776:                            '<input type="radio" name="selfenroll_registered" value="1"'.$regon.'/>'.
 5777:                            &mt('Yes').'</label>&nbsp;&nbsp;<label>'.
 5778:                            '<input type="radio" name="selfenroll_registered" value="0"'.$regoff.'/>'.
 5779:                            &mt('No').'</label>';
 5780:             } elsif ($item eq 'enroll_dates') {
 5781:                 my $starttime = $env{'course.'.$env{'request.course.id'}.'.internal.selfenroll_start_date'};
 5782:                 my $endtime = $env{'course.'.$env{'request.course.id'}.'.internal.selfenroll_end_date'};
 5783:                 if ($starttime eq '') {
 5784:                     $starttime = $env{'course.'.$env{'request.course.id'}.'.default_enrollment_start_date'};
 5785:                 }
 5786:                 if ($endtime eq '') {
 5787:                     $endtime = $env{'course.'.$env{'request.course.id'}.'.default_enrollment_end_date'};
 5788:                 }
 5789:                 my $startform =
 5790:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_start_date',$starttime,
 5791:                                       undef,undef,undef,undef,undef,undef,undef,$nolink);
 5792:                 my $endform =
 5793:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_end_date',$endtime,
 5794:                                       undef,undef,undef,undef,undef,undef,undef,$nolink);
 5795:                 $output .= &selfenroll_date_forms($startform,$endform);
 5796:             } elsif ($item eq 'access_dates') {
 5797:                 my $starttime = $env{'course.'.$env{'request.course.id'}.'.internal.selfenroll_start_access'};
 5798:                 my $endtime = $env{'course.'.$env{'request.course.id'}.'.internal.selfenroll_end_access'};
 5799:                 if ($starttime eq '') {
 5800:                     $starttime = $env{'course.'.$env{'request.course.id'}.'.default_enrollment_start_date'};
 5801:                 }
 5802:                 if ($endtime eq '') {
 5803:                     $endtime = $env{'course.'.$env{'request.course.id'}.'.default_enrollment_end_date'};
 5804:                 }
 5805:                 my $startform =
 5806:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_start_access',$starttime,
 5807:                                       undef,undef,undef,undef,undef,undef,undef,$nolink);
 5808:                 my $endform =
 5809:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_end_access',$endtime,
 5810:                                       undef,undef,undef,undef,undef,undef,undef,$nolink);
 5811:                 $output .= &selfenroll_date_forms($startform,$endform);
 5812:             } elsif ($item eq 'section') {
 5813:                 my $currsec = $env{'course.'.$env{'request.course.id'}.'.internal.selfenroll_section'}; 
 5814:                 my %sections_count = &Apache::loncommon::get_sections($cdom,$cnum);
 5815:                 my $newsecval;
 5816:                 if ($currsec ne 'none' && $currsec ne '') {
 5817:                     if (!defined($sections_count{$currsec})) {
 5818:                         $newsecval = $currsec;
 5819:                     }
 5820:                 }
 5821:                 my $sections_select = 
 5822:                     &Apache::lonuserutils::course_sections(\%sections_count,'st',$currsec);
 5823:                 $output .= '<table class="LC_createuser">'."\n".
 5824:                            '<tr class="LC_section_row">'."\n".
 5825:                            '<td align="center">'.&mt('Existing sections')."\n".
 5826:                            '<br />'.$sections_select.'</td><td align="center">'.
 5827:                            &mt('New section').'<br />'."\n".
 5828:                            '<input type="text" name="newsec" size="15" value="'.$newsecval.'" />'."\n".
 5829:                            '<input type="hidden" name="sections" value="" />'."\n".
 5830:                            '<input type="hidden" name="state" value="done" />'."\n".
 5831:                            '</td></tr></table>'."\n";
 5832:             } elsif ($item eq 'approval') {
 5833:                 my ($appon,$appoff);
 5834:                 my $cid = $env{'request.course.id'};
 5835:                 my $currnotified = $env{'course.'.$cid.'.internal.selfenroll_notifylist'};
 5836:                 if ($env{'course.'.$cid.'.internal.selfenroll_approval'}) {
 5837:                     $appon = ' checked="checked" ';
 5838:                     $appoff = ' ';
 5839:                 } else {
 5840:                     $appon = ' ';
 5841:                     $appoff = ' checked="checked" ';
 5842:                 }
 5843:                 $output .= '<label>'.
 5844:                            '<input type="radio" name="selfenroll_approval" value="1"'.$appon.'/>'.
 5845:                            &mt('Yes').'</label>&nbsp;&nbsp;<label>'.
 5846:                            '<input type="radio" name="selfenroll_approval" value="0"'.$appoff.'/>'.
 5847:                            &mt('No').'</label>';
 5848:                 my %advhash = &Apache::lonnet::get_course_adv_roles($cid,1);
 5849:                 my (@ccs,%notified);
 5850:                 my $ccrole = 'cc';
 5851:                 if ($crstype eq 'Community') {
 5852:                     $ccrole = 'co';
 5853:                 }
 5854:                 if ($advhash{$ccrole}) {
 5855:                     @ccs = split(/,/,$advhash{$ccrole});
 5856:                 }
 5857:                 if ($currnotified) {
 5858:                     foreach my $current (split(/,/,$currnotified)) {
 5859:                         $notified{$current} = 1;
 5860:                         if (!grep(/^\Q$current\E$/,@ccs)) {
 5861:                             push(@ccs,$current);
 5862:                         }
 5863:                     }
 5864:                 }
 5865:                 if (@ccs) {
 5866:                     $output .= '<br />'.&mt('Personnel to be notified when an enrollment request needs approval, or has been approved:').'&nbsp;'.&Apache::loncommon::start_data_table().
 5867:                                &Apache::loncommon::start_data_table_row();
 5868:                     my $count = 0;
 5869:                     my $numcols = 4;
 5870:                     foreach my $cc (sort(@ccs)) {
 5871:                         my $notifyon;
 5872:                         my ($ccuname,$ccudom) = split(/:/,$cc);
 5873:                         if ($notified{$cc}) {
 5874:                             $notifyon = ' checked="checked" ';
 5875:                         }
 5876:                         if ($count && !$count%$numcols) {
 5877:                             $output .= &Apache::loncommon::end_data_table_row().
 5878:                                        &Apache::loncommon::start_data_table_row()
 5879:                         }
 5880:                         $output .= '<td><span class="LC_nobreak"><label>'.
 5881:                                    '<input type="checkbox" name="selfenroll_notify"'.$notifyon.' value="'.$cc.'" />'.
 5882:                                    &Apache::loncommon::plainname($ccuname,$ccudom).
 5883:                                    '</label></span></td>';
 5884:                         $count ++;
 5885:                     }
 5886:                     my $rem = $count%$numcols;
 5887:                     if ($rem) {
 5888:                         my $emptycols = $numcols - $rem;
 5889:                         for (my $i=0; $i<$emptycols; $i++) { 
 5890:                             $output .= '<td>&nbsp;</td>';
 5891:                         }
 5892:                     }
 5893:                     $output .= &Apache::loncommon::end_data_table_row().
 5894:                                &Apache::loncommon::end_data_table();
 5895:                 }
 5896:             } elsif ($item eq 'limit') {
 5897:                 my ($crslimit,$selflimit,$nolimit);
 5898:                 my $cid = $env{'request.course.id'};
 5899:                 my $currlim = $env{'course.'.$cid.'.internal.selfenroll_limit'};
 5900:                 my $currcap = $env{'course.'.$cid.'.internal.selfenroll_cap'};
 5901:                 $nolimit = ' checked="checked" ';
 5902:                 if ($currlim eq 'allstudents') {
 5903:                     $crslimit = ' checked="checked" ';
 5904:                     $selflimit = ' ';
 5905:                     $nolimit = ' ';
 5906:                 } elsif ($currlim eq 'selfenrolled') {
 5907:                     $crslimit = ' ';
 5908:                     $selflimit = ' checked="checked" ';
 5909:                     $nolimit = ' '; 
 5910:                 } else {
 5911:                     $crslimit = ' ';
 5912:                     $selflimit = ' ';
 5913:                 }
 5914:                 $output .= '<table><tr><td><label>'.
 5915:                            '<input type="radio" name="selfenroll_limit" value="none"'.$nolimit.'/>'.
 5916:                            &mt('No limit').'</label></td><td><label>'.
 5917:                            '<input type="radio" name="selfenroll_limit" value="allstudents"'.$crslimit.'/>'.
 5918:                            &mt('Limit by total students').'</label></td><td><label>'.
 5919:                            '<input type="radio" name="selfenroll_limit" value="selfenrolled"'.$selflimit.'/>'.
 5920:                            &mt('Limit by total self-enrolled students').
 5921:                            '</td></tr><tr>'.
 5922:                            '<td>&nbsp;</td><td colspan="2"><span class="LC_nobreak">'.
 5923:                            ('&nbsp;'x3).&mt('Maximum number allowed: ').
 5924:                            '<input type="text" name="selfenroll_cap" size = "5" value="'.$currcap.'" /></td></tr></table>';
 5925:             }
 5926:             $output .= &Apache::lonhtmlcommon::row_closure(1);
 5927:         }
 5928:     }
 5929:     $output .= &Apache::lonhtmlcommon::end_pick_box().
 5930:                '<br /><input type="button" name="selfenrollconf" value="'
 5931:                .&mt('Save').'" onclick="validate_types(this.form);" />'
 5932:                .'<input type="hidden" name="action" value="selfenroll" /></form>';
 5933:     $r->print($output);
 5934:     return;
 5935: }
 5936: 
 5937: sub visible_in_cat {
 5938:     my ($cdom,$cnum) = @_;
 5939:     my %domconf = &Apache::lonnet::get_dom('configuration',['coursecategories'],$cdom);
 5940:     my ($cathash,%settable,@vismsgs,$cansetvis);
 5941:     my %visactions = &Apache::lonlocal::texthash(
 5942:                    vis => 'Your course/community currently appears in the Course/Community Catalog for this domain.',
 5943:                    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.',
 5944:                    miss => 'Your course/community does not currently appear in the Course/Community Catalog for this domain.',
 5945:                    yous => 'You should remedy this if you plan to allow self-enrollment, otherwise students will have difficulty finding your course.',
 5946:                    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.',
 5947:                    make => 'Make any changes to self-enrollment settings below, click "Save", then take action to include the course in the Catalog:',
 5948:                    take => 'Take the following action to ensure the course appears in the Catalog:',
 5949:                    dc_unhide  => 'Ask a domain coordinator to change the "Exclude from course catalog" setting.',
 5950:                    dc_addinst => 'Ask a domain coordinator to enable display the catalog of "Official courses (with institutional codes)".',
 5951:                    dc_instcode => 'Ask a domain coordinator to assign an institutional code (if this is an official course).',
 5952:                    dc_catalog  => 'Ask a domain coordinator to enable or create at least one course category in the domain.',
 5953:                    dc_categories => 'Ask a domain coordinator to create a hierarchy of categories and sub categories for courses in the domain.',
 5954:                    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',
 5955:                    dc_addcat => 'Ask a domain coordinator to assign a category to the course.',
 5956:     );
 5957:     $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>"');
 5958:     $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>"');
 5959:     $visactions{'addcat'} = &mt('Use [_1]Categorize course[_2] to assign a category to the course.','"<a href="/adm/courseprefs?phase=display&actions=courseinfo">','</a>"');
 5960:     if (ref($domconf{'coursecategories'}) eq 'HASH') {
 5961:         if ($domconf{'coursecategories'}{'togglecats'} eq 'crs') {
 5962:             $settable{'togglecats'} = 1;
 5963:         }
 5964:         if ($domconf{'coursecategories'}{'categorize'} eq 'crs') {
 5965:             $settable{'categorize'} = 1;
 5966:         }
 5967:         $cathash = $domconf{'coursecategories'}{'cats'};
 5968:     }
 5969:     if ($settable{'togglecats'} && $settable{'categorize'}) {
 5970:         $cansetvis = &mt('You are able to both assign a course category and choose to exclude this course from the catalog.');   
 5971:     } elsif ($settable{'togglecats'}) {
 5972:         $cansetvis = &mt('You are able to choose to exclude this course from the catalog, but only a Domain Coordinator may assign a course category.'); 
 5973:     } elsif ($settable{'categorize'}) {
 5974:         $cansetvis = &mt('You may assign a course category, but only a Domain Coordinator may choose to exclude this course from the catalog.');  
 5975:     } else {
 5976:         $cansetvis = &mt('Only a Domain Coordinator may assign a course category or choose to exclude this course from the catalog.'); 
 5977:     }
 5978:      
 5979:     my %currsettings =
 5980:         &Apache::lonnet::get('environment',['hidefromcat','categories','internal.coursecode'],
 5981:                              $cdom,$cnum);
 5982:     my $visible = 0;
 5983:     if ($currsettings{'internal.coursecode'} ne '') {
 5984:         if (ref($domconf{'coursecategories'}) eq 'HASH') {
 5985:             $cathash = $domconf{'coursecategories'}{'cats'};
 5986:             if (ref($cathash) eq 'HASH') {
 5987:                 if ($cathash->{'instcode::0'} eq '') {
 5988:                     push(@vismsgs,'dc_addinst'); 
 5989:                 } else {
 5990:                     $visible = 1;
 5991:                 }
 5992:             } else {
 5993:                 $visible = 1;
 5994:             }
 5995:         } else {
 5996:             $visible = 1;
 5997:         }
 5998:     } else {
 5999:         if (ref($cathash) eq 'HASH') {
 6000:             if ($cathash->{'instcode::0'} ne '') {
 6001:                 push(@vismsgs,'dc_instcode');
 6002:             }
 6003:         } else {
 6004:             push(@vismsgs,'dc_instcode');
 6005:         }
 6006:     }
 6007:     if ($currsettings{'categories'} ne '') {
 6008:         my $cathash;
 6009:         if (ref($domconf{'coursecategories'}) eq 'HASH') {
 6010:             $cathash = $domconf{'coursecategories'}{'cats'};
 6011:             if (ref($cathash) eq 'HASH') {
 6012:                 if (keys(%{$cathash}) == 0) {
 6013:                     push(@vismsgs,'dc_catalog');
 6014:                 } elsif ((keys(%{$cathash}) == 1) && ($cathash->{'instcode::0'} ne '')) {
 6015:                     push(@vismsgs,'dc_categories');
 6016:                 } else {
 6017:                     my @currcategories = split('&',$currsettings{'categories'});
 6018:                     my $matched = 0;
 6019:                     foreach my $cat (@currcategories) {
 6020:                         if ($cathash->{$cat} ne '') {
 6021:                             $visible = 1;
 6022:                             $matched = 1;
 6023:                             last;
 6024:                         }
 6025:                     }
 6026:                     if (!$matched) {
 6027:                         if ($settable{'categorize'}) { 
 6028:                             push(@vismsgs,'chgcat');
 6029:                         } else {
 6030:                             push(@vismsgs,'dc_chgcat');
 6031:                         }
 6032:                     }
 6033:                 }
 6034:             }
 6035:         }
 6036:     } else {
 6037:         if (ref($cathash) eq 'HASH') {
 6038:             if ((keys(%{$cathash}) > 1) || 
 6039:                 (keys(%{$cathash}) == 1) && ($cathash->{'instcode::0'} eq '')) {
 6040:                 if ($settable{'categorize'}) {
 6041:                     push(@vismsgs,'addcat');
 6042:                 } else {
 6043:                     push(@vismsgs,'dc_addcat');
 6044:                 }
 6045:             }
 6046:         }
 6047:     }
 6048:     if ($currsettings{'hidefromcat'} eq 'yes') {
 6049:         $visible = 0;
 6050:         if ($settable{'togglecats'}) {
 6051:             unshift(@vismsgs,'unhide');
 6052:         } else {
 6053:             unshift(@vismsgs,'dc_unhide')
 6054:         }
 6055:     }
 6056:     return ($visible,$cansetvis,\@vismsgs,\%visactions);
 6057: }
 6058: 
 6059: sub new_selfenroll_dom_row {
 6060:     my ($newdom,$num) = @_;
 6061:     my $domdesc = &Apache::lonnet::domain($newdom);
 6062:     my $output;
 6063:     if ($domdesc ne '') {
 6064:         $output .= &Apache::loncommon::start_data_table_row()
 6065:                    .'<td valign="top"><span class="LC_nobreak">'.&mt('Domain:').'&nbsp;<b>'.$domdesc
 6066:                    .' ('.$newdom.')</b><input type="hidden" name="selfenroll_dom_'.$num
 6067:                    .'" value="'.$newdom.'" /></span><br />'
 6068:                    .'<span class="LC_nobreak"><label><input type="checkbox" '
 6069:                    .'name="selfenroll_activate" value="'.$num.'" '
 6070:                    .'onchange="javascript:update_types('
 6071:                    ."'selfenroll_activate','$num'".');" />'
 6072:                    .&mt('Activate').'</label></span></td>';
 6073:         my @currinsttypes;
 6074:         $output .= '<td>'.&mt('User types:').'<br />'
 6075:                    .&selfenroll_inst_types($num,$newdom,\@currinsttypes).'</td>'
 6076:                    .&Apache::loncommon::end_data_table_row();
 6077:     }
 6078:     return $output;
 6079: }
 6080: 
 6081: sub selfenroll_inst_types {
 6082:     my ($num,$currdom,$currinsttypes) = @_;
 6083:     my $output;
 6084:     my $numinrow = 4;
 6085:     my $count = 0;
 6086:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($currdom);
 6087:     my $othervalue = 'any';
 6088:     if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 6089:         if (keys(%{$usertypes}) > 0) {
 6090:             $othervalue = 'other';
 6091:         }
 6092:         $output .= '<table><tr>';
 6093:         foreach my $type (@{$types}) {
 6094:             if (($count > 0) && ($count%$numinrow == 0)) {
 6095:                 $output .= '</tr><tr>';
 6096:             }
 6097:             if (defined($usertypes->{$type})) {
 6098:                 my $esc_type = &escape($type);
 6099:                 $output .= '<td><span class="LC_nobreak"><label><input type = "checkbox" value="'.
 6100:                            $esc_type.'" ';
 6101:                 if (ref($currinsttypes) eq 'ARRAY') {
 6102:                     if (@{$currinsttypes} > 0) {
 6103:                         if (grep(/^any$/,@{$currinsttypes})) {
 6104:                             $output .= 'checked="checked"';
 6105:                         } elsif (grep(/^\Q$esc_type\E$/,@{$currinsttypes})) {
 6106:                             $output .= 'checked="checked"';
 6107:                         }
 6108:                     } else {
 6109:                         $output .= 'checked="checked"';
 6110:                     }
 6111:                 }
 6112:                 $output .= ' name="selfenroll_types_'.$num.'" />'.$usertypes->{$type}.'</label></span></td>';
 6113:             }
 6114:             $count ++;
 6115:         }
 6116:         if (($count > 0) && ($count%$numinrow == 0)) {
 6117:             $output .= '</tr><tr>';
 6118:         }
 6119:         $output .= '<td><span class="LC_nobreak"><label><input type = "checkbox" value="'.$othervalue.'"';
 6120:         if (ref($currinsttypes) eq 'ARRAY') {
 6121:             if (@{$currinsttypes} > 0) {
 6122:                 if (grep(/^any$/,@{$currinsttypes})) { 
 6123:                     $output .= ' checked="checked"';
 6124:                 } elsif ($othervalue eq 'other') {
 6125:                     if (grep(/^\Q$othervalue\E$/,@{$currinsttypes})) {
 6126:                         $output .= ' checked="checked"';
 6127:                     }
 6128:                 }
 6129:             } else {
 6130:                 $output .= ' checked="checked"';
 6131:             }
 6132:         } else {
 6133:             $output .= ' checked="checked"';
 6134:         }
 6135:         $output .= ' name="selfenroll_types_'.$num.'" />'.$othertitle.'</label></span></td></tr></table>';
 6136:     }
 6137:     return $output;
 6138: }
 6139: 
 6140: sub selfenroll_date_forms {
 6141:     my ($startform,$endform) = @_;
 6142:     my $output .= &Apache::lonhtmlcommon::start_pick_box()."\n".
 6143:                   &Apache::lonhtmlcommon::row_title(&mt('Start date'),
 6144:                                                     'LC_oddrow_value')."\n".
 6145:                   $startform."\n".
 6146:                   &Apache::lonhtmlcommon::row_closure(1).
 6147:                   &Apache::lonhtmlcommon::row_title(&mt('End date'),
 6148:                                                    'LC_oddrow_value')."\n".
 6149:                   $endform."\n".
 6150:                   &Apache::lonhtmlcommon::row_closure(1).
 6151:                   &Apache::lonhtmlcommon::end_pick_box();
 6152:     return $output;
 6153: }
 6154: 
 6155: sub print_userchangelogs_display {
 6156:     my ($r,$context,$permission) = @_;
 6157:     my $formname = 'rolelog';
 6158:     my ($username,$domain,$crstype,%roleslog);
 6159:     if ($context eq 'domain') {
 6160:         $domain = $env{'request.role.domain'};
 6161:         %roleslog=&Apache::lonnet::dump_dom('nohist_rolelog',$domain);
 6162:     } else {
 6163:         if ($context eq 'course') { 
 6164:             $domain = $env{'course.'.$env{'request.course.id'}.'.domain'};
 6165:             $username = $env{'course.'.$env{'request.course.id'}.'.num'};
 6166:             $crstype = &Apache::loncommon::course_type();
 6167:             my %saveable_parameters = ('show' => 'scalar',);
 6168:             &Apache::loncommon::store_course_settings('roles_log',
 6169:                                                       \%saveable_parameters);
 6170:             &Apache::loncommon::restore_course_settings('roles_log',
 6171:                                                         \%saveable_parameters);
 6172:         } elsif ($context eq 'author') {
 6173:             $domain = $env{'user.domain'}; 
 6174:             if ($env{'request.role'} =~ m{^au\./\Q$domain\E/$}) {
 6175:                 $username = $env{'user.name'};
 6176:             } else {
 6177:                 undef($domain);
 6178:             }
 6179:         }
 6180:         if ($domain ne '' && $username ne '') { 
 6181:             %roleslog=&Apache::lonnet::dump('nohist_rolelog',$domain,$username);
 6182:         }
 6183:     }
 6184:     if ((keys(%roleslog))[0]=~/^error\:/) { undef(%roleslog); }
 6185: 
 6186:     # set defaults
 6187:     my $now = time();
 6188:     my $defstart = $now - (7*24*3600); #7 days ago 
 6189:     my %defaults = (
 6190:                      page               => '1',
 6191:                      show               => '10',
 6192:                      role               => 'any',
 6193:                      chgcontext         => 'any',
 6194:                      rolelog_start_date => $defstart,
 6195:                      rolelog_end_date   => $now,
 6196:                    );
 6197:     my $more_records = 0;
 6198: 
 6199:     # set current
 6200:     my %curr;
 6201:     foreach my $item ('show','page','role','chgcontext') {
 6202:         $curr{$item} = $env{'form.'.$item};
 6203:     }
 6204:     my ($startdate,$enddate) = 
 6205:         &Apache::lonuserutils::get_dates_from_form('rolelog_start_date','rolelog_end_date');
 6206:     $curr{'rolelog_start_date'} = $startdate;
 6207:     $curr{'rolelog_end_date'} = $enddate;
 6208:     foreach my $key (keys(%defaults)) {
 6209:         if ($curr{$key} eq '') {
 6210:             $curr{$key} = $defaults{$key};
 6211:         }
 6212:     }
 6213:     my (%whodunit,%changed,$version);
 6214:     ($version) = ($r->dir_config('lonVersion') =~ /^([\d\.]+)\-/);
 6215:     my ($minshown,$maxshown);
 6216:     $minshown = 1;
 6217:     my $count = 0;
 6218:     if ($curr{'show'} ne &mt('all')) { 
 6219:         $maxshown = $curr{'page'} * $curr{'show'};
 6220:         if ($curr{'page'} > 1) {
 6221:             $minshown = 1 + ($curr{'page'} - 1) * $curr{'show'};
 6222:         }
 6223:     }
 6224: 
 6225:     # Form Header
 6226:     $r->print('<form action="/adm/createuser" method="post" name="'.$formname.'">'.
 6227:               &role_display_filter($context,$formname,$domain,$username,\%curr,
 6228:                                    $version,$crstype));
 6229: 
 6230:     # Create navigation
 6231:     my ($nav_script,$nav_links) = &userlogdisplay_nav($formname,\%curr,$more_records);
 6232:     my $showntableheader = 0;
 6233: 
 6234:     # Table Header
 6235:     my $tableheader = 
 6236:         &Apache::loncommon::start_data_table_header_row()
 6237:        .'<th>&nbsp;</th>'
 6238:        .'<th>'.&mt('When').'</th>'
 6239:        .'<th>'.&mt('Who made the change').'</th>'
 6240:        .'<th>'.&mt('Changed User').'</th>'
 6241:        .'<th>'.&mt('Role').'</th>';
 6242: 
 6243:     if ($context eq 'course') {
 6244:         $tableheader .= '<th>'.&mt('Section').'</th>';
 6245:     }
 6246:     $tableheader .=
 6247:         '<th>'.&mt('Context').'</th>'
 6248:        .'<th>'.&mt('Start').'</th>'
 6249:        .'<th>'.&mt('End').'</th>'
 6250:        .&Apache::loncommon::end_data_table_header_row();
 6251: 
 6252:     # Display user change log data
 6253:     foreach my $id (sort { $roleslog{$b}{'exe_time'}<=>$roleslog{$a}{'exe_time'} } (keys(%roleslog))) {
 6254:         next if (($roleslog{$id}{'exe_time'} < $curr{'rolelog_start_date'}) ||
 6255:                  ($roleslog{$id}{'exe_time'} > $curr{'rolelog_end_date'}));
 6256:         if ($curr{'show'} ne &mt('all')) {
 6257:             if ($count >= $curr{'page'} * $curr{'show'}) {
 6258:                 $more_records = 1;
 6259:                 last;
 6260:             }
 6261:         }
 6262:         if ($curr{'role'} ne 'any') {
 6263:             next if ($roleslog{$id}{'logentry'}{'role'} ne $curr{'role'}); 
 6264:         }
 6265:         if ($curr{'chgcontext'} ne 'any') {
 6266:             if ($curr{'chgcontext'} eq 'selfenroll') {
 6267:                 next if (!$roleslog{$id}{'logentry'}{'selfenroll'});
 6268:             } else {
 6269:                 next if ($roleslog{$id}{'logentry'}{'context'} ne $curr{'chgcontext'});
 6270:             }
 6271:         }
 6272:         $count ++;
 6273:         next if ($count < $minshown);
 6274:         unless ($showntableheader) {
 6275:             $r->print($nav_script
 6276:                      .$nav_links
 6277:                      .&Apache::loncommon::start_data_table()
 6278:                      .$tableheader);
 6279:             $r->rflush();
 6280:             $showntableheader = 1;
 6281:         }
 6282:         if ($whodunit{$roleslog{$id}{'exe_uname'}.':'.$roleslog{$id}{'exe_udom'}} eq '') {
 6283:             $whodunit{$roleslog{$id}{'exe_uname'}.':'.$roleslog{$id}{'exe_udom'}} =
 6284:                 &Apache::loncommon::plainname($roleslog{$id}{'exe_uname'},$roleslog{$id}{'exe_udom'});
 6285:         }
 6286:         if ($changed{$roleslog{$id}{'uname'}.':'.$roleslog{$id}{'udom'}} eq '') {
 6287:             $changed{$roleslog{$id}{'uname'}.':'.$roleslog{$id}{'udom'}} =
 6288:                 &Apache::loncommon::plainname($roleslog{$id}{'uname'},$roleslog{$id}{'udom'});
 6289:         }
 6290:         my $sec = $roleslog{$id}{'logentry'}{'section'};
 6291:         if ($sec eq '') {
 6292:             $sec = &mt('None');
 6293:         }
 6294:         my ($rolestart,$roleend);
 6295:         if ($roleslog{$id}{'delflag'}) {
 6296:             $rolestart = &mt('deleted');
 6297:             $roleend = &mt('deleted');
 6298:         } else {
 6299:             $rolestart = $roleslog{$id}{'logentry'}{'start'};
 6300:             $roleend = $roleslog{$id}{'logentry'}{'end'};
 6301:             if ($rolestart eq '' || $rolestart == 0) {
 6302:                 $rolestart = &mt('No start date'); 
 6303:             } else {
 6304:                 $rolestart = &Apache::lonlocal::locallocaltime($rolestart);
 6305:             }
 6306:             if ($roleend eq '' || $roleend == 0) { 
 6307:                 $roleend = &mt('No end date');
 6308:             } else {
 6309:                 $roleend = &Apache::lonlocal::locallocaltime($roleend);
 6310:             }
 6311:         }
 6312:         my $chgcontext = $roleslog{$id}{'logentry'}{'context'};
 6313:         if ($roleslog{$id}{'logentry'}{'selfenroll'}) {
 6314:             $chgcontext = 'selfenroll';
 6315:         }
 6316:         my %lt = &rolechg_contexts($context,$crstype);
 6317:         if ($chgcontext ne '' && $lt{$chgcontext} ne '') {
 6318:             $chgcontext = $lt{$chgcontext};
 6319:         }
 6320:         $r->print(
 6321:             &Apache::loncommon::start_data_table_row()
 6322:            .'<td>'.$count.'</td>'
 6323:            .'<td>'.&Apache::lonlocal::locallocaltime($roleslog{$id}{'exe_time'}).'</td>'
 6324:            .'<td>'.$whodunit{$roleslog{$id}{'exe_uname'}.':'.$roleslog{$id}{'exe_udom'}}.'</td>'
 6325:            .'<td>'.$changed{$roleslog{$id}{'uname'}.':'.$roleslog{$id}{'udom'}}.'</td>'
 6326:            .'<td>'.&Apache::lonnet::plaintext($roleslog{$id}{'logentry'}{'role'},$crstype).'</td>');
 6327:         if ($context eq 'course') { 
 6328:             $r->print('<td>'.$sec.'</td>');
 6329:         }
 6330:         $r->print(
 6331:             '<td>'.$chgcontext.'</td>'
 6332:            .'<td>'.$rolestart.'</td>'
 6333:            .'<td>'.$roleend.'</td>'
 6334:            .&Apache::loncommon::end_data_table_row()."\n");
 6335:     }
 6336: 
 6337:     if ($showntableheader) { # Table footer, if content displayed above
 6338:         $r->print(&Apache::loncommon::end_data_table()
 6339:                  .$nav_links);
 6340:     } else { # No content displayed above
 6341:         $r->print('<p class="LC_info">'
 6342:                  .&mt('There are no records to display.')
 6343:                  .'</p>'
 6344:         );
 6345:     }
 6346: 
 6347:     # Form Footer
 6348:     $r->print( 
 6349:         '<input type="hidden" name="page" value="'.$curr{'page'}.'" />'
 6350:        .'<input type="hidden" name="action" value="changelogs" />'
 6351:        .'</form>');
 6352:     return;
 6353: }
 6354: 
 6355: sub userlogdisplay_nav {
 6356:     my ($formname,$curr,$more_records) = @_;
 6357:     my ($nav_script,$nav_links);
 6358:     if (ref($curr) eq 'HASH') {
 6359:         # Create Navigation:
 6360:         # Navigation Script
 6361:         $nav_script = <<"ENDSCRIPT";
 6362: <script type="text/javascript">
 6363: // <![CDATA[
 6364: function chgPage(caller) {
 6365:     if (caller == 'previous') {
 6366:         document.$formname.page.value --;
 6367:     }
 6368:     if (caller == 'next') {
 6369:         document.$formname.page.value ++;
 6370:     }
 6371:     document.$formname.submit();
 6372:     return;
 6373: }
 6374: // ]]>
 6375: </script>
 6376: ENDSCRIPT
 6377:         # Navigation Buttons
 6378:         $nav_links = '<p>';
 6379:         if (($curr->{'page'} > 1) || ($more_records)) {
 6380:             if ($curr->{'page'} > 1) {
 6381:                 $nav_links .= '<input type="button"'
 6382:                              .' onclick="javascript:chgPage('."'previous'".');"'
 6383:                              .' value="'.&mt('Previous [_1] changes',$curr->{'show'})
 6384:                              .'" /> ';
 6385:             }
 6386:             if ($more_records) {
 6387:                 $nav_links .= '<input type="button"'
 6388:                              .' onclick="javascript:chgPage('."'next'".');"'
 6389:                              .' value="'.&mt('Next [_1] changes',$curr->{'show'})
 6390:                              .'" />';
 6391:             }
 6392:         }
 6393:         $nav_links .= '</p>';
 6394:     }
 6395:     return ($nav_script,$nav_links);
 6396: }
 6397: 
 6398: sub role_display_filter {
 6399:     my ($context,$formname,$cdom,$cnum,$curr,$version,$crstype) = @_;
 6400:     my $lctype;
 6401:     if ($context eq 'course') {
 6402:         $lctype = lc($crstype);
 6403:     }
 6404:     my $nolink = 1;
 6405:     my $output = '<table><tr><td valign="top">'.
 6406:                  '<span class="LC_nobreak"><b>'.&mt('Changes/page:').'</b></span><br />'.
 6407:                  &Apache::lonmeta::selectbox('show',$curr->{'show'},undef,
 6408:                                               (&mt('all'),5,10,20,50,100,1000,10000)).
 6409:                  '</td><td>&nbsp;&nbsp;</td>';
 6410:     my $startform =
 6411:         &Apache::lonhtmlcommon::date_setter($formname,'rolelog_start_date',
 6412:                                             $curr->{'rolelog_start_date'},undef,
 6413:                                             undef,undef,undef,undef,undef,undef,$nolink);
 6414:     my $endform =
 6415:         &Apache::lonhtmlcommon::date_setter($formname,'rolelog_end_date',
 6416:                                             $curr->{'rolelog_end_date'},undef,
 6417:                                             undef,undef,undef,undef,undef,undef,$nolink);
 6418:     my %lt = &rolechg_contexts($context,$crstype);
 6419:     $output .= '<td valign="top"><b>'.&mt('Window during which changes occurred:').'</b><br />'.
 6420:                '<table><tr><td>'.&mt('After:').
 6421:                '</td><td>'.$startform.'</td></tr>'.
 6422:                '<tr><td>'.&mt('Before:').'</td>'.
 6423:                '<td>'.$endform.'</td></tr></table>'.
 6424:                '</td>'.
 6425:                '<td>&nbsp;&nbsp;</td>'.
 6426:                '<td valign="top"><b>'.&mt('Role:').'</b><br />'.
 6427:                '<select name="role"><option value="any"';
 6428:     if ($curr->{'role'} eq 'any') {
 6429:         $output .= ' selected="selected"';
 6430:     }
 6431:     $output .=  '>'.&mt('Any').'</option>'."\n";
 6432:     my @roles = &Apache::lonuserutils::roles_by_context($context,1,$crstype);
 6433:     foreach my $role (@roles) {
 6434:         my $plrole;
 6435:         if ($role eq 'cr') {
 6436:             $plrole = &mt('Custom Role');
 6437:         } else {
 6438:             $plrole=&Apache::lonnet::plaintext($role,$crstype);
 6439:         }
 6440:         my $selstr = '';
 6441:         if ($role eq $curr->{'role'}) {
 6442:             $selstr = ' selected="selected"';
 6443:         }
 6444:         $output .= '  <option value="'.$role.'"'.$selstr.'>'.$plrole.'</option>';
 6445:     }
 6446:     $output .= '</select></td>'.
 6447:                '<td>&nbsp;&nbsp;</td>'.
 6448:                '<td valign="top"><b>'.
 6449:                &mt('Context:').'</b><br /><select name="chgcontext">';
 6450:     my @posscontexts;
 6451:     if ($context eq 'course') {
 6452:         @posscontexts = ('any','automated','updatenow','createcourse','course','domain','selfenroll','requestcourses');
 6453:     } elsif ($context eq 'domain') {
 6454:         @posscontexts = ('any','domain','requestauthor','domconfig','server');
 6455:     } else {
 6456:         @posscontexts = ('any','author','domain');
 6457:     } 
 6458:     foreach my $chgtype (@posscontexts) {
 6459:         my $selstr = '';
 6460:         if ($curr->{'chgcontext'} eq $chgtype) {
 6461:             $selstr = ' selected="selected"';
 6462:         }
 6463:         if ($context eq 'course') {
 6464:             if (($chgtype eq 'automated') || ($chgtype eq 'updatenow')) {
 6465:                 next if (!&Apache::lonnet::auto_run($cnum,$cdom));
 6466:             }
 6467:         }
 6468:         $output .= '<option value="'.$chgtype.'"'.$selstr.'>'.$lt{$chgtype}.'</option>'."\n";
 6469:     }
 6470:     $output .= '</select></td>'
 6471:               .'</tr></table>';
 6472: 
 6473:     # Update Display button
 6474:     $output .= '<p>'
 6475:               .'<input type="submit" value="'.&mt('Update Display').'" />'
 6476:               .'</p>';
 6477: 
 6478:     # Server version info
 6479:     my $needsrev = '2.11.0';
 6480:     if ($context eq 'course') {
 6481:         $needsrev = '2.7.0';
 6482:     }
 6483:     
 6484:     $output .= '<p class="LC_info">'
 6485:               .&mt('Only changes made from servers running LON-CAPA [_1] or later are displayed.'
 6486:                   ,$needsrev);
 6487:     if ($version) {
 6488:         $output .= ' '.&mt('This LON-CAPA server is version [_1]',$version);
 6489:     }
 6490:     $output .= '</p><hr />';
 6491:     return $output;
 6492: }
 6493: 
 6494: sub rolechg_contexts {
 6495:     my ($context,$crstype) = @_;
 6496:     my %lt;
 6497:     if ($context eq 'course') {
 6498:         %lt = &Apache::lonlocal::texthash (
 6499:                                              any          => 'Any',
 6500:                                              automated    => 'Automated Enrollment',
 6501:                                              updatenow    => 'Roster Update',
 6502:                                              createcourse => 'Course Creation',
 6503:                                              course       => 'User Management in course',
 6504:                                              domain       => 'User Management in domain',
 6505:                                              selfenroll   => 'Self-enrolled',
 6506:                                              requestcourses => 'Course Request',
 6507:                                          );
 6508:         if ($crstype eq 'Community') {
 6509:             $lt{'createcourse'} = &mt('Community Creation');
 6510:             $lt{'course'} = &mt('User Management in community');
 6511:             $lt{'requestcourses'} = &mt('Community Request');
 6512:         }
 6513:     } elsif ($context eq 'domain') {
 6514:         %lt = &Apache::lonlocal::texthash (
 6515:                                              any           => 'Any',
 6516:                                              domain        => 'User Management in domain',
 6517:                                              requestauthor => 'Authoring Request',
 6518:                                              server        => 'Command line script (DC role)',
 6519:                                              domconfig     => 'Self-enrolled',
 6520:                                          );
 6521:     } else {
 6522:         %lt = &Apache::lonlocal::texthash (
 6523:                                              any    => 'Any',
 6524:                                              domain => 'User Management in domain',
 6525:                                              author => 'User Management by author',
 6526:                                          );
 6527:     } 
 6528:     return %lt;
 6529: }
 6530: 
 6531: #-------------------------------------------------- functions for &phase_two
 6532: sub user_search_result {
 6533:     my ($context,$srch) = @_;
 6534:     my %allhomes;
 6535:     my %inst_matches;
 6536:     my %srch_results;
 6537:     my ($response,$currstate,$forcenewuser,$dirsrchres);
 6538:     $srch->{'srchterm'} =~ s/\s+/ /g;
 6539:     if ($srch->{'srchby'} !~ /^(uname|lastname|lastfirst)$/) {
 6540:         $response = &mt('Invalid search.');
 6541:     }
 6542:     if ($srch->{'srchin'} !~ /^(crs|dom|alc|instd)$/) {
 6543:         $response = &mt('Invalid search.');
 6544:     }
 6545:     if ($srch->{'srchtype'} !~ /^(exact|contains|begins)$/) {
 6546:         $response = &mt('Invalid search.');
 6547:     }
 6548:     if ($srch->{'srchterm'} eq '') {
 6549:         $response = &mt('You must enter a search term.');
 6550:     }
 6551:     if ($srch->{'srchterm'} =~ /^\s+$/) {
 6552:         $response = &mt('Your search term must contain more than just spaces.');
 6553:     }
 6554:     if (($srch->{'srchin'} eq 'dom') || ($srch->{'srchin'} eq 'instd')) {
 6555:         if (($srch->{'srchdomain'} eq '') || 
 6556: 	    ! (&Apache::lonnet::domain($srch->{'srchdomain'}))) {
 6557:             $response = &mt('You must specify a valid domain when searching in a domain or institutional directory.')
 6558:         }
 6559:     }
 6560:     if (($srch->{'srchin'} eq 'dom') || ($srch->{'srchin'} eq 'crs') ||
 6561:         ($srch->{'srchin'} eq 'alc')) {
 6562:         if ($srch->{'srchby'} eq 'uname') {
 6563:             my $unamecheck = $srch->{'srchterm'};
 6564:             if ($srch->{'srchtype'} eq 'contains') {
 6565:                 if ($unamecheck !~ /^\w/) {
 6566:                     $unamecheck = 'a'.$unamecheck; 
 6567:                 }
 6568:             }
 6569:             if ($unamecheck !~ /^$match_username$/) {
 6570:                 $response = &mt('You must specify a valid username. Only the following are allowed: letters numbers - . @');
 6571:             }
 6572:         }
 6573:     }
 6574:     if ($response ne '') {
 6575:         $response = '<span class="LC_warning">'.$response.'</span>';
 6576:     }
 6577:     if ($srch->{'srchin'} eq 'instd') {
 6578:         my $instd_chk = &directorysrch_check($srch);
 6579:         if ($instd_chk ne 'ok') {
 6580:             $response = '<span class="LC_warning">'.$instd_chk.'</span>'.
 6581:                         '<br />'.&mt('You may want to search in the LON-CAPA domain instead of the institutional directory.').'<br /><br />';
 6582:         }
 6583:     }
 6584:     if ($response ne '') {
 6585:         return ($currstate,$response);
 6586:     }
 6587:     if ($srch->{'srchby'} eq 'uname') {
 6588:         if (($srch->{'srchin'} eq 'dom') || ($srch->{'srchin'} eq 'crs')) {
 6589:             if ($env{'form.forcenew'}) {
 6590:                 if ($srch->{'srchdomain'} ne $env{'request.role.domain'}) {
 6591:                     my $uhome=&Apache::lonnet::homeserver($srch->{'srchterm'},$srch->{'srchdomain'});
 6592:                     if ($uhome eq 'no_host') {
 6593:                         my $domdesc = &Apache::lonnet::domain($env{'request.role.domain'},'description');
 6594:                         my $showdom = &display_domain_info($env{'request.role.domain'});
 6595:                         $response = &mt('New users can only be created in the domain to which your current role belongs - [_1].',$showdom);
 6596:                     } else {
 6597:                         $currstate = 'modify';
 6598:                     }
 6599:                 } else {
 6600:                     $currstate = 'modify';
 6601:                 }
 6602:             } else {
 6603:                 if ($srch->{'srchin'} eq 'dom') {
 6604:                     if ($srch->{'srchtype'} eq 'exact') {
 6605:                         my $uhome=&Apache::lonnet::homeserver($srch->{'srchterm'},$srch->{'srchdomain'});
 6606:                         if ($uhome eq 'no_host') {
 6607:                             ($currstate,$response,$forcenewuser) =
 6608:                                 &build_search_response($context,$srch,%srch_results);
 6609:                         } else {
 6610:                             $currstate = 'modify';
 6611:                             my $uname = $srch->{'srchterm'};
 6612:                             my $udom = $srch->{'srchdomain'};
 6613:                             $srch_results{$uname.':'.$udom} =
 6614:                                 { &Apache::lonnet::get('environment',
 6615:                                                        ['firstname',
 6616:                                                         'lastname',
 6617:                                                         'permanentemail'],
 6618:                                                          $udom,$uname)
 6619:                                 };
 6620:                         }
 6621:                     } else {
 6622:                         %srch_results = &Apache::lonnet::usersearch($srch);
 6623:                         ($currstate,$response,$forcenewuser) =
 6624:                             &build_search_response($context,$srch,%srch_results);
 6625:                     }
 6626:                 } else {
 6627:                     my $courseusers = &get_courseusers();
 6628:                     if ($srch->{'srchtype'} eq 'exact') {
 6629:                         if (exists($courseusers->{$srch->{'srchterm'}.':'.$srch->{'srchdomain'}})) {
 6630:                             $currstate = 'modify';
 6631:                         } else {
 6632:                             ($currstate,$response,$forcenewuser) =
 6633:                                 &build_search_response($context,$srch,%srch_results);
 6634:                         }
 6635:                     } else {
 6636:                         foreach my $user (keys(%$courseusers)) {
 6637:                             my ($cuname,$cudomain) = split(/:/,$user);
 6638:                             if ($cudomain eq $srch->{'srchdomain'}) {
 6639:                                 my $matched = 0;
 6640:                                 if ($srch->{'srchtype'} eq 'begins') {
 6641:                                     if ($cuname =~ /^\Q$srch->{'srchterm'}\E/i) {
 6642:                                         $matched = 1;
 6643:                                     }
 6644:                                 } else {
 6645:                                     if ($cuname =~ /\Q$srch->{'srchterm'}\E/i) {
 6646:                                         $matched = 1;
 6647:                                     }
 6648:                                 }
 6649:                                 if ($matched) {
 6650:                                     $srch_results{$user} = 
 6651: 					{&Apache::lonnet::get('environment',
 6652: 							     ['firstname',
 6653: 							      'lastname',
 6654: 							      'permanentemail'],
 6655: 							      $cudomain,$cuname)};
 6656:                                 }
 6657:                             }
 6658:                         }
 6659:                         ($currstate,$response,$forcenewuser) =
 6660:                             &build_search_response($context,$srch,%srch_results);
 6661:                     }
 6662:                 }
 6663:             }
 6664:         } elsif ($srch->{'srchin'} eq 'alc') {
 6665:             $currstate = 'query';
 6666:         } elsif ($srch->{'srchin'} eq 'instd') {
 6667:             ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query($srch);
 6668:             if ($dirsrchres eq 'ok') {
 6669:                 ($currstate,$response,$forcenewuser) = 
 6670:                     &build_search_response($context,$srch,%srch_results);
 6671:             } else {
 6672:                 my $showdom = &display_domain_info($srch->{'srchdomain'});
 6673:                 $response = '<span class="LC_warning">'.
 6674:                     &mt('Institutional directory search is not available in domain: [_1]',$showdom).
 6675:                     '</span><br />'.
 6676:                     &mt('You may want to search in the LON-CAPA domain instead of the institutional directory.').
 6677:                     '<br /><br />'; 
 6678:             }
 6679:         }
 6680:     } else {
 6681:         if ($srch->{'srchin'} eq 'dom') {
 6682:             %srch_results = &Apache::lonnet::usersearch($srch);
 6683:             ($currstate,$response,$forcenewuser) = 
 6684:                 &build_search_response($context,$srch,%srch_results); 
 6685:         } elsif ($srch->{'srchin'} eq 'crs') {
 6686:             my $courseusers = &get_courseusers(); 
 6687:             foreach my $user (keys(%$courseusers)) {
 6688:                 my ($uname,$udom) = split(/:/,$user);
 6689:                 my %names = &Apache::loncommon::getnames($uname,$udom);
 6690:                 my %emails = &Apache::loncommon::getemails($uname,$udom);
 6691:                 if ($srch->{'srchby'} eq 'lastname') {
 6692:                     if ((($srch->{'srchtype'} eq 'exact') && 
 6693:                          ($names{'lastname'} eq $srch->{'srchterm'})) || 
 6694:                         (($srch->{'srchtype'} eq 'begins') &&
 6695:                          ($names{'lastname'} =~ /^\Q$srch->{'srchterm'}\E/i)) ||
 6696:                         (($srch->{'srchtype'} eq 'contains') &&
 6697:                          ($names{'lastname'} =~ /\Q$srch->{'srchterm'}\E/i))) {
 6698:                         $srch_results{$user} = {firstname => $names{'firstname'},
 6699:                                             lastname => $names{'lastname'},
 6700:                                             permanentemail => $emails{'permanentemail'},
 6701:                                            };
 6702:                     }
 6703:                 } elsif ($srch->{'srchby'} eq 'lastfirst') {
 6704:                     my ($srchlast,$srchfirst) = split(/,/,$srch->{'srchterm'});
 6705:                     $srchlast =~ s/\s+$//;
 6706:                     $srchfirst =~ s/^\s+//;
 6707:                     if ($srch->{'srchtype'} eq 'exact') {
 6708:                         if (($names{'lastname'} eq $srchlast) &&
 6709:                             ($names{'firstname'} eq $srchfirst)) {
 6710:                             $srch_results{$user} = {firstname => $names{'firstname'},
 6711:                                                 lastname => $names{'lastname'},
 6712:                                                 permanentemail => $emails{'permanentemail'},
 6713: 
 6714:                                            };
 6715:                         }
 6716:                     } elsif ($srch->{'srchtype'} eq 'begins') {
 6717:                         if (($names{'lastname'} =~ /^\Q$srchlast\E/i) &&
 6718:                             ($names{'firstname'} =~ /^\Q$srchfirst\E/i)) {
 6719:                             $srch_results{$user} = {firstname => $names{'firstname'},
 6720:                                                 lastname => $names{'lastname'},
 6721:                                                 permanentemail => $emails{'permanentemail'},
 6722:                                                };
 6723:                         }
 6724:                     } else {
 6725:                         if (($names{'lastname'} =~ /\Q$srchlast\E/i) && 
 6726:                             ($names{'firstname'} =~ /\Q$srchfirst\E/i)) {
 6727:                             $srch_results{$user} = {firstname => $names{'firstname'},
 6728:                                                 lastname => $names{'lastname'},
 6729:                                                 permanentemail => $emails{'permanentemail'},
 6730:                                                };
 6731:                         }
 6732:                     }
 6733:                 }
 6734:             }
 6735:             ($currstate,$response,$forcenewuser) = 
 6736:                 &build_search_response($context,$srch,%srch_results); 
 6737:         } elsif ($srch->{'srchin'} eq 'alc') {
 6738:             $currstate = 'query';
 6739:         } elsif ($srch->{'srchin'} eq 'instd') {
 6740:             ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query($srch); 
 6741:             if ($dirsrchres eq 'ok') {
 6742:                 ($currstate,$response,$forcenewuser) = 
 6743:                     &build_search_response($context,$srch,%srch_results);
 6744:             } else {
 6745:                 my $showdom = &display_domain_info($srch->{'srchdomain'});                $response = '<span class="LC_warning">'.
 6746:                     &mt('Institutional directory search is not available in domain: [_1]',$showdom).
 6747:                     '</span><br />'.
 6748:                     &mt('You may want to search in the LON-CAPA domain instead of the institutional directory.').
 6749:                     '<br /><br />';
 6750:             }
 6751:         }
 6752:     }
 6753:     return ($currstate,$response,$forcenewuser,\%srch_results);
 6754: }
 6755: 
 6756: sub directorysrch_check {
 6757:     my ($srch) = @_;
 6758:     my $can_search = 0;
 6759:     my $response;
 6760:     my %dom_inst_srch = &Apache::lonnet::get_dom('configuration',
 6761:                                              ['directorysrch'],$srch->{'srchdomain'});
 6762:     my $showdom = &display_domain_info($srch->{'srchdomain'});
 6763:     if (ref($dom_inst_srch{'directorysrch'}) eq 'HASH') {
 6764:         if (!$dom_inst_srch{'directorysrch'}{'available'}) {
 6765:             return &mt('Institutional directory search is not available in domain: [_1]',$showdom); 
 6766:         }
 6767:         if ($dom_inst_srch{'directorysrch'}{'localonly'}) {
 6768:             if ($env{'request.role.domain'} ne $srch->{'srchdomain'}) {
 6769:                 return &mt('Institutional directory search in domain: [_1] is only allowed for users with a current role in the domain.',$showdom); 
 6770:             }
 6771:             my @usertypes = split(/:/,$env{'environment.inststatus'});
 6772:             if (!@usertypes) {
 6773:                 push(@usertypes,'default');
 6774:             }
 6775:             if (ref($dom_inst_srch{'directorysrch'}{'cansearch'}) eq 'ARRAY') {
 6776:                 foreach my $type (@usertypes) {
 6777:                     if (grep(/^\Q$type\E$/,@{$dom_inst_srch{'directorysrch'}{'cansearch'}})) {
 6778:                         $can_search = 1;
 6779:                         last;
 6780:                     }
 6781:                 }
 6782:             }
 6783:             if (!$can_search) {
 6784:                 my ($insttypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($srch->{'srchdomain'});
 6785:                 my @longtypes; 
 6786:                 foreach my $item (@usertypes) {
 6787:                     if (defined($insttypes->{$item})) { 
 6788:                         push (@longtypes,$insttypes->{$item});
 6789:                     } elsif ($item eq 'default') {
 6790:                         push (@longtypes,&mt('other')); 
 6791:                     }
 6792:                 }
 6793:                 my $insttype_str = join(', ',@longtypes); 
 6794:                 return &mt('Institutional directory search in domain: [_1] is not available to your user type: ',$showdom).$insttype_str;
 6795:             }
 6796:         } else {
 6797:             $can_search = 1;
 6798:         }
 6799:     } else {
 6800:         return &mt('Institutional directory search has not been configured for domain: [_1]',$showdom);
 6801:     }
 6802:     my %longtext = &Apache::lonlocal::texthash (
 6803:                        uname     => 'username',
 6804:                        lastfirst => 'last name, first name',
 6805:                        lastname  => 'last name',
 6806:                        contains  => 'contains',
 6807:                        exact     => 'as exact match to',
 6808:                        begins    => 'begins with',
 6809:                    );
 6810:     if ($can_search) {
 6811:         if (ref($dom_inst_srch{'directorysrch'}{'searchby'}) eq 'ARRAY') {
 6812:             if (!grep(/^\Q$srch->{'srchby'}\E$/,@{$dom_inst_srch{'directorysrch'}{'searchby'}})) {
 6813:                 return &mt('Institutional directory search in domain: [_1] is not available for searching by "[_2]"',$showdom,$longtext{$srch->{'srchby'}});
 6814:             }
 6815:         } else {
 6816:             return &mt('Institutional directory search in domain: [_1] is not available.', $showdom);
 6817:         }
 6818:     }
 6819:     if ($can_search) {
 6820:         if (ref($dom_inst_srch{'directorysrch'}{'searchtypes'}) eq 'ARRAY') {
 6821:             if (grep(/^\Q$srch->{'srchtype'}\E/,@{$dom_inst_srch{'directorysrch'}{'searchtypes'}})) {
 6822:                 return 'ok';
 6823:             } else {
 6824:                 return &mt('Institutional directory search in domain [_1] is not available for the requested search type: "[_2]"',$showdom,$longtext{$srch->{'srchtype'}});
 6825:             }
 6826:         } else {
 6827:             if ((($dom_inst_srch{'directorysrch'}{'searchtypes'} eq 'specify') &&
 6828:                  ($srch->{'srchtype'} eq 'exact' || $srch->{'srchtype'} eq 'contains')) ||
 6829:                 ($dom_inst_srch{'directorysrch'}{'searchtypes'} eq $srch->{'srchtype'})) {
 6830:                 return 'ok';
 6831:             } else {
 6832:                 return &mt('Institutional directory search in domain [_1] is not available for the requested search type: "[_2]"',$showdom,$longtext{$srch->{'srchtype'}});
 6833:             }
 6834:         }
 6835:     }
 6836: }
 6837: 
 6838: sub get_courseusers {
 6839:     my %advhash;
 6840:     my $classlist = &Apache::loncoursedata::get_classlist();
 6841:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles();
 6842:     foreach my $role (sort(keys(%coursepersonnel))) {
 6843:         foreach my $user (split(/\,/,$coursepersonnel{$role})) {
 6844: 	    if (!exists($classlist->{$user})) {
 6845: 		$classlist->{$user} = [];
 6846: 	    }
 6847:         }
 6848:     }
 6849:     return $classlist;
 6850: }
 6851: 
 6852: sub build_search_response {
 6853:     my ($context,$srch,%srch_results) = @_;
 6854:     my ($currstate,$response,$forcenewuser);
 6855:     my %names = (
 6856:           'uname'     => 'username',
 6857:           'lastname'  => 'last name',
 6858:           'lastfirst' => 'last name, first name',
 6859:           'crs'       => 'this course',
 6860:           'dom'       => 'LON-CAPA domain',
 6861:           'instd'     => 'the institutional directory for domain',
 6862:     );
 6863: 
 6864:     my %single = (
 6865:                    begins   => 'A match',
 6866:                    contains => 'A match',
 6867:                    exact    => 'An exact match',
 6868:                  );
 6869:     my %nomatch = (
 6870:                    begins   => 'No match',
 6871:                    contains => 'No match',
 6872:                    exact    => 'No exact match',
 6873:                   );
 6874:     if (keys(%srch_results) > 1) {
 6875:         $currstate = 'select';
 6876:     } else {
 6877:         if (keys(%srch_results) == 1) {
 6878:             $currstate = 'modify';
 6879:             $response = &mt("$single{$srch->{'srchtype'}} was found for the $names{$srch->{'srchby'}} ([_1]) in $names{$srch->{'srchin'}}.",$srch->{'srchterm'});
 6880:             if ($srch->{'srchin'} eq 'dom' || $srch->{'srchin'} eq 'instd') {
 6881:                 $response .= ': '.&display_domain_info($srch->{'srchdomain'});
 6882:             }
 6883:         } else { # Search has nothing found. Prepare message to user.
 6884:             $response = '<span class="LC_warning">';
 6885:             if ($srch->{'srchin'} eq 'dom' || $srch->{'srchin'} eq 'instd') {
 6886:                 $response .= &mt("$nomatch{$srch->{'srchtype'}} found for the $names{$srch->{'srchby'}} [_1] in $names{$srch->{'srchin'}}: [_2]",
 6887:                                  '<b>'.$srch->{'srchterm'}.'</b>',
 6888:                                  &display_domain_info($srch->{'srchdomain'}));
 6889:             } else {
 6890:                 $response .= &mt("$nomatch{$srch->{'srchtype'}} found for the $names{$srch->{'srchby'}} [_1] in $names{$srch->{'srchin'}}.",
 6891:                                  '<b>'.$srch->{'srchterm'}.'</b>');
 6892:             }
 6893:             $response .= '</span>';
 6894: 
 6895:             if ($srch->{'srchin'} ne 'alc') {
 6896:                 $forcenewuser = 1;
 6897:                 my $cansrchinst = 0; 
 6898:                 if ($srch->{'srchdomain'}) {
 6899:                     my %domconfig = &Apache::lonnet::get_dom('configuration',['directorysrch'],$srch->{'srchdomain'});
 6900:                     if (ref($domconfig{'directorysrch'}) eq 'HASH') {
 6901:                         if ($domconfig{'directorysrch'}{'available'}) {
 6902:                             $cansrchinst = 1;
 6903:                         } 
 6904:                     }
 6905:                 }
 6906:                 if ((($srch->{'srchby'} eq 'lastfirst') || 
 6907:                      ($srch->{'srchby'} eq 'lastname')) &&
 6908:                     ($srch->{'srchin'} eq 'dom')) {
 6909:                     if ($cansrchinst) {
 6910:                         $response .= '<br />'.&mt('You may want to broaden your search to a search of the institutional directory for the domain.');
 6911:                     }
 6912:                 }
 6913:                 if ($srch->{'srchin'} eq 'crs') {
 6914:                     $response .= '<br />'.&mt('You may want to broaden your search to the selected LON-CAPA domain.');
 6915:                 }
 6916:             }
 6917:             my $createdom = $env{'request.role.domain'};
 6918:             if ($context eq 'requestcrs') {
 6919:                 if ($env{'form.coursedom'} ne '') {
 6920:                     $createdom = $env{'form.coursedom'};
 6921:                 }
 6922:             }
 6923:             if (!($srch->{'srchby'} eq 'uname' && $srch->{'srchin'} eq 'dom' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchdomain'} eq $createdom)) {
 6924:                 my $cancreate =
 6925:                     &Apache::lonuserutils::can_create_user($createdom,$context);
 6926:                 my $targetdom = '<span class="LC_cusr_emph">'.$createdom.'</span>';
 6927:                 if ($cancreate) {
 6928:                     my $showdom = &display_domain_info($createdom); 
 6929:                     $response .= '<br /><br />'
 6930:                                 .'<b>'.&mt('To add a new user:').'</b>'
 6931:                                 .'<br />';
 6932:                     if ($context eq 'requestcrs') {
 6933:                         $response .= &mt("(You can only define new users in the new course's domain - [_1])",$targetdom);
 6934:                     } else {
 6935:                         $response .= &mt("(You can only create new users in your current role's domain - [_1])",$targetdom);
 6936:                     }
 6937:                     $response .='<ul><li>'
 6938:                                 .&mt("Set 'Domain/institution to search' to: [_1]",'<span class="LC_cusr_emph">'.$showdom.'</span>')
 6939:                                 .'</li><li>'
 6940:                                 .&mt("Set 'Search criteria' to: [_1]username is ..... in selected LON-CAPA domain[_2]",'<span class="LC_cusr_emph">','</span>')
 6941:                                 .'</li><li>'
 6942:                                 .&mt('Provide the proposed username')
 6943:                                 .'</li><li>'
 6944:                                 .&mt("Click 'Search'")
 6945:                                 .'</li></ul><br />';
 6946:                 } else {
 6947:                     my $helplink = ' href="javascript:helpMenu('."'display'".')"';
 6948:                     $response .= '<br /><br />';
 6949:                     if ($context eq 'requestcrs') {
 6950:                         $response .= &mt("You are not authorized to define new users in the new course's domain - [_1].",$targetdom);
 6951:                     } else {
 6952:                         $response .= &mt("You are not authorized to create new users in your current role's domain - [_1].",$targetdom);
 6953:                     }
 6954:                     $response .= '<br />'
 6955:                                  .&mt('Please contact the [_1]helpdesk[_2] if you need to create a new user.'
 6956:                                     ,' <a'.$helplink.'>'
 6957:                                     ,'</a>')
 6958:                                  .'<br /><br />';
 6959:                 }
 6960:             }
 6961:         }
 6962:     }
 6963:     return ($currstate,$response,$forcenewuser);
 6964: }
 6965: 
 6966: sub display_domain_info {
 6967:     my ($dom) = @_;
 6968:     my $output = $dom;
 6969:     if ($dom ne '') { 
 6970:         my $domdesc = &Apache::lonnet::domain($dom,'description');
 6971:         if ($domdesc ne '') {
 6972:             $output .= ' <span class="LC_cusr_emph">('.$domdesc.')</span>';
 6973:         }
 6974:     }
 6975:     return $output;
 6976: }
 6977: 
 6978: sub crumb_utilities {
 6979:     my %elements = (
 6980:        crtuser => {
 6981:            srchterm => 'text',
 6982:            srchin => 'selectbox',
 6983:            srchby => 'selectbox',
 6984:            srchtype => 'selectbox',
 6985:            srchdomain => 'selectbox',
 6986:        },
 6987:        crtusername => {
 6988:            srchterm => 'text',
 6989:            srchdomain => 'selectbox',
 6990:        },
 6991:        docustom => {
 6992:            rolename => 'selectbox',
 6993:            newrolename => 'textbox',
 6994:        },
 6995:        studentform => {
 6996:            srchterm => 'text',
 6997:            srchin => 'selectbox',
 6998:            srchby => 'selectbox',
 6999:            srchtype => 'selectbox',
 7000:            srchdomain => 'selectbox',
 7001:        },
 7002:     );
 7003: 
 7004:     my $jsback .= qq|
 7005: function backPage(formname,prevphase,prevstate) {
 7006:     if (typeof prevphase == 'undefined') {
 7007:         formname.phase.value = '';
 7008:     }
 7009:     else {  
 7010:         formname.phase.value = prevphase;
 7011:     }
 7012:     if (typeof prevstate == 'undefined') {
 7013:         formname.currstate.value = '';
 7014:     }
 7015:     else {
 7016:         formname.currstate.value = prevstate;
 7017:     }
 7018:     formname.submit();
 7019: }
 7020: |;
 7021:     return ($jsback,\%elements);
 7022: }
 7023: 
 7024: sub course_level_table {
 7025:     my ($inccourses,$showcredits,$defaultcredits) = @_;
 7026:     return unless (ref($inccourses) eq 'HASH');
 7027:     my $table = '';
 7028: # Custom Roles?
 7029: 
 7030:     my %customroles=&Apache::lonuserutils::my_custom_roles();
 7031:     my %lt=&Apache::lonlocal::texthash(
 7032:             'exs'  => "Existing sections",
 7033:             'new'  => "Define new section",
 7034:             'ssd'  => "Set Start Date",
 7035:             'sed'  => "Set End Date",
 7036:             'crl'  => "Course Level",
 7037:             'act'  => "Activate",
 7038:             'rol'  => "Role",
 7039:             'ext'  => "Extent",
 7040:             'grs'  => "Section",
 7041:             'crd'  => "Credits",
 7042:             'sta'  => "Start",
 7043:             'end'  => "End"
 7044:     );
 7045: 
 7046:     foreach my $protectedcourse (sort(keys(%{$inccourses}))) {
 7047: 	my $thiscourse=$protectedcourse;
 7048: 	$thiscourse=~s:_:/:g;
 7049: 	my %coursedata=&Apache::lonnet::coursedescription($thiscourse);
 7050:         my $isowner = &Apache::lonuserutils::is_courseowner($protectedcourse,$coursedata{'internal.courseowner'});
 7051: 	my $area=$coursedata{'description'};
 7052:         my $crstype=$coursedata{'type'};
 7053: 	if (!defined($area)) { $area=&mt('Unavailable course').': '.$protectedcourse; }
 7054: 	my ($domain,$cnum)=split(/\//,$thiscourse);
 7055:         my %sections_count;
 7056:         if (defined($env{'request.course.id'})) {
 7057:             if ($env{'request.course.id'} eq $domain.'_'.$cnum) {
 7058:                 %sections_count = 
 7059: 		    &Apache::loncommon::get_sections($domain,$cnum);
 7060:             }
 7061:         }
 7062:         my @roles = &Apache::lonuserutils::roles_by_context('course','',$crstype);
 7063: 	foreach my $role (@roles) {
 7064:             my $plrole=&Apache::lonnet::plaintext($role,$crstype);
 7065: 	    if ((&Apache::lonnet::allowed('c'.$role,$thiscourse)) ||
 7066:                 ((($role eq 'cc') || ($role eq 'co')) && ($isowner))) {
 7067:                 $table .= &course_level_row($protectedcourse,$role,$area,$domain,
 7068:                                             $plrole,\%sections_count,\%lt,
 7069:                                             $defaultcredits,$crstype);
 7070:             } elsif ($env{'request.course.sec'} ne '') {
 7071:                 if (&Apache::lonnet::allowed('c'.$role,$thiscourse.'/'.
 7072:                                              $env{'request.course.sec'})) {
 7073:                     $table .= &course_level_row($protectedcourse,$role,$area,$domain,
 7074:                                                 $plrole,\%sections_count,\%lt,
 7075:                                                 $defaultcredits,$crstype);
 7076:                 }
 7077:             }
 7078:         }
 7079:         if (&Apache::lonnet::allowed('ccr',$thiscourse)) {
 7080:             foreach my $cust (sort(keys(%customroles))) {
 7081:                 next if ($crstype eq 'Community' && $customroles{$cust} =~ /bre\&S/);
 7082:                 my $role = 'cr_cr_'.$env{'user.domain'}.'_'.$env{'user.name'}.'_'.$cust;
 7083:                 $table .= &course_level_row($protectedcourse,$role,$area,$domain,
 7084:                                             $cust,\%sections_count,\%lt);
 7085:             }
 7086: 	}
 7087:     }
 7088:     return '' if ($table eq ''); # return nothing if there is nothing 
 7089:                                  # in the table
 7090:     my $result;
 7091:     if (!$env{'request.course.id'}) {
 7092:         $result = '<h4>'.$lt{'crl'}.'</h4>'."\n";
 7093:     }
 7094:     $result .= 
 7095: &Apache::loncommon::start_data_table().
 7096: &Apache::loncommon::start_data_table_header_row().
 7097: '<th>'.$lt{'act'}.'</th><th>'.$lt{'rol'}.'</th>'."\n".
 7098: '<th>'.$lt{'ext'}.'</th><th>'.$lt{'crd'}.'</th>'."\n".
 7099: '<th>'.$lt{'grs'}.'</th><th>'.$lt{'sta'}.'</th>'."\n".
 7100: '<th>'.$lt{'end'}.'</th>'.
 7101: &Apache::loncommon::end_data_table_header_row().
 7102: $table.
 7103: &Apache::loncommon::end_data_table();
 7104:     return $result;
 7105: }
 7106: 
 7107: sub course_level_row {
 7108:     my ($protectedcourse,$role,$area,$domain,$plrole,$sections_count,
 7109:         $lt,$defaultcredits,$crstype) = @_;
 7110:     my $creditem;
 7111:     my $row = &Apache::loncommon::start_data_table_row().
 7112:               ' <td><input type="checkbox" name="act_'.
 7113:               $protectedcourse.'_'.$role.'" /></td>'."\n".
 7114:               ' <td>'.$plrole.'</td>'."\n".
 7115:               ' <td>'.$area.'<br />Domain: '.$domain.'</td>'."\n";
 7116:     if (($role eq 'st') && ($crstype eq 'Course')) {
 7117:         $row .= 
 7118:             '<td><input type="text" name="credits_'.$protectedcourse.'_'.
 7119:             $role.'" size="3" value="'.$defaultcredits.'" /></td>';
 7120:     } else {
 7121:         $row .= '<td>&nbsp;</td>';
 7122:     }
 7123:     if (($role eq 'cc') || ($role eq 'co')) {
 7124:         $row .= '<td>&nbsp;</td>';
 7125:     } elsif ($env{'request.course.sec'} ne '') {
 7126:         $row .= ' <td><input type="hidden" value="'.
 7127:                 $env{'request.course.sec'}.'" '.
 7128:                 'name="sec_'.$protectedcourse.'_'.$role.'" />'.
 7129:                 $env{'request.course.sec'}.'</td>';
 7130:     } else {
 7131:         if (ref($sections_count) eq 'HASH') {
 7132:             my $currsec = 
 7133:                 &Apache::lonuserutils::course_sections($sections_count,
 7134:                                                        $protectedcourse.'_'.$role);
 7135:             $row .= '<td><table class="LC_createuser">'."\n".
 7136:                     '<tr class="LC_section_row">'."\n".
 7137:                     ' <td valign="top">'.$lt->{'exs'}.'<br />'.
 7138:                        $currsec.'</td>'."\n".
 7139:                      ' <td>&nbsp;&nbsp;</td>'."\n".
 7140:                      ' <td valign="top">&nbsp;'.$lt->{'new'}.'<br />'.
 7141:                      '<input type="text" name="newsec_'.$protectedcourse.'_'.$role.
 7142:                      '" value="" />'.
 7143:                      '<input type="hidden" '.
 7144:                      'name="sec_'.$protectedcourse.'_'.$role.'" /></td>'."\n".
 7145:                      '</tr></table></td>'."\n";
 7146:         } else {
 7147:             $row .= '<td><input type="text" size="10" '.
 7148:                     'name="sec_'.$protectedcourse.'_'.$role.'" /></td>'."\n";
 7149:         }
 7150:     }
 7151:     $row .= <<ENDTIMEENTRY;
 7152: <td><input type="hidden" name="start_$protectedcourse\_$role" value="" />
 7153: <a href=
 7154: "javascript:pjump('date_start','Start Date $plrole',document.cu.start_$protectedcourse\_$role.value,'start_$protectedcourse\_$role','cu.pres','dateset')">$lt->{'ssd'}</a></td>
 7155: <td><input type="hidden" name="end_$protectedcourse\_$role" value="" />
 7156: <a href=
 7157: "javascript:pjump('date_end','End Date $plrole',document.cu.end_$protectedcourse\_$role.value,'end_$protectedcourse\_$role','cu.pres','dateset')">$lt->{'sed'}</a></td>
 7158: ENDTIMEENTRY
 7159:     $row .= &Apache::loncommon::end_data_table_row();
 7160:     return $row;
 7161: }
 7162: 
 7163: sub course_level_dc {
 7164:     my ($dcdom,$showcredits) = @_;
 7165:     my %customroles=&Apache::lonuserutils::my_custom_roles();
 7166:     my @roles = &Apache::lonuserutils::roles_by_context('course');
 7167:     my $hiddenitems = '<input type="hidden" name="dcdomain" value="'.$dcdom.'" />'.
 7168:                       '<input type="hidden" name="origdom" value="'.$dcdom.'" />'.
 7169:                       '<input type="hidden" name="dccourse" value="" />';
 7170:     my $courseform=&Apache::loncommon::selectcourse_link
 7171:             ('cu','dccourse','dcdomain','coursedesc',undef,undef,'Select','crstype');
 7172:     my $credit_elem;
 7173:     if ($showcredits) {
 7174:         $credit_elem = 'credits';
 7175:     }
 7176:     my $cb_jscript = &Apache::loncommon::coursebrowser_javascript($dcdom,'currsec','cu','role','Course/Community Browser',$credit_elem);
 7177:     my %lt=&Apache::lonlocal::texthash(
 7178:                     'rol'  => "Role",
 7179:                     'grs'  => "Section",
 7180:                     'exs'  => "Existing sections",
 7181:                     'new'  => "Define new section", 
 7182:                     'sta'  => "Start",
 7183:                     'end'  => "End",
 7184:                     'ssd'  => "Set Start Date",
 7185:                     'sed'  => "Set End Date",
 7186:                     'scc'  => "Course/Community",
 7187:                     'crd'  => "Credits",
 7188:                   );
 7189:     my $header = '<h4>'.&mt('Course/Community Level').'</h4>'.
 7190:                  &Apache::loncommon::start_data_table().
 7191:                  &Apache::loncommon::start_data_table_header_row().
 7192:                  '<th>'.$lt{'scc'}.'</th><th>'.$lt{'rol'}.'</th>'."\n".
 7193:                  '<th>'.$lt{'grs'}.'</th><th>'.$lt{'crd'}.'</th>'."\n".
 7194:                  '<th>'.$lt{'sta'}.'</th><th>'.$lt{'end'}.'</th>'."\n".
 7195:                  &Apache::loncommon::end_data_table_header_row();
 7196:     my $otheritems = &Apache::loncommon::start_data_table_row()."\n".
 7197:                      '<td><br /><span class="LC_nobreak"><input type="text" name="coursedesc" value="" onfocus="this.blur();opencrsbrowser('."'cu','dccourse','dcdomain','coursedesc','','','','crstype'".')" />'.
 7198:                      $courseform.('&nbsp;' x4).'</span></td>'."\n".
 7199:                      '<td valign="top"><br /><select name="role">'."\n";
 7200:     foreach my $role (@roles) {
 7201:         my $plrole=&Apache::lonnet::plaintext($role);
 7202:         $otheritems .= '  <option value="'.$role.'">'.$plrole.'</option>';
 7203:     }
 7204:     if ( keys %customroles > 0) {
 7205:         foreach my $cust (sort keys %customroles) {
 7206:             my $custrole='cr_cr_'.$env{'user.domain'}.
 7207:                     '_'.$env{'user.name'}.'_'.$cust;
 7208:             $otheritems .= '  <option value="'.$custrole.'">'.$cust.'</option>';
 7209:         }
 7210:     }
 7211:     $otheritems .= '</select></td><td>'.
 7212:                      '<table border="0" cellspacing="0" cellpadding="0">'.
 7213:                      '<tr><td valign="top"><b>'.$lt{'exs'}.'</b><br /><select name="currsec">'.
 7214:                      ' <option value="">&lt;--'.&mt('Pick course first').'</option></select></td>'.
 7215:                      '<td>&nbsp;&nbsp;</td>'.
 7216:                      '<td valign="top">&nbsp;<b>'.$lt{'new'}.'</b><br />'.
 7217:                      '<input type="text" name="newsec" value="" />'.
 7218:                      '<input type="hidden" name="section" value="" />'.
 7219:                      '<input type="hidden" name="groups" value="" />'.
 7220:                      '<input type="hidden" name="crstype" value="" /></td>'.
 7221:                      '</tr></table></td>'."\n";
 7222:     if ($showcredits) {
 7223:         $otheritems .= '<td><br />'."\n".
 7224:                        '<input type="text" size="3" name="credits" value="" />'."\n";
 7225:     }
 7226:     $otheritems .= <<ENDTIMEENTRY;
 7227: <td><br /><input type="hidden" name="start" value='' />
 7228: <a href=
 7229: "javascript:pjump('date_start','Start Date',document.cu.start.value,'start','cu.pres','dateset')">$lt{'ssd'}</a></td>
 7230: <td><br /><input type="hidden" name="end" value='' />
 7231: <a href=
 7232: "javascript:pjump('date_end','End Date',document.cu.end.value,'end','cu.pres','dateset')">$lt{'sed'}</a></td>
 7233: ENDTIMEENTRY
 7234:     $otheritems .= &Apache::loncommon::end_data_table_row().
 7235:                    &Apache::loncommon::end_data_table()."\n";
 7236:     return $cb_jscript.$header.$hiddenitems.$otheritems;
 7237: }
 7238: 
 7239: sub update_selfenroll_config {
 7240:     my ($r,$context,$permission) = @_;
 7241:     my ($row,$lt) = &get_selfenroll_titles();
 7242:     my %curr_groups = &Apache::longroup::coursegroups();
 7243:     my (%changes,%warning);
 7244:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7245:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7246:     my $curr_types;
 7247:     if (ref($row) eq 'ARRAY') {
 7248:         foreach my $item (@{$row}) {
 7249:             if ($item eq 'enroll_dates') {
 7250:                 my (%currenrolldate,%newenrolldate);
 7251:                 foreach my $type ('start','end') {
 7252:                     $currenrolldate{$type} = $env{'course.'.$env{'request.course.id'}.'.internal.selfenroll_'.$type.'_date'};
 7253:                     $newenrolldate{$type} = &Apache::lonhtmlcommon::get_date_from_form('selfenroll_'.$type.'_date');
 7254:                     if ($newenrolldate{$type} ne $currenrolldate{$type}) {
 7255:                         $changes{'internal.selfenroll_'.$type.'_date'} = $newenrolldate{$type};
 7256:                     }
 7257:                 }
 7258:             } elsif ($item eq 'access_dates') {
 7259:                 my (%currdate,%newdate);
 7260:                 foreach my $type ('start','end') {
 7261:                     $currdate{$type} = $env{'course.'.$env{'request.course.id'}.'.internal.selfenroll_'.$type.'_access'};
 7262:                     $newdate{$type} = &Apache::lonhtmlcommon::get_date_from_form('selfenroll_'.$type.'_access');
 7263:                     if ($newdate{$type} ne $currdate{$type}) {
 7264:                         $changes{'internal.selfenroll_'.$type.'_access'} = $newdate{$type};
 7265:                     }
 7266:                 }
 7267:             } elsif ($item eq 'types') {
 7268:                 $curr_types =
 7269:                     $env{'course.'.$env{'request.course.id'}.'.internal.selfenroll_'.$item};
 7270:                 if ($env{'form.selfenroll_all'}) {
 7271:                     if ($curr_types ne '*') {
 7272:                         $changes{'internal.selfenroll_types'} = '*';
 7273:                     } else {
 7274:                         next;
 7275:                     }
 7276:                 } else {
 7277:                     my %currdoms;
 7278:                     my @entries = split(/;/,$curr_types);
 7279:                     my @deletedoms = &Apache::loncommon::get_env_multiple('form.selfenroll_delete');
 7280:                     my @activations = &Apache::loncommon::get_env_multiple('form.selfenroll_activate');
 7281:                     my $newnum = 0;
 7282:                     my @latesttypes;
 7283:                     foreach my $num (@activations) {
 7284:                         my @types = &Apache::loncommon::get_env_multiple('form.selfenroll_types_'.$num);
 7285:                         if (@types > 0) {
 7286:                             @types = sort(@types);
 7287:                             my $typestr = join(',',@types);
 7288:                             my $typedom = $env{'form.selfenroll_dom_'.$num};
 7289:                             $latesttypes[$newnum] = $typedom.':'.$typestr;
 7290:                             $currdoms{$typedom} = 1;
 7291:                             $newnum ++;
 7292:                         }
 7293:                     }
 7294:                     for (my $j=0; $j<$env{'form.selfenroll_types_total'}; $j++) {
 7295:                         if ((!grep(/^$j$/,@deletedoms)) && (!grep(/^$j$/,@activations))) {
 7296:                             my @types = &Apache::loncommon::get_env_multiple('form.selfenroll_types_'.$j);
 7297:                             if (@types > 0) {
 7298:                                 @types = sort(@types);
 7299:                                 my $typestr = join(',',@types);
 7300:                                 my $typedom = $env{'form.selfenroll_dom_'.$j};
 7301:                                 $latesttypes[$newnum] = $typedom.':'.$typestr;
 7302:                                 $currdoms{$typedom} = 1;
 7303:                                 $newnum ++;
 7304:                             }
 7305:                         }
 7306:                     }
 7307:                     if ($env{'form.selfenroll_newdom'} ne '') {
 7308:                         my $typedom = $env{'form.selfenroll_newdom'};
 7309:                         if ((!defined($currdoms{$typedom})) && 
 7310:                             (&Apache::lonnet::domain($typedom) ne '')) {
 7311:                             my $typestr;
 7312:                             my ($othertitle,$usertypes,$types) = 
 7313:                                 &Apache::loncommon::sorted_inst_types($typedom);
 7314:                             my $othervalue = 'any';
 7315:                             if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 7316:                                 if (@{$types} > 0) {
 7317:                                     my @esc_types = map { &escape($_); } @{$types};
 7318:                                     $othervalue = 'other';
 7319:                                     $typestr = join(',',(@esc_types,$othervalue));
 7320:                                 }
 7321:                                 $typestr = $othervalue;
 7322:                             } else {
 7323:                                 $typestr = $othervalue;
 7324:                             } 
 7325:                             $latesttypes[$newnum] = $typedom.':'.$typestr;
 7326:                             $newnum ++ ;
 7327:                         }
 7328:                     }
 7329:                     my $selfenroll_types = join(';',@latesttypes);
 7330:                     if ($selfenroll_types ne $curr_types) {
 7331:                         $changes{'internal.selfenroll_types'} = $selfenroll_types;
 7332:                     }
 7333:                 }
 7334:             } elsif ($item eq 'limit') {
 7335:                 my $newlimit = $env{'form.selfenroll_limit'};
 7336:                 my $newcap = $env{'form.selfenroll_cap'};
 7337:                 $newcap =~s/\s+//g;
 7338:                 my $currlimit =  $env{'course.'.$env{'request.course.id'}.'.internal.selfenroll_limit'};
 7339:                 $currlimit = 'none' if ($currlimit eq '');
 7340:                 my $currcap = $env{'course.'.$env{'request.course.id'}.'.internal.selfenroll_cap'};
 7341:                 if ($newlimit ne $currlimit) {
 7342:                     if ($newlimit ne 'none') {
 7343:                         if ($newcap =~ /^\d+$/) {
 7344:                             if ($newcap ne $currcap) {
 7345:                                 $changes{'internal.selfenroll_cap'} = $newcap;
 7346:                             }
 7347:                             $changes{'internal.selfenroll_limit'} = $newlimit;
 7348:                         } else {
 7349:                             $warning{$item} = &mt('Maximum enrollment setting unchanged.').'<br />'.&mt('The value provided was invalid - it must be a positive integer if enrollment is being limited.'); 
 7350:                         }
 7351:                     } elsif ($currcap ne '') {
 7352:                         $changes{'internal.selfenroll_cap'} = '';
 7353:                         $changes{'internal.selfenroll_limit'} = $newlimit; 
 7354:                     }
 7355:                 } elsif ($currlimit ne 'none') {
 7356:                     if ($newcap =~ /^\d+$/) {
 7357:                         if ($newcap ne $currcap) {
 7358:                             $changes{'internal.selfenroll_cap'} = $newcap;
 7359:                         }
 7360:                     } else {
 7361:                         $warning{$item} = &mt('Maximum enrollment setting unchanged.').'<br />'.&mt('The value provided was invalid - it must be a positive integer if enrollment is being limited.');
 7362:                     }
 7363:                 }
 7364:             } elsif ($item eq 'approval') {
 7365:                 my (@currnotified,@newnotified);
 7366:                 my $currapproval = $env{'course.'.$env{'request.course.id'}.'.internal.selfenroll_approval'};
 7367:                 my $currnotifylist = $env{'course.'.$env{'request.course.id'}.'.internal.selfenroll_notifylist'};
 7368:                 if ($currnotifylist ne '') {
 7369:                     @currnotified = split(/,/,$currnotifylist);
 7370:                     @currnotified = sort(@currnotified);
 7371:                 }
 7372:                 my $newapproval = $env{'form.selfenroll_approval'};
 7373:                 @newnotified = &Apache::loncommon::get_env_multiple('form.selfenroll_notify');
 7374:                 @newnotified = sort(@newnotified);
 7375:                 if ($newapproval ne $currapproval) {
 7376:                     $changes{'internal.selfenroll_approval'} = $newapproval;
 7377:                     if (!$newapproval) {
 7378:                         if ($currnotifylist ne '') {
 7379:                             $changes{'internal.selfenroll_notifylist'} = '';
 7380:                         }
 7381:                     } else {
 7382:                         my @differences =  
 7383:                             &Apache::loncommon::compare_arrays(\@currnotified,\@newnotified);
 7384:                         if (@differences > 0) {
 7385:                             if (@newnotified > 0) {
 7386:                                 $changes{'internal.selfenroll_notifylist'} = join(',',@newnotified);
 7387:                             } else {
 7388:                                 $changes{'internal.selfenroll_notifylist'} = join(',',@newnotified);
 7389:                             }
 7390:                         }
 7391:                     }
 7392:                 } else {
 7393:                     my @differences = &Apache::loncommon::compare_arrays(\@currnotified,\@newnotified);
 7394:                     if (@differences > 0) {
 7395:                         if (@newnotified > 0) {
 7396:                             $changes{'internal.selfenroll_notifylist'} = join(',',@newnotified);
 7397:                         } else {
 7398:                             $changes{'internal.selfenroll_notifylist'} = '';
 7399:                         }
 7400:                     }
 7401:                 }
 7402:             } else {
 7403:                 my $curr_val = 
 7404:                     $env{'course.'.$env{'request.course.id'}.'.internal.selfenroll_'.$item};
 7405:                 my $newval = $env{'form.selfenroll_'.$item};
 7406:                 if ($item eq 'section') {
 7407:                     $newval = $env{'form.sections'};
 7408:                     if (defined($curr_groups{$newval})) {
 7409:                         $newval = $curr_val;
 7410:                         $warning{$item} = &mt('Section for self-enrolled users unchanged as the proposed section is a group').'<br />'.&mt('Group names and section names must be distinct');
 7411:                     } elsif ($newval eq 'all') {
 7412:                         $newval = $curr_val;
 7413:                         $warning{$item} = &mt('Section for self-enrolled users unchanged, as "all" is a reserved section name.');
 7414:                     }
 7415:                     if ($newval eq '') {
 7416:                         $newval = 'none';
 7417:                     }
 7418:                 }
 7419:                 if ($newval ne $curr_val) {
 7420:                     $changes{'internal.selfenroll_'.$item} = $newval;
 7421:                 }
 7422:             }
 7423:         }
 7424:         if (keys(%warning) > 0) {
 7425:             foreach my $item (@{$row}) {
 7426:                 if (exists($warning{$item})) {
 7427:                     $r->print($warning{$item}.'<br />');
 7428:                 }
 7429:             } 
 7430:         }
 7431:         if (keys(%changes) > 0) {
 7432:             my $putresult = &Apache::lonnet::put('environment',\%changes,$cdom,$cnum);
 7433:             if ($putresult eq 'ok') {
 7434:                 if ((exists($changes{'internal.selfenroll_types'})) ||
 7435:                     (exists($changes{'internal.selfenroll_start_date'}))  ||
 7436:                     (exists($changes{'internal.selfenroll_end_date'}))) {
 7437:                     my %crsinfo = &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',
 7438:                                                                 $cnum,undef,undef,'Course');
 7439:                     my $chome = &Apache::lonnet::homeserver($cnum,$cdom);
 7440:                     if (ref($crsinfo{$env{'request.course.id'}}) eq 'HASH') {
 7441:                         foreach my $item ('selfenroll_types','selfenroll_start_date','selfenroll_end_date') {
 7442:                             if (exists($changes{'internal.'.$item})) {
 7443:                                 $crsinfo{$env{'request.course.id'}}{$item} = 
 7444:                                     $changes{'internal.'.$item};
 7445:                             }
 7446:                         }
 7447:                         my $crsputresult =
 7448:                             &Apache::lonnet::courseidput($cdom,\%crsinfo,
 7449:                                                          $chome,'notime');
 7450:                     }
 7451:                 }
 7452:                 $r->print(&mt('The following changes were made to self-enrollment settings:').'<ul>');
 7453:                 foreach my $item (@{$row}) {
 7454:                     my $title = $item;
 7455:                     if (ref($lt) eq 'HASH') {
 7456:                         $title = $lt->{$item};
 7457:                     }
 7458:                     if ($item eq 'enroll_dates') {
 7459:                         foreach my $type ('start','end') {
 7460:                             if (exists($changes{'internal.selfenroll_'.$type.'_date'})) {
 7461:                                 my $newdate = &Apache::lonlocal::locallocaltime($changes{'internal.selfenroll_'.$type.'_date'});
 7462:                                 $r->print('<li>'.&mt('[_1]: "[_2]" set to "[_3]".',
 7463:                                           $title,$type,$newdate).'</li>');
 7464:                             }
 7465:                         }
 7466:                     } elsif ($item eq 'access_dates') {
 7467:                         foreach my $type ('start','end') {
 7468:                             if (exists($changes{'internal.selfenroll_'.$type.'_access'})) {
 7469:                                 my $newdate = &Apache::lonlocal::locallocaltime($changes{'internal.selfenroll_'.$type.'_access'});
 7470:                                 $r->print('<li>'.&mt('[_1]: "[_2]" set to "[_3]".',
 7471:                                           $title,$type,$newdate).'</li>');
 7472:                             }
 7473:                         }
 7474:                     } elsif ($item eq 'limit') {
 7475:                         if ((exists($changes{'internal.selfenroll_limit'})) ||
 7476:                             (exists($changes{'internal.selfenroll_cap'}))) {
 7477:                             my ($newval,$newcap);
 7478:                             if ($changes{'internal.selfenroll_cap'} ne '') {
 7479:                                 $newcap = $changes{'internal.selfenroll_cap'}
 7480:                             } else {
 7481:                                 $newcap = $env{'course.'.$env{'request.course.id'}.'.internal.selfenroll_cap'};
 7482:                             }
 7483:                             if ($changes{'internal.selfenroll_limit'} eq 'none') {
 7484:                                 $newval = &mt('No limit');
 7485:                             } elsif ($changes{'internal.selfenroll_limit'} eq 
 7486:                                      'allstudents') {
 7487:                                 $newval = &mt('New self-enrollment no longer allowed when total (all students) reaches [_1].',$newcap);
 7488:                             } elsif ($changes{'internal.selfenroll_limit'} eq 'selfenrolled') {
 7489:                                 $newval = &mt('New self-enrollment no longer allowed when total number of self-enrolled students reaches [_1].',$newcap);
 7490:                             } else {
 7491:                                 my $currlimit =  $env{'course.'.$env{'request.course.id'}.'.internal.selfenroll_limit'};
 7492:                                 if ($currlimit eq 'allstudents') {
 7493:                                     $newval = &mt('New self-enrollment no longer allowed when total (all students) reaches [_1].',$newcap);
 7494:                                 } elsif ($changes{'internal.selfenroll_limit'} eq 'selfenrolled') {
 7495:                                     $newval =  &mt('New self-enrollment no longer allowed when total number of self-enrolled students reaches [_1].',$newcap);
 7496:                                 }
 7497:                             }
 7498:                             $r->print('<li>'.&mt('"[_1]" set to "[_2]".',$title,$newval).'</li>'."\n");
 7499:                         }
 7500:                     } elsif ($item eq 'approval') {
 7501:                         if ((exists($changes{'internal.selfenroll_approval'})) ||
 7502:                             (exists($changes{'internal.selfenroll_notifylist'}))) {
 7503:                             my ($newval,$newnotify);
 7504:                             if (exists($changes{'internal.selfenroll_notifylist'})) {
 7505:                                 $newnotify = $changes{'internal.selfenroll_notifylist'};
 7506:                             } else {   
 7507:                                 $newnotify = $env{'course.'.$env{'request.course.id'}.'.internal.selfenroll_notifylist'};
 7508:                             }
 7509:                             if ($changes{'internal.selfenroll_approval'}) {
 7510:                                 $newval = &mt('Yes');
 7511:                             } elsif ($changes{'internal.selfenroll_approval'} eq '0') {
 7512:                                 $newval = &mt('No');
 7513:                             } else {
 7514:                                 my $currapproval = 
 7515:                                     $env{'course.'.$env{'request.course.id'}.'.internal.selfenroll_approval'};
 7516:                                 if ($currapproval) {
 7517:                                     $newval = &mt('Yes');
 7518:                                 } else {
 7519:                                     $newval = &mt('No');
 7520:                                 }
 7521:                             }
 7522:                             $r->print('<li>'.&mt('"[_1]" set to "[_2]".',$title,$newval));
 7523:                             if ($newnotify) {
 7524:                                 $r->print('<br />'.&mt('The following will be notified when an enrollment request needs approval, or has been approved: [_1].',$newnotify));
 7525:                             } else {
 7526:                                 $r->print('<br />'.&mt('No notifications sent when an enrollment request needs approval, or has been approved.'));
 7527:                             }
 7528:                             $r->print('</li>'."\n");
 7529:                         }
 7530:                     } else {
 7531:                         if (exists($changes{'internal.selfenroll_'.$item})) {
 7532:                             my $newval = $changes{'internal.selfenroll_'.$item};
 7533:                             if ($item eq 'types') {
 7534:                                 if ($newval eq '') {
 7535:                                     $newval = &mt('None');
 7536:                                 } elsif ($newval eq '*') {
 7537:                                     $newval = &mt('Any user in any domain');
 7538:                                 }
 7539:                             } elsif ($item eq 'registered') {
 7540:                                 if ($newval eq '1') {
 7541:                                     $newval = &mt('Yes');
 7542:                                 } elsif ($newval eq '0') {
 7543:                                     $newval = &mt('No');
 7544:                                 }
 7545:                             }
 7546:                             $r->print('<li>'.&mt('"[_1]" set to "[_2]".',$title,$newval).'</li>'."\n");
 7547:                         }
 7548:                     }
 7549:                 }
 7550:                 $r->print('</ul>');
 7551:                 my %newenvhash;
 7552:                 foreach my $key (keys(%changes)) {
 7553:                     $newenvhash{'course.'.$env{'request.course.id'}.'.'.$key} = $changes{$key};
 7554:                 }
 7555:                 &Apache::lonnet::appenv(\%newenvhash);
 7556:             } else {
 7557:                 $r->print(&mt('An error occurred when saving changes to self-enrollment settings in this course.').'<br />'.&mt('The error was: [_1].',$putresult));
 7558:             }
 7559:         } else {
 7560:             $r->print(&mt('No changes were made to the existing self-enrollment settings in this course.'));
 7561:         }
 7562:     } else {
 7563:         $r->print(&mt('No changes were made to the existing self-enrollment settings in this course.'));
 7564:     }
 7565:     my ($visible,$cansetvis,$vismsgs,$visactions) = &visible_in_cat($cdom,$cnum);
 7566:     if (ref($visactions) eq 'HASH') {
 7567:         if (!$visible) {
 7568:             $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
 7569:                       '<br />');
 7570:             if (ref($vismsgs) eq 'ARRAY') {
 7571:                 $r->print('<br />'.$visactions->{'take'}.'<ul>');
 7572:                 foreach my $item (@{$vismsgs}) {
 7573:                     $r->print('<li>'.$visactions->{$item}.'</li>');
 7574:                 }
 7575:                 $r->print('</ul>');
 7576:             }
 7577:             $r->print($cansetvis);
 7578:         }
 7579:     } 
 7580:     return;
 7581: }
 7582: 
 7583: sub get_selfenroll_titles {
 7584:     my @row = ('types','registered','enroll_dates','access_dates','section',
 7585:                'approval','limit');
 7586:     my %lt = &Apache::lonlocal::texthash (
 7587:                 types        => 'Users allowed to self-enroll in this course',
 7588:                 registered   => 'Restrict self-enrollment to students officially registered for the course',
 7589:                 enroll_dates => 'Dates self-enrollment available',
 7590:                 access_dates => 'Course access dates assigned to self-enrolling users',
 7591:                 section      => 'Section assigned to self-enrolling users',
 7592:                 approval     => 'Self-enrollment requests need approval?',
 7593:                 limit        => 'Enrollment limit',
 7594:              );
 7595:     return (\@row,\%lt);
 7596: }
 7597: 
 7598: #---------------------------------------------- end functions for &phase_two
 7599: 
 7600: #--------------------------------- functions for &phase_two and &phase_three
 7601: 
 7602: #--------------------------end of functions for &phase_two and &phase_three
 7603: 
 7604: 1;
 7605: __END__
 7606: 
 7607: 

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