File:  [LON-CAPA] / loncom / interface / loncreateuser.pm
Revision 1.403: download - view: text, annotated - select for diffs
Mon Jun 30 14:49:35 2014 UTC (9 years, 10 months ago) by raeburn
Branches: MAIN
CVS tags: version_2_11_0, HEAD
- Update user's session environment if DC modifies his/her own rights to
  request textbook courses.

    1: # The LearningOnline Network with CAPA
    2: # Create a user
    3: #
    4: # $Id: loncreateuser.pm,v 1.403 2014/06/30 14:49:35 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('Custom role [_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,$usertype) = @_;
 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:                 if (ref($emailusername->{$usertype}) eq 'HASH') {
 2211:                     my ($infofields,$infotitles) = &Apache::loncommon::emailusername_info();
 2212:                     @userinfo = ();          
 2213:                     if ((ref($infofields) eq 'ARRAY') && (ref($infotitles) eq 'HASH')) {
 2214:                         foreach my $field (@{$infofields}) { 
 2215:                             if ($emailusername->{$usertype}->{$field}) {
 2216:                                 push(@userinfo,$field);
 2217:                                 $canmodify{$field} = 1;
 2218:                                 unless ($textboxsize{$field}) {
 2219:                                     $textboxsize{$field} = 25;
 2220:                                 }
 2221:                                 unless ($lt{$field}) {
 2222:                                     $lt{$field} = $infotitles->{$field};
 2223:                                 }
 2224:                                 if ($emailusername->{$usertype}->{$field} eq 'required') {
 2225:                                     $lt{$field} .= '<b>*</b>';
 2226:                                 }
 2227:                             }
 2228:                         }
 2229:                     }
 2230:                 }
 2231:             }
 2232:         } else {
 2233:             %canmodify = &selfcreate_canmodify($context,$ccdomain,\@userinfo,
 2234:                                                $inst_results,$rolesarray);
 2235:         }
 2236:     }
 2237: 
 2238:     my $genhelp=&Apache::loncommon::help_open_topic('Generation');
 2239:     $output = '<h3>'.$lt{'pd'}.'</h3>'.
 2240:               &Apache::lonhtmlcommon::start_pick_box();
 2241:     if (($context eq 'selfcreate') && ($newuser eq 'email')) {
 2242:         $output .= &Apache::lonhtmlcommon::row_title($lt{'email'}.'<b>*</b>',undef,
 2243:                                                      'LC_oddrow_value')."\n".
 2244:                    '<input type="text" name="uname" size="25" value="" autocomplete="off" />';
 2245:         $rowcount ++;
 2246:         $output .= &Apache::lonhtmlcommon::row_closure(1);
 2247:         my $upassone = '<input type="password" name="upass'.$now.'" size="10" autocomplete="off" />';
 2248:         my $upasstwo = '<input type="password" name="upasscheck'.$now.'" size="10" autocomplete="off" />';
 2249:         $output .= &Apache::lonhtmlcommon::row_title(&mt('Password').'<b>*</b>',
 2250:                                                     'LC_pick_box_title',
 2251:                                                     'LC_oddrow_value')."\n".
 2252:                    $upassone."\n".
 2253:                    &Apache::lonhtmlcommon::row_closure(1)."\n".
 2254:                    &Apache::lonhtmlcommon::row_title(&mt('Confirm password').'<b>*</b>',
 2255:                                                      'LC_pick_box_title',
 2256:                                                      'LC_oddrow_value')."\n".
 2257:                    $upasstwo.
 2258:                    &Apache::lonhtmlcommon::row_closure()."\n";
 2259:     }
 2260:     foreach my $item (@userinfo) {
 2261:         my $rowtitle = $lt{$item};
 2262:         my $hiderow = 0;
 2263:         if ($item eq 'generation') {
 2264:             $rowtitle = $genhelp.$rowtitle;
 2265:         }
 2266:         my $row = &Apache::lonhtmlcommon::row_title($rowtitle,undef,'LC_oddrow_value')."\n";
 2267:         if ($newuser) {
 2268:             if (ref($inst_results) eq 'HASH') {
 2269:                 if ($inst_results->{$item} ne '') {
 2270:                     $row .= '<input type="hidden" name="c'.$item.'" value="'.$inst_results->{$item}.'" />'.$inst_results->{$item};
 2271:                 } else {
 2272:                     if ($context eq 'selfcreate') {
 2273:                         if ($canmodify{$item}) {
 2274:                             $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="" autocomplete="off" />';
 2275:                             $editable ++;
 2276:                         } else {
 2277:                             $hiderow = 1;
 2278:                         }
 2279:                     } else {
 2280:                         $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="" />';
 2281:                     }
 2282:                 }
 2283:             } else {
 2284:                 if ($context eq 'selfcreate') {
 2285:                     if ($canmodify{$item}) {
 2286:                         if ($newuser eq 'email') {
 2287:                             $row .= '<input type="text" name="'.$item.'" size="'.$textboxsize{$item}.'" value="" autocomplete="off" />';
 2288:                         } else {
 2289:                             $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="" autocomplete="off" />';
 2290:                         }
 2291:                         $editable ++;
 2292:                     } else {
 2293:                         $hiderow = 1;
 2294:                     }
 2295:                 } else {
 2296:                     $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="" />';
 2297:                 }
 2298:             }
 2299:         } else {
 2300:             if ($canmodify{$item}) {
 2301:                 $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="'.$userenv{$item}.'" />';
 2302:                 if (($item eq 'id') && (!$newuser)) {
 2303:                     $row .= '<br />'.&Apache::lonuserutils::forceid_change($context);
 2304:                 }
 2305:             } else {
 2306:                 $row .= $userenv{$item};
 2307:             }
 2308:         }
 2309:         $row .= &Apache::lonhtmlcommon::row_closure(1);
 2310:         if (!$hiderow) {
 2311:             $output .= $row;
 2312:             $rowcount ++;
 2313:         }
 2314:     }
 2315:     if (($canmodify_status{'inststatus'}) || ($context ne 'selfcreate')) {
 2316:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($ccdomain);
 2317:         if (ref($types) eq 'ARRAY') {
 2318:             if (@{$types} > 0) {
 2319:                 my ($hiderow,$shown);
 2320:                 if ($canmodify_status{'inststatus'}) {
 2321:                     $shown = &pick_inst_statuses($userenv{'inststatus'},$usertypes,$types);
 2322:                 } else {
 2323:                     if ($userenv{'inststatus'} eq '') {
 2324:                         $hiderow = 1;
 2325:                     } else {
 2326:                         my @showitems;
 2327:                         foreach my $item ( map { &unescape($_); } split(':',$userenv{'inststatus'})) {
 2328:                             if (exists($usertypes->{$item})) {
 2329:                                 push(@showitems,$usertypes->{$item});
 2330:                             } else {
 2331:                                 push(@showitems,$item);
 2332:                             }
 2333:                         }
 2334:                         if (@showitems) {
 2335:                             $shown = join(', ',@showitems);
 2336:                         } else {
 2337:                             $hiderow = 1;
 2338:                         }
 2339:                     }
 2340:                 }
 2341:                 if (!$hiderow) {
 2342:                     my $row = &Apache::lonhtmlcommon::row_title(&mt('Affiliations'),undef,'LC_oddrow_value')."\n".
 2343:                               $shown.&Apache::lonhtmlcommon::row_closure(1); 
 2344:                     if ($context eq 'selfcreate') {
 2345:                         $rowcount ++;
 2346:                     }
 2347:                     $output .= $row;
 2348:                 }
 2349:             }
 2350:         }
 2351:     }
 2352:     if (($context eq 'selfcreate') && ($newuser eq 'email')) {
 2353:         if ($captchaform) {
 2354:             $output .= &Apache::lonhtmlcommon::row_title($lt{'valid'},
 2355:                                                          'LC_pick_box_title')."\n".
 2356:                        $captchaform."\n".'<br /><br />'.
 2357:                        &Apache::lonhtmlcommon::row_closure(1); 
 2358:             $rowcount ++;
 2359:         }
 2360:         my $submit_text = &mt('Create account');
 2361:         $output .= &Apache::lonhtmlcommon::row_title()."\n".
 2362:                    '<br /><input type="submit" name="createaccount" value="'.
 2363:                    $submit_text.'" />'.
 2364:                    '<input type="hidden" name="type" value="'.$usertype.'" />'.
 2365:                    &Apache::lonhtmlcommon::row_closure(1);
 2366:     }
 2367:     $output .= &Apache::lonhtmlcommon::end_pick_box();
 2368:     if (wantarray) {
 2369:         if ($context eq 'selfcreate') {
 2370:             return($output,$rowcount,$editable);
 2371:         } else {
 2372:             return $output;
 2373:         }
 2374:     } else {
 2375:         return $output;
 2376:     }
 2377: }
 2378: 
 2379: sub pick_inst_statuses {
 2380:     my ($curr,$usertypes,$types) = @_;
 2381:     my ($output,$rem,@currtypes);
 2382:     if ($curr ne '') {
 2383:         @currtypes = map { &unescape($_); } split(/:/,$curr);
 2384:     }
 2385:     my $numinrow = 2;
 2386:     if (ref($types) eq 'ARRAY') {
 2387:         $output = '<table>';
 2388:         my $lastcolspan; 
 2389:         for (my $i=0; $i<@{$types}; $i++) {
 2390:             if (defined($usertypes->{$types->[$i]})) {
 2391:                 my $rem = $i%($numinrow);
 2392:                 if ($rem == 0) {
 2393:                     if ($i<@{$types}-1) {
 2394:                         if ($i > 0) { 
 2395:                             $output .= '</tr>';
 2396:                         }
 2397:                         $output .= '<tr>';
 2398:                     }
 2399:                 } elsif ($i==@{$types}-1) {
 2400:                     my $colsleft = $numinrow - $rem;
 2401:                     if ($colsleft > 1) {
 2402:                         $lastcolspan = ' colspan="'.$colsleft.'"';
 2403:                     }
 2404:                 }
 2405:                 my $check = ' ';
 2406:                 if (grep(/^\Q$types->[$i]\E$/,@currtypes)) {
 2407:                     $check = ' checked="checked" ';
 2408:                 }
 2409:                 $output .= '<td class="LC_left_item"'.$lastcolspan.'>'.
 2410:                            '<span class="LC_nobreak"><label>'.
 2411:                            '<input type="checkbox" name="inststatus" '.
 2412:                            'value="'.$types->[$i].'"'.$check.'/>'.
 2413:                            $usertypes->{$types->[$i]}.'</label></span></td>';
 2414:             }
 2415:         }
 2416:         $output .= '</tr></table>';
 2417:     }
 2418:     return $output;
 2419: }
 2420: 
 2421: sub selfcreate_canmodify {
 2422:     my ($context,$dom,$userinfo,$inst_results,$rolesarray) = @_;
 2423:     if (ref($inst_results) eq 'HASH') {
 2424:         my @inststatuses = &get_inststatuses($inst_results);
 2425:         if (@inststatuses == 0) {
 2426:             @inststatuses = ('default');
 2427:         }
 2428:         $rolesarray = \@inststatuses;
 2429:     }
 2430:     my %canmodify =
 2431:         &Apache::lonuserutils::can_modify_userinfo($context,$dom,$userinfo,
 2432:                                                    $rolesarray);
 2433:     return %canmodify;
 2434: }
 2435: 
 2436: sub get_inststatuses {
 2437:     my ($insthashref) = @_;
 2438:     my @inststatuses = ();
 2439:     if (ref($insthashref) eq 'HASH') {
 2440:         if (ref($insthashref->{'inststatus'}) eq 'ARRAY') {
 2441:             @inststatuses = @{$insthashref->{'inststatus'}};
 2442:         }
 2443:     }
 2444:     return @inststatuses;
 2445: }
 2446: 
 2447: # ================================================================= Phase Three
 2448: sub update_user_data {
 2449:     my ($r,$context,$crstype,$brcrum,$showcredits) = @_; 
 2450:     my $uhome=&Apache::lonnet::homeserver($env{'form.ccuname'},
 2451:                                           $env{'form.ccdomain'});
 2452:     # Error messages
 2453:     my $error     = '<span class="LC_error">'.&mt('Error').': ';
 2454:     my $end       = '</span><br /><br />';
 2455:     my $rtnlink   = '<a href="javascript:backPage(document.userupdate,'.
 2456:                     "'$env{'form.prevphase'}','modify')".'" />'.
 2457:                     &mt('Return to previous page').'</a>'.
 2458:                     &Apache::loncommon::end_page();
 2459:     my $now = time;
 2460:     my $title;
 2461:     if (exists($env{'form.makeuser'})) {
 2462: 	$title='Set Privileges for New User';
 2463:     } else {
 2464:         $title='Modify User Privileges';
 2465:     }
 2466:     my $newuser = 0;
 2467:     my ($jsback,$elements) = &crumb_utilities();
 2468:     my $jscript = '<script type="text/javascript">'."\n".
 2469:                   '// <![CDATA['."\n".
 2470:                   $jsback."\n".
 2471:                   '// ]]>'."\n".
 2472:                   '</script>'."\n";
 2473:     my %breadcrumb_text = &singleuser_breadcrumb($crstype);
 2474:     push (@{$brcrum},
 2475:              {href => "javascript:backPage(document.userupdate)",
 2476:               text => $breadcrumb_text{'search'},
 2477:               faq  => 282,
 2478:               bug  => 'Instructor Interface',}
 2479:              );
 2480:     if ($env{'form.prevphase'} eq 'userpicked') {
 2481:         push(@{$brcrum},
 2482:                {href => "javascript:backPage(document.userupdate,'get_user_info','select')",
 2483:                 text => $breadcrumb_text{'userpicked'},
 2484:                 faq  => 282,
 2485:                 bug  => 'Instructor Interface',});
 2486:     }
 2487:     my $helpitem = 'Course_Change_Privileges';
 2488:     if ($env{'form.action'} eq 'singlestudent') {
 2489:         $helpitem = 'Course_Add_Student';
 2490:     }
 2491:     push(@{$brcrum}, 
 2492:             {href => "javascript:backPage(document.userupdate,'$env{'form.prevphase'}','modify')",
 2493:              text => $breadcrumb_text{'modify'},
 2494:              faq  => 282,
 2495:              bug  => 'Instructor Interface',},
 2496:             {href => "/adm/createuser",
 2497:              text => "Result",
 2498:              faq  => 282,
 2499:              bug  => 'Instructor Interface',
 2500:              help => $helpitem});
 2501:     my $args = {bread_crumbs          => $brcrum,
 2502:                 bread_crumbs_component => 'User Management'};
 2503:     if ($env{'form.popup'}) {
 2504:         $args->{'no_nav_bar'} = 1;
 2505:     }
 2506:     $r->print(&Apache::loncommon::start_page($title,$jscript,$args));
 2507:     $r->print(&update_result_form($uhome));
 2508:     # Check Inputs
 2509:     if (! $env{'form.ccuname'} ) {
 2510: 	$r->print($error.&mt('No login name specified').'.'.$end.$rtnlink);
 2511: 	return;
 2512:     }
 2513:     if (  $env{'form.ccuname'} ne 
 2514: 	  &LONCAPA::clean_username($env{'form.ccuname'}) ) {
 2515: 	$r->print($error.&mt('Invalid login name.').'  '.
 2516: 		  &mt('Only letters, numbers, periods, dashes, @, and underscores are valid.').
 2517: 		  $end.$rtnlink);
 2518: 	return;
 2519:     }
 2520:     if (! $env{'form.ccdomain'}       ) {
 2521: 	$r->print($error.&mt('No domain specified').'.'.$end.$rtnlink);
 2522: 	return;
 2523:     }
 2524:     if (  $env{'form.ccdomain'} ne
 2525: 	  &LONCAPA::clean_domain($env{'form.ccdomain'}) ) {
 2526: 	$r->print($error.&mt('Invalid domain name.').'  '.
 2527: 		  &mt('Only letters, numbers, periods, dashes, and underscores are valid.').
 2528: 		  $end.$rtnlink);
 2529: 	return;
 2530:     }
 2531:     if ($uhome eq 'no_host') {
 2532:         $newuser = 1;
 2533:     }
 2534:     if (! exists($env{'form.makeuser'})) {
 2535:         # Modifying an existing user, so check the validity of the name
 2536:         if ($uhome eq 'no_host') {
 2537:             $r->print(
 2538:                 $error
 2539:                .'<p class="LC_error">'
 2540:                .&mt('Unable to determine home server for [_1] in domain [_2].',
 2541:                         '"'.$env{'form.ccuname'}.'"','"'.$env{'form.ccdomain'}.'"')
 2542:                .'</p>');
 2543:             return;
 2544:         }
 2545:     }
 2546:     # Determine authentication method and password for the user being modified
 2547:     my $amode='';
 2548:     my $genpwd='';
 2549:     if ($env{'form.login'} eq 'krb') {
 2550: 	$amode='krb';
 2551: 	$amode.=$env{'form.krbver'};
 2552: 	$genpwd=$env{'form.krbarg'};
 2553:     } elsif ($env{'form.login'} eq 'int') {
 2554: 	$amode='internal';
 2555: 	$genpwd=$env{'form.intarg'};
 2556:     } elsif ($env{'form.login'} eq 'fsys') {
 2557: 	$amode='unix';
 2558: 	$genpwd=$env{'form.fsysarg'};
 2559:     } elsif ($env{'form.login'} eq 'loc') {
 2560: 	$amode='localauth';
 2561: 	$genpwd=$env{'form.locarg'};
 2562: 	$genpwd=" " if (!$genpwd);
 2563:     } elsif (($env{'form.login'} eq 'nochange') ||
 2564:              ($env{'form.login'} eq ''        )) { 
 2565:         # There is no need to tell the user we did not change what they
 2566:         # did not ask us to change.
 2567:         # If they are creating a new user but have not specified login
 2568:         # information this will be caught below.
 2569:     } else {
 2570:             $r->print($error.&mt('Invalid login mode or password').$end.$rtnlink);
 2571:             return;
 2572:     }
 2573: 
 2574:     $r->print('<h3>'.&mt('User [_1] in domain [_2]',
 2575:                         $env{'form.ccuname'}.' ('.&Apache::loncommon::plainname($env{'form.ccuname'},
 2576:                         $env{'form.ccdomain'}).')', $env{'form.ccdomain'}).'</h3>');
 2577:     my %prog_state = &Apache::lonhtmlcommon::Create_PrgWin($r,2);
 2578: 
 2579:     my (%alerts,%rulematch,%inst_results,%curr_rules);
 2580:     my @userinfo = ('firstname','middlename','lastname','generation','permanentemail','id');
 2581:     my @usertools = ('aboutme','blog','webdav','portfolio');
 2582:     my @requestcourses = ('official','unofficial','community','textbook');
 2583:     my @requestauthor = ('requestauthor');
 2584:     my ($othertitle,$usertypes,$types) = 
 2585:         &Apache::loncommon::sorted_inst_types($env{'form.ccdomain'});
 2586:     my %canmodify_status =
 2587:         &Apache::lonuserutils::can_modify_userinfo($context,$env{'form.ccdomain'},
 2588:                                                    ['inststatus']);
 2589:     if ($env{'form.makeuser'}) {
 2590: 	$r->print('<h3>'.&mt('Creating new account.').'</h3>');
 2591:         # Check for the authentication mode and password
 2592:         if (! $amode || ! $genpwd) {
 2593: 	    $r->print($error.&mt('Invalid login mode or password').$end.$rtnlink);    
 2594: 	    return;
 2595: 	}
 2596:         # Determine desired host
 2597:         my $desiredhost = $env{'form.hserver'};
 2598:         if (lc($desiredhost) eq 'default') {
 2599:             $desiredhost = undef;
 2600:         } else {
 2601:             my %home_servers = 
 2602: 		&Apache::lonnet::get_servers($env{'form.ccdomain'},'library');
 2603:             if (! exists($home_servers{$desiredhost})) {
 2604:                 $r->print($error.&mt('Invalid home server specified').$end.$rtnlink);
 2605:                 return;
 2606:             }
 2607:         }
 2608:         # Check ID format
 2609:         my %checkhash;
 2610:         my %checks = ('id' => 1);
 2611:         %{$checkhash{$env{'form.ccuname'}.':'.$env{'form.ccdomain'}}} = (
 2612:             'newuser' => $newuser, 
 2613:             'id' => $env{'form.cid'},
 2614:         );
 2615:         if ($env{'form.cid'} ne '') {
 2616:             &Apache::loncommon::user_rule_check(\%checkhash,\%checks,\%alerts,
 2617:                                           \%rulematch,\%inst_results,\%curr_rules);
 2618:             if (ref($alerts{'id'}) eq 'HASH') {
 2619:                 if (ref($alerts{'id'}{$env{'form.ccdomain'}}) eq 'HASH') {
 2620:                     my $domdesc =
 2621:                         &Apache::lonnet::domain($env{'form.ccdomain'},'description');
 2622:                     if ($alerts{'id'}{$env{'form.ccdomain'}}{$env{'form.cid'}}) {
 2623:                         my $userchkmsg;
 2624:                         if (ref($curr_rules{$env{'form.ccdomain'}}) eq 'HASH') {
 2625:                             $userchkmsg  = 
 2626:                                 &Apache::loncommon::instrule_disallow_msg('id',
 2627:                                                                     $domdesc,1).
 2628:                                 &Apache::loncommon::user_rule_formats($env{'form.ccdomain'},
 2629:                                     $domdesc,$curr_rules{$env{'form.ccdomain'}}{'id'},'id');
 2630:                         }
 2631:                         $r->print($error.&mt('Invalid ID format').$end.
 2632:                                   $userchkmsg.$rtnlink);
 2633:                         return;
 2634:                     }
 2635:                 }
 2636:             }
 2637:         }
 2638:         &Apache::lonhtmlcommon::Increment_PrgWin($r, \%prog_state);
 2639: 	# Call modifyuser
 2640: 	my $result = &Apache::lonnet::modifyuser
 2641: 	    ($env{'form.ccdomain'},$env{'form.ccuname'},$env{'form.cid'},
 2642:              $amode,$genpwd,$env{'form.cfirstname'},
 2643:              $env{'form.cmiddlename'},$env{'form.clastname'},
 2644:              $env{'form.cgeneration'},undef,$desiredhost,
 2645:              $env{'form.cpermanentemail'});
 2646: 	$r->print(&mt('Generating user').': '.$result);
 2647:         $uhome = &Apache::lonnet::homeserver($env{'form.ccuname'},
 2648:                                                $env{'form.ccdomain'});
 2649:         my (%changeHash,%newcustom,%changed,%changedinfo);
 2650:         if ($uhome ne 'no_host') {
 2651:             if ($context eq 'domain') {
 2652:                 foreach my $name ('portfolio','author') {
 2653:                     if ($env{'form.custom_'.$name.'quota'} == 1) {
 2654:                         if ($env{'form.'.$name.'quota'} eq '') {
 2655:                             $newcustom{$name.'quota'} = 0;
 2656:                         } else {
 2657:                             $newcustom{$name.'quota'} = $env{'form.'.$name.'quota'};
 2658:                             $newcustom{$name.'quota'} =~ s/[^\d\.]//g;
 2659:                         }
 2660:                         if (&quota_admin($newcustom{$name.'quota'},\%changeHash,$name)) {
 2661:                             $changed{$name.'quota'} = 1;
 2662:                         }
 2663:                     }
 2664:                 }
 2665:                 foreach my $item (@usertools) {
 2666:                     if ($env{'form.custom'.$item} == 1) {
 2667:                         $newcustom{$item} = $env{'form.tools_'.$item};
 2668:                         $changed{$item} = &tool_admin($item,$newcustom{$item},
 2669:                                                      \%changeHash,'tools');
 2670:                     }
 2671:                 }
 2672:                 foreach my $item (@requestcourses) {
 2673:                     if ($env{'form.custom'.$item} == 1) {
 2674:                         $newcustom{$item} = $env{'form.crsreq_'.$item};
 2675:                         if ($env{'form.crsreq_'.$item} eq 'autolimit') {
 2676:                             $newcustom{$item} .= '=';
 2677:                             $env{'form.crsreq_'.$item.'_limit'} =~ s/\D+//g;
 2678:                             if ($env{'form.crsreq_'.$item.'_limit'}) {
 2679:                                 $newcustom{$item} .= $env{'form.crsreq_'.$item.'_limit'};
 2680:                             }
 2681:                         }
 2682:                         $changed{$item} = &tool_admin($item,$newcustom{$item},
 2683:                                                       \%changeHash,'requestcourses');
 2684:                     }
 2685:                 }
 2686:                 if ($env{'form.customrequestauthor'} == 1) {
 2687:                     $newcustom{'requestauthor'} = $env{'form.requestauthor'};
 2688:                     $changed{'requestauthor'} = &tool_admin('requestauthor',
 2689:                                                     $newcustom{'requestauthor'},
 2690:                                                     \%changeHash,'requestauthor');
 2691:                 }
 2692:             }
 2693:             if ($canmodify_status{'inststatus'}) {
 2694:                 if (exists($env{'form.inststatus'})) {
 2695:                     my @inststatuses = &Apache::loncommon::get_env_multiple('form.inststatus');
 2696:                     if (@inststatuses > 0) {
 2697:                         $changeHash{'inststatus'} = join(',',@inststatuses);
 2698:                         $changed{'inststatus'} = $changeHash{'inststatus'};
 2699:                     }
 2700:                 }
 2701:             }
 2702:             if (keys(%changed)) {
 2703:                 foreach my $item (@userinfo) {
 2704:                     $changeHash{$item}  = $env{'form.c'.$item};
 2705:                 }
 2706:                 my $chgresult =
 2707:                      &Apache::lonnet::put('environment',\%changeHash,
 2708:                                           $env{'form.ccdomain'},$env{'form.ccuname'});
 2709:             } 
 2710:         }
 2711:         $r->print('<br />'.&mt('Home server').': '.$uhome.' '.
 2712:                   &Apache::lonnet::hostname($uhome));
 2713:     } elsif (($env{'form.login'} ne 'nochange') &&
 2714:              ($env{'form.login'} ne ''        )) {
 2715: 	# Modify user privileges
 2716:         if (! $amode || ! $genpwd) {
 2717: 	    $r->print($error.'Invalid login mode or password'.$end.$rtnlink);    
 2718: 	    return;
 2719: 	}
 2720: 	# Only allow authentication modification if the person has authority
 2721: 	if (&Apache::lonnet::allowed('mau',$env{'form.ccdomain'})) {
 2722: 	    $r->print('Modifying authentication: '.
 2723:                       &Apache::lonnet::modifyuserauth(
 2724: 		       $env{'form.ccdomain'},$env{'form.ccuname'},
 2725:                        $amode,$genpwd));
 2726:             $r->print('<br />'.&mt('Home server').': '.&Apache::lonnet::homeserver
 2727: 		  ($env{'form.ccuname'},$env{'form.ccdomain'}));
 2728: 	} else {
 2729: 	    # Okay, this is a non-fatal error.
 2730: 	    $r->print($error.&mt('You do not have the authority to modify this users authentication information.').$end);    
 2731: 	}
 2732:     }
 2733:     $r->rflush(); # Finish display of header before time consuming actions start
 2734:     &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state);
 2735:     ##
 2736:     my (@userroles,%userupdate,$cnum,$cdom,$defaultcredits,%namechanged);
 2737:     if ($context eq 'course') {
 2738:         ($cnum,$cdom) =
 2739:             &Apache::lonuserutils::get_course_identity();
 2740:         $crstype = &Apache::loncommon::course_type($cdom.'_'.$cnum);
 2741:         if ($showcredits) {
 2742:            $defaultcredits = &Apache::lonuserutils::get_defaultcredits($cdom,$cnum);
 2743:         }
 2744:     }
 2745:     if (! $env{'form.makeuser'} ) {
 2746:         # Check for need to change
 2747:         my %userenv = &Apache::lonnet::get
 2748:             ('environment',['firstname','middlename','lastname','generation',
 2749:              'id','permanentemail','portfolioquota','authorquota','inststatus',
 2750:              'tools.aboutme','tools.blog','tools.webdav','tools.portfolio',
 2751:              'requestcourses.official','requestcourses.unofficial',
 2752:              'requestcourses.community','requestcourses.textbook',
 2753:              'reqcrsotherdom.official','reqcrsotherdom.unofficial',
 2754:              'reqcrsotherdom.community','reqcrsotherdom.textbook',
 2755:              'requestauthor'],
 2756:               $env{'form.ccdomain'},$env{'form.ccuname'});
 2757:         my ($tmp) = keys(%userenv);
 2758:         if ($tmp =~ /^(con_lost|error)/i) { 
 2759:             %userenv = ();
 2760:         }
 2761:         my $no_forceid_alert;
 2762:         # Check to see if user information can be changed
 2763:         my %domconfig =
 2764:             &Apache::lonnet::get_dom('configuration',['usermodification'],
 2765:                                      $env{'form.ccdomain'});
 2766:         my @statuses = ('active','future');
 2767:         my %roles = &Apache::lonnet::get_my_roles($env{'form.ccuname'},$env{'form.ccdomain'},'userroles',\@statuses,undef,$env{'request.role.domain'});
 2768:         my ($auname,$audom);
 2769:         if ($context eq 'author') {
 2770:             $auname = $env{'user.name'};
 2771:             $audom = $env{'user.domain'};     
 2772:         }
 2773:         foreach my $item (keys(%roles)) {
 2774:             my ($rolenum,$roledom,$role) = split(/:/,$item,-1);
 2775:             if ($context eq 'course') {
 2776:                 if ($cnum ne '' && $cdom ne '') {
 2777:                     if ($rolenum eq $cnum && $roledom eq $cdom) {
 2778:                         if (!grep(/^\Q$role\E$/,@userroles)) {
 2779:                             push(@userroles,$role);
 2780:                         }
 2781:                     }
 2782:                 }
 2783:             } elsif ($context eq 'author') {
 2784:                 if ($rolenum eq $auname && $roledom eq $audom) {
 2785:                     if (!grep(/^\Q$role\E$/,@userroles)) { 
 2786:                         push(@userroles,$role);
 2787:                     }
 2788:                 }
 2789:             }
 2790:         }
 2791:         if ($env{'form.action'} eq 'singlestudent') {
 2792:             if (!grep(/^st$/,@userroles)) {
 2793:                 push(@userroles,'st');
 2794:             }
 2795:         } else {
 2796:             # Check for course or co-author roles being activated or re-enabled
 2797:             if ($context eq 'author' || $context eq 'course') {
 2798:                 foreach my $key (keys(%env)) {
 2799:                     if ($context eq 'author') {
 2800:                         if ($key=~/^form\.act_\Q$audom\E_\Q$auname\E_([^_]+)/) {
 2801:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 2802:                                 push(@userroles,$1);
 2803:                             }
 2804:                         } elsif ($key =~/^form\.ren\:\Q$audom\E\/\Q$auname\E_([^_]+)/) {
 2805:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 2806:                                 push(@userroles,$1);
 2807:                             }
 2808:                         }
 2809:                     } elsif ($context eq 'course') {
 2810:                         if ($key=~/^form\.act_\Q$cdom\E_\Q$cnum\E_([^_]+)/) {
 2811:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 2812:                                 push(@userroles,$1);
 2813:                             }
 2814:                         } elsif ($key =~/^form\.ren\:\Q$cdom\E\/\Q$cnum\E(\/?\w*)_([^_]+)/) {
 2815:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 2816:                                 push(@userroles,$1);
 2817:                             }
 2818:                         }
 2819:                     }
 2820:                 }
 2821:             }
 2822:         }
 2823:         #Check to see if we can change personal data for the user 
 2824:         my (@mod_disallowed,@longroles);
 2825:         foreach my $role (@userroles) {
 2826:             if ($role eq 'cr') {
 2827:                 push(@longroles,'Custom');
 2828:             } else {
 2829:                 push(@longroles,&Apache::lonnet::plaintext($role,$crstype)); 
 2830:             }
 2831:         }
 2832:         my %canmodify = &Apache::lonuserutils::can_modify_userinfo($context,$env{'form.ccdomain'},\@userinfo,\@userroles);
 2833:         foreach my $item (@userinfo) {
 2834:             # Strip leading and trailing whitespace
 2835:             $env{'form.c'.$item} =~ s/(\s+$|^\s+)//g;
 2836:             if (!$canmodify{$item}) {
 2837:                 if (defined($env{'form.c'.$item})) {
 2838:                     if ($env{'form.c'.$item} ne $userenv{$item}) {
 2839:                         push(@mod_disallowed,$item);
 2840:                     }
 2841:                 }
 2842:                 $env{'form.c'.$item} = $userenv{$item};
 2843:             }
 2844:         }
 2845:         # Check to see if we can change the Student/Employee ID
 2846:         my $forceid = $env{'form.forceid'};
 2847:         my $recurseid = $env{'form.recurseid'};
 2848:         my (%alerts,%rulematch,%idinst_results,%curr_rules,%got_rules);
 2849:         my %uidhash = &Apache::lonnet::idrget($env{'form.ccdomain'},
 2850:                                             $env{'form.ccuname'});
 2851:         if (($uidhash{$env{'form.ccuname'}}) && 
 2852:             ($uidhash{$env{'form.ccuname'}}!~/error\:/) && 
 2853:             (!$forceid)) {
 2854:             if ($env{'form.cid'} ne $uidhash{$env{'form.ccuname'}}) {
 2855:                 $env{'form.cid'} = $userenv{'id'};
 2856:                 $no_forceid_alert = &mt('New student/employee ID does not match existing ID for this user.')
 2857:                                    .'<br />'
 2858:                                    .&mt("Change is not permitted without checking the 'Force ID change' checkbox on the previous page.")
 2859:                                    .'<br />'."\n";
 2860:             }
 2861:         }
 2862:         if ($env{'form.cid'} ne $userenv{'id'}) {
 2863:             my $checkhash;
 2864:             my $checks = { 'id' => 1 };
 2865:             $checkhash->{$env{'form.ccuname'}.':'.$env{'form.ccdomain'}} = 
 2866:                    { 'newuser' => $newuser,
 2867:                      'id'  => $env{'form.cid'}, 
 2868:                    };
 2869:             &Apache::loncommon::user_rule_check($checkhash,$checks,
 2870:                 \%alerts,\%rulematch,\%idinst_results,\%curr_rules,\%got_rules);
 2871:             if (ref($alerts{'id'}) eq 'HASH') {
 2872:                 if (ref($alerts{'id'}{$env{'form.ccdomain'}}) eq 'HASH') {
 2873:                    $env{'form.cid'} = $userenv{'id'};
 2874:                 }
 2875:             }
 2876:         }
 2877:         my (%quotachanged,%oldquota,%newquota,%olddefquota,%newdefquota, 
 2878:             $oldinststatus,$newinststatus,%oldisdefault,%newisdefault,%oldsettings,
 2879:             %oldsettingstext,%newsettings,%newsettingstext,@disporder,
 2880:             %oldsettingstatus,%newsettingstatus);
 2881:         @disporder = ('inststatus');
 2882:         if ($env{'request.role.domain'} eq $env{'form.ccdomain'}) {
 2883:             push(@disporder,'requestcourses','requestauthor');
 2884:         } else {
 2885:             push(@disporder,'reqcrsotherdom');
 2886:         }
 2887:         push(@disporder,('quota','tools'));
 2888:         $oldinststatus = $userenv{'inststatus'};
 2889:         foreach my $name ('portfolio','author') {
 2890:             ($olddefquota{$name},$oldsettingstatus{$name}) = 
 2891:                 &Apache::loncommon::default_quota($env{'form.ccdomain'},$oldinststatus,$name);
 2892:             ($newdefquota{$name},$newsettingstatus{$name}) = ($olddefquota{$name},$oldsettingstatus{$name});
 2893:         }
 2894:         my %canshow;
 2895:         if (&Apache::lonnet::allowed('mpq',$env{'form.ccdomain'})) {
 2896:             $canshow{'quota'} = 1;
 2897:         }
 2898:         if (&Apache::lonnet::allowed('mut',$env{'form.ccdomain'})) {
 2899:             $canshow{'tools'} = 1;
 2900:         }
 2901:         if (&Apache::lonnet::allowed('ccc',$env{'form.ccdomain'})) {
 2902:             $canshow{'requestcourses'} = 1;
 2903:         } elsif (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) {
 2904:             $canshow{'reqcrsotherdom'} = 1;
 2905:         }
 2906:         if (&Apache::lonnet::allowed('mau',$env{'form.ccdomain'})) {
 2907:             $canshow{'inststatus'} = 1;
 2908:         }
 2909:         if (&Apache::lonnet::allowed('cau',$env{'form.ccdomain'})) {
 2910:             $canshow{'requestauthor'} = 1;
 2911:         }
 2912:         my (%changeHash,%changed);
 2913:         if ($oldinststatus eq '') {
 2914:             $oldsettings{'inststatus'} = $othertitle; 
 2915:         } else {
 2916:             if (ref($usertypes) eq 'HASH') {
 2917:                 $oldsettings{'inststatus'} = join(', ',map{ $usertypes->{ &unescape($_) }; } (split(/:/,$userenv{'inststatus'})));
 2918:             } else {
 2919:                 $oldsettings{'inststatus'} = join(', ',map{ &unescape($_); } (split(/:/,$userenv{'inststatus'})));
 2920:             }
 2921:         }
 2922:         $changeHash{'inststatus'} = $userenv{'inststatus'};
 2923:         if ($canmodify_status{'inststatus'}) {
 2924:             $canshow{'inststatus'} = 1;
 2925:             if (exists($env{'form.inststatus'})) {
 2926:                 my @inststatuses = &Apache::loncommon::get_env_multiple('form.inststatus');
 2927:                 if (@inststatuses > 0) {
 2928:                     $newinststatus = join(':',map { &escape($_); } @inststatuses);
 2929:                     $changeHash{'inststatus'} = $newinststatus;
 2930:                     if ($newinststatus ne $oldinststatus) {
 2931:                         $changed{'inststatus'} = $newinststatus;
 2932:                         foreach my $name ('portfolio','author') {
 2933:                             ($newdefquota{$name},$newsettingstatus{$name}) =
 2934:                                 &Apache::loncommon::default_quota($env{'form.ccdomain'},$newinststatus,$name);
 2935:                         }
 2936:                     }
 2937:                     if (ref($usertypes) eq 'HASH') {
 2938:                         $newsettings{'inststatus'} = join(', ',map{ $usertypes->{$_}; } (@inststatuses)); 
 2939:                     } else {
 2940:                         $newsettings{'inststatus'} = join(', ',@inststatuses);
 2941:                     }
 2942:                 }
 2943:             } else {
 2944:                 $newinststatus = '';
 2945:                 $changeHash{'inststatus'} = $newinststatus;
 2946:                 $newsettings{'inststatus'} = $othertitle;
 2947:                 if ($newinststatus ne $oldinststatus) {
 2948:                     $changed{'inststatus'} = $changeHash{'inststatus'};
 2949:                     foreach my $name ('portfolio','author') {
 2950:                         ($newdefquota{$name},$newsettingstatus{$name}) =
 2951:                             &Apache::loncommon::default_quota($env{'form.ccdomain'},$newinststatus,$name);
 2952:                     }
 2953:                 }
 2954:             }
 2955:         } elsif ($context ne 'selfcreate') {
 2956:             $canshow{'inststatus'} = 1;
 2957:             $newsettings{'inststatus'} = $oldsettings{'inststatus'};
 2958:         }
 2959:         foreach my $name ('portfolio','author') {
 2960:             $changeHash{$name.'quota'} = $userenv{$name.'quota'};
 2961:         }
 2962:         if ($context eq 'domain') {
 2963:             foreach my $name ('portfolio','author') {
 2964:                 if ($userenv{$name.'quota'} ne '') {
 2965:                     $oldquota{$name} = $userenv{$name.'quota'};
 2966:                     if ($env{'form.custom_'.$name.'quota'} == 1) {
 2967:                         if ($env{'form.'.$name.'quota'} eq '') {
 2968:                             $newquota{$name} = 0;
 2969:                         } else {
 2970:                             $newquota{$name} = $env{'form.'.$name.'quota'};
 2971:                             $newquota{$name} =~ s/[^\d\.]//g;
 2972:                         }
 2973:                         if ($newquota{$name} != $oldquota{$name}) {
 2974:                             if (&quota_admin($newquota{$name},\%changeHash,$name)) {
 2975:                                 $changed{$name.'quota'} = 1;
 2976:                             }
 2977:                         }
 2978:                     } else {
 2979:                         if (&quota_admin('',\%changeHash,$name)) {
 2980:                             $changed{$name.'quota'} = 1;
 2981:                             $newquota{$name} = $newdefquota{$name};
 2982:                             $newisdefault{$name} = 1;
 2983:                         }
 2984:                     }
 2985:                 } else {
 2986:                     $oldisdefault{$name} = 1;
 2987:                     $oldquota{$name} = $olddefquota{$name};
 2988:                     if ($env{'form.custom_'.$name.'quota'} == 1) {
 2989:                         if ($env{'form.'.$name.'quota'} eq '') {
 2990:                             $newquota{$name} = 0;
 2991:                         } else {
 2992:                             $newquota{$name} = $env{'form.'.$name.'quota'};
 2993:                             $newquota{$name} =~ s/[^\d\.]//g;
 2994:                         }
 2995:                         if (&quota_admin($newquota{$name},\%changeHash,$name)) {
 2996:                             $changed{$name.'quota'} = 1;
 2997:                         }
 2998:                     } else {
 2999:                         $newquota{$name} = $newdefquota{$name};
 3000:                         $newisdefault{$name} = 1;
 3001:                     }
 3002:                 }
 3003:                 if ($oldisdefault{$name}) {
 3004:                     $oldsettingstext{'quota'}{$name} = &get_defaultquota_text($oldsettingstatus{$name});
 3005:                 }  else {
 3006:                     $oldsettingstext{'quota'}{$name} = &mt('custom quota: [_1] MB',$oldquota{$name});
 3007:                 }
 3008:                 if ($newisdefault{$name}) {
 3009:                     $newsettingstext{'quota'}{$name} = &get_defaultquota_text($newsettingstatus{$name});
 3010:                 } else {
 3011:                     $newsettingstext{'quota'}{$name} = &mt('custom quota: [_1] MB',$newquota{$name});
 3012:                 }
 3013:             }
 3014:             &tool_changes('tools',\@usertools,\%oldsettings,\%oldsettingstext,\%userenv,
 3015:                           \%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3016:             if ($env{'form.ccdomain'} eq $env{'request.role.domain'}) {
 3017:                 &tool_changes('requestcourses',\@requestcourses,\%oldsettings,\%oldsettingstext,
 3018:                               \%userenv,\%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3019:                 &tool_changes('requestauthor',\@requestauthor,\%oldsettings,\%oldsettingstext,
 3020:                               \%userenv,\%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3021:             } else {
 3022:                 &tool_changes('reqcrsotherdom',\@requestcourses,\%oldsettings,\%oldsettingstext,
 3023:                               \%userenv,\%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3024:             }
 3025:         }
 3026:         foreach my $item (@userinfo) {
 3027:             if ($env{'form.c'.$item} ne $userenv{$item}) {
 3028:                 $namechanged{$item} = 1;
 3029:             }
 3030:         }
 3031:         foreach my $name ('portfolio','author') {
 3032:             $oldsettings{'quota'}{$name} = &mt('[_1] MB',$oldquota{$name});
 3033:             $newsettings{'quota'}{$name} = &mt('[_1] MB',$newquota{$name});
 3034:         }
 3035:         if ((keys(%namechanged) > 0) || (keys(%changed) > 0)) {
 3036:             my ($chgresult,$namechgresult);
 3037:             if (keys(%changed) > 0) {
 3038:                 $chgresult = 
 3039:                     &Apache::lonnet::put('environment',\%changeHash,
 3040:                                   $env{'form.ccdomain'},$env{'form.ccuname'});
 3041:                 if ($chgresult eq 'ok') {
 3042:                     if (($env{'user.name'} eq $env{'form.ccuname'}) &&
 3043:                         ($env{'user.domain'} eq $env{'form.ccdomain'})) {
 3044:                         my %newenvhash;
 3045:                         foreach my $key (keys(%changed)) {
 3046:                             if (($key eq 'official') || ($key eq 'unofficial')
 3047:                                 || ($key eq 'community') || ($key eq 'textbook')) {
 3048:                                 $newenvhash{'environment.requestcourses.'.$key} =
 3049:                                     $changeHash{'requestcourses.'.$key};
 3050:                                 if ($changeHash{'requestcourses.'.$key}) {
 3051:                                     $newenvhash{'environment.canrequest.'.$key} = 1;
 3052:                                 } else {
 3053:                                     $newenvhash{'environment.canrequest.'.$key} =
 3054:           &Apache::lonnet::usertools_access($env{'user.name'},$env{'user.domain'},
 3055:                                             $key,'reload','requestcourses');
 3056:                                 }
 3057:                             } elsif ($key eq 'requestauthor') {
 3058:                                 $newenvhash{'environment.'.$key} = $changeHash{$key};
 3059:                                 if ($changeHash{$key}) {
 3060:                                     $newenvhash{'environment.canrequest.author'} = 1;
 3061:                                 } else {
 3062:                                     $newenvhash{'environment.canrequest.author'} =
 3063:           &Apache::lonnet::usertools_access($env{'user.name'},$env{'user.domain'},
 3064:                                             $key,'reload','requestauthor');
 3065:                                 }
 3066:                             } elsif ($key ne 'quota') {
 3067:                                 $newenvhash{'environment.tools.'.$key} = 
 3068:                                     $changeHash{'tools.'.$key};
 3069:                                 if ($changeHash{'tools.'.$key} ne '') {
 3070:                                     $newenvhash{'environment.availabletools.'.$key} =
 3071:                                         $changeHash{'tools.'.$key};
 3072:                                 } else {
 3073:                                     $newenvhash{'environment.availabletools.'.$key} =
 3074:           &Apache::lonnet::usertools_access($env{'user.name'},$env{'user.domain'},
 3075:           $key,'reload','tools');
 3076:                                 }
 3077:                             }
 3078:                         }
 3079:                         if (keys(%newenvhash)) {
 3080:                             &Apache::lonnet::appenv(\%newenvhash);
 3081:                         }
 3082:                     }
 3083:                 }
 3084:             }
 3085:             if (keys(%namechanged) > 0) {
 3086:                 foreach my $field (@userinfo) {
 3087:                     $changeHash{$field}  = $env{'form.c'.$field};
 3088:                 }
 3089: # Make the change
 3090:                 $namechgresult =
 3091:                     &Apache::lonnet::modifyuser($env{'form.ccdomain'},
 3092:                         $env{'form.ccuname'},$changeHash{'id'},undef,undef,
 3093:                         $changeHash{'firstname'},$changeHash{'middlename'},
 3094:                         $changeHash{'lastname'},$changeHash{'generation'},
 3095:                         $changeHash{'id'},undef,$changeHash{'permanentemail'},undef,\@userinfo);
 3096:                 %userupdate = (
 3097:                                lastname   => $env{'form.clastname'},
 3098:                                middlename => $env{'form.cmiddlename'},
 3099:                                firstname  => $env{'form.cfirstname'},
 3100:                                generation => $env{'form.cgeneration'},
 3101:                                id         => $env{'form.cid'},
 3102:                              );
 3103:             }
 3104:             if (((keys(%namechanged) > 0) && $namechgresult eq 'ok') || 
 3105:                 ((keys(%changed) > 0) && $chgresult eq 'ok')) {
 3106:             # Tell the user we changed the name
 3107:                 &display_userinfo($r,1,\@disporder,\%canshow,\@requestcourses,
 3108:                                   \@usertools,\@requestauthor,\%userenv,\%changed,\%namechanged,
 3109:                                   \%oldsettings, \%oldsettingstext,\%newsettings,
 3110:                                   \%newsettingstext);
 3111:                 if ($env{'form.cid'} ne $userenv{'id'}) {
 3112:                     &Apache::lonnet::idput($env{'form.ccdomain'},
 3113:                          ($env{'form.ccuname'} => $env{'form.cid'}));
 3114:                     if (($recurseid) &&
 3115:                         (&Apache::lonnet::allowed('mau',$env{'form.ccdomain'}))) {
 3116:                         my $idresult = 
 3117:                             &Apache::lonuserutils::propagate_id_change(
 3118:                                 $env{'form.ccuname'},$env{'form.ccdomain'},
 3119:                                 \%userupdate);
 3120:                         $r->print('<br />'.$idresult.'<br />');
 3121:                     }
 3122:                 }
 3123:                 if (($env{'form.ccdomain'} eq $env{'user.domain'}) && 
 3124:                     ($env{'form.ccuname'} eq $env{'user.name'})) {
 3125:                     my %newenvhash;
 3126:                     foreach my $key (keys(%changeHash)) {
 3127:                         $newenvhash{'environment.'.$key} = $changeHash{$key};
 3128:                     }
 3129:                     &Apache::lonnet::appenv(\%newenvhash);
 3130:                 }
 3131:             } else { # error occurred
 3132:                 $r->print(
 3133:                     '<p class="LC_error">'
 3134:                    .&mt('Unable to successfully change environment for [_1] in domain [_2].',
 3135:                             '"'.$env{'form.ccuname'}.'"',
 3136:                             '"'.$env{'form.ccdomain'}.'"')
 3137:                    .'</p>');
 3138:             }
 3139:         } else { # End of if ($env ... ) logic
 3140:             # They did not want to change the users name, quota, tool availability,
 3141:             # or ability to request creation of courses, 
 3142:             # but we can still tell them what the name and quota and availabilities are  
 3143:             &display_userinfo($r,undef,\@disporder,\%canshow,\@requestcourses,
 3144:                               \@usertools,\@requestauthor,\%userenv,\%changed,\%namechanged,\%oldsettings,
 3145:                               \%oldsettingstext,\%newsettings,\%newsettingstext);
 3146:         }
 3147:         if (@mod_disallowed) {
 3148:             my ($rolestr,$contextname);
 3149:             if (@longroles > 0) {
 3150:                 $rolestr = join(', ',@longroles);
 3151:             } else {
 3152:                 $rolestr = &mt('No roles');
 3153:             }
 3154:             if ($context eq 'course') {
 3155:                 $contextname = 'course';
 3156:             } elsif ($context eq 'author') {
 3157:                 $contextname = 'co-author';
 3158:             }
 3159:             $r->print(&mt('The following fields were not updated: ').'<ul>');
 3160:             my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
 3161:             foreach my $field (@mod_disallowed) {
 3162:                 $r->print('<li>'.$fieldtitles{$field}.'</li>'."\n"); 
 3163:             }
 3164:             $r->print('</ul>');
 3165:             if (@mod_disallowed == 1) {
 3166:                 $r->print(&mt("You do not have the authority to change this field given the user's current set of active/future $contextname roles:"));
 3167:             } else {
 3168:                 $r->print(&mt("You do not have the authority to change these fields given the user's current set of active/future $contextname roles:"));
 3169:             }
 3170:             my $helplink = 'javascript:helpMenu('."'display'".')';
 3171:             $r->print('<span class="LC_cusr_emph">'.$rolestr.'</span><br />'
 3172:                      .&mt('Please contact your [_1]helpdesk[_2] for more information.'
 3173:                          ,'<a href="'.$helplink.'">','</a>')
 3174:                       .'<br />');
 3175:         }
 3176:         $r->print('<span class="LC_warning">'
 3177:                   .$no_forceid_alert
 3178:                   .&Apache::lonuserutils::print_namespacing_alerts($env{'form.ccdomain'},\%alerts,\%curr_rules)
 3179:                   .'</span>');
 3180:     }
 3181:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 3182:     if ($env{'form.action'} eq 'singlestudent') {
 3183:         &enroll_single_student($r,$uhome,$amode,$genpwd,$now,$newuser,$context,
 3184:                                $crstype,$showcredits,$defaultcredits);
 3185:         my $linktext = ($crstype eq 'Community' ?
 3186:             &mt('Enroll Another Member') : &mt('Enroll Another Student'));
 3187:         $r->print(
 3188:             &Apache::lonhtmlcommon::actionbox([
 3189:                 '<a href="javascript:backPage(document.userupdate)">'
 3190:                .($crstype eq 'Community' ? 
 3191:                     &mt('Enroll Another Member') : &mt('Enroll Another Student'))
 3192:                .'</a>']));
 3193:     } else {
 3194:         my @rolechanges = &update_roles($r,$context,$showcredits);
 3195:         if (keys(%namechanged) > 0) {
 3196:             if ($context eq 'course') {
 3197:                 if (@userroles > 0) {
 3198:                     if ((@rolechanges == 0) || 
 3199:                         (!(grep(/^st$/,@rolechanges)))) {
 3200:                         if (grep(/^st$/,@userroles)) {
 3201:                             my $classlistupdated =
 3202:                                 &Apache::lonuserutils::update_classlist($cdom,
 3203:                                               $cnum,$env{'form.ccdomain'},
 3204:                                        $env{'form.ccuname'},\%userupdate);
 3205:                         }
 3206:                     }
 3207:                 }
 3208:             }
 3209:         }
 3210:         my $userinfo = &Apache::loncommon::plainname($env{'form.ccuname'},
 3211:                                                      $env{'form.ccdomain'});
 3212:         if ($env{'form.popup'}) {
 3213:             $r->print('<p><a href="javascript:window.close()">'.&mt('Close window').'</a></p>');
 3214:         } else {
 3215:             $r->print('<br />'.&Apache::lonhtmlcommon::actionbox(['<a href="javascript:backPage(document.userupdate,'."'$env{'form.prevphase'}','modify'".')">'
 3216:                      .&mt('Modify this user: [_1]','<span class="LC_cusr_emph">'.$env{'form.ccuname'}.':'.$env{'form.ccdomain'}.' ('.$userinfo.')</span>').'</a>',
 3217:                      '<a href="javascript:backPage(document.userupdate)">'.&mt('Create/Modify Another User').'</a>']));
 3218:         }
 3219:     }
 3220: }
 3221: 
 3222: sub display_userinfo {
 3223:     my ($r,$changed,$order,$canshow,$requestcourses,$usertools,$requestauthor,
 3224:         $userenv,$changedhash,$namechangedhash,$oldsetting,$oldsettingtext,
 3225:         $newsetting,$newsettingtext) = @_;
 3226:     return unless (ref($order) eq 'ARRAY' &&
 3227:                    ref($canshow) eq 'HASH' && 
 3228:                    ref($requestcourses) eq 'ARRAY' && 
 3229:                    ref($requestauthor) eq 'ARRAY' &&
 3230:                    ref($usertools) eq 'ARRAY' && 
 3231:                    ref($userenv) eq 'HASH' &&
 3232:                    ref($changedhash) eq 'HASH' &&
 3233:                    ref($oldsetting) eq 'HASH' &&
 3234:                    ref($oldsettingtext) eq 'HASH' &&
 3235:                    ref($newsetting) eq 'HASH' &&
 3236:                    ref($newsettingtext) eq 'HASH');
 3237:     my %lt=&Apache::lonlocal::texthash(
 3238:          'ui'             => 'User Information',
 3239:          'uic'            => 'User Information Changed',
 3240:          'firstname'      => 'First Name',
 3241:          'middlename'     => 'Middle Name',
 3242:          'lastname'       => 'Last Name',
 3243:          'generation'     => 'Generation',
 3244:          'id'             => 'Student/Employee ID',
 3245:          'permanentemail' => 'Permanent e-mail address',
 3246:          'portfolioquota' => 'Disk space allocated to portfolio files',
 3247:          'authorquota'    => 'Disk space allocated to Authoring Space',
 3248:          'blog'           => 'Blog Availability',
 3249:          'webdav'         => 'WebDAV Availability',
 3250:          'aboutme'        => 'Personal Information Page Availability',
 3251:          'portfolio'      => 'Portfolio Availability',
 3252:          'official'       => 'Can Request Official Courses',
 3253:          'unofficial'     => 'Can Request Unofficial Courses',
 3254:          'community'      => 'Can Request Communities',
 3255:          'textbook'       => 'Can Request Textbook Courses',
 3256:          'requestauthor'  => 'Can Request Author Role',
 3257:          'inststatus'     => "Affiliation",
 3258:          'prvs'           => 'Previous Value:',
 3259:          'chto'           => 'Changed To:'
 3260:     );
 3261:     if ($changed) {
 3262:         $r->print('<h3>'.$lt{'uic'}.'</h3>'.
 3263:                 &Apache::loncommon::start_data_table().
 3264:                 &Apache::loncommon::start_data_table_header_row());
 3265:         $r->print("<th>&nbsp;</th>\n");
 3266:         $r->print('<th><b>'.$lt{'prvs'}.'</b></th>');
 3267:         $r->print('<th><span class="LC_nobreak"><b>'.$lt{'chto'}.'</b></span></th>');
 3268:         $r->print(&Apache::loncommon::end_data_table_header_row());
 3269:         my @userinfo = ('firstname','middlename','lastname','generation','permanentemail','id');
 3270: 
 3271:         foreach my $item (@userinfo) {
 3272:             my $value = $env{'form.c'.$item};
 3273:             #show changes only:
 3274:             unless ($value eq $userenv->{$item}){
 3275:                 $r->print(&Apache::loncommon::start_data_table_row());
 3276:                 $r->print("<td>$lt{$item}</td>\n");
 3277:                 $r->print("<td>".$userenv->{$item}."</td>\n");
 3278:                 $r->print("<td>$value </td>\n");
 3279:                 $r->print(&Apache::loncommon::end_data_table_row());
 3280:             }
 3281:         }
 3282:         foreach my $entry (@{$order}) {
 3283:             if ($canshow->{$entry}) {
 3284:                 if (($entry eq 'requestcourses') || ($entry eq 'reqcrsotherdom') || ($entry eq 'requestauthor')) {
 3285:                     my @items;
 3286:                     if ($entry eq 'requestauthor') {
 3287:                         @items = ($entry);
 3288:                     } else {
 3289:                         @items = @{$requestcourses};
 3290:                     }
 3291:                     foreach my $item (@items) {
 3292:                         if (($newsetting->{$item} ne $oldsetting->{$item}) || 
 3293:                             ($newsettingtext->{$item} ne $oldsettingtext->{$item})) {
 3294:                             $r->print(&Apache::loncommon::start_data_table_row()."\n");  
 3295:                             $r->print("<td>$lt{$item}</td>\n");
 3296:                             $r->print("<td>".$oldsetting->{$item});
 3297:                             if ($oldsettingtext->{$item}) {
 3298:                                 if ($oldsetting->{$item}) {
 3299:                                     $r->print(' -- ');
 3300:                                 }
 3301:                                 $r->print($oldsettingtext->{$item});
 3302:                             }
 3303:                             $r->print("</td>\n");
 3304:                             $r->print("<td>".$newsetting->{$item});
 3305:                             if ($newsettingtext->{$item}) {
 3306:                                 if ($newsetting->{$item}) {
 3307:                                     $r->print(' -- ');
 3308:                                 }
 3309:                                 $r->print($newsettingtext->{$item});
 3310:                             }
 3311:                             $r->print("</td>\n");
 3312:                             $r->print(&Apache::loncommon::end_data_table_row()."\n");
 3313:                         }
 3314:                     }
 3315:                 } elsif ($entry eq 'tools') {
 3316:                     foreach my $item (@{$usertools}) {
 3317:                         if ($newsetting->{$item} ne $oldsetting->{$item}) {
 3318:                             $r->print(&Apache::loncommon::start_data_table_row()."\n");
 3319:                             $r->print("<td>$lt{$item}</td>\n");
 3320:                             $r->print("<td>".$oldsetting->{$item}.' '.$oldsettingtext->{$item}."</td>\n");
 3321:                             $r->print("<td>".$newsetting->{$item}.' '.$newsettingtext->{$item}."</td>\n");
 3322:                             $r->print(&Apache::loncommon::end_data_table_row()."\n");
 3323:                         }
 3324:                     }
 3325:                 } elsif ($entry eq 'quota') {
 3326:                     if ((ref($oldsetting->{$entry}) eq 'HASH') && (ref($oldsettingtext->{$entry}) eq 'HASH') &&
 3327:                         (ref($newsetting->{$entry}) eq 'HASH') && (ref($newsettingtext->{$entry}) eq 'HASH')) {
 3328:                         foreach my $name ('portfolio','author') {
 3329:                             if ($newsetting->{$entry}->{$name} ne $oldsetting->{$entry}->{$name}) {
 3330:                                 $r->print(&Apache::loncommon::start_data_table_row()."\n");
 3331:                                 $r->print("<td>$lt{$name.$entry}</td>\n");
 3332:                                 $r->print("<td>".$oldsettingtext->{$entry}->{$name}."</td>\n");
 3333:                                 $r->print("<td>".$newsettingtext->{$entry}->{$name}."</td>\n");
 3334:                                 $r->print(&Apache::loncommon::end_data_table_row()."\n");
 3335:                             }
 3336:                         }
 3337:                     }
 3338:                 } else {
 3339:                     if ($newsetting->{$entry} ne $oldsetting->{$entry}) {
 3340:                         $r->print(&Apache::loncommon::start_data_table_row()."\n");
 3341:                         $r->print("<td>$lt{$entry}</td>\n");
 3342:                         $r->print("<td>".$oldsetting->{$entry}.' '.$oldsettingtext->{$entry}."</td>\n");
 3343:                         $r->print("<td>".$newsetting->{$entry}.' '.$newsettingtext->{$entry}."</td>\n");
 3344:                         $r->print(&Apache::loncommon::end_data_table_row()."\n");
 3345:                     }
 3346:                 }
 3347:             }
 3348:         }
 3349:         $r->print(&Apache::loncommon::end_data_table().'<br />');
 3350:     } else {
 3351:         $r->print('<h3>'.$lt{'ui'}.'</h3>'.
 3352:                   '<p>'.&mt('No changes made to user information').'</p>');
 3353:     }
 3354:     return;
 3355: }
 3356: 
 3357: sub tool_changes {
 3358:     my ($context,$usertools,$oldaccess,$oldaccesstext,$userenv,$changeHash,
 3359:         $changed,$newaccess,$newaccesstext) = @_;
 3360:     if (!((ref($usertools) eq 'ARRAY') && (ref($oldaccess) eq 'HASH') &&
 3361:           (ref($oldaccesstext) eq 'HASH') && (ref($userenv) eq 'HASH') &&
 3362:           (ref($changeHash) eq 'HASH') && (ref($changed) eq 'HASH') &&
 3363:           (ref($newaccess) eq 'HASH') && (ref($newaccesstext) eq 'HASH'))) {
 3364:         return;
 3365:     }
 3366:     my %reqdisplay = &requestchange_display();
 3367:     if ($context eq 'reqcrsotherdom') {
 3368:         my @options = ('approval','validate','autolimit');
 3369:         my $optregex = join('|',@options);
 3370:         my $cdom = $env{'request.role.domain'};
 3371:         foreach my $tool (@{$usertools}) {
 3372:             $oldaccesstext->{$tool} = &mt("availability set to 'off'");
 3373:             $newaccesstext->{$tool} = $oldaccesstext->{$tool};
 3374:             $changeHash->{$context.'.'.$tool} = $userenv->{$context.'.'.$tool};
 3375:             my ($newop,$limit);
 3376:             if ($env{'form.'.$context.'_'.$tool}) {
 3377:                 $newop = $env{'form.'.$context.'_'.$tool};
 3378:                 if ($newop eq 'autolimit') {
 3379:                     $limit = $env{'form.'.$context.'_'.$tool.'_limit'};
 3380:                     $limit =~ s/\D+//g;
 3381:                     $newop .= '='.$limit;
 3382:                 }
 3383:             }
 3384:             if ($userenv->{$context.'.'.$tool} eq '') {
 3385:                 if ($newop) {
 3386:                     $changed->{$tool}=&tool_admin($tool,$cdom.':'.$newop,
 3387:                                                   $changeHash,$context);
 3388:                     if ($changed->{$tool}) {
 3389:                         if ($newop =~ /^autolimit/) {
 3390:                             if ($limit) {
 3391:                                 $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3392:                             } else {
 3393:                                 $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3394:                             }
 3395:                         } else {
 3396:                             $newaccesstext->{$tool} = $reqdisplay{$newop};
 3397:                         }
 3398:                     } else {
 3399:                         $newaccesstext->{$tool} = $oldaccesstext->{$tool};
 3400:                     }
 3401:                 }
 3402:             } else {
 3403:                 my @curr = split(',',$userenv->{$context.'.'.$tool});
 3404:                 my @new;
 3405:                 my $changedoms;
 3406:                 foreach my $req (@curr) {
 3407:                     if ($req =~ /^\Q$cdom\E\:($optregex\=?\d*)$/) {
 3408:                         my $oldop = $1;
 3409:                         if ($oldop =~ /^autolimit=(\d*)/) {
 3410:                             my $limit = $1;
 3411:                             if ($limit) {
 3412:                                 $oldaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3413:                             } else {
 3414:                                 $oldaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3415:                             }
 3416:                         } else {
 3417:                             $oldaccesstext->{$tool} = $reqdisplay{$oldop};
 3418:                         }
 3419:                         if ($oldop ne $newop) {
 3420:                             $changedoms = 1;
 3421:                             foreach my $item (@curr) {
 3422:                                 my ($reqdom,$option) = split(':',$item);
 3423:                                 unless ($reqdom eq $cdom) {
 3424:                                     push(@new,$item);
 3425:                                 }
 3426:                             }
 3427:                             if ($newop) {
 3428:                                 push(@new,$cdom.':'.$newop);
 3429:                             }
 3430:                             @new = sort(@new);
 3431:                         }
 3432:                         last;
 3433:                     }
 3434:                 }
 3435:                 if ((!$changedoms) && ($newop)) {
 3436:                     $changedoms = 1;
 3437:                     @new = sort(@curr,$cdom.':'.$newop);
 3438:                 }
 3439:                 if ($changedoms) {
 3440:                     my $newdomstr;
 3441:                     if (@new) {
 3442:                         $newdomstr = join(',',@new);
 3443:                     }
 3444:                     $changed->{$tool}=&tool_admin($tool,$newdomstr,$changeHash,
 3445:                                                   $context);
 3446:                     if ($changed->{$tool}) {
 3447:                         if ($env{'form.'.$context.'_'.$tool}) {
 3448:                             if ($env{'form.'.$context.'_'.$tool} eq 'autolimit') {
 3449:                                 my $limit = $env{'form.'.$context.'_'.$tool.'_limit'};
 3450:                                 $limit =~ s/\D+//g;
 3451:                                 if ($limit) {
 3452:                                     $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3453:                                 } else {
 3454:                                     $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3455:                                 }
 3456:                             } else {
 3457:                                 $newaccesstext->{$tool} = $reqdisplay{$env{'form.'.$context.'_'.$tool}};
 3458:                             }
 3459:                         } else {
 3460:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3461:                         }
 3462:                     }
 3463:                 }
 3464:             }
 3465:         }
 3466:         return;
 3467:     }
 3468:     foreach my $tool (@{$usertools}) {
 3469:         my ($newval,$limit,$envkey);
 3470:         $envkey = $context.'.'.$tool;
 3471:         if ($context eq 'requestcourses') {
 3472:             $newval = $env{'form.crsreq_'.$tool};
 3473:             if ($newval eq 'autolimit') {
 3474:                 $limit = $env{'form.crsreq_'.$tool.'_limit'};
 3475:                 $limit =~ s/\D+//g;
 3476:                 $newval .= '='.$limit;
 3477:             }
 3478:         } elsif ($context eq 'requestauthor') {
 3479:             $newval = $env{'form.'.$context};
 3480:             $envkey = $context;
 3481:         } else {
 3482:             $newval = $env{'form.'.$context.'_'.$tool};
 3483:         }
 3484:         if ($userenv->{$envkey} ne '') {
 3485:             $oldaccess->{$tool} = &mt('custom');
 3486:             if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 3487:                 if ($userenv->{$envkey} =~ /^autolimit=(\d*)$/) {
 3488:                     my $currlimit = $1;
 3489:                     if ($currlimit eq '') {
 3490:                         $oldaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3491:                     } else {
 3492:                         $oldaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$currlimit);
 3493:                     }
 3494:                 } elsif ($userenv->{$envkey}) {
 3495:                     $oldaccesstext->{$tool} = $reqdisplay{$userenv->{$envkey}};
 3496:                 } else {
 3497:                     $oldaccesstext->{$tool} = &mt("availability set to 'off'");
 3498:                 }
 3499:             } else {
 3500:                 if ($userenv->{$envkey}) {
 3501:                     $oldaccesstext->{$tool} = &mt("availability set to 'on'");
 3502:                 } else {
 3503:                     $oldaccesstext->{$tool} = &mt("availability set to 'off'");
 3504:                 }
 3505:             }
 3506:             $changeHash->{$envkey} = $userenv->{$envkey};
 3507:             if ($env{'form.custom'.$tool} == 1) {
 3508:                 if ($newval ne $userenv->{$envkey}) {
 3509:                     $changed->{$tool} = &tool_admin($tool,$newval,$changeHash,
 3510:                                                     $context);
 3511:                     if ($changed->{$tool}) {
 3512:                         $newaccess->{$tool} = &mt('custom');
 3513:                         if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 3514:                             if ($newval =~ /^autolimit/) {
 3515:                                 if ($limit) {
 3516:                                     $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3517:                                 } else {
 3518:                                     $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3519:                                 }
 3520:                             } elsif ($newval) {
 3521:                                 $newaccesstext->{$tool} = $reqdisplay{$newval};
 3522:                             } else {
 3523:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3524:                             }
 3525:                         } else {
 3526:                             if ($newval) {
 3527:                                 $newaccesstext->{$tool} = &mt("availability set to 'on'");
 3528:                             } else {
 3529:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3530:                             }
 3531:                         }
 3532:                     } else {
 3533:                         $newaccess->{$tool} = $oldaccess->{$tool};
 3534:                         if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 3535:                             if ($newval =~ /^autolimit/) {
 3536:                                 if ($limit) {
 3537:                                     $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3538:                                 } else {
 3539:                                     $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3540:                                 }
 3541:                             } elsif ($newval) {
 3542:                                 $newaccesstext->{$tool} = $reqdisplay{$newval};
 3543:                             } else {
 3544:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3545:                             }
 3546:                         } else {
 3547:                             if ($userenv->{$context.'.'.$tool}) {
 3548:                                 $newaccesstext->{$tool} = &mt("availability set to 'on'");
 3549:                             } else {
 3550:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3551:                             }
 3552:                         }
 3553:                     }
 3554:                 } else {
 3555:                     $newaccess->{$tool} = $oldaccess->{$tool};
 3556:                     $newaccesstext->{$tool} = $oldaccesstext->{$tool};
 3557:                 }
 3558:             } else {
 3559:                 $changed->{$tool} = &tool_admin($tool,'',$changeHash,$context);
 3560:                 if ($changed->{$tool}) {
 3561:                     $newaccess->{$tool} = &mt('default');
 3562:                 } else {
 3563:                     $newaccess->{$tool} = $oldaccess->{$tool};
 3564:                     if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 3565:                         if ($newval =~ /^autolimit/) {
 3566:                             if ($limit) {
 3567:                                 $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3568:                             } else {
 3569:                                 $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3570:                             }
 3571:                         } elsif ($newval) {
 3572:                             $newaccesstext->{$tool} = $reqdisplay{$newval};
 3573:                         } else {
 3574:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3575:                         }
 3576:                     } else {
 3577:                         if ($userenv->{$context.'.'.$tool}) {
 3578:                             $newaccesstext->{$tool} = &mt("availability set to 'on'");
 3579:                         } else {
 3580:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3581:                         }
 3582:                     }
 3583:                 }
 3584:             }
 3585:         } else {
 3586:             $oldaccess->{$tool} = &mt('default');
 3587:             if ($env{'form.custom'.$tool} == 1) {
 3588:                 $changed->{$tool} = &tool_admin($tool,$newval,$changeHash,
 3589:                                                 $context);
 3590:                 if ($changed->{$tool}) {
 3591:                     $newaccess->{$tool} = &mt('custom');
 3592:                     if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 3593:                         if ($newval =~ /^autolimit/) {
 3594:                             if ($limit) {
 3595:                                 $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3596:                             } else {
 3597:                                 $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3598:                             }
 3599:                         } elsif ($newval) {
 3600:                             $newaccesstext->{$tool} = $reqdisplay{$newval};
 3601:                         } else {
 3602:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3603:                         }
 3604:                     } else {
 3605:                         if ($newval) {
 3606:                             $newaccesstext->{$tool} = &mt("availability set to 'on'");
 3607:                         } else {
 3608:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3609:                         }
 3610:                     }
 3611:                 } else {
 3612:                     $newaccess->{$tool} = $oldaccess->{$tool};
 3613:                 }
 3614:             } else {
 3615:                 $newaccess->{$tool} = $oldaccess->{$tool};
 3616:             }
 3617:         }
 3618:     }
 3619:     return;
 3620: }
 3621: 
 3622: sub update_roles {
 3623:     my ($r,$context,$showcredits) = @_;
 3624:     my $now=time;
 3625:     my @rolechanges;
 3626:     my %disallowed;
 3627:     $r->print('<h3>'.&mt('Modifying Roles').'</h3>');
 3628:     foreach my $key (keys (%env)) {
 3629: 	next if (! $env{$key});
 3630:         next if ($key eq 'form.action');
 3631: 	# Revoke roles
 3632: 	if ($key=~/^form\.rev/) {
 3633: 	    if ($key=~/^form\.rev\:([^\_]+)\_([^\_\.]+)$/) {
 3634: # Revoke standard role
 3635: 		my ($scope,$role) = ($1,$2);
 3636: 		my $result =
 3637: 		    &Apache::lonnet::revokerole($env{'form.ccdomain'},
 3638: 						$env{'form.ccuname'},
 3639: 						$scope,$role,'','',$context);
 3640:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
 3641:                             &mt('Revoking [_1] in [_2]',
 3642:                                 &Apache::lonnet::plaintext($role),
 3643:                                 &Apache::loncommon::show_role_extent($scope,$context,$role)),
 3644:                                 $result ne "ok").'<br />');
 3645:                 if ($result ne "ok") {
 3646:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 3647:                 }
 3648: 		if ($role eq 'st') {
 3649: 		    my $result = 
 3650:                         &Apache::lonuserutils::classlist_drop($scope,
 3651:                             $env{'form.ccuname'},$env{'form.ccdomain'},
 3652: 			    $now);
 3653:                     $r->print(&Apache::lonhtmlcommon::confirm_success($result));
 3654: 		}
 3655:                 if (!grep(/^\Q$role\E$/,@rolechanges)) {
 3656:                     push(@rolechanges,$role);
 3657:                 }
 3658: 	    }
 3659: 	    if ($key=~m{^form\.rev\:([^_]+)_cr\.cr/($match_domain)/($match_username)/(\w+)$}s) {
 3660: # Revoke custom role
 3661:                 my $result = &Apache::lonnet::revokecustomrole(
 3662:                     $env{'form.ccdomain'},$env{'form.ccuname'},$1,$2,$3,$4,'','',$context);
 3663:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
 3664:                             &mt('Revoking custom role [_1] by [_2] in [_3]',
 3665:                                 $4,$3.':'.$2,&Apache::loncommon::show_role_extent($1,$context,'cr')),
 3666:                             $result ne 'ok').'<br />');
 3667:                 if ($result ne "ok") {
 3668:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 3669:                 }
 3670:                 if (!grep(/^cr$/,@rolechanges)) {
 3671:                     push(@rolechanges,'cr');
 3672:                 }
 3673: 	    }
 3674: 	} elsif ($key=~/^form\.del/) {
 3675: 	    if ($key=~/^form\.del\:([^\_]+)\_([^\_\.]+)$/) {
 3676: # Delete standard role
 3677: 		my ($scope,$role) = ($1,$2);
 3678: 		my $result =
 3679: 		    &Apache::lonnet::assignrole($env{'form.ccdomain'},
 3680: 						$env{'form.ccuname'},
 3681: 						$scope,$role,$now,0,1,'',
 3682:                                                 $context);
 3683:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
 3684:                             &mt('Deleting [_1] in [_2]',
 3685:                                 &Apache::lonnet::plaintext($role),
 3686:                                 &Apache::loncommon::show_role_extent($scope,$context,$role)),
 3687:                             $result ne 'ok').'<br />');
 3688:                 if ($result ne "ok") {
 3689:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 3690:                 }
 3691: 
 3692: 		if ($role eq 'st') {
 3693: 		    my $result = 
 3694:                         &Apache::lonuserutils::classlist_drop($scope,
 3695:                             $env{'form.ccuname'},$env{'form.ccdomain'},
 3696: 			    $now);
 3697: 		    $r->print(&Apache::lonhtmlcommon::confirm_success($result));
 3698: 		}
 3699:                 if (!grep(/^\Q$role\E$/,@rolechanges)) {
 3700:                     push(@rolechanges,$role);
 3701:                 }
 3702:             }
 3703: 	    if ($key=~m{^form\.del\:([^_]+)_cr\.cr/($match_domain)/($match_username)/(\w+)$}) {
 3704:                 my ($url,$rdom,$rnam,$rolename) = ($1,$2,$3,$4);
 3705: # Delete custom role
 3706:                 my $result =
 3707:                     &Apache::lonnet::assigncustomrole($env{'form.ccdomain'},
 3708:                         $env{'form.ccuname'},$url,$rdom,$rnam,$rolename,$now,
 3709:                         0,1,$context);
 3710:                 $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('Deleting custom role [_1] by [_2] in [_3]',
 3711:                       $rolename,$rnam.':'.$rdom,&Apache::loncommon::show_role_extent($1,$context,'cr')),
 3712:                       $result ne "ok").'<br />');
 3713:                 if ($result ne "ok") {
 3714:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 3715:                 }
 3716: 
 3717:                 if (!grep(/^cr$/,@rolechanges)) {
 3718:                     push(@rolechanges,'cr');
 3719:                 }
 3720:             }
 3721: 	} elsif ($key=~/^form\.ren/) {
 3722:             my $udom = $env{'form.ccdomain'};
 3723:             my $uname = $env{'form.ccuname'};
 3724: # Re-enable standard role
 3725: 	    if ($key=~/^form\.ren\:([^\_]+)\_([^\_\.]+)$/) {
 3726:                 my $url = $1;
 3727:                 my $role = $2;
 3728:                 my $logmsg;
 3729:                 my $output;
 3730:                 if ($role eq 'st') {
 3731:                     if ($url =~ m-^/($match_domain)/($match_courseid)/?(\w*)$-) {
 3732:                         my ($cdom,$cnum,$csec) = ($1,$2,$3);
 3733:                         my $credits;
 3734:                         if ($showcredits) {
 3735:                             my $defaultcredits = 
 3736:                                 &Apache::lonuserutils::get_defaultcredits($cdom,$cnum);
 3737:                             $credits = &get_user_credits($defaultcredits,$cdom,$cnum);
 3738:                         }
 3739:                         my $result = &Apache::loncommon::commit_studentrole(\$logmsg,$udom,$uname,$url,$role,$now,0,$cdom,$cnum,$csec,$context,$credits);
 3740:                         if (($result =~ /^error/) || ($result eq 'not_in_class') || ($result eq 'unknown_course') || ($result eq 'refused')) {
 3741:                             if ($result eq 'refused' && $logmsg) {
 3742:                                 $output = $logmsg;
 3743:                             } else { 
 3744:                                 $output = &mt('Error: [_1]',$result)."\n";
 3745:                             }
 3746:                         } else {
 3747:                             $output = &Apache::lonhtmlcommon::confirm_success(&mt('Assigning [_1] in [_2] starting [_3]',
 3748:                                         &Apache::lonnet::plaintext($role),
 3749:                                         &Apache::loncommon::show_role_extent($url,$context,'st'),
 3750:                                         &Apache::lonlocal::locallocaltime($now))).'<br />'.$logmsg.'<br />';
 3751:                         }
 3752:                     }
 3753:                 } else {
 3754: 		    my $result=&Apache::lonnet::assignrole($env{'form.ccdomain'},
 3755:                                $env{'form.ccuname'},$url,$role,0,$now,'','',
 3756:                                $context);
 3757:                         $output = &Apache::lonhtmlcommon::confirm_success(&mt('Re-enabling [_1] in [_2]',
 3758:                                         &Apache::lonnet::plaintext($role),
 3759:                                         &Apache::loncommon::show_role_extent($url,$context,$role)),$result ne "ok").'<br />';
 3760:                     if ($result ne "ok") {
 3761:                         $output .= &mt('Error: [_1]',$result).'<br />';
 3762:                     }
 3763:                 }
 3764:                 $r->print($output);
 3765:                 if (!grep(/^\Q$role\E$/,@rolechanges)) {
 3766:                     push(@rolechanges,$role);
 3767:                 }
 3768: 	    }
 3769: # Re-enable custom role
 3770: 	    if ($key=~m{^form\.ren\:([^_]+)_cr\.cr/($match_domain)/($match_username)/(\w+)$}) {
 3771:                 my ($url,$rdom,$rnam,$rolename) = ($1,$2,$3,$4);
 3772:                 my $result = &Apache::lonnet::assigncustomrole(
 3773:                                $env{'form.ccdomain'}, $env{'form.ccuname'},
 3774:                                $url,$rdom,$rnam,$rolename,0,$now,undef,$context);
 3775:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
 3776:                     &mt('Re-enabling custom role [_1] by [_2] in [_3]',
 3777:                         $rolename,$rnam.':'.$rdom,&Apache::loncommon::show_role_extent($1,$context,'cr')),
 3778:                     $result ne "ok").'<br />');
 3779:                 if ($result ne "ok") {
 3780:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 3781:                 }
 3782:                 if (!grep(/^cr$/,@rolechanges)) {
 3783:                     push(@rolechanges,'cr');
 3784:                 }
 3785:             }
 3786: 	} elsif ($key=~/^form\.act/) {
 3787:             my $udom = $env{'form.ccdomain'};
 3788:             my $uname = $env{'form.ccuname'};
 3789: 	    if ($key=~/^form\.act\_($match_domain)\_($match_courseid)\_cr_cr_($match_domain)_($match_username)_([^\_]+)$/) {
 3790:                 # Activate a custom role
 3791: 		my ($one,$two,$three,$four,$five)=($1,$2,$3,$4,$5);
 3792: 		my $url='/'.$one.'/'.$two;
 3793: 		my $full=$one.'_'.$two.'_cr_cr_'.$three.'_'.$four.'_'.$five;
 3794: 
 3795:                 my $start = ( $env{'form.start_'.$full} ?
 3796:                               $env{'form.start_'.$full} :
 3797:                               $now );
 3798:                 my $end   = ( $env{'form.end_'.$full} ?
 3799:                               $env{'form.end_'.$full} :
 3800:                               0 );
 3801:                                                                                      
 3802:                 # split multiple sections
 3803:                 my %sections = ();
 3804:                 my $num_sections = &build_roles($env{'form.sec_'.$full},\%sections,$5);
 3805:                 if ($num_sections == 0) {
 3806:                     $r->print(&Apache::loncommon::commit_customrole($udom,$uname,$url,$three,$four,$five,$start,$end,$context));
 3807:                 } else {
 3808: 		    my %curr_groups =
 3809: 			&Apache::longroup::coursegroups($one,$two);
 3810:                     foreach my $sec (sort {$a cmp $b} keys %sections) {
 3811:                         if (($sec eq 'none') || ($sec eq 'all') || 
 3812:                             exists($curr_groups{$sec})) {
 3813:                             $disallowed{$sec} = $url;
 3814:                             next;
 3815:                         }
 3816:                         my $securl = $url.'/'.$sec;
 3817: 		        $r->print(&Apache::loncommon::commit_customrole($udom,$uname,$securl,$three,$four,$five,$start,$end,$context));
 3818:                     }
 3819:                 }
 3820:                 if (!grep(/^cr$/,@rolechanges)) {
 3821:                     push(@rolechanges,'cr');
 3822:                 }
 3823: 	    } elsif ($key=~/^form\.act\_($match_domain)\_($match_name)\_([^\_]+)$/) {
 3824: 		# Activate roles for sections with 3 id numbers
 3825: 		# set start, end times, and the url for the class
 3826: 		my ($one,$two,$three)=($1,$2,$3);
 3827: 		my $start = ( $env{'form.start_'.$one.'_'.$two.'_'.$three} ? 
 3828: 			      $env{'form.start_'.$one.'_'.$two.'_'.$three} : 
 3829: 			      $now );
 3830: 		my $end   = ( $env{'form.end_'.$one.'_'.$two.'_'.$three} ? 
 3831: 			      $env{'form.end_'.$one.'_'.$two.'_'.$three} :
 3832: 			      0 );
 3833: 		my $url='/'.$one.'/'.$two;
 3834:                 my $type = 'three';
 3835:                 # split multiple sections
 3836:                 my %sections = ();
 3837:                 my $num_sections = &build_roles($env{'form.sec_'.$one.'_'.$two.'_'.$three},\%sections,$three);
 3838:                 my $credits;
 3839:                 if ($three eq 'st') {
 3840:                     if ($showcredits) { 
 3841:                         my $defaultcredits = 
 3842:                             &Apache::lonuserutils::get_defaultcredits($one,$two);
 3843:                         $credits = $env{'form.credits_'.$one.'_'.$two.'_'.$three};
 3844:                         $credits =~ s/[^\d\.]//g;
 3845:                         if ($credits eq $defaultcredits) {
 3846:                             undef($credits);
 3847:                         }
 3848:                     }
 3849:                 }
 3850:                 if ($num_sections == 0) {
 3851:                     $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$three,$start,$end,$one,$two,'',$context,$credits));
 3852:                 } else {
 3853:                     my %curr_groups = 
 3854: 			&Apache::longroup::coursegroups($one,$two);
 3855:                     my $emptysec = 0;
 3856:                     foreach my $sec (sort {$a cmp $b} keys %sections) {
 3857:                         $sec =~ s/\W//g;
 3858:                         if ($sec ne '') {
 3859:                             if (($sec eq 'none') || ($sec eq 'all') || 
 3860:                                 exists($curr_groups{$sec})) {
 3861:                                 $disallowed{$sec} = $url;
 3862:                                 next;
 3863:                             }
 3864:                             my $securl = $url.'/'.$sec;
 3865:                             $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$securl,$three,$start,$end,$one,$two,$sec,$context,$credits));
 3866:                         } else {
 3867:                             $emptysec = 1;
 3868:                         }
 3869:                     }
 3870:                     if ($emptysec) {
 3871:                         $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$three,$start,$end,$one,$two,'',$context,$credits));
 3872:                     }
 3873:                 }
 3874:                 if (!grep(/^\Q$three\E$/,@rolechanges)) {
 3875:                     push(@rolechanges,$three);
 3876:                 }
 3877: 	    } elsif ($key=~/^form\.act\_([^\_]+)\_([^\_]+)$/) {
 3878: 		# Activate roles for sections with two id numbers
 3879: 		# set start, end times, and the url for the class
 3880: 		my $start = ( $env{'form.start_'.$1.'_'.$2} ? 
 3881: 			      $env{'form.start_'.$1.'_'.$2} : 
 3882: 			      $now );
 3883: 		my $end   = ( $env{'form.end_'.$1.'_'.$2} ? 
 3884: 			      $env{'form.end_'.$1.'_'.$2} :
 3885: 			      0 );
 3886:                 my $one = $1;
 3887:                 my $two = $2;
 3888: 		my $url='/'.$one.'/';
 3889:                 # split multiple sections
 3890:                 my %sections = ();
 3891:                 my $num_sections = &build_roles($env{'form.sec_'.$one.'_'.$two},\%sections,$two);
 3892:                 if ($num_sections == 0) {
 3893:                     $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$two,$start,$end,$one,undef,'',$context));
 3894:                 } else {
 3895:                     my $emptysec = 0;
 3896:                     foreach my $sec (sort {$a cmp $b} keys %sections) {
 3897:                         if ($sec ne '') {
 3898:                             my $securl = $url.'/'.$sec;
 3899:                             $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$securl,$two,$start,$end,$one,undef,$sec,$context));
 3900:                         } else {
 3901:                             $emptysec = 1;
 3902:                         }
 3903:                     }
 3904:                     if ($emptysec) {
 3905:                         $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$two,$start,$end,$one,undef,'',$context));
 3906:                     }
 3907:                 }
 3908:                 if (!grep(/^\Q$two\E$/,@rolechanges)) {
 3909:                     push(@rolechanges,$two);
 3910:                 }
 3911: 	    } else {
 3912: 		$r->print('<p><span class="LC_error">'.&mt('ERROR').': '.&mt('Unknown command').' <tt>'.$key.'</tt></span></p><br />');
 3913:             }
 3914:             foreach my $key (sort(keys(%disallowed))) {
 3915:                 $r->print('<p class="LC_warning">');
 3916:                 if (($key eq 'none') || ($key eq 'all')) {  
 3917:                     $r->print(&mt('[_1] may not be used as the name for a section, as it is a reserved word.','<tt>'.$key.'</tt>'));
 3918:                 } else {
 3919:                     $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>'));
 3920:                 }
 3921:                 $r->print('</p><p>'
 3922:                          .&mt('Please [_1]go back[_2] and choose a different section name.'
 3923:                              ,'<a href="javascript:history.go(-1)'
 3924:                              ,'</a>')
 3925:                          .'</p><br />'
 3926:                 );
 3927:             }
 3928: 	}
 3929:     } # End of foreach (keys(%env))
 3930: # Flush the course logs so reverse user roles immediately updated
 3931:     $r->register_cleanup(\&Apache::lonnet::flushcourselogs);
 3932:     if (@rolechanges == 0) {
 3933:         $r->print('<p>'.&mt('No roles to modify').'</p>');
 3934:     }
 3935:     return @rolechanges;
 3936: }
 3937: 
 3938: sub get_user_credits {
 3939:     my ($uname,$udom,$defaultcredits,$cdom,$cnum) = @_;
 3940:     if ($cdom eq '' || $cnum eq '') {
 3941:         return unless ($env{'request.course.id'});
 3942:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3943:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3944:     }
 3945:     my $credits;
 3946:     my %currhash =
 3947:         &Apache::lonnet::get('classlist',[$uname.':'.$udom],$cdom,$cnum);
 3948:     if (keys(%currhash) > 0) {
 3949:         my @items = split(/:/,$currhash{$uname.':'.$udom});
 3950:         my $crdidx = &Apache::loncoursedata::CL_CREDITS() - 3;
 3951:         $credits = $items[$crdidx];
 3952:         $credits =~ s/[^\d\.]//g;
 3953:     }
 3954:     if ($credits eq $defaultcredits) {
 3955:         undef($credits);
 3956:     }
 3957:     return $credits;
 3958: }
 3959: 
 3960: sub enroll_single_student {
 3961:     my ($r,$uhome,$amode,$genpwd,$now,$newuser,$context,$crstype,
 3962:         $showcredits,$defaultcredits) = @_;
 3963:     $r->print('<h3>');
 3964:     if ($crstype eq 'Community') {
 3965:         $r->print(&mt('Enrolling Member'));
 3966:     } else {
 3967:         $r->print(&mt('Enrolling Student'));
 3968:     }
 3969:     $r->print('</h3>');
 3970: 
 3971:     # Remove non alphanumeric values from section
 3972:     $env{'form.sections'}=~s/\W//g;
 3973: 
 3974:     my $credits;
 3975:     if (($showcredits) && ($env{'form.credits'} ne '')) {
 3976:         $credits = $env{'form.credits'};
 3977:         $credits =~ s/[^\d\.]//g;
 3978:         if ($credits ne '') {
 3979:             if ($credits eq $defaultcredits) {
 3980:                 undef($credits);
 3981:             }
 3982:         }
 3983:     }
 3984: 
 3985:     # Clean out any old student roles the user has in this class.
 3986:     &Apache::lonuserutils::modifystudent($env{'form.ccdomain'},
 3987:          $env{'form.ccuname'},$env{'request.course.id'},undef,$uhome);
 3988:     my ($startdate,$enddate) = &Apache::lonuserutils::get_dates_from_form();
 3989:     my $enroll_result =
 3990:         &Apache::lonnet::modify_student_enrollment($env{'form.ccdomain'},
 3991:             $env{'form.ccuname'},$env{'form.cid'},$env{'form.cfirstname'},
 3992:             $env{'form.cmiddlename'},$env{'form.clastname'},
 3993:             $env{'form.generation'},$env{'form.sections'},$enddate,
 3994:             $startdate,'manual',undef,$env{'request.course.id'},'',$context,
 3995:             $credits);
 3996:     if ($enroll_result =~ /^ok/) {
 3997:         $r->print(&mt('[_1] enrolled','<b>'.$env{'form.ccuname'}.':'.$env{'form.ccdomain'}.'</b>'));
 3998:         if ($env{'form.sections'} ne '') {
 3999:             $r->print(' '.&mt('in section [_1]',$env{'form.sections'}));
 4000:         }
 4001:         my ($showstart,$showend);
 4002:         if ($startdate <= $now) {
 4003:             $showstart = &mt('Access starts immediately');
 4004:         } else {
 4005:             $showstart = &mt('Access starts: ').&Apache::lonlocal::locallocaltime($startdate);
 4006:         }
 4007:         if ($enddate == 0) {
 4008:             $showend = &mt('ends: no ending date');
 4009:         } else {
 4010:             $showend = &mt('ends: ').&Apache::lonlocal::locallocaltime($enddate);
 4011:         }
 4012:         $r->print('.<br />'.$showstart.'; '.$showend);
 4013:         if ($startdate <= $now && !$newuser) {
 4014:             $r->print('<p class="LC_info">');
 4015:             if ($crstype eq 'Community') {
 4016:                 $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.'));
 4017:             } else {
 4018:                 $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.'));
 4019:            }
 4020:            $r->print('</p>');
 4021:         }
 4022:     } else {
 4023:         $r->print(&mt('unable to enroll').": ".$enroll_result);
 4024:     }
 4025:     return;
 4026: }
 4027: 
 4028: sub get_defaultquota_text {
 4029:     my ($settingstatus) = @_;
 4030:     my $defquotatext; 
 4031:     if ($settingstatus eq '') {
 4032:         $defquotatext = &mt('default');
 4033:     } else {
 4034:         my ($usertypes,$order) =
 4035:             &Apache::lonnet::retrieve_inst_usertypes($env{'form.ccdomain'});
 4036:         if ($usertypes->{$settingstatus} eq '') {
 4037:             $defquotatext = &mt('default');
 4038:         } else {
 4039:             $defquotatext = &mt('default for [_1]',$usertypes->{$settingstatus});
 4040:         }
 4041:     }
 4042:     return $defquotatext;
 4043: }
 4044: 
 4045: sub update_result_form {
 4046:     my ($uhome) = @_;
 4047:     my $outcome = 
 4048:     '<form name="userupdate" method="post" action="">'."\n";
 4049:     foreach my $item ('srchby','srchin','srchtype','srchterm','srchdomain','ccuname','ccdomain') {
 4050:         $outcome .= '<input type="hidden" name="'.$item.'" value="'.$env{'form.'.$item}.'" />'."\n";
 4051:     }
 4052:     if ($env{'form.origname'} ne '') {
 4053:         $outcome .= '<input type="hidden" name="origname" value="'.$env{'form.origname'}.'" />'."\n";
 4054:     }
 4055:     foreach my $item ('sortby','seluname','seludom') {
 4056:         if (exists($env{'form.'.$item})) {
 4057:             $outcome .= '<input type="hidden" name="'.$item.'" value="'.$env{'form.'.$item}.'" />'."\n";
 4058:         }
 4059:     }
 4060:     if ($uhome eq 'no_host') {
 4061:         $outcome .= '<input type="hidden" name="forcenewuser" value="1" />'."\n";
 4062:     }
 4063:     $outcome .= '<input type="hidden" name="phase" value="" />'."\n".
 4064:                 '<input type="hidden" name="currstate" value="" />'."\n".
 4065:                 '<input type="hidden" name="action" value="'.$env{'form.action'}.'" />'."\n".
 4066:                 '</form>';
 4067:     return $outcome;
 4068: }
 4069: 
 4070: sub quota_admin {
 4071:     my ($setquota,$changeHash,$name) = @_;
 4072:     my $quotachanged;
 4073:     if (&Apache::lonnet::allowed('mpq',$env{'form.ccdomain'})) {
 4074:         # Current user has quota modification privileges
 4075:         if (ref($changeHash) eq 'HASH') {
 4076:             $quotachanged = 1;
 4077:             $changeHash->{$name.'quota'} = $setquota;
 4078:         }
 4079:     }
 4080:     return $quotachanged;
 4081: }
 4082: 
 4083: sub tool_admin {
 4084:     my ($tool,$settool,$changeHash,$context) = @_;
 4085:     my $canchange = 0; 
 4086:     if ($context eq 'requestcourses') {
 4087:         if (&Apache::lonnet::allowed('ccc',$env{'form.ccdomain'})) {
 4088:             $canchange = 1;
 4089:         }
 4090:     } elsif ($context eq 'reqcrsotherdom') {
 4091:         if (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) {
 4092:             $canchange = 1;
 4093:         }
 4094:     } elsif ($context eq 'requestauthor') {
 4095:         if (&Apache::lonnet::allowed('cau',$env{'request.role.domain'})) {
 4096:             $canchange = 1;
 4097:         }
 4098:     } elsif (&Apache::lonnet::allowed('mut',$env{'form.ccdomain'})) {
 4099:         # Current user has quota modification privileges
 4100:         $canchange = 1;
 4101:     }
 4102:     my $toolchanged;
 4103:     if ($canchange) {
 4104:         if (ref($changeHash) eq 'HASH') {
 4105:             $toolchanged = 1;
 4106:             if ($tool eq 'requestauthor') {
 4107:                 $changeHash->{$context} = $settool;
 4108:             } else {
 4109:                 $changeHash->{$context.'.'.$tool} = $settool;
 4110:             }
 4111:         }
 4112:     }
 4113:     return $toolchanged;
 4114: }
 4115: 
 4116: sub build_roles {
 4117:     my ($sectionstr,$sections,$role) = @_;
 4118:     my $num_sections = 0;
 4119:     if ($sectionstr=~ /,/) {
 4120:         my @secnums = split/,/,$sectionstr;
 4121:         if ($role eq 'st') {
 4122:             $secnums[0] =~ s/\W//g;
 4123:             $$sections{$secnums[0]} = 1;
 4124:             $num_sections = 1;
 4125:         } else {
 4126:             foreach my $sec (@secnums) {
 4127:                 $sec =~ ~s/\W//g;
 4128:                 if (!($sec eq "")) {
 4129:                     if (exists($$sections{$sec})) {
 4130:                         $$sections{$sec} ++;
 4131:                     } else {
 4132:                         $$sections{$sec} = 1;
 4133:                         $num_sections ++;
 4134:                     }
 4135:                 }
 4136:             }
 4137:         }
 4138:     } else {
 4139:         $sectionstr=~s/\W//g;
 4140:         unless ($sectionstr eq '') {
 4141:             $$sections{$sectionstr} = 1;
 4142:             $num_sections ++;
 4143:         }
 4144:     }
 4145: 
 4146:     return $num_sections;
 4147: }
 4148: 
 4149: # ========================================================== Custom Role Editor
 4150: 
 4151: sub custom_role_editor {
 4152:     my ($r,$brcrum) = @_;
 4153:     my $action = $env{'form.customroleaction'};
 4154:     my $rolename; 
 4155:     if ($action eq 'new') {
 4156:         $rolename=$env{'form.newrolename'};
 4157:     } else {
 4158:         $rolename=$env{'form.rolename'};
 4159:     }
 4160: 
 4161:     my ($crstype,$context);
 4162:     if ($env{'request.course.id'}) {
 4163:         $crstype = &Apache::loncommon::course_type();
 4164:         $context = 'course';
 4165:     } else {
 4166:         $context = 'domain';
 4167:         $crstype = $env{'form.templatecrstype'};
 4168:     }
 4169: 
 4170:     $rolename=~s/[^A-Za-z0-9]//gs;
 4171:     if (!$rolename || $env{'form.phase'} eq 'pickrole') {
 4172: 	&print_username_entry_form($r,undef,undef,undef,undef,$crstype,$brcrum);
 4173:         return;
 4174:     }
 4175: 
 4176: # ------------------------------------------------------- What can be assigned?
 4177:     my %full=();
 4178:     my %courselevel=();
 4179:     my %courselevelcurrent=();
 4180:     my $syspriv='';
 4181:     my $dompriv='';
 4182:     my $coursepriv='';
 4183:     my $body_top;
 4184:     my $newrole;
 4185:     my ($rdummy,$roledef)=
 4186: 			 &Apache::lonnet::get('roles',["rolesdef_$rolename"]);
 4187: # ------------------------------------------------------- Does this role exist?
 4188:     $body_top .= '<h2>';
 4189:     if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 4190: 	$body_top .= &mt('Existing Role').' "';
 4191: # ------------------------------------------------- Get current role privileges
 4192: 	($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 4193:         if ($crstype eq 'Community') {
 4194:             $syspriv =~ s/bre\&S//;   
 4195:         }
 4196:     } else {
 4197:         $newrole = 1;
 4198: 	$body_top .= &mt('New Role').' "';
 4199: 	$roledef='';
 4200:     }
 4201:     $body_top .= $rolename.'"</h2>';
 4202:     foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
 4203: 	my ($priv,$restrict)=split(/\&/,$item);
 4204:         if (!$restrict) { $restrict='F'; }
 4205:         $courselevel{$priv}=$restrict;
 4206:         if ($coursepriv=~/\:$priv/) {
 4207: 	    $courselevelcurrent{$priv}=1;
 4208: 	}
 4209: 	$full{$priv}=1;
 4210:     }
 4211:     my %domainlevel=();
 4212:     my %domainlevelcurrent=();
 4213:     foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:d'})) {
 4214: 	my ($priv,$restrict)=split(/\&/,$item);
 4215:         if (!$restrict) { $restrict='F'; }
 4216:         $domainlevel{$priv}=$restrict;
 4217:         if ($dompriv=~/\:$priv/) {
 4218: 	    $domainlevelcurrent{$priv}=1;
 4219: 	}
 4220: 	$full{$priv}=1;
 4221:     }
 4222:     my %systemlevel=();
 4223:     my %systemlevelcurrent=();
 4224:     foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:s'})) {
 4225: 	my ($priv,$restrict)=split(/\&/,$item);
 4226:         if (!$restrict) { $restrict='F'; }
 4227:         $systemlevel{$priv}=$restrict;
 4228:         if ($syspriv=~/\:$priv/) {
 4229: 	    $systemlevelcurrent{$priv}=1;
 4230: 	}
 4231: 	$full{$priv}=1;
 4232:     }
 4233:     my ($jsback,$elements) = &crumb_utilities();
 4234:     my $button_code = "\n";
 4235:     my $head_script = "\n";
 4236:     $head_script .= '<script type="text/javascript">'."\n"
 4237:                    .'// <![CDATA['."\n";
 4238:     my @template_roles = ("in","ta","ep");
 4239:     if ($context eq 'domain') {
 4240:         push(@template_roles,"ad");
 4241:     }
 4242:     push(@template_roles,"st");
 4243:     if ($crstype eq 'Community') {
 4244:         unshift(@template_roles,'co');
 4245:     } else {
 4246:         unshift(@template_roles,'cc');
 4247:     }
 4248:     foreach my $role (@template_roles) {
 4249:         $head_script .= &make_script_template($role,$crstype);
 4250:         $button_code .= &make_button_code($role,$crstype).' ';
 4251:     }
 4252:     my $context_code;
 4253:     if ($context eq 'domain') {
 4254:         my $checkedCommunity = '';
 4255:         my $checkedCourse = ' checked="checked"';
 4256:         if ($env{'form.templatecrstype'} eq 'Community') {
 4257:             $checkedCommunity = $checkedCourse;
 4258:             $checkedCourse = '';
 4259:         }
 4260:         $context_code = '<label>'.
 4261:                         '<input type="radio" name="templatecrstype" value="Course"'.$checkedCourse.' onclick="this.form.submit();">'.
 4262:                         &mt('Course').
 4263:                         '</label>'.('&nbsp;' x2).
 4264:                         '<label>'.
 4265:                         '<input type="radio" name="templatecrstype" value="Community"'.$checkedCommunity.' onclick="this.form.submit();">'.
 4266:                         &mt('Community').
 4267:                         '</label>'.
 4268:                         '</fieldset>'.
 4269:                         '<input type="hidden" name="customroleaction" value="'.
 4270:                         $action.'" />';
 4271:         if ($env{'form.customroleaction'} eq 'new') {
 4272:             $context_code .= '<input type="hidden" name="newrolename" value="'.
 4273:                              $rolename.'" />';
 4274:         } else {
 4275:             $context_code .= '<input type="hidden" name="rolename" value="'.
 4276:                              $rolename.'" />';
 4277:         }
 4278:         $context_code .= '<input type="hidden" name="action" value="custom" />'.
 4279:                          '<input type="hidden" name="phase" value="selected_custom_edit" />';
 4280:     }
 4281: 
 4282:     $head_script .= "\n".$jsback."\n"
 4283:                    .'// ]]>'."\n"
 4284:                    .'</script>'."\n";
 4285:     push (@{$brcrum},
 4286:               {href => "javascript:backPage(document.form1,'pickrole','')",
 4287:                text => "Pick custom role",
 4288:                faq  => 282,bug=>'Instructor Interface',},
 4289:               {href => "javascript:backPage(document.form1,'','')",
 4290:                text => "Edit custom role",
 4291:                faq  => 282,
 4292:                bug  => 'Instructor Interface',
 4293:                help => 'Course_Editing_Custom_Roles'}
 4294:               );
 4295:     my $args = { bread_crumbs          => $brcrum,
 4296:                  bread_crumbs_component => 'User Management'};
 4297:  
 4298:     $r->print(&Apache::loncommon::start_page('Custom Role Editor',
 4299:                                              $head_script,$args).
 4300:               $body_top);
 4301:     my %lt=&Apache::lonlocal::texthash(
 4302: 		    'prv'  => "Privilege",
 4303: 		    'crl'  => "Course Level",
 4304:                     'dml'  => "Domain Level",
 4305:                     'ssl'  => "System Level");
 4306: 
 4307:     $r->print('<div class="LC_left_float">'
 4308:              .'<form action=""><fieldset>'
 4309:              .'<legend>'.&mt('Select a Template').'</legend>'
 4310:              .$button_code
 4311:              .'</fieldset></form></div>');
 4312:     if ($context_code) {
 4313:         $r->print('<div class="LC_left_float">'
 4314:                  .'<form action="/adm/createuser" method="post"><fieldset>'
 4315:                  .'<legend>'.&mt('Context').'</legend>'
 4316:                  .$context_code
 4317:                  .'</form>'
 4318:                  .'</div>'
 4319:         );
 4320:     }
 4321:     $r->print('<br clear="all" />');
 4322: 
 4323:     $r->print(<<ENDCCF);
 4324: <form name="form1" method="post" action="">
 4325: <input type="hidden" name="phase" value="set_custom_roles" />
 4326: <input type="hidden" name="rolename" value="$rolename" />
 4327: ENDCCF
 4328:     $r->print(&Apache::loncommon::start_data_table().
 4329:               &Apache::loncommon::start_data_table_header_row(). 
 4330: '<th>'.$lt{'prv'}.'</th><th>'.$lt{'crl'}.'</th><th>'.$lt{'dml'}.
 4331: '</th><th>'.$lt{'ssl'}.'</th>'.
 4332:               &Apache::loncommon::end_data_table_header_row());
 4333:     foreach my $priv (sort(keys(%full))) {
 4334:         my $privtext = &Apache::lonnet::plaintext($priv,$crstype);
 4335:         $r->print(&Apache::loncommon::start_data_table_row().
 4336: 	          '<td>'.$privtext.'</td><td>'.
 4337:     ($courselevel{$priv}?'<input type="checkbox" name="'.$priv.'_c"'.
 4338:     ($courselevelcurrent{$priv}?' checked="checked"':'').' />':'&nbsp;').
 4339:     '</td><td>'.
 4340:     ($domainlevel{$priv}?'<input type="checkbox" name="'.$priv.'_d"'.
 4341:     ($domainlevelcurrent{$priv}?' checked="checked"':'').' />':'&nbsp;').
 4342:     '</td><td>');
 4343:         if ($priv eq 'bre' && $crstype eq 'Community') {
 4344:             $r->print('&nbsp;');  
 4345:         } else {
 4346:             $r->print($systemlevel{$priv}?'<input type="checkbox" name="'.$priv.'_s"'.
 4347:                       ($systemlevelcurrent{$priv}?' checked="checked"':'').' />':'&nbsp;');
 4348:         }
 4349:         $r->print('</td>'.
 4350:                   &Apache::loncommon::end_data_table_row());
 4351:     }
 4352:     $r->print(&Apache::loncommon::end_data_table().
 4353:    '<input type="hidden" name="action" value="'.$env{'form.action'}.'" />'.
 4354:    '<input type="hidden" name="startrolename" value="'.$env{'form.rolename'}.
 4355:    '" />'."\n".'<input type="hidden" name="currstate" value="" />'."\n".   
 4356:    '<input type="reset" value="'.&mt("Reset").'" />'."\n".
 4357:    '<input type="submit" value="'.&mt('Save').'" /></form>');
 4358: }
 4359: # --------------------------------------------------------
 4360: sub make_script_template {
 4361:     my ($role,$crstype) = @_;
 4362:     my %full_c=();
 4363:     my %full_d=();
 4364:     my %full_s=();
 4365:     my $return_script;
 4366:     foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
 4367:         my ($priv,$restrict)=split(/\&/,$item);
 4368:         $full_c{$priv}=1;
 4369:     }
 4370:     foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:d'})) {
 4371:         my ($priv,$restrict)=split(/\&/,$item);
 4372:         $full_d{$priv}=1;
 4373:     }
 4374:     foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:s'})) {
 4375:         next if (($crstype eq 'Community') && ($item eq 'bre&S'));
 4376:         my ($priv,$restrict)=split(/\&/,$item);
 4377:         $full_s{$priv}=1;
 4378:     }
 4379:     $return_script .= 'function set_'.$role.'() {'."\n";
 4380:     my @temp = split(/:/,$Apache::lonnet::pr{$role.':c'});
 4381:     my %role_c;
 4382:     foreach my $priv (@temp) {
 4383:         my ($priv_item, $dummy) = split(/\&/,$priv);
 4384:         $role_c{$priv_item} = 1;
 4385:     }
 4386:     my %role_d;
 4387:     @temp = split(/:/,$Apache::lonnet::pr{$role.':d'});
 4388:     foreach my $priv(@temp) {
 4389:         my ($priv_item, $dummy) = split(/\&/,$priv);
 4390:         $role_d{$priv_item} = 1;
 4391:     }
 4392:     my %role_s;
 4393:     @temp = split(/:/,$Apache::lonnet::pr{$role.':s'});
 4394:     foreach my $priv(@temp) {
 4395:         my ($priv_item, $dummy) = split(/\&/,$priv);
 4396:         $role_s{$priv_item} = 1;
 4397:     }
 4398:     foreach my $priv_item (keys(%full_c)) {
 4399:         my ($priv, $dummy) = split(/\&/,$priv_item);
 4400:         if ((exists($role_c{$priv})) || (exists($role_d{$priv})) || 
 4401:             (exists($role_s{$priv}))) {
 4402:             $return_script .= "document.form1.$priv"."_c.checked = true;\n";
 4403:         } else {
 4404:             $return_script .= "document.form1.$priv"."_c.checked = false;\n";
 4405:         }
 4406:     }
 4407:     foreach my $priv_item (keys(%full_d)) {
 4408:         my ($priv, $dummy) = split(/\&/,$priv_item);
 4409:         if ((exists($role_d{$priv})) || (exists($role_s{$priv}))) {
 4410:             $return_script .= "document.form1.$priv"."_d.checked = true;\n";
 4411:         } else {
 4412:             $return_script .= "document.form1.$priv"."_d.checked = false;\n";
 4413:         }
 4414:     }
 4415:     foreach my $priv_item (keys(%full_s)) {
 4416:         my ($priv, $dummy) = split(/\&/,$priv_item);
 4417:         if (exists($role_s{$priv})) {
 4418:             $return_script .= "document.form1.$priv"."_s.checked = true;\n";
 4419:         } else {
 4420:             $return_script .= "document.form1.$priv"."_s.checked = false;\n";
 4421:         }
 4422:     }
 4423:     $return_script .= '}'."\n";
 4424:     return ($return_script);
 4425: }
 4426: # ----------------------------------------------------------
 4427: sub make_button_code {
 4428:     my ($role,$crstype) = @_;
 4429:     my $label = &Apache::lonnet::plaintext($role,$crstype);
 4430:     my $button_code = '<input type="button" onclick="set_'.$role.'()" value="'.$label.'" />';
 4431:     return ($button_code);
 4432: }
 4433: # ---------------------------------------------------------- Call to definerole
 4434: sub set_custom_role {
 4435:     my ($r,$context,$brcrum) = @_;
 4436:     my $rolename=$env{'form.rolename'};
 4437:     $rolename=~s/[^A-Za-z0-9]//gs;
 4438:     if (!$rolename) {
 4439: 	&custom_role_editor($r,$brcrum);
 4440:         return;
 4441:     }
 4442:     my ($jsback,$elements) = &crumb_utilities();
 4443:     my $jscript = '<script type="text/javascript">'
 4444:                  .'// <![CDATA['."\n"
 4445:                  .$jsback."\n"
 4446:                  .'// ]]>'."\n"
 4447:                  .'</script>'."\n";
 4448:     push(@{$brcrum},
 4449:         {href => "javascript:backPage(document.customresult,'pickrole','')",
 4450:          text => "Pick custom role",
 4451:          faq  => 282,
 4452:          bug  => 'Instructor Interface',},
 4453:         {href => "javascript:backPage(document.customresult,'selected_custom_edit','')",
 4454:          text => "Edit custom role",
 4455:          faq  => 282,
 4456:          bug  => 'Instructor Interface',},
 4457:         {href => "javascript:backPage(document.customresult,'set_custom_roles','')",
 4458:          text => "Result",
 4459:          faq  => 282,
 4460:          bug  => 'Instructor Interface',
 4461:          help => 'Course_Editing_Custom_Roles'},
 4462:         );
 4463:     my $args = { bread_crumbs           => $brcrum,
 4464:                  bread_crumbs_component => 'User Management'}; 
 4465:     $r->print(&Apache::loncommon::start_page('Save Custom Role',$jscript,$args));
 4466: 
 4467:     my $newrole;
 4468:     my ($rdummy,$roledef)=
 4469: 	&Apache::lonnet::get('roles',["rolesdef_$rolename"]);
 4470: 
 4471: # ------------------------------------------------------- Does this role exist?
 4472:     $r->print('<h3>');
 4473:     if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 4474: 	$r->print(&mt('Existing Role').' "');
 4475:     } else {
 4476: 	$r->print(&mt('New Role').' "');
 4477: 	$roledef='';
 4478:         $newrole = 1;
 4479:     }
 4480:     $r->print($rolename.'"</h3>');
 4481: # ------------------------------------------------------- What can be assigned?
 4482:     my $sysrole='';
 4483:     my $domrole='';
 4484:     my $courole='';
 4485: 
 4486:     foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
 4487: 	my ($priv,$restrict)=split(/\&/,$item);
 4488:         if (!$restrict) { $restrict=''; }
 4489:         if ($env{'form.'.$priv.'_c'}) {
 4490: 	    $courole.=':'.$item;
 4491: 	}
 4492:     }
 4493: 
 4494:     foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:d'})) {
 4495: 	my ($priv,$restrict)=split(/\&/,$item);
 4496:         if (!$restrict) { $restrict=''; }
 4497:         if ($env{'form.'.$priv.'_d'}) {
 4498: 	    $domrole.=':'.$item;
 4499: 	}
 4500:     }
 4501: 
 4502:     foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:s'})) {
 4503: 	my ($priv,$restrict)=split(/\&/,$item);
 4504:         if (!$restrict) { $restrict=''; }
 4505:         if ($env{'form.'.$priv.'_s'}) {
 4506: 	    $sysrole.=':'.$item;
 4507: 	}
 4508:     }
 4509:     # Assign role; Compile and show result
 4510:     my $errmsg;
 4511:     my $result =
 4512:         &Apache::lonnet::definerole($rolename,$sysrole,$domrole,$courole);
 4513:     if ($result ne 'ok') {
 4514:         $errmsg = ': '.$result;
 4515:     }
 4516:     my $message =
 4517:         &Apache::lonhtmlcommon::confirm_success(
 4518:             &mt('Defining Role').$errmsg, ($result eq 'ok' ? 0 : 1));
 4519:     if ($env{'request.course.id'}) {
 4520:         my $url='/'.$env{'request.course.id'};
 4521:         $url=~s/\_/\//g;
 4522:         $result =
 4523:             &Apache::lonnet::assigncustomrole(
 4524:                 $env{'user.domain'},$env{'user.name'},
 4525:                 $url,
 4526:                 $env{'user.domain'},$env{'user.name'},
 4527:                 $rolename,undef,undef,undef,$context);
 4528:         if ($result ne 'ok') {
 4529:             $errmsg = ': '.$result;
 4530:         }
 4531:         $message .=
 4532:             '<br />'
 4533:            .&Apache::lonhtmlcommon::confirm_success(
 4534:                 &mt('Assigning Role to Self').$errmsg, ($result eq 'ok' ? 0 : 1));
 4535:     }
 4536:     $r->print(
 4537:         &Apache::loncommon::confirmwrapper($message)
 4538:        .'<br />'
 4539:        .&Apache::lonhtmlcommon::actionbox([
 4540:             '<a href="javascript:backPage(document.customresult,'."'pickrole'".')">'
 4541:            .&mt('Create or edit another custom role')
 4542:            .'</a>'])
 4543:        .'<form name="customresult" method="post" action="">'
 4544:        .&Apache::lonhtmlcommon::echo_form_input([])
 4545:        .'</form>'
 4546:     );
 4547: }
 4548: 
 4549: # ================================================================ Main Handler
 4550: sub handler {
 4551:     my $r = shift;
 4552:     if ($r->header_only) {
 4553:        &Apache::loncommon::content_type($r,'text/html');
 4554:        $r->send_http_header;
 4555:        return OK;
 4556:     }
 4557:     my ($context,$crstype);
 4558:     if ($env{'request.course.id'}) {
 4559:         $context = 'course';
 4560:         $crstype = &Apache::loncommon::course_type();
 4561:     } elsif ($env{'request.role'} =~ /^au\./) {
 4562:         $context = 'author';
 4563:     } else {
 4564:         $context = 'domain';
 4565:     }
 4566: 
 4567:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 4568:         ['action','state','callingform','roletype','showrole','bulkaction','popup','phase',
 4569:          'username','domain','srchterm','srchdomain','srchin','srchby','srchtype','queue']);
 4570:     &Apache::lonhtmlcommon::clear_breadcrumbs();
 4571:     my $args;
 4572:     my $brcrum = [];
 4573:     my $bread_crumbs_component = 'User Management';
 4574:     if (($env{'form.action'} ne 'dateselect') && ($env{'form.action'} ne 'displayuserreq')) {
 4575:         $brcrum = [{href=>"/adm/createuser",
 4576:                     text=>"User Management",
 4577:                     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'}
 4578:                   ];
 4579:     }
 4580:     #SD Following files not added to help, because the corresponding .tex-files seem to
 4581:     #be missing: Course_Approve_Selfenroll,Course_User_Logs,
 4582:     my ($permission,$allowed) = 
 4583:         &Apache::lonuserutils::get_permission($context,$crstype);
 4584:     if (!$allowed) {
 4585:         if ($context eq 'course') {
 4586:             $r->internal_redirect('/adm/viewclasslist');
 4587:             return OK;
 4588:         }
 4589:         $env{'user.error.msg'}=
 4590:             "/adm/createuser:cst:0:0:Cannot create/modify user data ".
 4591:                                  "or view user status.";
 4592:         return HTTP_NOT_ACCEPTABLE;
 4593:     }
 4594: 
 4595:     &Apache::loncommon::content_type($r,'text/html');
 4596:     $r->send_http_header;
 4597: 
 4598:     my $showcredits;
 4599:     if ((($context eq 'course') && ($crstype eq 'Course')) || 
 4600:          ($context eq 'domain')) {
 4601:         my %domdefaults = 
 4602:             &Apache::lonnet::get_domain_defaults($env{'request.role.domain'});
 4603:         if ($domdefaults{'officialcredits'} || $domdefaults{'unofficialcredits'}) {
 4604:             $showcredits = 1;
 4605:         }
 4606:     }
 4607: 
 4608:     # Main switch on form.action and form.state, as appropriate
 4609:     if (! exists($env{'form.action'})) {
 4610:         $args = {bread_crumbs => $brcrum,
 4611:                  bread_crumbs_component => $bread_crumbs_component}; 
 4612:         $r->print(&header(undef,$args));
 4613:         $r->print(&print_main_menu($permission,$context,$crstype));
 4614:     } elsif ($env{'form.action'} eq 'upload' && $permission->{'cusr'}) {
 4615:         push(@{$brcrum},
 4616:               { href => '/adm/createuser?action=upload&state=',
 4617:                 text => 'Upload Users List',
 4618:                 help => 'Course_Create_Class_List',
 4619:               });
 4620:         $bread_crumbs_component = 'Upload Users List';
 4621:         $args = {bread_crumbs           => $brcrum,
 4622:                  bread_crumbs_component => $bread_crumbs_component};
 4623:         $r->print(&header(undef,$args));
 4624:         $r->print('<form name="studentform" method="post" '.
 4625:                   'enctype="multipart/form-data" '.
 4626:                   ' action="/adm/createuser">'."\n");
 4627:         if (! exists($env{'form.state'})) {
 4628:             &Apache::lonuserutils::print_first_users_upload_form($r,$context);
 4629:         } elsif ($env{'form.state'} eq 'got_file') {
 4630:             &Apache::lonuserutils::print_upload_manager_form($r,$context,$permission,
 4631:                                                              $crstype,$showcredits);
 4632:         } elsif ($env{'form.state'} eq 'enrolling') {
 4633:             if ($env{'form.datatoken'}) {
 4634:                 &Apache::lonuserutils::upfile_drop_add($r,$context,$permission,
 4635:                                                        $showcredits);
 4636:             }
 4637:         } else {
 4638:             &Apache::lonuserutils::print_first_users_upload_form($r,$context);
 4639:         }
 4640:     } elsif ((($env{'form.action'} eq 'singleuser') || ($env{'form.action'}
 4641:              eq 'singlestudent')) && ($permission->{'cusr'})) {
 4642:         my $phase = $env{'form.phase'};
 4643:         my @search = ('srchterm','srchby','srchin','srchtype','srchdomain');
 4644: 	&Apache::loncreateuser::restore_prev_selections();
 4645: 	my $srch;
 4646: 	foreach my $item (@search) {
 4647: 	    $srch->{$item} = $env{'form.'.$item};
 4648: 	}
 4649:         if (($phase eq 'get_user_info') || ($phase eq 'userpicked') ||
 4650:             ($phase eq 'createnewuser')) {
 4651:             if ($env{'form.phase'} eq 'createnewuser') {
 4652:                 my $response;
 4653:                 if ($env{'form.srchterm'} !~ /^$match_username$/) {
 4654:                     my $response =
 4655:                         '<span class="LC_warning">'
 4656:                        .&mt('You must specify a valid username. Only the following are allowed:'
 4657:                            .' letters numbers - . @')
 4658:                        .'</span>';
 4659:                     $env{'form.phase'} = '';
 4660:                     &print_username_entry_form($r,$context,$response,$srch,undef,
 4661:                                                $crstype,$brcrum,$showcredits);
 4662:                 } else {
 4663:                     my $ccuname =&LONCAPA::clean_username($srch->{'srchterm'});
 4664:                     my $ccdomain=&LONCAPA::clean_domain($srch->{'srchdomain'});
 4665:                     &print_user_modification_page($r,$ccuname,$ccdomain,
 4666:                                                   $srch,$response,$context,
 4667:                                                   $permission,$crstype,$brcrum,
 4668:                                                   $showcredits);
 4669:                 }
 4670:             } elsif ($env{'form.phase'} eq 'get_user_info') {
 4671:                 my ($currstate,$response,$forcenewuser,$results) = 
 4672:                     &user_search_result($context,$srch);
 4673:                 if ($env{'form.currstate'} eq 'modify') {
 4674:                     $currstate = $env{'form.currstate'};
 4675:                 }
 4676:                 if ($currstate eq 'select') {
 4677:                     &print_user_selection_page($r,$response,$srch,$results,
 4678:                                                \@search,$context,undef,$crstype,
 4679:                                                $brcrum);
 4680:                 } elsif ($currstate eq 'modify') {
 4681:                     my ($ccuname,$ccdomain);
 4682:                     if (($srch->{'srchby'} eq 'uname') && 
 4683:                         ($srch->{'srchtype'} eq 'exact')) {
 4684:                         $ccuname = $srch->{'srchterm'};
 4685:                         $ccdomain= $srch->{'srchdomain'};
 4686:                     } else {
 4687:                         my @matchedunames = keys(%{$results});
 4688:                         ($ccuname,$ccdomain) = split(/:/,$matchedunames[0]);
 4689:                     }
 4690:                     $ccuname =&LONCAPA::clean_username($ccuname);
 4691:                     $ccdomain=&LONCAPA::clean_domain($ccdomain);
 4692:                     if ($env{'form.forcenewuser'}) {
 4693:                         $response = '';
 4694:                     }
 4695:                     &print_user_modification_page($r,$ccuname,$ccdomain,
 4696:                                                   $srch,$response,$context,
 4697:                                                   $permission,$crstype,$brcrum);
 4698:                 } elsif ($currstate eq 'query') {
 4699:                     &print_user_query_page($r,'createuser',$brcrum);
 4700:                 } else {
 4701:                     $env{'form.phase'} = '';
 4702:                     &print_username_entry_form($r,$context,$response,$srch,
 4703:                                                $forcenewuser,$crstype,$brcrum);
 4704:                 }
 4705:             } elsif ($env{'form.phase'} eq 'userpicked') {
 4706:                 my $ccuname = &LONCAPA::clean_username($env{'form.seluname'});
 4707:                 my $ccdomain = &LONCAPA::clean_domain($env{'form.seludom'});
 4708:                 &print_user_modification_page($r,$ccuname,$ccdomain,$srch,'',
 4709:                                               $context,$permission,$crstype,
 4710:                                               $brcrum);
 4711:             }
 4712:         } elsif ($env{'form.phase'} eq 'update_user_data') {
 4713:             &update_user_data($r,$context,$crstype,$brcrum,$showcredits);
 4714:         } else {
 4715:             &print_username_entry_form($r,$context,undef,$srch,undef,$crstype,
 4716:                                        $brcrum);
 4717:         }
 4718:     } elsif ($env{'form.action'} eq 'custom' && $permission->{'custom'}) {
 4719:         if ($env{'form.phase'} eq 'set_custom_roles') {
 4720:             &set_custom_role($r,$context,$brcrum);
 4721:         } else {
 4722:             &custom_role_editor($r,$brcrum);
 4723:         }
 4724:     } elsif (($env{'form.action'} eq 'processauthorreq') &&
 4725:              ($permission->{'cusr'}) && 
 4726:              (&Apache::lonnet::allowed('cau',$env{'request.role.domain'}))) {
 4727:         push(@{$brcrum},
 4728:                  {href => '/adm/createuser?action=processauthorreq',
 4729:                   text => 'Authoring Space requests',
 4730:                   help => 'Domain_Role_Approvals'});
 4731:         $bread_crumbs_component = 'Authoring requests';
 4732:         if ($env{'form.state'} eq 'done') {
 4733:             push(@{$brcrum},
 4734:                      {href => '/adm/createuser?action=authorreqqueue',
 4735:                       text => 'Result',
 4736:                       help => 'Domain_Role_Approvals'});
 4737:             $bread_crumbs_component = 'Authoring request result';
 4738:         }
 4739:         $args = { bread_crumbs           => $brcrum,
 4740:                   bread_crumbs_component => $bread_crumbs_component};
 4741:         my $js = &usernamerequest_javascript();
 4742:         $r->print(&header(&add_script($js),$args));
 4743:         if (!exists($env{'form.state'})) {
 4744:             $r->print(&Apache::loncoursequeueadmin::display_queued_requests('requestauthor',
 4745:                                                                             $env{'request.role.domain'}));
 4746:         } elsif ($env{'form.state'} eq 'done') {
 4747:             $r->print('<h3>'.&mt('Authoring request processing').'</h3>'."\n");
 4748:             $r->print(&Apache::loncoursequeueadmin::update_request_queue('requestauthor',
 4749:                                                                          $env{'request.role.domain'}));
 4750:         }
 4751:     } elsif (($env{'form.action'} eq 'processusernamereq') &&
 4752:              ($permission->{'cusr'}) &&
 4753:              (&Apache::lonnet::allowed('cau',$env{'request.role.domain'}))) {
 4754:         push(@{$brcrum},
 4755:                  {href => '/adm/createuser?action=processusernamereq',
 4756:                   text => 'LON-CAPA account requests',
 4757:                   help => 'Domain_Username_Approvals'});
 4758:         $bread_crumbs_component = 'Account requests';
 4759:         if ($env{'form.state'} eq 'done') {
 4760:             push(@{$brcrum},
 4761:                      {href => '/adm/createuser?action=usernamereqqueue',
 4762:                       text => 'Result',
 4763:                       help => 'Domain_Username_Approvals'});
 4764:             $bread_crumbs_component = 'LON-CAPA account request result';
 4765:         }
 4766:         $args = { bread_crumbs           => $brcrum,
 4767:                   bread_crumbs_component => $bread_crumbs_component};
 4768:         my $js = &usernamerequest_javascript();
 4769:         $r->print(&header(&add_script($js),$args));
 4770:         if (!exists($env{'form.state'})) {
 4771:             $r->print(&Apache::loncoursequeueadmin::display_queued_requests('requestusername',
 4772:                                                                             $env{'request.role.domain'}));
 4773:         } elsif ($env{'form.state'} eq 'done') {
 4774:             $r->print('<h3>'.&mt('LON-CAPA account request processing').'</h3>'."\n");
 4775:             $r->print(&Apache::loncoursequeueadmin::update_request_queue('requestusername',
 4776:                                                                          $env{'request.role.domain'}));
 4777:         }
 4778:     } elsif (($env{'form.action'} eq 'displayuserreq') &&
 4779:              ($permission->{'cusr'})) {
 4780:         my $dom = $env{'form.domain'};
 4781:         my $uname = $env{'form.username'};
 4782:         my $warning;
 4783:         if (($dom =~ /^$match_domain$/) && (&Apache::lonnet::domain($dom) ne '')) {
 4784:             if (($dom eq $env{'request.role.domain'}) && (&Apache::lonnet::allowed('ccc',$dom))) {
 4785:                 if (($uname =~ /^$match_username$/) && ($env{'form.queue'} eq 'approval')) {
 4786:                     my $uhome = &Apache::lonnet::homeserver($uname,$dom);
 4787:                     if ($uhome eq 'no_host') {
 4788:                         my $queue = $env{'form.queue'};
 4789:                         my $reqkey = &escape($uname).'_'.$queue; 
 4790:                         my $namespace = 'usernamequeue';
 4791:                         my $domconfig = &Apache::lonnet::get_domainconfiguser($dom);
 4792:                         my %queued =
 4793:                             &Apache::lonnet::get($namespace,[$reqkey],$dom,$domconfig);
 4794:                         unless ($queued{$reqkey}) {
 4795:                             $warning = &mt('No information was found for this LON-CAPA account request.');
 4796:                         }
 4797:                     } else {
 4798:                         $warning = &mt('A LON-CAPA account already exists for the requested username and domain.');
 4799:                     }
 4800:                 } else {
 4801:                     $warning = &mt('LON-CAPA account request status check is for an invalid username.');
 4802:                 }
 4803:             } else {
 4804:                 $warning = &mt('You do not have rights to view LON-CAPA account requests in the domain specified.');
 4805:             }
 4806:         } else {
 4807:             $warning = &mt('LON-CAPA account request status check is for an invalid domain.');
 4808:         }
 4809:         my $args = { only_body => 1 };
 4810:         $r->print(&header(undef,$args).
 4811:                   '<h3>'.&mt('LON-CAPA Account Request Details').'</h3>');
 4812:         if ($warning ne '') {
 4813:             $r->print('<div class="LC_warning">'.$warning.'</div>');
 4814:         } else {
 4815:             my ($infofields,$infotitles) = &Apache::loncommon::emailusername_info();
 4816:             my $domconfiguser = &Apache::lonnet::get_domainconfiguser($dom);
 4817:             my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 4818:             if (ref($domconfig{'usercreation'}) eq 'HASH') {
 4819:                 if (ref($domconfig{'usercreation'}{'cancreate'}) eq 'HASH') {
 4820:                     if (ref($domconfig{'usercreation'}{'cancreate'}{'emailusername'}) eq 'HASH') {
 4821:                         my %info =
 4822:                             &Apache::lonnet::get('nohist_requestedusernames',[$uname],$dom,$domconfiguser);
 4823:                         if (ref($info{$uname}) eq 'HASH') {
 4824:                             my $usertype = $info{$uname}{'inststatus'};
 4825:                             unless ($usertype) {
 4826:                                 $usertype = 'default';
 4827:                             }
 4828:                             if (ref($domconfig{'usercreation'}{'cancreate'}{'emailusername'}{$usertype}) eq 'HASH') {
 4829:                                 if ((ref($infofields) eq 'ARRAY') && (ref($infotitles) eq 'HASH')) {
 4830:                                     $r->print('<div>'.&Apache::lonhtmlcommon::start_pick_box());
 4831:                                     my ($num,$count,$showstatus);
 4832:                                     $count = scalar(keys(%{$domconfig{'usercreation'}{'cancreate'}{'emailusername'}{$usertype}}));
 4833:                                     unless ($usertype eq 'default') {
 4834:                                         my ($othertitle,$usertypes,$types) = 
 4835:                                             &Apache::loncommon::sorted_inst_types($dom);
 4836:                                         if (ref($usertypes) eq 'HASH') {
 4837:                                             if ($usertypes->{$usertype}) {
 4838:                                                 $showstatus = $usertypes->{$usertype};
 4839:                                                 $count ++;
 4840:                                             }
 4841:                                         }
 4842:                                     }
 4843:                                     foreach my $field (@{$infofields}) {
 4844:                                         next unless ($domconfig{'usercreation'}{'cancreate'}{'emailusername'}{$usertype}{$field});
 4845:                                         next unless ($infotitles->{$field});
 4846:                                         $r->print(&Apache::lonhtmlcommon::row_title($infotitles->{$field}).
 4847:                                                   $info{$uname}{$field});
 4848:                                         $num ++;
 4849:                                         if ($count == $num) {
 4850:                                             $r->print(&Apache::lonhtmlcommon::row_closure(1));
 4851:                                         } else {
 4852:                                             $r->print(&Apache::lonhtmlcommon::row_closure());
 4853:                                         }
 4854:                                     }
 4855:                                     if ($showstatus) {
 4856:                                         $r->print(&Apache::lonhtmlcommon::row_title(&mt('Status type (self-reported)')).
 4857:                                                   $showstatus.
 4858:                                                   &Apache::lonhtmlcommon::row_closure(1));
 4859:                                     }
 4860:                                     $r->print(&Apache::lonhtmlcommon::end_pick_box().'</div>');
 4861:                                 }
 4862:                             }
 4863:                         }
 4864:                     }
 4865:                 }
 4866:             }
 4867:             $r->print(&close_popup_form());
 4868:         }
 4869:     } elsif (($env{'form.action'} eq 'listusers') && 
 4870:              ($permission->{'view'} || $permission->{'cusr'})) {
 4871:         if ($env{'form.phase'} eq 'bulkchange') {
 4872:             push(@{$brcrum},
 4873:                     {href => '/adm/createuser?action=listusers',
 4874:                      text => "List Users"},
 4875:                     {href => "/adm/createuser",
 4876:                      text => "Result",
 4877:                      help => 'Course_View_Class_List'});
 4878:             $bread_crumbs_component = 'Update Users';
 4879:             $args = {bread_crumbs           => $brcrum,
 4880:                      bread_crumbs_component => $bread_crumbs_component};
 4881:             $r->print(&header(undef,$args));
 4882:             my $setting = $env{'form.roletype'};
 4883:             my $choice = $env{'form.bulkaction'};
 4884:             if ($permission->{'cusr'}) {
 4885:                 &Apache::lonuserutils::update_user_list($r,$context,$setting,$choice,$crstype);
 4886:             } else {
 4887:                 $r->print(&mt('You are not authorized to make bulk changes to user roles'));
 4888:                 $r->print('<p><a href="/adm/createuser?action=listusers">'.&mt('Display User Lists').'</a>');
 4889:             }
 4890:         } else {
 4891:             push(@{$brcrum},
 4892:                     {href => '/adm/createuser?action=listusers',
 4893:                      text => "List Users",
 4894:                      help => 'Course_View_Class_List'});
 4895:             $bread_crumbs_component = 'List Users';
 4896:             $args = {bread_crumbs           => $brcrum,
 4897:                      bread_crumbs_component => $bread_crumbs_component};
 4898:             my ($cb_jscript,$jscript,$totcodes,$codetitles,$idlist,$idlist_titles);
 4899:             my $formname = 'studentform';
 4900:             my $hidecall = "hide_searching();";
 4901:             if (($context eq 'domain') && (($env{'form.roletype'} eq 'course') ||
 4902:                 ($env{'form.roletype'} eq 'community'))) {
 4903:                 if ($env{'form.roletype'} eq 'course') {
 4904:                     ($cb_jscript,$jscript,$totcodes,$codetitles,$idlist,$idlist_titles) = 
 4905:                         &Apache::lonuserutils::courses_selector($env{'request.role.domain'},
 4906:                                                                 $formname);
 4907:                 } elsif ($env{'form.roletype'} eq 'community') {
 4908:                     $cb_jscript = 
 4909:                         &Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'});
 4910:                     my %elements = (
 4911:                                       coursepick => 'radio',
 4912:                                       coursetotal => 'text',
 4913:                                       courselist => 'text',
 4914:                                    );
 4915:                     $jscript = &Apache::lonhtmlcommon::set_form_elements(\%elements);
 4916:                 }
 4917:                 $jscript .= &verify_user_display($context)."\n".
 4918:                             &Apache::loncommon::check_uncheck_jscript();
 4919:                 my $js = &add_script($jscript).$cb_jscript;
 4920:                 my $loadcode = 
 4921:                     &Apache::lonuserutils::course_selector_loadcode($formname);
 4922:                 if ($loadcode ne '') {
 4923:                     $args->{add_entries} = {onload => "$loadcode;$hidecall"};
 4924:                 } else {
 4925:                     $args->{add_entries} = {onload => $hidecall};
 4926:                 }
 4927:                 $r->print(&header($js,$args));
 4928:             } else {
 4929:                 $args->{add_entries} = {onload => $hidecall};
 4930:                 $jscript = &verify_user_display($context).
 4931:                            &Apache::loncommon::check_uncheck_jscript(); 
 4932:                 $r->print(&header(&add_script($jscript),$args));
 4933:             }
 4934:             &Apache::lonuserutils::print_userlist($r,undef,$permission,$context,
 4935:                          $formname,$totcodes,$codetitles,$idlist,$idlist_titles,
 4936:                          $showcredits);
 4937:         }
 4938:     } elsif ($env{'form.action'} eq 'drop' && $permission->{'cusr'}) {
 4939:         my $brtext;
 4940:         if ($crstype eq 'Community') {
 4941:             $brtext = 'Drop Members';
 4942:         } else {
 4943:             $brtext = 'Drop Students';
 4944:         }
 4945:         push(@{$brcrum},
 4946:                 {href => '/adm/createuser?action=drop',
 4947:                  text => $brtext,
 4948:                  help => 'Course_Drop_Student'});
 4949:         if ($env{'form.state'} eq 'done') {
 4950:             push(@{$brcrum},
 4951:                      {href=>'/adm/createuser?action=drop',
 4952:                       text=>"Result"});
 4953:         }
 4954:         $bread_crumbs_component = $brtext;
 4955:         $args = {bread_crumbs           => $brcrum,
 4956:                  bread_crumbs_component => $bread_crumbs_component}; 
 4957:         $r->print(&header(undef,$args));
 4958:         if (!exists($env{'form.state'})) {
 4959:             &Apache::lonuserutils::print_drop_menu($r,$context,$permission,$crstype);
 4960:         } elsif ($env{'form.state'} eq 'done') {
 4961:             &Apache::lonuserutils::update_user_list($r,$context,undef,
 4962:                                                     $env{'form.action'});
 4963:         }
 4964:     } elsif ($env{'form.action'} eq 'dateselect') {
 4965:         if ($permission->{'cusr'}) {
 4966:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 4967:                       &Apache::lonuserutils::date_section_selector($context,$permission,
 4968:                                                                    $crstype,$showcredits));
 4969:         } else {
 4970:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 4971:                      '<span class="LC_error">'.&mt('You do not have permission to modify dates or sections for users').'</span>'); 
 4972:         }
 4973:     } elsif ($env{'form.action'} eq 'selfenroll') {
 4974:         if ($permission->{selfenrolladmin}) {
 4975:             my $cid = $env{'request.course.id'};
 4976:             my $cdom = $env{'course.'.$cid.'.domain'};
 4977:             my $cnum = $env{'course.'.$cid.'.num'};
 4978:             my %currsettings = (
 4979:                 selfenroll_types              => $env{'course.'.$cid.'.internal.selfenroll_types'},
 4980:                 selfenroll_registered         => $env{'course.'.$cid.'.internal.selfenroll_registered'},
 4981:                 selfenroll_section            => $env{'course.'.$cid.'.internal.selfenroll_section'},
 4982:                 selfenroll_notifylist         => $env{'course.'.$cid.'.internal.selfenroll_notifylist'},
 4983:                 selfenroll_approval           => $env{'course.'.$cid.'.internal.selfenroll_approval'},
 4984:                 selfenroll_limit              => $env{'course.'.$cid.'.internal.selfenroll_limit'},
 4985:                 selfenroll_cap                => $env{'course.'.$cid.'.internal.selfenroll_cap'},
 4986:                 selfenroll_start_date         => $env{'course.'.$cid.'.internal.selfenroll_start_date'},
 4987:                 selfenroll_end_date           => $env{'course.'.$cid.'.internal.selfenroll_end_date'},
 4988:                 selfenroll_start_access       => $env{'course.'.$cid.'.internal.selfenroll_start_access'},
 4989:                 selfenroll_end_access         => $env{'course.'.$cid.'.internal.selfenroll_end_access'},
 4990:                 default_enrollment_start_date => $env{'course.'.$cid.'.default_enrollment_start_date'},
 4991:                 default_enrollment_end_date   => $env{'course.'.$cid.'.default_enrollment_end_date'},
 4992:                 uniquecode                    => $env{'course.'.$cid.'.internal.uniquecode'},
 4993:             );
 4994:             push(@{$brcrum},
 4995:                     {href => '/adm/createuser?action=selfenroll',
 4996:                      text => "Configure Self-enrollment",
 4997:                      help => 'Course_Self_Enrollment'});
 4998:             if (!exists($env{'form.state'})) {
 4999:                 $args = { bread_crumbs           => $brcrum,
 5000:                           bread_crumbs_component => 'Configure Self-enrollment'};
 5001:                 $r->print(&header(undef,$args));
 5002:                 $r->print('<h3>'.&mt('Self-enrollment with a student role').'</h3>'."\n");
 5003:                 &print_selfenroll_menu($r,'course',$cid,$cdom,$cnum,\%currsettings);
 5004:             } elsif ($env{'form.state'} eq 'done') {
 5005:                 push (@{$brcrum},
 5006:                           {href=>'/adm/createuser?action=selfenroll',
 5007:                            text=>"Result"});
 5008:                 $args = { bread_crumbs           => $brcrum,
 5009:                           bread_crumbs_component => 'Self-enrollment result'};
 5010:                 $r->print(&header(undef,$args));
 5011:                 $r->print('<h3>'.&mt('Self-enrollment with a student role').'</h3>'."\n");
 5012:                 &update_selfenroll_config($r,$cid,$cdom,$cnum,$context,$crstype,\%currsettings);
 5013:             }
 5014:         } else {
 5015:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 5016:                      '<span class="LC_error">'.&mt('You do not have permission to configure self-enrollment').'</span>');
 5017:         }
 5018:     } elsif ($env{'form.action'} eq 'selfenrollqueue') {
 5019:         push(@{$brcrum},
 5020:                  {href => '/adm/createuser?action=selfenrollqueue',
 5021:                   text => 'Enrollment requests',
 5022:                   help => 'Course_Self_Enrollment'});
 5023:         $bread_crumbs_component = 'Enrollment requests';
 5024:         if ($env{'form.state'} eq 'done') {
 5025:             push(@{$brcrum},
 5026:                      {href => '/adm/createuser?action=selfenrollqueue',
 5027:                       text => 'Result',
 5028:                       help => 'Course_Self_Enrollment'});
 5029:             $bread_crumbs_component = 'Enrollment result';
 5030:         }
 5031:         $args = { bread_crumbs           => $brcrum,
 5032:                   bread_crumbs_component => $bread_crumbs_component};
 5033:         $r->print(&header(undef,$args));
 5034:         my $cid = $env{'request.course.id'};
 5035:         my $cdom = $env{'course.'.$cid.'.domain'};
 5036:         my $cnum = $env{'course.'.$cid.'.num'};
 5037:         my $coursedesc = $env{'course.'.$cid.'.description'};
 5038:         if (!exists($env{'form.state'})) {
 5039:             $r->print('<h3>'.&mt('Pending enrollment requests').'</h3>'."\n");
 5040:             $r->print(&Apache::loncoursequeueadmin::display_queued_requests($context,
 5041:                                                                        $cdom,$cnum));
 5042:         } elsif ($env{'form.state'} eq 'done') {
 5043:             $r->print('<h3>'.&mt('Enrollment request processing').'</h3>'."\n");
 5044:             $r->print(&Apache::loncoursequeueadmin::update_request_queue($context,
 5045:                           $cdom,$cnum,$coursedesc));
 5046:         }
 5047:     } elsif ($env{'form.action'} eq 'changelogs') {
 5048:         my $helpitem;
 5049:         if ($context eq 'course') {
 5050:             $helpitem = 'Course_User_Logs';
 5051:         }
 5052:         push (@{$brcrum},
 5053:                  {href => '/adm/createuser?action=changelogs',
 5054:                   text => 'User Management Logs',
 5055:                   help => $helpitem});
 5056:         $bread_crumbs_component = 'User Changes';
 5057:         $args = { bread_crumbs           => $brcrum,
 5058:                   bread_crumbs_component => $bread_crumbs_component};
 5059:         $r->print(&header(undef,$args));
 5060:         &print_userchangelogs_display($r,$context,$permission);
 5061:     } else {
 5062:         $bread_crumbs_component = 'User Management';
 5063:         $args = { bread_crumbs           => $brcrum,
 5064:                   bread_crumbs_component => $bread_crumbs_component};
 5065:         $r->print(&header(undef,$args));
 5066:         $r->print(&print_main_menu($permission,$context,$crstype));
 5067:     }
 5068:     $r->print(&Apache::loncommon::end_page());
 5069:     return OK;
 5070: }
 5071: 
 5072: sub header {
 5073:     my ($jscript,$args) = @_;
 5074:     my $start_page;
 5075:     if (ref($args) eq 'HASH') {
 5076:         $start_page=&Apache::loncommon::start_page('User Management',$jscript,$args);
 5077:     } else {
 5078:         $start_page=&Apache::loncommon::start_page('User Management',$jscript);
 5079:     }
 5080:     return $start_page;
 5081: }
 5082: 
 5083: sub add_script {
 5084:     my ($js) = @_;
 5085:     return '<script type="text/javascript">'."\n"
 5086:           .'// <![CDATA['."\n"
 5087:           .$js."\n"
 5088:           .'// ]]>'."\n"
 5089:           .'</script>'."\n";
 5090: }
 5091: 
 5092: sub usernamerequest_javascript {
 5093:     my $js = <<ENDJS;
 5094: 
 5095: function openusernamereqdisplay(dom,uname,queue) {
 5096:     var url = '/adm/createuser?action=displayuserreq';
 5097:     url += '&domain='+dom+'&username='+uname+'&queue='+queue;
 5098:     var title = 'Account_Request_Browser';
 5099:     var options = 'scrollbars=1,resizable=1,menubar=0';
 5100:     options += ',width=700,height=600';
 5101:     var stdeditbrowser = open(url,title,options,'1');
 5102:     stdeditbrowser.focus();
 5103:     return;
 5104: }
 5105:  
 5106: ENDJS
 5107: }
 5108: 
 5109: sub close_popup_form {
 5110:     my $close= &mt('Close Window');
 5111:     return << "END";
 5112: <p><form name="displayreq" action="" method="post">
 5113: <input type="button" name="closeme" value="$close" onclick="javascript:self.close();" />
 5114: </form></p>
 5115: END
 5116: }
 5117: 
 5118: sub verify_user_display {
 5119:     my ($context) = @_;
 5120:     my %lt = &Apache::lonlocal::texthash (
 5121:         course    => 'course(s): description, section(s), status',
 5122:         community => 'community(s): description, section(s), status',
 5123:         author    => 'author',
 5124:     );
 5125:     my $photos;
 5126:     if (($context eq 'course') && $env{'request.course.id'}) {
 5127:         $photos = $env{'course.'.$env{'request.course.id'}.'.internal.showphoto'};
 5128:     }
 5129:     my $output = <<"END";
 5130: 
 5131: function hide_searching() {
 5132:     if (document.getElementById('searching')) {
 5133:         document.getElementById('searching').style.display = 'none';
 5134:     }
 5135:     return;
 5136: }
 5137: 
 5138: function display_update() {
 5139:     document.studentform.action.value = 'listusers';
 5140:     document.studentform.phase.value = 'display';
 5141:     document.studentform.submit();
 5142: }
 5143: 
 5144: function updateCols(caller) {
 5145:     var context = '$context';
 5146:     var photos = '$photos';
 5147:     if (caller == 'Status') {
 5148:         if ((context == 'domain') && 
 5149:             ((document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'course') ||
 5150:              (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'community'))) {
 5151:             document.getElementById('showcolstatus').checked = false;
 5152:             document.getElementById('showcolstatus').disabled = 'disabled';
 5153:             document.getElementById('showcolstart').checked = false;
 5154:             document.getElementById('showcolend').checked = false;
 5155:         } else {
 5156:             if (document.studentform.Status.options[document.studentform.Status.selectedIndex].value == 'Any') {
 5157:                 document.getElementById('showcolstatus').checked = true;
 5158:                 document.getElementById('showcolstatus').disabled = '';
 5159:                 document.getElementById('showcolstart').checked = true;
 5160:                 document.getElementById('showcolend').checked = true;
 5161:             } else {
 5162:                 document.getElementById('showcolstatus').checked = false;
 5163:                 document.getElementById('showcolstatus').disabled = 'disabled';
 5164:                 document.getElementById('showcolstart').checked = false;
 5165:                 document.getElementById('showcolend').checked = false;
 5166:             }
 5167:         }
 5168:     }
 5169:     if (caller == 'output') {
 5170:         if (photos == 1) {
 5171:             if (document.getElementById('showcolphoto')) {
 5172:                 var photoitem = document.getElementById('showcolphoto');
 5173:                 if (document.studentform.output.options[document.studentform.output.selectedIndex].value == 'html') {
 5174:                     photoitem.checked = true;
 5175:                     photoitem.disabled = '';
 5176:                 } else {
 5177:                     photoitem.checked = false;
 5178:                     photoitem.disabled = 'disabled';
 5179:                 }
 5180:             }
 5181:         }
 5182:     }
 5183:     if (caller == 'showrole') {
 5184:         if ((document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'Any') ||
 5185:             (document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'cr')) {
 5186:             document.getElementById('showcolrole').checked = true;
 5187:             document.getElementById('showcolrole').disabled = '';
 5188:         } else {
 5189:             document.getElementById('showcolrole').checked = false;
 5190:             document.getElementById('showcolrole').disabled = 'disabled';
 5191:         }
 5192:         if (context == 'domain') {
 5193:             var quotausageshow = 0;
 5194:             if ((document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'course') ||
 5195:                 (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'community')) {
 5196:                 document.getElementById('showcolstatus').checked = false;
 5197:                 document.getElementById('showcolstatus').disabled = 'disabled';
 5198:                 document.getElementById('showcolstart').checked = false;
 5199:                 document.getElementById('showcolend').checked = false;
 5200:             } else {
 5201:                 if (document.studentform.Status.options[document.studentform.Status.selectedIndex].value == 'Any') {
 5202:                     document.getElementById('showcolstatus').checked = true;
 5203:                     document.getElementById('showcolstatus').disabled = '';
 5204:                     document.getElementById('showcolstart').checked = true;
 5205:                     document.getElementById('showcolend').checked = true;
 5206:                 }
 5207:             }
 5208:             if (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'domain') {
 5209:                 document.getElementById('showcolextent').disabled = 'disabled';
 5210:                 document.getElementById('showcolextent').checked = 'false';
 5211:                 document.getElementById('showextent').style.display='none';
 5212:                 document.getElementById('showcoltextextent').innerHTML = '';
 5213:                 if ((document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'au') ||
 5214:                     (document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'Any')) {
 5215:                     if (document.getElementById('showcolauthorusage')) {
 5216:                         document.getElementById('showcolauthorusage').disabled = '';
 5217:                     }
 5218:                     if (document.getElementById('showcolauthorquota')) {
 5219:                         document.getElementById('showcolauthorquota').disabled = '';
 5220:                     }
 5221:                     quotausageshow = 1;
 5222:                 }
 5223:             } else {
 5224:                 document.getElementById('showextent').style.display='block';
 5225:                 document.getElementById('showextent').style.textAlign='left';
 5226:                 document.getElementById('showextent').style.textFace='normal';
 5227:                 if (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'author') {
 5228:                     document.getElementById('showcolextent').disabled = '';
 5229:                     document.getElementById('showcolextent').checked = 'true';
 5230:                     document.getElementById('showcoltextextent').innerHTML="$lt{'author'}";
 5231:                 } else {
 5232:                     document.getElementById('showcolextent').disabled = '';
 5233:                     document.getElementById('showcolextent').checked = 'true';
 5234:                     if (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'community') {
 5235:                         document.getElementById('showcoltextextent').innerHTML="$lt{'community'}";
 5236:                     } else {
 5237:                         document.getElementById('showcoltextextent').innerHTML="$lt{'course'}";
 5238:                     }
 5239:                 }
 5240:             }
 5241:             if (quotausageshow == 0)  {
 5242:                 if (document.getElementById('showcolauthorusage')) {
 5243:                     document.getElementById('showcolauthorusage').checked = false;
 5244:                     document.getElementById('showcolauthorusage').disabled = 'disabled';
 5245:                 }
 5246:                 if (document.getElementById('showcolauthorquota')) {
 5247:                     document.getElementById('showcolauthorquota').checked = false;
 5248:                     document.getElementById('showcolauthorquota').disabled = 'disabled';
 5249:                 }
 5250:             }
 5251:         }
 5252:     }
 5253:     return;
 5254: }
 5255: 
 5256: END
 5257:     return $output;
 5258: 
 5259: }
 5260: 
 5261: ###############################################################
 5262: ###############################################################
 5263: #  Menu Phase One
 5264: sub print_main_menu {
 5265:     my ($permission,$context,$crstype) = @_;
 5266:     my $linkcontext = $context;
 5267:     my $stuterm = lc(&Apache::lonnet::plaintext('st',$crstype));
 5268:     if (($context eq 'course') && ($crstype eq 'Community')) {
 5269:         $linkcontext = lc($crstype);
 5270:         $stuterm = 'Members';
 5271:     }
 5272:     my %links = (
 5273:                 domain => {
 5274:                             upload     => 'Upload a File of Users',
 5275:                             singleuser => 'Add/Modify a User',
 5276:                             listusers  => 'Manage Users',
 5277:                             },
 5278:                 author => {
 5279:                             upload     => 'Upload a File of Co-authors',
 5280:                             singleuser => 'Add/Modify a Co-author',
 5281:                             listusers  => 'Manage Co-authors',
 5282:                             },
 5283:                 course => {
 5284:                             upload     => 'Upload a File of Course Users',
 5285:                             singleuser => 'Add/Modify a Course User',
 5286:                             listusers  => 'List and Modify Multiple Course Users',
 5287:                             },
 5288:                 community => {
 5289:                             upload     => 'Upload a File of Community Users',
 5290:                             singleuser => 'Add/Modify a Community User',
 5291:                             listusers  => 'List and Modify Multiple Community Users',
 5292:                            },
 5293:                 );
 5294:      my %linktitles = (
 5295:                 domain => {
 5296:                             singleuser => 'Add a user to the domain, and/or a course or community in the domain.',
 5297:                             listusers  => 'Show and manage users in this domain.',
 5298:                             },
 5299:                 author => {
 5300:                             singleuser => 'Add a user with a co- or assistant author role.',
 5301:                             listusers  => 'Show and manage co- or assistant authors.',
 5302:                             },
 5303:                 course => {
 5304:                             singleuser => 'Add a user with a certain role to this course.',
 5305:                             listusers  => 'Show and manage users in this course.',
 5306:                             },
 5307:                 community => {
 5308:                             singleuser => 'Add a user with a certain role to this community.',
 5309:                             listusers  => 'Show and manage users in this community.',
 5310:                            },
 5311:                 );
 5312:   my @menu = ( {categorytitle => 'Single Users', 
 5313:          items =>
 5314:          [
 5315:             {
 5316:              linktext => $links{$linkcontext}{'singleuser'},
 5317:              icon => 'edit-redo.png',
 5318:              #help => 'Course_Change_Privileges',
 5319:              url => '/adm/createuser?action=singleuser',
 5320:              permission => $permission->{'cusr'},
 5321:              linktitle => $linktitles{$linkcontext}{'singleuser'},
 5322:             },
 5323:          ]},
 5324: 
 5325:          {categorytitle => 'Multiple Users',
 5326:          items => 
 5327:          [
 5328:             {
 5329:              linktext => $links{$linkcontext}{'upload'},
 5330:              icon => 'uplusr.png',
 5331:              #help => 'Course_Create_Class_List',
 5332:              url => '/adm/createuser?action=upload',
 5333:              permission => $permission->{'cusr'},
 5334:              linktitle => 'Upload a CSV or a text file containing users.',
 5335:             },
 5336:             {
 5337:              linktext => $links{$linkcontext}{'listusers'},
 5338:              icon => 'mngcu.png',
 5339:              #help => 'Course_View_Class_List',
 5340:              url => '/adm/createuser?action=listusers',
 5341:              permission => ($permission->{'view'} || $permission->{'cusr'}),
 5342:              linktitle => $linktitles{$linkcontext}{'listusers'}, 
 5343:             },
 5344: 
 5345:          ]},
 5346: 
 5347:          {categorytitle => 'Administration',
 5348:          items => [ ]},
 5349:        );
 5350:             
 5351:     if ($context eq 'domain'){
 5352:         
 5353:         push(@{ $menu[2]->{items} }, #Category: Administration
 5354:             {
 5355:              linktext => 'Custom Roles',
 5356:              icon => 'emblem-photos.png',
 5357:              #help => 'Course_Editing_Custom_Roles',
 5358:              url => '/adm/createuser?action=custom',
 5359:              permission => $permission->{'custom'},
 5360:              linktitle => 'Configure a custom role.',
 5361:             },
 5362:             {
 5363:              linktext => 'Authoring Space Requests',
 5364:              icon => 'selfenrl-queue.png',
 5365:              #help => 'Domain_Role_Approvals',
 5366:              url => '/adm/createuser?action=processauthorreq',
 5367:              permission => $permission->{'cusr'},
 5368:              linktitle => 'Approve or reject author role requests',
 5369:             },
 5370:             {
 5371:              linktext => 'LON-CAPA Account Requests',
 5372:              icon => 'list-add.png',
 5373:              #help => 'Domain_Username_Approvals',
 5374:              url => '/adm/createuser?action=processusernamereq',
 5375:              permission => $permission->{'cusr'},
 5376:              linktitle => 'Approve or reject LON-CAPA account requests',
 5377:             },
 5378:             {
 5379:              linktext => 'Change Log',
 5380:              icon => 'document-properties.png',
 5381:              #help => 'Course_User_Logs',
 5382:              url => '/adm/createuser?action=changelogs',
 5383:              permission => $permission->{'cusr'},
 5384:              linktitle => 'View change log.',
 5385:             },
 5386:         );
 5387:         
 5388:     }elsif ($context eq 'course'){
 5389:         my ($cnum,$cdom) = &Apache::lonuserutils::get_course_identity();
 5390: 
 5391:         my %linktext = (
 5392:                          'Course'    => {
 5393:                                           single => 'Add/Modify a Student', 
 5394:                                           drop   => 'Drop Students',
 5395:                                           groups => 'Course Groups',
 5396:                                         },
 5397:                          'Community' => {
 5398:                                           single => 'Add/Modify a Member', 
 5399:                                           drop   => 'Drop Members',
 5400:                                           groups => 'Community Groups',
 5401:                                         },
 5402:                        );
 5403: 
 5404:         my %linktitle = (
 5405:             'Course' => {
 5406:                   single => 'Add a user with the role of student to this course',
 5407:                   drop   => 'Remove a student from this course.',
 5408:                   groups => 'Manage course groups',
 5409:                         },
 5410:             'Community' => {
 5411:                   single => 'Add a user with the role of member to this community',
 5412:                   drop   => 'Remove a member from this community.',
 5413:                   groups => 'Manage community groups',
 5414:                            },
 5415:         );
 5416: 
 5417:         push(@{ $menu[0]->{items} }, #Category: Single Users
 5418:             {   
 5419:              linktext => $linktext{$crstype}{'single'},
 5420:              #help => 'Course_Add_Student',
 5421:              icon => 'list-add.png',
 5422:              url => '/adm/createuser?action=singlestudent',
 5423:              permission => $permission->{'cusr'},
 5424:              linktitle => $linktitle{$crstype}{'single'},
 5425:             },
 5426:         );
 5427:         
 5428:         push(@{ $menu[1]->{items} }, #Category: Multiple Users 
 5429:             {
 5430:              linktext => $linktext{$crstype}{'drop'},
 5431:              icon => 'edit-undo.png',
 5432:              #help => 'Course_Drop_Student',
 5433:              url => '/adm/createuser?action=drop',
 5434:              permission => $permission->{'cusr'},
 5435:              linktitle => $linktitle{$crstype}{'drop'},
 5436:             },
 5437:         );
 5438:         push(@{ $menu[2]->{items} }, #Category: Administration
 5439:             {    
 5440:              linktext => 'Custom Roles',
 5441:              icon => 'emblem-photos.png',
 5442:              #help => 'Course_Editing_Custom_Roles',
 5443:              url => '/adm/createuser?action=custom',
 5444:              permission => $permission->{'custom'},
 5445:              linktitle => 'Configure a custom role.',
 5446:             },
 5447:             {
 5448:              linktext => $linktext{$crstype}{'groups'},
 5449:              icon => 'grps.png',
 5450:              #help => 'Course_Manage_Group',
 5451:              url => '/adm/coursegroups?refpage=cusr',
 5452:              permission => $permission->{'grp_manage'},
 5453:              linktitle => $linktitle{$crstype}{'groups'},
 5454:             },
 5455:             {
 5456:              linktext => 'Change Log',
 5457:              icon => 'document-properties.png',
 5458:              #help => 'Course_User_Logs',
 5459:              url => '/adm/createuser?action=changelogs',
 5460:              permission => $permission->{'cusr'},
 5461:              linktitle => 'View change log.',
 5462:             },
 5463:         );
 5464:         if ($env{'course.'.$env{'request.course.id'}.'.internal.selfenroll_approval'}) {
 5465:             push(@{ $menu[2]->{items} },
 5466:                     {
 5467:                      linktext => 'Enrollment Requests',
 5468:                      icon => 'selfenrl-queue.png',
 5469:                      #help => 'Course_Approve_Selfenroll',
 5470:                      url => '/adm/createuser?action=selfenrollqueue',
 5471:                      permission => $permission->{'selfenrolladmin'},
 5472:                      linktitle =>'Approve or reject enrollment requests.',
 5473:                     },
 5474:             );
 5475:         }
 5476:         
 5477:         if (!exists($permission->{'cusr_section'})){
 5478:             if ($crstype ne 'Community') {
 5479:                 push(@{ $menu[2]->{items} },
 5480:                     {
 5481:                      linktext => 'Automated Enrollment',
 5482:                      icon => 'roles.png',
 5483:                      #help => 'Course_Automated_Enrollment',
 5484:                      permission => (&Apache::lonnet::auto_run($cnum,$cdom)
 5485:                                          && $permission->{'cusr'}),
 5486:                      url  => '/adm/populate',
 5487:                      linktitle => 'Automated enrollment manager.',
 5488:                     }
 5489:                 );
 5490:             }
 5491:             push(@{ $menu[2]->{items} }, 
 5492:                 {
 5493:                  linktext => 'User Self-Enrollment',
 5494:                  icon => 'self_enroll.png',
 5495:                  #help => 'Course_Self_Enrollment',
 5496:                  url => '/adm/createuser?action=selfenroll',
 5497:                  permission => $permission->{'selfenrolladmin'},
 5498:                  linktitle => 'Configure user self-enrollment.',
 5499:                 },
 5500:             );
 5501:         }
 5502:     } elsif ($context eq 'author') {
 5503:         push(@{ $menu[2]->{items} }, #Category: Administration
 5504:             {
 5505:              linktext => 'Change Log',
 5506:              icon => 'document-properties.png',
 5507:              #help => 'Course_User_Logs',
 5508:              url => '/adm/createuser?action=changelogs',
 5509:              permission => $permission->{'cusr'},
 5510:              linktitle => 'View change log.',
 5511:             },
 5512:         );
 5513:     }
 5514:     return Apache::lonhtmlcommon::generate_menu(@menu);
 5515: #               { text => 'View Log-in History',
 5516: #                 help => 'Course_User_Logins',
 5517: #                 action => 'logins',
 5518: #                 permission => $permission->{'cusr'},
 5519: #               });
 5520: }
 5521: 
 5522: sub restore_prev_selections {
 5523:     my %saveable_parameters = ('srchby'   => 'scalar',
 5524: 			       'srchin'   => 'scalar',
 5525: 			       'srchtype' => 'scalar',
 5526: 			       );
 5527:     &Apache::loncommon::store_settings('user','user_picker',
 5528: 				       \%saveable_parameters);
 5529:     &Apache::loncommon::restore_settings('user','user_picker',
 5530: 					 \%saveable_parameters);
 5531: }
 5532: 
 5533: sub print_selfenroll_menu {
 5534:     my ($r,$context,$cid,$cdom,$cnum,$currsettings,$additional) = @_;
 5535:     my $crstype = &Apache::loncommon::course_type();
 5536:     my $formname = 'selfenroll';
 5537:     my $nolink = 1;
 5538:     my ($row,$lt) = &Apache::lonuserutils::get_selfenroll_titles();
 5539:     my $groupslist = &Apache::lonuserutils::get_groupslist();
 5540:     my $setsec_js = 
 5541:         &Apache::lonuserutils::setsections_javascript($formname,$groupslist);
 5542:     my %alerts = &Apache::lonlocal::texthash(
 5543:         acto => 'Activation of self-enrollment was selected for the following domain(s)',
 5544:         butn => 'but no user types have been checked.',
 5545:         wilf => "Please uncheck 'activate' or check at least one type.",
 5546:     );
 5547:     my $selfenroll_js = <<"ENDSCRIPT";
 5548: function update_types(caller,num) {
 5549:     var delidx = getIndexByName('selfenroll_delete');
 5550:     var actidx = getIndexByName('selfenroll_activate');
 5551:     if (caller == 'selfenroll_all') {
 5552:         var selall;
 5553:         for (var i=0; i<document.$formname.selfenroll_all.length; i++) {
 5554:             if (document.$formname.selfenroll_all[i].checked) {
 5555:                 selall = document.$formname.selfenroll_all[i].value;
 5556:             }
 5557:         }
 5558:         if (selall == 1) {
 5559:             if (delidx != -1) {
 5560:                 if (document.$formname.selfenroll_delete.length) {
 5561:                     for (var j=0; j<document.$formname.selfenroll_delete.length; j++) {
 5562:                         document.$formname.selfenroll_delete[j].checked = true;
 5563:                     }
 5564:                 } else {
 5565:                     document.$formname.elements[delidx].checked = true;
 5566:                 }
 5567:             }
 5568:             if (actidx != -1) {
 5569:                 if (document.$formname.selfenroll_activate.length) {
 5570:                     for (var j=0; j<document.$formname.selfenroll_activate.length; j++) {
 5571:                         document.$formname.selfenroll_activate[j].checked = false;
 5572:                     }
 5573:                 } else {
 5574:                     document.$formname.elements[actidx].checked = false;
 5575:                 }
 5576:             }
 5577:             document.$formname.selfenroll_newdom.selectedIndex = 0; 
 5578:         }
 5579:     }
 5580:     if (caller == 'selfenroll_activate') {
 5581:         if (document.$formname.selfenroll_activate.length) {
 5582:             for (var j=0; j<document.$formname.selfenroll_activate.length; j++) {
 5583:                 if (document.$formname.selfenroll_activate[j].value == num) {
 5584:                     if (document.$formname.selfenroll_activate[j].checked) {
 5585:                         for (var i=0; i<document.$formname.selfenroll_all.length; i++) {
 5586:                             if (document.$formname.selfenroll_all[i].value == '1') {
 5587:                                 document.$formname.selfenroll_all[i].checked = false;
 5588:                             }
 5589:                             if (document.$formname.selfenroll_all[i].value == '0') {
 5590:                                 document.$formname.selfenroll_all[i].checked = true;
 5591:                             }
 5592:                         }
 5593:                     }
 5594:                 }
 5595:             }
 5596:         } else {
 5597:             for (var i=0; i<document.$formname.selfenroll_all.length; i++) {
 5598:                 if (document.$formname.selfenroll_all[i].value == '1') {
 5599:                     document.$formname.selfenroll_all[i].checked = false;
 5600:                 }
 5601:                 if (document.$formname.selfenroll_all[i].value == '0') {
 5602:                     document.$formname.selfenroll_all[i].checked = true;
 5603:                 }
 5604:             }
 5605:         }
 5606:     }
 5607:     if (caller == 'selfenroll_delete') {
 5608:         if (document.$formname.selfenroll_delete.length) {
 5609:             for (var j=0; j<document.$formname.selfenroll_delete.length; j++) {
 5610:                 if (document.$formname.selfenroll_delete[j].value == num) {
 5611:                     if (document.$formname.selfenroll_delete[j].checked) {
 5612:                         var delindex = getIndexByName('selfenroll_types_'+num);
 5613:                         if (delindex != -1) { 
 5614:                             if (document.$formname.elements[delindex].length) {
 5615:                                 for (var k=0; k<document.$formname.elements[delindex].length; k++) {
 5616:                                     document.$formname.elements[delindex][k].checked = false;
 5617:                                 }
 5618:                             } else {
 5619:                                 document.$formname.elements[delindex].checked = false;
 5620:                             }
 5621:                         }
 5622:                     }
 5623:                 }
 5624:             }
 5625:         } else {
 5626:             if (document.$formname.selfenroll_delete.checked) {
 5627:                 var delindex = getIndexByName('selfenroll_types_'+num);
 5628:                 if (delindex != -1) {
 5629:                     if (document.$formname.elements[delindex].length) {
 5630:                         for (var k=0; k<document.$formname.elements[delindex].length; k++) {
 5631:                             document.$formname.elements[delindex][k].checked = false;
 5632:                         }
 5633:                     } else {
 5634:                         document.$formname.elements[delindex].checked = false;
 5635:                     }
 5636:                 }
 5637:             }
 5638:         }
 5639:     }
 5640:     return;
 5641: }
 5642: 
 5643: function validate_types(form) {
 5644:     var needaction = new Array();
 5645:     var countfail = 0;
 5646:     var actidx = getIndexByName('selfenroll_activate');
 5647:     if (actidx != -1) {
 5648:         if (document.$formname.selfenroll_activate.length) {
 5649:             for (var j=0; j<document.$formname.selfenroll_activate.length; j++) {
 5650:                 var num = document.$formname.selfenroll_activate[j].value;
 5651:                 if (document.$formname.selfenroll_activate[j].checked) {
 5652:                     countfail = check_types(num,countfail,needaction)
 5653:                 }
 5654:             }
 5655:         } else {
 5656:             if (document.$formname.selfenroll_activate.checked) {
 5657:                 var num = document.$formname.selfenroll_activate.value;
 5658:                 countfail = check_types(num,countfail,needaction)
 5659:             }
 5660:         }
 5661:     }
 5662:     if (countfail > 0) {
 5663:         var msg = "$alerts{'acto'}\\n";
 5664:         var loopend = needaction.length -1;
 5665:         if (loopend > 0) {
 5666:             for (var m=0; m<loopend; m++) {
 5667:                 msg += needaction[m]+", ";
 5668:             }
 5669:         }
 5670:         msg += needaction[loopend]+"\\n$alerts{'butn'}\\n$alerts{'wilf'}";
 5671:         alert(msg);
 5672:         return; 
 5673:     }
 5674:     setSections(form);
 5675: }
 5676: 
 5677: function check_types(num,countfail,needaction) {
 5678:     var typeidx = getIndexByName('selfenroll_types_'+num);
 5679:     var count = 0;
 5680:     if (typeidx != -1) {
 5681:         if (document.$formname.elements[typeidx].length) {
 5682:             for (var k=0; k<document.$formname.elements[typeidx].length; k++) {
 5683:                 if (document.$formname.elements[typeidx][k].checked) {
 5684:                     count ++;
 5685:                 }
 5686:             }
 5687:         } else {
 5688:             if (document.$formname.elements[typeidx].checked) {
 5689:                 count ++;
 5690:             }
 5691:         }
 5692:         if (count == 0) {
 5693:             var domidx = getIndexByName('selfenroll_dom_'+num);
 5694:             if (domidx != -1) {
 5695:                 var domname = document.$formname.elements[domidx].value;
 5696:                 needaction[countfail] = domname;
 5697:                 countfail ++;
 5698:             }
 5699:         }
 5700:     }
 5701:     return countfail;
 5702: }
 5703: 
 5704: function toggleNotify() {
 5705:     var selfenrollApproval = 0;
 5706:     if (document.$formname.selfenroll_approval.length) {
 5707:         for (var i=0; i<document.$formname.selfenroll_approval.length; i++) {
 5708:             if (document.$formname.selfenroll_approval[i].checked) {
 5709:                 selfenrollApproval = document.$formname.selfenroll_approval[i].value;
 5710:                 break;        
 5711:             }
 5712:         }
 5713:     }
 5714:     if (document.getElementById('notified')) {
 5715:         if (selfenrollApproval == 0) {
 5716:             document.getElementById('notified').style.display='none';
 5717:         } else {
 5718:             document.getElementById('notified').style.display='block';
 5719:         }
 5720:     }
 5721:     return;
 5722: }
 5723: 
 5724: function getIndexByName(item) {
 5725:     for (var i=0;i<document.$formname.elements.length;i++) {
 5726:         if (document.$formname.elements[i].name == item) {
 5727:             return i;
 5728:         }
 5729:     }
 5730:     return -1;
 5731: }
 5732: ENDSCRIPT
 5733: 
 5734:     my $output = '<script type="text/javascript">'."\n".
 5735:                  '// <![CDATA['."\n".
 5736:                  $setsec_js."\n".$selfenroll_js."\n".
 5737:                  '// ]]>'."\n".
 5738:                  '</script>'."\n".
 5739:                  '<h3>'.$lt->{'selfenroll'}.'</h3>'."\n";
 5740:  
 5741:     my $visactions = &cat_visibility();
 5742:     my ($cathash,%cattype);
 5743:     my %domconfig = &Apache::lonnet::get_dom('configuration',['coursecategories'],$cdom);
 5744:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 5745:         $cathash = $domconfig{'coursecategories'}{'cats'};
 5746:         $cattype{'auth'} = $domconfig{'coursecategories'}{'auth'};
 5747:         $cattype{'unauth'} = $domconfig{'coursecategories'}{'unauth'};
 5748:     } else {
 5749:         $cathash = {};
 5750:         $cattype{'auth'} = 'std';
 5751:         $cattype{'unauth'} = 'std';
 5752:     }
 5753:     if (($cattype{'auth'} eq 'none') && ($cattype{'unauth'} eq 'none')) {
 5754:         $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
 5755:                   '<br />'.
 5756:                   '<br />'.$visactions->{'take'}.'<ul>'.
 5757:                   '<li>'.$visactions->{'dc_chgconf'}.'</li>'.
 5758:                   '</ul>');
 5759:     } elsif (($cattype{'auth'} !~ /^(std|domonly)$/) && ($cattype{'unauth'} !~ /^(std|domonly)$/)) {
 5760:         if ($currsettings->{'uniquecode'}) {
 5761:             $r->print('<span class="LC_info">'.$visactions->{'vis'}.'</span>');
 5762:         } else {
 5763:             $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
 5764:                   '<br />'.
 5765:                   '<br />'.$visactions->{'take'}.'<ul>'.
 5766:                   '<li>'.$visactions->{'dc_setcode'}.'</li>'.
 5767:                   '</ul><br />');
 5768:         }
 5769:     } else {
 5770:         my ($visible,$cansetvis,$vismsgs) = &visible_in_stdcat($cdom,$cnum,\%domconfig);
 5771:         if (ref($visactions) eq 'HASH') {
 5772:             if ($visible) {
 5773:                 $output .= '<p class="LC_info">'.$visactions->{'vis'}.'</p>';
 5774:            } else {
 5775:                 $output .= '<p class="LC_warning">'.$visactions->{'miss'}.'</p>'
 5776:                           .$visactions->{'yous'}.
 5777:                            '<p>'.$visactions->{'gen'}.'<br />'.$visactions->{'coca'};
 5778:                 if (ref($vismsgs) eq 'ARRAY') {
 5779:                     $output .= '<br />'.$visactions->{'make'}.'<ul>';
 5780:                     foreach my $item (@{$vismsgs}) {
 5781:                         $output .= '<li>'.$visactions->{$item}.'</li>';
 5782:                     }
 5783:                     $output .= '</ul>';
 5784:                 }
 5785:                 $output .= '</p>';
 5786:             }
 5787:         }
 5788:     }
 5789:     my $actionhref = '/adm/createuser';
 5790:     if ($context eq 'domain') {
 5791:         $actionhref = '/adm/modifycourse';
 5792:     }
 5793: 
 5794:     my %noedit;
 5795:     unless ($context eq 'domain') {
 5796:         %noedit = &get_noedit_fields($cdom,$cnum,$crstype,$row);
 5797:     }
 5798:     $output .= '<form name="'.$formname.'" method="post" action="'.$actionhref.'">'."\n".
 5799:                &Apache::lonhtmlcommon::start_pick_box();
 5800:     if (ref($row) eq 'ARRAY') {
 5801:         foreach my $item (@{$row}) {
 5802:             my $title = $item; 
 5803:             if (ref($lt) eq 'HASH') {
 5804:                 $title = $lt->{$item};
 5805:             }
 5806:             $output .= &Apache::lonhtmlcommon::row_title($title);
 5807:             if ($item eq 'types') {
 5808:                 my $curr_types;
 5809:                 if (ref($currsettings) eq 'HASH') {
 5810:                     $curr_types = $currsettings->{'selfenroll_types'};
 5811:                 }
 5812:                 if ($noedit{$item}) {
 5813:                     if ($curr_types eq '*') {
 5814:                         $output .= &mt('Any user in any domain');   
 5815:                     } else {
 5816:                         my @entries = split(/;/,$curr_types);
 5817:                         if (@entries > 0) {
 5818:                             $output .= '<ul>'; 
 5819:                             foreach my $entry (@entries) {
 5820:                                 my ($currdom,$typestr) = split(/:/,$entry);
 5821:                                 next if ($typestr eq '');
 5822:                                 my $domdesc = &Apache::lonnet::domain($currdom);
 5823:                                 my @currinsttypes = split(',',$typestr);
 5824:                                 my ($othertitle,$usertypes,$types) = 
 5825:                                     &Apache::loncommon::sorted_inst_types($currdom);
 5826:                                 if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 5827:                                     $usertypes->{'any'} = &mt('any user'); 
 5828:                                     if (keys(%{$usertypes}) > 0) {
 5829:                                         $usertypes->{'other'} = &mt('other users');
 5830:                                     }
 5831:                                     my @longinsttypes = map { $usertypes->{$_}; } @currinsttypes;
 5832:                                     $output .= '<li>'.$domdesc.':'.join(', ',@longinsttypes).'</li>';
 5833:                                  }
 5834:                             }
 5835:                             $output .= '</ul>';
 5836:                         } else {
 5837:                             $output .= &mt('None');
 5838:                         }
 5839:                     }
 5840:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 5841:                     next;
 5842:                 }
 5843:                 my $showdomdesc = 1;
 5844:                 my $includeempty = 1;
 5845:                 my $num = 0;
 5846:                 $output .= &Apache::loncommon::start_data_table().
 5847:                            &Apache::loncommon::start_data_table_row()
 5848:                            .'<td colspan="2"><span class="LC_nobreak"><label>'
 5849:                            .&mt('Any user in any domain:')
 5850:                            .'&nbsp;<input type="radio" name="selfenroll_all" value="1" ';
 5851:                 if ($curr_types eq '*') {
 5852:                     $output .= ' checked="checked" '; 
 5853:                 }
 5854:                 $output .= 'onchange="javascript:update_types('.
 5855:                            "'selfenroll_all'".');" />'.&mt('Yes').'</label>'.
 5856:                            '&nbsp;&nbsp;<input type="radio" name="selfenroll_all" value="0" ';
 5857:                 if ($curr_types ne '*') {
 5858:                     $output .= ' checked="checked" ';
 5859:                 }
 5860:                 $output .= ' onchange="javascript:update_types('.
 5861:                            "'selfenroll_all'".');"/>'.&mt('No').'</label></td>'.
 5862:                            &Apache::loncommon::end_data_table_row().
 5863:                            &Apache::loncommon::end_data_table().
 5864:                            &mt('Or').'<br />'.
 5865:                            &Apache::loncommon::start_data_table();
 5866:                 my %currdoms;
 5867:                 if ($curr_types eq '') {
 5868:                     $output .= &new_selfenroll_dom_row($cdom,'0');
 5869:                 } elsif ($curr_types ne '*') {
 5870:                     my @entries = split(/;/,$curr_types);
 5871:                     if (@entries > 0) {
 5872:                         foreach my $entry (@entries) {
 5873:                             my ($currdom,$typestr) = split(/:/,$entry);
 5874:                             $currdoms{$currdom} = 1;
 5875:                             my $domdesc = &Apache::lonnet::domain($currdom);
 5876:                             my @currinsttypes = split(',',$typestr);
 5877:                             $output .= &Apache::loncommon::start_data_table_row()
 5878:                                        .'<td valign="top"><span class="LC_nobreak">'.&mt('Domain:').'<b>'
 5879:                                        .'&nbsp;'.$domdesc.' ('.$currdom.')'
 5880:                                        .'</b><input type="hidden" name="selfenroll_dom_'.$num
 5881:                                        .'" value="'.$currdom.'" /></span><br />'
 5882:                                        .'<span class="LC_nobreak"><label><input type="checkbox" '
 5883:                                        .'name="selfenroll_delete" value="'.$num.'" onchange="javascript:update_types('."'selfenroll_delete','$num'".');" />'
 5884:                                        .&mt('Delete').'</label></span></td>';
 5885:                             $output .= '<td valign="top">&nbsp;&nbsp;'.&mt('User types:').'<br />'
 5886:                                        .&selfenroll_inst_types($num,$currdom,\@currinsttypes).'</td>'
 5887:                                        .&Apache::loncommon::end_data_table_row();
 5888:                             $num ++;
 5889:                         }
 5890:                     }
 5891:                 }
 5892:                 my $add_domtitle = &mt('Users in additional domain:');
 5893:                 if ($curr_types eq '*') { 
 5894:                     $add_domtitle = &mt('Users in specific domain:');
 5895:                 } elsif ($curr_types eq '') {
 5896:                     $add_domtitle = &mt('Users in other domain:');
 5897:                 }
 5898:                 $output .= &Apache::loncommon::start_data_table_row()
 5899:                            .'<td colspan="2"><span class="LC_nobreak">'.$add_domtitle.'</span><br />'
 5900:                            .&Apache::loncommon::select_dom_form('','selfenroll_newdom',
 5901:                                                                 $includeempty,$showdomdesc)
 5902:                            .'<input type="hidden" name="selfenroll_types_total" value="'.$num.'" />'
 5903:                            .'</td>'.&Apache::loncommon::end_data_table_row()
 5904:                            .&Apache::loncommon::end_data_table();
 5905:             } elsif ($item eq 'registered') {
 5906:                 my ($regon,$regoff);
 5907:                 my $registered;
 5908:                 if (ref($currsettings) eq 'HASH') {
 5909:                     $registered = $currsettings->{'selfenroll_registered'};
 5910:                 }
 5911:                 if ($noedit{$item}) {
 5912:                     if ($registered) {
 5913:                         $output .= &mt('Must be registered in course');
 5914:                     } else {
 5915:                         $output .= &mt('No requirement');
 5916:                     }
 5917:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 5918:                     next;
 5919:                 }
 5920:                 if ($registered) {
 5921:                     $regon = ' checked="checked" ';
 5922:                     $regoff = ' ';
 5923:                 } else {
 5924:                     $regon = ' ';
 5925:                     $regoff = ' checked="checked" ';
 5926:                 }
 5927:                 $output .= '<label>'.
 5928:                            '<input type="radio" name="selfenroll_registered" value="1"'.$regon.'/>'.
 5929:                            &mt('Yes').'</label>&nbsp;&nbsp;<label>'.
 5930:                            '<input type="radio" name="selfenroll_registered" value="0"'.$regoff.'/>'.
 5931:                            &mt('No').'</label>';
 5932:             } elsif ($item eq 'enroll_dates') {
 5933:                 my ($starttime,$endtime);
 5934:                 if (ref($currsettings) eq 'HASH') {
 5935:                     $starttime = $currsettings->{'selfenroll_start_date'};
 5936:                     $endtime = $currsettings->{'selfenroll_end_date'};
 5937:                     if ($starttime eq '') {
 5938:                         $starttime = $currsettings->{'default_enrollment_start_date'};
 5939:                     }
 5940:                     if ($endtime eq '') {
 5941:                         $endtime = $currsettings->{'default_enrollment_end_date'};
 5942:                     }
 5943:                 }
 5944:                 if ($noedit{$item}) {
 5945:                     $output .= &mt('From: [_1], to: [_2]',&Apache::lonlocal::locallocaltime($starttime),
 5946:                                                           &Apache::lonlocal::locallocaltime($endtime));
 5947:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 5948:                     next;
 5949:                 }
 5950:                 my $startform =
 5951:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_start_date',$starttime,
 5952:                                       undef,undef,undef,undef,undef,undef,undef,$nolink);
 5953:                 my $endform =
 5954:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_end_date',$endtime,
 5955:                                       undef,undef,undef,undef,undef,undef,undef,$nolink);
 5956:                 $output .= &selfenroll_date_forms($startform,$endform);
 5957:             } elsif ($item eq 'access_dates') {
 5958:                 my ($starttime,$endtime);
 5959:                 if (ref($currsettings) eq 'HASH') {
 5960:                     $starttime = $currsettings->{'selfenroll_start_access'};
 5961:                     $endtime = $currsettings->{'selfenroll_end_access'};
 5962:                     if ($starttime eq '') {
 5963:                         $starttime = $currsettings->{'default_enrollment_start_date'};
 5964:                     }
 5965:                     if ($endtime eq '') {
 5966:                         $endtime = $currsettings->{'default_enrollment_end_date'};
 5967:                     }
 5968:                 }
 5969:                 if ($noedit{$item}) {
 5970:                     $output .= &mt('From: [_1], to: [_2]',&Apache::lonlocal::locallocaltime($starttime),
 5971:                                                           &Apache::lonlocal::locallocaltime($endtime));
 5972:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 5973:                     next;
 5974:                 }
 5975:                 my $startform =
 5976:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_start_access',$starttime,
 5977:                                       undef,undef,undef,undef,undef,undef,undef,$nolink);
 5978:                 my $endform =
 5979:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_end_access',$endtime,
 5980:                                       undef,undef,undef,undef,undef,undef,undef,$nolink);
 5981:                 $output .= &selfenroll_date_forms($startform,$endform);
 5982:             } elsif ($item eq 'section') {
 5983:                 my $currsec;
 5984:                 if (ref($currsettings) eq 'HASH') {
 5985:                     $currsec = $currsettings->{'selfenroll_section'};
 5986:                 }
 5987:                 my %sections_count = &Apache::loncommon::get_sections($cdom,$cnum);
 5988:                 my $newsecval;
 5989:                 if ($currsec ne 'none' && $currsec ne '') {
 5990:                     if (!defined($sections_count{$currsec})) {
 5991:                         $newsecval = $currsec;
 5992:                     }
 5993:                 }
 5994:                 if ($noedit{$item}) {
 5995:                     if ($currsec ne '') {
 5996:                         $output .= $currsec;
 5997:                     } else {
 5998:                         $output .= &mt('No specific section');
 5999:                     }
 6000:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 6001:                     next;
 6002:                 }
 6003:                 my $sections_select = 
 6004:                     &Apache::lonuserutils::course_sections(\%sections_count,'st',$currsec);
 6005:                 $output .= '<table class="LC_createuser">'."\n".
 6006:                            '<tr class="LC_section_row">'."\n".
 6007:                            '<td align="center">'.&mt('Existing sections')."\n".
 6008:                            '<br />'.$sections_select.'</td><td align="center">'.
 6009:                            &mt('New section').'<br />'."\n".
 6010:                            '<input type="text" name="newsec" size="15" value="'.$newsecval.'" />'."\n".
 6011:                            '<input type="hidden" name="sections" value="" />'."\n".
 6012:                            '</td></tr></table>'."\n";
 6013:             } elsif ($item eq 'approval') {
 6014:                 my ($currnotified,$currapproval,%appchecked);
 6015:                 my %selfdescs = &Apache::lonuserutils::selfenroll_default_descs();
 6016:                 if (ref($currsettings) eq 'HASH') { 
 6017:                     $currnotified = $currsettings->{'selfenroll_notifylist'};
 6018:                     $currapproval = $currsettings->{'selfenroll_approval'};
 6019:                 }
 6020:                 if ($currapproval !~ /^[012]$/) {
 6021:                     $currapproval = 0;
 6022:                 }
 6023:                 if ($noedit{$item}) {
 6024:                     $output .=  $selfdescs{'approval'}{$currapproval}.
 6025:                                 '<br />'.&mt('(Set by Domain Coordinator)');
 6026:                     next;
 6027:                 }
 6028:                 $appchecked{$currapproval} = ' checked="checked"';
 6029:                 for my $i (0..2) {
 6030:                     $output .= '<label>'.
 6031:                                '<input type="radio" name="selfenroll_approval" value="'.$i.'"'.
 6032:                                $appchecked{$i}.' onclick="toggleNotify();" />'.$selfdescs{'approval'}{$i}.
 6033:                                '</label>'.('&nbsp;'x2);
 6034:                 }
 6035:                 my %advhash = &Apache::lonnet::get_course_adv_roles($cid,1);
 6036:                 my (@ccs,%notified);
 6037:                 my $ccrole = 'cc';
 6038:                 if ($crstype eq 'Community') {
 6039:                     $ccrole = 'co';
 6040:                 }
 6041:                 if ($advhash{$ccrole}) {
 6042:                     @ccs = split(/,/,$advhash{$ccrole});
 6043:                 }
 6044:                 if ($currnotified) {
 6045:                     foreach my $current (split(/,/,$currnotified)) {
 6046:                         $notified{$current} = 1;
 6047:                         if (!grep(/^\Q$current\E$/,@ccs)) {
 6048:                             push(@ccs,$current);
 6049:                         }
 6050:                     }
 6051:                 }
 6052:                 if (@ccs) {
 6053:                     my $style;
 6054:                     unless ($currapproval) {
 6055:                         $style = ' style="display: none;"'; 
 6056:                     }
 6057:                     $output .= '<br /><div id="notified"'.$style.'>'.
 6058:                                &mt('Personnel to be notified when an enrollment request needs approval, or has been approved:').'&nbsp;'.
 6059:                                &Apache::loncommon::start_data_table().
 6060:                                &Apache::loncommon::start_data_table_row();
 6061:                     my $count = 0;
 6062:                     my $numcols = 4;
 6063:                     foreach my $cc (sort(@ccs)) {
 6064:                         my $notifyon;
 6065:                         my ($ccuname,$ccudom) = split(/:/,$cc);
 6066:                         if ($notified{$cc}) {
 6067:                             $notifyon = ' checked="checked" ';
 6068:                         }
 6069:                         if ($count && !$count%$numcols) {
 6070:                             $output .= &Apache::loncommon::end_data_table_row().
 6071:                                        &Apache::loncommon::start_data_table_row()
 6072:                         }
 6073:                         $output .= '<td><span class="LC_nobreak"><label>'.
 6074:                                    '<input type="checkbox" name="selfenroll_notify"'.$notifyon.' value="'.$cc.'" />'.
 6075:                                    &Apache::loncommon::plainname($ccuname,$ccudom).
 6076:                                    '</label></span></td>';
 6077:                         $count ++;
 6078:                     }
 6079:                     my $rem = $count%$numcols;
 6080:                     if ($rem) {
 6081:                         my $emptycols = $numcols - $rem;
 6082:                         for (my $i=0; $i<$emptycols; $i++) { 
 6083:                             $output .= '<td>&nbsp;</td>';
 6084:                         }
 6085:                     }
 6086:                     $output .= &Apache::loncommon::end_data_table_row().
 6087:                                &Apache::loncommon::end_data_table().
 6088:                                '</div>';
 6089:                 }
 6090:             } elsif ($item eq 'limit') {
 6091:                 my ($crslimit,$selflimit,$nolimit,$currlim,$currcap);
 6092:                 if (ref($currsettings) eq 'HASH') {
 6093:                     $currlim = $currsettings->{'selfenroll_limit'};
 6094:                     $currcap = $currsettings->{'selfenroll_cap'};
 6095:                 }
 6096:                 if ($noedit{$item}) {
 6097:                     if (($currlim eq 'allstudents') || ($currlim eq 'selfenrolled')) {
 6098:                         if ($currlim eq 'allstudents') {
 6099:                             $output .= &mt('Limit by total students');
 6100:                         } elsif ($currlim eq 'selfenrolled') {
 6101:                             $output .= &mt('Limit by total self-enrolled students');
 6102:                         }
 6103:                         $output .= ' '.&mt('Maximum: [_1]',$currcap).
 6104:                                    '<br />'.&mt('(Set by Domain Coordinator)');
 6105:                     } else {
 6106:                         $output .= &mt('No limit').'<br />'.&mt('(Set by Domain Coordinator)');
 6107:                     }
 6108:                     next;
 6109:                 }
 6110:                 if ($currlim eq 'allstudents') {
 6111:                     $crslimit = ' checked="checked" ';
 6112:                     $selflimit = ' ';
 6113:                     $nolimit = ' ';
 6114:                 } elsif ($currlim eq 'selfenrolled') {
 6115:                     $crslimit = ' ';
 6116:                     $selflimit = ' checked="checked" ';
 6117:                     $nolimit = ' '; 
 6118:                 } else {
 6119:                     $crslimit = ' ';
 6120:                     $selflimit = ' ';
 6121:                     $nolimit = ' checked="checked" ';
 6122:                 }
 6123:                 $output .= '<table><tr><td><label>'.
 6124:                            '<input type="radio" name="selfenroll_limit" value="none"'.$nolimit.'/>'.
 6125:                            &mt('No limit').'</label></td><td><label>'.
 6126:                            '<input type="radio" name="selfenroll_limit" value="allstudents"'.$crslimit.'/>'.
 6127:                            &mt('Limit by total students').'</label></td><td><label>'.
 6128:                            '<input type="radio" name="selfenroll_limit" value="selfenrolled"'.$selflimit.'/>'.
 6129:                            &mt('Limit by total self-enrolled students').
 6130:                            '</td></tr><tr>'.
 6131:                            '<td>&nbsp;</td><td colspan="2"><span class="LC_nobreak">'.
 6132:                            ('&nbsp;'x3).&mt('Maximum number allowed: ').
 6133:                            '<input type="text" name="selfenroll_cap" size = "5" value="'.$currcap.'" /></td></tr></table>';
 6134:             }
 6135:             $output .= &Apache::lonhtmlcommon::row_closure(1);
 6136:         }
 6137:     }
 6138:     $output .= &Apache::lonhtmlcommon::end_pick_box().
 6139:                '<br /><input type="button" name="selfenrollconf" value="'
 6140:                .&mt('Save').'" onclick="validate_types(this.form);" />'
 6141:                .'<input type="hidden" name="action" value="selfenroll" />'
 6142:                .'<input type="hidden" name="state" value="done" />'."\n".
 6143:                $additional.'</form>';
 6144:     $r->print($output);
 6145:     return;
 6146: }
 6147: 
 6148: sub get_noedit_fields {
 6149:     my ($cdom,$cnum,$crstype,$row) = @_;
 6150:     my %noedit;
 6151:     if (ref($row) eq 'ARRAY') {
 6152:         my %settings = &Apache::lonnet::get('environment',['internal.coursecode','internal.textbook',
 6153:                                                            'internal.selfenrollmgrdc',
 6154:                                                            'internal.selfenrollmgrcc'],$cdom,$cnum);
 6155:         my $type = &Apache::lonuserutils::get_extended_type($cdom,$cnum,$crstype,\%settings);
 6156:         my (%specific_managebydc,%specific_managebycc,%default_managebydc);
 6157:         map { $specific_managebydc{$_} = 1; } (split(/,/,$settings{'internal.selfenrollmgrdc'}));
 6158:         map { $specific_managebycc{$_} = 1; } (split(/,/,$settings{'internal.selfenrollmgrcc'}));
 6159:         my %domdefaults = &Apache::lonnet::get_domain_defaults($cdom);
 6160:         map { $default_managebydc{$_} = 1; } (split(/,/,$domdefaults{$type.'selfenrolladmdc'}));
 6161: 
 6162:         foreach my $item (@{$row}) {
 6163:             next if ($specific_managebycc{$item});
 6164:             if (($specific_managebydc{$item}) || ($default_managebydc{$item})) {
 6165:                 $noedit{$item} = 1;
 6166:             }
 6167:         }
 6168:     }
 6169:     return %noedit;
 6170: } 
 6171: 
 6172: sub visible_in_stdcat {
 6173:     my ($cdom,$cnum,$domconf) = @_;
 6174:     my ($cathash,%settable,@vismsgs,$cansetvis,$visible);
 6175:     unless (ref($domconf) eq 'HASH') {
 6176:         return ($visible,$cansetvis,\@vismsgs);
 6177:     }
 6178:     if (ref($domconf->{'coursecategories'}) eq 'HASH') {
 6179:         if ($domconf->{'coursecategories'}{'togglecats'} eq 'crs') {
 6180:             $settable{'togglecats'} = 1;
 6181:         }
 6182:         if ($domconf->{'coursecategories'}{'categorize'} eq 'crs') {
 6183:             $settable{'categorize'} = 1;
 6184:         }
 6185:         $cathash = $domconf->{'coursecategories'}{'cats'};
 6186:     }
 6187:     if ($settable{'togglecats'} && $settable{'categorize'}) {
 6188:         $cansetvis = &mt('You are able to both assign a course category and choose to exclude this course from the catalog.');   
 6189:     } elsif ($settable{'togglecats'}) {
 6190:         $cansetvis = &mt('You are able to choose to exclude this course from the catalog, but only a Domain Coordinator may assign a course category.'); 
 6191:     } elsif ($settable{'categorize'}) {
 6192:         $cansetvis = &mt('You may assign a course category, but only a Domain Coordinator may choose to exclude this course from the catalog.');  
 6193:     } else {
 6194:         $cansetvis = &mt('Only a Domain Coordinator may assign a course category or choose to exclude this course from the catalog.'); 
 6195:     }
 6196:      
 6197:     my %currsettings =
 6198:         &Apache::lonnet::get('environment',['hidefromcat','categories','internal.coursecode'],
 6199:                              $cdom,$cnum);
 6200:     $visible = 0;
 6201:     if ($currsettings{'internal.coursecode'} ne '') {
 6202:         if (ref($domconf->{'coursecategories'}) eq 'HASH') {
 6203:             $cathash = $domconf->{'coursecategories'}{'cats'};
 6204:             if (ref($cathash) eq 'HASH') {
 6205:                 if ($cathash->{'instcode::0'} eq '') {
 6206:                     push(@vismsgs,'dc_addinst'); 
 6207:                 } else {
 6208:                     $visible = 1;
 6209:                 }
 6210:             } else {
 6211:                 $visible = 1;
 6212:             }
 6213:         } else {
 6214:             $visible = 1;
 6215:         }
 6216:     } else {
 6217:         if (ref($cathash) eq 'HASH') {
 6218:             if ($cathash->{'instcode::0'} ne '') {
 6219:                 push(@vismsgs,'dc_instcode');
 6220:             }
 6221:         } else {
 6222:             push(@vismsgs,'dc_instcode');
 6223:         }
 6224:     }
 6225:     if ($currsettings{'categories'} ne '') {
 6226:         my $cathash;
 6227:         if (ref($domconf->{'coursecategories'}) eq 'HASH') {
 6228:             $cathash = $domconf->{'coursecategories'}{'cats'};
 6229:             if (ref($cathash) eq 'HASH') {
 6230:                 if (keys(%{$cathash}) == 0) {
 6231:                     push(@vismsgs,'dc_catalog');
 6232:                 } elsif ((keys(%{$cathash}) == 1) && ($cathash->{'instcode::0'} ne '')) {
 6233:                     push(@vismsgs,'dc_categories');
 6234:                 } else {
 6235:                     my @currcategories = split('&',$currsettings{'categories'});
 6236:                     my $matched = 0;
 6237:                     foreach my $cat (@currcategories) {
 6238:                         if ($cathash->{$cat} ne '') {
 6239:                             $visible = 1;
 6240:                             $matched = 1;
 6241:                             last;
 6242:                         }
 6243:                     }
 6244:                     if (!$matched) {
 6245:                         if ($settable{'categorize'}) { 
 6246:                             push(@vismsgs,'chgcat');
 6247:                         } else {
 6248:                             push(@vismsgs,'dc_chgcat');
 6249:                         }
 6250:                     }
 6251:                 }
 6252:             }
 6253:         }
 6254:     } else {
 6255:         if (ref($cathash) eq 'HASH') {
 6256:             if ((keys(%{$cathash}) > 1) || 
 6257:                 (keys(%{$cathash}) == 1) && ($cathash->{'instcode::0'} eq '')) {
 6258:                 if ($settable{'categorize'}) {
 6259:                     push(@vismsgs,'addcat');
 6260:                 } else {
 6261:                     push(@vismsgs,'dc_addcat');
 6262:                 }
 6263:             }
 6264:         }
 6265:     }
 6266:     if ($currsettings{'hidefromcat'} eq 'yes') {
 6267:         $visible = 0;
 6268:         if ($settable{'togglecats'}) {
 6269:             unshift(@vismsgs,'unhide');
 6270:         } else {
 6271:             unshift(@vismsgs,'dc_unhide')
 6272:         }
 6273:     }
 6274:     return ($visible,$cansetvis,\@vismsgs);
 6275: }
 6276: 
 6277: sub cat_visibility {
 6278:     my %visactions = &Apache::lonlocal::texthash(
 6279:                    vis => 'This course/community currently appears in the Course/Community Catalog for this domain.',
 6280:                    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.',
 6281:                    miss => 'This course/community does not currently appear in the Course/Community Catalog for this domain.',
 6282:                    none => 'Display of a course catalog is disabled for this domain.',
 6283:                    yous => 'You should remedy this if you plan to allow self-enrollment, otherwise students will have difficulty finding this course.',
 6284:                    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.',
 6285:                    make => 'Make any changes to self-enrollment settings below, click "Save", then take action to include the course in the Catalog:',
 6286:                    take => 'Take the following action to ensure the course appears in the Catalog:',
 6287:                    dc_chgconf => 'Ask a domain coordinator to change the Catalog type for this domain.',
 6288:                    dc_setcode => 'Ask a domain coordinator to assign a six character code to the course',
 6289:                    dc_unhide  => 'Ask a domain coordinator to change the "Exclude from course catalog" setting.',
 6290:                    dc_addinst => 'Ask a domain coordinator to enable display the catalog of "Official courses (with institutional codes)".',
 6291:                    dc_instcode => 'Ask a domain coordinator to assign an institutional code (if this is an official course).',
 6292:                    dc_catalog  => 'Ask a domain coordinator to enable or create at least one course category in the domain.',
 6293:                    dc_categories => 'Ask a domain coordinator to create a hierarchy of categories and sub categories for courses in the domain.',
 6294:                    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',
 6295:                    dc_addcat => 'Ask a domain coordinator to assign a category to the course.',
 6296:     );
 6297:     $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>"');
 6298:     $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>"');
 6299:     $visactions{'addcat'} = &mt('Use [_1]Categorize course[_2] to assign a category to the course.','"<a href="/adm/courseprefs?phase=display&actions=courseinfo">','</a>"');
 6300:     return \%visactions;
 6301: }
 6302: 
 6303: sub new_selfenroll_dom_row {
 6304:     my ($newdom,$num) = @_;
 6305:     my $domdesc = &Apache::lonnet::domain($newdom);
 6306:     my $output;
 6307:     if ($domdesc ne '') {
 6308:         $output .= &Apache::loncommon::start_data_table_row()
 6309:                    .'<td valign="top"><span class="LC_nobreak">'.&mt('Domain:').'&nbsp;<b>'.$domdesc
 6310:                    .' ('.$newdom.')</b><input type="hidden" name="selfenroll_dom_'.$num
 6311:                    .'" value="'.$newdom.'" /></span><br />'
 6312:                    .'<span class="LC_nobreak"><label><input type="checkbox" '
 6313:                    .'name="selfenroll_activate" value="'.$num.'" '
 6314:                    .'onchange="javascript:update_types('
 6315:                    ."'selfenroll_activate','$num'".');" />'
 6316:                    .&mt('Activate').'</label></span></td>';
 6317:         my @currinsttypes;
 6318:         $output .= '<td>'.&mt('User types:').'<br />'
 6319:                    .&selfenroll_inst_types($num,$newdom,\@currinsttypes).'</td>'
 6320:                    .&Apache::loncommon::end_data_table_row();
 6321:     }
 6322:     return $output;
 6323: }
 6324: 
 6325: sub selfenroll_inst_types {
 6326:     my ($num,$currdom,$currinsttypes) = @_;
 6327:     my $output;
 6328:     my $numinrow = 4;
 6329:     my $count = 0;
 6330:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($currdom);
 6331:     my $othervalue = 'any';
 6332:     if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 6333:         if (keys(%{$usertypes}) > 0) {
 6334:             $othervalue = 'other';
 6335:         }
 6336:         $output .= '<table><tr>';
 6337:         foreach my $type (@{$types}) {
 6338:             if (($count > 0) && ($count%$numinrow == 0)) {
 6339:                 $output .= '</tr><tr>';
 6340:             }
 6341:             if (defined($usertypes->{$type})) {
 6342:                 my $esc_type = &escape($type);
 6343:                 $output .= '<td><span class="LC_nobreak"><label><input type = "checkbox" value="'.
 6344:                            $esc_type.'" ';
 6345:                 if (ref($currinsttypes) eq 'ARRAY') {
 6346:                     if (@{$currinsttypes} > 0) {
 6347:                         if (grep(/^any$/,@{$currinsttypes})) {
 6348:                             $output .= 'checked="checked"';
 6349:                         } elsif (grep(/^\Q$esc_type\E$/,@{$currinsttypes})) {
 6350:                             $output .= 'checked="checked"';
 6351:                         }
 6352:                     } else {
 6353:                         $output .= 'checked="checked"';
 6354:                     }
 6355:                 }
 6356:                 $output .= ' name="selfenroll_types_'.$num.'" />'.$usertypes->{$type}.'</label></span></td>';
 6357:             }
 6358:             $count ++;
 6359:         }
 6360:         if (($count > 0) && ($count%$numinrow == 0)) {
 6361:             $output .= '</tr><tr>';
 6362:         }
 6363:         $output .= '<td><span class="LC_nobreak"><label><input type = "checkbox" value="'.$othervalue.'"';
 6364:         if (ref($currinsttypes) eq 'ARRAY') {
 6365:             if (@{$currinsttypes} > 0) {
 6366:                 if (grep(/^any$/,@{$currinsttypes})) { 
 6367:                     $output .= ' checked="checked"';
 6368:                 } elsif ($othervalue eq 'other') {
 6369:                     if (grep(/^\Q$othervalue\E$/,@{$currinsttypes})) {
 6370:                         $output .= ' checked="checked"';
 6371:                     }
 6372:                 }
 6373:             } else {
 6374:                 $output .= ' checked="checked"';
 6375:             }
 6376:         } else {
 6377:             $output .= ' checked="checked"';
 6378:         }
 6379:         $output .= ' name="selfenroll_types_'.$num.'" />'.$othertitle.'</label></span></td></tr></table>';
 6380:     }
 6381:     return $output;
 6382: }
 6383: 
 6384: sub selfenroll_date_forms {
 6385:     my ($startform,$endform) = @_;
 6386:     my $output .= &Apache::lonhtmlcommon::start_pick_box()."\n".
 6387:                   &Apache::lonhtmlcommon::row_title(&mt('Start date'),
 6388:                                                     'LC_oddrow_value')."\n".
 6389:                   $startform."\n".
 6390:                   &Apache::lonhtmlcommon::row_closure(1).
 6391:                   &Apache::lonhtmlcommon::row_title(&mt('End date'),
 6392:                                                    'LC_oddrow_value')."\n".
 6393:                   $endform."\n".
 6394:                   &Apache::lonhtmlcommon::row_closure(1).
 6395:                   &Apache::lonhtmlcommon::end_pick_box();
 6396:     return $output;
 6397: }
 6398: 
 6399: sub print_userchangelogs_display {
 6400:     my ($r,$context,$permission) = @_;
 6401:     my $formname = 'rolelog';
 6402:     my ($username,$domain,$crstype,%roleslog);
 6403:     if ($context eq 'domain') {
 6404:         $domain = $env{'request.role.domain'};
 6405:         %roleslog=&Apache::lonnet::dump_dom('nohist_rolelog',$domain);
 6406:     } else {
 6407:         if ($context eq 'course') { 
 6408:             $domain = $env{'course.'.$env{'request.course.id'}.'.domain'};
 6409:             $username = $env{'course.'.$env{'request.course.id'}.'.num'};
 6410:             $crstype = &Apache::loncommon::course_type();
 6411:             my %saveable_parameters = ('show' => 'scalar',);
 6412:             &Apache::loncommon::store_course_settings('roles_log',
 6413:                                                       \%saveable_parameters);
 6414:             &Apache::loncommon::restore_course_settings('roles_log',
 6415:                                                         \%saveable_parameters);
 6416:         } elsif ($context eq 'author') {
 6417:             $domain = $env{'user.domain'}; 
 6418:             if ($env{'request.role'} =~ m{^au\./\Q$domain\E/$}) {
 6419:                 $username = $env{'user.name'};
 6420:             } else {
 6421:                 undef($domain);
 6422:             }
 6423:         }
 6424:         if ($domain ne '' && $username ne '') { 
 6425:             %roleslog=&Apache::lonnet::dump('nohist_rolelog',$domain,$username);
 6426:         }
 6427:     }
 6428:     if ((keys(%roleslog))[0]=~/^error\:/) { undef(%roleslog); }
 6429: 
 6430:     # set defaults
 6431:     my $now = time();
 6432:     my $defstart = $now - (7*24*3600); #7 days ago 
 6433:     my %defaults = (
 6434:                      page               => '1',
 6435:                      show               => '10',
 6436:                      role               => 'any',
 6437:                      chgcontext         => 'any',
 6438:                      rolelog_start_date => $defstart,
 6439:                      rolelog_end_date   => $now,
 6440:                    );
 6441:     my $more_records = 0;
 6442: 
 6443:     # set current
 6444:     my %curr;
 6445:     foreach my $item ('show','page','role','chgcontext') {
 6446:         $curr{$item} = $env{'form.'.$item};
 6447:     }
 6448:     my ($startdate,$enddate) = 
 6449:         &Apache::lonuserutils::get_dates_from_form('rolelog_start_date','rolelog_end_date');
 6450:     $curr{'rolelog_start_date'} = $startdate;
 6451:     $curr{'rolelog_end_date'} = $enddate;
 6452:     foreach my $key (keys(%defaults)) {
 6453:         if ($curr{$key} eq '') {
 6454:             $curr{$key} = $defaults{$key};
 6455:         }
 6456:     }
 6457:     my (%whodunit,%changed,$version);
 6458:     ($version) = ($r->dir_config('lonVersion') =~ /^([\d\.]+)\-/);
 6459:     my ($minshown,$maxshown);
 6460:     $minshown = 1;
 6461:     my $count = 0;
 6462:     if ($curr{'show'} ne &mt('all')) { 
 6463:         $maxshown = $curr{'page'} * $curr{'show'};
 6464:         if ($curr{'page'} > 1) {
 6465:             $minshown = 1 + ($curr{'page'} - 1) * $curr{'show'};
 6466:         }
 6467:     }
 6468: 
 6469:     # Form Header
 6470:     $r->print('<form action="/adm/createuser" method="post" name="'.$formname.'">'.
 6471:               &role_display_filter($context,$formname,$domain,$username,\%curr,
 6472:                                    $version,$crstype));
 6473: 
 6474:     # Create navigation
 6475:     my ($nav_script,$nav_links) = &userlogdisplay_nav($formname,\%curr,$more_records);
 6476:     my $showntableheader = 0;
 6477: 
 6478:     # Table Header
 6479:     my $tableheader = 
 6480:         &Apache::loncommon::start_data_table_header_row()
 6481:        .'<th>&nbsp;</th>'
 6482:        .'<th>'.&mt('When').'</th>'
 6483:        .'<th>'.&mt('Who made the change').'</th>'
 6484:        .'<th>'.&mt('Changed User').'</th>'
 6485:        .'<th>'.&mt('Role').'</th>';
 6486: 
 6487:     if ($context eq 'course') {
 6488:         $tableheader .= '<th>'.&mt('Section').'</th>';
 6489:     }
 6490:     $tableheader .=
 6491:         '<th>'.&mt('Context').'</th>'
 6492:        .'<th>'.&mt('Start').'</th>'
 6493:        .'<th>'.&mt('End').'</th>'
 6494:        .&Apache::loncommon::end_data_table_header_row();
 6495: 
 6496:     # Display user change log data
 6497:     foreach my $id (sort { $roleslog{$b}{'exe_time'}<=>$roleslog{$a}{'exe_time'} } (keys(%roleslog))) {
 6498:         next if (($roleslog{$id}{'exe_time'} < $curr{'rolelog_start_date'}) ||
 6499:                  ($roleslog{$id}{'exe_time'} > $curr{'rolelog_end_date'}));
 6500:         if ($curr{'show'} ne &mt('all')) {
 6501:             if ($count >= $curr{'page'} * $curr{'show'}) {
 6502:                 $more_records = 1;
 6503:                 last;
 6504:             }
 6505:         }
 6506:         if ($curr{'role'} ne 'any') {
 6507:             next if ($roleslog{$id}{'logentry'}{'role'} ne $curr{'role'}); 
 6508:         }
 6509:         if ($curr{'chgcontext'} ne 'any') {
 6510:             if ($curr{'chgcontext'} eq 'selfenroll') {
 6511:                 next if (!$roleslog{$id}{'logentry'}{'selfenroll'});
 6512:             } else {
 6513:                 next if ($roleslog{$id}{'logentry'}{'context'} ne $curr{'chgcontext'});
 6514:             }
 6515:         }
 6516:         $count ++;
 6517:         next if ($count < $minshown);
 6518:         unless ($showntableheader) {
 6519:             $r->print($nav_script
 6520:                      .$nav_links
 6521:                      .&Apache::loncommon::start_data_table()
 6522:                      .$tableheader);
 6523:             $r->rflush();
 6524:             $showntableheader = 1;
 6525:         }
 6526:         if ($whodunit{$roleslog{$id}{'exe_uname'}.':'.$roleslog{$id}{'exe_udom'}} eq '') {
 6527:             $whodunit{$roleslog{$id}{'exe_uname'}.':'.$roleslog{$id}{'exe_udom'}} =
 6528:                 &Apache::loncommon::plainname($roleslog{$id}{'exe_uname'},$roleslog{$id}{'exe_udom'});
 6529:         }
 6530:         if ($changed{$roleslog{$id}{'uname'}.':'.$roleslog{$id}{'udom'}} eq '') {
 6531:             $changed{$roleslog{$id}{'uname'}.':'.$roleslog{$id}{'udom'}} =
 6532:                 &Apache::loncommon::plainname($roleslog{$id}{'uname'},$roleslog{$id}{'udom'});
 6533:         }
 6534:         my $sec = $roleslog{$id}{'logentry'}{'section'};
 6535:         if ($sec eq '') {
 6536:             $sec = &mt('None');
 6537:         }
 6538:         my ($rolestart,$roleend);
 6539:         if ($roleslog{$id}{'delflag'}) {
 6540:             $rolestart = &mt('deleted');
 6541:             $roleend = &mt('deleted');
 6542:         } else {
 6543:             $rolestart = $roleslog{$id}{'logentry'}{'start'};
 6544:             $roleend = $roleslog{$id}{'logentry'}{'end'};
 6545:             if ($rolestart eq '' || $rolestart == 0) {
 6546:                 $rolestart = &mt('No start date'); 
 6547:             } else {
 6548:                 $rolestart = &Apache::lonlocal::locallocaltime($rolestart);
 6549:             }
 6550:             if ($roleend eq '' || $roleend == 0) { 
 6551:                 $roleend = &mt('No end date');
 6552:             } else {
 6553:                 $roleend = &Apache::lonlocal::locallocaltime($roleend);
 6554:             }
 6555:         }
 6556:         my $chgcontext = $roleslog{$id}{'logentry'}{'context'};
 6557:         if ($roleslog{$id}{'logentry'}{'selfenroll'}) {
 6558:             $chgcontext = 'selfenroll';
 6559:         }
 6560:         my %lt = &rolechg_contexts($context,$crstype);
 6561:         if ($chgcontext ne '' && $lt{$chgcontext} ne '') {
 6562:             $chgcontext = $lt{$chgcontext};
 6563:         }
 6564:         $r->print(
 6565:             &Apache::loncommon::start_data_table_row()
 6566:            .'<td>'.$count.'</td>'
 6567:            .'<td>'.&Apache::lonlocal::locallocaltime($roleslog{$id}{'exe_time'}).'</td>'
 6568:            .'<td>'.$whodunit{$roleslog{$id}{'exe_uname'}.':'.$roleslog{$id}{'exe_udom'}}.'</td>'
 6569:            .'<td>'.$changed{$roleslog{$id}{'uname'}.':'.$roleslog{$id}{'udom'}}.'</td>'
 6570:            .'<td>'.&Apache::lonnet::plaintext($roleslog{$id}{'logentry'}{'role'},$crstype).'</td>');
 6571:         if ($context eq 'course') { 
 6572:             $r->print('<td>'.$sec.'</td>');
 6573:         }
 6574:         $r->print(
 6575:             '<td>'.$chgcontext.'</td>'
 6576:            .'<td>'.$rolestart.'</td>'
 6577:            .'<td>'.$roleend.'</td>'
 6578:            .&Apache::loncommon::end_data_table_row()."\n");
 6579:     }
 6580: 
 6581:     if ($showntableheader) { # Table footer, if content displayed above
 6582:         $r->print(&Apache::loncommon::end_data_table()
 6583:                  .$nav_links);
 6584:     } else { # No content displayed above
 6585:         $r->print('<p class="LC_info">'
 6586:                  .&mt('There are no records to display.')
 6587:                  .'</p>'
 6588:         );
 6589:     }
 6590: 
 6591:     # Form Footer
 6592:     $r->print( 
 6593:         '<input type="hidden" name="page" value="'.$curr{'page'}.'" />'
 6594:        .'<input type="hidden" name="action" value="changelogs" />'
 6595:        .'</form>');
 6596:     return;
 6597: }
 6598: 
 6599: sub userlogdisplay_nav {
 6600:     my ($formname,$curr,$more_records) = @_;
 6601:     my ($nav_script,$nav_links);
 6602:     if (ref($curr) eq 'HASH') {
 6603:         # Create Navigation:
 6604:         # Navigation Script
 6605:         $nav_script = <<"ENDSCRIPT";
 6606: <script type="text/javascript">
 6607: // <![CDATA[
 6608: function chgPage(caller) {
 6609:     if (caller == 'previous') {
 6610:         document.$formname.page.value --;
 6611:     }
 6612:     if (caller == 'next') {
 6613:         document.$formname.page.value ++;
 6614:     }
 6615:     document.$formname.submit();
 6616:     return;
 6617: }
 6618: // ]]>
 6619: </script>
 6620: ENDSCRIPT
 6621:         # Navigation Buttons
 6622:         $nav_links = '<p>';
 6623:         if (($curr->{'page'} > 1) || ($more_records)) {
 6624:             if ($curr->{'page'} > 1) {
 6625:                 $nav_links .= '<input type="button"'
 6626:                              .' onclick="javascript:chgPage('."'previous'".');"'
 6627:                              .' value="'.&mt('Previous [_1] changes',$curr->{'show'})
 6628:                              .'" /> ';
 6629:             }
 6630:             if ($more_records) {
 6631:                 $nav_links .= '<input type="button"'
 6632:                              .' onclick="javascript:chgPage('."'next'".');"'
 6633:                              .' value="'.&mt('Next [_1] changes',$curr->{'show'})
 6634:                              .'" />';
 6635:             }
 6636:         }
 6637:         $nav_links .= '</p>';
 6638:     }
 6639:     return ($nav_script,$nav_links);
 6640: }
 6641: 
 6642: sub role_display_filter {
 6643:     my ($context,$formname,$cdom,$cnum,$curr,$version,$crstype) = @_;
 6644:     my $lctype;
 6645:     if ($context eq 'course') {
 6646:         $lctype = lc($crstype);
 6647:     }
 6648:     my $nolink = 1;
 6649:     my $output = '<table><tr><td valign="top">'.
 6650:                  '<span class="LC_nobreak"><b>'.&mt('Changes/page:').'</b></span><br />'.
 6651:                  &Apache::lonmeta::selectbox('show',$curr->{'show'},undef,
 6652:                                               (&mt('all'),5,10,20,50,100,1000,10000)).
 6653:                  '</td><td>&nbsp;&nbsp;</td>';
 6654:     my $startform =
 6655:         &Apache::lonhtmlcommon::date_setter($formname,'rolelog_start_date',
 6656:                                             $curr->{'rolelog_start_date'},undef,
 6657:                                             undef,undef,undef,undef,undef,undef,$nolink);
 6658:     my $endform =
 6659:         &Apache::lonhtmlcommon::date_setter($formname,'rolelog_end_date',
 6660:                                             $curr->{'rolelog_end_date'},undef,
 6661:                                             undef,undef,undef,undef,undef,undef,$nolink);
 6662:     my %lt = &rolechg_contexts($context,$crstype);
 6663:     $output .= '<td valign="top"><b>'.&mt('Window during which changes occurred:').'</b><br />'.
 6664:                '<table><tr><td>'.&mt('After:').
 6665:                '</td><td>'.$startform.'</td></tr>'.
 6666:                '<tr><td>'.&mt('Before:').'</td>'.
 6667:                '<td>'.$endform.'</td></tr></table>'.
 6668:                '</td>'.
 6669:                '<td>&nbsp;&nbsp;</td>'.
 6670:                '<td valign="top"><b>'.&mt('Role:').'</b><br />'.
 6671:                '<select name="role"><option value="any"';
 6672:     if ($curr->{'role'} eq 'any') {
 6673:         $output .= ' selected="selected"';
 6674:     }
 6675:     $output .=  '>'.&mt('Any').'</option>'."\n";
 6676:     my @roles = &Apache::lonuserutils::roles_by_context($context,1,$crstype);
 6677:     foreach my $role (@roles) {
 6678:         my $plrole;
 6679:         if ($role eq 'cr') {
 6680:             $plrole = &mt('Custom Role');
 6681:         } else {
 6682:             $plrole=&Apache::lonnet::plaintext($role,$crstype);
 6683:         }
 6684:         my $selstr = '';
 6685:         if ($role eq $curr->{'role'}) {
 6686:             $selstr = ' selected="selected"';
 6687:         }
 6688:         $output .= '  <option value="'.$role.'"'.$selstr.'>'.$plrole.'</option>';
 6689:     }
 6690:     $output .= '</select></td>'.
 6691:                '<td>&nbsp;&nbsp;</td>'.
 6692:                '<td valign="top"><b>'.
 6693:                &mt('Context:').'</b><br /><select name="chgcontext">';
 6694:     my @posscontexts;
 6695:     if ($context eq 'course') {
 6696:         @posscontexts = ('any','automated','updatenow','createcourse','course','domain','selfenroll','requestcourses');
 6697:     } elsif ($context eq 'domain') {
 6698:         @posscontexts = ('any','domain','requestauthor','domconfig','server');
 6699:     } else {
 6700:         @posscontexts = ('any','author','domain');
 6701:     } 
 6702:     foreach my $chgtype (@posscontexts) {
 6703:         my $selstr = '';
 6704:         if ($curr->{'chgcontext'} eq $chgtype) {
 6705:             $selstr = ' selected="selected"';
 6706:         }
 6707:         if ($context eq 'course') {
 6708:             if (($chgtype eq 'automated') || ($chgtype eq 'updatenow')) {
 6709:                 next if (!&Apache::lonnet::auto_run($cnum,$cdom));
 6710:             }
 6711:         }
 6712:         $output .= '<option value="'.$chgtype.'"'.$selstr.'>'.$lt{$chgtype}.'</option>'."\n";
 6713:     }
 6714:     $output .= '</select></td>'
 6715:               .'</tr></table>';
 6716: 
 6717:     # Update Display button
 6718:     $output .= '<p>'
 6719:               .'<input type="submit" value="'.&mt('Update Display').'" />'
 6720:               .'</p>';
 6721: 
 6722:     # Server version info
 6723:     my $needsrev = '2.11.0';
 6724:     if ($context eq 'course') {
 6725:         $needsrev = '2.7.0';
 6726:     }
 6727:     
 6728:     $output .= '<p class="LC_info">'
 6729:               .&mt('Only changes made from servers running LON-CAPA [_1] or later are displayed.'
 6730:                   ,$needsrev);
 6731:     if ($version) {
 6732:         $output .= ' '.&mt('This LON-CAPA server is version [_1]',$version);
 6733:     }
 6734:     $output .= '</p><hr />';
 6735:     return $output;
 6736: }
 6737: 
 6738: sub rolechg_contexts {
 6739:     my ($context,$crstype) = @_;
 6740:     my %lt;
 6741:     if ($context eq 'course') {
 6742:         %lt = &Apache::lonlocal::texthash (
 6743:                                              any          => 'Any',
 6744:                                              automated    => 'Automated Enrollment',
 6745:                                              updatenow    => 'Roster Update',
 6746:                                              createcourse => 'Course Creation',
 6747:                                              course       => 'User Management in course',
 6748:                                              domain       => 'User Management in domain',
 6749:                                              selfenroll   => 'Self-enrolled',
 6750:                                              requestcourses => 'Course Request',
 6751:                                          );
 6752:         if ($crstype eq 'Community') {
 6753:             $lt{'createcourse'} = &mt('Community Creation');
 6754:             $lt{'course'} = &mt('User Management in community');
 6755:             $lt{'requestcourses'} = &mt('Community Request');
 6756:         }
 6757:     } elsif ($context eq 'domain') {
 6758:         %lt = &Apache::lonlocal::texthash (
 6759:                                              any           => 'Any',
 6760:                                              domain        => 'User Management in domain',
 6761:                                              requestauthor => 'Authoring Request',
 6762:                                              server        => 'Command line script (DC role)',
 6763:                                              domconfig     => 'Self-enrolled',
 6764:                                          );
 6765:     } else {
 6766:         %lt = &Apache::lonlocal::texthash (
 6767:                                              any    => 'Any',
 6768:                                              domain => 'User Management in domain',
 6769:                                              author => 'User Management by author',
 6770:                                          );
 6771:     } 
 6772:     return %lt;
 6773: }
 6774: 
 6775: #-------------------------------------------------- functions for &phase_two
 6776: sub user_search_result {
 6777:     my ($context,$srch) = @_;
 6778:     my %allhomes;
 6779:     my %inst_matches;
 6780:     my %srch_results;
 6781:     my ($response,$currstate,$forcenewuser,$dirsrchres);
 6782:     $srch->{'srchterm'} =~ s/\s+/ /g;
 6783:     if ($srch->{'srchby'} !~ /^(uname|lastname|lastfirst)$/) {
 6784:         $response = &mt('Invalid search.');
 6785:     }
 6786:     if ($srch->{'srchin'} !~ /^(crs|dom|alc|instd)$/) {
 6787:         $response = &mt('Invalid search.');
 6788:     }
 6789:     if ($srch->{'srchtype'} !~ /^(exact|contains|begins)$/) {
 6790:         $response = &mt('Invalid search.');
 6791:     }
 6792:     if ($srch->{'srchterm'} eq '') {
 6793:         $response = &mt('You must enter a search term.');
 6794:     }
 6795:     if ($srch->{'srchterm'} =~ /^\s+$/) {
 6796:         $response = &mt('Your search term must contain more than just spaces.');
 6797:     }
 6798:     if (($srch->{'srchin'} eq 'dom') || ($srch->{'srchin'} eq 'instd')) {
 6799:         if (($srch->{'srchdomain'} eq '') || 
 6800: 	    ! (&Apache::lonnet::domain($srch->{'srchdomain'}))) {
 6801:             $response = &mt('You must specify a valid domain when searching in a domain or institutional directory.')
 6802:         }
 6803:     }
 6804:     if (($srch->{'srchin'} eq 'dom') || ($srch->{'srchin'} eq 'crs') ||
 6805:         ($srch->{'srchin'} eq 'alc')) {
 6806:         if ($srch->{'srchby'} eq 'uname') {
 6807:             my $unamecheck = $srch->{'srchterm'};
 6808:             if ($srch->{'srchtype'} eq 'contains') {
 6809:                 if ($unamecheck !~ /^\w/) {
 6810:                     $unamecheck = 'a'.$unamecheck; 
 6811:                 }
 6812:             }
 6813:             if ($unamecheck !~ /^$match_username$/) {
 6814:                 $response = &mt('You must specify a valid username. Only the following are allowed: letters numbers - . @');
 6815:             }
 6816:         }
 6817:     }
 6818:     if ($response ne '') {
 6819:         $response = '<span class="LC_warning">'.$response.'</span>';
 6820:     }
 6821:     if ($srch->{'srchin'} eq 'instd') {
 6822:         my $instd_chk = &directorysrch_check($srch);
 6823:         if ($instd_chk ne 'ok') {
 6824:             $response = '<span class="LC_warning">'.$instd_chk.'</span>'.
 6825:                         '<br />'.&mt('You may want to search in the LON-CAPA domain instead of the institutional directory.').'<br /><br />';
 6826:         }
 6827:     }
 6828:     if ($response ne '') {
 6829:         return ($currstate,$response);
 6830:     }
 6831:     if ($srch->{'srchby'} eq 'uname') {
 6832:         if (($srch->{'srchin'} eq 'dom') || ($srch->{'srchin'} eq 'crs')) {
 6833:             if ($env{'form.forcenew'}) {
 6834:                 if ($srch->{'srchdomain'} ne $env{'request.role.domain'}) {
 6835:                     my $uhome=&Apache::lonnet::homeserver($srch->{'srchterm'},$srch->{'srchdomain'});
 6836:                     if ($uhome eq 'no_host') {
 6837:                         my $domdesc = &Apache::lonnet::domain($env{'request.role.domain'},'description');
 6838:                         my $showdom = &display_domain_info($env{'request.role.domain'});
 6839:                         $response = &mt('New users can only be created in the domain to which your current role belongs - [_1].',$showdom);
 6840:                     } else {
 6841:                         $currstate = 'modify';
 6842:                     }
 6843:                 } else {
 6844:                     $currstate = 'modify';
 6845:                 }
 6846:             } else {
 6847:                 if ($srch->{'srchin'} eq 'dom') {
 6848:                     if ($srch->{'srchtype'} eq 'exact') {
 6849:                         my $uhome=&Apache::lonnet::homeserver($srch->{'srchterm'},$srch->{'srchdomain'});
 6850:                         if ($uhome eq 'no_host') {
 6851:                             ($currstate,$response,$forcenewuser) =
 6852:                                 &build_search_response($context,$srch,%srch_results);
 6853:                         } else {
 6854:                             $currstate = 'modify';
 6855:                             my $uname = $srch->{'srchterm'};
 6856:                             my $udom = $srch->{'srchdomain'};
 6857:                             $srch_results{$uname.':'.$udom} =
 6858:                                 { &Apache::lonnet::get('environment',
 6859:                                                        ['firstname',
 6860:                                                         'lastname',
 6861:                                                         'permanentemail'],
 6862:                                                          $udom,$uname)
 6863:                                 };
 6864:                         }
 6865:                     } else {
 6866:                         %srch_results = &Apache::lonnet::usersearch($srch);
 6867:                         ($currstate,$response,$forcenewuser) =
 6868:                             &build_search_response($context,$srch,%srch_results);
 6869:                     }
 6870:                 } else {
 6871:                     my $courseusers = &get_courseusers();
 6872:                     if ($srch->{'srchtype'} eq 'exact') {
 6873:                         if (exists($courseusers->{$srch->{'srchterm'}.':'.$srch->{'srchdomain'}})) {
 6874:                             $currstate = 'modify';
 6875:                         } else {
 6876:                             ($currstate,$response,$forcenewuser) =
 6877:                                 &build_search_response($context,$srch,%srch_results);
 6878:                         }
 6879:                     } else {
 6880:                         foreach my $user (keys(%$courseusers)) {
 6881:                             my ($cuname,$cudomain) = split(/:/,$user);
 6882:                             if ($cudomain eq $srch->{'srchdomain'}) {
 6883:                                 my $matched = 0;
 6884:                                 if ($srch->{'srchtype'} eq 'begins') {
 6885:                                     if ($cuname =~ /^\Q$srch->{'srchterm'}\E/i) {
 6886:                                         $matched = 1;
 6887:                                     }
 6888:                                 } else {
 6889:                                     if ($cuname =~ /\Q$srch->{'srchterm'}\E/i) {
 6890:                                         $matched = 1;
 6891:                                     }
 6892:                                 }
 6893:                                 if ($matched) {
 6894:                                     $srch_results{$user} = 
 6895: 					{&Apache::lonnet::get('environment',
 6896: 							     ['firstname',
 6897: 							      'lastname',
 6898: 							      'permanentemail'],
 6899: 							      $cudomain,$cuname)};
 6900:                                 }
 6901:                             }
 6902:                         }
 6903:                         ($currstate,$response,$forcenewuser) =
 6904:                             &build_search_response($context,$srch,%srch_results);
 6905:                     }
 6906:                 }
 6907:             }
 6908:         } elsif ($srch->{'srchin'} eq 'alc') {
 6909:             $currstate = 'query';
 6910:         } elsif ($srch->{'srchin'} eq 'instd') {
 6911:             ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query($srch);
 6912:             if ($dirsrchres eq 'ok') {
 6913:                 ($currstate,$response,$forcenewuser) = 
 6914:                     &build_search_response($context,$srch,%srch_results);
 6915:             } else {
 6916:                 my $showdom = &display_domain_info($srch->{'srchdomain'});
 6917:                 $response = '<span class="LC_warning">'.
 6918:                     &mt('Institutional directory search is not available in domain: [_1]',$showdom).
 6919:                     '</span><br />'.
 6920:                     &mt('You may want to search in the LON-CAPA domain instead of the institutional directory.').
 6921:                     '<br /><br />'; 
 6922:             }
 6923:         }
 6924:     } else {
 6925:         if ($srch->{'srchin'} eq 'dom') {
 6926:             %srch_results = &Apache::lonnet::usersearch($srch);
 6927:             ($currstate,$response,$forcenewuser) = 
 6928:                 &build_search_response($context,$srch,%srch_results); 
 6929:         } elsif ($srch->{'srchin'} eq 'crs') {
 6930:             my $courseusers = &get_courseusers(); 
 6931:             foreach my $user (keys(%$courseusers)) {
 6932:                 my ($uname,$udom) = split(/:/,$user);
 6933:                 my %names = &Apache::loncommon::getnames($uname,$udom);
 6934:                 my %emails = &Apache::loncommon::getemails($uname,$udom);
 6935:                 if ($srch->{'srchby'} eq 'lastname') {
 6936:                     if ((($srch->{'srchtype'} eq 'exact') && 
 6937:                          ($names{'lastname'} eq $srch->{'srchterm'})) || 
 6938:                         (($srch->{'srchtype'} eq 'begins') &&
 6939:                          ($names{'lastname'} =~ /^\Q$srch->{'srchterm'}\E/i)) ||
 6940:                         (($srch->{'srchtype'} eq 'contains') &&
 6941:                          ($names{'lastname'} =~ /\Q$srch->{'srchterm'}\E/i))) {
 6942:                         $srch_results{$user} = {firstname => $names{'firstname'},
 6943:                                             lastname => $names{'lastname'},
 6944:                                             permanentemail => $emails{'permanentemail'},
 6945:                                            };
 6946:                     }
 6947:                 } elsif ($srch->{'srchby'} eq 'lastfirst') {
 6948:                     my ($srchlast,$srchfirst) = split(/,/,$srch->{'srchterm'});
 6949:                     $srchlast =~ s/\s+$//;
 6950:                     $srchfirst =~ s/^\s+//;
 6951:                     if ($srch->{'srchtype'} eq 'exact') {
 6952:                         if (($names{'lastname'} eq $srchlast) &&
 6953:                             ($names{'firstname'} eq $srchfirst)) {
 6954:                             $srch_results{$user} = {firstname => $names{'firstname'},
 6955:                                                 lastname => $names{'lastname'},
 6956:                                                 permanentemail => $emails{'permanentemail'},
 6957: 
 6958:                                            };
 6959:                         }
 6960:                     } elsif ($srch->{'srchtype'} eq 'begins') {
 6961:                         if (($names{'lastname'} =~ /^\Q$srchlast\E/i) &&
 6962:                             ($names{'firstname'} =~ /^\Q$srchfirst\E/i)) {
 6963:                             $srch_results{$user} = {firstname => $names{'firstname'},
 6964:                                                 lastname => $names{'lastname'},
 6965:                                                 permanentemail => $emails{'permanentemail'},
 6966:                                                };
 6967:                         }
 6968:                     } else {
 6969:                         if (($names{'lastname'} =~ /\Q$srchlast\E/i) && 
 6970:                             ($names{'firstname'} =~ /\Q$srchfirst\E/i)) {
 6971:                             $srch_results{$user} = {firstname => $names{'firstname'},
 6972:                                                 lastname => $names{'lastname'},
 6973:                                                 permanentemail => $emails{'permanentemail'},
 6974:                                                };
 6975:                         }
 6976:                     }
 6977:                 }
 6978:             }
 6979:             ($currstate,$response,$forcenewuser) = 
 6980:                 &build_search_response($context,$srch,%srch_results); 
 6981:         } elsif ($srch->{'srchin'} eq 'alc') {
 6982:             $currstate = 'query';
 6983:         } elsif ($srch->{'srchin'} eq 'instd') {
 6984:             ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query($srch); 
 6985:             if ($dirsrchres eq 'ok') {
 6986:                 ($currstate,$response,$forcenewuser) = 
 6987:                     &build_search_response($context,$srch,%srch_results);
 6988:             } else {
 6989:                 my $showdom = &display_domain_info($srch->{'srchdomain'});                $response = '<span class="LC_warning">'.
 6990:                     &mt('Institutional directory search is not available in domain: [_1]',$showdom).
 6991:                     '</span><br />'.
 6992:                     &mt('You may want to search in the LON-CAPA domain instead of the institutional directory.').
 6993:                     '<br /><br />';
 6994:             }
 6995:         }
 6996:     }
 6997:     return ($currstate,$response,$forcenewuser,\%srch_results);
 6998: }
 6999: 
 7000: sub directorysrch_check {
 7001:     my ($srch) = @_;
 7002:     my $can_search = 0;
 7003:     my $response;
 7004:     my %dom_inst_srch = &Apache::lonnet::get_dom('configuration',
 7005:                                              ['directorysrch'],$srch->{'srchdomain'});
 7006:     my $showdom = &display_domain_info($srch->{'srchdomain'});
 7007:     if (ref($dom_inst_srch{'directorysrch'}) eq 'HASH') {
 7008:         if (!$dom_inst_srch{'directorysrch'}{'available'}) {
 7009:             return &mt('Institutional directory search is not available in domain: [_1]',$showdom); 
 7010:         }
 7011:         if ($dom_inst_srch{'directorysrch'}{'localonly'}) {
 7012:             if ($env{'request.role.domain'} ne $srch->{'srchdomain'}) {
 7013:                 return &mt('Institutional directory search in domain: [_1] is only allowed for users with a current role in the domain.',$showdom); 
 7014:             }
 7015:             my @usertypes = split(/:/,$env{'environment.inststatus'});
 7016:             if (!@usertypes) {
 7017:                 push(@usertypes,'default');
 7018:             }
 7019:             if (ref($dom_inst_srch{'directorysrch'}{'cansearch'}) eq 'ARRAY') {
 7020:                 foreach my $type (@usertypes) {
 7021:                     if (grep(/^\Q$type\E$/,@{$dom_inst_srch{'directorysrch'}{'cansearch'}})) {
 7022:                         $can_search = 1;
 7023:                         last;
 7024:                     }
 7025:                 }
 7026:             }
 7027:             if (!$can_search) {
 7028:                 my ($insttypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($srch->{'srchdomain'});
 7029:                 my @longtypes; 
 7030:                 foreach my $item (@usertypes) {
 7031:                     if (defined($insttypes->{$item})) { 
 7032:                         push (@longtypes,$insttypes->{$item});
 7033:                     } elsif ($item eq 'default') {
 7034:                         push (@longtypes,&mt('other')); 
 7035:                     }
 7036:                 }
 7037:                 my $insttype_str = join(', ',@longtypes); 
 7038:                 return &mt('Institutional directory search in domain: [_1] is not available to your user type: ',$showdom).$insttype_str;
 7039:             }
 7040:         } else {
 7041:             $can_search = 1;
 7042:         }
 7043:     } else {
 7044:         return &mt('Institutional directory search has not been configured for domain: [_1]',$showdom);
 7045:     }
 7046:     my %longtext = &Apache::lonlocal::texthash (
 7047:                        uname     => 'username',
 7048:                        lastfirst => 'last name, first name',
 7049:                        lastname  => 'last name',
 7050:                        contains  => 'contains',
 7051:                        exact     => 'as exact match to',
 7052:                        begins    => 'begins with',
 7053:                    );
 7054:     if ($can_search) {
 7055:         if (ref($dom_inst_srch{'directorysrch'}{'searchby'}) eq 'ARRAY') {
 7056:             if (!grep(/^\Q$srch->{'srchby'}\E$/,@{$dom_inst_srch{'directorysrch'}{'searchby'}})) {
 7057:                 return &mt('Institutional directory search in domain: [_1] is not available for searching by "[_2]"',$showdom,$longtext{$srch->{'srchby'}});
 7058:             }
 7059:         } else {
 7060:             return &mt('Institutional directory search in domain: [_1] is not available.', $showdom);
 7061:         }
 7062:     }
 7063:     if ($can_search) {
 7064:         if (ref($dom_inst_srch{'directorysrch'}{'searchtypes'}) eq 'ARRAY') {
 7065:             if (grep(/^\Q$srch->{'srchtype'}\E/,@{$dom_inst_srch{'directorysrch'}{'searchtypes'}})) {
 7066:                 return 'ok';
 7067:             } else {
 7068:                 return &mt('Institutional directory search in domain [_1] is not available for the requested search type: "[_2]"',$showdom,$longtext{$srch->{'srchtype'}});
 7069:             }
 7070:         } else {
 7071:             if ((($dom_inst_srch{'directorysrch'}{'searchtypes'} eq 'specify') &&
 7072:                  ($srch->{'srchtype'} eq 'exact' || $srch->{'srchtype'} eq 'contains')) ||
 7073:                 ($dom_inst_srch{'directorysrch'}{'searchtypes'} eq $srch->{'srchtype'})) {
 7074:                 return 'ok';
 7075:             } else {
 7076:                 return &mt('Institutional directory search in domain [_1] is not available for the requested search type: "[_2]"',$showdom,$longtext{$srch->{'srchtype'}});
 7077:             }
 7078:         }
 7079:     }
 7080: }
 7081: 
 7082: sub get_courseusers {
 7083:     my %advhash;
 7084:     my $classlist = &Apache::loncoursedata::get_classlist();
 7085:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles();
 7086:     foreach my $role (sort(keys(%coursepersonnel))) {
 7087:         foreach my $user (split(/\,/,$coursepersonnel{$role})) {
 7088: 	    if (!exists($classlist->{$user})) {
 7089: 		$classlist->{$user} = [];
 7090: 	    }
 7091:         }
 7092:     }
 7093:     return $classlist;
 7094: }
 7095: 
 7096: sub build_search_response {
 7097:     my ($context,$srch,%srch_results) = @_;
 7098:     my ($currstate,$response,$forcenewuser);
 7099:     my %names = (
 7100:           'uname'     => 'username',
 7101:           'lastname'  => 'last name',
 7102:           'lastfirst' => 'last name, first name',
 7103:           'crs'       => 'this course',
 7104:           'dom'       => 'LON-CAPA domain',
 7105:           'instd'     => 'the institutional directory for domain',
 7106:     );
 7107: 
 7108:     my %single = (
 7109:                    begins   => 'A match',
 7110:                    contains => 'A match',
 7111:                    exact    => 'An exact match',
 7112:                  );
 7113:     my %nomatch = (
 7114:                    begins   => 'No match',
 7115:                    contains => 'No match',
 7116:                    exact    => 'No exact match',
 7117:                   );
 7118:     if (keys(%srch_results) > 1) {
 7119:         $currstate = 'select';
 7120:     } else {
 7121:         if (keys(%srch_results) == 1) {
 7122:             $currstate = 'modify';
 7123:             $response = &mt("$single{$srch->{'srchtype'}} was found for the $names{$srch->{'srchby'}} ([_1]) in $names{$srch->{'srchin'}}.",$srch->{'srchterm'});
 7124:             if ($srch->{'srchin'} eq 'dom' || $srch->{'srchin'} eq 'instd') {
 7125:                 $response .= ': '.&display_domain_info($srch->{'srchdomain'});
 7126:             }
 7127:         } else { # Search has nothing found. Prepare message to user.
 7128:             $response = '<span class="LC_warning">';
 7129:             if ($srch->{'srchin'} eq 'dom' || $srch->{'srchin'} eq 'instd') {
 7130:                 $response .= &mt("$nomatch{$srch->{'srchtype'}} found for the $names{$srch->{'srchby'}} [_1] in $names{$srch->{'srchin'}}: [_2]",
 7131:                                  '<b>'.$srch->{'srchterm'}.'</b>',
 7132:                                  &display_domain_info($srch->{'srchdomain'}));
 7133:             } else {
 7134:                 $response .= &mt("$nomatch{$srch->{'srchtype'}} found for the $names{$srch->{'srchby'}} [_1] in $names{$srch->{'srchin'}}.",
 7135:                                  '<b>'.$srch->{'srchterm'}.'</b>');
 7136:             }
 7137:             $response .= '</span>';
 7138: 
 7139:             if ($srch->{'srchin'} ne 'alc') {
 7140:                 $forcenewuser = 1;
 7141:                 my $cansrchinst = 0; 
 7142:                 if ($srch->{'srchdomain'}) {
 7143:                     my %domconfig = &Apache::lonnet::get_dom('configuration',['directorysrch'],$srch->{'srchdomain'});
 7144:                     if (ref($domconfig{'directorysrch'}) eq 'HASH') {
 7145:                         if ($domconfig{'directorysrch'}{'available'}) {
 7146:                             $cansrchinst = 1;
 7147:                         } 
 7148:                     }
 7149:                 }
 7150:                 if ((($srch->{'srchby'} eq 'lastfirst') || 
 7151:                      ($srch->{'srchby'} eq 'lastname')) &&
 7152:                     ($srch->{'srchin'} eq 'dom')) {
 7153:                     if ($cansrchinst) {
 7154:                         $response .= '<br />'.&mt('You may want to broaden your search to a search of the institutional directory for the domain.');
 7155:                     }
 7156:                 }
 7157:                 if ($srch->{'srchin'} eq 'crs') {
 7158:                     $response .= '<br />'.&mt('You may want to broaden your search to the selected LON-CAPA domain.');
 7159:                 }
 7160:             }
 7161:             my $createdom = $env{'request.role.domain'};
 7162:             if ($context eq 'requestcrs') {
 7163:                 if ($env{'form.coursedom'} ne '') {
 7164:                     $createdom = $env{'form.coursedom'};
 7165:                 }
 7166:             }
 7167:             if (!($srch->{'srchby'} eq 'uname' && $srch->{'srchin'} eq 'dom' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchdomain'} eq $createdom)) {
 7168:                 my $cancreate =
 7169:                     &Apache::lonuserutils::can_create_user($createdom,$context);
 7170:                 my $targetdom = '<span class="LC_cusr_emph">'.$createdom.'</span>';
 7171:                 if ($cancreate) {
 7172:                     my $showdom = &display_domain_info($createdom); 
 7173:                     $response .= '<br /><br />'
 7174:                                 .'<b>'.&mt('To add a new user:').'</b>'
 7175:                                 .'<br />';
 7176:                     if ($context eq 'requestcrs') {
 7177:                         $response .= &mt("(You can only define new users in the new course's domain - [_1])",$targetdom);
 7178:                     } else {
 7179:                         $response .= &mt("(You can only create new users in your current role's domain - [_1])",$targetdom);
 7180:                     }
 7181:                     $response .='<ul><li>'
 7182:                                 .&mt("Set 'Domain/institution to search' to: [_1]",'<span class="LC_cusr_emph">'.$showdom.'</span>')
 7183:                                 .'</li><li>'
 7184:                                 .&mt("Set 'Search criteria' to: [_1]username is ..... in selected LON-CAPA domain[_2]",'<span class="LC_cusr_emph">','</span>')
 7185:                                 .'</li><li>'
 7186:                                 .&mt('Provide the proposed username')
 7187:                                 .'</li><li>'
 7188:                                 .&mt("Click 'Search'")
 7189:                                 .'</li></ul><br />';
 7190:                 } else {
 7191:                     my $helplink = ' href="javascript:helpMenu('."'display'".')"';
 7192:                     $response .= '<br /><br />';
 7193:                     if ($context eq 'requestcrs') {
 7194:                         $response .= &mt("You are not authorized to define new users in the new course's domain - [_1].",$targetdom);
 7195:                     } else {
 7196:                         $response .= &mt("You are not authorized to create new users in your current role's domain - [_1].",$targetdom);
 7197:                     }
 7198:                     $response .= '<br />'
 7199:                                  .&mt('Please contact the [_1]helpdesk[_2] if you need to create a new user.'
 7200:                                     ,' <a'.$helplink.'>'
 7201:                                     ,'</a>')
 7202:                                  .'<br /><br />';
 7203:                 }
 7204:             }
 7205:         }
 7206:     }
 7207:     return ($currstate,$response,$forcenewuser);
 7208: }
 7209: 
 7210: sub display_domain_info {
 7211:     my ($dom) = @_;
 7212:     my $output = $dom;
 7213:     if ($dom ne '') { 
 7214:         my $domdesc = &Apache::lonnet::domain($dom,'description');
 7215:         if ($domdesc ne '') {
 7216:             $output .= ' <span class="LC_cusr_emph">('.$domdesc.')</span>';
 7217:         }
 7218:     }
 7219:     return $output;
 7220: }
 7221: 
 7222: sub crumb_utilities {
 7223:     my %elements = (
 7224:        crtuser => {
 7225:            srchterm => 'text',
 7226:            srchin => 'selectbox',
 7227:            srchby => 'selectbox',
 7228:            srchtype => 'selectbox',
 7229:            srchdomain => 'selectbox',
 7230:        },
 7231:        crtusername => {
 7232:            srchterm => 'text',
 7233:            srchdomain => 'selectbox',
 7234:        },
 7235:        docustom => {
 7236:            rolename => 'selectbox',
 7237:            newrolename => 'textbox',
 7238:        },
 7239:        studentform => {
 7240:            srchterm => 'text',
 7241:            srchin => 'selectbox',
 7242:            srchby => 'selectbox',
 7243:            srchtype => 'selectbox',
 7244:            srchdomain => 'selectbox',
 7245:        },
 7246:     );
 7247: 
 7248:     my $jsback .= qq|
 7249: function backPage(formname,prevphase,prevstate) {
 7250:     if (typeof prevphase == 'undefined') {
 7251:         formname.phase.value = '';
 7252:     }
 7253:     else {  
 7254:         formname.phase.value = prevphase;
 7255:     }
 7256:     if (typeof prevstate == 'undefined') {
 7257:         formname.currstate.value = '';
 7258:     }
 7259:     else {
 7260:         formname.currstate.value = prevstate;
 7261:     }
 7262:     formname.submit();
 7263: }
 7264: |;
 7265:     return ($jsback,\%elements);
 7266: }
 7267: 
 7268: sub course_level_table {
 7269:     my ($inccourses,$showcredits,$defaultcredits) = @_;
 7270:     return unless (ref($inccourses) eq 'HASH');
 7271:     my $table = '';
 7272: # Custom Roles?
 7273: 
 7274:     my %customroles=&Apache::lonuserutils::my_custom_roles();
 7275:     my %lt=&Apache::lonlocal::texthash(
 7276:             'exs'  => "Existing sections",
 7277:             'new'  => "Define new section",
 7278:             'ssd'  => "Set Start Date",
 7279:             'sed'  => "Set End Date",
 7280:             'crl'  => "Course Level",
 7281:             'act'  => "Activate",
 7282:             'rol'  => "Role",
 7283:             'ext'  => "Extent",
 7284:             'grs'  => "Section",
 7285:             'crd'  => "Credits",
 7286:             'sta'  => "Start",
 7287:             'end'  => "End"
 7288:     );
 7289: 
 7290:     foreach my $protectedcourse (sort(keys(%{$inccourses}))) {
 7291: 	my $thiscourse=$protectedcourse;
 7292: 	$thiscourse=~s:_:/:g;
 7293: 	my %coursedata=&Apache::lonnet::coursedescription($thiscourse);
 7294:         my $isowner = &Apache::lonuserutils::is_courseowner($protectedcourse,$coursedata{'internal.courseowner'});
 7295: 	my $area=$coursedata{'description'};
 7296:         my $crstype=$coursedata{'type'};
 7297: 	if (!defined($area)) { $area=&mt('Unavailable course').': '.$protectedcourse; }
 7298: 	my ($domain,$cnum)=split(/\//,$thiscourse);
 7299:         my %sections_count;
 7300:         if (defined($env{'request.course.id'})) {
 7301:             if ($env{'request.course.id'} eq $domain.'_'.$cnum) {
 7302:                 %sections_count = 
 7303: 		    &Apache::loncommon::get_sections($domain,$cnum);
 7304:             }
 7305:         }
 7306:         my @roles = &Apache::lonuserutils::roles_by_context('course','',$crstype);
 7307: 	foreach my $role (@roles) {
 7308:             my $plrole=&Apache::lonnet::plaintext($role,$crstype);
 7309: 	    if ((&Apache::lonnet::allowed('c'.$role,$thiscourse)) ||
 7310:                 ((($role eq 'cc') || ($role eq 'co')) && ($isowner))) {
 7311:                 $table .= &course_level_row($protectedcourse,$role,$area,$domain,
 7312:                                             $plrole,\%sections_count,\%lt,
 7313:                                             $showcredits,$defaultcredits,$crstype);
 7314:             } elsif ($env{'request.course.sec'} ne '') {
 7315:                 if (&Apache::lonnet::allowed('c'.$role,$thiscourse.'/'.
 7316:                                              $env{'request.course.sec'})) {
 7317:                     $table .= &course_level_row($protectedcourse,$role,$area,$domain,
 7318:                                                 $plrole,\%sections_count,\%lt,
 7319:                                                 $showcredits,$defaultcredits,$crstype);
 7320:                 }
 7321:             }
 7322:         }
 7323:         if (&Apache::lonnet::allowed('ccr',$thiscourse)) {
 7324:             foreach my $cust (sort(keys(%customroles))) {
 7325:                 next if ($crstype eq 'Community' && $customroles{$cust} =~ /bre\&S/);
 7326:                 my $role = 'cr_cr_'.$env{'user.domain'}.'_'.$env{'user.name'}.'_'.$cust;
 7327:                 $table .= &course_level_row($protectedcourse,$role,$area,$domain,
 7328:                                             $cust,\%sections_count,\%lt,
 7329:                                             $showcredits,$defaultcredits,$crstype);
 7330:             }
 7331: 	}
 7332:     }
 7333:     return '' if ($table eq ''); # return nothing if there is nothing 
 7334:                                  # in the table
 7335:     my $result;
 7336:     if (!$env{'request.course.id'}) {
 7337:         $result = '<h4>'.$lt{'crl'}.'</h4>'."\n";
 7338:     }
 7339:     $result .= 
 7340: &Apache::loncommon::start_data_table().
 7341: &Apache::loncommon::start_data_table_header_row().
 7342: '<th>'.$lt{'act'}.'</th><th>'.$lt{'rol'}.'</th>'."\n".
 7343: '<th>'.$lt{'ext'}.'</th><th>'."\n";
 7344:     if ($showcredits) {
 7345:         $result .= $lt{'crd'}.'</th>';
 7346:     }
 7347:     $result .=
 7348: '<th>'.$lt{'grs'}.'</th><th>'.$lt{'sta'}.'</th>'."\n".
 7349: '<th>'.$lt{'end'}.'</th>'.
 7350: &Apache::loncommon::end_data_table_header_row().
 7351: $table.
 7352: &Apache::loncommon::end_data_table();
 7353:     return $result;
 7354: }
 7355: 
 7356: sub course_level_row {
 7357:     my ($protectedcourse,$role,$area,$domain,$plrole,$sections_count,
 7358:         $lt,$showcredits,$defaultcredits,$crstype) = @_;
 7359:     my $creditem;
 7360:     my $row = &Apache::loncommon::start_data_table_row().
 7361:               ' <td><input type="checkbox" name="act_'.
 7362:               $protectedcourse.'_'.$role.'" /></td>'."\n".
 7363:               ' <td>'.$plrole.'</td>'."\n".
 7364:               ' <td>'.$area.'<br />Domain: '.$domain.'</td>'."\n";
 7365:     if (($showcredits) && ($role eq 'st') && ($crstype eq 'Course')) {
 7366:         $row .= 
 7367:             '<td><input type="text" name="credits_'.$protectedcourse.'_'.
 7368:             $role.'" size="3" value="'.$defaultcredits.'" /></td>';
 7369:     } else {
 7370:         $row .= '<td>&nbsp;</td>';
 7371:     }
 7372:     if (($role eq 'cc') || ($role eq 'co')) {
 7373:         $row .= '<td>&nbsp;</td>';
 7374:     } elsif ($env{'request.course.sec'} ne '') {
 7375:         $row .= ' <td><input type="hidden" value="'.
 7376:                 $env{'request.course.sec'}.'" '.
 7377:                 'name="sec_'.$protectedcourse.'_'.$role.'" />'.
 7378:                 $env{'request.course.sec'}.'</td>';
 7379:     } else {
 7380:         if (ref($sections_count) eq 'HASH') {
 7381:             my $currsec = 
 7382:                 &Apache::lonuserutils::course_sections($sections_count,
 7383:                                                        $protectedcourse.'_'.$role);
 7384:             $row .= '<td><table class="LC_createuser">'."\n".
 7385:                     '<tr class="LC_section_row">'."\n".
 7386:                     ' <td valign="top">'.$lt->{'exs'}.'<br />'.
 7387:                        $currsec.'</td>'."\n".
 7388:                      ' <td>&nbsp;&nbsp;</td>'."\n".
 7389:                      ' <td valign="top">&nbsp;'.$lt->{'new'}.'<br />'.
 7390:                      '<input type="text" name="newsec_'.$protectedcourse.'_'.$role.
 7391:                      '" value="" />'.
 7392:                      '<input type="hidden" '.
 7393:                      'name="sec_'.$protectedcourse.'_'.$role.'" /></td>'."\n".
 7394:                      '</tr></table></td>'."\n";
 7395:         } else {
 7396:             $row .= '<td><input type="text" size="10" '.
 7397:                     'name="sec_'.$protectedcourse.'_'.$role.'" /></td>'."\n";
 7398:         }
 7399:     }
 7400:     $row .= <<ENDTIMEENTRY;
 7401: <td><input type="hidden" name="start_$protectedcourse\_$role" value="" />
 7402: <a href=
 7403: "javascript:pjump('date_start','Start Date $plrole',document.cu.start_$protectedcourse\_$role.value,'start_$protectedcourse\_$role','cu.pres','dateset')">$lt->{'ssd'}</a></td>
 7404: <td><input type="hidden" name="end_$protectedcourse\_$role" value="" />
 7405: <a href=
 7406: "javascript:pjump('date_end','End Date $plrole',document.cu.end_$protectedcourse\_$role.value,'end_$protectedcourse\_$role','cu.pres','dateset')">$lt->{'sed'}</a></td>
 7407: ENDTIMEENTRY
 7408:     $row .= &Apache::loncommon::end_data_table_row();
 7409:     return $row;
 7410: }
 7411: 
 7412: sub course_level_dc {
 7413:     my ($dcdom,$showcredits) = @_;
 7414:     my %customroles=&Apache::lonuserutils::my_custom_roles();
 7415:     my @roles = &Apache::lonuserutils::roles_by_context('course');
 7416:     my $hiddenitems = '<input type="hidden" name="dcdomain" value="'.$dcdom.'" />'.
 7417:                       '<input type="hidden" name="origdom" value="'.$dcdom.'" />'.
 7418:                       '<input type="hidden" name="dccourse" value="" />';
 7419:     my $courseform=&Apache::loncommon::selectcourse_link
 7420:             ('cu','dccourse','dcdomain','coursedesc',undef,undef,'Select','crstype');
 7421:     my $credit_elem;
 7422:     if ($showcredits) {
 7423:         $credit_elem = 'credits';
 7424:     }
 7425:     my $cb_jscript = &Apache::loncommon::coursebrowser_javascript($dcdom,'currsec','cu','role','Course/Community Browser',$credit_elem);
 7426:     my %lt=&Apache::lonlocal::texthash(
 7427:                     'rol'  => "Role",
 7428:                     'grs'  => "Section",
 7429:                     'exs'  => "Existing sections",
 7430:                     'new'  => "Define new section", 
 7431:                     'sta'  => "Start",
 7432:                     'end'  => "End",
 7433:                     'ssd'  => "Set Start Date",
 7434:                     'sed'  => "Set End Date",
 7435:                     'scc'  => "Course/Community",
 7436:                     'crd'  => "Credits",
 7437:                   );
 7438:     my $header = '<h4>'.&mt('Course/Community Level').'</h4>'.
 7439:                  &Apache::loncommon::start_data_table().
 7440:                  &Apache::loncommon::start_data_table_header_row().
 7441:                  '<th>'.$lt{'scc'}.'</th><th>'.$lt{'rol'}.'</th>'."\n".
 7442:                  '<th>'.$lt{'grs'}.'</th>'."\n";
 7443:     $header .=   '<th>'.$lt{'crd'}.'</th>'."\n" if ($showcredits);
 7444:     $header .=   '<th>'.$lt{'sta'}.'</th><th>'.$lt{'end'}.'</th>'."\n".
 7445:                  &Apache::loncommon::end_data_table_header_row();
 7446:     my $otheritems = &Apache::loncommon::start_data_table_row()."\n".
 7447:                      '<td><br /><span class="LC_nobreak"><input type="text" name="coursedesc" value="" onfocus="this.blur();opencrsbrowser('."'cu','dccourse','dcdomain','coursedesc','','','','crstype'".')" />'.
 7448:                      $courseform.('&nbsp;' x4).'</span></td>'."\n".
 7449:                      '<td valign="top"><br /><select name="role">'."\n";
 7450:     foreach my $role (@roles) {
 7451:         my $plrole=&Apache::lonnet::plaintext($role);
 7452:         $otheritems .= '  <option value="'.$role.'">'.$plrole.'</option>';
 7453:     }
 7454:     if ( keys %customroles > 0) {
 7455:         foreach my $cust (sort keys %customroles) {
 7456:             my $custrole='cr_cr_'.$env{'user.domain'}.
 7457:                     '_'.$env{'user.name'}.'_'.$cust;
 7458:             $otheritems .= '  <option value="'.$custrole.'">'.$cust.'</option>';
 7459:         }
 7460:     }
 7461:     $otheritems .= '</select></td><td>'.
 7462:                      '<table border="0" cellspacing="0" cellpadding="0">'.
 7463:                      '<tr><td valign="top"><b>'.$lt{'exs'}.'</b><br /><select name="currsec">'.
 7464:                      ' <option value="">&lt;--'.&mt('Pick course first').'</option></select></td>'.
 7465:                      '<td>&nbsp;&nbsp;</td>'.
 7466:                      '<td valign="top">&nbsp;<b>'.$lt{'new'}.'</b><br />'.
 7467:                      '<input type="text" name="newsec" value="" />'.
 7468:                      '<input type="hidden" name="section" value="" />'.
 7469:                      '<input type="hidden" name="groups" value="" />'.
 7470:                      '<input type="hidden" name="crstype" value="" /></td>'.
 7471:                      '</tr></table></td>'."\n";
 7472:     if ($showcredits) {
 7473:         $otheritems .= '<td><br />'."\n".
 7474:                        '<input type="text" size="3" name="credits" value="" /></td>'."\n";
 7475:     }
 7476:     $otheritems .= <<ENDTIMEENTRY;
 7477: <td><br /><input type="hidden" name="start" value='' />
 7478: <a href=
 7479: "javascript:pjump('date_start','Start Date',document.cu.start.value,'start','cu.pres','dateset')">$lt{'ssd'}</a></td>
 7480: <td><br /><input type="hidden" name="end" value='' />
 7481: <a href=
 7482: "javascript:pjump('date_end','End Date',document.cu.end.value,'end','cu.pres','dateset')">$lt{'sed'}</a></td>
 7483: ENDTIMEENTRY
 7484:     $otheritems .= &Apache::loncommon::end_data_table_row().
 7485:                    &Apache::loncommon::end_data_table()."\n";
 7486:     return $cb_jscript.$header.$hiddenitems.$otheritems;
 7487: }
 7488: 
 7489: sub update_selfenroll_config {
 7490:     my ($r,$cid,$cdom,$cnum,$context,$crstype,$currsettings) = @_;
 7491:     return unless (ref($currsettings) eq 'HASH');
 7492:     my ($row,$lt) = &Apache::lonuserutils::get_selfenroll_titles();
 7493:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
 7494:     my (%changes,%warning);
 7495:     my $curr_types;
 7496:     my %noedit;
 7497:     unless ($context eq 'domain') {
 7498:         %noedit = &get_noedit_fields($cdom,$cnum,$crstype,$row);
 7499:     }
 7500:     if (ref($row) eq 'ARRAY') {
 7501:         foreach my $item (@{$row}) {
 7502:             next if ($noedit{$item});
 7503:             if ($item eq 'enroll_dates') {
 7504:                 my (%currenrolldate,%newenrolldate);
 7505:                 foreach my $type ('start','end') {
 7506:                     $currenrolldate{$type} = $currsettings->{'selfenroll_'.$type.'_date'};
 7507:                     $newenrolldate{$type} = &Apache::lonhtmlcommon::get_date_from_form('selfenroll_'.$type.'_date');
 7508:                     if ($newenrolldate{$type} ne $currenrolldate{$type}) {
 7509:                         $changes{'internal.selfenroll_'.$type.'_date'} = $newenrolldate{$type};
 7510:                     }
 7511:                 }
 7512:             } elsif ($item eq 'access_dates') {
 7513:                 my (%currdate,%newdate);
 7514:                 foreach my $type ('start','end') {
 7515:                     $currdate{$type} = $currsettings->{'selfenroll_'.$type.'_access'};
 7516:                     $newdate{$type} = &Apache::lonhtmlcommon::get_date_from_form('selfenroll_'.$type.'_access');
 7517:                     if ($newdate{$type} ne $currdate{$type}) {
 7518:                         $changes{'internal.selfenroll_'.$type.'_access'} = $newdate{$type};
 7519:                     }
 7520:                 }
 7521:             } elsif ($item eq 'types') {
 7522:                 $curr_types = $currsettings->{'selfenroll_'.$item};
 7523:                 if ($env{'form.selfenroll_all'}) {
 7524:                     if ($curr_types ne '*') {
 7525:                         $changes{'internal.selfenroll_types'} = '*';
 7526:                     } else {
 7527:                         next;
 7528:                     }
 7529:                 } else {
 7530:                     my %currdoms;
 7531:                     my @entries = split(/;/,$curr_types);
 7532:                     my @deletedoms = &Apache::loncommon::get_env_multiple('form.selfenroll_delete');
 7533:                     my @activations = &Apache::loncommon::get_env_multiple('form.selfenroll_activate');
 7534:                     my $newnum = 0;
 7535:                     my @latesttypes;
 7536:                     foreach my $num (@activations) {
 7537:                         my @types = &Apache::loncommon::get_env_multiple('form.selfenroll_types_'.$num);
 7538:                         if (@types > 0) {
 7539:                             @types = sort(@types);
 7540:                             my $typestr = join(',',@types);
 7541:                             my $typedom = $env{'form.selfenroll_dom_'.$num};
 7542:                             $latesttypes[$newnum] = $typedom.':'.$typestr;
 7543:                             $currdoms{$typedom} = 1;
 7544:                             $newnum ++;
 7545:                         }
 7546:                     }
 7547:                     for (my $j=0; $j<$env{'form.selfenroll_types_total'}; $j++) {
 7548:                         if ((!grep(/^$j$/,@deletedoms)) && (!grep(/^$j$/,@activations))) {
 7549:                             my @types = &Apache::loncommon::get_env_multiple('form.selfenroll_types_'.$j);
 7550:                             if (@types > 0) {
 7551:                                 @types = sort(@types);
 7552:                                 my $typestr = join(',',@types);
 7553:                                 my $typedom = $env{'form.selfenroll_dom_'.$j};
 7554:                                 $latesttypes[$newnum] = $typedom.':'.$typestr;
 7555:                                 $currdoms{$typedom} = 1;
 7556:                                 $newnum ++;
 7557:                             }
 7558:                         }
 7559:                     }
 7560:                     if ($env{'form.selfenroll_newdom'} ne '') {
 7561:                         my $typedom = $env{'form.selfenroll_newdom'};
 7562:                         if ((!defined($currdoms{$typedom})) && 
 7563:                             (&Apache::lonnet::domain($typedom) ne '')) {
 7564:                             my $typestr;
 7565:                             my ($othertitle,$usertypes,$types) = 
 7566:                                 &Apache::loncommon::sorted_inst_types($typedom);
 7567:                             my $othervalue = 'any';
 7568:                             if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 7569:                                 if (@{$types} > 0) {
 7570:                                     my @esc_types = map { &escape($_); } @{$types};
 7571:                                     $othervalue = 'other';
 7572:                                     $typestr = join(',',(@esc_types,$othervalue));
 7573:                                 }
 7574:                                 $typestr = $othervalue;
 7575:                             } else {
 7576:                                 $typestr = $othervalue;
 7577:                             } 
 7578:                             $latesttypes[$newnum] = $typedom.':'.$typestr;
 7579:                             $newnum ++ ;
 7580:                         }
 7581:                     }
 7582:                     my $selfenroll_types = join(';',@latesttypes);
 7583:                     if ($selfenroll_types ne $curr_types) {
 7584:                         $changes{'internal.selfenroll_types'} = $selfenroll_types;
 7585:                     }
 7586:                 }
 7587:             } elsif ($item eq 'limit') {
 7588:                 my $newlimit = $env{'form.selfenroll_limit'};
 7589:                 my $newcap = $env{'form.selfenroll_cap'};
 7590:                 $newcap =~s/\s+//g;
 7591:                 my $currlimit =  $currsettings->{'selfenroll_limit'};
 7592:                 $currlimit = 'none' if ($currlimit eq '');
 7593:                 my $currcap = $currsettings->{'selfenroll_cap'};
 7594:                 if ($newlimit ne $currlimit) {
 7595:                     if ($newlimit ne 'none') {
 7596:                         if ($newcap =~ /^\d+$/) {
 7597:                             if ($newcap ne $currcap) {
 7598:                                 $changes{'internal.selfenroll_cap'} = $newcap;
 7599:                             }
 7600:                             $changes{'internal.selfenroll_limit'} = $newlimit;
 7601:                         } else {
 7602:                             $warning{$item} = &mt('Maximum enrollment setting unchanged.').'<br />'.
 7603:                                 &mt('The value provided was invalid - it must be a positive integer if enrollment is being limited.'); 
 7604:                         }
 7605:                     } elsif ($currcap ne '') {
 7606:                         $changes{'internal.selfenroll_cap'} = '';
 7607:                         $changes{'internal.selfenroll_limit'} = $newlimit; 
 7608:                     }
 7609:                 } elsif ($currlimit ne 'none') {
 7610:                     if ($newcap =~ /^\d+$/) {
 7611:                         if ($newcap ne $currcap) {
 7612:                             $changes{'internal.selfenroll_cap'} = $newcap;
 7613:                         }
 7614:                     } else {
 7615:                         $warning{$item} = &mt('Maximum enrollment setting unchanged.').'<br />'.
 7616:                             &mt('The value provided was invalid - it must be a positive integer if enrollment is being limited.');
 7617:                     }
 7618:                 }
 7619:             } elsif ($item eq 'approval') {
 7620:                 my (@currnotified,@newnotified);
 7621:                 my $currapproval = $currsettings->{'selfenroll_approval'};
 7622:                 my $currnotifylist = $currsettings->{'selfenroll_notifylist'};
 7623:                 if ($currnotifylist ne '') {
 7624:                     @currnotified = split(/,/,$currnotifylist);
 7625:                     @currnotified = sort(@currnotified);
 7626:                 }
 7627:                 my $newapproval = $env{'form.selfenroll_approval'};
 7628:                 @newnotified = &Apache::loncommon::get_env_multiple('form.selfenroll_notify');
 7629:                 @newnotified = sort(@newnotified);
 7630:                 if ($newapproval ne $currapproval) {
 7631:                     $changes{'internal.selfenroll_approval'} = $newapproval;
 7632:                     if (!$newapproval) {
 7633:                         if ($currnotifylist ne '') {
 7634:                             $changes{'internal.selfenroll_notifylist'} = '';
 7635:                         }
 7636:                     } else {
 7637:                         my @differences =  
 7638:                             &Apache::loncommon::compare_arrays(\@currnotified,\@newnotified);
 7639:                         if (@differences > 0) {
 7640:                             if (@newnotified > 0) {
 7641:                                 $changes{'internal.selfenroll_notifylist'} = join(',',@newnotified);
 7642:                             } else {
 7643:                                 $changes{'internal.selfenroll_notifylist'} = join(',',@newnotified);
 7644:                             }
 7645:                         }
 7646:                     }
 7647:                 } else {
 7648:                     my @differences = &Apache::loncommon::compare_arrays(\@currnotified,\@newnotified);
 7649:                     if (@differences > 0) {
 7650:                         if (@newnotified > 0) {
 7651:                             $changes{'internal.selfenroll_notifylist'} = join(',',@newnotified);
 7652:                         } else {
 7653:                             $changes{'internal.selfenroll_notifylist'} = '';
 7654:                         }
 7655:                     }
 7656:                 }
 7657:             } else {
 7658:                 my $curr_val = $currsettings->{'selfenroll_'.$item};
 7659:                 my $newval = $env{'form.selfenroll_'.$item};
 7660:                 if ($item eq 'section') {
 7661:                     $newval = $env{'form.sections'};
 7662:                     if (defined($curr_groups{$newval})) {
 7663:                         $newval = $curr_val;
 7664:                         $warning{$item} = &mt('Section for self-enrolled users unchanged as the proposed section is a group').'<br />'.
 7665:                                           &mt('Group names and section names must be distinct');
 7666:                     } elsif ($newval eq 'all') {
 7667:                         $newval = $curr_val;
 7668:                         $warning{$item} = &mt('Section for self-enrolled users unchanged, as "all" is a reserved section name.');
 7669:                     }
 7670:                     if ($newval eq '') {
 7671:                         $newval = 'none';
 7672:                     }
 7673:                 }
 7674:                 if ($newval ne $curr_val) {
 7675:                     $changes{'internal.selfenroll_'.$item} = $newval;
 7676:                 }
 7677:             }
 7678:         }
 7679:         if (keys(%warning) > 0) {
 7680:             foreach my $item (@{$row}) {
 7681:                 if (exists($warning{$item})) {
 7682:                     $r->print($warning{$item}.'<br />');
 7683:                 }
 7684:             } 
 7685:         }
 7686:         if (keys(%changes) > 0) {
 7687:             my $putresult = &Apache::lonnet::put('environment',\%changes,$cdom,$cnum);
 7688:             if ($putresult eq 'ok') {
 7689:                 if ((exists($changes{'internal.selfenroll_types'})) ||
 7690:                     (exists($changes{'internal.selfenroll_start_date'}))  ||
 7691:                     (exists($changes{'internal.selfenroll_end_date'}))) {
 7692:                     my %crsinfo = &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',
 7693:                                                                 $cnum,undef,undef,'Course');
 7694:                     my $chome = &Apache::lonnet::homeserver($cnum,$cdom);
 7695:                     if (ref($crsinfo{$cid}) eq 'HASH') {
 7696:                         foreach my $item ('selfenroll_types','selfenroll_start_date','selfenroll_end_date') {
 7697:                             if (exists($changes{'internal.'.$item})) {
 7698:                                 $crsinfo{$cid}{$item} = $changes{'internal.'.$item};
 7699:                             }
 7700:                         }
 7701:                         my $crsputresult =
 7702:                             &Apache::lonnet::courseidput($cdom,\%crsinfo,
 7703:                                                          $chome,'notime');
 7704:                     }
 7705:                 }
 7706:                 $r->print(&mt('The following changes were made to self-enrollment settings:').'<ul>');
 7707:                 foreach my $item (@{$row}) {
 7708:                     my $title = $item;
 7709:                     if (ref($lt) eq 'HASH') {
 7710:                         $title = $lt->{$item};
 7711:                     }
 7712:                     if ($item eq 'enroll_dates') {
 7713:                         foreach my $type ('start','end') {
 7714:                             if (exists($changes{'internal.selfenroll_'.$type.'_date'})) {
 7715:                                 my $newdate = &Apache::lonlocal::locallocaltime($changes{'internal.selfenroll_'.$type.'_date'});
 7716:                                 $r->print('<li>'.&mt('[_1]: "[_2]" set to "[_3]".',
 7717:                                           $title,$type,$newdate).'</li>');
 7718:                             }
 7719:                         }
 7720:                     } elsif ($item eq 'access_dates') {
 7721:                         foreach my $type ('start','end') {
 7722:                             if (exists($changes{'internal.selfenroll_'.$type.'_access'})) {
 7723:                                 my $newdate = &Apache::lonlocal::locallocaltime($changes{'internal.selfenroll_'.$type.'_access'});
 7724:                                 $r->print('<li>'.&mt('[_1]: "[_2]" set to "[_3]".',
 7725:                                           $title,$type,$newdate).'</li>');
 7726:                             }
 7727:                         }
 7728:                     } elsif ($item eq 'limit') {
 7729:                         if ((exists($changes{'internal.selfenroll_limit'})) ||
 7730:                             (exists($changes{'internal.selfenroll_cap'}))) {
 7731:                             my ($newval,$newcap);
 7732:                             if ($changes{'internal.selfenroll_cap'} ne '') {
 7733:                                 $newcap = $changes{'internal.selfenroll_cap'}
 7734:                             } else {
 7735:                                 $newcap = $currsettings->{'selfenroll_cap'};
 7736:                             }
 7737:                             if ($changes{'internal.selfenroll_limit'} eq 'none') {
 7738:                                 $newval = &mt('No limit');
 7739:                             } elsif ($changes{'internal.selfenroll_limit'} eq 
 7740:                                      'allstudents') {
 7741:                                 $newval = &mt('New self-enrollment no longer allowed when total (all students) reaches [_1].',$newcap);
 7742:                             } elsif ($changes{'internal.selfenroll_limit'} eq 'selfenrolled') {
 7743:                                 $newval = &mt('New self-enrollment no longer allowed when total number of self-enrolled students reaches [_1].',$newcap);
 7744:                             } else {
 7745:                                 my $currlimit =  $currsettings->{'selfenroll_limit'};
 7746:                                 if ($currlimit eq 'allstudents') {
 7747:                                     $newval = &mt('New self-enrollment no longer allowed when total (all students) reaches [_1].',$newcap);
 7748:                                 } elsif ($changes{'internal.selfenroll_limit'} eq 'selfenrolled') {
 7749:                                     $newval =  &mt('New self-enrollment no longer allowed when total number of self-enrolled students reaches [_1].',$newcap);
 7750:                                 }
 7751:                             }
 7752:                             $r->print('<li>'.&mt('"[_1]" set to "[_2]".',$title,$newval).'</li>'."\n");
 7753:                         }
 7754:                     } elsif ($item eq 'approval') {
 7755:                         if ((exists($changes{'internal.selfenroll_approval'})) ||
 7756:                             (exists($changes{'internal.selfenroll_notifylist'}))) {
 7757:                             my %selfdescs = &Apache::lonuserutils::selfenroll_default_descs();
 7758:                             my ($newval,$newnotify);
 7759:                             if (exists($changes{'internal.selfenroll_notifylist'})) {
 7760:                                 $newnotify = $changes{'internal.selfenroll_notifylist'};
 7761:                             } else {   
 7762:                                 $newnotify = $currsettings->{'selfenroll_notifylist'};
 7763:                             }
 7764:                             if (exists($changes{'internal.selfenroll_approval'})) {
 7765:                                 if ($changes{'internal.selfenroll_approval'} !~ /^[012]$/) {
 7766:                                     $changes{'internal.selfenroll_approval'} = '0';
 7767:                                 }
 7768:                                 $newval = $selfdescs{'approval'}{$changes{'internal.selfenroll_approval'}};
 7769:                             } else {
 7770:                                 my $currapproval = $currsettings->{'selfenroll_approval'}; 
 7771:                                 if ($currapproval !~ /^[012]$/) {
 7772:                                     $currapproval = 0;
 7773:                                 }
 7774:                                 $newval = $selfdescs{'approval'}{$currapproval};
 7775:                             }
 7776:                             $r->print('<li>'.&mt('"[_1]" set to "[_2]".',$title,$newval));
 7777:                             if ($newnotify) {
 7778:                                 $r->print('<br />'.&mt('The following will be notified when an enrollment request needs approval, or has been approved: [_1].',$newnotify));
 7779:                             } else {
 7780:                                 $r->print('<br />'.&mt('No notifications sent when an enrollment request needs approval, or has been approved.'));
 7781:                             }
 7782:                             $r->print('</li>'."\n");
 7783:                         }
 7784:                     } else {
 7785:                         if (exists($changes{'internal.selfenroll_'.$item})) {
 7786:                             my $newval = $changes{'internal.selfenroll_'.$item};
 7787:                             if ($item eq 'types') {
 7788:                                 if ($newval eq '') {
 7789:                                     $newval = &mt('None');
 7790:                                 } elsif ($newval eq '*') {
 7791:                                     $newval = &mt('Any user in any domain');
 7792:                                 }
 7793:                             } elsif ($item eq 'registered') {
 7794:                                 if ($newval eq '1') {
 7795:                                     $newval = &mt('Yes');
 7796:                                 } elsif ($newval eq '0') {
 7797:                                     $newval = &mt('No');
 7798:                                 }
 7799:                             }
 7800:                             $r->print('<li>'.&mt('"[_1]" set to "[_2]".',$title,$newval).'</li>'."\n");
 7801:                         }
 7802:                     }
 7803:                 }
 7804:                 $r->print('</ul>');
 7805:                 if ($env{'course.'.$cid.'.description'} ne '') {
 7806:                     my %newenvhash;
 7807:                     foreach my $key (keys(%changes)) {
 7808:                         $newenvhash{'course.'.$cid.'.'.$key} = $changes{$key};
 7809:                     }
 7810:                     &Apache::lonnet::appenv(\%newenvhash);
 7811:                 }
 7812:             } else {
 7813:                 $r->print(&mt('An error occurred when saving changes to self-enrollment settings in this course.').'<br />'.
 7814:                           &mt('The error was: [_1].',$putresult));
 7815:             }
 7816:         } else {
 7817:             $r->print(&mt('No changes were made to the existing self-enrollment settings in this course.'));
 7818:         }
 7819:     } else {
 7820:         $r->print(&mt('No changes were made to the existing self-enrollment settings in this course.'));
 7821:     }
 7822:     my $visactions = &cat_visibility();
 7823:     my ($cathash,%cattype);
 7824:     my %domconfig = &Apache::lonnet::get_dom('configuration',['coursecategories'],$cdom);
 7825:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 7826:         $cathash = $domconfig{'coursecategories'}{'cats'};
 7827:         $cattype{'auth'} = $domconfig{'coursecategories'}{'auth'};
 7828:         $cattype{'unauth'} = $domconfig{'coursecategories'}{'unauth'};
 7829:     } else {
 7830:         $cathash = {};
 7831:         $cattype{'auth'} = 'std';
 7832:         $cattype{'unauth'} = 'std';
 7833:     }
 7834:     if (($cattype{'auth'} eq 'none') && ($cattype{'unauth'} eq 'none')) {
 7835:         $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
 7836:                   '<br />'.
 7837:                   '<br />'.$visactions->{'take'}.'<ul>'.
 7838:                   '<li>'.$visactions->{'dc_chgconf'}.'</li>'.
 7839:                   '</ul>');
 7840:     } elsif (($cattype{'auth'} !~ /^(std|domonly)$/) && ($cattype{'unauth'} !~ /^(std|domonly)$/)) {
 7841:         if ($currsettings->{'uniquecode'}) {
 7842:             $r->print('<span class="LC_info">'.$visactions->{'vis'}.'</span>');
 7843:         } else {
 7844:             $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
 7845:                   '<br />'.
 7846:                   '<br />'.$visactions->{'take'}.'<ul>'.
 7847:                   '<li>'.$visactions->{'dc_setcode'}.'</li>'.
 7848:                   '</ul><br />');
 7849:         }
 7850:     } else {
 7851:         my ($visible,$cansetvis,$vismsgs) = &visible_in_stdcat($cdom,$cnum,\%domconfig);
 7852:         if (ref($visactions) eq 'HASH') {
 7853:             if (!$visible) {
 7854:                 $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
 7855:                           '<br />');
 7856:                 if (ref($vismsgs) eq 'ARRAY') {
 7857:                     $r->print('<br />'.$visactions->{'take'}.'<ul>');
 7858:                     foreach my $item (@{$vismsgs}) {
 7859:                         $r->print('<li>'.$visactions->{$item}.'</li>');
 7860:                     }
 7861:                     $r->print('</ul>');
 7862:                 }
 7863:                 $r->print($cansetvis);
 7864:             }
 7865:         }
 7866:     } 
 7867:     return;
 7868: }
 7869: 
 7870: #---------------------------------------------- end functions for &phase_two
 7871: 
 7872: #--------------------------------- functions for &phase_two and &phase_three
 7873: 
 7874: #--------------------------end of functions for &phase_two and &phase_three
 7875: 
 7876: 1;
 7877: __END__
 7878: 
 7879: 

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