File:  [LON-CAPA] / loncom / interface / loncreateuser.pm
Revision 1.414: download - view: text, annotated - select for diffs
Tue Oct 4 21:02:16 2016 UTC (7 years, 9 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Move routines for creating/modifying custom roles to lonuserutils.pm to
  facilitate re-use.
- Changes to standard role names and privilege names when switching from
  Course to Commmunity, when adding/modifying custom roles, with a domain
  role active, occur client-side, and no longer require page reload.

    1: # The LearningOnline Network with CAPA
    2: # Create a user
    3: #
    4: # $Id: loncreateuser.pm,v 1.414 2016/10/04 21:02:16 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 domadhocroles {
  535:     my ($ccuname,$ccdomain) = @_;
  536:     my $confname = &Apache::lonnet::get_domainconfiguser($env{'request.role.domain'}); 
  537:     my %existing=&Apache::lonnet::dump('roles',$env{'request.role.domain'},
  538:                                        $confname,'rolesdef_');
  539:     my $output;
  540:     if (keys(%existing) > 0) {
  541:         my @current;
  542:         my $curradhoc = 'adhocroles.'.$env{'request.role.domain'}; 
  543:         my %userenv = &Apache::lonnet::userenvironment($ccdomain,$ccuname,$curradhoc);
  544:         if ($userenv{$curradhoc}) {
  545:             @current = split(/,/,$userenv{$curradhoc});
  546:         }
  547:         my %customroles;
  548:         foreach my $key (keys(%existing)) {
  549:             if ($key=~/^rolesdef\_(\w+)$/) {
  550:                 my $rolename = $1;
  551:                 my %privs;
  552:                 ($privs{'system'},$privs{'domain'},$privs{'course'}) = split(/\_/,$existing{$key});
  553:                 $customroles{$rolename} = \%privs;
  554:             }
  555:         }
  556:         $output = '<br /><h3>'.
  557:                   &mt('Ad Hoc Course Roles Selectable via Helpdesk Role').
  558:                   '</h3>'."\n".
  559:                   &Apache::loncommon::start_data_table().
  560:                   &Apache::loncommon::start_data_table_header_row().
  561:                   '<th>'.&mt('Action').'</th><th>'.&mt('Role').'</th>'.
  562:                   '<th>'.&mt('Privileges in Course').'<th>'.
  563:                   &Apache::loncommon::end_data_table_header_row(); 
  564:         foreach my $key (sort(keys(%customroles))) {
  565:             $output .= &Apache::loncommon::start_data_table_row();
  566:             if (grep(/^\Q$key\E$/,@current)) {
  567:                 $output .= '<td><label>'.
  568:                            '<input type="checkbox" name="adhocroledel" value="'.$key.'" />'.
  569:                            &mt('Delete').'</label>'.
  570:                            '</td>';
  571:             } else {
  572:                 $output .= '<td><label>'.
  573:                            '<input type="checkbox" name="adhocroleadd" value="'.$key.'" />'.
  574:                            &mt('Add').'</label>'.
  575:                            '</td>';
  576:             }
  577:             $output .= '<td>'.$key.'</td><td>';
  578:             foreach my $level ('course','domain','system') {
  579:                 if ($customroles{$key}{$level}) {
  580:                     my $suffix;
  581:                     if (($level eq 'domain') || ($level eq 'system')) {
  582:                         $suffix = '&nbsp;('.&mt($level).')';
  583:                     }
  584:                     my @privs = split(/:/,$customroles{$key}{$level});
  585:                     foreach my $item (@privs) {
  586:                         next if ($item eq ''); 
  587:                         my ($priv,$cond) = split(/\&/,$item);
  588:                         $output .= &Apache::lonnet::plaintext($priv,'Course').$suffix.'<br />';
  589:                     }
  590:                 }
  591:             }
  592:             $output .= '</td>'.
  593:                        &Apache::loncommon::end_data_table_row();
  594:         }
  595:         $output .= &Apache::loncommon::end_data_table();
  596:     }
  597:     return $output;
  598: }
  599: 
  600: sub courserequest_titles {
  601:     my %titles = &Apache::lonlocal::texthash (
  602:                                    official   => 'Official',
  603:                                    unofficial => 'Unofficial',
  604:                                    community  => 'Communities',
  605:                                    textbook   => 'Textbook',
  606:                                    placement  => 'Placement Tests',
  607:                                    norequest  => 'Not allowed',
  608:                                    approval   => 'Approval by Dom. Coord.',
  609:                                    validate   => 'With validation',
  610:                                    autolimit  => 'Numerical limit',
  611:                                    unlimited  => '(blank for unlimited)',
  612:                  );
  613:     return %titles;
  614: }
  615: 
  616: sub courserequest_display {
  617:     my %titles = &Apache::lonlocal::texthash (
  618:                                    approval   => 'Yes, need approval',
  619:                                    validate   => 'Yes, with validation',
  620:                                    norequest  => 'No',
  621:    );
  622:    return %titles;
  623: }
  624: 
  625: sub requestauthor_titles {
  626:     my %titles = &Apache::lonlocal::texthash (
  627:                                    norequest  => 'Not allowed',
  628:                                    approval   => 'Approval by Dom. Coord.',
  629:                                    automatic  => 'Automatic approval',
  630:                  );
  631:     return %titles;
  632: 
  633: }
  634: 
  635: sub requestauthor_display {
  636:     my %titles = &Apache::lonlocal::texthash (
  637:                                    approval   => 'Yes, need approval',
  638:                                    automatic  => 'Yes, automatic approval',
  639:                                    norequest  => 'No',
  640:    );
  641:    return %titles;
  642: }
  643: 
  644: sub requestchange_display {
  645:     my %titles = &Apache::lonlocal::texthash (
  646:                                    approval   => "availability set to 'on' (approval required)", 
  647:                                    automatic  => "availability set to 'on' (automatic approval)",
  648:                                    norequest  => "availability set to 'off'",
  649:    );
  650:    return %titles;
  651: }
  652: 
  653: sub curr_requestauthor {
  654:     my ($uname,$udom,$isadv,$inststatuses,$domconfig) = @_;
  655:     return unless ((ref($inststatuses) eq 'ARRAY') && (ref($domconfig) eq 'HASH'));
  656:     if ($uname eq '' || $udom eq '') {
  657:         $uname = $env{'user.name'};
  658:         $udom = $env{'user.domain'};
  659:         $isadv = $env{'user.adv'};
  660:     }
  661:     my (%userenv,%settings,$val);
  662:     my @options = ('automatic','approval');
  663:     %userenv =
  664:         &Apache::lonnet::userenvironment($udom,$uname,'requestauthor','inststatus');
  665:     if ($userenv{'requestauthor'}) {
  666:         $val = $userenv{'requestauthor'};
  667:         @{$inststatuses} = ('_custom_');
  668:     } else {
  669:         my %alltasks;
  670:         if (ref($domconfig->{'requestauthor'}) eq 'HASH') {
  671:             %settings = %{$domconfig->{'requestauthor'}};
  672:             if (($isadv) && ($settings{'_LC_adv'} ne '')) {
  673:                 $val = $settings{'_LC_adv'};
  674:                 @{$inststatuses} = ('_LC_adv_');
  675:             } else {
  676:                 if ($userenv{'inststatus'} ne '') {
  677:                     @{$inststatuses} = split(',',$userenv{'inststatus'});
  678:                 } else {
  679:                     @{$inststatuses} = ('default');
  680:                 }
  681:                 foreach my $status (@{$inststatuses}) {
  682:                     if (exists($settings{$status})) {
  683:                         my $value = $settings{$status};
  684:                         next unless ($value);
  685:                         unless (exists($alltasks{$value})) {
  686:                             if (ref($alltasks{$value}) eq 'ARRAY') {
  687:                                 unless(grep(/^\Q$status\E$/,@{$alltasks{$value}})) {
  688:                                     push(@{$alltasks{$value}},$status);
  689:                                 }
  690:                             } else {
  691:                                 @{$alltasks{$value}} = ($status);
  692:                             }
  693:                         }
  694:                     }
  695:                 }
  696:                 foreach my $option (@options) {
  697:                     if ($alltasks{$option}) {
  698:                         $val = $option;
  699:                         last;
  700:                     }
  701:                 }
  702:             }
  703:         }
  704:     }
  705:     return $val;
  706: }
  707: 
  708: # =================================================================== Phase one
  709: 
  710: sub print_username_entry_form {
  711:     my ($r,$context,$response,$srch,$forcenewuser,$crstype,$brcrum) = @_;
  712:     my $defdom=$env{'request.role.domain'};
  713:     my $formtoset = 'crtuser';
  714:     if (exists($env{'form.startrolename'})) {
  715:         $formtoset = 'docustom';
  716:         $env{'form.rolename'} = $env{'form.startrolename'};
  717:     } elsif ($env{'form.origform'} eq 'crtusername') {
  718:         $formtoset =  $env{'form.origform'};
  719:     }
  720: 
  721:     my ($jsback,$elements) = &crumb_utilities();
  722: 
  723:     my $jscript = &Apache::loncommon::studentbrowser_javascript()."\n".
  724:         '<script type="text/javascript">'."\n".
  725:         '// <![CDATA['."\n".
  726:         &Apache::lonhtmlcommon::set_form_elements($elements->{$formtoset})."\n".
  727:         '// ]]>'."\n".
  728:         '</script>'."\n";
  729: 
  730:     my %existingroles=&Apache::lonuserutils::my_custom_roles($crstype);
  731:     if (($env{'form.action'} eq 'custom') && (keys(%existingroles) > 0)
  732:         && (&Apache::lonnet::allowed('mcr','/'))) {
  733:         $jscript .= &customrole_javascript();
  734:     }
  735:     my $helpitem = 'Course_Change_Privileges';
  736:     if ($env{'form.action'} eq 'custom') {
  737:         $helpitem = 'Course_Editing_Custom_Roles';
  738:     } elsif ($env{'form.action'} eq 'singlestudent') {
  739:         $helpitem = 'Course_Add_Student';
  740:     }
  741:     my %breadcrumb_text = &singleuser_breadcrumb($crstype);
  742:     if ($env{'form.action'} eq 'custom') {
  743:         push(@{$brcrum},
  744:                  {href=>"javascript:backPage(document.crtuser)",       
  745:                   text=>"Pick custom role",
  746:                   help => $helpitem,}
  747:                  );
  748:     } else {
  749:         push (@{$brcrum},
  750:                   {href => "javascript:backPage(document.crtuser)",
  751:                    text => $breadcrumb_text{'search'},
  752:                    help => $helpitem,
  753:                    faq  => 282,
  754:                    bug  => 'Instructor Interface',}
  755:                   );
  756:     }
  757:     my %loaditems = (
  758:                 'onload' => "javascript:setFormElements(document.$formtoset)",
  759:                     );
  760:     my $args = {bread_crumbs           => $brcrum,
  761:                 bread_crumbs_component => 'User Management',
  762:                 add_entries            => \%loaditems,};
  763:     $r->print(&Apache::loncommon::start_page('User Management',$jscript,$args));
  764: 
  765:     my %lt=&Apache::lonlocal::texthash(
  766:                     'srst' => 'Search for a user and enroll as a student',
  767:                     'srme' => 'Search for a user and enroll as a member',
  768:                     'srad' => 'Search for a user and modify/add user information or roles',
  769: 		    'usr'  => "Username",
  770:                     'dom'  => "Domain",
  771:                     'ecrp' => "Define or Edit Custom Role",
  772:                     'nr'   => "role name",
  773:                     'cre'  => "Next",
  774: 				       );
  775: 
  776:     if ($env{'form.action'} eq 'custom') {
  777:         if (&Apache::lonnet::allowed('mcr','/')) {
  778:             my $newroletext = &mt('Define new custom role:');
  779:             $r->print('<form action="/adm/createuser" method="post" name="docustom">'.
  780:                       '<input type="hidden" name="action" value="'.$env{'form.action'}.'" />'.
  781:                       '<input type="hidden" name="phase" value="selected_custom_edit" />'.
  782:                       '<h3>'.$lt{'ecrp'}.'</h3>'.
  783:                       &Apache::loncommon::start_data_table().
  784:                       &Apache::loncommon::start_data_table_row().
  785:                       '<td>');
  786:             if (keys(%existingroles) > 0) {
  787:                 $r->print('<br /><label><input type="radio" name="customroleaction" value="new" checked="checked" onclick="setCustomFields();" /><b>'.$newroletext.'</b></label>');
  788:             } else {
  789:                 $r->print('<br /><input type="hidden" name="customroleaction" value="new" /><b>'.$newroletext.'</b>');
  790:             }
  791:             $r->print('</td><td align="center">'.$lt{'nr'}.'<br /><input type="text" size="15" name="newrolename" onfocus="setCustomAction('."'new'".');" /></td>'.
  792:                       &Apache::loncommon::end_data_table_row());
  793:             if (keys(%existingroles) > 0) {
  794:                 $r->print(&Apache::loncommon::start_data_table_row().'<td><br />'.
  795:                           '<label><input type="radio" name="customroleaction" value="edit" onclick="setCustomFields();"/><b>'.
  796:                           &mt('View/Modify existing role:').'</b></label></td>'.
  797:                           '<td align="center"><br />'.
  798:                           '<select name="rolename" onchange="setCustomAction('."'edit'".');">'.
  799:                           '<option value="" selected="selected">'.
  800:                           &mt('Select'));
  801:                 foreach my $role (sort(keys(%existingroles))) {
  802:                     $r->print('<option value="'.$role.'">'.$role.'</option>');
  803:                 }
  804:                 $r->print('</select>'.
  805:                           '</td>'.
  806:                           &Apache::loncommon::end_data_table_row());
  807:             }
  808:             $r->print(&Apache::loncommon::end_data_table().'<p>'.
  809:                       '<input name="customeditor" type="submit" value="'.
  810:                       $lt{'cre'}.'" /></p>'.
  811:                       '</form>');
  812:         }
  813:     } else {
  814:         my $actiontext = $lt{'srad'};
  815:         if ($env{'form.action'} eq 'singlestudent') {
  816:             if ($crstype eq 'Community') {
  817:                 $actiontext = $lt{'srme'};
  818:             } else {
  819:                 $actiontext = $lt{'srst'};
  820:             }
  821:         }
  822:         $r->print("<h3>$actiontext</h3>");
  823:         if ($env{'form.origform'} ne 'crtusername') {
  824:             $r->print("\n".$response);
  825:         }
  826:         $r->print(&entry_form($defdom,$srch,$forcenewuser,$context,$response,$crstype));
  827:     }
  828: }
  829: 
  830: sub customrole_javascript {
  831:     my $js = <<"END";
  832: <script type="text/javascript">
  833: // <![CDATA[
  834: 
  835: function setCustomFields() {
  836:     if (document.docustom.customroleaction.length > 0) {
  837:         for (var i=0; i<document.docustom.customroleaction.length; i++) {
  838:             if (document.docustom.customroleaction[i].checked) {
  839:                 if (document.docustom.customroleaction[i].value == 'new') {
  840:                     document.docustom.rolename.selectedIndex = 0;
  841:                 } else {
  842:                     document.docustom.newrolename.value = '';
  843:                 }
  844:             }
  845:         }
  846:     }
  847:     return;
  848: }
  849: 
  850: function setCustomAction(caller) {
  851:     if (document.docustom.customroleaction.length > 0) {
  852:         for (var i=0; i<document.docustom.customroleaction.length; i++) {
  853:             if (document.docustom.customroleaction[i].value == caller) {
  854:                 document.docustom.customroleaction[i].checked = true;
  855:             }
  856:         }
  857:     }
  858:     setCustomFields();
  859:     return;
  860: }
  861: 
  862: // ]]>
  863: </script>
  864: END
  865:     return $js;
  866: }
  867: 
  868: sub entry_form {
  869:     my ($dom,$srch,$forcenewuser,$context,$responsemsg,$crstype) = @_;
  870:     my ($usertype,$inexact);
  871:     if (ref($srch) eq 'HASH') {
  872:         if (($srch->{'srchin'} eq 'dom') &&
  873:             ($srch->{'srchby'} eq 'uname') &&
  874:             ($srch->{'srchtype'} eq 'exact') &&
  875:             ($srch->{'srchdomain'} ne '') &&
  876:             ($srch->{'srchterm'} ne '')) {
  877:             my (%curr_rules,%got_rules);
  878:             my ($rules,$ruleorder) =
  879:                 &Apache::lonnet::inst_userrules($srch->{'srchdomain'},'username');
  880:             $usertype = &Apache::lonuserutils::check_usertype($srch->{'srchdomain'},$srch->{'srchterm'},$rules,\%curr_rules,\%got_rules);
  881:         } else {
  882:             $inexact = 1;
  883:         }
  884:     }
  885:     my $cancreate =
  886:         &Apache::lonuserutils::can_create_user($dom,$context,$usertype);
  887:     my ($userpicker,$cansearch) = 
  888:        &Apache::loncommon::user_picker($dom,$srch,$forcenewuser,
  889:                                        'document.crtuser',$cancreate,$usertype);
  890:     my $srchbutton = &mt('Search');
  891:     if ($env{'form.action'} eq 'singlestudent') {
  892:         $srchbutton = &mt('Search and Enroll');
  893:     } elsif ($cancreate && $responsemsg ne '' && $inexact) {
  894:         $srchbutton = &mt('Search or Add New User');
  895:     }
  896:     my $output;
  897:     if ($cansearch) {
  898:         $output = <<"ENDBLOCK";
  899: <form action="/adm/createuser" method="post" name="crtuser">
  900: <input type="hidden" name="action" value="$env{'form.action'}" />
  901: <input type="hidden" name="phase" value="get_user_info" />
  902: $userpicker
  903: <input name="userrole" type="button" value="$srchbutton" onclick="javascript:validateEntry(document.crtuser)" />
  904: </form>
  905: ENDBLOCK
  906:     } else {
  907:         $output = '<p>'.$userpicker.'</p>';
  908:     }
  909:     if ($env{'form.phase'} eq '') {
  910:         my $defdom=$env{'request.role.domain'};
  911:         my $domform = &Apache::loncommon::select_dom_form($defdom,'srchdomain');
  912:         my %lt=&Apache::lonlocal::texthash(
  913:                   'enro' => 'Enroll one student',
  914:                   'enrm' => 'Enroll one member',
  915:                   'admo' => 'Add/modify a single user',
  916:                   'crea' => 'create new user if required',
  917:                   'uskn' => "username is known",
  918:                   'crnu' => 'Create a new user',
  919:                   'usr'  => 'Username',
  920:                   'dom'  => 'in domain',
  921:                   'enrl' => 'Enroll',
  922:                   'cram'  => 'Create/Modify user',
  923:         );
  924:         my $sellink=&Apache::loncommon::selectstudent_link('crtusername','srchterm','srchdomain');
  925:         my ($title,$buttontext,$showresponse);
  926:         if ($env{'form.action'} eq 'singlestudent') {
  927:             if ($crstype eq 'Community') {
  928:                 $title = $lt{'enrm'};
  929:             } else {
  930:                 $title = $lt{'enro'};
  931:             }
  932:             $buttontext = $lt{'enrl'};
  933:         } else {
  934:             $title = $lt{'admo'};
  935:             $buttontext = $lt{'cram'};
  936:         }
  937:         if ($cancreate) {
  938:             $title .= ' <span class="LC_cusr_subheading">('.$lt{'crea'}.')</span>';
  939:         } else {
  940:             $title .= ' <span class="LC_cusr_subheading">('.$lt{'uskn'}.')</span>';
  941:         }
  942:         if ($env{'form.origform'} eq 'crtusername') {
  943:             $showresponse = $responsemsg;
  944:         }
  945:         $output .= <<"ENDDOCUMENT";
  946: <br />
  947: <form action="/adm/createuser" method="post" name="crtusername">
  948: <input type="hidden" name="action" value="$env{'form.action'}" />
  949: <input type="hidden" name="phase" value="createnewuser" />
  950: <input type="hidden" name="srchtype" value="exact" />
  951: <input type="hidden" name="srchby" value="uname" />
  952: <input type="hidden" name="srchin" value="dom" />
  953: <input type="hidden" name="forcenewuser" value="1" />
  954: <input type="hidden" name="origform" value="crtusername" />
  955: <h3>$title</h3>
  956: $showresponse
  957: <table>
  958:  <tr>
  959:   <td>$lt{'usr'}:</td>
  960:   <td><input type="text" size="15" name="srchterm" /></td>
  961:   <td>&nbsp;$lt{'dom'}:</td><td>$domform</td>
  962:   <td>&nbsp;$sellink&nbsp;</td>
  963:   <td>&nbsp;<input name="userrole" type="submit" value="$buttontext" /></td>
  964:  </tr>
  965: </table>
  966: </form>
  967: ENDDOCUMENT
  968:     }
  969:     return $output;
  970: }
  971: 
  972: sub user_modification_js {
  973:     my ($pjump_def,$dc_setcourse_code,$nondc_setsection_code,$groupslist)=@_;
  974:     
  975:     return <<END;
  976: <script type="text/javascript" language="Javascript">
  977: // <![CDATA[
  978: 
  979:     $pjump_def
  980:     $dc_setcourse_code
  981: 
  982:     function dateset() {
  983:         eval("document.cu."+document.cu.pres_marker.value+
  984:             ".value=document.cu.pres_value.value");
  985:         modalWindow.close();
  986:     }
  987: 
  988:     $nondc_setsection_code
  989: // ]]>
  990: </script>
  991: END
  992: }
  993: 
  994: # =================================================================== Phase two
  995: sub print_user_selection_page {
  996:     my ($r,$response,$srch,$srch_results,$srcharray,$context,$opener_elements,$crstype,$brcrum) = @_;
  997:     my @fields = ('username','domain','lastname','firstname','permanentemail');
  998:     my $sortby = $env{'form.sortby'};
  999: 
 1000:     if (!grep(/^\Q$sortby\E$/,@fields)) {
 1001:         $sortby = 'lastname';
 1002:     }
 1003: 
 1004:     my ($jsback,$elements) = &crumb_utilities();
 1005: 
 1006:     my $jscript = (<<ENDSCRIPT);
 1007: <script type="text/javascript">
 1008: // <![CDATA[
 1009: function pickuser(uname,udom) {
 1010:     document.usersrchform.seluname.value=uname;
 1011:     document.usersrchform.seludom.value=udom;
 1012:     document.usersrchform.phase.value="userpicked";
 1013:     document.usersrchform.submit();
 1014: }
 1015: 
 1016: $jsback
 1017: // ]]>
 1018: </script>
 1019: ENDSCRIPT
 1020: 
 1021:     my %lt=&Apache::lonlocal::texthash(
 1022:                                        'usrch'          => "User Search to add/modify roles",
 1023:                                        'stusrch'        => "User Search to enroll student",
 1024:                                        'memsrch'        => "User Search to enroll member",
 1025:                                        'usel'           => "Select a user to add/modify roles",
 1026:                                        'stusel'         => "Select a user to enroll as a student",
 1027:                                        'memsel'         => "Select a user to enroll as a member",
 1028:                                        'username'       => "username",
 1029:                                        'domain'         => "domain",
 1030:                                        'lastname'       => "last name",
 1031:                                        'firstname'      => "first name",
 1032:                                        'permanentemail' => "permanent e-mail",
 1033:                                       );
 1034:     if ($context eq 'requestcrs') {
 1035:         $r->print('<div>');
 1036:     } else {
 1037:         my %breadcrumb_text = &singleuser_breadcrumb($crstype);
 1038:         my $helpitem;
 1039:         if ($env{'form.action'} eq 'singleuser') {
 1040:             $helpitem = 'Course_Change_Privileges';
 1041:         } elsif ($env{'form.action'} eq 'singlestudent') {
 1042:             $helpitem = 'Course_Add_Student';
 1043:         }
 1044:         push (@{$brcrum},
 1045:                   {href => "javascript:backPage(document.usersrchform,'','')",
 1046:                    text => $breadcrumb_text{'search'},
 1047:                    faq  => 282,
 1048:                    bug  => 'Instructor Interface',},
 1049:                   {href => "javascript:backPage(document.usersrchform,'get_user_info','select')",
 1050:                    text => $breadcrumb_text{'userpicked'},
 1051:                    faq  => 282,
 1052:                    bug  => 'Instructor Interface',
 1053:                    help => $helpitem}
 1054:                   );
 1055:         $r->print(&Apache::loncommon::start_page('User Management',$jscript,{bread_crumbs => $brcrum}));
 1056:         if ($env{'form.action'} eq 'singleuser') {
 1057:             $r->print("<b>$lt{'usrch'}</b><br />");
 1058:             $r->print(&entry_form($srch->{'srchdomain'},$srch,undef,$context,undef,$crstype));
 1059:             $r->print('<h3>'.$lt{'usel'}.'</h3>');
 1060:         } elsif ($env{'form.action'} eq 'singlestudent') {
 1061:             $r->print($jscript."<b>");
 1062:             if ($crstype eq 'Community') {
 1063:                 $r->print($lt{'memsrch'});
 1064:             } else {
 1065:                 $r->print($lt{'stusrch'});
 1066:             }
 1067:             $r->print("</b><br />");
 1068:             $r->print(&entry_form($srch->{'srchdomain'},$srch,undef,$context,undef,$crstype));
 1069:             $r->print('</form><h3>');
 1070:             if ($crstype eq 'Community') {
 1071:                 $r->print($lt{'memsel'});
 1072:             } else {
 1073:                 $r->print($lt{'stusel'});
 1074:             }
 1075:             $r->print('</h3>');
 1076:         }
 1077:     }
 1078:     $r->print('<form name="usersrchform" method="post" action="">'.
 1079:               &Apache::loncommon::start_data_table()."\n".
 1080:               &Apache::loncommon::start_data_table_header_row()."\n".
 1081:               ' <th> </th>'."\n");
 1082:     foreach my $field (@fields) {
 1083:         $r->print(' <th><a href="javascript:document.usersrchform.sortby.value='.
 1084:                   "'".$field."'".';document.usersrchform.submit();">'.
 1085:                   $lt{$field}.'</a></th>'."\n");
 1086:     }
 1087:     $r->print(&Apache::loncommon::end_data_table_header_row());
 1088: 
 1089:     my @sorted_users = sort {
 1090:         lc($srch_results->{$a}->{$sortby})   cmp lc($srch_results->{$b}->{$sortby})
 1091:             ||
 1092:         lc($srch_results->{$a}->{lastname})  cmp lc($srch_results->{$b}->{lastname})
 1093:             ||
 1094:         lc($srch_results->{$a}->{firstname}) cmp lc($srch_results->{$b}->{firstname})
 1095: 	    ||
 1096: 	lc($a) cmp lc($b)
 1097:         } (keys(%$srch_results));
 1098: 
 1099:     foreach my $user (@sorted_users) {
 1100:         my ($uname,$udom) = split(/:/,$user);
 1101:         my $onclick;
 1102:         if ($context eq 'requestcrs') {
 1103:             $onclick =
 1104:                 'onclick="javascript:gochoose('."'$uname','$udom',".
 1105:                                                "'$srch_results->{$user}->{firstname}',".
 1106:                                                "'$srch_results->{$user}->{lastname}',".
 1107:                                                "'$srch_results->{$user}->{permanentemail}'".');"';
 1108:         } else {
 1109:             $onclick =
 1110:                 ' onclick="javascript:pickuser('."'".$uname."'".','."'".$udom."'".');"';
 1111:         }
 1112:         $r->print(&Apache::loncommon::start_data_table_row().
 1113:                   '<td><input type="button" name="seluser" value="'.&mt('Select').'" '.
 1114:                   $onclick.' /></td>'.
 1115:                   '<td><tt>'.$uname.'</tt></td>'.
 1116:                   '<td><tt>'.$udom.'</tt></td>');
 1117:         foreach my $field ('lastname','firstname','permanentemail') {
 1118:             $r->print('<td>'.$srch_results->{$user}->{$field}.'</td>');
 1119:         }
 1120:         $r->print(&Apache::loncommon::end_data_table_row());
 1121:     }
 1122:     $r->print(&Apache::loncommon::end_data_table().'<br /><br />');
 1123:     if (ref($srcharray) eq 'ARRAY') {
 1124:         foreach my $item (@{$srcharray}) {
 1125:             $r->print('<input type="hidden" name="'.$item.'" value="'.$env{'form.'.$item}.'" />'."\n");
 1126:         }
 1127:     }
 1128:     $r->print(' <input type="hidden" name="sortby" value="'.$sortby.'" />'."\n".
 1129:               ' <input type="hidden" name="seluname" value="" />'."\n".
 1130:               ' <input type="hidden" name="seludom" value="" />'."\n".
 1131:               ' <input type="hidden" name="currstate" value="select" />'."\n".
 1132:               ' <input type="hidden" name="phase" value="get_user_info" />'."\n".
 1133:               ' <input type="hidden" name="action" value="'.$env{'form.action'}.'" />'."\n");
 1134:     if ($context eq 'requestcrs') {
 1135:         $r->print($opener_elements.'</form></div>');
 1136:     } else {
 1137:         $r->print($response.'</form>');
 1138:     }
 1139: }
 1140: 
 1141: sub print_user_query_page {
 1142:     my ($r,$caller,$brcrum) = @_;
 1143: # FIXME - this is for a network-wide name search (similar to catalog search)
 1144: # To use frames with similar behavior to catalog/portfolio search.
 1145: # To be implemented. 
 1146:     return;
 1147: }
 1148: 
 1149: sub print_user_modification_page {
 1150:     my ($r,$ccuname,$ccdomain,$srch,$response,$context,$permission,$crstype,
 1151:         $brcrum,$showcredits) = @_;
 1152:     if (($ccuname eq '') || ($ccdomain eq '')) {
 1153:         my $usermsg = &mt('No username and/or domain provided.');
 1154:         $env{'form.phase'} = '';
 1155: 	&print_username_entry_form($r,$context,$usermsg,'','',$crstype,$brcrum);
 1156:         return;
 1157:     }
 1158:     my ($form,$formname);
 1159:     if ($env{'form.action'} eq 'singlestudent') {
 1160:         $form = 'document.enrollstudent';
 1161:         $formname = 'enrollstudent';
 1162:     } else {
 1163:         $form = 'document.cu';
 1164:         $formname = 'cu';
 1165:     }
 1166:     my %abv_auth = &auth_abbrev();
 1167:     my (%rulematch,%inst_results,$newuser,%alerts,%curr_rules,%got_rules);
 1168:     my $uhome=&Apache::lonnet::homeserver($ccuname,$ccdomain);
 1169:     if ($uhome eq 'no_host') {
 1170:         my $usertype;
 1171:         my ($rules,$ruleorder) =
 1172:             &Apache::lonnet::inst_userrules($ccdomain,'username');
 1173:             $usertype =
 1174:                 &Apache::lonuserutils::check_usertype($ccdomain,$ccuname,$rules,
 1175:                                                       \%curr_rules,\%got_rules);
 1176:         my $cancreate =
 1177:             &Apache::lonuserutils::can_create_user($ccdomain,$context,
 1178:                                                    $usertype);
 1179:         if (!$cancreate) {
 1180:             my $helplink = 'javascript:helpMenu('."'display'".')';
 1181:             my %usertypetext = (
 1182:                 official   => 'institutional',
 1183:                 unofficial => 'non-institutional',
 1184:             );
 1185:             my $response;
 1186:             if ($env{'form.origform'} eq 'crtusername') {
 1187:                 $response = '<span class="LC_warning">'.
 1188:                             &mt('No match found for the username [_1] in LON-CAPA domain: [_2]',
 1189:                                 '<b>'.$ccuname.'</b>',$ccdomain).
 1190:                             '</span><br />';
 1191:             }
 1192:             $response .= '<p class="LC_warning">'
 1193:                         .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
 1194:                         .' '
 1195:                         .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
 1196:                             ,'<a href="'.$helplink.'">','</a>')
 1197:                         .'</p><br />';
 1198:             $env{'form.phase'} = '';
 1199:             &print_username_entry_form($r,$context,$response,undef,undef,$crstype,$brcrum);
 1200:             return;
 1201:         }
 1202:         $newuser = 1;
 1203:         my $checkhash;
 1204:         my $checks = { 'username' => 1 };
 1205:         $checkhash->{$ccuname.':'.$ccdomain} = { 'newuser' => $newuser };
 1206:         &Apache::loncommon::user_rule_check($checkhash,$checks,
 1207:             \%alerts,\%rulematch,\%inst_results,\%curr_rules,\%got_rules);
 1208:         if (ref($alerts{'username'}) eq 'HASH') {
 1209:             if (ref($alerts{'username'}{$ccdomain}) eq 'HASH') {
 1210:                 my $domdesc =
 1211:                     &Apache::lonnet::domain($ccdomain,'description');
 1212:                 if ($alerts{'username'}{$ccdomain}{$ccuname}) {
 1213:                     my $userchkmsg;
 1214:                     if (ref($curr_rules{$ccdomain}) eq 'HASH') {  
 1215:                         $userchkmsg = 
 1216:                             &Apache::loncommon::instrule_disallow_msg('username',
 1217:                                                                  $domdesc,1).
 1218:                         &Apache::loncommon::user_rule_formats($ccdomain,
 1219:                             $domdesc,$curr_rules{$ccdomain}{'username'},
 1220:                             'username');
 1221:                     }
 1222:                     $env{'form.phase'} = '';
 1223:                     &print_username_entry_form($r,$context,$userchkmsg,undef,undef,$crstype,$brcrum);
 1224:                     return;
 1225:                 }
 1226:             }
 1227:         }
 1228:     } else {
 1229:         $newuser = 0;
 1230:     }
 1231:     if ($response) {
 1232:         $response = '<br />'.$response;
 1233:     }
 1234: 
 1235:     my $pjump_def = &Apache::lonhtmlcommon::pjump_javascript_definition();
 1236:     my $dc_setcourse_code = '';
 1237:     my $nondc_setsection_code = '';                                        
 1238:     my %loaditem;
 1239: 
 1240:     my $groupslist = &Apache::lonuserutils::get_groupslist();
 1241: 
 1242:     my $js = &validation_javascript($context,$ccdomain,$pjump_def,$crstype,
 1243:                                $groupslist,$newuser,$formname,\%loaditem);
 1244:     my %breadcrumb_text = &singleuser_breadcrumb($crstype);
 1245:     my $helpitem = 'Course_Change_Privileges';
 1246:     if ($env{'form.action'} eq 'singlestudent') {
 1247:         $helpitem = 'Course_Add_Student';
 1248:     }
 1249:     push (@{$brcrum},
 1250:         {href => "javascript:backPage($form)",
 1251:          text => $breadcrumb_text{'search'},
 1252:          faq  => 282,
 1253:          bug  => 'Instructor Interface',});
 1254:     if ($env{'form.phase'} eq 'userpicked') {
 1255:        push(@{$brcrum},
 1256:               {href => "javascript:backPage($form,'get_user_info','select')",
 1257:                text => $breadcrumb_text{'userpicked'},
 1258:                faq  => 282,
 1259:                bug  => 'Instructor Interface',});
 1260:     }
 1261:     push(@{$brcrum},
 1262:             {href => "javascript:backPage($form,'$env{'form.phase'}','modify')",
 1263:              text => $breadcrumb_text{'modify'},
 1264:              faq  => 282,
 1265:              bug  => 'Instructor Interface',
 1266:              help => $helpitem});
 1267:     my $args = {'add_entries'           => \%loaditem,
 1268:                 'bread_crumbs'          => $brcrum,
 1269:                 'bread_crumbs_component' => 'User Management'};
 1270:     if ($env{'form.popup'}) {
 1271:         $args->{'no_nav_bar'} = 1;
 1272:     }
 1273:     my $start_page =
 1274:         &Apache::loncommon::start_page('User Management',$js,$args);
 1275: 
 1276:     my $forminfo =<<"ENDFORMINFO";
 1277: <form action="/adm/createuser" method="post" name="$formname">
 1278: <input type="hidden" name="phase" value="update_user_data" />
 1279: <input type="hidden" name="ccuname" value="$ccuname" />
 1280: <input type="hidden" name="ccdomain" value="$ccdomain" />
 1281: <input type="hidden" name="pres_value"  value="" />
 1282: <input type="hidden" name="pres_type"   value="" />
 1283: <input type="hidden" name="pres_marker" value="" />
 1284: ENDFORMINFO
 1285:     my (%inccourses,$roledom,$defaultcredits);
 1286:     if ($context eq 'course') {
 1287:         $inccourses{$env{'request.course.id'}}=1;
 1288:         $roledom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 1289:         if ($showcredits) {
 1290:             $defaultcredits = &Apache::lonuserutils::get_defaultcredits();
 1291:         }
 1292:     } elsif ($context eq 'author') {
 1293:         $roledom = $env{'request.role.domain'};
 1294:     } elsif ($context eq 'domain') {
 1295:         foreach my $key (keys(%env)) {
 1296:             $roledom = $env{'request.role.domain'};
 1297:             if ($key=~/^user\.priv\.cm\.\/($roledom)\/($match_username)/) {
 1298:                 $inccourses{$1.'_'.$2}=1;
 1299:             }
 1300:         }
 1301:     } else {
 1302:         foreach my $key (keys(%env)) {
 1303: 	    if ($key=~/^user\.priv\.cm\.\/($match_domain)\/($match_username)/) {
 1304: 	        $inccourses{$1.'_'.$2}=1;
 1305:             }
 1306:         }
 1307:     }
 1308:     my $title = '';
 1309:     if ($newuser) {
 1310:         my ($portfolioform,$domroleform,$adhocroleform);
 1311:         if ((&Apache::lonnet::allowed('mpq',$env{'request.role.domain'})) ||
 1312:             (&Apache::lonnet::allowed('mut',$env{'request.role.domain'}))) {
 1313:             # Current user has quota or user tools modification privileges
 1314:             $portfolioform = '<br />'.&user_quotas($ccuname,$ccdomain);
 1315:         }
 1316:         if ((&Apache::lonnet::allowed('cau',$env{'request.role.domain'})) &&
 1317:             ($ccdomain eq $env{'request.role.domain'})) {
 1318:             $domroleform = '<br />'.&domainrole_req($ccuname,$ccdomain);
 1319:         }
 1320:         if (&Apache::lonnet::allowed('cdh',$env{'request.role.domain'})) {
 1321:             $adhocroleform = &domadhocroles($ccuname,$ccdomain);
 1322:             if ($adhocroleform) {
 1323:                 $adhocroleform = '<br />'.$adhocroleform;
 1324:             }
 1325:         }
 1326:         &initialize_authen_forms($ccdomain,$formname);
 1327:         my %lt=&Apache::lonlocal::texthash(
 1328:                 'lg'             => 'Login Data',
 1329:                 'hs'             => "Home Server",
 1330:         );
 1331: 	$r->print(<<ENDTITLE);
 1332: $start_page
 1333: $response
 1334: $forminfo
 1335: <script type="text/javascript" language="Javascript">
 1336: // <![CDATA[
 1337: $loginscript
 1338: // ]]>
 1339: </script>
 1340: <input type='hidden' name='makeuser' value='1' />
 1341: ENDTITLE
 1342:         if ($env{'form.action'} eq 'singlestudent') {
 1343:             if ($crstype eq 'Community') {
 1344:                 $title = &mt('Create New User [_1] in domain [_2] as a member',
 1345:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1346:             } else {
 1347:                 $title = &mt('Create New User [_1] in domain [_2] as a student',
 1348:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1349:             }
 1350:         } else {
 1351:                 $title = &mt('Create New User [_1] in domain [_2]',
 1352:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1353:         }
 1354:         $r->print('<h2>'.$title.'</h2>'."\n");
 1355:         $r->print('<div class="LC_left_float">');
 1356:         $r->print(&personal_data_display($ccuname,$ccdomain,$newuser,$context,
 1357:                                          $inst_results{$ccuname.':'.$ccdomain}));
 1358:         # Option to disable student/employee ID conflict checking not offerred for new users.
 1359:         my ($home_server_pick,$numlib) = 
 1360:             &Apache::loncommon::home_server_form_item($ccdomain,'hserver',
 1361:                                                       'default','hide');
 1362:         if ($numlib > 1) {
 1363:             $r->print("
 1364: <br />
 1365: $lt{'hs'}: $home_server_pick
 1366: <br />");
 1367:         } else {
 1368:             $r->print($home_server_pick);
 1369:         }
 1370:         if (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) {
 1371:             $r->print('<br /><h3>'.
 1372:                       &mt('User Can Request Creation of Courses/Communities in this Domain?').'</h3>'.
 1373:                       &Apache::loncommon::start_data_table().
 1374:                       &build_tools_display($ccuname,$ccdomain,
 1375:                                            'requestcourses').
 1376:                       &Apache::loncommon::end_data_table());
 1377:         }
 1378:         $r->print('</div>'."\n".'<div class="LC_left_float"><h3>'.
 1379:                   $lt{'lg'}.'</h3>');
 1380:         my ($fixedauth,$varauth,$authmsg); 
 1381:         if (ref($rulematch{$ccuname.':'.$ccdomain}) eq 'HASH') {
 1382:             my $matchedrule = $rulematch{$ccuname.':'.$ccdomain}{'username'};
 1383:             my ($rules,$ruleorder) = 
 1384:                 &Apache::lonnet::inst_userrules($ccdomain,'username');
 1385:             if (ref($rules) eq 'HASH') {
 1386:                 if (ref($rules->{$matchedrule}) eq 'HASH') {
 1387:                     my $authtype = $rules->{$matchedrule}{'authtype'};
 1388:                     if ($authtype !~ /^(krb4|krb5|int|fsys|loc)$/) {
 1389:                         $r->print(&Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc));
 1390:                     } else { 
 1391:                         my $authparm = $rules->{$matchedrule}{'authparm'};
 1392:                         $authmsg = $rules->{$matchedrule}{'authmsg'};
 1393:                         if ($authtype =~ /^krb(4|5)$/) {
 1394:                             my $ver = $1;
 1395:                             if ($authparm ne '') {
 1396:                                 $fixedauth = <<"KERB"; 
 1397: <input type="hidden" name="login" value="krb" />
 1398: <input type="hidden" name="krbver" value="$ver" />
 1399: <input type="hidden" name="krbarg" value="$authparm" />
 1400: KERB
 1401:                             }
 1402:                         } else {
 1403:                             $fixedauth = 
 1404: '<input type="hidden" name="login" value="'.$authtype.'" />'."\n";
 1405:                             if ($rules->{$matchedrule}{'authparmfixed'}) {
 1406:                                 $fixedauth .=    
 1407: '<input type="hidden" name="'.$authtype.'arg" value="'.$authparm.'" />'."\n";
 1408:                             } else {
 1409:                                 if ($authtype eq 'int') {
 1410:                                     $varauth = '<br />'.
 1411: &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>';
 1412:                                 } elsif ($authtype eq 'loc') {
 1413:                                     $varauth = '<br />'.
 1414: &mt('[_1] Local Authentication with argument [_2]','','<input type="text" name="'.$authtype.'arg" value="" />')."\n";
 1415:                                 } else {
 1416:                                     $varauth =
 1417: '<input type="text" name="'.$authtype.'arg" value="" />'."\n";
 1418:                                 }
 1419:                             }
 1420:                         }
 1421:                     }
 1422:                 } else {
 1423:                     $r->print(&Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc));
 1424:                 }
 1425:             }
 1426:             if ($authmsg) {
 1427:                 $r->print(<<ENDAUTH);
 1428: $fixedauth
 1429: $authmsg
 1430: $varauth
 1431: ENDAUTH
 1432:             }
 1433:         } else {
 1434:             $r->print(&Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc)); 
 1435:         }
 1436:         $r->print($portfolioform.$domroleform.$adhocroleform);
 1437:         if ($env{'form.action'} eq 'singlestudent') {
 1438:             $r->print(&date_sections_select($context,$newuser,$formname,
 1439:                                             $permission,$crstype,$ccuname,
 1440:                                             $ccdomain,$showcredits));
 1441:         }
 1442:         $r->print('</div><div class="LC_clear_float_footer"></div>');
 1443:     } else { # user already exists
 1444: 	$r->print($start_page.$forminfo);
 1445:         if ($env{'form.action'} eq 'singlestudent') {
 1446:             if ($crstype eq 'Community') {
 1447:                 $title = &mt('Enroll one member: [_1] in domain [_2]',
 1448:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1449:             } else {
 1450:                 $title = &mt('Enroll one student: [_1] in domain [_2]',
 1451:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1452:             }
 1453:         } else {
 1454:             $title = &mt('Modify existing user: [_1] in domain [_2]',
 1455:                              '"'.$ccuname.'"','"'.$ccdomain.'"');
 1456:         }
 1457:         $r->print('<h2>'.$title.'</h2>'."\n");
 1458:         $r->print('<div class="LC_left_float">');
 1459:         $r->print(&personal_data_display($ccuname,$ccdomain,$newuser,$context,
 1460:                                          $inst_results{$ccuname.':'.$ccdomain}));
 1461:         if (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) {
 1462:             $r->print('<br /><h3>'.&mt('User Can Request Creation of Courses/Communities in this Domain?').'</h3>'.
 1463:                       &Apache::loncommon::start_data_table());
 1464:             if ($env{'request.role.domain'} eq $ccdomain) {
 1465:                 $r->print(&build_tools_display($ccuname,$ccdomain,'requestcourses'));
 1466:             } else {
 1467:                 $r->print(&coursereq_externaluser($ccuname,$ccdomain,
 1468:                                                   $env{'request.role.domain'}));
 1469:             }
 1470:             $r->print(&Apache::loncommon::end_data_table());
 1471:         }
 1472:         $r->print('</div>');
 1473:         my @order = ('auth','quota','tools','requestauthor','adhocroles');
 1474:         my %user_text;
 1475:         my ($isadv,$isauthor) = 
 1476:             &Apache::lonnet::is_advanced_user($ccuname,$ccdomain);
 1477:         if ((!$isauthor) && 
 1478:             (&Apache::lonnet::allowed('cau',$env{'request.role.domain'}))
 1479:             && ($env{'request.role.domain'} eq $ccdomain)) {
 1480:             $user_text{'requestauthor'} = &domainrole_req($ccuname,$ccdomain);
 1481:         }
 1482:         if (&Apache::lonnet::allowed('cdh',$env{'request.role.domain'})) {
 1483:             $user_text{'adhocroles'} = &domadhocroles($ccuname,$ccdomain);
 1484:         }
 1485:         $user_text{'auth'} =  &user_authentication($ccuname,$ccdomain,$formname);
 1486:         if ((&Apache::lonnet::allowed('mpq',$ccdomain)) ||
 1487:             (&Apache::lonnet::allowed('mut',$ccdomain))) {
 1488:             # Current user has quota modification privileges
 1489:             $user_text{'quota'} = &user_quotas($ccuname,$ccdomain);
 1490:         }
 1491:         if (!&Apache::lonnet::allowed('mpq',$ccdomain)) {
 1492:             if (&Apache::lonnet::allowed('mpq',$env{'request.role.domain'})) {
 1493:                 my %lt=&Apache::lonlocal::texthash(
 1494:                     'dska'  => "Disk quotas for user's portfolio and Authoring Space",
 1495:                     'youd'  => "You do not have privileges to modify the portfolio and/or Authoring Space quotas for this user.",
 1496:                     'ichr'  => "If a change is required, contact a domain coordinator for the domain",
 1497:                 );
 1498:                 $user_text{'quota'} = <<ENDNOPORTPRIV;
 1499: <h3>$lt{'dska'}</h3>
 1500: $lt{'youd'} $lt{'ichr'}: $ccdomain
 1501: ENDNOPORTPRIV
 1502:             }
 1503:         }
 1504:         if (!&Apache::lonnet::allowed('mut',$ccdomain)) {
 1505:             if (&Apache::lonnet::allowed('mut',$env{'request.role.domain'})) {
 1506:                 my %lt=&Apache::lonlocal::texthash(
 1507:                     'utav'  => "User Tools Availability",
 1508:                     'yodo'  => "You do not have privileges to modify Portfolio, Blog, WebDAV, or Personal Information Page settings for this user.",
 1509:                     'ifch'  => "If a change is required, contact a domain coordinator for the domain",
 1510:                 );
 1511:                 $user_text{'tools'} = <<ENDNOTOOLSPRIV;
 1512: <h3>$lt{'utav'}</h3>
 1513: $lt{'yodo'} $lt{'ifch'}: $ccdomain
 1514: ENDNOTOOLSPRIV
 1515:             }
 1516:         }
 1517:         my $gotdiv = 0; 
 1518:         foreach my $item (@order) {
 1519:             if ($user_text{$item} ne '') {
 1520:                 unless ($gotdiv) {
 1521:                     $r->print('<div class="LC_left_float">');
 1522:                     $gotdiv = 1;
 1523:                 }
 1524:                 $r->print('<br />'.$user_text{$item});
 1525:             }
 1526:         }
 1527:         if ($env{'form.action'} eq 'singlestudent') {
 1528:             unless ($gotdiv) {
 1529:                 $r->print('<div class="LC_left_float">');
 1530:             }
 1531:             my $credits;
 1532:             if ($showcredits) {
 1533:                 $credits = &get_user_credits($ccuname,$ccdomain,$defaultcredits);
 1534:                 if ($credits eq '') {
 1535:                     $credits = $defaultcredits;
 1536:                 }
 1537:             }
 1538:             $r->print(&date_sections_select($context,$newuser,$formname,
 1539:                                             $permission,$crstype,$ccuname,
 1540:                                             $ccdomain,$showcredits));
 1541:         }
 1542:         if ($gotdiv) {
 1543:             $r->print('</div><div class="LC_clear_float_footer"></div>');
 1544:         }
 1545:         if ($env{'form.action'} ne 'singlestudent') {
 1546:             &display_existing_roles($r,$ccuname,$ccdomain,\%inccourses,$context,
 1547:                                     $roledom,$crstype);
 1548:         }
 1549:     } ## End of new user/old user logic
 1550:     if ($env{'form.action'} eq 'singlestudent') {
 1551:         my $btntxt;
 1552:         if ($crstype eq 'Community') {
 1553:             $btntxt = &mt('Enroll Member');
 1554:         } else {
 1555:             $btntxt = &mt('Enroll Student');
 1556:         }
 1557:         $r->print('<br /><input type="button" value="'.$btntxt.'" onclick="setSections(this.form)" />'."\n");
 1558:     } else {
 1559:         $r->print('<div class="LC_left_float">'.
 1560:                   '<fieldset><legend>'.&mt('Add Roles').'</legend>');
 1561:         my $addrolesdisplay = 0;
 1562:         if ($context eq 'domain' || $context eq 'author') {
 1563:             $addrolesdisplay = &new_coauthor_roles($r,$ccuname,$ccdomain);
 1564:         }
 1565:         if ($context eq 'domain') {
 1566:             my $add_domainroles = &new_domain_roles($r,$ccdomain);
 1567:             if (!$addrolesdisplay) {
 1568:                 $addrolesdisplay = $add_domainroles;
 1569:             }
 1570:             $r->print(&course_level_dc($env{'request.role.domain'},$showcredits));
 1571:             $r->print('</fieldset></div><div class="LC_clear_float_footer"></div>'.
 1572:                       '<br /><input type="button" value="'.&mt('Save').'" onclick="setCourse()" />'."\n");
 1573:         } elsif ($context eq 'author') {
 1574:             if ($addrolesdisplay) {
 1575:                 $r->print('</fieldset></div><div class="LC_clear_float_footer"></div>'.
 1576:                           '<br /><input type="button" value="'.&mt('Save').'"');
 1577:                 if ($newuser) {
 1578:                     $r->print(' onclick="auth_check()" \>'."\n");
 1579:                 } else {
 1580:                     $r->print('onclick="this.form.submit()" \>'."\n");
 1581:                 }
 1582:             } else {
 1583:                 $r->print('</fieldset></div>'.
 1584:                           '<div class="LC_clear_float_footer"></div>'.
 1585:                           '<br /><a href="javascript:backPage(document.cu)">'.
 1586:                           &mt('Back to previous page').'</a>');
 1587:             }
 1588:         } else {
 1589:             $r->print(&course_level_table(\%inccourses,$showcredits,$defaultcredits));
 1590:             $r->print('</fieldset></div><div class="LC_clear_float_footer"></div>'.
 1591:                       '<br /><input type="button" value="'.&mt('Save').'" onclick="setSections(this.form)" />'."\n");
 1592:         }
 1593:     }
 1594:     $r->print(&Apache::lonhtmlcommon::echo_form_input(['phase','userrole','ccdomain','prevphase','currstate','ccuname','ccdomain']));
 1595:     $r->print('<input type="hidden" name="currstate" value="" />');
 1596:     $r->print('<input type="hidden" name="prevphase" value="'.$env{'form.phase'}.'" /></form><br /><br />');
 1597:     return;
 1598: }
 1599: 
 1600: sub singleuser_breadcrumb {
 1601:     my ($crstype) = @_;
 1602:     my %breadcrumb_text;
 1603:     if ($env{'form.action'} eq 'singlestudent') {
 1604:         if ($crstype eq 'Community') {
 1605:             $breadcrumb_text{'search'} = 'Enroll a member';
 1606:         } else {
 1607:             $breadcrumb_text{'search'} = 'Enroll a student';
 1608:         }
 1609:         $breadcrumb_text{'userpicked'} = 'Select a user',
 1610:         $breadcrumb_text{'modify'} = 'Set section/dates',
 1611:     } else {
 1612:         $breadcrumb_text{'search'} = 'Create/modify a user';
 1613:         $breadcrumb_text{'userpicked'} = 'Select a user',
 1614:         $breadcrumb_text{'modify'} = 'Set user role',
 1615:     }
 1616:     return %breadcrumb_text;
 1617: }
 1618: 
 1619: sub date_sections_select {
 1620:     my ($context,$newuser,$formname,$permission,$crstype,$ccuname,$ccdomain,
 1621:         $showcredits) = @_;
 1622:     my $credits;
 1623:     if ($showcredits) {
 1624:         my $defaultcredits = &Apache::lonuserutils::get_defaultcredits();
 1625:         $credits = &get_user_credits($ccuname,$ccdomain,$defaultcredits);
 1626:         if ($credits eq '') {
 1627:             $credits = $defaultcredits;
 1628:         }
 1629:     }
 1630:     my $cid = $env{'request.course.id'};
 1631:     my ($cnum,$cdom) = &Apache::lonuserutils::get_course_identity($cid);
 1632:     my $date_table = '<h3>'.&mt('Starting and Ending Dates').'</h3>'."\n".
 1633:         &Apache::lonuserutils::date_setting_table(undef,undef,$context,
 1634:                                                   undef,$formname,$permission);
 1635:     my $rowtitle = 'Section';
 1636:     my $secbox = '<h3>'.&mt('Section and Credits').'</h3>'."\n".
 1637:         &Apache::lonuserutils::section_picker($cdom,$cnum,'st',$rowtitle,
 1638:                                               $permission,$context,'',$crstype,
 1639:                                               $showcredits,$credits);
 1640:     my $output = $date_table.$secbox;
 1641:     return $output;
 1642: }
 1643: 
 1644: sub validation_javascript {
 1645:     my ($context,$ccdomain,$pjump_def,$crstype,$groupslist,$newuser,$formname,
 1646:         $loaditem) = @_;
 1647:     my $dc_setcourse_code = '';
 1648:     my $nondc_setsection_code = '';
 1649:     if ($context eq 'domain') {
 1650:         my $dcdom = $env{'request.role.domain'};
 1651:         $loaditem->{'onload'} = "document.cu.coursedesc.value='';";
 1652:         $dc_setcourse_code = 
 1653:             &Apache::lonuserutils::dc_setcourse_js('cu','singleuser',$context);
 1654:     } else {
 1655:         my $checkauth; 
 1656:         if (($newuser) || (&Apache::lonnet::allowed('mau',$ccdomain))) {
 1657:             $checkauth = 1;
 1658:         }
 1659:         if ($context eq 'course') {
 1660:             $nondc_setsection_code =
 1661:                 &Apache::lonuserutils::setsections_javascript($formname,$groupslist,
 1662:                                                               undef,$checkauth,
 1663:                                                               $crstype);
 1664:         }
 1665:         if ($checkauth) {
 1666:             $nondc_setsection_code .= 
 1667:                 &Apache::lonuserutils::verify_authen($formname,$context);
 1668:         }
 1669:     }
 1670:     my $js = &user_modification_js($pjump_def,$dc_setcourse_code,
 1671:                                    $nondc_setsection_code,$groupslist);
 1672:     my ($jsback,$elements) = &crumb_utilities();
 1673:     $js .= "\n".
 1674:            '<script type="text/javascript">'."\n".
 1675:            '// <![CDATA['."\n".
 1676:            $jsback."\n".
 1677:            '// ]]>'."\n".
 1678:            '</script>'."\n";
 1679:     return $js;
 1680: }
 1681: 
 1682: sub display_existing_roles {
 1683:     my ($r,$ccuname,$ccdomain,$inccourses,$context,$roledom,$crstype,
 1684:         $showcredits) = @_;
 1685:     my $now=time;
 1686:     my %lt=&Apache::lonlocal::texthash(
 1687:                     'rer'  => "Existing Roles",
 1688:                     'rev'  => "Revoke",
 1689:                     'del'  => "Delete",
 1690:                     'ren'  => "Re-Enable",
 1691:                     'rol'  => "Role",
 1692:                     'ext'  => "Extent",
 1693:                     'crd'  => "Credits",
 1694:                     'sta'  => "Start",
 1695:                     'end'  => "End",
 1696:                                        );
 1697:     my (%rolesdump,%roletext,%sortrole,%roleclass,%rolepriv);
 1698:     if ($context eq 'course' || $context eq 'author') {
 1699:         my @roles = &Apache::lonuserutils::roles_by_context($context,1,$crstype);
 1700:         my %roleshash = 
 1701:             &Apache::lonnet::get_my_roles($ccuname,$ccdomain,'userroles',
 1702:                               ['active','previous','future'],\@roles,$roledom,1);
 1703:         foreach my $key (keys(%roleshash)) {
 1704:             my ($start,$end) = split(':',$roleshash{$key});
 1705:             next if ($start eq '-1' || $end eq '-1');
 1706:             my ($rnum,$rdom,$role,$sec) = split(':',$key);
 1707:             if ($context eq 'course') {
 1708:                 next unless (($rnum eq $env{'course.'.$env{'request.course.id'}.'.num'})
 1709:                              && ($rdom eq $env{'course.'.$env{'request.course.id'}.'.domain'}));
 1710:             } elsif ($context eq 'author') {
 1711:                 next unless (($rnum eq $env{'user.name'}) && ($rdom eq $env{'request.role.domain'}));
 1712:             }
 1713:             my ($newkey,$newvalue,$newrole);
 1714:             $newkey = '/'.$rdom.'/'.$rnum;
 1715:             if ($sec ne '') {
 1716:                 $newkey .= '/'.$sec;
 1717:             }
 1718:             $newvalue = $role;
 1719:             if ($role =~ /^cr/) {
 1720:                 $newrole = 'cr';
 1721:             } else {
 1722:                 $newrole = $role;
 1723:             }
 1724:             $newkey .= '_'.$newrole;
 1725:             if ($start ne '' && $end ne '') {
 1726:                 $newvalue .= '_'.$end.'_'.$start;
 1727:             } elsif ($end ne '') {
 1728:                 $newvalue .= '_'.$end;
 1729:             }
 1730:             $rolesdump{$newkey} = $newvalue;
 1731:         }
 1732:     } else {
 1733:         %rolesdump=&Apache::lonnet::dump('roles',$ccdomain,$ccuname);
 1734:     }
 1735:     # Build up table of user roles to allow revocation and re-enabling of roles.
 1736:     my ($tmp) = keys(%rolesdump);
 1737:     return if ($tmp =~ /^(con_lost|error)/i);
 1738:     foreach my $area (sort { my $a1=join('_',(split('_',$a))[1,0]);
 1739:                                 my $b1=join('_',(split('_',$b))[1,0]);
 1740:                                 return $a1 cmp $b1;
 1741:                             } keys(%rolesdump)) {
 1742:         next if ($area =~ /^rolesdef/);
 1743:         my $envkey=$area;
 1744:         my $role = $rolesdump{$area};
 1745:         my $thisrole=$area;
 1746:         $area =~ s/\_\w\w$//;
 1747:         my ($role_code,$role_end_time,$role_start_time) =
 1748:             split(/_/,$role);
 1749: # Is this a custom role? Get role owner and title.
 1750:         my ($croleudom,$croleuname,$croletitle)=
 1751:             ($role_code=~m{^cr/($match_domain)/($match_username)/(\w+)$});
 1752:         my $allowed=0;
 1753:         my $delallowed=0;
 1754:         my $sortkey=$role_code;
 1755:         my $class='Unknown';
 1756:         my $credits='';
 1757:         if ($area =~ m{^/($match_domain)/($match_courseid)} ) {
 1758:             $class='Course';
 1759:             my ($coursedom,$coursedir) = ($1,$2);
 1760:             my $cid = $1.'_'.$2;
 1761:             # $1.'_'.$2 is the course id (eg. 103_12345abcef103l3).
 1762:             my %coursedata=
 1763:                 &Apache::lonnet::coursedescription($cid);
 1764:             if ($coursedir =~ /^$match_community$/) {
 1765:                 $class='Community';
 1766:             }
 1767:             $sortkey.="\0$coursedom";
 1768:             my $carea;
 1769:             if (defined($coursedata{'description'})) {
 1770:                 $carea=$coursedata{'description'}.
 1771:                     '<br />'.&mt('Domain').': '.$coursedom.('&nbsp;'x8).
 1772:     &Apache::loncommon::syllabuswrapper(&mt('Syllabus'),$coursedir,$coursedom);
 1773:                 $sortkey.="\0".$coursedata{'description'};
 1774:             } else {
 1775:                 if ($class eq 'Community') {
 1776:                     $carea=&mt('Unavailable community').': '.$area;
 1777:                     $sortkey.="\0".&mt('Unavailable community').': '.$area;
 1778:                 } else {
 1779:                     $carea=&mt('Unavailable course').': '.$area;
 1780:                     $sortkey.="\0".&mt('Unavailable course').': '.$area;
 1781:                 }
 1782:             }
 1783:             $sortkey.="\0$coursedir";
 1784:             $inccourses->{$cid}=1;
 1785:             if (($showcredits) && ($class eq 'Course') && ($role_code eq 'st')) {
 1786:                 my $defaultcredits = $coursedata{'internal.defaultcredits'};
 1787:                 $credits =
 1788:                     &get_user_credits($ccuname,$ccdomain,$defaultcredits,
 1789:                                       $coursedom,$coursedir);
 1790:                 if ($credits eq '') {
 1791:                     $credits = $defaultcredits;
 1792:                 }
 1793:             }
 1794:             if ((&Apache::lonnet::allowed('c'.$role_code,$coursedom.'/'.$coursedir)) ||
 1795:                 (&Apache::lonnet::allowed('c'.$role_code,$ccdomain))) {
 1796:                 $allowed=1;
 1797:             }
 1798:             unless ($allowed) {
 1799:                 my $isowner = &Apache::lonuserutils::is_courseowner($cid,$coursedata{'internal.courseowner'});
 1800:                 if ($isowner) {
 1801:                     if (($role_code eq 'co') && ($class eq 'Community')) {
 1802:                         $allowed = 1;
 1803:                     } elsif (($role_code eq 'cc') && ($class eq 'Course')) {
 1804:                         $allowed = 1;
 1805:                     }
 1806:                 }
 1807:             } 
 1808:             if ((&Apache::lonnet::allowed('dro',$coursedom)) ||
 1809:                 (&Apache::lonnet::allowed('dro',$ccdomain))) {
 1810:                 $delallowed=1;
 1811:             }
 1812: # - custom role. Needs more info, too
 1813:             if ($croletitle) {
 1814:                 if (&Apache::lonnet::allowed('ccr',$coursedom.'/'.$coursedir)) {
 1815:                     $allowed=1;
 1816:                     $thisrole.='.'.$role_code;
 1817:                 }
 1818:             }
 1819:             if ($area=~m{^/($match_domain)/($match_courseid)/(\w+)}) {
 1820:                 $carea.='<br />'.&mt('Section: [_1]',$3);
 1821:                 $sortkey.="\0$3";
 1822:                 if (!$allowed) {
 1823:                     if ($env{'request.course.sec'} eq $3) {
 1824:                         if (&Apache::lonnet::allowed('c'.$role_code,$1.'/'.$2.'/'.$3)) {
 1825:                             $allowed = 1;
 1826:                         }
 1827:                     }
 1828:                 }
 1829:             }
 1830:             $area=$carea;
 1831:         } else {
 1832:             $sortkey.="\0".$area;
 1833:             # Determine if current user is able to revoke privileges
 1834:             if ($area=~m{^/($match_domain)/}) {
 1835:                 if ((&Apache::lonnet::allowed('c'.$role_code,$1)) ||
 1836:                    (&Apache::lonnet::allowed('c'.$role_code,$ccdomain))) {
 1837:                    $allowed=1;
 1838:                 }
 1839:                 if (((&Apache::lonnet::allowed('dro',$1))  ||
 1840:                     (&Apache::lonnet::allowed('dro',$ccdomain))) &&
 1841:                     ($role_code ne 'dc')) {
 1842:                     $delallowed=1;
 1843:                 }
 1844:             } else {
 1845:                 if (&Apache::lonnet::allowed('c'.$role_code,'/')) {
 1846:                     $allowed=1;
 1847:                 }
 1848:             }
 1849:             if ($role_code eq 'ca' || $role_code eq 'au' || $role_code eq 'aa') {
 1850:                 $class='Authoring Space';
 1851:             } elsif ($role_code eq 'su') {
 1852:                 $class='System';
 1853:             } else {
 1854:                 $class='Domain';
 1855:             }
 1856:         }
 1857:         if (($role_code eq 'ca') || ($role_code eq 'aa')) {
 1858:             $area=~m{/($match_domain)/($match_username)};
 1859:             if (&Apache::lonuserutils::authorpriv($2,$1)) {
 1860:                 $allowed=1;
 1861:             } else {
 1862:                 $allowed=0;
 1863:             }
 1864:         }
 1865:         my $row = '';
 1866:         $row.= '<td>';
 1867:         my $active=1;
 1868:         $active=0 if (($role_end_time) && ($now>$role_end_time));
 1869:         if (($active) && ($allowed)) {
 1870:             $row.= '<input type="checkbox" name="rev:'.$thisrole.'" />';
 1871:         } else {
 1872:             if ($active) {
 1873:                $row.='&nbsp;';
 1874:             } else {
 1875:                $row.=&mt('expired or revoked');
 1876:             }
 1877:         }
 1878:         $row.='</td><td>';
 1879:         if ($allowed && !$active) {
 1880:             $row.= '<input type="checkbox" name="ren:'.$thisrole.'" />';
 1881:         } else {
 1882:             $row.='&nbsp;';
 1883:         }
 1884:         $row.='</td><td>';
 1885:         if ($delallowed) {
 1886:             $row.= '<input type="checkbox" name="del:'.$thisrole.'" />';
 1887:         } else {
 1888:             $row.='&nbsp;';
 1889:         }
 1890:         my $plaintext='';
 1891:         if (!$croletitle) {
 1892:             $plaintext=&Apache::lonnet::plaintext($role_code,$class);
 1893:             if (($showcredits) && ($credits ne '')) {
 1894:                 $plaintext .= '<br/ ><span class="LC_nobreak">'.
 1895:                               '<span class="LC_fontsize_small">'.
 1896:                               &mt('Credits: [_1]',$credits).
 1897:                               '</span></span>';
 1898:             }
 1899:         } else {
 1900:             $plaintext=
 1901:                 &mt('Custom role [_1][_2]defined by [_3]',
 1902:                         '"'.$croletitle.'"',
 1903:                         '<br />',
 1904:                         $croleuname.':'.$croleudom);
 1905:         }
 1906:         $row.= '</td><td>'.$plaintext.
 1907:                '</td><td>'.$area.
 1908:                '</td><td>'.($role_start_time?&Apache::lonlocal::locallocaltime($role_start_time)
 1909:                                             : '&nbsp;' ).
 1910:                '</td><td>'.($role_end_time  ?&Apache::lonlocal::locallocaltime($role_end_time)
 1911:                                             : '&nbsp;' )
 1912:                ."</td>";
 1913:         $sortrole{$sortkey}=$envkey;
 1914:         $roletext{$envkey}=$row;
 1915:         $roleclass{$envkey}=$class;
 1916:         $rolepriv{$envkey}=$allowed;
 1917:     } # end of foreach        (table building loop)
 1918: 
 1919:     my $rolesdisplay = 0;
 1920:     my %output = ();
 1921:     foreach my $type ('Authoring Space','Course','Community','Domain','System','Unknown') {
 1922:         $output{$type} = '';
 1923:         foreach my $which (sort {uc($a) cmp uc($b)} (keys(%sortrole))) {
 1924:             if ( ($roleclass{$sortrole{$which}} =~ /^\Q$type\E/ ) && ($rolepriv{$sortrole{$which}}) ) {
 1925:                  $output{$type}.=
 1926:                       &Apache::loncommon::start_data_table_row().
 1927:                       $roletext{$sortrole{$which}}.
 1928:                       &Apache::loncommon::end_data_table_row();
 1929:             }
 1930:         }
 1931:         unless($output{$type} eq '') {
 1932:             $output{$type} = '<tr class="LC_info_row">'.
 1933:                       "<td align='center' colspan='7'>".&mt($type)."</td></tr>".
 1934:                       $output{$type};
 1935:             $rolesdisplay = 1;
 1936:         }
 1937:     }
 1938:     if ($rolesdisplay == 1) {
 1939:         my $contextrole='';
 1940:         if ($env{'request.course.id'}) {
 1941:             if (&Apache::loncommon::course_type() eq 'Community') {
 1942:                 $contextrole = &mt('Existing Roles in this Community');
 1943:             } else {
 1944:                 $contextrole = &mt('Existing Roles in this Course');
 1945:             }
 1946:         } elsif ($env{'request.role'} =~ /^au\./) {
 1947:             $contextrole = &mt('Existing Co-Author Roles in your Authoring Space');
 1948:         } else {
 1949:             $contextrole = &mt('Existing Roles in this Domain');
 1950:         }
 1951:         $r->print('<div class="LC_left_float">'.
 1952: '<fieldset><legend>'.$contextrole.'</legend>'.
 1953: &Apache::loncommon::start_data_table("LC_createuser").
 1954: &Apache::loncommon::start_data_table_header_row().
 1955: '<th>'.$lt{'rev'}.'</th><th>'.$lt{'ren'}.'</th><th>'.$lt{'del'}.
 1956: '</th><th>'.$lt{'rol'}.'</th><th>'.$lt{'ext'}.
 1957: '</th><th>'.$lt{'sta'}.'</th><th>'.$lt{'end'}.'</th>'.
 1958: &Apache::loncommon::end_data_table_header_row());
 1959:         foreach my $type ('Authoring Space','Course','Community','Domain','System','Unknown') {
 1960:             if ($output{$type}) {
 1961:                 $r->print($output{$type}."\n");
 1962:             }
 1963:         }
 1964:         $r->print(&Apache::loncommon::end_data_table().
 1965:                   '</fieldset></div>');
 1966:     }
 1967:     return;
 1968: }
 1969: 
 1970: sub new_coauthor_roles {
 1971:     my ($r,$ccuname,$ccdomain) = @_;
 1972:     my $addrolesdisplay = 0;
 1973:     #
 1974:     # Co-Author
 1975:     #
 1976:     if (&Apache::lonuserutils::authorpriv($env{'user.name'},
 1977:                                           $env{'request.role.domain'}) &&
 1978:         ($env{'user.name'} ne $ccuname || $env{'user.domain'} ne $ccdomain)) {
 1979:         # No sense in assigning co-author role to yourself
 1980:         $addrolesdisplay = 1;
 1981:         my $cuname=$env{'user.name'};
 1982:         my $cudom=$env{'request.role.domain'};
 1983:         my %lt=&Apache::lonlocal::texthash(
 1984:                     'cs'   => "Authoring Space",
 1985:                     'act'  => "Activate",
 1986:                     'rol'  => "Role",
 1987:                     'ext'  => "Extent",
 1988:                     'sta'  => "Start",
 1989:                     'end'  => "End",
 1990:                     'cau'  => "Co-Author",
 1991:                     'caa'  => "Assistant Co-Author",
 1992:                     'ssd'  => "Set Start Date",
 1993:                     'sed'  => "Set End Date"
 1994:                                        );
 1995:         $r->print('<h4>'.$lt{'cs'}.'</h4>'."\n".
 1996:                   &Apache::loncommon::start_data_table()."\n".
 1997:                   &Apache::loncommon::start_data_table_header_row()."\n".
 1998:                   '<th>'.$lt{'act'}.'</th><th>'.$lt{'rol'}.'</th>'.
 1999:                   '<th>'.$lt{'ext'}.'</th><th>'.$lt{'sta'}.'</th>'.
 2000:                   '<th>'.$lt{'end'}.'</th>'."\n".
 2001:                   &Apache::loncommon::end_data_table_header_row()."\n".
 2002:                   &Apache::loncommon::start_data_table_row().'
 2003:            <td>
 2004:             <input type="checkbox" name="act_'.$cudom.'_'.$cuname.'_ca" />
 2005:            </td>
 2006:            <td>'.$lt{'cau'}.'</td>
 2007:            <td>'.$cudom.'_'.$cuname.'</td>
 2008:            <td><input type="hidden" name="start_'.$cudom.'_'.$cuname.'_ca" value="" />
 2009:              <a href=
 2010: "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>
 2011: <td><input type="hidden" name="end_'.$cudom.'_'.$cuname.'_ca" value="" />
 2012: <a href=
 2013: "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".
 2014:               &Apache::loncommon::end_data_table_row()."\n".
 2015:               &Apache::loncommon::start_data_table_row()."\n".
 2016: '<td><input type="checkbox" name="act_'.$cudom.'_'.$cuname.'_aa" /></td>
 2017: <td>'.$lt{'caa'}.'</td>
 2018: <td>'.$cudom.'_'.$cuname.'</td>
 2019: <td><input type="hidden" name="start_'.$cudom.'_'.$cuname.'_aa" value="" />
 2020: <a href=
 2021: "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>
 2022: <td><input type="hidden" name="end_'.$cudom.'_'.$cuname.'_aa" value="" />
 2023: <a href=
 2024: "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".
 2025:              &Apache::loncommon::end_data_table_row()."\n".
 2026:              &Apache::loncommon::end_data_table());
 2027:     } elsif ($env{'request.role'} =~ /^au\./) {
 2028:         if (!(&Apache::lonuserutils::authorpriv($env{'user.name'},
 2029:                                                 $env{'request.role.domain'}))) {
 2030:             $r->print('<span class="LC_error">'.
 2031:                       &mt('You do not have privileges to assign co-author roles.').
 2032:                       '</span>');
 2033:         } elsif (($env{'user.name'} eq $ccuname) &&
 2034:              ($env{'user.domain'} eq $ccdomain)) {
 2035:             $r->print(&mt('Assigning yourself a co-author or assistant co-author role in your own author area in Authoring Space is not permitted'));
 2036:         }
 2037:     }
 2038:     return $addrolesdisplay;;
 2039: }
 2040: 
 2041: sub new_domain_roles {
 2042:     my ($r,$ccdomain) = @_;
 2043:     my $addrolesdisplay = 0;
 2044:     #
 2045:     # Domain level
 2046:     #
 2047:     my $num_domain_level = 0;
 2048:     my $domaintext =
 2049:     '<h4>'.&mt('Domain Level').'</h4>'.
 2050:     &Apache::loncommon::start_data_table().
 2051:     &Apache::loncommon::start_data_table_header_row().
 2052:     '<th>'.&mt('Activate').'</th><th>'.&mt('Role').'</th><th>'.
 2053:     &mt('Extent').'</th>'.
 2054:     '<th>'.&mt('Start').'</th><th>'.&mt('End').'</th>'.
 2055:     &Apache::loncommon::end_data_table_header_row();
 2056:     my @allroles = &Apache::lonuserutils::roles_by_context('domain');
 2057:     foreach my $thisdomain (sort(&Apache::lonnet::all_domains())) {
 2058:         foreach my $role (@allroles) {
 2059:             next if ($role eq 'ad');
 2060:             next if (($role eq 'au') && ($ccdomain ne $thisdomain));
 2061:             if (&Apache::lonnet::allowed('c'.$role,$thisdomain)) {
 2062:                my $plrole=&Apache::lonnet::plaintext($role);
 2063:                my %lt=&Apache::lonlocal::texthash(
 2064:                     'ssd'  => "Set Start Date",
 2065:                     'sed'  => "Set End Date"
 2066:                                        );
 2067:                $num_domain_level ++;
 2068:                $domaintext .=
 2069: &Apache::loncommon::start_data_table_row().
 2070: '<td><input type="checkbox" name="act_'.$thisdomain.'_'.$role.'" /></td>
 2071: <td>'.$plrole.'</td>
 2072: <td>'.$thisdomain.'</td>
 2073: <td><input type="hidden" name="start_'.$thisdomain.'_'.$role.'" value="" />
 2074: <a href=
 2075: "javascript:pjump('."'date_start','Start Date $plrole',document.cu.start_$thisdomain\_$role.value,'start_$thisdomain\_$role','cu.pres','dateset'".')">'.$lt{'ssd'}.'</a></td>
 2076: <td><input type="hidden" name="end_'.$thisdomain.'_'.$role.'" value="" />
 2077: <a href=
 2078: "javascript:pjump('."'date_end','End Date $plrole',document.cu.end_$thisdomain\_$role.value,'end_$thisdomain\_$role','cu.pres','dateset'".')">'.$lt{'sed'}.'</a></td>'.
 2079: &Apache::loncommon::end_data_table_row();
 2080:             }
 2081:         }
 2082:     }
 2083:     $domaintext.= &Apache::loncommon::end_data_table();
 2084:     if ($num_domain_level > 0) {
 2085:         $r->print($domaintext);
 2086:         $addrolesdisplay = 1;
 2087:     }
 2088:     return $addrolesdisplay;
 2089: }
 2090: 
 2091: sub user_authentication {
 2092:     my ($ccuname,$ccdomain,$formname) = @_;
 2093:     my $currentauth=&Apache::lonnet::queryauthenticate($ccuname,$ccdomain);
 2094:     my $outcome;
 2095:     # Check for a bad authentication type
 2096:     if ($currentauth !~ /^(krb4|krb5|unix|internal|localauth):/) {
 2097:         # bad authentication scheme
 2098:         my %lt=&Apache::lonlocal::texthash(
 2099:                        'err'   => "ERROR",
 2100:                        'uuas'  => "This user has an unrecognized authentication scheme",
 2101:                        'adcs'  => "Please alert a domain coordinator of this situation",
 2102:                        'sldb'  => "Please specify login data below",
 2103:                        'ld'    => "Login Data"
 2104:         );
 2105:         if (&Apache::lonnet::allowed('mau',$ccdomain)) {
 2106:             &initialize_authen_forms($ccdomain,$formname);
 2107: 
 2108:             my $choices = &Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc);
 2109:             $outcome = <<ENDBADAUTH;
 2110: <script type="text/javascript" language="Javascript">
 2111: // <![CDATA[
 2112: $loginscript
 2113: // ]]>
 2114: </script>
 2115: <span class="LC_error">$lt{'err'}:
 2116: $lt{'uuas'} ($currentauth). $lt{'sldb'}.</span>
 2117: <h3>$lt{'ld'}</h3>
 2118: $choices
 2119: ENDBADAUTH
 2120:         } else {
 2121:             # This user is not allowed to modify the user's
 2122:             # authentication scheme, so just notify them of the problem
 2123:             $outcome = <<ENDBADAUTH;
 2124: <span class="LC_error"> $lt{'err'}: 
 2125: $lt{'uuas'} ($currentauth). $lt{'adcs'}.
 2126: </span>
 2127: ENDBADAUTH
 2128:         }
 2129:     } else { # Authentication type is valid
 2130:         &initialize_authen_forms($ccdomain,$formname,$currentauth,'modifyuser');
 2131:         my ($authformcurrent,$can_modify,@authform_others) =
 2132:             &modify_login_block($ccdomain,$currentauth);
 2133:         if (&Apache::lonnet::allowed('mau',$ccdomain)) {
 2134:             # Current user has login modification privileges
 2135:             my %lt=&Apache::lonlocal::texthash (
 2136:                            'ld'    => "Login Data",
 2137:                            'ccld'  => "Change Current Login Data",
 2138:                            'enld'  => "Enter New Login Data"
 2139:                                                );
 2140:             $outcome =
 2141:                        '<script type="text/javascript" language="Javascript">'."\n".
 2142:                        '// <![CDATA['."\n".
 2143:                        $loginscript."\n".
 2144:                        '// ]]>'."\n".
 2145:                        '</script>'."\n".
 2146:                        '<h3>'.$lt{'ld'}.'</h3>'.
 2147:                        &Apache::loncommon::start_data_table().
 2148:                        &Apache::loncommon::start_data_table_row().
 2149:                        '<td>'.$authformnop;
 2150:             if ($can_modify) {
 2151:                 $outcome .= '</td>'."\n".
 2152:                             &Apache::loncommon::end_data_table_row().
 2153:                             &Apache::loncommon::start_data_table_row().
 2154:                             '<td>'.$authformcurrent.'</td>'.
 2155:                             &Apache::loncommon::end_data_table_row()."\n";
 2156:             } else {
 2157:                 $outcome .= '&nbsp;('.$authformcurrent.')</td>'.
 2158:                             &Apache::loncommon::end_data_table_row()."\n";
 2159:             }
 2160:             foreach my $item (@authform_others) { 
 2161:                 $outcome .= &Apache::loncommon::start_data_table_row().
 2162:                             '<td>'.$item.'</td>'.
 2163:                             &Apache::loncommon::end_data_table_row()."\n";
 2164:             }
 2165:             $outcome .= &Apache::loncommon::end_data_table();
 2166:         } else {
 2167:             if (&Apache::lonnet::allowed('mau',$env{'request.role.domain'})) {
 2168:                 my %lt=&Apache::lonlocal::texthash(
 2169:                            'ccld'  => "Change Current Login Data",
 2170:                            'yodo'  => "You do not have privileges to modify the authentication configuration for this user.",
 2171:                            'ifch'  => "If a change is required, contact a domain coordinator for the domain",
 2172:                 );
 2173:                 $outcome .= <<ENDNOPRIV;
 2174: <h3>$lt{'ccld'}</h3>
 2175: $lt{'yodo'} $lt{'ifch'}: $ccdomain
 2176: <input type="hidden" name="login" value="nochange" />
 2177: ENDNOPRIV
 2178:             }
 2179:         }
 2180:     }  ## End of "check for bad authentication type" logic
 2181:     return $outcome;
 2182: }
 2183: 
 2184: sub modify_login_block {
 2185:     my ($dom,$currentauth) = @_;
 2186:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 2187:     my ($authnum,%can_assign) =
 2188:         &Apache::loncommon::get_assignable_auth($dom);
 2189:     my ($authformcurrent,@authform_others,$show_override_msg);
 2190:     if ($currentauth=~/^krb(4|5):/) {
 2191:         $authformcurrent=$authformkrb;
 2192:         if ($can_assign{'int'}) {
 2193:             push(@authform_others,$authformint);
 2194:         }
 2195:         if ($can_assign{'loc'}) {
 2196:             push(@authform_others,$authformloc);
 2197:         }
 2198:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2199:             $show_override_msg = 1;
 2200:         }
 2201:     } elsif ($currentauth=~/^internal:/) {
 2202:         $authformcurrent=$authformint;
 2203:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2204:             push(@authform_others,$authformkrb);
 2205:         }
 2206:         if ($can_assign{'loc'}) {
 2207:             push(@authform_others,$authformloc);
 2208:         }
 2209:         if ($can_assign{'int'}) {
 2210:             $show_override_msg = 1;
 2211:         }
 2212:     } elsif ($currentauth=~/^unix:/) {
 2213:         $authformcurrent=$authformfsys;
 2214:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2215:             push(@authform_others,$authformkrb);
 2216:         }
 2217:         if ($can_assign{'int'}) {
 2218:             push(@authform_others,$authformint);
 2219:         }
 2220:         if ($can_assign{'loc'}) {
 2221:             push(@authform_others,$authformloc);
 2222:         }
 2223:         if ($can_assign{'fsys'}) {
 2224:             $show_override_msg = 1;
 2225:         }
 2226:     } elsif ($currentauth=~/^localauth:/) {
 2227:         $authformcurrent=$authformloc;
 2228:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2229:             push(@authform_others,$authformkrb);
 2230:         }
 2231:         if ($can_assign{'int'}) {
 2232:             push(@authform_others,$authformint);
 2233:         }
 2234:         if ($can_assign{'loc'}) {
 2235:             $show_override_msg = 1;
 2236:         }
 2237:     }
 2238:     if ($show_override_msg) {
 2239:         $authformcurrent = '<table><tr><td colspan="3">'.$authformcurrent.
 2240:                            '</td></tr>'."\n".
 2241:                            '<tr><td>&nbsp;&nbsp;&nbsp;</td>'.
 2242:                            '<td><b>'.&mt('Currently in use').'</b></td>'.
 2243:                            '<td align="right"><span class="LC_cusr_emph">'.
 2244:                             &mt('will override current values').
 2245:                             '</span></td></tr></table>';
 2246:     }
 2247:     return ($authformcurrent,$show_override_msg,@authform_others); 
 2248: }
 2249: 
 2250: sub personal_data_display {
 2251:     my ($ccuname,$ccdomain,$newuser,$context,$inst_results,$rolesarray,
 2252:         $now,$captchaform,$emailusername,$usertype) = @_;
 2253:     my ($output,%userenv,%canmodify,%canmodify_status);
 2254:     my @userinfo = ('firstname','middlename','lastname','generation',
 2255:                     'permanentemail','id');
 2256:     my $rowcount = 0;
 2257:     my $editable = 0;
 2258:     my %textboxsize = (
 2259:                        firstname      => '15',
 2260:                        middlename     => '15',
 2261:                        lastname       => '15',
 2262:                        generation     => '5',
 2263:                        permanentemail => '25',
 2264:                        id             => '15',
 2265:                       );
 2266: 
 2267:     my %lt=&Apache::lonlocal::texthash(
 2268:                 'pd'             => "Personal Data",
 2269:                 'firstname'      => "First Name",
 2270:                 'middlename'     => "Middle Name",
 2271:                 'lastname'       => "Last Name",
 2272:                 'generation'     => "Generation",
 2273:                 'permanentemail' => "Permanent e-mail address",
 2274:                 'id'             => "Student/Employee ID",
 2275:                 'lg'             => "Login Data",
 2276:                 'inststatus'     => "Affiliation",
 2277:                 'email'          => 'E-mail address',
 2278:                 'valid'          => 'Validation',
 2279:     );
 2280: 
 2281:     %canmodify_status =
 2282:         &Apache::lonuserutils::can_modify_userinfo($context,$ccdomain,
 2283:                                                    ['inststatus'],$rolesarray);
 2284:     if (!$newuser) {
 2285:         # Get the users information
 2286:         %userenv = &Apache::lonnet::get('environment',
 2287:                    ['firstname','middlename','lastname','generation',
 2288:                     'permanentemail','id','inststatus'],$ccdomain,$ccuname);
 2289:         %canmodify =
 2290:             &Apache::lonuserutils::can_modify_userinfo($context,$ccdomain,
 2291:                                                        \@userinfo,$rolesarray);
 2292:     } elsif ($context eq 'selfcreate') {
 2293:         if ($newuser eq 'email') {
 2294:             if (ref($emailusername) eq 'HASH') {
 2295:                 if (ref($emailusername->{$usertype}) eq 'HASH') {
 2296:                     my ($infofields,$infotitles) = &Apache::loncommon::emailusername_info();
 2297:                     @userinfo = ();          
 2298:                     if ((ref($infofields) eq 'ARRAY') && (ref($infotitles) eq 'HASH')) {
 2299:                         foreach my $field (@{$infofields}) { 
 2300:                             if ($emailusername->{$usertype}->{$field}) {
 2301:                                 push(@userinfo,$field);
 2302:                                 $canmodify{$field} = 1;
 2303:                                 unless ($textboxsize{$field}) {
 2304:                                     $textboxsize{$field} = 25;
 2305:                                 }
 2306:                                 unless ($lt{$field}) {
 2307:                                     $lt{$field} = $infotitles->{$field};
 2308:                                 }
 2309:                                 if ($emailusername->{$usertype}->{$field} eq 'required') {
 2310:                                     $lt{$field} .= '<b>*</b>';
 2311:                                 }
 2312:                             }
 2313:                         }
 2314:                     }
 2315:                 }
 2316:             }
 2317:         } else {
 2318:             %canmodify = &selfcreate_canmodify($context,$ccdomain,\@userinfo,
 2319:                                                $inst_results,$rolesarray);
 2320:         }
 2321:     }
 2322: 
 2323:     my $genhelp=&Apache::loncommon::help_open_topic('Generation');
 2324:     $output = '<h3>'.$lt{'pd'}.'</h3>'.
 2325:               &Apache::lonhtmlcommon::start_pick_box();
 2326:     if (($context eq 'selfcreate') && ($newuser eq 'email')) {
 2327:         $output .= &Apache::lonhtmlcommon::row_title($lt{'email'}.'<b>*</b>',undef,
 2328:                                                      'LC_oddrow_value')."\n".
 2329:                    '<input type="text" name="uname" size="25" value="" autocomplete="off" />';
 2330:         $rowcount ++;
 2331:         $output .= &Apache::lonhtmlcommon::row_closure(1);
 2332:         my $upassone = '<input type="password" name="upass'.$now.'" size="20" autocomplete="off" />';
 2333:         my $upasstwo = '<input type="password" name="upasscheck'.$now.'" size="20" autocomplete="off" />';
 2334:         $output .= &Apache::lonhtmlcommon::row_title(&mt('Password').'<b>*</b>',
 2335:                                                     'LC_pick_box_title',
 2336:                                                     'LC_oddrow_value')."\n".
 2337:                    $upassone."\n".
 2338:                    &Apache::lonhtmlcommon::row_closure(1)."\n".
 2339:                    &Apache::lonhtmlcommon::row_title(&mt('Confirm password').'<b>*</b>',
 2340:                                                      'LC_pick_box_title',
 2341:                                                      'LC_oddrow_value')."\n".
 2342:                    $upasstwo.
 2343:                    &Apache::lonhtmlcommon::row_closure()."\n";
 2344:     }
 2345:     foreach my $item (@userinfo) {
 2346:         my $rowtitle = $lt{$item};
 2347:         my $hiderow = 0;
 2348:         if ($item eq 'generation') {
 2349:             $rowtitle = $genhelp.$rowtitle;
 2350:         }
 2351:         my $row = &Apache::lonhtmlcommon::row_title($rowtitle,undef,'LC_oddrow_value')."\n";
 2352:         if ($newuser) {
 2353:             if (ref($inst_results) eq 'HASH') {
 2354:                 if ($inst_results->{$item} ne '') {
 2355:                     $row .= '<input type="hidden" name="c'.$item.'" value="'.$inst_results->{$item}.'" />'.$inst_results->{$item};
 2356:                 } else {
 2357:                     if ($context eq 'selfcreate') {
 2358:                         if ($canmodify{$item}) {
 2359:                             $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="" autocomplete="off" />';
 2360:                             $editable ++;
 2361:                         } else {
 2362:                             $hiderow = 1;
 2363:                         }
 2364:                     } else {
 2365:                         $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="" />';
 2366:                     }
 2367:                 }
 2368:             } else {
 2369:                 if ($context eq 'selfcreate') {
 2370:                     if ($canmodify{$item}) {
 2371:                         if ($newuser eq 'email') {
 2372:                             $row .= '<input type="text" name="'.$item.'" size="'.$textboxsize{$item}.'" value="" autocomplete="off" />';
 2373:                         } else {
 2374:                             $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="" autocomplete="off" />';
 2375:                         }
 2376:                         $editable ++;
 2377:                     } else {
 2378:                         $hiderow = 1;
 2379:                     }
 2380:                 } else {
 2381:                     $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="" />';
 2382:                 }
 2383:             }
 2384:         } else {
 2385:             if ($canmodify{$item}) {
 2386:                 $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="'.$userenv{$item}.'" />';
 2387:                 if (($item eq 'id') && (!$newuser)) {
 2388:                     $row .= '<br />'.&Apache::lonuserutils::forceid_change($context);
 2389:                 }
 2390:             } else {
 2391:                 $row .= $userenv{$item};
 2392:             }
 2393:         }
 2394:         $row .= &Apache::lonhtmlcommon::row_closure(1);
 2395:         if (!$hiderow) {
 2396:             $output .= $row;
 2397:             $rowcount ++;
 2398:         }
 2399:     }
 2400:     if (($canmodify_status{'inststatus'}) || ($context ne 'selfcreate')) {
 2401:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($ccdomain);
 2402:         if (ref($types) eq 'ARRAY') {
 2403:             if (@{$types} > 0) {
 2404:                 my ($hiderow,$shown);
 2405:                 if ($canmodify_status{'inststatus'}) {
 2406:                     $shown = &pick_inst_statuses($userenv{'inststatus'},$usertypes,$types);
 2407:                 } else {
 2408:                     if ($userenv{'inststatus'} eq '') {
 2409:                         $hiderow = 1;
 2410:                     } else {
 2411:                         my @showitems;
 2412:                         foreach my $item ( map { &unescape($_); } split(':',$userenv{'inststatus'})) {
 2413:                             if (exists($usertypes->{$item})) {
 2414:                                 push(@showitems,$usertypes->{$item});
 2415:                             } else {
 2416:                                 push(@showitems,$item);
 2417:                             }
 2418:                         }
 2419:                         if (@showitems) {
 2420:                             $shown = join(', ',@showitems);
 2421:                         } else {
 2422:                             $hiderow = 1;
 2423:                         }
 2424:                     }
 2425:                 }
 2426:                 if (!$hiderow) {
 2427:                     my $row = &Apache::lonhtmlcommon::row_title(&mt('Affiliations'),undef,'LC_oddrow_value')."\n".
 2428:                               $shown.&Apache::lonhtmlcommon::row_closure(1); 
 2429:                     if ($context eq 'selfcreate') {
 2430:                         $rowcount ++;
 2431:                     }
 2432:                     $output .= $row;
 2433:                 }
 2434:             }
 2435:         }
 2436:     }
 2437:     if (($context eq 'selfcreate') && ($newuser eq 'email')) {
 2438:         if ($captchaform) {
 2439:             $output .= &Apache::lonhtmlcommon::row_title($lt{'valid'}.'*',
 2440:                                                          'LC_pick_box_title')."\n".
 2441:                        $captchaform."\n".'<br /><br />'.
 2442:                        &Apache::lonhtmlcommon::row_closure(1); 
 2443:             $rowcount ++;
 2444:         }
 2445:         my $submit_text = &mt('Create account');
 2446:         $output .= &Apache::lonhtmlcommon::row_title()."\n".
 2447:                    '<br /><input type="submit" name="createaccount" value="'.
 2448:                    $submit_text.'" />'.
 2449:                    '<input type="hidden" name="type" value="'.$usertype.'" />'.
 2450:                    &Apache::lonhtmlcommon::row_closure(1);
 2451:     }
 2452:     $output .= &Apache::lonhtmlcommon::end_pick_box();
 2453:     if (wantarray) {
 2454:         if ($context eq 'selfcreate') {
 2455:             return($output,$rowcount,$editable);
 2456:         } else {
 2457:             return $output;
 2458:         }
 2459:     } else {
 2460:         return $output;
 2461:     }
 2462: }
 2463: 
 2464: sub pick_inst_statuses {
 2465:     my ($curr,$usertypes,$types) = @_;
 2466:     my ($output,$rem,@currtypes);
 2467:     if ($curr ne '') {
 2468:         @currtypes = map { &unescape($_); } split(/:/,$curr);
 2469:     }
 2470:     my $numinrow = 2;
 2471:     if (ref($types) eq 'ARRAY') {
 2472:         $output = '<table>';
 2473:         my $lastcolspan; 
 2474:         for (my $i=0; $i<@{$types}; $i++) {
 2475:             if (defined($usertypes->{$types->[$i]})) {
 2476:                 my $rem = $i%($numinrow);
 2477:                 if ($rem == 0) {
 2478:                     if ($i<@{$types}-1) {
 2479:                         if ($i > 0) { 
 2480:                             $output .= '</tr>';
 2481:                         }
 2482:                         $output .= '<tr>';
 2483:                     }
 2484:                 } elsif ($i==@{$types}-1) {
 2485:                     my $colsleft = $numinrow - $rem;
 2486:                     if ($colsleft > 1) {
 2487:                         $lastcolspan = ' colspan="'.$colsleft.'"';
 2488:                     }
 2489:                 }
 2490:                 my $check = ' ';
 2491:                 if (grep(/^\Q$types->[$i]\E$/,@currtypes)) {
 2492:                     $check = ' checked="checked" ';
 2493:                 }
 2494:                 $output .= '<td class="LC_left_item"'.$lastcolspan.'>'.
 2495:                            '<span class="LC_nobreak"><label>'.
 2496:                            '<input type="checkbox" name="inststatus" '.
 2497:                            'value="'.$types->[$i].'"'.$check.'/>'.
 2498:                            $usertypes->{$types->[$i]}.'</label></span></td>';
 2499:             }
 2500:         }
 2501:         $output .= '</tr></table>';
 2502:     }
 2503:     return $output;
 2504: }
 2505: 
 2506: sub selfcreate_canmodify {
 2507:     my ($context,$dom,$userinfo,$inst_results,$rolesarray) = @_;
 2508:     if (ref($inst_results) eq 'HASH') {
 2509:         my @inststatuses = &get_inststatuses($inst_results);
 2510:         if (@inststatuses == 0) {
 2511:             @inststatuses = ('default');
 2512:         }
 2513:         $rolesarray = \@inststatuses;
 2514:     }
 2515:     my %canmodify =
 2516:         &Apache::lonuserutils::can_modify_userinfo($context,$dom,$userinfo,
 2517:                                                    $rolesarray);
 2518:     return %canmodify;
 2519: }
 2520: 
 2521: sub get_inststatuses {
 2522:     my ($insthashref) = @_;
 2523:     my @inststatuses = ();
 2524:     if (ref($insthashref) eq 'HASH') {
 2525:         if (ref($insthashref->{'inststatus'}) eq 'ARRAY') {
 2526:             @inststatuses = @{$insthashref->{'inststatus'}};
 2527:         }
 2528:     }
 2529:     return @inststatuses;
 2530: }
 2531: 
 2532: # ================================================================= Phase Three
 2533: sub update_user_data {
 2534:     my ($r,$context,$crstype,$brcrum,$showcredits) = @_; 
 2535:     my $uhome=&Apache::lonnet::homeserver($env{'form.ccuname'},
 2536:                                           $env{'form.ccdomain'});
 2537:     # Error messages
 2538:     my $error     = '<span class="LC_error">'.&mt('Error').': ';
 2539:     my $end       = '</span><br /><br />';
 2540:     my $rtnlink   = '<a href="javascript:backPage(document.userupdate,'.
 2541:                     "'$env{'form.prevphase'}','modify')".'" />'.
 2542:                     &mt('Return to previous page').'</a>'.
 2543:                     &Apache::loncommon::end_page();
 2544:     my $now = time;
 2545:     my $title;
 2546:     if (exists($env{'form.makeuser'})) {
 2547: 	$title='Set Privileges for New User';
 2548:     } else {
 2549:         $title='Modify User Privileges';
 2550:     }
 2551:     my $newuser = 0;
 2552:     my ($jsback,$elements) = &crumb_utilities();
 2553:     my $jscript = '<script type="text/javascript">'."\n".
 2554:                   '// <![CDATA['."\n".
 2555:                   $jsback."\n".
 2556:                   '// ]]>'."\n".
 2557:                   '</script>'."\n";
 2558:     my %breadcrumb_text = &singleuser_breadcrumb($crstype);
 2559:     push (@{$brcrum},
 2560:              {href => "javascript:backPage(document.userupdate)",
 2561:               text => $breadcrumb_text{'search'},
 2562:               faq  => 282,
 2563:               bug  => 'Instructor Interface',}
 2564:              );
 2565:     if ($env{'form.prevphase'} eq 'userpicked') {
 2566:         push(@{$brcrum},
 2567:                {href => "javascript:backPage(document.userupdate,'get_user_info','select')",
 2568:                 text => $breadcrumb_text{'userpicked'},
 2569:                 faq  => 282,
 2570:                 bug  => 'Instructor Interface',});
 2571:     }
 2572:     my $helpitem = 'Course_Change_Privileges';
 2573:     if ($env{'form.action'} eq 'singlestudent') {
 2574:         $helpitem = 'Course_Add_Student';
 2575:     }
 2576:     push(@{$brcrum}, 
 2577:             {href => "javascript:backPage(document.userupdate,'$env{'form.prevphase'}','modify')",
 2578:              text => $breadcrumb_text{'modify'},
 2579:              faq  => 282,
 2580:              bug  => 'Instructor Interface',},
 2581:             {href => "/adm/createuser",
 2582:              text => "Result",
 2583:              faq  => 282,
 2584:              bug  => 'Instructor Interface',
 2585:              help => $helpitem});
 2586:     my $args = {bread_crumbs          => $brcrum,
 2587:                 bread_crumbs_component => 'User Management'};
 2588:     if ($env{'form.popup'}) {
 2589:         $args->{'no_nav_bar'} = 1;
 2590:     }
 2591:     $r->print(&Apache::loncommon::start_page($title,$jscript,$args));
 2592:     $r->print(&update_result_form($uhome));
 2593:     # Check Inputs
 2594:     if (! $env{'form.ccuname'} ) {
 2595: 	$r->print($error.&mt('No login name specified').'.'.$end.$rtnlink);
 2596: 	return;
 2597:     }
 2598:     if (  $env{'form.ccuname'} ne 
 2599: 	  &LONCAPA::clean_username($env{'form.ccuname'}) ) {
 2600: 	$r->print($error.&mt('Invalid login name.').'  '.
 2601: 		  &mt('Only letters, numbers, periods, dashes, @, and underscores are valid.').
 2602: 		  $end.$rtnlink);
 2603: 	return;
 2604:     }
 2605:     if (! $env{'form.ccdomain'}       ) {
 2606: 	$r->print($error.&mt('No domain specified').'.'.$end.$rtnlink);
 2607: 	return;
 2608:     }
 2609:     if (  $env{'form.ccdomain'} ne
 2610: 	  &LONCAPA::clean_domain($env{'form.ccdomain'}) ) {
 2611: 	$r->print($error.&mt('Invalid domain name.').'  '.
 2612: 		  &mt('Only letters, numbers, periods, dashes, and underscores are valid.').
 2613: 		  $end.$rtnlink);
 2614: 	return;
 2615:     }
 2616:     if ($uhome eq 'no_host') {
 2617:         $newuser = 1;
 2618:     }
 2619:     if (! exists($env{'form.makeuser'})) {
 2620:         # Modifying an existing user, so check the validity of the name
 2621:         if ($uhome eq 'no_host') {
 2622:             $r->print(
 2623:                 $error
 2624:                .'<p class="LC_error">'
 2625:                .&mt('Unable to determine home server for [_1] in domain [_2].',
 2626:                         '"'.$env{'form.ccuname'}.'"','"'.$env{'form.ccdomain'}.'"')
 2627:                .'</p>');
 2628:             return;
 2629:         }
 2630:     }
 2631:     # Determine authentication method and password for the user being modified
 2632:     my $amode='';
 2633:     my $genpwd='';
 2634:     if ($env{'form.login'} eq 'krb') {
 2635: 	$amode='krb';
 2636: 	$amode.=$env{'form.krbver'};
 2637: 	$genpwd=$env{'form.krbarg'};
 2638:     } elsif ($env{'form.login'} eq 'int') {
 2639: 	$amode='internal';
 2640: 	$genpwd=$env{'form.intarg'};
 2641:     } elsif ($env{'form.login'} eq 'fsys') {
 2642: 	$amode='unix';
 2643: 	$genpwd=$env{'form.fsysarg'};
 2644:     } elsif ($env{'form.login'} eq 'loc') {
 2645: 	$amode='localauth';
 2646: 	$genpwd=$env{'form.locarg'};
 2647: 	$genpwd=" " if (!$genpwd);
 2648:     } elsif (($env{'form.login'} eq 'nochange') ||
 2649:              ($env{'form.login'} eq ''        )) { 
 2650:         # There is no need to tell the user we did not change what they
 2651:         # did not ask us to change.
 2652:         # If they are creating a new user but have not specified login
 2653:         # information this will be caught below.
 2654:     } else {
 2655:             $r->print($error.&mt('Invalid login mode or password').$end.$rtnlink);
 2656:             return;
 2657:     }
 2658: 
 2659:     $r->print('<h3>'.&mt('User [_1] in domain [_2]',
 2660:                         $env{'form.ccuname'}.' ('.&Apache::loncommon::plainname($env{'form.ccuname'},
 2661:                         $env{'form.ccdomain'}).')', $env{'form.ccdomain'}).'</h3>');
 2662:     my %prog_state = &Apache::lonhtmlcommon::Create_PrgWin($r,2);
 2663: 
 2664:     my (%alerts,%rulematch,%inst_results,%curr_rules);
 2665:     my @userinfo = ('firstname','middlename','lastname','generation','permanentemail','id');
 2666:     my @usertools = ('aboutme','blog','webdav','portfolio');
 2667:     my @requestcourses = ('official','unofficial','community','textbook','placement');
 2668:     my @requestauthor = ('requestauthor');
 2669:     my ($othertitle,$usertypes,$types) = 
 2670:         &Apache::loncommon::sorted_inst_types($env{'form.ccdomain'});
 2671:     my %canmodify_status =
 2672:         &Apache::lonuserutils::can_modify_userinfo($context,$env{'form.ccdomain'},
 2673:                                                    ['inststatus']);
 2674:     if ($env{'form.makeuser'}) {
 2675: 	$r->print('<h3>'.&mt('Creating new account.').'</h3>');
 2676:         # Check for the authentication mode and password
 2677:         if (! $amode || ! $genpwd) {
 2678: 	    $r->print($error.&mt('Invalid login mode or password').$end.$rtnlink);    
 2679: 	    return;
 2680: 	}
 2681:         # Determine desired host
 2682:         my $desiredhost = $env{'form.hserver'};
 2683:         if (lc($desiredhost) eq 'default') {
 2684:             $desiredhost = undef;
 2685:         } else {
 2686:             my %home_servers = 
 2687: 		&Apache::lonnet::get_servers($env{'form.ccdomain'},'library');
 2688:             if (! exists($home_servers{$desiredhost})) {
 2689:                 $r->print($error.&mt('Invalid home server specified').$end.$rtnlink);
 2690:                 return;
 2691:             }
 2692:         }
 2693:         # Check ID format
 2694:         my %checkhash;
 2695:         my %checks = ('id' => 1);
 2696:         %{$checkhash{$env{'form.ccuname'}.':'.$env{'form.ccdomain'}}} = (
 2697:             'newuser' => $newuser, 
 2698:             'id' => $env{'form.cid'},
 2699:         );
 2700:         if ($env{'form.cid'} ne '') {
 2701:             &Apache::loncommon::user_rule_check(\%checkhash,\%checks,\%alerts,
 2702:                                           \%rulematch,\%inst_results,\%curr_rules);
 2703:             if (ref($alerts{'id'}) eq 'HASH') {
 2704:                 if (ref($alerts{'id'}{$env{'form.ccdomain'}}) eq 'HASH') {
 2705:                     my $domdesc =
 2706:                         &Apache::lonnet::domain($env{'form.ccdomain'},'description');
 2707:                     if ($alerts{'id'}{$env{'form.ccdomain'}}{$env{'form.cid'}}) {
 2708:                         my $userchkmsg;
 2709:                         if (ref($curr_rules{$env{'form.ccdomain'}}) eq 'HASH') {
 2710:                             $userchkmsg  = 
 2711:                                 &Apache::loncommon::instrule_disallow_msg('id',
 2712:                                                                     $domdesc,1).
 2713:                                 &Apache::loncommon::user_rule_formats($env{'form.ccdomain'},
 2714:                                     $domdesc,$curr_rules{$env{'form.ccdomain'}}{'id'},'id');
 2715:                         }
 2716:                         $r->print($error.&mt('Invalid ID format').$end.
 2717:                                   $userchkmsg.$rtnlink);
 2718:                         return;
 2719:                     }
 2720:                 }
 2721:             }
 2722:         }
 2723:         &Apache::lonhtmlcommon::Increment_PrgWin($r, \%prog_state);
 2724: 	# Call modifyuser
 2725: 	my $result = &Apache::lonnet::modifyuser
 2726: 	    ($env{'form.ccdomain'},$env{'form.ccuname'},$env{'form.cid'},
 2727:              $amode,$genpwd,$env{'form.cfirstname'},
 2728:              $env{'form.cmiddlename'},$env{'form.clastname'},
 2729:              $env{'form.cgeneration'},undef,$desiredhost,
 2730:              $env{'form.cpermanentemail'});
 2731: 	$r->print(&mt('Generating user').': '.$result);
 2732:         $uhome = &Apache::lonnet::homeserver($env{'form.ccuname'},
 2733:                                                $env{'form.ccdomain'});
 2734:         my (%changeHash,%newcustom,%changed,%changedinfo);
 2735:         if ($uhome ne 'no_host') {
 2736:             if ($context eq 'domain') {
 2737:                 foreach my $name ('portfolio','author') {
 2738:                     if ($env{'form.custom_'.$name.'quota'} == 1) {
 2739:                         if ($env{'form.'.$name.'quota'} eq '') {
 2740:                             $newcustom{$name.'quota'} = 0;
 2741:                         } else {
 2742:                             $newcustom{$name.'quota'} = $env{'form.'.$name.'quota'};
 2743:                             $newcustom{$name.'quota'} =~ s/[^\d\.]//g;
 2744:                         }
 2745:                         if (&quota_admin($newcustom{$name.'quota'},\%changeHash,$name)) {
 2746:                             $changed{$name.'quota'} = 1;
 2747:                         }
 2748:                     }
 2749:                 }
 2750:                 foreach my $item (@usertools) {
 2751:                     if ($env{'form.custom'.$item} == 1) {
 2752:                         $newcustom{$item} = $env{'form.tools_'.$item};
 2753:                         $changed{$item} = &tool_admin($item,$newcustom{$item},
 2754:                                                      \%changeHash,'tools');
 2755:                     }
 2756:                 }
 2757:                 foreach my $item (@requestcourses) {
 2758:                     if ($env{'form.custom'.$item} == 1) {
 2759:                         $newcustom{$item} = $env{'form.crsreq_'.$item};
 2760:                         if ($env{'form.crsreq_'.$item} eq 'autolimit') {
 2761:                             $newcustom{$item} .= '=';
 2762:                             $env{'form.crsreq_'.$item.'_limit'} =~ s/\D+//g;
 2763:                             if ($env{'form.crsreq_'.$item.'_limit'}) {
 2764:                                 $newcustom{$item} .= $env{'form.crsreq_'.$item.'_limit'};
 2765:                             }
 2766:                         }
 2767:                         $changed{$item} = &tool_admin($item,$newcustom{$item},
 2768:                                                       \%changeHash,'requestcourses');
 2769:                     }
 2770:                 }
 2771:                 if ($env{'form.customrequestauthor'} == 1) {
 2772:                     $newcustom{'requestauthor'} = $env{'form.requestauthor'};
 2773:                     $changed{'requestauthor'} = &tool_admin('requestauthor',
 2774:                                                     $newcustom{'requestauthor'},
 2775:                                                     \%changeHash,'requestauthor');
 2776:                 }
 2777:                 if (&Apache::lonnet::allowed('cdh',$env{'request.role.domain'})) {
 2778:                     my @adds = &Apache::loncommon::get_env_multiple('form.adhocroleadd');
 2779:                     if (&adhocrole_changes(\%changeHash)) {
 2780:                         $changed{'adhocroles.'.$env{'request.role.domain'}} = $changeHash{'adhocroles.'.$env{'request.role.domain'}};
 2781:                     }  
 2782:                 }
 2783:             }
 2784:             if ($canmodify_status{'inststatus'}) {
 2785:                 if (exists($env{'form.inststatus'})) {
 2786:                     my @inststatuses = &Apache::loncommon::get_env_multiple('form.inststatus');
 2787:                     if (@inststatuses > 0) {
 2788:                         $changeHash{'inststatus'} = join(',',@inststatuses);
 2789:                         $changed{'inststatus'} = $changeHash{'inststatus'};
 2790:                     }
 2791:                 }
 2792:             }
 2793:             if (keys(%changed)) {
 2794:                 foreach my $item (@userinfo) {
 2795:                     $changeHash{$item}  = $env{'form.c'.$item};
 2796:                 }
 2797:                 my $chgresult =
 2798:                      &Apache::lonnet::put('environment',\%changeHash,
 2799:                                           $env{'form.ccdomain'},$env{'form.ccuname'});
 2800:             } 
 2801:         }
 2802:         $r->print('<br />'.&mt('Home server').': '.$uhome.' '.
 2803:                   &Apache::lonnet::hostname($uhome));
 2804:     } elsif (($env{'form.login'} ne 'nochange') &&
 2805:              ($env{'form.login'} ne ''        )) {
 2806: 	# Modify user privileges
 2807:         if (! $amode || ! $genpwd) {
 2808: 	    $r->print($error.'Invalid login mode or password'.$end.$rtnlink);    
 2809: 	    return;
 2810: 	}
 2811: 	# Only allow authentication modification if the person has authority
 2812: 	if (&Apache::lonnet::allowed('mau',$env{'form.ccdomain'})) {
 2813: 	    $r->print('Modifying authentication: '.
 2814:                       &Apache::lonnet::modifyuserauth(
 2815: 		       $env{'form.ccdomain'},$env{'form.ccuname'},
 2816:                        $amode,$genpwd));
 2817:             $r->print('<br />'.&mt('Home server').': '.&Apache::lonnet::homeserver
 2818: 		  ($env{'form.ccuname'},$env{'form.ccdomain'}));
 2819: 	} else {
 2820: 	    # Okay, this is a non-fatal error.
 2821: 	    $r->print($error.&mt('You do not have the authority to modify this users authentication information.').$end);    
 2822: 	}
 2823:     }
 2824:     $r->rflush(); # Finish display of header before time consuming actions start
 2825:     &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state);
 2826:     ##
 2827:     my (@userroles,%userupdate,$cnum,$cdom,$defaultcredits,%namechanged);
 2828:     if ($context eq 'course') {
 2829:         ($cnum,$cdom) =
 2830:             &Apache::lonuserutils::get_course_identity();
 2831:         $crstype = &Apache::loncommon::course_type($cdom.'_'.$cnum);
 2832:         if ($showcredits) {
 2833:            $defaultcredits = &Apache::lonuserutils::get_defaultcredits($cdom,$cnum);
 2834:         }
 2835:     }
 2836:     if (! $env{'form.makeuser'} ) {
 2837:         # Check for need to change
 2838:         my %userenv = &Apache::lonnet::get
 2839:             ('environment',['firstname','middlename','lastname','generation',
 2840:              'id','permanentemail','portfolioquota','authorquota','inststatus',
 2841:              'tools.aboutme','tools.blog','tools.webdav','tools.portfolio',
 2842:              'requestcourses.official','requestcourses.unofficial',
 2843:              'requestcourses.community','requestcourses.textbook',
 2844:              'reqcrsotherdom.official','reqcrsotherdom.unofficial',
 2845:              'reqcrsotherdom.community','reqcrsotherdom.textbook',
 2846:              'reqcrsotherdom.placement','requestauthor',
 2847:              'adhocroles.'.$env{'request.role.domain'}],
 2848:               $env{'form.ccdomain'},$env{'form.ccuname'});
 2849:         my ($tmp) = keys(%userenv);
 2850:         if ($tmp =~ /^(con_lost|error)/i) { 
 2851:             %userenv = ();
 2852:         }
 2853:         my $no_forceid_alert;
 2854:         # Check to see if user information can be changed
 2855:         my %domconfig =
 2856:             &Apache::lonnet::get_dom('configuration',['usermodification'],
 2857:                                      $env{'form.ccdomain'});
 2858:         my @statuses = ('active','future');
 2859:         my %roles = &Apache::lonnet::get_my_roles($env{'form.ccuname'},$env{'form.ccdomain'},'userroles',\@statuses,undef,$env{'request.role.domain'});
 2860:         my ($auname,$audom);
 2861:         if ($context eq 'author') {
 2862:             $auname = $env{'user.name'};
 2863:             $audom = $env{'user.domain'};     
 2864:         }
 2865:         foreach my $item (keys(%roles)) {
 2866:             my ($rolenum,$roledom,$role) = split(/:/,$item,-1);
 2867:             if ($context eq 'course') {
 2868:                 if ($cnum ne '' && $cdom ne '') {
 2869:                     if ($rolenum eq $cnum && $roledom eq $cdom) {
 2870:                         if (!grep(/^\Q$role\E$/,@userroles)) {
 2871:                             push(@userroles,$role);
 2872:                         }
 2873:                     }
 2874:                 }
 2875:             } elsif ($context eq 'author') {
 2876:                 if ($rolenum eq $auname && $roledom eq $audom) {
 2877:                     if (!grep(/^\Q$role\E$/,@userroles)) { 
 2878:                         push(@userroles,$role);
 2879:                     }
 2880:                 }
 2881:             }
 2882:         }
 2883:         if ($env{'form.action'} eq 'singlestudent') {
 2884:             if (!grep(/^st$/,@userroles)) {
 2885:                 push(@userroles,'st');
 2886:             }
 2887:         } else {
 2888:             # Check for course or co-author roles being activated or re-enabled
 2889:             if ($context eq 'author' || $context eq 'course') {
 2890:                 foreach my $key (keys(%env)) {
 2891:                     if ($context eq 'author') {
 2892:                         if ($key=~/^form\.act_\Q$audom\E_\Q$auname\E_([^_]+)/) {
 2893:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 2894:                                 push(@userroles,$1);
 2895:                             }
 2896:                         } elsif ($key =~/^form\.ren\:\Q$audom\E\/\Q$auname\E_([^_]+)/) {
 2897:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 2898:                                 push(@userroles,$1);
 2899:                             }
 2900:                         }
 2901:                     } elsif ($context eq 'course') {
 2902:                         if ($key=~/^form\.act_\Q$cdom\E_\Q$cnum\E_([^_]+)/) {
 2903:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 2904:                                 push(@userroles,$1);
 2905:                             }
 2906:                         } elsif ($key =~/^form\.ren\:\Q$cdom\E\/\Q$cnum\E(\/?\w*)_([^_]+)/) {
 2907:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 2908:                                 push(@userroles,$1);
 2909:                             }
 2910:                         }
 2911:                     }
 2912:                 }
 2913:             }
 2914:         }
 2915:         #Check to see if we can change personal data for the user 
 2916:         my (@mod_disallowed,@longroles);
 2917:         foreach my $role (@userroles) {
 2918:             if ($role eq 'cr') {
 2919:                 push(@longroles,'Custom');
 2920:             } else {
 2921:                 push(@longroles,&Apache::lonnet::plaintext($role,$crstype)); 
 2922:             }
 2923:         }
 2924:         my %canmodify = &Apache::lonuserutils::can_modify_userinfo($context,$env{'form.ccdomain'},\@userinfo,\@userroles);
 2925:         foreach my $item (@userinfo) {
 2926:             # Strip leading and trailing whitespace
 2927:             $env{'form.c'.$item} =~ s/(\s+$|^\s+)//g;
 2928:             if (!$canmodify{$item}) {
 2929:                 if (defined($env{'form.c'.$item})) {
 2930:                     if ($env{'form.c'.$item} ne $userenv{$item}) {
 2931:                         push(@mod_disallowed,$item);
 2932:                     }
 2933:                 }
 2934:                 $env{'form.c'.$item} = $userenv{$item};
 2935:             }
 2936:         }
 2937:         # Check to see if we can change the Student/Employee ID
 2938:         my $forceid = $env{'form.forceid'};
 2939:         my $recurseid = $env{'form.recurseid'};
 2940:         my (%alerts,%rulematch,%idinst_results,%curr_rules,%got_rules);
 2941:         my %uidhash = &Apache::lonnet::idrget($env{'form.ccdomain'},
 2942:                                             $env{'form.ccuname'});
 2943:         if (($uidhash{$env{'form.ccuname'}}) && 
 2944:             ($uidhash{$env{'form.ccuname'}}!~/error\:/) && 
 2945:             (!$forceid)) {
 2946:             if ($env{'form.cid'} ne $uidhash{$env{'form.ccuname'}}) {
 2947:                 $env{'form.cid'} = $userenv{'id'};
 2948:                 $no_forceid_alert = &mt('New student/employee ID does not match existing ID for this user.')
 2949:                                    .'<br />'
 2950:                                    .&mt("Change is not permitted without checking the 'Force ID change' checkbox on the previous page.")
 2951:                                    .'<br />'."\n";
 2952:             }
 2953:         }
 2954:         if ($env{'form.cid'} ne $userenv{'id'}) {
 2955:             my $checkhash;
 2956:             my $checks = { 'id' => 1 };
 2957:             $checkhash->{$env{'form.ccuname'}.':'.$env{'form.ccdomain'}} = 
 2958:                    { 'newuser' => $newuser,
 2959:                      'id'  => $env{'form.cid'}, 
 2960:                    };
 2961:             &Apache::loncommon::user_rule_check($checkhash,$checks,
 2962:                 \%alerts,\%rulematch,\%idinst_results,\%curr_rules,\%got_rules);
 2963:             if (ref($alerts{'id'}) eq 'HASH') {
 2964:                 if (ref($alerts{'id'}{$env{'form.ccdomain'}}) eq 'HASH') {
 2965:                    $env{'form.cid'} = $userenv{'id'};
 2966:                 }
 2967:             }
 2968:         }
 2969:         my (%quotachanged,%oldquota,%newquota,%olddefquota,%newdefquota, 
 2970:             $oldinststatus,$newinststatus,%oldisdefault,%newisdefault,%oldsettings,
 2971:             %oldsettingstext,%newsettings,%newsettingstext,@disporder,
 2972:             %oldsettingstatus,%newsettingstatus);
 2973:         @disporder = ('inststatus');
 2974:         if ($env{'request.role.domain'} eq $env{'form.ccdomain'}) {
 2975:             push(@disporder,'requestcourses','requestauthor');
 2976:         } else {
 2977:             push(@disporder,'reqcrsotherdom');
 2978:         }
 2979:         push(@disporder,('quota','tools'));
 2980:         $oldinststatus = $userenv{'inststatus'};
 2981:         foreach my $name ('portfolio','author') {
 2982:             ($olddefquota{$name},$oldsettingstatus{$name}) = 
 2983:                 &Apache::loncommon::default_quota($env{'form.ccdomain'},$oldinststatus,$name);
 2984:             ($newdefquota{$name},$newsettingstatus{$name}) = ($olddefquota{$name},$oldsettingstatus{$name});
 2985:         }
 2986:         push(@disporder,'adhocroles');
 2987:         my %canshow;
 2988:         if (&Apache::lonnet::allowed('mpq',$env{'form.ccdomain'})) {
 2989:             $canshow{'quota'} = 1;
 2990:         }
 2991:         if (&Apache::lonnet::allowed('mut',$env{'form.ccdomain'})) {
 2992:             $canshow{'tools'} = 1;
 2993:         }
 2994:         if (&Apache::lonnet::allowed('ccc',$env{'form.ccdomain'})) {
 2995:             $canshow{'requestcourses'} = 1;
 2996:         } elsif (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) {
 2997:             $canshow{'reqcrsotherdom'} = 1;
 2998:         }
 2999:         if (&Apache::lonnet::allowed('mau',$env{'form.ccdomain'})) {
 3000:             $canshow{'inststatus'} = 1;
 3001:         }
 3002:         if (&Apache::lonnet::allowed('cau',$env{'form.ccdomain'})) {
 3003:             $canshow{'requestauthor'} = 1;
 3004:         }
 3005:         if (&Apache::lonnet::allowed('cdh',$env{'request.role.domain'})) {
 3006:             $canshow{'adhocroles'} = 1;
 3007:         }
 3008:         my (%changeHash,%changed);
 3009:         if ($oldinststatus eq '') {
 3010:             $oldsettings{'inststatus'} = $othertitle; 
 3011:         } else {
 3012:             if (ref($usertypes) eq 'HASH') {
 3013:                 $oldsettings{'inststatus'} = join(', ',map{ $usertypes->{ &unescape($_) }; } (split(/:/,$userenv{'inststatus'})));
 3014:             } else {
 3015:                 $oldsettings{'inststatus'} = join(', ',map{ &unescape($_); } (split(/:/,$userenv{'inststatus'})));
 3016:             }
 3017:         }
 3018:         $changeHash{'inststatus'} = $userenv{'inststatus'};
 3019:         if ($canmodify_status{'inststatus'}) {
 3020:             $canshow{'inststatus'} = 1;
 3021:             if (exists($env{'form.inststatus'})) {
 3022:                 my @inststatuses = &Apache::loncommon::get_env_multiple('form.inststatus');
 3023:                 if (@inststatuses > 0) {
 3024:                     $newinststatus = join(':',map { &escape($_); } @inststatuses);
 3025:                     $changeHash{'inststatus'} = $newinststatus;
 3026:                     if ($newinststatus ne $oldinststatus) {
 3027:                         $changed{'inststatus'} = $newinststatus;
 3028:                         foreach my $name ('portfolio','author') {
 3029:                             ($newdefquota{$name},$newsettingstatus{$name}) =
 3030:                                 &Apache::loncommon::default_quota($env{'form.ccdomain'},$newinststatus,$name);
 3031:                         }
 3032:                     }
 3033:                     if (ref($usertypes) eq 'HASH') {
 3034:                         $newsettings{'inststatus'} = join(', ',map{ $usertypes->{$_}; } (@inststatuses)); 
 3035:                     } else {
 3036:                         $newsettings{'inststatus'} = join(', ',@inststatuses);
 3037:                     }
 3038:                 }
 3039:             } else {
 3040:                 $newinststatus = '';
 3041:                 $changeHash{'inststatus'} = $newinststatus;
 3042:                 $newsettings{'inststatus'} = $othertitle;
 3043:                 if ($newinststatus ne $oldinststatus) {
 3044:                     $changed{'inststatus'} = $changeHash{'inststatus'};
 3045:                     foreach my $name ('portfolio','author') {
 3046:                         ($newdefquota{$name},$newsettingstatus{$name}) =
 3047:                             &Apache::loncommon::default_quota($env{'form.ccdomain'},$newinststatus,$name);
 3048:                     }
 3049:                 }
 3050:             }
 3051:         } elsif ($context ne 'selfcreate') {
 3052:             $canshow{'inststatus'} = 1;
 3053:             $newsettings{'inststatus'} = $oldsettings{'inststatus'};
 3054:         }
 3055:         foreach my $name ('portfolio','author') {
 3056:             $changeHash{$name.'quota'} = $userenv{$name.'quota'};
 3057:         }
 3058:         if ($context eq 'domain') {
 3059:             foreach my $name ('portfolio','author') {
 3060:                 if ($userenv{$name.'quota'} ne '') {
 3061:                     $oldquota{$name} = $userenv{$name.'quota'};
 3062:                     if ($env{'form.custom_'.$name.'quota'} == 1) {
 3063:                         if ($env{'form.'.$name.'quota'} eq '') {
 3064:                             $newquota{$name} = 0;
 3065:                         } else {
 3066:                             $newquota{$name} = $env{'form.'.$name.'quota'};
 3067:                             $newquota{$name} =~ s/[^\d\.]//g;
 3068:                         }
 3069:                         if ($newquota{$name} != $oldquota{$name}) {
 3070:                             if (&quota_admin($newquota{$name},\%changeHash,$name)) {
 3071:                                 $changed{$name.'quota'} = 1;
 3072:                             }
 3073:                         }
 3074:                     } else {
 3075:                         if (&quota_admin('',\%changeHash,$name)) {
 3076:                             $changed{$name.'quota'} = 1;
 3077:                             $newquota{$name} = $newdefquota{$name};
 3078:                             $newisdefault{$name} = 1;
 3079:                         }
 3080:                     }
 3081:                 } else {
 3082:                     $oldisdefault{$name} = 1;
 3083:                     $oldquota{$name} = $olddefquota{$name};
 3084:                     if ($env{'form.custom_'.$name.'quota'} == 1) {
 3085:                         if ($env{'form.'.$name.'quota'} eq '') {
 3086:                             $newquota{$name} = 0;
 3087:                         } else {
 3088:                             $newquota{$name} = $env{'form.'.$name.'quota'};
 3089:                             $newquota{$name} =~ s/[^\d\.]//g;
 3090:                         }
 3091:                         if (&quota_admin($newquota{$name},\%changeHash,$name)) {
 3092:                             $changed{$name.'quota'} = 1;
 3093:                         }
 3094:                     } else {
 3095:                         $newquota{$name} = $newdefquota{$name};
 3096:                         $newisdefault{$name} = 1;
 3097:                     }
 3098:                 }
 3099:                 if ($oldisdefault{$name}) {
 3100:                     $oldsettingstext{'quota'}{$name} = &get_defaultquota_text($oldsettingstatus{$name});
 3101:                 }  else {
 3102:                     $oldsettingstext{'quota'}{$name} = &mt('custom quota: [_1] MB',$oldquota{$name});
 3103:                 }
 3104:                 if ($newisdefault{$name}) {
 3105:                     $newsettingstext{'quota'}{$name} = &get_defaultquota_text($newsettingstatus{$name});
 3106:                 } else {
 3107:                     $newsettingstext{'quota'}{$name} = &mt('custom quota: [_1] MB',$newquota{$name});
 3108:                 }
 3109:             }
 3110:             &tool_changes('tools',\@usertools,\%oldsettings,\%oldsettingstext,\%userenv,
 3111:                           \%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3112:             if ($env{'form.ccdomain'} eq $env{'request.role.domain'}) {
 3113:                 &tool_changes('requestcourses',\@requestcourses,\%oldsettings,\%oldsettingstext,
 3114:                               \%userenv,\%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3115:                 &tool_changes('requestauthor',\@requestauthor,\%oldsettings,\%oldsettingstext,
 3116:                               \%userenv,\%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3117:             } else {
 3118:                 &tool_changes('reqcrsotherdom',\@requestcourses,\%oldsettings,\%oldsettingstext,
 3119:                               \%userenv,\%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3120:             }
 3121:             if ($userenv{'adhocroles.'.$env{'request.role.domain'}}) {
 3122:                 $changeHash{'adhocroles.'.$env{'request.role.domain'}} = $userenv{'adhocroles.'.$env{'request.role.domain'}};
 3123:             }
 3124:             if (&adhocrole_changes(\%changeHash,\%userenv)) {
 3125:                 $changed{'adhocroles'} = 1;
 3126:                 $oldsettings{'adhocroles'} = $userenv{'adhocroles.'.$env{'request.role.domain'}};
 3127:                 $newsettings{'adhocroles'} = $changeHash{'adhocroles.'.$env{'request.role.domain'}}; 
 3128:             }
 3129:         }
 3130:         foreach my $item (@userinfo) {
 3131:             if ($env{'form.c'.$item} ne $userenv{$item}) {
 3132:                 $namechanged{$item} = 1;
 3133:             }
 3134:         }
 3135:         foreach my $name ('portfolio','author') {
 3136:             $oldsettings{'quota'}{$name} = &mt('[_1] MB',$oldquota{$name});
 3137:             $newsettings{'quota'}{$name} = &mt('[_1] MB',$newquota{$name});
 3138:         }
 3139:         if ((keys(%namechanged) > 0) || (keys(%changed) > 0)) {
 3140:             my ($chgresult,$namechgresult);
 3141:             if (keys(%changed) > 0) {
 3142:                 $chgresult = 
 3143:                     &Apache::lonnet::put('environment',\%changeHash,
 3144:                                   $env{'form.ccdomain'},$env{'form.ccuname'});
 3145:                 if ($chgresult eq 'ok') {
 3146:                     if (($env{'user.name'} eq $env{'form.ccuname'}) &&
 3147:                         ($env{'user.domain'} eq $env{'form.ccdomain'})) {
 3148:                         my %newenvhash;
 3149:                         foreach my $key (keys(%changed)) {
 3150:                             if (($key eq 'official') || ($key eq 'unofficial') ||
 3151:                                 ($key eq 'community') || ($key eq 'textbook') ||
 3152:                                 ($key eq 'placement')) {
 3153:                                 $newenvhash{'environment.requestcourses.'.$key} =
 3154:                                     $changeHash{'requestcourses.'.$key};
 3155:                                 if ($changeHash{'requestcourses.'.$key}) {
 3156:                                     $newenvhash{'environment.canrequest.'.$key} = 1;
 3157:                                 } else {
 3158:                                     $newenvhash{'environment.canrequest.'.$key} =
 3159:           &Apache::lonnet::usertools_access($env{'user.name'},$env{'user.domain'},
 3160:                                             $key,'reload','requestcourses');
 3161:                                 }
 3162:                             } elsif ($key eq 'requestauthor') {
 3163:                                 $newenvhash{'environment.'.$key} = $changeHash{$key};
 3164:                                 if ($changeHash{$key}) {
 3165:                                     $newenvhash{'environment.canrequest.author'} = 1;
 3166:                                 } else {
 3167:                                     $newenvhash{'environment.canrequest.author'} =
 3168:           &Apache::lonnet::usertools_access($env{'user.name'},$env{'user.domain'},
 3169:                                             $key,'reload','requestauthor');
 3170:                                 }
 3171:                             } elsif ($key eq 'adhocroles') {
 3172:                                 $newenvhash{'adhocroles.'.$env{'request.role.domain'}} =
 3173:                                     $changeHash{'adhocroles.'.$env{'request.role.domain'}};
 3174:                             } elsif ($key ne 'quota') {
 3175:                                 $newenvhash{'environment.tools.'.$key} = 
 3176:                                     $changeHash{'tools.'.$key};
 3177:                                 if ($changeHash{'tools.'.$key} ne '') {
 3178:                                     $newenvhash{'environment.availabletools.'.$key} =
 3179:                                         $changeHash{'tools.'.$key};
 3180:                                 } else {
 3181:                                     $newenvhash{'environment.availabletools.'.$key} =
 3182:           &Apache::lonnet::usertools_access($env{'user.name'},$env{'user.domain'},
 3183:           $key,'reload','tools');
 3184:                                 }
 3185:                             }
 3186:                         }
 3187:                         if (keys(%newenvhash)) {
 3188:                             &Apache::lonnet::appenv(\%newenvhash);
 3189:                         }
 3190:                     }
 3191:                 }
 3192:             }
 3193:             if (keys(%namechanged) > 0) {
 3194:                 foreach my $field (@userinfo) {
 3195:                     $changeHash{$field}  = $env{'form.c'.$field};
 3196:                 }
 3197: # Make the change
 3198:                 $namechgresult =
 3199:                     &Apache::lonnet::modifyuser($env{'form.ccdomain'},
 3200:                         $env{'form.ccuname'},$changeHash{'id'},undef,undef,
 3201:                         $changeHash{'firstname'},$changeHash{'middlename'},
 3202:                         $changeHash{'lastname'},$changeHash{'generation'},
 3203:                         $changeHash{'id'},undef,$changeHash{'permanentemail'},undef,\@userinfo);
 3204:                 %userupdate = (
 3205:                                lastname   => $env{'form.clastname'},
 3206:                                middlename => $env{'form.cmiddlename'},
 3207:                                firstname  => $env{'form.cfirstname'},
 3208:                                generation => $env{'form.cgeneration'},
 3209:                                id         => $env{'form.cid'},
 3210:                              );
 3211:             }
 3212:             if (((keys(%namechanged) > 0) && $namechgresult eq 'ok') || 
 3213:                 ((keys(%changed) > 0) && $chgresult eq 'ok')) {
 3214:             # Tell the user we changed the name
 3215:                 &display_userinfo($r,1,\@disporder,\%canshow,\@requestcourses,
 3216:                                   \@usertools,\@requestauthor,\%userenv,\%changed,\%namechanged,
 3217:                                   \%oldsettings, \%oldsettingstext,\%newsettings,
 3218:                                   \%newsettingstext);
 3219:                 if ($env{'form.cid'} ne $userenv{'id'}) {
 3220:                     &Apache::lonnet::idput($env{'form.ccdomain'},
 3221:                          {$env{'form.ccuname'} => $env{'form.cid'}},$uhome,'ids');
 3222:                     if (($recurseid) &&
 3223:                         (&Apache::lonnet::allowed('mau',$env{'form.ccdomain'}))) {
 3224:                         my $idresult = 
 3225:                             &Apache::lonuserutils::propagate_id_change(
 3226:                                 $env{'form.ccuname'},$env{'form.ccdomain'},
 3227:                                 \%userupdate);
 3228:                         $r->print('<br />'.$idresult.'<br />');
 3229:                     }
 3230:                 }
 3231:                 if (($env{'form.ccdomain'} eq $env{'user.domain'}) && 
 3232:                     ($env{'form.ccuname'} eq $env{'user.name'})) {
 3233:                     my %newenvhash;
 3234:                     foreach my $key (keys(%changeHash)) {
 3235:                         $newenvhash{'environment.'.$key} = $changeHash{$key};
 3236:                     }
 3237:                     &Apache::lonnet::appenv(\%newenvhash);
 3238:                 }
 3239:             } else { # error occurred
 3240:                 $r->print(
 3241:                     '<p class="LC_error">'
 3242:                    .&mt('Unable to successfully change environment for [_1] in domain [_2].',
 3243:                             '"'.$env{'form.ccuname'}.'"',
 3244:                             '"'.$env{'form.ccdomain'}.'"')
 3245:                    .'</p>');
 3246:             }
 3247:         } else { # End of if ($env ... ) logic
 3248:             # They did not want to change the users name, quota, tool availability,
 3249:             # or ability to request creation of courses, 
 3250:             # but we can still tell them what the name and quota and availabilities are  
 3251:             &display_userinfo($r,undef,\@disporder,\%canshow,\@requestcourses,
 3252:                               \@usertools,\@requestauthor,\%userenv,\%changed,\%namechanged,\%oldsettings,
 3253:                               \%oldsettingstext,\%newsettings,\%newsettingstext);
 3254:         }
 3255:         if (@mod_disallowed) {
 3256:             my ($rolestr,$contextname);
 3257:             if (@longroles > 0) {
 3258:                 $rolestr = join(', ',@longroles);
 3259:             } else {
 3260:                 $rolestr = &mt('No roles');
 3261:             }
 3262:             if ($context eq 'course') {
 3263:                 $contextname = 'course';
 3264:             } elsif ($context eq 'author') {
 3265:                 $contextname = 'co-author';
 3266:             }
 3267:             $r->print(&mt('The following fields were not updated: ').'<ul>');
 3268:             my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
 3269:             foreach my $field (@mod_disallowed) {
 3270:                 $r->print('<li>'.$fieldtitles{$field}.'</li>'."\n"); 
 3271:             }
 3272:             $r->print('</ul>');
 3273:             if (@mod_disallowed == 1) {
 3274:                 $r->print(&mt("You do not have the authority to change this field given the user's current set of active/future $contextname roles:"));
 3275:             } else {
 3276:                 $r->print(&mt("You do not have the authority to change these fields given the user's current set of active/future $contextname roles:"));
 3277:             }
 3278:             my $helplink = 'javascript:helpMenu('."'display'".')';
 3279:             $r->print('<span class="LC_cusr_emph">'.$rolestr.'</span><br />'
 3280:                      .&mt('Please contact your [_1]helpdesk[_2] for more information.'
 3281:                          ,'<a href="'.$helplink.'">','</a>')
 3282:                       .'<br />');
 3283:         }
 3284:         $r->print('<span class="LC_warning">'
 3285:                   .$no_forceid_alert
 3286:                   .&Apache::lonuserutils::print_namespacing_alerts($env{'form.ccdomain'},\%alerts,\%curr_rules)
 3287:                   .'</span>');
 3288:     }
 3289:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 3290:     if ($env{'form.action'} eq 'singlestudent') {
 3291:         &enroll_single_student($r,$uhome,$amode,$genpwd,$now,$newuser,$context,
 3292:                                $crstype,$showcredits,$defaultcredits);
 3293:         my $linktext = ($crstype eq 'Community' ?
 3294:             &mt('Enroll Another Member') : &mt('Enroll Another Student'));
 3295:         $r->print(
 3296:             &Apache::lonhtmlcommon::actionbox([
 3297:                 '<a href="javascript:backPage(document.userupdate)">'
 3298:                .($crstype eq 'Community' ? 
 3299:                     &mt('Enroll Another Member') : &mt('Enroll Another Student'))
 3300:                .'</a>']));
 3301:     } else {
 3302:         my @rolechanges = &update_roles($r,$context,$showcredits);
 3303:         if (keys(%namechanged) > 0) {
 3304:             if ($context eq 'course') {
 3305:                 if (@userroles > 0) {
 3306:                     if ((@rolechanges == 0) || 
 3307:                         (!(grep(/^st$/,@rolechanges)))) {
 3308:                         if (grep(/^st$/,@userroles)) {
 3309:                             my $classlistupdated =
 3310:                                 &Apache::lonuserutils::update_classlist($cdom,
 3311:                                               $cnum,$env{'form.ccdomain'},
 3312:                                        $env{'form.ccuname'},\%userupdate);
 3313:                         }
 3314:                     }
 3315:                 }
 3316:             }
 3317:         }
 3318:         my $userinfo = &Apache::loncommon::plainname($env{'form.ccuname'},
 3319:                                                      $env{'form.ccdomain'});
 3320:         if ($env{'form.popup'}) {
 3321:             $r->print('<p><a href="javascript:window.close()">'.&mt('Close window').'</a></p>');
 3322:         } else {
 3323:             $r->print('<br />'.&Apache::lonhtmlcommon::actionbox(['<a href="javascript:backPage(document.userupdate,'."'$env{'form.prevphase'}','modify'".')">'
 3324:                      .&mt('Modify this user: [_1]','<span class="LC_cusr_emph">'.$env{'form.ccuname'}.':'.$env{'form.ccdomain'}.' ('.$userinfo.')</span>').'</a>',
 3325:                      '<a href="javascript:backPage(document.userupdate)">'.&mt('Create/Modify Another User').'</a>']));
 3326:         }
 3327:     }
 3328: }
 3329: 
 3330: sub display_userinfo {
 3331:     my ($r,$changed,$order,$canshow,$requestcourses,$usertools,$requestauthor,
 3332:         $userenv,$changedhash,$namechangedhash,$oldsetting,$oldsettingtext,
 3333:         $newsetting,$newsettingtext) = @_;
 3334:     return unless (ref($order) eq 'ARRAY' &&
 3335:                    ref($canshow) eq 'HASH' && 
 3336:                    ref($requestcourses) eq 'ARRAY' && 
 3337:                    ref($requestauthor) eq 'ARRAY' &&
 3338:                    ref($usertools) eq 'ARRAY' && 
 3339:                    ref($userenv) eq 'HASH' &&
 3340:                    ref($changedhash) eq 'HASH' &&
 3341:                    ref($oldsetting) eq 'HASH' &&
 3342:                    ref($oldsettingtext) eq 'HASH' &&
 3343:                    ref($newsetting) eq 'HASH' &&
 3344:                    ref($newsettingtext) eq 'HASH');
 3345:     my %lt=&Apache::lonlocal::texthash(
 3346:          'ui'             => 'User Information',
 3347:          'uic'            => 'User Information Changed',
 3348:          'firstname'      => 'First Name',
 3349:          'middlename'     => 'Middle Name',
 3350:          'lastname'       => 'Last Name',
 3351:          'generation'     => 'Generation',
 3352:          'id'             => 'Student/Employee ID',
 3353:          'permanentemail' => 'Permanent e-mail address',
 3354:          'portfolioquota' => 'Disk space allocated to portfolio files',
 3355:          'authorquota'    => 'Disk space allocated to Authoring Space',
 3356:          'blog'           => 'Blog Availability',
 3357:          'webdav'         => 'WebDAV Availability',
 3358:          'aboutme'        => 'Personal Information Page Availability',
 3359:          'portfolio'      => 'Portfolio Availability',
 3360:          'official'       => 'Can Request Official Courses',
 3361:          'unofficial'     => 'Can Request Unofficial Courses',
 3362:          'community'      => 'Can Request Communities',
 3363:          'textbook'       => 'Can Request Textbook Courses',
 3364:          'placement'      => 'Can Request Placement Tests',
 3365:          'requestauthor'  => 'Can Request Author Role',
 3366:          'adhocroles'     => 'Ad Hoc Roles Selectable via Helpdesk Role',
 3367:          'inststatus'     => "Affiliation",
 3368:          'prvs'           => 'Previous Value:',
 3369:          'chto'           => 'Changed To:'
 3370:     );
 3371:     if ($changed) {
 3372:         $r->print('<h3>'.$lt{'uic'}.'</h3>'.
 3373:                 &Apache::loncommon::start_data_table().
 3374:                 &Apache::loncommon::start_data_table_header_row());
 3375:         $r->print("<th>&nbsp;</th>\n");
 3376:         $r->print('<th><b>'.$lt{'prvs'}.'</b></th>');
 3377:         $r->print('<th><span class="LC_nobreak"><b>'.$lt{'chto'}.'</b></span></th>');
 3378:         $r->print(&Apache::loncommon::end_data_table_header_row());
 3379:         my @userinfo = ('firstname','middlename','lastname','generation','permanentemail','id');
 3380: 
 3381:         foreach my $item (@userinfo) {
 3382:             my $value = $env{'form.c'.$item};
 3383:             #show changes only:
 3384:             unless ($value eq $userenv->{$item}){
 3385:                 $r->print(&Apache::loncommon::start_data_table_row());
 3386:                 $r->print("<td>$lt{$item}</td>\n");
 3387:                 $r->print("<td>".$userenv->{$item}."</td>\n");
 3388:                 $r->print("<td>$value </td>\n");
 3389:                 $r->print(&Apache::loncommon::end_data_table_row());
 3390:             }
 3391:         }
 3392:         foreach my $entry (@{$order}) {
 3393:             if ($canshow->{$entry}) {
 3394:                 if (($entry eq 'requestcourses') || ($entry eq 'reqcrsotherdom') || ($entry eq 'requestauthor')) {
 3395:                     my @items;
 3396:                     if ($entry eq 'requestauthor') {
 3397:                         @items = ($entry);
 3398:                     } else {
 3399:                         @items = @{$requestcourses};
 3400:                     }
 3401:                     foreach my $item (@items) {
 3402:                         if (($newsetting->{$item} ne $oldsetting->{$item}) || 
 3403:                             ($newsettingtext->{$item} ne $oldsettingtext->{$item})) {
 3404:                             $r->print(&Apache::loncommon::start_data_table_row()."\n");  
 3405:                             $r->print("<td>$lt{$item}</td>\n");
 3406:                             $r->print("<td>".$oldsetting->{$item});
 3407:                             if ($oldsettingtext->{$item}) {
 3408:                                 if ($oldsetting->{$item}) {
 3409:                                     $r->print(' -- ');
 3410:                                 }
 3411:                                 $r->print($oldsettingtext->{$item});
 3412:                             }
 3413:                             $r->print("</td>\n");
 3414:                             $r->print("<td>".$newsetting->{$item});
 3415:                             if ($newsettingtext->{$item}) {
 3416:                                 if ($newsetting->{$item}) {
 3417:                                     $r->print(' -- ');
 3418:                                 }
 3419:                                 $r->print($newsettingtext->{$item});
 3420:                             }
 3421:                             $r->print("</td>\n");
 3422:                             $r->print(&Apache::loncommon::end_data_table_row()."\n");
 3423:                         }
 3424:                     }
 3425:                 } elsif ($entry eq 'tools') {
 3426:                     foreach my $item (@{$usertools}) {
 3427:                         if ($newsetting->{$item} ne $oldsetting->{$item}) {
 3428:                             $r->print(&Apache::loncommon::start_data_table_row()."\n");
 3429:                             $r->print("<td>$lt{$item}</td>\n");
 3430:                             $r->print("<td>".$oldsetting->{$item}.' '.$oldsettingtext->{$item}."</td>\n");
 3431:                             $r->print("<td>".$newsetting->{$item}.' '.$newsettingtext->{$item}."</td>\n");
 3432:                             $r->print(&Apache::loncommon::end_data_table_row()."\n");
 3433:                         }
 3434:                     }
 3435:                 } elsif ($entry eq 'quota') {
 3436:                     if ((ref($oldsetting->{$entry}) eq 'HASH') && (ref($oldsettingtext->{$entry}) eq 'HASH') &&
 3437:                         (ref($newsetting->{$entry}) eq 'HASH') && (ref($newsettingtext->{$entry}) eq 'HASH')) {
 3438:                         foreach my $name ('portfolio','author') {
 3439:                             if ($newsetting->{$entry}->{$name} ne $oldsetting->{$entry}->{$name}) {
 3440:                                 $r->print(&Apache::loncommon::start_data_table_row()."\n");
 3441:                                 $r->print("<td>$lt{$name.$entry}</td>\n");
 3442:                                 $r->print("<td>".$oldsettingtext->{$entry}->{$name}."</td>\n");
 3443:                                 $r->print("<td>".$newsettingtext->{$entry}->{$name}."</td>\n");
 3444:                                 $r->print(&Apache::loncommon::end_data_table_row()."\n");
 3445:                             }
 3446:                         }
 3447:                     }
 3448:                 } else {
 3449:                     if ($newsetting->{$entry} ne $oldsetting->{$entry}) {
 3450:                         $r->print(&Apache::loncommon::start_data_table_row()."\n");
 3451:                         $r->print("<td>$lt{$entry}</td>\n");
 3452:                         $r->print("<td>".$oldsetting->{$entry}.' '.$oldsettingtext->{$entry}."</td>\n");
 3453:                         $r->print("<td>".$newsetting->{$entry}.' '.$newsettingtext->{$entry}."</td>\n");
 3454:                         $r->print(&Apache::loncommon::end_data_table_row()."\n");
 3455:                     }
 3456:                 }
 3457:             }
 3458:         }
 3459:         $r->print(&Apache::loncommon::end_data_table().'<br />');
 3460:     } else {
 3461:         $r->print('<h3>'.$lt{'ui'}.'</h3>'.
 3462:                   '<p>'.&mt('No changes made to user information').'</p>');
 3463:     }
 3464:     return;
 3465: }
 3466: 
 3467: sub tool_changes {
 3468:     my ($context,$usertools,$oldaccess,$oldaccesstext,$userenv,$changeHash,
 3469:         $changed,$newaccess,$newaccesstext) = @_;
 3470:     if (!((ref($usertools) eq 'ARRAY') && (ref($oldaccess) eq 'HASH') &&
 3471:           (ref($oldaccesstext) eq 'HASH') && (ref($userenv) eq 'HASH') &&
 3472:           (ref($changeHash) eq 'HASH') && (ref($changed) eq 'HASH') &&
 3473:           (ref($newaccess) eq 'HASH') && (ref($newaccesstext) eq 'HASH'))) {
 3474:         return;
 3475:     }
 3476:     my %reqdisplay = &requestchange_display();
 3477:     if ($context eq 'reqcrsotherdom') {
 3478:         my @options = ('approval','validate','autolimit');
 3479:         my $optregex = join('|',@options);
 3480:         my $cdom = $env{'request.role.domain'};
 3481:         foreach my $tool (@{$usertools}) {
 3482:             $oldaccesstext->{$tool} = &mt("availability set to 'off'");
 3483:             $newaccesstext->{$tool} = $oldaccesstext->{$tool};
 3484:             $changeHash->{$context.'.'.$tool} = $userenv->{$context.'.'.$tool};
 3485:             my ($newop,$limit);
 3486:             if ($env{'form.'.$context.'_'.$tool}) {
 3487:                 $newop = $env{'form.'.$context.'_'.$tool};
 3488:                 if ($newop eq 'autolimit') {
 3489:                     $limit = $env{'form.'.$context.'_'.$tool.'_limit'};
 3490:                     $limit =~ s/\D+//g;
 3491:                     $newop .= '='.$limit;
 3492:                 }
 3493:             }
 3494:             if ($userenv->{$context.'.'.$tool} eq '') {
 3495:                 if ($newop) {
 3496:                     $changed->{$tool}=&tool_admin($tool,$cdom.':'.$newop,
 3497:                                                   $changeHash,$context);
 3498:                     if ($changed->{$tool}) {
 3499:                         if ($newop =~ /^autolimit/) {
 3500:                             if ($limit) {
 3501:                                 $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3502:                             } else {
 3503:                                 $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3504:                             }
 3505:                         } else {
 3506:                             $newaccesstext->{$tool} = $reqdisplay{$newop};
 3507:                         }
 3508:                     } else {
 3509:                         $newaccesstext->{$tool} = $oldaccesstext->{$tool};
 3510:                     }
 3511:                 }
 3512:             } else {
 3513:                 my @curr = split(',',$userenv->{$context.'.'.$tool});
 3514:                 my @new;
 3515:                 my $changedoms;
 3516:                 foreach my $req (@curr) {
 3517:                     if ($req =~ /^\Q$cdom\E\:($optregex\=?\d*)$/) {
 3518:                         my $oldop = $1;
 3519:                         if ($oldop =~ /^autolimit=(\d*)/) {
 3520:                             my $limit = $1;
 3521:                             if ($limit) {
 3522:                                 $oldaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3523:                             } else {
 3524:                                 $oldaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3525:                             }
 3526:                         } else {
 3527:                             $oldaccesstext->{$tool} = $reqdisplay{$oldop};
 3528:                         }
 3529:                         if ($oldop ne $newop) {
 3530:                             $changedoms = 1;
 3531:                             foreach my $item (@curr) {
 3532:                                 my ($reqdom,$option) = split(':',$item);
 3533:                                 unless ($reqdom eq $cdom) {
 3534:                                     push(@new,$item);
 3535:                                 }
 3536:                             }
 3537:                             if ($newop) {
 3538:                                 push(@new,$cdom.':'.$newop);
 3539:                             }
 3540:                             @new = sort(@new);
 3541:                         }
 3542:                         last;
 3543:                     }
 3544:                 }
 3545:                 if ((!$changedoms) && ($newop)) {
 3546:                     $changedoms = 1;
 3547:                     @new = sort(@curr,$cdom.':'.$newop);
 3548:                 }
 3549:                 if ($changedoms) {
 3550:                     my $newdomstr;
 3551:                     if (@new) {
 3552:                         $newdomstr = join(',',@new);
 3553:                     }
 3554:                     $changed->{$tool}=&tool_admin($tool,$newdomstr,$changeHash,
 3555:                                                   $context);
 3556:                     if ($changed->{$tool}) {
 3557:                         if ($env{'form.'.$context.'_'.$tool}) {
 3558:                             if ($env{'form.'.$context.'_'.$tool} eq 'autolimit') {
 3559:                                 my $limit = $env{'form.'.$context.'_'.$tool.'_limit'};
 3560:                                 $limit =~ s/\D+//g;
 3561:                                 if ($limit) {
 3562:                                     $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3563:                                 } else {
 3564:                                     $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3565:                                 }
 3566:                             } else {
 3567:                                 $newaccesstext->{$tool} = $reqdisplay{$env{'form.'.$context.'_'.$tool}};
 3568:                             }
 3569:                         } else {
 3570:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3571:                         }
 3572:                     }
 3573:                 }
 3574:             }
 3575:         }
 3576:         return;
 3577:     }
 3578:     foreach my $tool (@{$usertools}) {
 3579:         my ($newval,$limit,$envkey);
 3580:         $envkey = $context.'.'.$tool;
 3581:         if ($context eq 'requestcourses') {
 3582:             $newval = $env{'form.crsreq_'.$tool};
 3583:             if ($newval eq 'autolimit') {
 3584:                 $limit = $env{'form.crsreq_'.$tool.'_limit'};
 3585:                 $limit =~ s/\D+//g;
 3586:                 $newval .= '='.$limit;
 3587:             }
 3588:         } elsif ($context eq 'requestauthor') {
 3589:             $newval = $env{'form.'.$context};
 3590:             $envkey = $context;
 3591:         } else {
 3592:             $newval = $env{'form.'.$context.'_'.$tool};
 3593:         }
 3594:         if ($userenv->{$envkey} ne '') {
 3595:             $oldaccess->{$tool} = &mt('custom');
 3596:             if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 3597:                 if ($userenv->{$envkey} =~ /^autolimit=(\d*)$/) {
 3598:                     my $currlimit = $1;
 3599:                     if ($currlimit eq '') {
 3600:                         $oldaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3601:                     } else {
 3602:                         $oldaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$currlimit);
 3603:                     }
 3604:                 } elsif ($userenv->{$envkey}) {
 3605:                     $oldaccesstext->{$tool} = $reqdisplay{$userenv->{$envkey}};
 3606:                 } else {
 3607:                     $oldaccesstext->{$tool} = &mt("availability set to 'off'");
 3608:                 }
 3609:             } else {
 3610:                 if ($userenv->{$envkey}) {
 3611:                     $oldaccesstext->{$tool} = &mt("availability set to 'on'");
 3612:                 } else {
 3613:                     $oldaccesstext->{$tool} = &mt("availability set to 'off'");
 3614:                 }
 3615:             }
 3616:             $changeHash->{$envkey} = $userenv->{$envkey};
 3617:             if ($env{'form.custom'.$tool} == 1) {
 3618:                 if ($newval ne $userenv->{$envkey}) {
 3619:                     $changed->{$tool} = &tool_admin($tool,$newval,$changeHash,
 3620:                                                     $context);
 3621:                     if ($changed->{$tool}) {
 3622:                         $newaccess->{$tool} = &mt('custom');
 3623:                         if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 3624:                             if ($newval =~ /^autolimit/) {
 3625:                                 if ($limit) {
 3626:                                     $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3627:                                 } else {
 3628:                                     $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3629:                                 }
 3630:                             } elsif ($newval) {
 3631:                                 $newaccesstext->{$tool} = $reqdisplay{$newval};
 3632:                             } else {
 3633:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3634:                             }
 3635:                         } else {
 3636:                             if ($newval) {
 3637:                                 $newaccesstext->{$tool} = &mt("availability set to 'on'");
 3638:                             } else {
 3639:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3640:                             }
 3641:                         }
 3642:                     } else {
 3643:                         $newaccess->{$tool} = $oldaccess->{$tool};
 3644:                         if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 3645:                             if ($newval =~ /^autolimit/) {
 3646:                                 if ($limit) {
 3647:                                     $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3648:                                 } else {
 3649:                                     $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3650:                                 }
 3651:                             } elsif ($newval) {
 3652:                                 $newaccesstext->{$tool} = $reqdisplay{$newval};
 3653:                             } else {
 3654:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3655:                             }
 3656:                         } else {
 3657:                             if ($userenv->{$context.'.'.$tool}) {
 3658:                                 $newaccesstext->{$tool} = &mt("availability set to 'on'");
 3659:                             } else {
 3660:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3661:                             }
 3662:                         }
 3663:                     }
 3664:                 } else {
 3665:                     $newaccess->{$tool} = $oldaccess->{$tool};
 3666:                     $newaccesstext->{$tool} = $oldaccesstext->{$tool};
 3667:                 }
 3668:             } else {
 3669:                 $changed->{$tool} = &tool_admin($tool,'',$changeHash,$context);
 3670:                 if ($changed->{$tool}) {
 3671:                     $newaccess->{$tool} = &mt('default');
 3672:                 } else {
 3673:                     $newaccess->{$tool} = $oldaccess->{$tool};
 3674:                     if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 3675:                         if ($newval =~ /^autolimit/) {
 3676:                             if ($limit) {
 3677:                                 $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3678:                             } else {
 3679:                                 $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3680:                             }
 3681:                         } elsif ($newval) {
 3682:                             $newaccesstext->{$tool} = $reqdisplay{$newval};
 3683:                         } else {
 3684:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3685:                         }
 3686:                     } else {
 3687:                         if ($userenv->{$context.'.'.$tool}) {
 3688:                             $newaccesstext->{$tool} = &mt("availability set to 'on'");
 3689:                         } else {
 3690:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3691:                         }
 3692:                     }
 3693:                 }
 3694:             }
 3695:         } else {
 3696:             $oldaccess->{$tool} = &mt('default');
 3697:             if ($env{'form.custom'.$tool} == 1) {
 3698:                 $changed->{$tool} = &tool_admin($tool,$newval,$changeHash,
 3699:                                                 $context);
 3700:                 if ($changed->{$tool}) {
 3701:                     $newaccess->{$tool} = &mt('custom');
 3702:                     if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 3703:                         if ($newval =~ /^autolimit/) {
 3704:                             if ($limit) {
 3705:                                 $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3706:                             } else {
 3707:                                 $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3708:                             }
 3709:                         } elsif ($newval) {
 3710:                             $newaccesstext->{$tool} = $reqdisplay{$newval};
 3711:                         } else {
 3712:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3713:                         }
 3714:                     } else {
 3715:                         if ($newval) {
 3716:                             $newaccesstext->{$tool} = &mt("availability set to 'on'");
 3717:                         } else {
 3718:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3719:                         }
 3720:                     }
 3721:                 } else {
 3722:                     $newaccess->{$tool} = $oldaccess->{$tool};
 3723:                 }
 3724:             } else {
 3725:                 $newaccess->{$tool} = $oldaccess->{$tool};
 3726:             }
 3727:         }
 3728:     }
 3729:     return;
 3730: }
 3731: 
 3732: sub adhocrole_changes {
 3733:     my ($changehashref,$userenv) = @_;
 3734:     my @adds = &Apache::loncommon::get_env_multiple('form.adhocroleadd');
 3735:     my @dels = &Apache::loncommon::get_env_multiple('form.adhocroledel');
 3736:     my (@saved,@added,@alladhoc,$changed);
 3737:     my $adhoc_key = 'adhocroles.'.$env{'request.role.domain'};
 3738:     if (!$env{'form.makeuser'}) {
 3739:         if (ref($userenv) eq 'HASH') {
 3740:             my @current;
 3741:             if ($userenv->{$adhoc_key}) {
 3742:                 @current = split(/,/,$userenv->{$adhoc_key});
 3743:                 if (@dels) {
 3744:                     foreach my $curr (@current) {
 3745:                         next if ($curr eq ''); 
 3746:                         unless (grep(/\Q$curr\E$/,@dels)) {
 3747:                             push(@saved,$curr);
 3748:                         }
 3749:                     }
 3750:                     $changed = 1;
 3751:                 } else {
 3752:                     @saved = @current;
 3753:                 }
 3754:             }
 3755:         }
 3756:     }
 3757:     if (@adds) {
 3758:         my $confname = &Apache::lonnet::get_domainconfiguser($env{'request.role.domain'});
 3759:         my %existing=&Apache::lonnet::dump('roles',$env{'request.role.domain'},
 3760:                                            $confname,'rolesdef_');
 3761:         foreach my $poss (@adds) {
 3762:             if (exists($existing{'rolesdef_'.$poss})) {
 3763:                 push(@added,$poss);
 3764:                 $changed = 1;
 3765:             }
 3766:         }
 3767:     }
 3768:     if (@added) {
 3769:         if (@saved) {
 3770:             foreach my $add (@added) {
 3771:                 unless (grep(/^\Q$add\E$/,@saved)) {
 3772:                     push(@alladhoc,$add);
 3773:                 }
 3774:             }
 3775:         } else {
 3776:             push(@alladhoc,@added);
 3777:         }
 3778:     }
 3779:     if (@saved) {
 3780:         push(@alladhoc,@saved);
 3781:     }
 3782:     if (@alladhoc) {
 3783:         my $adhocstr = join(',',sort(@alladhoc)); 
 3784:         $changehashref->{$adhoc_key} = $adhocstr;
 3785:     } elsif (@dels) {
 3786:         &Apache::lonnet::del('environment',[$adhoc_key],$env{'form.ccdomain'},$env{'form.ccuname'});
 3787:         delete($changehashref->{$adhoc_key});
 3788:         if (($env{'form.ccdomain'} eq $env{'user.domain'}) &&
 3789:             ($env{'form.ccuname'} eq $env{'user.name'})) {
 3790:             &Apache::lonnet::delenv($adhoc_key);
 3791:         }
 3792:     }
 3793:     return $changed;
 3794: }
 3795: 
 3796: sub update_roles {
 3797:     my ($r,$context,$showcredits) = @_;
 3798:     my $now=time;
 3799:     my @rolechanges;
 3800:     my %disallowed;
 3801:     $r->print('<h3>'.&mt('Modifying Roles').'</h3>');
 3802:     foreach my $key (keys(%env)) {
 3803: 	next if (! $env{$key});
 3804:         next if ($key eq 'form.action');
 3805: 	# Revoke roles
 3806: 	if ($key=~/^form\.rev/) {
 3807: 	    if ($key=~/^form\.rev\:([^\_]+)\_([^\_\.]+)$/) {
 3808: # Revoke standard role
 3809: 		my ($scope,$role) = ($1,$2);
 3810: 		my $result =
 3811: 		    &Apache::lonnet::revokerole($env{'form.ccdomain'},
 3812: 						$env{'form.ccuname'},
 3813: 						$scope,$role,'','',$context);
 3814:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
 3815:                             &mt('Revoking [_1] in [_2]',
 3816:                                 &Apache::lonnet::plaintext($role),
 3817:                                 &Apache::loncommon::show_role_extent($scope,$context,$role)),
 3818:                                 $result ne "ok").'<br />');
 3819:                 if ($result ne "ok") {
 3820:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 3821:                 }
 3822: 		if ($role eq 'st') {
 3823: 		    my $result = 
 3824:                         &Apache::lonuserutils::classlist_drop($scope,
 3825:                             $env{'form.ccuname'},$env{'form.ccdomain'},
 3826: 			    $now);
 3827:                     $r->print(&Apache::lonhtmlcommon::confirm_success($result));
 3828: 		}
 3829:                 if (!grep(/^\Q$role\E$/,@rolechanges)) {
 3830:                     push(@rolechanges,$role);
 3831:                 }
 3832: 	    }
 3833: 	    if ($key=~m{^form\.rev\:([^_]+)_cr\.cr/($match_domain)/($match_username)/(\w+)$}s) {
 3834: # Revoke custom role
 3835:                 my $result = &Apache::lonnet::revokecustomrole(
 3836:                     $env{'form.ccdomain'},$env{'form.ccuname'},$1,$2,$3,$4,'','',$context);
 3837:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
 3838:                             &mt('Revoking custom role [_1] by [_2] in [_3]',
 3839:                                 $4,$3.':'.$2,&Apache::loncommon::show_role_extent($1,$context,'cr')),
 3840:                             $result ne 'ok').'<br />');
 3841:                 if ($result ne "ok") {
 3842:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 3843:                 }
 3844:                 if (!grep(/^cr$/,@rolechanges)) {
 3845:                     push(@rolechanges,'cr');
 3846:                 }
 3847: 	    }
 3848: 	} elsif ($key=~/^form\.del/) {
 3849: 	    if ($key=~/^form\.del\:([^\_]+)\_([^\_\.]+)$/) {
 3850: # Delete standard role
 3851: 		my ($scope,$role) = ($1,$2);
 3852: 		my $result =
 3853: 		    &Apache::lonnet::assignrole($env{'form.ccdomain'},
 3854: 						$env{'form.ccuname'},
 3855: 						$scope,$role,$now,0,1,'',
 3856:                                                 $context);
 3857:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
 3858:                             &mt('Deleting [_1] in [_2]',
 3859:                                 &Apache::lonnet::plaintext($role),
 3860:                                 &Apache::loncommon::show_role_extent($scope,$context,$role)),
 3861:                             $result ne 'ok').'<br />');
 3862:                 if ($result ne "ok") {
 3863:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 3864:                 }
 3865: 
 3866: 		if ($role eq 'st') {
 3867: 		    my $result = 
 3868:                         &Apache::lonuserutils::classlist_drop($scope,
 3869:                             $env{'form.ccuname'},$env{'form.ccdomain'},
 3870: 			    $now);
 3871: 		    $r->print(&Apache::lonhtmlcommon::confirm_success($result));
 3872: 		}
 3873:                 if (!grep(/^\Q$role\E$/,@rolechanges)) {
 3874:                     push(@rolechanges,$role);
 3875:                 }
 3876:             }
 3877: 	    if ($key=~m{^form\.del\:([^_]+)_cr\.cr/($match_domain)/($match_username)/(\w+)$}) {
 3878:                 my ($url,$rdom,$rnam,$rolename) = ($1,$2,$3,$4);
 3879: # Delete custom role
 3880:                 my $result =
 3881:                     &Apache::lonnet::assigncustomrole($env{'form.ccdomain'},
 3882:                         $env{'form.ccuname'},$url,$rdom,$rnam,$rolename,$now,
 3883:                         0,1,$context);
 3884:                 $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('Deleting custom role [_1] by [_2] in [_3]',
 3885:                       $rolename,$rnam.':'.$rdom,&Apache::loncommon::show_role_extent($1,$context,'cr')),
 3886:                       $result ne "ok").'<br />');
 3887:                 if ($result ne "ok") {
 3888:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 3889:                 }
 3890: 
 3891:                 if (!grep(/^cr$/,@rolechanges)) {
 3892:                     push(@rolechanges,'cr');
 3893:                 }
 3894:             }
 3895: 	} elsif ($key=~/^form\.ren/) {
 3896:             my $udom = $env{'form.ccdomain'};
 3897:             my $uname = $env{'form.ccuname'};
 3898: # Re-enable standard role
 3899: 	    if ($key=~/^form\.ren\:([^\_]+)\_([^\_\.]+)$/) {
 3900:                 my $url = $1;
 3901:                 my $role = $2;
 3902:                 my $logmsg;
 3903:                 my $output;
 3904:                 if ($role eq 'st') {
 3905:                     if ($url =~ m-^/($match_domain)/($match_courseid)/?(\w*)$-) {
 3906:                         my ($cdom,$cnum,$csec) = ($1,$2,$3);
 3907:                         my $credits;
 3908:                         if ($showcredits) {
 3909:                             my $defaultcredits = 
 3910:                                 &Apache::lonuserutils::get_defaultcredits($cdom,$cnum);
 3911:                             $credits = &get_user_credits($defaultcredits,$cdom,$cnum);
 3912:                         }
 3913:                         my $result = &Apache::loncommon::commit_studentrole(\$logmsg,$udom,$uname,$url,$role,$now,0,$cdom,$cnum,$csec,$context,$credits);
 3914:                         if (($result =~ /^error/) || ($result eq 'not_in_class') || ($result eq 'unknown_course') || ($result eq 'refused')) {
 3915:                             if ($result eq 'refused' && $logmsg) {
 3916:                                 $output = $logmsg;
 3917:                             } else { 
 3918:                                 $output = &mt('Error: [_1]',$result)."\n";
 3919:                             }
 3920:                         } else {
 3921:                             $output = &Apache::lonhtmlcommon::confirm_success(&mt('Assigning [_1] in [_2] starting [_3]',
 3922:                                         &Apache::lonnet::plaintext($role),
 3923:                                         &Apache::loncommon::show_role_extent($url,$context,'st'),
 3924:                                         &Apache::lonlocal::locallocaltime($now))).'<br />'.$logmsg.'<br />';
 3925:                         }
 3926:                     }
 3927:                 } else {
 3928: 		    my $result=&Apache::lonnet::assignrole($env{'form.ccdomain'},
 3929:                                $env{'form.ccuname'},$url,$role,0,$now,'','',
 3930:                                $context);
 3931:                         $output = &Apache::lonhtmlcommon::confirm_success(&mt('Re-enabling [_1] in [_2]',
 3932:                                         &Apache::lonnet::plaintext($role),
 3933:                                         &Apache::loncommon::show_role_extent($url,$context,$role)),$result ne "ok").'<br />';
 3934:                     if ($result ne "ok") {
 3935:                         $output .= &mt('Error: [_1]',$result).'<br />';
 3936:                     }
 3937:                 }
 3938:                 $r->print($output);
 3939:                 if (!grep(/^\Q$role\E$/,@rolechanges)) {
 3940:                     push(@rolechanges,$role);
 3941:                 }
 3942: 	    }
 3943: # Re-enable custom role
 3944: 	    if ($key=~m{^form\.ren\:([^_]+)_cr\.cr/($match_domain)/($match_username)/(\w+)$}) {
 3945:                 my ($url,$rdom,$rnam,$rolename) = ($1,$2,$3,$4);
 3946:                 my $result = &Apache::lonnet::assigncustomrole(
 3947:                                $env{'form.ccdomain'}, $env{'form.ccuname'},
 3948:                                $url,$rdom,$rnam,$rolename,0,$now,undef,$context);
 3949:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
 3950:                     &mt('Re-enabling custom role [_1] by [_2] in [_3]',
 3951:                         $rolename,$rnam.':'.$rdom,&Apache::loncommon::show_role_extent($1,$context,'cr')),
 3952:                     $result ne "ok").'<br />');
 3953:                 if ($result ne "ok") {
 3954:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 3955:                 }
 3956:                 if (!grep(/^cr$/,@rolechanges)) {
 3957:                     push(@rolechanges,'cr');
 3958:                 }
 3959:             }
 3960: 	} elsif ($key=~/^form\.act/) {
 3961:             my $udom = $env{'form.ccdomain'};
 3962:             my $uname = $env{'form.ccuname'};
 3963: 	    if ($key=~/^form\.act\_($match_domain)\_($match_courseid)\_cr_cr_($match_domain)_($match_username)_([^\_]+)$/) {
 3964:                 # Activate a custom role
 3965: 		my ($one,$two,$three,$four,$five)=($1,$2,$3,$4,$5);
 3966: 		my $url='/'.$one.'/'.$two;
 3967: 		my $full=$one.'_'.$two.'_cr_cr_'.$three.'_'.$four.'_'.$five;
 3968: 
 3969:                 my $start = ( $env{'form.start_'.$full} ?
 3970:                               $env{'form.start_'.$full} :
 3971:                               $now );
 3972:                 my $end   = ( $env{'form.end_'.$full} ?
 3973:                               $env{'form.end_'.$full} :
 3974:                               0 );
 3975:                                                                                      
 3976:                 # split multiple sections
 3977:                 my %sections = ();
 3978:                 my $num_sections = &build_roles($env{'form.sec_'.$full},\%sections,$5);
 3979:                 if ($num_sections == 0) {
 3980:                     $r->print(&Apache::loncommon::commit_customrole($udom,$uname,$url,$three,$four,$five,$start,$end,$context));
 3981:                 } else {
 3982: 		    my %curr_groups =
 3983: 			&Apache::longroup::coursegroups($one,$two);
 3984:                     foreach my $sec (sort {$a cmp $b} keys(%sections)) {
 3985:                         if (($sec eq 'none') || ($sec eq 'all') || 
 3986:                             exists($curr_groups{$sec})) {
 3987:                             $disallowed{$sec} = $url;
 3988:                             next;
 3989:                         }
 3990:                         my $securl = $url.'/'.$sec;
 3991: 		        $r->print(&Apache::loncommon::commit_customrole($udom,$uname,$securl,$three,$four,$five,$start,$end,$context));
 3992:                     }
 3993:                 }
 3994:                 if (!grep(/^cr$/,@rolechanges)) {
 3995:                     push(@rolechanges,'cr');
 3996:                 }
 3997: 	    } elsif ($key=~/^form\.act\_($match_domain)\_($match_name)\_([^\_]+)$/) {
 3998: 		# Activate roles for sections with 3 id numbers
 3999: 		# set start, end times, and the url for the class
 4000: 		my ($one,$two,$three)=($1,$2,$3);
 4001: 		my $start = ( $env{'form.start_'.$one.'_'.$two.'_'.$three} ? 
 4002: 			      $env{'form.start_'.$one.'_'.$two.'_'.$three} : 
 4003: 			      $now );
 4004: 		my $end   = ( $env{'form.end_'.$one.'_'.$two.'_'.$three} ? 
 4005: 			      $env{'form.end_'.$one.'_'.$two.'_'.$three} :
 4006: 			      0 );
 4007: 		my $url='/'.$one.'/'.$two;
 4008:                 my $type = 'three';
 4009:                 # split multiple sections
 4010:                 my %sections = ();
 4011:                 my $num_sections = &build_roles($env{'form.sec_'.$one.'_'.$two.'_'.$three},\%sections,$three);
 4012:                 my $credits;
 4013:                 if ($three eq 'st') {
 4014:                     if ($showcredits) { 
 4015:                         my $defaultcredits = 
 4016:                             &Apache::lonuserutils::get_defaultcredits($one,$two);
 4017:                         $credits = $env{'form.credits_'.$one.'_'.$two.'_'.$three};
 4018:                         $credits =~ s/[^\d\.]//g;
 4019:                         if ($credits eq $defaultcredits) {
 4020:                             undef($credits);
 4021:                         }
 4022:                     }
 4023:                 }
 4024:                 if ($num_sections == 0) {
 4025:                     $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$three,$start,$end,$one,$two,'',$context,$credits));
 4026:                 } else {
 4027:                     my %curr_groups = 
 4028: 			&Apache::longroup::coursegroups($one,$two);
 4029:                     my $emptysec = 0;
 4030:                     foreach my $sec (sort {$a cmp $b} keys(%sections)) {
 4031:                         $sec =~ s/\W//g;
 4032:                         if ($sec ne '') {
 4033:                             if (($sec eq 'none') || ($sec eq 'all') || 
 4034:                                 exists($curr_groups{$sec})) {
 4035:                                 $disallowed{$sec} = $url;
 4036:                                 next;
 4037:                             }
 4038:                             my $securl = $url.'/'.$sec;
 4039:                             $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$securl,$three,$start,$end,$one,$two,$sec,$context,$credits));
 4040:                         } else {
 4041:                             $emptysec = 1;
 4042:                         }
 4043:                     }
 4044:                     if ($emptysec) {
 4045:                         $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$three,$start,$end,$one,$two,'',$context,$credits));
 4046:                     }
 4047:                 }
 4048:                 if (!grep(/^\Q$three\E$/,@rolechanges)) {
 4049:                     push(@rolechanges,$three);
 4050:                 }
 4051: 	    } elsif ($key=~/^form\.act\_([^\_]+)\_([^\_]+)$/) {
 4052: 		# Activate roles for sections with two id numbers
 4053: 		# set start, end times, and the url for the class
 4054: 		my $start = ( $env{'form.start_'.$1.'_'.$2} ? 
 4055: 			      $env{'form.start_'.$1.'_'.$2} : 
 4056: 			      $now );
 4057: 		my $end   = ( $env{'form.end_'.$1.'_'.$2} ? 
 4058: 			      $env{'form.end_'.$1.'_'.$2} :
 4059: 			      0 );
 4060:                 my $one = $1;
 4061:                 my $two = $2;
 4062: 		my $url='/'.$one.'/';
 4063:                 # split multiple sections
 4064:                 my %sections = ();
 4065:                 my $num_sections = &build_roles($env{'form.sec_'.$one.'_'.$two},\%sections,$two);
 4066:                 if ($num_sections == 0) {
 4067:                     $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$two,$start,$end,$one,undef,'',$context));
 4068:                 } else {
 4069:                     my $emptysec = 0;
 4070:                     foreach my $sec (sort {$a cmp $b} keys(%sections)) {
 4071:                         if ($sec ne '') {
 4072:                             my $securl = $url.'/'.$sec;
 4073:                             $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$securl,$two,$start,$end,$one,undef,$sec,$context));
 4074:                         } else {
 4075:                             $emptysec = 1;
 4076:                         }
 4077:                     }
 4078:                     if ($emptysec) {
 4079:                         $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$two,$start,$end,$one,undef,'',$context));
 4080:                     }
 4081:                 }
 4082:                 if (!grep(/^\Q$two\E$/,@rolechanges)) {
 4083:                     push(@rolechanges,$two);
 4084:                 }
 4085: 	    } else {
 4086: 		$r->print('<p><span class="LC_error">'.&mt('ERROR').': '.&mt('Unknown command').' <tt>'.$key.'</tt></span></p><br />');
 4087:             }
 4088:             foreach my $key (sort(keys(%disallowed))) {
 4089:                 $r->print('<p class="LC_warning">');
 4090:                 if (($key eq 'none') || ($key eq 'all')) {  
 4091:                     $r->print(&mt('[_1] may not be used as the name for a section, as it is a reserved word.','<tt>'.$key.'</tt>'));
 4092:                 } else {
 4093:                     $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>'));
 4094:                 }
 4095:                 $r->print('</p><p>'
 4096:                          .&mt('Please [_1]go back[_2] and choose a different section name.'
 4097:                              ,'<a href="javascript:history.go(-1)'
 4098:                              ,'</a>')
 4099:                          .'</p><br />'
 4100:                 );
 4101:             }
 4102: 	}
 4103:     } # End of foreach (keys(%env))
 4104: # Flush the course logs so reverse user roles immediately updated
 4105:     $r->register_cleanup(\&Apache::lonnet::flushcourselogs);
 4106:     if (@rolechanges == 0) {
 4107:         $r->print('<p>'.&mt('No roles to modify').'</p>');
 4108:     }
 4109:     return @rolechanges;
 4110: }
 4111: 
 4112: sub get_user_credits {
 4113:     my ($uname,$udom,$defaultcredits,$cdom,$cnum) = @_;
 4114:     if ($cdom eq '' || $cnum eq '') {
 4115:         return unless ($env{'request.course.id'});
 4116:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4117:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4118:     }
 4119:     my $credits;
 4120:     my %currhash =
 4121:         &Apache::lonnet::get('classlist',[$uname.':'.$udom],$cdom,$cnum);
 4122:     if (keys(%currhash) > 0) {
 4123:         my @items = split(/:/,$currhash{$uname.':'.$udom});
 4124:         my $crdidx = &Apache::loncoursedata::CL_CREDITS() - 3;
 4125:         $credits = $items[$crdidx];
 4126:         $credits =~ s/[^\d\.]//g;
 4127:     }
 4128:     if ($credits eq $defaultcredits) {
 4129:         undef($credits);
 4130:     }
 4131:     return $credits;
 4132: }
 4133: 
 4134: sub enroll_single_student {
 4135:     my ($r,$uhome,$amode,$genpwd,$now,$newuser,$context,$crstype,
 4136:         $showcredits,$defaultcredits) = @_;
 4137:     $r->print('<h3>');
 4138:     if ($crstype eq 'Community') {
 4139:         $r->print(&mt('Enrolling Member'));
 4140:     } else {
 4141:         $r->print(&mt('Enrolling Student'));
 4142:     }
 4143:     $r->print('</h3>');
 4144: 
 4145:     # Remove non alphanumeric values from section
 4146:     $env{'form.sections'}=~s/\W//g;
 4147: 
 4148:     my $credits;
 4149:     if (($showcredits) && ($env{'form.credits'} ne '')) {
 4150:         $credits = $env{'form.credits'};
 4151:         $credits =~ s/[^\d\.]//g;
 4152:         if ($credits ne '') {
 4153:             if ($credits eq $defaultcredits) {
 4154:                 undef($credits);
 4155:             }
 4156:         }
 4157:     }
 4158: 
 4159:     # Clean out any old student roles the user has in this class.
 4160:     &Apache::lonuserutils::modifystudent($env{'form.ccdomain'},
 4161:          $env{'form.ccuname'},$env{'request.course.id'},undef,$uhome);
 4162:     my ($startdate,$enddate) = &Apache::lonuserutils::get_dates_from_form();
 4163:     my $enroll_result =
 4164:         &Apache::lonnet::modify_student_enrollment($env{'form.ccdomain'},
 4165:             $env{'form.ccuname'},$env{'form.cid'},$env{'form.cfirstname'},
 4166:             $env{'form.cmiddlename'},$env{'form.clastname'},
 4167:             $env{'form.generation'},$env{'form.sections'},$enddate,
 4168:             $startdate,'manual',undef,$env{'request.course.id'},'',$context,
 4169:             $credits);
 4170:     if ($enroll_result =~ /^ok/) {
 4171:         $r->print(&mt('[_1] enrolled','<b>'.$env{'form.ccuname'}.':'.$env{'form.ccdomain'}.'</b>'));
 4172:         if ($env{'form.sections'} ne '') {
 4173:             $r->print(' '.&mt('in section [_1]',$env{'form.sections'}));
 4174:         }
 4175:         my ($showstart,$showend);
 4176:         if ($startdate <= $now) {
 4177:             $showstart = &mt('Access starts immediately');
 4178:         } else {
 4179:             $showstart = &mt('Access starts: ').&Apache::lonlocal::locallocaltime($startdate);
 4180:         }
 4181:         if ($enddate == 0) {
 4182:             $showend = &mt('ends: no ending date');
 4183:         } else {
 4184:             $showend = &mt('ends: ').&Apache::lonlocal::locallocaltime($enddate);
 4185:         }
 4186:         $r->print('.<br />'.$showstart.'; '.$showend);
 4187:         if ($startdate <= $now && !$newuser) {
 4188:             $r->print('<p class="LC_info">');
 4189:             if ($crstype eq 'Community') {
 4190:                 $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.'));
 4191:             } else {
 4192:                 $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.'));
 4193:            }
 4194:            $r->print('</p>');
 4195:         }
 4196:     } else {
 4197:         $r->print(&mt('unable to enroll').": ".$enroll_result);
 4198:     }
 4199:     return;
 4200: }
 4201: 
 4202: sub get_defaultquota_text {
 4203:     my ($settingstatus) = @_;
 4204:     my $defquotatext; 
 4205:     if ($settingstatus eq '') {
 4206:         $defquotatext = &mt('default');
 4207:     } else {
 4208:         my ($usertypes,$order) =
 4209:             &Apache::lonnet::retrieve_inst_usertypes($env{'form.ccdomain'});
 4210:         if ($usertypes->{$settingstatus} eq '') {
 4211:             $defquotatext = &mt('default');
 4212:         } else {
 4213:             $defquotatext = &mt('default for [_1]',$usertypes->{$settingstatus});
 4214:         }
 4215:     }
 4216:     return $defquotatext;
 4217: }
 4218: 
 4219: sub update_result_form {
 4220:     my ($uhome) = @_;
 4221:     my $outcome = 
 4222:     '<form name="userupdate" method="post" action="">'."\n";
 4223:     foreach my $item ('srchby','srchin','srchtype','srchterm','srchdomain','ccuname','ccdomain') {
 4224:         $outcome .= '<input type="hidden" name="'.$item.'" value="'.$env{'form.'.$item}.'" />'."\n";
 4225:     }
 4226:     if ($env{'form.origname'} ne '') {
 4227:         $outcome .= '<input type="hidden" name="origname" value="'.$env{'form.origname'}.'" />'."\n";
 4228:     }
 4229:     foreach my $item ('sortby','seluname','seludom') {
 4230:         if (exists($env{'form.'.$item})) {
 4231:             $outcome .= '<input type="hidden" name="'.$item.'" value="'.$env{'form.'.$item}.'" />'."\n";
 4232:         }
 4233:     }
 4234:     if ($uhome eq 'no_host') {
 4235:         $outcome .= '<input type="hidden" name="forcenewuser" value="1" />'."\n";
 4236:     }
 4237:     $outcome .= '<input type="hidden" name="phase" value="" />'."\n".
 4238:                 '<input type="hidden" name="currstate" value="" />'."\n".
 4239:                 '<input type="hidden" name="action" value="'.$env{'form.action'}.'" />'."\n".
 4240:                 '</form>';
 4241:     return $outcome;
 4242: }
 4243: 
 4244: sub quota_admin {
 4245:     my ($setquota,$changeHash,$name) = @_;
 4246:     my $quotachanged;
 4247:     if (&Apache::lonnet::allowed('mpq',$env{'form.ccdomain'})) {
 4248:         # Current user has quota modification privileges
 4249:         if (ref($changeHash) eq 'HASH') {
 4250:             $quotachanged = 1;
 4251:             $changeHash->{$name.'quota'} = $setquota;
 4252:         }
 4253:     }
 4254:     return $quotachanged;
 4255: }
 4256: 
 4257: sub tool_admin {
 4258:     my ($tool,$settool,$changeHash,$context) = @_;
 4259:     my $canchange = 0; 
 4260:     if ($context eq 'requestcourses') {
 4261:         if (&Apache::lonnet::allowed('ccc',$env{'form.ccdomain'})) {
 4262:             $canchange = 1;
 4263:         }
 4264:     } elsif ($context eq 'reqcrsotherdom') {
 4265:         if (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) {
 4266:             $canchange = 1;
 4267:         }
 4268:     } elsif ($context eq 'requestauthor') {
 4269:         if (&Apache::lonnet::allowed('cau',$env{'request.role.domain'})) {
 4270:             $canchange = 1;
 4271:         }
 4272:     } elsif (&Apache::lonnet::allowed('mut',$env{'form.ccdomain'})) {
 4273:         # Current user has quota modification privileges
 4274:         $canchange = 1;
 4275:     }
 4276:     my $toolchanged;
 4277:     if ($canchange) {
 4278:         if (ref($changeHash) eq 'HASH') {
 4279:             $toolchanged = 1;
 4280:             if ($tool eq 'requestauthor') {
 4281:                 $changeHash->{$context} = $settool;
 4282:             } else {
 4283:                 $changeHash->{$context.'.'.$tool} = $settool;
 4284:             }
 4285:         }
 4286:     }
 4287:     return $toolchanged;
 4288: }
 4289: 
 4290: sub build_roles {
 4291:     my ($sectionstr,$sections,$role) = @_;
 4292:     my $num_sections = 0;
 4293:     if ($sectionstr=~ /,/) {
 4294:         my @secnums = split/,/,$sectionstr;
 4295:         if ($role eq 'st') {
 4296:             $secnums[0] =~ s/\W//g;
 4297:             $$sections{$secnums[0]} = 1;
 4298:             $num_sections = 1;
 4299:         } else {
 4300:             foreach my $sec (@secnums) {
 4301:                 $sec =~ ~s/\W//g;
 4302:                 if (!($sec eq "")) {
 4303:                     if (exists($$sections{$sec})) {
 4304:                         $$sections{$sec} ++;
 4305:                     } else {
 4306:                         $$sections{$sec} = 1;
 4307:                         $num_sections ++;
 4308:                     }
 4309:                 }
 4310:             }
 4311:         }
 4312:     } else {
 4313:         $sectionstr=~s/\W//g;
 4314:         unless ($sectionstr eq '') {
 4315:             $$sections{$sectionstr} = 1;
 4316:             $num_sections ++;
 4317:         }
 4318:     }
 4319: 
 4320:     return $num_sections;
 4321: }
 4322: 
 4323: # ========================================================== Custom Role Editor
 4324: 
 4325: sub custom_role_editor {
 4326:     my ($r,$brcrum,$prefix) = @_;
 4327:     my $action = $env{'form.customroleaction'};
 4328:     my $rolename; 
 4329:     if ($action eq 'new') {
 4330:         $rolename=$env{'form.newrolename'};
 4331:     } else {
 4332:         $rolename=$env{'form.rolename'};
 4333:     }
 4334: 
 4335:     my ($crstype,$context);
 4336:     if ($env{'request.course.id'}) {
 4337:         $crstype = &Apache::loncommon::course_type();
 4338:         $context = 'course';
 4339:     } else {
 4340:         $context = 'domain';
 4341:         $crstype = 'course';
 4342:     }
 4343: 
 4344:     $rolename=~s/[^A-Za-z0-9]//gs;
 4345:     if (!$rolename || $env{'form.phase'} eq 'pickrole') {
 4346: 	&print_username_entry_form($r,undef,undef,undef,undef,$crstype,$brcrum);
 4347:         return;
 4348:     }
 4349: 
 4350:     my $formname = 'form1';
 4351:     my %privs=();
 4352:     my $body_top = '<h2>';
 4353: # ------------------------------------------------------- Does this role exist?
 4354:     my ($rdummy,$roledef)=
 4355: 			 &Apache::lonnet::get('roles',["rolesdef_$rolename"]);
 4356:     if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 4357:         $body_top .= &mt('Existing Role').' "';
 4358: # ------------------------------------------------- Get current role privileges
 4359:         ($privs{'system'},$privs{'domain'},$privs{'course'})=split(/\_/,$roledef);
 4360:         if ($privs{'system'} =~ /bre\&S/) {
 4361:             if ($context eq 'domain') {
 4362:                 $crstype = 'Course'; 
 4363:             } elsif ($crstype eq 'Community') {
 4364:                 $privs{'system'} =~ s/bre\&S//;
 4365:             }
 4366:         } elsif ($context eq 'domain') {
 4367:             $crstype = 'Course';
 4368:         }
 4369:     } else {
 4370:         $body_top .= &mt('New Role').' "';
 4371:         $roledef='';
 4372:     }
 4373:     $body_top .= $rolename.'"</h2>';
 4374: 
 4375: # ------------------------------------------------------- What can be assigned?
 4376:     my %full=();
 4377:     my %levels=( 
 4378:                  course => {},
 4379:                  domain => {},
 4380:                  system => {},
 4381:                );
 4382:     my %levelscurrent=(
 4383:                         course => {},
 4384:                         domain => {},
 4385:                         system => {},
 4386:                       );
 4387:     &Apache::lonuserutils::custom_role_privs(\%privs,\%full,\%levels,\%levelscurrent);
 4388:     my ($jsback,$elements) = &crumb_utilities();
 4389:     my @templateroles = &Apache::lonuserutils::custom_template_roles($context,$crstype);
 4390:     my $head_script = 
 4391:         &Apache::lonuserutils::custom_roledefs_js($context,$crstype,$formname,
 4392:                                                   \%full,\@templateroles,$jsback);
 4393:     push (@{$brcrum},
 4394:               {href => "javascript:backPage(document.$formname,'pickrole','')",
 4395:                text => "Pick custom role",
 4396:                faq  => 282,bug=>'Instructor Interface',},
 4397:               {href => "javascript:backPage(document.$formname,'','')",
 4398:                text => "Edit custom role",
 4399:                faq  => 282,
 4400:                bug  => 'Instructor Interface',
 4401:                help => 'Course_Editing_Custom_Roles'}
 4402:               );
 4403:     my $args = { bread_crumbs          => $brcrum,
 4404:                  bread_crumbs_component => 'User Management'};
 4405:  
 4406:     $r->print(&Apache::loncommon::start_page('Custom Role Editor',
 4407:                                              $head_script,$args).
 4408:               $body_top);
 4409:     $r->print('<form name="'.$formname.'" method="post" action="">'."\n".
 4410:               &Apache::lonuserutils::custom_role_header($context,$crstype,
 4411:                                                         \@templateroles,$prefix));
 4412: 
 4413:     $r->print(<<ENDCCF);
 4414: <input type="hidden" name="phase" value="set_custom_roles" />
 4415: <input type="hidden" name="rolename" value="$rolename" />
 4416: ENDCCF
 4417:     $r->print(&Apache::lonuserutils::custom_role_table($crstype,\%full,\%levels,
 4418:                                                        \%levelscurrent,$prefix));
 4419:     $r->print(&Apache::loncommon::end_data_table().
 4420:    '<input type="hidden" name="action" value="'.$env{'form.action'}.'" />'.
 4421:    '<input type="hidden" name="startrolename" value="'.$env{'form.rolename'}.
 4422:    '" />'."\n".'<input type="hidden" name="currstate" value="" />'."\n".   
 4423:    '<input type="reset" value="'.&mt("Reset").'" />'."\n".
 4424:    '<input type="submit" value="'.&mt('Save').'" /></form>');
 4425: }
 4426: 
 4427: # ---------------------------------------------------------- Call to definerole
 4428: sub set_custom_role {
 4429:     my ($r,$context,$brcrum,$prefix) = @_;
 4430:     my $rolename=$env{'form.rolename'};
 4431:     $rolename=~s/[^A-Za-z0-9]//gs;
 4432:     if (!$rolename) {
 4433: 	&custom_role_editor($r,$brcrum,$prefix);
 4434:         return;
 4435:     }
 4436:     my ($jsback,$elements) = &crumb_utilities();
 4437:     my $jscript = '<script type="text/javascript">'
 4438:                  .'// <![CDATA['."\n"
 4439:                  .$jsback."\n"
 4440:                  .'// ]]>'."\n"
 4441:                  .'</script>'."\n";
 4442:     push(@{$brcrum},
 4443:         {href => "javascript:backPage(document.customresult,'pickrole','')",
 4444:          text => "Pick custom role",
 4445:          faq  => 282,
 4446:          bug  => 'Instructor Interface',},
 4447:         {href => "javascript:backPage(document.customresult,'selected_custom_edit','')",
 4448:          text => "Edit custom role",
 4449:          faq  => 282,
 4450:          bug  => 'Instructor Interface',},
 4451:         {href => "javascript:backPage(document.customresult,'set_custom_roles','')",
 4452:          text => "Result",
 4453:          faq  => 282,
 4454:          bug  => 'Instructor Interface',
 4455:          help => 'Course_Editing_Custom_Roles'},
 4456:         );
 4457:     my $args = { bread_crumbs           => $brcrum,
 4458:                  bread_crumbs_component => 'User Management'};
 4459:     $r->print(&Apache::loncommon::start_page('Save Custom Role',$jscript,$args));
 4460: 
 4461:     my $newrole;
 4462:     my ($rdummy,$roledef)=
 4463: 	&Apache::lonnet::get('roles',["rolesdef_$rolename"]);
 4464: 
 4465: # ------------------------------------------------------- Does this role exist?
 4466:     $r->print('<h3>');
 4467:     if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 4468: 	$r->print(&mt('Existing Role').' "');
 4469:     } else {
 4470: 	$r->print(&mt('New Role').' "');
 4471: 	$roledef='';
 4472:         $newrole = 1;
 4473:     }
 4474:     $r->print($rolename.'"</h3>');
 4475: # ------------------------------------------------- Assign role and show result
 4476: 
 4477:     my $errmsg;
 4478:     my %newprivs = &Apache::lonuserutils::custom_role_update($rolename,$prefix);
 4479:     # Assign role and return result
 4480:     my $result = &Apache::lonnet::definerole($rolename,$newprivs{'s'},$newprivs{'d'},
 4481:                                              $newprivs{'c'});
 4482:     if ($result ne 'ok') {
 4483:         $errmsg = ': '.$result;
 4484:     }
 4485:     my $message =
 4486:         &Apache::lonhtmlcommon::confirm_success(
 4487:             &mt('Defining Role').$errmsg, ($result eq 'ok' ? 0 : 1));
 4488:     if ($env{'request.course.id'}) {
 4489:         my $url='/'.$env{'request.course.id'};
 4490:         $url=~s/\_/\//g;
 4491:         $result =
 4492:             &Apache::lonnet::assigncustomrole(
 4493:                 $env{'user.domain'},$env{'user.name'},
 4494:                 $url,
 4495:                 $env{'user.domain'},$env{'user.name'},
 4496:                 $rolename,undef,undef,undef,$context);
 4497:         if ($result ne 'ok') {
 4498:             $errmsg = ': '.$result;
 4499:         }
 4500:         $message .=
 4501:             '<br />'
 4502:            .&Apache::lonhtmlcommon::confirm_success(
 4503:                 &mt('Assigning Role to Self').$errmsg, ($result eq 'ok' ? 0 : 1));
 4504:     }
 4505:     $r->print(
 4506:         &Apache::loncommon::confirmwrapper($message)
 4507:        .'<br />'
 4508:        .&Apache::lonhtmlcommon::actionbox([
 4509:             '<a href="javascript:backPage(document.customresult,'."'pickrole'".')">'
 4510:            .&mt('Create or edit another custom role')
 4511:            .'</a>'])
 4512:        .'<form name="customresult" method="post" action="">'
 4513:        .&Apache::lonhtmlcommon::echo_form_input([])
 4514:        .'</form>'
 4515:     );
 4516: }
 4517: 
 4518: # ================================================================ Main Handler
 4519: sub handler {
 4520:     my $r = shift;
 4521:     if ($r->header_only) {
 4522:        &Apache::loncommon::content_type($r,'text/html');
 4523:        $r->send_http_header;
 4524:        return OK;
 4525:     }
 4526:     my ($context,$crstype);
 4527:     if ($env{'request.course.id'}) {
 4528:         $context = 'course';
 4529:         $crstype = &Apache::loncommon::course_type();
 4530:     } elsif ($env{'request.role'} =~ /^au\./) {
 4531:         $context = 'author';
 4532:     } else {
 4533:         $context = 'domain';
 4534:     }
 4535: 
 4536:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 4537:         ['action','state','callingform','roletype','showrole','bulkaction','popup','phase',
 4538:          'username','domain','srchterm','srchdomain','srchin','srchby','srchtype','queue']);
 4539:     &Apache::lonhtmlcommon::clear_breadcrumbs();
 4540:     my $args;
 4541:     my $brcrum = [];
 4542:     my $bread_crumbs_component = 'User Management';
 4543:     if (($env{'form.action'} ne 'dateselect') && ($env{'form.action'} ne 'displayuserreq')) {
 4544:         $brcrum = [{href=>"/adm/createuser",
 4545:                     text=>"User Management",
 4546:                     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'}
 4547:                   ];
 4548:     }
 4549:     #SD Following files not added to help, because the corresponding .tex-files seem to
 4550:     #be missing: Course_Approve_Selfenroll,Course_User_Logs,
 4551:     my ($permission,$allowed) = 
 4552:         &Apache::lonuserutils::get_permission($context,$crstype);
 4553:     if (!$allowed) {
 4554:         if ($context eq 'course') {
 4555:             $r->internal_redirect('/adm/viewclasslist');
 4556:             return OK;
 4557:         }
 4558:         $env{'user.error.msg'}=
 4559:             "/adm/createuser:cst:0:0:Cannot create/modify user data ".
 4560:                                  "or view user status.";
 4561:         return HTTP_NOT_ACCEPTABLE;
 4562:     }
 4563: 
 4564:     &Apache::loncommon::content_type($r,'text/html');
 4565:     $r->send_http_header;
 4566: 
 4567:     my $showcredits;
 4568:     if ((($context eq 'course') && ($crstype eq 'Course')) || 
 4569:          ($context eq 'domain')) {
 4570:         my %domdefaults = 
 4571:             &Apache::lonnet::get_domain_defaults($env{'request.role.domain'});
 4572:         if ($domdefaults{'officialcredits'} || $domdefaults{'unofficialcredits'}) {
 4573:             $showcredits = 1;
 4574:         }
 4575:     }
 4576: 
 4577:     # Main switch on form.action and form.state, as appropriate
 4578:     if (! exists($env{'form.action'})) {
 4579:         $args = {bread_crumbs => $brcrum,
 4580:                  bread_crumbs_component => $bread_crumbs_component}; 
 4581:         $r->print(&header(undef,$args));
 4582:         $r->print(&print_main_menu($permission,$context,$crstype));
 4583:     } elsif ($env{'form.action'} eq 'upload' && $permission->{'cusr'}) {
 4584:         push(@{$brcrum},
 4585:               { href => '/adm/createuser?action=upload&state=',
 4586:                 text => 'Upload Users List',
 4587:                 help => 'Course_Create_Class_List',
 4588:               });
 4589:         $bread_crumbs_component = 'Upload Users List';
 4590:         $args = {bread_crumbs           => $brcrum,
 4591:                  bread_crumbs_component => $bread_crumbs_component};
 4592:         $r->print(&header(undef,$args));
 4593:         $r->print('<form name="studentform" method="post" '.
 4594:                   'enctype="multipart/form-data" '.
 4595:                   ' action="/adm/createuser">'."\n");
 4596:         if (! exists($env{'form.state'})) {
 4597:             &Apache::lonuserutils::print_first_users_upload_form($r,$context);
 4598:         } elsif ($env{'form.state'} eq 'got_file') {
 4599:             &Apache::lonuserutils::print_upload_manager_form($r,$context,$permission,
 4600:                                                              $crstype,$showcredits);
 4601:         } elsif ($env{'form.state'} eq 'enrolling') {
 4602:             if ($env{'form.datatoken'}) {
 4603:                 &Apache::lonuserutils::upfile_drop_add($r,$context,$permission,
 4604:                                                        $showcredits);
 4605:             }
 4606:         } else {
 4607:             &Apache::lonuserutils::print_first_users_upload_form($r,$context);
 4608:         }
 4609:     } elsif ((($env{'form.action'} eq 'singleuser') || ($env{'form.action'}
 4610:              eq 'singlestudent')) && ($permission->{'cusr'})) {
 4611:         my $phase = $env{'form.phase'};
 4612:         my @search = ('srchterm','srchby','srchin','srchtype','srchdomain');
 4613: 	&Apache::loncreateuser::restore_prev_selections();
 4614: 	my $srch;
 4615: 	foreach my $item (@search) {
 4616: 	    $srch->{$item} = $env{'form.'.$item};
 4617: 	}
 4618:         if (($phase eq 'get_user_info') || ($phase eq 'userpicked') ||
 4619:             ($phase eq 'createnewuser')) {
 4620:             if ($env{'form.phase'} eq 'createnewuser') {
 4621:                 my $response;
 4622:                 if ($env{'form.srchterm'} !~ /^$match_username$/) {
 4623:                     my $response =
 4624:                         '<span class="LC_warning">'
 4625:                        .&mt('You must specify a valid username. Only the following are allowed:'
 4626:                            .' letters numbers - . @')
 4627:                        .'</span>';
 4628:                     $env{'form.phase'} = '';
 4629:                     &print_username_entry_form($r,$context,$response,$srch,undef,
 4630:                                                $crstype,$brcrum,$showcredits);
 4631:                 } else {
 4632:                     my $ccuname =&LONCAPA::clean_username($srch->{'srchterm'});
 4633:                     my $ccdomain=&LONCAPA::clean_domain($srch->{'srchdomain'});
 4634:                     &print_user_modification_page($r,$ccuname,$ccdomain,
 4635:                                                   $srch,$response,$context,
 4636:                                                   $permission,$crstype,$brcrum,
 4637:                                                   $showcredits);
 4638:                 }
 4639:             } elsif ($env{'form.phase'} eq 'get_user_info') {
 4640:                 my ($currstate,$response,$forcenewuser,$results) = 
 4641:                     &user_search_result($context,$srch);
 4642:                 if ($env{'form.currstate'} eq 'modify') {
 4643:                     $currstate = $env{'form.currstate'};
 4644:                 }
 4645:                 if ($currstate eq 'select') {
 4646:                     &print_user_selection_page($r,$response,$srch,$results,
 4647:                                                \@search,$context,undef,$crstype,
 4648:                                                $brcrum);
 4649:                 } elsif ($currstate eq 'modify') {
 4650:                     my ($ccuname,$ccdomain);
 4651:                     if (($srch->{'srchby'} eq 'uname') && 
 4652:                         ($srch->{'srchtype'} eq 'exact')) {
 4653:                         $ccuname = $srch->{'srchterm'};
 4654:                         $ccdomain= $srch->{'srchdomain'};
 4655:                     } else {
 4656:                         my @matchedunames = keys(%{$results});
 4657:                         ($ccuname,$ccdomain) = split(/:/,$matchedunames[0]);
 4658:                     }
 4659:                     $ccuname =&LONCAPA::clean_username($ccuname);
 4660:                     $ccdomain=&LONCAPA::clean_domain($ccdomain);
 4661:                     if ($env{'form.forcenewuser'}) {
 4662:                         $response = '';
 4663:                     }
 4664:                     &print_user_modification_page($r,$ccuname,$ccdomain,
 4665:                                                   $srch,$response,$context,
 4666:                                                   $permission,$crstype,$brcrum);
 4667:                 } elsif ($currstate eq 'query') {
 4668:                     &print_user_query_page($r,'createuser',$brcrum);
 4669:                 } else {
 4670:                     $env{'form.phase'} = '';
 4671:                     &print_username_entry_form($r,$context,$response,$srch,
 4672:                                                $forcenewuser,$crstype,$brcrum);
 4673:                 }
 4674:             } elsif ($env{'form.phase'} eq 'userpicked') {
 4675:                 my $ccuname = &LONCAPA::clean_username($env{'form.seluname'});
 4676:                 my $ccdomain = &LONCAPA::clean_domain($env{'form.seludom'});
 4677:                 &print_user_modification_page($r,$ccuname,$ccdomain,$srch,'',
 4678:                                               $context,$permission,$crstype,
 4679:                                               $brcrum);
 4680:             }
 4681:         } elsif ($env{'form.phase'} eq 'update_user_data') {
 4682:             &update_user_data($r,$context,$crstype,$brcrum,$showcredits);
 4683:         } else {
 4684:             &print_username_entry_form($r,$context,undef,$srch,undef,$crstype,
 4685:                                        $brcrum);
 4686:         }
 4687:     } elsif ($env{'form.action'} eq 'custom' && $permission->{'custom'}) {
 4688:         my $prefix;
 4689:         if ($env{'form.phase'} eq 'set_custom_roles') {
 4690:             &set_custom_role($r,$context,$brcrum,$prefix);
 4691:         } else {
 4692:             &custom_role_editor($r,$brcrum,$prefix);
 4693:         }
 4694:     } elsif (($env{'form.action'} eq 'processauthorreq') &&
 4695:              ($permission->{'cusr'}) && 
 4696:              (&Apache::lonnet::allowed('cau',$env{'request.role.domain'}))) {
 4697:         push(@{$brcrum},
 4698:                  {href => '/adm/createuser?action=processauthorreq',
 4699:                   text => 'Authoring Space requests',
 4700:                   help => 'Domain_Role_Approvals'});
 4701:         $bread_crumbs_component = 'Authoring requests';
 4702:         if ($env{'form.state'} eq 'done') {
 4703:             push(@{$brcrum},
 4704:                      {href => '/adm/createuser?action=authorreqqueue',
 4705:                       text => 'Result',
 4706:                       help => 'Domain_Role_Approvals'});
 4707:             $bread_crumbs_component = 'Authoring request result';
 4708:         }
 4709:         $args = { bread_crumbs           => $brcrum,
 4710:                   bread_crumbs_component => $bread_crumbs_component};
 4711:         my $js = &usernamerequest_javascript();
 4712:         $r->print(&header(&add_script($js),$args));
 4713:         if (!exists($env{'form.state'})) {
 4714:             $r->print(&Apache::loncoursequeueadmin::display_queued_requests('requestauthor',
 4715:                                                                             $env{'request.role.domain'}));
 4716:         } elsif ($env{'form.state'} eq 'done') {
 4717:             $r->print('<h3>'.&mt('Authoring request processing').'</h3>'."\n");
 4718:             $r->print(&Apache::loncoursequeueadmin::update_request_queue('requestauthor',
 4719:                                                                          $env{'request.role.domain'}));
 4720:         }
 4721:     } elsif (($env{'form.action'} eq 'processusernamereq') &&
 4722:              ($permission->{'cusr'}) &&
 4723:              (&Apache::lonnet::allowed('cau',$env{'request.role.domain'}))) {
 4724:         push(@{$brcrum},
 4725:                  {href => '/adm/createuser?action=processusernamereq',
 4726:                   text => 'LON-CAPA account requests',
 4727:                   help => 'Domain_Username_Approvals'});
 4728:         $bread_crumbs_component = 'Account requests';
 4729:         if ($env{'form.state'} eq 'done') {
 4730:             push(@{$brcrum},
 4731:                      {href => '/adm/createuser?action=usernamereqqueue',
 4732:                       text => 'Result',
 4733:                       help => 'Domain_Username_Approvals'});
 4734:             $bread_crumbs_component = 'LON-CAPA account request result';
 4735:         }
 4736:         $args = { bread_crumbs           => $brcrum,
 4737:                   bread_crumbs_component => $bread_crumbs_component};
 4738:         my $js = &usernamerequest_javascript();
 4739:         $r->print(&header(&add_script($js),$args));
 4740:         if (!exists($env{'form.state'})) {
 4741:             $r->print(&Apache::loncoursequeueadmin::display_queued_requests('requestusername',
 4742:                                                                             $env{'request.role.domain'}));
 4743:         } elsif ($env{'form.state'} eq 'done') {
 4744:             $r->print('<h3>'.&mt('LON-CAPA account request processing').'</h3>'."\n");
 4745:             $r->print(&Apache::loncoursequeueadmin::update_request_queue('requestusername',
 4746:                                                                          $env{'request.role.domain'}));
 4747:         }
 4748:     } elsif (($env{'form.action'} eq 'displayuserreq') &&
 4749:              ($permission->{'cusr'})) {
 4750:         my $dom = $env{'form.domain'};
 4751:         my $uname = $env{'form.username'};
 4752:         my $warning;
 4753:         if (($dom =~ /^$match_domain$/) && (&Apache::lonnet::domain($dom) ne '')) {
 4754:             if (($dom eq $env{'request.role.domain'}) && (&Apache::lonnet::allowed('ccc',$dom))) {
 4755:                 if (($uname =~ /^$match_username$/) && ($env{'form.queue'} eq 'approval')) {
 4756:                     my $uhome = &Apache::lonnet::homeserver($uname,$dom);
 4757:                     if ($uhome eq 'no_host') {
 4758:                         my $queue = $env{'form.queue'};
 4759:                         my $reqkey = &escape($uname).'_'.$queue; 
 4760:                         my $namespace = 'usernamequeue';
 4761:                         my $domconfig = &Apache::lonnet::get_domainconfiguser($dom);
 4762:                         my %queued =
 4763:                             &Apache::lonnet::get($namespace,[$reqkey],$dom,$domconfig);
 4764:                         unless ($queued{$reqkey}) {
 4765:                             $warning = &mt('No information was found for this LON-CAPA account request.');
 4766:                         }
 4767:                     } else {
 4768:                         $warning = &mt('A LON-CAPA account already exists for the requested username and domain.');
 4769:                     }
 4770:                 } else {
 4771:                     $warning = &mt('LON-CAPA account request status check is for an invalid username.');
 4772:                 }
 4773:             } else {
 4774:                 $warning = &mt('You do not have rights to view LON-CAPA account requests in the domain specified.');
 4775:             }
 4776:         } else {
 4777:             $warning = &mt('LON-CAPA account request status check is for an invalid domain.');
 4778:         }
 4779:         my $args = { only_body => 1 };
 4780:         $r->print(&header(undef,$args).
 4781:                   '<h3>'.&mt('LON-CAPA Account Request Details').'</h3>');
 4782:         if ($warning ne '') {
 4783:             $r->print('<div class="LC_warning">'.$warning.'</div>');
 4784:         } else {
 4785:             my ($infofields,$infotitles) = &Apache::loncommon::emailusername_info();
 4786:             my $domconfiguser = &Apache::lonnet::get_domainconfiguser($dom);
 4787:             my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 4788:             if (ref($domconfig{'usercreation'}) eq 'HASH') {
 4789:                 if (ref($domconfig{'usercreation'}{'cancreate'}) eq 'HASH') {
 4790:                     if (ref($domconfig{'usercreation'}{'cancreate'}{'emailusername'}) eq 'HASH') {
 4791:                         my %info =
 4792:                             &Apache::lonnet::get('nohist_requestedusernames',[$uname],$dom,$domconfiguser);
 4793:                         if (ref($info{$uname}) eq 'HASH') {
 4794:                             my $usertype = $info{$uname}{'inststatus'};
 4795:                             unless ($usertype) {
 4796:                                 $usertype = 'default';
 4797:                             }
 4798:                             if (ref($domconfig{'usercreation'}{'cancreate'}{'emailusername'}{$usertype}) eq 'HASH') {
 4799:                                 if ((ref($infofields) eq 'ARRAY') && (ref($infotitles) eq 'HASH')) {
 4800:                                     $r->print('<div>'.&Apache::lonhtmlcommon::start_pick_box());
 4801:                                     my ($num,$count,$showstatus);
 4802:                                     $count = scalar(keys(%{$domconfig{'usercreation'}{'cancreate'}{'emailusername'}{$usertype}}));
 4803:                                     unless ($usertype eq 'default') {
 4804:                                         my ($othertitle,$usertypes,$types) = 
 4805:                                             &Apache::loncommon::sorted_inst_types($dom);
 4806:                                         if (ref($usertypes) eq 'HASH') {
 4807:                                             if ($usertypes->{$usertype}) {
 4808:                                                 $showstatus = $usertypes->{$usertype};
 4809:                                                 $count ++;
 4810:                                             }
 4811:                                         }
 4812:                                     }
 4813:                                     foreach my $field (@{$infofields}) {
 4814:                                         next unless ($domconfig{'usercreation'}{'cancreate'}{'emailusername'}{$usertype}{$field});
 4815:                                         next unless ($infotitles->{$field});
 4816:                                         $r->print(&Apache::lonhtmlcommon::row_title($infotitles->{$field}).
 4817:                                                   $info{$uname}{$field});
 4818:                                         $num ++;
 4819:                                         if ($count == $num) {
 4820:                                             $r->print(&Apache::lonhtmlcommon::row_closure(1));
 4821:                                         } else {
 4822:                                             $r->print(&Apache::lonhtmlcommon::row_closure());
 4823:                                         }
 4824:                                     }
 4825:                                     if ($showstatus) {
 4826:                                         $r->print(&Apache::lonhtmlcommon::row_title(&mt('Status type (self-reported)')).
 4827:                                                   $showstatus.
 4828:                                                   &Apache::lonhtmlcommon::row_closure(1));
 4829:                                     }
 4830:                                     $r->print(&Apache::lonhtmlcommon::end_pick_box().'</div>');
 4831:                                 }
 4832:                             }
 4833:                         }
 4834:                     }
 4835:                 }
 4836:             }
 4837:             $r->print(&close_popup_form());
 4838:         }
 4839:     } elsif (($env{'form.action'} eq 'listusers') && 
 4840:              ($permission->{'view'} || $permission->{'cusr'})) {
 4841:         if ($env{'form.phase'} eq 'bulkchange') {
 4842:             push(@{$brcrum},
 4843:                     {href => '/adm/createuser?action=listusers',
 4844:                      text => "List Users"},
 4845:                     {href => "/adm/createuser",
 4846:                      text => "Result",
 4847:                      help => 'Course_View_Class_List'});
 4848:             $bread_crumbs_component = 'Update Users';
 4849:             $args = {bread_crumbs           => $brcrum,
 4850:                      bread_crumbs_component => $bread_crumbs_component};
 4851:             $r->print(&header(undef,$args));
 4852:             my $setting = $env{'form.roletype'};
 4853:             my $choice = $env{'form.bulkaction'};
 4854:             if ($permission->{'cusr'}) {
 4855:                 &Apache::lonuserutils::update_user_list($r,$context,$setting,$choice,$crstype);
 4856:             } else {
 4857:                 $r->print(&mt('You are not authorized to make bulk changes to user roles'));
 4858:                 $r->print('<p><a href="/adm/createuser?action=listusers">'.&mt('Display User Lists').'</a>');
 4859:             }
 4860:         } else {
 4861:             push(@{$brcrum},
 4862:                     {href => '/adm/createuser?action=listusers',
 4863:                      text => "List Users",
 4864:                      help => 'Course_View_Class_List'});
 4865:             $bread_crumbs_component = 'List Users';
 4866:             $args = {bread_crumbs           => $brcrum,
 4867:                      bread_crumbs_component => $bread_crumbs_component};
 4868:             my ($cb_jscript,$jscript,$totcodes,$codetitles,$idlist,$idlist_titles);
 4869:             my $formname = 'studentform';
 4870:             my $hidecall = "hide_searching();";
 4871:             if (($context eq 'domain') && (($env{'form.roletype'} eq 'course') ||
 4872:                 ($env{'form.roletype'} eq 'community'))) {
 4873:                 if ($env{'form.roletype'} eq 'course') {
 4874:                     ($cb_jscript,$jscript,$totcodes,$codetitles,$idlist,$idlist_titles) = 
 4875:                         &Apache::lonuserutils::courses_selector($env{'request.role.domain'},
 4876:                                                                 $formname);
 4877:                 } elsif ($env{'form.roletype'} eq 'community') {
 4878:                     $cb_jscript = 
 4879:                         &Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'});
 4880:                     my %elements = (
 4881:                                       coursepick => 'radio',
 4882:                                       coursetotal => 'text',
 4883:                                       courselist => 'text',
 4884:                                    );
 4885:                     $jscript = &Apache::lonhtmlcommon::set_form_elements(\%elements);
 4886:                 }
 4887:                 $jscript .= &verify_user_display($context)."\n".
 4888:                             &Apache::loncommon::check_uncheck_jscript();
 4889:                 my $js = &add_script($jscript).$cb_jscript;
 4890:                 my $loadcode = 
 4891:                     &Apache::lonuserutils::course_selector_loadcode($formname);
 4892:                 if ($loadcode ne '') {
 4893:                     $args->{add_entries} = {onload => "$loadcode;$hidecall"};
 4894:                 } else {
 4895:                     $args->{add_entries} = {onload => $hidecall};
 4896:                 }
 4897:                 $r->print(&header($js,$args));
 4898:             } else {
 4899:                 $args->{add_entries} = {onload => $hidecall};
 4900:                 $jscript = &verify_user_display($context).
 4901:                            &Apache::loncommon::check_uncheck_jscript(); 
 4902:                 $r->print(&header(&add_script($jscript),$args));
 4903:             }
 4904:             &Apache::lonuserutils::print_userlist($r,undef,$permission,$context,
 4905:                          $formname,$totcodes,$codetitles,$idlist,$idlist_titles,
 4906:                          $showcredits);
 4907:         }
 4908:     } elsif ($env{'form.action'} eq 'drop' && $permission->{'cusr'}) {
 4909:         my $brtext;
 4910:         if ($crstype eq 'Community') {
 4911:             $brtext = 'Drop Members';
 4912:         } else {
 4913:             $brtext = 'Drop Students';
 4914:         }
 4915:         push(@{$brcrum},
 4916:                 {href => '/adm/createuser?action=drop',
 4917:                  text => $brtext,
 4918:                  help => 'Course_Drop_Student'});
 4919:         if ($env{'form.state'} eq 'done') {
 4920:             push(@{$brcrum},
 4921:                      {href=>'/adm/createuser?action=drop',
 4922:                       text=>"Result"});
 4923:         }
 4924:         $bread_crumbs_component = $brtext;
 4925:         $args = {bread_crumbs           => $brcrum,
 4926:                  bread_crumbs_component => $bread_crumbs_component}; 
 4927:         $r->print(&header(undef,$args));
 4928:         if (!exists($env{'form.state'})) {
 4929:             &Apache::lonuserutils::print_drop_menu($r,$context,$permission,$crstype);
 4930:         } elsif ($env{'form.state'} eq 'done') {
 4931:             &Apache::lonuserutils::update_user_list($r,$context,undef,
 4932:                                                     $env{'form.action'});
 4933:         }
 4934:     } elsif ($env{'form.action'} eq 'dateselect') {
 4935:         if ($permission->{'cusr'}) {
 4936:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 4937:                       &Apache::lonuserutils::date_section_selector($context,$permission,
 4938:                                                                    $crstype,$showcredits));
 4939:         } else {
 4940:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 4941:                      '<span class="LC_error">'.&mt('You do not have permission to modify dates or sections for users').'</span>'); 
 4942:         }
 4943:     } elsif ($env{'form.action'} eq 'selfenroll') {
 4944:         if ($permission->{selfenrolladmin}) {
 4945:             my $cid = $env{'request.course.id'};
 4946:             my $cdom = $env{'course.'.$cid.'.domain'};
 4947:             my $cnum = $env{'course.'.$cid.'.num'};
 4948:             my %currsettings = (
 4949:                 selfenroll_types              => $env{'course.'.$cid.'.internal.selfenroll_types'},
 4950:                 selfenroll_registered         => $env{'course.'.$cid.'.internal.selfenroll_registered'},
 4951:                 selfenroll_section            => $env{'course.'.$cid.'.internal.selfenroll_section'},
 4952:                 selfenroll_notifylist         => $env{'course.'.$cid.'.internal.selfenroll_notifylist'},
 4953:                 selfenroll_approval           => $env{'course.'.$cid.'.internal.selfenroll_approval'},
 4954:                 selfenroll_limit              => $env{'course.'.$cid.'.internal.selfenroll_limit'},
 4955:                 selfenroll_cap                => $env{'course.'.$cid.'.internal.selfenroll_cap'},
 4956:                 selfenroll_start_date         => $env{'course.'.$cid.'.internal.selfenroll_start_date'},
 4957:                 selfenroll_end_date           => $env{'course.'.$cid.'.internal.selfenroll_end_date'},
 4958:                 selfenroll_start_access       => $env{'course.'.$cid.'.internal.selfenroll_start_access'},
 4959:                 selfenroll_end_access         => $env{'course.'.$cid.'.internal.selfenroll_end_access'},
 4960:                 default_enrollment_start_date => $env{'course.'.$cid.'.default_enrollment_start_date'},
 4961:                 default_enrollment_end_date   => $env{'course.'.$cid.'.default_enrollment_end_date'},
 4962:                 uniquecode                    => $env{'course.'.$cid.'.internal.uniquecode'},
 4963:             );
 4964:             push(@{$brcrum},
 4965:                     {href => '/adm/createuser?action=selfenroll',
 4966:                      text => "Configure Self-enrollment",
 4967:                      help => 'Course_Self_Enrollment'});
 4968:             if (!exists($env{'form.state'})) {
 4969:                 $args = { bread_crumbs           => $brcrum,
 4970:                           bread_crumbs_component => 'Configure Self-enrollment'};
 4971:                 $r->print(&header(undef,$args));
 4972:                 $r->print('<h3>'.&mt('Self-enrollment with a student role').'</h3>'."\n");
 4973:                 &print_selfenroll_menu($r,'course',$cid,$cdom,$cnum,\%currsettings);
 4974:             } elsif ($env{'form.state'} eq 'done') {
 4975:                 push (@{$brcrum},
 4976:                           {href=>'/adm/createuser?action=selfenroll',
 4977:                            text=>"Result"});
 4978:                 $args = { bread_crumbs           => $brcrum,
 4979:                           bread_crumbs_component => 'Self-enrollment result'};
 4980:                 $r->print(&header(undef,$args));
 4981:                 $r->print('<h3>'.&mt('Self-enrollment with a student role').'</h3>'."\n");
 4982:                 &update_selfenroll_config($r,$cid,$cdom,$cnum,$context,$crstype,\%currsettings);
 4983:             }
 4984:         } else {
 4985:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 4986:                      '<span class="LC_error">'.&mt('You do not have permission to configure self-enrollment').'</span>');
 4987:         }
 4988:     } elsif ($env{'form.action'} eq 'selfenrollqueue') {
 4989:         push(@{$brcrum},
 4990:                  {href => '/adm/createuser?action=selfenrollqueue',
 4991:                   text => 'Enrollment requests',
 4992:                   help => 'Course_Self_Enrollment'});
 4993:         $bread_crumbs_component = 'Enrollment requests';
 4994:         if ($env{'form.state'} eq 'done') {
 4995:             push(@{$brcrum},
 4996:                      {href => '/adm/createuser?action=selfenrollqueue',
 4997:                       text => 'Result',
 4998:                       help => 'Course_Self_Enrollment'});
 4999:             $bread_crumbs_component = 'Enrollment result';
 5000:         }
 5001:         $args = { bread_crumbs           => $brcrum,
 5002:                   bread_crumbs_component => $bread_crumbs_component};
 5003:         $r->print(&header(undef,$args));
 5004:         my $cid = $env{'request.course.id'};
 5005:         my $cdom = $env{'course.'.$cid.'.domain'};
 5006:         my $cnum = $env{'course.'.$cid.'.num'};
 5007:         my $coursedesc = $env{'course.'.$cid.'.description'};
 5008:         if (!exists($env{'form.state'})) {
 5009:             $r->print('<h3>'.&mt('Pending enrollment requests').'</h3>'."\n");
 5010:             $r->print(&Apache::loncoursequeueadmin::display_queued_requests($context,
 5011:                                                                        $cdom,$cnum));
 5012:         } elsif ($env{'form.state'} eq 'done') {
 5013:             $r->print('<h3>'.&mt('Enrollment request processing').'</h3>'."\n");
 5014:             $r->print(&Apache::loncoursequeueadmin::update_request_queue($context,
 5015:                           $cdom,$cnum,$coursedesc));
 5016:         }
 5017:     } elsif ($env{'form.action'} eq 'changelogs') {
 5018:         my $helpitem;
 5019:         if ($context eq 'course') {
 5020:             $helpitem = 'Course_User_Logs';
 5021:         }
 5022:         push (@{$brcrum},
 5023:                  {href => '/adm/createuser?action=changelogs',
 5024:                   text => 'User Management Logs',
 5025:                   help => $helpitem});
 5026:         $bread_crumbs_component = 'User Changes';
 5027:         $args = { bread_crumbs           => $brcrum,
 5028:                   bread_crumbs_component => $bread_crumbs_component};
 5029:         $r->print(&header(undef,$args));
 5030:         &print_userchangelogs_display($r,$context,$permission);
 5031:     } else {
 5032:         $bread_crumbs_component = 'User Management';
 5033:         $args = { bread_crumbs           => $brcrum,
 5034:                   bread_crumbs_component => $bread_crumbs_component};
 5035:         $r->print(&header(undef,$args));
 5036:         $r->print(&print_main_menu($permission,$context,$crstype));
 5037:     }
 5038:     $r->print(&Apache::loncommon::end_page());
 5039:     return OK;
 5040: }
 5041: 
 5042: sub header {
 5043:     my ($jscript,$args) = @_;
 5044:     my $start_page;
 5045:     if (ref($args) eq 'HASH') {
 5046:         $start_page=&Apache::loncommon::start_page('User Management',$jscript,$args);
 5047:     } else {
 5048:         $start_page=&Apache::loncommon::start_page('User Management',$jscript);
 5049:     }
 5050:     return $start_page;
 5051: }
 5052: 
 5053: sub add_script {
 5054:     my ($js) = @_;
 5055:     return '<script type="text/javascript">'."\n"
 5056:           .'// <![CDATA['."\n"
 5057:           .$js."\n"
 5058:           .'// ]]>'."\n"
 5059:           .'</script>'."\n";
 5060: }
 5061: 
 5062: sub usernamerequest_javascript {
 5063:     my $js = <<ENDJS;
 5064: 
 5065: function openusernamereqdisplay(dom,uname,queue) {
 5066:     var url = '/adm/createuser?action=displayuserreq';
 5067:     url += '&domain='+dom+'&username='+uname+'&queue='+queue;
 5068:     var title = 'Account_Request_Browser';
 5069:     var options = 'scrollbars=1,resizable=1,menubar=0';
 5070:     options += ',width=700,height=600';
 5071:     var stdeditbrowser = open(url,title,options,'1');
 5072:     stdeditbrowser.focus();
 5073:     return;
 5074: }
 5075:  
 5076: ENDJS
 5077: }
 5078: 
 5079: sub close_popup_form {
 5080:     my $close= &mt('Close Window');
 5081:     return << "END";
 5082: <p><form name="displayreq" action="" method="post">
 5083: <input type="button" name="closeme" value="$close" onclick="javascript:self.close();" />
 5084: </form></p>
 5085: END
 5086: }
 5087: 
 5088: sub verify_user_display {
 5089:     my ($context) = @_;
 5090:     my %lt = &Apache::lonlocal::texthash (
 5091:         course    => 'course(s): description, section(s), status',
 5092:         community => 'community(s): description, section(s), status',
 5093:         author    => 'author',
 5094:     );
 5095:     my $photos;
 5096:     if (($context eq 'course') && $env{'request.course.id'}) {
 5097:         $photos = $env{'course.'.$env{'request.course.id'}.'.internal.showphoto'};
 5098:     }
 5099:     my $output = <<"END";
 5100: 
 5101: function hide_searching() {
 5102:     if (document.getElementById('searching')) {
 5103:         document.getElementById('searching').style.display = 'none';
 5104:     }
 5105:     return;
 5106: }
 5107: 
 5108: function display_update() {
 5109:     document.studentform.action.value = 'listusers';
 5110:     document.studentform.phase.value = 'display';
 5111:     document.studentform.submit();
 5112: }
 5113: 
 5114: function updateCols(caller) {
 5115:     var context = '$context';
 5116:     var photos = '$photos';
 5117:     if (caller == 'Status') {
 5118:         if ((context == 'domain') && 
 5119:             ((document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'course') ||
 5120:              (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'community'))) {
 5121:             document.getElementById('showcolstatus').checked = false;
 5122:             document.getElementById('showcolstatus').disabled = 'disabled';
 5123:             document.getElementById('showcolstart').checked = false;
 5124:             document.getElementById('showcolend').checked = false;
 5125:         } else {
 5126:             if (document.studentform.Status.options[document.studentform.Status.selectedIndex].value == 'Any') {
 5127:                 document.getElementById('showcolstatus').checked = true;
 5128:                 document.getElementById('showcolstatus').disabled = '';
 5129:                 document.getElementById('showcolstart').checked = true;
 5130:                 document.getElementById('showcolend').checked = true;
 5131:             } else {
 5132:                 document.getElementById('showcolstatus').checked = false;
 5133:                 document.getElementById('showcolstatus').disabled = 'disabled';
 5134:                 document.getElementById('showcolstart').checked = false;
 5135:                 document.getElementById('showcolend').checked = false;
 5136:             }
 5137:         }
 5138:     }
 5139:     if (caller == 'output') {
 5140:         if (photos == 1) {
 5141:             if (document.getElementById('showcolphoto')) {
 5142:                 var photoitem = document.getElementById('showcolphoto');
 5143:                 if (document.studentform.output.options[document.studentform.output.selectedIndex].value == 'html') {
 5144:                     photoitem.checked = true;
 5145:                     photoitem.disabled = '';
 5146:                 } else {
 5147:                     photoitem.checked = false;
 5148:                     photoitem.disabled = 'disabled';
 5149:                 }
 5150:             }
 5151:         }
 5152:     }
 5153:     if (caller == 'showrole') {
 5154:         if ((document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'Any') ||
 5155:             (document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'cr')) {
 5156:             document.getElementById('showcolrole').checked = true;
 5157:             document.getElementById('showcolrole').disabled = '';
 5158:         } else {
 5159:             document.getElementById('showcolrole').checked = false;
 5160:             document.getElementById('showcolrole').disabled = 'disabled';
 5161:         }
 5162:         if (context == 'domain') {
 5163:             var quotausageshow = 0;
 5164:             if ((document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'course') ||
 5165:                 (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'community')) {
 5166:                 document.getElementById('showcolstatus').checked = false;
 5167:                 document.getElementById('showcolstatus').disabled = 'disabled';
 5168:                 document.getElementById('showcolstart').checked = false;
 5169:                 document.getElementById('showcolend').checked = false;
 5170:             } else {
 5171:                 if (document.studentform.Status.options[document.studentform.Status.selectedIndex].value == 'Any') {
 5172:                     document.getElementById('showcolstatus').checked = true;
 5173:                     document.getElementById('showcolstatus').disabled = '';
 5174:                     document.getElementById('showcolstart').checked = true;
 5175:                     document.getElementById('showcolend').checked = true;
 5176:                 }
 5177:             }
 5178:             if (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'domain') {
 5179:                 document.getElementById('showcolextent').disabled = 'disabled';
 5180:                 document.getElementById('showcolextent').checked = 'false';
 5181:                 document.getElementById('showextent').style.display='none';
 5182:                 document.getElementById('showcoltextextent').innerHTML = '';
 5183:                 if ((document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'au') ||
 5184:                     (document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'Any')) {
 5185:                     if (document.getElementById('showcolauthorusage')) {
 5186:                         document.getElementById('showcolauthorusage').disabled = '';
 5187:                     }
 5188:                     if (document.getElementById('showcolauthorquota')) {
 5189:                         document.getElementById('showcolauthorquota').disabled = '';
 5190:                     }
 5191:                     quotausageshow = 1;
 5192:                 }
 5193:             } else {
 5194:                 document.getElementById('showextent').style.display='block';
 5195:                 document.getElementById('showextent').style.textAlign='left';
 5196:                 document.getElementById('showextent').style.textFace='normal';
 5197:                 if (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'author') {
 5198:                     document.getElementById('showcolextent').disabled = '';
 5199:                     document.getElementById('showcolextent').checked = 'true';
 5200:                     document.getElementById('showcoltextextent').innerHTML="$lt{'author'}";
 5201:                 } else {
 5202:                     document.getElementById('showcolextent').disabled = '';
 5203:                     document.getElementById('showcolextent').checked = 'true';
 5204:                     if (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'community') {
 5205:                         document.getElementById('showcoltextextent').innerHTML="$lt{'community'}";
 5206:                     } else {
 5207:                         document.getElementById('showcoltextextent').innerHTML="$lt{'course'}";
 5208:                     }
 5209:                 }
 5210:             }
 5211:             if (quotausageshow == 0)  {
 5212:                 if (document.getElementById('showcolauthorusage')) {
 5213:                     document.getElementById('showcolauthorusage').checked = false;
 5214:                     document.getElementById('showcolauthorusage').disabled = 'disabled';
 5215:                 }
 5216:                 if (document.getElementById('showcolauthorquota')) {
 5217:                     document.getElementById('showcolauthorquota').checked = false;
 5218:                     document.getElementById('showcolauthorquota').disabled = 'disabled';
 5219:                 }
 5220:             }
 5221:         }
 5222:     }
 5223:     return;
 5224: }
 5225: 
 5226: END
 5227:     return $output;
 5228: 
 5229: }
 5230: 
 5231: ###############################################################
 5232: ###############################################################
 5233: #  Menu Phase One
 5234: sub print_main_menu {
 5235:     my ($permission,$context,$crstype) = @_;
 5236:     my $linkcontext = $context;
 5237:     my $stuterm = lc(&Apache::lonnet::plaintext('st',$crstype));
 5238:     if (($context eq 'course') && ($crstype eq 'Community')) {
 5239:         $linkcontext = lc($crstype);
 5240:         $stuterm = 'Members';
 5241:     }
 5242:     my %links = (
 5243:                 domain => {
 5244:                             upload     => 'Upload a File of Users',
 5245:                             singleuser => 'Add/Modify a User',
 5246:                             listusers  => 'Manage Users',
 5247:                             },
 5248:                 author => {
 5249:                             upload     => 'Upload a File of Co-authors',
 5250:                             singleuser => 'Add/Modify a Co-author',
 5251:                             listusers  => 'Manage Co-authors',
 5252:                             },
 5253:                 course => {
 5254:                             upload     => 'Upload a File of Course Users',
 5255:                             singleuser => 'Add/Modify a Course User',
 5256:                             listusers  => 'List and Modify Multiple Course Users',
 5257:                             },
 5258:                 community => {
 5259:                             upload     => 'Upload a File of Community Users',
 5260:                             singleuser => 'Add/Modify a Community User',
 5261:                             listusers  => 'List and Modify Multiple Community Users',
 5262:                            },
 5263:                 );
 5264:      my %linktitles = (
 5265:                 domain => {
 5266:                             singleuser => 'Add a user to the domain, and/or a course or community in the domain.',
 5267:                             listusers  => 'Show and manage users in this domain.',
 5268:                             },
 5269:                 author => {
 5270:                             singleuser => 'Add a user with a co- or assistant author role.',
 5271:                             listusers  => 'Show and manage co- or assistant authors.',
 5272:                             },
 5273:                 course => {
 5274:                             singleuser => 'Add a user with a certain role to this course.',
 5275:                             listusers  => 'Show and manage users in this course.',
 5276:                             },
 5277:                 community => {
 5278:                             singleuser => 'Add a user with a certain role to this community.',
 5279:                             listusers  => 'Show and manage users in this community.',
 5280:                            },
 5281:                 );
 5282:   my @menu = ( {categorytitle => 'Single Users', 
 5283:          items =>
 5284:          [
 5285:             {
 5286:              linktext => $links{$linkcontext}{'singleuser'},
 5287:              icon => 'edit-redo.png',
 5288:              #help => 'Course_Change_Privileges',
 5289:              url => '/adm/createuser?action=singleuser',
 5290:              permission => $permission->{'cusr'},
 5291:              linktitle => $linktitles{$linkcontext}{'singleuser'},
 5292:             },
 5293:          ]},
 5294: 
 5295:          {categorytitle => 'Multiple Users',
 5296:          items => 
 5297:          [
 5298:             {
 5299:              linktext => $links{$linkcontext}{'upload'},
 5300:              icon => 'uplusr.png',
 5301:              #help => 'Course_Create_Class_List',
 5302:              url => '/adm/createuser?action=upload',
 5303:              permission => $permission->{'cusr'},
 5304:              linktitle => 'Upload a CSV or a text file containing users.',
 5305:             },
 5306:             {
 5307:              linktext => $links{$linkcontext}{'listusers'},
 5308:              icon => 'mngcu.png',
 5309:              #help => 'Course_View_Class_List',
 5310:              url => '/adm/createuser?action=listusers',
 5311:              permission => ($permission->{'view'} || $permission->{'cusr'}),
 5312:              linktitle => $linktitles{$linkcontext}{'listusers'}, 
 5313:             },
 5314: 
 5315:          ]},
 5316: 
 5317:          {categorytitle => 'Administration',
 5318:          items => [ ]},
 5319:        );
 5320:             
 5321:     if ($context eq 'domain'){
 5322:         
 5323:         push(@{ $menu[2]->{items} }, #Category: Administration
 5324:             {
 5325:              linktext => 'Custom Roles',
 5326:              icon => 'emblem-photos.png',
 5327:              #help => 'Course_Editing_Custom_Roles',
 5328:              url => '/adm/createuser?action=custom',
 5329:              permission => $permission->{'custom'},
 5330:              linktitle => 'Configure a custom role.',
 5331:             },
 5332:             {
 5333:              linktext => 'Authoring Space Requests',
 5334:              icon => 'selfenrl-queue.png',
 5335:              #help => 'Domain_Role_Approvals',
 5336:              url => '/adm/createuser?action=processauthorreq',
 5337:              permission => $permission->{'cusr'},
 5338:              linktitle => 'Approve or reject author role requests',
 5339:             },
 5340:             {
 5341:              linktext => 'LON-CAPA Account Requests',
 5342:              icon => 'list-add.png',
 5343:              #help => 'Domain_Username_Approvals',
 5344:              url => '/adm/createuser?action=processusernamereq',
 5345:              permission => $permission->{'cusr'},
 5346:              linktitle => 'Approve or reject LON-CAPA account requests',
 5347:             },
 5348:             {
 5349:              linktext => 'Change Log',
 5350:              icon => 'document-properties.png',
 5351:              #help => 'Course_User_Logs',
 5352:              url => '/adm/createuser?action=changelogs',
 5353:              permission => $permission->{'cusr'},
 5354:              linktitle => 'View change log.',
 5355:             },
 5356:         );
 5357:         
 5358:     }elsif ($context eq 'course'){
 5359:         my ($cnum,$cdom) = &Apache::lonuserutils::get_course_identity();
 5360: 
 5361:         my %linktext = (
 5362:                          'Course'    => {
 5363:                                           single => 'Add/Modify a Student', 
 5364:                                           drop   => 'Drop Students',
 5365:                                           groups => 'Course Groups',
 5366:                                         },
 5367:                          'Community' => {
 5368:                                           single => 'Add/Modify a Member', 
 5369:                                           drop   => 'Drop Members',
 5370:                                           groups => 'Community Groups',
 5371:                                         },
 5372:                        );
 5373:         $linktext{'Placement'} = $linktext{'Course'};
 5374: 
 5375:         my %linktitle = (
 5376:             'Course' => {
 5377:                   single => 'Add a user with the role of student to this course',
 5378:                   drop   => 'Remove a student from this course.',
 5379:                   groups => 'Manage course groups',
 5380:                         },
 5381:             'Community' => {
 5382:                   single => 'Add a user with the role of member to this community',
 5383:                   drop   => 'Remove a member from this community.',
 5384:                   groups => 'Manage community groups',
 5385:                            },
 5386:         );
 5387: 
 5388:         $linktitle{'Placement'} = $linktitle{'Course'};
 5389: 
 5390:         push(@{ $menu[0]->{items} }, #Category: Single Users
 5391:             {   
 5392:              linktext => $linktext{$crstype}{'single'},
 5393:              #help => 'Course_Add_Student',
 5394:              icon => 'list-add.png',
 5395:              url => '/adm/createuser?action=singlestudent',
 5396:              permission => $permission->{'cusr'},
 5397:              linktitle => $linktitle{$crstype}{'single'},
 5398:             },
 5399:         );
 5400:         
 5401:         push(@{ $menu[1]->{items} }, #Category: Multiple Users 
 5402:             {
 5403:              linktext => $linktext{$crstype}{'drop'},
 5404:              icon => 'edit-undo.png',
 5405:              #help => 'Course_Drop_Student',
 5406:              url => '/adm/createuser?action=drop',
 5407:              permission => $permission->{'cusr'},
 5408:              linktitle => $linktitle{$crstype}{'drop'},
 5409:             },
 5410:         );
 5411:         push(@{ $menu[2]->{items} }, #Category: Administration
 5412:             {    
 5413:              linktext => 'Custom Roles',
 5414:              icon => 'emblem-photos.png',
 5415:              #help => 'Course_Editing_Custom_Roles',
 5416:              url => '/adm/createuser?action=custom',
 5417:              permission => $permission->{'custom'},
 5418:              linktitle => 'Configure a custom role.',
 5419:             },
 5420:             {
 5421:              linktext => $linktext{$crstype}{'groups'},
 5422:              icon => 'grps.png',
 5423:              #help => 'Course_Manage_Group',
 5424:              url => '/adm/coursegroups?refpage=cusr',
 5425:              permission => $permission->{'grp_manage'},
 5426:              linktitle => $linktitle{$crstype}{'groups'},
 5427:             },
 5428:             {
 5429:              linktext => 'Change Log',
 5430:              icon => 'document-properties.png',
 5431:              #help => 'Course_User_Logs',
 5432:              url => '/adm/createuser?action=changelogs',
 5433:              permission => $permission->{'cusr'},
 5434:              linktitle => 'View change log.',
 5435:             },
 5436:         );
 5437:         if ($env{'course.'.$env{'request.course.id'}.'.internal.selfenroll_approval'}) {
 5438:             push(@{ $menu[2]->{items} },
 5439:                     {
 5440:                      linktext => 'Enrollment Requests',
 5441:                      icon => 'selfenrl-queue.png',
 5442:                      #help => 'Course_Approve_Selfenroll',
 5443:                      url => '/adm/createuser?action=selfenrollqueue',
 5444:                      permission => $permission->{'selfenrolladmin'},
 5445:                      linktitle =>'Approve or reject enrollment requests.',
 5446:                     },
 5447:             );
 5448:         }
 5449:         
 5450:         if (!exists($permission->{'cusr_section'})){
 5451:             if ($crstype ne 'Community') {
 5452:                 push(@{ $menu[2]->{items} },
 5453:                     {
 5454:                      linktext => 'Automated Enrollment',
 5455:                      icon => 'roles.png',
 5456:                      #help => 'Course_Automated_Enrollment',
 5457:                      permission => (&Apache::lonnet::auto_run($cnum,$cdom)
 5458:                                          && $permission->{'cusr'}),
 5459:                      url  => '/adm/populate',
 5460:                      linktitle => 'Automated enrollment manager.',
 5461:                     }
 5462:                 );
 5463:             }
 5464:             push(@{ $menu[2]->{items} }, 
 5465:                 {
 5466:                  linktext => 'User Self-Enrollment',
 5467:                  icon => 'self_enroll.png',
 5468:                  #help => 'Course_Self_Enrollment',
 5469:                  url => '/adm/createuser?action=selfenroll',
 5470:                  permission => $permission->{'selfenrolladmin'},
 5471:                  linktitle => 'Configure user self-enrollment.',
 5472:                 },
 5473:             );
 5474:         }
 5475:     } elsif ($context eq 'author') {
 5476:         push(@{ $menu[2]->{items} }, #Category: Administration
 5477:             {
 5478:              linktext => 'Change Log',
 5479:              icon => 'document-properties.png',
 5480:              #help => 'Course_User_Logs',
 5481:              url => '/adm/createuser?action=changelogs',
 5482:              permission => $permission->{'cusr'},
 5483:              linktitle => 'View change log.',
 5484:             },
 5485:         );
 5486:     }
 5487:     return Apache::lonhtmlcommon::generate_menu(@menu);
 5488: #               { text => 'View Log-in History',
 5489: #                 help => 'Course_User_Logins',
 5490: #                 action => 'logins',
 5491: #                 permission => $permission->{'cusr'},
 5492: #               });
 5493: }
 5494: 
 5495: sub restore_prev_selections {
 5496:     my %saveable_parameters = ('srchby'   => 'scalar',
 5497: 			       'srchin'   => 'scalar',
 5498: 			       'srchtype' => 'scalar',
 5499: 			       );
 5500:     &Apache::loncommon::store_settings('user','user_picker',
 5501: 				       \%saveable_parameters);
 5502:     &Apache::loncommon::restore_settings('user','user_picker',
 5503: 					 \%saveable_parameters);
 5504: }
 5505: 
 5506: sub print_selfenroll_menu {
 5507:     my ($r,$context,$cid,$cdom,$cnum,$currsettings,$additional) = @_;
 5508:     my $crstype = &Apache::loncommon::course_type();
 5509:     my $formname = 'selfenroll';
 5510:     my $nolink = 1;
 5511:     my ($row,$lt) = &Apache::lonuserutils::get_selfenroll_titles();
 5512:     my $groupslist = &Apache::lonuserutils::get_groupslist();
 5513:     my $setsec_js = 
 5514:         &Apache::lonuserutils::setsections_javascript($formname,$groupslist);
 5515:     my %alerts = &Apache::lonlocal::texthash(
 5516:         acto => 'Activation of self-enrollment was selected for the following domain(s)',
 5517:         butn => 'but no user types have been checked.',
 5518:         wilf => "Please uncheck 'activate' or check at least one type.",
 5519:     );
 5520:     &js_escape(\%alerts);
 5521:     my $selfenroll_js = <<"ENDSCRIPT";
 5522: function update_types(caller,num) {
 5523:     var delidx = getIndexByName('selfenroll_delete');
 5524:     var actidx = getIndexByName('selfenroll_activate');
 5525:     if (caller == 'selfenroll_all') {
 5526:         var selall;
 5527:         for (var i=0; i<document.$formname.selfenroll_all.length; i++) {
 5528:             if (document.$formname.selfenroll_all[i].checked) {
 5529:                 selall = document.$formname.selfenroll_all[i].value;
 5530:             }
 5531:         }
 5532:         if (selall == 1) {
 5533:             if (delidx != -1) {
 5534:                 if (document.$formname.selfenroll_delete.length) {
 5535:                     for (var j=0; j<document.$formname.selfenroll_delete.length; j++) {
 5536:                         document.$formname.selfenroll_delete[j].checked = true;
 5537:                     }
 5538:                 } else {
 5539:                     document.$formname.elements[delidx].checked = true;
 5540:                 }
 5541:             }
 5542:             if (actidx != -1) {
 5543:                 if (document.$formname.selfenroll_activate.length) {
 5544:                     for (var j=0; j<document.$formname.selfenroll_activate.length; j++) {
 5545:                         document.$formname.selfenroll_activate[j].checked = false;
 5546:                     }
 5547:                 } else {
 5548:                     document.$formname.elements[actidx].checked = false;
 5549:                 }
 5550:             }
 5551:             document.$formname.selfenroll_newdom.selectedIndex = 0; 
 5552:         }
 5553:     }
 5554:     if (caller == 'selfenroll_activate') {
 5555:         if (document.$formname.selfenroll_activate.length) {
 5556:             for (var j=0; j<document.$formname.selfenroll_activate.length; j++) {
 5557:                 if (document.$formname.selfenroll_activate[j].value == num) {
 5558:                     if (document.$formname.selfenroll_activate[j].checked) {
 5559:                         for (var i=0; i<document.$formname.selfenroll_all.length; i++) {
 5560:                             if (document.$formname.selfenroll_all[i].value == '1') {
 5561:                                 document.$formname.selfenroll_all[i].checked = false;
 5562:                             }
 5563:                             if (document.$formname.selfenroll_all[i].value == '0') {
 5564:                                 document.$formname.selfenroll_all[i].checked = true;
 5565:                             }
 5566:                         }
 5567:                     }
 5568:                 }
 5569:             }
 5570:         } else {
 5571:             for (var i=0; i<document.$formname.selfenroll_all.length; i++) {
 5572:                 if (document.$formname.selfenroll_all[i].value == '1') {
 5573:                     document.$formname.selfenroll_all[i].checked = false;
 5574:                 }
 5575:                 if (document.$formname.selfenroll_all[i].value == '0') {
 5576:                     document.$formname.selfenroll_all[i].checked = true;
 5577:                 }
 5578:             }
 5579:         }
 5580:     }
 5581:     if (caller == 'selfenroll_delete') {
 5582:         if (document.$formname.selfenroll_delete.length) {
 5583:             for (var j=0; j<document.$formname.selfenroll_delete.length; j++) {
 5584:                 if (document.$formname.selfenroll_delete[j].value == num) {
 5585:                     if (document.$formname.selfenroll_delete[j].checked) {
 5586:                         var delindex = getIndexByName('selfenroll_types_'+num);
 5587:                         if (delindex != -1) { 
 5588:                             if (document.$formname.elements[delindex].length) {
 5589:                                 for (var k=0; k<document.$formname.elements[delindex].length; k++) {
 5590:                                     document.$formname.elements[delindex][k].checked = false;
 5591:                                 }
 5592:                             } else {
 5593:                                 document.$formname.elements[delindex].checked = false;
 5594:                             }
 5595:                         }
 5596:                     }
 5597:                 }
 5598:             }
 5599:         } else {
 5600:             if (document.$formname.selfenroll_delete.checked) {
 5601:                 var delindex = getIndexByName('selfenroll_types_'+num);
 5602:                 if (delindex != -1) {
 5603:                     if (document.$formname.elements[delindex].length) {
 5604:                         for (var k=0; k<document.$formname.elements[delindex].length; k++) {
 5605:                             document.$formname.elements[delindex][k].checked = false;
 5606:                         }
 5607:                     } else {
 5608:                         document.$formname.elements[delindex].checked = false;
 5609:                     }
 5610:                 }
 5611:             }
 5612:         }
 5613:     }
 5614:     return;
 5615: }
 5616: 
 5617: function validate_types(form) {
 5618:     var needaction = new Array();
 5619:     var countfail = 0;
 5620:     var actidx = getIndexByName('selfenroll_activate');
 5621:     if (actidx != -1) {
 5622:         if (document.$formname.selfenroll_activate.length) {
 5623:             for (var j=0; j<document.$formname.selfenroll_activate.length; j++) {
 5624:                 var num = document.$formname.selfenroll_activate[j].value;
 5625:                 if (document.$formname.selfenroll_activate[j].checked) {
 5626:                     countfail = check_types(num,countfail,needaction)
 5627:                 }
 5628:             }
 5629:         } else {
 5630:             if (document.$formname.selfenroll_activate.checked) {
 5631:                 var num = document.$formname.selfenroll_activate.value;
 5632:                 countfail = check_types(num,countfail,needaction)
 5633:             }
 5634:         }
 5635:     }
 5636:     if (countfail > 0) {
 5637:         var msg = "$alerts{'acto'}\\n";
 5638:         var loopend = needaction.length -1;
 5639:         if (loopend > 0) {
 5640:             for (var m=0; m<loopend; m++) {
 5641:                 msg += needaction[m]+", ";
 5642:             }
 5643:         }
 5644:         msg += needaction[loopend]+"\\n$alerts{'butn'}\\n$alerts{'wilf'}";
 5645:         alert(msg);
 5646:         return; 
 5647:     }
 5648:     setSections(form);
 5649: }
 5650: 
 5651: function check_types(num,countfail,needaction) {
 5652:     var typeidx = getIndexByName('selfenroll_types_'+num);
 5653:     var count = 0;
 5654:     if (typeidx != -1) {
 5655:         if (document.$formname.elements[typeidx].length) {
 5656:             for (var k=0; k<document.$formname.elements[typeidx].length; k++) {
 5657:                 if (document.$formname.elements[typeidx][k].checked) {
 5658:                     count ++;
 5659:                 }
 5660:             }
 5661:         } else {
 5662:             if (document.$formname.elements[typeidx].checked) {
 5663:                 count ++;
 5664:             }
 5665:         }
 5666:         if (count == 0) {
 5667:             var domidx = getIndexByName('selfenroll_dom_'+num);
 5668:             if (domidx != -1) {
 5669:                 var domname = document.$formname.elements[domidx].value;
 5670:                 needaction[countfail] = domname;
 5671:                 countfail ++;
 5672:             }
 5673:         }
 5674:     }
 5675:     return countfail;
 5676: }
 5677: 
 5678: function toggleNotify() {
 5679:     var selfenrollApproval = 0;
 5680:     if (document.$formname.selfenroll_approval.length) {
 5681:         for (var i=0; i<document.$formname.selfenroll_approval.length; i++) {
 5682:             if (document.$formname.selfenroll_approval[i].checked) {
 5683:                 selfenrollApproval = document.$formname.selfenroll_approval[i].value;
 5684:                 break;        
 5685:             }
 5686:         }
 5687:     }
 5688:     if (document.getElementById('notified')) {
 5689:         if (selfenrollApproval == 0) {
 5690:             document.getElementById('notified').style.display='none';
 5691:         } else {
 5692:             document.getElementById('notified').style.display='block';
 5693:         }
 5694:     }
 5695:     return;
 5696: }
 5697: 
 5698: function getIndexByName(item) {
 5699:     for (var i=0;i<document.$formname.elements.length;i++) {
 5700:         if (document.$formname.elements[i].name == item) {
 5701:             return i;
 5702:         }
 5703:     }
 5704:     return -1;
 5705: }
 5706: ENDSCRIPT
 5707: 
 5708:     my $output = '<script type="text/javascript">'."\n".
 5709:                  '// <![CDATA['."\n".
 5710:                  $setsec_js."\n".$selfenroll_js."\n".
 5711:                  '// ]]>'."\n".
 5712:                  '</script>'."\n".
 5713:                  '<h3>'.$lt->{'selfenroll'}.'</h3>'."\n";
 5714:  
 5715:     my $visactions = &cat_visibility();
 5716:     my ($cathash,%cattype);
 5717:     my %domconfig = &Apache::lonnet::get_dom('configuration',['coursecategories'],$cdom);
 5718:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 5719:         $cathash = $domconfig{'coursecategories'}{'cats'};
 5720:         $cattype{'auth'} = $domconfig{'coursecategories'}{'auth'};
 5721:         $cattype{'unauth'} = $domconfig{'coursecategories'}{'unauth'};
 5722:         if ($cattype{'auth'} eq '') {
 5723:             $cattype{'auth'} = 'std';
 5724:         }
 5725:         if ($cattype{'unauth'} eq '') {
 5726:             $cattype{'unauth'} = 'std';
 5727:         }
 5728:     } else {
 5729:         $cathash = {};
 5730:         $cattype{'auth'} = 'std';
 5731:         $cattype{'unauth'} = 'std';
 5732:     }
 5733:     if (($cattype{'auth'} eq 'none') && ($cattype{'unauth'} eq 'none')) {
 5734:         $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
 5735:                   '<br />'.
 5736:                   '<br />'.$visactions->{'take'}.'<ul>'.
 5737:                   '<li>'.$visactions->{'dc_chgconf'}.'</li>'.
 5738:                   '</ul>');
 5739:     } elsif (($cattype{'auth'} !~ /^(std|domonly)$/) && ($cattype{'unauth'} !~ /^(std|domonly)$/)) {
 5740:         if ($currsettings->{'uniquecode'}) {
 5741:             $r->print('<span class="LC_info">'.$visactions->{'vis'}.'</span>');
 5742:         } else {
 5743:             $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
 5744:                   '<br />'.
 5745:                   '<br />'.$visactions->{'take'}.'<ul>'.
 5746:                   '<li>'.$visactions->{'dc_setcode'}.'</li>'.
 5747:                   '</ul><br />');
 5748:         }
 5749:     } else {
 5750:         my ($visible,$cansetvis,$vismsgs) = &visible_in_stdcat($cdom,$cnum,\%domconfig);
 5751:         if (ref($visactions) eq 'HASH') {
 5752:             if ($visible) {
 5753:                 $output .= '<p class="LC_info">'.$visactions->{'vis'}.'</p>';
 5754:            } else {
 5755:                 $output .= '<p class="LC_warning">'.$visactions->{'miss'}.'</p>'
 5756:                           .$visactions->{'yous'}.
 5757:                            '<p>'.$visactions->{'gen'}.'<br />'.$visactions->{'coca'};
 5758:                 if (ref($vismsgs) eq 'ARRAY') {
 5759:                     $output .= '<br />'.$visactions->{'make'}.'<ul>';
 5760:                     foreach my $item (@{$vismsgs}) {
 5761:                         $output .= '<li>'.$visactions->{$item}.'</li>';
 5762:                     }
 5763:                     $output .= '</ul>';
 5764:                 }
 5765:                 $output .= '</p>';
 5766:             }
 5767:         }
 5768:     }
 5769:     my $actionhref = '/adm/createuser';
 5770:     if ($context eq 'domain') {
 5771:         $actionhref = '/adm/modifycourse';
 5772:     }
 5773: 
 5774:     my %noedit;
 5775:     unless ($context eq 'domain') {
 5776:         %noedit = &get_noedit_fields($cdom,$cnum,$crstype,$row);
 5777:     }
 5778:     $output .= '<form name="'.$formname.'" method="post" action="'.$actionhref.'">'."\n".
 5779:                &Apache::lonhtmlcommon::start_pick_box();
 5780:     if (ref($row) eq 'ARRAY') {
 5781:         foreach my $item (@{$row}) {
 5782:             my $title = $item; 
 5783:             if (ref($lt) eq 'HASH') {
 5784:                 $title = $lt->{$item};
 5785:             }
 5786:             $output .= &Apache::lonhtmlcommon::row_title($title);
 5787:             if ($item eq 'types') {
 5788:                 my $curr_types;
 5789:                 if (ref($currsettings) eq 'HASH') {
 5790:                     $curr_types = $currsettings->{'selfenroll_types'};
 5791:                 }
 5792:                 if ($noedit{$item}) {
 5793:                     if ($curr_types eq '*') {
 5794:                         $output .= &mt('Any user in any domain');   
 5795:                     } else {
 5796:                         my @entries = split(/;/,$curr_types);
 5797:                         if (@entries > 0) {
 5798:                             $output .= '<ul>'; 
 5799:                             foreach my $entry (@entries) {
 5800:                                 my ($currdom,$typestr) = split(/:/,$entry);
 5801:                                 next if ($typestr eq '');
 5802:                                 my $domdesc = &Apache::lonnet::domain($currdom);
 5803:                                 my @currinsttypes = split(',',$typestr);
 5804:                                 my ($othertitle,$usertypes,$types) = 
 5805:                                     &Apache::loncommon::sorted_inst_types($currdom);
 5806:                                 if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 5807:                                     $usertypes->{'any'} = &mt('any user'); 
 5808:                                     if (keys(%{$usertypes}) > 0) {
 5809:                                         $usertypes->{'other'} = &mt('other users');
 5810:                                     }
 5811:                                     my @longinsttypes = map { $usertypes->{$_}; } @currinsttypes;
 5812:                                     $output .= '<li>'.$domdesc.':'.join(', ',@longinsttypes).'</li>';
 5813:                                  }
 5814:                             }
 5815:                             $output .= '</ul>';
 5816:                         } else {
 5817:                             $output .= &mt('None');
 5818:                         }
 5819:                     }
 5820:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 5821:                     next;
 5822:                 }
 5823:                 my $showdomdesc = 1;
 5824:                 my $includeempty = 1;
 5825:                 my $num = 0;
 5826:                 $output .= &Apache::loncommon::start_data_table().
 5827:                            &Apache::loncommon::start_data_table_row()
 5828:                            .'<td colspan="2"><span class="LC_nobreak"><label>'
 5829:                            .&mt('Any user in any domain:')
 5830:                            .'&nbsp;<input type="radio" name="selfenroll_all" value="1" ';
 5831:                 if ($curr_types eq '*') {
 5832:                     $output .= ' checked="checked" '; 
 5833:                 }
 5834:                 $output .= 'onchange="javascript:update_types('.
 5835:                            "'selfenroll_all'".');" />'.&mt('Yes').'</label>'.
 5836:                            '&nbsp;&nbsp;<input type="radio" name="selfenroll_all" value="0" ';
 5837:                 if ($curr_types ne '*') {
 5838:                     $output .= ' checked="checked" ';
 5839:                 }
 5840:                 $output .= ' onchange="javascript:update_types('.
 5841:                            "'selfenroll_all'".');"/>'.&mt('No').'</label></td>'.
 5842:                            &Apache::loncommon::end_data_table_row().
 5843:                            &Apache::loncommon::end_data_table().
 5844:                            &mt('Or').'<br />'.
 5845:                            &Apache::loncommon::start_data_table();
 5846:                 my %currdoms;
 5847:                 if ($curr_types eq '') {
 5848:                     $output .= &new_selfenroll_dom_row($cdom,'0');
 5849:                 } elsif ($curr_types ne '*') {
 5850:                     my @entries = split(/;/,$curr_types);
 5851:                     if (@entries > 0) {
 5852:                         foreach my $entry (@entries) {
 5853:                             my ($currdom,$typestr) = split(/:/,$entry);
 5854:                             $currdoms{$currdom} = 1;
 5855:                             my $domdesc = &Apache::lonnet::domain($currdom);
 5856:                             my @currinsttypes = split(',',$typestr);
 5857:                             $output .= &Apache::loncommon::start_data_table_row()
 5858:                                        .'<td valign="top"><span class="LC_nobreak">'.&mt('Domain:').'<b>'
 5859:                                        .'&nbsp;'.$domdesc.' ('.$currdom.')'
 5860:                                        .'</b><input type="hidden" name="selfenroll_dom_'.$num
 5861:                                        .'" value="'.$currdom.'" /></span><br />'
 5862:                                        .'<span class="LC_nobreak"><label><input type="checkbox" '
 5863:                                        .'name="selfenroll_delete" value="'.$num.'" onchange="javascript:update_types('."'selfenroll_delete','$num'".');" />'
 5864:                                        .&mt('Delete').'</label></span></td>';
 5865:                             $output .= '<td valign="top">&nbsp;&nbsp;'.&mt('User types:').'<br />'
 5866:                                        .&selfenroll_inst_types($num,$currdom,\@currinsttypes).'</td>'
 5867:                                        .&Apache::loncommon::end_data_table_row();
 5868:                             $num ++;
 5869:                         }
 5870:                     }
 5871:                 }
 5872:                 my $add_domtitle = &mt('Users in additional domain:');
 5873:                 if ($curr_types eq '*') { 
 5874:                     $add_domtitle = &mt('Users in specific domain:');
 5875:                 } elsif ($curr_types eq '') {
 5876:                     $add_domtitle = &mt('Users in other domain:');
 5877:                 }
 5878:                 $output .= &Apache::loncommon::start_data_table_row()
 5879:                            .'<td colspan="2"><span class="LC_nobreak">'.$add_domtitle.'</span><br />'
 5880:                            .&Apache::loncommon::select_dom_form('','selfenroll_newdom',
 5881:                                                                 $includeempty,$showdomdesc)
 5882:                            .'<input type="hidden" name="selfenroll_types_total" value="'.$num.'" />'
 5883:                            .'</td>'.&Apache::loncommon::end_data_table_row()
 5884:                            .&Apache::loncommon::end_data_table();
 5885:             } elsif ($item eq 'registered') {
 5886:                 my ($regon,$regoff);
 5887:                 my $registered;
 5888:                 if (ref($currsettings) eq 'HASH') {
 5889:                     $registered = $currsettings->{'selfenroll_registered'};
 5890:                 }
 5891:                 if ($noedit{$item}) {
 5892:                     if ($registered) {
 5893:                         $output .= &mt('Must be registered in course');
 5894:                     } else {
 5895:                         $output .= &mt('No requirement');
 5896:                     }
 5897:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 5898:                     next;
 5899:                 }
 5900:                 if ($registered) {
 5901:                     $regon = ' checked="checked" ';
 5902:                     $regoff = ' ';
 5903:                 } else {
 5904:                     $regon = ' ';
 5905:                     $regoff = ' checked="checked" ';
 5906:                 }
 5907:                 $output .= '<label>'.
 5908:                            '<input type="radio" name="selfenroll_registered" value="1"'.$regon.'/>'.
 5909:                            &mt('Yes').'</label>&nbsp;&nbsp;<label>'.
 5910:                            '<input type="radio" name="selfenroll_registered" value="0"'.$regoff.'/>'.
 5911:                            &mt('No').'</label>';
 5912:             } elsif ($item eq 'enroll_dates') {
 5913:                 my ($starttime,$endtime);
 5914:                 if (ref($currsettings) eq 'HASH') {
 5915:                     $starttime = $currsettings->{'selfenroll_start_date'};
 5916:                     $endtime = $currsettings->{'selfenroll_end_date'};
 5917:                     if ($starttime eq '') {
 5918:                         $starttime = $currsettings->{'default_enrollment_start_date'};
 5919:                     }
 5920:                     if ($endtime eq '') {
 5921:                         $endtime = $currsettings->{'default_enrollment_end_date'};
 5922:                     }
 5923:                 }
 5924:                 if ($noedit{$item}) {
 5925:                     $output .= &mt('From: [_1], to: [_2]',&Apache::lonlocal::locallocaltime($starttime),
 5926:                                                           &Apache::lonlocal::locallocaltime($endtime));
 5927:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 5928:                     next;
 5929:                 }
 5930:                 my $startform =
 5931:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_start_date',$starttime,
 5932:                                       undef,undef,undef,undef,undef,undef,undef,$nolink);
 5933:                 my $endform =
 5934:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_end_date',$endtime,
 5935:                                       undef,undef,undef,undef,undef,undef,undef,$nolink);
 5936:                 $output .= &selfenroll_date_forms($startform,$endform);
 5937:             } elsif ($item eq 'access_dates') {
 5938:                 my ($starttime,$endtime);
 5939:                 if (ref($currsettings) eq 'HASH') {
 5940:                     $starttime = $currsettings->{'selfenroll_start_access'};
 5941:                     $endtime = $currsettings->{'selfenroll_end_access'};
 5942:                     if ($starttime eq '') {
 5943:                         $starttime = $currsettings->{'default_enrollment_start_date'};
 5944:                     }
 5945:                     if ($endtime eq '') {
 5946:                         $endtime = $currsettings->{'default_enrollment_end_date'};
 5947:                     }
 5948:                 }
 5949:                 if ($noedit{$item}) {
 5950:                     $output .= &mt('From: [_1], to: [_2]',&Apache::lonlocal::locallocaltime($starttime),
 5951:                                                           &Apache::lonlocal::locallocaltime($endtime));
 5952:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 5953:                     next;
 5954:                 }
 5955:                 my $startform =
 5956:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_start_access',$starttime,
 5957:                                       undef,undef,undef,undef,undef,undef,undef,$nolink);
 5958:                 my $endform =
 5959:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_end_access',$endtime,
 5960:                                       undef,undef,undef,undef,undef,undef,undef,$nolink);
 5961:                 $output .= &selfenroll_date_forms($startform,$endform);
 5962:             } elsif ($item eq 'section') {
 5963:                 my $currsec;
 5964:                 if (ref($currsettings) eq 'HASH') {
 5965:                     $currsec = $currsettings->{'selfenroll_section'};
 5966:                 }
 5967:                 my %sections_count = &Apache::loncommon::get_sections($cdom,$cnum);
 5968:                 my $newsecval;
 5969:                 if ($currsec ne 'none' && $currsec ne '') {
 5970:                     if (!defined($sections_count{$currsec})) {
 5971:                         $newsecval = $currsec;
 5972:                     }
 5973:                 }
 5974:                 if ($noedit{$item}) {
 5975:                     if ($currsec ne '') {
 5976:                         $output .= $currsec;
 5977:                     } else {
 5978:                         $output .= &mt('No specific section');
 5979:                     }
 5980:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 5981:                     next;
 5982:                 }
 5983:                 my $sections_select = 
 5984:                     &Apache::lonuserutils::course_sections(\%sections_count,'st',$currsec);
 5985:                 $output .= '<table class="LC_createuser">'."\n".
 5986:                            '<tr class="LC_section_row">'."\n".
 5987:                            '<td align="center">'.&mt('Existing sections')."\n".
 5988:                            '<br />'.$sections_select.'</td><td align="center">'.
 5989:                            &mt('New section').'<br />'."\n".
 5990:                            '<input type="text" name="newsec" size="15" value="'.$newsecval.'" />'."\n".
 5991:                            '<input type="hidden" name="sections" value="" />'."\n".
 5992:                            '</td></tr></table>'."\n";
 5993:             } elsif ($item eq 'approval') {
 5994:                 my ($currnotified,$currapproval,%appchecked);
 5995:                 my %selfdescs = &Apache::lonuserutils::selfenroll_default_descs();
 5996:                 if (ref($currsettings) eq 'HASH') { 
 5997:                     $currnotified = $currsettings->{'selfenroll_notifylist'};
 5998:                     $currapproval = $currsettings->{'selfenroll_approval'};
 5999:                 }
 6000:                 if ($currapproval !~ /^[012]$/) {
 6001:                     $currapproval = 0;
 6002:                 }
 6003:                 if ($noedit{$item}) {
 6004:                     $output .=  $selfdescs{'approval'}{$currapproval}.
 6005:                                 '<br />'.&mt('(Set by Domain Coordinator)');
 6006:                     next;
 6007:                 }
 6008:                 $appchecked{$currapproval} = ' checked="checked"';
 6009:                 for my $i (0..2) {
 6010:                     $output .= '<label>'.
 6011:                                '<input type="radio" name="selfenroll_approval" value="'.$i.'"'.
 6012:                                $appchecked{$i}.' onclick="toggleNotify();" />'.$selfdescs{'approval'}{$i}.
 6013:                                '</label>'.('&nbsp;'x2);
 6014:                 }
 6015:                 my %advhash = &Apache::lonnet::get_course_adv_roles($cid,1);
 6016:                 my (@ccs,%notified);
 6017:                 my $ccrole = 'cc';
 6018:                 if ($crstype eq 'Community') {
 6019:                     $ccrole = 'co';
 6020:                 }
 6021:                 if ($advhash{$ccrole}) {
 6022:                     @ccs = split(/,/,$advhash{$ccrole});
 6023:                 }
 6024:                 if ($currnotified) {
 6025:                     foreach my $current (split(/,/,$currnotified)) {
 6026:                         $notified{$current} = 1;
 6027:                         if (!grep(/^\Q$current\E$/,@ccs)) {
 6028:                             push(@ccs,$current);
 6029:                         }
 6030:                     }
 6031:                 }
 6032:                 if (@ccs) {
 6033:                     my $style;
 6034:                     unless ($currapproval) {
 6035:                         $style = ' style="display: none;"'; 
 6036:                     }
 6037:                     $output .= '<br /><div id="notified"'.$style.'>'.
 6038:                                &mt('Personnel to be notified when an enrollment request needs approval, or has been approved:').'&nbsp;'.
 6039:                                &Apache::loncommon::start_data_table().
 6040:                                &Apache::loncommon::start_data_table_row();
 6041:                     my $count = 0;
 6042:                     my $numcols = 4;
 6043:                     foreach my $cc (sort(@ccs)) {
 6044:                         my $notifyon;
 6045:                         my ($ccuname,$ccudom) = split(/:/,$cc);
 6046:                         if ($notified{$cc}) {
 6047:                             $notifyon = ' checked="checked" ';
 6048:                         }
 6049:                         if ($count && !$count%$numcols) {
 6050:                             $output .= &Apache::loncommon::end_data_table_row().
 6051:                                        &Apache::loncommon::start_data_table_row()
 6052:                         }
 6053:                         $output .= '<td><span class="LC_nobreak"><label>'.
 6054:                                    '<input type="checkbox" name="selfenroll_notify"'.$notifyon.' value="'.$cc.'" />'.
 6055:                                    &Apache::loncommon::plainname($ccuname,$ccudom).
 6056:                                    '</label></span></td>';
 6057:                         $count ++;
 6058:                     }
 6059:                     my $rem = $count%$numcols;
 6060:                     if ($rem) {
 6061:                         my $emptycols = $numcols - $rem;
 6062:                         for (my $i=0; $i<$emptycols; $i++) { 
 6063:                             $output .= '<td>&nbsp;</td>';
 6064:                         }
 6065:                     }
 6066:                     $output .= &Apache::loncommon::end_data_table_row().
 6067:                                &Apache::loncommon::end_data_table().
 6068:                                '</div>';
 6069:                 }
 6070:             } elsif ($item eq 'limit') {
 6071:                 my ($crslimit,$selflimit,$nolimit,$currlim,$currcap);
 6072:                 if (ref($currsettings) eq 'HASH') {
 6073:                     $currlim = $currsettings->{'selfenroll_limit'};
 6074:                     $currcap = $currsettings->{'selfenroll_cap'};
 6075:                 }
 6076:                 if ($noedit{$item}) {
 6077:                     if (($currlim eq 'allstudents') || ($currlim eq 'selfenrolled')) {
 6078:                         if ($currlim eq 'allstudents') {
 6079:                             $output .= &mt('Limit by total students');
 6080:                         } elsif ($currlim eq 'selfenrolled') {
 6081:                             $output .= &mt('Limit by total self-enrolled students');
 6082:                         }
 6083:                         $output .= ' '.&mt('Maximum: [_1]',$currcap).
 6084:                                    '<br />'.&mt('(Set by Domain Coordinator)');
 6085:                     } else {
 6086:                         $output .= &mt('No limit').'<br />'.&mt('(Set by Domain Coordinator)');
 6087:                     }
 6088:                     next;
 6089:                 }
 6090:                 if ($currlim eq 'allstudents') {
 6091:                     $crslimit = ' checked="checked" ';
 6092:                     $selflimit = ' ';
 6093:                     $nolimit = ' ';
 6094:                 } elsif ($currlim eq 'selfenrolled') {
 6095:                     $crslimit = ' ';
 6096:                     $selflimit = ' checked="checked" ';
 6097:                     $nolimit = ' '; 
 6098:                 } else {
 6099:                     $crslimit = ' ';
 6100:                     $selflimit = ' ';
 6101:                     $nolimit = ' checked="checked" ';
 6102:                 }
 6103:                 $output .= '<table><tr><td><label>'.
 6104:                            '<input type="radio" name="selfenroll_limit" value="none"'.$nolimit.'/>'.
 6105:                            &mt('No limit').'</label></td><td><label>'.
 6106:                            '<input type="radio" name="selfenroll_limit" value="allstudents"'.$crslimit.'/>'.
 6107:                            &mt('Limit by total students').'</label></td><td><label>'.
 6108:                            '<input type="radio" name="selfenroll_limit" value="selfenrolled"'.$selflimit.'/>'.
 6109:                            &mt('Limit by total self-enrolled students').
 6110:                            '</td></tr><tr>'.
 6111:                            '<td>&nbsp;</td><td colspan="2"><span class="LC_nobreak">'.
 6112:                            ('&nbsp;'x3).&mt('Maximum number allowed: ').
 6113:                            '<input type="text" name="selfenroll_cap" size = "5" value="'.$currcap.'" /></td></tr></table>';
 6114:             }
 6115:             $output .= &Apache::lonhtmlcommon::row_closure(1);
 6116:         }
 6117:     }
 6118:     $output .= &Apache::lonhtmlcommon::end_pick_box().
 6119:                '<br /><input type="button" name="selfenrollconf" value="'
 6120:                .&mt('Save').'" onclick="validate_types(this.form);" />'
 6121:                .'<input type="hidden" name="action" value="selfenroll" />'
 6122:                .'<input type="hidden" name="state" value="done" />'."\n".
 6123:                $additional.'</form>';
 6124:     $r->print($output);
 6125:     return;
 6126: }
 6127: 
 6128: sub get_noedit_fields {
 6129:     my ($cdom,$cnum,$crstype,$row) = @_;
 6130:     my %noedit;
 6131:     if (ref($row) eq 'ARRAY') {
 6132:         my %settings = &Apache::lonnet::get('environment',['internal.coursecode','internal.textbook',
 6133:                                                            'internal.selfenrollmgrdc',
 6134:                                                            'internal.selfenrollmgrcc'],$cdom,$cnum);
 6135:         my $type = &Apache::lonuserutils::get_extended_type($cdom,$cnum,$crstype,\%settings);
 6136:         my (%specific_managebydc,%specific_managebycc,%default_managebydc);
 6137:         map { $specific_managebydc{$_} = 1; } (split(/,/,$settings{'internal.selfenrollmgrdc'}));
 6138:         map { $specific_managebycc{$_} = 1; } (split(/,/,$settings{'internal.selfenrollmgrcc'}));
 6139:         my %domdefaults = &Apache::lonnet::get_domain_defaults($cdom);
 6140:         map { $default_managebydc{$_} = 1; } (split(/,/,$domdefaults{$type.'selfenrolladmdc'}));
 6141: 
 6142:         foreach my $item (@{$row}) {
 6143:             next if ($specific_managebycc{$item});
 6144:             if (($specific_managebydc{$item}) || ($default_managebydc{$item})) {
 6145:                 $noedit{$item} = 1;
 6146:             }
 6147:         }
 6148:     }
 6149:     return %noedit;
 6150: } 
 6151: 
 6152: sub visible_in_stdcat {
 6153:     my ($cdom,$cnum,$domconf) = @_;
 6154:     my ($cathash,%settable,@vismsgs,$cansetvis,$visible);
 6155:     unless (ref($domconf) eq 'HASH') {
 6156:         return ($visible,$cansetvis,\@vismsgs);
 6157:     }
 6158:     if (ref($domconf->{'coursecategories'}) eq 'HASH') {
 6159:         if ($domconf->{'coursecategories'}{'togglecats'} eq 'crs') {
 6160:             $settable{'togglecats'} = 1;
 6161:         }
 6162:         if ($domconf->{'coursecategories'}{'categorize'} eq 'crs') {
 6163:             $settable{'categorize'} = 1;
 6164:         }
 6165:         $cathash = $domconf->{'coursecategories'}{'cats'};
 6166:     }
 6167:     if ($settable{'togglecats'} && $settable{'categorize'}) {
 6168:         $cansetvis = &mt('You are able to both assign a course category and choose to exclude this course from the catalog.');   
 6169:     } elsif ($settable{'togglecats'}) {
 6170:         $cansetvis = &mt('You are able to choose to exclude this course from the catalog, but only a Domain Coordinator may assign a course category.'); 
 6171:     } elsif ($settable{'categorize'}) {
 6172:         $cansetvis = &mt('You may assign a course category, but only a Domain Coordinator may choose to exclude this course from the catalog.');  
 6173:     } else {
 6174:         $cansetvis = &mt('Only a Domain Coordinator may assign a course category or choose to exclude this course from the catalog.'); 
 6175:     }
 6176:      
 6177:     my %currsettings =
 6178:         &Apache::lonnet::get('environment',['hidefromcat','categories','internal.coursecode'],
 6179:                              $cdom,$cnum);
 6180:     $visible = 0;
 6181:     if ($currsettings{'internal.coursecode'} ne '') {
 6182:         if (ref($domconf->{'coursecategories'}) eq 'HASH') {
 6183:             $cathash = $domconf->{'coursecategories'}{'cats'};
 6184:             if (ref($cathash) eq 'HASH') {
 6185:                 if ($cathash->{'instcode::0'} eq '') {
 6186:                     push(@vismsgs,'dc_addinst'); 
 6187:                 } else {
 6188:                     $visible = 1;
 6189:                 }
 6190:             } else {
 6191:                 $visible = 1;
 6192:             }
 6193:         } else {
 6194:             $visible = 1;
 6195:         }
 6196:     } else {
 6197:         if (ref($cathash) eq 'HASH') {
 6198:             if ($cathash->{'instcode::0'} ne '') {
 6199:                 push(@vismsgs,'dc_instcode');
 6200:             }
 6201:         } else {
 6202:             push(@vismsgs,'dc_instcode');
 6203:         }
 6204:     }
 6205:     if ($currsettings{'categories'} ne '') {
 6206:         my $cathash;
 6207:         if (ref($domconf->{'coursecategories'}) eq 'HASH') {
 6208:             $cathash = $domconf->{'coursecategories'}{'cats'};
 6209:             if (ref($cathash) eq 'HASH') {
 6210:                 if (keys(%{$cathash}) == 0) {
 6211:                     push(@vismsgs,'dc_catalog');
 6212:                 } elsif ((keys(%{$cathash}) == 1) && ($cathash->{'instcode::0'} ne '')) {
 6213:                     push(@vismsgs,'dc_categories');
 6214:                 } else {
 6215:                     my @currcategories = split('&',$currsettings{'categories'});
 6216:                     my $matched = 0;
 6217:                     foreach my $cat (@currcategories) {
 6218:                         if ($cathash->{$cat} ne '') {
 6219:                             $visible = 1;
 6220:                             $matched = 1;
 6221:                             last;
 6222:                         }
 6223:                     }
 6224:                     if (!$matched) {
 6225:                         if ($settable{'categorize'}) { 
 6226:                             push(@vismsgs,'chgcat');
 6227:                         } else {
 6228:                             push(@vismsgs,'dc_chgcat');
 6229:                         }
 6230:                     }
 6231:                 }
 6232:             }
 6233:         }
 6234:     } else {
 6235:         if (ref($cathash) eq 'HASH') {
 6236:             if ((keys(%{$cathash}) > 1) || 
 6237:                 (keys(%{$cathash}) == 1) && ($cathash->{'instcode::0'} eq '')) {
 6238:                 if ($settable{'categorize'}) {
 6239:                     push(@vismsgs,'addcat');
 6240:                 } else {
 6241:                     push(@vismsgs,'dc_addcat');
 6242:                 }
 6243:             }
 6244:         }
 6245:     }
 6246:     if ($currsettings{'hidefromcat'} eq 'yes') {
 6247:         $visible = 0;
 6248:         if ($settable{'togglecats'}) {
 6249:             unshift(@vismsgs,'unhide');
 6250:         } else {
 6251:             unshift(@vismsgs,'dc_unhide')
 6252:         }
 6253:     }
 6254:     return ($visible,$cansetvis,\@vismsgs);
 6255: }
 6256: 
 6257: sub cat_visibility {
 6258:     my %visactions = &Apache::lonlocal::texthash(
 6259:                    vis => 'This course/community currently appears in the Course/Community Catalog for this domain.',
 6260:                    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.',
 6261:                    miss => 'This course/community does not currently appear in the Course/Community Catalog for this domain.',
 6262:                    none => 'Display of a course catalog is disabled for this domain.',
 6263:                    yous => 'You should remedy this if you plan to allow self-enrollment, otherwise students will have difficulty finding this course.',
 6264:                    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.',
 6265:                    make => 'Make any changes to self-enrollment settings below, click "Save", then take action to include the course in the Catalog:',
 6266:                    take => 'Take the following action to ensure the course appears in the Catalog:',
 6267:                    dc_chgconf => 'Ask a domain coordinator to change the Catalog type for this domain.',
 6268:                    dc_setcode => 'Ask a domain coordinator to assign a six character code to the course',
 6269:                    dc_unhide  => 'Ask a domain coordinator to change the "Exclude from course catalog" setting.',
 6270:                    dc_addinst => 'Ask a domain coordinator to enable display the catalog of "Official courses (with institutional codes)".',
 6271:                    dc_instcode => 'Ask a domain coordinator to assign an institutional code (if this is an official course).',
 6272:                    dc_catalog  => 'Ask a domain coordinator to enable or create at least one course category in the domain.',
 6273:                    dc_categories => 'Ask a domain coordinator to create a hierarchy of categories and sub categories for courses in the domain.',
 6274:                    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',
 6275:                    dc_addcat => 'Ask a domain coordinator to assign a category to the course.',
 6276:     );
 6277:     $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>"');
 6278:     $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>"');
 6279:     $visactions{'addcat'} = &mt('Use [_1]Categorize course[_2] to assign a category to the course.','"<a href="/adm/courseprefs?phase=display&actions=courseinfo">','</a>"');
 6280:     return \%visactions;
 6281: }
 6282: 
 6283: sub new_selfenroll_dom_row {
 6284:     my ($newdom,$num) = @_;
 6285:     my $domdesc = &Apache::lonnet::domain($newdom);
 6286:     my $output;
 6287:     if ($domdesc ne '') {
 6288:         $output .= &Apache::loncommon::start_data_table_row()
 6289:                    .'<td valign="top"><span class="LC_nobreak">'.&mt('Domain:').'&nbsp;<b>'.$domdesc
 6290:                    .' ('.$newdom.')</b><input type="hidden" name="selfenroll_dom_'.$num
 6291:                    .'" value="'.$newdom.'" /></span><br />'
 6292:                    .'<span class="LC_nobreak"><label><input type="checkbox" '
 6293:                    .'name="selfenroll_activate" value="'.$num.'" '
 6294:                    .'onchange="javascript:update_types('
 6295:                    ."'selfenroll_activate','$num'".');" />'
 6296:                    .&mt('Activate').'</label></span></td>';
 6297:         my @currinsttypes;
 6298:         $output .= '<td>'.&mt('User types:').'<br />'
 6299:                    .&selfenroll_inst_types($num,$newdom,\@currinsttypes).'</td>'
 6300:                    .&Apache::loncommon::end_data_table_row();
 6301:     }
 6302:     return $output;
 6303: }
 6304: 
 6305: sub selfenroll_inst_types {
 6306:     my ($num,$currdom,$currinsttypes) = @_;
 6307:     my $output;
 6308:     my $numinrow = 4;
 6309:     my $count = 0;
 6310:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($currdom);
 6311:     my $othervalue = 'any';
 6312:     if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 6313:         if (keys(%{$usertypes}) > 0) {
 6314:             $othervalue = 'other';
 6315:         }
 6316:         $output .= '<table><tr>';
 6317:         foreach my $type (@{$types}) {
 6318:             if (($count > 0) && ($count%$numinrow == 0)) {
 6319:                 $output .= '</tr><tr>';
 6320:             }
 6321:             if (defined($usertypes->{$type})) {
 6322:                 my $esc_type = &escape($type);
 6323:                 $output .= '<td><span class="LC_nobreak"><label><input type = "checkbox" value="'.
 6324:                            $esc_type.'" ';
 6325:                 if (ref($currinsttypes) eq 'ARRAY') {
 6326:                     if (@{$currinsttypes} > 0) {
 6327:                         if (grep(/^any$/,@{$currinsttypes})) {
 6328:                             $output .= 'checked="checked"';
 6329:                         } elsif (grep(/^\Q$esc_type\E$/,@{$currinsttypes})) {
 6330:                             $output .= 'checked="checked"';
 6331:                         }
 6332:                     } else {
 6333:                         $output .= 'checked="checked"';
 6334:                     }
 6335:                 }
 6336:                 $output .= ' name="selfenroll_types_'.$num.'" />'.$usertypes->{$type}.'</label></span></td>';
 6337:             }
 6338:             $count ++;
 6339:         }
 6340:         if (($count > 0) && ($count%$numinrow == 0)) {
 6341:             $output .= '</tr><tr>';
 6342:         }
 6343:         $output .= '<td><span class="LC_nobreak"><label><input type = "checkbox" value="'.$othervalue.'"';
 6344:         if (ref($currinsttypes) eq 'ARRAY') {
 6345:             if (@{$currinsttypes} > 0) {
 6346:                 if (grep(/^any$/,@{$currinsttypes})) { 
 6347:                     $output .= ' checked="checked"';
 6348:                 } elsif ($othervalue eq 'other') {
 6349:                     if (grep(/^\Q$othervalue\E$/,@{$currinsttypes})) {
 6350:                         $output .= ' checked="checked"';
 6351:                     }
 6352:                 }
 6353:             } else {
 6354:                 $output .= ' checked="checked"';
 6355:             }
 6356:         } else {
 6357:             $output .= ' checked="checked"';
 6358:         }
 6359:         $output .= ' name="selfenroll_types_'.$num.'" />'.$othertitle.'</label></span></td></tr></table>';
 6360:     }
 6361:     return $output;
 6362: }
 6363: 
 6364: sub selfenroll_date_forms {
 6365:     my ($startform,$endform) = @_;
 6366:     my $output .= &Apache::lonhtmlcommon::start_pick_box()."\n".
 6367:                   &Apache::lonhtmlcommon::row_title(&mt('Start date'),
 6368:                                                     'LC_oddrow_value')."\n".
 6369:                   $startform."\n".
 6370:                   &Apache::lonhtmlcommon::row_closure(1).
 6371:                   &Apache::lonhtmlcommon::row_title(&mt('End date'),
 6372:                                                    'LC_oddrow_value')."\n".
 6373:                   $endform."\n".
 6374:                   &Apache::lonhtmlcommon::row_closure(1).
 6375:                   &Apache::lonhtmlcommon::end_pick_box();
 6376:     return $output;
 6377: }
 6378: 
 6379: sub print_userchangelogs_display {
 6380:     my ($r,$context,$permission) = @_;
 6381:     my $formname = 'rolelog';
 6382:     my ($username,$domain,$crstype,%roleslog);
 6383:     if ($context eq 'domain') {
 6384:         $domain = $env{'request.role.domain'};
 6385:         %roleslog=&Apache::lonnet::dump_dom('nohist_rolelog',$domain);
 6386:     } else {
 6387:         if ($context eq 'course') { 
 6388:             $domain = $env{'course.'.$env{'request.course.id'}.'.domain'};
 6389:             $username = $env{'course.'.$env{'request.course.id'}.'.num'};
 6390:             $crstype = &Apache::loncommon::course_type();
 6391:             my %saveable_parameters = ('show' => 'scalar',);
 6392:             &Apache::loncommon::store_course_settings('roles_log',
 6393:                                                       \%saveable_parameters);
 6394:             &Apache::loncommon::restore_course_settings('roles_log',
 6395:                                                         \%saveable_parameters);
 6396:         } elsif ($context eq 'author') {
 6397:             $domain = $env{'user.domain'}; 
 6398:             if ($env{'request.role'} =~ m{^au\./\Q$domain\E/$}) {
 6399:                 $username = $env{'user.name'};
 6400:             } else {
 6401:                 undef($domain);
 6402:             }
 6403:         }
 6404:         if ($domain ne '' && $username ne '') { 
 6405:             %roleslog=&Apache::lonnet::dump('nohist_rolelog',$domain,$username);
 6406:         }
 6407:     }
 6408:     if ((keys(%roleslog))[0]=~/^error\:/) { undef(%roleslog); }
 6409: 
 6410:     # set defaults
 6411:     my $now = time();
 6412:     my $defstart = $now - (7*24*3600); #7 days ago 
 6413:     my %defaults = (
 6414:                      page               => '1',
 6415:                      show               => '10',
 6416:                      role               => 'any',
 6417:                      chgcontext         => 'any',
 6418:                      rolelog_start_date => $defstart,
 6419:                      rolelog_end_date   => $now,
 6420:                    );
 6421:     my $more_records = 0;
 6422: 
 6423:     # set current
 6424:     my %curr;
 6425:     foreach my $item ('show','page','role','chgcontext') {
 6426:         $curr{$item} = $env{'form.'.$item};
 6427:     }
 6428:     my ($startdate,$enddate) = 
 6429:         &Apache::lonuserutils::get_dates_from_form('rolelog_start_date','rolelog_end_date');
 6430:     $curr{'rolelog_start_date'} = $startdate;
 6431:     $curr{'rolelog_end_date'} = $enddate;
 6432:     foreach my $key (keys(%defaults)) {
 6433:         if ($curr{$key} eq '') {
 6434:             $curr{$key} = $defaults{$key};
 6435:         }
 6436:     }
 6437:     my (%whodunit,%changed,$version);
 6438:     ($version) = ($r->dir_config('lonVersion') =~ /^([\d\.]+)\-/);
 6439:     my ($minshown,$maxshown);
 6440:     $minshown = 1;
 6441:     my $count = 0;
 6442:     if ($curr{'show'} ne &mt('all')) { 
 6443:         $maxshown = $curr{'page'} * $curr{'show'};
 6444:         if ($curr{'page'} > 1) {
 6445:             $minshown = 1 + ($curr{'page'} - 1) * $curr{'show'};
 6446:         }
 6447:     }
 6448: 
 6449:     # Form Header
 6450:     $r->print('<form action="/adm/createuser" method="post" name="'.$formname.'">'.
 6451:               &role_display_filter($context,$formname,$domain,$username,\%curr,
 6452:                                    $version,$crstype));
 6453: 
 6454:     # Create navigation
 6455:     my ($nav_script,$nav_links) = &userlogdisplay_nav($formname,\%curr,$more_records);
 6456:     my $showntableheader = 0;
 6457: 
 6458:     # Table Header
 6459:     my $tableheader = 
 6460:         &Apache::loncommon::start_data_table_header_row()
 6461:        .'<th>&nbsp;</th>'
 6462:        .'<th>'.&mt('When').'</th>'
 6463:        .'<th>'.&mt('Who made the change').'</th>'
 6464:        .'<th>'.&mt('Changed User').'</th>'
 6465:        .'<th>'.&mt('Role').'</th>';
 6466: 
 6467:     if ($context eq 'course') {
 6468:         $tableheader .= '<th>'.&mt('Section').'</th>';
 6469:     }
 6470:     $tableheader .=
 6471:         '<th>'.&mt('Context').'</th>'
 6472:        .'<th>'.&mt('Start').'</th>'
 6473:        .'<th>'.&mt('End').'</th>'
 6474:        .&Apache::loncommon::end_data_table_header_row();
 6475: 
 6476:     # Display user change log data
 6477:     foreach my $id (sort { $roleslog{$b}{'exe_time'}<=>$roleslog{$a}{'exe_time'} } (keys(%roleslog))) {
 6478:         next if (($roleslog{$id}{'exe_time'} < $curr{'rolelog_start_date'}) ||
 6479:                  ($roleslog{$id}{'exe_time'} > $curr{'rolelog_end_date'}));
 6480:         if ($curr{'show'} ne &mt('all')) {
 6481:             if ($count >= $curr{'page'} * $curr{'show'}) {
 6482:                 $more_records = 1;
 6483:                 last;
 6484:             }
 6485:         }
 6486:         if ($curr{'role'} ne 'any') {
 6487:             next if ($roleslog{$id}{'logentry'}{'role'} ne $curr{'role'}); 
 6488:         }
 6489:         if ($curr{'chgcontext'} ne 'any') {
 6490:             if ($curr{'chgcontext'} eq 'selfenroll') {
 6491:                 next if (!$roleslog{$id}{'logentry'}{'selfenroll'});
 6492:             } else {
 6493:                 next if ($roleslog{$id}{'logentry'}{'context'} ne $curr{'chgcontext'});
 6494:             }
 6495:         }
 6496:         $count ++;
 6497:         next if ($count < $minshown);
 6498:         unless ($showntableheader) {
 6499:             $r->print($nav_script
 6500:                      .$nav_links
 6501:                      .&Apache::loncommon::start_data_table()
 6502:                      .$tableheader);
 6503:             $r->rflush();
 6504:             $showntableheader = 1;
 6505:         }
 6506:         if ($whodunit{$roleslog{$id}{'exe_uname'}.':'.$roleslog{$id}{'exe_udom'}} eq '') {
 6507:             $whodunit{$roleslog{$id}{'exe_uname'}.':'.$roleslog{$id}{'exe_udom'}} =
 6508:                 &Apache::loncommon::plainname($roleslog{$id}{'exe_uname'},$roleslog{$id}{'exe_udom'});
 6509:         }
 6510:         if ($changed{$roleslog{$id}{'uname'}.':'.$roleslog{$id}{'udom'}} eq '') {
 6511:             $changed{$roleslog{$id}{'uname'}.':'.$roleslog{$id}{'udom'}} =
 6512:                 &Apache::loncommon::plainname($roleslog{$id}{'uname'},$roleslog{$id}{'udom'});
 6513:         }
 6514:         my $sec = $roleslog{$id}{'logentry'}{'section'};
 6515:         if ($sec eq '') {
 6516:             $sec = &mt('None');
 6517:         }
 6518:         my ($rolestart,$roleend);
 6519:         if ($roleslog{$id}{'delflag'}) {
 6520:             $rolestart = &mt('deleted');
 6521:             $roleend = &mt('deleted');
 6522:         } else {
 6523:             $rolestart = $roleslog{$id}{'logentry'}{'start'};
 6524:             $roleend = $roleslog{$id}{'logentry'}{'end'};
 6525:             if ($rolestart eq '' || $rolestart == 0) {
 6526:                 $rolestart = &mt('No start date'); 
 6527:             } else {
 6528:                 $rolestart = &Apache::lonlocal::locallocaltime($rolestart);
 6529:             }
 6530:             if ($roleend eq '' || $roleend == 0) { 
 6531:                 $roleend = &mt('No end date');
 6532:             } else {
 6533:                 $roleend = &Apache::lonlocal::locallocaltime($roleend);
 6534:             }
 6535:         }
 6536:         my $chgcontext = $roleslog{$id}{'logentry'}{'context'};
 6537:         if ($roleslog{$id}{'logentry'}{'selfenroll'}) {
 6538:             $chgcontext = 'selfenroll';
 6539:         }
 6540:         my %lt = &rolechg_contexts($context,$crstype);
 6541:         if ($chgcontext ne '' && $lt{$chgcontext} ne '') {
 6542:             $chgcontext = $lt{$chgcontext};
 6543:         }
 6544:         $r->print(
 6545:             &Apache::loncommon::start_data_table_row()
 6546:            .'<td>'.$count.'</td>'
 6547:            .'<td>'.&Apache::lonlocal::locallocaltime($roleslog{$id}{'exe_time'}).'</td>'
 6548:            .'<td>'.$whodunit{$roleslog{$id}{'exe_uname'}.':'.$roleslog{$id}{'exe_udom'}}.'</td>'
 6549:            .'<td>'.$changed{$roleslog{$id}{'uname'}.':'.$roleslog{$id}{'udom'}}.'</td>'
 6550:            .'<td>'.&Apache::lonnet::plaintext($roleslog{$id}{'logentry'}{'role'},$crstype).'</td>');
 6551:         if ($context eq 'course') { 
 6552:             $r->print('<td>'.$sec.'</td>');
 6553:         }
 6554:         $r->print(
 6555:             '<td>'.$chgcontext.'</td>'
 6556:            .'<td>'.$rolestart.'</td>'
 6557:            .'<td>'.$roleend.'</td>'
 6558:            .&Apache::loncommon::end_data_table_row()."\n");
 6559:     }
 6560: 
 6561:     if ($showntableheader) { # Table footer, if content displayed above
 6562:         $r->print(&Apache::loncommon::end_data_table()
 6563:                  .$nav_links);
 6564:     } else { # No content displayed above
 6565:         $r->print('<p class="LC_info">'
 6566:                  .&mt('There are no records to display.')
 6567:                  .'</p>'
 6568:         );
 6569:     }
 6570: 
 6571:     # Form Footer
 6572:     $r->print( 
 6573:         '<input type="hidden" name="page" value="'.$curr{'page'}.'" />'
 6574:        .'<input type="hidden" name="action" value="changelogs" />'
 6575:        .'</form>');
 6576:     return;
 6577: }
 6578: 
 6579: sub userlogdisplay_nav {
 6580:     my ($formname,$curr,$more_records) = @_;
 6581:     my ($nav_script,$nav_links);
 6582:     if (ref($curr) eq 'HASH') {
 6583:         # Create Navigation:
 6584:         # Navigation Script
 6585:         $nav_script = <<"ENDSCRIPT";
 6586: <script type="text/javascript">
 6587: // <![CDATA[
 6588: function chgPage(caller) {
 6589:     if (caller == 'previous') {
 6590:         document.$formname.page.value --;
 6591:     }
 6592:     if (caller == 'next') {
 6593:         document.$formname.page.value ++;
 6594:     }
 6595:     document.$formname.submit();
 6596:     return;
 6597: }
 6598: // ]]>
 6599: </script>
 6600: ENDSCRIPT
 6601:         # Navigation Buttons
 6602:         $nav_links = '<p>';
 6603:         if (($curr->{'page'} > 1) || ($more_records)) {
 6604:             if ($curr->{'page'} > 1) {
 6605:                 $nav_links .= '<input type="button"'
 6606:                              .' onclick="javascript:chgPage('."'previous'".');"'
 6607:                              .' value="'.&mt('Previous [_1] changes',$curr->{'show'})
 6608:                              .'" /> ';
 6609:             }
 6610:             if ($more_records) {
 6611:                 $nav_links .= '<input type="button"'
 6612:                              .' onclick="javascript:chgPage('."'next'".');"'
 6613:                              .' value="'.&mt('Next [_1] changes',$curr->{'show'})
 6614:                              .'" />';
 6615:             }
 6616:         }
 6617:         $nav_links .= '</p>';
 6618:     }
 6619:     return ($nav_script,$nav_links);
 6620: }
 6621: 
 6622: sub role_display_filter {
 6623:     my ($context,$formname,$cdom,$cnum,$curr,$version,$crstype) = @_;
 6624:     my $lctype;
 6625:     if ($context eq 'course') {
 6626:         $lctype = lc($crstype);
 6627:     }
 6628:     my $nolink = 1;
 6629:     my $output = '<table><tr><td valign="top">'.
 6630:                  '<span class="LC_nobreak"><b>'.&mt('Changes/page:').'</b></span><br />'.
 6631:                  &Apache::lonmeta::selectbox('show',$curr->{'show'},undef,
 6632:                                               (&mt('all'),5,10,20,50,100,1000,10000)).
 6633:                  '</td><td>&nbsp;&nbsp;</td>';
 6634:     my $startform =
 6635:         &Apache::lonhtmlcommon::date_setter($formname,'rolelog_start_date',
 6636:                                             $curr->{'rolelog_start_date'},undef,
 6637:                                             undef,undef,undef,undef,undef,undef,$nolink);
 6638:     my $endform =
 6639:         &Apache::lonhtmlcommon::date_setter($formname,'rolelog_end_date',
 6640:                                             $curr->{'rolelog_end_date'},undef,
 6641:                                             undef,undef,undef,undef,undef,undef,$nolink);
 6642:     my %lt = &rolechg_contexts($context,$crstype);
 6643:     $output .= '<td valign="top"><b>'.&mt('Window during which changes occurred:').'</b><br />'.
 6644:                '<table><tr><td>'.&mt('After:').
 6645:                '</td><td>'.$startform.'</td></tr>'.
 6646:                '<tr><td>'.&mt('Before:').'</td>'.
 6647:                '<td>'.$endform.'</td></tr></table>'.
 6648:                '</td>'.
 6649:                '<td>&nbsp;&nbsp;</td>'.
 6650:                '<td valign="top"><b>'.&mt('Role:').'</b><br />'.
 6651:                '<select name="role"><option value="any"';
 6652:     if ($curr->{'role'} eq 'any') {
 6653:         $output .= ' selected="selected"';
 6654:     }
 6655:     $output .=  '>'.&mt('Any').'</option>'."\n";
 6656:     my @roles = &Apache::lonuserutils::roles_by_context($context,1,$crstype);
 6657:     foreach my $role (@roles) {
 6658:         my $plrole;
 6659:         if ($role eq 'cr') {
 6660:             $plrole = &mt('Custom Role');
 6661:         } else {
 6662:             $plrole=&Apache::lonnet::plaintext($role,$crstype);
 6663:         }
 6664:         my $selstr = '';
 6665:         if ($role eq $curr->{'role'}) {
 6666:             $selstr = ' selected="selected"';
 6667:         }
 6668:         $output .= '  <option value="'.$role.'"'.$selstr.'>'.$plrole.'</option>';
 6669:     }
 6670:     $output .= '</select></td>'.
 6671:                '<td>&nbsp;&nbsp;</td>'.
 6672:                '<td valign="top"><b>'.
 6673:                &mt('Context:').'</b><br /><select name="chgcontext">';
 6674:     my @posscontexts;
 6675:     if ($context eq 'course') {
 6676:         @posscontexts = ('any','automated','updatenow','createcourse','course','domain','selfenroll','requestcourses');
 6677:     } elsif ($context eq 'domain') {
 6678:         @posscontexts = ('any','domain','requestauthor','domconfig','server');
 6679:     } else {
 6680:         @posscontexts = ('any','author','domain');
 6681:     } 
 6682:     foreach my $chgtype (@posscontexts) {
 6683:         my $selstr = '';
 6684:         if ($curr->{'chgcontext'} eq $chgtype) {
 6685:             $selstr = ' selected="selected"';
 6686:         }
 6687:         if ($context eq 'course') {
 6688:             if (($chgtype eq 'automated') || ($chgtype eq 'updatenow')) {
 6689:                 next if (!&Apache::lonnet::auto_run($cnum,$cdom));
 6690:             }
 6691:         }
 6692:         $output .= '<option value="'.$chgtype.'"'.$selstr.'>'.$lt{$chgtype}.'</option>'."\n";
 6693:     }
 6694:     $output .= '</select></td>'
 6695:               .'</tr></table>';
 6696: 
 6697:     # Update Display button
 6698:     $output .= '<p>'
 6699:               .'<input type="submit" value="'.&mt('Update Display').'" />'
 6700:               .'</p>';
 6701: 
 6702:     # Server version info
 6703:     my $needsrev = '2.11.0';
 6704:     if ($context eq 'course') {
 6705:         $needsrev = '2.7.0';
 6706:     }
 6707:     
 6708:     $output .= '<p class="LC_info">'
 6709:               .&mt('Only changes made from servers running LON-CAPA [_1] or later are displayed.'
 6710:                   ,$needsrev);
 6711:     if ($version) {
 6712:         $output .= ' '.&mt('This LON-CAPA server is version [_1]',$version);
 6713:     }
 6714:     $output .= '</p><hr />';
 6715:     return $output;
 6716: }
 6717: 
 6718: sub rolechg_contexts {
 6719:     my ($context,$crstype) = @_;
 6720:     my %lt;
 6721:     if ($context eq 'course') {
 6722:         %lt = &Apache::lonlocal::texthash (
 6723:                                              any          => 'Any',
 6724:                                              automated    => 'Automated Enrollment',
 6725:                                              updatenow    => 'Roster Update',
 6726:                                              createcourse => 'Course Creation',
 6727:                                              course       => 'User Management in course',
 6728:                                              domain       => 'User Management in domain',
 6729:                                              selfenroll   => 'Self-enrolled',
 6730:                                              requestcourses => 'Course Request',
 6731:                                          );
 6732:         if ($crstype eq 'Community') {
 6733:             $lt{'createcourse'} = &mt('Community Creation');
 6734:             $lt{'course'} = &mt('User Management in community');
 6735:             $lt{'requestcourses'} = &mt('Community Request');
 6736:         }
 6737:     } elsif ($context eq 'domain') {
 6738:         %lt = &Apache::lonlocal::texthash (
 6739:                                              any           => 'Any',
 6740:                                              domain        => 'User Management in domain',
 6741:                                              requestauthor => 'Authoring Request',
 6742:                                              server        => 'Command line script (DC role)',
 6743:                                              domconfig     => 'Self-enrolled',
 6744:                                          );
 6745:     } else {
 6746:         %lt = &Apache::lonlocal::texthash (
 6747:                                              any    => 'Any',
 6748:                                              domain => 'User Management in domain',
 6749:                                              author => 'User Management by author',
 6750:                                          );
 6751:     } 
 6752:     return %lt;
 6753: }
 6754: 
 6755: #-------------------------------------------------- functions for &phase_two
 6756: sub user_search_result {
 6757:     my ($context,$srch) = @_;
 6758:     my %allhomes;
 6759:     my %inst_matches;
 6760:     my %srch_results;
 6761:     my ($response,$currstate,$forcenewuser,$dirsrchres);
 6762:     $srch->{'srchterm'} =~ s/\s+/ /g;
 6763:     if ($srch->{'srchby'} !~ /^(uname|lastname|lastfirst)$/) {
 6764:         $response = &mt('Invalid search.');
 6765:     }
 6766:     if ($srch->{'srchin'} !~ /^(crs|dom|alc|instd)$/) {
 6767:         $response = &mt('Invalid search.');
 6768:     }
 6769:     if ($srch->{'srchtype'} !~ /^(exact|contains|begins)$/) {
 6770:         $response = &mt('Invalid search.');
 6771:     }
 6772:     if ($srch->{'srchterm'} eq '') {
 6773:         $response = &mt('You must enter a search term.');
 6774:     }
 6775:     if ($srch->{'srchterm'} =~ /^\s+$/) {
 6776:         $response = &mt('Your search term must contain more than just spaces.');
 6777:     }
 6778:     if (($srch->{'srchin'} eq 'dom') || ($srch->{'srchin'} eq 'instd')) {
 6779:         if (($srch->{'srchdomain'} eq '') || 
 6780: 	    ! (&Apache::lonnet::domain($srch->{'srchdomain'}))) {
 6781:             $response = &mt('You must specify a valid domain when searching in a domain or institutional directory.')
 6782:         }
 6783:     }
 6784:     if (($srch->{'srchin'} eq 'dom') || ($srch->{'srchin'} eq 'crs') ||
 6785:         ($srch->{'srchin'} eq 'alc')) {
 6786:         if ($srch->{'srchby'} eq 'uname') {
 6787:             my $unamecheck = $srch->{'srchterm'};
 6788:             if ($srch->{'srchtype'} eq 'contains') {
 6789:                 if ($unamecheck !~ /^\w/) {
 6790:                     $unamecheck = 'a'.$unamecheck; 
 6791:                 }
 6792:             }
 6793:             if ($unamecheck !~ /^$match_username$/) {
 6794:                 $response = &mt('You must specify a valid username. Only the following are allowed: letters numbers - . @');
 6795:             }
 6796:         }
 6797:     }
 6798:     if ($response ne '') {
 6799:         $response = '<span class="LC_warning">'.$response.'</span><br />';
 6800:     }
 6801:     if ($srch->{'srchin'} eq 'instd') {
 6802:         my $instd_chk = &instdirectorysrch_check($srch);
 6803:         if ($instd_chk ne 'ok') {
 6804:             my $domd_chk = &domdirectorysrch_check($srch);
 6805:             $response .= '<span class="LC_warning">'.$instd_chk.'</span><br />';
 6806:             if ($domd_chk eq 'ok') {
 6807:                 $response .= &mt('You may want to search in the LON-CAPA domain instead of the institutional directory.');
 6808:             }
 6809:             $response .= '<br /><br />';
 6810:         }
 6811:     } else {
 6812:         unless (($context eq 'requestcrs') && ($srch->{'srchtype'} eq 'exact')) { 
 6813:             my $domd_chk = &domdirectorysrch_check($srch);
 6814:             if ($domd_chk ne 'ok') {
 6815:                 my $instd_chk = &instdirectorysrch_check($srch);
 6816:                 $response .= '<span class="LC_warning">'.$domd_chk.'</span><br />';
 6817:                 if ($instd_chk eq 'ok') {
 6818:                     $response .= &mt('You may want to search in the institutional directory instead of the LON-CAPA domain.');
 6819:                 }
 6820:                 $response .= '<br /><br />';
 6821:             }
 6822:         }
 6823:     }
 6824:     if ($response ne '') {
 6825:         return ($currstate,$response);
 6826:     }
 6827:     if ($srch->{'srchby'} eq 'uname') {
 6828:         if (($srch->{'srchin'} eq 'dom') || ($srch->{'srchin'} eq 'crs')) {
 6829:             if ($env{'form.forcenew'}) {
 6830:                 if ($srch->{'srchdomain'} ne $env{'request.role.domain'}) {
 6831:                     my $uhome=&Apache::lonnet::homeserver($srch->{'srchterm'},$srch->{'srchdomain'});
 6832:                     if ($uhome eq 'no_host') {
 6833:                         my $domdesc = &Apache::lonnet::domain($env{'request.role.domain'},'description');
 6834:                         my $showdom = &display_domain_info($env{'request.role.domain'});
 6835:                         $response = &mt('New users can only be created in the domain to which your current role belongs - [_1].',$showdom);
 6836:                     } else {
 6837:                         $currstate = 'modify';
 6838:                     }
 6839:                 } else {
 6840:                     $currstate = 'modify';
 6841:                 }
 6842:             } else {
 6843:                 if ($srch->{'srchin'} eq 'dom') {
 6844:                     if ($srch->{'srchtype'} eq 'exact') {
 6845:                         my $uhome=&Apache::lonnet::homeserver($srch->{'srchterm'},$srch->{'srchdomain'});
 6846:                         if ($uhome eq 'no_host') {
 6847:                             ($currstate,$response,$forcenewuser) =
 6848:                                 &build_search_response($context,$srch,%srch_results);
 6849:                         } else {
 6850:                             $currstate = 'modify';
 6851:                             my $uname = $srch->{'srchterm'};
 6852:                             my $udom = $srch->{'srchdomain'};
 6853:                             $srch_results{$uname.':'.$udom} =
 6854:                                 { &Apache::lonnet::get('environment',
 6855:                                                        ['firstname',
 6856:                                                         'lastname',
 6857:                                                         'permanentemail'],
 6858:                                                          $udom,$uname)
 6859:                                 };
 6860:                         }
 6861:                     } else {
 6862:                         %srch_results = &Apache::lonnet::usersearch($srch);
 6863:                         ($currstate,$response,$forcenewuser) =
 6864:                             &build_search_response($context,$srch,%srch_results);
 6865:                     }
 6866:                 } else {
 6867:                     my $courseusers = &get_courseusers();
 6868:                     if ($srch->{'srchtype'} eq 'exact') {
 6869:                         if (exists($courseusers->{$srch->{'srchterm'}.':'.$srch->{'srchdomain'}})) {
 6870:                             $currstate = 'modify';
 6871:                         } else {
 6872:                             ($currstate,$response,$forcenewuser) =
 6873:                                 &build_search_response($context,$srch,%srch_results);
 6874:                         }
 6875:                     } else {
 6876:                         foreach my $user (keys(%$courseusers)) {
 6877:                             my ($cuname,$cudomain) = split(/:/,$user);
 6878:                             if ($cudomain eq $srch->{'srchdomain'}) {
 6879:                                 my $matched = 0;
 6880:                                 if ($srch->{'srchtype'} eq 'begins') {
 6881:                                     if ($cuname =~ /^\Q$srch->{'srchterm'}\E/i) {
 6882:                                         $matched = 1;
 6883:                                     }
 6884:                                 } else {
 6885:                                     if ($cuname =~ /\Q$srch->{'srchterm'}\E/i) {
 6886:                                         $matched = 1;
 6887:                                     }
 6888:                                 }
 6889:                                 if ($matched) {
 6890:                                     $srch_results{$user} = 
 6891: 					{&Apache::lonnet::get('environment',
 6892: 							     ['firstname',
 6893: 							      'lastname',
 6894: 							      'permanentemail'],
 6895: 							      $cudomain,$cuname)};
 6896:                                 }
 6897:                             }
 6898:                         }
 6899:                         ($currstate,$response,$forcenewuser) =
 6900:                             &build_search_response($context,$srch,%srch_results);
 6901:                     }
 6902:                 }
 6903:             }
 6904:         } elsif ($srch->{'srchin'} eq 'alc') {
 6905:             $currstate = 'query';
 6906:         } elsif ($srch->{'srchin'} eq 'instd') {
 6907:             ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query($srch);
 6908:             if ($dirsrchres eq 'ok') {
 6909:                 ($currstate,$response,$forcenewuser) = 
 6910:                     &build_search_response($context,$srch,%srch_results);
 6911:             } else {
 6912:                 my $showdom = &display_domain_info($srch->{'srchdomain'});
 6913:                 $response = '<span class="LC_warning">'.
 6914:                     &mt('Institutional directory search is not available in domain: [_1]',$showdom).
 6915:                     '</span><br />'.
 6916:                     &mt('You may want to search in the LON-CAPA domain instead of the institutional directory.').
 6917:                     '<br /><br />'; 
 6918:             }
 6919:         }
 6920:     } else {
 6921:         if ($srch->{'srchin'} eq 'dom') {
 6922:             %srch_results = &Apache::lonnet::usersearch($srch);
 6923:             ($currstate,$response,$forcenewuser) = 
 6924:                 &build_search_response($context,$srch,%srch_results); 
 6925:         } elsif ($srch->{'srchin'} eq 'crs') {
 6926:             my $courseusers = &get_courseusers(); 
 6927:             foreach my $user (keys(%$courseusers)) {
 6928:                 my ($uname,$udom) = split(/:/,$user);
 6929:                 my %names = &Apache::loncommon::getnames($uname,$udom);
 6930:                 my %emails = &Apache::loncommon::getemails($uname,$udom);
 6931:                 if ($srch->{'srchby'} eq 'lastname') {
 6932:                     if ((($srch->{'srchtype'} eq 'exact') && 
 6933:                          ($names{'lastname'} eq $srch->{'srchterm'})) || 
 6934:                         (($srch->{'srchtype'} eq 'begins') &&
 6935:                          ($names{'lastname'} =~ /^\Q$srch->{'srchterm'}\E/i)) ||
 6936:                         (($srch->{'srchtype'} eq 'contains') &&
 6937:                          ($names{'lastname'} =~ /\Q$srch->{'srchterm'}\E/i))) {
 6938:                         $srch_results{$user} = {firstname => $names{'firstname'},
 6939:                                             lastname => $names{'lastname'},
 6940:                                             permanentemail => $emails{'permanentemail'},
 6941:                                            };
 6942:                     }
 6943:                 } elsif ($srch->{'srchby'} eq 'lastfirst') {
 6944:                     my ($srchlast,$srchfirst) = split(/,/,$srch->{'srchterm'});
 6945:                     $srchlast =~ s/\s+$//;
 6946:                     $srchfirst =~ s/^\s+//;
 6947:                     if ($srch->{'srchtype'} eq 'exact') {
 6948:                         if (($names{'lastname'} eq $srchlast) &&
 6949:                             ($names{'firstname'} eq $srchfirst)) {
 6950:                             $srch_results{$user} = {firstname => $names{'firstname'},
 6951:                                                 lastname => $names{'lastname'},
 6952:                                                 permanentemail => $emails{'permanentemail'},
 6953: 
 6954:                                            };
 6955:                         }
 6956:                     } elsif ($srch->{'srchtype'} eq 'begins') {
 6957:                         if (($names{'lastname'} =~ /^\Q$srchlast\E/i) &&
 6958:                             ($names{'firstname'} =~ /^\Q$srchfirst\E/i)) {
 6959:                             $srch_results{$user} = {firstname => $names{'firstname'},
 6960:                                                 lastname => $names{'lastname'},
 6961:                                                 permanentemail => $emails{'permanentemail'},
 6962:                                                };
 6963:                         }
 6964:                     } else {
 6965:                         if (($names{'lastname'} =~ /\Q$srchlast\E/i) && 
 6966:                             ($names{'firstname'} =~ /\Q$srchfirst\E/i)) {
 6967:                             $srch_results{$user} = {firstname => $names{'firstname'},
 6968:                                                 lastname => $names{'lastname'},
 6969:                                                 permanentemail => $emails{'permanentemail'},
 6970:                                                };
 6971:                         }
 6972:                     }
 6973:                 }
 6974:             }
 6975:             ($currstate,$response,$forcenewuser) = 
 6976:                 &build_search_response($context,$srch,%srch_results); 
 6977:         } elsif ($srch->{'srchin'} eq 'alc') {
 6978:             $currstate = 'query';
 6979:         } elsif ($srch->{'srchin'} eq 'instd') {
 6980:             ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query($srch); 
 6981:             if ($dirsrchres eq 'ok') {
 6982:                 ($currstate,$response,$forcenewuser) = 
 6983:                     &build_search_response($context,$srch,%srch_results);
 6984:             } else {
 6985:                 my $showdom = &display_domain_info($srch->{'srchdomain'});
 6986:                 $response = '<span class="LC_warning">'.
 6987:                     &mt('Institutional directory search is not available in domain: [_1]',$showdom).
 6988:                     '</span><br />'.
 6989:                     &mt('You may want to search in the LON-CAPA domain instead of the institutional directory.').
 6990:                     '<br /><br />';
 6991:             }
 6992:         }
 6993:     }
 6994:     return ($currstate,$response,$forcenewuser,\%srch_results);
 6995: }
 6996: 
 6997: sub domdirectorysrch_check {
 6998:     my ($srch) = @_;
 6999:     my $response;
 7000:     my %dom_inst_srch = &Apache::lonnet::get_dom('configuration',
 7001:                                              ['directorysrch'],$srch->{'srchdomain'});
 7002:     my $showdom = &display_domain_info($srch->{'srchdomain'});
 7003:     if (ref($dom_inst_srch{'directorysrch'}) eq 'HASH') {
 7004:         if ($dom_inst_srch{'directorysrch'}{'lcavailable'} eq '0') {
 7005:             return &mt('LON-CAPA directory search is not available in domain: [_1]',$showdom);
 7006:         }
 7007:         if ($dom_inst_srch{'directorysrch'}{'lclocalonly'}) {
 7008:             if ($env{'request.role.domain'} ne $srch->{'srchdomain'}) {
 7009:                 return &mt('LON-CAPA directory search in domain: [_1] is only allowed for users with a current role in the domain.',$showdom);
 7010:             }
 7011:         }
 7012:     }
 7013:     return 'ok';
 7014: }
 7015: 
 7016: sub instdirectorysrch_check {
 7017:     my ($srch) = @_;
 7018:     my $can_search = 0;
 7019:     my $response;
 7020:     my %dom_inst_srch = &Apache::lonnet::get_dom('configuration',
 7021:                                              ['directorysrch'],$srch->{'srchdomain'});
 7022:     my $showdom = &display_domain_info($srch->{'srchdomain'});
 7023:     if (ref($dom_inst_srch{'directorysrch'}) eq 'HASH') {
 7024:         if (!$dom_inst_srch{'directorysrch'}{'available'}) {
 7025:             return &mt('Institutional directory search is not available in domain: [_1]',$showdom); 
 7026:         }
 7027:         if ($dom_inst_srch{'directorysrch'}{'localonly'}) {
 7028:             if ($env{'request.role.domain'} ne $srch->{'srchdomain'}) {
 7029:                 return &mt('Institutional directory search in domain: [_1] is only allowed for users with a current role in the domain.',$showdom); 
 7030:             }
 7031:             my @usertypes = split(/:/,$env{'environment.inststatus'});
 7032:             if (!@usertypes) {
 7033:                 push(@usertypes,'default');
 7034:             }
 7035:             if (ref($dom_inst_srch{'directorysrch'}{'cansearch'}) eq 'ARRAY') {
 7036:                 foreach my $type (@usertypes) {
 7037:                     if (grep(/^\Q$type\E$/,@{$dom_inst_srch{'directorysrch'}{'cansearch'}})) {
 7038:                         $can_search = 1;
 7039:                         last;
 7040:                     }
 7041:                 }
 7042:             }
 7043:             if (!$can_search) {
 7044:                 my ($insttypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($srch->{'srchdomain'});
 7045:                 my @longtypes; 
 7046:                 foreach my $item (@usertypes) {
 7047:                     if (defined($insttypes->{$item})) { 
 7048:                         push (@longtypes,$insttypes->{$item});
 7049:                     } elsif ($item eq 'default') {
 7050:                         push (@longtypes,&mt('other')); 
 7051:                     }
 7052:                 }
 7053:                 my $insttype_str = join(', ',@longtypes); 
 7054:                 return &mt('Institutional directory search in domain: [_1] is not available to your user type: ',$showdom).$insttype_str;
 7055:             }
 7056:         } else {
 7057:             $can_search = 1;
 7058:         }
 7059:     } else {
 7060:         return &mt('Institutional directory search has not been configured for domain: [_1]',$showdom);
 7061:     }
 7062:     my %longtext = &Apache::lonlocal::texthash (
 7063:                        uname     => 'username',
 7064:                        lastfirst => 'last name, first name',
 7065:                        lastname  => 'last name',
 7066:                        contains  => 'contains',
 7067:                        exact     => 'as exact match to',
 7068:                        begins    => 'begins with',
 7069:                    );
 7070:     if ($can_search) {
 7071:         if (ref($dom_inst_srch{'directorysrch'}{'searchby'}) eq 'ARRAY') {
 7072:             if (!grep(/^\Q$srch->{'srchby'}\E$/,@{$dom_inst_srch{'directorysrch'}{'searchby'}})) {
 7073:                 return &mt('Institutional directory search in domain: [_1] is not available for searching by "[_2]"',$showdom,$longtext{$srch->{'srchby'}});
 7074:             }
 7075:         } else {
 7076:             return &mt('Institutional directory search in domain: [_1] is not available.', $showdom);
 7077:         }
 7078:     }
 7079:     if ($can_search) {
 7080:         if (ref($dom_inst_srch{'directorysrch'}{'searchtypes'}) eq 'ARRAY') {
 7081:             if (grep(/^\Q$srch->{'srchtype'}\E/,@{$dom_inst_srch{'directorysrch'}{'searchtypes'}})) {
 7082:                 return 'ok';
 7083:             } else {
 7084:                 return &mt('Institutional directory search in domain [_1] is not available for the requested search type: "[_2]"',$showdom,$longtext{$srch->{'srchtype'}});
 7085:             }
 7086:         } else {
 7087:             if ((($dom_inst_srch{'directorysrch'}{'searchtypes'} eq 'specify') &&
 7088:                  ($srch->{'srchtype'} eq 'exact' || $srch->{'srchtype'} eq 'contains')) ||
 7089:                 ($dom_inst_srch{'directorysrch'}{'searchtypes'} eq $srch->{'srchtype'})) {
 7090:                 return 'ok';
 7091:             } else {
 7092:                 return &mt('Institutional directory search in domain [_1] is not available for the requested search type: "[_2]"',$showdom,$longtext{$srch->{'srchtype'}});
 7093:             }
 7094:         }
 7095:     }
 7096: }
 7097: 
 7098: sub get_courseusers {
 7099:     my %advhash;
 7100:     my $classlist = &Apache::loncoursedata::get_classlist();
 7101:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles();
 7102:     foreach my $role (sort(keys(%coursepersonnel))) {
 7103:         foreach my $user (split(/\,/,$coursepersonnel{$role})) {
 7104: 	    if (!exists($classlist->{$user})) {
 7105: 		$classlist->{$user} = [];
 7106: 	    }
 7107:         }
 7108:     }
 7109:     return $classlist;
 7110: }
 7111: 
 7112: sub build_search_response {
 7113:     my ($context,$srch,%srch_results) = @_;
 7114:     my ($currstate,$response,$forcenewuser);
 7115:     my %names = (
 7116:           'uname'     => 'username',
 7117:           'lastname'  => 'last name',
 7118:           'lastfirst' => 'last name, first name',
 7119:           'crs'       => 'this course',
 7120:           'dom'       => 'LON-CAPA domain',
 7121:           'instd'     => 'the institutional directory for domain',
 7122:     );
 7123: 
 7124:     my %single = (
 7125:                    begins   => 'A match',
 7126:                    contains => 'A match',
 7127:                    exact    => 'An exact match',
 7128:                  );
 7129:     my %nomatch = (
 7130:                    begins   => 'No match',
 7131:                    contains => 'No match',
 7132:                    exact    => 'No exact match',
 7133:                   );
 7134:     if (keys(%srch_results) > 1) {
 7135:         $currstate = 'select';
 7136:     } else {
 7137:         if (keys(%srch_results) == 1) {
 7138:             $currstate = 'modify';
 7139:             $response = &mt("$single{$srch->{'srchtype'}} was found for the $names{$srch->{'srchby'}} ([_1]) in $names{$srch->{'srchin'}}.",$srch->{'srchterm'});
 7140:             if ($srch->{'srchin'} eq 'dom' || $srch->{'srchin'} eq 'instd') {
 7141:                 $response .= ': '.&display_domain_info($srch->{'srchdomain'});
 7142:             }
 7143:         } else { # Search has nothing found. Prepare message to user.
 7144:             $response = '<span class="LC_warning">';
 7145:             if ($srch->{'srchin'} eq 'dom' || $srch->{'srchin'} eq 'instd') {
 7146:                 $response .= &mt("$nomatch{$srch->{'srchtype'}} found for the $names{$srch->{'srchby'}} [_1] in $names{$srch->{'srchin'}}: [_2]",
 7147:                                  '<b>'.$srch->{'srchterm'}.'</b>',
 7148:                                  &display_domain_info($srch->{'srchdomain'}));
 7149:             } else {
 7150:                 $response .= &mt("$nomatch{$srch->{'srchtype'}} found for the $names{$srch->{'srchby'}} [_1] in $names{$srch->{'srchin'}}.",
 7151:                                  '<b>'.$srch->{'srchterm'}.'</b>');
 7152:             }
 7153:             $response .= '</span>';
 7154: 
 7155:             if ($srch->{'srchin'} ne 'alc') {
 7156:                 $forcenewuser = 1;
 7157:                 my $cansrchinst = 0; 
 7158:                 if ($srch->{'srchdomain'}) {
 7159:                     my %domconfig = &Apache::lonnet::get_dom('configuration',['directorysrch'],$srch->{'srchdomain'});
 7160:                     if (ref($domconfig{'directorysrch'}) eq 'HASH') {
 7161:                         if ($domconfig{'directorysrch'}{'available'}) {
 7162:                             $cansrchinst = 1;
 7163:                         } 
 7164:                     }
 7165:                 }
 7166:                 if ((($srch->{'srchby'} eq 'lastfirst') || 
 7167:                      ($srch->{'srchby'} eq 'lastname')) &&
 7168:                     ($srch->{'srchin'} eq 'dom')) {
 7169:                     if ($cansrchinst) {
 7170:                         $response .= '<br />'.&mt('You may want to broaden your search to a search of the institutional directory for the domain.');
 7171:                     }
 7172:                 }
 7173:                 if ($srch->{'srchin'} eq 'crs') {
 7174:                     $response .= '<br />'.&mt('You may want to broaden your search to the selected LON-CAPA domain.');
 7175:                 }
 7176:             }
 7177:             my $createdom = $env{'request.role.domain'};
 7178:             if ($context eq 'requestcrs') {
 7179:                 if ($env{'form.coursedom'} ne '') {
 7180:                     $createdom = $env{'form.coursedom'};
 7181:                 }
 7182:             }
 7183:             if (!($srch->{'srchby'} eq 'uname' && $srch->{'srchin'} eq 'dom' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchdomain'} eq $createdom)) {
 7184:                 my $cancreate =
 7185:                     &Apache::lonuserutils::can_create_user($createdom,$context);
 7186:                 my $targetdom = '<span class="LC_cusr_emph">'.$createdom.'</span>';
 7187:                 if ($cancreate) {
 7188:                     my $showdom = &display_domain_info($createdom); 
 7189:                     $response .= '<br /><br />'
 7190:                                 .'<b>'.&mt('To add a new user:').'</b>'
 7191:                                 .'<br />';
 7192:                     if ($context eq 'requestcrs') {
 7193:                         $response .= &mt("(You can only define new users in the new course's domain - [_1])",$targetdom);
 7194:                     } else {
 7195:                         $response .= &mt("(You can only create new users in your current role's domain - [_1])",$targetdom);
 7196:                     }
 7197:                     $response .='<ul><li>'
 7198:                                 .&mt("Set 'Domain/institution to search' to: [_1]",'<span class="LC_cusr_emph">'.$showdom.'</span>')
 7199:                                 .'</li><li>'
 7200:                                 .&mt("Set 'Search criteria' to: [_1]username is ..... in selected LON-CAPA domain[_2]",'<span class="LC_cusr_emph">','</span>')
 7201:                                 .'</li><li>'
 7202:                                 .&mt('Provide the proposed username')
 7203:                                 .'</li><li>'
 7204:                                 .&mt("Click 'Search'")
 7205:                                 .'</li></ul><br />';
 7206:                 } else {
 7207:                     my $helplink = ' href="javascript:helpMenu('."'display'".')"';
 7208:                     $response .= '<br /><br />';
 7209:                     if ($context eq 'requestcrs') {
 7210:                         $response .= &mt("You are not authorized to define new users in the new course's domain - [_1].",$targetdom);
 7211:                     } else {
 7212:                         $response .= &mt("You are not authorized to create new users in your current role's domain - [_1].",$targetdom);
 7213:                     }
 7214:                     $response .= '<br />'
 7215:                                  .&mt('Please contact the [_1]helpdesk[_2] if you need to create a new user.'
 7216:                                     ,' <a'.$helplink.'>'
 7217:                                     ,'</a>')
 7218:                                  .'<br /><br />';
 7219:                 }
 7220:             }
 7221:         }
 7222:     }
 7223:     return ($currstate,$response,$forcenewuser);
 7224: }
 7225: 
 7226: sub display_domain_info {
 7227:     my ($dom) = @_;
 7228:     my $output = $dom;
 7229:     if ($dom ne '') { 
 7230:         my $domdesc = &Apache::lonnet::domain($dom,'description');
 7231:         if ($domdesc ne '') {
 7232:             $output .= ' <span class="LC_cusr_emph">('.$domdesc.')</span>';
 7233:         }
 7234:     }
 7235:     return $output;
 7236: }
 7237: 
 7238: sub crumb_utilities {
 7239:     my %elements = (
 7240:        crtuser => {
 7241:            srchterm => 'text',
 7242:            srchin => 'selectbox',
 7243:            srchby => 'selectbox',
 7244:            srchtype => 'selectbox',
 7245:            srchdomain => 'selectbox',
 7246:        },
 7247:        crtusername => {
 7248:            srchterm => 'text',
 7249:            srchdomain => 'selectbox',
 7250:        },
 7251:        docustom => {
 7252:            rolename => 'selectbox',
 7253:            newrolename => 'textbox',
 7254:        },
 7255:        studentform => {
 7256:            srchterm => 'text',
 7257:            srchin => 'selectbox',
 7258:            srchby => 'selectbox',
 7259:            srchtype => 'selectbox',
 7260:            srchdomain => 'selectbox',
 7261:        },
 7262:     );
 7263: 
 7264:     my $jsback .= qq|
 7265: function backPage(formname,prevphase,prevstate) {
 7266:     if (typeof prevphase == 'undefined') {
 7267:         formname.phase.value = '';
 7268:     }
 7269:     else {  
 7270:         formname.phase.value = prevphase;
 7271:     }
 7272:     if (typeof prevstate == 'undefined') {
 7273:         formname.currstate.value = '';
 7274:     }
 7275:     else {
 7276:         formname.currstate.value = prevstate;
 7277:     }
 7278:     formname.submit();
 7279: }
 7280: |;
 7281:     return ($jsback,\%elements);
 7282: }
 7283: 
 7284: sub course_level_table {
 7285:     my ($inccourses,$showcredits,$defaultcredits) = @_;
 7286:     return unless (ref($inccourses) eq 'HASH');
 7287:     my $table = '';
 7288: # Custom Roles?
 7289: 
 7290:     my %customroles=&Apache::lonuserutils::my_custom_roles();
 7291:     my %lt=&Apache::lonlocal::texthash(
 7292:             'exs'  => "Existing sections",
 7293:             'new'  => "Define new section",
 7294:             'ssd'  => "Set Start Date",
 7295:             'sed'  => "Set End Date",
 7296:             'crl'  => "Course Level",
 7297:             'act'  => "Activate",
 7298:             'rol'  => "Role",
 7299:             'ext'  => "Extent",
 7300:             'grs'  => "Section",
 7301:             'crd'  => "Credits",
 7302:             'sta'  => "Start",
 7303:             'end'  => "End"
 7304:     );
 7305: 
 7306:     foreach my $protectedcourse (sort(keys(%{$inccourses}))) {
 7307: 	my $thiscourse=$protectedcourse;
 7308: 	$thiscourse=~s:_:/:g;
 7309: 	my %coursedata=&Apache::lonnet::coursedescription($thiscourse);
 7310:         my $isowner = &Apache::lonuserutils::is_courseowner($protectedcourse,$coursedata{'internal.courseowner'});
 7311: 	my $area=$coursedata{'description'};
 7312:         my $crstype=$coursedata{'type'};
 7313: 	if (!defined($area)) { $area=&mt('Unavailable course').': '.$protectedcourse; }
 7314: 	my ($domain,$cnum)=split(/\//,$thiscourse);
 7315:         my %sections_count;
 7316:         if (defined($env{'request.course.id'})) {
 7317:             if ($env{'request.course.id'} eq $domain.'_'.$cnum) {
 7318:                 %sections_count = 
 7319: 		    &Apache::loncommon::get_sections($domain,$cnum);
 7320:             }
 7321:         }
 7322:         my @roles = &Apache::lonuserutils::roles_by_context('course','',$crstype);
 7323: 	foreach my $role (@roles) {
 7324:             my $plrole=&Apache::lonnet::plaintext($role,$crstype);
 7325: 	    if ((&Apache::lonnet::allowed('c'.$role,$thiscourse)) ||
 7326:                 ((($role eq 'cc') || ($role eq 'co')) && ($isowner))) {
 7327:                 $table .= &course_level_row($protectedcourse,$role,$area,$domain,
 7328:                                             $plrole,\%sections_count,\%lt,
 7329:                                             $showcredits,$defaultcredits,$crstype);
 7330:             } elsif ($env{'request.course.sec'} ne '') {
 7331:                 if (&Apache::lonnet::allowed('c'.$role,$thiscourse.'/'.
 7332:                                              $env{'request.course.sec'})) {
 7333:                     $table .= &course_level_row($protectedcourse,$role,$area,$domain,
 7334:                                                 $plrole,\%sections_count,\%lt,
 7335:                                                 $showcredits,$defaultcredits,$crstype);
 7336:                 }
 7337:             }
 7338:         }
 7339:         if (&Apache::lonnet::allowed('ccr',$thiscourse)) {
 7340:             foreach my $cust (sort(keys(%customroles))) {
 7341:                 next if ($crstype eq 'Community' && $customroles{$cust} =~ /bre\&S/);
 7342:                 my $role = 'cr_cr_'.$env{'user.domain'}.'_'.$env{'user.name'}.'_'.$cust;
 7343:                 $table .= &course_level_row($protectedcourse,$role,$area,$domain,
 7344:                                             $cust,\%sections_count,\%lt,
 7345:                                             $showcredits,$defaultcredits,$crstype);
 7346:             }
 7347: 	}
 7348:     }
 7349:     return '' if ($table eq ''); # return nothing if there is nothing 
 7350:                                  # in the table
 7351:     my $result;
 7352:     if (!$env{'request.course.id'}) {
 7353:         $result = '<h4>'.$lt{'crl'}.'</h4>'."\n";
 7354:     }
 7355:     $result .= 
 7356: &Apache::loncommon::start_data_table().
 7357: &Apache::loncommon::start_data_table_header_row().
 7358: '<th>'.$lt{'act'}.'</th><th>'.$lt{'rol'}.'</th>'."\n".
 7359: '<th>'.$lt{'ext'}.'</th><th>'."\n";
 7360:     if ($showcredits) {
 7361:         $result .= $lt{'crd'}.'</th>';
 7362:     }
 7363:     $result .=
 7364: '<th>'.$lt{'grs'}.'</th><th>'.$lt{'sta'}.'</th>'."\n".
 7365: '<th>'.$lt{'end'}.'</th>'.
 7366: &Apache::loncommon::end_data_table_header_row().
 7367: $table.
 7368: &Apache::loncommon::end_data_table();
 7369:     return $result;
 7370: }
 7371: 
 7372: sub course_level_row {
 7373:     my ($protectedcourse,$role,$area,$domain,$plrole,$sections_count,
 7374:         $lt,$showcredits,$defaultcredits,$crstype) = @_;
 7375:     my $creditem;
 7376:     my $row = &Apache::loncommon::start_data_table_row().
 7377:               ' <td><input type="checkbox" name="act_'.
 7378:               $protectedcourse.'_'.$role.'" /></td>'."\n".
 7379:               ' <td>'.$plrole.'</td>'."\n".
 7380:               ' <td>'.$area.'<br />Domain: '.$domain.'</td>'."\n";
 7381:     if (($showcredits) && ($role eq 'st') && ($crstype eq 'Course')) {
 7382:         $row .= 
 7383:             '<td><input type="text" name="credits_'.$protectedcourse.'_'.
 7384:             $role.'" size="3" value="'.$defaultcredits.'" /></td>';
 7385:     } else {
 7386:         $row .= '<td>&nbsp;</td>';
 7387:     }
 7388:     if (($role eq 'cc') || ($role eq 'co')) {
 7389:         $row .= '<td>&nbsp;</td>';
 7390:     } elsif ($env{'request.course.sec'} ne '') {
 7391:         $row .= ' <td><input type="hidden" value="'.
 7392:                 $env{'request.course.sec'}.'" '.
 7393:                 'name="sec_'.$protectedcourse.'_'.$role.'" />'.
 7394:                 $env{'request.course.sec'}.'</td>';
 7395:     } else {
 7396:         if (ref($sections_count) eq 'HASH') {
 7397:             my $currsec = 
 7398:                 &Apache::lonuserutils::course_sections($sections_count,
 7399:                                                        $protectedcourse.'_'.$role);
 7400:             $row .= '<td><table class="LC_createuser">'."\n".
 7401:                     '<tr class="LC_section_row">'."\n".
 7402:                     ' <td valign="top">'.$lt->{'exs'}.'<br />'.
 7403:                        $currsec.'</td>'."\n".
 7404:                      ' <td>&nbsp;&nbsp;</td>'."\n".
 7405:                      ' <td valign="top">&nbsp;'.$lt->{'new'}.'<br />'.
 7406:                      '<input type="text" name="newsec_'.$protectedcourse.'_'.$role.
 7407:                      '" value="" />'.
 7408:                      '<input type="hidden" '.
 7409:                      'name="sec_'.$protectedcourse.'_'.$role.'" /></td>'."\n".
 7410:                      '</tr></table></td>'."\n";
 7411:         } else {
 7412:             $row .= '<td><input type="text" size="10" '.
 7413:                     'name="sec_'.$protectedcourse.'_'.$role.'" /></td>'."\n";
 7414:         }
 7415:     }
 7416:     $row .= <<ENDTIMEENTRY;
 7417: <td><input type="hidden" name="start_$protectedcourse\_$role" value="" />
 7418: <a href=
 7419: "javascript:pjump('date_start','Start Date $plrole',document.cu.start_$protectedcourse\_$role.value,'start_$protectedcourse\_$role','cu.pres','dateset')">$lt->{'ssd'}</a></td>
 7420: <td><input type="hidden" name="end_$protectedcourse\_$role" value="" />
 7421: <a href=
 7422: "javascript:pjump('date_end','End Date $plrole',document.cu.end_$protectedcourse\_$role.value,'end_$protectedcourse\_$role','cu.pres','dateset')">$lt->{'sed'}</a></td>
 7423: ENDTIMEENTRY
 7424:     $row .= &Apache::loncommon::end_data_table_row();
 7425:     return $row;
 7426: }
 7427: 
 7428: sub course_level_dc {
 7429:     my ($dcdom,$showcredits) = @_;
 7430:     my %customroles=&Apache::lonuserutils::my_custom_roles();
 7431:     my @roles = &Apache::lonuserutils::roles_by_context('course');
 7432:     my $hiddenitems = '<input type="hidden" name="dcdomain" value="'.$dcdom.'" />'.
 7433:                       '<input type="hidden" name="origdom" value="'.$dcdom.'" />'.
 7434:                       '<input type="hidden" name="dccourse" value="" />';
 7435:     my $courseform=&Apache::loncommon::selectcourse_link
 7436:             ('cu','dccourse','dcdomain','coursedesc',undef,undef,'Select','crstype');
 7437:     my $credit_elem;
 7438:     if ($showcredits) {
 7439:         $credit_elem = 'credits';
 7440:     }
 7441:     my $cb_jscript = &Apache::loncommon::coursebrowser_javascript($dcdom,'currsec','cu','role','Course/Community Browser',$credit_elem);
 7442:     my %lt=&Apache::lonlocal::texthash(
 7443:                     'rol'  => "Role",
 7444:                     'grs'  => "Section",
 7445:                     'exs'  => "Existing sections",
 7446:                     'new'  => "Define new section", 
 7447:                     'sta'  => "Start",
 7448:                     'end'  => "End",
 7449:                     'ssd'  => "Set Start Date",
 7450:                     'sed'  => "Set End Date",
 7451:                     'scc'  => "Course/Community",
 7452:                     'crd'  => "Credits",
 7453:                   );
 7454:     my $header = '<h4>'.&mt('Course/Community Level').'</h4>'.
 7455:                  &Apache::loncommon::start_data_table().
 7456:                  &Apache::loncommon::start_data_table_header_row().
 7457:                  '<th>'.$lt{'scc'}.'</th><th>'.$lt{'rol'}.'</th>'."\n".
 7458:                  '<th>'.$lt{'grs'}.'</th>'."\n";
 7459:     $header .=   '<th>'.$lt{'crd'}.'</th>'."\n" if ($showcredits);
 7460:     $header .=   '<th>'.$lt{'sta'}.'</th><th>'.$lt{'end'}.'</th>'."\n".
 7461:                  &Apache::loncommon::end_data_table_header_row();
 7462:     my $otheritems = &Apache::loncommon::start_data_table_row()."\n".
 7463:                      '<td><br /><span class="LC_nobreak"><input type="text" name="coursedesc" value="" onfocus="this.blur();opencrsbrowser('."'cu','dccourse','dcdomain','coursedesc','','','','crstype'".')" />'.
 7464:                      $courseform.('&nbsp;' x4).'</span></td>'."\n".
 7465:                      '<td valign="top"><br /><select name="role">'."\n";
 7466:     foreach my $role (@roles) {
 7467:         my $plrole=&Apache::lonnet::plaintext($role);
 7468:         $otheritems .= '  <option value="'.$role.'">'.$plrole.'</option>';
 7469:     }
 7470:     if ( keys(%customroles) > 0) {
 7471:         foreach my $cust (sort(keys(%customroles))) {
 7472:             my $custrole='cr_cr_'.$env{'user.domain'}.
 7473:                     '_'.$env{'user.name'}.'_'.$cust;
 7474:             $otheritems .= '  <option value="'.$custrole.'">'.$cust.'</option>';
 7475:         }
 7476:     }
 7477:     $otheritems .= '</select></td><td>'.
 7478:                      '<table border="0" cellspacing="0" cellpadding="0">'.
 7479:                      '<tr><td valign="top"><b>'.$lt{'exs'}.'</b><br /><select name="currsec">'.
 7480:                      ' <option value="">&lt;--'.&mt('Pick course first').'</option></select></td>'.
 7481:                      '<td>&nbsp;&nbsp;</td>'.
 7482:                      '<td valign="top">&nbsp;<b>'.$lt{'new'}.'</b><br />'.
 7483:                      '<input type="text" name="newsec" value="" />'.
 7484:                      '<input type="hidden" name="section" value="" />'.
 7485:                      '<input type="hidden" name="groups" value="" />'.
 7486:                      '<input type="hidden" name="crstype" value="" /></td>'.
 7487:                      '</tr></table></td>'."\n";
 7488:     if ($showcredits) {
 7489:         $otheritems .= '<td><br />'."\n".
 7490:                        '<input type="text" size="3" name="credits" value="" /></td>'."\n";
 7491:     }
 7492:     $otheritems .= <<ENDTIMEENTRY;
 7493: <td><br /><input type="hidden" name="start" value='' />
 7494: <a href=
 7495: "javascript:pjump('date_start','Start Date',document.cu.start.value,'start','cu.pres','dateset')">$lt{'ssd'}</a></td>
 7496: <td><br /><input type="hidden" name="end" value='' />
 7497: <a href=
 7498: "javascript:pjump('date_end','End Date',document.cu.end.value,'end','cu.pres','dateset')">$lt{'sed'}</a></td>
 7499: ENDTIMEENTRY
 7500:     $otheritems .= &Apache::loncommon::end_data_table_row().
 7501:                    &Apache::loncommon::end_data_table()."\n";
 7502:     return $cb_jscript.$header.$hiddenitems.$otheritems;
 7503: }
 7504: 
 7505: sub update_selfenroll_config {
 7506:     my ($r,$cid,$cdom,$cnum,$context,$crstype,$currsettings) = @_;
 7507:     return unless (ref($currsettings) eq 'HASH');
 7508:     my ($row,$lt) = &Apache::lonuserutils::get_selfenroll_titles();
 7509:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
 7510:     my (%changes,%warning);
 7511:     my $curr_types;
 7512:     my %noedit;
 7513:     unless ($context eq 'domain') {
 7514:         %noedit = &get_noedit_fields($cdom,$cnum,$crstype,$row);
 7515:     }
 7516:     if (ref($row) eq 'ARRAY') {
 7517:         foreach my $item (@{$row}) {
 7518:             next if ($noedit{$item});
 7519:             if ($item eq 'enroll_dates') {
 7520:                 my (%currenrolldate,%newenrolldate);
 7521:                 foreach my $type ('start','end') {
 7522:                     $currenrolldate{$type} = $currsettings->{'selfenroll_'.$type.'_date'};
 7523:                     $newenrolldate{$type} = &Apache::lonhtmlcommon::get_date_from_form('selfenroll_'.$type.'_date');
 7524:                     if ($newenrolldate{$type} ne $currenrolldate{$type}) {
 7525:                         $changes{'internal.selfenroll_'.$type.'_date'} = $newenrolldate{$type};
 7526:                     }
 7527:                 }
 7528:             } elsif ($item eq 'access_dates') {
 7529:                 my (%currdate,%newdate);
 7530:                 foreach my $type ('start','end') {
 7531:                     $currdate{$type} = $currsettings->{'selfenroll_'.$type.'_access'};
 7532:                     $newdate{$type} = &Apache::lonhtmlcommon::get_date_from_form('selfenroll_'.$type.'_access');
 7533:                     if ($newdate{$type} ne $currdate{$type}) {
 7534:                         $changes{'internal.selfenroll_'.$type.'_access'} = $newdate{$type};
 7535:                     }
 7536:                 }
 7537:             } elsif ($item eq 'types') {
 7538:                 $curr_types = $currsettings->{'selfenroll_'.$item};
 7539:                 if ($env{'form.selfenroll_all'}) {
 7540:                     if ($curr_types ne '*') {
 7541:                         $changes{'internal.selfenroll_types'} = '*';
 7542:                     } else {
 7543:                         next;
 7544:                     }
 7545:                 } else {
 7546:                     my %currdoms;
 7547:                     my @entries = split(/;/,$curr_types);
 7548:                     my @deletedoms = &Apache::loncommon::get_env_multiple('form.selfenroll_delete');
 7549:                     my @activations = &Apache::loncommon::get_env_multiple('form.selfenroll_activate');
 7550:                     my $newnum = 0;
 7551:                     my @latesttypes;
 7552:                     foreach my $num (@activations) {
 7553:                         my @types = &Apache::loncommon::get_env_multiple('form.selfenroll_types_'.$num);
 7554:                         if (@types > 0) {
 7555:                             @types = sort(@types);
 7556:                             my $typestr = join(',',@types);
 7557:                             my $typedom = $env{'form.selfenroll_dom_'.$num};
 7558:                             $latesttypes[$newnum] = $typedom.':'.$typestr;
 7559:                             $currdoms{$typedom} = 1;
 7560:                             $newnum ++;
 7561:                         }
 7562:                     }
 7563:                     for (my $j=0; $j<$env{'form.selfenroll_types_total'}; $j++) {
 7564:                         if ((!grep(/^$j$/,@deletedoms)) && (!grep(/^$j$/,@activations))) {
 7565:                             my @types = &Apache::loncommon::get_env_multiple('form.selfenroll_types_'.$j);
 7566:                             if (@types > 0) {
 7567:                                 @types = sort(@types);
 7568:                                 my $typestr = join(',',@types);
 7569:                                 my $typedom = $env{'form.selfenroll_dom_'.$j};
 7570:                                 $latesttypes[$newnum] = $typedom.':'.$typestr;
 7571:                                 $currdoms{$typedom} = 1;
 7572:                                 $newnum ++;
 7573:                             }
 7574:                         }
 7575:                     }
 7576:                     if ($env{'form.selfenroll_newdom'} ne '') {
 7577:                         my $typedom = $env{'form.selfenroll_newdom'};
 7578:                         if ((!defined($currdoms{$typedom})) && 
 7579:                             (&Apache::lonnet::domain($typedom) ne '')) {
 7580:                             my $typestr;
 7581:                             my ($othertitle,$usertypes,$types) = 
 7582:                                 &Apache::loncommon::sorted_inst_types($typedom);
 7583:                             my $othervalue = 'any';
 7584:                             if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 7585:                                 if (@{$types} > 0) {
 7586:                                     my @esc_types = map { &escape($_); } @{$types};
 7587:                                     $othervalue = 'other';
 7588:                                     $typestr = join(',',(@esc_types,$othervalue));
 7589:                                 }
 7590:                                 $typestr = $othervalue;
 7591:                             } else {
 7592:                                 $typestr = $othervalue;
 7593:                             } 
 7594:                             $latesttypes[$newnum] = $typedom.':'.$typestr;
 7595:                             $newnum ++ ;
 7596:                         }
 7597:                     }
 7598:                     my $selfenroll_types = join(';',@latesttypes);
 7599:                     if ($selfenroll_types ne $curr_types) {
 7600:                         $changes{'internal.selfenroll_types'} = $selfenroll_types;
 7601:                     }
 7602:                 }
 7603:             } elsif ($item eq 'limit') {
 7604:                 my $newlimit = $env{'form.selfenroll_limit'};
 7605:                 my $newcap = $env{'form.selfenroll_cap'};
 7606:                 $newcap =~s/\s+//g;
 7607:                 my $currlimit =  $currsettings->{'selfenroll_limit'};
 7608:                 $currlimit = 'none' if ($currlimit eq '');
 7609:                 my $currcap = $currsettings->{'selfenroll_cap'};
 7610:                 if ($newlimit ne $currlimit) {
 7611:                     if ($newlimit ne 'none') {
 7612:                         if ($newcap =~ /^\d+$/) {
 7613:                             if ($newcap ne $currcap) {
 7614:                                 $changes{'internal.selfenroll_cap'} = $newcap;
 7615:                             }
 7616:                             $changes{'internal.selfenroll_limit'} = $newlimit;
 7617:                         } else {
 7618:                             $warning{$item} = &mt('Maximum enrollment setting unchanged.').'<br />'.
 7619:                                 &mt('The value provided was invalid - it must be a positive integer if enrollment is being limited.'); 
 7620:                         }
 7621:                     } elsif ($currcap ne '') {
 7622:                         $changes{'internal.selfenroll_cap'} = '';
 7623:                         $changes{'internal.selfenroll_limit'} = $newlimit; 
 7624:                     }
 7625:                 } elsif ($currlimit ne 'none') {
 7626:                     if ($newcap =~ /^\d+$/) {
 7627:                         if ($newcap ne $currcap) {
 7628:                             $changes{'internal.selfenroll_cap'} = $newcap;
 7629:                         }
 7630:                     } else {
 7631:                         $warning{$item} = &mt('Maximum enrollment setting unchanged.').'<br />'.
 7632:                             &mt('The value provided was invalid - it must be a positive integer if enrollment is being limited.');
 7633:                     }
 7634:                 }
 7635:             } elsif ($item eq 'approval') {
 7636:                 my (@currnotified,@newnotified);
 7637:                 my $currapproval = $currsettings->{'selfenroll_approval'};
 7638:                 my $currnotifylist = $currsettings->{'selfenroll_notifylist'};
 7639:                 if ($currnotifylist ne '') {
 7640:                     @currnotified = split(/,/,$currnotifylist);
 7641:                     @currnotified = sort(@currnotified);
 7642:                 }
 7643:                 my $newapproval = $env{'form.selfenroll_approval'};
 7644:                 @newnotified = &Apache::loncommon::get_env_multiple('form.selfenroll_notify');
 7645:                 @newnotified = sort(@newnotified);
 7646:                 if ($newapproval ne $currapproval) {
 7647:                     $changes{'internal.selfenroll_approval'} = $newapproval;
 7648:                     if (!$newapproval) {
 7649:                         if ($currnotifylist ne '') {
 7650:                             $changes{'internal.selfenroll_notifylist'} = '';
 7651:                         }
 7652:                     } else {
 7653:                         my @differences =  
 7654:                             &Apache::loncommon::compare_arrays(\@currnotified,\@newnotified);
 7655:                         if (@differences > 0) {
 7656:                             if (@newnotified > 0) {
 7657:                                 $changes{'internal.selfenroll_notifylist'} = join(',',@newnotified);
 7658:                             } else {
 7659:                                 $changes{'internal.selfenroll_notifylist'} = join(',',@newnotified);
 7660:                             }
 7661:                         }
 7662:                     }
 7663:                 } else {
 7664:                     my @differences = &Apache::loncommon::compare_arrays(\@currnotified,\@newnotified);
 7665:                     if (@differences > 0) {
 7666:                         if (@newnotified > 0) {
 7667:                             $changes{'internal.selfenroll_notifylist'} = join(',',@newnotified);
 7668:                         } else {
 7669:                             $changes{'internal.selfenroll_notifylist'} = '';
 7670:                         }
 7671:                     }
 7672:                 }
 7673:             } else {
 7674:                 my $curr_val = $currsettings->{'selfenroll_'.$item};
 7675:                 my $newval = $env{'form.selfenroll_'.$item};
 7676:                 if ($item eq 'section') {
 7677:                     $newval = $env{'form.sections'};
 7678:                     if (defined($curr_groups{$newval})) {
 7679:                         $newval = $curr_val;
 7680:                         $warning{$item} = &mt('Section for self-enrolled users unchanged as the proposed section is a group').'<br />'.
 7681:                                           &mt('Group names and section names must be distinct');
 7682:                     } elsif ($newval eq 'all') {
 7683:                         $newval = $curr_val;
 7684:                         $warning{$item} = &mt('Section for self-enrolled users unchanged, as "all" is a reserved section name.');
 7685:                     }
 7686:                     if ($newval eq '') {
 7687:                         $newval = 'none';
 7688:                     }
 7689:                 }
 7690:                 if ($newval ne $curr_val) {
 7691:                     $changes{'internal.selfenroll_'.$item} = $newval;
 7692:                 }
 7693:             }
 7694:         }
 7695:         if (keys(%warning) > 0) {
 7696:             foreach my $item (@{$row}) {
 7697:                 if (exists($warning{$item})) {
 7698:                     $r->print($warning{$item}.'<br />');
 7699:                 }
 7700:             } 
 7701:         }
 7702:         if (keys(%changes) > 0) {
 7703:             my $putresult = &Apache::lonnet::put('environment',\%changes,$cdom,$cnum);
 7704:             if ($putresult eq 'ok') {
 7705:                 if ((exists($changes{'internal.selfenroll_types'})) ||
 7706:                     (exists($changes{'internal.selfenroll_start_date'}))  ||
 7707:                     (exists($changes{'internal.selfenroll_end_date'}))) {
 7708:                     my %crsinfo = &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',
 7709:                                                                 $cnum,undef,undef,'Course');
 7710:                     my $chome = &Apache::lonnet::homeserver($cnum,$cdom);
 7711:                     if (ref($crsinfo{$cid}) eq 'HASH') {
 7712:                         foreach my $item ('selfenroll_types','selfenroll_start_date','selfenroll_end_date') {
 7713:                             if (exists($changes{'internal.'.$item})) {
 7714:                                 $crsinfo{$cid}{$item} = $changes{'internal.'.$item};
 7715:                             }
 7716:                         }
 7717:                         my $crsputresult =
 7718:                             &Apache::lonnet::courseidput($cdom,\%crsinfo,
 7719:                                                          $chome,'notime');
 7720:                     }
 7721:                 }
 7722:                 $r->print(&mt('The following changes were made to self-enrollment settings:').'<ul>');
 7723:                 foreach my $item (@{$row}) {
 7724:                     my $title = $item;
 7725:                     if (ref($lt) eq 'HASH') {
 7726:                         $title = $lt->{$item};
 7727:                     }
 7728:                     if ($item eq 'enroll_dates') {
 7729:                         foreach my $type ('start','end') {
 7730:                             if (exists($changes{'internal.selfenroll_'.$type.'_date'})) {
 7731:                                 my $newdate = &Apache::lonlocal::locallocaltime($changes{'internal.selfenroll_'.$type.'_date'});
 7732:                                 $r->print('<li>'.&mt('[_1]: "[_2]" set to "[_3]".',
 7733:                                           $title,$type,$newdate).'</li>');
 7734:                             }
 7735:                         }
 7736:                     } elsif ($item eq 'access_dates') {
 7737:                         foreach my $type ('start','end') {
 7738:                             if (exists($changes{'internal.selfenroll_'.$type.'_access'})) {
 7739:                                 my $newdate = &Apache::lonlocal::locallocaltime($changes{'internal.selfenroll_'.$type.'_access'});
 7740:                                 $r->print('<li>'.&mt('[_1]: "[_2]" set to "[_3]".',
 7741:                                           $title,$type,$newdate).'</li>');
 7742:                             }
 7743:                         }
 7744:                     } elsif ($item eq 'limit') {
 7745:                         if ((exists($changes{'internal.selfenroll_limit'})) ||
 7746:                             (exists($changes{'internal.selfenroll_cap'}))) {
 7747:                             my ($newval,$newcap);
 7748:                             if ($changes{'internal.selfenroll_cap'} ne '') {
 7749:                                 $newcap = $changes{'internal.selfenroll_cap'}
 7750:                             } else {
 7751:                                 $newcap = $currsettings->{'selfenroll_cap'};
 7752:                             }
 7753:                             if ($changes{'internal.selfenroll_limit'} eq 'none') {
 7754:                                 $newval = &mt('No limit');
 7755:                             } elsif ($changes{'internal.selfenroll_limit'} eq 
 7756:                                      'allstudents') {
 7757:                                 $newval = &mt('New self-enrollment no longer allowed when total (all students) reaches [_1].',$newcap);
 7758:                             } elsif ($changes{'internal.selfenroll_limit'} eq 'selfenrolled') {
 7759:                                 $newval = &mt('New self-enrollment no longer allowed when total number of self-enrolled students reaches [_1].',$newcap);
 7760:                             } else {
 7761:                                 my $currlimit =  $currsettings->{'selfenroll_limit'};
 7762:                                 if ($currlimit eq 'allstudents') {
 7763:                                     $newval = &mt('New self-enrollment no longer allowed when total (all students) reaches [_1].',$newcap);
 7764:                                 } elsif ($changes{'internal.selfenroll_limit'} eq 'selfenrolled') {
 7765:                                     $newval =  &mt('New self-enrollment no longer allowed when total number of self-enrolled students reaches [_1].',$newcap);
 7766:                                 }
 7767:                             }
 7768:                             $r->print('<li>'.&mt('"[_1]" set to "[_2]".',$title,$newval).'</li>'."\n");
 7769:                         }
 7770:                     } elsif ($item eq 'approval') {
 7771:                         if ((exists($changes{'internal.selfenroll_approval'})) ||
 7772:                             (exists($changes{'internal.selfenroll_notifylist'}))) {
 7773:                             my %selfdescs = &Apache::lonuserutils::selfenroll_default_descs();
 7774:                             my ($newval,$newnotify);
 7775:                             if (exists($changes{'internal.selfenroll_notifylist'})) {
 7776:                                 $newnotify = $changes{'internal.selfenroll_notifylist'};
 7777:                             } else {   
 7778:                                 $newnotify = $currsettings->{'selfenroll_notifylist'};
 7779:                             }
 7780:                             if (exists($changes{'internal.selfenroll_approval'})) {
 7781:                                 if ($changes{'internal.selfenroll_approval'} !~ /^[012]$/) {
 7782:                                     $changes{'internal.selfenroll_approval'} = '0';
 7783:                                 }
 7784:                                 $newval = $selfdescs{'approval'}{$changes{'internal.selfenroll_approval'}};
 7785:                             } else {
 7786:                                 my $currapproval = $currsettings->{'selfenroll_approval'}; 
 7787:                                 if ($currapproval !~ /^[012]$/) {
 7788:                                     $currapproval = 0;
 7789:                                 }
 7790:                                 $newval = $selfdescs{'approval'}{$currapproval};
 7791:                             }
 7792:                             $r->print('<li>'.&mt('"[_1]" set to "[_2]".',$title,$newval));
 7793:                             if ($newnotify) {
 7794:                                 $r->print('<br />'.&mt('The following will be notified when an enrollment request needs approval, or has been approved: [_1].',$newnotify));
 7795:                             } else {
 7796:                                 $r->print('<br />'.&mt('No notifications sent when an enrollment request needs approval, or has been approved.'));
 7797:                             }
 7798:                             $r->print('</li>'."\n");
 7799:                         }
 7800:                     } else {
 7801:                         if (exists($changes{'internal.selfenroll_'.$item})) {
 7802:                             my $newval = $changes{'internal.selfenroll_'.$item};
 7803:                             if ($item eq 'types') {
 7804:                                 if ($newval eq '') {
 7805:                                     $newval = &mt('None');
 7806:                                 } elsif ($newval eq '*') {
 7807:                                     $newval = &mt('Any user in any domain');
 7808:                                 }
 7809:                             } elsif ($item eq 'registered') {
 7810:                                 if ($newval eq '1') {
 7811:                                     $newval = &mt('Yes');
 7812:                                 } elsif ($newval eq '0') {
 7813:                                     $newval = &mt('No');
 7814:                                 }
 7815:                             }
 7816:                             $r->print('<li>'.&mt('"[_1]" set to "[_2]".',$title,$newval).'</li>'."\n");
 7817:                         }
 7818:                     }
 7819:                 }
 7820:                 $r->print('</ul>');
 7821:                 if ($env{'course.'.$cid.'.description'} ne '') {
 7822:                     my %newenvhash;
 7823:                     foreach my $key (keys(%changes)) {
 7824:                         $newenvhash{'course.'.$cid.'.'.$key} = $changes{$key};
 7825:                     }
 7826:                     &Apache::lonnet::appenv(\%newenvhash);
 7827:                 }
 7828:             } else {
 7829:                 $r->print(&mt('An error occurred when saving changes to self-enrollment settings in this course.').'<br />'.
 7830:                           &mt('The error was: [_1].',$putresult));
 7831:             }
 7832:         } else {
 7833:             $r->print(&mt('No changes were made to the existing self-enrollment settings in this course.'));
 7834:         }
 7835:     } else {
 7836:         $r->print(&mt('No changes were made to the existing self-enrollment settings in this course.'));
 7837:     }
 7838:     my $visactions = &cat_visibility();
 7839:     my ($cathash,%cattype);
 7840:     my %domconfig = &Apache::lonnet::get_dom('configuration',['coursecategories'],$cdom);
 7841:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 7842:         $cathash = $domconfig{'coursecategories'}{'cats'};
 7843:         $cattype{'auth'} = $domconfig{'coursecategories'}{'auth'};
 7844:         $cattype{'unauth'} = $domconfig{'coursecategories'}{'unauth'};
 7845:     } else {
 7846:         $cathash = {};
 7847:         $cattype{'auth'} = 'std';
 7848:         $cattype{'unauth'} = 'std';
 7849:     }
 7850:     if (($cattype{'auth'} eq 'none') && ($cattype{'unauth'} eq 'none')) {
 7851:         $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
 7852:                   '<br />'.
 7853:                   '<br />'.$visactions->{'take'}.'<ul>'.
 7854:                   '<li>'.$visactions->{'dc_chgconf'}.'</li>'.
 7855:                   '</ul>');
 7856:     } elsif (($cattype{'auth'} !~ /^(std|domonly)$/) && ($cattype{'unauth'} !~ /^(std|domonly)$/)) {
 7857:         if ($currsettings->{'uniquecode'}) {
 7858:             $r->print('<span class="LC_info">'.$visactions->{'vis'}.'</span>');
 7859:         } else {
 7860:             $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
 7861:                   '<br />'.
 7862:                   '<br />'.$visactions->{'take'}.'<ul>'.
 7863:                   '<li>'.$visactions->{'dc_setcode'}.'</li>'.
 7864:                   '</ul><br />');
 7865:         }
 7866:     } else {
 7867:         my ($visible,$cansetvis,$vismsgs) = &visible_in_stdcat($cdom,$cnum,\%domconfig);
 7868:         if (ref($visactions) eq 'HASH') {
 7869:             if (!$visible) {
 7870:                 $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
 7871:                           '<br />');
 7872:                 if (ref($vismsgs) eq 'ARRAY') {
 7873:                     $r->print('<br />'.$visactions->{'take'}.'<ul>');
 7874:                     foreach my $item (@{$vismsgs}) {
 7875:                         $r->print('<li>'.$visactions->{$item}.'</li>');
 7876:                     }
 7877:                     $r->print('</ul>');
 7878:                 }
 7879:                 $r->print($cansetvis);
 7880:             }
 7881:         }
 7882:     } 
 7883:     return;
 7884: }
 7885: 
 7886: #---------------------------------------------- end functions for &phase_two
 7887: 
 7888: #--------------------------------- functions for &phase_two and &phase_three
 7889: 
 7890: #--------------------------end of functions for &phase_two and &phase_three
 7891: 
 7892: 1;
 7893: __END__
 7894: 
 7895: 

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