File:  [LON-CAPA] / loncom / interface / loncreateuser.pm
Revision 1.411: download - view: text, annotated - select for diffs
Sat Apr 2 04:30:20 2016 UTC (8 years, 2 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Bug 6808. New course container -- "Placement" for Placement Tests.
  Work in progress.

    1: # The LearningOnline Network with CAPA
    2: # Create a user
    3: #
    4: # $Id: loncreateuser.pm,v 1.411 2016/04/02 04:30:20 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:                    'placement'  => 'Can request creation of placement tests',
  255:                    'requestauthor'  => 'Can request author space',
  256:     );
  257:     if ($context eq 'requestcourses') {
  258:         %userenv = &Apache::lonnet::userenvironment($ccdomain,$ccuname,
  259:                       'requestcourses.official','requestcourses.unofficial',
  260:                       'requestcourses.community','requestcourses.textbook',
  261:                       'requestcourses.placement');
  262:         @usertools = ('official','unofficial','community','textbook','placement');
  263:         @options =('norequest','approval','autolimit','validate');
  264:         %validations = &Apache::lonnet::auto_courserequest_checks($ccdomain);
  265:         %reqtitles = &courserequest_titles();
  266:         %reqdisplay = &courserequest_display();
  267:         $colspan = ' colspan="2"';
  268:         %domconfig =
  269:             &Apache::lonnet::get_dom('configuration',['requestcourses'],$ccdomain);
  270:         $isadv = &Apache::lonnet::is_advanced_user($ccuname,$ccdomain);
  271:     } elsif ($context eq 'requestauthor') {
  272:         %userenv = &Apache::lonnet::userenvironment($ccdomain,$ccuname,
  273:                                                     'requestauthor');
  274:         @usertools = ('requestauthor');
  275:         @options =('norequest','approval','automatic');
  276:         %reqtitles = &requestauthor_titles();
  277:         %reqdisplay = &requestauthor_display();
  278:         $colspan = ' colspan="2"';
  279:         %domconfig =
  280:             &Apache::lonnet::get_dom('configuration',['requestauthor'],$ccdomain);
  281:     } else {
  282:         %userenv = &Apache::lonnet::userenvironment($ccdomain,$ccuname,
  283:                           'tools.aboutme','tools.portfolio','tools.blog',
  284:                           'tools.webdav');
  285:         @usertools = ('aboutme','blog','webdav','portfolio');
  286:     }
  287:     foreach my $item (@usertools) {
  288:         my ($custom_access,$curr_access,$cust_on,$cust_off,$tool_on,$tool_off,
  289:             $currdisp,$custdisp,$custradio);
  290:         $cust_off = 'checked="checked" ';
  291:         $tool_on = 'checked="checked" ';
  292:         $curr_access =  
  293:             &Apache::lonnet::usertools_access($ccuname,$ccdomain,$item,undef,
  294:                                               $context);
  295:         if ($context eq 'requestauthor') {
  296:             if ($userenv{$context} ne '') {
  297:                 $cust_on = ' checked="checked" ';
  298:                 $cust_off = '';
  299:             }  
  300:         } elsif ($userenv{$context.'.'.$item} ne '') {
  301:             $cust_on = ' checked="checked" ';
  302:             $cust_off = '';
  303:         }
  304:         if ($context eq 'requestcourses') {
  305:             if ($userenv{$context.'.'.$item} eq '') {
  306:                 $custom_access = &mt('Currently from default setting.');
  307:             } else {
  308:                 $custom_access = &mt('Currently from custom setting.');
  309:             }
  310:         } elsif ($context eq 'requestauthor') {
  311:             if ($userenv{$context} eq '') {
  312:                 $custom_access = &mt('Currently from default setting.');
  313:             } else {
  314:                 $custom_access = &mt('Currently from custom setting.');
  315:             }
  316:         } else {
  317:             if ($userenv{$context.'.'.$item} eq '') {
  318:                 $custom_access =
  319:                     &mt('Availability determined currently from default setting.');
  320:                 if (!$curr_access) {
  321:                     $tool_off = 'checked="checked" ';
  322:                     $tool_on = '';
  323:                 }
  324:             } else {
  325:                 $custom_access =
  326:                     &mt('Availability determined currently from custom setting.');
  327:                 if ($userenv{$context.'.'.$item} == 0) {
  328:                     $tool_off = 'checked="checked" ';
  329:                     $tool_on = '';
  330:                 }
  331:             }
  332:         }
  333:         $output .= '  <tr class="LC_info_row">'."\n".
  334:                    '   <td'.$colspan.'>'.$lt{$item}.'</td>'."\n".
  335:                    '  </tr>'."\n".
  336:                    &Apache::loncommon::start_data_table_row()."\n";
  337:         if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
  338:             my ($curroption,$currlimit);
  339:             my $envkey = $context.'.'.$item;
  340:             if ($context eq 'requestauthor') {
  341:                 $envkey = $context;
  342:             }
  343:             if ($userenv{$envkey} ne '') {
  344:                 $curroption = $userenv{$envkey};
  345:             } else {
  346:                 my (@inststatuses);
  347:                 if ($context eq 'requestcourses') {
  348:                     $curroption =
  349:                         &Apache::loncoursequeueadmin::get_processtype('course',$ccuname,$ccdomain,
  350:                                                                       $isadv,$ccdomain,$item,
  351:                                                                       \@inststatuses,\%domconfig);
  352:                 } else {
  353:                      $curroption = 
  354:                          &Apache::loncoursequeueadmin::get_processtype('requestauthor',$ccuname,$ccdomain,
  355:                                                                        $isadv,$ccdomain,undef,
  356:                                                                        \@inststatuses,\%domconfig);
  357:                 }
  358:             }
  359:             if (!$curroption) {
  360:                 $curroption = 'norequest';
  361:             }
  362:             if ($curroption =~ /^autolimit=(\d*)$/) {
  363:                 $currlimit = $1;
  364:                 if ($currlimit eq '') {
  365:                     $currdisp = &mt('Yes, automatic creation');
  366:                 } else {
  367:                     $currdisp = &mt('Yes, up to [quant,_1,request]/user',$currlimit);
  368:                 }
  369:             } else {
  370:                 $currdisp = $reqdisplay{$curroption};
  371:             }
  372:             $custdisp = '<table>';
  373:             foreach my $option (@options) {
  374:                 my $val = $option;
  375:                 if ($option eq 'norequest') {
  376:                     $val = 0;
  377:                 }
  378:                 if ($option eq 'validate') {
  379:                     my $canvalidate = 0;
  380:                     if (ref($validations{$item}) eq 'HASH') {
  381:                         if ($validations{$item}{'_custom_'}) {
  382:                             $canvalidate = 1;
  383:                         }
  384:                     }
  385:                     next if (!$canvalidate);
  386:                 }
  387:                 my $checked = '';
  388:                 if ($option eq $curroption) {
  389:                     $checked = ' checked="checked"';
  390:                 } elsif ($option eq 'autolimit') {
  391:                     if ($curroption =~ /^autolimit/) {
  392:                         $checked = ' checked="checked"';
  393:                     }
  394:                 }
  395:                 my $name = 'crsreq_'.$item;
  396:                 if ($context eq 'requestauthor') {
  397:                     $name = $item;
  398:                 }
  399:                 $custdisp .= '<tr><td><span class="LC_nobreak"><label>'.
  400:                              '<input type="radio" name="'.$name.'" '.
  401:                              'value="'.$val.'"'.$checked.' />'.
  402:                              $reqtitles{$option}.'</label>&nbsp;';
  403:                 if ($option eq 'autolimit') {
  404:                     $custdisp .= '<input type="text" name="'.$name.
  405:                                  '_limit" size="1" '.
  406:                                  'value="'.$currlimit.'" /></span><br />'.
  407:                                  $reqtitles{'unlimited'};
  408:                 } else {
  409:                     $custdisp .= '</span>';
  410:                 }
  411:                 $custdisp .= '</td></tr>';
  412:             }
  413:             $custdisp .= '</table>';
  414:             $custradio = '</span></td><td>'.&mt('Custom setting').'<br />'.$custdisp;
  415:         } else {
  416:             $currdisp = ($curr_access?&mt('Yes'):&mt('No'));
  417:             my $name = $context.'_'.$item;
  418:             if ($context eq 'requestauthor') {
  419:                 $name = $context;
  420:             }
  421:             $custdisp = '<span class="LC_nobreak"><label>'.
  422:                         '<input type="radio" name="'.$name.'"'.
  423:                         ' value="1" '.$tool_on.'/>'.&mt('On').'</label>&nbsp;<label>'.
  424:                         '<input type="radio" name="'.$name.'" value="0" '.
  425:                         $tool_off.'/>'.&mt('Off').'</label></span>';
  426:             $custradio = ('&nbsp;'x2).'--'.$lt{'cusa'}.':&nbsp;'.$custdisp.
  427:                           '</span>';
  428:         }
  429:         $output .= '  <td'.$colspan.'>'.$custom_access.('&nbsp;'x4).
  430:                    $lt{'avai'}.': '.$currdisp.'</td>'."\n".
  431:                    &Apache::loncommon::end_data_table_row()."\n".
  432:                    &Apache::loncommon::start_data_table_row()."\n".
  433:                    '  <td style="vertical-align:top;"><span class="LC_nobreak">'.
  434:                    $lt{'chse'}.': <label>'.
  435:                    '<input type="radio" name="custom'.$item.'" value="0" '.
  436:                    $cust_off.'/>'.$lt{'usde'}.'</label>'.('&nbsp;' x3).
  437:                    '<label><input type="radio" name="custom'.$item.'" value="1" '.
  438:                    $cust_on.'/>'.$lt{'uscu'}.'</label>'.$custradio.'</td>'.
  439:                    &Apache::loncommon::end_data_table_row()."\n";
  440:     }
  441:     return $output;
  442: }
  443: 
  444: sub coursereq_externaluser {
  445:     my ($ccuname,$ccdomain,$cdom) = @_;
  446:     my (@usertools,@options,%validations,%userenv,$output);
  447:     my %lt = &Apache::lonlocal::texthash (
  448:                    'official'   => 'Can request creation of official courses',
  449:                    'unofficial' => 'Can request creation of unofficial courses',
  450:                    'community'  => 'Can request creation of communities',
  451:                    'textbook'   => 'Can request creation of textbook courses',
  452:                    'placement'  => 'Can request creation of placement tests',
  453:     );
  454: 
  455:     %userenv = &Apache::lonnet::userenvironment($ccdomain,$ccuname,
  456:                       'reqcrsotherdom.official','reqcrsotherdom.unofficial',
  457:                       'reqcrsotherdom.community','reqcrsotherdom.textbook',
  458:                       'reqcrsotherdom.placement');
  459:     @usertools = ('official','unofficial','community','textbook','placement');
  460:     @options = ('approval','validate','autolimit');
  461:     %validations = &Apache::lonnet::auto_courserequest_checks($cdom);
  462:     my $optregex = join('|',@options);
  463:     my %reqtitles = &courserequest_titles();
  464:     foreach my $item (@usertools) {
  465:         my ($curroption,$currlimit,$tooloff);
  466:         if ($userenv{'reqcrsotherdom.'.$item} ne '') {
  467:             my @curr = split(',',$userenv{'reqcrsotherdom.'.$item});
  468:             foreach my $req (@curr) {
  469:                 if ($req =~ /^\Q$cdom\E\:($optregex)=?(\d*)$/) {
  470:                     $curroption = $1;
  471:                     $currlimit = $2;
  472:                     last;
  473:                 }
  474:             }
  475:             if (!$curroption) {
  476:                 $curroption = 'norequest';
  477:                 $tooloff = ' checked="checked"';
  478:             }
  479:         } else {
  480:             $curroption = 'norequest';
  481:             $tooloff = ' checked="checked"';
  482:         }
  483:         $output.= &Apache::loncommon::start_data_table_row()."\n".
  484:                   '  <td><span class="LC_nobreak">'.$lt{$item}.': </span></td><td>'.
  485:                   '<table><tr><td valign="top">'."\n".
  486:                   '<label><input type="radio" name="reqcrsotherdom_'.$item.
  487:                   '" value=""'.$tooloff.' />'.$reqtitles{'norequest'}.
  488:                   '</label></td>';
  489:         foreach my $option (@options) {
  490:             if ($option eq 'validate') {
  491:                 my $canvalidate = 0;
  492:                 if (ref($validations{$item}) eq 'HASH') {
  493:                     if ($validations{$item}{'_external_'}) {
  494:                         $canvalidate = 1;
  495:                     }
  496:                 }
  497:                 next if (!$canvalidate);
  498:             }
  499:             my $checked = '';
  500:             if ($option eq $curroption) {
  501:                 $checked = ' checked="checked"';
  502:             }
  503:             $output .= '<td valign="top"><span class="LC_nobreak"><label>'.
  504:                        '<input type="radio" name="reqcrsotherdom_'.$item.
  505:                        '" value="'.$option.'"'.$checked.' />'.
  506:                        $reqtitles{$option}.'</label>';
  507:             if ($option eq 'autolimit') {
  508:                 $output .= '&nbsp;<input type="text" name="reqcrsotherdom_'.
  509:                            $item.'_limit" size="1" '.
  510:                            'value="'.$currlimit.'" /></span>'.
  511:                            '<br />'.$reqtitles{'unlimited'};
  512:             } else {
  513:                 $output .= '</span>';
  514:             }
  515:             $output .= '</td>';
  516:         }
  517:         $output .= '</td></tr></table></td>'."\n".
  518:                    &Apache::loncommon::end_data_table_row()."\n";
  519:     }
  520:     return $output;
  521: }
  522: 
  523: sub domainrole_req {
  524:     my ($ccuname,$ccdomain) = @_;
  525:     return '<br /><h3>'.
  526:            &mt('User Can Request Assignment of Domain Roles?').
  527:            '</h3>'."\n".
  528:            &Apache::loncommon::start_data_table().
  529:            &build_tools_display($ccuname,$ccdomain,
  530:                                 'requestauthor').
  531:            &Apache::loncommon::end_data_table();
  532: }
  533: 
  534: sub courserequest_titles {
  535:     my %titles = &Apache::lonlocal::texthash (
  536:                                    official   => 'Official',
  537:                                    unofficial => 'Unofficial',
  538:                                    community  => 'Communities',
  539:                                    textbook   => 'Textbook',
  540:                                    placement  => 'Placement Tests',
  541:                                    norequest  => 'Not allowed',
  542:                                    approval   => 'Approval by Dom. Coord.',
  543:                                    validate   => 'With validation',
  544:                                    autolimit  => 'Numerical limit',
  545:                                    unlimited  => '(blank for unlimited)',
  546:                  );
  547:     return %titles;
  548: }
  549: 
  550: sub courserequest_display {
  551:     my %titles = &Apache::lonlocal::texthash (
  552:                                    approval   => 'Yes, need approval',
  553:                                    validate   => 'Yes, with validation',
  554:                                    norequest  => 'No',
  555:    );
  556:    return %titles;
  557: }
  558: 
  559: sub requestauthor_titles {
  560:     my %titles = &Apache::lonlocal::texthash (
  561:                                    norequest  => 'Not allowed',
  562:                                    approval   => 'Approval by Dom. Coord.',
  563:                                    automatic  => 'Automatic approval',
  564:                  );
  565:     return %titles;
  566: 
  567: }
  568: 
  569: sub requestauthor_display {
  570:     my %titles = &Apache::lonlocal::texthash (
  571:                                    approval   => 'Yes, need approval',
  572:                                    automatic  => 'Yes, automatic approval',
  573:                                    norequest  => 'No',
  574:    );
  575:    return %titles;
  576: }
  577: 
  578: sub requestchange_display {
  579:     my %titles = &Apache::lonlocal::texthash (
  580:                                    approval   => "availability set to 'on' (approval required)", 
  581:                                    automatic  => "availability set to 'on' (automatic approval)",
  582:                                    norequest  => "availability set to 'off'",
  583:    );
  584:    return %titles;
  585: }
  586: 
  587: sub curr_requestauthor {
  588:     my ($uname,$udom,$isadv,$inststatuses,$domconfig) = @_;
  589:     return unless ((ref($inststatuses) eq 'ARRAY') && (ref($domconfig) eq 'HASH'));
  590:     if ($uname eq '' || $udom eq '') {
  591:         $uname = $env{'user.name'};
  592:         $udom = $env{'user.domain'};
  593:         $isadv = $env{'user.adv'};
  594:     }
  595:     my (%userenv,%settings,$val);
  596:     my @options = ('automatic','approval');
  597:     %userenv =
  598:         &Apache::lonnet::userenvironment($udom,$uname,'requestauthor','inststatus');
  599:     if ($userenv{'requestauthor'}) {
  600:         $val = $userenv{'requestauthor'};
  601:         @{$inststatuses} = ('_custom_');
  602:     } else {
  603:         my %alltasks;
  604:         if (ref($domconfig->{'requestauthor'}) eq 'HASH') {
  605:             %settings = %{$domconfig->{'requestauthor'}};
  606:             if (($isadv) && ($settings{'_LC_adv'} ne '')) {
  607:                 $val = $settings{'_LC_adv'};
  608:                 @{$inststatuses} = ('_LC_adv_');
  609:             } else {
  610:                 if ($userenv{'inststatus'} ne '') {
  611:                     @{$inststatuses} = split(',',$userenv{'inststatus'});
  612:                 } else {
  613:                     @{$inststatuses} = ('default');
  614:                 }
  615:                 foreach my $status (@{$inststatuses}) {
  616:                     if (exists($settings{$status})) {
  617:                         my $value = $settings{$status};
  618:                         next unless ($value);
  619:                         unless (exists($alltasks{$value})) {
  620:                             if (ref($alltasks{$value}) eq 'ARRAY') {
  621:                                 unless(grep(/^\Q$status\E$/,@{$alltasks{$value}})) {
  622:                                     push(@{$alltasks{$value}},$status);
  623:                                 }
  624:                             } else {
  625:                                 @{$alltasks{$value}} = ($status);
  626:                             }
  627:                         }
  628:                     }
  629:                 }
  630:                 foreach my $option (@options) {
  631:                     if ($alltasks{$option}) {
  632:                         $val = $option;
  633:                         last;
  634:                     }
  635:                 }
  636:             }
  637:         }
  638:     }
  639:     return $val;
  640: }
  641: 
  642: # =================================================================== Phase one
  643: 
  644: sub print_username_entry_form {
  645:     my ($r,$context,$response,$srch,$forcenewuser,$crstype,$brcrum) = @_;
  646:     my $defdom=$env{'request.role.domain'};
  647:     my $formtoset = 'crtuser';
  648:     if (exists($env{'form.startrolename'})) {
  649:         $formtoset = 'docustom';
  650:         $env{'form.rolename'} = $env{'form.startrolename'};
  651:     } elsif ($env{'form.origform'} eq 'crtusername') {
  652:         $formtoset =  $env{'form.origform'};
  653:     }
  654: 
  655:     my ($jsback,$elements) = &crumb_utilities();
  656: 
  657:     my $jscript = &Apache::loncommon::studentbrowser_javascript()."\n".
  658:         '<script type="text/javascript">'."\n".
  659:         '// <![CDATA['."\n".
  660:         &Apache::lonhtmlcommon::set_form_elements($elements->{$formtoset})."\n".
  661:         '// ]]>'."\n".
  662:         '</script>'."\n";
  663: 
  664:     my %existingroles=&Apache::lonuserutils::my_custom_roles($crstype);
  665:     if (($env{'form.action'} eq 'custom') && (keys(%existingroles) > 0)
  666:         && (&Apache::lonnet::allowed('mcr','/'))) {
  667:         $jscript .= &customrole_javascript();
  668:     }
  669:     my $helpitem = 'Course_Change_Privileges';
  670:     if ($env{'form.action'} eq 'custom') {
  671:         $helpitem = 'Course_Editing_Custom_Roles';
  672:     } elsif ($env{'form.action'} eq 'singlestudent') {
  673:         $helpitem = 'Course_Add_Student';
  674:     }
  675:     my %breadcrumb_text = &singleuser_breadcrumb($crstype);
  676:     if ($env{'form.action'} eq 'custom') {
  677:         push(@{$brcrum},
  678:                  {href=>"javascript:backPage(document.crtuser)",       
  679:                   text=>"Pick custom role",
  680:                   help => $helpitem,}
  681:                  );
  682:     } else {
  683:         push (@{$brcrum},
  684:                   {href => "javascript:backPage(document.crtuser)",
  685:                    text => $breadcrumb_text{'search'},
  686:                    help => $helpitem,
  687:                    faq  => 282,
  688:                    bug  => 'Instructor Interface',}
  689:                   );
  690:     }
  691:     my %loaditems = (
  692:                 'onload' => "javascript:setFormElements(document.$formtoset)",
  693:                     );
  694:     my $args = {bread_crumbs           => $brcrum,
  695:                 bread_crumbs_component => 'User Management',
  696:                 add_entries            => \%loaditems,};
  697:     $r->print(&Apache::loncommon::start_page('User Management',$jscript,$args));
  698: 
  699:     my %lt=&Apache::lonlocal::texthash(
  700:                     'srst' => 'Search for a user and enroll as a student',
  701:                     'srme' => 'Search for a user and enroll as a member',
  702:                     'srad' => 'Search for a user and modify/add user information or roles',
  703: 		    'usr'  => "Username",
  704:                     'dom'  => "Domain",
  705:                     'ecrp' => "Define or Edit Custom Role",
  706:                     'nr'   => "role name",
  707:                     'cre'  => "Next",
  708: 				       );
  709: 
  710:     if ($env{'form.action'} eq 'custom') {
  711:         if (&Apache::lonnet::allowed('mcr','/')) {
  712:             my $newroletext = &mt('Define new custom role:');
  713:             $r->print('<form action="/adm/createuser" method="post" name="docustom">'.
  714:                       '<input type="hidden" name="action" value="'.$env{'form.action'}.'" />'.
  715:                       '<input type="hidden" name="phase" value="selected_custom_edit" />'.
  716:                       '<h3>'.$lt{'ecrp'}.'</h3>'.
  717:                       &Apache::loncommon::start_data_table().
  718:                       &Apache::loncommon::start_data_table_row().
  719:                       '<td>');
  720:             if (keys(%existingroles) > 0) {
  721:                 $r->print('<br /><label><input type="radio" name="customroleaction" value="new" checked="checked" onclick="setCustomFields();" /><b>'.$newroletext.'</b></label>');
  722:             } else {
  723:                 $r->print('<br /><input type="hidden" name="customroleaction" value="new" /><b>'.$newroletext.'</b>');
  724:             }
  725:             $r->print('</td><td align="center">'.$lt{'nr'}.'<br /><input type="text" size="15" name="newrolename" onfocus="setCustomAction('."'new'".');" /></td>'.
  726:                       &Apache::loncommon::end_data_table_row());
  727:             if (keys(%existingroles) > 0) {
  728:                 $r->print(&Apache::loncommon::start_data_table_row().'<td><br />'.
  729:                           '<label><input type="radio" name="customroleaction" value="edit" onclick="setCustomFields();"/><b>'.
  730:                           &mt('View/Modify existing role:').'</b></label></td>'.
  731:                           '<td align="center"><br />'.
  732:                           '<select name="rolename" onchange="setCustomAction('."'edit'".');">'.
  733:                           '<option value="" selected="selected">'.
  734:                           &mt('Select'));
  735:                 foreach my $role (sort(keys(%existingroles))) {
  736:                     $r->print('<option value="'.$role.'">'.$role.'</option>');
  737:                 }
  738:                 $r->print('</select>'.
  739:                           '</td>'.
  740:                           &Apache::loncommon::end_data_table_row());
  741:             }
  742:             $r->print(&Apache::loncommon::end_data_table().'<p>'.
  743:                       '<input name="customeditor" type="submit" value="'.
  744:                       $lt{'cre'}.'" /></p>'.
  745:                       '</form>');
  746:         }
  747:     } else {
  748:         my $actiontext = $lt{'srad'};
  749:         if ($env{'form.action'} eq 'singlestudent') {
  750:             if ($crstype eq 'Community') {
  751:                 $actiontext = $lt{'srme'};
  752:             } else {
  753:                 $actiontext = $lt{'srst'};
  754:             }
  755:         }
  756:         $r->print("<h3>$actiontext</h3>");
  757:         if ($env{'form.origform'} ne 'crtusername') {
  758:             $r->print("\n".$response);
  759:         }
  760:         $r->print(&entry_form($defdom,$srch,$forcenewuser,$context,$response,$crstype));
  761:     }
  762: }
  763: 
  764: sub customrole_javascript {
  765:     my $js = <<"END";
  766: <script type="text/javascript">
  767: // <![CDATA[
  768: 
  769: function setCustomFields() {
  770:     if (document.docustom.customroleaction.length > 0) {
  771:         for (var i=0; i<document.docustom.customroleaction.length; i++) {
  772:             if (document.docustom.customroleaction[i].checked) {
  773:                 if (document.docustom.customroleaction[i].value == 'new') {
  774:                     document.docustom.rolename.selectedIndex = 0;
  775:                 } else {
  776:                     document.docustom.newrolename.value = '';
  777:                 }
  778:             }
  779:         }
  780:     }
  781:     return;
  782: }
  783: 
  784: function setCustomAction(caller) {
  785:     if (document.docustom.customroleaction.length > 0) {
  786:         for (var i=0; i<document.docustom.customroleaction.length; i++) {
  787:             if (document.docustom.customroleaction[i].value == caller) {
  788:                 document.docustom.customroleaction[i].checked = true;
  789:             }
  790:         }
  791:     }
  792:     setCustomFields();
  793:     return;
  794: }
  795: 
  796: // ]]>
  797: </script>
  798: END
  799:     return $js;
  800: }
  801: 
  802: sub entry_form {
  803:     my ($dom,$srch,$forcenewuser,$context,$responsemsg,$crstype) = @_;
  804:     my ($usertype,$inexact);
  805:     if (ref($srch) eq 'HASH') {
  806:         if (($srch->{'srchin'} eq 'dom') &&
  807:             ($srch->{'srchby'} eq 'uname') &&
  808:             ($srch->{'srchtype'} eq 'exact') &&
  809:             ($srch->{'srchdomain'} ne '') &&
  810:             ($srch->{'srchterm'} ne '')) {
  811:             my (%curr_rules,%got_rules);
  812:             my ($rules,$ruleorder) =
  813:                 &Apache::lonnet::inst_userrules($srch->{'srchdomain'},'username');
  814:             $usertype = &Apache::lonuserutils::check_usertype($srch->{'srchdomain'},$srch->{'srchterm'},$rules,\%curr_rules,\%got_rules);
  815:         } else {
  816:             $inexact = 1;
  817:         }
  818:     }
  819:     my $cancreate =
  820:         &Apache::lonuserutils::can_create_user($dom,$context,$usertype);
  821:     my $userpicker = 
  822:        &Apache::loncommon::user_picker($dom,$srch,$forcenewuser,
  823:                                        'document.crtuser',$cancreate,$usertype);
  824:     my $srchbutton = &mt('Search');
  825:     if ($env{'form.action'} eq 'singlestudent') {
  826:         $srchbutton = &mt('Search and Enroll');
  827:     } elsif ($cancreate && $responsemsg ne '' && $inexact) {
  828:         $srchbutton = &mt('Search or Add New User');
  829:     }
  830:     my $output = <<"ENDBLOCK";
  831: <form action="/adm/createuser" method="post" name="crtuser">
  832: <input type="hidden" name="action" value="$env{'form.action'}" />
  833: <input type="hidden" name="phase" value="get_user_info" />
  834: $userpicker
  835: <input name="userrole" type="button" value="$srchbutton" onclick="javascript:validateEntry(document.crtuser)" />
  836: </form>
  837: ENDBLOCK
  838:     if ($env{'form.phase'} eq '') {
  839:         my $defdom=$env{'request.role.domain'};
  840:         my $domform = &Apache::loncommon::select_dom_form($defdom,'srchdomain');
  841:         my %lt=&Apache::lonlocal::texthash(
  842:                   'enro' => 'Enroll one student',
  843:                   'enrm' => 'Enroll one member',
  844:                   'admo' => 'Add/modify a single user',
  845:                   'crea' => 'create new user if required',
  846:                   'uskn' => "username is known",
  847:                   'crnu' => 'Create a new user',
  848:                   'usr'  => 'Username',
  849:                   'dom'  => 'in domain',
  850:                   'enrl' => 'Enroll',
  851:                   'cram'  => 'Create/Modify user',
  852:         );
  853:         my $sellink=&Apache::loncommon::selectstudent_link('crtusername','srchterm','srchdomain');
  854:         my ($title,$buttontext,$showresponse);
  855:         if ($env{'form.action'} eq 'singlestudent') {
  856:             if ($crstype eq 'Community') {
  857:                 $title = $lt{'enrm'};
  858:             } else {
  859:                 $title = $lt{'enro'};
  860:             }
  861:             $buttontext = $lt{'enrl'};
  862:         } else {
  863:             $title = $lt{'admo'};
  864:             $buttontext = $lt{'cram'};
  865:         }
  866:         if ($cancreate) {
  867:             $title .= ' <span class="LC_cusr_subheading">('.$lt{'crea'}.')</span>';
  868:         } else {
  869:             $title .= ' <span class="LC_cusr_subheading">('.$lt{'uskn'}.')</span>';
  870:         }
  871:         if ($env{'form.origform'} eq 'crtusername') {
  872:             $showresponse = $responsemsg;
  873:         }
  874:         $output .= <<"ENDDOCUMENT";
  875: <br />
  876: <form action="/adm/createuser" method="post" name="crtusername">
  877: <input type="hidden" name="action" value="$env{'form.action'}" />
  878: <input type="hidden" name="phase" value="createnewuser" />
  879: <input type="hidden" name="srchtype" value="exact" />
  880: <input type="hidden" name="srchby" value="uname" />
  881: <input type="hidden" name="srchin" value="dom" />
  882: <input type="hidden" name="forcenewuser" value="1" />
  883: <input type="hidden" name="origform" value="crtusername" />
  884: <h3>$title</h3>
  885: $showresponse
  886: <table>
  887:  <tr>
  888:   <td>$lt{'usr'}:</td>
  889:   <td><input type="text" size="15" name="srchterm" /></td>
  890:   <td>&nbsp;$lt{'dom'}:</td><td>$domform</td>
  891:   <td>&nbsp;$sellink&nbsp;</td>
  892:   <td>&nbsp;<input name="userrole" type="submit" value="$buttontext" /></td>
  893:  </tr>
  894: </table>
  895: </form>
  896: ENDDOCUMENT
  897:     }
  898:     return $output;
  899: }
  900: 
  901: sub user_modification_js {
  902:     my ($pjump_def,$dc_setcourse_code,$nondc_setsection_code,$groupslist)=@_;
  903:     
  904:     return <<END;
  905: <script type="text/javascript" language="Javascript">
  906: // <![CDATA[
  907: 
  908:     $pjump_def
  909:     $dc_setcourse_code
  910: 
  911:     function dateset() {
  912:         eval("document.cu."+document.cu.pres_marker.value+
  913:             ".value=document.cu.pres_value.value");
  914:         modalWindow.close();
  915:     }
  916: 
  917:     $nondc_setsection_code
  918: // ]]>
  919: </script>
  920: END
  921: }
  922: 
  923: # =================================================================== Phase two
  924: sub print_user_selection_page {
  925:     my ($r,$response,$srch,$srch_results,$srcharray,$context,$opener_elements,$crstype,$brcrum) = @_;
  926:     my @fields = ('username','domain','lastname','firstname','permanentemail');
  927:     my $sortby = $env{'form.sortby'};
  928: 
  929:     if (!grep(/^\Q$sortby\E$/,@fields)) {
  930:         $sortby = 'lastname';
  931:     }
  932: 
  933:     my ($jsback,$elements) = &crumb_utilities();
  934: 
  935:     my $jscript = (<<ENDSCRIPT);
  936: <script type="text/javascript">
  937: // <![CDATA[
  938: function pickuser(uname,udom) {
  939:     document.usersrchform.seluname.value=uname;
  940:     document.usersrchform.seludom.value=udom;
  941:     document.usersrchform.phase.value="userpicked";
  942:     document.usersrchform.submit();
  943: }
  944: 
  945: $jsback
  946: // ]]>
  947: </script>
  948: ENDSCRIPT
  949: 
  950:     my %lt=&Apache::lonlocal::texthash(
  951:                                        'usrch'          => "User Search to add/modify roles",
  952:                                        'stusrch'        => "User Search to enroll student",
  953:                                        'memsrch'        => "User Search to enroll member",
  954:                                        'usel'           => "Select a user to add/modify roles",
  955:                                        'stusel'         => "Select a user to enroll as a student",
  956:                                        'memsel'         => "Select a user to enroll as a member",
  957:                                        'username'       => "username",
  958:                                        'domain'         => "domain",
  959:                                        'lastname'       => "last name",
  960:                                        'firstname'      => "first name",
  961:                                        'permanentemail' => "permanent e-mail",
  962:                                       );
  963:     if ($context eq 'requestcrs') {
  964:         $r->print('<div>');
  965:     } else {
  966:         my %breadcrumb_text = &singleuser_breadcrumb($crstype);
  967:         my $helpitem;
  968:         if ($env{'form.action'} eq 'singleuser') {
  969:             $helpitem = 'Course_Change_Privileges';
  970:         } elsif ($env{'form.action'} eq 'singlestudent') {
  971:             $helpitem = 'Course_Add_Student';
  972:         }
  973:         push (@{$brcrum},
  974:                   {href => "javascript:backPage(document.usersrchform,'','')",
  975:                    text => $breadcrumb_text{'search'},
  976:                    faq  => 282,
  977:                    bug  => 'Instructor Interface',},
  978:                   {href => "javascript:backPage(document.usersrchform,'get_user_info','select')",
  979:                    text => $breadcrumb_text{'userpicked'},
  980:                    faq  => 282,
  981:                    bug  => 'Instructor Interface',
  982:                    help => $helpitem}
  983:                   );
  984:         $r->print(&Apache::loncommon::start_page('User Management',$jscript,{bread_crumbs => $brcrum}));
  985:         if ($env{'form.action'} eq 'singleuser') {
  986:             $r->print("<b>$lt{'usrch'}</b><br />");
  987:             $r->print(&entry_form($srch->{'srchdomain'},$srch,undef,$context,undef,$crstype));
  988:             $r->print('<h3>'.$lt{'usel'}.'</h3>');
  989:         } elsif ($env{'form.action'} eq 'singlestudent') {
  990:             $r->print($jscript."<b>");
  991:             if ($crstype eq 'Community') {
  992:                 $r->print($lt{'memsrch'});
  993:             } else {
  994:                 $r->print($lt{'stusrch'});
  995:             }
  996:             $r->print("</b><br />");
  997:             $r->print(&entry_form($srch->{'srchdomain'},$srch,undef,$context,undef,$crstype));
  998:             $r->print('</form><h3>');
  999:             if ($crstype eq 'Community') {
 1000:                 $r->print($lt{'memsel'});
 1001:             } else {
 1002:                 $r->print($lt{'stusel'});
 1003:             }
 1004:             $r->print('</h3>');
 1005:         }
 1006:     }
 1007:     $r->print('<form name="usersrchform" method="post" action="">'.
 1008:               &Apache::loncommon::start_data_table()."\n".
 1009:               &Apache::loncommon::start_data_table_header_row()."\n".
 1010:               ' <th> </th>'."\n");
 1011:     foreach my $field (@fields) {
 1012:         $r->print(' <th><a href="javascript:document.usersrchform.sortby.value='.
 1013:                   "'".$field."'".';document.usersrchform.submit();">'.
 1014:                   $lt{$field}.'</a></th>'."\n");
 1015:     }
 1016:     $r->print(&Apache::loncommon::end_data_table_header_row());
 1017: 
 1018:     my @sorted_users = sort {
 1019:         lc($srch_results->{$a}->{$sortby})   cmp lc($srch_results->{$b}->{$sortby})
 1020:             ||
 1021:         lc($srch_results->{$a}->{lastname})  cmp lc($srch_results->{$b}->{lastname})
 1022:             ||
 1023:         lc($srch_results->{$a}->{firstname}) cmp lc($srch_results->{$b}->{firstname})
 1024: 	    ||
 1025: 	lc($a) cmp lc($b)
 1026:         } (keys(%$srch_results));
 1027: 
 1028:     foreach my $user (@sorted_users) {
 1029:         my ($uname,$udom) = split(/:/,$user);
 1030:         my $onclick;
 1031:         if ($context eq 'requestcrs') {
 1032:             $onclick =
 1033:                 'onclick="javascript:gochoose('."'$uname','$udom',".
 1034:                                                "'$srch_results->{$user}->{firstname}',".
 1035:                                                "'$srch_results->{$user}->{lastname}',".
 1036:                                                "'$srch_results->{$user}->{permanentemail}'".');"';
 1037:         } else {
 1038:             $onclick =
 1039:                 ' onclick="javascript:pickuser('."'".$uname."'".','."'".$udom."'".');"';
 1040:         }
 1041:         $r->print(&Apache::loncommon::start_data_table_row().
 1042:                   '<td><input type="button" name="seluser" value="'.&mt('Select').'" '.
 1043:                   $onclick.' /></td>'.
 1044:                   '<td><tt>'.$uname.'</tt></td>'.
 1045:                   '<td><tt>'.$udom.'</tt></td>');
 1046:         foreach my $field ('lastname','firstname','permanentemail') {
 1047:             $r->print('<td>'.$srch_results->{$user}->{$field}.'</td>');
 1048:         }
 1049:         $r->print(&Apache::loncommon::end_data_table_row());
 1050:     }
 1051:     $r->print(&Apache::loncommon::end_data_table().'<br /><br />');
 1052:     if (ref($srcharray) eq 'ARRAY') {
 1053:         foreach my $item (@{$srcharray}) {
 1054:             $r->print('<input type="hidden" name="'.$item.'" value="'.$env{'form.'.$item}.'" />'."\n");
 1055:         }
 1056:     }
 1057:     $r->print(' <input type="hidden" name="sortby" value="'.$sortby.'" />'."\n".
 1058:               ' <input type="hidden" name="seluname" value="" />'."\n".
 1059:               ' <input type="hidden" name="seludom" value="" />'."\n".
 1060:               ' <input type="hidden" name="currstate" value="select" />'."\n".
 1061:               ' <input type="hidden" name="phase" value="get_user_info" />'."\n".
 1062:               ' <input type="hidden" name="action" value="'.$env{'form.action'}.'" />'."\n");
 1063:     if ($context eq 'requestcrs') {
 1064:         $r->print($opener_elements.'</form></div>');
 1065:     } else {
 1066:         $r->print($response.'</form>');
 1067:     }
 1068: }
 1069: 
 1070: sub print_user_query_page {
 1071:     my ($r,$caller,$brcrum) = @_;
 1072: # FIXME - this is for a network-wide name search (similar to catalog search)
 1073: # To use frames with similar behavior to catalog/portfolio search.
 1074: # To be implemented. 
 1075:     return;
 1076: }
 1077: 
 1078: sub print_user_modification_page {
 1079:     my ($r,$ccuname,$ccdomain,$srch,$response,$context,$permission,$crstype,
 1080:         $brcrum,$showcredits) = @_;
 1081:     if (($ccuname eq '') || ($ccdomain eq '')) {
 1082:         my $usermsg = &mt('No username and/or domain provided.');
 1083:         $env{'form.phase'} = '';
 1084: 	&print_username_entry_form($r,$context,$usermsg,'','',$crstype,$brcrum);
 1085:         return;
 1086:     }
 1087:     my ($form,$formname);
 1088:     if ($env{'form.action'} eq 'singlestudent') {
 1089:         $form = 'document.enrollstudent';
 1090:         $formname = 'enrollstudent';
 1091:     } else {
 1092:         $form = 'document.cu';
 1093:         $formname = 'cu';
 1094:     }
 1095:     my %abv_auth = &auth_abbrev();
 1096:     my (%rulematch,%inst_results,$newuser,%alerts,%curr_rules,%got_rules);
 1097:     my $uhome=&Apache::lonnet::homeserver($ccuname,$ccdomain);
 1098:     if ($uhome eq 'no_host') {
 1099:         my $usertype;
 1100:         my ($rules,$ruleorder) =
 1101:             &Apache::lonnet::inst_userrules($ccdomain,'username');
 1102:             $usertype =
 1103:                 &Apache::lonuserutils::check_usertype($ccdomain,$ccuname,$rules,
 1104:                                                       \%curr_rules,\%got_rules);
 1105:         my $cancreate =
 1106:             &Apache::lonuserutils::can_create_user($ccdomain,$context,
 1107:                                                    $usertype);
 1108:         if (!$cancreate) {
 1109:             my $helplink = 'javascript:helpMenu('."'display'".')';
 1110:             my %usertypetext = (
 1111:                 official   => 'institutional',
 1112:                 unofficial => 'non-institutional',
 1113:             );
 1114:             my $response;
 1115:             if ($env{'form.origform'} eq 'crtusername') {
 1116:                 $response = '<span class="LC_warning">'.
 1117:                             &mt('No match found for the username [_1] in LON-CAPA domain: [_2]',
 1118:                                 '<b>'.$ccuname.'</b>',$ccdomain).
 1119:                             '</span><br />';
 1120:             }
 1121:             $response .= '<p class="LC_warning">'
 1122:                         .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
 1123:                         .' '
 1124:                         .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
 1125:                             ,'<a href="'.$helplink.'">','</a>')
 1126:                         .'</p><br />';
 1127:             $env{'form.phase'} = '';
 1128:             &print_username_entry_form($r,$context,$response,undef,undef,$crstype,$brcrum);
 1129:             return;
 1130:         }
 1131:         $newuser = 1;
 1132:         my $checkhash;
 1133:         my $checks = { 'username' => 1 };
 1134:         $checkhash->{$ccuname.':'.$ccdomain} = { 'newuser' => $newuser };
 1135:         &Apache::loncommon::user_rule_check($checkhash,$checks,
 1136:             \%alerts,\%rulematch,\%inst_results,\%curr_rules,\%got_rules);
 1137:         if (ref($alerts{'username'}) eq 'HASH') {
 1138:             if (ref($alerts{'username'}{$ccdomain}) eq 'HASH') {
 1139:                 my $domdesc =
 1140:                     &Apache::lonnet::domain($ccdomain,'description');
 1141:                 if ($alerts{'username'}{$ccdomain}{$ccuname}) {
 1142:                     my $userchkmsg;
 1143:                     if (ref($curr_rules{$ccdomain}) eq 'HASH') {  
 1144:                         $userchkmsg = 
 1145:                             &Apache::loncommon::instrule_disallow_msg('username',
 1146:                                                                  $domdesc,1).
 1147:                         &Apache::loncommon::user_rule_formats($ccdomain,
 1148:                             $domdesc,$curr_rules{$ccdomain}{'username'},
 1149:                             'username');
 1150:                     }
 1151:                     $env{'form.phase'} = '';
 1152:                     &print_username_entry_form($r,$context,$userchkmsg,undef,undef,$crstype,$brcrum);
 1153:                     return;
 1154:                 }
 1155:             }
 1156:         }
 1157:     } else {
 1158:         $newuser = 0;
 1159:     }
 1160:     if ($response) {
 1161:         $response = '<br />'.$response;
 1162:     }
 1163: 
 1164:     my $pjump_def = &Apache::lonhtmlcommon::pjump_javascript_definition();
 1165:     my $dc_setcourse_code = '';
 1166:     my $nondc_setsection_code = '';                                        
 1167:     my %loaditem;
 1168: 
 1169:     my $groupslist = &Apache::lonuserutils::get_groupslist();
 1170: 
 1171:     my $js = &validation_javascript($context,$ccdomain,$pjump_def,$crstype,
 1172:                                $groupslist,$newuser,$formname,\%loaditem);
 1173:     my %breadcrumb_text = &singleuser_breadcrumb($crstype);
 1174:     my $helpitem = 'Course_Change_Privileges';
 1175:     if ($env{'form.action'} eq 'singlestudent') {
 1176:         $helpitem = 'Course_Add_Student';
 1177:     }
 1178:     push (@{$brcrum},
 1179:         {href => "javascript:backPage($form)",
 1180:          text => $breadcrumb_text{'search'},
 1181:          faq  => 282,
 1182:          bug  => 'Instructor Interface',});
 1183:     if ($env{'form.phase'} eq 'userpicked') {
 1184:        push(@{$brcrum},
 1185:               {href => "javascript:backPage($form,'get_user_info','select')",
 1186:                text => $breadcrumb_text{'userpicked'},
 1187:                faq  => 282,
 1188:                bug  => 'Instructor Interface',});
 1189:     }
 1190:     push(@{$brcrum},
 1191:             {href => "javascript:backPage($form,'$env{'form.phase'}','modify')",
 1192:              text => $breadcrumb_text{'modify'},
 1193:              faq  => 282,
 1194:              bug  => 'Instructor Interface',
 1195:              help => $helpitem});
 1196:     my $args = {'add_entries'           => \%loaditem,
 1197:                 'bread_crumbs'          => $brcrum,
 1198:                 'bread_crumbs_component' => 'User Management'};
 1199:     if ($env{'form.popup'}) {
 1200:         $args->{'no_nav_bar'} = 1;
 1201:     }
 1202:     my $start_page =
 1203:         &Apache::loncommon::start_page('User Management',$js,$args);
 1204: 
 1205:     my $forminfo =<<"ENDFORMINFO";
 1206: <form action="/adm/createuser" method="post" name="$formname">
 1207: <input type="hidden" name="phase" value="update_user_data" />
 1208: <input type="hidden" name="ccuname" value="$ccuname" />
 1209: <input type="hidden" name="ccdomain" value="$ccdomain" />
 1210: <input type="hidden" name="pres_value"  value="" />
 1211: <input type="hidden" name="pres_type"   value="" />
 1212: <input type="hidden" name="pres_marker" value="" />
 1213: ENDFORMINFO
 1214:     my (%inccourses,$roledom,$defaultcredits);
 1215:     if ($context eq 'course') {
 1216:         $inccourses{$env{'request.course.id'}}=1;
 1217:         $roledom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 1218:         if ($showcredits) {
 1219:             $defaultcredits = &Apache::lonuserutils::get_defaultcredits();
 1220:         }
 1221:     } elsif ($context eq 'author') {
 1222:         $roledom = $env{'request.role.domain'};
 1223:     } elsif ($context eq 'domain') {
 1224:         foreach my $key (keys(%env)) {
 1225:             $roledom = $env{'request.role.domain'};
 1226:             if ($key=~/^user\.priv\.cm\.\/($roledom)\/($match_username)/) {
 1227:                 $inccourses{$1.'_'.$2}=1;
 1228:             }
 1229:         }
 1230:     } else {
 1231:         foreach my $key (keys(%env)) {
 1232: 	    if ($key=~/^user\.priv\.cm\.\/($match_domain)\/($match_username)/) {
 1233: 	        $inccourses{$1.'_'.$2}=1;
 1234:             }
 1235:         }
 1236:     }
 1237:     my $title = '';
 1238:     if ($newuser) {
 1239:         my ($portfolioform,$domroleform);
 1240:         if ((&Apache::lonnet::allowed('mpq',$env{'request.role.domain'})) ||
 1241:             (&Apache::lonnet::allowed('mut',$env{'request.role.domain'}))) {
 1242:             # Current user has quota or user tools modification privileges
 1243:             $portfolioform = '<br />'.&user_quotas($ccuname,$ccdomain);
 1244:         }
 1245:         if ((&Apache::lonnet::allowed('cau',$env{'request.role.domain'})) &&
 1246:             ($ccdomain eq $env{'request.role.domain'})) {
 1247:             $domroleform = '<br />'.&domainrole_req($ccuname,$ccdomain);
 1248:         }
 1249:         &initialize_authen_forms($ccdomain,$formname);
 1250:         my %lt=&Apache::lonlocal::texthash(
 1251:                 'lg'             => 'Login Data',
 1252:                 'hs'             => "Home Server",
 1253:         );
 1254: 	$r->print(<<ENDTITLE);
 1255: $start_page
 1256: $response
 1257: $forminfo
 1258: <script type="text/javascript" language="Javascript">
 1259: // <![CDATA[
 1260: $loginscript
 1261: // ]]>
 1262: </script>
 1263: <input type='hidden' name='makeuser' value='1' />
 1264: ENDTITLE
 1265:         if ($env{'form.action'} eq 'singlestudent') {
 1266:             if ($crstype eq 'Community') {
 1267:                 $title = &mt('Create New User [_1] in domain [_2] as a member',
 1268:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1269:             } else {
 1270:                 $title = &mt('Create New User [_1] in domain [_2] as a student',
 1271:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1272:             }
 1273:         } else {
 1274:                 $title = &mt('Create New User [_1] in domain [_2]',
 1275:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1276:         }
 1277:         $r->print('<h2>'.$title.'</h2>'."\n");
 1278:         $r->print('<div class="LC_left_float">');
 1279:         $r->print(&personal_data_display($ccuname,$ccdomain,$newuser,$context,
 1280:                                          $inst_results{$ccuname.':'.$ccdomain}));
 1281:         # Option to disable student/employee ID conflict checking not offerred for new users.
 1282:         my ($home_server_pick,$numlib) = 
 1283:             &Apache::loncommon::home_server_form_item($ccdomain,'hserver',
 1284:                                                       'default','hide');
 1285:         if ($numlib > 1) {
 1286:             $r->print("
 1287: <br />
 1288: $lt{'hs'}: $home_server_pick
 1289: <br />");
 1290:         } else {
 1291:             $r->print($home_server_pick);
 1292:         }
 1293:         if (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) {
 1294:             $r->print('<br /><h3>'.
 1295:                       &mt('User Can Request Creation of Courses/Communities in this Domain?').'</h3>'.
 1296:                       &Apache::loncommon::start_data_table().
 1297:                       &build_tools_display($ccuname,$ccdomain,
 1298:                                            'requestcourses').
 1299:                       &Apache::loncommon::end_data_table());
 1300:         }
 1301:         $r->print('</div>'."\n".'<div class="LC_left_float"><h3>'.
 1302:                   $lt{'lg'}.'</h3>');
 1303:         my ($fixedauth,$varauth,$authmsg); 
 1304:         if (ref($rulematch{$ccuname.':'.$ccdomain}) eq 'HASH') {
 1305:             my $matchedrule = $rulematch{$ccuname.':'.$ccdomain}{'username'};
 1306:             my ($rules,$ruleorder) = 
 1307:                 &Apache::lonnet::inst_userrules($ccdomain,'username');
 1308:             if (ref($rules) eq 'HASH') {
 1309:                 if (ref($rules->{$matchedrule}) eq 'HASH') {
 1310:                     my $authtype = $rules->{$matchedrule}{'authtype'};
 1311:                     if ($authtype !~ /^(krb4|krb5|int|fsys|loc)$/) {
 1312:                         $r->print(&Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc));
 1313:                     } else { 
 1314:                         my $authparm = $rules->{$matchedrule}{'authparm'};
 1315:                         $authmsg = $rules->{$matchedrule}{'authmsg'};
 1316:                         if ($authtype =~ /^krb(4|5)$/) {
 1317:                             my $ver = $1;
 1318:                             if ($authparm ne '') {
 1319:                                 $fixedauth = <<"KERB"; 
 1320: <input type="hidden" name="login" value="krb" />
 1321: <input type="hidden" name="krbver" value="$ver" />
 1322: <input type="hidden" name="krbarg" value="$authparm" />
 1323: KERB
 1324:                             }
 1325:                         } else {
 1326:                             $fixedauth = 
 1327: '<input type="hidden" name="login" value="'.$authtype.'" />'."\n";
 1328:                             if ($rules->{$matchedrule}{'authparmfixed'}) {
 1329:                                 $fixedauth .=    
 1330: '<input type="hidden" name="'.$authtype.'arg" value="'.$authparm.'" />'."\n";
 1331:                             } else {
 1332:                                 if ($authtype eq 'int') {
 1333:                                     $varauth = '<br />'.
 1334: &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>';
 1335:                                 } elsif ($authtype eq 'loc') {
 1336:                                     $varauth = '<br />'.
 1337: &mt('[_1] Local Authentication with argument [_2]','','<input type="text" name="'.$authtype.'arg" value="" />')."\n";
 1338:                                 } else {
 1339:                                     $varauth =
 1340: '<input type="text" name="'.$authtype.'arg" value="" />'."\n";
 1341:                                 }
 1342:                             }
 1343:                         }
 1344:                     }
 1345:                 } else {
 1346:                     $r->print(&Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc));
 1347:                 }
 1348:             }
 1349:             if ($authmsg) {
 1350:                 $r->print(<<ENDAUTH);
 1351: $fixedauth
 1352: $authmsg
 1353: $varauth
 1354: ENDAUTH
 1355:             }
 1356:         } else {
 1357:             $r->print(&Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc)); 
 1358:         }
 1359:         $r->print($portfolioform.$domroleform);
 1360:         if ($env{'form.action'} eq 'singlestudent') {
 1361:             $r->print(&date_sections_select($context,$newuser,$formname,
 1362:                                             $permission,$crstype,$ccuname,
 1363:                                             $ccdomain,$showcredits));
 1364:         }
 1365:         $r->print('</div><div class="LC_clear_float_footer"></div>');
 1366:     } else { # user already exists
 1367: 	$r->print($start_page.$forminfo);
 1368:         if ($env{'form.action'} eq 'singlestudent') {
 1369:             if ($crstype eq 'Community') {
 1370:                 $title = &mt('Enroll one member: [_1] in domain [_2]',
 1371:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1372:             } else {
 1373:                 $title = &mt('Enroll one student: [_1] in domain [_2]',
 1374:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1375:             }
 1376:         } else {
 1377:             $title = &mt('Modify existing user: [_1] in domain [_2]',
 1378:                              '"'.$ccuname.'"','"'.$ccdomain.'"');
 1379:         }
 1380:         $r->print('<h2>'.$title.'</h2>'."\n");
 1381:         $r->print('<div class="LC_left_float">');
 1382:         $r->print(&personal_data_display($ccuname,$ccdomain,$newuser,$context,
 1383:                                          $inst_results{$ccuname.':'.$ccdomain}));
 1384:         if (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) {
 1385:             $r->print('<br /><h3>'.&mt('User Can Request Creation of Courses/Communities in this Domain?').'</h3>'.
 1386:                       &Apache::loncommon::start_data_table());
 1387:             if ($env{'request.role.domain'} eq $ccdomain) {
 1388:                 $r->print(&build_tools_display($ccuname,$ccdomain,'requestcourses'));
 1389:             } else {
 1390:                 $r->print(&coursereq_externaluser($ccuname,$ccdomain,
 1391:                                                   $env{'request.role.domain'}));
 1392:             }
 1393:             $r->print(&Apache::loncommon::end_data_table());
 1394:         }
 1395:         $r->print('</div>');
 1396:         my @order = ('auth','quota','tools','requestauthor');
 1397:         my %user_text;
 1398:         my ($isadv,$isauthor) = 
 1399:             &Apache::lonnet::is_advanced_user($ccuname,$ccdomain);
 1400:         if ((!$isauthor) && 
 1401:             (&Apache::lonnet::allowed('cau',$env{'request.role.domain'}))
 1402:             && ($env{'request.role.domain'} eq $ccdomain)) {
 1403:             $user_text{'requestauthor'} = &domainrole_req($ccuname,$ccdomain);
 1404:         }
 1405:         $user_text{'auth'} =  &user_authentication($ccuname,$ccdomain,$formname);
 1406:         if ((&Apache::lonnet::allowed('mpq',$ccdomain)) ||
 1407:             (&Apache::lonnet::allowed('mut',$ccdomain))) {
 1408:             # Current user has quota modification privileges
 1409:             $user_text{'quota'} = &user_quotas($ccuname,$ccdomain);
 1410:         }
 1411:         if (!&Apache::lonnet::allowed('mpq',$ccdomain)) {
 1412:             if (&Apache::lonnet::allowed('mpq',$env{'request.role.domain'})) {
 1413:                 my %lt=&Apache::lonlocal::texthash(
 1414:                     'dska'  => "Disk quotas for user's portfolio and Authoring Space",
 1415:                     'youd'  => "You do not have privileges to modify the portfolio and/or Authoring Space quotas for this user.",
 1416:                     'ichr'  => "If a change is required, contact a domain coordinator for the domain",
 1417:                 );
 1418:                 $user_text{'quota'} = <<ENDNOPORTPRIV;
 1419: <h3>$lt{'dska'}</h3>
 1420: $lt{'youd'} $lt{'ichr'}: $ccdomain
 1421: ENDNOPORTPRIV
 1422:             }
 1423:         }
 1424:         if (!&Apache::lonnet::allowed('mut',$ccdomain)) {
 1425:             if (&Apache::lonnet::allowed('mut',$env{'request.role.domain'})) {
 1426:                 my %lt=&Apache::lonlocal::texthash(
 1427:                     'utav'  => "User Tools Availability",
 1428:                     'yodo'  => "You do not have privileges to modify Portfolio, Blog, WebDAV, or Personal Information Page settings for this user.",
 1429:                     'ifch'  => "If a change is required, contact a domain coordinator for the domain",
 1430:                 );
 1431:                 $user_text{'tools'} = <<ENDNOTOOLSPRIV;
 1432: <h3>$lt{'utav'}</h3>
 1433: $lt{'yodo'} $lt{'ifch'}: $ccdomain
 1434: ENDNOTOOLSPRIV
 1435:             }
 1436:         }
 1437:         my $gotdiv = 0; 
 1438:         foreach my $item (@order) {
 1439:             if ($user_text{$item} ne '') {
 1440:                 unless ($gotdiv) {
 1441:                     $r->print('<div class="LC_left_float">');
 1442:                     $gotdiv = 1;
 1443:                 }
 1444:                 $r->print('<br />'.$user_text{$item});
 1445:             }
 1446:         }
 1447:         if ($env{'form.action'} eq 'singlestudent') {
 1448:             unless ($gotdiv) {
 1449:                 $r->print('<div class="LC_left_float">');
 1450:             }
 1451:             my $credits;
 1452:             if ($showcredits) {
 1453:                 $credits = &get_user_credits($ccuname,$ccdomain,$defaultcredits);
 1454:                 if ($credits eq '') {
 1455:                     $credits = $defaultcredits;
 1456:                 }
 1457:             }
 1458:             $r->print(&date_sections_select($context,$newuser,$formname,
 1459:                                             $permission,$crstype,$ccuname,
 1460:                                             $ccdomain,$showcredits));
 1461:         }
 1462:         if ($gotdiv) {
 1463:             $r->print('</div><div class="LC_clear_float_footer"></div>');
 1464:         }
 1465:         if ($env{'form.action'} ne 'singlestudent') {
 1466:             &display_existing_roles($r,$ccuname,$ccdomain,\%inccourses,$context,
 1467:                                     $roledom,$crstype);
 1468:         }
 1469:     } ## End of new user/old user logic
 1470:     if ($env{'form.action'} eq 'singlestudent') {
 1471:         my $btntxt;
 1472:         if ($crstype eq 'Community') {
 1473:             $btntxt = &mt('Enroll Member');
 1474:         } else {
 1475:             $btntxt = &mt('Enroll Student');
 1476:         }
 1477:         $r->print('<br /><input type="button" value="'.$btntxt.'" onclick="setSections(this.form)" />'."\n");
 1478:     } else {
 1479:         $r->print('<div class="LC_left_float">'.
 1480:                   '<fieldset><legend>'.&mt('Add Roles').'</legend>');
 1481:         my $addrolesdisplay = 0;
 1482:         if ($context eq 'domain' || $context eq 'author') {
 1483:             $addrolesdisplay = &new_coauthor_roles($r,$ccuname,$ccdomain);
 1484:         }
 1485:         if ($context eq 'domain') {
 1486:             my $add_domainroles = &new_domain_roles($r,$ccdomain);
 1487:             if (!$addrolesdisplay) {
 1488:                 $addrolesdisplay = $add_domainroles;
 1489:             }
 1490:             $r->print(&course_level_dc($env{'request.role.domain'},$showcredits));
 1491:             $r->print('</fieldset></div><div class="LC_clear_float_footer"></div>'.
 1492:                       '<br /><input type="button" value="'.&mt('Save').'" onclick="setCourse()" />'."\n");
 1493:         } elsif ($context eq 'author') {
 1494:             if ($addrolesdisplay) {
 1495:                 $r->print('</fieldset></div><div class="LC_clear_float_footer"></div>'.
 1496:                           '<br /><input type="button" value="'.&mt('Save').'"');
 1497:                 if ($newuser) {
 1498:                     $r->print(' onclick="auth_check()" \>'."\n");
 1499:                 } else {
 1500:                     $r->print('onclick="this.form.submit()" \>'."\n");
 1501:                 }
 1502:             } else {
 1503:                 $r->print('</fieldset></div>'.
 1504:                           '<div class="LC_clear_float_footer"></div>'.
 1505:                           '<br /><a href="javascript:backPage(document.cu)">'.
 1506:                           &mt('Back to previous page').'</a>');
 1507:             }
 1508:         } else {
 1509:             $r->print(&course_level_table(\%inccourses,$showcredits,$defaultcredits));
 1510:             $r->print('</fieldset></div><div class="LC_clear_float_footer"></div>'.
 1511:                       '<br /><input type="button" value="'.&mt('Save').'" onclick="setSections(this.form)" />'."\n");
 1512:         }
 1513:     }
 1514:     $r->print(&Apache::lonhtmlcommon::echo_form_input(['phase','userrole','ccdomain','prevphase','currstate','ccuname','ccdomain']));
 1515:     $r->print('<input type="hidden" name="currstate" value="" />');
 1516:     $r->print('<input type="hidden" name="prevphase" value="'.$env{'form.phase'}.'" /></form><br /><br />');
 1517:     return;
 1518: }
 1519: 
 1520: sub singleuser_breadcrumb {
 1521:     my ($crstype) = @_;
 1522:     my %breadcrumb_text;
 1523:     if ($env{'form.action'} eq 'singlestudent') {
 1524:         if ($crstype eq 'Community') {
 1525:             $breadcrumb_text{'search'} = 'Enroll a member';
 1526:         } else {
 1527:             $breadcrumb_text{'search'} = 'Enroll a student';
 1528:         }
 1529:         $breadcrumb_text{'userpicked'} = 'Select a user',
 1530:         $breadcrumb_text{'modify'} = 'Set section/dates',
 1531:     } else {
 1532:         $breadcrumb_text{'search'} = 'Create/modify a user';
 1533:         $breadcrumb_text{'userpicked'} = 'Select a user',
 1534:         $breadcrumb_text{'modify'} = 'Set user role',
 1535:     }
 1536:     return %breadcrumb_text;
 1537: }
 1538: 
 1539: sub date_sections_select {
 1540:     my ($context,$newuser,$formname,$permission,$crstype,$ccuname,$ccdomain,
 1541:         $showcredits) = @_;
 1542:     my $credits;
 1543:     if ($showcredits) {
 1544:         my $defaultcredits = &Apache::lonuserutils::get_defaultcredits();
 1545:         $credits = &get_user_credits($ccuname,$ccdomain,$defaultcredits);
 1546:         if ($credits eq '') {
 1547:             $credits = $defaultcredits;
 1548:         }
 1549:     }
 1550:     my $cid = $env{'request.course.id'};
 1551:     my ($cnum,$cdom) = &Apache::lonuserutils::get_course_identity($cid);
 1552:     my $date_table = '<h3>'.&mt('Starting and Ending Dates').'</h3>'."\n".
 1553:         &Apache::lonuserutils::date_setting_table(undef,undef,$context,
 1554:                                                   undef,$formname,$permission);
 1555:     my $rowtitle = 'Section';
 1556:     my $secbox = '<h3>'.&mt('Section and Credits').'</h3>'."\n".
 1557:         &Apache::lonuserutils::section_picker($cdom,$cnum,'st',$rowtitle,
 1558:                                               $permission,$context,'',$crstype,
 1559:                                               $showcredits,$credits);
 1560:     my $output = $date_table.$secbox;
 1561:     return $output;
 1562: }
 1563: 
 1564: sub validation_javascript {
 1565:     my ($context,$ccdomain,$pjump_def,$crstype,$groupslist,$newuser,$formname,
 1566:         $loaditem) = @_;
 1567:     my $dc_setcourse_code = '';
 1568:     my $nondc_setsection_code = '';
 1569:     if ($context eq 'domain') {
 1570:         my $dcdom = $env{'request.role.domain'};
 1571:         $loaditem->{'onload'} = "document.cu.coursedesc.value='';";
 1572:         $dc_setcourse_code = 
 1573:             &Apache::lonuserutils::dc_setcourse_js('cu','singleuser',$context);
 1574:     } else {
 1575:         my $checkauth; 
 1576:         if (($newuser) || (&Apache::lonnet::allowed('mau',$ccdomain))) {
 1577:             $checkauth = 1;
 1578:         }
 1579:         if ($context eq 'course') {
 1580:             $nondc_setsection_code =
 1581:                 &Apache::lonuserutils::setsections_javascript($formname,$groupslist,
 1582:                                                               undef,$checkauth,
 1583:                                                               $crstype);
 1584:         }
 1585:         if ($checkauth) {
 1586:             $nondc_setsection_code .= 
 1587:                 &Apache::lonuserutils::verify_authen($formname,$context);
 1588:         }
 1589:     }
 1590:     my $js = &user_modification_js($pjump_def,$dc_setcourse_code,
 1591:                                    $nondc_setsection_code,$groupslist);
 1592:     my ($jsback,$elements) = &crumb_utilities();
 1593:     $js .= "\n".
 1594:            '<script type="text/javascript">'."\n".
 1595:            '// <![CDATA['."\n".
 1596:            $jsback."\n".
 1597:            '// ]]>'."\n".
 1598:            '</script>'."\n";
 1599:     return $js;
 1600: }
 1601: 
 1602: sub display_existing_roles {
 1603:     my ($r,$ccuname,$ccdomain,$inccourses,$context,$roledom,$crstype,
 1604:         $showcredits) = @_;
 1605:     my $now=time;
 1606:     my %lt=&Apache::lonlocal::texthash(
 1607:                     'rer'  => "Existing Roles",
 1608:                     'rev'  => "Revoke",
 1609:                     'del'  => "Delete",
 1610:                     'ren'  => "Re-Enable",
 1611:                     'rol'  => "Role",
 1612:                     'ext'  => "Extent",
 1613:                     'crd'  => "Credits",
 1614:                     'sta'  => "Start",
 1615:                     'end'  => "End",
 1616:                                        );
 1617:     my (%rolesdump,%roletext,%sortrole,%roleclass,%rolepriv);
 1618:     if ($context eq 'course' || $context eq 'author') {
 1619:         my @roles = &Apache::lonuserutils::roles_by_context($context,1,$crstype);
 1620:         my %roleshash = 
 1621:             &Apache::lonnet::get_my_roles($ccuname,$ccdomain,'userroles',
 1622:                               ['active','previous','future'],\@roles,$roledom,1);
 1623:         foreach my $key (keys(%roleshash)) {
 1624:             my ($start,$end) = split(':',$roleshash{$key});
 1625:             next if ($start eq '-1' || $end eq '-1');
 1626:             my ($rnum,$rdom,$role,$sec) = split(':',$key);
 1627:             if ($context eq 'course') {
 1628:                 next unless (($rnum eq $env{'course.'.$env{'request.course.id'}.'.num'})
 1629:                              && ($rdom eq $env{'course.'.$env{'request.course.id'}.'.domain'}));
 1630:             } elsif ($context eq 'author') {
 1631:                 next unless (($rnum eq $env{'user.name'}) && ($rdom eq $env{'request.role.domain'}));
 1632:             }
 1633:             my ($newkey,$newvalue,$newrole);
 1634:             $newkey = '/'.$rdom.'/'.$rnum;
 1635:             if ($sec ne '') {
 1636:                 $newkey .= '/'.$sec;
 1637:             }
 1638:             $newvalue = $role;
 1639:             if ($role =~ /^cr/) {
 1640:                 $newrole = 'cr';
 1641:             } else {
 1642:                 $newrole = $role;
 1643:             }
 1644:             $newkey .= '_'.$newrole;
 1645:             if ($start ne '' && $end ne '') {
 1646:                 $newvalue .= '_'.$end.'_'.$start;
 1647:             } elsif ($end ne '') {
 1648:                 $newvalue .= '_'.$end;
 1649:             }
 1650:             $rolesdump{$newkey} = $newvalue;
 1651:         }
 1652:     } else {
 1653:         %rolesdump=&Apache::lonnet::dump('roles',$ccdomain,$ccuname);
 1654:     }
 1655:     # Build up table of user roles to allow revocation and re-enabling of roles.
 1656:     my ($tmp) = keys(%rolesdump);
 1657:     return if ($tmp =~ /^(con_lost|error)/i);
 1658:     foreach my $area (sort { my $a1=join('_',(split('_',$a))[1,0]);
 1659:                                 my $b1=join('_',(split('_',$b))[1,0]);
 1660:                                 return $a1 cmp $b1;
 1661:                             } keys(%rolesdump)) {
 1662:         next if ($area =~ /^rolesdef/);
 1663:         my $envkey=$area;
 1664:         my $role = $rolesdump{$area};
 1665:         my $thisrole=$area;
 1666:         $area =~ s/\_\w\w$//;
 1667:         my ($role_code,$role_end_time,$role_start_time) =
 1668:             split(/_/,$role);
 1669: # Is this a custom role? Get role owner and title.
 1670:         my ($croleudom,$croleuname,$croletitle)=
 1671:             ($role_code=~m{^cr/($match_domain)/($match_username)/(\w+)$});
 1672:         my $allowed=0;
 1673:         my $delallowed=0;
 1674:         my $sortkey=$role_code;
 1675:         my $class='Unknown';
 1676:         my $credits='';
 1677:         if ($area =~ m{^/($match_domain)/($match_courseid)} ) {
 1678:             $class='Course';
 1679:             my ($coursedom,$coursedir) = ($1,$2);
 1680:             my $cid = $1.'_'.$2;
 1681:             # $1.'_'.$2 is the course id (eg. 103_12345abcef103l3).
 1682:             my %coursedata=
 1683:                 &Apache::lonnet::coursedescription($cid);
 1684:             if ($coursedir =~ /^$match_community$/) {
 1685:                 $class='Community';
 1686:             }
 1687:             $sortkey.="\0$coursedom";
 1688:             my $carea;
 1689:             if (defined($coursedata{'description'})) {
 1690:                 $carea=$coursedata{'description'}.
 1691:                     '<br />'.&mt('Domain').': '.$coursedom.('&nbsp;'x8).
 1692:     &Apache::loncommon::syllabuswrapper(&mt('Syllabus'),$coursedir,$coursedom);
 1693:                 $sortkey.="\0".$coursedata{'description'};
 1694:             } else {
 1695:                 if ($class eq 'Community') {
 1696:                     $carea=&mt('Unavailable community').': '.$area;
 1697:                     $sortkey.="\0".&mt('Unavailable community').': '.$area;
 1698:                 } else {
 1699:                     $carea=&mt('Unavailable course').': '.$area;
 1700:                     $sortkey.="\0".&mt('Unavailable course').': '.$area;
 1701:                 }
 1702:             }
 1703:             $sortkey.="\0$coursedir";
 1704:             $inccourses->{$cid}=1;
 1705:             if (($showcredits) && ($class eq 'Course') && ($role_code eq 'st')) {
 1706:                 my $defaultcredits = $coursedata{'internal.defaultcredits'};
 1707:                 $credits =
 1708:                     &get_user_credits($ccuname,$ccdomain,$defaultcredits,
 1709:                                       $coursedom,$coursedir);
 1710:                 if ($credits eq '') {
 1711:                     $credits = $defaultcredits;
 1712:                 }
 1713:             }
 1714:             if ((&Apache::lonnet::allowed('c'.$role_code,$coursedom.'/'.$coursedir)) ||
 1715:                 (&Apache::lonnet::allowed('c'.$role_code,$ccdomain))) {
 1716:                 $allowed=1;
 1717:             }
 1718:             unless ($allowed) {
 1719:                 my $isowner = &Apache::lonuserutils::is_courseowner($cid,$coursedata{'internal.courseowner'});
 1720:                 if ($isowner) {
 1721:                     if (($role_code eq 'co') && ($class eq 'Community')) {
 1722:                         $allowed = 1;
 1723:                     } elsif (($role_code eq 'cc') && ($class eq 'Course')) {
 1724:                         $allowed = 1;
 1725:                     }
 1726:                 }
 1727:             } 
 1728:             if ((&Apache::lonnet::allowed('dro',$coursedom)) ||
 1729:                 (&Apache::lonnet::allowed('dro',$ccdomain))) {
 1730:                 $delallowed=1;
 1731:             }
 1732: # - custom role. Needs more info, too
 1733:             if ($croletitle) {
 1734:                 if (&Apache::lonnet::allowed('ccr',$coursedom.'/'.$coursedir)) {
 1735:                     $allowed=1;
 1736:                     $thisrole.='.'.$role_code;
 1737:                 }
 1738:             }
 1739:             if ($area=~m{^/($match_domain)/($match_courseid)/(\w+)}) {
 1740:                 $carea.='<br />'.&mt('Section: [_1]',$3);
 1741:                 $sortkey.="\0$3";
 1742:                 if (!$allowed) {
 1743:                     if ($env{'request.course.sec'} eq $3) {
 1744:                         if (&Apache::lonnet::allowed('c'.$role_code,$1.'/'.$2.'/'.$3)) {
 1745:                             $allowed = 1;
 1746:                         }
 1747:                     }
 1748:                 }
 1749:             }
 1750:             $area=$carea;
 1751:         } else {
 1752:             $sortkey.="\0".$area;
 1753:             # Determine if current user is able to revoke privileges
 1754:             if ($area=~m{^/($match_domain)/}) {
 1755:                 if ((&Apache::lonnet::allowed('c'.$role_code,$1)) ||
 1756:                    (&Apache::lonnet::allowed('c'.$role_code,$ccdomain))) {
 1757:                    $allowed=1;
 1758:                 }
 1759:                 if (((&Apache::lonnet::allowed('dro',$1))  ||
 1760:                     (&Apache::lonnet::allowed('dro',$ccdomain))) &&
 1761:                     ($role_code ne 'dc')) {
 1762:                     $delallowed=1;
 1763:                 }
 1764:             } else {
 1765:                 if (&Apache::lonnet::allowed('c'.$role_code,'/')) {
 1766:                     $allowed=1;
 1767:                 }
 1768:             }
 1769:             if ($role_code eq 'ca' || $role_code eq 'au' || $role_code eq 'aa') {
 1770:                 $class='Authoring Space';
 1771:             } elsif ($role_code eq 'su') {
 1772:                 $class='System';
 1773:             } else {
 1774:                 $class='Domain';
 1775:             }
 1776:         }
 1777:         if (($role_code eq 'ca') || ($role_code eq 'aa')) {
 1778:             $area=~m{/($match_domain)/($match_username)};
 1779:             if (&Apache::lonuserutils::authorpriv($2,$1)) {
 1780:                 $allowed=1;
 1781:             } else {
 1782:                 $allowed=0;
 1783:             }
 1784:         }
 1785:         my $row = '';
 1786:         $row.= '<td>';
 1787:         my $active=1;
 1788:         $active=0 if (($role_end_time) && ($now>$role_end_time));
 1789:         if (($active) && ($allowed)) {
 1790:             $row.= '<input type="checkbox" name="rev:'.$thisrole.'" />';
 1791:         } else {
 1792:             if ($active) {
 1793:                $row.='&nbsp;';
 1794:             } else {
 1795:                $row.=&mt('expired or revoked');
 1796:             }
 1797:         }
 1798:         $row.='</td><td>';
 1799:         if ($allowed && !$active) {
 1800:             $row.= '<input type="checkbox" name="ren:'.$thisrole.'" />';
 1801:         } else {
 1802:             $row.='&nbsp;';
 1803:         }
 1804:         $row.='</td><td>';
 1805:         if ($delallowed) {
 1806:             $row.= '<input type="checkbox" name="del:'.$thisrole.'" />';
 1807:         } else {
 1808:             $row.='&nbsp;';
 1809:         }
 1810:         my $plaintext='';
 1811:         if (!$croletitle) {
 1812:             $plaintext=&Apache::lonnet::plaintext($role_code,$class);
 1813:             if (($showcredits) && ($credits ne '')) {
 1814:                 $plaintext .= '<br/ ><span class="LC_nobreak">'.
 1815:                               '<span class="LC_fontsize_small">'.
 1816:                               &mt('Credits: [_1]',$credits).
 1817:                               '</span></span>';
 1818:             }
 1819:         } else {
 1820:             $plaintext=
 1821:                 &mt('Custom role [_1][_2]defined by [_3]',
 1822:                         '"'.$croletitle.'"',
 1823:                         '<br />',
 1824:                         $croleuname.':'.$croleudom);
 1825:         }
 1826:         $row.= '</td><td>'.$plaintext.
 1827:                '</td><td>'.$area.
 1828:                '</td><td>'.($role_start_time?&Apache::lonlocal::locallocaltime($role_start_time)
 1829:                                             : '&nbsp;' ).
 1830:                '</td><td>'.($role_end_time  ?&Apache::lonlocal::locallocaltime($role_end_time)
 1831:                                             : '&nbsp;' )
 1832:                ."</td>";
 1833:         $sortrole{$sortkey}=$envkey;
 1834:         $roletext{$envkey}=$row;
 1835:         $roleclass{$envkey}=$class;
 1836:         $rolepriv{$envkey}=$allowed;
 1837:     } # end of foreach        (table building loop)
 1838: 
 1839:     my $rolesdisplay = 0;
 1840:     my %output = ();
 1841:     foreach my $type ('Authoring Space','Course','Community','Domain','System','Unknown') {
 1842:         $output{$type} = '';
 1843:         foreach my $which (sort {uc($a) cmp uc($b)} (keys(%sortrole))) {
 1844:             if ( ($roleclass{$sortrole{$which}} =~ /^\Q$type\E/ ) && ($rolepriv{$sortrole{$which}}) ) {
 1845:                  $output{$type}.=
 1846:                       &Apache::loncommon::start_data_table_row().
 1847:                       $roletext{$sortrole{$which}}.
 1848:                       &Apache::loncommon::end_data_table_row();
 1849:             }
 1850:         }
 1851:         unless($output{$type} eq '') {
 1852:             $output{$type} = '<tr class="LC_info_row">'.
 1853:                       "<td align='center' colspan='7'>".&mt($type)."</td></tr>".
 1854:                       $output{$type};
 1855:             $rolesdisplay = 1;
 1856:         }
 1857:     }
 1858:     if ($rolesdisplay == 1) {
 1859:         my $contextrole='';
 1860:         if ($env{'request.course.id'}) {
 1861:             if (&Apache::loncommon::course_type() eq 'Community') {
 1862:                 $contextrole = &mt('Existing Roles in this Community');
 1863:             } else {
 1864:                 $contextrole = &mt('Existing Roles in this Course');
 1865:             }
 1866:         } elsif ($env{'request.role'} =~ /^au\./) {
 1867:             $contextrole = &mt('Existing Co-Author Roles in your Authoring Space');
 1868:         } else {
 1869:             $contextrole = &mt('Existing Roles in this Domain');
 1870:         }
 1871:         $r->print('<div class="LC_left_float">'.
 1872: '<fieldset><legend>'.$contextrole.'</legend>'.
 1873: &Apache::loncommon::start_data_table("LC_createuser").
 1874: &Apache::loncommon::start_data_table_header_row().
 1875: '<th>'.$lt{'rev'}.'</th><th>'.$lt{'ren'}.'</th><th>'.$lt{'del'}.
 1876: '</th><th>'.$lt{'rol'}.'</th><th>'.$lt{'ext'}.
 1877: '</th><th>'.$lt{'sta'}.'</th><th>'.$lt{'end'}.'</th>'.
 1878: &Apache::loncommon::end_data_table_header_row());
 1879:         foreach my $type ('Authoring Space','Course','Community','Domain','System','Unknown') {
 1880:             if ($output{$type}) {
 1881:                 $r->print($output{$type}."\n");
 1882:             }
 1883:         }
 1884:         $r->print(&Apache::loncommon::end_data_table().
 1885:                   '</fieldset></div>');
 1886:     }
 1887:     return;
 1888: }
 1889: 
 1890: sub new_coauthor_roles {
 1891:     my ($r,$ccuname,$ccdomain) = @_;
 1892:     my $addrolesdisplay = 0;
 1893:     #
 1894:     # Co-Author
 1895:     #
 1896:     if (&Apache::lonuserutils::authorpriv($env{'user.name'},
 1897:                                           $env{'request.role.domain'}) &&
 1898:         ($env{'user.name'} ne $ccuname || $env{'user.domain'} ne $ccdomain)) {
 1899:         # No sense in assigning co-author role to yourself
 1900:         $addrolesdisplay = 1;
 1901:         my $cuname=$env{'user.name'};
 1902:         my $cudom=$env{'request.role.domain'};
 1903:         my %lt=&Apache::lonlocal::texthash(
 1904:                     'cs'   => "Authoring Space",
 1905:                     'act'  => "Activate",
 1906:                     'rol'  => "Role",
 1907:                     'ext'  => "Extent",
 1908:                     'sta'  => "Start",
 1909:                     'end'  => "End",
 1910:                     'cau'  => "Co-Author",
 1911:                     'caa'  => "Assistant Co-Author",
 1912:                     'ssd'  => "Set Start Date",
 1913:                     'sed'  => "Set End Date"
 1914:                                        );
 1915:         $r->print('<h4>'.$lt{'cs'}.'</h4>'."\n".
 1916:                   &Apache::loncommon::start_data_table()."\n".
 1917:                   &Apache::loncommon::start_data_table_header_row()."\n".
 1918:                   '<th>'.$lt{'act'}.'</th><th>'.$lt{'rol'}.'</th>'.
 1919:                   '<th>'.$lt{'ext'}.'</th><th>'.$lt{'sta'}.'</th>'.
 1920:                   '<th>'.$lt{'end'}.'</th>'."\n".
 1921:                   &Apache::loncommon::end_data_table_header_row()."\n".
 1922:                   &Apache::loncommon::start_data_table_row().'
 1923:            <td>
 1924:             <input type="checkbox" name="act_'.$cudom.'_'.$cuname.'_ca" />
 1925:            </td>
 1926:            <td>'.$lt{'cau'}.'</td>
 1927:            <td>'.$cudom.'_'.$cuname.'</td>
 1928:            <td><input type="hidden" name="start_'.$cudom.'_'.$cuname.'_ca" value="" />
 1929:              <a href=
 1930: "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>
 1931: <td><input type="hidden" name="end_'.$cudom.'_'.$cuname.'_ca" value="" />
 1932: <a href=
 1933: "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".
 1934:               &Apache::loncommon::end_data_table_row()."\n".
 1935:               &Apache::loncommon::start_data_table_row()."\n".
 1936: '<td><input type="checkbox" name="act_'.$cudom.'_'.$cuname.'_aa" /></td>
 1937: <td>'.$lt{'caa'}.'</td>
 1938: <td>'.$cudom.'_'.$cuname.'</td>
 1939: <td><input type="hidden" name="start_'.$cudom.'_'.$cuname.'_aa" value="" />
 1940: <a href=
 1941: "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>
 1942: <td><input type="hidden" name="end_'.$cudom.'_'.$cuname.'_aa" value="" />
 1943: <a href=
 1944: "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".
 1945:              &Apache::loncommon::end_data_table_row()."\n".
 1946:              &Apache::loncommon::end_data_table());
 1947:     } elsif ($env{'request.role'} =~ /^au\./) {
 1948:         if (!(&Apache::lonuserutils::authorpriv($env{'user.name'},
 1949:                                                 $env{'request.role.domain'}))) {
 1950:             $r->print('<span class="LC_error">'.
 1951:                       &mt('You do not have privileges to assign co-author roles.').
 1952:                       '</span>');
 1953:         } elsif (($env{'user.name'} eq $ccuname) &&
 1954:              ($env{'user.domain'} eq $ccdomain)) {
 1955:             $r->print(&mt('Assigning yourself a co-author or assistant co-author role in your own author area in Authoring Space is not permitted'));
 1956:         }
 1957:     }
 1958:     return $addrolesdisplay;;
 1959: }
 1960: 
 1961: sub new_domain_roles {
 1962:     my ($r,$ccdomain) = @_;
 1963:     my $addrolesdisplay = 0;
 1964:     #
 1965:     # Domain level
 1966:     #
 1967:     my $num_domain_level = 0;
 1968:     my $domaintext =
 1969:     '<h4>'.&mt('Domain Level').'</h4>'.
 1970:     &Apache::loncommon::start_data_table().
 1971:     &Apache::loncommon::start_data_table_header_row().
 1972:     '<th>'.&mt('Activate').'</th><th>'.&mt('Role').'</th><th>'.
 1973:     &mt('Extent').'</th>'.
 1974:     '<th>'.&mt('Start').'</th><th>'.&mt('End').'</th>'.
 1975:     &Apache::loncommon::end_data_table_header_row();
 1976:     my @allroles = &Apache::lonuserutils::roles_by_context('domain');
 1977:     foreach my $thisdomain (sort(&Apache::lonnet::all_domains())) {
 1978:         foreach my $role (@allroles) {
 1979:             next if ($role eq 'ad');
 1980:             next if (($role eq 'au') && ($ccdomain ne $thisdomain));
 1981:             if (&Apache::lonnet::allowed('c'.$role,$thisdomain)) {
 1982:                my $plrole=&Apache::lonnet::plaintext($role);
 1983:                my %lt=&Apache::lonlocal::texthash(
 1984:                     'ssd'  => "Set Start Date",
 1985:                     'sed'  => "Set End Date"
 1986:                                        );
 1987:                $num_domain_level ++;
 1988:                $domaintext .=
 1989: &Apache::loncommon::start_data_table_row().
 1990: '<td><input type="checkbox" name="act_'.$thisdomain.'_'.$role.'" /></td>
 1991: <td>'.$plrole.'</td>
 1992: <td>'.$thisdomain.'</td>
 1993: <td><input type="hidden" name="start_'.$thisdomain.'_'.$role.'" value="" />
 1994: <a href=
 1995: "javascript:pjump('."'date_start','Start Date $plrole',document.cu.start_$thisdomain\_$role.value,'start_$thisdomain\_$role','cu.pres','dateset'".')">'.$lt{'ssd'}.'</a></td>
 1996: <td><input type="hidden" name="end_'.$thisdomain.'_'.$role.'" value="" />
 1997: <a href=
 1998: "javascript:pjump('."'date_end','End Date $plrole',document.cu.end_$thisdomain\_$role.value,'end_$thisdomain\_$role','cu.pres','dateset'".')">'.$lt{'sed'}.'</a></td>'.
 1999: &Apache::loncommon::end_data_table_row();
 2000:             }
 2001:         }
 2002:     }
 2003:     $domaintext.= &Apache::loncommon::end_data_table();
 2004:     if ($num_domain_level > 0) {
 2005:         $r->print($domaintext);
 2006:         $addrolesdisplay = 1;
 2007:     }
 2008:     return $addrolesdisplay;
 2009: }
 2010: 
 2011: sub user_authentication {
 2012:     my ($ccuname,$ccdomain,$formname) = @_;
 2013:     my $currentauth=&Apache::lonnet::queryauthenticate($ccuname,$ccdomain);
 2014:     my $outcome;
 2015:     # Check for a bad authentication type
 2016:     if ($currentauth !~ /^(krb4|krb5|unix|internal|localauth):/) {
 2017:         # bad authentication scheme
 2018:         my %lt=&Apache::lonlocal::texthash(
 2019:                        'err'   => "ERROR",
 2020:                        'uuas'  => "This user has an unrecognized authentication scheme",
 2021:                        'adcs'  => "Please alert a domain coordinator of this situation",
 2022:                        'sldb'  => "Please specify login data below",
 2023:                        'ld'    => "Login Data"
 2024:         );
 2025:         if (&Apache::lonnet::allowed('mau',$ccdomain)) {
 2026:             &initialize_authen_forms($ccdomain,$formname);
 2027: 
 2028:             my $choices = &Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc);
 2029:             $outcome = <<ENDBADAUTH;
 2030: <script type="text/javascript" language="Javascript">
 2031: // <![CDATA[
 2032: $loginscript
 2033: // ]]>
 2034: </script>
 2035: <span class="LC_error">$lt{'err'}:
 2036: $lt{'uuas'} ($currentauth). $lt{'sldb'}.</span>
 2037: <h3>$lt{'ld'}</h3>
 2038: $choices
 2039: ENDBADAUTH
 2040:         } else {
 2041:             # This user is not allowed to modify the user's
 2042:             # authentication scheme, so just notify them of the problem
 2043:             $outcome = <<ENDBADAUTH;
 2044: <span class="LC_error"> $lt{'err'}: 
 2045: $lt{'uuas'} ($currentauth). $lt{'adcs'}.
 2046: </span>
 2047: ENDBADAUTH
 2048:         }
 2049:     } else { # Authentication type is valid
 2050:         &initialize_authen_forms($ccdomain,$formname,$currentauth,'modifyuser');
 2051:         my ($authformcurrent,$can_modify,@authform_others) =
 2052:             &modify_login_block($ccdomain,$currentauth);
 2053:         if (&Apache::lonnet::allowed('mau',$ccdomain)) {
 2054:             # Current user has login modification privileges
 2055:             my %lt=&Apache::lonlocal::texthash (
 2056:                            'ld'    => "Login Data",
 2057:                            'ccld'  => "Change Current Login Data",
 2058:                            'enld'  => "Enter New Login Data"
 2059:                                                );
 2060:             $outcome =
 2061:                        '<script type="text/javascript" language="Javascript">'."\n".
 2062:                        '// <![CDATA['."\n".
 2063:                        $loginscript."\n".
 2064:                        '// ]]>'."\n".
 2065:                        '</script>'."\n".
 2066:                        '<h3>'.$lt{'ld'}.'</h3>'.
 2067:                        &Apache::loncommon::start_data_table().
 2068:                        &Apache::loncommon::start_data_table_row().
 2069:                        '<td>'.$authformnop;
 2070:             if ($can_modify) {
 2071:                 $outcome .= '</td>'."\n".
 2072:                             &Apache::loncommon::end_data_table_row().
 2073:                             &Apache::loncommon::start_data_table_row().
 2074:                             '<td>'.$authformcurrent.'</td>'.
 2075:                             &Apache::loncommon::end_data_table_row()."\n";
 2076:             } else {
 2077:                 $outcome .= '&nbsp;('.$authformcurrent.')</td>'.
 2078:                             &Apache::loncommon::end_data_table_row()."\n";
 2079:             }
 2080:             foreach my $item (@authform_others) { 
 2081:                 $outcome .= &Apache::loncommon::start_data_table_row().
 2082:                             '<td>'.$item.'</td>'.
 2083:                             &Apache::loncommon::end_data_table_row()."\n";
 2084:             }
 2085:             $outcome .= &Apache::loncommon::end_data_table();
 2086:         } else {
 2087:             if (&Apache::lonnet::allowed('mau',$env{'request.role.domain'})) {
 2088:                 my %lt=&Apache::lonlocal::texthash(
 2089:                            'ccld'  => "Change Current Login Data",
 2090:                            'yodo'  => "You do not have privileges to modify the authentication configuration for this user.",
 2091:                            'ifch'  => "If a change is required, contact a domain coordinator for the domain",
 2092:                 );
 2093:                 $outcome .= <<ENDNOPRIV;
 2094: <h3>$lt{'ccld'}</h3>
 2095: $lt{'yodo'} $lt{'ifch'}: $ccdomain
 2096: <input type="hidden" name="login" value="nochange" />
 2097: ENDNOPRIV
 2098:             }
 2099:         }
 2100:     }  ## End of "check for bad authentication type" logic
 2101:     return $outcome;
 2102: }
 2103: 
 2104: sub modify_login_block {
 2105:     my ($dom,$currentauth) = @_;
 2106:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 2107:     my ($authnum,%can_assign) =
 2108:         &Apache::loncommon::get_assignable_auth($dom);
 2109:     my ($authformcurrent,@authform_others,$show_override_msg);
 2110:     if ($currentauth=~/^krb(4|5):/) {
 2111:         $authformcurrent=$authformkrb;
 2112:         if ($can_assign{'int'}) {
 2113:             push(@authform_others,$authformint);
 2114:         }
 2115:         if ($can_assign{'loc'}) {
 2116:             push(@authform_others,$authformloc);
 2117:         }
 2118:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2119:             $show_override_msg = 1;
 2120:         }
 2121:     } elsif ($currentauth=~/^internal:/) {
 2122:         $authformcurrent=$authformint;
 2123:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2124:             push(@authform_others,$authformkrb);
 2125:         }
 2126:         if ($can_assign{'loc'}) {
 2127:             push(@authform_others,$authformloc);
 2128:         }
 2129:         if ($can_assign{'int'}) {
 2130:             $show_override_msg = 1;
 2131:         }
 2132:     } elsif ($currentauth=~/^unix:/) {
 2133:         $authformcurrent=$authformfsys;
 2134:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2135:             push(@authform_others,$authformkrb);
 2136:         }
 2137:         if ($can_assign{'int'}) {
 2138:             push(@authform_others,$authformint);
 2139:         }
 2140:         if ($can_assign{'loc'}) {
 2141:             push(@authform_others,$authformloc);
 2142:         }
 2143:         if ($can_assign{'fsys'}) {
 2144:             $show_override_msg = 1;
 2145:         }
 2146:     } elsif ($currentauth=~/^localauth:/) {
 2147:         $authformcurrent=$authformloc;
 2148:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2149:             push(@authform_others,$authformkrb);
 2150:         }
 2151:         if ($can_assign{'int'}) {
 2152:             push(@authform_others,$authformint);
 2153:         }
 2154:         if ($can_assign{'loc'}) {
 2155:             $show_override_msg = 1;
 2156:         }
 2157:     }
 2158:     if ($show_override_msg) {
 2159:         $authformcurrent = '<table><tr><td colspan="3">'.$authformcurrent.
 2160:                            '</td></tr>'."\n".
 2161:                            '<tr><td>&nbsp;&nbsp;&nbsp;</td>'.
 2162:                            '<td><b>'.&mt('Currently in use').'</b></td>'.
 2163:                            '<td align="right"><span class="LC_cusr_emph">'.
 2164:                             &mt('will override current values').
 2165:                             '</span></td></tr></table>';
 2166:     }
 2167:     return ($authformcurrent,$show_override_msg,@authform_others); 
 2168: }
 2169: 
 2170: sub personal_data_display {
 2171:     my ($ccuname,$ccdomain,$newuser,$context,$inst_results,$rolesarray,
 2172:         $now,$captchaform,$emailusername,$usertype) = @_;
 2173:     my ($output,%userenv,%canmodify,%canmodify_status);
 2174:     my @userinfo = ('firstname','middlename','lastname','generation',
 2175:                     'permanentemail','id');
 2176:     my $rowcount = 0;
 2177:     my $editable = 0;
 2178:     my %textboxsize = (
 2179:                        firstname      => '15',
 2180:                        middlename     => '15',
 2181:                        lastname       => '15',
 2182:                        generation     => '5',
 2183:                        permanentemail => '25',
 2184:                        id             => '15',
 2185:                       );
 2186: 
 2187:     my %lt=&Apache::lonlocal::texthash(
 2188:                 'pd'             => "Personal Data",
 2189:                 'firstname'      => "First Name",
 2190:                 'middlename'     => "Middle Name",
 2191:                 'lastname'       => "Last Name",
 2192:                 'generation'     => "Generation",
 2193:                 'permanentemail' => "Permanent e-mail address",
 2194:                 'id'             => "Student/Employee ID",
 2195:                 'lg'             => "Login Data",
 2196:                 'inststatus'     => "Affiliation",
 2197:                 'email'          => 'E-mail address',
 2198:                 'valid'          => 'Validation',
 2199:     );
 2200: 
 2201:     %canmodify_status =
 2202:         &Apache::lonuserutils::can_modify_userinfo($context,$ccdomain,
 2203:                                                    ['inststatus'],$rolesarray);
 2204:     if (!$newuser) {
 2205:         # Get the users information
 2206:         %userenv = &Apache::lonnet::get('environment',
 2207:                    ['firstname','middlename','lastname','generation',
 2208:                     'permanentemail','id','inststatus'],$ccdomain,$ccuname);
 2209:         %canmodify =
 2210:             &Apache::lonuserutils::can_modify_userinfo($context,$ccdomain,
 2211:                                                        \@userinfo,$rolesarray);
 2212:     } elsif ($context eq 'selfcreate') {
 2213:         if ($newuser eq 'email') {
 2214:             if (ref($emailusername) eq 'HASH') {
 2215:                 if (ref($emailusername->{$usertype}) eq 'HASH') {
 2216:                     my ($infofields,$infotitles) = &Apache::loncommon::emailusername_info();
 2217:                     @userinfo = ();          
 2218:                     if ((ref($infofields) eq 'ARRAY') && (ref($infotitles) eq 'HASH')) {
 2219:                         foreach my $field (@{$infofields}) { 
 2220:                             if ($emailusername->{$usertype}->{$field}) {
 2221:                                 push(@userinfo,$field);
 2222:                                 $canmodify{$field} = 1;
 2223:                                 unless ($textboxsize{$field}) {
 2224:                                     $textboxsize{$field} = 25;
 2225:                                 }
 2226:                                 unless ($lt{$field}) {
 2227:                                     $lt{$field} = $infotitles->{$field};
 2228:                                 }
 2229:                                 if ($emailusername->{$usertype}->{$field} eq 'required') {
 2230:                                     $lt{$field} .= '<b>*</b>';
 2231:                                 }
 2232:                             }
 2233:                         }
 2234:                     }
 2235:                 }
 2236:             }
 2237:         } else {
 2238:             %canmodify = &selfcreate_canmodify($context,$ccdomain,\@userinfo,
 2239:                                                $inst_results,$rolesarray);
 2240:         }
 2241:     }
 2242: 
 2243:     my $genhelp=&Apache::loncommon::help_open_topic('Generation');
 2244:     $output = '<h3>'.$lt{'pd'}.'</h3>'.
 2245:               &Apache::lonhtmlcommon::start_pick_box();
 2246:     if (($context eq 'selfcreate') && ($newuser eq 'email')) {
 2247:         $output .= &Apache::lonhtmlcommon::row_title($lt{'email'}.'<b>*</b>',undef,
 2248:                                                      'LC_oddrow_value')."\n".
 2249:                    '<input type="text" name="uname" size="25" value="" autocomplete="off" />';
 2250:         $rowcount ++;
 2251:         $output .= &Apache::lonhtmlcommon::row_closure(1);
 2252:         my $upassone = '<input type="password" name="upass'.$now.'" size="20" autocomplete="off" />';
 2253:         my $upasstwo = '<input type="password" name="upasscheck'.$now.'" size="20" autocomplete="off" />';
 2254:         $output .= &Apache::lonhtmlcommon::row_title(&mt('Password').'<b>*</b>',
 2255:                                                     'LC_pick_box_title',
 2256:                                                     'LC_oddrow_value')."\n".
 2257:                    $upassone."\n".
 2258:                    &Apache::lonhtmlcommon::row_closure(1)."\n".
 2259:                    &Apache::lonhtmlcommon::row_title(&mt('Confirm password').'<b>*</b>',
 2260:                                                      'LC_pick_box_title',
 2261:                                                      'LC_oddrow_value')."\n".
 2262:                    $upasstwo.
 2263:                    &Apache::lonhtmlcommon::row_closure()."\n";
 2264:     }
 2265:     foreach my $item (@userinfo) {
 2266:         my $rowtitle = $lt{$item};
 2267:         my $hiderow = 0;
 2268:         if ($item eq 'generation') {
 2269:             $rowtitle = $genhelp.$rowtitle;
 2270:         }
 2271:         my $row = &Apache::lonhtmlcommon::row_title($rowtitle,undef,'LC_oddrow_value')."\n";
 2272:         if ($newuser) {
 2273:             if (ref($inst_results) eq 'HASH') {
 2274:                 if ($inst_results->{$item} ne '') {
 2275:                     $row .= '<input type="hidden" name="c'.$item.'" value="'.$inst_results->{$item}.'" />'.$inst_results->{$item};
 2276:                 } else {
 2277:                     if ($context eq 'selfcreate') {
 2278:                         if ($canmodify{$item}) {
 2279:                             $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="" autocomplete="off" />';
 2280:                             $editable ++;
 2281:                         } else {
 2282:                             $hiderow = 1;
 2283:                         }
 2284:                     } else {
 2285:                         $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="" />';
 2286:                     }
 2287:                 }
 2288:             } else {
 2289:                 if ($context eq 'selfcreate') {
 2290:                     if ($canmodify{$item}) {
 2291:                         if ($newuser eq 'email') {
 2292:                             $row .= '<input type="text" name="'.$item.'" size="'.$textboxsize{$item}.'" value="" autocomplete="off" />';
 2293:                         } else {
 2294:                             $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="" autocomplete="off" />';
 2295:                         }
 2296:                         $editable ++;
 2297:                     } else {
 2298:                         $hiderow = 1;
 2299:                     }
 2300:                 } else {
 2301:                     $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="" />';
 2302:                 }
 2303:             }
 2304:         } else {
 2305:             if ($canmodify{$item}) {
 2306:                 $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="'.$userenv{$item}.'" />';
 2307:                 if (($item eq 'id') && (!$newuser)) {
 2308:                     $row .= '<br />'.&Apache::lonuserutils::forceid_change($context);
 2309:                 }
 2310:             } else {
 2311:                 $row .= $userenv{$item};
 2312:             }
 2313:         }
 2314:         $row .= &Apache::lonhtmlcommon::row_closure(1);
 2315:         if (!$hiderow) {
 2316:             $output .= $row;
 2317:             $rowcount ++;
 2318:         }
 2319:     }
 2320:     if (($canmodify_status{'inststatus'}) || ($context ne 'selfcreate')) {
 2321:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($ccdomain);
 2322:         if (ref($types) eq 'ARRAY') {
 2323:             if (@{$types} > 0) {
 2324:                 my ($hiderow,$shown);
 2325:                 if ($canmodify_status{'inststatus'}) {
 2326:                     $shown = &pick_inst_statuses($userenv{'inststatus'},$usertypes,$types);
 2327:                 } else {
 2328:                     if ($userenv{'inststatus'} eq '') {
 2329:                         $hiderow = 1;
 2330:                     } else {
 2331:                         my @showitems;
 2332:                         foreach my $item ( map { &unescape($_); } split(':',$userenv{'inststatus'})) {
 2333:                             if (exists($usertypes->{$item})) {
 2334:                                 push(@showitems,$usertypes->{$item});
 2335:                             } else {
 2336:                                 push(@showitems,$item);
 2337:                             }
 2338:                         }
 2339:                         if (@showitems) {
 2340:                             $shown = join(', ',@showitems);
 2341:                         } else {
 2342:                             $hiderow = 1;
 2343:                         }
 2344:                     }
 2345:                 }
 2346:                 if (!$hiderow) {
 2347:                     my $row = &Apache::lonhtmlcommon::row_title(&mt('Affiliations'),undef,'LC_oddrow_value')."\n".
 2348:                               $shown.&Apache::lonhtmlcommon::row_closure(1); 
 2349:                     if ($context eq 'selfcreate') {
 2350:                         $rowcount ++;
 2351:                     }
 2352:                     $output .= $row;
 2353:                 }
 2354:             }
 2355:         }
 2356:     }
 2357:     if (($context eq 'selfcreate') && ($newuser eq 'email')) {
 2358:         if ($captchaform) {
 2359:             $output .= &Apache::lonhtmlcommon::row_title($lt{'valid'}.'*',
 2360:                                                          'LC_pick_box_title')."\n".
 2361:                        $captchaform."\n".'<br /><br />'.
 2362:                        &Apache::lonhtmlcommon::row_closure(1); 
 2363:             $rowcount ++;
 2364:         }
 2365:         my $submit_text = &mt('Create account');
 2366:         $output .= &Apache::lonhtmlcommon::row_title()."\n".
 2367:                    '<br /><input type="submit" name="createaccount" value="'.
 2368:                    $submit_text.'" />'.
 2369:                    '<input type="hidden" name="type" value="'.$usertype.'" />'.
 2370:                    &Apache::lonhtmlcommon::row_closure(1);
 2371:     }
 2372:     $output .= &Apache::lonhtmlcommon::end_pick_box();
 2373:     if (wantarray) {
 2374:         if ($context eq 'selfcreate') {
 2375:             return($output,$rowcount,$editable);
 2376:         } else {
 2377:             return $output;
 2378:         }
 2379:     } else {
 2380:         return $output;
 2381:     }
 2382: }
 2383: 
 2384: sub pick_inst_statuses {
 2385:     my ($curr,$usertypes,$types) = @_;
 2386:     my ($output,$rem,@currtypes);
 2387:     if ($curr ne '') {
 2388:         @currtypes = map { &unescape($_); } split(/:/,$curr);
 2389:     }
 2390:     my $numinrow = 2;
 2391:     if (ref($types) eq 'ARRAY') {
 2392:         $output = '<table>';
 2393:         my $lastcolspan; 
 2394:         for (my $i=0; $i<@{$types}; $i++) {
 2395:             if (defined($usertypes->{$types->[$i]})) {
 2396:                 my $rem = $i%($numinrow);
 2397:                 if ($rem == 0) {
 2398:                     if ($i<@{$types}-1) {
 2399:                         if ($i > 0) { 
 2400:                             $output .= '</tr>';
 2401:                         }
 2402:                         $output .= '<tr>';
 2403:                     }
 2404:                 } elsif ($i==@{$types}-1) {
 2405:                     my $colsleft = $numinrow - $rem;
 2406:                     if ($colsleft > 1) {
 2407:                         $lastcolspan = ' colspan="'.$colsleft.'"';
 2408:                     }
 2409:                 }
 2410:                 my $check = ' ';
 2411:                 if (grep(/^\Q$types->[$i]\E$/,@currtypes)) {
 2412:                     $check = ' checked="checked" ';
 2413:                 }
 2414:                 $output .= '<td class="LC_left_item"'.$lastcolspan.'>'.
 2415:                            '<span class="LC_nobreak"><label>'.
 2416:                            '<input type="checkbox" name="inststatus" '.
 2417:                            'value="'.$types->[$i].'"'.$check.'/>'.
 2418:                            $usertypes->{$types->[$i]}.'</label></span></td>';
 2419:             }
 2420:         }
 2421:         $output .= '</tr></table>';
 2422:     }
 2423:     return $output;
 2424: }
 2425: 
 2426: sub selfcreate_canmodify {
 2427:     my ($context,$dom,$userinfo,$inst_results,$rolesarray) = @_;
 2428:     if (ref($inst_results) eq 'HASH') {
 2429:         my @inststatuses = &get_inststatuses($inst_results);
 2430:         if (@inststatuses == 0) {
 2431:             @inststatuses = ('default');
 2432:         }
 2433:         $rolesarray = \@inststatuses;
 2434:     }
 2435:     my %canmodify =
 2436:         &Apache::lonuserutils::can_modify_userinfo($context,$dom,$userinfo,
 2437:                                                    $rolesarray);
 2438:     return %canmodify;
 2439: }
 2440: 
 2441: sub get_inststatuses {
 2442:     my ($insthashref) = @_;
 2443:     my @inststatuses = ();
 2444:     if (ref($insthashref) eq 'HASH') {
 2445:         if (ref($insthashref->{'inststatus'}) eq 'ARRAY') {
 2446:             @inststatuses = @{$insthashref->{'inststatus'}};
 2447:         }
 2448:     }
 2449:     return @inststatuses;
 2450: }
 2451: 
 2452: # ================================================================= Phase Three
 2453: sub update_user_data {
 2454:     my ($r,$context,$crstype,$brcrum,$showcredits) = @_; 
 2455:     my $uhome=&Apache::lonnet::homeserver($env{'form.ccuname'},
 2456:                                           $env{'form.ccdomain'});
 2457:     # Error messages
 2458:     my $error     = '<span class="LC_error">'.&mt('Error').': ';
 2459:     my $end       = '</span><br /><br />';
 2460:     my $rtnlink   = '<a href="javascript:backPage(document.userupdate,'.
 2461:                     "'$env{'form.prevphase'}','modify')".'" />'.
 2462:                     &mt('Return to previous page').'</a>'.
 2463:                     &Apache::loncommon::end_page();
 2464:     my $now = time;
 2465:     my $title;
 2466:     if (exists($env{'form.makeuser'})) {
 2467: 	$title='Set Privileges for New User';
 2468:     } else {
 2469:         $title='Modify User Privileges';
 2470:     }
 2471:     my $newuser = 0;
 2472:     my ($jsback,$elements) = &crumb_utilities();
 2473:     my $jscript = '<script type="text/javascript">'."\n".
 2474:                   '// <![CDATA['."\n".
 2475:                   $jsback."\n".
 2476:                   '// ]]>'."\n".
 2477:                   '</script>'."\n";
 2478:     my %breadcrumb_text = &singleuser_breadcrumb($crstype);
 2479:     push (@{$brcrum},
 2480:              {href => "javascript:backPage(document.userupdate)",
 2481:               text => $breadcrumb_text{'search'},
 2482:               faq  => 282,
 2483:               bug  => 'Instructor Interface',}
 2484:              );
 2485:     if ($env{'form.prevphase'} eq 'userpicked') {
 2486:         push(@{$brcrum},
 2487:                {href => "javascript:backPage(document.userupdate,'get_user_info','select')",
 2488:                 text => $breadcrumb_text{'userpicked'},
 2489:                 faq  => 282,
 2490:                 bug  => 'Instructor Interface',});
 2491:     }
 2492:     my $helpitem = 'Course_Change_Privileges';
 2493:     if ($env{'form.action'} eq 'singlestudent') {
 2494:         $helpitem = 'Course_Add_Student';
 2495:     }
 2496:     push(@{$brcrum}, 
 2497:             {href => "javascript:backPage(document.userupdate,'$env{'form.prevphase'}','modify')",
 2498:              text => $breadcrumb_text{'modify'},
 2499:              faq  => 282,
 2500:              bug  => 'Instructor Interface',},
 2501:             {href => "/adm/createuser",
 2502:              text => "Result",
 2503:              faq  => 282,
 2504:              bug  => 'Instructor Interface',
 2505:              help => $helpitem});
 2506:     my $args = {bread_crumbs          => $brcrum,
 2507:                 bread_crumbs_component => 'User Management'};
 2508:     if ($env{'form.popup'}) {
 2509:         $args->{'no_nav_bar'} = 1;
 2510:     }
 2511:     $r->print(&Apache::loncommon::start_page($title,$jscript,$args));
 2512:     $r->print(&update_result_form($uhome));
 2513:     # Check Inputs
 2514:     if (! $env{'form.ccuname'} ) {
 2515: 	$r->print($error.&mt('No login name specified').'.'.$end.$rtnlink);
 2516: 	return;
 2517:     }
 2518:     if (  $env{'form.ccuname'} ne 
 2519: 	  &LONCAPA::clean_username($env{'form.ccuname'}) ) {
 2520: 	$r->print($error.&mt('Invalid login name.').'  '.
 2521: 		  &mt('Only letters, numbers, periods, dashes, @, and underscores are valid.').
 2522: 		  $end.$rtnlink);
 2523: 	return;
 2524:     }
 2525:     if (! $env{'form.ccdomain'}       ) {
 2526: 	$r->print($error.&mt('No domain specified').'.'.$end.$rtnlink);
 2527: 	return;
 2528:     }
 2529:     if (  $env{'form.ccdomain'} ne
 2530: 	  &LONCAPA::clean_domain($env{'form.ccdomain'}) ) {
 2531: 	$r->print($error.&mt('Invalid domain name.').'  '.
 2532: 		  &mt('Only letters, numbers, periods, dashes, and underscores are valid.').
 2533: 		  $end.$rtnlink);
 2534: 	return;
 2535:     }
 2536:     if ($uhome eq 'no_host') {
 2537:         $newuser = 1;
 2538:     }
 2539:     if (! exists($env{'form.makeuser'})) {
 2540:         # Modifying an existing user, so check the validity of the name
 2541:         if ($uhome eq 'no_host') {
 2542:             $r->print(
 2543:                 $error
 2544:                .'<p class="LC_error">'
 2545:                .&mt('Unable to determine home server for [_1] in domain [_2].',
 2546:                         '"'.$env{'form.ccuname'}.'"','"'.$env{'form.ccdomain'}.'"')
 2547:                .'</p>');
 2548:             return;
 2549:         }
 2550:     }
 2551:     # Determine authentication method and password for the user being modified
 2552:     my $amode='';
 2553:     my $genpwd='';
 2554:     if ($env{'form.login'} eq 'krb') {
 2555: 	$amode='krb';
 2556: 	$amode.=$env{'form.krbver'};
 2557: 	$genpwd=$env{'form.krbarg'};
 2558:     } elsif ($env{'form.login'} eq 'int') {
 2559: 	$amode='internal';
 2560: 	$genpwd=$env{'form.intarg'};
 2561:     } elsif ($env{'form.login'} eq 'fsys') {
 2562: 	$amode='unix';
 2563: 	$genpwd=$env{'form.fsysarg'};
 2564:     } elsif ($env{'form.login'} eq 'loc') {
 2565: 	$amode='localauth';
 2566: 	$genpwd=$env{'form.locarg'};
 2567: 	$genpwd=" " if (!$genpwd);
 2568:     } elsif (($env{'form.login'} eq 'nochange') ||
 2569:              ($env{'form.login'} eq ''        )) { 
 2570:         # There is no need to tell the user we did not change what they
 2571:         # did not ask us to change.
 2572:         # If they are creating a new user but have not specified login
 2573:         # information this will be caught below.
 2574:     } else {
 2575:             $r->print($error.&mt('Invalid login mode or password').$end.$rtnlink);
 2576:             return;
 2577:     }
 2578: 
 2579:     $r->print('<h3>'.&mt('User [_1] in domain [_2]',
 2580:                         $env{'form.ccuname'}.' ('.&Apache::loncommon::plainname($env{'form.ccuname'},
 2581:                         $env{'form.ccdomain'}).')', $env{'form.ccdomain'}).'</h3>');
 2582:     my %prog_state = &Apache::lonhtmlcommon::Create_PrgWin($r,2);
 2583: 
 2584:     my (%alerts,%rulematch,%inst_results,%curr_rules);
 2585:     my @userinfo = ('firstname','middlename','lastname','generation','permanentemail','id');
 2586:     my @usertools = ('aboutme','blog','webdav','portfolio');
 2587:     my @requestcourses = ('official','unofficial','community','textbook','placement');
 2588:     my @requestauthor = ('requestauthor');
 2589:     my ($othertitle,$usertypes,$types) = 
 2590:         &Apache::loncommon::sorted_inst_types($env{'form.ccdomain'});
 2591:     my %canmodify_status =
 2592:         &Apache::lonuserutils::can_modify_userinfo($context,$env{'form.ccdomain'},
 2593:                                                    ['inststatus']);
 2594:     if ($env{'form.makeuser'}) {
 2595: 	$r->print('<h3>'.&mt('Creating new account.').'</h3>');
 2596:         # Check for the authentication mode and password
 2597:         if (! $amode || ! $genpwd) {
 2598: 	    $r->print($error.&mt('Invalid login mode or password').$end.$rtnlink);    
 2599: 	    return;
 2600: 	}
 2601:         # Determine desired host
 2602:         my $desiredhost = $env{'form.hserver'};
 2603:         if (lc($desiredhost) eq 'default') {
 2604:             $desiredhost = undef;
 2605:         } else {
 2606:             my %home_servers = 
 2607: 		&Apache::lonnet::get_servers($env{'form.ccdomain'},'library');
 2608:             if (! exists($home_servers{$desiredhost})) {
 2609:                 $r->print($error.&mt('Invalid home server specified').$end.$rtnlink);
 2610:                 return;
 2611:             }
 2612:         }
 2613:         # Check ID format
 2614:         my %checkhash;
 2615:         my %checks = ('id' => 1);
 2616:         %{$checkhash{$env{'form.ccuname'}.':'.$env{'form.ccdomain'}}} = (
 2617:             'newuser' => $newuser, 
 2618:             'id' => $env{'form.cid'},
 2619:         );
 2620:         if ($env{'form.cid'} ne '') {
 2621:             &Apache::loncommon::user_rule_check(\%checkhash,\%checks,\%alerts,
 2622:                                           \%rulematch,\%inst_results,\%curr_rules);
 2623:             if (ref($alerts{'id'}) eq 'HASH') {
 2624:                 if (ref($alerts{'id'}{$env{'form.ccdomain'}}) eq 'HASH') {
 2625:                     my $domdesc =
 2626:                         &Apache::lonnet::domain($env{'form.ccdomain'},'description');
 2627:                     if ($alerts{'id'}{$env{'form.ccdomain'}}{$env{'form.cid'}}) {
 2628:                         my $userchkmsg;
 2629:                         if (ref($curr_rules{$env{'form.ccdomain'}}) eq 'HASH') {
 2630:                             $userchkmsg  = 
 2631:                                 &Apache::loncommon::instrule_disallow_msg('id',
 2632:                                                                     $domdesc,1).
 2633:                                 &Apache::loncommon::user_rule_formats($env{'form.ccdomain'},
 2634:                                     $domdesc,$curr_rules{$env{'form.ccdomain'}}{'id'},'id');
 2635:                         }
 2636:                         $r->print($error.&mt('Invalid ID format').$end.
 2637:                                   $userchkmsg.$rtnlink);
 2638:                         return;
 2639:                     }
 2640:                 }
 2641:             }
 2642:         }
 2643:         &Apache::lonhtmlcommon::Increment_PrgWin($r, \%prog_state);
 2644: 	# Call modifyuser
 2645: 	my $result = &Apache::lonnet::modifyuser
 2646: 	    ($env{'form.ccdomain'},$env{'form.ccuname'},$env{'form.cid'},
 2647:              $amode,$genpwd,$env{'form.cfirstname'},
 2648:              $env{'form.cmiddlename'},$env{'form.clastname'},
 2649:              $env{'form.cgeneration'},undef,$desiredhost,
 2650:              $env{'form.cpermanentemail'});
 2651: 	$r->print(&mt('Generating user').': '.$result);
 2652:         $uhome = &Apache::lonnet::homeserver($env{'form.ccuname'},
 2653:                                                $env{'form.ccdomain'});
 2654:         my (%changeHash,%newcustom,%changed,%changedinfo);
 2655:         if ($uhome ne 'no_host') {
 2656:             if ($context eq 'domain') {
 2657:                 foreach my $name ('portfolio','author') {
 2658:                     if ($env{'form.custom_'.$name.'quota'} == 1) {
 2659:                         if ($env{'form.'.$name.'quota'} eq '') {
 2660:                             $newcustom{$name.'quota'} = 0;
 2661:                         } else {
 2662:                             $newcustom{$name.'quota'} = $env{'form.'.$name.'quota'};
 2663:                             $newcustom{$name.'quota'} =~ s/[^\d\.]//g;
 2664:                         }
 2665:                         if (&quota_admin($newcustom{$name.'quota'},\%changeHash,$name)) {
 2666:                             $changed{$name.'quota'} = 1;
 2667:                         }
 2668:                     }
 2669:                 }
 2670:                 foreach my $item (@usertools) {
 2671:                     if ($env{'form.custom'.$item} == 1) {
 2672:                         $newcustom{$item} = $env{'form.tools_'.$item};
 2673:                         $changed{$item} = &tool_admin($item,$newcustom{$item},
 2674:                                                      \%changeHash,'tools');
 2675:                     }
 2676:                 }
 2677:                 foreach my $item (@requestcourses) {
 2678:                     if ($env{'form.custom'.$item} == 1) {
 2679:                         $newcustom{$item} = $env{'form.crsreq_'.$item};
 2680:                         if ($env{'form.crsreq_'.$item} eq 'autolimit') {
 2681:                             $newcustom{$item} .= '=';
 2682:                             $env{'form.crsreq_'.$item.'_limit'} =~ s/\D+//g;
 2683:                             if ($env{'form.crsreq_'.$item.'_limit'}) {
 2684:                                 $newcustom{$item} .= $env{'form.crsreq_'.$item.'_limit'};
 2685:                             }
 2686:                         }
 2687:                         $changed{$item} = &tool_admin($item,$newcustom{$item},
 2688:                                                       \%changeHash,'requestcourses');
 2689:                     }
 2690:                 }
 2691:                 if ($env{'form.customrequestauthor'} == 1) {
 2692:                     $newcustom{'requestauthor'} = $env{'form.requestauthor'};
 2693:                     $changed{'requestauthor'} = &tool_admin('requestauthor',
 2694:                                                     $newcustom{'requestauthor'},
 2695:                                                     \%changeHash,'requestauthor');
 2696:                 }
 2697:             }
 2698:             if ($canmodify_status{'inststatus'}) {
 2699:                 if (exists($env{'form.inststatus'})) {
 2700:                     my @inststatuses = &Apache::loncommon::get_env_multiple('form.inststatus');
 2701:                     if (@inststatuses > 0) {
 2702:                         $changeHash{'inststatus'} = join(',',@inststatuses);
 2703:                         $changed{'inststatus'} = $changeHash{'inststatus'};
 2704:                     }
 2705:                 }
 2706:             }
 2707:             if (keys(%changed)) {
 2708:                 foreach my $item (@userinfo) {
 2709:                     $changeHash{$item}  = $env{'form.c'.$item};
 2710:                 }
 2711:                 my $chgresult =
 2712:                      &Apache::lonnet::put('environment',\%changeHash,
 2713:                                           $env{'form.ccdomain'},$env{'form.ccuname'});
 2714:             } 
 2715:         }
 2716:         $r->print('<br />'.&mt('Home server').': '.$uhome.' '.
 2717:                   &Apache::lonnet::hostname($uhome));
 2718:     } elsif (($env{'form.login'} ne 'nochange') &&
 2719:              ($env{'form.login'} ne ''        )) {
 2720: 	# Modify user privileges
 2721:         if (! $amode || ! $genpwd) {
 2722: 	    $r->print($error.'Invalid login mode or password'.$end.$rtnlink);    
 2723: 	    return;
 2724: 	}
 2725: 	# Only allow authentication modification if the person has authority
 2726: 	if (&Apache::lonnet::allowed('mau',$env{'form.ccdomain'})) {
 2727: 	    $r->print('Modifying authentication: '.
 2728:                       &Apache::lonnet::modifyuserauth(
 2729: 		       $env{'form.ccdomain'},$env{'form.ccuname'},
 2730:                        $amode,$genpwd));
 2731:             $r->print('<br />'.&mt('Home server').': '.&Apache::lonnet::homeserver
 2732: 		  ($env{'form.ccuname'},$env{'form.ccdomain'}));
 2733: 	} else {
 2734: 	    # Okay, this is a non-fatal error.
 2735: 	    $r->print($error.&mt('You do not have the authority to modify this users authentication information.').$end);    
 2736: 	}
 2737:     }
 2738:     $r->rflush(); # Finish display of header before time consuming actions start
 2739:     &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state);
 2740:     ##
 2741:     my (@userroles,%userupdate,$cnum,$cdom,$defaultcredits,%namechanged);
 2742:     if ($context eq 'course') {
 2743:         ($cnum,$cdom) =
 2744:             &Apache::lonuserutils::get_course_identity();
 2745:         $crstype = &Apache::loncommon::course_type($cdom.'_'.$cnum);
 2746:         if ($showcredits) {
 2747:            $defaultcredits = &Apache::lonuserutils::get_defaultcredits($cdom,$cnum);
 2748:         }
 2749:     }
 2750:     if (! $env{'form.makeuser'} ) {
 2751:         # Check for need to change
 2752:         my %userenv = &Apache::lonnet::get
 2753:             ('environment',['firstname','middlename','lastname','generation',
 2754:              'id','permanentemail','portfolioquota','authorquota','inststatus',
 2755:              'tools.aboutme','tools.blog','tools.webdav','tools.portfolio',
 2756:              'requestcourses.official','requestcourses.unofficial',
 2757:              'requestcourses.community','requestcourses.textbook',
 2758:              'reqcrsotherdom.official','reqcrsotherdom.unofficial',
 2759:              'reqcrsotherdom.community','reqcrsotherdom.textbook',
 2760:              'reqcrsotherdom.placement','requestauthor'],
 2761:               $env{'form.ccdomain'},$env{'form.ccuname'});
 2762:         my ($tmp) = keys(%userenv);
 2763:         if ($tmp =~ /^(con_lost|error)/i) { 
 2764:             %userenv = ();
 2765:         }
 2766:         my $no_forceid_alert;
 2767:         # Check to see if user information can be changed
 2768:         my %domconfig =
 2769:             &Apache::lonnet::get_dom('configuration',['usermodification'],
 2770:                                      $env{'form.ccdomain'});
 2771:         my @statuses = ('active','future');
 2772:         my %roles = &Apache::lonnet::get_my_roles($env{'form.ccuname'},$env{'form.ccdomain'},'userroles',\@statuses,undef,$env{'request.role.domain'});
 2773:         my ($auname,$audom);
 2774:         if ($context eq 'author') {
 2775:             $auname = $env{'user.name'};
 2776:             $audom = $env{'user.domain'};     
 2777:         }
 2778:         foreach my $item (keys(%roles)) {
 2779:             my ($rolenum,$roledom,$role) = split(/:/,$item,-1);
 2780:             if ($context eq 'course') {
 2781:                 if ($cnum ne '' && $cdom ne '') {
 2782:                     if ($rolenum eq $cnum && $roledom eq $cdom) {
 2783:                         if (!grep(/^\Q$role\E$/,@userroles)) {
 2784:                             push(@userroles,$role);
 2785:                         }
 2786:                     }
 2787:                 }
 2788:             } elsif ($context eq 'author') {
 2789:                 if ($rolenum eq $auname && $roledom eq $audom) {
 2790:                     if (!grep(/^\Q$role\E$/,@userroles)) { 
 2791:                         push(@userroles,$role);
 2792:                     }
 2793:                 }
 2794:             }
 2795:         }
 2796:         if ($env{'form.action'} eq 'singlestudent') {
 2797:             if (!grep(/^st$/,@userroles)) {
 2798:                 push(@userroles,'st');
 2799:             }
 2800:         } else {
 2801:             # Check for course or co-author roles being activated or re-enabled
 2802:             if ($context eq 'author' || $context eq 'course') {
 2803:                 foreach my $key (keys(%env)) {
 2804:                     if ($context eq 'author') {
 2805:                         if ($key=~/^form\.act_\Q$audom\E_\Q$auname\E_([^_]+)/) {
 2806:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 2807:                                 push(@userroles,$1);
 2808:                             }
 2809:                         } elsif ($key =~/^form\.ren\:\Q$audom\E\/\Q$auname\E_([^_]+)/) {
 2810:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 2811:                                 push(@userroles,$1);
 2812:                             }
 2813:                         }
 2814:                     } elsif ($context eq 'course') {
 2815:                         if ($key=~/^form\.act_\Q$cdom\E_\Q$cnum\E_([^_]+)/) {
 2816:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 2817:                                 push(@userroles,$1);
 2818:                             }
 2819:                         } elsif ($key =~/^form\.ren\:\Q$cdom\E\/\Q$cnum\E(\/?\w*)_([^_]+)/) {
 2820:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 2821:                                 push(@userroles,$1);
 2822:                             }
 2823:                         }
 2824:                     }
 2825:                 }
 2826:             }
 2827:         }
 2828:         #Check to see if we can change personal data for the user 
 2829:         my (@mod_disallowed,@longroles);
 2830:         foreach my $role (@userroles) {
 2831:             if ($role eq 'cr') {
 2832:                 push(@longroles,'Custom');
 2833:             } else {
 2834:                 push(@longroles,&Apache::lonnet::plaintext($role,$crstype)); 
 2835:             }
 2836:         }
 2837:         my %canmodify = &Apache::lonuserutils::can_modify_userinfo($context,$env{'form.ccdomain'},\@userinfo,\@userroles);
 2838:         foreach my $item (@userinfo) {
 2839:             # Strip leading and trailing whitespace
 2840:             $env{'form.c'.$item} =~ s/(\s+$|^\s+)//g;
 2841:             if (!$canmodify{$item}) {
 2842:                 if (defined($env{'form.c'.$item})) {
 2843:                     if ($env{'form.c'.$item} ne $userenv{$item}) {
 2844:                         push(@mod_disallowed,$item);
 2845:                     }
 2846:                 }
 2847:                 $env{'form.c'.$item} = $userenv{$item};
 2848:             }
 2849:         }
 2850:         # Check to see if we can change the Student/Employee ID
 2851:         my $forceid = $env{'form.forceid'};
 2852:         my $recurseid = $env{'form.recurseid'};
 2853:         my (%alerts,%rulematch,%idinst_results,%curr_rules,%got_rules);
 2854:         my %uidhash = &Apache::lonnet::idrget($env{'form.ccdomain'},
 2855:                                             $env{'form.ccuname'});
 2856:         if (($uidhash{$env{'form.ccuname'}}) && 
 2857:             ($uidhash{$env{'form.ccuname'}}!~/error\:/) && 
 2858:             (!$forceid)) {
 2859:             if ($env{'form.cid'} ne $uidhash{$env{'form.ccuname'}}) {
 2860:                 $env{'form.cid'} = $userenv{'id'};
 2861:                 $no_forceid_alert = &mt('New student/employee ID does not match existing ID for this user.')
 2862:                                    .'<br />'
 2863:                                    .&mt("Change is not permitted without checking the 'Force ID change' checkbox on the previous page.")
 2864:                                    .'<br />'."\n";
 2865:             }
 2866:         }
 2867:         if ($env{'form.cid'} ne $userenv{'id'}) {
 2868:             my $checkhash;
 2869:             my $checks = { 'id' => 1 };
 2870:             $checkhash->{$env{'form.ccuname'}.':'.$env{'form.ccdomain'}} = 
 2871:                    { 'newuser' => $newuser,
 2872:                      'id'  => $env{'form.cid'}, 
 2873:                    };
 2874:             &Apache::loncommon::user_rule_check($checkhash,$checks,
 2875:                 \%alerts,\%rulematch,\%idinst_results,\%curr_rules,\%got_rules);
 2876:             if (ref($alerts{'id'}) eq 'HASH') {
 2877:                 if (ref($alerts{'id'}{$env{'form.ccdomain'}}) eq 'HASH') {
 2878:                    $env{'form.cid'} = $userenv{'id'};
 2879:                 }
 2880:             }
 2881:         }
 2882:         my (%quotachanged,%oldquota,%newquota,%olddefquota,%newdefquota, 
 2883:             $oldinststatus,$newinststatus,%oldisdefault,%newisdefault,%oldsettings,
 2884:             %oldsettingstext,%newsettings,%newsettingstext,@disporder,
 2885:             %oldsettingstatus,%newsettingstatus);
 2886:         @disporder = ('inststatus');
 2887:         if ($env{'request.role.domain'} eq $env{'form.ccdomain'}) {
 2888:             push(@disporder,'requestcourses','requestauthor');
 2889:         } else {
 2890:             push(@disporder,'reqcrsotherdom');
 2891:         }
 2892:         push(@disporder,('quota','tools'));
 2893:         $oldinststatus = $userenv{'inststatus'};
 2894:         foreach my $name ('portfolio','author') {
 2895:             ($olddefquota{$name},$oldsettingstatus{$name}) = 
 2896:                 &Apache::loncommon::default_quota($env{'form.ccdomain'},$oldinststatus,$name);
 2897:             ($newdefquota{$name},$newsettingstatus{$name}) = ($olddefquota{$name},$oldsettingstatus{$name});
 2898:         }
 2899:         my %canshow;
 2900:         if (&Apache::lonnet::allowed('mpq',$env{'form.ccdomain'})) {
 2901:             $canshow{'quota'} = 1;
 2902:         }
 2903:         if (&Apache::lonnet::allowed('mut',$env{'form.ccdomain'})) {
 2904:             $canshow{'tools'} = 1;
 2905:         }
 2906:         if (&Apache::lonnet::allowed('ccc',$env{'form.ccdomain'})) {
 2907:             $canshow{'requestcourses'} = 1;
 2908:         } elsif (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) {
 2909:             $canshow{'reqcrsotherdom'} = 1;
 2910:         }
 2911:         if (&Apache::lonnet::allowed('mau',$env{'form.ccdomain'})) {
 2912:             $canshow{'inststatus'} = 1;
 2913:         }
 2914:         if (&Apache::lonnet::allowed('cau',$env{'form.ccdomain'})) {
 2915:             $canshow{'requestauthor'} = 1;
 2916:         }
 2917:         my (%changeHash,%changed);
 2918:         if ($oldinststatus eq '') {
 2919:             $oldsettings{'inststatus'} = $othertitle; 
 2920:         } else {
 2921:             if (ref($usertypes) eq 'HASH') {
 2922:                 $oldsettings{'inststatus'} = join(', ',map{ $usertypes->{ &unescape($_) }; } (split(/:/,$userenv{'inststatus'})));
 2923:             } else {
 2924:                 $oldsettings{'inststatus'} = join(', ',map{ &unescape($_); } (split(/:/,$userenv{'inststatus'})));
 2925:             }
 2926:         }
 2927:         $changeHash{'inststatus'} = $userenv{'inststatus'};
 2928:         if ($canmodify_status{'inststatus'}) {
 2929:             $canshow{'inststatus'} = 1;
 2930:             if (exists($env{'form.inststatus'})) {
 2931:                 my @inststatuses = &Apache::loncommon::get_env_multiple('form.inststatus');
 2932:                 if (@inststatuses > 0) {
 2933:                     $newinststatus = join(':',map { &escape($_); } @inststatuses);
 2934:                     $changeHash{'inststatus'} = $newinststatus;
 2935:                     if ($newinststatus ne $oldinststatus) {
 2936:                         $changed{'inststatus'} = $newinststatus;
 2937:                         foreach my $name ('portfolio','author') {
 2938:                             ($newdefquota{$name},$newsettingstatus{$name}) =
 2939:                                 &Apache::loncommon::default_quota($env{'form.ccdomain'},$newinststatus,$name);
 2940:                         }
 2941:                     }
 2942:                     if (ref($usertypes) eq 'HASH') {
 2943:                         $newsettings{'inststatus'} = join(', ',map{ $usertypes->{$_}; } (@inststatuses)); 
 2944:                     } else {
 2945:                         $newsettings{'inststatus'} = join(', ',@inststatuses);
 2946:                     }
 2947:                 }
 2948:             } else {
 2949:                 $newinststatus = '';
 2950:                 $changeHash{'inststatus'} = $newinststatus;
 2951:                 $newsettings{'inststatus'} = $othertitle;
 2952:                 if ($newinststatus ne $oldinststatus) {
 2953:                     $changed{'inststatus'} = $changeHash{'inststatus'};
 2954:                     foreach my $name ('portfolio','author') {
 2955:                         ($newdefquota{$name},$newsettingstatus{$name}) =
 2956:                             &Apache::loncommon::default_quota($env{'form.ccdomain'},$newinststatus,$name);
 2957:                     }
 2958:                 }
 2959:             }
 2960:         } elsif ($context ne 'selfcreate') {
 2961:             $canshow{'inststatus'} = 1;
 2962:             $newsettings{'inststatus'} = $oldsettings{'inststatus'};
 2963:         }
 2964:         foreach my $name ('portfolio','author') {
 2965:             $changeHash{$name.'quota'} = $userenv{$name.'quota'};
 2966:         }
 2967:         if ($context eq 'domain') {
 2968:             foreach my $name ('portfolio','author') {
 2969:                 if ($userenv{$name.'quota'} ne '') {
 2970:                     $oldquota{$name} = $userenv{$name.'quota'};
 2971:                     if ($env{'form.custom_'.$name.'quota'} == 1) {
 2972:                         if ($env{'form.'.$name.'quota'} eq '') {
 2973:                             $newquota{$name} = 0;
 2974:                         } else {
 2975:                             $newquota{$name} = $env{'form.'.$name.'quota'};
 2976:                             $newquota{$name} =~ s/[^\d\.]//g;
 2977:                         }
 2978:                         if ($newquota{$name} != $oldquota{$name}) {
 2979:                             if (&quota_admin($newquota{$name},\%changeHash,$name)) {
 2980:                                 $changed{$name.'quota'} = 1;
 2981:                             }
 2982:                         }
 2983:                     } else {
 2984:                         if (&quota_admin('',\%changeHash,$name)) {
 2985:                             $changed{$name.'quota'} = 1;
 2986:                             $newquota{$name} = $newdefquota{$name};
 2987:                             $newisdefault{$name} = 1;
 2988:                         }
 2989:                     }
 2990:                 } else {
 2991:                     $oldisdefault{$name} = 1;
 2992:                     $oldquota{$name} = $olddefquota{$name};
 2993:                     if ($env{'form.custom_'.$name.'quota'} == 1) {
 2994:                         if ($env{'form.'.$name.'quota'} eq '') {
 2995:                             $newquota{$name} = 0;
 2996:                         } else {
 2997:                             $newquota{$name} = $env{'form.'.$name.'quota'};
 2998:                             $newquota{$name} =~ s/[^\d\.]//g;
 2999:                         }
 3000:                         if (&quota_admin($newquota{$name},\%changeHash,$name)) {
 3001:                             $changed{$name.'quota'} = 1;
 3002:                         }
 3003:                     } else {
 3004:                         $newquota{$name} = $newdefquota{$name};
 3005:                         $newisdefault{$name} = 1;
 3006:                     }
 3007:                 }
 3008:                 if ($oldisdefault{$name}) {
 3009:                     $oldsettingstext{'quota'}{$name} = &get_defaultquota_text($oldsettingstatus{$name});
 3010:                 }  else {
 3011:                     $oldsettingstext{'quota'}{$name} = &mt('custom quota: [_1] MB',$oldquota{$name});
 3012:                 }
 3013:                 if ($newisdefault{$name}) {
 3014:                     $newsettingstext{'quota'}{$name} = &get_defaultquota_text($newsettingstatus{$name});
 3015:                 } else {
 3016:                     $newsettingstext{'quota'}{$name} = &mt('custom quota: [_1] MB',$newquota{$name});
 3017:                 }
 3018:             }
 3019:             &tool_changes('tools',\@usertools,\%oldsettings,\%oldsettingstext,\%userenv,
 3020:                           \%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3021:             if ($env{'form.ccdomain'} eq $env{'request.role.domain'}) {
 3022:                 &tool_changes('requestcourses',\@requestcourses,\%oldsettings,\%oldsettingstext,
 3023:                               \%userenv,\%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3024:                 &tool_changes('requestauthor',\@requestauthor,\%oldsettings,\%oldsettingstext,
 3025:                               \%userenv,\%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3026:             } else {
 3027:                 &tool_changes('reqcrsotherdom',\@requestcourses,\%oldsettings,\%oldsettingstext,
 3028:                               \%userenv,\%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3029:             }
 3030:         }
 3031:         foreach my $item (@userinfo) {
 3032:             if ($env{'form.c'.$item} ne $userenv{$item}) {
 3033:                 $namechanged{$item} = 1;
 3034:             }
 3035:         }
 3036:         foreach my $name ('portfolio','author') {
 3037:             $oldsettings{'quota'}{$name} = &mt('[_1] MB',$oldquota{$name});
 3038:             $newsettings{'quota'}{$name} = &mt('[_1] MB',$newquota{$name});
 3039:         }
 3040:         if ((keys(%namechanged) > 0) || (keys(%changed) > 0)) {
 3041:             my ($chgresult,$namechgresult);
 3042:             if (keys(%changed) > 0) {
 3043:                 $chgresult = 
 3044:                     &Apache::lonnet::put('environment',\%changeHash,
 3045:                                   $env{'form.ccdomain'},$env{'form.ccuname'});
 3046:                 if ($chgresult eq 'ok') {
 3047:                     if (($env{'user.name'} eq $env{'form.ccuname'}) &&
 3048:                         ($env{'user.domain'} eq $env{'form.ccdomain'})) {
 3049:                         my %newenvhash;
 3050:                         foreach my $key (keys(%changed)) {
 3051:                             if (($key eq 'official') || ($key eq 'unofficial') ||
 3052:                                 ($key eq 'community') || ($key eq 'textbook') ||
 3053:                                 ($key eq 'placement')) {
 3054:                                 $newenvhash{'environment.requestcourses.'.$key} =
 3055:                                     $changeHash{'requestcourses.'.$key};
 3056:                                 if ($changeHash{'requestcourses.'.$key}) {
 3057:                                     $newenvhash{'environment.canrequest.'.$key} = 1;
 3058:                                 } else {
 3059:                                     $newenvhash{'environment.canrequest.'.$key} =
 3060:           &Apache::lonnet::usertools_access($env{'user.name'},$env{'user.domain'},
 3061:                                             $key,'reload','requestcourses');
 3062:                                 }
 3063:                             } elsif ($key eq 'requestauthor') {
 3064:                                 $newenvhash{'environment.'.$key} = $changeHash{$key};
 3065:                                 if ($changeHash{$key}) {
 3066:                                     $newenvhash{'environment.canrequest.author'} = 1;
 3067:                                 } else {
 3068:                                     $newenvhash{'environment.canrequest.author'} =
 3069:           &Apache::lonnet::usertools_access($env{'user.name'},$env{'user.domain'},
 3070:                                             $key,'reload','requestauthor');
 3071:                                 }
 3072:                             } elsif ($key ne 'quota') {
 3073:                                 $newenvhash{'environment.tools.'.$key} = 
 3074:                                     $changeHash{'tools.'.$key};
 3075:                                 if ($changeHash{'tools.'.$key} ne '') {
 3076:                                     $newenvhash{'environment.availabletools.'.$key} =
 3077:                                         $changeHash{'tools.'.$key};
 3078:                                 } else {
 3079:                                     $newenvhash{'environment.availabletools.'.$key} =
 3080:           &Apache::lonnet::usertools_access($env{'user.name'},$env{'user.domain'},
 3081:           $key,'reload','tools');
 3082:                                 }
 3083:                             }
 3084:                         }
 3085:                         if (keys(%newenvhash)) {
 3086:                             &Apache::lonnet::appenv(\%newenvhash);
 3087:                         }
 3088:                     }
 3089:                 }
 3090:             }
 3091:             if (keys(%namechanged) > 0) {
 3092:                 foreach my $field (@userinfo) {
 3093:                     $changeHash{$field}  = $env{'form.c'.$field};
 3094:                 }
 3095: # Make the change
 3096:                 $namechgresult =
 3097:                     &Apache::lonnet::modifyuser($env{'form.ccdomain'},
 3098:                         $env{'form.ccuname'},$changeHash{'id'},undef,undef,
 3099:                         $changeHash{'firstname'},$changeHash{'middlename'},
 3100:                         $changeHash{'lastname'},$changeHash{'generation'},
 3101:                         $changeHash{'id'},undef,$changeHash{'permanentemail'},undef,\@userinfo);
 3102:                 %userupdate = (
 3103:                                lastname   => $env{'form.clastname'},
 3104:                                middlename => $env{'form.cmiddlename'},
 3105:                                firstname  => $env{'form.cfirstname'},
 3106:                                generation => $env{'form.cgeneration'},
 3107:                                id         => $env{'form.cid'},
 3108:                              );
 3109:             }
 3110:             if (((keys(%namechanged) > 0) && $namechgresult eq 'ok') || 
 3111:                 ((keys(%changed) > 0) && $chgresult eq 'ok')) {
 3112:             # Tell the user we changed the name
 3113:                 &display_userinfo($r,1,\@disporder,\%canshow,\@requestcourses,
 3114:                                   \@usertools,\@requestauthor,\%userenv,\%changed,\%namechanged,
 3115:                                   \%oldsettings, \%oldsettingstext,\%newsettings,
 3116:                                   \%newsettingstext);
 3117:                 if ($env{'form.cid'} ne $userenv{'id'}) {
 3118:                     &Apache::lonnet::idput($env{'form.ccdomain'},
 3119:                          {$env{'form.ccuname'} => $env{'form.cid'}},$uhome,'ids');
 3120:                     if (($recurseid) &&
 3121:                         (&Apache::lonnet::allowed('mau',$env{'form.ccdomain'}))) {
 3122:                         my $idresult = 
 3123:                             &Apache::lonuserutils::propagate_id_change(
 3124:                                 $env{'form.ccuname'},$env{'form.ccdomain'},
 3125:                                 \%userupdate);
 3126:                         $r->print('<br />'.$idresult.'<br />');
 3127:                     }
 3128:                 }
 3129:                 if (($env{'form.ccdomain'} eq $env{'user.domain'}) && 
 3130:                     ($env{'form.ccuname'} eq $env{'user.name'})) {
 3131:                     my %newenvhash;
 3132:                     foreach my $key (keys(%changeHash)) {
 3133:                         $newenvhash{'environment.'.$key} = $changeHash{$key};
 3134:                     }
 3135:                     &Apache::lonnet::appenv(\%newenvhash);
 3136:                 }
 3137:             } else { # error occurred
 3138:                 $r->print(
 3139:                     '<p class="LC_error">'
 3140:                    .&mt('Unable to successfully change environment for [_1] in domain [_2].',
 3141:                             '"'.$env{'form.ccuname'}.'"',
 3142:                             '"'.$env{'form.ccdomain'}.'"')
 3143:                    .'</p>');
 3144:             }
 3145:         } else { # End of if ($env ... ) logic
 3146:             # They did not want to change the users name, quota, tool availability,
 3147:             # or ability to request creation of courses, 
 3148:             # but we can still tell them what the name and quota and availabilities are  
 3149:             &display_userinfo($r,undef,\@disporder,\%canshow,\@requestcourses,
 3150:                               \@usertools,\@requestauthor,\%userenv,\%changed,\%namechanged,\%oldsettings,
 3151:                               \%oldsettingstext,\%newsettings,\%newsettingstext);
 3152:         }
 3153:         if (@mod_disallowed) {
 3154:             my ($rolestr,$contextname);
 3155:             if (@longroles > 0) {
 3156:                 $rolestr = join(', ',@longroles);
 3157:             } else {
 3158:                 $rolestr = &mt('No roles');
 3159:             }
 3160:             if ($context eq 'course') {
 3161:                 $contextname = 'course';
 3162:             } elsif ($context eq 'author') {
 3163:                 $contextname = 'co-author';
 3164:             }
 3165:             $r->print(&mt('The following fields were not updated: ').'<ul>');
 3166:             my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
 3167:             foreach my $field (@mod_disallowed) {
 3168:                 $r->print('<li>'.$fieldtitles{$field}.'</li>'."\n"); 
 3169:             }
 3170:             $r->print('</ul>');
 3171:             if (@mod_disallowed == 1) {
 3172:                 $r->print(&mt("You do not have the authority to change this field given the user's current set of active/future $contextname roles:"));
 3173:             } else {
 3174:                 $r->print(&mt("You do not have the authority to change these fields given the user's current set of active/future $contextname roles:"));
 3175:             }
 3176:             my $helplink = 'javascript:helpMenu('."'display'".')';
 3177:             $r->print('<span class="LC_cusr_emph">'.$rolestr.'</span><br />'
 3178:                      .&mt('Please contact your [_1]helpdesk[_2] for more information.'
 3179:                          ,'<a href="'.$helplink.'">','</a>')
 3180:                       .'<br />');
 3181:         }
 3182:         $r->print('<span class="LC_warning">'
 3183:                   .$no_forceid_alert
 3184:                   .&Apache::lonuserutils::print_namespacing_alerts($env{'form.ccdomain'},\%alerts,\%curr_rules)
 3185:                   .'</span>');
 3186:     }
 3187:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 3188:     if ($env{'form.action'} eq 'singlestudent') {
 3189:         &enroll_single_student($r,$uhome,$amode,$genpwd,$now,$newuser,$context,
 3190:                                $crstype,$showcredits,$defaultcredits);
 3191:         my $linktext = ($crstype eq 'Community' ?
 3192:             &mt('Enroll Another Member') : &mt('Enroll Another Student'));
 3193:         $r->print(
 3194:             &Apache::lonhtmlcommon::actionbox([
 3195:                 '<a href="javascript:backPage(document.userupdate)">'
 3196:                .($crstype eq 'Community' ? 
 3197:                     &mt('Enroll Another Member') : &mt('Enroll Another Student'))
 3198:                .'</a>']));
 3199:     } else {
 3200:         my @rolechanges = &update_roles($r,$context,$showcredits);
 3201:         if (keys(%namechanged) > 0) {
 3202:             if ($context eq 'course') {
 3203:                 if (@userroles > 0) {
 3204:                     if ((@rolechanges == 0) || 
 3205:                         (!(grep(/^st$/,@rolechanges)))) {
 3206:                         if (grep(/^st$/,@userroles)) {
 3207:                             my $classlistupdated =
 3208:                                 &Apache::lonuserutils::update_classlist($cdom,
 3209:                                               $cnum,$env{'form.ccdomain'},
 3210:                                        $env{'form.ccuname'},\%userupdate);
 3211:                         }
 3212:                     }
 3213:                 }
 3214:             }
 3215:         }
 3216:         my $userinfo = &Apache::loncommon::plainname($env{'form.ccuname'},
 3217:                                                      $env{'form.ccdomain'});
 3218:         if ($env{'form.popup'}) {
 3219:             $r->print('<p><a href="javascript:window.close()">'.&mt('Close window').'</a></p>');
 3220:         } else {
 3221:             $r->print('<br />'.&Apache::lonhtmlcommon::actionbox(['<a href="javascript:backPage(document.userupdate,'."'$env{'form.prevphase'}','modify'".')">'
 3222:                      .&mt('Modify this user: [_1]','<span class="LC_cusr_emph">'.$env{'form.ccuname'}.':'.$env{'form.ccdomain'}.' ('.$userinfo.')</span>').'</a>',
 3223:                      '<a href="javascript:backPage(document.userupdate)">'.&mt('Create/Modify Another User').'</a>']));
 3224:         }
 3225:     }
 3226: }
 3227: 
 3228: sub display_userinfo {
 3229:     my ($r,$changed,$order,$canshow,$requestcourses,$usertools,$requestauthor,
 3230:         $userenv,$changedhash,$namechangedhash,$oldsetting,$oldsettingtext,
 3231:         $newsetting,$newsettingtext) = @_;
 3232:     return unless (ref($order) eq 'ARRAY' &&
 3233:                    ref($canshow) eq 'HASH' && 
 3234:                    ref($requestcourses) eq 'ARRAY' && 
 3235:                    ref($requestauthor) eq 'ARRAY' &&
 3236:                    ref($usertools) eq 'ARRAY' && 
 3237:                    ref($userenv) eq 'HASH' &&
 3238:                    ref($changedhash) eq 'HASH' &&
 3239:                    ref($oldsetting) eq 'HASH' &&
 3240:                    ref($oldsettingtext) eq 'HASH' &&
 3241:                    ref($newsetting) eq 'HASH' &&
 3242:                    ref($newsettingtext) eq 'HASH');
 3243:     my %lt=&Apache::lonlocal::texthash(
 3244:          'ui'             => 'User Information',
 3245:          'uic'            => 'User Information Changed',
 3246:          'firstname'      => 'First Name',
 3247:          'middlename'     => 'Middle Name',
 3248:          'lastname'       => 'Last Name',
 3249:          'generation'     => 'Generation',
 3250:          'id'             => 'Student/Employee ID',
 3251:          'permanentemail' => 'Permanent e-mail address',
 3252:          'portfolioquota' => 'Disk space allocated to portfolio files',
 3253:          'authorquota'    => 'Disk space allocated to Authoring Space',
 3254:          'blog'           => 'Blog Availability',
 3255:          'webdav'         => 'WebDAV Availability',
 3256:          'aboutme'        => 'Personal Information Page Availability',
 3257:          'portfolio'      => 'Portfolio Availability',
 3258:          'official'       => 'Can Request Official Courses',
 3259:          'unofficial'     => 'Can Request Unofficial Courses',
 3260:          'community'      => 'Can Request Communities',
 3261:          'textbook'       => 'Can Request Textbook Courses',
 3262:          'placement'      => 'Can Request Placement Tests',
 3263:          'requestauthor'  => 'Can Request Author Role',
 3264:          'inststatus'     => "Affiliation",
 3265:          'prvs'           => 'Previous Value:',
 3266:          'chto'           => 'Changed To:'
 3267:     );
 3268:     if ($changed) {
 3269:         $r->print('<h3>'.$lt{'uic'}.'</h3>'.
 3270:                 &Apache::loncommon::start_data_table().
 3271:                 &Apache::loncommon::start_data_table_header_row());
 3272:         $r->print("<th>&nbsp;</th>\n");
 3273:         $r->print('<th><b>'.$lt{'prvs'}.'</b></th>');
 3274:         $r->print('<th><span class="LC_nobreak"><b>'.$lt{'chto'}.'</b></span></th>');
 3275:         $r->print(&Apache::loncommon::end_data_table_header_row());
 3276:         my @userinfo = ('firstname','middlename','lastname','generation','permanentemail','id');
 3277: 
 3278:         foreach my $item (@userinfo) {
 3279:             my $value = $env{'form.c'.$item};
 3280:             #show changes only:
 3281:             unless ($value eq $userenv->{$item}){
 3282:                 $r->print(&Apache::loncommon::start_data_table_row());
 3283:                 $r->print("<td>$lt{$item}</td>\n");
 3284:                 $r->print("<td>".$userenv->{$item}."</td>\n");
 3285:                 $r->print("<td>$value </td>\n");
 3286:                 $r->print(&Apache::loncommon::end_data_table_row());
 3287:             }
 3288:         }
 3289:         foreach my $entry (@{$order}) {
 3290:             if ($canshow->{$entry}) {
 3291:                 if (($entry eq 'requestcourses') || ($entry eq 'reqcrsotherdom') || ($entry eq 'requestauthor')) {
 3292:                     my @items;
 3293:                     if ($entry eq 'requestauthor') {
 3294:                         @items = ($entry);
 3295:                     } else {
 3296:                         @items = @{$requestcourses};
 3297:                     }
 3298:                     foreach my $item (@items) {
 3299:                         if (($newsetting->{$item} ne $oldsetting->{$item}) || 
 3300:                             ($newsettingtext->{$item} ne $oldsettingtext->{$item})) {
 3301:                             $r->print(&Apache::loncommon::start_data_table_row()."\n");  
 3302:                             $r->print("<td>$lt{$item}</td>\n");
 3303:                             $r->print("<td>".$oldsetting->{$item});
 3304:                             if ($oldsettingtext->{$item}) {
 3305:                                 if ($oldsetting->{$item}) {
 3306:                                     $r->print(' -- ');
 3307:                                 }
 3308:                                 $r->print($oldsettingtext->{$item});
 3309:                             }
 3310:                             $r->print("</td>\n");
 3311:                             $r->print("<td>".$newsetting->{$item});
 3312:                             if ($newsettingtext->{$item}) {
 3313:                                 if ($newsetting->{$item}) {
 3314:                                     $r->print(' -- ');
 3315:                                 }
 3316:                                 $r->print($newsettingtext->{$item});
 3317:                             }
 3318:                             $r->print("</td>\n");
 3319:                             $r->print(&Apache::loncommon::end_data_table_row()."\n");
 3320:                         }
 3321:                     }
 3322:                 } elsif ($entry eq 'tools') {
 3323:                     foreach my $item (@{$usertools}) {
 3324:                         if ($newsetting->{$item} ne $oldsetting->{$item}) {
 3325:                             $r->print(&Apache::loncommon::start_data_table_row()."\n");
 3326:                             $r->print("<td>$lt{$item}</td>\n");
 3327:                             $r->print("<td>".$oldsetting->{$item}.' '.$oldsettingtext->{$item}."</td>\n");
 3328:                             $r->print("<td>".$newsetting->{$item}.' '.$newsettingtext->{$item}."</td>\n");
 3329:                             $r->print(&Apache::loncommon::end_data_table_row()."\n");
 3330:                         }
 3331:                     }
 3332:                 } elsif ($entry eq 'quota') {
 3333:                     if ((ref($oldsetting->{$entry}) eq 'HASH') && (ref($oldsettingtext->{$entry}) eq 'HASH') &&
 3334:                         (ref($newsetting->{$entry}) eq 'HASH') && (ref($newsettingtext->{$entry}) eq 'HASH')) {
 3335:                         foreach my $name ('portfolio','author') {
 3336:                             if ($newsetting->{$entry}->{$name} ne $oldsetting->{$entry}->{$name}) {
 3337:                                 $r->print(&Apache::loncommon::start_data_table_row()."\n");
 3338:                                 $r->print("<td>$lt{$name.$entry}</td>\n");
 3339:                                 $r->print("<td>".$oldsettingtext->{$entry}->{$name}."</td>\n");
 3340:                                 $r->print("<td>".$newsettingtext->{$entry}->{$name}."</td>\n");
 3341:                                 $r->print(&Apache::loncommon::end_data_table_row()."\n");
 3342:                             }
 3343:                         }
 3344:                     }
 3345:                 } else {
 3346:                     if ($newsetting->{$entry} ne $oldsetting->{$entry}) {
 3347:                         $r->print(&Apache::loncommon::start_data_table_row()."\n");
 3348:                         $r->print("<td>$lt{$entry}</td>\n");
 3349:                         $r->print("<td>".$oldsetting->{$entry}.' '.$oldsettingtext->{$entry}."</td>\n");
 3350:                         $r->print("<td>".$newsetting->{$entry}.' '.$newsettingtext->{$entry}."</td>\n");
 3351:                         $r->print(&Apache::loncommon::end_data_table_row()."\n");
 3352:                     }
 3353:                 }
 3354:             }
 3355:         }
 3356:         $r->print(&Apache::loncommon::end_data_table().'<br />');
 3357:     } else {
 3358:         $r->print('<h3>'.$lt{'ui'}.'</h3>'.
 3359:                   '<p>'.&mt('No changes made to user information').'</p>');
 3360:     }
 3361:     return;
 3362: }
 3363: 
 3364: sub tool_changes {
 3365:     my ($context,$usertools,$oldaccess,$oldaccesstext,$userenv,$changeHash,
 3366:         $changed,$newaccess,$newaccesstext) = @_;
 3367:     if (!((ref($usertools) eq 'ARRAY') && (ref($oldaccess) eq 'HASH') &&
 3368:           (ref($oldaccesstext) eq 'HASH') && (ref($userenv) eq 'HASH') &&
 3369:           (ref($changeHash) eq 'HASH') && (ref($changed) eq 'HASH') &&
 3370:           (ref($newaccess) eq 'HASH') && (ref($newaccesstext) eq 'HASH'))) {
 3371:         return;
 3372:     }
 3373:     my %reqdisplay = &requestchange_display();
 3374:     if ($context eq 'reqcrsotherdom') {
 3375:         my @options = ('approval','validate','autolimit');
 3376:         my $optregex = join('|',@options);
 3377:         my $cdom = $env{'request.role.domain'};
 3378:         foreach my $tool (@{$usertools}) {
 3379:             $oldaccesstext->{$tool} = &mt("availability set to 'off'");
 3380:             $newaccesstext->{$tool} = $oldaccesstext->{$tool};
 3381:             $changeHash->{$context.'.'.$tool} = $userenv->{$context.'.'.$tool};
 3382:             my ($newop,$limit);
 3383:             if ($env{'form.'.$context.'_'.$tool}) {
 3384:                 $newop = $env{'form.'.$context.'_'.$tool};
 3385:                 if ($newop eq 'autolimit') {
 3386:                     $limit = $env{'form.'.$context.'_'.$tool.'_limit'};
 3387:                     $limit =~ s/\D+//g;
 3388:                     $newop .= '='.$limit;
 3389:                 }
 3390:             }
 3391:             if ($userenv->{$context.'.'.$tool} eq '') {
 3392:                 if ($newop) {
 3393:                     $changed->{$tool}=&tool_admin($tool,$cdom.':'.$newop,
 3394:                                                   $changeHash,$context);
 3395:                     if ($changed->{$tool}) {
 3396:                         if ($newop =~ /^autolimit/) {
 3397:                             if ($limit) {
 3398:                                 $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3399:                             } else {
 3400:                                 $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3401:                             }
 3402:                         } else {
 3403:                             $newaccesstext->{$tool} = $reqdisplay{$newop};
 3404:                         }
 3405:                     } else {
 3406:                         $newaccesstext->{$tool} = $oldaccesstext->{$tool};
 3407:                     }
 3408:                 }
 3409:             } else {
 3410:                 my @curr = split(',',$userenv->{$context.'.'.$tool});
 3411:                 my @new;
 3412:                 my $changedoms;
 3413:                 foreach my $req (@curr) {
 3414:                     if ($req =~ /^\Q$cdom\E\:($optregex\=?\d*)$/) {
 3415:                         my $oldop = $1;
 3416:                         if ($oldop =~ /^autolimit=(\d*)/) {
 3417:                             my $limit = $1;
 3418:                             if ($limit) {
 3419:                                 $oldaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3420:                             } else {
 3421:                                 $oldaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3422:                             }
 3423:                         } else {
 3424:                             $oldaccesstext->{$tool} = $reqdisplay{$oldop};
 3425:                         }
 3426:                         if ($oldop ne $newop) {
 3427:                             $changedoms = 1;
 3428:                             foreach my $item (@curr) {
 3429:                                 my ($reqdom,$option) = split(':',$item);
 3430:                                 unless ($reqdom eq $cdom) {
 3431:                                     push(@new,$item);
 3432:                                 }
 3433:                             }
 3434:                             if ($newop) {
 3435:                                 push(@new,$cdom.':'.$newop);
 3436:                             }
 3437:                             @new = sort(@new);
 3438:                         }
 3439:                         last;
 3440:                     }
 3441:                 }
 3442:                 if ((!$changedoms) && ($newop)) {
 3443:                     $changedoms = 1;
 3444:                     @new = sort(@curr,$cdom.':'.$newop);
 3445:                 }
 3446:                 if ($changedoms) {
 3447:                     my $newdomstr;
 3448:                     if (@new) {
 3449:                         $newdomstr = join(',',@new);
 3450:                     }
 3451:                     $changed->{$tool}=&tool_admin($tool,$newdomstr,$changeHash,
 3452:                                                   $context);
 3453:                     if ($changed->{$tool}) {
 3454:                         if ($env{'form.'.$context.'_'.$tool}) {
 3455:                             if ($env{'form.'.$context.'_'.$tool} eq 'autolimit') {
 3456:                                 my $limit = $env{'form.'.$context.'_'.$tool.'_limit'};
 3457:                                 $limit =~ s/\D+//g;
 3458:                                 if ($limit) {
 3459:                                     $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3460:                                 } else {
 3461:                                     $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3462:                                 }
 3463:                             } else {
 3464:                                 $newaccesstext->{$tool} = $reqdisplay{$env{'form.'.$context.'_'.$tool}};
 3465:                             }
 3466:                         } else {
 3467:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3468:                         }
 3469:                     }
 3470:                 }
 3471:             }
 3472:         }
 3473:         return;
 3474:     }
 3475:     foreach my $tool (@{$usertools}) {
 3476:         my ($newval,$limit,$envkey);
 3477:         $envkey = $context.'.'.$tool;
 3478:         if ($context eq 'requestcourses') {
 3479:             $newval = $env{'form.crsreq_'.$tool};
 3480:             if ($newval eq 'autolimit') {
 3481:                 $limit = $env{'form.crsreq_'.$tool.'_limit'};
 3482:                 $limit =~ s/\D+//g;
 3483:                 $newval .= '='.$limit;
 3484:             }
 3485:         } elsif ($context eq 'requestauthor') {
 3486:             $newval = $env{'form.'.$context};
 3487:             $envkey = $context;
 3488:         } else {
 3489:             $newval = $env{'form.'.$context.'_'.$tool};
 3490:         }
 3491:         if ($userenv->{$envkey} ne '') {
 3492:             $oldaccess->{$tool} = &mt('custom');
 3493:             if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 3494:                 if ($userenv->{$envkey} =~ /^autolimit=(\d*)$/) {
 3495:                     my $currlimit = $1;
 3496:                     if ($currlimit eq '') {
 3497:                         $oldaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3498:                     } else {
 3499:                         $oldaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$currlimit);
 3500:                     }
 3501:                 } elsif ($userenv->{$envkey}) {
 3502:                     $oldaccesstext->{$tool} = $reqdisplay{$userenv->{$envkey}};
 3503:                 } else {
 3504:                     $oldaccesstext->{$tool} = &mt("availability set to 'off'");
 3505:                 }
 3506:             } else {
 3507:                 if ($userenv->{$envkey}) {
 3508:                     $oldaccesstext->{$tool} = &mt("availability set to 'on'");
 3509:                 } else {
 3510:                     $oldaccesstext->{$tool} = &mt("availability set to 'off'");
 3511:                 }
 3512:             }
 3513:             $changeHash->{$envkey} = $userenv->{$envkey};
 3514:             if ($env{'form.custom'.$tool} == 1) {
 3515:                 if ($newval ne $userenv->{$envkey}) {
 3516:                     $changed->{$tool} = &tool_admin($tool,$newval,$changeHash,
 3517:                                                     $context);
 3518:                     if ($changed->{$tool}) {
 3519:                         $newaccess->{$tool} = &mt('custom');
 3520:                         if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 3521:                             if ($newval =~ /^autolimit/) {
 3522:                                 if ($limit) {
 3523:                                     $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3524:                                 } else {
 3525:                                     $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3526:                                 }
 3527:                             } elsif ($newval) {
 3528:                                 $newaccesstext->{$tool} = $reqdisplay{$newval};
 3529:                             } else {
 3530:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3531:                             }
 3532:                         } else {
 3533:                             if ($newval) {
 3534:                                 $newaccesstext->{$tool} = &mt("availability set to 'on'");
 3535:                             } else {
 3536:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3537:                             }
 3538:                         }
 3539:                     } else {
 3540:                         $newaccess->{$tool} = $oldaccess->{$tool};
 3541:                         if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 3542:                             if ($newval =~ /^autolimit/) {
 3543:                                 if ($limit) {
 3544:                                     $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3545:                                 } else {
 3546:                                     $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3547:                                 }
 3548:                             } elsif ($newval) {
 3549:                                 $newaccesstext->{$tool} = $reqdisplay{$newval};
 3550:                             } else {
 3551:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3552:                             }
 3553:                         } else {
 3554:                             if ($userenv->{$context.'.'.$tool}) {
 3555:                                 $newaccesstext->{$tool} = &mt("availability set to 'on'");
 3556:                             } else {
 3557:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3558:                             }
 3559:                         }
 3560:                     }
 3561:                 } else {
 3562:                     $newaccess->{$tool} = $oldaccess->{$tool};
 3563:                     $newaccesstext->{$tool} = $oldaccesstext->{$tool};
 3564:                 }
 3565:             } else {
 3566:                 $changed->{$tool} = &tool_admin($tool,'',$changeHash,$context);
 3567:                 if ($changed->{$tool}) {
 3568:                     $newaccess->{$tool} = &mt('default');
 3569:                 } else {
 3570:                     $newaccess->{$tool} = $oldaccess->{$tool};
 3571:                     if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 3572:                         if ($newval =~ /^autolimit/) {
 3573:                             if ($limit) {
 3574:                                 $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3575:                             } else {
 3576:                                 $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3577:                             }
 3578:                         } elsif ($newval) {
 3579:                             $newaccesstext->{$tool} = $reqdisplay{$newval};
 3580:                         } else {
 3581:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3582:                         }
 3583:                     } else {
 3584:                         if ($userenv->{$context.'.'.$tool}) {
 3585:                             $newaccesstext->{$tool} = &mt("availability set to 'on'");
 3586:                         } else {
 3587:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3588:                         }
 3589:                     }
 3590:                 }
 3591:             }
 3592:         } else {
 3593:             $oldaccess->{$tool} = &mt('default');
 3594:             if ($env{'form.custom'.$tool} == 1) {
 3595:                 $changed->{$tool} = &tool_admin($tool,$newval,$changeHash,
 3596:                                                 $context);
 3597:                 if ($changed->{$tool}) {
 3598:                     $newaccess->{$tool} = &mt('custom');
 3599:                     if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 3600:                         if ($newval =~ /^autolimit/) {
 3601:                             if ($limit) {
 3602:                                 $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3603:                             } else {
 3604:                                 $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3605:                             }
 3606:                         } elsif ($newval) {
 3607:                             $newaccesstext->{$tool} = $reqdisplay{$newval};
 3608:                         } else {
 3609:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3610:                         }
 3611:                     } else {
 3612:                         if ($newval) {
 3613:                             $newaccesstext->{$tool} = &mt("availability set to 'on'");
 3614:                         } else {
 3615:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3616:                         }
 3617:                     }
 3618:                 } else {
 3619:                     $newaccess->{$tool} = $oldaccess->{$tool};
 3620:                 }
 3621:             } else {
 3622:                 $newaccess->{$tool} = $oldaccess->{$tool};
 3623:             }
 3624:         }
 3625:     }
 3626:     return;
 3627: }
 3628: 
 3629: sub update_roles {
 3630:     my ($r,$context,$showcredits) = @_;
 3631:     my $now=time;
 3632:     my @rolechanges;
 3633:     my %disallowed;
 3634:     $r->print('<h3>'.&mt('Modifying Roles').'</h3>');
 3635:     foreach my $key (keys(%env)) {
 3636: 	next if (! $env{$key});
 3637:         next if ($key eq 'form.action');
 3638: 	# Revoke roles
 3639: 	if ($key=~/^form\.rev/) {
 3640: 	    if ($key=~/^form\.rev\:([^\_]+)\_([^\_\.]+)$/) {
 3641: # Revoke standard role
 3642: 		my ($scope,$role) = ($1,$2);
 3643: 		my $result =
 3644: 		    &Apache::lonnet::revokerole($env{'form.ccdomain'},
 3645: 						$env{'form.ccuname'},
 3646: 						$scope,$role,'','',$context);
 3647:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
 3648:                             &mt('Revoking [_1] in [_2]',
 3649:                                 &Apache::lonnet::plaintext($role),
 3650:                                 &Apache::loncommon::show_role_extent($scope,$context,$role)),
 3651:                                 $result ne "ok").'<br />');
 3652:                 if ($result ne "ok") {
 3653:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 3654:                 }
 3655: 		if ($role eq 'st') {
 3656: 		    my $result = 
 3657:                         &Apache::lonuserutils::classlist_drop($scope,
 3658:                             $env{'form.ccuname'},$env{'form.ccdomain'},
 3659: 			    $now);
 3660:                     $r->print(&Apache::lonhtmlcommon::confirm_success($result));
 3661: 		}
 3662:                 if (!grep(/^\Q$role\E$/,@rolechanges)) {
 3663:                     push(@rolechanges,$role);
 3664:                 }
 3665: 	    }
 3666: 	    if ($key=~m{^form\.rev\:([^_]+)_cr\.cr/($match_domain)/($match_username)/(\w+)$}s) {
 3667: # Revoke custom role
 3668:                 my $result = &Apache::lonnet::revokecustomrole(
 3669:                     $env{'form.ccdomain'},$env{'form.ccuname'},$1,$2,$3,$4,'','',$context);
 3670:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
 3671:                             &mt('Revoking custom role [_1] by [_2] in [_3]',
 3672:                                 $4,$3.':'.$2,&Apache::loncommon::show_role_extent($1,$context,'cr')),
 3673:                             $result ne 'ok').'<br />');
 3674:                 if ($result ne "ok") {
 3675:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 3676:                 }
 3677:                 if (!grep(/^cr$/,@rolechanges)) {
 3678:                     push(@rolechanges,'cr');
 3679:                 }
 3680: 	    }
 3681: 	} elsif ($key=~/^form\.del/) {
 3682: 	    if ($key=~/^form\.del\:([^\_]+)\_([^\_\.]+)$/) {
 3683: # Delete standard role
 3684: 		my ($scope,$role) = ($1,$2);
 3685: 		my $result =
 3686: 		    &Apache::lonnet::assignrole($env{'form.ccdomain'},
 3687: 						$env{'form.ccuname'},
 3688: 						$scope,$role,$now,0,1,'',
 3689:                                                 $context);
 3690:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
 3691:                             &mt('Deleting [_1] in [_2]',
 3692:                                 &Apache::lonnet::plaintext($role),
 3693:                                 &Apache::loncommon::show_role_extent($scope,$context,$role)),
 3694:                             $result ne 'ok').'<br />');
 3695:                 if ($result ne "ok") {
 3696:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 3697:                 }
 3698: 
 3699: 		if ($role eq 'st') {
 3700: 		    my $result = 
 3701:                         &Apache::lonuserutils::classlist_drop($scope,
 3702:                             $env{'form.ccuname'},$env{'form.ccdomain'},
 3703: 			    $now);
 3704: 		    $r->print(&Apache::lonhtmlcommon::confirm_success($result));
 3705: 		}
 3706:                 if (!grep(/^\Q$role\E$/,@rolechanges)) {
 3707:                     push(@rolechanges,$role);
 3708:                 }
 3709:             }
 3710: 	    if ($key=~m{^form\.del\:([^_]+)_cr\.cr/($match_domain)/($match_username)/(\w+)$}) {
 3711:                 my ($url,$rdom,$rnam,$rolename) = ($1,$2,$3,$4);
 3712: # Delete custom role
 3713:                 my $result =
 3714:                     &Apache::lonnet::assigncustomrole($env{'form.ccdomain'},
 3715:                         $env{'form.ccuname'},$url,$rdom,$rnam,$rolename,$now,
 3716:                         0,1,$context);
 3717:                 $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('Deleting custom role [_1] by [_2] in [_3]',
 3718:                       $rolename,$rnam.':'.$rdom,&Apache::loncommon::show_role_extent($1,$context,'cr')),
 3719:                       $result ne "ok").'<br />');
 3720:                 if ($result ne "ok") {
 3721:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 3722:                 }
 3723: 
 3724:                 if (!grep(/^cr$/,@rolechanges)) {
 3725:                     push(@rolechanges,'cr');
 3726:                 }
 3727:             }
 3728: 	} elsif ($key=~/^form\.ren/) {
 3729:             my $udom = $env{'form.ccdomain'};
 3730:             my $uname = $env{'form.ccuname'};
 3731: # Re-enable standard role
 3732: 	    if ($key=~/^form\.ren\:([^\_]+)\_([^\_\.]+)$/) {
 3733:                 my $url = $1;
 3734:                 my $role = $2;
 3735:                 my $logmsg;
 3736:                 my $output;
 3737:                 if ($role eq 'st') {
 3738:                     if ($url =~ m-^/($match_domain)/($match_courseid)/?(\w*)$-) {
 3739:                         my ($cdom,$cnum,$csec) = ($1,$2,$3);
 3740:                         my $credits;
 3741:                         if ($showcredits) {
 3742:                             my $defaultcredits = 
 3743:                                 &Apache::lonuserutils::get_defaultcredits($cdom,$cnum);
 3744:                             $credits = &get_user_credits($defaultcredits,$cdom,$cnum);
 3745:                         }
 3746:                         my $result = &Apache::loncommon::commit_studentrole(\$logmsg,$udom,$uname,$url,$role,$now,0,$cdom,$cnum,$csec,$context,$credits);
 3747:                         if (($result =~ /^error/) || ($result eq 'not_in_class') || ($result eq 'unknown_course') || ($result eq 'refused')) {
 3748:                             if ($result eq 'refused' && $logmsg) {
 3749:                                 $output = $logmsg;
 3750:                             } else { 
 3751:                                 $output = &mt('Error: [_1]',$result)."\n";
 3752:                             }
 3753:                         } else {
 3754:                             $output = &Apache::lonhtmlcommon::confirm_success(&mt('Assigning [_1] in [_2] starting [_3]',
 3755:                                         &Apache::lonnet::plaintext($role),
 3756:                                         &Apache::loncommon::show_role_extent($url,$context,'st'),
 3757:                                         &Apache::lonlocal::locallocaltime($now))).'<br />'.$logmsg.'<br />';
 3758:                         }
 3759:                     }
 3760:                 } else {
 3761: 		    my $result=&Apache::lonnet::assignrole($env{'form.ccdomain'},
 3762:                                $env{'form.ccuname'},$url,$role,0,$now,'','',
 3763:                                $context);
 3764:                         $output = &Apache::lonhtmlcommon::confirm_success(&mt('Re-enabling [_1] in [_2]',
 3765:                                         &Apache::lonnet::plaintext($role),
 3766:                                         &Apache::loncommon::show_role_extent($url,$context,$role)),$result ne "ok").'<br />';
 3767:                     if ($result ne "ok") {
 3768:                         $output .= &mt('Error: [_1]',$result).'<br />';
 3769:                     }
 3770:                 }
 3771:                 $r->print($output);
 3772:                 if (!grep(/^\Q$role\E$/,@rolechanges)) {
 3773:                     push(@rolechanges,$role);
 3774:                 }
 3775: 	    }
 3776: # Re-enable custom role
 3777: 	    if ($key=~m{^form\.ren\:([^_]+)_cr\.cr/($match_domain)/($match_username)/(\w+)$}) {
 3778:                 my ($url,$rdom,$rnam,$rolename) = ($1,$2,$3,$4);
 3779:                 my $result = &Apache::lonnet::assigncustomrole(
 3780:                                $env{'form.ccdomain'}, $env{'form.ccuname'},
 3781:                                $url,$rdom,$rnam,$rolename,0,$now,undef,$context);
 3782:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
 3783:                     &mt('Re-enabling custom role [_1] by [_2] in [_3]',
 3784:                         $rolename,$rnam.':'.$rdom,&Apache::loncommon::show_role_extent($1,$context,'cr')),
 3785:                     $result ne "ok").'<br />');
 3786:                 if ($result ne "ok") {
 3787:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 3788:                 }
 3789:                 if (!grep(/^cr$/,@rolechanges)) {
 3790:                     push(@rolechanges,'cr');
 3791:                 }
 3792:             }
 3793: 	} elsif ($key=~/^form\.act/) {
 3794:             my $udom = $env{'form.ccdomain'};
 3795:             my $uname = $env{'form.ccuname'};
 3796: 	    if ($key=~/^form\.act\_($match_domain)\_($match_courseid)\_cr_cr_($match_domain)_($match_username)_([^\_]+)$/) {
 3797:                 # Activate a custom role
 3798: 		my ($one,$two,$three,$four,$five)=($1,$2,$3,$4,$5);
 3799: 		my $url='/'.$one.'/'.$two;
 3800: 		my $full=$one.'_'.$two.'_cr_cr_'.$three.'_'.$four.'_'.$five;
 3801: 
 3802:                 my $start = ( $env{'form.start_'.$full} ?
 3803:                               $env{'form.start_'.$full} :
 3804:                               $now );
 3805:                 my $end   = ( $env{'form.end_'.$full} ?
 3806:                               $env{'form.end_'.$full} :
 3807:                               0 );
 3808:                                                                                      
 3809:                 # split multiple sections
 3810:                 my %sections = ();
 3811:                 my $num_sections = &build_roles($env{'form.sec_'.$full},\%sections,$5);
 3812:                 if ($num_sections == 0) {
 3813:                     $r->print(&Apache::loncommon::commit_customrole($udom,$uname,$url,$three,$four,$five,$start,$end,$context));
 3814:                 } else {
 3815: 		    my %curr_groups =
 3816: 			&Apache::longroup::coursegroups($one,$two);
 3817:                     foreach my $sec (sort {$a cmp $b} keys(%sections)) {
 3818:                         if (($sec eq 'none') || ($sec eq 'all') || 
 3819:                             exists($curr_groups{$sec})) {
 3820:                             $disallowed{$sec} = $url;
 3821:                             next;
 3822:                         }
 3823:                         my $securl = $url.'/'.$sec;
 3824: 		        $r->print(&Apache::loncommon::commit_customrole($udom,$uname,$securl,$three,$four,$five,$start,$end,$context));
 3825:                     }
 3826:                 }
 3827:                 if (!grep(/^cr$/,@rolechanges)) {
 3828:                     push(@rolechanges,'cr');
 3829:                 }
 3830: 	    } elsif ($key=~/^form\.act\_($match_domain)\_($match_name)\_([^\_]+)$/) {
 3831: 		# Activate roles for sections with 3 id numbers
 3832: 		# set start, end times, and the url for the class
 3833: 		my ($one,$two,$three)=($1,$2,$3);
 3834: 		my $start = ( $env{'form.start_'.$one.'_'.$two.'_'.$three} ? 
 3835: 			      $env{'form.start_'.$one.'_'.$two.'_'.$three} : 
 3836: 			      $now );
 3837: 		my $end   = ( $env{'form.end_'.$one.'_'.$two.'_'.$three} ? 
 3838: 			      $env{'form.end_'.$one.'_'.$two.'_'.$three} :
 3839: 			      0 );
 3840: 		my $url='/'.$one.'/'.$two;
 3841:                 my $type = 'three';
 3842:                 # split multiple sections
 3843:                 my %sections = ();
 3844:                 my $num_sections = &build_roles($env{'form.sec_'.$one.'_'.$two.'_'.$three},\%sections,$three);
 3845:                 my $credits;
 3846:                 if ($three eq 'st') {
 3847:                     if ($showcredits) { 
 3848:                         my $defaultcredits = 
 3849:                             &Apache::lonuserutils::get_defaultcredits($one,$two);
 3850:                         $credits = $env{'form.credits_'.$one.'_'.$two.'_'.$three};
 3851:                         $credits =~ s/[^\d\.]//g;
 3852:                         if ($credits eq $defaultcredits) {
 3853:                             undef($credits);
 3854:                         }
 3855:                     }
 3856:                 }
 3857:                 if ($num_sections == 0) {
 3858:                     $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$three,$start,$end,$one,$two,'',$context,$credits));
 3859:                 } else {
 3860:                     my %curr_groups = 
 3861: 			&Apache::longroup::coursegroups($one,$two);
 3862:                     my $emptysec = 0;
 3863:                     foreach my $sec (sort {$a cmp $b} keys(%sections)) {
 3864:                         $sec =~ s/\W//g;
 3865:                         if ($sec ne '') {
 3866:                             if (($sec eq 'none') || ($sec eq 'all') || 
 3867:                                 exists($curr_groups{$sec})) {
 3868:                                 $disallowed{$sec} = $url;
 3869:                                 next;
 3870:                             }
 3871:                             my $securl = $url.'/'.$sec;
 3872:                             $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$securl,$three,$start,$end,$one,$two,$sec,$context,$credits));
 3873:                         } else {
 3874:                             $emptysec = 1;
 3875:                         }
 3876:                     }
 3877:                     if ($emptysec) {
 3878:                         $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$three,$start,$end,$one,$two,'',$context,$credits));
 3879:                     }
 3880:                 }
 3881:                 if (!grep(/^\Q$three\E$/,@rolechanges)) {
 3882:                     push(@rolechanges,$three);
 3883:                 }
 3884: 	    } elsif ($key=~/^form\.act\_([^\_]+)\_([^\_]+)$/) {
 3885: 		# Activate roles for sections with two id numbers
 3886: 		# set start, end times, and the url for the class
 3887: 		my $start = ( $env{'form.start_'.$1.'_'.$2} ? 
 3888: 			      $env{'form.start_'.$1.'_'.$2} : 
 3889: 			      $now );
 3890: 		my $end   = ( $env{'form.end_'.$1.'_'.$2} ? 
 3891: 			      $env{'form.end_'.$1.'_'.$2} :
 3892: 			      0 );
 3893:                 my $one = $1;
 3894:                 my $two = $2;
 3895: 		my $url='/'.$one.'/';
 3896:                 # split multiple sections
 3897:                 my %sections = ();
 3898:                 my $num_sections = &build_roles($env{'form.sec_'.$one.'_'.$two},\%sections,$two);
 3899:                 if ($num_sections == 0) {
 3900:                     $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$two,$start,$end,$one,undef,'',$context));
 3901:                 } else {
 3902:                     my $emptysec = 0;
 3903:                     foreach my $sec (sort {$a cmp $b} keys(%sections)) {
 3904:                         if ($sec ne '') {
 3905:                             my $securl = $url.'/'.$sec;
 3906:                             $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$securl,$two,$start,$end,$one,undef,$sec,$context));
 3907:                         } else {
 3908:                             $emptysec = 1;
 3909:                         }
 3910:                     }
 3911:                     if ($emptysec) {
 3912:                         $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$two,$start,$end,$one,undef,'',$context));
 3913:                     }
 3914:                 }
 3915:                 if (!grep(/^\Q$two\E$/,@rolechanges)) {
 3916:                     push(@rolechanges,$two);
 3917:                 }
 3918: 	    } else {
 3919: 		$r->print('<p><span class="LC_error">'.&mt('ERROR').': '.&mt('Unknown command').' <tt>'.$key.'</tt></span></p><br />');
 3920:             }
 3921:             foreach my $key (sort(keys(%disallowed))) {
 3922:                 $r->print('<p class="LC_warning">');
 3923:                 if (($key eq 'none') || ($key eq 'all')) {  
 3924:                     $r->print(&mt('[_1] may not be used as the name for a section, as it is a reserved word.','<tt>'.$key.'</tt>'));
 3925:                 } else {
 3926:                     $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>'));
 3927:                 }
 3928:                 $r->print('</p><p>'
 3929:                          .&mt('Please [_1]go back[_2] and choose a different section name.'
 3930:                              ,'<a href="javascript:history.go(-1)'
 3931:                              ,'</a>')
 3932:                          .'</p><br />'
 3933:                 );
 3934:             }
 3935: 	}
 3936:     } # End of foreach (keys(%env))
 3937: # Flush the course logs so reverse user roles immediately updated
 3938:     $r->register_cleanup(\&Apache::lonnet::flushcourselogs);
 3939:     if (@rolechanges == 0) {
 3940:         $r->print('<p>'.&mt('No roles to modify').'</p>');
 3941:     }
 3942:     return @rolechanges;
 3943: }
 3944: 
 3945: sub get_user_credits {
 3946:     my ($uname,$udom,$defaultcredits,$cdom,$cnum) = @_;
 3947:     if ($cdom eq '' || $cnum eq '') {
 3948:         return unless ($env{'request.course.id'});
 3949:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3950:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3951:     }
 3952:     my $credits;
 3953:     my %currhash =
 3954:         &Apache::lonnet::get('classlist',[$uname.':'.$udom],$cdom,$cnum);
 3955:     if (keys(%currhash) > 0) {
 3956:         my @items = split(/:/,$currhash{$uname.':'.$udom});
 3957:         my $crdidx = &Apache::loncoursedata::CL_CREDITS() - 3;
 3958:         $credits = $items[$crdidx];
 3959:         $credits =~ s/[^\d\.]//g;
 3960:     }
 3961:     if ($credits eq $defaultcredits) {
 3962:         undef($credits);
 3963:     }
 3964:     return $credits;
 3965: }
 3966: 
 3967: sub enroll_single_student {
 3968:     my ($r,$uhome,$amode,$genpwd,$now,$newuser,$context,$crstype,
 3969:         $showcredits,$defaultcredits) = @_;
 3970:     $r->print('<h3>');
 3971:     if ($crstype eq 'Community') {
 3972:         $r->print(&mt('Enrolling Member'));
 3973:     } else {
 3974:         $r->print(&mt('Enrolling Student'));
 3975:     }
 3976:     $r->print('</h3>');
 3977: 
 3978:     # Remove non alphanumeric values from section
 3979:     $env{'form.sections'}=~s/\W//g;
 3980: 
 3981:     my $credits;
 3982:     if (($showcredits) && ($env{'form.credits'} ne '')) {
 3983:         $credits = $env{'form.credits'};
 3984:         $credits =~ s/[^\d\.]//g;
 3985:         if ($credits ne '') {
 3986:             if ($credits eq $defaultcredits) {
 3987:                 undef($credits);
 3988:             }
 3989:         }
 3990:     }
 3991: 
 3992:     # Clean out any old student roles the user has in this class.
 3993:     &Apache::lonuserutils::modifystudent($env{'form.ccdomain'},
 3994:          $env{'form.ccuname'},$env{'request.course.id'},undef,$uhome);
 3995:     my ($startdate,$enddate) = &Apache::lonuserutils::get_dates_from_form();
 3996:     my $enroll_result =
 3997:         &Apache::lonnet::modify_student_enrollment($env{'form.ccdomain'},
 3998:             $env{'form.ccuname'},$env{'form.cid'},$env{'form.cfirstname'},
 3999:             $env{'form.cmiddlename'},$env{'form.clastname'},
 4000:             $env{'form.generation'},$env{'form.sections'},$enddate,
 4001:             $startdate,'manual',undef,$env{'request.course.id'},'',$context,
 4002:             $credits);
 4003:     if ($enroll_result =~ /^ok/) {
 4004:         $r->print(&mt('[_1] enrolled','<b>'.$env{'form.ccuname'}.':'.$env{'form.ccdomain'}.'</b>'));
 4005:         if ($env{'form.sections'} ne '') {
 4006:             $r->print(' '.&mt('in section [_1]',$env{'form.sections'}));
 4007:         }
 4008:         my ($showstart,$showend);
 4009:         if ($startdate <= $now) {
 4010:             $showstart = &mt('Access starts immediately');
 4011:         } else {
 4012:             $showstart = &mt('Access starts: ').&Apache::lonlocal::locallocaltime($startdate);
 4013:         }
 4014:         if ($enddate == 0) {
 4015:             $showend = &mt('ends: no ending date');
 4016:         } else {
 4017:             $showend = &mt('ends: ').&Apache::lonlocal::locallocaltime($enddate);
 4018:         }
 4019:         $r->print('.<br />'.$showstart.'; '.$showend);
 4020:         if ($startdate <= $now && !$newuser) {
 4021:             $r->print('<p class="LC_info">');
 4022:             if ($crstype eq 'Community') {
 4023:                 $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.'));
 4024:             } else {
 4025:                 $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.'));
 4026:            }
 4027:            $r->print('</p>');
 4028:         }
 4029:     } else {
 4030:         $r->print(&mt('unable to enroll').": ".$enroll_result);
 4031:     }
 4032:     return;
 4033: }
 4034: 
 4035: sub get_defaultquota_text {
 4036:     my ($settingstatus) = @_;
 4037:     my $defquotatext; 
 4038:     if ($settingstatus eq '') {
 4039:         $defquotatext = &mt('default');
 4040:     } else {
 4041:         my ($usertypes,$order) =
 4042:             &Apache::lonnet::retrieve_inst_usertypes($env{'form.ccdomain'});
 4043:         if ($usertypes->{$settingstatus} eq '') {
 4044:             $defquotatext = &mt('default');
 4045:         } else {
 4046:             $defquotatext = &mt('default for [_1]',$usertypes->{$settingstatus});
 4047:         }
 4048:     }
 4049:     return $defquotatext;
 4050: }
 4051: 
 4052: sub update_result_form {
 4053:     my ($uhome) = @_;
 4054:     my $outcome = 
 4055:     '<form name="userupdate" method="post" action="">'."\n";
 4056:     foreach my $item ('srchby','srchin','srchtype','srchterm','srchdomain','ccuname','ccdomain') {
 4057:         $outcome .= '<input type="hidden" name="'.$item.'" value="'.$env{'form.'.$item}.'" />'."\n";
 4058:     }
 4059:     if ($env{'form.origname'} ne '') {
 4060:         $outcome .= '<input type="hidden" name="origname" value="'.$env{'form.origname'}.'" />'."\n";
 4061:     }
 4062:     foreach my $item ('sortby','seluname','seludom') {
 4063:         if (exists($env{'form.'.$item})) {
 4064:             $outcome .= '<input type="hidden" name="'.$item.'" value="'.$env{'form.'.$item}.'" />'."\n";
 4065:         }
 4066:     }
 4067:     if ($uhome eq 'no_host') {
 4068:         $outcome .= '<input type="hidden" name="forcenewuser" value="1" />'."\n";
 4069:     }
 4070:     $outcome .= '<input type="hidden" name="phase" value="" />'."\n".
 4071:                 '<input type="hidden" name="currstate" value="" />'."\n".
 4072:                 '<input type="hidden" name="action" value="'.$env{'form.action'}.'" />'."\n".
 4073:                 '</form>';
 4074:     return $outcome;
 4075: }
 4076: 
 4077: sub quota_admin {
 4078:     my ($setquota,$changeHash,$name) = @_;
 4079:     my $quotachanged;
 4080:     if (&Apache::lonnet::allowed('mpq',$env{'form.ccdomain'})) {
 4081:         # Current user has quota modification privileges
 4082:         if (ref($changeHash) eq 'HASH') {
 4083:             $quotachanged = 1;
 4084:             $changeHash->{$name.'quota'} = $setquota;
 4085:         }
 4086:     }
 4087:     return $quotachanged;
 4088: }
 4089: 
 4090: sub tool_admin {
 4091:     my ($tool,$settool,$changeHash,$context) = @_;
 4092:     my $canchange = 0; 
 4093:     if ($context eq 'requestcourses') {
 4094:         if (&Apache::lonnet::allowed('ccc',$env{'form.ccdomain'})) {
 4095:             $canchange = 1;
 4096:         }
 4097:     } elsif ($context eq 'reqcrsotherdom') {
 4098:         if (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) {
 4099:             $canchange = 1;
 4100:         }
 4101:     } elsif ($context eq 'requestauthor') {
 4102:         if (&Apache::lonnet::allowed('cau',$env{'request.role.domain'})) {
 4103:             $canchange = 1;
 4104:         }
 4105:     } elsif (&Apache::lonnet::allowed('mut',$env{'form.ccdomain'})) {
 4106:         # Current user has quota modification privileges
 4107:         $canchange = 1;
 4108:     }
 4109:     my $toolchanged;
 4110:     if ($canchange) {
 4111:         if (ref($changeHash) eq 'HASH') {
 4112:             $toolchanged = 1;
 4113:             if ($tool eq 'requestauthor') {
 4114:                 $changeHash->{$context} = $settool;
 4115:             } else {
 4116:                 $changeHash->{$context.'.'.$tool} = $settool;
 4117:             }
 4118:         }
 4119:     }
 4120:     return $toolchanged;
 4121: }
 4122: 
 4123: sub build_roles {
 4124:     my ($sectionstr,$sections,$role) = @_;
 4125:     my $num_sections = 0;
 4126:     if ($sectionstr=~ /,/) {
 4127:         my @secnums = split/,/,$sectionstr;
 4128:         if ($role eq 'st') {
 4129:             $secnums[0] =~ s/\W//g;
 4130:             $$sections{$secnums[0]} = 1;
 4131:             $num_sections = 1;
 4132:         } else {
 4133:             foreach my $sec (@secnums) {
 4134:                 $sec =~ ~s/\W//g;
 4135:                 if (!($sec eq "")) {
 4136:                     if (exists($$sections{$sec})) {
 4137:                         $$sections{$sec} ++;
 4138:                     } else {
 4139:                         $$sections{$sec} = 1;
 4140:                         $num_sections ++;
 4141:                     }
 4142:                 }
 4143:             }
 4144:         }
 4145:     } else {
 4146:         $sectionstr=~s/\W//g;
 4147:         unless ($sectionstr eq '') {
 4148:             $$sections{$sectionstr} = 1;
 4149:             $num_sections ++;
 4150:         }
 4151:     }
 4152: 
 4153:     return $num_sections;
 4154: }
 4155: 
 4156: # ========================================================== Custom Role Editor
 4157: 
 4158: sub custom_role_editor {
 4159:     my ($r,$brcrum) = @_;
 4160:     my $action = $env{'form.customroleaction'};
 4161:     my $rolename; 
 4162:     if ($action eq 'new') {
 4163:         $rolename=$env{'form.newrolename'};
 4164:     } else {
 4165:         $rolename=$env{'form.rolename'};
 4166:     }
 4167: 
 4168:     my ($crstype,$context);
 4169:     if ($env{'request.course.id'}) {
 4170:         $crstype = &Apache::loncommon::course_type();
 4171:         $context = 'course';
 4172:     } else {
 4173:         $context = 'domain';
 4174:         $crstype = $env{'form.templatecrstype'};
 4175:     }
 4176: 
 4177:     $rolename=~s/[^A-Za-z0-9]//gs;
 4178:     if (!$rolename || $env{'form.phase'} eq 'pickrole') {
 4179: 	&print_username_entry_form($r,undef,undef,undef,undef,$crstype,$brcrum);
 4180:         return;
 4181:     }
 4182: 
 4183: # ------------------------------------------------------- What can be assigned?
 4184:     my %full=();
 4185:     my %courselevel=();
 4186:     my %courselevelcurrent=();
 4187:     my $syspriv='';
 4188:     my $dompriv='';
 4189:     my $coursepriv='';
 4190:     my $body_top;
 4191:     my $newrole;
 4192:     my ($rdummy,$roledef)=
 4193: 			 &Apache::lonnet::get('roles',["rolesdef_$rolename"]);
 4194: # ------------------------------------------------------- Does this role exist?
 4195:     $body_top .= '<h2>';
 4196:     if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 4197: 	$body_top .= &mt('Existing Role').' "';
 4198: # ------------------------------------------------- Get current role privileges
 4199: 	($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 4200:         if ($crstype eq 'Community') {
 4201:             $syspriv =~ s/bre\&S//;   
 4202:         }
 4203:     } else {
 4204:         $newrole = 1;
 4205: 	$body_top .= &mt('New Role').' "';
 4206: 	$roledef='';
 4207:     }
 4208:     $body_top .= $rolename.'"</h2>';
 4209:     foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
 4210: 	my ($priv,$restrict)=split(/\&/,$item);
 4211:         if (!$restrict) { $restrict='F'; }
 4212:         $courselevel{$priv}=$restrict;
 4213:         if ($coursepriv=~/\:$priv/) {
 4214: 	    $courselevelcurrent{$priv}=1;
 4215: 	}
 4216: 	$full{$priv}=1;
 4217:     }
 4218:     my %domainlevel=();
 4219:     my %domainlevelcurrent=();
 4220:     foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:d'})) {
 4221: 	my ($priv,$restrict)=split(/\&/,$item);
 4222:         if (!$restrict) { $restrict='F'; }
 4223:         $domainlevel{$priv}=$restrict;
 4224:         if ($dompriv=~/\:$priv/) {
 4225: 	    $domainlevelcurrent{$priv}=1;
 4226: 	}
 4227: 	$full{$priv}=1;
 4228:     }
 4229:     my %systemlevel=();
 4230:     my %systemlevelcurrent=();
 4231:     foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:s'})) {
 4232: 	my ($priv,$restrict)=split(/\&/,$item);
 4233:         if (!$restrict) { $restrict='F'; }
 4234:         $systemlevel{$priv}=$restrict;
 4235:         if ($syspriv=~/\:$priv/) {
 4236: 	    $systemlevelcurrent{$priv}=1;
 4237: 	}
 4238: 	$full{$priv}=1;
 4239:     }
 4240:     my ($jsback,$elements) = &crumb_utilities();
 4241:     my $button_code = "\n";
 4242:     my $head_script = "\n";
 4243:     $head_script .= '<script type="text/javascript">'."\n"
 4244:                    .'// <![CDATA['."\n";
 4245:     my @template_roles = ("in","ta","ep");
 4246:     if ($context eq 'domain') {
 4247:         push(@template_roles,"ad");
 4248:     }
 4249:     push(@template_roles,"st");
 4250:     if ($crstype eq 'Community') {
 4251:         unshift(@template_roles,'co');
 4252:     } else {
 4253:         unshift(@template_roles,'cc');
 4254:     }
 4255:     foreach my $role (@template_roles) {
 4256:         $head_script .= &make_script_template($role,$crstype);
 4257:         $button_code .= &make_button_code($role,$crstype).' ';
 4258:     }
 4259:     my $context_code;
 4260:     if ($context eq 'domain') {
 4261:         my $checkedCommunity = '';
 4262:         my $checkedCourse = ' checked="checked"';
 4263:         if ($env{'form.templatecrstype'} eq 'Community') {
 4264:             $checkedCommunity = $checkedCourse;
 4265:             $checkedCourse = '';
 4266:         }
 4267:         $context_code = '<label>'.
 4268:                         '<input type="radio" name="templatecrstype" value="Course"'.$checkedCourse.' onclick="this.form.submit();">'.
 4269:                         &mt('Course').
 4270:                         '</label>'.('&nbsp;' x2).
 4271:                         '<label>'.
 4272:                         '<input type="radio" name="templatecrstype" value="Community"'.$checkedCommunity.' onclick="this.form.submit();">'.
 4273:                         &mt('Community').
 4274:                         '</label>'.
 4275:                         '</fieldset>'.
 4276:                         '<input type="hidden" name="customroleaction" value="'.
 4277:                         $action.'" />';
 4278:         if ($env{'form.customroleaction'} eq 'new') {
 4279:             $context_code .= '<input type="hidden" name="newrolename" value="'.
 4280:                              $rolename.'" />';
 4281:         } else {
 4282:             $context_code .= '<input type="hidden" name="rolename" value="'.
 4283:                              $rolename.'" />';
 4284:         }
 4285:         $context_code .= '<input type="hidden" name="action" value="custom" />'.
 4286:                          '<input type="hidden" name="phase" value="selected_custom_edit" />';
 4287:     }
 4288: 
 4289:     $head_script .= "\n".$jsback."\n"
 4290:                    .'// ]]>'."\n"
 4291:                    .'</script>'."\n";
 4292:     push (@{$brcrum},
 4293:               {href => "javascript:backPage(document.form1,'pickrole','')",
 4294:                text => "Pick custom role",
 4295:                faq  => 282,bug=>'Instructor Interface',},
 4296:               {href => "javascript:backPage(document.form1,'','')",
 4297:                text => "Edit custom role",
 4298:                faq  => 282,
 4299:                bug  => 'Instructor Interface',
 4300:                help => 'Course_Editing_Custom_Roles'}
 4301:               );
 4302:     my $args = { bread_crumbs          => $brcrum,
 4303:                  bread_crumbs_component => 'User Management'};
 4304:  
 4305:     $r->print(&Apache::loncommon::start_page('Custom Role Editor',
 4306:                                              $head_script,$args).
 4307:               $body_top);
 4308:     my %lt=&Apache::lonlocal::texthash(
 4309: 		    'prv'  => "Privilege",
 4310: 		    'crl'  => "Course Level",
 4311:                     'dml'  => "Domain Level",
 4312:                     'ssl'  => "System Level");
 4313: 
 4314:     $r->print('<div class="LC_left_float">'
 4315:              .'<form action=""><fieldset>'
 4316:              .'<legend>'.&mt('Select a Template').'</legend>'
 4317:              .$button_code
 4318:              .'</fieldset></form></div>');
 4319:     if ($context_code) {
 4320:         $r->print('<div class="LC_left_float">'
 4321:                  .'<form action="/adm/createuser" method="post"><fieldset>'
 4322:                  .'<legend>'.&mt('Context').'</legend>'
 4323:                  .$context_code
 4324:                  .'</form>'
 4325:                  .'</div>'
 4326:         );
 4327:     }
 4328:     $r->print('<br clear="all" />');
 4329: 
 4330:     $r->print(<<ENDCCF);
 4331: <form name="form1" method="post" action="">
 4332: <input type="hidden" name="phase" value="set_custom_roles" />
 4333: <input type="hidden" name="rolename" value="$rolename" />
 4334: ENDCCF
 4335:     $r->print(&Apache::loncommon::start_data_table().
 4336:               &Apache::loncommon::start_data_table_header_row(). 
 4337: '<th>'.$lt{'prv'}.'</th><th>'.$lt{'crl'}.'</th><th>'.$lt{'dml'}.
 4338: '</th><th>'.$lt{'ssl'}.'</th>'.
 4339:               &Apache::loncommon::end_data_table_header_row());
 4340:     foreach my $priv (sort(keys(%full))) {
 4341:         my $privtext = &Apache::lonnet::plaintext($priv,$crstype);
 4342:         $r->print(&Apache::loncommon::start_data_table_row().
 4343: 	          '<td>'.$privtext.'</td><td>'.
 4344:     ($courselevel{$priv}?'<input type="checkbox" name="'.$priv.'_c"'.
 4345:     ($courselevelcurrent{$priv}?' checked="checked"':'').' />':'&nbsp;').
 4346:     '</td><td>'.
 4347:     ($domainlevel{$priv}?'<input type="checkbox" name="'.$priv.'_d"'.
 4348:     ($domainlevelcurrent{$priv}?' checked="checked"':'').' />':'&nbsp;').
 4349:     '</td><td>');
 4350:         if ($priv eq 'bre' && $crstype eq 'Community') {
 4351:             $r->print('&nbsp;');  
 4352:         } else {
 4353:             $r->print($systemlevel{$priv}?'<input type="checkbox" name="'.$priv.'_s"'.
 4354:                       ($systemlevelcurrent{$priv}?' checked="checked"':'').' />':'&nbsp;');
 4355:         }
 4356:         $r->print('</td>'.
 4357:                   &Apache::loncommon::end_data_table_row());
 4358:     }
 4359:     $r->print(&Apache::loncommon::end_data_table().
 4360:    '<input type="hidden" name="action" value="'.$env{'form.action'}.'" />'.
 4361:    '<input type="hidden" name="startrolename" value="'.$env{'form.rolename'}.
 4362:    '" />'."\n".'<input type="hidden" name="currstate" value="" />'."\n".   
 4363:    '<input type="reset" value="'.&mt("Reset").'" />'."\n".
 4364:    '<input type="submit" value="'.&mt('Save').'" /></form>');
 4365: }
 4366: # --------------------------------------------------------
 4367: sub make_script_template {
 4368:     my ($role,$crstype) = @_;
 4369:     my %full_c=();
 4370:     my %full_d=();
 4371:     my %full_s=();
 4372:     my $return_script;
 4373:     foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
 4374:         my ($priv,$restrict)=split(/\&/,$item);
 4375:         $full_c{$priv}=1;
 4376:     }
 4377:     foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:d'})) {
 4378:         my ($priv,$restrict)=split(/\&/,$item);
 4379:         $full_d{$priv}=1;
 4380:     }
 4381:     foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:s'})) {
 4382:         next if (($crstype eq 'Community') && ($item eq 'bre&S'));
 4383:         my ($priv,$restrict)=split(/\&/,$item);
 4384:         $full_s{$priv}=1;
 4385:     }
 4386:     $return_script .= 'function set_'.$role.'() {'."\n";
 4387:     my @temp = split(/:/,$Apache::lonnet::pr{$role.':c'});
 4388:     my %role_c;
 4389:     foreach my $priv (@temp) {
 4390:         my ($priv_item, $dummy) = split(/\&/,$priv);
 4391:         $role_c{$priv_item} = 1;
 4392:     }
 4393:     my %role_d;
 4394:     @temp = split(/:/,$Apache::lonnet::pr{$role.':d'});
 4395:     foreach my $priv(@temp) {
 4396:         my ($priv_item, $dummy) = split(/\&/,$priv);
 4397:         $role_d{$priv_item} = 1;
 4398:     }
 4399:     my %role_s;
 4400:     @temp = split(/:/,$Apache::lonnet::pr{$role.':s'});
 4401:     foreach my $priv(@temp) {
 4402:         my ($priv_item, $dummy) = split(/\&/,$priv);
 4403:         $role_s{$priv_item} = 1;
 4404:     }
 4405:     foreach my $priv_item (keys(%full_c)) {
 4406:         my ($priv, $dummy) = split(/\&/,$priv_item);
 4407:         if ((exists($role_c{$priv})) || (exists($role_d{$priv})) || 
 4408:             (exists($role_s{$priv}))) {
 4409:             $return_script .= "document.form1.$priv"."_c.checked = true;\n";
 4410:         } else {
 4411:             $return_script .= "document.form1.$priv"."_c.checked = false;\n";
 4412:         }
 4413:     }
 4414:     foreach my $priv_item (keys(%full_d)) {
 4415:         my ($priv, $dummy) = split(/\&/,$priv_item);
 4416:         if ((exists($role_d{$priv})) || (exists($role_s{$priv}))) {
 4417:             $return_script .= "document.form1.$priv"."_d.checked = true;\n";
 4418:         } else {
 4419:             $return_script .= "document.form1.$priv"."_d.checked = false;\n";
 4420:         }
 4421:     }
 4422:     foreach my $priv_item (keys(%full_s)) {
 4423:         my ($priv, $dummy) = split(/\&/,$priv_item);
 4424:         if (exists($role_s{$priv})) {
 4425:             $return_script .= "document.form1.$priv"."_s.checked = true;\n";
 4426:         } else {
 4427:             $return_script .= "document.form1.$priv"."_s.checked = false;\n";
 4428:         }
 4429:     }
 4430:     $return_script .= '}'."\n";
 4431:     return ($return_script);
 4432: }
 4433: # ----------------------------------------------------------
 4434: sub make_button_code {
 4435:     my ($role,$crstype) = @_;
 4436:     my $label = &Apache::lonnet::plaintext($role,$crstype);
 4437:     my $button_code = '<input type="button" onclick="set_'.$role.'()" value="'.$label.'" />';
 4438:     return ($button_code);
 4439: }
 4440: # ---------------------------------------------------------- Call to definerole
 4441: sub set_custom_role {
 4442:     my ($r,$context,$brcrum) = @_;
 4443:     my $rolename=$env{'form.rolename'};
 4444:     $rolename=~s/[^A-Za-z0-9]//gs;
 4445:     if (!$rolename) {
 4446: 	&custom_role_editor($r,$brcrum);
 4447:         return;
 4448:     }
 4449:     my ($jsback,$elements) = &crumb_utilities();
 4450:     my $jscript = '<script type="text/javascript">'
 4451:                  .'// <![CDATA['."\n"
 4452:                  .$jsback."\n"
 4453:                  .'// ]]>'."\n"
 4454:                  .'</script>'."\n";
 4455:     push(@{$brcrum},
 4456:         {href => "javascript:backPage(document.customresult,'pickrole','')",
 4457:          text => "Pick custom role",
 4458:          faq  => 282,
 4459:          bug  => 'Instructor Interface',},
 4460:         {href => "javascript:backPage(document.customresult,'selected_custom_edit','')",
 4461:          text => "Edit custom role",
 4462:          faq  => 282,
 4463:          bug  => 'Instructor Interface',},
 4464:         {href => "javascript:backPage(document.customresult,'set_custom_roles','')",
 4465:          text => "Result",
 4466:          faq  => 282,
 4467:          bug  => 'Instructor Interface',
 4468:          help => 'Course_Editing_Custom_Roles'},
 4469:         );
 4470:     my $args = { bread_crumbs           => $brcrum,
 4471:                  bread_crumbs_component => 'User Management'}; 
 4472:     $r->print(&Apache::loncommon::start_page('Save Custom Role',$jscript,$args));
 4473: 
 4474:     my $newrole;
 4475:     my ($rdummy,$roledef)=
 4476: 	&Apache::lonnet::get('roles',["rolesdef_$rolename"]);
 4477: 
 4478: # ------------------------------------------------------- Does this role exist?
 4479:     $r->print('<h3>');
 4480:     if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 4481: 	$r->print(&mt('Existing Role').' "');
 4482:     } else {
 4483: 	$r->print(&mt('New Role').' "');
 4484: 	$roledef='';
 4485:         $newrole = 1;
 4486:     }
 4487:     $r->print($rolename.'"</h3>');
 4488: # ------------------------------------------------------- What can be assigned?
 4489:     my $sysrole='';
 4490:     my $domrole='';
 4491:     my $courole='';
 4492: 
 4493:     foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
 4494: 	my ($priv,$restrict)=split(/\&/,$item);
 4495:         if (!$restrict) { $restrict=''; }
 4496:         if ($env{'form.'.$priv.'_c'}) {
 4497: 	    $courole.=':'.$item;
 4498: 	}
 4499:     }
 4500: 
 4501:     foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:d'})) {
 4502: 	my ($priv,$restrict)=split(/\&/,$item);
 4503:         if (!$restrict) { $restrict=''; }
 4504:         if ($env{'form.'.$priv.'_d'}) {
 4505: 	    $domrole.=':'.$item;
 4506: 	}
 4507:     }
 4508: 
 4509:     foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:s'})) {
 4510: 	my ($priv,$restrict)=split(/\&/,$item);
 4511:         if (!$restrict) { $restrict=''; }
 4512:         if ($env{'form.'.$priv.'_s'}) {
 4513: 	    $sysrole.=':'.$item;
 4514: 	}
 4515:     }
 4516:     # Assign role; Compile and show result
 4517:     my $errmsg;
 4518:     my $result =
 4519:         &Apache::lonnet::definerole($rolename,$sysrole,$domrole,$courole);
 4520:     if ($result ne 'ok') {
 4521:         $errmsg = ': '.$result;
 4522:     }
 4523:     my $message =
 4524:         &Apache::lonhtmlcommon::confirm_success(
 4525:             &mt('Defining Role').$errmsg, ($result eq 'ok' ? 0 : 1));
 4526:     if ($env{'request.course.id'}) {
 4527:         my $url='/'.$env{'request.course.id'};
 4528:         $url=~s/\_/\//g;
 4529:         $result =
 4530:             &Apache::lonnet::assigncustomrole(
 4531:                 $env{'user.domain'},$env{'user.name'},
 4532:                 $url,
 4533:                 $env{'user.domain'},$env{'user.name'},
 4534:                 $rolename,undef,undef,undef,$context);
 4535:         if ($result ne 'ok') {
 4536:             $errmsg = ': '.$result;
 4537:         }
 4538:         $message .=
 4539:             '<br />'
 4540:            .&Apache::lonhtmlcommon::confirm_success(
 4541:                 &mt('Assigning Role to Self').$errmsg, ($result eq 'ok' ? 0 : 1));
 4542:     }
 4543:     $r->print(
 4544:         &Apache::loncommon::confirmwrapper($message)
 4545:        .'<br />'
 4546:        .&Apache::lonhtmlcommon::actionbox([
 4547:             '<a href="javascript:backPage(document.customresult,'."'pickrole'".')">'
 4548:            .&mt('Create or edit another custom role')
 4549:            .'</a>'])
 4550:        .'<form name="customresult" method="post" action="">'
 4551:        .&Apache::lonhtmlcommon::echo_form_input([])
 4552:        .'</form>'
 4553:     );
 4554: }
 4555: 
 4556: # ================================================================ Main Handler
 4557: sub handler {
 4558:     my $r = shift;
 4559:     if ($r->header_only) {
 4560:        &Apache::loncommon::content_type($r,'text/html');
 4561:        $r->send_http_header;
 4562:        return OK;
 4563:     }
 4564:     my ($context,$crstype);
 4565:     if ($env{'request.course.id'}) {
 4566:         $context = 'course';
 4567:         $crstype = &Apache::loncommon::course_type();
 4568:     } elsif ($env{'request.role'} =~ /^au\./) {
 4569:         $context = 'author';
 4570:     } else {
 4571:         $context = 'domain';
 4572:     }
 4573: 
 4574:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 4575:         ['action','state','callingform','roletype','showrole','bulkaction','popup','phase',
 4576:          'username','domain','srchterm','srchdomain','srchin','srchby','srchtype','queue']);
 4577:     &Apache::lonhtmlcommon::clear_breadcrumbs();
 4578:     my $args;
 4579:     my $brcrum = [];
 4580:     my $bread_crumbs_component = 'User Management';
 4581:     if (($env{'form.action'} ne 'dateselect') && ($env{'form.action'} ne 'displayuserreq')) {
 4582:         $brcrum = [{href=>"/adm/createuser",
 4583:                     text=>"User Management",
 4584:                     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'}
 4585:                   ];
 4586:     }
 4587:     #SD Following files not added to help, because the corresponding .tex-files seem to
 4588:     #be missing: Course_Approve_Selfenroll,Course_User_Logs,
 4589:     my ($permission,$allowed) = 
 4590:         &Apache::lonuserutils::get_permission($context,$crstype);
 4591:     if (!$allowed) {
 4592:         if ($context eq 'course') {
 4593:             $r->internal_redirect('/adm/viewclasslist');
 4594:             return OK;
 4595:         }
 4596:         $env{'user.error.msg'}=
 4597:             "/adm/createuser:cst:0:0:Cannot create/modify user data ".
 4598:                                  "or view user status.";
 4599:         return HTTP_NOT_ACCEPTABLE;
 4600:     }
 4601: 
 4602:     &Apache::loncommon::content_type($r,'text/html');
 4603:     $r->send_http_header;
 4604: 
 4605:     my $showcredits;
 4606:     if ((($context eq 'course') && ($crstype eq 'Course')) || 
 4607:          ($context eq 'domain')) {
 4608:         my %domdefaults = 
 4609:             &Apache::lonnet::get_domain_defaults($env{'request.role.domain'});
 4610:         if ($domdefaults{'officialcredits'} || $domdefaults{'unofficialcredits'}) {
 4611:             $showcredits = 1;
 4612:         }
 4613:     }
 4614: 
 4615:     # Main switch on form.action and form.state, as appropriate
 4616:     if (! exists($env{'form.action'})) {
 4617:         $args = {bread_crumbs => $brcrum,
 4618:                  bread_crumbs_component => $bread_crumbs_component}; 
 4619:         $r->print(&header(undef,$args));
 4620:         $r->print(&print_main_menu($permission,$context,$crstype));
 4621:     } elsif ($env{'form.action'} eq 'upload' && $permission->{'cusr'}) {
 4622:         push(@{$brcrum},
 4623:               { href => '/adm/createuser?action=upload&state=',
 4624:                 text => 'Upload Users List',
 4625:                 help => 'Course_Create_Class_List',
 4626:               });
 4627:         $bread_crumbs_component = 'Upload Users List';
 4628:         $args = {bread_crumbs           => $brcrum,
 4629:                  bread_crumbs_component => $bread_crumbs_component};
 4630:         $r->print(&header(undef,$args));
 4631:         $r->print('<form name="studentform" method="post" '.
 4632:                   'enctype="multipart/form-data" '.
 4633:                   ' action="/adm/createuser">'."\n");
 4634:         if (! exists($env{'form.state'})) {
 4635:             &Apache::lonuserutils::print_first_users_upload_form($r,$context);
 4636:         } elsif ($env{'form.state'} eq 'got_file') {
 4637:             &Apache::lonuserutils::print_upload_manager_form($r,$context,$permission,
 4638:                                                              $crstype,$showcredits);
 4639:         } elsif ($env{'form.state'} eq 'enrolling') {
 4640:             if ($env{'form.datatoken'}) {
 4641:                 &Apache::lonuserutils::upfile_drop_add($r,$context,$permission,
 4642:                                                        $showcredits);
 4643:             }
 4644:         } else {
 4645:             &Apache::lonuserutils::print_first_users_upload_form($r,$context);
 4646:         }
 4647:     } elsif ((($env{'form.action'} eq 'singleuser') || ($env{'form.action'}
 4648:              eq 'singlestudent')) && ($permission->{'cusr'})) {
 4649:         my $phase = $env{'form.phase'};
 4650:         my @search = ('srchterm','srchby','srchin','srchtype','srchdomain');
 4651: 	&Apache::loncreateuser::restore_prev_selections();
 4652: 	my $srch;
 4653: 	foreach my $item (@search) {
 4654: 	    $srch->{$item} = $env{'form.'.$item};
 4655: 	}
 4656:         if (($phase eq 'get_user_info') || ($phase eq 'userpicked') ||
 4657:             ($phase eq 'createnewuser')) {
 4658:             if ($env{'form.phase'} eq 'createnewuser') {
 4659:                 my $response;
 4660:                 if ($env{'form.srchterm'} !~ /^$match_username$/) {
 4661:                     my $response =
 4662:                         '<span class="LC_warning">'
 4663:                        .&mt('You must specify a valid username. Only the following are allowed:'
 4664:                            .' letters numbers - . @')
 4665:                        .'</span>';
 4666:                     $env{'form.phase'} = '';
 4667:                     &print_username_entry_form($r,$context,$response,$srch,undef,
 4668:                                                $crstype,$brcrum,$showcredits);
 4669:                 } else {
 4670:                     my $ccuname =&LONCAPA::clean_username($srch->{'srchterm'});
 4671:                     my $ccdomain=&LONCAPA::clean_domain($srch->{'srchdomain'});
 4672:                     &print_user_modification_page($r,$ccuname,$ccdomain,
 4673:                                                   $srch,$response,$context,
 4674:                                                   $permission,$crstype,$brcrum,
 4675:                                                   $showcredits);
 4676:                 }
 4677:             } elsif ($env{'form.phase'} eq 'get_user_info') {
 4678:                 my ($currstate,$response,$forcenewuser,$results) = 
 4679:                     &user_search_result($context,$srch);
 4680:                 if ($env{'form.currstate'} eq 'modify') {
 4681:                     $currstate = $env{'form.currstate'};
 4682:                 }
 4683:                 if ($currstate eq 'select') {
 4684:                     &print_user_selection_page($r,$response,$srch,$results,
 4685:                                                \@search,$context,undef,$crstype,
 4686:                                                $brcrum);
 4687:                 } elsif ($currstate eq 'modify') {
 4688:                     my ($ccuname,$ccdomain);
 4689:                     if (($srch->{'srchby'} eq 'uname') && 
 4690:                         ($srch->{'srchtype'} eq 'exact')) {
 4691:                         $ccuname = $srch->{'srchterm'};
 4692:                         $ccdomain= $srch->{'srchdomain'};
 4693:                     } else {
 4694:                         my @matchedunames = keys(%{$results});
 4695:                         ($ccuname,$ccdomain) = split(/:/,$matchedunames[0]);
 4696:                     }
 4697:                     $ccuname =&LONCAPA::clean_username($ccuname);
 4698:                     $ccdomain=&LONCAPA::clean_domain($ccdomain);
 4699:                     if ($env{'form.forcenewuser'}) {
 4700:                         $response = '';
 4701:                     }
 4702:                     &print_user_modification_page($r,$ccuname,$ccdomain,
 4703:                                                   $srch,$response,$context,
 4704:                                                   $permission,$crstype,$brcrum);
 4705:                 } elsif ($currstate eq 'query') {
 4706:                     &print_user_query_page($r,'createuser',$brcrum);
 4707:                 } else {
 4708:                     $env{'form.phase'} = '';
 4709:                     &print_username_entry_form($r,$context,$response,$srch,
 4710:                                                $forcenewuser,$crstype,$brcrum);
 4711:                 }
 4712:             } elsif ($env{'form.phase'} eq 'userpicked') {
 4713:                 my $ccuname = &LONCAPA::clean_username($env{'form.seluname'});
 4714:                 my $ccdomain = &LONCAPA::clean_domain($env{'form.seludom'});
 4715:                 &print_user_modification_page($r,$ccuname,$ccdomain,$srch,'',
 4716:                                               $context,$permission,$crstype,
 4717:                                               $brcrum);
 4718:             }
 4719:         } elsif ($env{'form.phase'} eq 'update_user_data') {
 4720:             &update_user_data($r,$context,$crstype,$brcrum,$showcredits);
 4721:         } else {
 4722:             &print_username_entry_form($r,$context,undef,$srch,undef,$crstype,
 4723:                                        $brcrum);
 4724:         }
 4725:     } elsif ($env{'form.action'} eq 'custom' && $permission->{'custom'}) {
 4726:         if ($env{'form.phase'} eq 'set_custom_roles') {
 4727:             &set_custom_role($r,$context,$brcrum);
 4728:         } else {
 4729:             &custom_role_editor($r,$brcrum);
 4730:         }
 4731:     } elsif (($env{'form.action'} eq 'processauthorreq') &&
 4732:              ($permission->{'cusr'}) && 
 4733:              (&Apache::lonnet::allowed('cau',$env{'request.role.domain'}))) {
 4734:         push(@{$brcrum},
 4735:                  {href => '/adm/createuser?action=processauthorreq',
 4736:                   text => 'Authoring Space requests',
 4737:                   help => 'Domain_Role_Approvals'});
 4738:         $bread_crumbs_component = 'Authoring requests';
 4739:         if ($env{'form.state'} eq 'done') {
 4740:             push(@{$brcrum},
 4741:                      {href => '/adm/createuser?action=authorreqqueue',
 4742:                       text => 'Result',
 4743:                       help => 'Domain_Role_Approvals'});
 4744:             $bread_crumbs_component = 'Authoring request result';
 4745:         }
 4746:         $args = { bread_crumbs           => $brcrum,
 4747:                   bread_crumbs_component => $bread_crumbs_component};
 4748:         my $js = &usernamerequest_javascript();
 4749:         $r->print(&header(&add_script($js),$args));
 4750:         if (!exists($env{'form.state'})) {
 4751:             $r->print(&Apache::loncoursequeueadmin::display_queued_requests('requestauthor',
 4752:                                                                             $env{'request.role.domain'}));
 4753:         } elsif ($env{'form.state'} eq 'done') {
 4754:             $r->print('<h3>'.&mt('Authoring request processing').'</h3>'."\n");
 4755:             $r->print(&Apache::loncoursequeueadmin::update_request_queue('requestauthor',
 4756:                                                                          $env{'request.role.domain'}));
 4757:         }
 4758:     } elsif (($env{'form.action'} eq 'processusernamereq') &&
 4759:              ($permission->{'cusr'}) &&
 4760:              (&Apache::lonnet::allowed('cau',$env{'request.role.domain'}))) {
 4761:         push(@{$brcrum},
 4762:                  {href => '/adm/createuser?action=processusernamereq',
 4763:                   text => 'LON-CAPA account requests',
 4764:                   help => 'Domain_Username_Approvals'});
 4765:         $bread_crumbs_component = 'Account requests';
 4766:         if ($env{'form.state'} eq 'done') {
 4767:             push(@{$brcrum},
 4768:                      {href => '/adm/createuser?action=usernamereqqueue',
 4769:                       text => 'Result',
 4770:                       help => 'Domain_Username_Approvals'});
 4771:             $bread_crumbs_component = 'LON-CAPA account request result';
 4772:         }
 4773:         $args = { bread_crumbs           => $brcrum,
 4774:                   bread_crumbs_component => $bread_crumbs_component};
 4775:         my $js = &usernamerequest_javascript();
 4776:         $r->print(&header(&add_script($js),$args));
 4777:         if (!exists($env{'form.state'})) {
 4778:             $r->print(&Apache::loncoursequeueadmin::display_queued_requests('requestusername',
 4779:                                                                             $env{'request.role.domain'}));
 4780:         } elsif ($env{'form.state'} eq 'done') {
 4781:             $r->print('<h3>'.&mt('LON-CAPA account request processing').'</h3>'."\n");
 4782:             $r->print(&Apache::loncoursequeueadmin::update_request_queue('requestusername',
 4783:                                                                          $env{'request.role.domain'}));
 4784:         }
 4785:     } elsif (($env{'form.action'} eq 'displayuserreq') &&
 4786:              ($permission->{'cusr'})) {
 4787:         my $dom = $env{'form.domain'};
 4788:         my $uname = $env{'form.username'};
 4789:         my $warning;
 4790:         if (($dom =~ /^$match_domain$/) && (&Apache::lonnet::domain($dom) ne '')) {
 4791:             if (($dom eq $env{'request.role.domain'}) && (&Apache::lonnet::allowed('ccc',$dom))) {
 4792:                 if (($uname =~ /^$match_username$/) && ($env{'form.queue'} eq 'approval')) {
 4793:                     my $uhome = &Apache::lonnet::homeserver($uname,$dom);
 4794:                     if ($uhome eq 'no_host') {
 4795:                         my $queue = $env{'form.queue'};
 4796:                         my $reqkey = &escape($uname).'_'.$queue; 
 4797:                         my $namespace = 'usernamequeue';
 4798:                         my $domconfig = &Apache::lonnet::get_domainconfiguser($dom);
 4799:                         my %queued =
 4800:                             &Apache::lonnet::get($namespace,[$reqkey],$dom,$domconfig);
 4801:                         unless ($queued{$reqkey}) {
 4802:                             $warning = &mt('No information was found for this LON-CAPA account request.');
 4803:                         }
 4804:                     } else {
 4805:                         $warning = &mt('A LON-CAPA account already exists for the requested username and domain.');
 4806:                     }
 4807:                 } else {
 4808:                     $warning = &mt('LON-CAPA account request status check is for an invalid username.');
 4809:                 }
 4810:             } else {
 4811:                 $warning = &mt('You do not have rights to view LON-CAPA account requests in the domain specified.');
 4812:             }
 4813:         } else {
 4814:             $warning = &mt('LON-CAPA account request status check is for an invalid domain.');
 4815:         }
 4816:         my $args = { only_body => 1 };
 4817:         $r->print(&header(undef,$args).
 4818:                   '<h3>'.&mt('LON-CAPA Account Request Details').'</h3>');
 4819:         if ($warning ne '') {
 4820:             $r->print('<div class="LC_warning">'.$warning.'</div>');
 4821:         } else {
 4822:             my ($infofields,$infotitles) = &Apache::loncommon::emailusername_info();
 4823:             my $domconfiguser = &Apache::lonnet::get_domainconfiguser($dom);
 4824:             my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 4825:             if (ref($domconfig{'usercreation'}) eq 'HASH') {
 4826:                 if (ref($domconfig{'usercreation'}{'cancreate'}) eq 'HASH') {
 4827:                     if (ref($domconfig{'usercreation'}{'cancreate'}{'emailusername'}) eq 'HASH') {
 4828:                         my %info =
 4829:                             &Apache::lonnet::get('nohist_requestedusernames',[$uname],$dom,$domconfiguser);
 4830:                         if (ref($info{$uname}) eq 'HASH') {
 4831:                             my $usertype = $info{$uname}{'inststatus'};
 4832:                             unless ($usertype) {
 4833:                                 $usertype = 'default';
 4834:                             }
 4835:                             if (ref($domconfig{'usercreation'}{'cancreate'}{'emailusername'}{$usertype}) eq 'HASH') {
 4836:                                 if ((ref($infofields) eq 'ARRAY') && (ref($infotitles) eq 'HASH')) {
 4837:                                     $r->print('<div>'.&Apache::lonhtmlcommon::start_pick_box());
 4838:                                     my ($num,$count,$showstatus);
 4839:                                     $count = scalar(keys(%{$domconfig{'usercreation'}{'cancreate'}{'emailusername'}{$usertype}}));
 4840:                                     unless ($usertype eq 'default') {
 4841:                                         my ($othertitle,$usertypes,$types) = 
 4842:                                             &Apache::loncommon::sorted_inst_types($dom);
 4843:                                         if (ref($usertypes) eq 'HASH') {
 4844:                                             if ($usertypes->{$usertype}) {
 4845:                                                 $showstatus = $usertypes->{$usertype};
 4846:                                                 $count ++;
 4847:                                             }
 4848:                                         }
 4849:                                     }
 4850:                                     foreach my $field (@{$infofields}) {
 4851:                                         next unless ($domconfig{'usercreation'}{'cancreate'}{'emailusername'}{$usertype}{$field});
 4852:                                         next unless ($infotitles->{$field});
 4853:                                         $r->print(&Apache::lonhtmlcommon::row_title($infotitles->{$field}).
 4854:                                                   $info{$uname}{$field});
 4855:                                         $num ++;
 4856:                                         if ($count == $num) {
 4857:                                             $r->print(&Apache::lonhtmlcommon::row_closure(1));
 4858:                                         } else {
 4859:                                             $r->print(&Apache::lonhtmlcommon::row_closure());
 4860:                                         }
 4861:                                     }
 4862:                                     if ($showstatus) {
 4863:                                         $r->print(&Apache::lonhtmlcommon::row_title(&mt('Status type (self-reported)')).
 4864:                                                   $showstatus.
 4865:                                                   &Apache::lonhtmlcommon::row_closure(1));
 4866:                                     }
 4867:                                     $r->print(&Apache::lonhtmlcommon::end_pick_box().'</div>');
 4868:                                 }
 4869:                             }
 4870:                         }
 4871:                     }
 4872:                 }
 4873:             }
 4874:             $r->print(&close_popup_form());
 4875:         }
 4876:     } elsif (($env{'form.action'} eq 'listusers') && 
 4877:              ($permission->{'view'} || $permission->{'cusr'})) {
 4878:         if ($env{'form.phase'} eq 'bulkchange') {
 4879:             push(@{$brcrum},
 4880:                     {href => '/adm/createuser?action=listusers',
 4881:                      text => "List Users"},
 4882:                     {href => "/adm/createuser",
 4883:                      text => "Result",
 4884:                      help => 'Course_View_Class_List'});
 4885:             $bread_crumbs_component = 'Update Users';
 4886:             $args = {bread_crumbs           => $brcrum,
 4887:                      bread_crumbs_component => $bread_crumbs_component};
 4888:             $r->print(&header(undef,$args));
 4889:             my $setting = $env{'form.roletype'};
 4890:             my $choice = $env{'form.bulkaction'};
 4891:             if ($permission->{'cusr'}) {
 4892:                 &Apache::lonuserutils::update_user_list($r,$context,$setting,$choice,$crstype);
 4893:             } else {
 4894:                 $r->print(&mt('You are not authorized to make bulk changes to user roles'));
 4895:                 $r->print('<p><a href="/adm/createuser?action=listusers">'.&mt('Display User Lists').'</a>');
 4896:             }
 4897:         } else {
 4898:             push(@{$brcrum},
 4899:                     {href => '/adm/createuser?action=listusers',
 4900:                      text => "List Users",
 4901:                      help => 'Course_View_Class_List'});
 4902:             $bread_crumbs_component = 'List Users';
 4903:             $args = {bread_crumbs           => $brcrum,
 4904:                      bread_crumbs_component => $bread_crumbs_component};
 4905:             my ($cb_jscript,$jscript,$totcodes,$codetitles,$idlist,$idlist_titles);
 4906:             my $formname = 'studentform';
 4907:             my $hidecall = "hide_searching();";
 4908:             if (($context eq 'domain') && (($env{'form.roletype'} eq 'course') ||
 4909:                 ($env{'form.roletype'} eq 'community'))) {
 4910:                 if ($env{'form.roletype'} eq 'course') {
 4911:                     ($cb_jscript,$jscript,$totcodes,$codetitles,$idlist,$idlist_titles) = 
 4912:                         &Apache::lonuserutils::courses_selector($env{'request.role.domain'},
 4913:                                                                 $formname);
 4914:                 } elsif ($env{'form.roletype'} eq 'community') {
 4915:                     $cb_jscript = 
 4916:                         &Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'});
 4917:                     my %elements = (
 4918:                                       coursepick => 'radio',
 4919:                                       coursetotal => 'text',
 4920:                                       courselist => 'text',
 4921:                                    );
 4922:                     $jscript = &Apache::lonhtmlcommon::set_form_elements(\%elements);
 4923:                 }
 4924:                 $jscript .= &verify_user_display($context)."\n".
 4925:                             &Apache::loncommon::check_uncheck_jscript();
 4926:                 my $js = &add_script($jscript).$cb_jscript;
 4927:                 my $loadcode = 
 4928:                     &Apache::lonuserutils::course_selector_loadcode($formname);
 4929:                 if ($loadcode ne '') {
 4930:                     $args->{add_entries} = {onload => "$loadcode;$hidecall"};
 4931:                 } else {
 4932:                     $args->{add_entries} = {onload => $hidecall};
 4933:                 }
 4934:                 $r->print(&header($js,$args));
 4935:             } else {
 4936:                 $args->{add_entries} = {onload => $hidecall};
 4937:                 $jscript = &verify_user_display($context).
 4938:                            &Apache::loncommon::check_uncheck_jscript(); 
 4939:                 $r->print(&header(&add_script($jscript),$args));
 4940:             }
 4941:             &Apache::lonuserutils::print_userlist($r,undef,$permission,$context,
 4942:                          $formname,$totcodes,$codetitles,$idlist,$idlist_titles,
 4943:                          $showcredits);
 4944:         }
 4945:     } elsif ($env{'form.action'} eq 'drop' && $permission->{'cusr'}) {
 4946:         my $brtext;
 4947:         if ($crstype eq 'Community') {
 4948:             $brtext = 'Drop Members';
 4949:         } else {
 4950:             $brtext = 'Drop Students';
 4951:         }
 4952:         push(@{$brcrum},
 4953:                 {href => '/adm/createuser?action=drop',
 4954:                  text => $brtext,
 4955:                  help => 'Course_Drop_Student'});
 4956:         if ($env{'form.state'} eq 'done') {
 4957:             push(@{$brcrum},
 4958:                      {href=>'/adm/createuser?action=drop',
 4959:                       text=>"Result"});
 4960:         }
 4961:         $bread_crumbs_component = $brtext;
 4962:         $args = {bread_crumbs           => $brcrum,
 4963:                  bread_crumbs_component => $bread_crumbs_component}; 
 4964:         $r->print(&header(undef,$args));
 4965:         if (!exists($env{'form.state'})) {
 4966:             &Apache::lonuserutils::print_drop_menu($r,$context,$permission,$crstype);
 4967:         } elsif ($env{'form.state'} eq 'done') {
 4968:             &Apache::lonuserutils::update_user_list($r,$context,undef,
 4969:                                                     $env{'form.action'});
 4970:         }
 4971:     } elsif ($env{'form.action'} eq 'dateselect') {
 4972:         if ($permission->{'cusr'}) {
 4973:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 4974:                       &Apache::lonuserutils::date_section_selector($context,$permission,
 4975:                                                                    $crstype,$showcredits));
 4976:         } else {
 4977:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 4978:                      '<span class="LC_error">'.&mt('You do not have permission to modify dates or sections for users').'</span>'); 
 4979:         }
 4980:     } elsif ($env{'form.action'} eq 'selfenroll') {
 4981:         if ($permission->{selfenrolladmin}) {
 4982:             my $cid = $env{'request.course.id'};
 4983:             my $cdom = $env{'course.'.$cid.'.domain'};
 4984:             my $cnum = $env{'course.'.$cid.'.num'};
 4985:             my %currsettings = (
 4986:                 selfenroll_types              => $env{'course.'.$cid.'.internal.selfenroll_types'},
 4987:                 selfenroll_registered         => $env{'course.'.$cid.'.internal.selfenroll_registered'},
 4988:                 selfenroll_section            => $env{'course.'.$cid.'.internal.selfenroll_section'},
 4989:                 selfenroll_notifylist         => $env{'course.'.$cid.'.internal.selfenroll_notifylist'},
 4990:                 selfenroll_approval           => $env{'course.'.$cid.'.internal.selfenroll_approval'},
 4991:                 selfenroll_limit              => $env{'course.'.$cid.'.internal.selfenroll_limit'},
 4992:                 selfenroll_cap                => $env{'course.'.$cid.'.internal.selfenroll_cap'},
 4993:                 selfenroll_start_date         => $env{'course.'.$cid.'.internal.selfenroll_start_date'},
 4994:                 selfenroll_end_date           => $env{'course.'.$cid.'.internal.selfenroll_end_date'},
 4995:                 selfenroll_start_access       => $env{'course.'.$cid.'.internal.selfenroll_start_access'},
 4996:                 selfenroll_end_access         => $env{'course.'.$cid.'.internal.selfenroll_end_access'},
 4997:                 default_enrollment_start_date => $env{'course.'.$cid.'.default_enrollment_start_date'},
 4998:                 default_enrollment_end_date   => $env{'course.'.$cid.'.default_enrollment_end_date'},
 4999:                 uniquecode                    => $env{'course.'.$cid.'.internal.uniquecode'},
 5000:             );
 5001:             push(@{$brcrum},
 5002:                     {href => '/adm/createuser?action=selfenroll',
 5003:                      text => "Configure Self-enrollment",
 5004:                      help => 'Course_Self_Enrollment'});
 5005:             if (!exists($env{'form.state'})) {
 5006:                 $args = { bread_crumbs           => $brcrum,
 5007:                           bread_crumbs_component => 'Configure Self-enrollment'};
 5008:                 $r->print(&header(undef,$args));
 5009:                 $r->print('<h3>'.&mt('Self-enrollment with a student role').'</h3>'."\n");
 5010:                 &print_selfenroll_menu($r,'course',$cid,$cdom,$cnum,\%currsettings);
 5011:             } elsif ($env{'form.state'} eq 'done') {
 5012:                 push (@{$brcrum},
 5013:                           {href=>'/adm/createuser?action=selfenroll',
 5014:                            text=>"Result"});
 5015:                 $args = { bread_crumbs           => $brcrum,
 5016:                           bread_crumbs_component => 'Self-enrollment result'};
 5017:                 $r->print(&header(undef,$args));
 5018:                 $r->print('<h3>'.&mt('Self-enrollment with a student role').'</h3>'."\n");
 5019:                 &update_selfenroll_config($r,$cid,$cdom,$cnum,$context,$crstype,\%currsettings);
 5020:             }
 5021:         } else {
 5022:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 5023:                      '<span class="LC_error">'.&mt('You do not have permission to configure self-enrollment').'</span>');
 5024:         }
 5025:     } elsif ($env{'form.action'} eq 'selfenrollqueue') {
 5026:         push(@{$brcrum},
 5027:                  {href => '/adm/createuser?action=selfenrollqueue',
 5028:                   text => 'Enrollment requests',
 5029:                   help => 'Course_Self_Enrollment'});
 5030:         $bread_crumbs_component = 'Enrollment requests';
 5031:         if ($env{'form.state'} eq 'done') {
 5032:             push(@{$brcrum},
 5033:                      {href => '/adm/createuser?action=selfenrollqueue',
 5034:                       text => 'Result',
 5035:                       help => 'Course_Self_Enrollment'});
 5036:             $bread_crumbs_component = 'Enrollment result';
 5037:         }
 5038:         $args = { bread_crumbs           => $brcrum,
 5039:                   bread_crumbs_component => $bread_crumbs_component};
 5040:         $r->print(&header(undef,$args));
 5041:         my $cid = $env{'request.course.id'};
 5042:         my $cdom = $env{'course.'.$cid.'.domain'};
 5043:         my $cnum = $env{'course.'.$cid.'.num'};
 5044:         my $coursedesc = $env{'course.'.$cid.'.description'};
 5045:         if (!exists($env{'form.state'})) {
 5046:             $r->print('<h3>'.&mt('Pending enrollment requests').'</h3>'."\n");
 5047:             $r->print(&Apache::loncoursequeueadmin::display_queued_requests($context,
 5048:                                                                        $cdom,$cnum));
 5049:         } elsif ($env{'form.state'} eq 'done') {
 5050:             $r->print('<h3>'.&mt('Enrollment request processing').'</h3>'."\n");
 5051:             $r->print(&Apache::loncoursequeueadmin::update_request_queue($context,
 5052:                           $cdom,$cnum,$coursedesc));
 5053:         }
 5054:     } elsif ($env{'form.action'} eq 'changelogs') {
 5055:         my $helpitem;
 5056:         if ($context eq 'course') {
 5057:             $helpitem = 'Course_User_Logs';
 5058:         }
 5059:         push (@{$brcrum},
 5060:                  {href => '/adm/createuser?action=changelogs',
 5061:                   text => 'User Management Logs',
 5062:                   help => $helpitem});
 5063:         $bread_crumbs_component = 'User Changes';
 5064:         $args = { bread_crumbs           => $brcrum,
 5065:                   bread_crumbs_component => $bread_crumbs_component};
 5066:         $r->print(&header(undef,$args));
 5067:         &print_userchangelogs_display($r,$context,$permission);
 5068:     } else {
 5069:         $bread_crumbs_component = 'User Management';
 5070:         $args = { bread_crumbs           => $brcrum,
 5071:                   bread_crumbs_component => $bread_crumbs_component};
 5072:         $r->print(&header(undef,$args));
 5073:         $r->print(&print_main_menu($permission,$context,$crstype));
 5074:     }
 5075:     $r->print(&Apache::loncommon::end_page());
 5076:     return OK;
 5077: }
 5078: 
 5079: sub header {
 5080:     my ($jscript,$args) = @_;
 5081:     my $start_page;
 5082:     if (ref($args) eq 'HASH') {
 5083:         $start_page=&Apache::loncommon::start_page('User Management',$jscript,$args);
 5084:     } else {
 5085:         $start_page=&Apache::loncommon::start_page('User Management',$jscript);
 5086:     }
 5087:     return $start_page;
 5088: }
 5089: 
 5090: sub add_script {
 5091:     my ($js) = @_;
 5092:     return '<script type="text/javascript">'."\n"
 5093:           .'// <![CDATA['."\n"
 5094:           .$js."\n"
 5095:           .'// ]]>'."\n"
 5096:           .'</script>'."\n";
 5097: }
 5098: 
 5099: sub usernamerequest_javascript {
 5100:     my $js = <<ENDJS;
 5101: 
 5102: function openusernamereqdisplay(dom,uname,queue) {
 5103:     var url = '/adm/createuser?action=displayuserreq';
 5104:     url += '&domain='+dom+'&username='+uname+'&queue='+queue;
 5105:     var title = 'Account_Request_Browser';
 5106:     var options = 'scrollbars=1,resizable=1,menubar=0';
 5107:     options += ',width=700,height=600';
 5108:     var stdeditbrowser = open(url,title,options,'1');
 5109:     stdeditbrowser.focus();
 5110:     return;
 5111: }
 5112:  
 5113: ENDJS
 5114: }
 5115: 
 5116: sub close_popup_form {
 5117:     my $close= &mt('Close Window');
 5118:     return << "END";
 5119: <p><form name="displayreq" action="" method="post">
 5120: <input type="button" name="closeme" value="$close" onclick="javascript:self.close();" />
 5121: </form></p>
 5122: END
 5123: }
 5124: 
 5125: sub verify_user_display {
 5126:     my ($context) = @_;
 5127:     my %lt = &Apache::lonlocal::texthash (
 5128:         course    => 'course(s): description, section(s), status',
 5129:         community => 'community(s): description, section(s), status',
 5130:         author    => 'author',
 5131:     );
 5132:     my $photos;
 5133:     if (($context eq 'course') && $env{'request.course.id'}) {
 5134:         $photos = $env{'course.'.$env{'request.course.id'}.'.internal.showphoto'};
 5135:     }
 5136:     my $output = <<"END";
 5137: 
 5138: function hide_searching() {
 5139:     if (document.getElementById('searching')) {
 5140:         document.getElementById('searching').style.display = 'none';
 5141:     }
 5142:     return;
 5143: }
 5144: 
 5145: function display_update() {
 5146:     document.studentform.action.value = 'listusers';
 5147:     document.studentform.phase.value = 'display';
 5148:     document.studentform.submit();
 5149: }
 5150: 
 5151: function updateCols(caller) {
 5152:     var context = '$context';
 5153:     var photos = '$photos';
 5154:     if (caller == 'Status') {
 5155:         if ((context == 'domain') && 
 5156:             ((document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'course') ||
 5157:              (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'community'))) {
 5158:             document.getElementById('showcolstatus').checked = false;
 5159:             document.getElementById('showcolstatus').disabled = 'disabled';
 5160:             document.getElementById('showcolstart').checked = false;
 5161:             document.getElementById('showcolend').checked = false;
 5162:         } else {
 5163:             if (document.studentform.Status.options[document.studentform.Status.selectedIndex].value == 'Any') {
 5164:                 document.getElementById('showcolstatus').checked = true;
 5165:                 document.getElementById('showcolstatus').disabled = '';
 5166:                 document.getElementById('showcolstart').checked = true;
 5167:                 document.getElementById('showcolend').checked = true;
 5168:             } else {
 5169:                 document.getElementById('showcolstatus').checked = false;
 5170:                 document.getElementById('showcolstatus').disabled = 'disabled';
 5171:                 document.getElementById('showcolstart').checked = false;
 5172:                 document.getElementById('showcolend').checked = false;
 5173:             }
 5174:         }
 5175:     }
 5176:     if (caller == 'output') {
 5177:         if (photos == 1) {
 5178:             if (document.getElementById('showcolphoto')) {
 5179:                 var photoitem = document.getElementById('showcolphoto');
 5180:                 if (document.studentform.output.options[document.studentform.output.selectedIndex].value == 'html') {
 5181:                     photoitem.checked = true;
 5182:                     photoitem.disabled = '';
 5183:                 } else {
 5184:                     photoitem.checked = false;
 5185:                     photoitem.disabled = 'disabled';
 5186:                 }
 5187:             }
 5188:         }
 5189:     }
 5190:     if (caller == 'showrole') {
 5191:         if ((document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'Any') ||
 5192:             (document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'cr')) {
 5193:             document.getElementById('showcolrole').checked = true;
 5194:             document.getElementById('showcolrole').disabled = '';
 5195:         } else {
 5196:             document.getElementById('showcolrole').checked = false;
 5197:             document.getElementById('showcolrole').disabled = 'disabled';
 5198:         }
 5199:         if (context == 'domain') {
 5200:             var quotausageshow = 0;
 5201:             if ((document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'course') ||
 5202:                 (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'community')) {
 5203:                 document.getElementById('showcolstatus').checked = false;
 5204:                 document.getElementById('showcolstatus').disabled = 'disabled';
 5205:                 document.getElementById('showcolstart').checked = false;
 5206:                 document.getElementById('showcolend').checked = false;
 5207:             } else {
 5208:                 if (document.studentform.Status.options[document.studentform.Status.selectedIndex].value == 'Any') {
 5209:                     document.getElementById('showcolstatus').checked = true;
 5210:                     document.getElementById('showcolstatus').disabled = '';
 5211:                     document.getElementById('showcolstart').checked = true;
 5212:                     document.getElementById('showcolend').checked = true;
 5213:                 }
 5214:             }
 5215:             if (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'domain') {
 5216:                 document.getElementById('showcolextent').disabled = 'disabled';
 5217:                 document.getElementById('showcolextent').checked = 'false';
 5218:                 document.getElementById('showextent').style.display='none';
 5219:                 document.getElementById('showcoltextextent').innerHTML = '';
 5220:                 if ((document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'au') ||
 5221:                     (document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'Any')) {
 5222:                     if (document.getElementById('showcolauthorusage')) {
 5223:                         document.getElementById('showcolauthorusage').disabled = '';
 5224:                     }
 5225:                     if (document.getElementById('showcolauthorquota')) {
 5226:                         document.getElementById('showcolauthorquota').disabled = '';
 5227:                     }
 5228:                     quotausageshow = 1;
 5229:                 }
 5230:             } else {
 5231:                 document.getElementById('showextent').style.display='block';
 5232:                 document.getElementById('showextent').style.textAlign='left';
 5233:                 document.getElementById('showextent').style.textFace='normal';
 5234:                 if (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'author') {
 5235:                     document.getElementById('showcolextent').disabled = '';
 5236:                     document.getElementById('showcolextent').checked = 'true';
 5237:                     document.getElementById('showcoltextextent').innerHTML="$lt{'author'}";
 5238:                 } else {
 5239:                     document.getElementById('showcolextent').disabled = '';
 5240:                     document.getElementById('showcolextent').checked = 'true';
 5241:                     if (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'community') {
 5242:                         document.getElementById('showcoltextextent').innerHTML="$lt{'community'}";
 5243:                     } else {
 5244:                         document.getElementById('showcoltextextent').innerHTML="$lt{'course'}";
 5245:                     }
 5246:                 }
 5247:             }
 5248:             if (quotausageshow == 0)  {
 5249:                 if (document.getElementById('showcolauthorusage')) {
 5250:                     document.getElementById('showcolauthorusage').checked = false;
 5251:                     document.getElementById('showcolauthorusage').disabled = 'disabled';
 5252:                 }
 5253:                 if (document.getElementById('showcolauthorquota')) {
 5254:                     document.getElementById('showcolauthorquota').checked = false;
 5255:                     document.getElementById('showcolauthorquota').disabled = 'disabled';
 5256:                 }
 5257:             }
 5258:         }
 5259:     }
 5260:     return;
 5261: }
 5262: 
 5263: END
 5264:     return $output;
 5265: 
 5266: }
 5267: 
 5268: ###############################################################
 5269: ###############################################################
 5270: #  Menu Phase One
 5271: sub print_main_menu {
 5272:     my ($permission,$context,$crstype) = @_;
 5273:     my $linkcontext = $context;
 5274:     my $stuterm = lc(&Apache::lonnet::plaintext('st',$crstype));
 5275:     if (($context eq 'course') && ($crstype eq 'Community')) {
 5276:         $linkcontext = lc($crstype);
 5277:         $stuterm = 'Members';
 5278:     }
 5279:     my %links = (
 5280:                 domain => {
 5281:                             upload     => 'Upload a File of Users',
 5282:                             singleuser => 'Add/Modify a User',
 5283:                             listusers  => 'Manage Users',
 5284:                             },
 5285:                 author => {
 5286:                             upload     => 'Upload a File of Co-authors',
 5287:                             singleuser => 'Add/Modify a Co-author',
 5288:                             listusers  => 'Manage Co-authors',
 5289:                             },
 5290:                 course => {
 5291:                             upload     => 'Upload a File of Course Users',
 5292:                             singleuser => 'Add/Modify a Course User',
 5293:                             listusers  => 'List and Modify Multiple Course Users',
 5294:                             },
 5295:                 community => {
 5296:                             upload     => 'Upload a File of Community Users',
 5297:                             singleuser => 'Add/Modify a Community User',
 5298:                             listusers  => 'List and Modify Multiple Community Users',
 5299:                            },
 5300:                 );
 5301:      my %linktitles = (
 5302:                 domain => {
 5303:                             singleuser => 'Add a user to the domain, and/or a course or community in the domain.',
 5304:                             listusers  => 'Show and manage users in this domain.',
 5305:                             },
 5306:                 author => {
 5307:                             singleuser => 'Add a user with a co- or assistant author role.',
 5308:                             listusers  => 'Show and manage co- or assistant authors.',
 5309:                             },
 5310:                 course => {
 5311:                             singleuser => 'Add a user with a certain role to this course.',
 5312:                             listusers  => 'Show and manage users in this course.',
 5313:                             },
 5314:                 community => {
 5315:                             singleuser => 'Add a user with a certain role to this community.',
 5316:                             listusers  => 'Show and manage users in this community.',
 5317:                            },
 5318:                 );
 5319:   my @menu = ( {categorytitle => 'Single Users', 
 5320:          items =>
 5321:          [
 5322:             {
 5323:              linktext => $links{$linkcontext}{'singleuser'},
 5324:              icon => 'edit-redo.png',
 5325:              #help => 'Course_Change_Privileges',
 5326:              url => '/adm/createuser?action=singleuser',
 5327:              permission => $permission->{'cusr'},
 5328:              linktitle => $linktitles{$linkcontext}{'singleuser'},
 5329:             },
 5330:          ]},
 5331: 
 5332:          {categorytitle => 'Multiple Users',
 5333:          items => 
 5334:          [
 5335:             {
 5336:              linktext => $links{$linkcontext}{'upload'},
 5337:              icon => 'uplusr.png',
 5338:              #help => 'Course_Create_Class_List',
 5339:              url => '/adm/createuser?action=upload',
 5340:              permission => $permission->{'cusr'},
 5341:              linktitle => 'Upload a CSV or a text file containing users.',
 5342:             },
 5343:             {
 5344:              linktext => $links{$linkcontext}{'listusers'},
 5345:              icon => 'mngcu.png',
 5346:              #help => 'Course_View_Class_List',
 5347:              url => '/adm/createuser?action=listusers',
 5348:              permission => ($permission->{'view'} || $permission->{'cusr'}),
 5349:              linktitle => $linktitles{$linkcontext}{'listusers'}, 
 5350:             },
 5351: 
 5352:          ]},
 5353: 
 5354:          {categorytitle => 'Administration',
 5355:          items => [ ]},
 5356:        );
 5357:             
 5358:     if ($context eq 'domain'){
 5359:         
 5360:         push(@{ $menu[2]->{items} }, #Category: Administration
 5361:             {
 5362:              linktext => 'Custom Roles',
 5363:              icon => 'emblem-photos.png',
 5364:              #help => 'Course_Editing_Custom_Roles',
 5365:              url => '/adm/createuser?action=custom',
 5366:              permission => $permission->{'custom'},
 5367:              linktitle => 'Configure a custom role.',
 5368:             },
 5369:             {
 5370:              linktext => 'Authoring Space Requests',
 5371:              icon => 'selfenrl-queue.png',
 5372:              #help => 'Domain_Role_Approvals',
 5373:              url => '/adm/createuser?action=processauthorreq',
 5374:              permission => $permission->{'cusr'},
 5375:              linktitle => 'Approve or reject author role requests',
 5376:             },
 5377:             {
 5378:              linktext => 'LON-CAPA Account Requests',
 5379:              icon => 'list-add.png',
 5380:              #help => 'Domain_Username_Approvals',
 5381:              url => '/adm/createuser?action=processusernamereq',
 5382:              permission => $permission->{'cusr'},
 5383:              linktitle => 'Approve or reject LON-CAPA account requests',
 5384:             },
 5385:             {
 5386:              linktext => 'Change Log',
 5387:              icon => 'document-properties.png',
 5388:              #help => 'Course_User_Logs',
 5389:              url => '/adm/createuser?action=changelogs',
 5390:              permission => $permission->{'cusr'},
 5391:              linktitle => 'View change log.',
 5392:             },
 5393:         );
 5394:         
 5395:     }elsif ($context eq 'course'){
 5396:         my ($cnum,$cdom) = &Apache::lonuserutils::get_course_identity();
 5397: 
 5398:         my %linktext = (
 5399:                          'Course'    => {
 5400:                                           single => 'Add/Modify a Student', 
 5401:                                           drop   => 'Drop Students',
 5402:                                           groups => 'Course Groups',
 5403:                                         },
 5404:                          'Community' => {
 5405:                                           single => 'Add/Modify a Member', 
 5406:                                           drop   => 'Drop Members',
 5407:                                           groups => 'Community Groups',
 5408:                                         },
 5409:                        );
 5410:         $linktext{'Placement'} = $linktext{'Course'};
 5411: 
 5412:         my %linktitle = (
 5413:             'Course' => {
 5414:                   single => 'Add a user with the role of student to this course',
 5415:                   drop   => 'Remove a student from this course.',
 5416:                   groups => 'Manage course groups',
 5417:                         },
 5418:             'Community' => {
 5419:                   single => 'Add a user with the role of member to this community',
 5420:                   drop   => 'Remove a member from this community.',
 5421:                   groups => 'Manage community groups',
 5422:                            },
 5423:         );
 5424: 
 5425:         $linktitle{'Placement'} = $linktitle{'Course'};
 5426: 
 5427:         push(@{ $menu[0]->{items} }, #Category: Single Users
 5428:             {   
 5429:              linktext => $linktext{$crstype}{'single'},
 5430:              #help => 'Course_Add_Student',
 5431:              icon => 'list-add.png',
 5432:              url => '/adm/createuser?action=singlestudent',
 5433:              permission => $permission->{'cusr'},
 5434:              linktitle => $linktitle{$crstype}{'single'},
 5435:             },
 5436:         );
 5437:         
 5438:         push(@{ $menu[1]->{items} }, #Category: Multiple Users 
 5439:             {
 5440:              linktext => $linktext{$crstype}{'drop'},
 5441:              icon => 'edit-undo.png',
 5442:              #help => 'Course_Drop_Student',
 5443:              url => '/adm/createuser?action=drop',
 5444:              permission => $permission->{'cusr'},
 5445:              linktitle => $linktitle{$crstype}{'drop'},
 5446:             },
 5447:         );
 5448:         push(@{ $menu[2]->{items} }, #Category: Administration
 5449:             {    
 5450:              linktext => 'Custom Roles',
 5451:              icon => 'emblem-photos.png',
 5452:              #help => 'Course_Editing_Custom_Roles',
 5453:              url => '/adm/createuser?action=custom',
 5454:              permission => $permission->{'custom'},
 5455:              linktitle => 'Configure a custom role.',
 5456:             },
 5457:             {
 5458:              linktext => $linktext{$crstype}{'groups'},
 5459:              icon => 'grps.png',
 5460:              #help => 'Course_Manage_Group',
 5461:              url => '/adm/coursegroups?refpage=cusr',
 5462:              permission => $permission->{'grp_manage'},
 5463:              linktitle => $linktitle{$crstype}{'groups'},
 5464:             },
 5465:             {
 5466:              linktext => 'Change Log',
 5467:              icon => 'document-properties.png',
 5468:              #help => 'Course_User_Logs',
 5469:              url => '/adm/createuser?action=changelogs',
 5470:              permission => $permission->{'cusr'},
 5471:              linktitle => 'View change log.',
 5472:             },
 5473:         );
 5474:         if ($env{'course.'.$env{'request.course.id'}.'.internal.selfenroll_approval'}) {
 5475:             push(@{ $menu[2]->{items} },
 5476:                     {
 5477:                      linktext => 'Enrollment Requests',
 5478:                      icon => 'selfenrl-queue.png',
 5479:                      #help => 'Course_Approve_Selfenroll',
 5480:                      url => '/adm/createuser?action=selfenrollqueue',
 5481:                      permission => $permission->{'selfenrolladmin'},
 5482:                      linktitle =>'Approve or reject enrollment requests.',
 5483:                     },
 5484:             );
 5485:         }
 5486:         
 5487:         if (!exists($permission->{'cusr_section'})){
 5488:             if ($crstype ne 'Community') {
 5489:                 push(@{ $menu[2]->{items} },
 5490:                     {
 5491:                      linktext => 'Automated Enrollment',
 5492:                      icon => 'roles.png',
 5493:                      #help => 'Course_Automated_Enrollment',
 5494:                      permission => (&Apache::lonnet::auto_run($cnum,$cdom)
 5495:                                          && $permission->{'cusr'}),
 5496:                      url  => '/adm/populate',
 5497:                      linktitle => 'Automated enrollment manager.',
 5498:                     }
 5499:                 );
 5500:             }
 5501:             push(@{ $menu[2]->{items} }, 
 5502:                 {
 5503:                  linktext => 'User Self-Enrollment',
 5504:                  icon => 'self_enroll.png',
 5505:                  #help => 'Course_Self_Enrollment',
 5506:                  url => '/adm/createuser?action=selfenroll',
 5507:                  permission => $permission->{'selfenrolladmin'},
 5508:                  linktitle => 'Configure user self-enrollment.',
 5509:                 },
 5510:             );
 5511:         }
 5512:     } elsif ($context eq 'author') {
 5513:         push(@{ $menu[2]->{items} }, #Category: Administration
 5514:             {
 5515:              linktext => 'Change Log',
 5516:              icon => 'document-properties.png',
 5517:              #help => 'Course_User_Logs',
 5518:              url => '/adm/createuser?action=changelogs',
 5519:              permission => $permission->{'cusr'},
 5520:              linktitle => 'View change log.',
 5521:             },
 5522:         );
 5523:     }
 5524:     return Apache::lonhtmlcommon::generate_menu(@menu);
 5525: #               { text => 'View Log-in History',
 5526: #                 help => 'Course_User_Logins',
 5527: #                 action => 'logins',
 5528: #                 permission => $permission->{'cusr'},
 5529: #               });
 5530: }
 5531: 
 5532: sub restore_prev_selections {
 5533:     my %saveable_parameters = ('srchby'   => 'scalar',
 5534: 			       'srchin'   => 'scalar',
 5535: 			       'srchtype' => 'scalar',
 5536: 			       );
 5537:     &Apache::loncommon::store_settings('user','user_picker',
 5538: 				       \%saveable_parameters);
 5539:     &Apache::loncommon::restore_settings('user','user_picker',
 5540: 					 \%saveable_parameters);
 5541: }
 5542: 
 5543: sub print_selfenroll_menu {
 5544:     my ($r,$context,$cid,$cdom,$cnum,$currsettings,$additional) = @_;
 5545:     my $crstype = &Apache::loncommon::course_type();
 5546:     my $formname = 'selfenroll';
 5547:     my $nolink = 1;
 5548:     my ($row,$lt) = &Apache::lonuserutils::get_selfenroll_titles();
 5549:     my $groupslist = &Apache::lonuserutils::get_groupslist();
 5550:     my $setsec_js = 
 5551:         &Apache::lonuserutils::setsections_javascript($formname,$groupslist);
 5552:     my %alerts = &Apache::lonlocal::texthash(
 5553:         acto => 'Activation of self-enrollment was selected for the following domain(s)',
 5554:         butn => 'but no user types have been checked.',
 5555:         wilf => "Please uncheck 'activate' or check at least one type.",
 5556:     );
 5557:     &js_escape(\%alerts);
 5558:     my $selfenroll_js = <<"ENDSCRIPT";
 5559: function update_types(caller,num) {
 5560:     var delidx = getIndexByName('selfenroll_delete');
 5561:     var actidx = getIndexByName('selfenroll_activate');
 5562:     if (caller == 'selfenroll_all') {
 5563:         var selall;
 5564:         for (var i=0; i<document.$formname.selfenroll_all.length; i++) {
 5565:             if (document.$formname.selfenroll_all[i].checked) {
 5566:                 selall = document.$formname.selfenroll_all[i].value;
 5567:             }
 5568:         }
 5569:         if (selall == 1) {
 5570:             if (delidx != -1) {
 5571:                 if (document.$formname.selfenroll_delete.length) {
 5572:                     for (var j=0; j<document.$formname.selfenroll_delete.length; j++) {
 5573:                         document.$formname.selfenroll_delete[j].checked = true;
 5574:                     }
 5575:                 } else {
 5576:                     document.$formname.elements[delidx].checked = true;
 5577:                 }
 5578:             }
 5579:             if (actidx != -1) {
 5580:                 if (document.$formname.selfenroll_activate.length) {
 5581:                     for (var j=0; j<document.$formname.selfenroll_activate.length; j++) {
 5582:                         document.$formname.selfenroll_activate[j].checked = false;
 5583:                     }
 5584:                 } else {
 5585:                     document.$formname.elements[actidx].checked = false;
 5586:                 }
 5587:             }
 5588:             document.$formname.selfenroll_newdom.selectedIndex = 0; 
 5589:         }
 5590:     }
 5591:     if (caller == 'selfenroll_activate') {
 5592:         if (document.$formname.selfenroll_activate.length) {
 5593:             for (var j=0; j<document.$formname.selfenroll_activate.length; j++) {
 5594:                 if (document.$formname.selfenroll_activate[j].value == num) {
 5595:                     if (document.$formname.selfenroll_activate[j].checked) {
 5596:                         for (var i=0; i<document.$formname.selfenroll_all.length; i++) {
 5597:                             if (document.$formname.selfenroll_all[i].value == '1') {
 5598:                                 document.$formname.selfenroll_all[i].checked = false;
 5599:                             }
 5600:                             if (document.$formname.selfenroll_all[i].value == '0') {
 5601:                                 document.$formname.selfenroll_all[i].checked = true;
 5602:                             }
 5603:                         }
 5604:                     }
 5605:                 }
 5606:             }
 5607:         } else {
 5608:             for (var i=0; i<document.$formname.selfenroll_all.length; i++) {
 5609:                 if (document.$formname.selfenroll_all[i].value == '1') {
 5610:                     document.$formname.selfenroll_all[i].checked = false;
 5611:                 }
 5612:                 if (document.$formname.selfenroll_all[i].value == '0') {
 5613:                     document.$formname.selfenroll_all[i].checked = true;
 5614:                 }
 5615:             }
 5616:         }
 5617:     }
 5618:     if (caller == 'selfenroll_delete') {
 5619:         if (document.$formname.selfenroll_delete.length) {
 5620:             for (var j=0; j<document.$formname.selfenroll_delete.length; j++) {
 5621:                 if (document.$formname.selfenroll_delete[j].value == num) {
 5622:                     if (document.$formname.selfenroll_delete[j].checked) {
 5623:                         var delindex = getIndexByName('selfenroll_types_'+num);
 5624:                         if (delindex != -1) { 
 5625:                             if (document.$formname.elements[delindex].length) {
 5626:                                 for (var k=0; k<document.$formname.elements[delindex].length; k++) {
 5627:                                     document.$formname.elements[delindex][k].checked = false;
 5628:                                 }
 5629:                             } else {
 5630:                                 document.$formname.elements[delindex].checked = false;
 5631:                             }
 5632:                         }
 5633:                     }
 5634:                 }
 5635:             }
 5636:         } else {
 5637:             if (document.$formname.selfenroll_delete.checked) {
 5638:                 var delindex = getIndexByName('selfenroll_types_'+num);
 5639:                 if (delindex != -1) {
 5640:                     if (document.$formname.elements[delindex].length) {
 5641:                         for (var k=0; k<document.$formname.elements[delindex].length; k++) {
 5642:                             document.$formname.elements[delindex][k].checked = false;
 5643:                         }
 5644:                     } else {
 5645:                         document.$formname.elements[delindex].checked = false;
 5646:                     }
 5647:                 }
 5648:             }
 5649:         }
 5650:     }
 5651:     return;
 5652: }
 5653: 
 5654: function validate_types(form) {
 5655:     var needaction = new Array();
 5656:     var countfail = 0;
 5657:     var actidx = getIndexByName('selfenroll_activate');
 5658:     if (actidx != -1) {
 5659:         if (document.$formname.selfenroll_activate.length) {
 5660:             for (var j=0; j<document.$formname.selfenroll_activate.length; j++) {
 5661:                 var num = document.$formname.selfenroll_activate[j].value;
 5662:                 if (document.$formname.selfenroll_activate[j].checked) {
 5663:                     countfail = check_types(num,countfail,needaction)
 5664:                 }
 5665:             }
 5666:         } else {
 5667:             if (document.$formname.selfenroll_activate.checked) {
 5668:                 var num = document.$formname.selfenroll_activate.value;
 5669:                 countfail = check_types(num,countfail,needaction)
 5670:             }
 5671:         }
 5672:     }
 5673:     if (countfail > 0) {
 5674:         var msg = "$alerts{'acto'}\\n";
 5675:         var loopend = needaction.length -1;
 5676:         if (loopend > 0) {
 5677:             for (var m=0; m<loopend; m++) {
 5678:                 msg += needaction[m]+", ";
 5679:             }
 5680:         }
 5681:         msg += needaction[loopend]+"\\n$alerts{'butn'}\\n$alerts{'wilf'}";
 5682:         alert(msg);
 5683:         return; 
 5684:     }
 5685:     setSections(form);
 5686: }
 5687: 
 5688: function check_types(num,countfail,needaction) {
 5689:     var typeidx = getIndexByName('selfenroll_types_'+num);
 5690:     var count = 0;
 5691:     if (typeidx != -1) {
 5692:         if (document.$formname.elements[typeidx].length) {
 5693:             for (var k=0; k<document.$formname.elements[typeidx].length; k++) {
 5694:                 if (document.$formname.elements[typeidx][k].checked) {
 5695:                     count ++;
 5696:                 }
 5697:             }
 5698:         } else {
 5699:             if (document.$formname.elements[typeidx].checked) {
 5700:                 count ++;
 5701:             }
 5702:         }
 5703:         if (count == 0) {
 5704:             var domidx = getIndexByName('selfenroll_dom_'+num);
 5705:             if (domidx != -1) {
 5706:                 var domname = document.$formname.elements[domidx].value;
 5707:                 needaction[countfail] = domname;
 5708:                 countfail ++;
 5709:             }
 5710:         }
 5711:     }
 5712:     return countfail;
 5713: }
 5714: 
 5715: function toggleNotify() {
 5716:     var selfenrollApproval = 0;
 5717:     if (document.$formname.selfenroll_approval.length) {
 5718:         for (var i=0; i<document.$formname.selfenroll_approval.length; i++) {
 5719:             if (document.$formname.selfenroll_approval[i].checked) {
 5720:                 selfenrollApproval = document.$formname.selfenroll_approval[i].value;
 5721:                 break;        
 5722:             }
 5723:         }
 5724:     }
 5725:     if (document.getElementById('notified')) {
 5726:         if (selfenrollApproval == 0) {
 5727:             document.getElementById('notified').style.display='none';
 5728:         } else {
 5729:             document.getElementById('notified').style.display='block';
 5730:         }
 5731:     }
 5732:     return;
 5733: }
 5734: 
 5735: function getIndexByName(item) {
 5736:     for (var i=0;i<document.$formname.elements.length;i++) {
 5737:         if (document.$formname.elements[i].name == item) {
 5738:             return i;
 5739:         }
 5740:     }
 5741:     return -1;
 5742: }
 5743: ENDSCRIPT
 5744: 
 5745:     my $output = '<script type="text/javascript">'."\n".
 5746:                  '// <![CDATA['."\n".
 5747:                  $setsec_js."\n".$selfenroll_js."\n".
 5748:                  '// ]]>'."\n".
 5749:                  '</script>'."\n".
 5750:                  '<h3>'.$lt->{'selfenroll'}.'</h3>'."\n";
 5751:  
 5752:     my $visactions = &cat_visibility();
 5753:     my ($cathash,%cattype);
 5754:     my %domconfig = &Apache::lonnet::get_dom('configuration',['coursecategories'],$cdom);
 5755:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 5756:         $cathash = $domconfig{'coursecategories'}{'cats'};
 5757:         $cattype{'auth'} = $domconfig{'coursecategories'}{'auth'};
 5758:         $cattype{'unauth'} = $domconfig{'coursecategories'}{'unauth'};
 5759:         if ($cattype{'auth'} eq '') {
 5760:             $cattype{'auth'} = 'std';
 5761:         }
 5762:         if ($cattype{'unauth'} eq '') {
 5763:             $cattype{'unauth'} = 'std';
 5764:         }
 5765:     } else {
 5766:         $cathash = {};
 5767:         $cattype{'auth'} = 'std';
 5768:         $cattype{'unauth'} = 'std';
 5769:     }
 5770:     if (($cattype{'auth'} eq 'none') && ($cattype{'unauth'} eq 'none')) {
 5771:         $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
 5772:                   '<br />'.
 5773:                   '<br />'.$visactions->{'take'}.'<ul>'.
 5774:                   '<li>'.$visactions->{'dc_chgconf'}.'</li>'.
 5775:                   '</ul>');
 5776:     } elsif (($cattype{'auth'} !~ /^(std|domonly)$/) && ($cattype{'unauth'} !~ /^(std|domonly)$/)) {
 5777:         if ($currsettings->{'uniquecode'}) {
 5778:             $r->print('<span class="LC_info">'.$visactions->{'vis'}.'</span>');
 5779:         } else {
 5780:             $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
 5781:                   '<br />'.
 5782:                   '<br />'.$visactions->{'take'}.'<ul>'.
 5783:                   '<li>'.$visactions->{'dc_setcode'}.'</li>'.
 5784:                   '</ul><br />');
 5785:         }
 5786:     } else {
 5787:         my ($visible,$cansetvis,$vismsgs) = &visible_in_stdcat($cdom,$cnum,\%domconfig);
 5788:         if (ref($visactions) eq 'HASH') {
 5789:             if ($visible) {
 5790:                 $output .= '<p class="LC_info">'.$visactions->{'vis'}.'</p>';
 5791:            } else {
 5792:                 $output .= '<p class="LC_warning">'.$visactions->{'miss'}.'</p>'
 5793:                           .$visactions->{'yous'}.
 5794:                            '<p>'.$visactions->{'gen'}.'<br />'.$visactions->{'coca'};
 5795:                 if (ref($vismsgs) eq 'ARRAY') {
 5796:                     $output .= '<br />'.$visactions->{'make'}.'<ul>';
 5797:                     foreach my $item (@{$vismsgs}) {
 5798:                         $output .= '<li>'.$visactions->{$item}.'</li>';
 5799:                     }
 5800:                     $output .= '</ul>';
 5801:                 }
 5802:                 $output .= '</p>';
 5803:             }
 5804:         }
 5805:     }
 5806:     my $actionhref = '/adm/createuser';
 5807:     if ($context eq 'domain') {
 5808:         $actionhref = '/adm/modifycourse';
 5809:     }
 5810: 
 5811:     my %noedit;
 5812:     unless ($context eq 'domain') {
 5813:         %noedit = &get_noedit_fields($cdom,$cnum,$crstype,$row);
 5814:     }
 5815:     $output .= '<form name="'.$formname.'" method="post" action="'.$actionhref.'">'."\n".
 5816:                &Apache::lonhtmlcommon::start_pick_box();
 5817:     if (ref($row) eq 'ARRAY') {
 5818:         foreach my $item (@{$row}) {
 5819:             my $title = $item; 
 5820:             if (ref($lt) eq 'HASH') {
 5821:                 $title = $lt->{$item};
 5822:             }
 5823:             $output .= &Apache::lonhtmlcommon::row_title($title);
 5824:             if ($item eq 'types') {
 5825:                 my $curr_types;
 5826:                 if (ref($currsettings) eq 'HASH') {
 5827:                     $curr_types = $currsettings->{'selfenroll_types'};
 5828:                 }
 5829:                 if ($noedit{$item}) {
 5830:                     if ($curr_types eq '*') {
 5831:                         $output .= &mt('Any user in any domain');   
 5832:                     } else {
 5833:                         my @entries = split(/;/,$curr_types);
 5834:                         if (@entries > 0) {
 5835:                             $output .= '<ul>'; 
 5836:                             foreach my $entry (@entries) {
 5837:                                 my ($currdom,$typestr) = split(/:/,$entry);
 5838:                                 next if ($typestr eq '');
 5839:                                 my $domdesc = &Apache::lonnet::domain($currdom);
 5840:                                 my @currinsttypes = split(',',$typestr);
 5841:                                 my ($othertitle,$usertypes,$types) = 
 5842:                                     &Apache::loncommon::sorted_inst_types($currdom);
 5843:                                 if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 5844:                                     $usertypes->{'any'} = &mt('any user'); 
 5845:                                     if (keys(%{$usertypes}) > 0) {
 5846:                                         $usertypes->{'other'} = &mt('other users');
 5847:                                     }
 5848:                                     my @longinsttypes = map { $usertypes->{$_}; } @currinsttypes;
 5849:                                     $output .= '<li>'.$domdesc.':'.join(', ',@longinsttypes).'</li>';
 5850:                                  }
 5851:                             }
 5852:                             $output .= '</ul>';
 5853:                         } else {
 5854:                             $output .= &mt('None');
 5855:                         }
 5856:                     }
 5857:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 5858:                     next;
 5859:                 }
 5860:                 my $showdomdesc = 1;
 5861:                 my $includeempty = 1;
 5862:                 my $num = 0;
 5863:                 $output .= &Apache::loncommon::start_data_table().
 5864:                            &Apache::loncommon::start_data_table_row()
 5865:                            .'<td colspan="2"><span class="LC_nobreak"><label>'
 5866:                            .&mt('Any user in any domain:')
 5867:                            .'&nbsp;<input type="radio" name="selfenroll_all" value="1" ';
 5868:                 if ($curr_types eq '*') {
 5869:                     $output .= ' checked="checked" '; 
 5870:                 }
 5871:                 $output .= 'onchange="javascript:update_types('.
 5872:                            "'selfenroll_all'".');" />'.&mt('Yes').'</label>'.
 5873:                            '&nbsp;&nbsp;<input type="radio" name="selfenroll_all" value="0" ';
 5874:                 if ($curr_types ne '*') {
 5875:                     $output .= ' checked="checked" ';
 5876:                 }
 5877:                 $output .= ' onchange="javascript:update_types('.
 5878:                            "'selfenroll_all'".');"/>'.&mt('No').'</label></td>'.
 5879:                            &Apache::loncommon::end_data_table_row().
 5880:                            &Apache::loncommon::end_data_table().
 5881:                            &mt('Or').'<br />'.
 5882:                            &Apache::loncommon::start_data_table();
 5883:                 my %currdoms;
 5884:                 if ($curr_types eq '') {
 5885:                     $output .= &new_selfenroll_dom_row($cdom,'0');
 5886:                 } elsif ($curr_types ne '*') {
 5887:                     my @entries = split(/;/,$curr_types);
 5888:                     if (@entries > 0) {
 5889:                         foreach my $entry (@entries) {
 5890:                             my ($currdom,$typestr) = split(/:/,$entry);
 5891:                             $currdoms{$currdom} = 1;
 5892:                             my $domdesc = &Apache::lonnet::domain($currdom);
 5893:                             my @currinsttypes = split(',',$typestr);
 5894:                             $output .= &Apache::loncommon::start_data_table_row()
 5895:                                        .'<td valign="top"><span class="LC_nobreak">'.&mt('Domain:').'<b>'
 5896:                                        .'&nbsp;'.$domdesc.' ('.$currdom.')'
 5897:                                        .'</b><input type="hidden" name="selfenroll_dom_'.$num
 5898:                                        .'" value="'.$currdom.'" /></span><br />'
 5899:                                        .'<span class="LC_nobreak"><label><input type="checkbox" '
 5900:                                        .'name="selfenroll_delete" value="'.$num.'" onchange="javascript:update_types('."'selfenroll_delete','$num'".');" />'
 5901:                                        .&mt('Delete').'</label></span></td>';
 5902:                             $output .= '<td valign="top">&nbsp;&nbsp;'.&mt('User types:').'<br />'
 5903:                                        .&selfenroll_inst_types($num,$currdom,\@currinsttypes).'</td>'
 5904:                                        .&Apache::loncommon::end_data_table_row();
 5905:                             $num ++;
 5906:                         }
 5907:                     }
 5908:                 }
 5909:                 my $add_domtitle = &mt('Users in additional domain:');
 5910:                 if ($curr_types eq '*') { 
 5911:                     $add_domtitle = &mt('Users in specific domain:');
 5912:                 } elsif ($curr_types eq '') {
 5913:                     $add_domtitle = &mt('Users in other domain:');
 5914:                 }
 5915:                 $output .= &Apache::loncommon::start_data_table_row()
 5916:                            .'<td colspan="2"><span class="LC_nobreak">'.$add_domtitle.'</span><br />'
 5917:                            .&Apache::loncommon::select_dom_form('','selfenroll_newdom',
 5918:                                                                 $includeempty,$showdomdesc)
 5919:                            .'<input type="hidden" name="selfenroll_types_total" value="'.$num.'" />'
 5920:                            .'</td>'.&Apache::loncommon::end_data_table_row()
 5921:                            .&Apache::loncommon::end_data_table();
 5922:             } elsif ($item eq 'registered') {
 5923:                 my ($regon,$regoff);
 5924:                 my $registered;
 5925:                 if (ref($currsettings) eq 'HASH') {
 5926:                     $registered = $currsettings->{'selfenroll_registered'};
 5927:                 }
 5928:                 if ($noedit{$item}) {
 5929:                     if ($registered) {
 5930:                         $output .= &mt('Must be registered in course');
 5931:                     } else {
 5932:                         $output .= &mt('No requirement');
 5933:                     }
 5934:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 5935:                     next;
 5936:                 }
 5937:                 if ($registered) {
 5938:                     $regon = ' checked="checked" ';
 5939:                     $regoff = ' ';
 5940:                 } else {
 5941:                     $regon = ' ';
 5942:                     $regoff = ' checked="checked" ';
 5943:                 }
 5944:                 $output .= '<label>'.
 5945:                            '<input type="radio" name="selfenroll_registered" value="1"'.$regon.'/>'.
 5946:                            &mt('Yes').'</label>&nbsp;&nbsp;<label>'.
 5947:                            '<input type="radio" name="selfenroll_registered" value="0"'.$regoff.'/>'.
 5948:                            &mt('No').'</label>';
 5949:             } elsif ($item eq 'enroll_dates') {
 5950:                 my ($starttime,$endtime);
 5951:                 if (ref($currsettings) eq 'HASH') {
 5952:                     $starttime = $currsettings->{'selfenroll_start_date'};
 5953:                     $endtime = $currsettings->{'selfenroll_end_date'};
 5954:                     if ($starttime eq '') {
 5955:                         $starttime = $currsettings->{'default_enrollment_start_date'};
 5956:                     }
 5957:                     if ($endtime eq '') {
 5958:                         $endtime = $currsettings->{'default_enrollment_end_date'};
 5959:                     }
 5960:                 }
 5961:                 if ($noedit{$item}) {
 5962:                     $output .= &mt('From: [_1], to: [_2]',&Apache::lonlocal::locallocaltime($starttime),
 5963:                                                           &Apache::lonlocal::locallocaltime($endtime));
 5964:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 5965:                     next;
 5966:                 }
 5967:                 my $startform =
 5968:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_start_date',$starttime,
 5969:                                       undef,undef,undef,undef,undef,undef,undef,$nolink);
 5970:                 my $endform =
 5971:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_end_date',$endtime,
 5972:                                       undef,undef,undef,undef,undef,undef,undef,$nolink);
 5973:                 $output .= &selfenroll_date_forms($startform,$endform);
 5974:             } elsif ($item eq 'access_dates') {
 5975:                 my ($starttime,$endtime);
 5976:                 if (ref($currsettings) eq 'HASH') {
 5977:                     $starttime = $currsettings->{'selfenroll_start_access'};
 5978:                     $endtime = $currsettings->{'selfenroll_end_access'};
 5979:                     if ($starttime eq '') {
 5980:                         $starttime = $currsettings->{'default_enrollment_start_date'};
 5981:                     }
 5982:                     if ($endtime eq '') {
 5983:                         $endtime = $currsettings->{'default_enrollment_end_date'};
 5984:                     }
 5985:                 }
 5986:                 if ($noedit{$item}) {
 5987:                     $output .= &mt('From: [_1], to: [_2]',&Apache::lonlocal::locallocaltime($starttime),
 5988:                                                           &Apache::lonlocal::locallocaltime($endtime));
 5989:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 5990:                     next;
 5991:                 }
 5992:                 my $startform =
 5993:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_start_access',$starttime,
 5994:                                       undef,undef,undef,undef,undef,undef,undef,$nolink);
 5995:                 my $endform =
 5996:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_end_access',$endtime,
 5997:                                       undef,undef,undef,undef,undef,undef,undef,$nolink);
 5998:                 $output .= &selfenroll_date_forms($startform,$endform);
 5999:             } elsif ($item eq 'section') {
 6000:                 my $currsec;
 6001:                 if (ref($currsettings) eq 'HASH') {
 6002:                     $currsec = $currsettings->{'selfenroll_section'};
 6003:                 }
 6004:                 my %sections_count = &Apache::loncommon::get_sections($cdom,$cnum);
 6005:                 my $newsecval;
 6006:                 if ($currsec ne 'none' && $currsec ne '') {
 6007:                     if (!defined($sections_count{$currsec})) {
 6008:                         $newsecval = $currsec;
 6009:                     }
 6010:                 }
 6011:                 if ($noedit{$item}) {
 6012:                     if ($currsec ne '') {
 6013:                         $output .= $currsec;
 6014:                     } else {
 6015:                         $output .= &mt('No specific section');
 6016:                     }
 6017:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 6018:                     next;
 6019:                 }
 6020:                 my $sections_select = 
 6021:                     &Apache::lonuserutils::course_sections(\%sections_count,'st',$currsec);
 6022:                 $output .= '<table class="LC_createuser">'."\n".
 6023:                            '<tr class="LC_section_row">'."\n".
 6024:                            '<td align="center">'.&mt('Existing sections')."\n".
 6025:                            '<br />'.$sections_select.'</td><td align="center">'.
 6026:                            &mt('New section').'<br />'."\n".
 6027:                            '<input type="text" name="newsec" size="15" value="'.$newsecval.'" />'."\n".
 6028:                            '<input type="hidden" name="sections" value="" />'."\n".
 6029:                            '</td></tr></table>'."\n";
 6030:             } elsif ($item eq 'approval') {
 6031:                 my ($currnotified,$currapproval,%appchecked);
 6032:                 my %selfdescs = &Apache::lonuserutils::selfenroll_default_descs();
 6033:                 if (ref($currsettings) eq 'HASH') { 
 6034:                     $currnotified = $currsettings->{'selfenroll_notifylist'};
 6035:                     $currapproval = $currsettings->{'selfenroll_approval'};
 6036:                 }
 6037:                 if ($currapproval !~ /^[012]$/) {
 6038:                     $currapproval = 0;
 6039:                 }
 6040:                 if ($noedit{$item}) {
 6041:                     $output .=  $selfdescs{'approval'}{$currapproval}.
 6042:                                 '<br />'.&mt('(Set by Domain Coordinator)');
 6043:                     next;
 6044:                 }
 6045:                 $appchecked{$currapproval} = ' checked="checked"';
 6046:                 for my $i (0..2) {
 6047:                     $output .= '<label>'.
 6048:                                '<input type="radio" name="selfenroll_approval" value="'.$i.'"'.
 6049:                                $appchecked{$i}.' onclick="toggleNotify();" />'.$selfdescs{'approval'}{$i}.
 6050:                                '</label>'.('&nbsp;'x2);
 6051:                 }
 6052:                 my %advhash = &Apache::lonnet::get_course_adv_roles($cid,1);
 6053:                 my (@ccs,%notified);
 6054:                 my $ccrole = 'cc';
 6055:                 if ($crstype eq 'Community') {
 6056:                     $ccrole = 'co';
 6057:                 }
 6058:                 if ($advhash{$ccrole}) {
 6059:                     @ccs = split(/,/,$advhash{$ccrole});
 6060:                 }
 6061:                 if ($currnotified) {
 6062:                     foreach my $current (split(/,/,$currnotified)) {
 6063:                         $notified{$current} = 1;
 6064:                         if (!grep(/^\Q$current\E$/,@ccs)) {
 6065:                             push(@ccs,$current);
 6066:                         }
 6067:                     }
 6068:                 }
 6069:                 if (@ccs) {
 6070:                     my $style;
 6071:                     unless ($currapproval) {
 6072:                         $style = ' style="display: none;"'; 
 6073:                     }
 6074:                     $output .= '<br /><div id="notified"'.$style.'>'.
 6075:                                &mt('Personnel to be notified when an enrollment request needs approval, or has been approved:').'&nbsp;'.
 6076:                                &Apache::loncommon::start_data_table().
 6077:                                &Apache::loncommon::start_data_table_row();
 6078:                     my $count = 0;
 6079:                     my $numcols = 4;
 6080:                     foreach my $cc (sort(@ccs)) {
 6081:                         my $notifyon;
 6082:                         my ($ccuname,$ccudom) = split(/:/,$cc);
 6083:                         if ($notified{$cc}) {
 6084:                             $notifyon = ' checked="checked" ';
 6085:                         }
 6086:                         if ($count && !$count%$numcols) {
 6087:                             $output .= &Apache::loncommon::end_data_table_row().
 6088:                                        &Apache::loncommon::start_data_table_row()
 6089:                         }
 6090:                         $output .= '<td><span class="LC_nobreak"><label>'.
 6091:                                    '<input type="checkbox" name="selfenroll_notify"'.$notifyon.' value="'.$cc.'" />'.
 6092:                                    &Apache::loncommon::plainname($ccuname,$ccudom).
 6093:                                    '</label></span></td>';
 6094:                         $count ++;
 6095:                     }
 6096:                     my $rem = $count%$numcols;
 6097:                     if ($rem) {
 6098:                         my $emptycols = $numcols - $rem;
 6099:                         for (my $i=0; $i<$emptycols; $i++) { 
 6100:                             $output .= '<td>&nbsp;</td>';
 6101:                         }
 6102:                     }
 6103:                     $output .= &Apache::loncommon::end_data_table_row().
 6104:                                &Apache::loncommon::end_data_table().
 6105:                                '</div>';
 6106:                 }
 6107:             } elsif ($item eq 'limit') {
 6108:                 my ($crslimit,$selflimit,$nolimit,$currlim,$currcap);
 6109:                 if (ref($currsettings) eq 'HASH') {
 6110:                     $currlim = $currsettings->{'selfenroll_limit'};
 6111:                     $currcap = $currsettings->{'selfenroll_cap'};
 6112:                 }
 6113:                 if ($noedit{$item}) {
 6114:                     if (($currlim eq 'allstudents') || ($currlim eq 'selfenrolled')) {
 6115:                         if ($currlim eq 'allstudents') {
 6116:                             $output .= &mt('Limit by total students');
 6117:                         } elsif ($currlim eq 'selfenrolled') {
 6118:                             $output .= &mt('Limit by total self-enrolled students');
 6119:                         }
 6120:                         $output .= ' '.&mt('Maximum: [_1]',$currcap).
 6121:                                    '<br />'.&mt('(Set by Domain Coordinator)');
 6122:                     } else {
 6123:                         $output .= &mt('No limit').'<br />'.&mt('(Set by Domain Coordinator)');
 6124:                     }
 6125:                     next;
 6126:                 }
 6127:                 if ($currlim eq 'allstudents') {
 6128:                     $crslimit = ' checked="checked" ';
 6129:                     $selflimit = ' ';
 6130:                     $nolimit = ' ';
 6131:                 } elsif ($currlim eq 'selfenrolled') {
 6132:                     $crslimit = ' ';
 6133:                     $selflimit = ' checked="checked" ';
 6134:                     $nolimit = ' '; 
 6135:                 } else {
 6136:                     $crslimit = ' ';
 6137:                     $selflimit = ' ';
 6138:                     $nolimit = ' checked="checked" ';
 6139:                 }
 6140:                 $output .= '<table><tr><td><label>'.
 6141:                            '<input type="radio" name="selfenroll_limit" value="none"'.$nolimit.'/>'.
 6142:                            &mt('No limit').'</label></td><td><label>'.
 6143:                            '<input type="radio" name="selfenroll_limit" value="allstudents"'.$crslimit.'/>'.
 6144:                            &mt('Limit by total students').'</label></td><td><label>'.
 6145:                            '<input type="radio" name="selfenroll_limit" value="selfenrolled"'.$selflimit.'/>'.
 6146:                            &mt('Limit by total self-enrolled students').
 6147:                            '</td></tr><tr>'.
 6148:                            '<td>&nbsp;</td><td colspan="2"><span class="LC_nobreak">'.
 6149:                            ('&nbsp;'x3).&mt('Maximum number allowed: ').
 6150:                            '<input type="text" name="selfenroll_cap" size = "5" value="'.$currcap.'" /></td></tr></table>';
 6151:             }
 6152:             $output .= &Apache::lonhtmlcommon::row_closure(1);
 6153:         }
 6154:     }
 6155:     $output .= &Apache::lonhtmlcommon::end_pick_box().
 6156:                '<br /><input type="button" name="selfenrollconf" value="'
 6157:                .&mt('Save').'" onclick="validate_types(this.form);" />'
 6158:                .'<input type="hidden" name="action" value="selfenroll" />'
 6159:                .'<input type="hidden" name="state" value="done" />'."\n".
 6160:                $additional.'</form>';
 6161:     $r->print($output);
 6162:     return;
 6163: }
 6164: 
 6165: sub get_noedit_fields {
 6166:     my ($cdom,$cnum,$crstype,$row) = @_;
 6167:     my %noedit;
 6168:     if (ref($row) eq 'ARRAY') {
 6169:         my %settings = &Apache::lonnet::get('environment',['internal.coursecode','internal.textbook',
 6170:                                                            'internal.selfenrollmgrdc',
 6171:                                                            'internal.selfenrollmgrcc'],$cdom,$cnum);
 6172:         my $type = &Apache::lonuserutils::get_extended_type($cdom,$cnum,$crstype,\%settings);
 6173:         my (%specific_managebydc,%specific_managebycc,%default_managebydc);
 6174:         map { $specific_managebydc{$_} = 1; } (split(/,/,$settings{'internal.selfenrollmgrdc'}));
 6175:         map { $specific_managebycc{$_} = 1; } (split(/,/,$settings{'internal.selfenrollmgrcc'}));
 6176:         my %domdefaults = &Apache::lonnet::get_domain_defaults($cdom);
 6177:         map { $default_managebydc{$_} = 1; } (split(/,/,$domdefaults{$type.'selfenrolladmdc'}));
 6178: 
 6179:         foreach my $item (@{$row}) {
 6180:             next if ($specific_managebycc{$item});
 6181:             if (($specific_managebydc{$item}) || ($default_managebydc{$item})) {
 6182:                 $noedit{$item} = 1;
 6183:             }
 6184:         }
 6185:     }
 6186:     return %noedit;
 6187: } 
 6188: 
 6189: sub visible_in_stdcat {
 6190:     my ($cdom,$cnum,$domconf) = @_;
 6191:     my ($cathash,%settable,@vismsgs,$cansetvis,$visible);
 6192:     unless (ref($domconf) eq 'HASH') {
 6193:         return ($visible,$cansetvis,\@vismsgs);
 6194:     }
 6195:     if (ref($domconf->{'coursecategories'}) eq 'HASH') {
 6196:         if ($domconf->{'coursecategories'}{'togglecats'} eq 'crs') {
 6197:             $settable{'togglecats'} = 1;
 6198:         }
 6199:         if ($domconf->{'coursecategories'}{'categorize'} eq 'crs') {
 6200:             $settable{'categorize'} = 1;
 6201:         }
 6202:         $cathash = $domconf->{'coursecategories'}{'cats'};
 6203:     }
 6204:     if ($settable{'togglecats'} && $settable{'categorize'}) {
 6205:         $cansetvis = &mt('You are able to both assign a course category and choose to exclude this course from the catalog.');   
 6206:     } elsif ($settable{'togglecats'}) {
 6207:         $cansetvis = &mt('You are able to choose to exclude this course from the catalog, but only a Domain Coordinator may assign a course category.'); 
 6208:     } elsif ($settable{'categorize'}) {
 6209:         $cansetvis = &mt('You may assign a course category, but only a Domain Coordinator may choose to exclude this course from the catalog.');  
 6210:     } else {
 6211:         $cansetvis = &mt('Only a Domain Coordinator may assign a course category or choose to exclude this course from the catalog.'); 
 6212:     }
 6213:      
 6214:     my %currsettings =
 6215:         &Apache::lonnet::get('environment',['hidefromcat','categories','internal.coursecode'],
 6216:                              $cdom,$cnum);
 6217:     $visible = 0;
 6218:     if ($currsettings{'internal.coursecode'} ne '') {
 6219:         if (ref($domconf->{'coursecategories'}) eq 'HASH') {
 6220:             $cathash = $domconf->{'coursecategories'}{'cats'};
 6221:             if (ref($cathash) eq 'HASH') {
 6222:                 if ($cathash->{'instcode::0'} eq '') {
 6223:                     push(@vismsgs,'dc_addinst'); 
 6224:                 } else {
 6225:                     $visible = 1;
 6226:                 }
 6227:             } else {
 6228:                 $visible = 1;
 6229:             }
 6230:         } else {
 6231:             $visible = 1;
 6232:         }
 6233:     } else {
 6234:         if (ref($cathash) eq 'HASH') {
 6235:             if ($cathash->{'instcode::0'} ne '') {
 6236:                 push(@vismsgs,'dc_instcode');
 6237:             }
 6238:         } else {
 6239:             push(@vismsgs,'dc_instcode');
 6240:         }
 6241:     }
 6242:     if ($currsettings{'categories'} ne '') {
 6243:         my $cathash;
 6244:         if (ref($domconf->{'coursecategories'}) eq 'HASH') {
 6245:             $cathash = $domconf->{'coursecategories'}{'cats'};
 6246:             if (ref($cathash) eq 'HASH') {
 6247:                 if (keys(%{$cathash}) == 0) {
 6248:                     push(@vismsgs,'dc_catalog');
 6249:                 } elsif ((keys(%{$cathash}) == 1) && ($cathash->{'instcode::0'} ne '')) {
 6250:                     push(@vismsgs,'dc_categories');
 6251:                 } else {
 6252:                     my @currcategories = split('&',$currsettings{'categories'});
 6253:                     my $matched = 0;
 6254:                     foreach my $cat (@currcategories) {
 6255:                         if ($cathash->{$cat} ne '') {
 6256:                             $visible = 1;
 6257:                             $matched = 1;
 6258:                             last;
 6259:                         }
 6260:                     }
 6261:                     if (!$matched) {
 6262:                         if ($settable{'categorize'}) { 
 6263:                             push(@vismsgs,'chgcat');
 6264:                         } else {
 6265:                             push(@vismsgs,'dc_chgcat');
 6266:                         }
 6267:                     }
 6268:                 }
 6269:             }
 6270:         }
 6271:     } else {
 6272:         if (ref($cathash) eq 'HASH') {
 6273:             if ((keys(%{$cathash}) > 1) || 
 6274:                 (keys(%{$cathash}) == 1) && ($cathash->{'instcode::0'} eq '')) {
 6275:                 if ($settable{'categorize'}) {
 6276:                     push(@vismsgs,'addcat');
 6277:                 } else {
 6278:                     push(@vismsgs,'dc_addcat');
 6279:                 }
 6280:             }
 6281:         }
 6282:     }
 6283:     if ($currsettings{'hidefromcat'} eq 'yes') {
 6284:         $visible = 0;
 6285:         if ($settable{'togglecats'}) {
 6286:             unshift(@vismsgs,'unhide');
 6287:         } else {
 6288:             unshift(@vismsgs,'dc_unhide')
 6289:         }
 6290:     }
 6291:     return ($visible,$cansetvis,\@vismsgs);
 6292: }
 6293: 
 6294: sub cat_visibility {
 6295:     my %visactions = &Apache::lonlocal::texthash(
 6296:                    vis => 'This course/community currently appears in the Course/Community Catalog for this domain.',
 6297:                    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.',
 6298:                    miss => 'This course/community does not currently appear in the Course/Community Catalog for this domain.',
 6299:                    none => 'Display of a course catalog is disabled for this domain.',
 6300:                    yous => 'You should remedy this if you plan to allow self-enrollment, otherwise students will have difficulty finding this course.',
 6301:                    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.',
 6302:                    make => 'Make any changes to self-enrollment settings below, click "Save", then take action to include the course in the Catalog:',
 6303:                    take => 'Take the following action to ensure the course appears in the Catalog:',
 6304:                    dc_chgconf => 'Ask a domain coordinator to change the Catalog type for this domain.',
 6305:                    dc_setcode => 'Ask a domain coordinator to assign a six character code to the course',
 6306:                    dc_unhide  => 'Ask a domain coordinator to change the "Exclude from course catalog" setting.',
 6307:                    dc_addinst => 'Ask a domain coordinator to enable display the catalog of "Official courses (with institutional codes)".',
 6308:                    dc_instcode => 'Ask a domain coordinator to assign an institutional code (if this is an official course).',
 6309:                    dc_catalog  => 'Ask a domain coordinator to enable or create at least one course category in the domain.',
 6310:                    dc_categories => 'Ask a domain coordinator to create a hierarchy of categories and sub categories for courses in the domain.',
 6311:                    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',
 6312:                    dc_addcat => 'Ask a domain coordinator to assign a category to the course.',
 6313:     );
 6314:     $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>"');
 6315:     $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>"');
 6316:     $visactions{'addcat'} = &mt('Use [_1]Categorize course[_2] to assign a category to the course.','"<a href="/adm/courseprefs?phase=display&actions=courseinfo">','</a>"');
 6317:     return \%visactions;
 6318: }
 6319: 
 6320: sub new_selfenroll_dom_row {
 6321:     my ($newdom,$num) = @_;
 6322:     my $domdesc = &Apache::lonnet::domain($newdom);
 6323:     my $output;
 6324:     if ($domdesc ne '') {
 6325:         $output .= &Apache::loncommon::start_data_table_row()
 6326:                    .'<td valign="top"><span class="LC_nobreak">'.&mt('Domain:').'&nbsp;<b>'.$domdesc
 6327:                    .' ('.$newdom.')</b><input type="hidden" name="selfenroll_dom_'.$num
 6328:                    .'" value="'.$newdom.'" /></span><br />'
 6329:                    .'<span class="LC_nobreak"><label><input type="checkbox" '
 6330:                    .'name="selfenroll_activate" value="'.$num.'" '
 6331:                    .'onchange="javascript:update_types('
 6332:                    ."'selfenroll_activate','$num'".');" />'
 6333:                    .&mt('Activate').'</label></span></td>';
 6334:         my @currinsttypes;
 6335:         $output .= '<td>'.&mt('User types:').'<br />'
 6336:                    .&selfenroll_inst_types($num,$newdom,\@currinsttypes).'</td>'
 6337:                    .&Apache::loncommon::end_data_table_row();
 6338:     }
 6339:     return $output;
 6340: }
 6341: 
 6342: sub selfenroll_inst_types {
 6343:     my ($num,$currdom,$currinsttypes) = @_;
 6344:     my $output;
 6345:     my $numinrow = 4;
 6346:     my $count = 0;
 6347:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($currdom);
 6348:     my $othervalue = 'any';
 6349:     if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 6350:         if (keys(%{$usertypes}) > 0) {
 6351:             $othervalue = 'other';
 6352:         }
 6353:         $output .= '<table><tr>';
 6354:         foreach my $type (@{$types}) {
 6355:             if (($count > 0) && ($count%$numinrow == 0)) {
 6356:                 $output .= '</tr><tr>';
 6357:             }
 6358:             if (defined($usertypes->{$type})) {
 6359:                 my $esc_type = &escape($type);
 6360:                 $output .= '<td><span class="LC_nobreak"><label><input type = "checkbox" value="'.
 6361:                            $esc_type.'" ';
 6362:                 if (ref($currinsttypes) eq 'ARRAY') {
 6363:                     if (@{$currinsttypes} > 0) {
 6364:                         if (grep(/^any$/,@{$currinsttypes})) {
 6365:                             $output .= 'checked="checked"';
 6366:                         } elsif (grep(/^\Q$esc_type\E$/,@{$currinsttypes})) {
 6367:                             $output .= 'checked="checked"';
 6368:                         }
 6369:                     } else {
 6370:                         $output .= 'checked="checked"';
 6371:                     }
 6372:                 }
 6373:                 $output .= ' name="selfenroll_types_'.$num.'" />'.$usertypes->{$type}.'</label></span></td>';
 6374:             }
 6375:             $count ++;
 6376:         }
 6377:         if (($count > 0) && ($count%$numinrow == 0)) {
 6378:             $output .= '</tr><tr>';
 6379:         }
 6380:         $output .= '<td><span class="LC_nobreak"><label><input type = "checkbox" value="'.$othervalue.'"';
 6381:         if (ref($currinsttypes) eq 'ARRAY') {
 6382:             if (@{$currinsttypes} > 0) {
 6383:                 if (grep(/^any$/,@{$currinsttypes})) { 
 6384:                     $output .= ' checked="checked"';
 6385:                 } elsif ($othervalue eq 'other') {
 6386:                     if (grep(/^\Q$othervalue\E$/,@{$currinsttypes})) {
 6387:                         $output .= ' checked="checked"';
 6388:                     }
 6389:                 }
 6390:             } else {
 6391:                 $output .= ' checked="checked"';
 6392:             }
 6393:         } else {
 6394:             $output .= ' checked="checked"';
 6395:         }
 6396:         $output .= ' name="selfenroll_types_'.$num.'" />'.$othertitle.'</label></span></td></tr></table>';
 6397:     }
 6398:     return $output;
 6399: }
 6400: 
 6401: sub selfenroll_date_forms {
 6402:     my ($startform,$endform) = @_;
 6403:     my $output .= &Apache::lonhtmlcommon::start_pick_box()."\n".
 6404:                   &Apache::lonhtmlcommon::row_title(&mt('Start date'),
 6405:                                                     'LC_oddrow_value')."\n".
 6406:                   $startform."\n".
 6407:                   &Apache::lonhtmlcommon::row_closure(1).
 6408:                   &Apache::lonhtmlcommon::row_title(&mt('End date'),
 6409:                                                    'LC_oddrow_value')."\n".
 6410:                   $endform."\n".
 6411:                   &Apache::lonhtmlcommon::row_closure(1).
 6412:                   &Apache::lonhtmlcommon::end_pick_box();
 6413:     return $output;
 6414: }
 6415: 
 6416: sub print_userchangelogs_display {
 6417:     my ($r,$context,$permission) = @_;
 6418:     my $formname = 'rolelog';
 6419:     my ($username,$domain,$crstype,%roleslog);
 6420:     if ($context eq 'domain') {
 6421:         $domain = $env{'request.role.domain'};
 6422:         %roleslog=&Apache::lonnet::dump_dom('nohist_rolelog',$domain);
 6423:     } else {
 6424:         if ($context eq 'course') { 
 6425:             $domain = $env{'course.'.$env{'request.course.id'}.'.domain'};
 6426:             $username = $env{'course.'.$env{'request.course.id'}.'.num'};
 6427:             $crstype = &Apache::loncommon::course_type();
 6428:             my %saveable_parameters = ('show' => 'scalar',);
 6429:             &Apache::loncommon::store_course_settings('roles_log',
 6430:                                                       \%saveable_parameters);
 6431:             &Apache::loncommon::restore_course_settings('roles_log',
 6432:                                                         \%saveable_parameters);
 6433:         } elsif ($context eq 'author') {
 6434:             $domain = $env{'user.domain'}; 
 6435:             if ($env{'request.role'} =~ m{^au\./\Q$domain\E/$}) {
 6436:                 $username = $env{'user.name'};
 6437:             } else {
 6438:                 undef($domain);
 6439:             }
 6440:         }
 6441:         if ($domain ne '' && $username ne '') { 
 6442:             %roleslog=&Apache::lonnet::dump('nohist_rolelog',$domain,$username);
 6443:         }
 6444:     }
 6445:     if ((keys(%roleslog))[0]=~/^error\:/) { undef(%roleslog); }
 6446: 
 6447:     # set defaults
 6448:     my $now = time();
 6449:     my $defstart = $now - (7*24*3600); #7 days ago 
 6450:     my %defaults = (
 6451:                      page               => '1',
 6452:                      show               => '10',
 6453:                      role               => 'any',
 6454:                      chgcontext         => 'any',
 6455:                      rolelog_start_date => $defstart,
 6456:                      rolelog_end_date   => $now,
 6457:                    );
 6458:     my $more_records = 0;
 6459: 
 6460:     # set current
 6461:     my %curr;
 6462:     foreach my $item ('show','page','role','chgcontext') {
 6463:         $curr{$item} = $env{'form.'.$item};
 6464:     }
 6465:     my ($startdate,$enddate) = 
 6466:         &Apache::lonuserutils::get_dates_from_form('rolelog_start_date','rolelog_end_date');
 6467:     $curr{'rolelog_start_date'} = $startdate;
 6468:     $curr{'rolelog_end_date'} = $enddate;
 6469:     foreach my $key (keys(%defaults)) {
 6470:         if ($curr{$key} eq '') {
 6471:             $curr{$key} = $defaults{$key};
 6472:         }
 6473:     }
 6474:     my (%whodunit,%changed,$version);
 6475:     ($version) = ($r->dir_config('lonVersion') =~ /^([\d\.]+)\-/);
 6476:     my ($minshown,$maxshown);
 6477:     $minshown = 1;
 6478:     my $count = 0;
 6479:     if ($curr{'show'} ne &mt('all')) { 
 6480:         $maxshown = $curr{'page'} * $curr{'show'};
 6481:         if ($curr{'page'} > 1) {
 6482:             $minshown = 1 + ($curr{'page'} - 1) * $curr{'show'};
 6483:         }
 6484:     }
 6485: 
 6486:     # Form Header
 6487:     $r->print('<form action="/adm/createuser" method="post" name="'.$formname.'">'.
 6488:               &role_display_filter($context,$formname,$domain,$username,\%curr,
 6489:                                    $version,$crstype));
 6490: 
 6491:     # Create navigation
 6492:     my ($nav_script,$nav_links) = &userlogdisplay_nav($formname,\%curr,$more_records);
 6493:     my $showntableheader = 0;
 6494: 
 6495:     # Table Header
 6496:     my $tableheader = 
 6497:         &Apache::loncommon::start_data_table_header_row()
 6498:        .'<th>&nbsp;</th>'
 6499:        .'<th>'.&mt('When').'</th>'
 6500:        .'<th>'.&mt('Who made the change').'</th>'
 6501:        .'<th>'.&mt('Changed User').'</th>'
 6502:        .'<th>'.&mt('Role').'</th>';
 6503: 
 6504:     if ($context eq 'course') {
 6505:         $tableheader .= '<th>'.&mt('Section').'</th>';
 6506:     }
 6507:     $tableheader .=
 6508:         '<th>'.&mt('Context').'</th>'
 6509:        .'<th>'.&mt('Start').'</th>'
 6510:        .'<th>'.&mt('End').'</th>'
 6511:        .&Apache::loncommon::end_data_table_header_row();
 6512: 
 6513:     # Display user change log data
 6514:     foreach my $id (sort { $roleslog{$b}{'exe_time'}<=>$roleslog{$a}{'exe_time'} } (keys(%roleslog))) {
 6515:         next if (($roleslog{$id}{'exe_time'} < $curr{'rolelog_start_date'}) ||
 6516:                  ($roleslog{$id}{'exe_time'} > $curr{'rolelog_end_date'}));
 6517:         if ($curr{'show'} ne &mt('all')) {
 6518:             if ($count >= $curr{'page'} * $curr{'show'}) {
 6519:                 $more_records = 1;
 6520:                 last;
 6521:             }
 6522:         }
 6523:         if ($curr{'role'} ne 'any') {
 6524:             next if ($roleslog{$id}{'logentry'}{'role'} ne $curr{'role'}); 
 6525:         }
 6526:         if ($curr{'chgcontext'} ne 'any') {
 6527:             if ($curr{'chgcontext'} eq 'selfenroll') {
 6528:                 next if (!$roleslog{$id}{'logentry'}{'selfenroll'});
 6529:             } else {
 6530:                 next if ($roleslog{$id}{'logentry'}{'context'} ne $curr{'chgcontext'});
 6531:             }
 6532:         }
 6533:         $count ++;
 6534:         next if ($count < $minshown);
 6535:         unless ($showntableheader) {
 6536:             $r->print($nav_script
 6537:                      .$nav_links
 6538:                      .&Apache::loncommon::start_data_table()
 6539:                      .$tableheader);
 6540:             $r->rflush();
 6541:             $showntableheader = 1;
 6542:         }
 6543:         if ($whodunit{$roleslog{$id}{'exe_uname'}.':'.$roleslog{$id}{'exe_udom'}} eq '') {
 6544:             $whodunit{$roleslog{$id}{'exe_uname'}.':'.$roleslog{$id}{'exe_udom'}} =
 6545:                 &Apache::loncommon::plainname($roleslog{$id}{'exe_uname'},$roleslog{$id}{'exe_udom'});
 6546:         }
 6547:         if ($changed{$roleslog{$id}{'uname'}.':'.$roleslog{$id}{'udom'}} eq '') {
 6548:             $changed{$roleslog{$id}{'uname'}.':'.$roleslog{$id}{'udom'}} =
 6549:                 &Apache::loncommon::plainname($roleslog{$id}{'uname'},$roleslog{$id}{'udom'});
 6550:         }
 6551:         my $sec = $roleslog{$id}{'logentry'}{'section'};
 6552:         if ($sec eq '') {
 6553:             $sec = &mt('None');
 6554:         }
 6555:         my ($rolestart,$roleend);
 6556:         if ($roleslog{$id}{'delflag'}) {
 6557:             $rolestart = &mt('deleted');
 6558:             $roleend = &mt('deleted');
 6559:         } else {
 6560:             $rolestart = $roleslog{$id}{'logentry'}{'start'};
 6561:             $roleend = $roleslog{$id}{'logentry'}{'end'};
 6562:             if ($rolestart eq '' || $rolestart == 0) {
 6563:                 $rolestart = &mt('No start date'); 
 6564:             } else {
 6565:                 $rolestart = &Apache::lonlocal::locallocaltime($rolestart);
 6566:             }
 6567:             if ($roleend eq '' || $roleend == 0) { 
 6568:                 $roleend = &mt('No end date');
 6569:             } else {
 6570:                 $roleend = &Apache::lonlocal::locallocaltime($roleend);
 6571:             }
 6572:         }
 6573:         my $chgcontext = $roleslog{$id}{'logentry'}{'context'};
 6574:         if ($roleslog{$id}{'logentry'}{'selfenroll'}) {
 6575:             $chgcontext = 'selfenroll';
 6576:         }
 6577:         my %lt = &rolechg_contexts($context,$crstype);
 6578:         if ($chgcontext ne '' && $lt{$chgcontext} ne '') {
 6579:             $chgcontext = $lt{$chgcontext};
 6580:         }
 6581:         $r->print(
 6582:             &Apache::loncommon::start_data_table_row()
 6583:            .'<td>'.$count.'</td>'
 6584:            .'<td>'.&Apache::lonlocal::locallocaltime($roleslog{$id}{'exe_time'}).'</td>'
 6585:            .'<td>'.$whodunit{$roleslog{$id}{'exe_uname'}.':'.$roleslog{$id}{'exe_udom'}}.'</td>'
 6586:            .'<td>'.$changed{$roleslog{$id}{'uname'}.':'.$roleslog{$id}{'udom'}}.'</td>'
 6587:            .'<td>'.&Apache::lonnet::plaintext($roleslog{$id}{'logentry'}{'role'},$crstype).'</td>');
 6588:         if ($context eq 'course') { 
 6589:             $r->print('<td>'.$sec.'</td>');
 6590:         }
 6591:         $r->print(
 6592:             '<td>'.$chgcontext.'</td>'
 6593:            .'<td>'.$rolestart.'</td>'
 6594:            .'<td>'.$roleend.'</td>'
 6595:            .&Apache::loncommon::end_data_table_row()."\n");
 6596:     }
 6597: 
 6598:     if ($showntableheader) { # Table footer, if content displayed above
 6599:         $r->print(&Apache::loncommon::end_data_table()
 6600:                  .$nav_links);
 6601:     } else { # No content displayed above
 6602:         $r->print('<p class="LC_info">'
 6603:                  .&mt('There are no records to display.')
 6604:                  .'</p>'
 6605:         );
 6606:     }
 6607: 
 6608:     # Form Footer
 6609:     $r->print( 
 6610:         '<input type="hidden" name="page" value="'.$curr{'page'}.'" />'
 6611:        .'<input type="hidden" name="action" value="changelogs" />'
 6612:        .'</form>');
 6613:     return;
 6614: }
 6615: 
 6616: sub userlogdisplay_nav {
 6617:     my ($formname,$curr,$more_records) = @_;
 6618:     my ($nav_script,$nav_links);
 6619:     if (ref($curr) eq 'HASH') {
 6620:         # Create Navigation:
 6621:         # Navigation Script
 6622:         $nav_script = <<"ENDSCRIPT";
 6623: <script type="text/javascript">
 6624: // <![CDATA[
 6625: function chgPage(caller) {
 6626:     if (caller == 'previous') {
 6627:         document.$formname.page.value --;
 6628:     }
 6629:     if (caller == 'next') {
 6630:         document.$formname.page.value ++;
 6631:     }
 6632:     document.$formname.submit();
 6633:     return;
 6634: }
 6635: // ]]>
 6636: </script>
 6637: ENDSCRIPT
 6638:         # Navigation Buttons
 6639:         $nav_links = '<p>';
 6640:         if (($curr->{'page'} > 1) || ($more_records)) {
 6641:             if ($curr->{'page'} > 1) {
 6642:                 $nav_links .= '<input type="button"'
 6643:                              .' onclick="javascript:chgPage('."'previous'".');"'
 6644:                              .' value="'.&mt('Previous [_1] changes',$curr->{'show'})
 6645:                              .'" /> ';
 6646:             }
 6647:             if ($more_records) {
 6648:                 $nav_links .= '<input type="button"'
 6649:                              .' onclick="javascript:chgPage('."'next'".');"'
 6650:                              .' value="'.&mt('Next [_1] changes',$curr->{'show'})
 6651:                              .'" />';
 6652:             }
 6653:         }
 6654:         $nav_links .= '</p>';
 6655:     }
 6656:     return ($nav_script,$nav_links);
 6657: }
 6658: 
 6659: sub role_display_filter {
 6660:     my ($context,$formname,$cdom,$cnum,$curr,$version,$crstype) = @_;
 6661:     my $lctype;
 6662:     if ($context eq 'course') {
 6663:         $lctype = lc($crstype);
 6664:     }
 6665:     my $nolink = 1;
 6666:     my $output = '<table><tr><td valign="top">'.
 6667:                  '<span class="LC_nobreak"><b>'.&mt('Changes/page:').'</b></span><br />'.
 6668:                  &Apache::lonmeta::selectbox('show',$curr->{'show'},undef,
 6669:                                               (&mt('all'),5,10,20,50,100,1000,10000)).
 6670:                  '</td><td>&nbsp;&nbsp;</td>';
 6671:     my $startform =
 6672:         &Apache::lonhtmlcommon::date_setter($formname,'rolelog_start_date',
 6673:                                             $curr->{'rolelog_start_date'},undef,
 6674:                                             undef,undef,undef,undef,undef,undef,$nolink);
 6675:     my $endform =
 6676:         &Apache::lonhtmlcommon::date_setter($formname,'rolelog_end_date',
 6677:                                             $curr->{'rolelog_end_date'},undef,
 6678:                                             undef,undef,undef,undef,undef,undef,$nolink);
 6679:     my %lt = &rolechg_contexts($context,$crstype);
 6680:     $output .= '<td valign="top"><b>'.&mt('Window during which changes occurred:').'</b><br />'.
 6681:                '<table><tr><td>'.&mt('After:').
 6682:                '</td><td>'.$startform.'</td></tr>'.
 6683:                '<tr><td>'.&mt('Before:').'</td>'.
 6684:                '<td>'.$endform.'</td></tr></table>'.
 6685:                '</td>'.
 6686:                '<td>&nbsp;&nbsp;</td>'.
 6687:                '<td valign="top"><b>'.&mt('Role:').'</b><br />'.
 6688:                '<select name="role"><option value="any"';
 6689:     if ($curr->{'role'} eq 'any') {
 6690:         $output .= ' selected="selected"';
 6691:     }
 6692:     $output .=  '>'.&mt('Any').'</option>'."\n";
 6693:     my @roles = &Apache::lonuserutils::roles_by_context($context,1,$crstype);
 6694:     foreach my $role (@roles) {
 6695:         my $plrole;
 6696:         if ($role eq 'cr') {
 6697:             $plrole = &mt('Custom Role');
 6698:         } else {
 6699:             $plrole=&Apache::lonnet::plaintext($role,$crstype);
 6700:         }
 6701:         my $selstr = '';
 6702:         if ($role eq $curr->{'role'}) {
 6703:             $selstr = ' selected="selected"';
 6704:         }
 6705:         $output .= '  <option value="'.$role.'"'.$selstr.'>'.$plrole.'</option>';
 6706:     }
 6707:     $output .= '</select></td>'.
 6708:                '<td>&nbsp;&nbsp;</td>'.
 6709:                '<td valign="top"><b>'.
 6710:                &mt('Context:').'</b><br /><select name="chgcontext">';
 6711:     my @posscontexts;
 6712:     if ($context eq 'course') {
 6713:         @posscontexts = ('any','automated','updatenow','createcourse','course','domain','selfenroll','requestcourses');
 6714:     } elsif ($context eq 'domain') {
 6715:         @posscontexts = ('any','domain','requestauthor','domconfig','server');
 6716:     } else {
 6717:         @posscontexts = ('any','author','domain');
 6718:     } 
 6719:     foreach my $chgtype (@posscontexts) {
 6720:         my $selstr = '';
 6721:         if ($curr->{'chgcontext'} eq $chgtype) {
 6722:             $selstr = ' selected="selected"';
 6723:         }
 6724:         if ($context eq 'course') {
 6725:             if (($chgtype eq 'automated') || ($chgtype eq 'updatenow')) {
 6726:                 next if (!&Apache::lonnet::auto_run($cnum,$cdom));
 6727:             }
 6728:         }
 6729:         $output .= '<option value="'.$chgtype.'"'.$selstr.'>'.$lt{$chgtype}.'</option>'."\n";
 6730:     }
 6731:     $output .= '</select></td>'
 6732:               .'</tr></table>';
 6733: 
 6734:     # Update Display button
 6735:     $output .= '<p>'
 6736:               .'<input type="submit" value="'.&mt('Update Display').'" />'
 6737:               .'</p>';
 6738: 
 6739:     # Server version info
 6740:     my $needsrev = '2.11.0';
 6741:     if ($context eq 'course') {
 6742:         $needsrev = '2.7.0';
 6743:     }
 6744:     
 6745:     $output .= '<p class="LC_info">'
 6746:               .&mt('Only changes made from servers running LON-CAPA [_1] or later are displayed.'
 6747:                   ,$needsrev);
 6748:     if ($version) {
 6749:         $output .= ' '.&mt('This LON-CAPA server is version [_1]',$version);
 6750:     }
 6751:     $output .= '</p><hr />';
 6752:     return $output;
 6753: }
 6754: 
 6755: sub rolechg_contexts {
 6756:     my ($context,$crstype) = @_;
 6757:     my %lt;
 6758:     if ($context eq 'course') {
 6759:         %lt = &Apache::lonlocal::texthash (
 6760:                                              any          => 'Any',
 6761:                                              automated    => 'Automated Enrollment',
 6762:                                              updatenow    => 'Roster Update',
 6763:                                              createcourse => 'Course Creation',
 6764:                                              course       => 'User Management in course',
 6765:                                              domain       => 'User Management in domain',
 6766:                                              selfenroll   => 'Self-enrolled',
 6767:                                              requestcourses => 'Course Request',
 6768:                                          );
 6769:         if ($crstype eq 'Community') {
 6770:             $lt{'createcourse'} = &mt('Community Creation');
 6771:             $lt{'course'} = &mt('User Management in community');
 6772:             $lt{'requestcourses'} = &mt('Community Request');
 6773:         }
 6774:     } elsif ($context eq 'domain') {
 6775:         %lt = &Apache::lonlocal::texthash (
 6776:                                              any           => 'Any',
 6777:                                              domain        => 'User Management in domain',
 6778:                                              requestauthor => 'Authoring Request',
 6779:                                              server        => 'Command line script (DC role)',
 6780:                                              domconfig     => 'Self-enrolled',
 6781:                                          );
 6782:     } else {
 6783:         %lt = &Apache::lonlocal::texthash (
 6784:                                              any    => 'Any',
 6785:                                              domain => 'User Management in domain',
 6786:                                              author => 'User Management by author',
 6787:                                          );
 6788:     } 
 6789:     return %lt;
 6790: }
 6791: 
 6792: #-------------------------------------------------- functions for &phase_two
 6793: sub user_search_result {
 6794:     my ($context,$srch) = @_;
 6795:     my %allhomes;
 6796:     my %inst_matches;
 6797:     my %srch_results;
 6798:     my ($response,$currstate,$forcenewuser,$dirsrchres);
 6799:     $srch->{'srchterm'} =~ s/\s+/ /g;
 6800:     if ($srch->{'srchby'} !~ /^(uname|lastname|lastfirst)$/) {
 6801:         $response = &mt('Invalid search.');
 6802:     }
 6803:     if ($srch->{'srchin'} !~ /^(crs|dom|alc|instd)$/) {
 6804:         $response = &mt('Invalid search.');
 6805:     }
 6806:     if ($srch->{'srchtype'} !~ /^(exact|contains|begins)$/) {
 6807:         $response = &mt('Invalid search.');
 6808:     }
 6809:     if ($srch->{'srchterm'} eq '') {
 6810:         $response = &mt('You must enter a search term.');
 6811:     }
 6812:     if ($srch->{'srchterm'} =~ /^\s+$/) {
 6813:         $response = &mt('Your search term must contain more than just spaces.');
 6814:     }
 6815:     if (($srch->{'srchin'} eq 'dom') || ($srch->{'srchin'} eq 'instd')) {
 6816:         if (($srch->{'srchdomain'} eq '') || 
 6817: 	    ! (&Apache::lonnet::domain($srch->{'srchdomain'}))) {
 6818:             $response = &mt('You must specify a valid domain when searching in a domain or institutional directory.')
 6819:         }
 6820:     }
 6821:     if (($srch->{'srchin'} eq 'dom') || ($srch->{'srchin'} eq 'crs') ||
 6822:         ($srch->{'srchin'} eq 'alc')) {
 6823:         if ($srch->{'srchby'} eq 'uname') {
 6824:             my $unamecheck = $srch->{'srchterm'};
 6825:             if ($srch->{'srchtype'} eq 'contains') {
 6826:                 if ($unamecheck !~ /^\w/) {
 6827:                     $unamecheck = 'a'.$unamecheck; 
 6828:                 }
 6829:             }
 6830:             if ($unamecheck !~ /^$match_username$/) {
 6831:                 $response = &mt('You must specify a valid username. Only the following are allowed: letters numbers - . @');
 6832:             }
 6833:         }
 6834:     }
 6835:     if ($response ne '') {
 6836:         $response = '<span class="LC_warning">'.$response.'</span>';
 6837:     }
 6838:     if ($srch->{'srchin'} eq 'instd') {
 6839:         my $instd_chk = &directorysrch_check($srch);
 6840:         if ($instd_chk ne 'ok') {
 6841:             $response = '<span class="LC_warning">'.$instd_chk.'</span>'.
 6842:                         '<br />'.&mt('You may want to search in the LON-CAPA domain instead of the institutional directory.').'<br /><br />';
 6843:         }
 6844:     }
 6845:     if ($response ne '') {
 6846:         return ($currstate,$response);
 6847:     }
 6848:     if ($srch->{'srchby'} eq 'uname') {
 6849:         if (($srch->{'srchin'} eq 'dom') || ($srch->{'srchin'} eq 'crs')) {
 6850:             if ($env{'form.forcenew'}) {
 6851:                 if ($srch->{'srchdomain'} ne $env{'request.role.domain'}) {
 6852:                     my $uhome=&Apache::lonnet::homeserver($srch->{'srchterm'},$srch->{'srchdomain'});
 6853:                     if ($uhome eq 'no_host') {
 6854:                         my $domdesc = &Apache::lonnet::domain($env{'request.role.domain'},'description');
 6855:                         my $showdom = &display_domain_info($env{'request.role.domain'});
 6856:                         $response = &mt('New users can only be created in the domain to which your current role belongs - [_1].',$showdom);
 6857:                     } else {
 6858:                         $currstate = 'modify';
 6859:                     }
 6860:                 } else {
 6861:                     $currstate = 'modify';
 6862:                 }
 6863:             } else {
 6864:                 if ($srch->{'srchin'} eq 'dom') {
 6865:                     if ($srch->{'srchtype'} eq 'exact') {
 6866:                         my $uhome=&Apache::lonnet::homeserver($srch->{'srchterm'},$srch->{'srchdomain'});
 6867:                         if ($uhome eq 'no_host') {
 6868:                             ($currstate,$response,$forcenewuser) =
 6869:                                 &build_search_response($context,$srch,%srch_results);
 6870:                         } else {
 6871:                             $currstate = 'modify';
 6872:                             my $uname = $srch->{'srchterm'};
 6873:                             my $udom = $srch->{'srchdomain'};
 6874:                             $srch_results{$uname.':'.$udom} =
 6875:                                 { &Apache::lonnet::get('environment',
 6876:                                                        ['firstname',
 6877:                                                         'lastname',
 6878:                                                         'permanentemail'],
 6879:                                                          $udom,$uname)
 6880:                                 };
 6881:                         }
 6882:                     } else {
 6883:                         %srch_results = &Apache::lonnet::usersearch($srch);
 6884:                         ($currstate,$response,$forcenewuser) =
 6885:                             &build_search_response($context,$srch,%srch_results);
 6886:                     }
 6887:                 } else {
 6888:                     my $courseusers = &get_courseusers();
 6889:                     if ($srch->{'srchtype'} eq 'exact') {
 6890:                         if (exists($courseusers->{$srch->{'srchterm'}.':'.$srch->{'srchdomain'}})) {
 6891:                             $currstate = 'modify';
 6892:                         } else {
 6893:                             ($currstate,$response,$forcenewuser) =
 6894:                                 &build_search_response($context,$srch,%srch_results);
 6895:                         }
 6896:                     } else {
 6897:                         foreach my $user (keys(%$courseusers)) {
 6898:                             my ($cuname,$cudomain) = split(/:/,$user);
 6899:                             if ($cudomain eq $srch->{'srchdomain'}) {
 6900:                                 my $matched = 0;
 6901:                                 if ($srch->{'srchtype'} eq 'begins') {
 6902:                                     if ($cuname =~ /^\Q$srch->{'srchterm'}\E/i) {
 6903:                                         $matched = 1;
 6904:                                     }
 6905:                                 } else {
 6906:                                     if ($cuname =~ /\Q$srch->{'srchterm'}\E/i) {
 6907:                                         $matched = 1;
 6908:                                     }
 6909:                                 }
 6910:                                 if ($matched) {
 6911:                                     $srch_results{$user} = 
 6912: 					{&Apache::lonnet::get('environment',
 6913: 							     ['firstname',
 6914: 							      'lastname',
 6915: 							      'permanentemail'],
 6916: 							      $cudomain,$cuname)};
 6917:                                 }
 6918:                             }
 6919:                         }
 6920:                         ($currstate,$response,$forcenewuser) =
 6921:                             &build_search_response($context,$srch,%srch_results);
 6922:                     }
 6923:                 }
 6924:             }
 6925:         } elsif ($srch->{'srchin'} eq 'alc') {
 6926:             $currstate = 'query';
 6927:         } elsif ($srch->{'srchin'} eq 'instd') {
 6928:             ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query($srch);
 6929:             if ($dirsrchres eq 'ok') {
 6930:                 ($currstate,$response,$forcenewuser) = 
 6931:                     &build_search_response($context,$srch,%srch_results);
 6932:             } else {
 6933:                 my $showdom = &display_domain_info($srch->{'srchdomain'});
 6934:                 $response = '<span class="LC_warning">'.
 6935:                     &mt('Institutional directory search is not available in domain: [_1]',$showdom).
 6936:                     '</span><br />'.
 6937:                     &mt('You may want to search in the LON-CAPA domain instead of the institutional directory.').
 6938:                     '<br /><br />'; 
 6939:             }
 6940:         }
 6941:     } else {
 6942:         if ($srch->{'srchin'} eq 'dom') {
 6943:             %srch_results = &Apache::lonnet::usersearch($srch);
 6944:             ($currstate,$response,$forcenewuser) = 
 6945:                 &build_search_response($context,$srch,%srch_results); 
 6946:         } elsif ($srch->{'srchin'} eq 'crs') {
 6947:             my $courseusers = &get_courseusers(); 
 6948:             foreach my $user (keys(%$courseusers)) {
 6949:                 my ($uname,$udom) = split(/:/,$user);
 6950:                 my %names = &Apache::loncommon::getnames($uname,$udom);
 6951:                 my %emails = &Apache::loncommon::getemails($uname,$udom);
 6952:                 if ($srch->{'srchby'} eq 'lastname') {
 6953:                     if ((($srch->{'srchtype'} eq 'exact') && 
 6954:                          ($names{'lastname'} eq $srch->{'srchterm'})) || 
 6955:                         (($srch->{'srchtype'} eq 'begins') &&
 6956:                          ($names{'lastname'} =~ /^\Q$srch->{'srchterm'}\E/i)) ||
 6957:                         (($srch->{'srchtype'} eq 'contains') &&
 6958:                          ($names{'lastname'} =~ /\Q$srch->{'srchterm'}\E/i))) {
 6959:                         $srch_results{$user} = {firstname => $names{'firstname'},
 6960:                                             lastname => $names{'lastname'},
 6961:                                             permanentemail => $emails{'permanentemail'},
 6962:                                            };
 6963:                     }
 6964:                 } elsif ($srch->{'srchby'} eq 'lastfirst') {
 6965:                     my ($srchlast,$srchfirst) = split(/,/,$srch->{'srchterm'});
 6966:                     $srchlast =~ s/\s+$//;
 6967:                     $srchfirst =~ s/^\s+//;
 6968:                     if ($srch->{'srchtype'} eq 'exact') {
 6969:                         if (($names{'lastname'} eq $srchlast) &&
 6970:                             ($names{'firstname'} eq $srchfirst)) {
 6971:                             $srch_results{$user} = {firstname => $names{'firstname'},
 6972:                                                 lastname => $names{'lastname'},
 6973:                                                 permanentemail => $emails{'permanentemail'},
 6974: 
 6975:                                            };
 6976:                         }
 6977:                     } elsif ($srch->{'srchtype'} eq 'begins') {
 6978:                         if (($names{'lastname'} =~ /^\Q$srchlast\E/i) &&
 6979:                             ($names{'firstname'} =~ /^\Q$srchfirst\E/i)) {
 6980:                             $srch_results{$user} = {firstname => $names{'firstname'},
 6981:                                                 lastname => $names{'lastname'},
 6982:                                                 permanentemail => $emails{'permanentemail'},
 6983:                                                };
 6984:                         }
 6985:                     } else {
 6986:                         if (($names{'lastname'} =~ /\Q$srchlast\E/i) && 
 6987:                             ($names{'firstname'} =~ /\Q$srchfirst\E/i)) {
 6988:                             $srch_results{$user} = {firstname => $names{'firstname'},
 6989:                                                 lastname => $names{'lastname'},
 6990:                                                 permanentemail => $emails{'permanentemail'},
 6991:                                                };
 6992:                         }
 6993:                     }
 6994:                 }
 6995:             }
 6996:             ($currstate,$response,$forcenewuser) = 
 6997:                 &build_search_response($context,$srch,%srch_results); 
 6998:         } elsif ($srch->{'srchin'} eq 'alc') {
 6999:             $currstate = 'query';
 7000:         } elsif ($srch->{'srchin'} eq 'instd') {
 7001:             ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query($srch); 
 7002:             if ($dirsrchres eq 'ok') {
 7003:                 ($currstate,$response,$forcenewuser) = 
 7004:                     &build_search_response($context,$srch,%srch_results);
 7005:             } else {
 7006:                 my $showdom = &display_domain_info($srch->{'srchdomain'});                $response = '<span class="LC_warning">'.
 7007:                     &mt('Institutional directory search is not available in domain: [_1]',$showdom).
 7008:                     '</span><br />'.
 7009:                     &mt('You may want to search in the LON-CAPA domain instead of the institutional directory.').
 7010:                     '<br /><br />';
 7011:             }
 7012:         }
 7013:     }
 7014:     return ($currstate,$response,$forcenewuser,\%srch_results);
 7015: }
 7016: 
 7017: sub directorysrch_check {
 7018:     my ($srch) = @_;
 7019:     my $can_search = 0;
 7020:     my $response;
 7021:     my %dom_inst_srch = &Apache::lonnet::get_dom('configuration',
 7022:                                              ['directorysrch'],$srch->{'srchdomain'});
 7023:     my $showdom = &display_domain_info($srch->{'srchdomain'});
 7024:     if (ref($dom_inst_srch{'directorysrch'}) eq 'HASH') {
 7025:         if (!$dom_inst_srch{'directorysrch'}{'available'}) {
 7026:             return &mt('Institutional directory search is not available in domain: [_1]',$showdom); 
 7027:         }
 7028:         if ($dom_inst_srch{'directorysrch'}{'localonly'}) {
 7029:             if ($env{'request.role.domain'} ne $srch->{'srchdomain'}) {
 7030:                 return &mt('Institutional directory search in domain: [_1] is only allowed for users with a current role in the domain.',$showdom); 
 7031:             }
 7032:             my @usertypes = split(/:/,$env{'environment.inststatus'});
 7033:             if (!@usertypes) {
 7034:                 push(@usertypes,'default');
 7035:             }
 7036:             if (ref($dom_inst_srch{'directorysrch'}{'cansearch'}) eq 'ARRAY') {
 7037:                 foreach my $type (@usertypes) {
 7038:                     if (grep(/^\Q$type\E$/,@{$dom_inst_srch{'directorysrch'}{'cansearch'}})) {
 7039:                         $can_search = 1;
 7040:                         last;
 7041:                     }
 7042:                 }
 7043:             }
 7044:             if (!$can_search) {
 7045:                 my ($insttypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($srch->{'srchdomain'});
 7046:                 my @longtypes; 
 7047:                 foreach my $item (@usertypes) {
 7048:                     if (defined($insttypes->{$item})) { 
 7049:                         push (@longtypes,$insttypes->{$item});
 7050:                     } elsif ($item eq 'default') {
 7051:                         push (@longtypes,&mt('other')); 
 7052:                     }
 7053:                 }
 7054:                 my $insttype_str = join(', ',@longtypes); 
 7055:                 return &mt('Institutional directory search in domain: [_1] is not available to your user type: ',$showdom).$insttype_str;
 7056:             }
 7057:         } else {
 7058:             $can_search = 1;
 7059:         }
 7060:     } else {
 7061:         return &mt('Institutional directory search has not been configured for domain: [_1]',$showdom);
 7062:     }
 7063:     my %longtext = &Apache::lonlocal::texthash (
 7064:                        uname     => 'username',
 7065:                        lastfirst => 'last name, first name',
 7066:                        lastname  => 'last name',
 7067:                        contains  => 'contains',
 7068:                        exact     => 'as exact match to',
 7069:                        begins    => 'begins with',
 7070:                    );
 7071:     if ($can_search) {
 7072:         if (ref($dom_inst_srch{'directorysrch'}{'searchby'}) eq 'ARRAY') {
 7073:             if (!grep(/^\Q$srch->{'srchby'}\E$/,@{$dom_inst_srch{'directorysrch'}{'searchby'}})) {
 7074:                 return &mt('Institutional directory search in domain: [_1] is not available for searching by "[_2]"',$showdom,$longtext{$srch->{'srchby'}});
 7075:             }
 7076:         } else {
 7077:             return &mt('Institutional directory search in domain: [_1] is not available.', $showdom);
 7078:         }
 7079:     }
 7080:     if ($can_search) {
 7081:         if (ref($dom_inst_srch{'directorysrch'}{'searchtypes'}) eq 'ARRAY') {
 7082:             if (grep(/^\Q$srch->{'srchtype'}\E/,@{$dom_inst_srch{'directorysrch'}{'searchtypes'}})) {
 7083:                 return 'ok';
 7084:             } else {
 7085:                 return &mt('Institutional directory search in domain [_1] is not available for the requested search type: "[_2]"',$showdom,$longtext{$srch->{'srchtype'}});
 7086:             }
 7087:         } else {
 7088:             if ((($dom_inst_srch{'directorysrch'}{'searchtypes'} eq 'specify') &&
 7089:                  ($srch->{'srchtype'} eq 'exact' || $srch->{'srchtype'} eq 'contains')) ||
 7090:                 ($dom_inst_srch{'directorysrch'}{'searchtypes'} eq $srch->{'srchtype'})) {
 7091:                 return 'ok';
 7092:             } else {
 7093:                 return &mt('Institutional directory search in domain [_1] is not available for the requested search type: "[_2]"',$showdom,$longtext{$srch->{'srchtype'}});
 7094:             }
 7095:         }
 7096:     }
 7097: }
 7098: 
 7099: sub get_courseusers {
 7100:     my %advhash;
 7101:     my $classlist = &Apache::loncoursedata::get_classlist();
 7102:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles();
 7103:     foreach my $role (sort(keys(%coursepersonnel))) {
 7104:         foreach my $user (split(/\,/,$coursepersonnel{$role})) {
 7105: 	    if (!exists($classlist->{$user})) {
 7106: 		$classlist->{$user} = [];
 7107: 	    }
 7108:         }
 7109:     }
 7110:     return $classlist;
 7111: }
 7112: 
 7113: sub build_search_response {
 7114:     my ($context,$srch,%srch_results) = @_;
 7115:     my ($currstate,$response,$forcenewuser);
 7116:     my %names = (
 7117:           'uname'     => 'username',
 7118:           'lastname'  => 'last name',
 7119:           'lastfirst' => 'last name, first name',
 7120:           'crs'       => 'this course',
 7121:           'dom'       => 'LON-CAPA domain',
 7122:           'instd'     => 'the institutional directory for domain',
 7123:     );
 7124: 
 7125:     my %single = (
 7126:                    begins   => 'A match',
 7127:                    contains => 'A match',
 7128:                    exact    => 'An exact match',
 7129:                  );
 7130:     my %nomatch = (
 7131:                    begins   => 'No match',
 7132:                    contains => 'No match',
 7133:                    exact    => 'No exact match',
 7134:                   );
 7135:     if (keys(%srch_results) > 1) {
 7136:         $currstate = 'select';
 7137:     } else {
 7138:         if (keys(%srch_results) == 1) {
 7139:             $currstate = 'modify';
 7140:             $response = &mt("$single{$srch->{'srchtype'}} was found for the $names{$srch->{'srchby'}} ([_1]) in $names{$srch->{'srchin'}}.",$srch->{'srchterm'});
 7141:             if ($srch->{'srchin'} eq 'dom' || $srch->{'srchin'} eq 'instd') {
 7142:                 $response .= ': '.&display_domain_info($srch->{'srchdomain'});
 7143:             }
 7144:         } else { # Search has nothing found. Prepare message to user.
 7145:             $response = '<span class="LC_warning">';
 7146:             if ($srch->{'srchin'} eq 'dom' || $srch->{'srchin'} eq 'instd') {
 7147:                 $response .= &mt("$nomatch{$srch->{'srchtype'}} found for the $names{$srch->{'srchby'}} [_1] in $names{$srch->{'srchin'}}: [_2]",
 7148:                                  '<b>'.$srch->{'srchterm'}.'</b>',
 7149:                                  &display_domain_info($srch->{'srchdomain'}));
 7150:             } else {
 7151:                 $response .= &mt("$nomatch{$srch->{'srchtype'}} found for the $names{$srch->{'srchby'}} [_1] in $names{$srch->{'srchin'}}.",
 7152:                                  '<b>'.$srch->{'srchterm'}.'</b>');
 7153:             }
 7154:             $response .= '</span>';
 7155: 
 7156:             if ($srch->{'srchin'} ne 'alc') {
 7157:                 $forcenewuser = 1;
 7158:                 my $cansrchinst = 0; 
 7159:                 if ($srch->{'srchdomain'}) {
 7160:                     my %domconfig = &Apache::lonnet::get_dom('configuration',['directorysrch'],$srch->{'srchdomain'});
 7161:                     if (ref($domconfig{'directorysrch'}) eq 'HASH') {
 7162:                         if ($domconfig{'directorysrch'}{'available'}) {
 7163:                             $cansrchinst = 1;
 7164:                         } 
 7165:                     }
 7166:                 }
 7167:                 if ((($srch->{'srchby'} eq 'lastfirst') || 
 7168:                      ($srch->{'srchby'} eq 'lastname')) &&
 7169:                     ($srch->{'srchin'} eq 'dom')) {
 7170:                     if ($cansrchinst) {
 7171:                         $response .= '<br />'.&mt('You may want to broaden your search to a search of the institutional directory for the domain.');
 7172:                     }
 7173:                 }
 7174:                 if ($srch->{'srchin'} eq 'crs') {
 7175:                     $response .= '<br />'.&mt('You may want to broaden your search to the selected LON-CAPA domain.');
 7176:                 }
 7177:             }
 7178:             my $createdom = $env{'request.role.domain'};
 7179:             if ($context eq 'requestcrs') {
 7180:                 if ($env{'form.coursedom'} ne '') {
 7181:                     $createdom = $env{'form.coursedom'};
 7182:                 }
 7183:             }
 7184:             if (!($srch->{'srchby'} eq 'uname' && $srch->{'srchin'} eq 'dom' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchdomain'} eq $createdom)) {
 7185:                 my $cancreate =
 7186:                     &Apache::lonuserutils::can_create_user($createdom,$context);
 7187:                 my $targetdom = '<span class="LC_cusr_emph">'.$createdom.'</span>';
 7188:                 if ($cancreate) {
 7189:                     my $showdom = &display_domain_info($createdom); 
 7190:                     $response .= '<br /><br />'
 7191:                                 .'<b>'.&mt('To add a new user:').'</b>'
 7192:                                 .'<br />';
 7193:                     if ($context eq 'requestcrs') {
 7194:                         $response .= &mt("(You can only define new users in the new course's domain - [_1])",$targetdom);
 7195:                     } else {
 7196:                         $response .= &mt("(You can only create new users in your current role's domain - [_1])",$targetdom);
 7197:                     }
 7198:                     $response .='<ul><li>'
 7199:                                 .&mt("Set 'Domain/institution to search' to: [_1]",'<span class="LC_cusr_emph">'.$showdom.'</span>')
 7200:                                 .'</li><li>'
 7201:                                 .&mt("Set 'Search criteria' to: [_1]username is ..... in selected LON-CAPA domain[_2]",'<span class="LC_cusr_emph">','</span>')
 7202:                                 .'</li><li>'
 7203:                                 .&mt('Provide the proposed username')
 7204:                                 .'</li><li>'
 7205:                                 .&mt("Click 'Search'")
 7206:                                 .'</li></ul><br />';
 7207:                 } else {
 7208:                     my $helplink = ' href="javascript:helpMenu('."'display'".')"';
 7209:                     $response .= '<br /><br />';
 7210:                     if ($context eq 'requestcrs') {
 7211:                         $response .= &mt("You are not authorized to define new users in the new course's domain - [_1].",$targetdom);
 7212:                     } else {
 7213:                         $response .= &mt("You are not authorized to create new users in your current role's domain - [_1].",$targetdom);
 7214:                     }
 7215:                     $response .= '<br />'
 7216:                                  .&mt('Please contact the [_1]helpdesk[_2] if you need to create a new user.'
 7217:                                     ,' <a'.$helplink.'>'
 7218:                                     ,'</a>')
 7219:                                  .'<br /><br />';
 7220:                 }
 7221:             }
 7222:         }
 7223:     }
 7224:     return ($currstate,$response,$forcenewuser);
 7225: }
 7226: 
 7227: sub display_domain_info {
 7228:     my ($dom) = @_;
 7229:     my $output = $dom;
 7230:     if ($dom ne '') { 
 7231:         my $domdesc = &Apache::lonnet::domain($dom,'description');
 7232:         if ($domdesc ne '') {
 7233:             $output .= ' <span class="LC_cusr_emph">('.$domdesc.')</span>';
 7234:         }
 7235:     }
 7236:     return $output;
 7237: }
 7238: 
 7239: sub crumb_utilities {
 7240:     my %elements = (
 7241:        crtuser => {
 7242:            srchterm => 'text',
 7243:            srchin => 'selectbox',
 7244:            srchby => 'selectbox',
 7245:            srchtype => 'selectbox',
 7246:            srchdomain => 'selectbox',
 7247:        },
 7248:        crtusername => {
 7249:            srchterm => 'text',
 7250:            srchdomain => 'selectbox',
 7251:        },
 7252:        docustom => {
 7253:            rolename => 'selectbox',
 7254:            newrolename => 'textbox',
 7255:        },
 7256:        studentform => {
 7257:            srchterm => 'text',
 7258:            srchin => 'selectbox',
 7259:            srchby => 'selectbox',
 7260:            srchtype => 'selectbox',
 7261:            srchdomain => 'selectbox',
 7262:        },
 7263:     );
 7264: 
 7265:     my $jsback .= qq|
 7266: function backPage(formname,prevphase,prevstate) {
 7267:     if (typeof prevphase == 'undefined') {
 7268:         formname.phase.value = '';
 7269:     }
 7270:     else {  
 7271:         formname.phase.value = prevphase;
 7272:     }
 7273:     if (typeof prevstate == 'undefined') {
 7274:         formname.currstate.value = '';
 7275:     }
 7276:     else {
 7277:         formname.currstate.value = prevstate;
 7278:     }
 7279:     formname.submit();
 7280: }
 7281: |;
 7282:     return ($jsback,\%elements);
 7283: }
 7284: 
 7285: sub course_level_table {
 7286:     my ($inccourses,$showcredits,$defaultcredits) = @_;
 7287:     return unless (ref($inccourses) eq 'HASH');
 7288:     my $table = '';
 7289: # Custom Roles?
 7290: 
 7291:     my %customroles=&Apache::lonuserutils::my_custom_roles();
 7292:     my %lt=&Apache::lonlocal::texthash(
 7293:             'exs'  => "Existing sections",
 7294:             'new'  => "Define new section",
 7295:             'ssd'  => "Set Start Date",
 7296:             'sed'  => "Set End Date",
 7297:             'crl'  => "Course Level",
 7298:             'act'  => "Activate",
 7299:             'rol'  => "Role",
 7300:             'ext'  => "Extent",
 7301:             'grs'  => "Section",
 7302:             'crd'  => "Credits",
 7303:             'sta'  => "Start",
 7304:             'end'  => "End"
 7305:     );
 7306: 
 7307:     foreach my $protectedcourse (sort(keys(%{$inccourses}))) {
 7308: 	my $thiscourse=$protectedcourse;
 7309: 	$thiscourse=~s:_:/:g;
 7310: 	my %coursedata=&Apache::lonnet::coursedescription($thiscourse);
 7311:         my $isowner = &Apache::lonuserutils::is_courseowner($protectedcourse,$coursedata{'internal.courseowner'});
 7312: 	my $area=$coursedata{'description'};
 7313:         my $crstype=$coursedata{'type'};
 7314: 	if (!defined($area)) { $area=&mt('Unavailable course').': '.$protectedcourse; }
 7315: 	my ($domain,$cnum)=split(/\//,$thiscourse);
 7316:         my %sections_count;
 7317:         if (defined($env{'request.course.id'})) {
 7318:             if ($env{'request.course.id'} eq $domain.'_'.$cnum) {
 7319:                 %sections_count = 
 7320: 		    &Apache::loncommon::get_sections($domain,$cnum);
 7321:             }
 7322:         }
 7323:         my @roles = &Apache::lonuserutils::roles_by_context('course','',$crstype);
 7324: 	foreach my $role (@roles) {
 7325:             my $plrole=&Apache::lonnet::plaintext($role,$crstype);
 7326: 	    if ((&Apache::lonnet::allowed('c'.$role,$thiscourse)) ||
 7327:                 ((($role eq 'cc') || ($role eq 'co')) && ($isowner))) {
 7328:                 $table .= &course_level_row($protectedcourse,$role,$area,$domain,
 7329:                                             $plrole,\%sections_count,\%lt,
 7330:                                             $showcredits,$defaultcredits,$crstype);
 7331:             } elsif ($env{'request.course.sec'} ne '') {
 7332:                 if (&Apache::lonnet::allowed('c'.$role,$thiscourse.'/'.
 7333:                                              $env{'request.course.sec'})) {
 7334:                     $table .= &course_level_row($protectedcourse,$role,$area,$domain,
 7335:                                                 $plrole,\%sections_count,\%lt,
 7336:                                                 $showcredits,$defaultcredits,$crstype);
 7337:                 }
 7338:             }
 7339:         }
 7340:         if (&Apache::lonnet::allowed('ccr',$thiscourse)) {
 7341:             foreach my $cust (sort(keys(%customroles))) {
 7342:                 next if ($crstype eq 'Community' && $customroles{$cust} =~ /bre\&S/);
 7343:                 my $role = 'cr_cr_'.$env{'user.domain'}.'_'.$env{'user.name'}.'_'.$cust;
 7344:                 $table .= &course_level_row($protectedcourse,$role,$area,$domain,
 7345:                                             $cust,\%sections_count,\%lt,
 7346:                                             $showcredits,$defaultcredits,$crstype);
 7347:             }
 7348: 	}
 7349:     }
 7350:     return '' if ($table eq ''); # return nothing if there is nothing 
 7351:                                  # in the table
 7352:     my $result;
 7353:     if (!$env{'request.course.id'}) {
 7354:         $result = '<h4>'.$lt{'crl'}.'</h4>'."\n";
 7355:     }
 7356:     $result .= 
 7357: &Apache::loncommon::start_data_table().
 7358: &Apache::loncommon::start_data_table_header_row().
 7359: '<th>'.$lt{'act'}.'</th><th>'.$lt{'rol'}.'</th>'."\n".
 7360: '<th>'.$lt{'ext'}.'</th><th>'."\n";
 7361:     if ($showcredits) {
 7362:         $result .= $lt{'crd'}.'</th>';
 7363:     }
 7364:     $result .=
 7365: '<th>'.$lt{'grs'}.'</th><th>'.$lt{'sta'}.'</th>'."\n".
 7366: '<th>'.$lt{'end'}.'</th>'.
 7367: &Apache::loncommon::end_data_table_header_row().
 7368: $table.
 7369: &Apache::loncommon::end_data_table();
 7370:     return $result;
 7371: }
 7372: 
 7373: sub course_level_row {
 7374:     my ($protectedcourse,$role,$area,$domain,$plrole,$sections_count,
 7375:         $lt,$showcredits,$defaultcredits,$crstype) = @_;
 7376:     my $creditem;
 7377:     my $row = &Apache::loncommon::start_data_table_row().
 7378:               ' <td><input type="checkbox" name="act_'.
 7379:               $protectedcourse.'_'.$role.'" /></td>'."\n".
 7380:               ' <td>'.$plrole.'</td>'."\n".
 7381:               ' <td>'.$area.'<br />Domain: '.$domain.'</td>'."\n";
 7382:     if (($showcredits) && ($role eq 'st') && ($crstype eq 'Course')) {
 7383:         $row .= 
 7384:             '<td><input type="text" name="credits_'.$protectedcourse.'_'.
 7385:             $role.'" size="3" value="'.$defaultcredits.'" /></td>';
 7386:     } else {
 7387:         $row .= '<td>&nbsp;</td>';
 7388:     }
 7389:     if (($role eq 'cc') || ($role eq 'co')) {
 7390:         $row .= '<td>&nbsp;</td>';
 7391:     } elsif ($env{'request.course.sec'} ne '') {
 7392:         $row .= ' <td><input type="hidden" value="'.
 7393:                 $env{'request.course.sec'}.'" '.
 7394:                 'name="sec_'.$protectedcourse.'_'.$role.'" />'.
 7395:                 $env{'request.course.sec'}.'</td>';
 7396:     } else {
 7397:         if (ref($sections_count) eq 'HASH') {
 7398:             my $currsec = 
 7399:                 &Apache::lonuserutils::course_sections($sections_count,
 7400:                                                        $protectedcourse.'_'.$role);
 7401:             $row .= '<td><table class="LC_createuser">'."\n".
 7402:                     '<tr class="LC_section_row">'."\n".
 7403:                     ' <td valign="top">'.$lt->{'exs'}.'<br />'.
 7404:                        $currsec.'</td>'."\n".
 7405:                      ' <td>&nbsp;&nbsp;</td>'."\n".
 7406:                      ' <td valign="top">&nbsp;'.$lt->{'new'}.'<br />'.
 7407:                      '<input type="text" name="newsec_'.$protectedcourse.'_'.$role.
 7408:                      '" value="" />'.
 7409:                      '<input type="hidden" '.
 7410:                      'name="sec_'.$protectedcourse.'_'.$role.'" /></td>'."\n".
 7411:                      '</tr></table></td>'."\n";
 7412:         } else {
 7413:             $row .= '<td><input type="text" size="10" '.
 7414:                     'name="sec_'.$protectedcourse.'_'.$role.'" /></td>'."\n";
 7415:         }
 7416:     }
 7417:     $row .= <<ENDTIMEENTRY;
 7418: <td><input type="hidden" name="start_$protectedcourse\_$role" value="" />
 7419: <a href=
 7420: "javascript:pjump('date_start','Start Date $plrole',document.cu.start_$protectedcourse\_$role.value,'start_$protectedcourse\_$role','cu.pres','dateset')">$lt->{'ssd'}</a></td>
 7421: <td><input type="hidden" name="end_$protectedcourse\_$role" value="" />
 7422: <a href=
 7423: "javascript:pjump('date_end','End Date $plrole',document.cu.end_$protectedcourse\_$role.value,'end_$protectedcourse\_$role','cu.pres','dateset')">$lt->{'sed'}</a></td>
 7424: ENDTIMEENTRY
 7425:     $row .= &Apache::loncommon::end_data_table_row();
 7426:     return $row;
 7427: }
 7428: 
 7429: sub course_level_dc {
 7430:     my ($dcdom,$showcredits) = @_;
 7431:     my %customroles=&Apache::lonuserutils::my_custom_roles();
 7432:     my @roles = &Apache::lonuserutils::roles_by_context('course');
 7433:     my $hiddenitems = '<input type="hidden" name="dcdomain" value="'.$dcdom.'" />'.
 7434:                       '<input type="hidden" name="origdom" value="'.$dcdom.'" />'.
 7435:                       '<input type="hidden" name="dccourse" value="" />';
 7436:     my $courseform=&Apache::loncommon::selectcourse_link
 7437:             ('cu','dccourse','dcdomain','coursedesc',undef,undef,'Select','crstype');
 7438:     my $credit_elem;
 7439:     if ($showcredits) {
 7440:         $credit_elem = 'credits';
 7441:     }
 7442:     my $cb_jscript = &Apache::loncommon::coursebrowser_javascript($dcdom,'currsec','cu','role','Course/Community Browser',$credit_elem);
 7443:     my %lt=&Apache::lonlocal::texthash(
 7444:                     'rol'  => "Role",
 7445:                     'grs'  => "Section",
 7446:                     'exs'  => "Existing sections",
 7447:                     'new'  => "Define new section", 
 7448:                     'sta'  => "Start",
 7449:                     'end'  => "End",
 7450:                     'ssd'  => "Set Start Date",
 7451:                     'sed'  => "Set End Date",
 7452:                     'scc'  => "Course/Community",
 7453:                     'crd'  => "Credits",
 7454:                   );
 7455:     my $header = '<h4>'.&mt('Course/Community Level').'</h4>'.
 7456:                  &Apache::loncommon::start_data_table().
 7457:                  &Apache::loncommon::start_data_table_header_row().
 7458:                  '<th>'.$lt{'scc'}.'</th><th>'.$lt{'rol'}.'</th>'."\n".
 7459:                  '<th>'.$lt{'grs'}.'</th>'."\n";
 7460:     $header .=   '<th>'.$lt{'crd'}.'</th>'."\n" if ($showcredits);
 7461:     $header .=   '<th>'.$lt{'sta'}.'</th><th>'.$lt{'end'}.'</th>'."\n".
 7462:                  &Apache::loncommon::end_data_table_header_row();
 7463:     my $otheritems = &Apache::loncommon::start_data_table_row()."\n".
 7464:                      '<td><br /><span class="LC_nobreak"><input type="text" name="coursedesc" value="" onfocus="this.blur();opencrsbrowser('."'cu','dccourse','dcdomain','coursedesc','','','','crstype'".')" />'.
 7465:                      $courseform.('&nbsp;' x4).'</span></td>'."\n".
 7466:                      '<td valign="top"><br /><select name="role">'."\n";
 7467:     foreach my $role (@roles) {
 7468:         my $plrole=&Apache::lonnet::plaintext($role);
 7469:         $otheritems .= '  <option value="'.$role.'">'.$plrole.'</option>';
 7470:     }
 7471:     if ( keys(%customroles) > 0) {
 7472:         foreach my $cust (sort(keys(%customroles))) {
 7473:             my $custrole='cr_cr_'.$env{'user.domain'}.
 7474:                     '_'.$env{'user.name'}.'_'.$cust;
 7475:             $otheritems .= '  <option value="'.$custrole.'">'.$cust.'</option>';
 7476:         }
 7477:     }
 7478:     $otheritems .= '</select></td><td>'.
 7479:                      '<table border="0" cellspacing="0" cellpadding="0">'.
 7480:                      '<tr><td valign="top"><b>'.$lt{'exs'}.'</b><br /><select name="currsec">'.
 7481:                      ' <option value="">&lt;--'.&mt('Pick course first').'</option></select></td>'.
 7482:                      '<td>&nbsp;&nbsp;</td>'.
 7483:                      '<td valign="top">&nbsp;<b>'.$lt{'new'}.'</b><br />'.
 7484:                      '<input type="text" name="newsec" value="" />'.
 7485:                      '<input type="hidden" name="section" value="" />'.
 7486:                      '<input type="hidden" name="groups" value="" />'.
 7487:                      '<input type="hidden" name="crstype" value="" /></td>'.
 7488:                      '</tr></table></td>'."\n";
 7489:     if ($showcredits) {
 7490:         $otheritems .= '<td><br />'."\n".
 7491:                        '<input type="text" size="3" name="credits" value="" /></td>'."\n";
 7492:     }
 7493:     $otheritems .= <<ENDTIMEENTRY;
 7494: <td><br /><input type="hidden" name="start" value='' />
 7495: <a href=
 7496: "javascript:pjump('date_start','Start Date',document.cu.start.value,'start','cu.pres','dateset')">$lt{'ssd'}</a></td>
 7497: <td><br /><input type="hidden" name="end" value='' />
 7498: <a href=
 7499: "javascript:pjump('date_end','End Date',document.cu.end.value,'end','cu.pres','dateset')">$lt{'sed'}</a></td>
 7500: ENDTIMEENTRY
 7501:     $otheritems .= &Apache::loncommon::end_data_table_row().
 7502:                    &Apache::loncommon::end_data_table()."\n";
 7503:     return $cb_jscript.$header.$hiddenitems.$otheritems;
 7504: }
 7505: 
 7506: sub update_selfenroll_config {
 7507:     my ($r,$cid,$cdom,$cnum,$context,$crstype,$currsettings) = @_;
 7508:     return unless (ref($currsettings) eq 'HASH');
 7509:     my ($row,$lt) = &Apache::lonuserutils::get_selfenroll_titles();
 7510:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
 7511:     my (%changes,%warning);
 7512:     my $curr_types;
 7513:     my %noedit;
 7514:     unless ($context eq 'domain') {
 7515:         %noedit = &get_noedit_fields($cdom,$cnum,$crstype,$row);
 7516:     }
 7517:     if (ref($row) eq 'ARRAY') {
 7518:         foreach my $item (@{$row}) {
 7519:             next if ($noedit{$item});
 7520:             if ($item eq 'enroll_dates') {
 7521:                 my (%currenrolldate,%newenrolldate);
 7522:                 foreach my $type ('start','end') {
 7523:                     $currenrolldate{$type} = $currsettings->{'selfenroll_'.$type.'_date'};
 7524:                     $newenrolldate{$type} = &Apache::lonhtmlcommon::get_date_from_form('selfenroll_'.$type.'_date');
 7525:                     if ($newenrolldate{$type} ne $currenrolldate{$type}) {
 7526:                         $changes{'internal.selfenroll_'.$type.'_date'} = $newenrolldate{$type};
 7527:                     }
 7528:                 }
 7529:             } elsif ($item eq 'access_dates') {
 7530:                 my (%currdate,%newdate);
 7531:                 foreach my $type ('start','end') {
 7532:                     $currdate{$type} = $currsettings->{'selfenroll_'.$type.'_access'};
 7533:                     $newdate{$type} = &Apache::lonhtmlcommon::get_date_from_form('selfenroll_'.$type.'_access');
 7534:                     if ($newdate{$type} ne $currdate{$type}) {
 7535:                         $changes{'internal.selfenroll_'.$type.'_access'} = $newdate{$type};
 7536:                     }
 7537:                 }
 7538:             } elsif ($item eq 'types') {
 7539:                 $curr_types = $currsettings->{'selfenroll_'.$item};
 7540:                 if ($env{'form.selfenroll_all'}) {
 7541:                     if ($curr_types ne '*') {
 7542:                         $changes{'internal.selfenroll_types'} = '*';
 7543:                     } else {
 7544:                         next;
 7545:                     }
 7546:                 } else {
 7547:                     my %currdoms;
 7548:                     my @entries = split(/;/,$curr_types);
 7549:                     my @deletedoms = &Apache::loncommon::get_env_multiple('form.selfenroll_delete');
 7550:                     my @activations = &Apache::loncommon::get_env_multiple('form.selfenroll_activate');
 7551:                     my $newnum = 0;
 7552:                     my @latesttypes;
 7553:                     foreach my $num (@activations) {
 7554:                         my @types = &Apache::loncommon::get_env_multiple('form.selfenroll_types_'.$num);
 7555:                         if (@types > 0) {
 7556:                             @types = sort(@types);
 7557:                             my $typestr = join(',',@types);
 7558:                             my $typedom = $env{'form.selfenroll_dom_'.$num};
 7559:                             $latesttypes[$newnum] = $typedom.':'.$typestr;
 7560:                             $currdoms{$typedom} = 1;
 7561:                             $newnum ++;
 7562:                         }
 7563:                     }
 7564:                     for (my $j=0; $j<$env{'form.selfenroll_types_total'}; $j++) {
 7565:                         if ((!grep(/^$j$/,@deletedoms)) && (!grep(/^$j$/,@activations))) {
 7566:                             my @types = &Apache::loncommon::get_env_multiple('form.selfenroll_types_'.$j);
 7567:                             if (@types > 0) {
 7568:                                 @types = sort(@types);
 7569:                                 my $typestr = join(',',@types);
 7570:                                 my $typedom = $env{'form.selfenroll_dom_'.$j};
 7571:                                 $latesttypes[$newnum] = $typedom.':'.$typestr;
 7572:                                 $currdoms{$typedom} = 1;
 7573:                                 $newnum ++;
 7574:                             }
 7575:                         }
 7576:                     }
 7577:                     if ($env{'form.selfenroll_newdom'} ne '') {
 7578:                         my $typedom = $env{'form.selfenroll_newdom'};
 7579:                         if ((!defined($currdoms{$typedom})) && 
 7580:                             (&Apache::lonnet::domain($typedom) ne '')) {
 7581:                             my $typestr;
 7582:                             my ($othertitle,$usertypes,$types) = 
 7583:                                 &Apache::loncommon::sorted_inst_types($typedom);
 7584:                             my $othervalue = 'any';
 7585:                             if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 7586:                                 if (@{$types} > 0) {
 7587:                                     my @esc_types = map { &escape($_); } @{$types};
 7588:                                     $othervalue = 'other';
 7589:                                     $typestr = join(',',(@esc_types,$othervalue));
 7590:                                 }
 7591:                                 $typestr = $othervalue;
 7592:                             } else {
 7593:                                 $typestr = $othervalue;
 7594:                             } 
 7595:                             $latesttypes[$newnum] = $typedom.':'.$typestr;
 7596:                             $newnum ++ ;
 7597:                         }
 7598:                     }
 7599:                     my $selfenroll_types = join(';',@latesttypes);
 7600:                     if ($selfenroll_types ne $curr_types) {
 7601:                         $changes{'internal.selfenroll_types'} = $selfenroll_types;
 7602:                     }
 7603:                 }
 7604:             } elsif ($item eq 'limit') {
 7605:                 my $newlimit = $env{'form.selfenroll_limit'};
 7606:                 my $newcap = $env{'form.selfenroll_cap'};
 7607:                 $newcap =~s/\s+//g;
 7608:                 my $currlimit =  $currsettings->{'selfenroll_limit'};
 7609:                 $currlimit = 'none' if ($currlimit eq '');
 7610:                 my $currcap = $currsettings->{'selfenroll_cap'};
 7611:                 if ($newlimit ne $currlimit) {
 7612:                     if ($newlimit ne 'none') {
 7613:                         if ($newcap =~ /^\d+$/) {
 7614:                             if ($newcap ne $currcap) {
 7615:                                 $changes{'internal.selfenroll_cap'} = $newcap;
 7616:                             }
 7617:                             $changes{'internal.selfenroll_limit'} = $newlimit;
 7618:                         } else {
 7619:                             $warning{$item} = &mt('Maximum enrollment setting unchanged.').'<br />'.
 7620:                                 &mt('The value provided was invalid - it must be a positive integer if enrollment is being limited.'); 
 7621:                         }
 7622:                     } elsif ($currcap ne '') {
 7623:                         $changes{'internal.selfenroll_cap'} = '';
 7624:                         $changes{'internal.selfenroll_limit'} = $newlimit; 
 7625:                     }
 7626:                 } elsif ($currlimit ne 'none') {
 7627:                     if ($newcap =~ /^\d+$/) {
 7628:                         if ($newcap ne $currcap) {
 7629:                             $changes{'internal.selfenroll_cap'} = $newcap;
 7630:                         }
 7631:                     } else {
 7632:                         $warning{$item} = &mt('Maximum enrollment setting unchanged.').'<br />'.
 7633:                             &mt('The value provided was invalid - it must be a positive integer if enrollment is being limited.');
 7634:                     }
 7635:                 }
 7636:             } elsif ($item eq 'approval') {
 7637:                 my (@currnotified,@newnotified);
 7638:                 my $currapproval = $currsettings->{'selfenroll_approval'};
 7639:                 my $currnotifylist = $currsettings->{'selfenroll_notifylist'};
 7640:                 if ($currnotifylist ne '') {
 7641:                     @currnotified = split(/,/,$currnotifylist);
 7642:                     @currnotified = sort(@currnotified);
 7643:                 }
 7644:                 my $newapproval = $env{'form.selfenroll_approval'};
 7645:                 @newnotified = &Apache::loncommon::get_env_multiple('form.selfenroll_notify');
 7646:                 @newnotified = sort(@newnotified);
 7647:                 if ($newapproval ne $currapproval) {
 7648:                     $changes{'internal.selfenroll_approval'} = $newapproval;
 7649:                     if (!$newapproval) {
 7650:                         if ($currnotifylist ne '') {
 7651:                             $changes{'internal.selfenroll_notifylist'} = '';
 7652:                         }
 7653:                     } else {
 7654:                         my @differences =  
 7655:                             &Apache::loncommon::compare_arrays(\@currnotified,\@newnotified);
 7656:                         if (@differences > 0) {
 7657:                             if (@newnotified > 0) {
 7658:                                 $changes{'internal.selfenroll_notifylist'} = join(',',@newnotified);
 7659:                             } else {
 7660:                                 $changes{'internal.selfenroll_notifylist'} = join(',',@newnotified);
 7661:                             }
 7662:                         }
 7663:                     }
 7664:                 } else {
 7665:                     my @differences = &Apache::loncommon::compare_arrays(\@currnotified,\@newnotified);
 7666:                     if (@differences > 0) {
 7667:                         if (@newnotified > 0) {
 7668:                             $changes{'internal.selfenroll_notifylist'} = join(',',@newnotified);
 7669:                         } else {
 7670:                             $changes{'internal.selfenroll_notifylist'} = '';
 7671:                         }
 7672:                     }
 7673:                 }
 7674:             } else {
 7675:                 my $curr_val = $currsettings->{'selfenroll_'.$item};
 7676:                 my $newval = $env{'form.selfenroll_'.$item};
 7677:                 if ($item eq 'section') {
 7678:                     $newval = $env{'form.sections'};
 7679:                     if (defined($curr_groups{$newval})) {
 7680:                         $newval = $curr_val;
 7681:                         $warning{$item} = &mt('Section for self-enrolled users unchanged as the proposed section is a group').'<br />'.
 7682:                                           &mt('Group names and section names must be distinct');
 7683:                     } elsif ($newval eq 'all') {
 7684:                         $newval = $curr_val;
 7685:                         $warning{$item} = &mt('Section for self-enrolled users unchanged, as "all" is a reserved section name.');
 7686:                     }
 7687:                     if ($newval eq '') {
 7688:                         $newval = 'none';
 7689:                     }
 7690:                 }
 7691:                 if ($newval ne $curr_val) {
 7692:                     $changes{'internal.selfenroll_'.$item} = $newval;
 7693:                 }
 7694:             }
 7695:         }
 7696:         if (keys(%warning) > 0) {
 7697:             foreach my $item (@{$row}) {
 7698:                 if (exists($warning{$item})) {
 7699:                     $r->print($warning{$item}.'<br />');
 7700:                 }
 7701:             } 
 7702:         }
 7703:         if (keys(%changes) > 0) {
 7704:             my $putresult = &Apache::lonnet::put('environment',\%changes,$cdom,$cnum);
 7705:             if ($putresult eq 'ok') {
 7706:                 if ((exists($changes{'internal.selfenroll_types'})) ||
 7707:                     (exists($changes{'internal.selfenroll_start_date'}))  ||
 7708:                     (exists($changes{'internal.selfenroll_end_date'}))) {
 7709:                     my %crsinfo = &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',
 7710:                                                                 $cnum,undef,undef,'Course');
 7711:                     my $chome = &Apache::lonnet::homeserver($cnum,$cdom);
 7712:                     if (ref($crsinfo{$cid}) eq 'HASH') {
 7713:                         foreach my $item ('selfenroll_types','selfenroll_start_date','selfenroll_end_date') {
 7714:                             if (exists($changes{'internal.'.$item})) {
 7715:                                 $crsinfo{$cid}{$item} = $changes{'internal.'.$item};
 7716:                             }
 7717:                         }
 7718:                         my $crsputresult =
 7719:                             &Apache::lonnet::courseidput($cdom,\%crsinfo,
 7720:                                                          $chome,'notime');
 7721:                     }
 7722:                 }
 7723:                 $r->print(&mt('The following changes were made to self-enrollment settings:').'<ul>');
 7724:                 foreach my $item (@{$row}) {
 7725:                     my $title = $item;
 7726:                     if (ref($lt) eq 'HASH') {
 7727:                         $title = $lt->{$item};
 7728:                     }
 7729:                     if ($item eq 'enroll_dates') {
 7730:                         foreach my $type ('start','end') {
 7731:                             if (exists($changes{'internal.selfenroll_'.$type.'_date'})) {
 7732:                                 my $newdate = &Apache::lonlocal::locallocaltime($changes{'internal.selfenroll_'.$type.'_date'});
 7733:                                 $r->print('<li>'.&mt('[_1]: "[_2]" set to "[_3]".',
 7734:                                           $title,$type,$newdate).'</li>');
 7735:                             }
 7736:                         }
 7737:                     } elsif ($item eq 'access_dates') {
 7738:                         foreach my $type ('start','end') {
 7739:                             if (exists($changes{'internal.selfenroll_'.$type.'_access'})) {
 7740:                                 my $newdate = &Apache::lonlocal::locallocaltime($changes{'internal.selfenroll_'.$type.'_access'});
 7741:                                 $r->print('<li>'.&mt('[_1]: "[_2]" set to "[_3]".',
 7742:                                           $title,$type,$newdate).'</li>');
 7743:                             }
 7744:                         }
 7745:                     } elsif ($item eq 'limit') {
 7746:                         if ((exists($changes{'internal.selfenroll_limit'})) ||
 7747:                             (exists($changes{'internal.selfenroll_cap'}))) {
 7748:                             my ($newval,$newcap);
 7749:                             if ($changes{'internal.selfenroll_cap'} ne '') {
 7750:                                 $newcap = $changes{'internal.selfenroll_cap'}
 7751:                             } else {
 7752:                                 $newcap = $currsettings->{'selfenroll_cap'};
 7753:                             }
 7754:                             if ($changes{'internal.selfenroll_limit'} eq 'none') {
 7755:                                 $newval = &mt('No limit');
 7756:                             } elsif ($changes{'internal.selfenroll_limit'} eq 
 7757:                                      'allstudents') {
 7758:                                 $newval = &mt('New self-enrollment no longer allowed when total (all students) reaches [_1].',$newcap);
 7759:                             } elsif ($changes{'internal.selfenroll_limit'} eq 'selfenrolled') {
 7760:                                 $newval = &mt('New self-enrollment no longer allowed when total number of self-enrolled students reaches [_1].',$newcap);
 7761:                             } else {
 7762:                                 my $currlimit =  $currsettings->{'selfenroll_limit'};
 7763:                                 if ($currlimit eq 'allstudents') {
 7764:                                     $newval = &mt('New self-enrollment no longer allowed when total (all students) reaches [_1].',$newcap);
 7765:                                 } elsif ($changes{'internal.selfenroll_limit'} eq 'selfenrolled') {
 7766:                                     $newval =  &mt('New self-enrollment no longer allowed when total number of self-enrolled students reaches [_1].',$newcap);
 7767:                                 }
 7768:                             }
 7769:                             $r->print('<li>'.&mt('"[_1]" set to "[_2]".',$title,$newval).'</li>'."\n");
 7770:                         }
 7771:                     } elsif ($item eq 'approval') {
 7772:                         if ((exists($changes{'internal.selfenroll_approval'})) ||
 7773:                             (exists($changes{'internal.selfenroll_notifylist'}))) {
 7774:                             my %selfdescs = &Apache::lonuserutils::selfenroll_default_descs();
 7775:                             my ($newval,$newnotify);
 7776:                             if (exists($changes{'internal.selfenroll_notifylist'})) {
 7777:                                 $newnotify = $changes{'internal.selfenroll_notifylist'};
 7778:                             } else {   
 7779:                                 $newnotify = $currsettings->{'selfenroll_notifylist'};
 7780:                             }
 7781:                             if (exists($changes{'internal.selfenroll_approval'})) {
 7782:                                 if ($changes{'internal.selfenroll_approval'} !~ /^[012]$/) {
 7783:                                     $changes{'internal.selfenroll_approval'} = '0';
 7784:                                 }
 7785:                                 $newval = $selfdescs{'approval'}{$changes{'internal.selfenroll_approval'}};
 7786:                             } else {
 7787:                                 my $currapproval = $currsettings->{'selfenroll_approval'}; 
 7788:                                 if ($currapproval !~ /^[012]$/) {
 7789:                                     $currapproval = 0;
 7790:                                 }
 7791:                                 $newval = $selfdescs{'approval'}{$currapproval};
 7792:                             }
 7793:                             $r->print('<li>'.&mt('"[_1]" set to "[_2]".',$title,$newval));
 7794:                             if ($newnotify) {
 7795:                                 $r->print('<br />'.&mt('The following will be notified when an enrollment request needs approval, or has been approved: [_1].',$newnotify));
 7796:                             } else {
 7797:                                 $r->print('<br />'.&mt('No notifications sent when an enrollment request needs approval, or has been approved.'));
 7798:                             }
 7799:                             $r->print('</li>'."\n");
 7800:                         }
 7801:                     } else {
 7802:                         if (exists($changes{'internal.selfenroll_'.$item})) {
 7803:                             my $newval = $changes{'internal.selfenroll_'.$item};
 7804:                             if ($item eq 'types') {
 7805:                                 if ($newval eq '') {
 7806:                                     $newval = &mt('None');
 7807:                                 } elsif ($newval eq '*') {
 7808:                                     $newval = &mt('Any user in any domain');
 7809:                                 }
 7810:                             } elsif ($item eq 'registered') {
 7811:                                 if ($newval eq '1') {
 7812:                                     $newval = &mt('Yes');
 7813:                                 } elsif ($newval eq '0') {
 7814:                                     $newval = &mt('No');
 7815:                                 }
 7816:                             }
 7817:                             $r->print('<li>'.&mt('"[_1]" set to "[_2]".',$title,$newval).'</li>'."\n");
 7818:                         }
 7819:                     }
 7820:                 }
 7821:                 $r->print('</ul>');
 7822:                 if ($env{'course.'.$cid.'.description'} ne '') {
 7823:                     my %newenvhash;
 7824:                     foreach my $key (keys(%changes)) {
 7825:                         $newenvhash{'course.'.$cid.'.'.$key} = $changes{$key};
 7826:                     }
 7827:                     &Apache::lonnet::appenv(\%newenvhash);
 7828:                 }
 7829:             } else {
 7830:                 $r->print(&mt('An error occurred when saving changes to self-enrollment settings in this course.').'<br />'.
 7831:                           &mt('The error was: [_1].',$putresult));
 7832:             }
 7833:         } else {
 7834:             $r->print(&mt('No changes were made to the existing self-enrollment settings in this course.'));
 7835:         }
 7836:     } else {
 7837:         $r->print(&mt('No changes were made to the existing self-enrollment settings in this course.'));
 7838:     }
 7839:     my $visactions = &cat_visibility();
 7840:     my ($cathash,%cattype);
 7841:     my %domconfig = &Apache::lonnet::get_dom('configuration',['coursecategories'],$cdom);
 7842:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 7843:         $cathash = $domconfig{'coursecategories'}{'cats'};
 7844:         $cattype{'auth'} = $domconfig{'coursecategories'}{'auth'};
 7845:         $cattype{'unauth'} = $domconfig{'coursecategories'}{'unauth'};
 7846:     } else {
 7847:         $cathash = {};
 7848:         $cattype{'auth'} = 'std';
 7849:         $cattype{'unauth'} = 'std';
 7850:     }
 7851:     if (($cattype{'auth'} eq 'none') && ($cattype{'unauth'} eq 'none')) {
 7852:         $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
 7853:                   '<br />'.
 7854:                   '<br />'.$visactions->{'take'}.'<ul>'.
 7855:                   '<li>'.$visactions->{'dc_chgconf'}.'</li>'.
 7856:                   '</ul>');
 7857:     } elsif (($cattype{'auth'} !~ /^(std|domonly)$/) && ($cattype{'unauth'} !~ /^(std|domonly)$/)) {
 7858:         if ($currsettings->{'uniquecode'}) {
 7859:             $r->print('<span class="LC_info">'.$visactions->{'vis'}.'</span>');
 7860:         } else {
 7861:             $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
 7862:                   '<br />'.
 7863:                   '<br />'.$visactions->{'take'}.'<ul>'.
 7864:                   '<li>'.$visactions->{'dc_setcode'}.'</li>'.
 7865:                   '</ul><br />');
 7866:         }
 7867:     } else {
 7868:         my ($visible,$cansetvis,$vismsgs) = &visible_in_stdcat($cdom,$cnum,\%domconfig);
 7869:         if (ref($visactions) eq 'HASH') {
 7870:             if (!$visible) {
 7871:                 $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
 7872:                           '<br />');
 7873:                 if (ref($vismsgs) eq 'ARRAY') {
 7874:                     $r->print('<br />'.$visactions->{'take'}.'<ul>');
 7875:                     foreach my $item (@{$vismsgs}) {
 7876:                         $r->print('<li>'.$visactions->{$item}.'</li>');
 7877:                     }
 7878:                     $r->print('</ul>');
 7879:                 }
 7880:                 $r->print($cansetvis);
 7881:             }
 7882:         }
 7883:     } 
 7884:     return;
 7885: }
 7886: 
 7887: #---------------------------------------------- end functions for &phase_two
 7888: 
 7889: #--------------------------------- functions for &phase_two and &phase_three
 7890: 
 7891: #--------------------------end of functions for &phase_two and &phase_three
 7892: 
 7893: 1;
 7894: __END__
 7895: 
 7896: 

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