File:  [LON-CAPA] / loncom / interface / loncreateuser.pm
Revision 1.363: download - view: text, annotated - select for diffs
Fri Aug 17 22:43:31 2012 UTC (11 years, 9 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Logging of role changes for domain roles and co-author roles
  (who, what, when, context, and by whom).
- Access to appropriate log via submenu in Modify users in au or dc context
- Scripts used to make, add or expire DC role from command line also write
  to rolelog.db on same server (stored with domainconfig user).

    1: # The LearningOnline Network with CAPA
    2: # Create a user
    3: #
    4: # $Id: loncreateuser.pm,v 1.363 2012/08/17 22:43:31 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:                      localuth => 'loc',
  118:                      unix     => 'fsys',
  119:                    );
  120:     return %abv_auth;
  121: }
  122: 
  123: # ====================================================
  124: 
  125: sub portfolio_quota {
  126:     my ($ccuname,$ccdomain) = @_;
  127:     my %lt = &Apache::lonlocal::texthash(
  128:                    'usrt'      => "User Tools",
  129:                    'disk'      => "Disk space allocated to user's portfolio files",
  130:                    'cuqu'      => "Current quota",
  131:                    'cust'      => "Custom quota",
  132:                    'defa'      => "Default",
  133:                    'chqu'      => "Change quota",
  134:     );
  135:     my ($currquota,$quotatype,$inststatus,$defquota) = 
  136:         &Apache::loncommon::get_user_quota($ccuname,$ccdomain);
  137:     my ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($ccdomain);
  138:     my ($longinsttype,$showquota,$custom_on,$custom_off,$defaultinfo);
  139:     if ($inststatus ne '') {
  140:         if ($usertypes->{$inststatus} ne '') {
  141:             $longinsttype = $usertypes->{$inststatus};
  142:         }
  143:     }
  144:     $custom_on = ' ';
  145:     $custom_off = ' checked="checked" ';
  146:     my $quota_javascript = <<"END_SCRIPT";
  147: <script type="text/javascript">
  148: // <![CDATA[
  149: function quota_changes(caller) {
  150:     if (caller == "custom") {
  151:         if (document.cu.customquota[0].checked) {
  152:             document.cu.portfolioquota.value = "";
  153:         }
  154:     }
  155:     if (caller == "quota") {
  156:         document.cu.customquota[1].checked = true;
  157:     }
  158: }
  159: // ]]>
  160: </script>
  161: END_SCRIPT
  162:     if ($quotatype eq 'custom') {
  163:         $custom_on = $custom_off;
  164:         $custom_off = ' ';
  165:         $showquota = $currquota;
  166:         if ($longinsttype eq '') {
  167:             $defaultinfo = &mt('For this user, the default quota would be [_1]'
  168:                             .' Mb.',$defquota);
  169:         } else {
  170:             $defaultinfo = &mt("For this user, the default quota would be [_1]".
  171:                                " Mb, as determined by the user's institutional".
  172:                                " affiliation ([_2]).",$defquota,$longinsttype);
  173:         }
  174:     } else {
  175:         if ($longinsttype eq '') {
  176:             $defaultinfo = &mt('For this user, the default quota is [_1]'
  177:                             .' Mb.',$defquota);
  178:         } else {
  179:             $defaultinfo = &mt("For this user, the default quota of [_1]".
  180:                                " Mb, is determined by the user's institutional".
  181:                                " affiliation ([_2]).",$defquota,$longinsttype);
  182:         }
  183:     }
  184: 
  185:     my $output = $quota_javascript."\n".
  186:                  '<h3>'.$lt{'usrt'}.'</h3>'."\n".
  187:                  &Apache::loncommon::start_data_table();
  188: 
  189:     if (&Apache::lonnet::allowed('mut',$ccdomain)) {
  190:         $output .= &build_tools_display($ccuname,$ccdomain,'tools');
  191:     }
  192:     if (&Apache::lonnet::allowed('mpq',$ccdomain)) {
  193:         $output .= '<tr class="LC_info_row">'."\n".
  194:                    '    <td>'.$lt{'disk'}.'</td>'."\n".
  195:                    '  </tr>'."\n".
  196:                    &Apache::loncommon::start_data_table_row()."\n".
  197:                    '  <td>'.$lt{'cuqu'}.': '.
  198:                    $currquota.'&nbsp;Mb.&nbsp;&nbsp;'.
  199:                    $defaultinfo.'</td>'."\n".
  200:                    &Apache::loncommon::end_data_table_row()."\n".
  201:                    &Apache::loncommon::start_data_table_row()."\n".
  202:                    '  <td><span class="LC_nobreak">'.$lt{'chqu'}.
  203:                    ': <label>'.
  204:                    '<input type="radio" name="customquota" value="0" '.
  205:                    $custom_off.' onchange="javascript:quota_changes('."'custom'".')"'.
  206:                    ' />'.$lt{'defa'}.'&nbsp;('.$defquota.' Mb).</label>&nbsp;'.
  207:                    '&nbsp;<label><input type="radio" name="customquota" value="1" '. 
  208:                    $custom_on.'  onchange="javascript:quota_changes('."'custom'".')" />'.
  209:                    $lt{'cust'}.':</label>&nbsp;'.
  210:                    '<input type="text" name="portfolioquota" size ="5" value="'.
  211:                    $showquota.'" onfocus="javascript:quota_changes('."'quota'".')" '.
  212:                    '/>&nbsp;Mb</span></td>'."\n".
  213:                    &Apache::loncommon::end_data_table_row()."\n";
  214:     }  
  215:     $output .= &Apache::loncommon::end_data_table();
  216:     return $output;
  217: }
  218: 
  219: sub build_tools_display {
  220:     my ($ccuname,$ccdomain,$context) = @_;
  221:     my (@usertools,%userenv,$output,@options,%validations,%reqtitles,%reqdisplay,
  222:         $colspan,$isadv,%domconfig);
  223:     my %lt = &Apache::lonlocal::texthash (
  224:                    'blog'       => "Personal User Blog",
  225:                    'aboutme'    => "Personal Information Page",
  226:                    'webdav'     => "WebDAV access to authoring spaces (if SSL and author/co-author)",
  227:                    'portfolio'  => "Personal User Portfolio",
  228:                    'avai'       => "Available",
  229:                    'cusa'       => "availability",
  230:                    'chse'       => "Change setting",
  231:                    'usde'       => "Use default",
  232:                    'uscu'       => "Use custom",
  233:                    'official'   => 'Can request creation of official courses',
  234:                    'unofficial' => 'Can request creation of unofficial courses',
  235:                    'community'  => 'Can request creation of communities',
  236:                    'requestauthor'  => 'Can request author space',
  237:     );
  238:     if ($context eq 'requestcourses') {
  239:         %userenv = &Apache::lonnet::userenvironment($ccdomain,$ccuname,
  240:                       'requestcourses.official','requestcourses.unofficial',
  241:                       'requestcourses.community');
  242:         @usertools = ('official','unofficial','community');
  243:         @options =('norequest','approval','autolimit','validate');
  244:         %validations = &Apache::lonnet::auto_courserequest_checks($ccdomain);
  245:         %reqtitles = &courserequest_titles();
  246:         %reqdisplay = &courserequest_display();
  247:         $colspan = ' colspan="2"';
  248:         %domconfig =
  249:             &Apache::lonnet::get_dom('configuration',['requestcourses'],$ccdomain);
  250:         $isadv = &Apache::lonnet::is_advanced_user($ccuname,$ccdomain);
  251:     } elsif ($context eq 'requestauthor') {
  252:         %userenv = &Apache::lonnet::userenvironment($ccdomain,$ccuname,
  253:                                                     'requestauthor');
  254:         @usertools = ('requestauthor');
  255:         @options =('norequest','approval','automatic');
  256:         %reqtitles = &requestauthor_titles();
  257:         %reqdisplay = &requestauthor_display();
  258:         $colspan = ' colspan="2"';
  259:         %domconfig =
  260:             &Apache::lonnet::get_dom('configuration',['requestauthor'],$ccdomain);
  261:     } else {
  262:         %userenv = &Apache::lonnet::userenvironment($ccdomain,$ccuname,
  263:                           'tools.aboutme','tools.portfolio','tools.blog',
  264:                           'tools.webdav');
  265:         @usertools = ('aboutme','blog','webdav','portfolio');
  266:     }
  267:     foreach my $item (@usertools) {
  268:         my ($custom_access,$curr_access,$cust_on,$cust_off,$tool_on,$tool_off,
  269:             $currdisp,$custdisp,$custradio);
  270:         $cust_off = 'checked="checked" ';
  271:         $tool_on = 'checked="checked" ';
  272:         $curr_access =  
  273:             &Apache::lonnet::usertools_access($ccuname,$ccdomain,$item,undef,
  274:                                               $context);
  275:         if ($context eq 'requestauthor') {
  276:             if ($userenv{$context} ne '') {
  277:                 $cust_on = ' checked="checked" ';
  278:                 $cust_off = '';
  279:             }  
  280:         } elsif ($userenv{$context.'.'.$item} ne '') {
  281:             $cust_on = ' checked="checked" ';
  282:             $cust_off = '';
  283:         }
  284:         if ($context eq 'requestcourses') {
  285:             if ($userenv{$context.'.'.$item} eq '') {
  286:                 $custom_access = &mt('Currently from default setting.');
  287:             } else {
  288:                 $custom_access = &mt('Currently from custom setting.');
  289:             }
  290:         } elsif ($context eq 'requestauthor') {
  291:             if ($userenv{$context} eq '') {
  292:                 $custom_access = &mt('Currently from default setting.');
  293:             } else {
  294:                 $custom_access = &mt('Currently from custom setting.');
  295:             }
  296:         } else {
  297:             if ($userenv{$context.'.'.$item} eq '') {
  298:                 $custom_access =
  299:                     &mt('Availability determined currently from default setting.');
  300:                 if (!$curr_access) {
  301:                     $tool_off = 'checked="checked" ';
  302:                     $tool_on = '';
  303:                 }
  304:             } else {
  305:                 $custom_access =
  306:                     &mt('Availability determined currently from custom setting.');
  307:                 if ($userenv{$context.'.'.$item} == 0) {
  308:                     $tool_off = 'checked="checked" ';
  309:                     $tool_on = '';
  310:                 }
  311:             }
  312:         }
  313:         $output .= '  <tr class="LC_info_row">'."\n".
  314:                    '   <td'.$colspan.'>'.$lt{$item}.'</td>'."\n".
  315:                    '  </tr>'."\n".
  316:                    &Apache::loncommon::start_data_table_row()."\n";
  317:         if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
  318:             my ($curroption,$currlimit);
  319:             my $envkey = $context.'.'.$item;
  320:             if ($context eq 'requestauthor') {
  321:                 $envkey = $context;
  322:             }
  323:             if ($userenv{$envkey} ne '') {
  324:                 $curroption = $userenv{$envkey};
  325:             } else {
  326:                 my (@inststatuses);
  327:                 if ($context eq 'requestcourses') {
  328:                     $curroption =
  329:                         &Apache::loncoursequeueadmin::get_processtype('course',$ccuname,$ccdomain,
  330:                                                                       $isadv,$ccdomain,$item,
  331:                                                                       \@inststatuses,\%domconfig);
  332:                 } else {
  333:                      $curroption = 
  334:                          &Apache::loncoursequeueadmin::get_processtype('requestauthor',$ccuname,$ccdomain,
  335:                                                                        $isadv,$ccdomain,undef,
  336:                                                                        \@inststatuses,\%domconfig);
  337:                 }
  338:             }
  339:             if (!$curroption) {
  340:                 $curroption = 'norequest';
  341:             }
  342:             if ($curroption =~ /^autolimit=(\d*)$/) {
  343:                 $currlimit = $1;
  344:                 if ($currlimit eq '') {
  345:                     $currdisp = &mt('Yes, automatic creation');
  346:                 } else {
  347:                     $currdisp = &mt('Yes, up to [quant,_1,request]/user',$currlimit);
  348:                 }
  349:             } else {
  350:                 $currdisp = $reqdisplay{$curroption};
  351:             }
  352:             $custdisp = '<table>';
  353:             foreach my $option (@options) {
  354:                 my $val = $option;
  355:                 if ($option eq 'norequest') {
  356:                     $val = 0;
  357:                 }
  358:                 if ($option eq 'validate') {
  359:                     my $canvalidate = 0;
  360:                     if (ref($validations{$item}) eq 'HASH') {
  361:                         if ($validations{$item}{'_custom_'}) {
  362:                             $canvalidate = 1;
  363:                         }
  364:                     }
  365:                     next if (!$canvalidate);
  366:                 }
  367:                 my $checked = '';
  368:                 if ($option eq $curroption) {
  369:                     $checked = ' checked="checked"';
  370:                 } elsif ($option eq 'autolimit') {
  371:                     if ($curroption =~ /^autolimit/) {
  372:                         $checked = ' checked="checked"';
  373:                     }
  374:                 }
  375:                 my $name = 'crsreq_'.$item;
  376:                 if ($context eq 'requestauthor') {
  377:                     $name = $item;
  378:                 }
  379:                 $custdisp .= '<tr><td><span class="LC_nobreak"><label>'.
  380:                              '<input type="radio" name="'.$name.'" '.
  381:                              'value="'.$val.'"'.$checked.' />'.
  382:                              $reqtitles{$option}.'</label>&nbsp;';
  383:                 if ($option eq 'autolimit') {
  384:                     $custdisp .= '<input type="text" name="'.$name.
  385:                                  '_limit" size="1" '.
  386:                                  'value="'.$currlimit.'" /></span><br />'.
  387:                                  $reqtitles{'unlimited'};
  388:                 } else {
  389:                     $custdisp .= '</span>';
  390:                 }
  391:                 $custdisp .= '</td></tr>';
  392:             }
  393:             $custdisp .= '</table>';
  394:             $custradio = '</span></td><td>'.&mt('Custom setting').'<br />'.$custdisp;
  395:         } else {
  396:             $currdisp = ($curr_access?&mt('Yes'):&mt('No'));
  397:             my $name = $context.'_'.$item;
  398:             if ($context eq 'requestauthor') {
  399:                 $name = $context;
  400:             }
  401:             $custdisp = '<span class="LC_nobreak"><label>'.
  402:                         '<input type="radio" name="'.$name.'"'.
  403:                         ' value="1" '.$tool_on.'/>'.&mt('On').'</label>&nbsp;<label>'.
  404:                         '<input type="radio" name="'.$name.'" value="0" '.
  405:                         $tool_off.'/>'.&mt('Off').'</label></span>';
  406:             $custradio = ('&nbsp;'x2).'--'.$lt{'cusa'}.':&nbsp;'.$custdisp.
  407:                           '</span>';
  408:         }
  409:         $output .= '  <td'.$colspan.'>'.$custom_access.('&nbsp;'x4).
  410:                    $lt{'avai'}.': '.$currdisp.'</td>'."\n".
  411:                    &Apache::loncommon::end_data_table_row()."\n".
  412:                    &Apache::loncommon::start_data_table_row()."\n".
  413:                    '  <td style="vertical-align:top;"><span class="LC_nobreak">'.
  414:                    $lt{'chse'}.': <label>'.
  415:                    '<input type="radio" name="custom'.$item.'" value="0" '.
  416:                    $cust_off.'/>'.$lt{'usde'}.'</label>'.('&nbsp;' x3).
  417:                    '<label><input type="radio" name="custom'.$item.'" value="1" '.
  418:                    $cust_on.'/>'.$lt{'uscu'}.'</label>'.$custradio.'</td>'.
  419:                    &Apache::loncommon::end_data_table_row()."\n";
  420:     }
  421:     return $output;
  422: }
  423: 
  424: sub coursereq_externaluser {
  425:     my ($ccuname,$ccdomain,$cdom) = @_;
  426:     my (@usertools,@options,%validations,%userenv,$output);
  427:     my %lt = &Apache::lonlocal::texthash (
  428:                    'official'   => 'Can request creation of official courses',
  429:                    'unofficial' => 'Can request creation of unofficial courses',
  430:                    'community'  => 'Can request creation of communities',
  431:     );
  432: 
  433:     %userenv = &Apache::lonnet::userenvironment($ccdomain,$ccuname,
  434:                       'reqcrsotherdom.official','reqcrsotherdom.unofficial',
  435:                       'reqcrsotherdom.community');
  436:     @usertools = ('official','unofficial','community');
  437:     @options = ('approval','validate','autolimit');
  438:     %validations = &Apache::lonnet::auto_courserequest_checks($cdom);
  439:     my $optregex = join('|',@options);
  440:     my %reqtitles = &courserequest_titles();
  441:     foreach my $item (@usertools) {
  442:         my ($curroption,$currlimit,$tooloff);
  443:         if ($userenv{'reqcrsotherdom.'.$item} ne '') {
  444:             my @curr = split(',',$userenv{'reqcrsotherdom.'.$item});
  445:             foreach my $req (@curr) {
  446:                 if ($req =~ /^\Q$cdom\E\:($optregex)=?(\d*)$/) {
  447:                     $curroption = $1;
  448:                     $currlimit = $2;
  449:                     last;
  450:                 }
  451:             }
  452:             if (!$curroption) {
  453:                 $curroption = 'norequest';
  454:                 $tooloff = ' checked="checked"';
  455:             }
  456:         } else {
  457:             $curroption = 'norequest';
  458:             $tooloff = ' checked="checked"';
  459:         }
  460:         $output.= &Apache::loncommon::start_data_table_row()."\n".
  461:                   '  <td><span class="LC_nobreak">'.$lt{$item}.': </span></td><td>'.
  462:                   '<table><tr><td valign="top">'."\n".
  463:                   '<label><input type="radio" name="reqcrsotherdom_'.$item.
  464:                   '" value=""'.$tooloff.' />'.$reqtitles{'norequest'}.
  465:                   '</label></td>';
  466:         foreach my $option (@options) {
  467:             if ($option eq 'validate') {
  468:                 my $canvalidate = 0;
  469:                 if (ref($validations{$item}) eq 'HASH') {
  470:                     if ($validations{$item}{'_external_'}) {
  471:                         $canvalidate = 1;
  472:                     }
  473:                 }
  474:                 next if (!$canvalidate);
  475:             }
  476:             my $checked = '';
  477:             if ($option eq $curroption) {
  478:                 $checked = ' checked="checked"';
  479:             }
  480:             $output .= '<td valign="top"><span class="LC_nobreak"><label>'.
  481:                        '<input type="radio" name="reqcrsotherdom_'.$item.
  482:                        '" value="'.$option.'"'.$checked.' />'.
  483:                        $reqtitles{$option}.'</label>';
  484:             if ($option eq 'autolimit') {
  485:                 $output .= '&nbsp;<input type="text" name="reqcrsotherdom_'.
  486:                            $item.'_limit" size="1" '.
  487:                            'value="'.$currlimit.'" /></span>'.
  488:                            '<br />'.$reqtitles{'unlimited'};
  489:             } else {
  490:                 $output .= '</span>';
  491:             }
  492:             $output .= '</td>';
  493:         }
  494:         $output .= '</td></tr></table></td>'."\n".
  495:                    &Apache::loncommon::end_data_table_row()."\n";
  496:     }
  497:     return $output;
  498: }
  499: 
  500: sub domainrole_req {
  501:     my ($ccuname,$ccdomain) = @_;
  502:     return '<br /><h3>'.
  503:            &mt('User Can Request Assignment of Domain Roles?').
  504:            '</h3>'."\n".
  505:            &Apache::loncommon::start_data_table().
  506:            &build_tools_display($ccuname,$ccdomain,
  507:                                 'requestauthor').
  508:            &Apache::loncommon::end_data_table();
  509: }
  510: 
  511: sub courserequest_titles {
  512:     my %titles = &Apache::lonlocal::texthash (
  513:                                    official   => 'Official',
  514:                                    unofficial => 'Unofficial',
  515:                                    community  => 'Communities',
  516:                                    norequest  => 'Not allowed',
  517:                                    approval   => 'Approval by Dom. Coord.',
  518:                                    validate   => 'With validation',
  519:                                    autolimit  => 'Numerical limit',
  520:                                    unlimited  => '(blank for unlimited)',
  521:                  );
  522:     return %titles;
  523: }
  524: 
  525: sub courserequest_display {
  526:     my %titles = &Apache::lonlocal::texthash (
  527:                                    approval   => 'Yes, need approval',
  528:                                    validate   => 'Yes, with validation',
  529:                                    norequest  => 'No',
  530:    );
  531:    return %titles;
  532: }
  533: 
  534: sub requestauthor_titles {
  535:     my %titles = &Apache::lonlocal::texthash (
  536:                                    norequest  => 'Not allowed',
  537:                                    approval   => 'Approval by Dom. Coord.',
  538:                                    automatic  => 'Automatic approval',
  539:                  );
  540:     return %titles;
  541: 
  542: }
  543: 
  544: sub requestauthor_display {
  545:     my %titles = &Apache::lonlocal::texthash (
  546:                                    approval   => 'Yes, need approval',
  547:                                    automatic  => 'Yes, automatic approval',
  548:                                    norequest  => 'No',
  549:    );
  550:    return %titles;
  551: }
  552: 
  553: sub curr_requestauthor {
  554:     my ($uname,$udom,$isadv,$inststatuses,$domconfig) = @_;
  555:     return unless ((ref($inststatuses) eq 'ARRAY') && (ref($domconfig) eq 'HASH'));
  556:     if ($uname eq '' || $udom eq '') {
  557:         $uname = $env{'user.name'};
  558:         $udom = $env{'user.domain'};
  559:         $isadv = $env{'user.adv'};
  560:     }
  561:     my (%userenv,%settings,$val);
  562:     my @options = ('automatic','approval');
  563:     %userenv =
  564:         &Apache::lonnet::userenvironment($udom,$uname,'requestauthor','inststatus');
  565:     if ($userenv{'requestauthor'}) {
  566:         $val = $userenv{'requestauthor'};
  567:         @{$inststatuses} = ('_custom_');
  568:     } else {
  569:         my %alltasks;
  570:         if (ref($domconfig->{'requestauthor'}) eq 'HASH') {
  571:             %settings = %{$domconfig->{'requestauthor'}};
  572:             if (($isadv) && ($settings{'_LC_adv'} ne '')) {
  573:                 $val = $settings{'_LC_adv'};
  574:                 @{$inststatuses} = ('_LC_adv_');
  575:             } else {
  576:                 if ($userenv{'inststatus'} ne '') {
  577:                     @{$inststatuses} = split(',',$userenv{'inststatus'});
  578:                 } else {
  579:                     @{$inststatuses} = ('default');
  580:                 }
  581:                 foreach my $status (@{$inststatuses}) {
  582:                     if (exists($settings{$status})) {
  583:                         my $value = $settings{$status};
  584:                         next unless ($value);
  585:                         unless (exists($alltasks{$value})) {
  586:                             if (ref($alltasks{$value}) eq 'ARRAY') {
  587:                                 unless(grep(/^\Q$status\E$/,@{$alltasks{$value}})) {
  588:                                     push(@{$alltasks{$value}},$status);
  589:                                 }
  590:                             } else {
  591:                                 @{$alltasks{$value}} = ($status);
  592:                             }
  593:                         }
  594:                     }
  595:                 }
  596:                 foreach my $option (@options) {
  597:                     if ($alltasks{$option}) {
  598:                         $val = $option;
  599:                         last;
  600:                     }
  601:                 }
  602:             }
  603:         }
  604:     }
  605:     return $val;
  606: }
  607: 
  608: # =================================================================== Phase one
  609: 
  610: sub print_username_entry_form {
  611:     my ($r,$context,$response,$srch,$forcenewuser,$crstype,$brcrum) = @_;
  612:     my $defdom=$env{'request.role.domain'};
  613:     my $formtoset = 'crtuser';
  614:     if (exists($env{'form.startrolename'})) {
  615:         $formtoset = 'docustom';
  616:         $env{'form.rolename'} = $env{'form.startrolename'};
  617:     } elsif ($env{'form.origform'} eq 'crtusername') {
  618:         $formtoset =  $env{'form.origform'};
  619:     }
  620: 
  621:     my ($jsback,$elements) = &crumb_utilities();
  622: 
  623:     my $jscript = &Apache::loncommon::studentbrowser_javascript()."\n".
  624:         '<script type="text/javascript">'."\n".
  625:         '// <![CDATA['."\n".
  626:         &Apache::lonhtmlcommon::set_form_elements($elements->{$formtoset})."\n".
  627:         '// ]]>'."\n".
  628:         '</script>'."\n";
  629: 
  630:     my %existingroles=&Apache::lonuserutils::my_custom_roles($crstype);
  631:     if (($env{'form.action'} eq 'custom') && (keys(%existingroles) > 0)
  632:         && (&Apache::lonnet::allowed('mcr','/'))) {
  633:         $jscript .= &customrole_javascript();
  634:     }
  635:     my $helpitem = 'Course_Change_Privileges';
  636:     if ($env{'form.action'} eq 'custom') {
  637:         $helpitem = 'Course_Editing_Custom_Roles';
  638:     } elsif ($env{'form.action'} eq 'singlestudent') {
  639:         $helpitem = 'Course_Add_Student';
  640:     }
  641:     my %breadcrumb_text = &singleuser_breadcrumb($crstype);
  642:     if ($env{'form.action'} eq 'custom') {
  643:         push(@{$brcrum},
  644:                  {href=>"javascript:backPage(document.crtuser)",       
  645:                   text=>"Pick custom role",
  646:                   help => $helpitem,}
  647:                  );
  648:     } else {
  649:         push (@{$brcrum},
  650:                   {href => "javascript:backPage(document.crtuser)",
  651:                    text => $breadcrumb_text{'search'},
  652:                    help => $helpitem,
  653:                    faq  => 282,
  654:                    bug  => 'Instructor Interface',}
  655:                   );
  656:     }
  657:     my %loaditems = (
  658:                 'onload' => "javascript:setFormElements(document.$formtoset)",
  659:                     );
  660:     my $args = {bread_crumbs           => $brcrum,
  661:                 bread_crumbs_component => 'User Management',
  662:                 add_entries            => \%loaditems,};
  663:     $r->print(&Apache::loncommon::start_page('User Management',$jscript,$args));
  664: 
  665:     my %lt=&Apache::lonlocal::texthash(
  666:                     'srst' => 'Search for a user and enroll as a student',
  667:                     'srme' => 'Search for a user and enroll as a member',
  668:                     'srad' => 'Search for a user and modify/add user information or roles',
  669: 		    'usr'  => "Username",
  670:                     'dom'  => "Domain",
  671:                     'ecrp' => "Define or Edit Custom Role",
  672:                     'nr'   => "role name",
  673:                     'cre'  => "Next",
  674: 				       );
  675: 
  676:     if ($env{'form.action'} eq 'custom') {
  677:         if (&Apache::lonnet::allowed('mcr','/')) {
  678:             my $newroletext = &mt('Define new custom role:');
  679:             $r->print('<form action="/adm/createuser" method="post" name="docustom">'.
  680:                       '<input type="hidden" name="action" value="'.$env{'form.action'}.'" />'.
  681:                       '<input type="hidden" name="phase" value="selected_custom_edit" />'.
  682:                       '<h3>'.$lt{'ecrp'}.'</h3>'.
  683:                       &Apache::loncommon::start_data_table().
  684:                       &Apache::loncommon::start_data_table_row().
  685:                       '<td>');
  686:             if (keys(%existingroles) > 0) {
  687:                 $r->print('<br /><label><input type="radio" name="customroleaction" value="new" checked="checked" onclick="setCustomFields();" /><b>'.$newroletext.'</b></label>');
  688:             } else {
  689:                 $r->print('<br /><input type="hidden" name="customroleaction" value="new" /><b>'.$newroletext.'</b>');
  690:             }
  691:             $r->print('</td><td align="center">'.$lt{'nr'}.'<br /><input type="text" size="15" name="newrolename" onfocus="setCustomAction('."'new'".');" /></td>'.
  692:                       &Apache::loncommon::end_data_table_row());
  693:             if (keys(%existingroles) > 0) {
  694:                 $r->print(&Apache::loncommon::start_data_table_row().'<td><br />'.
  695:                           '<label><input type="radio" name="customroleaction" value="edit" onclick="setCustomFields();"/><b>'.
  696:                           &mt('View/Modify existing role:').'</b></label></td>'.
  697:                           '<td align="center"><br />'.
  698:                           '<select name="rolename" onchange="setCustomAction('."'edit'".');">'.
  699:                           '<option value="" selected="selected">'.
  700:                           &mt('Select'));
  701:                 foreach my $role (sort(keys(%existingroles))) {
  702:                     $r->print('<option value="'.$role.'">'.$role.'</option>');
  703:                 }
  704:                 $r->print('</select>'.
  705:                           '</td>'.
  706:                           &Apache::loncommon::end_data_table_row());
  707:             }
  708:             $r->print(&Apache::loncommon::end_data_table().'<p>'.
  709:                       '<input name="customeditor" type="submit" value="'.
  710:                       $lt{'cre'}.'" /></p>'.
  711:                       '</form>');
  712:         }
  713:     } else {
  714:         my $actiontext = $lt{'srad'};
  715:         if ($env{'form.action'} eq 'singlestudent') {
  716:             if ($crstype eq 'Community') {
  717:                 $actiontext = $lt{'srme'};
  718:             } else {
  719:                 $actiontext = $lt{'srst'};
  720:             }
  721:         }
  722:         $r->print("<h3>$actiontext</h3>");
  723:         if ($env{'form.origform'} ne 'crtusername') {
  724:             $r->print("\n".$response);
  725:         }
  726:         $r->print(&entry_form($defdom,$srch,$forcenewuser,$context,$response,$crstype));
  727:     }
  728: }
  729: 
  730: sub customrole_javascript {
  731:     my $js = <<"END";
  732: <script type="text/javascript">
  733: // <![CDATA[
  734: 
  735: function setCustomFields() {
  736:     if (document.docustom.customroleaction.length > 0) {
  737:         for (var i=0; i<document.docustom.customroleaction.length; i++) {
  738:             if (document.docustom.customroleaction[i].checked) {
  739:                 if (document.docustom.customroleaction[i].value == 'new') {
  740:                     document.docustom.rolename.selectedIndex = 0;
  741:                 } else {
  742:                     document.docustom.newrolename.value = '';
  743:                 }
  744:             }
  745:         }
  746:     }
  747:     return;
  748: }
  749: 
  750: function setCustomAction(caller) {
  751:     if (document.docustom.customroleaction.length > 0) {
  752:         for (var i=0; i<document.docustom.customroleaction.length; i++) {
  753:             if (document.docustom.customroleaction[i].value == caller) {
  754:                 document.docustom.customroleaction[i].checked = true;
  755:             }
  756:         }
  757:     }
  758:     setCustomFields();
  759:     return;
  760: }
  761: 
  762: // ]]>
  763: </script>
  764: END
  765:     return $js;
  766: }
  767: 
  768: sub entry_form {
  769:     my ($dom,$srch,$forcenewuser,$context,$responsemsg,$crstype) = @_;
  770:     my ($usertype,$inexact);
  771:     if (ref($srch) eq 'HASH') {
  772:         if (($srch->{'srchin'} eq 'dom') &&
  773:             ($srch->{'srchby'} eq 'uname') &&
  774:             ($srch->{'srchtype'} eq 'exact') &&
  775:             ($srch->{'srchdomain'} ne '') &&
  776:             ($srch->{'srchterm'} ne '')) {
  777:             my (%curr_rules,%got_rules);
  778:             my ($rules,$ruleorder) =
  779:                 &Apache::lonnet::inst_userrules($srch->{'srchdomain'},'username');
  780:             $usertype = &Apache::lonuserutils::check_usertype($srch->{'srchdomain'},$srch->{'srchterm'},$rules,\%curr_rules,\%got_rules);
  781:         } else {
  782:             $inexact = 1;
  783:         }
  784:     }
  785:     my $cancreate =
  786:         &Apache::lonuserutils::can_create_user($dom,$context,$usertype);
  787:     my $userpicker = 
  788:        &Apache::loncommon::user_picker($dom,$srch,$forcenewuser,
  789:                                        'document.crtuser',$cancreate,$usertype);
  790:     my $srchbutton = &mt('Search');
  791:     if ($env{'form.action'} eq 'singlestudent') {
  792:         $srchbutton = &mt('Search and Enroll');
  793:     } elsif ($cancreate && $responsemsg ne '' && $inexact) {
  794:         $srchbutton = &mt('Search or Add New User');
  795:     }
  796:     my $output = <<"ENDBLOCK";
  797: <form action="/adm/createuser" method="post" name="crtuser">
  798: <input type="hidden" name="action" value="$env{'form.action'}" />
  799: <input type="hidden" name="phase" value="get_user_info" />
  800: $userpicker
  801: <input name="userrole" type="button" value="$srchbutton" onclick="javascript:validateEntry(document.crtuser)" />
  802: </form>
  803: ENDBLOCK
  804:     if ($env{'form.phase'} eq '') {
  805:         my $defdom=$env{'request.role.domain'};
  806:         my $domform = &Apache::loncommon::select_dom_form($defdom,'srchdomain');
  807:         my %lt=&Apache::lonlocal::texthash(
  808:                   'enro' => 'Enroll one student',
  809:                   'enrm' => 'Enroll one member',
  810:                   'admo' => 'Add/modify a single user',
  811:                   'crea' => 'create new user if required',
  812:                   'uskn' => "username is known",
  813:                   'crnu' => 'Create a new user',
  814:                   'usr'  => 'Username',
  815:                   'dom'  => 'in domain',
  816:                   'enrl' => 'Enroll',
  817:                   'cram'  => 'Create/Modify user',
  818:         );
  819:         my $sellink=&Apache::loncommon::selectstudent_link('crtusername','srchterm','srchdomain');
  820:         my ($title,$buttontext,$showresponse);
  821:         if ($env{'form.action'} eq 'singlestudent') {
  822:             if ($crstype eq 'Community') {
  823:                 $title = $lt{'enrm'};
  824:             } else {
  825:                 $title = $lt{'enro'};
  826:             }
  827:             $buttontext = $lt{'enrl'};
  828:         } else {
  829:             $title = $lt{'admo'};
  830:             $buttontext = $lt{'cram'};
  831:         }
  832:         if ($cancreate) {
  833:             $title .= ' <span class="LC_cusr_subheading">('.$lt{'crea'}.')</span>';
  834:         } else {
  835:             $title .= ' <span class="LC_cusr_subheading">('.$lt{'uskn'}.')</span>';
  836:         }
  837:         if ($env{'form.origform'} eq 'crtusername') {
  838:             $showresponse = $responsemsg;
  839:         }
  840:         $output .= <<"ENDDOCUMENT";
  841: <br />
  842: <form action="/adm/createuser" method="post" name="crtusername">
  843: <input type="hidden" name="action" value="$env{'form.action'}" />
  844: <input type="hidden" name="phase" value="createnewuser" />
  845: <input type="hidden" name="srchtype" value="exact" />
  846: <input type="hidden" name="srchby" value="uname" />
  847: <input type="hidden" name="srchin" value="dom" />
  848: <input type="hidden" name="forcenewuser" value="1" />
  849: <input type="hidden" name="origform" value="crtusername" />
  850: <h3>$title</h3>
  851: $showresponse
  852: <table>
  853:  <tr>
  854:   <td>$lt{'usr'}:</td>
  855:   <td><input type="text" size="15" name="srchterm" /></td>
  856:   <td>&nbsp;$lt{'dom'}:</td><td>$domform</td>
  857:   <td>&nbsp;$sellink&nbsp;</td>
  858:   <td>&nbsp;<input name="userrole" type="submit" value="$buttontext" /></td>
  859:  </tr>
  860: </table>
  861: </form>
  862: ENDDOCUMENT
  863:     }
  864:     return $output;
  865: }
  866: 
  867: sub user_modification_js {
  868:     my ($pjump_def,$dc_setcourse_code,$nondc_setsection_code,$groupslist)=@_;
  869:     
  870:     return <<END;
  871: <script type="text/javascript" language="Javascript">
  872: // <![CDATA[
  873: 
  874:     $pjump_def
  875:     $dc_setcourse_code
  876: 
  877:     function dateset() {
  878:         eval("document.cu."+document.cu.pres_marker.value+
  879:             ".value=document.cu.pres_value.value");
  880:         modalWindow.close();
  881:     }
  882: 
  883:     $nondc_setsection_code
  884: // ]]>
  885: </script>
  886: END
  887: }
  888: 
  889: # =================================================================== Phase two
  890: sub print_user_selection_page {
  891:     my ($r,$response,$srch,$srch_results,$srcharray,$context,$opener_elements,$crstype,$brcrum) = @_;
  892:     my @fields = ('username','domain','lastname','firstname','permanentemail');
  893:     my $sortby = $env{'form.sortby'};
  894: 
  895:     if (!grep(/^\Q$sortby\E$/,@fields)) {
  896:         $sortby = 'lastname';
  897:     }
  898: 
  899:     my ($jsback,$elements) = &crumb_utilities();
  900: 
  901:     my $jscript = (<<ENDSCRIPT);
  902: <script type="text/javascript">
  903: // <![CDATA[
  904: function pickuser(uname,udom) {
  905:     document.usersrchform.seluname.value=uname;
  906:     document.usersrchform.seludom.value=udom;
  907:     document.usersrchform.phase.value="userpicked";
  908:     document.usersrchform.submit();
  909: }
  910: 
  911: $jsback
  912: // ]]>
  913: </script>
  914: ENDSCRIPT
  915: 
  916:     my %lt=&Apache::lonlocal::texthash(
  917:                                        'usrch'          => "User Search to add/modify roles",
  918:                                        'stusrch'        => "User Search to enroll student",
  919:                                        'memsrch'        => "User Search to enroll member",
  920:                                        'usel'           => "Select a user to add/modify roles",
  921:                                        'stusel'         => "Select a user to enroll as a student",
  922:                                        'memsel'         => "Select a user to enroll as a member",
  923:                                        'username'       => "username",
  924:                                        'domain'         => "domain",
  925:                                        'lastname'       => "last name",
  926:                                        'firstname'      => "first name",
  927:                                        'permanentemail' => "permanent e-mail",
  928:                                       );
  929:     if ($context eq 'requestcrs') {
  930:         $r->print('<div>');
  931:     } else {
  932:         my %breadcrumb_text = &singleuser_breadcrumb($crstype);
  933:         my $helpitem;
  934:         if ($env{'form.action'} eq 'singleuser') {
  935:             $helpitem = 'Course_Change_Privileges';
  936:         } elsif ($env{'form.action'} eq 'singlestudent') {
  937:             $helpitem = 'Course_Add_Student';
  938:         }
  939:         push (@{$brcrum},
  940:                   {href => "javascript:backPage(document.usersrchform,'','')",
  941:                    text => $breadcrumb_text{'search'},
  942:                    faq  => 282,
  943:                    bug  => 'Instructor Interface',},
  944:                   {href => "javascript:backPage(document.usersrchform,'get_user_info','select')",
  945:                    text => $breadcrumb_text{'userpicked'},
  946:                    faq  => 282,
  947:                    bug  => 'Instructor Interface',
  948:                    help => $helpitem}
  949:                   );
  950:         $r->print(&Apache::loncommon::start_page('User Management',$jscript,{bread_crumbs => $brcrum}));
  951:         if ($env{'form.action'} eq 'singleuser') {
  952:             $r->print("<b>$lt{'usrch'}</b><br />");
  953:             $r->print(&entry_form($srch->{'srchdomain'},$srch,undef,$context,undef,$crstype));
  954:             $r->print('<h3>'.$lt{'usel'}.'</h3>');
  955:         } elsif ($env{'form.action'} eq 'singlestudent') {
  956:             $r->print($jscript."<b>");
  957:             if ($crstype eq 'Community') {
  958:                 $r->print($lt{'memsrch'});
  959:             } else {
  960:                 $r->print($lt{'stusrch'});
  961:             }
  962:             $r->print("</b><br />");
  963:             $r->print(&entry_form($srch->{'srchdomain'},$srch,undef,$context,undef,$crstype));
  964:             $r->print('</form><h3>');
  965:             if ($crstype eq 'Community') {
  966:                 $r->print($lt{'memsel'});
  967:             } else {
  968:                 $r->print($lt{'stusel'});
  969:             }
  970:             $r->print('</h3>');
  971:         }
  972:     }
  973:     $r->print('<form name="usersrchform" method="post">'.
  974:               &Apache::loncommon::start_data_table()."\n".
  975:               &Apache::loncommon::start_data_table_header_row()."\n".
  976:               ' <th> </th>'."\n");
  977:     foreach my $field (@fields) {
  978:         $r->print(' <th><a href="javascript:document.usersrchform.sortby.value='.
  979:                   "'".$field."'".';document.usersrchform.submit();">'.
  980:                   $lt{$field}.'</a></th>'."\n");
  981:     }
  982:     $r->print(&Apache::loncommon::end_data_table_header_row());
  983: 
  984:     my @sorted_users = sort {
  985:         lc($srch_results->{$a}->{$sortby})   cmp lc($srch_results->{$b}->{$sortby})
  986:             ||
  987:         lc($srch_results->{$a}->{lastname})  cmp lc($srch_results->{$b}->{lastname})
  988:             ||
  989:         lc($srch_results->{$a}->{firstname}) cmp lc($srch_results->{$b}->{firstname})
  990: 	    ||
  991: 	lc($a) cmp lc($b)
  992:         } (keys(%$srch_results));
  993: 
  994:     foreach my $user (@sorted_users) {
  995:         my ($uname,$udom) = split(/:/,$user);
  996:         my $onclick;
  997:         if ($context eq 'requestcrs') {
  998:             $onclick =
  999:                 'onclick="javascript:gochoose('."'$uname','$udom',".
 1000:                                                "'$srch_results->{$user}->{firstname}',".
 1001:                                                "'$srch_results->{$user}->{lastname}',".
 1002:                                                "'$srch_results->{$user}->{permanentemail}'".');"';
 1003:         } else {
 1004:             $onclick =
 1005:                 ' onclick="javascript:pickuser('."'".$uname."'".','."'".$udom."'".');"';
 1006:         }
 1007:         $r->print(&Apache::loncommon::start_data_table_row().
 1008:                   '<td><input type="button" name="seluser" value="'.&mt('Select').'" '.
 1009:                   $onclick.' /></td>'.
 1010:                   '<td><tt>'.$uname.'</tt></td>'.
 1011:                   '<td><tt>'.$udom.'</tt></td>');
 1012:         foreach my $field ('lastname','firstname','permanentemail') {
 1013:             $r->print('<td>'.$srch_results->{$user}->{$field}.'</td>');
 1014:         }
 1015:         $r->print(&Apache::loncommon::end_data_table_row());
 1016:     }
 1017:     $r->print(&Apache::loncommon::end_data_table().'<br /><br />');
 1018:     if (ref($srcharray) eq 'ARRAY') {
 1019:         foreach my $item (@{$srcharray}) {
 1020:             $r->print('<input type="hidden" name="'.$item.'" value="'.$env{'form.'.$item}.'" />'."\n");
 1021:         }
 1022:     }
 1023:     $r->print(' <input type="hidden" name="sortby" value="'.$sortby.'" />'."\n".
 1024:               ' <input type="hidden" name="seluname" value="" />'."\n".
 1025:               ' <input type="hidden" name="seludom" value="" />'."\n".
 1026:               ' <input type="hidden" name="currstate" value="select" />'."\n".
 1027:               ' <input type="hidden" name="phase" value="get_user_info" />'."\n".
 1028:               ' <input type="hidden" name="action" value="'.$env{'form.action'}.'" />'."\n");
 1029:     if ($context eq 'requestcrs') {
 1030:         $r->print($opener_elements.'</form></div>');
 1031:     } else {
 1032:         $r->print($response.'</form>');
 1033:     }
 1034: }
 1035: 
 1036: sub print_user_query_page {
 1037:     my ($r,$caller,$brcrum) = @_;
 1038: # FIXME - this is for a network-wide name search (similar to catalog search)
 1039: # To use frames with similar behavior to catalog/portfolio search.
 1040: # To be implemented. 
 1041:     return;
 1042: }
 1043: 
 1044: sub print_user_modification_page {
 1045:     my ($r,$ccuname,$ccdomain,$srch,$response,$context,$permission,$crstype,$brcrum) = @_;
 1046:     if (($ccuname eq '') || ($ccdomain eq '')) {
 1047:         my $usermsg = &mt('No username and/or domain provided.');
 1048:         $env{'form.phase'} = '';
 1049: 	&print_username_entry_form($r,$context,$usermsg,'','',$crstype,$brcrum);
 1050:         return;
 1051:     }
 1052:     my ($form,$formname);
 1053:     if ($env{'form.action'} eq 'singlestudent') {
 1054:         $form = 'document.enrollstudent';
 1055:         $formname = 'enrollstudent';
 1056:     } else {
 1057:         $form = 'document.cu';
 1058:         $formname = 'cu';
 1059:     }
 1060:     my %abv_auth = &auth_abbrev();
 1061:     my (%rulematch,%inst_results,$newuser,%alerts,%curr_rules,%got_rules);
 1062:     my $uhome=&Apache::lonnet::homeserver($ccuname,$ccdomain);
 1063:     if ($uhome eq 'no_host') {
 1064:         my $usertype;
 1065:         my ($rules,$ruleorder) =
 1066:             &Apache::lonnet::inst_userrules($ccdomain,'username');
 1067:             $usertype =
 1068:                 &Apache::lonuserutils::check_usertype($ccdomain,$ccuname,$rules,
 1069:                                                       \%curr_rules,\%got_rules);
 1070:         my $cancreate =
 1071:             &Apache::lonuserutils::can_create_user($ccdomain,$context,
 1072:                                                    $usertype);
 1073:         if (!$cancreate) {
 1074:             my $helplink = 'javascript:helpMenu('."'display'".')';
 1075:             my %usertypetext = (
 1076:                 official   => 'institutional',
 1077:                 unofficial => 'non-institutional',
 1078:             );
 1079:             my $response;
 1080:             if ($env{'form.origform'} eq 'crtusername') {
 1081:                 $response = '<span class="LC_warning">'.
 1082:                             &mt('No match found for the username [_1] in LON-CAPA domain: [_2]',
 1083:                                 '<b>'.$ccuname.'</b>',$ccdomain).
 1084:                             '</span><br />';
 1085:             }
 1086:             $response .= '<p class="LC_warning">'
 1087:                         .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
 1088:                         .' '
 1089:                         .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
 1090:                             ,'<a href="'.$helplink.'">','</a>')
 1091:                         .'</p><br />';
 1092:             $env{'form.phase'} = '';
 1093:             &print_username_entry_form($r,$context,$response,undef,undef,$crstype,$brcrum);
 1094:             return;
 1095:         }
 1096:         $newuser = 1;
 1097:         my $checkhash;
 1098:         my $checks = { 'username' => 1 };
 1099:         $checkhash->{$ccuname.':'.$ccdomain} = { 'newuser' => $newuser };
 1100:         &Apache::loncommon::user_rule_check($checkhash,$checks,
 1101:             \%alerts,\%rulematch,\%inst_results,\%curr_rules,\%got_rules);
 1102:         if (ref($alerts{'username'}) eq 'HASH') {
 1103:             if (ref($alerts{'username'}{$ccdomain}) eq 'HASH') {
 1104:                 my $domdesc =
 1105:                     &Apache::lonnet::domain($ccdomain,'description');
 1106:                 if ($alerts{'username'}{$ccdomain}{$ccuname}) {
 1107:                     my $userchkmsg;
 1108:                     if (ref($curr_rules{$ccdomain}) eq 'HASH') {  
 1109:                         $userchkmsg = 
 1110:                             &Apache::loncommon::instrule_disallow_msg('username',
 1111:                                                                  $domdesc,1).
 1112:                         &Apache::loncommon::user_rule_formats($ccdomain,
 1113:                             $domdesc,$curr_rules{$ccdomain}{'username'},
 1114:                             'username');
 1115:                     }
 1116:                     $env{'form.phase'} = '';
 1117:                     &print_username_entry_form($r,$context,$userchkmsg,undef,undef,$crstype,$brcrum);
 1118:                     return;
 1119:                 }
 1120:             }
 1121:         }
 1122:     } else {
 1123:         $newuser = 0;
 1124:     }
 1125:     if ($response) {
 1126:         $response = '<br />'.$response;
 1127:     }
 1128: 
 1129:     my $pjump_def = &Apache::lonhtmlcommon::pjump_javascript_definition();
 1130:     my $dc_setcourse_code = '';
 1131:     my $nondc_setsection_code = '';                                        
 1132:     my %loaditem;
 1133: 
 1134:     my $groupslist = &Apache::lonuserutils::get_groupslist();
 1135: 
 1136:     my $js = &validation_javascript($context,$ccdomain,$pjump_def,
 1137:                                $groupslist,$newuser,$formname,\%loaditem);
 1138:     my %breadcrumb_text = &singleuser_breadcrumb($crstype);
 1139:     my $helpitem = 'Course_Change_Privileges';
 1140:     if ($env{'form.action'} eq 'singlestudent') {
 1141:         $helpitem = 'Course_Add_Student';
 1142:     }
 1143:     push (@{$brcrum},
 1144:         {href => "javascript:backPage($form)",
 1145:          text => $breadcrumb_text{'search'},
 1146:          faq  => 282,
 1147:          bug  => 'Instructor Interface',});
 1148:     if ($env{'form.phase'} eq 'userpicked') {
 1149:        push(@{$brcrum},
 1150:               {href => "javascript:backPage($form,'get_user_info','select')",
 1151:                text => $breadcrumb_text{'userpicked'},
 1152:                faq  => 282,
 1153:                bug  => 'Instructor Interface',});
 1154:     }
 1155:     push(@{$brcrum},
 1156:             {href => "javascript:backPage($form,'$env{'form.phase'}','modify')",
 1157:              text => $breadcrumb_text{'modify'},
 1158:              faq  => 282,
 1159:              bug  => 'Instructor Interface',
 1160:              help => $helpitem});
 1161:     my $args = {'add_entries'           => \%loaditem,
 1162:                 'bread_crumbs'          => $brcrum,
 1163:                 'bread_crumbs_component' => 'User Management'};
 1164:     if ($env{'form.popup'}) {
 1165:         $args->{'no_nav_bar'} = 1;
 1166:     }
 1167:     my $start_page =
 1168:         &Apache::loncommon::start_page('User Management',$js,$args);
 1169: 
 1170:     my $forminfo =<<"ENDFORMINFO";
 1171: <form action="/adm/createuser" method="post" name="$formname">
 1172: <input type="hidden" name="phase" value="update_user_data" />
 1173: <input type="hidden" name="ccuname" value="$ccuname" />
 1174: <input type="hidden" name="ccdomain" value="$ccdomain" />
 1175: <input type="hidden" name="pres_value"  value="" />
 1176: <input type="hidden" name="pres_type"   value="" />
 1177: <input type="hidden" name="pres_marker" value="" />
 1178: ENDFORMINFO
 1179:     my (%inccourses,$roledom);
 1180:     if ($context eq 'course') {
 1181:         $inccourses{$env{'request.course.id'}}=1;
 1182:         $roledom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 1183:     } elsif ($context eq 'author') {
 1184:         $roledom = $env{'request.role.domain'};
 1185:     } elsif ($context eq 'domain') {
 1186:         foreach my $key (keys(%env)) {
 1187:             $roledom = $env{'request.role.domain'};
 1188:             if ($key=~/^user\.priv\.cm\.\/($roledom)\/($match_username)/) {
 1189:                 $inccourses{$1.'_'.$2}=1;
 1190:             }
 1191:         }
 1192:     } else {
 1193:         foreach my $key (keys(%env)) {
 1194: 	    if ($key=~/^user\.priv\.cm\.\/($match_domain)\/($match_username)/) {
 1195: 	        $inccourses{$1.'_'.$2}=1;
 1196:             }
 1197:         }
 1198:     }
 1199:     if ($newuser) {
 1200:         my ($portfolioform,$domroleform);
 1201:         if ((&Apache::lonnet::allowed('mpq',$env{'request.role.domain'})) ||
 1202:             (&Apache::lonnet::allowed('mut',$env{'request.role.domain'}))) {
 1203:             # Current user has quota or user tools modification privileges
 1204:             $portfolioform = '<br />'.&portfolio_quota($ccuname,$ccdomain);
 1205:         }
 1206:         if (&Apache::lonnet::allowed('cau',$env{'request.role.domain'})) {
 1207:             $domroleform = '<br />'.&domainrole_req($ccuname,$ccdomain);
 1208:         }
 1209:         &initialize_authen_forms($ccdomain,$formname);
 1210:         my %lt=&Apache::lonlocal::texthash(
 1211:                 'cnu'            => 'Create New User',
 1212:                 'ast'            => 'as a student',
 1213:                 'ame'            => 'as a member',
 1214:                 'ind'            => 'in domain',
 1215:                 'lg'             => 'Login Data',
 1216:                 'hs'             => "Home Server",
 1217:         );
 1218: 	$r->print(<<ENDTITLE);
 1219: $start_page
 1220: $response
 1221: $forminfo
 1222: <script type="text/javascript" language="Javascript">
 1223: // <![CDATA[
 1224: $loginscript
 1225: // ]]>
 1226: </script>
 1227: <input type='hidden' name='makeuser' value='1' />
 1228: <h2>$lt{'cnu'} "$ccuname" $lt{'ind'} $ccdomain
 1229: ENDTITLE
 1230:         if ($env{'form.action'} eq 'singlestudent') {
 1231:             if ($crstype eq 'Community') {
 1232:                 $r->print(' ('.$lt{'ame'}.')');
 1233:             } else {
 1234:                 $r->print(' ('.$lt{'ast'}.')');
 1235:             }
 1236:         }
 1237:         $r->print('</h2>'."\n".'<div class="LC_left_float">');
 1238:         my $personal_table = 
 1239:             &personal_data_display($ccuname,$ccdomain,$newuser,$context,
 1240:                                    $inst_results{$ccuname.':'.$ccdomain});
 1241:         $r->print($personal_table);
 1242:         my ($home_server_pick,$numlib) = 
 1243:             &Apache::loncommon::home_server_form_item($ccdomain,'hserver',
 1244:                                                       'default','hide');
 1245:         if ($numlib > 1) {
 1246:             $r->print("
 1247: <br />
 1248: $lt{'hs'}: $home_server_pick
 1249: <br />");
 1250:         } else {
 1251:             $r->print($home_server_pick);
 1252:         }
 1253:         if (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) {
 1254:             $r->print('<br /><h3>'.
 1255:                       &mt('User Can Request Creation of Courses/Communities in this Domain?').'</h3>'.
 1256:                       &Apache::loncommon::start_data_table().
 1257:                       &build_tools_display($ccuname,$ccdomain,
 1258:                                            'requestcourses').
 1259:                       &Apache::loncommon::end_data_table());
 1260:         }
 1261:         $r->print('</div>'."\n".'<div class="LC_left_float"><h3>'.
 1262:                   $lt{'lg'}.'</h3>');
 1263:         my ($fixedauth,$varauth,$authmsg); 
 1264:         if (ref($rulematch{$ccuname.':'.$ccdomain}) eq 'HASH') {
 1265:             my $matchedrule = $rulematch{$ccuname.':'.$ccdomain}{'username'};
 1266:             my ($rules,$ruleorder) = 
 1267:                 &Apache::lonnet::inst_userrules($ccdomain,'username');
 1268:             if (ref($rules) eq 'HASH') {
 1269:                 if (ref($rules->{$matchedrule}) eq 'HASH') {
 1270:                     my $authtype = $rules->{$matchedrule}{'authtype'};
 1271:                     if ($authtype !~ /^(krb4|krb5|int|fsys|loc)$/) {
 1272:                         $r->print(&Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc));
 1273:                     } else { 
 1274:                         my $authparm = $rules->{$matchedrule}{'authparm'};
 1275:                         $authmsg = $rules->{$matchedrule}{'authmsg'};
 1276:                         if ($authtype =~ /^krb(4|5)$/) {
 1277:                             my $ver = $1;
 1278:                             if ($authparm ne '') {
 1279:                                 $fixedauth = <<"KERB"; 
 1280: <input type="hidden" name="login" value="krb" />
 1281: <input type="hidden" name="krbver" value="$ver" />
 1282: <input type="hidden" name="krbarg" value="$authparm" />
 1283: KERB
 1284:                             }
 1285:                         } else {
 1286:                             $fixedauth = 
 1287: '<input type="hidden" name="login" value="'.$authtype.'" />'."\n";
 1288:                             if ($rules->{$matchedrule}{'authparmfixed'}) {
 1289:                                 $fixedauth .=    
 1290: '<input type="hidden" name="'.$authtype.'arg" value="'.$authparm.'" />'."\n";
 1291:                             } else {
 1292:                                 if ($authtype eq 'int') {
 1293:                                     $varauth = '<br />'.
 1294: &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>';
 1295:                                 } elsif ($authtype eq 'loc') {
 1296:                                     $varauth = '<br />'.
 1297: &mt('[_1] Local Authentication with argument [_2]','','<input type="text" name="'.$authtype.'arg" value="" />')."\n";
 1298:                                 } else {
 1299:                                     $varauth =
 1300: '<input type="text" name="'.$authtype.'arg" value="" />'."\n";
 1301:                                 }
 1302:                             }
 1303:                         }
 1304:                     }
 1305:                 } else {
 1306:                     $r->print(&Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc));
 1307:                 }
 1308:             }
 1309:             if ($authmsg) {
 1310:                 $r->print(<<ENDAUTH);
 1311: $fixedauth
 1312: $authmsg
 1313: $varauth
 1314: ENDAUTH
 1315:             }
 1316:         } else {
 1317:             $r->print(&Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc)); 
 1318:         }
 1319:         $r->print($portfolioform.$domroleform);
 1320:         if ($env{'form.action'} eq 'singlestudent') {
 1321:             $r->print(&date_sections_select($context,$newuser,$formname,
 1322:                                             $permission));
 1323:         }
 1324:         $r->print('</div><div class="LC_clear_float_footer"></div>');
 1325:     } else { # user already exists
 1326: 	my %lt=&Apache::lonlocal::texthash(
 1327:                     'cup'  => "Modify existing user: ",
 1328:                     'ens'  => "Enroll one student: ",
 1329:                     'enm'  => "Enroll one member: ",
 1330:                     'id'   => "in domain",
 1331: 				       );
 1332: 	$r->print(<<ENDCHANGEUSER);
 1333: $start_page
 1334: $forminfo
 1335: <h2>
 1336: ENDCHANGEUSER
 1337:         if ($env{'form.action'} eq 'singlestudent') {
 1338:             if ($crstype eq 'Community') {
 1339:                 $r->print($lt{'enm'});
 1340:             } else {
 1341:                 $r->print($lt{'ens'});
 1342:             }
 1343:         } else {
 1344:             $r->print($lt{'cup'});
 1345:         }
 1346:         $r->print(' "'.$ccuname.'" '.$lt{'id'}.' "'.$ccdomain.'"</h2>'.
 1347:                   "\n".'<div class="LC_left_float">');
 1348:         my ($personal_table,$showforceid) = 
 1349:             &personal_data_display($ccuname,$ccdomain,$newuser,$context,
 1350:                                    $inst_results{$ccuname.':'.$ccdomain});
 1351:         $r->print($personal_table);
 1352:         if ($showforceid) {
 1353:             $r->print('<table>'.&Apache::lonuserutils::forceid_change($context).'</table>');
 1354:         }
 1355:         if (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) {
 1356:             $r->print('<br /><h3>'.&mt('User Can Request Creation of Courses/Communities in this Domain?').'</h3>'.
 1357:                       &Apache::loncommon::start_data_table());
 1358:             if ($env{'request.role.domain'} eq $ccdomain) {
 1359:                 $r->print(&build_tools_display($ccuname,$ccdomain,'requestcourses'));
 1360:             } else {
 1361:                 $r->print(&coursereq_externaluser($ccuname,$ccdomain,
 1362:                                                   $env{'request.role.domain'}));
 1363:             }
 1364:             $r->print(&Apache::loncommon::end_data_table());
 1365:         }
 1366:         $r->print('</div>');
 1367:         my @order = ('auth','quota','tools','requestauthor');
 1368:         my %user_text;
 1369:         my ($isadv,$isauthor) = 
 1370:             &Apache::lonnet::is_advanced_user($ccuname,$ccdomain);
 1371:         if ((!$isauthor) && 
 1372:             (&Apache::lonnet::allowed('cau',$env{'request.role.domain'}))) {
 1373:             $user_text{'requestauthor'} = &domainrole_req($ccuname,$ccdomain);
 1374:         }
 1375:         $user_text{'auth'} =  &user_authentication($ccuname,$ccdomain,$formname);
 1376:         if ((&Apache::lonnet::allowed('mpq',$ccdomain)) ||
 1377:             (&Apache::lonnet::allowed('mut',$ccdomain))) {
 1378:             # Current user has quota modification privileges
 1379:             $user_text{'quota'} = &portfolio_quota($ccuname,$ccdomain);
 1380:         }
 1381:         if (!&Apache::lonnet::allowed('mpq',$ccdomain)) {
 1382:             if (&Apache::lonnet::allowed('mpq',$env{'request.role.domain'})) {
 1383:                 # Get the user's portfolio information
 1384:                 my %portq = &Apache::lonnet::get('environment',['portfolioquota'],
 1385:                                                  $ccdomain,$ccuname);
 1386:                 my %lt=&Apache::lonlocal::texthash(
 1387:                     'dska'  => "Disk space allocated to user's portfolio files",
 1388:                     'youd'  => "You do not have privileges to modify the portfolio quota for this user.",
 1389:                     'ichr'  => "If a change is required, contact a domain coordinator for the domain",
 1390:                 );
 1391:                 $user_text{'quota'} = <<ENDNOPORTPRIV;
 1392: <h3>$lt{'dska'}</h3>
 1393: $lt{'youd'} $lt{'ichr'}: $ccdomain
 1394: ENDNOPORTPRIV
 1395:             }
 1396:         }
 1397:         if (!&Apache::lonnet::allowed('mut',$ccdomain)) {
 1398:             if (&Apache::lonnet::allowed('mut',$env{'request.role.domain'})) {
 1399:                 my %lt=&Apache::lonlocal::texthash(
 1400:                     'utav'  => "User Tools Availability",
 1401:                     'yodo'  => "You do not have privileges to modify Portfolio, Blog, WebDAV, or Personal Information Page settings for this user.",
 1402:                     'ifch'  => "If a change is required, contact a domain coordinator for the domain",
 1403:                 );
 1404:                 $user_text{'tools'} = <<ENDNOTOOLSPRIV;
 1405: <h3>$lt{'utav'}</h3>
 1406: $lt{'yodo'} $lt{'ifch'}: $ccdomain
 1407: ENDNOTOOLSPRIV
 1408:             }
 1409:         }
 1410:         my $gotdiv = 0; 
 1411:         foreach my $item (@order) {
 1412:             if ($user_text{$item} ne '') {
 1413:                 unless ($gotdiv) {
 1414:                     $r->print('<div class="LC_left_float">');
 1415:                     $gotdiv = 1;
 1416:                 }
 1417:                 $r->print('<br />'.$user_text{$item});
 1418:             }
 1419:         }
 1420:         if ($env{'form.action'} eq 'singlestudent') {
 1421:             unless ($gotdiv) {
 1422:                 $r->print('<div class="LC_left_float">');
 1423:             }
 1424:             $r->print(&date_sections_select($context,$newuser,$formname));
 1425:         } 
 1426:         if ($gotdiv) {
 1427:             $r->print('</div><div class="LC_clear_float_footer"></div>');
 1428:         }
 1429:         if ($env{'form.action'} ne 'singlestudent') {
 1430:             &display_existing_roles($r,$ccuname,$ccdomain,\%inccourses,$context,
 1431:                                     $roledom,$crstype);
 1432:         }
 1433:     } ## End of new user/old user logic
 1434:     if ($env{'form.action'} eq 'singlestudent') {
 1435:         my $btntxt;
 1436:         if ($crstype eq 'Community') {
 1437:             $btntxt = &mt('Enroll Member');
 1438:         } else {
 1439:             $btntxt = &mt('Enroll Student');
 1440:         }
 1441:         $r->print('<br /><input type="button" value="'.$btntxt.'" onclick="setSections(this.form)" />'."\n");
 1442:     } else {
 1443:         $r->print('<h3>'.&mt('Add Roles').'</h3>');
 1444:         my $addrolesdisplay = 0;
 1445:         if ($context eq 'domain' || $context eq 'author') {
 1446:             $addrolesdisplay = &new_coauthor_roles($r,$ccuname,$ccdomain);
 1447:         }
 1448:         if ($context eq 'domain') {
 1449:             my $add_domainroles = &new_domain_roles($r,$ccdomain);
 1450:             if (!$addrolesdisplay) {
 1451:                 $addrolesdisplay = $add_domainroles;
 1452:             }
 1453:             $r->print(&course_level_dc($env{'request.role.domain'},'Course'));
 1454:             $r->print('<br /><input type="button" value="'.&mt('Save').'" onclick="setCourse()" />'."\n");
 1455:         } elsif ($context eq 'author') {
 1456:             if ($addrolesdisplay) {
 1457:                 $r->print('<br /><input type="button" value="'.&mt('Save').'"');
 1458:                 if ($newuser) {
 1459:                     $r->print(' onclick="auth_check()" \>'."\n");
 1460:                 } else {
 1461:                     $r->print('onclick="this.form.submit()" \>'."\n");
 1462:                 }
 1463:             } else {
 1464:                 $r->print('<br /><a href="javascript:backPage(document.cu)">'.
 1465:                           &mt('Back to previous page').'</a>');
 1466:             }
 1467:         } else {
 1468:             $r->print(&course_level_table(%inccourses));
 1469:             $r->print('<br /><input type="button" value="'.&mt('Save').'" onclick="setSections(this.form)" />'."\n");
 1470:         }
 1471:     }
 1472:     $r->print(&Apache::lonhtmlcommon::echo_form_input(['phase','userrole','ccdomain','prevphase','currstate','ccuname','ccdomain']));
 1473:     $r->print('<input type="hidden" name="currstate" value="" />');
 1474:     $r->print('<input type="hidden" name="prevphase" value="'.$env{'form.phase'}.'" /></form>');
 1475:     return;
 1476: }
 1477: 
 1478: sub singleuser_breadcrumb {
 1479:     my ($crstype) = @_;
 1480:     my %breadcrumb_text;
 1481:     if ($env{'form.action'} eq 'singlestudent') {
 1482:         if ($crstype eq 'Community') {
 1483:             $breadcrumb_text{'search'} = 'Enroll a member';
 1484:         } else {
 1485:             $breadcrumb_text{'search'} = 'Enroll a student';
 1486:         }
 1487:         $breadcrumb_text{'userpicked'} = 'Select a user',
 1488:         $breadcrumb_text{'modify'} = 'Set section/dates',
 1489:     } else {
 1490:         $breadcrumb_text{'search'} = 'Create/modify a user';
 1491:         $breadcrumb_text{'userpicked'} = 'Select a user',
 1492:         $breadcrumb_text{'modify'} = 'Set user role',
 1493:     }
 1494:     return %breadcrumb_text;
 1495: }
 1496: 
 1497: sub date_sections_select {
 1498:     my ($context,$newuser,$formname,$permission) = @_;
 1499:     my $cid = $env{'request.course.id'};
 1500:     my ($cnum,$cdom) = &Apache::lonuserutils::get_course_identity($cid);
 1501:     my $date_table = '<h3>'.&mt('Starting and Ending Dates').'</h3>'."\n".
 1502:         &Apache::lonuserutils::date_setting_table(undef,undef,$context,
 1503:                                                   undef,$formname,$permission);
 1504:     my $rowtitle = 'Section';
 1505:     my $secbox = '<h3>'.&mt('Section').'</h3>'."\n".
 1506:         &Apache::lonuserutils::section_picker($cdom,$cnum,'st',$rowtitle,
 1507:                                               $permission);
 1508:     my $output = $date_table.$secbox;
 1509:     return $output;
 1510: }
 1511: 
 1512: sub validation_javascript {
 1513:     my ($context,$ccdomain,$pjump_def,$groupslist,$newuser,$formname,
 1514:         $loaditem) = @_;
 1515:     my $dc_setcourse_code = '';
 1516:     my $nondc_setsection_code = '';
 1517:     if ($context eq 'domain') {
 1518:         my $dcdom = $env{'request.role.domain'};
 1519:         $loaditem->{'onload'} = "document.cu.coursedesc.value='';";
 1520:         $dc_setcourse_code = 
 1521:             &Apache::lonuserutils::dc_setcourse_js('cu','singleuser',$context);
 1522:     } else {
 1523:         my $checkauth; 
 1524:         if (($newuser) || (&Apache::lonnet::allowed('mau',$ccdomain))) {
 1525:             $checkauth = 1;
 1526:         }
 1527:         if ($context eq 'course') {
 1528:             $nondc_setsection_code =
 1529:                 &Apache::lonuserutils::setsections_javascript($formname,$groupslist,
 1530:                                                               undef,$checkauth);
 1531:         }
 1532:         if ($checkauth) {
 1533:             $nondc_setsection_code .= 
 1534:                 &Apache::lonuserutils::verify_authen($formname,$context);
 1535:         }
 1536:     }
 1537:     my $js = &user_modification_js($pjump_def,$dc_setcourse_code,
 1538:                                    $nondc_setsection_code,$groupslist);
 1539:     my ($jsback,$elements) = &crumb_utilities();
 1540:     $js .= "\n".
 1541:            '<script type="text/javascript">'."\n".
 1542:            '// <![CDATA['."\n".
 1543:            $jsback."\n".
 1544:            '// ]]>'."\n".
 1545:            '</script>'."\n";
 1546:     return $js;
 1547: }
 1548: 
 1549: sub display_existing_roles {
 1550:     my ($r,$ccuname,$ccdomain,$inccourses,$context,$roledom,$crstype) = @_;
 1551:     my $now=time;
 1552:     my %lt=&Apache::lonlocal::texthash(
 1553:                     'rer'  => "Existing Roles",
 1554:                     'rev'  => "Revoke",
 1555:                     'del'  => "Delete",
 1556:                     'ren'  => "Re-Enable",
 1557:                     'rol'  => "Role",
 1558:                     'ext'  => "Extent",
 1559:                     'sta'  => "Start",
 1560:                     'end'  => "End",
 1561:                                        );
 1562:     my (%rolesdump,%roletext,%sortrole,%roleclass,%rolepriv);
 1563:     if ($context eq 'course' || $context eq 'author') {
 1564:         my @roles = &Apache::lonuserutils::roles_by_context($context,1,$crstype);
 1565:         my %roleshash = 
 1566:             &Apache::lonnet::get_my_roles($ccuname,$ccdomain,'userroles',
 1567:                               ['active','previous','future'],\@roles,$roledom,1);
 1568:         foreach my $key (keys(%roleshash)) {
 1569:             my ($start,$end) = split(':',$roleshash{$key});
 1570:             next if ($start eq '-1' || $end eq '-1');
 1571:             my ($rnum,$rdom,$role,$sec) = split(':',$key);
 1572:             if ($context eq 'course') {
 1573:                 next unless (($rnum eq $env{'course.'.$env{'request.course.id'}.'.num'})
 1574:                              && ($rdom eq $env{'course.'.$env{'request.course.id'}.'.domain'}));
 1575:             } elsif ($context eq 'author') {
 1576:                 next unless (($rnum eq $env{'user.name'}) && ($rdom eq $env{'request.role.domain'}));
 1577:             }
 1578:             my ($newkey,$newvalue,$newrole);
 1579:             $newkey = '/'.$rdom.'/'.$rnum;
 1580:             if ($sec ne '') {
 1581:                 $newkey .= '/'.$sec;
 1582:             }
 1583:             $newvalue = $role;
 1584:             if ($role =~ /^cr/) {
 1585:                 $newrole = 'cr';
 1586:             } else {
 1587:                 $newrole = $role;
 1588:             }
 1589:             $newkey .= '_'.$newrole;
 1590:             if ($start ne '' && $end ne '') {
 1591:                 $newvalue .= '_'.$end.'_'.$start;
 1592:             } elsif ($end ne '') {
 1593:                 $newvalue .= '_'.$end;
 1594:             }
 1595:             $rolesdump{$newkey} = $newvalue;
 1596:         }
 1597:     } else {
 1598:         %rolesdump=&Apache::lonnet::dump('roles',$ccdomain,$ccuname);
 1599:     }
 1600:     # Build up table of user roles to allow revocation and re-enabling of roles.
 1601:     my ($tmp) = keys(%rolesdump);
 1602:     return if ($tmp =~ /^(con_lost|error)/i);
 1603:     foreach my $area (sort { my $a1=join('_',(split('_',$a))[1,0]);
 1604:                                 my $b1=join('_',(split('_',$b))[1,0]);
 1605:                                 return $a1 cmp $b1;
 1606:                             } keys(%rolesdump)) {
 1607:         next if ($area =~ /^rolesdef/);
 1608:         my $envkey=$area;
 1609:         my $role = $rolesdump{$area};
 1610:         my $thisrole=$area;
 1611:         $area =~ s/\_\w\w$//;
 1612:         my ($role_code,$role_end_time,$role_start_time) =
 1613:             split(/_/,$role);
 1614: # Is this a custom role? Get role owner and title.
 1615:         my ($croleudom,$croleuname,$croletitle)=
 1616:             ($role_code=~m{^cr/($match_domain)/($match_username)/(\w+)$});
 1617:         my $allowed=0;
 1618:         my $delallowed=0;
 1619:         my $sortkey=$role_code;
 1620:         my $class='Unknown';
 1621:         if ($area =~ m{^/($match_domain)/($match_courseid)} ) {
 1622:             $class='Course';
 1623:             my ($coursedom,$coursedir) = ($1,$2);
 1624:             my $cid = $1.'_'.$2;
 1625:             # $1.'_'.$2 is the course id (eg. 103_12345abcef103l3).
 1626:             my %coursedata=
 1627:                 &Apache::lonnet::coursedescription($cid);
 1628:             if ($coursedir =~ /^$match_community$/) {
 1629:                 $class='Community';
 1630:             }
 1631:             $sortkey.="\0$coursedom";
 1632:             my $carea;
 1633:             if (defined($coursedata{'description'})) {
 1634:                 $carea=$coursedata{'description'}.
 1635:                     '<br />'.&mt('Domain').': '.$coursedom.('&nbsp;'x8).
 1636:     &Apache::loncommon::syllabuswrapper(&mt('Syllabus'),$coursedir,$coursedom);
 1637:                 $sortkey.="\0".$coursedata{'description'};
 1638:             } else {
 1639:                 if ($class eq 'Community') {
 1640:                     $carea=&mt('Unavailable community').': '.$area;
 1641:                     $sortkey.="\0".&mt('Unavailable community').': '.$area;
 1642:                 } else {
 1643:                     $carea=&mt('Unavailable course').': '.$area;
 1644:                     $sortkey.="\0".&mt('Unavailable course').': '.$area;
 1645:                 }
 1646:             }
 1647:             $sortkey.="\0$coursedir";
 1648:             $inccourses->{$cid}=1;
 1649:             if ((&Apache::lonnet::allowed('c'.$role_code,$coursedom.'/'.$coursedir)) ||
 1650:                 (&Apache::lonnet::allowed('c'.$role_code,$ccdomain))) {
 1651:                 $allowed=1;
 1652:             }
 1653:             unless ($allowed) {
 1654:                 my $isowner = &is_courseowner($cid,$coursedata{'internal.courseowner'});
 1655:                 if ($isowner) {
 1656:                     if (($role_code eq 'co') && ($class eq 'Community')) {
 1657:                         $allowed = 1;
 1658:                     } elsif (($role_code eq 'cc') && ($class eq 'Course')) {
 1659:                         $allowed = 1;
 1660:                     }
 1661:                 }
 1662:             } 
 1663:             if ((&Apache::lonnet::allowed('dro',$coursedom)) ||
 1664:                 (&Apache::lonnet::allowed('dro',$ccdomain))) {
 1665:                 $delallowed=1;
 1666:             }
 1667: # - custom role. Needs more info, too
 1668:             if ($croletitle) {
 1669:                 if (&Apache::lonnet::allowed('ccr',$coursedom.'/'.$coursedir)) {
 1670:                     $allowed=1;
 1671:                     $thisrole.='.'.$role_code;
 1672:                 }
 1673:             }
 1674:             if ($area=~m{^/($match_domain)/($match_courseid)/(\w+)}) {
 1675:                 $carea.='<br />Section: '.$3;
 1676:                 $sortkey.="\0$3";
 1677:                 if (!$allowed) {
 1678:                     if ($env{'request.course.sec'} eq $3) {
 1679:                         if (&Apache::lonnet::allowed('c'.$role_code,$1.'/'.$2.'/'.$3)) {
 1680:                             $allowed = 1;
 1681:                         }
 1682:                     }
 1683:                 }
 1684:             }
 1685:             $area=$carea;
 1686:         } else {
 1687:             $sortkey.="\0".$area;
 1688:             # Determine if current user is able to revoke privileges
 1689:             if ($area=~m{^/($match_domain)/}) {
 1690:                 if ((&Apache::lonnet::allowed('c'.$role_code,$1)) ||
 1691:                    (&Apache::lonnet::allowed('c'.$role_code,$ccdomain))) {
 1692:                    $allowed=1;
 1693:                 }
 1694:                 if (((&Apache::lonnet::allowed('dro',$1))  ||
 1695:                     (&Apache::lonnet::allowed('dro',$ccdomain))) &&
 1696:                     ($role_code ne 'dc')) {
 1697:                     $delallowed=1;
 1698:                 }
 1699:             } else {
 1700:                 if (&Apache::lonnet::allowed('c'.$role_code,'/')) {
 1701:                     $allowed=1;
 1702:                 }
 1703:             }
 1704:             if ($role_code eq 'ca' || $role_code eq 'au' || $role_code eq 'aa') {
 1705:                 $class='Construction Space';
 1706:             } elsif ($role_code eq 'su') {
 1707:                 $class='System';
 1708:             } else {
 1709:                 $class='Domain';
 1710:             }
 1711:         }
 1712:         if (($role_code eq 'ca') || ($role_code eq 'aa')) {
 1713:             $area=~m{/($match_domain)/($match_username)};
 1714:             if (&Apache::lonuserutils::authorpriv($2,$1)) {
 1715:                 $allowed=1;
 1716:             } else {
 1717:                 $allowed=0;
 1718:             }
 1719:         }
 1720:         my $row = '';
 1721:         $row.= '<td>';
 1722:         my $active=1;
 1723:         $active=0 if (($role_end_time) && ($now>$role_end_time));
 1724:         if (($active) && ($allowed)) {
 1725:             $row.= '<input type="checkbox" name="rev:'.$thisrole.'" />';
 1726:         } else {
 1727:             if ($active) {
 1728:                $row.='&nbsp;';
 1729:             } else {
 1730:                $row.=&mt('expired or revoked');
 1731:             }
 1732:         }
 1733:         $row.='</td><td>';
 1734:         if ($allowed && !$active) {
 1735:             $row.= '<input type="checkbox" name="ren:'.$thisrole.'" />';
 1736:         } else {
 1737:             $row.='&nbsp;';
 1738:         }
 1739:         $row.='</td><td>';
 1740:         if ($delallowed) {
 1741:             $row.= '<input type="checkbox" name="del:'.$thisrole.'" />';
 1742:         } else {
 1743:             $row.='&nbsp;';
 1744:         }
 1745:         my $plaintext='';
 1746:         if (!$croletitle) {
 1747:             $plaintext=&Apache::lonnet::plaintext($role_code,$class)
 1748:         } else {
 1749:             $plaintext=
 1750:                 &mt('Customrole [_1][_2]defined by [_3]',
 1751:                         '"'.$croletitle.'"',
 1752:                         '<br />',
 1753:                         $croleuname.':'.$croleudom);
 1754:         }
 1755:         $row.= '</td><td>'.$plaintext.
 1756:                '</td><td>'.$area.
 1757:                '</td><td>'.($role_start_time?&Apache::lonlocal::locallocaltime($role_start_time)
 1758:                                             : '&nbsp;' ).
 1759:                '</td><td>'.($role_end_time  ?&Apache::lonlocal::locallocaltime($role_end_time)
 1760:                                             : '&nbsp;' )
 1761:                ."</td>";
 1762:         $sortrole{$sortkey}=$envkey;
 1763:         $roletext{$envkey}=$row;
 1764:         $roleclass{$envkey}=$class;
 1765:         $rolepriv{$envkey}=$allowed;
 1766:     } # end of foreach        (table building loop)
 1767: 
 1768:     my $rolesdisplay = 0;
 1769:     my %output = ();
 1770:     foreach my $type ('Construction Space','Course','Community','Domain','System','Unknown') {
 1771:         $output{$type} = '';
 1772:         foreach my $which (sort {uc($a) cmp uc($b)} (keys(%sortrole))) {
 1773:             if ( ($roleclass{$sortrole{$which}} =~ /^\Q$type\E/ ) && ($rolepriv{$sortrole{$which}}) ) {
 1774:                  $output{$type}.=
 1775:                       &Apache::loncommon::start_data_table_row().
 1776:                       $roletext{$sortrole{$which}}.
 1777:                       &Apache::loncommon::end_data_table_row();
 1778:             }
 1779:         }
 1780:         unless($output{$type} eq '') {
 1781:             $output{$type} = '<tr class="LC_info_row">'.
 1782:                       "<td align='center' colspan='7'>".&mt($type)."</td></tr>".
 1783:                       $output{$type};
 1784:             $rolesdisplay = 1;
 1785:         }
 1786:     }
 1787:     if ($rolesdisplay == 1) {
 1788:         my $contextrole='';
 1789:         if ($env{'request.course.id'}) {
 1790:             if (&Apache::loncommon::course_type() eq 'Community') {
 1791:                 $contextrole = &mt('Existing Roles in this Community');
 1792:             } else {
 1793:                 $contextrole = &mt('Existing Roles in this Course');
 1794:             }
 1795:         } elsif ($env{'request.role'} =~ /^au\./) {
 1796:             $contextrole = &mt('Existing Co-Author Roles in your Construction Space');
 1797:         } else {
 1798:             $contextrole = &mt('Existing Roles in this Domain');
 1799:         }
 1800:         $r->print('
 1801: <h3>'.$lt{'rer'}.'</h3>'.
 1802: '<div>'.$contextrole.'</div>'.
 1803: &Apache::loncommon::start_data_table("LC_createuser").
 1804: &Apache::loncommon::start_data_table_header_row().
 1805: '<th>'.$lt{'rev'}.'</th><th>'.$lt{'ren'}.'</th><th>'.$lt{'del'}.
 1806: '</th><th>'.$lt{'rol'}.'</th><th>'.$lt{'ext'}.
 1807: '</th><th>'.$lt{'sta'}.'</th><th>'.$lt{'end'}.'</th>'.
 1808: &Apache::loncommon::end_data_table_header_row());
 1809:         foreach my $type ('Construction Space','Course','Community','Domain','System','Unknown') {
 1810:             if ($output{$type}) {
 1811:                 $r->print($output{$type}."\n");
 1812:             }
 1813:         }
 1814:         $r->print(&Apache::loncommon::end_data_table());
 1815:     }
 1816:     return;
 1817: }
 1818: 
 1819: sub new_coauthor_roles {
 1820:     my ($r,$ccuname,$ccdomain) = @_;
 1821:     my $addrolesdisplay = 0;
 1822:     #
 1823:     # Co-Author
 1824:     #
 1825:     if (&Apache::lonuserutils::authorpriv($env{'user.name'},
 1826:                                           $env{'request.role.domain'}) &&
 1827:         ($env{'user.name'} ne $ccuname || $env{'user.domain'} ne $ccdomain)) {
 1828:         # No sense in assigning co-author role to yourself
 1829:         $addrolesdisplay = 1;
 1830:         my $cuname=$env{'user.name'};
 1831:         my $cudom=$env{'request.role.domain'};
 1832:         my %lt=&Apache::lonlocal::texthash(
 1833:                     'cs'   => "Construction Space",
 1834:                     'act'  => "Activate",
 1835:                     'rol'  => "Role",
 1836:                     'ext'  => "Extent",
 1837:                     'sta'  => "Start",
 1838:                     'end'  => "End",
 1839:                     'cau'  => "Co-Author",
 1840:                     'caa'  => "Assistant Co-Author",
 1841:                     'ssd'  => "Set Start Date",
 1842:                     'sed'  => "Set End Date"
 1843:                                        );
 1844:         $r->print('<h4>'.$lt{'cs'}.'</h4>'."\n".
 1845:                   &Apache::loncommon::start_data_table()."\n".
 1846:                   &Apache::loncommon::start_data_table_header_row()."\n".
 1847:                   '<th>'.$lt{'act'}.'</th><th>'.$lt{'rol'}.'</th>'.
 1848:                   '<th>'.$lt{'ext'}.'</th><th>'.$lt{'sta'}.'</th>'.
 1849:                   '<th>'.$lt{'end'}.'</th>'."\n".
 1850:                   &Apache::loncommon::end_data_table_header_row()."\n".
 1851:                   &Apache::loncommon::start_data_table_row().'
 1852:            <td>
 1853:             <input type="checkbox" name="act_'.$cudom.'_'.$cuname.'_ca" />
 1854:            </td>
 1855:            <td>'.$lt{'cau'}.'</td>
 1856:            <td>'.$cudom.'_'.$cuname.'</td>
 1857:            <td><input type="hidden" name="start_'.$cudom.'_'.$cuname.'_ca" value="" />
 1858:              <a href=
 1859: "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>
 1860: <td><input type="hidden" name="end_'.$cudom.'_'.$cuname.'_ca" value="" />
 1861: <a href=
 1862: "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".
 1863:               &Apache::loncommon::end_data_table_row()."\n".
 1864:               &Apache::loncommon::start_data_table_row()."\n".
 1865: '<td><input type="checkbox" name="act_'.$cudom.'_'.$cuname.'_aa" /></td>
 1866: <td>'.$lt{'caa'}.'</td>
 1867: <td>'.$cudom.'_'.$cuname.'</td>
 1868: <td><input type="hidden" name="start_'.$cudom.'_'.$cuname.'_aa" value="" />
 1869: <a href=
 1870: "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>
 1871: <td><input type="hidden" name="end_'.$cudom.'_'.$cuname.'_aa" value="" />
 1872: <a href=
 1873: "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".
 1874:              &Apache::loncommon::end_data_table_row()."\n".
 1875:              &Apache::loncommon::end_data_table());
 1876:     } elsif ($env{'request.role'} =~ /^au\./) {
 1877:         if (!(&Apache::lonuserutils::authorpriv($env{'user.name'},
 1878:                                                 $env{'request.role.domain'}))) {
 1879:             $r->print('<span class="LC_error">'.
 1880:                       &mt('You do not have privileges to assign co-author roles.').
 1881:                       '</span>');
 1882:         } elsif (($env{'user.name'} eq $ccuname) &&
 1883:              ($env{'user.domain'} eq $ccdomain)) {
 1884:             $r->print(&mt('Assigning yourself a co-author or assistant co-author role in your own author area in Construction Space is not permitted'));
 1885:         }
 1886:     }
 1887:     return $addrolesdisplay;;
 1888: }
 1889: 
 1890: sub new_domain_roles {
 1891:     my ($r,$ccdomain) = @_;
 1892:     my $addrolesdisplay = 0;
 1893:     #
 1894:     # Domain level
 1895:     #
 1896:     my $num_domain_level = 0;
 1897:     my $domaintext =
 1898:     '<h4>'.&mt('Domain Level').'</h4>'.
 1899:     &Apache::loncommon::start_data_table().
 1900:     &Apache::loncommon::start_data_table_header_row().
 1901:     '<th>'.&mt('Activate').'</th><th>'.&mt('Role').'</th><th>'.
 1902:     &mt('Extent').'</th>'.
 1903:     '<th>'.&mt('Start').'</th><th>'.&mt('End').'</th>'.
 1904:     &Apache::loncommon::end_data_table_header_row();
 1905:     my @allroles = &Apache::lonuserutils::roles_by_context('domain');
 1906:     foreach my $thisdomain (sort(&Apache::lonnet::all_domains())) {
 1907:         foreach my $role (@allroles) {
 1908:             next if ($role eq 'ad');
 1909:             next if (($role eq 'au') && ($ccdomain ne $thisdomain));
 1910:             if (&Apache::lonnet::allowed('c'.$role,$thisdomain)) {
 1911:                my $plrole=&Apache::lonnet::plaintext($role);
 1912:                my %lt=&Apache::lonlocal::texthash(
 1913:                     'ssd'  => "Set Start Date",
 1914:                     'sed'  => "Set End Date"
 1915:                                        );
 1916:                $num_domain_level ++;
 1917:                $domaintext .=
 1918: &Apache::loncommon::start_data_table_row().
 1919: '<td><input type="checkbox" name="act_'.$thisdomain.'_'.$role.'" /></td>
 1920: <td>'.$plrole.'</td>
 1921: <td>'.$thisdomain.'</td>
 1922: <td><input type="hidden" name="start_'.$thisdomain.'_'.$role.'" value="" />
 1923: <a href=
 1924: "javascript:pjump('."'date_start','Start Date $plrole',document.cu.start_$thisdomain\_$role.value,'start_$thisdomain\_$role','cu.pres','dateset'".')">'.$lt{'ssd'}.'</a></td>
 1925: <td><input type="hidden" name="end_'.$thisdomain.'_'.$role.'" value="" />
 1926: <a href=
 1927: "javascript:pjump('."'date_end','End Date $plrole',document.cu.end_$thisdomain\_$role.value,'end_$thisdomain\_$role','cu.pres','dateset'".')">'.$lt{'sed'}.'</a></td>'.
 1928: &Apache::loncommon::end_data_table_row();
 1929:             }
 1930:         }
 1931:     }
 1932:     $domaintext.= &Apache::loncommon::end_data_table();
 1933:     if ($num_domain_level > 0) {
 1934:         $r->print($domaintext);
 1935:         $addrolesdisplay = 1;
 1936:     }
 1937:     return $addrolesdisplay;
 1938: }
 1939: 
 1940: sub user_authentication {
 1941:     my ($ccuname,$ccdomain,$formname) = @_;
 1942:     my $currentauth=&Apache::lonnet::queryauthenticate($ccuname,$ccdomain);
 1943:     my $outcome;
 1944:     # Check for a bad authentication type
 1945:     if ($currentauth !~ /^(krb4|krb5|unix|internal|localauth):/) {
 1946:         # bad authentication scheme
 1947:         my %lt=&Apache::lonlocal::texthash(
 1948:                        'err'   => "ERROR",
 1949:                        'uuas'  => "This user has an unrecognized authentication scheme",
 1950:                        'adcs'  => "Please alert a domain coordinator of this situation",
 1951:                        'sldb'  => "Please specify login data below",
 1952:                        'ld'    => "Login Data"
 1953:         );
 1954:         if (&Apache::lonnet::allowed('mau',$ccdomain)) {
 1955:             &initialize_authen_forms($ccdomain,$formname);
 1956: 
 1957:             my $choices = &Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc);
 1958:             $outcome = <<ENDBADAUTH;
 1959: <script type="text/javascript" language="Javascript">
 1960: // <![CDATA[
 1961: $loginscript
 1962: // ]]>
 1963: </script>
 1964: <span class="LC_error">$lt{'err'}:
 1965: $lt{'uuas'} ($currentauth). $lt{'sldb'}.</span>
 1966: <h3>$lt{'ld'}</h3>
 1967: $choices
 1968: ENDBADAUTH
 1969:         } else {
 1970:             # This user is not allowed to modify the user's
 1971:             # authentication scheme, so just notify them of the problem
 1972:             $outcome = <<ENDBADAUTH;
 1973: <span class="LC_error"> $lt{'err'}: 
 1974: $lt{'uuas'} ($currentauth). $lt{'adcs'}.
 1975: </span>
 1976: ENDBADAUTH
 1977:         }
 1978:     } else { # Authentication type is valid
 1979:         &initialize_authen_forms($ccdomain,$formname,$currentauth,'modifyuser');
 1980:         my ($authformcurrent,$can_modify,@authform_others) =
 1981:             &modify_login_block($ccdomain,$currentauth);
 1982:         if (&Apache::lonnet::allowed('mau',$ccdomain)) {
 1983:             # Current user has login modification privileges
 1984:             my %lt=&Apache::lonlocal::texthash (
 1985:                            'ld'    => "Login Data",
 1986:                            'ccld'  => "Change Current Login Data",
 1987:                            'enld'  => "Enter New Login Data"
 1988:                                                );
 1989:             $outcome =
 1990:                        '<script type="text/javascript" language="Javascript">'."\n".
 1991:                        '// <![CDATA['."\n".
 1992:                        $loginscript."\n".
 1993:                        '// ]]>'."\n".
 1994:                        '</script>'."\n".
 1995:                        '<h3>'.$lt{'ld'}.'</h3>'.
 1996:                        &Apache::loncommon::start_data_table().
 1997:                        &Apache::loncommon::start_data_table_row().
 1998:                        '<td>'.$authformnop;
 1999:             if ($can_modify) {
 2000:                 $outcome .= '</td>'."\n".
 2001:                             &Apache::loncommon::end_data_table_row().
 2002:                             &Apache::loncommon::start_data_table_row().
 2003:                             '<td>'.$authformcurrent.'</td>'.
 2004:                             &Apache::loncommon::end_data_table_row()."\n";
 2005:             } else {
 2006:                 $outcome .= '&nbsp;('.$authformcurrent.')</td>'.
 2007:                             &Apache::loncommon::end_data_table_row()."\n";
 2008:             }
 2009:             foreach my $item (@authform_others) { 
 2010:                 $outcome .= &Apache::loncommon::start_data_table_row().
 2011:                             '<td>'.$item.'</td>'.
 2012:                             &Apache::loncommon::end_data_table_row()."\n";
 2013:             }
 2014:             $outcome .= &Apache::loncommon::end_data_table();
 2015:         } else {
 2016:             if (&Apache::lonnet::allowed('mau',$env{'request.role.domain'})) {
 2017:                 my %lt=&Apache::lonlocal::texthash(
 2018:                            'ccld'  => "Change Current Login Data",
 2019:                            'yodo'  => "You do not have privileges to modify the authentication configuration for this user.",
 2020:                            'ifch'  => "If a change is required, contact a domain coordinator for the domain",
 2021:                 );
 2022:                 $outcome .= <<ENDNOPRIV;
 2023: <h3>$lt{'ccld'}</h3>
 2024: $lt{'yodo'} $lt{'ifch'}: $ccdomain
 2025: <input type="hidden" name="login" value="nochange" />
 2026: ENDNOPRIV
 2027:             }
 2028:         }
 2029:     }  ## End of "check for bad authentication type" logic
 2030:     return $outcome;
 2031: }
 2032: 
 2033: sub modify_login_block {
 2034:     my ($dom,$currentauth) = @_;
 2035:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 2036:     my ($authnum,%can_assign) =
 2037:         &Apache::loncommon::get_assignable_auth($dom);
 2038:     my ($authformcurrent,@authform_others,$show_override_msg);
 2039:     if ($currentauth=~/^krb(4|5):/) {
 2040:         $authformcurrent=$authformkrb;
 2041:         if ($can_assign{'int'}) {
 2042:             push(@authform_others,$authformint);
 2043:         }
 2044:         if ($can_assign{'loc'}) {
 2045:             push(@authform_others,$authformloc);
 2046:         }
 2047:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2048:             $show_override_msg = 1;
 2049:         }
 2050:     } elsif ($currentauth=~/^internal:/) {
 2051:         $authformcurrent=$authformint;
 2052:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2053:             push(@authform_others,$authformkrb);
 2054:         }
 2055:         if ($can_assign{'loc'}) {
 2056:             push(@authform_others,$authformloc);
 2057:         }
 2058:         if ($can_assign{'int'}) {
 2059:             $show_override_msg = 1;
 2060:         }
 2061:     } elsif ($currentauth=~/^unix:/) {
 2062:         $authformcurrent=$authformfsys;
 2063:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2064:             push(@authform_others,$authformkrb);
 2065:         }
 2066:         if ($can_assign{'int'}) {
 2067:             push(@authform_others,$authformint);
 2068:         }
 2069:         if ($can_assign{'loc'}) {
 2070:             push(@authform_others,$authformloc);
 2071:         }
 2072:         if ($can_assign{'fsys'}) {
 2073:             $show_override_msg = 1;
 2074:         }
 2075:     } elsif ($currentauth=~/^localauth:/) {
 2076:         $authformcurrent=$authformloc;
 2077:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2078:             push(@authform_others,$authformkrb);
 2079:         }
 2080:         if ($can_assign{'int'}) {
 2081:             push(@authform_others,$authformint);
 2082:         }
 2083:         if ($can_assign{'loc'}) {
 2084:             $show_override_msg = 1;
 2085:         }
 2086:     }
 2087:     if ($show_override_msg) {
 2088:         $authformcurrent = '<table><tr><td colspan="3">'.$authformcurrent.
 2089:                            '</td></tr>'."\n".
 2090:                            '<tr><td>&nbsp;&nbsp;&nbsp;</td>'.
 2091:                            '<td><b>'.&mt('Currently in use').'</b></td>'.
 2092:                            '<td align="right"><span class="LC_cusr_emph">'.
 2093:                             &mt('will override current values').
 2094:                             '</span></td></tr></table>';
 2095:     }
 2096:     return ($authformcurrent,$show_override_msg,@authform_others); 
 2097: }
 2098: 
 2099: sub personal_data_display {
 2100:     my ($ccuname,$ccdomain,$newuser,$context,$inst_results,$rolesarray) = @_;
 2101:     my ($output,$showforceid,%userenv,%canmodify,%canmodify_status);
 2102:     my @userinfo = ('firstname','middlename','lastname','generation',
 2103:                     'permanentemail','id');
 2104:     my $rowcount = 0;
 2105:     my $editable = 0;
 2106:     %canmodify_status = 
 2107:         &Apache::lonuserutils::can_modify_userinfo($context,$ccdomain,
 2108:                                                    ['inststatus'],$rolesarray);
 2109:     if (!$newuser) {
 2110:         # Get the users information
 2111:         %userenv = &Apache::lonnet::get('environment',
 2112:                    ['firstname','middlename','lastname','generation',
 2113:                     'permanentemail','id','inststatus'],$ccdomain,$ccuname);
 2114:         %canmodify =
 2115:             &Apache::lonuserutils::can_modify_userinfo($context,$ccdomain,
 2116:                                                        \@userinfo,$rolesarray);
 2117:     } elsif ($context eq 'selfcreate') {
 2118:         %canmodify = &selfcreate_canmodify($context,$ccdomain,\@userinfo,
 2119:                                            $inst_results,$rolesarray);
 2120:     }
 2121:     my %lt=&Apache::lonlocal::texthash(
 2122:                 'pd'             => "Personal Data",
 2123:                 'firstname'      => "First Name",
 2124:                 'middlename'     => "Middle Name",
 2125:                 'lastname'       => "Last Name",
 2126:                 'generation'     => "Generation",
 2127:                 'permanentemail' => "Permanent e-mail address",
 2128:                 'id'             => "Student/Employee ID",
 2129:                 'lg'             => "Login Data",
 2130:                 'inststatus'     => "Affiliation",
 2131:     );
 2132:     my %textboxsize = (
 2133:                        firstname      => '15',
 2134:                        middlename     => '15',
 2135:                        lastname       => '15',
 2136:                        generation     => '5',
 2137:                        permanentemail => '25',
 2138:                        id             => '15',
 2139:                       );
 2140:     my $genhelp=&Apache::loncommon::help_open_topic('Generation');
 2141:     $output = '<h3>'.$lt{'pd'}.'</h3>'.
 2142:               &Apache::lonhtmlcommon::start_pick_box();
 2143:     foreach my $item (@userinfo) {
 2144:         my $rowtitle = $lt{$item};
 2145:         my $hiderow = 0;
 2146:         if ($item eq 'generation') {
 2147:             $rowtitle = $genhelp.$rowtitle;
 2148:         }
 2149:         my $row = &Apache::lonhtmlcommon::row_title($rowtitle,undef,'LC_oddrow_value')."\n";
 2150:         if ($newuser) {
 2151:             if (ref($inst_results) eq 'HASH') {
 2152:                 if ($inst_results->{$item} ne '') {
 2153:                     $row .= '<input type="hidden" name="c'.$item.'" value="'.$inst_results->{$item}.'" />'.$inst_results->{$item};
 2154:                 } else {
 2155:                     if ($context eq 'selfcreate') {
 2156:                         if ($canmodify{$item}) { 
 2157:                             $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="" />';
 2158:                             $editable ++;
 2159:                         } else {
 2160:                             $hiderow = 1;
 2161:                         }
 2162:                     } else {
 2163:                         $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="" />';
 2164:                     }
 2165:                 }
 2166:             } else {
 2167:                 if ($context eq 'selfcreate') {
 2168:                     if (($item eq 'permanentemail') && ($newuser eq 'email')) {
 2169:                         $row .= $ccuname;
 2170:                     } else {
 2171:                         if ($canmodify{$item}) {
 2172:                             $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="" />';
 2173:                             $editable ++;
 2174:                         } else {
 2175:                             $hiderow = 1;
 2176:                         }
 2177:                     }
 2178:                 } else {
 2179:                     $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="" />';
 2180:                 }
 2181:             }
 2182:         } else {
 2183:             if ($canmodify{$item}) {
 2184:                 $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="'.$userenv{$item}.'" />';
 2185:             } else {
 2186:                 $row .= $userenv{$item};
 2187:             }
 2188:             if ($item eq 'id') {
 2189:                 $showforceid = $canmodify{$item};
 2190:             }
 2191:         }
 2192:         $row .= &Apache::lonhtmlcommon::row_closure(1);
 2193:         if (!$hiderow) {
 2194:             $output .= $row;
 2195:             $rowcount ++;
 2196:         }
 2197:     }
 2198:     if (($canmodify_status{'inststatus'}) || ($context ne 'selfcreate')) {
 2199:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($ccdomain);
 2200:         if (ref($types) eq 'ARRAY') {
 2201:             if (@{$types} > 0) {
 2202:                 my ($hiderow,$shown);
 2203:                 if ($canmodify_status{'inststatus'}) {
 2204:                     $shown = &pick_inst_statuses($userenv{'inststatus'},$usertypes,$types);
 2205:                 } else {
 2206:                     if ($userenv{'inststatus'} eq '') {
 2207:                         $hiderow = 1;
 2208:                     } else {
 2209:                         my @showitems;
 2210:                         foreach my $item ( map { &unescape($_); } split(':',$userenv{'inststatus'})) {
 2211:                             if (exists($usertypes->{$item})) {
 2212:                                 push(@showitems,$usertypes->{$item});
 2213:                             } else {
 2214:                                 push(@showitems,$item);
 2215:                             }
 2216:                         }
 2217:                         if (@showitems) {
 2218:                             $shown = join(', ',@showitems);
 2219:                         } else {
 2220:                             $hiderow = 1;
 2221:                         }
 2222:                     }
 2223:                 }
 2224:                 if (!$hiderow) {
 2225:                     my $row = &Apache::lonhtmlcommon::row_title(&mt('Affliations'),undef,'LC_oddrow_value')."\n".
 2226:                               $shown.&Apache::lonhtmlcommon::row_closure(1); 
 2227:                     if ($context eq 'selfcreate') {
 2228:                         $rowcount ++;
 2229:                     }
 2230:                     $output .= $row;
 2231:                 }
 2232:             }
 2233:         }
 2234:     }
 2235:     $output .= &Apache::lonhtmlcommon::end_pick_box();
 2236:     if (wantarray) {
 2237:         if ($context eq 'selfcreate') {
 2238:             return($output,$rowcount,$editable);
 2239:         } else {
 2240:             return ($output,$showforceid);
 2241:         }
 2242:     } else {
 2243:         return $output;
 2244:     }
 2245: }
 2246: 
 2247: sub pick_inst_statuses {
 2248:     my ($curr,$usertypes,$types) = @_;
 2249:     my ($output,$rem,@currtypes);
 2250:     if ($curr ne '') {
 2251:         @currtypes = map { &unescape($_); } split(/:/,$curr);
 2252:     }
 2253:     my $numinrow = 2;
 2254:     if (ref($types) eq 'ARRAY') {
 2255:         $output = '<table>';
 2256:         my $lastcolspan; 
 2257:         for (my $i=0; $i<@{$types}; $i++) {
 2258:             if (defined($usertypes->{$types->[$i]})) {
 2259:                 my $rem = $i%($numinrow);
 2260:                 if ($rem == 0) {
 2261:                     if ($i<@{$types}-1) {
 2262:                         if ($i > 0) { 
 2263:                             $output .= '</tr>';
 2264:                         }
 2265:                         $output .= '<tr>';
 2266:                     }
 2267:                 } elsif ($i==@{$types}-1) {
 2268:                     my $colsleft = $numinrow - $rem;
 2269:                     if ($colsleft > 1) {
 2270:                         $lastcolspan = ' colspan="'.$colsleft.'"';
 2271:                     }
 2272:                 }
 2273:                 my $check = ' ';
 2274:                 if (grep(/^\Q$types->[$i]\E$/,@currtypes)) {
 2275:                     $check = ' checked="checked" ';
 2276:                 }
 2277:                 $output .= '<td class="LC_left_item"'.$lastcolspan.'>'.
 2278:                            '<span class="LC_nobreak"><label>'.
 2279:                            '<input type="checkbox" name="inststatus" '.
 2280:                            'value="'.$types->[$i].'"'.$check.'/>'.
 2281:                            $usertypes->{$types->[$i]}.'</label></span></td>';
 2282:             }
 2283:         }
 2284:         $output .= '</tr></table>';
 2285:     }
 2286:     return $output;
 2287: }
 2288: 
 2289: sub selfcreate_canmodify {
 2290:     my ($context,$dom,$userinfo,$inst_results,$rolesarray) = @_;
 2291:     if (ref($inst_results) eq 'HASH') {
 2292:         my @inststatuses = &get_inststatuses($inst_results);
 2293:         if (@inststatuses == 0) {
 2294:             @inststatuses = ('default');
 2295:         }
 2296:         $rolesarray = \@inststatuses;
 2297:     }
 2298:     my %canmodify =
 2299:         &Apache::lonuserutils::can_modify_userinfo($context,$dom,$userinfo,
 2300:                                                    $rolesarray);
 2301:     return %canmodify;
 2302: }
 2303: 
 2304: sub get_inststatuses {
 2305:     my ($insthashref) = @_;
 2306:     my @inststatuses = ();
 2307:     if (ref($insthashref) eq 'HASH') {
 2308:         if (ref($insthashref->{'inststatus'}) eq 'ARRAY') {
 2309:             @inststatuses = @{$insthashref->{'inststatus'}};
 2310:         }
 2311:     }
 2312:     return @inststatuses;
 2313: }
 2314: 
 2315: # ================================================================= Phase Three
 2316: sub update_user_data {
 2317:     my ($r,$context,$crstype,$brcrum) = @_; 
 2318:     my $uhome=&Apache::lonnet::homeserver($env{'form.ccuname'},
 2319:                                           $env{'form.ccdomain'});
 2320:     # Error messages
 2321:     my $error     = '<span class="LC_error">'.&mt('Error').': ';
 2322:     my $end       = '</span><br /><br />';
 2323:     my $rtnlink   = '<a href="javascript:backPage(document.userupdate,'.
 2324:                     "'$env{'form.prevphase'}','modify')".'" />'.
 2325:                     &mt('Return to previous page').'</a>'.
 2326:                     &Apache::loncommon::end_page();
 2327:     my $now = time;
 2328:     my $title;
 2329:     if (exists($env{'form.makeuser'})) {
 2330: 	$title='Set Privileges for New User';
 2331:     } else {
 2332:         $title='Modify User Privileges';
 2333:     }
 2334:     my $newuser = 0;
 2335:     my ($jsback,$elements) = &crumb_utilities();
 2336:     my $jscript = '<script type="text/javascript">'."\n".
 2337:                   '// <![CDATA['."\n".
 2338:                   $jsback."\n".
 2339:                   '// ]]>'."\n".
 2340:                   '</script>'."\n";
 2341:     my %breadcrumb_text = &singleuser_breadcrumb($crstype);
 2342:     push (@{$brcrum},
 2343:              {href => "javascript:backPage(document.userupdate)",
 2344:               text => $breadcrumb_text{'search'},
 2345:               faq  => 282,
 2346:               bug  => 'Instructor Interface',}
 2347:              );
 2348:     if ($env{'form.prevphase'} eq 'userpicked') {
 2349:         push(@{$brcrum},
 2350:                {href => "javascript:backPage(document.userupdate,'get_user_info','select')",
 2351:                 text => $breadcrumb_text{'userpicked'},
 2352:                 faq  => 282,
 2353:                 bug  => 'Instructor Interface',});
 2354:     }
 2355:     my $helpitem = 'Course_Change_Privileges';
 2356:     if ($env{'form.action'} eq 'singlestudent') {
 2357:         $helpitem = 'Course_Add_Student';
 2358:     }
 2359:     push(@{$brcrum}, 
 2360:             {href => "javascript:backPage(document.userupdate,'$env{'form.prevphase'}','modify')",
 2361:              text => $breadcrumb_text{'modify'},
 2362:              faq  => 282,
 2363:              bug  => 'Instructor Interface',},
 2364:             {href => "/adm/createuser",
 2365:              text => "Result",
 2366:              faq  => 282,
 2367:              bug  => 'Instructor Interface',
 2368:              help => $helpitem});
 2369:     my $args = {bread_crumbs          => $brcrum,
 2370:                 bread_crumbs_component => 'User Management'};
 2371:     if ($env{'form.popup'}) {
 2372:         $args->{'no_nav_bar'} = 1;
 2373:     }
 2374:     $r->print(&Apache::loncommon::start_page($title,$jscript,$args));
 2375:     $r->print(&update_result_form($uhome));
 2376:     # Check Inputs
 2377:     if (! $env{'form.ccuname'} ) {
 2378: 	$r->print($error.&mt('No login name specified').'.'.$end.$rtnlink);
 2379: 	return;
 2380:     }
 2381:     if (  $env{'form.ccuname'} ne 
 2382: 	  &LONCAPA::clean_username($env{'form.ccuname'}) ) {
 2383: 	$r->print($error.&mt('Invalid login name.').'  '.
 2384: 		  &mt('Only letters, numbers, periods, dashes, @, and underscores are valid.').
 2385: 		  $end.$rtnlink);
 2386: 	return;
 2387:     }
 2388:     if (! $env{'form.ccdomain'}       ) {
 2389: 	$r->print($error.&mt('No domain specified').'.'.$end.$rtnlink);
 2390: 	return;
 2391:     }
 2392:     if (  $env{'form.ccdomain'} ne
 2393: 	  &LONCAPA::clean_domain($env{'form.ccdomain'}) ) {
 2394: 	$r->print($error.&mt('Invalid domain name.').'  '.
 2395: 		  &mt('Only letters, numbers, periods, dashes, and underscores are valid.').
 2396: 		  $end.$rtnlink);
 2397: 	return;
 2398:     }
 2399:     if ($uhome eq 'no_host') {
 2400:         $newuser = 1;
 2401:     }
 2402:     if (! exists($env{'form.makeuser'})) {
 2403:         # Modifying an existing user, so check the validity of the name
 2404:         if ($uhome eq 'no_host') {
 2405:             $r->print($error.&mt('Unable to determine home server for ').
 2406:                       $env{'form.ccuname'}.&mt(' in domain ').
 2407:                       $env{'form.ccdomain'}.'.');
 2408:             return;
 2409:         }
 2410:     }
 2411:     # Determine authentication method and password for the user being modified
 2412:     my $amode='';
 2413:     my $genpwd='';
 2414:     if ($env{'form.login'} eq 'krb') {
 2415: 	$amode='krb';
 2416: 	$amode.=$env{'form.krbver'};
 2417: 	$genpwd=$env{'form.krbarg'};
 2418:     } elsif ($env{'form.login'} eq 'int') {
 2419: 	$amode='internal';
 2420: 	$genpwd=$env{'form.intarg'};
 2421:     } elsif ($env{'form.login'} eq 'fsys') {
 2422: 	$amode='unix';
 2423: 	$genpwd=$env{'form.fsysarg'};
 2424:     } elsif ($env{'form.login'} eq 'loc') {
 2425: 	$amode='localauth';
 2426: 	$genpwd=$env{'form.locarg'};
 2427: 	$genpwd=" " if (!$genpwd);
 2428:     } elsif (($env{'form.login'} eq 'nochange') ||
 2429:              ($env{'form.login'} eq ''        )) { 
 2430:         # There is no need to tell the user we did not change what they
 2431:         # did not ask us to change.
 2432:         # If they are creating a new user but have not specified login
 2433:         # information this will be caught below.
 2434:     } else {
 2435: 	    $r->print($error.&mt('Invalid login mode or password').$end.$rtnlink);    
 2436: 	    return;
 2437:     }
 2438: 
 2439:     $r->print('<h3>'.&mt('User [_1] in domain [_2]',
 2440: 			 $env{'form.ccuname'}, $env{'form.ccdomain'}).'</h3>');
 2441:     $r->print('<p class="LC_info">'.&mt('Please be patient').'</p>');
 2442: 
 2443:     my (%alerts,%rulematch,%inst_results,%curr_rules);
 2444:     my @userinfo = ('firstname','middlename','lastname','generation','permanentemail','id');
 2445:     my @usertools = ('aboutme','blog','webdav','portfolio');
 2446:     my @requestcourses = ('official','unofficial','community');
 2447:     my @requestauthor = ('requestauthor');
 2448:     my ($othertitle,$usertypes,$types) = 
 2449:         &Apache::loncommon::sorted_inst_types($env{'form.ccdomain'});
 2450:     my %canmodify_status =
 2451:         &Apache::lonuserutils::can_modify_userinfo($context,$env{'form.ccdomain'},
 2452:                                                    ['inststatus']);
 2453:     if ($env{'form.makeuser'}) {
 2454: 	$r->print('<h3>'.&mt('Creating new account.').'</h3>');
 2455:         # Check for the authentication mode and password
 2456:         if (! $amode || ! $genpwd) {
 2457: 	    $r->print($error.&mt('Invalid login mode or password').$end.$rtnlink);    
 2458: 	    return;
 2459: 	}
 2460:         # Determine desired host
 2461:         my $desiredhost = $env{'form.hserver'};
 2462:         if (lc($desiredhost) eq 'default') {
 2463:             $desiredhost = undef;
 2464:         } else {
 2465:             my %home_servers = 
 2466: 		&Apache::lonnet::get_servers($env{'form.ccdomain'},'library');
 2467:             if (! exists($home_servers{$desiredhost})) {
 2468:                 $r->print($error.&mt('Invalid home server specified').$end.$rtnlink);
 2469:                 return;
 2470:             }
 2471:         }
 2472:         # Check ID format
 2473:         my %checkhash;
 2474:         my %checks = ('id' => 1);
 2475:         %{$checkhash{$env{'form.ccuname'}.':'.$env{'form.ccdomain'}}} = (
 2476:             'newuser' => $newuser, 
 2477:             'id' => $env{'form.cid'},
 2478:         );
 2479:         if ($env{'form.cid'} ne '') {
 2480:             &Apache::loncommon::user_rule_check(\%checkhash,\%checks,\%alerts,
 2481:                                           \%rulematch,\%inst_results,\%curr_rules);
 2482:             if (ref($alerts{'id'}) eq 'HASH') {
 2483:                 if (ref($alerts{'id'}{$env{'form.ccdomain'}}) eq 'HASH') {
 2484:                     my $domdesc =
 2485:                         &Apache::lonnet::domain($env{'form.ccdomain'},'description');
 2486:                     if ($alerts{'id'}{$env{'form.ccdomain'}}{$env{'form.cid'}}) {
 2487:                         my $userchkmsg;
 2488:                         if (ref($curr_rules{$env{'form.ccdomain'}}) eq 'HASH') {
 2489:                             $userchkmsg  = 
 2490:                                 &Apache::loncommon::instrule_disallow_msg('id',
 2491:                                                                     $domdesc,1).
 2492:                                 &Apache::loncommon::user_rule_formats($env{'form.ccdomain'},
 2493:                                     $domdesc,$curr_rules{$env{'form.ccdomain'}}{'id'},'id');
 2494:                         }
 2495:                         $r->print($error.&mt('Invalid ID format').$end.
 2496:                                   $userchkmsg.$rtnlink);
 2497:                         return;
 2498:                     }
 2499:                 }
 2500:             }
 2501:         }
 2502: 	# Call modifyuser
 2503: 	my $result = &Apache::lonnet::modifyuser
 2504: 	    ($env{'form.ccdomain'},$env{'form.ccuname'},$env{'form.cid'},
 2505:              $amode,$genpwd,$env{'form.cfirstname'},
 2506:              $env{'form.cmiddlename'},$env{'form.clastname'},
 2507:              $env{'form.cgeneration'},undef,$desiredhost,
 2508:              $env{'form.cpermanentemail'});
 2509: 	$r->print(&mt('Generating user').': '.$result);
 2510:         $uhome = &Apache::lonnet::homeserver($env{'form.ccuname'},
 2511:                                                $env{'form.ccdomain'});
 2512:         my (%changeHash,%newcustom,%changed,%changedinfo);
 2513:         if ($uhome ne 'no_host') {
 2514:             if ($context eq 'domain') {
 2515:                 if ($env{'form.customquota'} == 1) {
 2516:                     if ($env{'form.portfolioquota'} eq '') {
 2517:                         $newcustom{'quota'} = 0;
 2518:                     } else {
 2519:                         $newcustom{'quota'} = $env{'form.portfolioquota'};
 2520:                         $newcustom{'quota'} =~ s/[^\d\.]//g;
 2521:                     }
 2522:                     $changed{'quota'} = &quota_admin($newcustom{'quota'},\%changeHash);
 2523:                 }
 2524:                 foreach my $item (@usertools) {
 2525:                     if ($env{'form.custom'.$item} == 1) {
 2526:                         $newcustom{$item} = $env{'form.tools_'.$item};
 2527:                         $changed{$item} = &tool_admin($item,$newcustom{$item},
 2528:                                                      \%changeHash,'tools');
 2529:                     }
 2530:                 }
 2531:                 foreach my $item (@requestcourses) {
 2532:                     if ($env{'form.custom'.$item} == 1) {
 2533:                         $newcustom{$item} = $env{'form.crsreq_'.$item};
 2534:                         if ($env{'form.crsreq_'.$item} eq 'autolimit') {
 2535:                             $newcustom{$item} .= '=';
 2536:                             unless ($env{'form.crsreq_'.$item.'_limit'} =~ /\D/) {
 2537:                                 $newcustom{$item} .= $env{'form.crsreq_'.$item.'_limit'};
 2538:                             }
 2539:                         }
 2540:                         $changed{$item} = &tool_admin($item,$newcustom{$item},
 2541:                                                       \%changeHash,'requestcourses');
 2542:                     }
 2543:                 }
 2544:                 if ($env{'form.customrequestauthor'} == 1) {
 2545:                     $newcustom{'requestauthor'} = $env{'form.requestauthor'};
 2546:                     $changed{'requestauthor'} = &tool_admin('requestauthor',
 2547:                                                     $newcustom{'requestauthor'},
 2548:                                                     \%changeHash,'requestauthor');
 2549:                 }
 2550:             }
 2551:             if ($canmodify_status{'inststatus'}) {
 2552:                 if (exists($env{'form.inststatus'})) {
 2553:                     my @inststatuses = &Apache::loncommon::get_env_multiple('form.inststatus');
 2554:                     if (@inststatuses > 0) {
 2555:                         $changeHash{'inststatus'} = join(',',@inststatuses);
 2556:                         $changed{'inststatus'} = $changeHash{'inststatus'};
 2557:                     }
 2558:                 }
 2559:             }
 2560:             if (keys(%changed)) {
 2561:                 foreach my $item (@userinfo) {
 2562:                     $changeHash{$item}  = $env{'form.c'.$item};
 2563:                 }
 2564:                 my $chgresult =
 2565:                      &Apache::lonnet::put('environment',\%changeHash,
 2566:                                           $env{'form.ccdomain'},$env{'form.ccuname'});
 2567:             } 
 2568:         }
 2569:         $r->print('<br />'.&mt('Home server').': '.$uhome.' '.
 2570:                   &Apache::lonnet::hostname($uhome));
 2571:     } elsif (($env{'form.login'} ne 'nochange') &&
 2572:              ($env{'form.login'} ne ''        )) {
 2573: 	# Modify user privileges
 2574:         if (! $amode || ! $genpwd) {
 2575: 	    $r->print($error.'Invalid login mode or password'.$end.$rtnlink);    
 2576: 	    return;
 2577: 	}
 2578: 	# Only allow authentification modification if the person has authority
 2579: 	if (&Apache::lonnet::allowed('mau',$env{'form.ccdomain'})) {
 2580: 	    $r->print('Modifying authentication: '.
 2581:                       &Apache::lonnet::modifyuserauth(
 2582: 		       $env{'form.ccdomain'},$env{'form.ccuname'},
 2583:                        $amode,$genpwd));
 2584:             $r->print('<br />'.&mt('Home server').': '.&Apache::lonnet::homeserver
 2585: 		  ($env{'form.ccuname'},$env{'form.ccdomain'}));
 2586: 	} else {
 2587: 	    # Okay, this is a non-fatal error.
 2588: 	    $r->print($error.&mt('You do not have the authority to modify this users authentification information').'.'.$end);    
 2589: 	}
 2590:     }
 2591: 
 2592:     $r->rflush(); # Finish display of header before time consuming actions start
 2593: 
 2594:     ##
 2595:     my (@userroles,%userupdate,$cnum,$cdom,%namechanged);
 2596:     if ($context eq 'course') {
 2597:         ($cnum,$cdom) = &Apache::lonuserutils::get_course_identity();
 2598:         $crstype = &Apache::loncommon::course_type($cdom.'_'.$cnum);
 2599:     }
 2600:     if (! $env{'form.makeuser'} ) {
 2601:         # Check for need to change
 2602:         my %userenv = &Apache::lonnet::get
 2603:             ('environment',['firstname','middlename','lastname','generation',
 2604:              'id','permanentemail','portfolioquota','inststatus','tools.aboutme',
 2605:              'tools.blog','tools.webdav','tools.portfolio',
 2606:              'requestcourses.official','requestcourses.unofficial',
 2607:              'requestcourses.community','reqcrsotherdom.official',
 2608:              'reqcrsotherdom.unofficial','reqcrsotherdom.community',
 2609:              'requestauthor'],
 2610:               $env{'form.ccdomain'},$env{'form.ccuname'});
 2611:         my ($tmp) = keys(%userenv);
 2612:         if ($tmp =~ /^(con_lost|error)/i) { 
 2613:             %userenv = ();
 2614:         }
 2615:         my $no_forceid_alert;
 2616:         # Check to see if user information can be changed
 2617:         my %domconfig =
 2618:             &Apache::lonnet::get_dom('configuration',['usermodification'],
 2619:                                      $env{'form.ccdomain'});
 2620:         my @statuses = ('active','future');
 2621:         my %roles = &Apache::lonnet::get_my_roles($env{'form.ccuname'},$env{'form.ccdomain'},'userroles',\@statuses,undef,$env{'request.role.domain'});
 2622:         my ($auname,$audom);
 2623:         if ($context eq 'author') {
 2624:             $auname = $env{'user.name'};
 2625:             $audom = $env{'user.domain'};     
 2626:         }
 2627:         foreach my $item (keys(%roles)) {
 2628:             my ($rolenum,$roledom,$role) = split(/:/,$item,-1);
 2629:             if ($context eq 'course') {
 2630:                 if ($cnum ne '' && $cdom ne '') {
 2631:                     if ($rolenum eq $cnum && $roledom eq $cdom) {
 2632:                         if (!grep(/^\Q$role\E$/,@userroles)) {
 2633:                             push(@userroles,$role);
 2634:                         }
 2635:                     }
 2636:                 }
 2637:             } elsif ($context eq 'author') {
 2638:                 if ($rolenum eq $auname && $roledom eq $audom) {
 2639:                     if (!grep(/^\Q$role\E$/,@userroles)) { 
 2640:                         push(@userroles,$role);
 2641:                     }
 2642:                 }
 2643:             }
 2644:         }
 2645:         if ($env{'form.action'} eq 'singlestudent') {
 2646:             if (!grep(/^st$/,@userroles)) {
 2647:                 push(@userroles,'st');
 2648:             }
 2649:         } else {
 2650:             # Check for course or co-author roles being activated or re-enabled
 2651:             if ($context eq 'author' || $context eq 'course') {
 2652:                 foreach my $key (keys(%env)) {
 2653:                     if ($context eq 'author') {
 2654:                         if ($key=~/^form\.act_\Q$audom\E_\Q$auname\E_([^_]+)/) {
 2655:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 2656:                                 push(@userroles,$1);
 2657:                             }
 2658:                         } elsif ($key =~/^form\.ren\:\Q$audom\E\/\Q$auname\E_([^_]+)/) {
 2659:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 2660:                                 push(@userroles,$1);
 2661:                             }
 2662:                         }
 2663:                     } elsif ($context eq 'course') {
 2664:                         if ($key=~/^form\.act_\Q$cdom\E_\Q$cnum\E_([^_]+)/) {
 2665:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 2666:                                 push(@userroles,$1);
 2667:                             }
 2668:                         } elsif ($key =~/^form\.ren\:\Q$cdom\E\/\Q$cnum\E(\/?\w*)_([^_]+)/) {
 2669:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 2670:                                 push(@userroles,$1);
 2671:                             }
 2672:                         }
 2673:                     }
 2674:                 }
 2675:             }
 2676:         }
 2677:         #Check to see if we can change personal data for the user 
 2678:         my (@mod_disallowed,@longroles);
 2679:         foreach my $role (@userroles) {
 2680:             if ($role eq 'cr') {
 2681:                 push(@longroles,'Custom');
 2682:             } else {
 2683:                 push(@longroles,&Apache::lonnet::plaintext($role,$crstype)); 
 2684:             }
 2685:         }
 2686:         my %canmodify = &Apache::lonuserutils::can_modify_userinfo($context,$env{'form.ccdomain'},\@userinfo,\@userroles);
 2687:         foreach my $item (@userinfo) {
 2688:             # Strip leading and trailing whitespace
 2689:             $env{'form.c'.$item} =~ s/(\s+$|^\s+)//g;
 2690:             if (!$canmodify{$item}) {
 2691:                 if (defined($env{'form.c'.$item})) {
 2692:                     if ($env{'form.c'.$item} ne $userenv{$item}) {
 2693:                         push(@mod_disallowed,$item);
 2694:                     }
 2695:                 }
 2696:                 $env{'form.c'.$item} = $userenv{$item};
 2697:             }
 2698:         }
 2699:         # Check to see if we can change the Student/Employee ID
 2700:         my $forceid = $env{'form.forceid'};
 2701:         my $recurseid = $env{'form.recurseid'};
 2702:         my (%alerts,%rulematch,%idinst_results,%curr_rules,%got_rules);
 2703:         my %uidhash = &Apache::lonnet::idrget($env{'form.ccdomain'},
 2704:                                             $env{'form.ccuname'});
 2705:         if (($uidhash{$env{'form.ccuname'}}) && 
 2706:             ($uidhash{$env{'form.ccuname'}}!~/error\:/) && 
 2707:             (!$forceid)) {
 2708:             if ($env{'form.cid'} ne $uidhash{$env{'form.ccuname'}}) {
 2709:                 $env{'form.cid'} = $userenv{'id'};
 2710:                 $no_forceid_alert = &mt('New student/employee ID does not match existing ID for this user.')
 2711:                                    .'<br />'
 2712:                                    .&mt("Change is not permitted without checking the 'Force ID change' checkbox on the previous page.")
 2713:                                    .'<br />'."\n";
 2714:             }
 2715:         }
 2716:         if ($env{'form.cid'} ne $userenv{'id'}) {
 2717:             my $checkhash;
 2718:             my $checks = { 'id' => 1 };
 2719:             $checkhash->{$env{'form.ccuname'}.':'.$env{'form.ccdomain'}} = 
 2720:                    { 'newuser' => $newuser,
 2721:                      'id'  => $env{'form.cid'}, 
 2722:                    };
 2723:             &Apache::loncommon::user_rule_check($checkhash,$checks,
 2724:                 \%alerts,\%rulematch,\%idinst_results,\%curr_rules,\%got_rules);
 2725:             if (ref($alerts{'id'}) eq 'HASH') {
 2726:                 if (ref($alerts{'id'}{$env{'form.ccdomain'}}) eq 'HASH') {
 2727:                    $env{'form.cid'} = $userenv{'id'};
 2728:                 }
 2729:             }
 2730:         }
 2731:         my ($quotachanged,$oldportfolioquota,$newportfolioquota,$oldinststatus,
 2732:             $newinststatus,$oldisdefault,$newisdefault,%oldsettings,
 2733:             %oldsettingstext,%newsettings,%newsettingstext,@disporder,
 2734:             $olddefquota,$oldsettingstatus,$newdefquota,$newsettingstatus);
 2735:         @disporder = ('inststatus');
 2736:         if ($env{'request.role.domain'} eq $env{'form.ccdomain'}) {
 2737:             push(@disporder,'requestcourses','requestauthor');
 2738:         } else {
 2739:             push(@disporder,'reqcrsotherdom');
 2740:         }
 2741:         push(@disporder,('quota','tools'));
 2742:         $oldinststatus = $userenv{'inststatus'};
 2743:         ($olddefquota,$oldsettingstatus) = 
 2744:             &Apache::loncommon::default_quota($env{'form.ccdomain'},$oldinststatus);
 2745:         ($newdefquota,$newsettingstatus) = ($olddefquota,$oldsettingstatus);
 2746:         my %canshow;
 2747:         if (&Apache::lonnet::allowed('mpq',$env{'form.ccdomain'})) {
 2748:             $canshow{'quota'} = 1;
 2749:         }
 2750:         if (&Apache::lonnet::allowed('mut',$env{'form.ccdomain'})) {
 2751:             $canshow{'tools'} = 1;
 2752:         }
 2753:         if (&Apache::lonnet::allowed('ccc',$env{'form.ccdomain'})) {
 2754:             $canshow{'requestcourses'} = 1;
 2755:         } elsif (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) {
 2756:             $canshow{'reqcrsotherdom'} = 1;
 2757:         }
 2758:         if (&Apache::lonnet::allowed('mau',$env{'form.ccdomain'})) {
 2759:             $canshow{'inststatus'} = 1;
 2760:         }
 2761:         if (&Apache::lonnet::allowed('cau',$env{'form.ccdomain'})) {
 2762:             $canshow{'requestauthor'} = 1;
 2763:         }
 2764:         my (%changeHash,%changed);
 2765:         if ($oldinststatus eq '') {
 2766:             $oldsettings{'inststatus'} = $othertitle; 
 2767:         } else {
 2768:             if (ref($usertypes) eq 'HASH') {
 2769:                 $oldsettings{'inststatus'} = join(', ',map{ $usertypes->{ &unescape($_) }; } (split(/:/,$userenv{'inststatus'})));
 2770:             } else {
 2771:                 $oldsettings{'inststatus'} = join(', ',map{ &unescape($_); } (split(/:/,$userenv{'inststatus'})));
 2772:             }
 2773:         }
 2774:         $changeHash{'inststatus'} = $userenv{'inststatus'};
 2775:         if ($canmodify_status{'inststatus'}) {
 2776:             $canshow{'inststatus'} = 1;
 2777:             if (exists($env{'form.inststatus'})) {
 2778:                 my @inststatuses = &Apache::loncommon::get_env_multiple('form.inststatus');
 2779:                 if (@inststatuses > 0) {
 2780:                     $newinststatus = join(':',map { &escape($_); } @inststatuses);
 2781:                     $changeHash{'inststatus'} = $newinststatus;
 2782:                     if ($newinststatus ne $oldinststatus) {
 2783:                         $changed{'inststatus'} = $newinststatus;
 2784:                         ($newdefquota,$newsettingstatus) =
 2785:                             &Apache::loncommon::default_quota($env{'form.ccdomain'},$newinststatus);
 2786:                     }
 2787:                     if (ref($usertypes) eq 'HASH') {
 2788:                         $newsettings{'inststatus'} = join(', ',map{ $usertypes->{$_}; } (@inststatuses)); 
 2789:                     } else {
 2790:                         $newsettings{'inststatus'} = join(', ',@inststatuses);
 2791:                     }
 2792:                 }
 2793:             } else {
 2794:                 $newinststatus = '';
 2795:                 $changeHash{'inststatus'} = $newinststatus;
 2796:                 $newsettings{'inststatus'} = $othertitle;
 2797:                 if ($newinststatus ne $oldinststatus) {
 2798:                     $changed{'inststatus'} = $changeHash{'inststatus'};
 2799:                     ($newdefquota,$newsettingstatus) =
 2800:                         &Apache::loncommon::default_quota($env{'form.ccdomain'},$newinststatus);
 2801:                 }
 2802:             }
 2803:         } elsif ($context ne 'selfcreate') {
 2804:             $canshow{'inststatus'} = 1;
 2805:             $newsettings{'inststatus'} = $oldsettings{'inststatus'};
 2806:         }
 2807:         $changeHash{'portfolioquota'} = $userenv{'portfolioquota'};
 2808:         if ($context eq 'domain') {
 2809:             if ($userenv{'portfolioquota'} ne '') {
 2810:                 $oldportfolioquota = $userenv{'portfolioquota'};
 2811:                 if ($env{'form.customquota'} == 1) {
 2812:                     if ($env{'form.portfolioquota'} eq '') {
 2813:                         $newportfolioquota = 0;
 2814:                     } else {
 2815:                         $newportfolioquota = $env{'form.portfolioquota'};
 2816:                         $newportfolioquota =~ s/[^\d\.]//g;
 2817:                     }
 2818:                     if ($newportfolioquota != $oldportfolioquota) {
 2819:                         $changed{'quota'} = &quota_admin($newportfolioquota,\%changeHash);
 2820:                     }
 2821:                 } else {
 2822:                     $changed{'quota'} = &quota_admin('',\%changeHash);
 2823:                     $newportfolioquota = $newdefquota;
 2824:                     $newisdefault = 1;
 2825:                 }
 2826:             } else {
 2827:                 $oldisdefault = 1;
 2828:                 $oldportfolioquota = $olddefquota;
 2829:                 if ($env{'form.customquota'} == 1) {
 2830:                     if ($env{'form.portfolioquota'} eq '') {
 2831:                         $newportfolioquota = 0;
 2832:                     } else {
 2833:                         $newportfolioquota = $env{'form.portfolioquota'};
 2834:                         $newportfolioquota =~ s/[^\d\.]//g;
 2835:                     }
 2836:                     $changed{'quota'} = &quota_admin($newportfolioquota,\%changeHash);
 2837:                 } else {
 2838:                     $newportfolioquota = $newdefquota;
 2839:                     $newisdefault = 1;
 2840:                 }
 2841:             }
 2842:             if ($oldisdefault) {
 2843:                 $oldsettingstext{'quota'} = &get_defaultquota_text($oldsettingstatus);
 2844:             }
 2845:             if ($newisdefault) {
 2846:                 $newsettingstext{'quota'} = &get_defaultquota_text($newsettingstatus);
 2847:             }
 2848:             &tool_changes('tools',\@usertools,\%oldsettings,\%oldsettingstext,\%userenv,
 2849:                           \%changeHash,\%changed,\%newsettings,\%newsettingstext);
 2850:             if ($env{'form.ccdomain'} eq $env{'request.role.domain'}) {
 2851:                 &tool_changes('requestcourses',\@requestcourses,\%oldsettings,\%oldsettingstext,
 2852:                               \%userenv,\%changeHash,\%changed,\%newsettings,\%newsettingstext);
 2853:                 &tool_changes('requestauthor',\@requestauthor,\%oldsettings,\%oldsettingstext,\%userenv,\%changeHash,\%changed,\%newsettings,\%newsettingstext);
 2854:             } else {
 2855:                 &tool_changes('reqcrsotherdom',\@requestcourses,\%oldsettings,\%oldsettingstext,
 2856:                               \%userenv,\%changeHash,\%changed,\%newsettings,\%newsettingstext);
 2857:             }
 2858:         }
 2859:         foreach my $item (@userinfo) {
 2860:             if ($env{'form.c'.$item} ne $userenv{$item}) {
 2861:                 $namechanged{$item} = 1;
 2862:             }
 2863:         }
 2864:         $oldsettings{'quota'} = $oldportfolioquota.' Mb';
 2865:         $newsettings{'quota'} = $newportfolioquota.' Mb';
 2866:         if ((keys(%namechanged) > 0) || (keys(%changed) > 0)) {
 2867:             my ($chgresult,$namechgresult);
 2868:             if (keys(%changed) > 0) {
 2869:                 $chgresult = 
 2870:                     &Apache::lonnet::put('environment',\%changeHash,
 2871:                                   $env{'form.ccdomain'},$env{'form.ccuname'});
 2872:                 if ($chgresult eq 'ok') {
 2873:                     if (($env{'user.name'} eq $env{'form.ccuname'}) &&
 2874:                         ($env{'user.domain'} eq $env{'form.ccdomain'})) {
 2875:                         my %newenvhash;
 2876:                         foreach my $key (keys(%changed)) {
 2877:                             if (($key eq 'official') || ($key eq 'unofficial')
 2878:                                 || ($key eq 'community')) {
 2879:                                 $newenvhash{'environment.requestcourses.'.$key} =
 2880:                                     $changeHash{'requestcourses.'.$key};
 2881:                                 if ($changeHash{'requestcourses.'.$key}) {
 2882:                                     $newenvhash{'environment.canrequest.'.$key} = 1;
 2883:                                 } else {
 2884:                                     $newenvhash{'environment.canrequest.'.$key} =
 2885:           &Apache::lonnet::usertools_access($env{'user.name'},$env{'user.domain'},
 2886:                                             $key,'reload','requestcourses');
 2887:                                 }
 2888:                             } elsif ($key eq 'requestauthor') {
 2889:                                 $newenvhash{'environment.'.$key} = $changeHash{$key};
 2890:                                 if ($changeHash{$key}) {
 2891:                                     $newenvhash{'environment.canrequest.author'} = 1;
 2892:                                 } else {
 2893:                                     $newenvhash{'environment.canrequest.author'} =
 2894:           &Apache::lonnet::usertools_access($env{'user.name'},$env{'user.domain'},
 2895:                                             $key,'reload','requestauthor');
 2896:                                 }
 2897:                             } elsif ($key ne 'quota') {
 2898:                                 $newenvhash{'environment.tools.'.$key} = 
 2899:                                     $changeHash{'tools.'.$key};
 2900:                                 if ($changeHash{'tools.'.$key} ne '') {
 2901:                                     $newenvhash{'environment.availabletools.'.$key} =
 2902:                                         $changeHash{'tools.'.$key};
 2903:                                 } else {
 2904:                                     $newenvhash{'environment.availabletools.'.$key} =
 2905:           &Apache::lonnet::usertools_access($env{'user.name'},$env{'user.domain'},                                            $key,'reload','tools');
 2906:                                 }
 2907:                             }
 2908:                         }
 2909:                         if (keys(%newenvhash)) {
 2910:                             &Apache::lonnet::appenv(\%newenvhash);
 2911:                         }
 2912:                     }
 2913:                 }
 2914:             }
 2915:             if (keys(%namechanged) > 0) {
 2916:                 foreach my $field (@userinfo) {
 2917:                     $changeHash{$field}  = $env{'form.c'.$field};
 2918:                 }
 2919: # Make the change
 2920:                 $namechgresult =
 2921:                     &Apache::lonnet::modifyuser($env{'form.ccdomain'},
 2922:                         $env{'form.ccuname'},$changeHash{'id'},undef,undef,
 2923:                         $changeHash{'firstname'},$changeHash{'middlename'},
 2924:                         $changeHash{'lastname'},$changeHash{'generation'},
 2925:                         $changeHash{'id'},undef,$changeHash{'permanentemail'},undef,\@userinfo);
 2926:                 %userupdate = (
 2927:                                lastname   => $env{'form.clastname'},
 2928:                                middlename => $env{'form.cmiddlename'},
 2929:                                firstname  => $env{'form.cfirstname'},
 2930:                                generation => $env{'form.cgeneration'},
 2931:                                id         => $env{'form.cid'},
 2932:                              );
 2933:             }
 2934:             if (((keys(%namechanged) > 0) && $namechgresult eq 'ok') || 
 2935:                 ((keys(%changed) > 0) && $chgresult eq 'ok')) {
 2936:             # Tell the user we changed the name
 2937:                 &display_userinfo($r,1,\@disporder,\%canshow,\@requestcourses,
 2938:                                   \@usertools,\@requestauthor,\%userenv,\%changed,\%namechanged,
 2939:                                   \%oldsettings, \%oldsettingstext,\%newsettings,
 2940:                                   \%newsettingstext);
 2941:                 if ($env{'form.cid'} ne $userenv{'id'}) {
 2942:                     &Apache::lonnet::idput($env{'form.ccdomain'},
 2943:                          ($env{'form.ccuname'} => $env{'form.cid'}));
 2944:                     if (($recurseid) &&
 2945:                         (&Apache::lonnet::allowed('mau',$env{'form.ccdomain'}))) {
 2946:                         my $idresult = 
 2947:                             &Apache::lonuserutils::propagate_id_change(
 2948:                                 $env{'form.ccuname'},$env{'form.ccdomain'},
 2949:                                 \%userupdate);
 2950:                         $r->print('<br />'.$idresult.'<br />');
 2951:                     }
 2952:                 }
 2953:                 if (($env{'form.ccdomain'} eq $env{'user.domain'}) && 
 2954:                     ($env{'form.ccuname'} eq $env{'user.name'})) {
 2955:                     my %newenvhash;
 2956:                     foreach my $key (keys(%changeHash)) {
 2957:                         $newenvhash{'environment.'.$key} = $changeHash{$key};
 2958:                     }
 2959:                     &Apache::lonnet::appenv(\%newenvhash);
 2960:                 }
 2961:             } else { # error occurred
 2962:                 $r->print('<span class="LC_error">'.&mt('Unable to successfully change environment for').' '.
 2963:                       $env{'form.ccuname'}.' '.&mt('in domain').' '.
 2964:                       $env{'form.ccdomain'}.'</span><br />');
 2965:             }
 2966:         } else { # End of if ($env ... ) logic
 2967:             # They did not want to change the users name, quota, tool availability,
 2968:             # or ability to request creation of courses, 
 2969:             # but we can still tell them what the name and quota and availabilities are  
 2970:             &display_userinfo($r,undef,\@disporder,\%canshow,\@requestcourses,
 2971:                               \@usertools,\@requestauthor,\%userenv,\%changed,\%namechanged,\%oldsettings,
 2972:                               \%oldsettingstext,\%newsettings,\%newsettingstext);
 2973:         }
 2974:         if (@mod_disallowed) {
 2975:             my ($rolestr,$contextname);
 2976:             if (@longroles > 0) {
 2977:                 $rolestr = join(', ',@longroles);
 2978:             } else {
 2979:                 $rolestr = &mt('No roles');
 2980:             }
 2981:             if ($context eq 'course') {
 2982:                 $contextname = &mt('course');
 2983:             } elsif ($context eq 'author') {
 2984:                 $contextname = &mt('co-author');
 2985:             }
 2986:             $r->print(&mt('The following fields were not updated: ').'<ul>');
 2987:             my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
 2988:             foreach my $field (@mod_disallowed) {
 2989:                 $r->print('<li>'.$fieldtitles{$field}.'</li>'."\n"); 
 2990:             }
 2991:             $r->print('</ul>');
 2992:             if (@mod_disallowed == 1) {
 2993:                 $r->print(&mt("You do not have the authority to change this field given the user's current set of active/future [_1] roles:",$contextname));
 2994:             } else {
 2995:                 $r->print(&mt("You do not have the authority to change these fields given the user's current set of active/future [_1] roles:",$contextname));
 2996:             }
 2997:             my $helplink = 'javascript:helpMenu('."'display'".')';
 2998:             $r->print('<span class="LC_cusr_emph">'.$rolestr.'</span><br />'
 2999:                      .&mt('Please contact your [_1]helpdesk[_2] for more information.'
 3000:                          ,'<a href="'.$helplink.'">','</a>')
 3001:                       .'<br />');
 3002:         }
 3003:         $r->print('<span class="LC_warning">'
 3004:                   .$no_forceid_alert
 3005:                   .&Apache::lonuserutils::print_namespacing_alerts($env{'form.ccdomain'},\%alerts,\%curr_rules)
 3006:                   .'</span>');
 3007:     }
 3008:     if ($env{'form.action'} eq 'singlestudent') {
 3009:         &enroll_single_student($r,$uhome,$amode,$genpwd,$now,$newuser,$context,$crstype);
 3010:         $r->print('<p><a href="javascript:backPage(document.userupdate)">');
 3011:         if ($crstype eq 'Community') {
 3012:             $r->print(&mt('Enroll Another Member'));
 3013:         } else {
 3014:             $r->print(&mt('Enroll Another Student'));
 3015:         }
 3016:         $r->print('</a></p>');
 3017:     } else {
 3018:         my @rolechanges = &update_roles($r,$context);
 3019:         if (keys(%namechanged) > 0) {
 3020:             if ($context eq 'course') {
 3021:                 if (@userroles > 0) {
 3022:                     if ((@rolechanges == 0) || 
 3023:                         (!(grep(/^st$/,@rolechanges)))) {
 3024:                         if (grep(/^st$/,@userroles)) {
 3025:                             my $classlistupdated =
 3026:                                 &Apache::lonuserutils::update_classlist($cdom,
 3027:                                               $cnum,$env{'form.ccdomain'},
 3028:                                        $env{'form.ccuname'},\%userupdate);
 3029:                         }
 3030:                     }
 3031:                 }
 3032:             }
 3033:         }
 3034:         my $userinfo = &Apache::loncommon::plainname($env{'form.ccuname'},
 3035:                                                      $env{'form.ccdomain'});
 3036:         if ($env{'form.popup'}) {
 3037:             $r->print('<p><a href="javascript:window.close()">'.&mt('Close window').'</a></p>');
 3038:         } else {
 3039:             $r->print('<p><a href="javascript:backPage(document.userupdate,'."'$env{'form.prevphase'}','modify'".')">'
 3040:                      .&mt('Modify this user: [_1]','<span class="LC_cusr_emph">'.$env{'form.ccuname'}.':'.$env{'form.ccdomain'}.' ('.$userinfo.')</span>').'</a>'
 3041:                      .('&nbsp;'x5).'<a href="javascript:backPage(document.userupdate)">'
 3042:                      .&mt('Create/Modify Another User').'</a></p>');
 3043:         }
 3044:     }
 3045: }
 3046: 
 3047: sub display_userinfo {
 3048:     my ($r,$changed,$order,$canshow,$requestcourses,$usertools,$requestauthor,
 3049:         $userenv,$changedhash,$namechangedhash,$oldsetting,$oldsettingtext,
 3050:         $newsetting,$newsettingtext) = @_;
 3051:     return unless (ref($order) eq 'ARRAY' &&
 3052:                    ref($canshow) eq 'HASH' && 
 3053:                    ref($requestcourses) eq 'ARRAY' && 
 3054:                    ref($requestauthor) eq 'ARRAY' &&
 3055:                    ref($usertools) eq 'ARRAY' && 
 3056:                    ref($userenv) eq 'HASH' &&
 3057:                    ref($changedhash) eq 'HASH' &&
 3058:                    ref($oldsetting) eq 'HASH' &&
 3059:                    ref($oldsettingtext) eq 'HASH' &&
 3060:                    ref($newsetting) eq 'HASH' &&
 3061:                    ref($newsettingtext) eq 'HASH');
 3062:     my %lt=&Apache::lonlocal::texthash(
 3063:          'ui'             => 'User Information (unchanged)',
 3064:          'uic'            => 'User Information Changed',
 3065:          'firstname'      => 'First Name',
 3066:          'middlename'     => 'Middle Name',
 3067:          'lastname'       => 'Last Name',
 3068:          'generation'     => 'Generation',
 3069:          'id'             => 'Student/Employee ID',
 3070:          'permanentemail' => 'Permanent e-mail address',
 3071:          'quota'          => 'Disk space allocated to portfolio files',
 3072:          'blog'           => 'Blog Availability',
 3073:          'webdav'         => 'WebDAV Availability',
 3074:          'aboutme'        => 'Personal Information Page Availability',
 3075:          'portfolio'      => 'Portfolio Availability',
 3076:          'official'       => 'Can Request Official Courses',
 3077:          'unofficial'     => 'Can Request Unofficial Courses',
 3078:          'community'      => 'Can Request Communities',
 3079:          'requestauthor'  => 'Can Request Author Role',
 3080:          'inststatus'     => "Affiliation",
 3081:          'prvs'           => 'Previous Value:',
 3082:          'chto'           => 'Changed To:'
 3083:     );
 3084:     my $title = $lt{'ui'}; 
 3085:     if ($changed) {
 3086:         $title = $lt{'uic'};
 3087:     }
 3088:     $r->print('<h4>'.$title.'</h4>'.
 3089:               &Apache::loncommon::start_data_table().
 3090:               &Apache::loncommon::start_data_table_header_row());
 3091:     if ($changed) {
 3092:         $r->print("<th>&nbsp;</th>\n");
 3093:     }
 3094:     my @userinfo = ('firstname','middlename','lastname','generation','permanentemail','id');
 3095:     foreach my $item (@userinfo) {
 3096:         $r->print("<th>$lt{$item}</th>\n");
 3097:     }
 3098:     foreach my $entry (@{$order}) {
 3099:         if ($canshow->{$entry}) {
 3100:             if (($entry eq 'requestcourses') || ($entry eq 'reqcrsotherdom')) {
 3101:                 foreach my $item (@{$requestcourses}) {
 3102:                     $r->print("<th>$lt{$item}</th>\n");
 3103:                 }
 3104:             } elsif ($entry eq 'tools') {
 3105:                 foreach my $item (@{$usertools}) {
 3106:                     $r->print("<th>$lt{$item}</th>\n");
 3107:                 }
 3108:             } else {
 3109:                 $r->print("<th>$lt{$entry}</th>\n");
 3110:             }
 3111:         }
 3112:     }
 3113:     $r->print(&Apache::loncommon::end_data_table_header_row().
 3114:              &Apache::loncommon::start_data_table_row());
 3115:     if ($changed) {
 3116:         $r->print('<td><b>'.$lt{'prvs'}.'</b></td>'."\n");
 3117:     }
 3118:     foreach my $item (@userinfo) {
 3119:         $r->print('<td>'.$userenv->{$item}.' </td>'."\n");
 3120:     }
 3121:     foreach my $entry (@{$order}) {
 3122:         if ($canshow->{$entry}) {
 3123:             if (($entry eq 'requestcourses') || ($entry eq 'reqcrsotherdom')) {
 3124:                 foreach my $item (@{$requestcourses}) {
 3125:                     $r->print("<td>$oldsetting->{$item} $oldsettingtext->{$item}</td>\n");
 3126:                 }
 3127:             } elsif ($entry eq 'tools') {
 3128:                 foreach my $item (@{$usertools}) {
 3129:                     $r->print("<td>$oldsetting->{$item} $oldsettingtext->{$item}</td>\n");
 3130:                 }
 3131:             } else {
 3132:                 $r->print("<td>$oldsetting->{$entry} $oldsettingtext->{$entry} </td>\n");
 3133:             }
 3134:         }
 3135:     }
 3136:     $r->print(&Apache::loncommon::end_data_table_row());
 3137:     if ($changed) {
 3138:         $r->print(&Apache::loncommon::start_data_table_row().
 3139:                   '<td><span class="LC_nobreak"><b>'.$lt{'chto'}.'</b></span></td>'."\n");
 3140:         foreach my $item (@userinfo) {
 3141:             my $value = $env{'form.c'.$item};
 3142:             if ($namechangedhash->{$item}) {
 3143:                 $value = '<span class="LC_cusr_emph">'.$value.'</span>';
 3144:             }
 3145:             $r->print("<td>$value </td>\n");
 3146:         }
 3147:         foreach my $entry (@{$order}) {
 3148:             if ($canshow->{$entry}) {
 3149:                 if (($entry eq 'requestcourses') || ($entry eq 'reqcrsotherdom')) {
 3150:                     foreach my $item (@{$requestcourses}) {
 3151:                         my $value = $newsetting->{$item}.' '.$newsettingtext->{$item};
 3152:                         if ($changedhash->{$item}) {
 3153:                             $value = '<span class="LC_cusr_emph">'.$value.'</span>';
 3154:                         }
 3155:                         $r->print("<td>$value </td>\n");
 3156:                     }
 3157:                 } elsif ($entry eq 'tools') {
 3158:                     foreach my $item (@{$usertools}) {
 3159:                         my $value = $newsetting->{$item}.' '.$newsettingtext->{$item};
 3160:                         if ($changedhash->{$item}) {
 3161:                             $value = '<span class="LC_cusr_emph">'.$value.'</span>';
 3162:                         }
 3163:                         $r->print("<td>$value </td>\n");
 3164:                     }
 3165:                 } else {
 3166:                     my $value = $newsetting->{$entry}.' '.$newsettingtext->{$entry};
 3167:                     if ($changedhash->{$entry}) {
 3168:                         $value = '<span class="LC_cusr_emph">'.$value.'</span>';
 3169:                     }
 3170:                     $r->print("<td>$value </td>\n");
 3171:                 }
 3172:             }
 3173:         }
 3174:         $r->print(&Apache::loncommon::end_data_table_row());
 3175:     }
 3176:     $r->print(&Apache::loncommon::end_data_table().'<br />');
 3177:     return;
 3178: }
 3179: 
 3180: sub tool_changes {
 3181:     my ($context,$usertools,$oldaccess,$oldaccesstext,$userenv,$changeHash,
 3182:         $changed,$newaccess,$newaccesstext) = @_;
 3183:     if (!((ref($usertools) eq 'ARRAY') && (ref($oldaccess) eq 'HASH') &&
 3184:           (ref($oldaccesstext) eq 'HASH') && (ref($userenv) eq 'HASH') &&
 3185:           (ref($changeHash) eq 'HASH') && (ref($changed) eq 'HASH') &&
 3186:           (ref($newaccess) eq 'HASH') && (ref($newaccesstext) eq 'HASH'))) {
 3187:         return;
 3188:     }
 3189:     if ($context eq 'reqcrsotherdom') {
 3190:         my @options = ('approval','validate','autolimit');
 3191:         my $optregex = join('|',@options);
 3192:         my %reqdisplay = &courserequest_display();
 3193:         my $cdom = $env{'request.role.domain'};
 3194:         foreach my $tool (@{$usertools}) {
 3195:             $oldaccesstext->{$tool} = &mt('No');
 3196:             $newaccesstext->{$tool} = $oldaccesstext->{$tool};
 3197:             $changeHash->{$context.'.'.$tool} = $userenv->{$context.'.'.$tool};
 3198:             my $newop;
 3199:             if ($env{'form.'.$context.'_'.$tool}) {
 3200:                 $newop = $env{'form.'.$context.'_'.$tool};
 3201:                 if ($newop eq 'autolimit') {
 3202:                     my $limit = $env{'form.'.$context.'_'.$tool.'_limit'};
 3203:                     $limit =~ s/\D+//g;
 3204:                     $newop .= '='.$limit;
 3205:                 }
 3206:             }
 3207:             if ($userenv->{$context.'.'.$tool} eq '') {
 3208:                 if ($newop) {
 3209:                     $changed->{$tool}=&tool_admin($tool,$cdom.':'.$newop,
 3210:                                                   $changeHash,$context);
 3211:                     if ($changed->{$tool}) {
 3212:                         $newaccesstext->{$tool} = &mt('Yes');
 3213:                     } else {
 3214:                         $newaccesstext->{$tool} = $oldaccesstext->{$tool};
 3215:                     }
 3216:                 }
 3217:             } else {
 3218:                 my @curr = split(',',$userenv->{$context.'.'.$tool});
 3219:                 my @new;
 3220:                 my $changedoms;
 3221:                 foreach my $req (@curr) {
 3222:                     if ($req =~ /^\Q$cdom\E\:($optregex\=?\d*)$/) {
 3223:                         $oldaccesstext->{$tool} = &mt('Yes');
 3224:                         my $oldop = $1;
 3225:                         if ($oldop ne $newop) {
 3226:                             $changedoms = 1;
 3227:                             foreach my $item (@curr) {
 3228:                                 my ($reqdom,$option) = split(':',$item);
 3229:                                 unless ($reqdom eq $cdom) {
 3230:                                     push(@new,$item);
 3231:                                 }
 3232:                             }
 3233:                             if ($newop) {
 3234:                                 push(@new,$cdom.':'.$newop);
 3235:                             }
 3236:                             @new = sort(@new);
 3237:                         }
 3238:                         last;
 3239:                     }
 3240:                 }
 3241:                 if ((!$changedoms) && ($newop)) {
 3242:                     $changedoms = 1;
 3243:                     @new = sort(@curr,$cdom.':'.$newop);
 3244:                 }
 3245:                 if ($changedoms) {
 3246:                     my $newdomstr;
 3247:                     if (@new) {
 3248:                         $newdomstr = join(',',@new);
 3249:                     }
 3250:                     $changed->{$tool}=&tool_admin($tool,$newdomstr,$changeHash,
 3251:                                                   $context);
 3252:                     if ($changed->{$tool}) {
 3253:                         if ($env{'form.'.$context.'_'.$tool}) {
 3254:                             if ($env{'form.'.$context.'_'.$tool} eq 'autolimit') {
 3255:                                 my $limit = $env{'form.'.$context.'_'.$tool.'_limit'};
 3256:                                 $limit =~ s/\D+//g;
 3257:                                 if ($limit) {
 3258:                                     $newaccesstext->{$tool} = &mt('Yes, up to limit of [quant,_1,request] per user.',$limit);
 3259:                                 } else {
 3260:                                     $newaccesstext->{$tool} = &mt('Yes, processed automatically');
 3261:                                 }
 3262:                             } else {
 3263:                                 $newaccesstext->{$tool} = $reqdisplay{$env{'form.'.$context.'_'.$tool}};
 3264:                             }
 3265:                         } else {
 3266:                             $newaccesstext->{$tool} = &mt('No');
 3267:                         }
 3268:                     }
 3269:                 }
 3270:             }
 3271:         }
 3272:         return;
 3273:     }
 3274:     foreach my $tool (@{$usertools}) {
 3275:         my ($newval,$envkey);
 3276:         $envkey = $context.'.'.$tool;
 3277:         if ($context eq 'requestcourses') {
 3278:             $newval = $env{'form.crsreq_'.$tool};
 3279:             if ($newval eq 'autolimit') {
 3280:                 $newval .= '='.$env{'form.crsreq_'.$tool.'_limit'};
 3281:             }
 3282:         } elsif ($context eq 'requestauthor') {
 3283:             $newval = $env{'form.'.$context};
 3284:             $envkey = $context;
 3285:         } else {
 3286:             $newval = $env{'form.'.$context.'_'.$tool};
 3287:         }
 3288:         if ($userenv->{$envkey} ne '') {
 3289:             $oldaccess->{$tool} = &mt('custom');
 3290:             if ($userenv->{$envkey}) {
 3291:                 $oldaccesstext->{$tool} = &mt("availability set to 'on'");
 3292:             } else {
 3293:                 $oldaccesstext->{$tool} = &mt("availability set to 'off'");
 3294:             }
 3295:             $changeHash->{$envkey} = $userenv->{$envkey};
 3296:             if ($env{'form.custom'.$tool} == 1) {
 3297:                 if ($newval ne $userenv->{$envkey}) {
 3298:                     $changed->{$tool} = &tool_admin($tool,$newval,$changeHash,
 3299:                                                     $context);
 3300:                     if ($changed->{$tool}) {
 3301:                         $newaccess->{$tool} = &mt('custom');
 3302:                         if ($newval) {
 3303:                             $newaccesstext->{$tool} = &mt("availability set to 'on'");
 3304:                         } else {
 3305:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3306:                         }
 3307:                     } else {
 3308:                         $newaccess->{$tool} = $oldaccess->{$tool};
 3309:                         if ($userenv->{$context.'.'.$tool}) {
 3310:                             $newaccesstext->{$tool} = &mt("availability set to 'on'");
 3311:                         } else {
 3312:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3313:                         }
 3314:                     }
 3315:                 } else {
 3316:                     $newaccess->{$tool} = $oldaccess->{$tool};
 3317:                     $newaccesstext->{$tool} = $oldaccesstext->{$tool};
 3318:                 }
 3319:             } else {
 3320:                 $changed->{$tool} = &tool_admin($tool,'',$changeHash,$context);
 3321:                 if ($changed->{$tool}) {
 3322:                     $newaccess->{$tool} = &mt('default');
 3323:                 } else {
 3324:                     $newaccess->{$tool} = $oldaccess->{$tool};
 3325:                     if ($userenv->{$context.'.'.$tool}) {
 3326:                         $newaccesstext->{$tool} = &mt("availability set to 'on'");
 3327:                     } else {
 3328:                         $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3329:                     }
 3330:                 }
 3331:             }
 3332:         } else {
 3333:             $oldaccess->{$tool} = &mt('default');
 3334:             if ($env{'form.custom'.$tool} == 1) {
 3335:                 $changed->{$tool} = &tool_admin($tool,$newval,$changeHash,
 3336:                                                 $context);
 3337:                 if ($changed->{$tool}) {
 3338:                     $newaccess->{$tool} = &mt('custom');
 3339:                     if ($newval) {
 3340:                         $newaccesstext->{$tool} = &mt("availability set to 'on'");
 3341:                     } else {
 3342:                         $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3343:                     }
 3344:                 } else {
 3345:                     $newaccess->{$tool} = $oldaccess->{$tool};
 3346:                 }
 3347:             } else {
 3348:                 $newaccess->{$tool} = $oldaccess->{$tool};
 3349:             }
 3350:         }
 3351:     }
 3352:     return;
 3353: }
 3354: 
 3355: sub update_roles {
 3356:     my ($r,$context) = @_;
 3357:     my $now=time;
 3358:     my @rolechanges;
 3359:     my %disallowed;
 3360:     $r->print('<h3>'.&mt('Modifying Roles').'</h3>');
 3361:     foreach my $key (keys (%env)) {
 3362: 	next if (! $env{$key});
 3363:         next if ($key eq 'form.action');
 3364: 	# Revoke roles
 3365: 	if ($key=~/^form\.rev/) {
 3366: 	    if ($key=~/^form\.rev\:([^\_]+)\_([^\_\.]+)$/) {
 3367: # Revoke standard role
 3368: 		my ($scope,$role) = ($1,$2);
 3369: 		my $result =
 3370: 		    &Apache::lonnet::revokerole($env{'form.ccdomain'},
 3371: 						$env{'form.ccuname'},
 3372: 						$scope,$role,'','',$context);
 3373: 	        $r->print(&mt('Revoking [_1] in [_2]: [_3]',
 3374: 			      $role,$scope,'<b>'.$result.'</b>').'<br />');
 3375: 		if ($role eq 'st') {
 3376: 		    my $result = 
 3377:                         &Apache::lonuserutils::classlist_drop($scope,
 3378:                             $env{'form.ccuname'},$env{'form.ccdomain'},
 3379: 			    $now);
 3380: 		    $r->print($result);
 3381: 		}
 3382:                 if (!grep(/^\Q$role\E$/,@rolechanges)) {
 3383:                     push(@rolechanges,$role);
 3384:                 }
 3385: 	    }
 3386: 	    if ($key=~m{^form\.rev\:([^_]+)_cr\.cr/($match_domain)/($match_username)/(\w+)$}s) {
 3387: # Revoke custom role
 3388: 		$r->print(&mt('Revoking custom role:').
 3389:                       ' '.$4.' by '.$3.':'.$2.' in '.$1.': <b>'.
 3390:                       &Apache::lonnet::revokecustomrole($env{'form.ccdomain'},
 3391: 				  $env{'form.ccuname'},$1,$2,$3,$4,'','',$context).
 3392: 		'</b><br />');
 3393:                 if (!grep(/^cr$/,@rolechanges)) {
 3394:                     push(@rolechanges,'cr');
 3395:                 }
 3396: 	    }
 3397: 	} elsif ($key=~/^form\.del/) {
 3398: 	    if ($key=~/^form\.del\:([^\_]+)\_([^\_\.]+)$/) {
 3399: # Delete standard role
 3400: 		my ($scope,$role) = ($1,$2);
 3401: 		my $result =
 3402: 		    &Apache::lonnet::assignrole($env{'form.ccdomain'},
 3403: 						$env{'form.ccuname'},
 3404: 						$scope,$role,$now,0,1,'',
 3405:                                                 $context);
 3406: 	        $r->print(&mt('Deleting [_1] in [_2]: [_3]',$role,$scope,
 3407: 			      '<b>'.$result.'</b>').'<br />');
 3408: 		if ($role eq 'st') {
 3409: 		    my $result = 
 3410:                         &Apache::lonuserutils::classlist_drop($scope,
 3411:                             $env{'form.ccuname'},$env{'form.ccdomain'},
 3412: 			    $now);
 3413: 		    $r->print($result);
 3414: 		}
 3415:                 if (!grep(/^\Q$role\E$/,@rolechanges)) {
 3416:                     push(@rolechanges,$role);
 3417:                 }
 3418:             }
 3419: 	    if ($key=~m{^form\.del\:([^_]+)_cr\.cr/($match_domain)/($match_username)/(\w+)$}) {
 3420:                 my ($url,$rdom,$rnam,$rolename) = ($1,$2,$3,$4);
 3421: # Delete custom role
 3422:                 $r->print(&mt('Deleting custom role [_1] by [_2] in [_3]',
 3423:                       $rolename,$rnam.':'.$rdom,$url).': <b>'.
 3424:                       &Apache::lonnet::assigncustomrole($env{'form.ccdomain'},
 3425:                          $env{'form.ccuname'},$url,$rdom,$rnam,$rolename,$now,
 3426:                          0,1,$context).'</b><br />');
 3427:                 if (!grep(/^cr$/,@rolechanges)) {
 3428:                     push(@rolechanges,'cr');
 3429:                 }
 3430:             }
 3431: 	} elsif ($key=~/^form\.ren/) {
 3432:             my $udom = $env{'form.ccdomain'};
 3433:             my $uname = $env{'form.ccuname'};
 3434: # Re-enable standard role
 3435: 	    if ($key=~/^form\.ren\:([^\_]+)\_([^\_\.]+)$/) {
 3436:                 my $url = $1;
 3437:                 my $role = $2;
 3438:                 my $logmsg;
 3439:                 my $output;
 3440:                 if ($role eq 'st') {
 3441:                     if ($url =~ m-^/($match_domain)/($match_courseid)/?(\w*)$-) {
 3442:                         my $result = &Apache::loncommon::commit_studentrole(\$logmsg,$udom,$uname,$url,$role,$now,0,$1,$2,$3);
 3443:                         if (($result =~ /^error/) || ($result eq 'not_in_class') || ($result eq 'unknown_course') || ($result eq 'refused')) {
 3444:                             if ($result eq 'refused' && $logmsg) {
 3445:                                 $output = $logmsg;
 3446:                             } else { 
 3447:                                 $output = "Error: $result\n";
 3448:                             }
 3449:                         } else {
 3450:                             $output = &mt('Assigning').' '.$role.' in '.$url.
 3451:                                       &mt('starting').' '.localtime($now).
 3452:                                       ': <br />'.$logmsg.'<br />'.
 3453:                                       &mt('Add to classlist').': <b>ok</b><br />';
 3454:                         }
 3455:                     }
 3456:                 } else {
 3457: 		    my $result=&Apache::lonnet::assignrole($env{'form.ccdomain'},
 3458:                                $env{'form.ccuname'},$url,$role,0,$now,'','',
 3459:                                $context);
 3460: 		    $output = &mt('Re-enabling [_1] in [_2]: [_3]',
 3461: 			      $role,$url,'<b>'.$result.'</b>').'<br />';
 3462: 		}
 3463:                 $r->print($output);
 3464:                 if (!grep(/^\Q$role\E$/,@rolechanges)) {
 3465:                     push(@rolechanges,$role);
 3466:                 }
 3467: 	    }
 3468: # Re-enable custom role
 3469: 	    if ($key=~m{^form\.ren\:([^_]+)_cr\.cr/($match_domain)/($match_username)/(\w+)$}) {
 3470:                 my ($url,$rdom,$rnam,$rolename) = ($1,$2,$3,$4);
 3471:                 my $result = &Apache::lonnet::assigncustomrole(
 3472:                                $env{'form.ccdomain'}, $env{'form.ccuname'},
 3473:                                $url,$rdom,$rnam,$rolename,0,$now,undef,$context);
 3474:                 $r->print(&mt('Re-enabling custom role [_1] by [_2] in [_3]: [_4]',
 3475:                           $rolename,$rnam.':'.$rdom,$url,'<b>'.$result.'</b>').'<br />');
 3476:                 if (!grep(/^cr$/,@rolechanges)) {
 3477:                     push(@rolechanges,'cr');
 3478:                 }
 3479:             }
 3480: 	} elsif ($key=~/^form\.act/) {
 3481:             my $udom = $env{'form.ccdomain'};
 3482:             my $uname = $env{'form.ccuname'};
 3483: 	    if ($key=~/^form\.act\_($match_domain)\_($match_courseid)\_cr_cr_($match_domain)_($match_username)_([^\_]+)$/) {
 3484:                 # Activate a custom role
 3485: 		my ($one,$two,$three,$four,$five)=($1,$2,$3,$4,$5);
 3486: 		my $url='/'.$one.'/'.$two;
 3487: 		my $full=$one.'_'.$two.'_cr_cr_'.$three.'_'.$four.'_'.$five;
 3488: 
 3489:                 my $start = ( $env{'form.start_'.$full} ?
 3490:                               $env{'form.start_'.$full} :
 3491:                               $now );
 3492:                 my $end   = ( $env{'form.end_'.$full} ?
 3493:                               $env{'form.end_'.$full} :
 3494:                               0 );
 3495:                                                                                      
 3496:                 # split multiple sections
 3497:                 my %sections = ();
 3498:                 my $num_sections = &build_roles($env{'form.sec_'.$full},\%sections,$5);
 3499:                 if ($num_sections == 0) {
 3500:                     $r->print(&Apache::loncommon::commit_customrole($udom,$uname,$url,$three,$four,$five,$start,$end,$context));
 3501:                 } else {
 3502: 		    my %curr_groups =
 3503: 			&Apache::longroup::coursegroups($one,$two);
 3504:                     foreach my $sec (sort {$a cmp $b} keys %sections) {
 3505:                         if (($sec eq 'none') || ($sec eq 'all') || 
 3506:                             exists($curr_groups{$sec})) {
 3507:                             $disallowed{$sec} = $url;
 3508:                             next;
 3509:                         }
 3510:                         my $securl = $url.'/'.$sec;
 3511: 		        $r->print(&Apache::loncommon::commit_customrole($udom,$uname,$securl,$three,$four,$five,$start,$end,$context));
 3512:                     }
 3513:                 }
 3514:                 if (!grep(/^cr$/,@rolechanges)) {
 3515:                     push(@rolechanges,'cr');
 3516:                 }
 3517: 	    } elsif ($key=~/^form\.act\_($match_domain)\_($match_name)\_([^\_]+)$/) {
 3518: 		# Activate roles for sections with 3 id numbers
 3519: 		# set start, end times, and the url for the class
 3520: 		my ($one,$two,$three)=($1,$2,$3);
 3521: 		my $start = ( $env{'form.start_'.$one.'_'.$two.'_'.$three} ? 
 3522: 			      $env{'form.start_'.$one.'_'.$two.'_'.$three} : 
 3523: 			      $now );
 3524: 		my $end   = ( $env{'form.end_'.$one.'_'.$two.'_'.$three} ? 
 3525: 			      $env{'form.end_'.$one.'_'.$two.'_'.$three} :
 3526: 			      0 );
 3527: 		my $url='/'.$one.'/'.$two;
 3528:                 my $type = 'three';
 3529:                 # split multiple sections
 3530:                 my %sections = ();
 3531:                 my $num_sections = &build_roles($env{'form.sec_'.$one.'_'.$two.'_'.$three},\%sections,$three);
 3532:                 if ($num_sections == 0) {
 3533:                     $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$three,$start,$end,$one,$two,'',$context));
 3534:                 } else {
 3535:                     my %curr_groups = 
 3536: 			&Apache::longroup::coursegroups($one,$two);
 3537:                     my $emptysec = 0;
 3538:                     foreach my $sec (sort {$a cmp $b} keys %sections) {
 3539:                         $sec =~ s/\W//g;
 3540:                         if ($sec ne '') {
 3541:                             if (($sec eq 'none') || ($sec eq 'all') || 
 3542:                                 exists($curr_groups{$sec})) {
 3543:                                 $disallowed{$sec} = $url;
 3544:                                 next;
 3545:                             }
 3546:                             my $securl = $url.'/'.$sec;
 3547:                             $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$securl,$three,$start,$end,$one,$two,$sec,$context));
 3548:                         } else {
 3549:                             $emptysec = 1;
 3550:                         }
 3551:                     }
 3552:                     if ($emptysec) {
 3553:                         $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$three,$start,$end,$one,$two,'',$context));
 3554:                     }
 3555:                 }
 3556:                 if (!grep(/^\Q$three\E$/,@rolechanges)) {
 3557:                     push(@rolechanges,$three);
 3558:                 }
 3559: 	    } elsif ($key=~/^form\.act\_([^\_]+)\_([^\_]+)$/) {
 3560: 		# Activate roles for sections with two id numbers
 3561: 		# set start, end times, and the url for the class
 3562: 		my $start = ( $env{'form.start_'.$1.'_'.$2} ? 
 3563: 			      $env{'form.start_'.$1.'_'.$2} : 
 3564: 			      $now );
 3565: 		my $end   = ( $env{'form.end_'.$1.'_'.$2} ? 
 3566: 			      $env{'form.end_'.$1.'_'.$2} :
 3567: 			      0 );
 3568:                 my $one = $1;
 3569:                 my $two = $2;
 3570: 		my $url='/'.$one.'/';
 3571:                 # split multiple sections
 3572:                 my %sections = ();
 3573:                 my $num_sections = &build_roles($env{'form.sec_'.$one.'_'.$two},\%sections,$two);
 3574:                 if ($num_sections == 0) {
 3575:                     $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$two,$start,$end,$one,undef,'',$context));
 3576:                 } else {
 3577:                     my $emptysec = 0;
 3578:                     foreach my $sec (sort {$a cmp $b} keys %sections) {
 3579:                         if ($sec ne '') {
 3580:                             my $securl = $url.'/'.$sec;
 3581:                             $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$securl,$two,$start,$end,$one,undef,$sec,$context));
 3582:                         } else {
 3583:                             $emptysec = 1;
 3584:                         }
 3585:                     }
 3586:                     if ($emptysec) {
 3587:                         $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$two,$start,$end,$one,undef,'',$context));
 3588:                     }
 3589:                 }
 3590:                 if (!grep(/^\Q$two\E$/,@rolechanges)) {
 3591:                     push(@rolechanges,$two);
 3592:                 }
 3593: 	    } else {
 3594: 		$r->print('<p><span class="LC_error">'.&mt('ERROR').': '.&mt('Unknown command').' <tt>'.$key.'</tt></span></p><br />');
 3595:             }
 3596:             foreach my $key (sort(keys(%disallowed))) {
 3597:                 $r->print('<p class="LC_warning">');
 3598:                 if (($key eq 'none') || ($key eq 'all')) {  
 3599:                     $r->print(&mt('[_1] may not be used as the name for a section, as it is a reserved word.','<tt>'.$key.'</tt>'));
 3600:                 } else {
 3601:                     $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>'));
 3602:                 }
 3603:                 $r->print('</p><p>'
 3604:                          .&mt('Please [_1]go back[_2] and choose a different section name.'
 3605:                              ,'<a href="javascript:history.go(-1)'
 3606:                              ,'</a>')
 3607:                          .'</p><br />'
 3608:                 );
 3609:             }
 3610: 	}
 3611:     } # End of foreach (keys(%env))
 3612: # Flush the course logs so reverse user roles immediately updated
 3613:     $r->register_cleanup(\&Apache::lonnet::flushcourselogs);
 3614:     if (@rolechanges == 0) {
 3615:         $r->print(&mt('No roles to modify'));
 3616:     }
 3617:     return @rolechanges;
 3618: }
 3619: 
 3620: sub enroll_single_student {
 3621:     my ($r,$uhome,$amode,$genpwd,$now,$newuser,$context,$crstype) = @_;
 3622:     $r->print('<h3>');
 3623:     if ($crstype eq 'Community') {
 3624:         $r->print(&mt('Enrolling Member'));
 3625:     } else {
 3626:         $r->print(&mt('Enrolling Student'));
 3627:     }
 3628:     $r->print('</h3>');
 3629: 
 3630:     # Remove non alphanumeric values from section
 3631:     $env{'form.sections'}=~s/\W//g;
 3632: 
 3633:     # Clean out any old student roles the user has in this class.
 3634:     &Apache::lonuserutils::modifystudent($env{'form.ccdomain'},
 3635:          $env{'form.ccuname'},$env{'request.course.id'},undef,$uhome);
 3636:     my ($startdate,$enddate) = &Apache::lonuserutils::get_dates_from_form();
 3637:     my $enroll_result =
 3638:         &Apache::lonnet::modify_student_enrollment($env{'form.ccdomain'},
 3639:             $env{'form.ccuname'},$env{'form.cid'},$env{'form.cfirstname'},
 3640:             $env{'form.cmiddlename'},$env{'form.clastname'},
 3641:             $env{'form.generation'},$env{'form.sections'},$enddate,
 3642:             $startdate,'manual',undef,$env{'request.course.id'},'',$context);
 3643:     if ($enroll_result =~ /^ok/) {
 3644:         $r->print(&mt('<b>[_1]</b> enrolled',$env{'form.ccuname'}.':'.$env{'form.ccdomain'}));
 3645:         if ($env{'form.sections'} ne '') {
 3646:             $r->print(' '.&mt('in section [_1]',$env{'form.sections'}));
 3647:         }
 3648:         my ($showstart,$showend);
 3649:         if ($startdate <= $now) {
 3650:             $showstart = &mt('Access starts immediately');
 3651:         } else {
 3652:             $showstart = &mt('Access starts: ').&Apache::lonlocal::locallocaltime($startdate);
 3653:         }
 3654:         if ($enddate == 0) {
 3655:             $showend = &mt('ends: no ending date');
 3656:         } else {
 3657:             $showend = &mt('ends: ').&Apache::lonlocal::locallocaltime($enddate);
 3658:         }
 3659:         $r->print('.<br />'.$showstart.'; '.$showend);
 3660:         if ($startdate <= $now && !$newuser) {
 3661:             $r->print('<p> ');
 3662:             if ($crstype eq 'Community') {
 3663:                 $r->print(&mt('If the member is currently logged-in to LON-CAPA, the new role will be available when the member next logs in.'));
 3664:             } else {
 3665:                 $r->print(&mt('If the student is currently logged-in to LON-CAPA, the new role will be available when the student next logs in.'));
 3666:            }
 3667:            $r->print('</p>');
 3668:         }
 3669:     } else {
 3670:         $r->print(&mt('unable to enroll').": ".$enroll_result);
 3671:     }
 3672:     return;
 3673: }
 3674: 
 3675: sub get_defaultquota_text {
 3676:     my ($settingstatus) = @_;
 3677:     my $defquotatext; 
 3678:     if ($settingstatus eq '') {
 3679:         $defquotatext = &mt('(default)');
 3680:     } else {
 3681:         my ($usertypes,$order) =
 3682:             &Apache::lonnet::retrieve_inst_usertypes($env{'form.ccdomain'});
 3683:         if ($usertypes->{$settingstatus} eq '') {
 3684:             $defquotatext = &mt('(default)');
 3685:         } else {
 3686:             $defquotatext = &mt('(default for [_1])',$usertypes->{$settingstatus});
 3687:         }
 3688:     }
 3689:     return $defquotatext;
 3690: }
 3691: 
 3692: sub update_result_form {
 3693:     my ($uhome) = @_;
 3694:     my $outcome = 
 3695:     '<form name="userupdate" method="post" />'."\n";
 3696:     foreach my $item ('srchby','srchin','srchtype','srchterm','srchdomain','ccuname','ccdomain') {
 3697:         $outcome .= '<input type="hidden" name="'.$item.'" value="'.$env{'form.'.$item}.'" />'."\n";
 3698:     }
 3699:     if ($env{'form.origname'} ne '') {
 3700:         $outcome .= '<input type="hidden" name="origname" value="'.$env{'form.origname'}.'" />'."\n";
 3701:     }
 3702:     foreach my $item ('sortby','seluname','seludom') {
 3703:         if (exists($env{'form.'.$item})) {
 3704:             $outcome .= '<input type="hidden" name="'.$item.'" value="'.$env{'form.'.$item}.'" />'."\n";
 3705:         }
 3706:     }
 3707:     if ($uhome eq 'no_host') {
 3708:         $outcome .= '<input type="hidden" name="forcenewuser" value="1" />'."\n";
 3709:     }
 3710:     $outcome .= '<input type="hidden" name="phase" value="" />'."\n".
 3711:                 '<input type ="hidden" name="currstate" value="" />'."\n".
 3712:                 '<input type ="hidden" name="action" value="'.$env{'form.action'}.'" />'."\n".
 3713:                 '</form>';
 3714:     return $outcome;
 3715: }
 3716: 
 3717: sub quota_admin {
 3718:     my ($setquota,$changeHash) = @_;
 3719:     my $quotachanged;
 3720:     if (&Apache::lonnet::allowed('mpq',$env{'form.ccdomain'})) {
 3721:         # Current user has quota modification privileges
 3722:         if (ref($changeHash) eq 'HASH') {
 3723:             $quotachanged = 1;
 3724:             $changeHash->{'portfolioquota'} = $setquota;
 3725:         }
 3726:     }
 3727:     return $quotachanged;
 3728: }
 3729: 
 3730: sub tool_admin {
 3731:     my ($tool,$settool,$changeHash,$context) = @_;
 3732:     my $canchange = 0; 
 3733:     if ($context eq 'requestcourses') {
 3734:         if (&Apache::lonnet::allowed('ccc',$env{'form.ccdomain'})) {
 3735:             $canchange = 1;
 3736:         }
 3737:     } elsif ($context eq 'reqcrsotherdom') {
 3738:         if (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) {
 3739:             $canchange = 1;
 3740:         }
 3741:     } elsif ($context eq 'requestauthor') {
 3742:         if (&Apache::lonnet::allowed('cau',$env{'request.role.domain'})) {
 3743:             $canchange = 1;
 3744:         }
 3745:     } elsif (&Apache::lonnet::allowed('mut',$env{'form.ccdomain'})) {
 3746:         # Current user has quota modification privileges
 3747:         $canchange = 1;
 3748:     }
 3749:     my $toolchanged;
 3750:     if ($canchange) {
 3751:         if (ref($changeHash) eq 'HASH') {
 3752:             $toolchanged = 1;
 3753:             if ($tool eq 'requestauthor') {
 3754:                 $changeHash->{$context} = $settool;
 3755:             } else {
 3756:                 $changeHash->{$context.'.'.$tool} = $settool;
 3757:             }
 3758:         }
 3759:     }
 3760:     return $toolchanged;
 3761: }
 3762: 
 3763: sub build_roles {
 3764:     my ($sectionstr,$sections,$role) = @_;
 3765:     my $num_sections = 0;
 3766:     if ($sectionstr=~ /,/) {
 3767:         my @secnums = split/,/,$sectionstr;
 3768:         if ($role eq 'st') {
 3769:             $secnums[0] =~ s/\W//g;
 3770:             $$sections{$secnums[0]} = 1;
 3771:             $num_sections = 1;
 3772:         } else {
 3773:             foreach my $sec (@secnums) {
 3774:                 $sec =~ ~s/\W//g;
 3775:                 if (!($sec eq "")) {
 3776:                     if (exists($$sections{$sec})) {
 3777:                         $$sections{$sec} ++;
 3778:                     } else {
 3779:                         $$sections{$sec} = 1;
 3780:                         $num_sections ++;
 3781:                     }
 3782:                 }
 3783:             }
 3784:         }
 3785:     } else {
 3786:         $sectionstr=~s/\W//g;
 3787:         unless ($sectionstr eq '') {
 3788:             $$sections{$sectionstr} = 1;
 3789:             $num_sections ++;
 3790:         }
 3791:     }
 3792: 
 3793:     return $num_sections;
 3794: }
 3795: 
 3796: # ========================================================== Custom Role Editor
 3797: 
 3798: sub custom_role_editor {
 3799:     my ($r,$brcrum) = @_;
 3800:     my $action = $env{'form.customroleaction'};
 3801:     my $rolename; 
 3802:     if ($action eq 'new') {
 3803:         $rolename=$env{'form.newrolename'};
 3804:     } else {
 3805:         $rolename=$env{'form.rolename'};
 3806:     }
 3807: 
 3808:     my ($crstype,$context);
 3809:     if ($env{'request.course.id'}) {
 3810:         $crstype = &Apache::loncommon::course_type();
 3811:         $context = 'course';
 3812:     } else {
 3813:         $context = 'domain';
 3814:         $crstype = $env{'form.templatecrstype'};
 3815:     }
 3816: 
 3817:     $rolename=~s/[^A-Za-z0-9]//gs;
 3818:     if (!$rolename || $env{'form.phase'} eq 'pickrole') {
 3819: 	&print_username_entry_form($r,undef,undef,undef,undef,$crstype,$brcrum);
 3820:         return;
 3821:     }
 3822: 
 3823: # ------------------------------------------------------- What can be assigned?
 3824:     my %full=();
 3825:     my %courselevel=();
 3826:     my %courselevelcurrent=();
 3827:     my $syspriv='';
 3828:     my $dompriv='';
 3829:     my $coursepriv='';
 3830:     my $body_top;
 3831:     my ($rdummy,$roledef)=
 3832: 			 &Apache::lonnet::get('roles',["rolesdef_$rolename"]);
 3833: # ------------------------------------------------------- Does this role exist?
 3834:     $body_top .= '<h2>';
 3835:     if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 3836: 	$body_top .= &mt('Existing Role').' "';
 3837: # ------------------------------------------------- Get current role privileges
 3838: 	($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 3839:         if ($crstype eq 'Community') {
 3840:             $syspriv =~ s/bre\&S//;   
 3841:         }
 3842:     } else {
 3843: 	$body_top .= &mt('New Role').' "';
 3844: 	$roledef='';
 3845:     }
 3846:     $body_top .= $rolename.'"</h2>';
 3847:     foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
 3848: 	my ($priv,$restrict)=split(/\&/,$item);
 3849:         if (!$restrict) { $restrict='F'; }
 3850:         $courselevel{$priv}=$restrict;
 3851:         if ($coursepriv=~/\:$priv/) {
 3852: 	    $courselevelcurrent{$priv}=1;
 3853: 	}
 3854: 	$full{$priv}=1;
 3855:     }
 3856:     my %domainlevel=();
 3857:     my %domainlevelcurrent=();
 3858:     foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:d'})) {
 3859: 	my ($priv,$restrict)=split(/\&/,$item);
 3860:         if (!$restrict) { $restrict='F'; }
 3861:         $domainlevel{$priv}=$restrict;
 3862:         if ($dompriv=~/\:$priv/) {
 3863: 	    $domainlevelcurrent{$priv}=1;
 3864: 	}
 3865: 	$full{$priv}=1;
 3866:     }
 3867:     my %systemlevel=();
 3868:     my %systemlevelcurrent=();
 3869:     foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:s'})) {
 3870: 	my ($priv,$restrict)=split(/\&/,$item);
 3871:         if (!$restrict) { $restrict='F'; }
 3872:         $systemlevel{$priv}=$restrict;
 3873:         if ($syspriv=~/\:$priv/) {
 3874: 	    $systemlevelcurrent{$priv}=1;
 3875: 	}
 3876: 	$full{$priv}=1;
 3877:     }
 3878:     my ($jsback,$elements) = &crumb_utilities();
 3879:     my $button_code = "\n";
 3880:     my $head_script = "\n";
 3881:     $head_script .= '<script type="text/javascript">'."\n"
 3882:                    .'// <![CDATA['."\n";
 3883:     my @template_roles = ("in","ta","ep");
 3884:     if ($context eq 'domain') {
 3885:         push(@template_roles,"ad");
 3886:     }
 3887:     push(@template_roles,"st");
 3888:     if ($crstype eq 'Community') {
 3889:         unshift(@template_roles,'co');
 3890:     } else {
 3891:         unshift(@template_roles,'cc');
 3892:     }
 3893:     foreach my $role (@template_roles) {
 3894:         $head_script .= &make_script_template($role,$crstype);
 3895:         $button_code .= &make_button_code($role,$crstype).' ';
 3896:     }
 3897:     my $context_code;
 3898:     if ($context eq 'domain') {
 3899:         my $checkedCommunity = '';
 3900:         my $checkedCourse = ' checked="checked"';
 3901:         if ($env{'form.templatecrstype'} eq 'Community') {
 3902:             $checkedCommunity = $checkedCourse;
 3903:             $checkedCourse = '';
 3904:         }
 3905:         $context_code = '<label>'.
 3906:                         '<input type="radio" name="templatecrstype" value="Course"'.$checkedCourse.' onclick="this.form.submit();">'.
 3907:                         &mt('Course').
 3908:                         '</label>'.('&nbsp;' x2).
 3909:                         '<label>'.
 3910:                         '<input type="radio" name="templatecrstype" value="Community"'.$checkedCommunity.' onclick="this.form.submit();">'.
 3911:                         &mt('Community').
 3912:                         '</label>'.
 3913:                         '</fieldset>'.
 3914:                         '<input type="hidden" name="customroleaction" value="'.
 3915:                         $action.'" />';
 3916:         if ($env{'form.customroleaction'} eq 'new') {
 3917:             $context_code .= '<input type="hidden" name="newrolename" value="'.
 3918:                              $rolename.'" />';
 3919:         } else {
 3920:             $context_code .= '<input type="hidden" name="rolename" value="'.
 3921:                              $rolename.'" />';
 3922:         }
 3923:         $context_code .= '<input type="hidden" name="action" value="custom" />'.
 3924:                          '<input type="hidden" name="phase" value="selected_custom_edit" />';
 3925:     }
 3926: 
 3927:     $head_script .= "\n".$jsback."\n"
 3928:                    .'// ]]>'."\n"
 3929:                    .'</script>'."\n";
 3930:     push (@{$brcrum},
 3931:               {href => "javascript:backPage(document.form1,'pickrole','')",
 3932:                text => "Pick custom role",
 3933:                faq  => 282,bug=>'Instructor Interface',},
 3934:               {href => "javascript:backPage(document.form1,'','')",
 3935:                text => "Edit custom role",
 3936:                faq  => 282,
 3937:                bug  => 'Instructor Interface',
 3938:                help => 'Course_Editing_Custom_Roles'}
 3939:               );
 3940:     my $args = { bread_crumbs          => $brcrum,
 3941:                  bread_crumbs_component => 'User Management'};
 3942:  
 3943:     $r->print(&Apache::loncommon::start_page('Custom Role Editor',
 3944:                                              $head_script,$args).
 3945:               $body_top);
 3946:     my %lt=&Apache::lonlocal::texthash(
 3947: 		    'prv'  => "Privilege",
 3948: 		    'crl'  => "Course Level",
 3949:                     'dml'  => "Domain Level",
 3950:                     'ssl'  => "System Level");
 3951: 
 3952:     $r->print('<div class="LC_left_float">'
 3953:              .'<form action=""><fieldset>'
 3954:              .'<legend>'.&mt('Select a Template').'</legend>'
 3955:              .$button_code
 3956:              .'</fieldset></form></div>');
 3957:     if ($context_code) {
 3958:         $r->print('<div class="LC_left_float">'
 3959:                  .'<form action="/adm/createuser" method="post"><fieldset>'
 3960:                  .'<legend>'.&mt('Context').'</legend>'
 3961:                  .$context_code
 3962:                  .'</form>'
 3963:                  .'</div>'
 3964:         );
 3965:     }
 3966:     $r->print('<br clear="all" />');
 3967: 
 3968:     $r->print(<<ENDCCF);
 3969: <form name="form1" method="post">
 3970: <input type="hidden" name="phase" value="set_custom_roles" />
 3971: <input type="hidden" name="rolename" value="$rolename" />
 3972: ENDCCF
 3973:     $r->print(&Apache::loncommon::start_data_table().
 3974:               &Apache::loncommon::start_data_table_header_row(). 
 3975: '<th>'.$lt{'prv'}.'</th><th>'.$lt{'crl'}.'</th><th>'.$lt{'dml'}.
 3976: '</th><th>'.$lt{'ssl'}.'</th>'.
 3977:               &Apache::loncommon::end_data_table_header_row());
 3978:     foreach my $priv (sort(keys(%full))) {
 3979:         my $privtext = &Apache::lonnet::plaintext($priv,$crstype);
 3980:         $r->print(&Apache::loncommon::start_data_table_row().
 3981: 	          '<td>'.$privtext.'</td><td>'.
 3982:     ($courselevel{$priv}?'<input type="checkbox" name="'.$priv.'_c"'.
 3983:     ($courselevelcurrent{$priv}?' checked="checked"':'').' />':'&nbsp;').
 3984:     '</td><td>'.
 3985:     ($domainlevel{$priv}?'<input type="checkbox" name="'.$priv.'_d"'.
 3986:     ($domainlevelcurrent{$priv}?' checked="checked"':'').' />':'&nbsp;').
 3987:     '</td><td>');
 3988:         if ($priv eq 'bre' && $crstype eq 'Community') {
 3989:             $r->print('&nbsp;');  
 3990:         } else {
 3991:             $r->print($systemlevel{$priv}?'<input type="checkbox" name="'.$priv.'_s"'.
 3992:                       ($systemlevelcurrent{$priv}?' checked="checked"':'').' />':'&nbsp;');
 3993:         }
 3994:         $r->print('</td>'.
 3995:                   &Apache::loncommon::end_data_table_row());
 3996:     }
 3997:     $r->print(&Apache::loncommon::end_data_table().
 3998:    '<input type="hidden" name="action" value="'.$env{'form.action'}.'" />'.
 3999:    '<input type="hidden" name="startrolename" value="'.$env{'form.rolename'}.
 4000:    '" />'."\n".'<input type="hidden" name="currstate" value="" />'."\n".   
 4001:    '<input type="reset" value="'.&mt("Reset").'" />'."\n".
 4002:    '<input type="submit" value="'.&mt('Save').'" /></form>');
 4003: }
 4004: # --------------------------------------------------------
 4005: sub make_script_template {
 4006:     my ($role,$crstype) = @_;
 4007:     my %full_c=();
 4008:     my %full_d=();
 4009:     my %full_s=();
 4010:     my $return_script;
 4011:     foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
 4012:         my ($priv,$restrict)=split(/\&/,$item);
 4013:         $full_c{$priv}=1;
 4014:     }
 4015:     foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:d'})) {
 4016:         my ($priv,$restrict)=split(/\&/,$item);
 4017:         $full_d{$priv}=1;
 4018:     }
 4019:     foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:s'})) {
 4020:         next if (($crstype eq 'Community') && ($item eq 'bre&S'));
 4021:         my ($priv,$restrict)=split(/\&/,$item);
 4022:         $full_s{$priv}=1;
 4023:     }
 4024:     $return_script .= 'function set_'.$role.'() {'."\n";
 4025:     my @temp = split(/:/,$Apache::lonnet::pr{$role.':c'});
 4026:     my %role_c;
 4027:     foreach my $priv (@temp) {
 4028:         my ($priv_item, $dummy) = split(/\&/,$priv);
 4029:         $role_c{$priv_item} = 1;
 4030:     }
 4031:     my %role_d;
 4032:     @temp = split(/:/,$Apache::lonnet::pr{$role.':d'});
 4033:     foreach my $priv(@temp) {
 4034:         my ($priv_item, $dummy) = split(/\&/,$priv);
 4035:         $role_d{$priv_item} = 1;
 4036:     }
 4037:     my %role_s;
 4038:     @temp = split(/:/,$Apache::lonnet::pr{$role.':s'});
 4039:     foreach my $priv(@temp) {
 4040:         my ($priv_item, $dummy) = split(/\&/,$priv);
 4041:         $role_s{$priv_item} = 1;
 4042:     }
 4043:     foreach my $priv_item (keys(%full_c)) {
 4044:         my ($priv, $dummy) = split(/\&/,$priv_item);
 4045:         if ((exists($role_c{$priv})) || (exists($role_d{$priv})) || 
 4046:             (exists($role_s{$priv}))) {
 4047:             $return_script .= "document.form1.$priv"."_c.checked = true;\n";
 4048:         } else {
 4049:             $return_script .= "document.form1.$priv"."_c.checked = false;\n";
 4050:         }
 4051:     }
 4052:     foreach my $priv_item (keys(%full_d)) {
 4053:         my ($priv, $dummy) = split(/\&/,$priv_item);
 4054:         if ((exists($role_d{$priv})) || (exists($role_s{$priv}))) {
 4055:             $return_script .= "document.form1.$priv"."_d.checked = true;\n";
 4056:         } else {
 4057:             $return_script .= "document.form1.$priv"."_d.checked = false;\n";
 4058:         }
 4059:     }
 4060:     foreach my $priv_item (keys(%full_s)) {
 4061:         my ($priv, $dummy) = split(/\&/,$priv_item);
 4062:         if (exists($role_s{$priv})) {
 4063:             $return_script .= "document.form1.$priv"."_s.checked = true;\n";
 4064:         } else {
 4065:             $return_script .= "document.form1.$priv"."_s.checked = false;\n";
 4066:         }
 4067:     }
 4068:     $return_script .= '}'."\n";
 4069:     return ($return_script);
 4070: }
 4071: # ----------------------------------------------------------
 4072: sub make_button_code {
 4073:     my ($role,$crstype) = @_;
 4074:     my $label = &Apache::lonnet::plaintext($role,$crstype);
 4075:     my $button_code = '<input type="button" onclick="set_'.$role.'()" value="'.$label.'" />';
 4076:     return ($button_code);
 4077: }
 4078: # ---------------------------------------------------------- Call to definerole
 4079: sub set_custom_role {
 4080:     my ($r,$context,$brcrum) = @_;
 4081:     my $rolename=$env{'form.rolename'};
 4082:     $rolename=~s/[^A-Za-z0-9]//gs;
 4083:     if (!$rolename) {
 4084: 	&custom_role_editor($r,$brcrum);
 4085:         return;
 4086:     }
 4087:     my ($jsback,$elements) = &crumb_utilities();
 4088:     my $jscript = '<script type="text/javascript">'
 4089:                  .'// <![CDATA['."\n"
 4090:                  .$jsback."\n"
 4091:                  .'// ]]>'."\n"
 4092:                  .'</script>'."\n";
 4093:     push(@{$brcrum},
 4094:         {href => "javascript:backPage(document.customresult,'pickrole','')",
 4095:          text => "Pick custom role",
 4096:          faq  => 282,
 4097:          bug  => 'Instructor Interface',},
 4098:         {href => "javascript:backPage(document.customresult,'selected_custom_edit','')",
 4099:          text => "Edit custom role",
 4100:          faq  => 282,
 4101:          bug  => 'Instructor Interface',},
 4102:         {href => "javascript:backPage(document.customresult,'set_custom_roles','')",
 4103:          text => "Result",
 4104:          faq  => 282,
 4105:          bug  => 'Instructor Interface',
 4106:          help => 'Course_Editing_Custom_Roles'},
 4107:         );
 4108:     my $args = { bread_crumbs           => $brcrum,
 4109:                  bread_crumbs_component => 'User Management'}; 
 4110:     $r->print(&Apache::loncommon::start_page('Save Custom Role',$jscript,$args));
 4111: 
 4112:     my ($rdummy,$roledef)=
 4113: 	&Apache::lonnet::get('roles',["rolesdef_$rolename"]);
 4114: 
 4115: # ------------------------------------------------------- Does this role exist?
 4116:     $r->print('<h3>');
 4117:     if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 4118: 	$r->print(&mt('Existing Role').' "');
 4119:     } else {
 4120: 	$r->print(&mt('New Role').' "');
 4121: 	$roledef='';
 4122:     }
 4123:     $r->print($rolename.'"</h3>');
 4124: # ------------------------------------------------------- What can be assigned?
 4125:     my $sysrole='';
 4126:     my $domrole='';
 4127:     my $courole='';
 4128: 
 4129:     foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
 4130: 	my ($priv,$restrict)=split(/\&/,$item);
 4131:         if (!$restrict) { $restrict=''; }
 4132:         if ($env{'form.'.$priv.'_c'}) {
 4133: 	    $courole.=':'.$item;
 4134: 	}
 4135:     }
 4136: 
 4137:     foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:d'})) {
 4138: 	my ($priv,$restrict)=split(/\&/,$item);
 4139:         if (!$restrict) { $restrict=''; }
 4140:         if ($env{'form.'.$priv.'_d'}) {
 4141: 	    $domrole.=':'.$item;
 4142: 	}
 4143:     }
 4144: 
 4145:     foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:s'})) {
 4146: 	my ($priv,$restrict)=split(/\&/,$item);
 4147:         if (!$restrict) { $restrict=''; }
 4148:         if ($env{'form.'.$priv.'_s'}) {
 4149: 	    $sysrole.=':'.$item;
 4150: 	}
 4151:     }
 4152:     $r->print('<br />Defining Role: '.
 4153: 	   &Apache::lonnet::definerole($rolename,$sysrole,$domrole,$courole));
 4154:     if ($env{'request.course.id'}) {
 4155:         my $url='/'.$env{'request.course.id'};
 4156:         $url=~s/\_/\//g;
 4157: 	$r->print('<br />'.&mt('Assigning Role to Self').': '.
 4158: 	      &Apache::lonnet::assigncustomrole($env{'user.domain'},
 4159: 						$env{'user.name'},
 4160: 						$url,
 4161: 						$env{'user.domain'},
 4162: 						$env{'user.name'},
 4163: 						$rolename,undef,undef,undef,$context));
 4164:     }
 4165:     $r->print('<p><a href="javascript:backPage(document.customresult,'."'pickrole'".')">'.&mt('Create or edit another custom role').'</a></p><form name="customresult" method="post">');
 4166:     $r->print(&Apache::lonhtmlcommon::echo_form_input([]).'</form>');
 4167: }
 4168: 
 4169: # ================================================================ Main Handler
 4170: sub handler {
 4171:     my $r = shift;
 4172:     if ($r->header_only) {
 4173:        &Apache::loncommon::content_type($r,'text/html');
 4174:        $r->send_http_header;
 4175:        return OK;
 4176:     }
 4177:     my ($context,$crstype);
 4178:     if ($env{'request.course.id'}) {
 4179:         $context = 'course';
 4180:         $crstype = &Apache::loncommon::course_type();
 4181:     } elsif ($env{'request.role'} =~ /^au\./) {
 4182:         $context = 'author';
 4183:     } else {
 4184:         $context = 'domain';
 4185:     }
 4186:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 4187:         ['action','state','callingform','roletype','showrole','bulkaction','popup','phase',
 4188:          'username','domain','srchterm','srchdomain','srchin','srchby','srchtype']);
 4189:     &Apache::lonhtmlcommon::clear_breadcrumbs();
 4190:     my $args;
 4191:     my $brcrum = [];
 4192:     my $bread_crumbs_component = 'User Management';
 4193:     if ($env{'form.action'} ne 'dateselect') {
 4194:         $brcrum = [{href=>"/adm/createuser",
 4195:                     text=>"User Management",
 4196:                     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'}
 4197:                   ];
 4198:     }
 4199:     #SD Following files not added to help, because the corresponding .tex-files seem to
 4200:     #be missing: Course_Approve_Selfenroll,Course_User_Logs,
 4201:     my ($permission,$allowed) = 
 4202:         &Apache::lonuserutils::get_permission($context,$crstype);
 4203:     if (!$allowed) {
 4204:         if ($context eq 'course') {
 4205:             $r->internal_redirect('/adm/viewclasslist');
 4206:             return OK;
 4207:         }
 4208:         $env{'user.error.msg'}=
 4209:             "/adm/createuser:cst:0:0:Cannot create/modify user data ".
 4210:                                  "or view user status.";
 4211:         return HTTP_NOT_ACCEPTABLE;
 4212:     }
 4213: 
 4214:     &Apache::loncommon::content_type($r,'text/html');
 4215:     $r->send_http_header;
 4216: 
 4217:     # Main switch on form.action and form.state, as appropriate
 4218:     if (! exists($env{'form.action'})) {
 4219:         $args = {bread_crumbs => $brcrum,
 4220:                  bread_crumbs_component => $bread_crumbs_component}; 
 4221:         $r->print(&header(undef,$args));
 4222:         $r->print(&print_main_menu($permission,$context,$crstype));
 4223:     } elsif ($env{'form.action'} eq 'upload' && $permission->{'cusr'}) {
 4224:         push(@{$brcrum},
 4225:               { href => '/adm/createuser?action=upload&state=',
 4226:                 text => 'Upload Users List',
 4227:                 help => 'Course_Create_Class_List',
 4228:               });
 4229:         $bread_crumbs_component = 'Upload Users List';
 4230:         $args = {bread_crumbs           => $brcrum,
 4231:                  bread_crumbs_component => $bread_crumbs_component};
 4232:         $r->print(&header(undef,$args));
 4233:         $r->print('<form name="studentform" method="post" '.
 4234:                   'enctype="multipart/form-data" '.
 4235:                   ' action="/adm/createuser">'."\n");
 4236:         if (! exists($env{'form.state'})) {
 4237:             &Apache::lonuserutils::print_first_users_upload_form($r,$context);
 4238:         } elsif ($env{'form.state'} eq 'got_file') {
 4239:             &Apache::lonuserutils::print_upload_manager_form($r,$context,
 4240:                                                              $permission,$crstype);
 4241:         } elsif ($env{'form.state'} eq 'enrolling') {
 4242:             if ($env{'form.datatoken'}) {
 4243:                 &Apache::lonuserutils::upfile_drop_add($r,$context,$permission);
 4244:             }
 4245:         } else {
 4246:             &Apache::lonuserutils::print_first_users_upload_form($r,$context);
 4247:         }
 4248:     } elsif ((($env{'form.action'} eq 'singleuser') || ($env{'form.action'}
 4249:              eq 'singlestudent')) && ($permission->{'cusr'})) {
 4250:         my $phase = $env{'form.phase'};
 4251:         my @search = ('srchterm','srchby','srchin','srchtype','srchdomain');
 4252: 	&Apache::loncreateuser::restore_prev_selections();
 4253: 	my $srch;
 4254: 	foreach my $item (@search) {
 4255: 	    $srch->{$item} = $env{'form.'.$item};
 4256: 	}
 4257:         if (($phase eq 'get_user_info') || ($phase eq 'userpicked') ||
 4258:             ($phase eq 'createnewuser')) {
 4259:             if ($env{'form.phase'} eq 'createnewuser') {
 4260:                 my $response;
 4261:                 if ($env{'form.srchterm'} !~ /^$match_username$/) {
 4262:                     my $response = &mt('You must specify a valid username. Only the following are allowed: letters numbers - . @');
 4263:                     $env{'form.phase'} = '';
 4264:                     &print_username_entry_form($r,$context,$response,$srch,undef,$crstype,$brcrum);
 4265:                 } else {
 4266:                     my $ccuname =&LONCAPA::clean_username($srch->{'srchterm'});
 4267:                     my $ccdomain=&LONCAPA::clean_domain($srch->{'srchdomain'});
 4268:                     &print_user_modification_page($r,$ccuname,$ccdomain,
 4269:                                                   $srch,$response,$context,
 4270:                                                   $permission,$crstype,$brcrum);
 4271:                 }
 4272:             } elsif ($env{'form.phase'} eq 'get_user_info') {
 4273:                 my ($currstate,$response,$forcenewuser,$results) = 
 4274:                     &user_search_result($context,$srch);
 4275:                 if ($env{'form.currstate'} eq 'modify') {
 4276:                     $currstate = $env{'form.currstate'};
 4277:                 }
 4278:                 if ($currstate eq 'select') {
 4279:                     &print_user_selection_page($r,$response,$srch,$results,
 4280:                                                \@search,$context,undef,$crstype,
 4281:                                                $brcrum);
 4282:                 } elsif ($currstate eq 'modify') {
 4283:                     my ($ccuname,$ccdomain);
 4284:                     if (($srch->{'srchby'} eq 'uname') && 
 4285:                         ($srch->{'srchtype'} eq 'exact')) {
 4286:                         $ccuname = $srch->{'srchterm'};
 4287:                         $ccdomain= $srch->{'srchdomain'};
 4288:                     } else {
 4289:                         my @matchedunames = keys(%{$results});
 4290:                         ($ccuname,$ccdomain) = split(/:/,$matchedunames[0]);
 4291:                     }
 4292:                     $ccuname =&LONCAPA::clean_username($ccuname);
 4293:                     $ccdomain=&LONCAPA::clean_domain($ccdomain);
 4294:                     if ($env{'form.forcenewuser'}) {
 4295:                         $response = '';
 4296:                     }
 4297:                     &print_user_modification_page($r,$ccuname,$ccdomain,
 4298:                                                   $srch,$response,$context,
 4299:                                                   $permission,$crstype,$brcrum);
 4300:                 } elsif ($currstate eq 'query') {
 4301:                     &print_user_query_page($r,'createuser',$brcrum);
 4302:                 } else {
 4303:                     $env{'form.phase'} = '';
 4304:                     &print_username_entry_form($r,$context,$response,$srch,
 4305:                                                $forcenewuser,$crstype,$brcrum);
 4306:                 }
 4307:             } elsif ($env{'form.phase'} eq 'userpicked') {
 4308:                 my $ccuname = &LONCAPA::clean_username($env{'form.seluname'});
 4309:                 my $ccdomain = &LONCAPA::clean_domain($env{'form.seludom'});
 4310:                 &print_user_modification_page($r,$ccuname,$ccdomain,$srch,'',
 4311:                                               $context,$permission,$crstype,
 4312:                                               $brcrum);
 4313:             }
 4314:         } elsif ($env{'form.phase'} eq 'update_user_data') {
 4315:             &update_user_data($r,$context,$crstype,$brcrum);
 4316:         } else {
 4317:             &print_username_entry_form($r,$context,undef,$srch,undef,$crstype,
 4318:                                        $brcrum);
 4319:         }
 4320:     } elsif ($env{'form.action'} eq 'custom' && $permission->{'custom'}) {
 4321:         if ($env{'form.phase'} eq 'set_custom_roles') {
 4322:             &set_custom_role($r,$context,$brcrum);
 4323:         } else {
 4324:             &custom_role_editor($r,$brcrum);
 4325:         }
 4326:     } elsif (($env{'form.action'} eq 'processauthorreq') &&
 4327:              ($permission->{'cusr'}) && 
 4328:              (&Apache::lonnet::allowed('cau',$env{'request.role.domain'}))) {
 4329:         push(@{$brcrum},
 4330:                  {href => '/adm/createuser?action=processauthorreq',
 4331:                   text => 'Authoring space requests',
 4332:                   help => 'Domain_Role_Approvals'});
 4333:         $bread_crumbs_component = 'Authoring requests';
 4334:         if ($env{'form.state'} eq 'done') {
 4335:             push(@{$brcrum},
 4336:                      {href => '/adm/createuser?action=authorreqqueue',
 4337:                       text => 'Result',
 4338:                       help => 'Domain_Role_Approvals'});
 4339:             $bread_crumbs_component = 'Authoring request result';
 4340:         }
 4341:         $args = { bread_crumbs           => $brcrum,
 4342:                   bread_crumbs_component => $bread_crumbs_component};
 4343:         $r->print(&header(undef,$args));
 4344:         if (!exists($env{'form.state'})) {
 4345:             $r->print(&Apache::loncoursequeueadmin::display_queued_requests('requestauthor',
 4346:                                                                             $env{'request.role.domain'}));
 4347:         } elsif ($env{'form.state'} eq 'done') {
 4348:             $r->print('<h3>'.&mt('Authoring request processing').'</h3>'."\n");
 4349:             $r->print(&Apache::loncoursequeueadmin::update_request_queue('requestauthor',
 4350:                                                                          $env{'request.role.domain'}));
 4351:         }
 4352:     } elsif (($env{'form.action'} eq 'listusers') && 
 4353:              ($permission->{'view'} || $permission->{'cusr'})) {
 4354:         if ($env{'form.phase'} eq 'bulkchange') {
 4355:             push(@{$brcrum},
 4356:                     {href => '/adm/createuser?action=listusers',
 4357:                      text => "List Users"},
 4358:                     {href => "/adm/createuser",
 4359:                      text => "Result",
 4360:                      help => 'Course_View_Class_List'});
 4361:             $bread_crumbs_component = 'Update Users';
 4362:             $args = {bread_crumbs           => $brcrum,
 4363:                      bread_crumbs_component => $bread_crumbs_component};
 4364:             $r->print(&header(undef,$args));
 4365:             my $setting = $env{'form.roletype'};
 4366:             my $choice = $env{'form.bulkaction'};
 4367:             if ($permission->{'cusr'}) {
 4368:                 &Apache::lonuserutils::update_user_list($r,$context,$setting,$choice,$crstype);
 4369:             } else {
 4370:                 $r->print(&mt('You are not authorized to make bulk changes to user roles'));
 4371:                 $r->print('<p><a href="/adm/createuser?action=listusers">'.&mt('Display User Lists').'</a>');
 4372:             }
 4373:         } else {
 4374:             push(@{$brcrum},
 4375:                     {href => '/adm/createuser?action=listusers',
 4376:                      text => "List Users",
 4377:                      help => 'Course_View_Class_List'});
 4378:             $bread_crumbs_component = 'List Users';
 4379:             $args = {bread_crumbs           => $brcrum,
 4380:                      bread_crumbs_component => $bread_crumbs_component};
 4381:             my ($cb_jscript,$jscript,$totcodes,$codetitles,$idlist,$idlist_titles);
 4382:             my $formname = 'studentform';
 4383:             if (($context eq 'domain') && (($env{'form.roletype'} eq 'course') ||
 4384:                 ($env{'form.roletype'} eq 'community'))) {
 4385:                 if ($env{'form.roletype'} eq 'course') {
 4386:                     ($cb_jscript,$jscript,$totcodes,$codetitles,$idlist,$idlist_titles) = 
 4387:                         &Apache::lonuserutils::courses_selector($env{'request.role.domain'},
 4388:                                                                 $formname);
 4389:                 } elsif ($env{'form.roletype'} eq 'community') {
 4390:                     $cb_jscript = 
 4391:                         &Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'});
 4392:                     my %elements = (
 4393:                                       coursepick => 'radio',
 4394:                                       coursetotal => 'text',
 4395:                                       courselist => 'text',
 4396:                                    );
 4397:                     $jscript = &Apache::lonhtmlcommon::set_form_elements(\%elements);
 4398:                 }
 4399:                 $jscript .= &verify_user_display();
 4400:                 my $js = &add_script($jscript).$cb_jscript;
 4401:                 my $loadcode = 
 4402:                     &Apache::lonuserutils::course_selector_loadcode($formname);
 4403:                 if ($loadcode ne '') {
 4404:                     $args->{add_entries} = {onload => $loadcode};
 4405:                 }
 4406:                 $r->print(&header($js,$args));
 4407:             } else {
 4408:                 $r->print(&header(&add_script(&verify_user_display()),$args));
 4409:             }
 4410:             &Apache::lonuserutils::print_userlist($r,undef,$permission,$context,
 4411:                          $formname,$totcodes,$codetitles,$idlist,$idlist_titles);
 4412:         }
 4413:     } elsif ($env{'form.action'} eq 'drop' && $permission->{'cusr'}) {
 4414:         my $brtext;
 4415:         if ($crstype eq 'Community') {
 4416:             $brtext = 'Drop Members';
 4417:         } else {
 4418:             $brtext = 'Drop Students';
 4419:         }
 4420:         push(@{$brcrum},
 4421:                 {href => '/adm/createuser?action=drop',
 4422:                  text => $brtext,
 4423:                  help => 'Course_Drop_Student'});
 4424:         if ($env{'form.state'} eq 'done') {
 4425:             push(@{$brcrum},
 4426:                      {href=>'/adm/createuser?action=drop',
 4427:                       text=>"Result"});
 4428:         }
 4429:         $bread_crumbs_component = $brtext;
 4430:         $args = {bread_crumbs           => $brcrum,
 4431:                  bread_crumbs_component => $bread_crumbs_component}; 
 4432:         $r->print(&header(undef,$args));
 4433:         if (!exists($env{'form.state'})) {
 4434:             &Apache::lonuserutils::print_drop_menu($r,$context,$permission,$crstype);
 4435:         } elsif ($env{'form.state'} eq 'done') {
 4436:             &Apache::lonuserutils::update_user_list($r,$context,undef,
 4437:                                                     $env{'form.action'});
 4438:         }
 4439:     } elsif ($env{'form.action'} eq 'dateselect') {
 4440:         if ($permission->{'cusr'}) {
 4441:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 4442:                       &Apache::lonuserutils::date_section_selector($context,
 4443:                                                                    $permission,$crstype));
 4444:         } else {
 4445:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 4446:                      '<span class="LC_error">'.&mt('You do not have permission to modify dates or sections for users').'</span>'); 
 4447:         }
 4448:     } elsif ($env{'form.action'} eq 'selfenroll') {
 4449:         push(@{$brcrum},
 4450:                 {href => '/adm/createuser?action=selfenroll',
 4451:                  text => "Configure Self-enrollment",
 4452:                  help => 'Course_Self_Enrollment'});
 4453:         if (!exists($env{'form.state'})) {
 4454:             $args = { bread_crumbs           => $brcrum,
 4455:                       bread_crumbs_component => 'Configure Self-enrollment'};
 4456:             $r->print(&header(undef,$args));
 4457:             $r->print('<h3>'.&mt('Self-enrollment with a student role').'</h3>'."\n");
 4458:             &print_selfenroll_menu($r,$context,$permission);
 4459:         } elsif ($env{'form.state'} eq 'done') {
 4460:             push (@{$brcrum},
 4461:                       {href=>'/adm/createuser?action=selfenroll',
 4462:                        text=>"Result"});
 4463:             $args = { bread_crumbs           => $brcrum,
 4464:                       bread_crumbs_component => 'Self-enrollment result'};
 4465:             $r->print(&header(undef,$args));
 4466:             $r->print('<h3>'.&mt('Self-enrollment with a student role').'</h3>'."\n");
 4467:             &update_selfenroll_config($r,$context,$permission);
 4468:         }
 4469:     } elsif ($env{'form.action'} eq 'selfenrollqueue') {
 4470:         push(@{$brcrum},
 4471:                  {href => '/adm/createuser?action=selfenrollqueue',
 4472:                   text => 'Enrollment requests',
 4473:                   help => 'Course_Self_Enrollment'});
 4474:         $bread_crumbs_component = 'Enrollment requests';
 4475:         if ($env{'form.state'} eq 'done') {
 4476:             push(@{$brcrum},
 4477:                      {href => '/adm/createuser?action=selfenrollqueue',
 4478:                       text => 'Result',
 4479:                       help => 'Course_Self_Enrollment'});
 4480:             $bread_crumbs_component = 'Enrollment result';
 4481:         }
 4482:         $args = { bread_crumbs           => $brcrum,
 4483:                   bread_crumbs_component => $bread_crumbs_component};
 4484:         $r->print(&header(undef,$args));
 4485:         my $cid = $env{'request.course.id'};
 4486:         my $cdom = $env{'course.'.$cid.'.domain'};
 4487:         my $cnum = $env{'course.'.$cid.'.num'};
 4488:         my $coursedesc = $env{'course.'.$cid.'.description'};
 4489:         if (!exists($env{'form.state'})) {
 4490:             $r->print('<h3>'.&mt('Pending enrollment requests').'</h3>'."\n");
 4491:             $r->print(&Apache::loncoursequeueadmin::display_queued_requests($context,
 4492:                                                                        $cdom,$cnum));
 4493:         } elsif ($env{'form.state'} eq 'done') {
 4494:             $r->print('<h3>'.&mt('Enrollment request processing').'</h3>'."\n");
 4495:             $r->print(&Apache::loncoursequeueadmin::update_request_queue($context,
 4496:                           $cdom,$cnum,$coursedesc));
 4497:         }
 4498:     } elsif ($env{'form.action'} eq 'changelogs') {
 4499:         my $helpitem;
 4500:         if ($context eq 'course') {
 4501:             $helpitem = 'Course_User_Logs';
 4502:         }
 4503:         push (@{$brcrum},
 4504:                  {href => '/adm/createuser?action=changelogs',
 4505:                   text => 'User Management Logs',
 4506:                   help => $helpitem});
 4507:         $bread_crumbs_component = 'User Changes';
 4508:         $args = { bread_crumbs           => $brcrum,
 4509:                   bread_crumbs_component => $bread_crumbs_component};
 4510:         $r->print(&header(undef,$args));
 4511:         &print_userchangelogs_display($r,$context,$permission);
 4512:     } else {
 4513:         $bread_crumbs_component = 'User Management';
 4514:         $args = { bread_crumbs           => $brcrum,
 4515:                   bread_crumbs_component => $bread_crumbs_component};
 4516:         $r->print(&header(undef,$args));
 4517:         $r->print(&print_main_menu($permission,$context,$crstype));
 4518:     }
 4519:     $r->print(&Apache::loncommon::end_page());
 4520:     return OK;
 4521: }
 4522: 
 4523: sub header {
 4524:     my ($jscript,$args) = @_;
 4525:     my $start_page;
 4526:     if (ref($args) eq 'HASH') {
 4527:         $start_page=&Apache::loncommon::start_page('User Management',$jscript,$args);
 4528:     } else {
 4529:         $start_page=&Apache::loncommon::start_page('User Management',$jscript);
 4530:     }
 4531:     return $start_page;
 4532: }
 4533: 
 4534: sub add_script {
 4535:     my ($js) = @_;
 4536:     return '<script type="text/javascript">'."\n"
 4537:           .'// <![CDATA['."\n"
 4538:           .$js."\n"
 4539:           .'// ]]>'."\n"
 4540:           .'</script>'."\n";
 4541: }
 4542: 
 4543: sub verify_user_display {
 4544:     my $output = <<"END";
 4545: 
 4546: function display_update() {
 4547:     document.studentform.action.value = 'listusers';
 4548:     document.studentform.phase.value = 'display';
 4549:     document.studentform.submit();
 4550: }
 4551: 
 4552: END
 4553:     return $output;
 4554: 
 4555: }
 4556: 
 4557: ###############################################################
 4558: ###############################################################
 4559: #  Menu Phase One
 4560: sub print_main_menu {
 4561:     my ($permission,$context,$crstype) = @_;
 4562:     my $linkcontext = $context;
 4563:     my $stuterm = lc(&Apache::lonnet::plaintext('st',$crstype));
 4564:     if (($context eq 'course') && ($crstype eq 'Community')) {
 4565:         $linkcontext = lc($crstype);
 4566:         $stuterm = 'Members';
 4567:     }
 4568:     my %links = (
 4569:                 domain => {
 4570:                             upload     => 'Upload a File of Users',
 4571:                             singleuser => 'Add/Modify a User',
 4572:                             listusers  => 'Manage Users',
 4573:                             },
 4574:                 author => {
 4575:                             upload     => 'Upload a File of Co-authors',
 4576:                             singleuser => 'Add/Modify a Co-author',
 4577:                             listusers  => 'Manage Co-authors',
 4578:                             },
 4579:                 course => {
 4580:                             upload     => 'Upload a File of Course Users',
 4581:                             singleuser => 'Add/Modify a Course User',
 4582:                             listusers  => 'List and Modify Multiple Course Users',
 4583:                             },
 4584:                 community => {
 4585:                             upload     => 'Upload a File of Community Users',
 4586:                             singleuser => 'Add/Modify a Community User',
 4587:                             listusers  => 'List and Modify Multiple Community Users',
 4588:                            },
 4589:                 );
 4590:      my %linktitles = (
 4591:                 domain => {
 4592:                             singleuser => 'Add a user to the domain, and/or a course or community in the domain.',
 4593:                             listusers  => 'Show and manage users in this domain.',
 4594:                             },
 4595:                 author => {
 4596:                             singleuser => 'Add a user with a co- or assistant author role.',
 4597:                             listusers  => 'Show and manage co- or assistant authors.',
 4598:                             },
 4599:                 course => {
 4600:                             singleuser => 'Add a user with a certain role to this course.',
 4601:                             listusers  => 'Show and manage users in this course.',
 4602:                             },
 4603:                 community => {
 4604:                             singleuser => 'Add a user with a certain role to this community.',
 4605:                             listusers  => 'Show and manage users in this community.',
 4606:                            },
 4607:                 );
 4608:   my @menu = ( {categorytitle => 'Single Users', 
 4609:          items =>
 4610:          [
 4611:             {
 4612:              linktext => $links{$linkcontext}{'singleuser'},
 4613:              icon => 'edit-redo.png',
 4614:              #help => 'Course_Change_Privileges',
 4615:              url => '/adm/createuser?action=singleuser',
 4616:              permission => $permission->{'cusr'},
 4617:              linktitle => $linktitles{$linkcontext}{'singleuser'},
 4618:             },
 4619:          ]},
 4620: 
 4621:          {categorytitle => 'Multiple Users',
 4622:          items => 
 4623:          [
 4624:             {
 4625:              linktext => $links{$linkcontext}{'upload'},
 4626:              icon => 'uplusr.png',
 4627:              #help => 'Course_Create_Class_List',
 4628:              url => '/adm/createuser?action=upload',
 4629:              permission => $permission->{'cusr'},
 4630:              linktitle => 'Upload a CSV or a text file containing users.',
 4631:             },
 4632:             {
 4633:              linktext => $links{$linkcontext}{'listusers'},
 4634:              icon => 'mngcu.png',
 4635:              #help => 'Course_View_Class_List',
 4636:              url => '/adm/createuser?action=listusers',
 4637:              permission => ($permission->{'view'} || $permission->{'cusr'}),
 4638:              linktitle => $linktitles{$linkcontext}{'listusers'}, 
 4639:             },
 4640: 
 4641:          ]},
 4642: 
 4643:          {categorytitle => 'Administration',
 4644:          items => [ ]},
 4645:        );
 4646:             
 4647:     if ($context eq 'domain'){
 4648:         
 4649:         push(@{ $menu[2]->{items} }, #Category: Administration
 4650:             {
 4651:              linktext => 'Custom Roles',
 4652:              icon => 'emblem-photos.png',
 4653:              #help => 'Course_Editing_Custom_Roles',
 4654:              url => '/adm/createuser?action=custom',
 4655:              permission => $permission->{'custom'},
 4656:              linktitle => 'Configure a custom role.',
 4657:             },
 4658:             {
 4659:              linktext => 'Authoring Space Requests',
 4660:              icon => 'selfenrl-queue.png',
 4661:              #help => 'Domain_Role_Approvals',
 4662:              url => '/adm/createuser?action=processauthorreq',
 4663:              permission => $permission->{'cusr'},
 4664:              linktitle => 'Approve or reject author role requests',
 4665:             },
 4666:             {
 4667:              linktext => 'Change Log',
 4668:              icon => 'document-properties.png',
 4669:              #help => 'Course_User_Logs',
 4670:              url => '/adm/createuser?action=changelogs',
 4671:              permission => $permission->{'cusr'},
 4672:              linktitle => 'View change log.',
 4673:             },
 4674:         );
 4675:         
 4676:     }elsif ($context eq 'course'){
 4677:         my ($cnum,$cdom) = &Apache::lonuserutils::get_course_identity();
 4678: 
 4679:         my %linktext = (
 4680:                          'Course'    => {
 4681:                                           single => 'Add/Modify a Student', 
 4682:                                           drop   => 'Drop Students',
 4683:                                           groups => 'Course Groups',
 4684:                                         },
 4685:                          'Community' => {
 4686:                                           single => 'Add/Modify a Member', 
 4687:                                           drop   => 'Drop Members',
 4688:                                           groups => 'Community Groups',
 4689:                                         },
 4690:                        );
 4691: 
 4692:         my %linktitle = (
 4693:             'Course' => {
 4694:                   single => 'Add a user with the role of student to this course',
 4695:                   drop   => 'Remove a student from this course.',
 4696:                   groups => 'Manage course groups',
 4697:                         },
 4698:             'Community' => {
 4699:                   single => 'Add a user with the role of member to this community',
 4700:                   drop   => 'Remove a member from this community.',
 4701:                   groups => 'Manage community groups',
 4702:                            },
 4703:         );
 4704: 
 4705:         push(@{ $menu[0]->{items} }, #Category: Single Users
 4706:             {   
 4707:              linktext => $linktext{$crstype}{'single'},
 4708:              #help => 'Course_Add_Student',
 4709:              icon => 'list-add.png',
 4710:              url => '/adm/createuser?action=singlestudent',
 4711:              permission => $permission->{'cusr'},
 4712:              linktitle => $linktitle{$crstype}{'single'},
 4713:             },
 4714:         );
 4715:         
 4716:         push(@{ $menu[1]->{items} }, #Category: Multiple Users 
 4717:             {
 4718:              linktext => $linktext{$crstype}{'drop'},
 4719:              icon => 'edit-undo.png',
 4720:              #help => 'Course_Drop_Student',
 4721:              url => '/adm/createuser?action=drop',
 4722:              permission => $permission->{'cusr'},
 4723:              linktitle => $linktitle{$crstype}{'drop'},
 4724:             },
 4725:         );
 4726:         push(@{ $menu[2]->{items} }, #Category: Administration
 4727:             {    
 4728:              linktext => 'Custom Roles',
 4729:              icon => 'emblem-photos.png',
 4730:              #help => 'Course_Editing_Custom_Roles',
 4731:              url => '/adm/createuser?action=custom',
 4732:              permission => $permission->{'custom'},
 4733:              linktitle => 'Configure a custom role.',
 4734:             },
 4735:             {
 4736:              linktext => $linktext{$crstype}{'groups'},
 4737:              icon => 'grps.png',
 4738:              #help => 'Course_Manage_Group',
 4739:              url => '/adm/coursegroups?refpage=cusr',
 4740:              permission => $permission->{'grp_manage'},
 4741:              linktitle => $linktitle{$crstype}{'groups'},
 4742:             },
 4743:             {
 4744:              linktext => 'Change Log',
 4745:              icon => 'document-properties.png',
 4746:              #help => 'Course_User_Logs',
 4747:              url => '/adm/createuser?action=changelogs',
 4748:              permission => $permission->{'cusr'},
 4749:              linktitle => 'View change log.',
 4750:             },
 4751:         );
 4752:         if ($env{'course.'.$env{'request.course.id'}.'.internal.selfenroll_approval'}) {
 4753:             push(@{ $menu[2]->{items} },
 4754:                     {   
 4755:                      linktext => 'Enrollment Requests',
 4756:                      icon => 'selfenrl-queue.png',
 4757:                      #help => 'Course_Approve_Selfenroll',
 4758:                      url => '/adm/createuser?action=selfenrollqueue',
 4759:                      permission => $permission->{'cusr'},
 4760:                      linktitle =>'Approve or reject enrollment requests.',
 4761:                     },
 4762:             );
 4763:         }
 4764:         
 4765:         if (!exists($permission->{'cusr_section'})){
 4766:             if ($crstype ne 'Community') {
 4767:                 push(@{ $menu[2]->{items} },
 4768:                     {
 4769:                      linktext => 'Automated Enrollment',
 4770:                      icon => 'roles.png',
 4771:                      #help => 'Course_Automated_Enrollment',
 4772:                      permission => (&Apache::lonnet::auto_run($cnum,$cdom)
 4773:                                          && $permission->{'cusr'}),
 4774:                      url  => '/adm/populate',
 4775:                      linktitle => 'Automated enrollment manager.',
 4776:                     }
 4777:                 );
 4778:             }
 4779:             push(@{ $menu[2]->{items} }, 
 4780:                 {
 4781:                  linktext => 'User Self-Enrollment',
 4782:                  icon => 'self_enroll.png',
 4783:                  #help => 'Course_Self_Enrollment',
 4784:                  url => '/adm/createuser?action=selfenroll',
 4785:                  permission => $permission->{'cusr'},
 4786:                  linktitle => 'Configure user self-enrollment.',
 4787:                 },
 4788:             );
 4789:         }
 4790:     } elsif ($context eq 'author') {
 4791:             {
 4792:              linktext => 'Change Log',
 4793:              icon => 'document-properties.png',
 4794:              #help => 'Course_User_Logs',
 4795:              url => '/adm/createuser?action=changelogs',
 4796:              permission => $permission->{'cusr'},
 4797:              linktitle => 'View change log.',
 4798:             },
 4799:     }
 4800:     return Apache::lonhtmlcommon::generate_menu(@menu);
 4801: #               { text => 'View Log-in History',
 4802: #                 help => 'Course_User_Logins',
 4803: #                 action => 'logins',
 4804: #                 permission => $permission->{'cusr'},
 4805: #               });
 4806: }
 4807: 
 4808: sub restore_prev_selections {
 4809:     my %saveable_parameters = ('srchby'   => 'scalar',
 4810: 			       'srchin'   => 'scalar',
 4811: 			       'srchtype' => 'scalar',
 4812: 			       );
 4813:     &Apache::loncommon::store_settings('user','user_picker',
 4814: 				       \%saveable_parameters);
 4815:     &Apache::loncommon::restore_settings('user','user_picker',
 4816: 					 \%saveable_parameters);
 4817: }
 4818: 
 4819: sub print_selfenroll_menu {
 4820:     my ($r,$context,$permission) = @_;
 4821:     my $crstype = &Apache::loncommon::course_type();
 4822:     my $formname = 'enrollstudent';
 4823:     my $nolink = 1;
 4824:     my ($row,$lt) = &get_selfenroll_titles();
 4825:     my $groupslist = &Apache::lonuserutils::get_groupslist();
 4826:     my $setsec_js = 
 4827:         &Apache::lonuserutils::setsections_javascript($formname,$groupslist);
 4828:     my %alerts = &Apache::lonlocal::texthash(
 4829:         acto => 'Activation of self-enrollment was selected for the following domain(s)',
 4830:         butn => 'but no user types have been checked.',
 4831:         wilf => "Please uncheck 'activate' or check at least one type.",
 4832:     );
 4833:     my $selfenroll_js = <<"ENDSCRIPT";
 4834: function update_types(caller,num) {
 4835:     var delidx = getIndexByName('selfenroll_delete');
 4836:     var actidx = getIndexByName('selfenroll_activate');
 4837:     if (caller == 'selfenroll_all') {
 4838:         var selall;
 4839:         for (var i=0; i<document.$formname.selfenroll_all.length; i++) {
 4840:             if (document.$formname.selfenroll_all[i].checked) {
 4841:                 selall = document.$formname.selfenroll_all[i].value;
 4842:             }
 4843:         }
 4844:         if (selall == 1) {
 4845:             if (delidx != -1) {
 4846:                 if (document.$formname.selfenroll_delete.length) {
 4847:                     for (var j=0; j<document.$formname.selfenroll_delete.length; j++) {
 4848:                         document.$formname.selfenroll_delete[j].checked = true;
 4849:                     }
 4850:                 } else {
 4851:                     document.$formname.elements[delidx].checked = true;
 4852:                 }
 4853:             }
 4854:             if (actidx != -1) {
 4855:                 if (document.$formname.selfenroll_activate.length) {
 4856:                     for (var j=0; j<document.$formname.selfenroll_activate.length; j++) {
 4857:                         document.$formname.selfenroll_activate[j].checked = false;
 4858:                     }
 4859:                 } else {
 4860:                     document.$formname.elements[actidx].checked = false;
 4861:                 }
 4862:             }
 4863:             document.$formname.selfenroll_newdom.selectedIndex = 0; 
 4864:         }
 4865:     }
 4866:     if (caller == 'selfenroll_activate') {
 4867:         if (document.$formname.selfenroll_activate.length) {
 4868:             for (var j=0; j<document.$formname.selfenroll_activate.length; j++) {
 4869:                 if (document.$formname.selfenroll_activate[j].value == num) {
 4870:                     if (document.$formname.selfenroll_activate[j].checked) {
 4871:                         for (var i=0; i<document.$formname.selfenroll_all.length; i++) {
 4872:                             if (document.$formname.selfenroll_all[i].value == '1') {
 4873:                                 document.$formname.selfenroll_all[i].checked = false;
 4874:                             }
 4875:                             if (document.$formname.selfenroll_all[i].value == '0') {
 4876:                                 document.$formname.selfenroll_all[i].checked = true;
 4877:                             }
 4878:                         }
 4879:                     }
 4880:                 }
 4881:             }
 4882:         } else {
 4883:             for (var i=0; i<document.$formname.selfenroll_all.length; i++) {
 4884:                 if (document.$formname.selfenroll_all[i].value == '1') {
 4885:                     document.$formname.selfenroll_all[i].checked = false;
 4886:                 }
 4887:                 if (document.$formname.selfenroll_all[i].value == '0') {
 4888:                     document.$formname.selfenroll_all[i].checked = true;
 4889:                 }
 4890:             }
 4891:         }
 4892:     }
 4893:     if (caller == 'selfenroll_delete') {
 4894:         if (document.$formname.selfenroll_delete.length) {
 4895:             for (var j=0; j<document.$formname.selfenroll_delete.length; j++) {
 4896:                 if (document.$formname.selfenroll_delete[j].value == num) {
 4897:                     if (document.$formname.selfenroll_delete[j].checked) {
 4898:                         var delindex = getIndexByName('selfenroll_types_'+num);
 4899:                         if (delindex != -1) { 
 4900:                             if (document.$formname.elements[delindex].length) {
 4901:                                 for (var k=0; k<document.$formname.elements[delindex].length; k++) {
 4902:                                     document.$formname.elements[delindex][k].checked = false;
 4903:                                 }
 4904:                             } else {
 4905:                                 document.$formname.elements[delindex].checked = false;
 4906:                             }
 4907:                         }
 4908:                     }
 4909:                 }
 4910:             }
 4911:         } else {
 4912:             if (document.$formname.selfenroll_delete.checked) {
 4913:                 var delindex = getIndexByName('selfenroll_types_'+num);
 4914:                 if (delindex != -1) {
 4915:                     if (document.$formname.elements[delindex].length) {
 4916:                         for (var k=0; k<document.$formname.elements[delindex].length; k++) {
 4917:                             document.$formname.elements[delindex][k].checked = false;
 4918:                         }
 4919:                     } else {
 4920:                         document.$formname.elements[delindex].checked = false;
 4921:                     }
 4922:                 }
 4923:             }
 4924:         }
 4925:     }
 4926:     return;
 4927: }
 4928: 
 4929: function validate_types(form) {
 4930:     var needaction = new Array();
 4931:     var countfail = 0;
 4932:     var actidx = getIndexByName('selfenroll_activate');
 4933:     if (actidx != -1) {
 4934:         if (document.$formname.selfenroll_activate.length) {
 4935:             for (var j=0; j<document.$formname.selfenroll_activate.length; j++) {
 4936:                 var num = document.$formname.selfenroll_activate[j].value;
 4937:                 if (document.$formname.selfenroll_activate[j].checked) {
 4938:                     countfail = check_types(num,countfail,needaction)
 4939:                 }
 4940:             }
 4941:         } else {
 4942:             if (document.$formname.selfenroll_activate.checked) {
 4943:                 var num = document.enrollstudent.selfenroll_activate.value;
 4944:                 countfail = check_types(num,countfail,needaction)
 4945:             }
 4946:         }
 4947:     }
 4948:     if (countfail > 0) {
 4949:         var msg = "$alerts{'acto'}\\n";
 4950:         var loopend = needaction.length -1;
 4951:         if (loopend > 0) {
 4952:             for (var m=0; m<loopend; m++) {
 4953:                 msg += needaction[m]+", ";
 4954:             }
 4955:         }
 4956:         msg += needaction[loopend]+"\\n$alerts{'butn'}\\n$alerts{'wilf'}";
 4957:         alert(msg);
 4958:         return; 
 4959:     }
 4960:     setSections(form);
 4961: }
 4962: 
 4963: function check_types(num,countfail,needaction) {
 4964:     var typeidx = getIndexByName('selfenroll_types_'+num);
 4965:     var count = 0;
 4966:     if (typeidx != -1) {
 4967:         if (document.$formname.elements[typeidx].length) {
 4968:             for (var k=0; k<document.$formname.elements[typeidx].length; k++) {
 4969:                 if (document.$formname.elements[typeidx][k].checked) {
 4970:                     count ++;
 4971:                 }
 4972:             }
 4973:         } else {
 4974:             if (document.$formname.elements[typeidx].checked) {
 4975:                 count ++;
 4976:             }
 4977:         }
 4978:         if (count == 0) {
 4979:             var domidx = getIndexByName('selfenroll_dom_'+num);
 4980:             if (domidx != -1) {
 4981:                 var domname = document.$formname.elements[domidx].value;
 4982:                 needaction[countfail] = domname;
 4983:                 countfail ++;
 4984:             }
 4985:         }
 4986:     }
 4987:     return countfail;
 4988: }
 4989: 
 4990: function getIndexByName(item) {
 4991:     for (var i=0;i<document.$formname.elements.length;i++) {
 4992:         if (document.$formname.elements[i].name == item) {
 4993:             return i;
 4994:         }
 4995:     }
 4996:     return -1;
 4997: }
 4998: ENDSCRIPT
 4999:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5000:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 5001: 
 5002:     my $output = '<script type="text/javascript">'."\n".
 5003:                  '// <![CDATA['."\n".
 5004:                  $setsec_js."\n".$selfenroll_js."\n".
 5005:                  '// ]]>'."\n".
 5006:                  '</script>'."\n".
 5007:                  '<h3>'.$lt->{'selfenroll'}.'</h3>'."\n";
 5008:     my ($visible,$cansetvis,$vismsgs,$visactions) = &visible_in_cat($cdom,$cnum);
 5009:     if (ref($visactions) eq 'HASH') {
 5010:         if ($visible) {
 5011:             $output .= '<p class="LC_info">'.$visactions->{'vis'}.'</p>';
 5012:         } else {
 5013:             $output .= '<p class="LC_warning">'.$visactions->{'miss'}.'</p>'
 5014:                       .$visactions->{'yous'}.
 5015:                        '<p>'.$visactions->{'gen'}.'<br />'.$visactions->{'coca'};
 5016:             if (ref($vismsgs) eq 'ARRAY') {
 5017:                 $output .= '<br />'.$visactions->{'make'}.'<ul>';
 5018:                 foreach my $item (@{$vismsgs}) {
 5019:                     $output .= '<li>'.$visactions->{$item}.'</li>';
 5020:                 }
 5021:                 $output .= '</ul>';
 5022:             }
 5023:             $output .= '</p>';
 5024:         }
 5025:     }
 5026:     $output .= '<form name="'.$formname.'" method="post" action="/adm/createuser">'."\n".
 5027:                &Apache::lonhtmlcommon::start_pick_box();
 5028:     if (ref($row) eq 'ARRAY') {
 5029:         foreach my $item (@{$row}) {
 5030:             my $title = $item; 
 5031:             if (ref($lt) eq 'HASH') {
 5032:                 $title = $lt->{$item};
 5033:             }
 5034:             $output .= &Apache::lonhtmlcommon::row_title($title);
 5035:             if ($item eq 'types') {
 5036:                 my $curr_types = $env{'course.'.$env{'request.course.id'}.'.internal.selfenroll_types'};
 5037:                 my $showdomdesc = 1;
 5038:                 my $includeempty = 1;
 5039:                 my $num = 0;
 5040:                 $output .= &Apache::loncommon::start_data_table().
 5041:                            &Apache::loncommon::start_data_table_row()
 5042:                            .'<td colspan="2"><span class="LC_nobreak"><label>'
 5043:                            .&mt('Any user in any domain:')
 5044:                            .'&nbsp;<input type="radio" name="selfenroll_all" value="1" ';
 5045:                 if ($curr_types eq '*') {
 5046:                     $output .= ' checked="checked" '; 
 5047:                 }
 5048:                 $output .= 'onchange="javascript:update_types('.
 5049:                            "'selfenroll_all'".');" />'.&mt('Yes').'</label>'.
 5050:                            '&nbsp;&nbsp;<input type="radio" name="selfenroll_all" value="0" ';
 5051:                 if ($curr_types ne '*') {
 5052:                     $output .= ' checked="checked" ';
 5053:                 }
 5054:                 $output .= ' onchange="javascript:update_types('.
 5055:                            "'selfenroll_all'".');"/>'.&mt('No').'</label></td>'.
 5056:                            &Apache::loncommon::end_data_table_row().
 5057:                            &Apache::loncommon::end_data_table().
 5058:                            &mt('Or').'<br />'.
 5059:                            &Apache::loncommon::start_data_table();
 5060:                 my %currdoms;
 5061:                 if ($curr_types eq '') {
 5062:                     $output .= &new_selfenroll_dom_row($cdom,'0');
 5063:                 } elsif ($curr_types ne '*') {
 5064:                     my @entries = split(/;/,$curr_types);
 5065:                     if (@entries > 0) {
 5066:                         foreach my $entry (@entries) {
 5067:                             my ($currdom,$typestr) = split(/:/,$entry);
 5068:                             $currdoms{$currdom} = 1;
 5069:                             my $domdesc = &Apache::lonnet::domain($currdom);
 5070:                             my @currinsttypes = split(',',$typestr);
 5071:                             $output .= &Apache::loncommon::start_data_table_row()
 5072:                                        .'<td valign="top"><span class="LC_nobreak">'.&mt('Domain:').'<b>'
 5073:                                        .'&nbsp;'.$domdesc.' ('.$currdom.')'
 5074:                                        .'</b><input type="hidden" name="selfenroll_dom_'.$num
 5075:                                        .'" value="'.$currdom.'" /></span><br />'
 5076:                                        .'<span class="LC_nobreak"><label><input type="checkbox" '
 5077:                                        .'name="selfenroll_delete" value="'.$num.'" onchange="javascript:update_types('."'selfenroll_delete','$num'".');" />'
 5078:                                        .&mt('Delete').'</label></span></td>';
 5079:                             $output .= '<td valign="top">&nbsp;&nbsp;'.&mt('User types:').'<br />'
 5080:                                        .&selfenroll_inst_types($num,$currdom,\@currinsttypes).'</td>'
 5081:                                        .&Apache::loncommon::end_data_table_row();
 5082:                             $num ++;
 5083:                         }
 5084:                     }
 5085:                 }
 5086:                 my $add_domtitle = &mt('Users in additional domain:');
 5087:                 if ($curr_types eq '*') { 
 5088:                     $add_domtitle = &mt('Users in specific domain:');
 5089:                 } elsif ($curr_types eq '') {
 5090:                     $add_domtitle = &mt('Users in other domain:');
 5091:                 }
 5092:                 $output .= &Apache::loncommon::start_data_table_row()
 5093:                            .'<td colspan="2"><span class="LC_nobreak">'.$add_domtitle.'</span><br />'
 5094:                            .&Apache::loncommon::select_dom_form('','selfenroll_newdom',
 5095:                                                                 $includeempty,$showdomdesc)
 5096:                            .'<input type="hidden" name="selfenroll_types_total" value="'.$num.'" />'
 5097:                            .'</td>'.&Apache::loncommon::end_data_table_row()
 5098:                            .&Apache::loncommon::end_data_table();
 5099:             } elsif ($item eq 'registered') {
 5100:                 my ($regon,$regoff);
 5101:                 if ($env{'course.'.$env{'request.course.id'}.'.internal.selfenroll_registered'}) {
 5102:                     $regon = ' checked="checked" ';
 5103:                     $regoff = ' ';
 5104:                 } else {
 5105:                     $regon = ' ';
 5106:                     $regoff = ' checked="checked" ';
 5107:                 }
 5108:                 $output .= '<label>'.
 5109:                            '<input type="radio" name="selfenroll_registered" value="1"'.$regon.'/>'.
 5110:                            &mt('Yes').'</label>&nbsp;&nbsp;<label>'.
 5111:                            '<input type="radio" name="selfenroll_registered" value="0"'.$regoff.'/>'.
 5112:                            &mt('No').'</label>';
 5113:             } elsif ($item eq 'enroll_dates') {
 5114:                 my $starttime = $env{'course.'.$env{'request.course.id'}.'.internal.selfenroll_start_date'};
 5115:                 my $endtime = $env{'course.'.$env{'request.course.id'}.'.internal.selfenroll_end_date'};
 5116:                 if ($starttime eq '') {
 5117:                     $starttime = $env{'course.'.$env{'request.course.id'}.'.default_enrollment_start_date'};
 5118:                 }
 5119:                 if ($endtime eq '') {
 5120:                     $endtime = $env{'course.'.$env{'request.course.id'}.'.default_enrollment_end_date'};
 5121:                 }
 5122:                 my $startform =
 5123:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_start_date',$starttime,
 5124:                                       undef,undef,undef,undef,undef,undef,undef,$nolink);
 5125:                 my $endform =
 5126:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_end_date',$endtime,
 5127:                                       undef,undef,undef,undef,undef,undef,undef,$nolink);
 5128:                 $output .= &selfenroll_date_forms($startform,$endform);
 5129:             } elsif ($item eq 'access_dates') {
 5130:                 my $starttime = $env{'course.'.$env{'request.course.id'}.'.internal.selfenroll_start_access'};
 5131:                 my $endtime = $env{'course.'.$env{'request.course.id'}.'.internal.selfenroll_end_access'};
 5132:                 if ($starttime eq '') {
 5133:                     $starttime = $env{'course.'.$env{'request.course.id'}.'.default_enrollment_start_date'};
 5134:                 }
 5135:                 if ($endtime eq '') {
 5136:                     $endtime = $env{'course.'.$env{'request.course.id'}.'.default_enrollment_end_date'};
 5137:                 }
 5138:                 my $startform =
 5139:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_start_access',$starttime,
 5140:                                       undef,undef,undef,undef,undef,undef,undef,$nolink);
 5141:                 my $endform =
 5142:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_end_access',$endtime,
 5143:                                       undef,undef,undef,undef,undef,undef,undef,$nolink);
 5144:                 $output .= &selfenroll_date_forms($startform,$endform);
 5145:             } elsif ($item eq 'section') {
 5146:                 my $currsec = $env{'course.'.$env{'request.course.id'}.'.internal.selfenroll_section'}; 
 5147:                 my %sections_count = &Apache::loncommon::get_sections($cdom,$cnum);
 5148:                 my $newsecval;
 5149:                 if ($currsec ne 'none' && $currsec ne '') {
 5150:                     if (!defined($sections_count{$currsec})) {
 5151:                         $newsecval = $currsec;
 5152:                     }
 5153:                 }
 5154:                 my $sections_select = 
 5155:                     &Apache::lonuserutils::course_sections(\%sections_count,'st',$currsec);
 5156:                 $output .= '<table class="LC_createuser">'."\n".
 5157:                            '<tr class="LC_section_row">'."\n".
 5158:                            '<td align="center">'.&mt('Existing sections')."\n".
 5159:                            '<br />'.$sections_select.'</td><td align="center">'.
 5160:                            &mt('New section').'<br />'."\n".
 5161:                            '<input type="text" name="newsec" size="15" value="'.$newsecval.'" />'."\n".
 5162:                            '<input type="hidden" name="sections" value="" />'."\n".
 5163:                            '<input type="hidden" name="state" value="done" />'."\n".
 5164:                            '</td></tr></table>'."\n";
 5165:             } elsif ($item eq 'approval') {
 5166:                 my ($appon,$appoff);
 5167:                 my $cid = $env{'request.course.id'};
 5168:                 my $currnotified = $env{'course.'.$cid.'.internal.selfenroll_notifylist'};
 5169:                 if ($env{'course.'.$cid.'.internal.selfenroll_approval'}) {
 5170:                     $appon = ' checked="checked" ';
 5171:                     $appoff = ' ';
 5172:                 } else {
 5173:                     $appon = ' ';
 5174:                     $appoff = ' checked="checked" ';
 5175:                 }
 5176:                 $output .= '<label>'.
 5177:                            '<input type="radio" name="selfenroll_approval" value="1"'.$appon.'/>'.
 5178:                            &mt('Yes').'</label>&nbsp;&nbsp;<label>'.
 5179:                            '<input type="radio" name="selfenroll_approval" value="0"'.$appoff.'/>'.
 5180:                            &mt('No').'</label>';
 5181:                 my %advhash = &Apache::lonnet::get_course_adv_roles($cid,1);
 5182:                 my (@ccs,%notified);
 5183:                 my $ccrole = 'cc';
 5184:                 if ($crstype eq 'Community') {
 5185:                     $ccrole = 'co';
 5186:                 }
 5187:                 if ($advhash{$ccrole}) {
 5188:                     @ccs = split(/,/,$advhash{$ccrole});
 5189:                 }
 5190:                 if ($currnotified) {
 5191:                     foreach my $current (split(/,/,$currnotified)) {
 5192:                         $notified{$current} = 1;
 5193:                         if (!grep(/^\Q$current\E$/,@ccs)) {
 5194:                             push(@ccs,$current);
 5195:                         }
 5196:                     }
 5197:                 }
 5198:                 if (@ccs) {
 5199:                     $output .= '<br />'.&mt('Personnel to be notified when an enrollment request needs approval, or has been approved:').'&nbsp;'.&Apache::loncommon::start_data_table().
 5200:                                &Apache::loncommon::start_data_table_row();
 5201:                     my $count = 0;
 5202:                     my $numcols = 4;
 5203:                     foreach my $cc (sort(@ccs)) {
 5204:                         my $notifyon;
 5205:                         my ($ccuname,$ccudom) = split(/:/,$cc);
 5206:                         if ($notified{$cc}) {
 5207:                             $notifyon = ' checked="checked" ';
 5208:                         }
 5209:                         if ($count && !$count%$numcols) {
 5210:                             $output .= &Apache::loncommon::end_data_table_row().
 5211:                                        &Apache::loncommon::start_data_table_row()
 5212:                         }
 5213:                         $output .= '<td><span class="LC_nobreak"><label>'.
 5214:                                    '<input type="checkbox" name="selfenroll_notify"'.$notifyon.' value="'.$cc.'" />'.
 5215:                                    &Apache::loncommon::plainname($ccuname,$ccudom).
 5216:                                    '</label></span></td>';
 5217:                         $count ++;
 5218:                     }
 5219:                     my $rem = $count%$numcols;
 5220:                     if ($rem) {
 5221:                         my $emptycols = $numcols - $rem;
 5222:                         for (my $i=0; $i<$emptycols; $i++) { 
 5223:                             $output .= '<td>&nbsp;</td>';
 5224:                         }
 5225:                     }
 5226:                     $output .= &Apache::loncommon::end_data_table_row().
 5227:                                &Apache::loncommon::end_data_table();
 5228:                 }
 5229:             } elsif ($item eq 'limit') {
 5230:                 my ($crslimit,$selflimit,$nolimit);
 5231:                 my $cid = $env{'request.course.id'};
 5232:                 my $currlim = $env{'course.'.$cid.'.internal.selfenroll_limit'};
 5233:                 my $currcap = $env{'course.'.$cid.'.internal.selfenroll_cap'};
 5234:                 $nolimit = ' checked="checked" ';
 5235:                 if ($currlim eq 'allstudents') {
 5236:                     $crslimit = ' checked="checked" ';
 5237:                     $selflimit = ' ';
 5238:                     $nolimit = ' ';
 5239:                 } elsif ($currlim eq 'selfenrolled') {
 5240:                     $crslimit = ' ';
 5241:                     $selflimit = ' checked="checked" ';
 5242:                     $nolimit = ' '; 
 5243:                 } else {
 5244:                     $crslimit = ' ';
 5245:                     $selflimit = ' ';
 5246:                 }
 5247:                 $output .= '<table><tr><td><label>'.
 5248:                            '<input type="radio" name="selfenroll_limit" value="none"'.$nolimit.'/>'.
 5249:                            &mt('No limit').'</label></td><td><label>'.
 5250:                            '<input type="radio" name="selfenroll_limit" value="allstudents"'.$crslimit.'/>'.
 5251:                            &mt('Limit by total students').'</label></td><td><label>'.
 5252:                            '<input type="radio" name="selfenroll_limit" value="selfenrolled"'.$selflimit.'/>'.
 5253:                            &mt('Limit by total self-enrolled students').
 5254:                            '</td></tr><tr>'.
 5255:                            '<td>&nbsp;</td><td colspan="2"><span class="LC_nobreak">'.
 5256:                            ('&nbsp;'x3).&mt('Maximum number allowed: ').
 5257:                            '<input type="text" name="selfenroll_cap" size = "5" value="'.$currcap.'" /></td></tr></table>';
 5258:             }
 5259:             $output .= &Apache::lonhtmlcommon::row_closure(1);
 5260:         }
 5261:     }
 5262:     $output .= &Apache::lonhtmlcommon::end_pick_box().
 5263:                '<br /><input type="button" name="selfenrollconf" value="'
 5264:                .&mt('Save').'" onclick="validate_types(this.form);" />'
 5265:                .'<input type="hidden" name="action" value="selfenroll" /></form>';
 5266:     $r->print($output);
 5267:     return;
 5268: }
 5269: 
 5270: sub visible_in_cat {
 5271:     my ($cdom,$cnum) = @_;
 5272:     my %domconf = &Apache::lonnet::get_dom('configuration',['coursecategories'],$cdom);
 5273:     my ($cathash,%settable,@vismsgs,$cansetvis);
 5274:     my %visactions = &Apache::lonlocal::texthash(
 5275:                    vis => 'Your course/community currently appears in the Course/Community Catalog for this domain.',
 5276:                    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.',
 5277:                    miss => 'Your course/community does not currently appear in the Course/Community Catalog for this domain.',
 5278:                    yous => 'You should remedy this if you plan to allow self-enrollment, otherwise students will have difficulty finding your course.',
 5279:                    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.',
 5280:                    make => 'Make any changes to self-enrollment settings below, click "Save", then take action to include the course in the Catalog:',
 5281:                    take => 'Take the following action to ensure the course appears in the Catalog:',
 5282:                    dc_unhide  => 'Ask a domain coordinator to change the "Exclude from course catalog" setting.',
 5283:                    dc_addinst => 'Ask a domain coordinator to enable display the catalog of "Official courses (with institutional codes)".',
 5284:                    dc_instcode => 'Ask a domain coordinator to assign an institutional code (if this is an official course).',
 5285:                    dc_catalog  => 'Ask a domain coordinator to enable or create at least one course category in the domain.',
 5286:                    dc_categories => 'Ask a domain coordinator to create a hierarchy of categories and sub categories for courses in the domain.',
 5287:                    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',
 5288:                    dc_addcat => 'Ask a domain coordinator to assign a category to the course.',
 5289:     );
 5290:     $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>"');
 5291:     $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>"');
 5292:     $visactions{'addcat'} = &mt('Use [_1]Categorize course[_2] to assign a category to the course.','"<a href="/adm/courseprefs?phase=display&actions=courseinfo">','</a>"');
 5293:     if (ref($domconf{'coursecategories'}) eq 'HASH') {
 5294:         if ($domconf{'coursecategories'}{'togglecats'} eq 'crs') {
 5295:             $settable{'togglecats'} = 1;
 5296:         }
 5297:         if ($domconf{'coursecategories'}{'categorize'} eq 'crs') {
 5298:             $settable{'categorize'} = 1;
 5299:         }
 5300:         $cathash = $domconf{'coursecategories'}{'cats'};
 5301:     }
 5302:     if ($settable{'togglecats'} && $settable{'categorize'}) {
 5303:         $cansetvis = &mt('You are able to both assign a course category and choose to exclude this course from the catalog.');   
 5304:     } elsif ($settable{'togglecats'}) {
 5305:         $cansetvis = &mt('You are able to choose to exclude this course from the catalog, but only a Domain Coordinator may assign a course category.'); 
 5306:     } elsif ($settable{'categorize'}) {
 5307:         $cansetvis = &mt('You may assign a course category, but only a Domain Coordinator may choose to exclude this course from the catalog.');  
 5308:     } else {
 5309:         $cansetvis = &mt('Only a Domain Coordinator may assign a course category or choose to exclude this course from the catalog.'); 
 5310:     }
 5311:      
 5312:     my %currsettings =
 5313:         &Apache::lonnet::get('environment',['hidefromcat','categories','internal.coursecode'],
 5314:                              $cdom,$cnum);
 5315:     my $visible = 0;
 5316:     if ($currsettings{'internal.coursecode'} ne '') {
 5317:         if (ref($domconf{'coursecategories'}) eq 'HASH') {
 5318:             $cathash = $domconf{'coursecategories'}{'cats'};
 5319:             if (ref($cathash) eq 'HASH') {
 5320:                 if ($cathash->{'instcode::0'} eq '') {
 5321:                     push(@vismsgs,'dc_addinst'); 
 5322:                 } else {
 5323:                     $visible = 1;
 5324:                 }
 5325:             } else {
 5326:                 $visible = 1;
 5327:             }
 5328:         } else {
 5329:             $visible = 1;
 5330:         }
 5331:     } else {
 5332:         if (ref($cathash) eq 'HASH') {
 5333:             if ($cathash->{'instcode::0'} ne '') {
 5334:                 push(@vismsgs,'dc_instcode');
 5335:             }
 5336:         } else {
 5337:             push(@vismsgs,'dc_instcode');
 5338:         }
 5339:     }
 5340:     if ($currsettings{'categories'} ne '') {
 5341:         my $cathash;
 5342:         if (ref($domconf{'coursecategories'}) eq 'HASH') {
 5343:             $cathash = $domconf{'coursecategories'}{'cats'};
 5344:             if (ref($cathash) eq 'HASH') {
 5345:                 if (keys(%{$cathash}) == 0) {
 5346:                     push(@vismsgs,'dc_catalog');
 5347:                 } elsif ((keys(%{$cathash}) == 1) && ($cathash->{'instcode::0'} ne '')) {
 5348:                     push(@vismsgs,'dc_categories');
 5349:                 } else {
 5350:                     my @currcategories = split('&',$currsettings{'categories'});
 5351:                     my $matched = 0;
 5352:                     foreach my $cat (@currcategories) {
 5353:                         if ($cathash->{$cat} ne '') {
 5354:                             $visible = 1;
 5355:                             $matched = 1;
 5356:                             last;
 5357:                         }
 5358:                     }
 5359:                     if (!$matched) {
 5360:                         if ($settable{'categorize'}) { 
 5361:                             push(@vismsgs,'chgcat');
 5362:                         } else {
 5363:                             push(@vismsgs,'dc_chgcat');
 5364:                         }
 5365:                     }
 5366:                 }
 5367:             }
 5368:         }
 5369:     } else {
 5370:         if (ref($cathash) eq 'HASH') {
 5371:             if ((keys(%{$cathash}) > 1) || 
 5372:                 (keys(%{$cathash}) == 1) && ($cathash->{'instcode::0'} eq '')) {
 5373:                 if ($settable{'categorize'}) {
 5374:                     push(@vismsgs,'addcat');
 5375:                 } else {
 5376:                     push(@vismsgs,'dc_addcat');
 5377:                 }
 5378:             }
 5379:         }
 5380:     }
 5381:     if ($currsettings{'hidefromcat'} eq 'yes') {
 5382:         $visible = 0;
 5383:         if ($settable{'togglecats'}) {
 5384:             unshift(@vismsgs,'unhide');
 5385:         } else {
 5386:             unshift(@vismsgs,'dc_unhide')
 5387:         }
 5388:     }
 5389:     return ($visible,$cansetvis,\@vismsgs,\%visactions);
 5390: }
 5391: 
 5392: sub new_selfenroll_dom_row {
 5393:     my ($newdom,$num) = @_;
 5394:     my $domdesc = &Apache::lonnet::domain($newdom);
 5395:     my $output;
 5396:     if ($domdesc ne '') {
 5397:         $output .= &Apache::loncommon::start_data_table_row()
 5398:                    .'<td valign="top"><span class="LC_nobreak">'.&mt('Domain:').'&nbsp;<b>'.$domdesc
 5399:                    .' ('.$newdom.')</b><input type="hidden" name="selfenroll_dom_'.$num
 5400:                    .'" value="'.$newdom.'" /></span><br />'
 5401:                    .'<span class="LC_nobreak"><label><input type="checkbox" '
 5402:                    .'name="selfenroll_activate" value="'.$num.'" '
 5403:                    .'onchange="javascript:update_types('
 5404:                    ."'selfenroll_activate','$num'".');" />'
 5405:                    .&mt('Activate').'</label></span></td>';
 5406:         my @currinsttypes;
 5407:         $output .= '<td>'.&mt('User types:').'<br />'
 5408:                    .&selfenroll_inst_types($num,$newdom,\@currinsttypes).'</td>'
 5409:                    .&Apache::loncommon::end_data_table_row();
 5410:     }
 5411:     return $output;
 5412: }
 5413: 
 5414: sub selfenroll_inst_types {
 5415:     my ($num,$currdom,$currinsttypes) = @_;
 5416:     my $output;
 5417:     my $numinrow = 4;
 5418:     my $count = 0;
 5419:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($currdom);
 5420:     my $othervalue = 'any';
 5421:     if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 5422:         if (keys(%{$usertypes}) > 0) {
 5423:             $othervalue = 'other';
 5424:         }
 5425:         $output .= '<table><tr>';
 5426:         foreach my $type (@{$types}) {
 5427:             if (($count > 0) && ($count%$numinrow == 0)) {
 5428:                 $output .= '</tr><tr>';
 5429:             }
 5430:             if (defined($usertypes->{$type})) {
 5431:                 my $esc_type = &escape($type);
 5432:                 $output .= '<td><span class="LC_nobreak"><label><input type = "checkbox" value="'.
 5433:                            $esc_type.'" ';
 5434:                 if (ref($currinsttypes) eq 'ARRAY') {
 5435:                     if (@{$currinsttypes} > 0) {
 5436:                         if (grep(/^any$/,@{$currinsttypes})) {
 5437:                             $output .= 'checked="checked"';
 5438:                         } elsif (grep(/^\Q$esc_type\E$/,@{$currinsttypes})) {
 5439:                             $output .= 'checked="checked"';
 5440:                         }
 5441:                     } else {
 5442:                         $output .= 'checked="checked"';
 5443:                     }
 5444:                 }
 5445:                 $output .= ' name="selfenroll_types_'.$num.'" />'.$usertypes->{$type}.'</label></span></td>';
 5446:             }
 5447:             $count ++;
 5448:         }
 5449:         if (($count > 0) && ($count%$numinrow == 0)) {
 5450:             $output .= '</tr><tr>';
 5451:         }
 5452:         $output .= '<td><span class="LC_nobreak"><label><input type = "checkbox" value="'.$othervalue.'"';
 5453:         if (ref($currinsttypes) eq 'ARRAY') {
 5454:             if (@{$currinsttypes} > 0) {
 5455:                 if (grep(/^any$/,@{$currinsttypes})) { 
 5456:                     $output .= ' checked="checked"';
 5457:                 } elsif ($othervalue eq 'other') {
 5458:                     if (grep(/^\Q$othervalue\E$/,@{$currinsttypes})) {
 5459:                         $output .= ' checked="checked"';
 5460:                     }
 5461:                 }
 5462:             } else {
 5463:                 $output .= ' checked="checked"';
 5464:             }
 5465:         } else {
 5466:             $output .= ' checked="checked"';
 5467:         }
 5468:         $output .= ' name="selfenroll_types_'.$num.'" />'.$othertitle.'</label></span></td></tr></table>';
 5469:     }
 5470:     return $output;
 5471: }
 5472: 
 5473: sub selfenroll_date_forms {
 5474:     my ($startform,$endform) = @_;
 5475:     my $output .= &Apache::lonhtmlcommon::start_pick_box()."\n".
 5476:                   &Apache::lonhtmlcommon::row_title(&mt('Start date'),
 5477:                                                     'LC_oddrow_value')."\n".
 5478:                   $startform."\n".
 5479:                   &Apache::lonhtmlcommon::row_closure(1).
 5480:                   &Apache::lonhtmlcommon::row_title(&mt('End date'),
 5481:                                                    'LC_oddrow_value')."\n".
 5482:                   $endform."\n".
 5483:                   &Apache::lonhtmlcommon::row_closure(1).
 5484:                   &Apache::lonhtmlcommon::end_pick_box();
 5485:     return $output;
 5486: }
 5487: 
 5488: sub print_userchangelogs_display {
 5489:     my ($r,$context,$permission) = @_;
 5490:     my $formname = 'rolelog';
 5491:     my ($username,$domain,$crstype,%roleslog);
 5492:     if ($context eq 'domain') {
 5493:         $domain = $env{'request.role.domain'};
 5494:         %roleslog=&Apache::lonnet::dump_dom('nohist_rolelog',$domain);
 5495:     } else {
 5496:         if ($context eq 'course') { 
 5497:             $domain = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5498:             $username = $env{'course.'.$env{'request.course.id'}.'.num'};
 5499:             $crstype = &Apache::loncommon::course_type();
 5500:             my %saveable_parameters = ('show' => 'scalar',);
 5501:             &Apache::loncommon::store_course_settings('roles_log',
 5502:                                                       \%saveable_parameters);
 5503:             &Apache::loncommon::restore_course_settings('roles_log',
 5504:                                                         \%saveable_parameters);
 5505:         } elsif ($context eq 'author') {
 5506:             $domain = $env{'user.domain'}; 
 5507:             if ($env{'request.role'} =~ m{^au\./\Q$domain\E/$}) {
 5508:                 $username = $env{'user.name'};
 5509:             } else {
 5510:                 undef($domain);
 5511:             }
 5512:         }
 5513:         if ($domain ne '' && $username ne '') { 
 5514:             %roleslog=&Apache::lonnet::dump('nohist_rolelog',$domain,$username);
 5515:         }
 5516:     }
 5517:     if ((keys(%roleslog))[0]=~/^error\:/) { undef(%roleslog); }
 5518: 
 5519:     # set defaults
 5520:     my $now = time();
 5521:     my $defstart = $now - (7*24*3600); #7 days ago 
 5522:     my %defaults = (
 5523:                      page               => '1',
 5524:                      show               => '10',
 5525:                      role               => 'any',
 5526:                      chgcontext         => 'any',
 5527:                      rolelog_start_date => $defstart,
 5528:                      rolelog_end_date   => $now,
 5529:                    );
 5530:     my $more_records = 0;
 5531: 
 5532:     # set current
 5533:     my %curr;
 5534:     foreach my $item ('show','page','role','chgcontext') {
 5535:         $curr{$item} = $env{'form.'.$item};
 5536:     }
 5537:     my ($startdate,$enddate) = 
 5538:         &Apache::lonuserutils::get_dates_from_form('rolelog_start_date','rolelog_end_date');
 5539:     $curr{'rolelog_start_date'} = $startdate;
 5540:     $curr{'rolelog_end_date'} = $enddate;
 5541:     foreach my $key (keys(%defaults)) {
 5542:         if ($curr{$key} eq '') {
 5543:             $curr{$key} = $defaults{$key};
 5544:         }
 5545:     }
 5546:     my (%whodunit,%changed,$version);
 5547:     ($version) = ($r->dir_config('lonVersion') =~ /^([\d\.]+)\-/);
 5548:     my ($minshown,$maxshown);
 5549:     $minshown = 1;
 5550:     my $count = 0;
 5551:     if ($curr{'show'} ne &mt('all')) { 
 5552:         $maxshown = $curr{'page'} * $curr{'show'};
 5553:         if ($curr{'page'} > 1) {
 5554:             $minshown = 1 + ($curr{'page'} - 1) * $curr{'show'};
 5555:         }
 5556:     }
 5557: 
 5558:     # Form Header
 5559:     $r->print('<form action="/adm/createuser" method="post" name="'.$formname.'">'.
 5560:               &role_display_filter($context,$formname,$domain,$username,\%curr,
 5561:                                    $version,$crstype));
 5562: 
 5563:     # Create navigation
 5564:     my ($nav_script,$nav_links) = &userlogdisplay_nav($formname,\%curr,$more_records);
 5565:     my $showntableheader = 0;
 5566: 
 5567:     # Table Header
 5568:     my $tableheader = 
 5569:         &Apache::loncommon::start_data_table_header_row()
 5570:        .'<th>&nbsp;</th>'
 5571:        .'<th>'.&mt('When').'</th>'
 5572:        .'<th>'.&mt('Who made the change').'</th>'
 5573:        .'<th>'.&mt('Changed User').'</th>'
 5574:        .'<th>'.&mt('Role').'</th>';
 5575: 
 5576:     if ($context eq 'course') {
 5577:         $tableheader .= '<th>'.&mt('Section').'</th>';
 5578:     }
 5579:     $tableheader .=
 5580:         '<th>'.&mt('Context').'</th>'
 5581:        .'<th>'.&mt('Start').'</th>'
 5582:        .'<th>'.&mt('End').'</th>'
 5583:        .&Apache::loncommon::end_data_table_header_row();
 5584: 
 5585:     # Display user change log data
 5586:     foreach my $id (sort { $roleslog{$b}{'exe_time'}<=>$roleslog{$a}{'exe_time'} } (keys(%roleslog))) {
 5587:         next if (($roleslog{$id}{'exe_time'} < $curr{'rolelog_start_date'}) ||
 5588:                  ($roleslog{$id}{'exe_time'} > $curr{'rolelog_end_date'}));
 5589:         if ($curr{'show'} ne &mt('all')) {
 5590:             if ($count >= $curr{'page'} * $curr{'show'}) {
 5591:                 $more_records = 1;
 5592:                 last;
 5593:             }
 5594:         }
 5595:         if ($curr{'role'} ne 'any') {
 5596:             next if ($roleslog{$id}{'logentry'}{'role'} ne $curr{'role'}); 
 5597:         }
 5598:         if ($curr{'chgcontext'} ne 'any') {
 5599:             if ($curr{'chgcontext'} eq 'selfenroll') {
 5600:                 next if (!$roleslog{$id}{'logentry'}{'selfenroll'});
 5601:             } else {
 5602:                 next if ($roleslog{$id}{'logentry'}{'context'} ne $curr{'chgcontext'});
 5603:             }
 5604:         }
 5605:         $count ++;
 5606:         next if ($count < $minshown);
 5607:         unless ($showntableheader) {
 5608:             $r->print($nav_script
 5609:                      .$nav_links
 5610:                      .&Apache::loncommon::start_data_table()
 5611:                      .$tableheader);
 5612:             $r->rflush();
 5613:             $showntableheader = 1;
 5614:         }
 5615:         if ($whodunit{$roleslog{$id}{'exe_uname'}.':'.$roleslog{$id}{'exe_udom'}} eq '') {
 5616:             $whodunit{$roleslog{$id}{'exe_uname'}.':'.$roleslog{$id}{'exe_udom'}} =
 5617:                 &Apache::loncommon::plainname($roleslog{$id}{'exe_uname'},$roleslog{$id}{'exe_udom'});
 5618:         }
 5619:         if ($changed{$roleslog{$id}{'uname'}.':'.$roleslog{$id}{'udom'}} eq '') {
 5620:             $changed{$roleslog{$id}{'uname'}.':'.$roleslog{$id}{'udom'}} =
 5621:                 &Apache::loncommon::plainname($roleslog{$id}{'uname'},$roleslog{$id}{'udom'});
 5622:         }
 5623:         my $sec = $roleslog{$id}{'logentry'}{'section'};
 5624:         if ($sec eq '') {
 5625:             $sec = &mt('None');
 5626:         }
 5627:         my ($rolestart,$roleend);
 5628:         if ($roleslog{$id}{'delflag'}) {
 5629:             $rolestart = &mt('deleted');
 5630:             $roleend = &mt('deleted');
 5631:         } else {
 5632:             $rolestart = $roleslog{$id}{'logentry'}{'start'};
 5633:             $roleend = $roleslog{$id}{'logentry'}{'end'};
 5634:             if ($rolestart eq '' || $rolestart == 0) {
 5635:                 $rolestart = &mt('No start date'); 
 5636:             } else {
 5637:                 $rolestart = &Apache::lonlocal::locallocaltime($rolestart);
 5638:             }
 5639:             if ($roleend eq '' || $roleend == 0) { 
 5640:                 $roleend = &mt('No end date');
 5641:             } else {
 5642:                 $roleend = &Apache::lonlocal::locallocaltime($roleend);
 5643:             }
 5644:         }
 5645:         my $chgcontext = $roleslog{$id}{'logentry'}{'context'};
 5646:         if ($roleslog{$id}{'logentry'}{'selfenroll'}) {
 5647:             $chgcontext = 'selfenroll';
 5648:         }
 5649:         my %lt = &rolechg_contexts($context,$crstype);
 5650:         if ($chgcontext ne '' && $lt{$chgcontext} ne '') {
 5651:             $chgcontext = $lt{$chgcontext};
 5652:         }
 5653:         $r->print(
 5654:             &Apache::loncommon::start_data_table_row()
 5655:            .'<td>'.$count.'</td>'
 5656:            .'<td>'.&Apache::lonlocal::locallocaltime($roleslog{$id}{'exe_time'}).'</td>'
 5657:            .'<td>'.$whodunit{$roleslog{$id}{'exe_uname'}.':'.$roleslog{$id}{'exe_udom'}}.'</td>'
 5658:            .'<td>'.$changed{$roleslog{$id}{'uname'}.':'.$roleslog{$id}{'udom'}}.'</td>'
 5659:            .'<td>'.&Apache::lonnet::plaintext($roleslog{$id}{'logentry'}{'role'},$crstype).'</td>');
 5660:         if ($context eq 'course') { 
 5661:             $r->print('<td>'.$sec.'</td>');
 5662:         }
 5663:         $r->print(
 5664:             '<td>'.$chgcontext.'</td>'
 5665:            .'<td>'.$rolestart.'</td>'
 5666:            .'<td>'.$roleend.'</td>'
 5667:            .&Apache::loncommon::end_data_table_row()."\n");
 5668:     }
 5669: 
 5670:     if ($showntableheader) { # Table footer, if content displayed above
 5671:         $r->print(&Apache::loncommon::end_data_table()
 5672:                  .$nav_links);
 5673:     } else { # No content displayed above
 5674:         $r->print('<p class="LC_info">'
 5675:                  .&mt('There are no records to display.')
 5676:                  .'</p>'
 5677:         );
 5678:     }
 5679: 
 5680:     # Form Footer
 5681:     $r->print( 
 5682:         '<input type="hidden" name="page" value="'.$curr{'page'}.'" />'
 5683:        .'<input type="hidden" name="action" value="changelogs" />'
 5684:        .'</form>');
 5685:     return;
 5686: }
 5687: 
 5688: sub userlogdisplay_nav {
 5689:     my ($formname,$curr,$more_records) = @_;
 5690:     my ($nav_script,$nav_links);
 5691:     if (ref($curr) eq 'HASH') {
 5692:         # Create Navigation:
 5693:         # Navigation Script
 5694:         $nav_script = <<"ENDSCRIPT";
 5695: <script type="text/javascript">
 5696: // <![CDATA[
 5697: function chgPage(caller) {
 5698:     if (caller == 'previous') {
 5699:         document.$formname.page.value --;
 5700:     }
 5701:     if (caller == 'next') {
 5702:         document.$formname.page.value ++;
 5703:     }
 5704:     document.$formname.submit();
 5705:     return;
 5706: }
 5707: // ]]>
 5708: </script>
 5709: ENDSCRIPT
 5710:         # Navigation Buttons
 5711:         $nav_links = '<p>';
 5712:         if (($curr->{'page'} > 1) || ($more_records)) {
 5713:             if ($curr->{'page'} > 1) {
 5714:                 $nav_links .= '<input type="button"'
 5715:                              .' onclick="javascript:chgPage('."'previous'".');"'
 5716:                              .' value="'.&mt('Previous [_1] changes',$curr->{'show'})
 5717:                              .'" /> ';
 5718:             }
 5719:             if ($more_records) {
 5720:                 $nav_links .= '<input type="button"'
 5721:                              .' onclick="javascript:chgPage('."'next'".');"'
 5722:                              .' value="'.&mt('Next [_1] changes',$curr->{'show'})
 5723:                              .'" />';
 5724:             }
 5725:         }
 5726:         $nav_links .= '</p>';
 5727:     }
 5728:     return ($nav_script,$nav_links);
 5729: }
 5730: 
 5731: sub role_display_filter {
 5732:     my ($context,$formname,$cdom,$cnum,$curr,$version,$crstype) = @_;
 5733:     my $lctype;
 5734:     if ($context eq 'course') {
 5735:         $lctype = lc($crstype);
 5736:     }
 5737:     my $nolink = 1;
 5738:     my $output = '<table><tr><td valign="top">'.
 5739:                  '<span class="LC_nobreak"><b>'.&mt('Changes/page:').'</b></span><br />'.
 5740:                  &Apache::lonmeta::selectbox('show',$curr->{'show'},undef,
 5741:                                               (&mt('all'),5,10,20,50,100,1000,10000)).
 5742:                  '</td><td>&nbsp;&nbsp;</td>';
 5743:     my $startform =
 5744:         &Apache::lonhtmlcommon::date_setter($formname,'rolelog_start_date',
 5745:                                             $curr->{'rolelog_start_date'},undef,
 5746:                                             undef,undef,undef,undef,undef,undef,$nolink);
 5747:     my $endform =
 5748:         &Apache::lonhtmlcommon::date_setter($formname,'rolelog_end_date',
 5749:                                             $curr->{'rolelog_end_date'},undef,
 5750:                                             undef,undef,undef,undef,undef,undef,$nolink);
 5751:     my %lt = &rolechg_contexts($context,$crstype);
 5752:     $output .= '<td valign="top"><b>'.&mt('Window during which changes occurred:').'</b><br />'.
 5753:                '<table><tr><td>'.&mt('After:').
 5754:                '</td><td>'.$startform.'</td></tr>'.
 5755:                '<tr><td>'.&mt('Before:').'</td>'.
 5756:                '<td>'.$endform.'</td></tr></table>'.
 5757:                '</td>'.
 5758:                '<td>&nbsp;&nbsp;</td>'.
 5759:                '<td valign="top"><b>'.&mt('Role:').'</b><br />'.
 5760:                '<select name="role"><option value="any"';
 5761:     if ($curr->{'role'} eq 'any') {
 5762:         $output .= ' selected="selected"';
 5763:     }
 5764:     $output .=  '>'.&mt('Any').'</option>'."\n";
 5765:     my @roles = &Apache::lonuserutils::roles_by_context($context,1,$crstype);
 5766:     foreach my $role (@roles) {
 5767:         my $plrole;
 5768:         if ($role eq 'cr') {
 5769:             $plrole = &mt('Custom Role');
 5770:         } else {
 5771:             $plrole=&Apache::lonnet::plaintext($role,$crstype);
 5772:         }
 5773:         my $selstr = '';
 5774:         if ($role eq $curr->{'role'}) {
 5775:             $selstr = ' selected="selected"';
 5776:         }
 5777:         $output .= '  <option value="'.$role.'"'.$selstr.'>'.$plrole.'</option>';
 5778:     }
 5779:     $output .= '</select></td>'.
 5780:                '<td>&nbsp;&nbsp;</td>'.
 5781:                '<td valign="top"><b>'.
 5782:                &mt('Context:').'</b><br /><select name="chgcontext">';
 5783:     my @posscontexts;
 5784:     if ($context eq 'course') {
 5785:         @posscontexts = ('any','auto','updatenow','createcourse','course','domain','selfenroll','requestcourses');
 5786:     } elsif ($context eq 'domain') {
 5787:         @posscontexts = ('any','domain','requestauthor','domconfig','server');
 5788:     } else {
 5789:         @posscontexts = ('any','author','domain');
 5790:     } 
 5791:     foreach my $chgtype (@posscontexts) {
 5792:         my $selstr = '';
 5793:         if ($curr->{'chgcontext'} eq $chgtype) {
 5794:             $selstr = ' selected="selected"';
 5795:         }
 5796:         if ($context eq 'course') {
 5797:             if (($chgtype eq 'auto') || ($chgtype eq 'updatenow')) {
 5798:                 next if (!&Apache::lonnet::auto_run($cnum,$cdom));
 5799:             }
 5800:         }
 5801:         $output .= '<option value="'.$chgtype.'"'.$selstr.'>'.$lt{$chgtype}.'</option>'."\n";
 5802:     }
 5803:     $output .= '</select></td>'
 5804:               .'</tr></table>';
 5805: 
 5806:     # Update Display button
 5807:     $output .= '<p>'
 5808:               .'<input type="submit" value="'.&mt('Update Display').'" />'
 5809:               .'</p>';
 5810: 
 5811:     # Server version info
 5812:     my $needsrev = '2.11.0';
 5813:     if ($context eq 'course') {
 5814:         $needsrev = '2.7.0';
 5815:     }
 5816:     
 5817:     $output .= '<p class="LC_info">'
 5818:               .&mt('Only changes made from servers running LON-CAPA [_1] or later are displayed.'
 5819:                   ,$needsrev);
 5820:     if ($version) {
 5821:         $output .= ' '.&mt('This LON-CAPA server is version [_1]',$version);
 5822:     }
 5823:     $output .= '</p><hr />';
 5824:     return $output;
 5825: }
 5826: 
 5827: sub rolechg_contexts {
 5828:     my ($context,$crstype) = @_;
 5829:     my %lt;
 5830:     if ($context eq 'course') {
 5831:         %lt = &Apache::lonlocal::texthash (
 5832:                                              any          => 'Any',
 5833:                                              auto         => 'Automated enrollment',
 5834:                                              updatenow    => 'Roster Update',
 5835:                                              createcourse => 'Course Creation',
 5836:                                              course       => 'User Management in course',
 5837:                                              domain       => 'User Management in domain',
 5838:                                              selfenroll   => 'Self-enrolled',
 5839:                                              requestcourses => 'Course Request',
 5840:                                          );
 5841:         if ($crstype eq 'Community') {
 5842:             $lt{'createcourse'} = &mt('Community Creation');
 5843:             $lt{'course'} = &mt('User Management in community');
 5844:             $lt{'requestcourses'} = &mt('Community Request');
 5845:         }
 5846:     } elsif ($context eq 'domain') {
 5847:         %lt = &Apache::lonlocal::texthash (
 5848:                                              any           => 'Any',
 5849:                                              domain        => 'User Management in domain',
 5850:                                              requestauthor => 'Authoring Request',
 5851:                                              server        => 'Command line script (DC role)',
 5852:                                              domconfig     => 'Self-enrolled',
 5853:                                          );
 5854:     } else {
 5855:         %lt = &Apache::lonlocal::texthash (
 5856:                                              any    => 'Any',
 5857:                                              domain => 'User Management in domain',
 5858:                                              author => 'User Management by author',
 5859:                                          );
 5860:     } 
 5861:     return %lt;
 5862: }
 5863: 
 5864: #-------------------------------------------------- functions for &phase_two
 5865: sub user_search_result {
 5866:     my ($context,$srch) = @_;
 5867:     my %allhomes;
 5868:     my %inst_matches;
 5869:     my %srch_results;
 5870:     my ($response,$currstate,$forcenewuser,$dirsrchres);
 5871:     $srch->{'srchterm'} =~ s/\s+/ /g;
 5872:     if ($srch->{'srchby'} !~ /^(uname|lastname|lastfirst)$/) {
 5873:         $response = &mt('Invalid search.');
 5874:     }
 5875:     if ($srch->{'srchin'} !~ /^(crs|dom|alc|instd)$/) {
 5876:         $response = &mt('Invalid search.');
 5877:     }
 5878:     if ($srch->{'srchtype'} !~ /^(exact|contains|begins)$/) {
 5879:         $response = &mt('Invalid search.');
 5880:     }
 5881:     if ($srch->{'srchterm'} eq '') {
 5882:         $response = &mt('You must enter a search term.');
 5883:     }
 5884:     if ($srch->{'srchterm'} =~ /^\s+$/) {
 5885:         $response = &mt('Your search term must contain more than just spaces.');
 5886:     }
 5887:     if (($srch->{'srchin'} eq 'dom') || ($srch->{'srchin'} eq 'instd')) {
 5888:         if (($srch->{'srchdomain'} eq '') || 
 5889: 	    ! (&Apache::lonnet::domain($srch->{'srchdomain'}))) {
 5890:             $response = &mt('You must specify a valid domain when searching in a domain or institutional directory.')
 5891:         }
 5892:     }
 5893:     if (($srch->{'srchin'} eq 'dom') || ($srch->{'srchin'} eq 'crs') ||
 5894:         ($srch->{'srchin'} eq 'alc')) {
 5895:         if ($srch->{'srchby'} eq 'uname') {
 5896:             my $unamecheck = $srch->{'srchterm'};
 5897:             if ($srch->{'srchtype'} eq 'contains') {
 5898:                 if ($unamecheck !~ /^\w/) {
 5899:                     $unamecheck = 'a'.$unamecheck; 
 5900:                 }
 5901:             }
 5902:             if ($unamecheck !~ /^$match_username$/) {
 5903:                 $response = &mt('You must specify a valid username. Only the following are allowed: letters numbers - . @');
 5904:             }
 5905:         }
 5906:     }
 5907:     if ($response ne '') {
 5908:         $response = '<span class="LC_warning">'.$response.'</span>';
 5909:     }
 5910:     if ($srch->{'srchin'} eq 'instd') {
 5911:         my $instd_chk = &directorysrch_check($srch);
 5912:         if ($instd_chk ne 'ok') {
 5913:             $response = '<span class="LC_warning">'.$instd_chk.'</span>'.
 5914:                         '<br />'.&mt('You may want to search in the LON-CAPA domain instead of the institutional directory.').'<br /><br />';
 5915:         }
 5916:     }
 5917:     if ($response ne '') {
 5918:         return ($currstate,$response);
 5919:     }
 5920:     if ($srch->{'srchby'} eq 'uname') {
 5921:         if (($srch->{'srchin'} eq 'dom') || ($srch->{'srchin'} eq 'crs')) {
 5922:             if ($env{'form.forcenew'}) {
 5923:                 if ($srch->{'srchdomain'} ne $env{'request.role.domain'}) {
 5924:                     my $uhome=&Apache::lonnet::homeserver($srch->{'srchterm'},$srch->{'srchdomain'});
 5925:                     if ($uhome eq 'no_host') {
 5926:                         my $domdesc = &Apache::lonnet::domain($env{'request.role.domain'},'description');
 5927:                         my $showdom = &display_domain_info($env{'request.role.domain'});
 5928:                         $response = &mt('New users can only be created in the domain to which your current role belongs - [_1].',$showdom);
 5929:                     } else {
 5930:                         $currstate = 'modify';
 5931:                     }
 5932:                 } else {
 5933:                     $currstate = 'modify';
 5934:                 }
 5935:             } else {
 5936:                 if ($srch->{'srchin'} eq 'dom') {
 5937:                     if ($srch->{'srchtype'} eq 'exact') {
 5938:                         my $uhome=&Apache::lonnet::homeserver($srch->{'srchterm'},$srch->{'srchdomain'});
 5939:                         if ($uhome eq 'no_host') {
 5940:                             ($currstate,$response,$forcenewuser) =
 5941:                                 &build_search_response($context,$srch,%srch_results);
 5942:                         } else {
 5943:                             $currstate = 'modify';
 5944:                             my $uname = $srch->{'srchterm'};
 5945:                             my $udom = $srch->{'srchdomain'};
 5946:                             $srch_results{$uname.':'.$udom} =
 5947:                                 { &Apache::lonnet::get('environment',
 5948:                                                        ['firstname',
 5949:                                                         'lastname',
 5950:                                                         'permanentemail'],
 5951:                                                          $udom,$uname)
 5952:                                 };
 5953:                         }
 5954:                     } else {
 5955:                         %srch_results = &Apache::lonnet::usersearch($srch);
 5956:                         ($currstate,$response,$forcenewuser) =
 5957:                             &build_search_response($context,$srch,%srch_results);
 5958:                     }
 5959:                 } else {
 5960:                     my $courseusers = &get_courseusers();
 5961:                     if ($srch->{'srchtype'} eq 'exact') {
 5962:                         if (exists($courseusers->{$srch->{'srchterm'}.':'.$srch->{'srchdomain'}})) {
 5963:                             $currstate = 'modify';
 5964:                         } else {
 5965:                             ($currstate,$response,$forcenewuser) =
 5966:                                 &build_search_response($context,$srch,%srch_results);
 5967:                         }
 5968:                     } else {
 5969:                         foreach my $user (keys(%$courseusers)) {
 5970:                             my ($cuname,$cudomain) = split(/:/,$user);
 5971:                             if ($cudomain eq $srch->{'srchdomain'}) {
 5972:                                 my $matched = 0;
 5973:                                 if ($srch->{'srchtype'} eq 'begins') {
 5974:                                     if ($cuname =~ /^\Q$srch->{'srchterm'}\E/i) {
 5975:                                         $matched = 1;
 5976:                                     }
 5977:                                 } else {
 5978:                                     if ($cuname =~ /\Q$srch->{'srchterm'}\E/i) {
 5979:                                         $matched = 1;
 5980:                                     }
 5981:                                 }
 5982:                                 if ($matched) {
 5983:                                     $srch_results{$user} = 
 5984: 					{&Apache::lonnet::get('environment',
 5985: 							     ['firstname',
 5986: 							      'lastname',
 5987: 							      'permanentemail'],
 5988: 							      $cudomain,$cuname)};
 5989:                                 }
 5990:                             }
 5991:                         }
 5992:                         ($currstate,$response,$forcenewuser) =
 5993:                             &build_search_response($context,$srch,%srch_results);
 5994:                     }
 5995:                 }
 5996:             }
 5997:         } elsif ($srch->{'srchin'} eq 'alc') {
 5998:             $currstate = 'query';
 5999:         } elsif ($srch->{'srchin'} eq 'instd') {
 6000:             ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query($srch);
 6001:             if ($dirsrchres eq 'ok') {
 6002:                 ($currstate,$response,$forcenewuser) = 
 6003:                     &build_search_response($context,$srch,%srch_results);
 6004:             } else {
 6005:                 my $showdom = &display_domain_info($srch->{'srchdomain'});
 6006:                 $response = '<span class="LC_warning">'.
 6007:                     &mt('Institutional directory search is not available in domain: [_1]',$showdom).
 6008:                     '</span><br />'.
 6009:                     &mt('You may want to search in the LON-CAPA domain instead of the institutional directory.').
 6010:                     '<br /><br />'; 
 6011:             }
 6012:         }
 6013:     } else {
 6014:         if ($srch->{'srchin'} eq 'dom') {
 6015:             %srch_results = &Apache::lonnet::usersearch($srch);
 6016:             ($currstate,$response,$forcenewuser) = 
 6017:                 &build_search_response($context,$srch,%srch_results); 
 6018:         } elsif ($srch->{'srchin'} eq 'crs') {
 6019:             my $courseusers = &get_courseusers(); 
 6020:             foreach my $user (keys(%$courseusers)) {
 6021:                 my ($uname,$udom) = split(/:/,$user);
 6022:                 my %names = &Apache::loncommon::getnames($uname,$udom);
 6023:                 my %emails = &Apache::loncommon::getemails($uname,$udom);
 6024:                 if ($srch->{'srchby'} eq 'lastname') {
 6025:                     if ((($srch->{'srchtype'} eq 'exact') && 
 6026:                          ($names{'lastname'} eq $srch->{'srchterm'})) || 
 6027:                         (($srch->{'srchtype'} eq 'begins') &&
 6028:                          ($names{'lastname'} =~ /^\Q$srch->{'srchterm'}\E/i)) ||
 6029:                         (($srch->{'srchtype'} eq 'contains') &&
 6030:                          ($names{'lastname'} =~ /\Q$srch->{'srchterm'}\E/i))) {
 6031:                         $srch_results{$user} = {firstname => $names{'firstname'},
 6032:                                             lastname => $names{'lastname'},
 6033:                                             permanentemail => $emails{'permanentemail'},
 6034:                                            };
 6035:                     }
 6036:                 } elsif ($srch->{'srchby'} eq 'lastfirst') {
 6037:                     my ($srchlast,$srchfirst) = split(/,/,$srch->{'srchterm'});
 6038:                     $srchlast =~ s/\s+$//;
 6039:                     $srchfirst =~ s/^\s+//;
 6040:                     if ($srch->{'srchtype'} eq 'exact') {
 6041:                         if (($names{'lastname'} eq $srchlast) &&
 6042:                             ($names{'firstname'} eq $srchfirst)) {
 6043:                             $srch_results{$user} = {firstname => $names{'firstname'},
 6044:                                                 lastname => $names{'lastname'},
 6045:                                                 permanentemail => $emails{'permanentemail'},
 6046: 
 6047:                                            };
 6048:                         }
 6049:                     } elsif ($srch->{'srchtype'} eq 'begins') {
 6050:                         if (($names{'lastname'} =~ /^\Q$srchlast\E/i) &&
 6051:                             ($names{'firstname'} =~ /^\Q$srchfirst\E/i)) {
 6052:                             $srch_results{$user} = {firstname => $names{'firstname'},
 6053:                                                 lastname => $names{'lastname'},
 6054:                                                 permanentemail => $emails{'permanentemail'},
 6055:                                                };
 6056:                         }
 6057:                     } else {
 6058:                         if (($names{'lastname'} =~ /\Q$srchlast\E/i) && 
 6059:                             ($names{'firstname'} =~ /\Q$srchfirst\E/i)) {
 6060:                             $srch_results{$user} = {firstname => $names{'firstname'},
 6061:                                                 lastname => $names{'lastname'},
 6062:                                                 permanentemail => $emails{'permanentemail'},
 6063:                                                };
 6064:                         }
 6065:                     }
 6066:                 }
 6067:             }
 6068:             ($currstate,$response,$forcenewuser) = 
 6069:                 &build_search_response($context,$srch,%srch_results); 
 6070:         } elsif ($srch->{'srchin'} eq 'alc') {
 6071:             $currstate = 'query';
 6072:         } elsif ($srch->{'srchin'} eq 'instd') {
 6073:             ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query($srch); 
 6074:             if ($dirsrchres eq 'ok') {
 6075:                 ($currstate,$response,$forcenewuser) = 
 6076:                     &build_search_response($context,$srch,%srch_results);
 6077:             } else {
 6078:                 my $showdom = &display_domain_info($srch->{'srchdomain'});                $response = '<span class="LC_warning">'.
 6079:                     &mt('Institutional directory search is not available in domain: [_1]',$showdom).
 6080:                     '</span><br />'.
 6081:                     &mt('You may want to search in the LON-CAPA domain instead of the institutional directory.').
 6082:                     '<br /><br />';
 6083:             }
 6084:         }
 6085:     }
 6086:     return ($currstate,$response,$forcenewuser,\%srch_results);
 6087: }
 6088: 
 6089: sub directorysrch_check {
 6090:     my ($srch) = @_;
 6091:     my $can_search = 0;
 6092:     my $response;
 6093:     my %dom_inst_srch = &Apache::lonnet::get_dom('configuration',
 6094:                                              ['directorysrch'],$srch->{'srchdomain'});
 6095:     my $showdom = &display_domain_info($srch->{'srchdomain'});
 6096:     if (ref($dom_inst_srch{'directorysrch'}) eq 'HASH') {
 6097:         if (!$dom_inst_srch{'directorysrch'}{'available'}) {
 6098:             return &mt('Institutional directory search is not available in domain: [_1]',$showdom); 
 6099:         }
 6100:         if ($dom_inst_srch{'directorysrch'}{'localonly'}) {
 6101:             if ($env{'request.role.domain'} ne $srch->{'srchdomain'}) {
 6102:                 return &mt('Institutional directory search in domain: [_1] is only allowed for users with a current role in the domain.',$showdom); 
 6103:             }
 6104:             my @usertypes = split(/:/,$env{'environment.inststatus'});
 6105:             if (!@usertypes) {
 6106:                 push(@usertypes,'default');
 6107:             }
 6108:             if (ref($dom_inst_srch{'directorysrch'}{'cansearch'}) eq 'ARRAY') {
 6109:                 foreach my $type (@usertypes) {
 6110:                     if (grep(/^\Q$type\E$/,@{$dom_inst_srch{'directorysrch'}{'cansearch'}})) {
 6111:                         $can_search = 1;
 6112:                         last;
 6113:                     }
 6114:                 }
 6115:             }
 6116:             if (!$can_search) {
 6117:                 my ($insttypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($srch->{'srchdomain'});
 6118:                 my @longtypes; 
 6119:                 foreach my $item (@usertypes) {
 6120:                     if (defined($insttypes->{$item})) { 
 6121:                         push (@longtypes,$insttypes->{$item});
 6122:                     } elsif ($item eq 'default') {
 6123:                         push (@longtypes,&mt('other')); 
 6124:                     }
 6125:                 }
 6126:                 my $insttype_str = join(', ',@longtypes); 
 6127:                 return &mt('Institutional directory search in domain: [_1] is not available to your user type: ',$showdom).$insttype_str;
 6128:             }
 6129:         } else {
 6130:             $can_search = 1;
 6131:         }
 6132:     } else {
 6133:         return &mt('Institutional directory search has not been configured for domain: [_1]',$showdom);
 6134:     }
 6135:     my %longtext = &Apache::lonlocal::texthash (
 6136:                        uname     => 'username',
 6137:                        lastfirst => 'last name, first name',
 6138:                        lastname  => 'last name',
 6139:                        contains  => 'contains',
 6140:                        exact     => 'as exact match to',
 6141:                        begins    => 'begins with',
 6142:                    );
 6143:     if ($can_search) {
 6144:         if (ref($dom_inst_srch{'directorysrch'}{'searchby'}) eq 'ARRAY') {
 6145:             if (!grep(/^\Q$srch->{'srchby'}\E$/,@{$dom_inst_srch{'directorysrch'}{'searchby'}})) {
 6146:                 return &mt('Institutional directory search in domain: [_1] is not available for searching by "[_2]"',$showdom,$longtext{$srch->{'srchby'}});
 6147:             }
 6148:         } else {
 6149:             return &mt('Institutional directory search in domain: [_1] is not available.', $showdom);
 6150:         }
 6151:     }
 6152:     if ($can_search) {
 6153:         if (ref($dom_inst_srch{'directorysrch'}{'searchtypes'}) eq 'ARRAY') {
 6154:             if (grep(/^\Q$srch->{'srchtype'}\E/,@{$dom_inst_srch{'directorysrch'}{'searchtypes'}})) {
 6155:                 return 'ok';
 6156:             } else {
 6157:                 return &mt('Institutional directory search in domain [_1] is not available for the requested search type: "[_2]"',$showdom,$longtext{$srch->{'srchtype'}});
 6158:             }
 6159:         } else {
 6160:             if ((($dom_inst_srch{'directorysrch'}{'searchtypes'} eq 'specify') &&
 6161:                  ($srch->{'srchtype'} eq 'exact' || $srch->{'srchtype'} eq 'contains')) ||
 6162:                 ($dom_inst_srch{'directorysrch'}{'searchtypes'} eq $srch->{'srchtype'})) {
 6163:                 return 'ok';
 6164:             } else {
 6165:                 return &mt('Institutional directory search in domain [_1] is not available for the requested search type: "[_2]"',$showdom,$longtext{$srch->{'srchtype'}});
 6166:             }
 6167:         }
 6168:     }
 6169: }
 6170: 
 6171: sub get_courseusers {
 6172:     my %advhash;
 6173:     my $classlist = &Apache::loncoursedata::get_classlist();
 6174:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles();
 6175:     foreach my $role (sort(keys(%coursepersonnel))) {
 6176:         foreach my $user (split(/\,/,$coursepersonnel{$role})) {
 6177: 	    if (!exists($classlist->{$user})) {
 6178: 		$classlist->{$user} = [];
 6179: 	    }
 6180:         }
 6181:     }
 6182:     return $classlist;
 6183: }
 6184: 
 6185: sub build_search_response {
 6186:     my ($context,$srch,%srch_results) = @_;
 6187:     my ($currstate,$response,$forcenewuser);
 6188:     my %names = (
 6189:           'uname'     => 'username',
 6190:           'lastname'  => 'last name',
 6191:           'lastfirst' => 'last name, first name',
 6192:           'crs'       => 'this course',
 6193:           'dom'       => 'LON-CAPA domain',
 6194:           'instd'     => 'the institutional directory for domain',
 6195:     );
 6196: 
 6197:     my %single = (
 6198:                    begins   => 'A match',
 6199:                    contains => 'A match',
 6200:                    exact    => 'An exact match',
 6201:                  );
 6202:     my %nomatch = (
 6203:                    begins   => 'No match',
 6204:                    contains => 'No match',
 6205:                    exact    => 'No exact match',
 6206:                   );
 6207:     if (keys(%srch_results) > 1) {
 6208:         $currstate = 'select';
 6209:     } else {
 6210:         if (keys(%srch_results) == 1) {
 6211:             $currstate = 'modify';
 6212:             $response = &mt("$single{$srch->{'srchtype'}} was found for the $names{$srch->{'srchby'}} ([_1]) in $names{$srch->{'srchin'}}.",$srch->{'srchterm'});
 6213:             if ($srch->{'srchin'} eq 'dom' || $srch->{'srchin'} eq 'instd') {
 6214:                 $response .= ': '.&display_domain_info($srch->{'srchdomain'});
 6215:             }
 6216:         } else { # Search has nothing found. Prepare message to user.
 6217:             $response = '<span class="LC_warning">';
 6218:             if ($srch->{'srchin'} eq 'dom' || $srch->{'srchin'} eq 'instd') {
 6219:                 $response .= &mt("$nomatch{$srch->{'srchtype'}} found for the $names{$srch->{'srchby'}} [_1] in $names{$srch->{'srchin'}}: [_2]",
 6220:                                  '<b>'.$srch->{'srchterm'}.'</b>',
 6221:                                  &display_domain_info($srch->{'srchdomain'}));
 6222:             } else {
 6223:                 $response .= &mt("$nomatch{$srch->{'srchtype'}} found for the $names{$srch->{'srchby'}} [_1] in $names{$srch->{'srchin'}}.",
 6224:                                  '<b>'.$srch->{'srchterm'}.'</b>');
 6225:             }
 6226:             $response .= '</span>';
 6227: 
 6228:             if ($srch->{'srchin'} ne 'alc') {
 6229:                 $forcenewuser = 1;
 6230:                 my $cansrchinst = 0; 
 6231:                 if ($srch->{'srchdomain'}) {
 6232:                     my %domconfig = &Apache::lonnet::get_dom('configuration',['directorysrch'],$srch->{'srchdomain'});
 6233:                     if (ref($domconfig{'directorysrch'}) eq 'HASH') {
 6234:                         if ($domconfig{'directorysrch'}{'available'}) {
 6235:                             $cansrchinst = 1;
 6236:                         } 
 6237:                     }
 6238:                 }
 6239:                 if ((($srch->{'srchby'} eq 'lastfirst') || 
 6240:                      ($srch->{'srchby'} eq 'lastname')) &&
 6241:                     ($srch->{'srchin'} eq 'dom')) {
 6242:                     if ($cansrchinst) {
 6243:                         $response .= '<br />'.&mt('You may want to broaden your search to a search of the institutional directory for the domain.');
 6244:                     }
 6245:                 }
 6246:                 if ($srch->{'srchin'} eq 'crs') {
 6247:                     $response .= '<br />'.&mt('You may want to broaden your search to the selected LON-CAPA domain.');
 6248:                 }
 6249:             }
 6250:             my $createdom = $env{'request.role.domain'};
 6251:             if ($context eq 'requestcrs') {
 6252:                 if ($env{'form.coursedom'} ne '') {
 6253:                     $createdom = $env{'form.coursedom'};
 6254:                 }
 6255:             }
 6256:             if (!($srch->{'srchby'} eq 'uname' && $srch->{'srchin'} eq 'dom' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchdomain'} eq $createdom)) {
 6257:                 my $cancreate =
 6258:                     &Apache::lonuserutils::can_create_user($createdom,$context);
 6259:                 my $targetdom = '<span class="LC_cusr_emph">'.$createdom.'</span>';
 6260:                 if ($cancreate) {
 6261:                     my $showdom = &display_domain_info($createdom); 
 6262:                     $response .= '<br /><br />'
 6263:                                 .'<b>'.&mt('To add a new user:').'</b>'
 6264:                                 .'<br />';
 6265:                     if ($context eq 'requestcrs') {
 6266:                         $response .= &mt("(You can only define new users in the new course's domain - [_1])",$targetdom);
 6267:                     } else {
 6268:                         $response .= &mt("(You can only create new users in your current role's domain - [_1])",$targetdom);
 6269:                     }
 6270:                     $response .='<ul><li>'
 6271:                                 .&mt("Set 'Domain/institution to search' to: [_1]",'<span class="LC_cusr_emph">'.$showdom.'</span>')
 6272:                                 .'</li><li>'
 6273:                                 .&mt("Set 'Search criteria' to: [_1]username is ..... in selected LON-CAPA domain[_2]",'<span class="LC_cusr_emph">','</span>')
 6274:                                 .'</li><li>'
 6275:                                 .&mt('Provide the proposed username')
 6276:                                 .'</li><li>'
 6277:                                 .&mt("Click 'Search'")
 6278:                                 .'</li></ul><br />';
 6279:                 } else {
 6280:                     my $helplink = ' href="javascript:helpMenu('."'display'".')"';
 6281:                     $response .= '<br /><br />';
 6282:                     if ($context eq 'requestcrs') {
 6283:                         $response .= &mt("You are not authorized to define new users in the new course's domain - [_1].",$targetdom);
 6284:                     } else {
 6285:                         $response .= &mt("You are not authorized to create new users in your current role's domain - [_1].",$targetdom);
 6286:                     }
 6287:                     $response .= '<br />'
 6288:                                  .&mt('Please contact the [_1]helpdesk[_2] if you need to create a new user.'
 6289:                                     ,' <a'.$helplink.'>'
 6290:                                     ,'</a>')
 6291:                                  .'<br /><br />';
 6292:                 }
 6293:             }
 6294:         }
 6295:     }
 6296:     return ($currstate,$response,$forcenewuser);
 6297: }
 6298: 
 6299: sub display_domain_info {
 6300:     my ($dom) = @_;
 6301:     my $output = $dom;
 6302:     if ($dom ne '') { 
 6303:         my $domdesc = &Apache::lonnet::domain($dom,'description');
 6304:         if ($domdesc ne '') {
 6305:             $output .= ' <span class="LC_cusr_emph">('.$domdesc.')</span>';
 6306:         }
 6307:     }
 6308:     return $output;
 6309: }
 6310: 
 6311: sub crumb_utilities {
 6312:     my %elements = (
 6313:        crtuser => {
 6314:            srchterm => 'text',
 6315:            srchin => 'selectbox',
 6316:            srchby => 'selectbox',
 6317:            srchtype => 'selectbox',
 6318:            srchdomain => 'selectbox',
 6319:        },
 6320:        crtusername => {
 6321:            srchterm => 'text',
 6322:            srchdomain => 'selectbox',
 6323:        },
 6324:        docustom => {
 6325:            rolename => 'selectbox',
 6326:            newrolename => 'textbox',
 6327:        },
 6328:        studentform => {
 6329:            srchterm => 'text',
 6330:            srchin => 'selectbox',
 6331:            srchby => 'selectbox',
 6332:            srchtype => 'selectbox',
 6333:            srchdomain => 'selectbox',
 6334:        },
 6335:     );
 6336: 
 6337:     my $jsback .= qq|
 6338: function backPage(formname,prevphase,prevstate) {
 6339:     if (typeof prevphase == 'undefined') {
 6340:         formname.phase.value = '';
 6341:     }
 6342:     else {  
 6343:         formname.phase.value = prevphase;
 6344:     }
 6345:     if (typeof prevstate == 'undefined') {
 6346:         formname.currstate.value = '';
 6347:     }
 6348:     else {
 6349:         formname.currstate.value = prevstate;
 6350:     }
 6351:     formname.submit();
 6352: }
 6353: |;
 6354:     return ($jsback,\%elements);
 6355: }
 6356: 
 6357: sub course_level_table {
 6358:     my (%inccourses) = @_;
 6359:     my $table = '';
 6360: # Custom Roles?
 6361: 
 6362:     my %customroles=&Apache::lonuserutils::my_custom_roles();
 6363:     my %lt=&Apache::lonlocal::texthash(
 6364:             'exs'  => "Existing sections",
 6365:             'new'  => "Define new section",
 6366:             'ssd'  => "Set Start Date",
 6367:             'sed'  => "Set End Date",
 6368:             'crl'  => "Course Level",
 6369:             'act'  => "Activate",
 6370:             'rol'  => "Role",
 6371:             'ext'  => "Extent",
 6372:             'grs'  => "Section",
 6373:             'sta'  => "Start",
 6374:             'end'  => "End"
 6375:     );
 6376: 
 6377:     foreach my $protectedcourse (sort(keys(%inccourses))) {
 6378: 	my $thiscourse=$protectedcourse;
 6379: 	$thiscourse=~s:_:/:g;
 6380: 	my %coursedata=&Apache::lonnet::coursedescription($thiscourse);
 6381:         my $isowner = &is_courseowner($protectedcourse,$coursedata{'internal.courseowner'});
 6382: 	my $area=$coursedata{'description'};
 6383:         my $crstype=$coursedata{'type'};
 6384: 	if (!defined($area)) { $area=&mt('Unavailable course').': '.$protectedcourse; }
 6385: 	my ($domain,$cnum)=split(/\//,$thiscourse);
 6386:         my %sections_count;
 6387:         if (defined($env{'request.course.id'})) {
 6388:             if ($env{'request.course.id'} eq $domain.'_'.$cnum) {
 6389:                 %sections_count = 
 6390: 		    &Apache::loncommon::get_sections($domain,$cnum);
 6391:             }
 6392:         }
 6393:         my @roles = &Apache::lonuserutils::roles_by_context('course','',$crstype);
 6394: 	foreach my $role (@roles) {
 6395:             my $plrole=&Apache::lonnet::plaintext($role,$crstype);
 6396: 	    if ((&Apache::lonnet::allowed('c'.$role,$thiscourse)) ||
 6397:                 ((($role eq 'cc') || ($role eq 'co')) && ($isowner))) {
 6398:                 $table .= &course_level_row($protectedcourse,$role,$area,$domain,
 6399:                                             $plrole,\%sections_count,\%lt);
 6400:             } elsif ($env{'request.course.sec'} ne '') {
 6401:                 if (&Apache::lonnet::allowed('c'.$role,$thiscourse.'/'.
 6402:                                              $env{'request.course.sec'})) {
 6403:                     $table .= &course_level_row($protectedcourse,$role,$area,$domain,
 6404:                                                 $plrole,\%sections_count,\%lt);
 6405:                 }
 6406:             }
 6407:         }
 6408:         if (&Apache::lonnet::allowed('ccr',$thiscourse)) {
 6409:             foreach my $cust (sort(keys(%customroles))) {
 6410:                 next if ($crstype eq 'Community' && $customroles{$cust} =~ /bre\&S/);
 6411:                 my $role = 'cr_cr_'.$env{'user.domain'}.'_'.$env{'user.name'}.'_'.$cust;
 6412:                 $table .= &course_level_row($protectedcourse,$role,$area,$domain,
 6413:                                             $cust,\%sections_count,\%lt);
 6414:             }
 6415: 	}
 6416:     }
 6417:     return '' if ($table eq ''); # return nothing if there is nothing 
 6418:                                  # in the table
 6419:     my $result;
 6420:     if (!$env{'request.course.id'}) {
 6421:         $result = '<h4>'.$lt{'crl'}.'</h4>'."\n";
 6422:     }
 6423:     $result .= 
 6424: &Apache::loncommon::start_data_table().
 6425: &Apache::loncommon::start_data_table_header_row().
 6426: '<th>'.$lt{'act'}.'</th><th>'.$lt{'rol'}.'</th><th>'.$lt{'ext'}.'</th>
 6427: <th>'.$lt{'grs'}.'</th><th>'.$lt{'sta'}.'</th><th>'.$lt{'end'}.'</th>'.
 6428: &Apache::loncommon::end_data_table_header_row().
 6429: $table.
 6430: &Apache::loncommon::end_data_table();
 6431:     return $result;
 6432: }
 6433: 
 6434: sub course_level_row {
 6435:     my ($protectedcourse,$role,$area,$domain,$plrole,$sections_count,$lt) = @_;
 6436:     my $row = &Apache::loncommon::start_data_table_row().
 6437:               ' <td><input type="checkbox" name="act_'.
 6438:               $protectedcourse.'_'.$role.'" /></td>'."\n".
 6439:               ' <td>'.$plrole.'</td>'."\n".
 6440:               ' <td>'.$area.'<br />Domain: '.$domain.'</td>'."\n";
 6441:     if (($role eq 'cc') || ($role eq 'co')) {
 6442:         $row .= '<td>&nbsp;</td>';
 6443:     } elsif ($env{'request.course.sec'} ne '') {
 6444:         $row .= ' <td><input type="hidden" value="'.
 6445:                 $env{'request.course.sec'}.'" '.
 6446:                 'name="sec_'.$protectedcourse.'_'.$role.'" />'.
 6447:                 $env{'request.course.sec'}.'</td>';
 6448:     } else {
 6449:         if (ref($sections_count) eq 'HASH') {
 6450:             my $currsec = 
 6451:                 &Apache::lonuserutils::course_sections($sections_count,
 6452:                                                        $protectedcourse.'_'.$role);
 6453:             $row .= '<td><table class="LC_createuser">'."\n".
 6454:                     '<tr class="LC_section_row">'."\n".
 6455:                     ' <td valign="top">'.$lt->{'exs'}.'<br />'.
 6456:                        $currsec.'</td>'."\n".
 6457:                      ' <td>&nbsp;&nbsp;</td>'."\n".
 6458:                      ' <td valign="top">&nbsp;'.$lt->{'new'}.'<br />'.
 6459:                      '<input type="text" name="newsec_'.$protectedcourse.'_'.$role.
 6460:                      '" value="" />'.
 6461:                      '<input type="hidden" '.
 6462:                      'name="sec_'.$protectedcourse.'_'.$role.'" /></td>'."\n".
 6463:                      '</tr></table></td>'."\n";
 6464:         } else {
 6465:             $row .= '<td><input type="text" size="10" '.
 6466:                       'name="sec_'.$protectedcourse.'_'.$role.'" /></td>'."\n";
 6467:         }
 6468:     }
 6469:     $row .= <<ENDTIMEENTRY;
 6470: <td><input type="hidden" name="start_$protectedcourse\_$role" value="" />
 6471: <a href=
 6472: "javascript:pjump('date_start','Start Date $plrole',document.cu.start_$protectedcourse\_$role.value,'start_$protectedcourse\_$role','cu.pres','dateset')">$lt->{'ssd'}</a></td>
 6473: <td><input type="hidden" name="end_$protectedcourse\_$role" value="" />
 6474: <a href=
 6475: "javascript:pjump('date_end','End Date $plrole',document.cu.end_$protectedcourse\_$role.value,'end_$protectedcourse\_$role','cu.pres','dateset')">$lt->{'sed'}</a></td>
 6476: ENDTIMEENTRY
 6477:     $row .= &Apache::loncommon::end_data_table_row();
 6478:     return $row;
 6479: }
 6480: 
 6481: sub course_level_dc {
 6482:     my ($dcdom) = @_;
 6483:     my %customroles=&Apache::lonuserutils::my_custom_roles();
 6484:     my @roles = &Apache::lonuserutils::roles_by_context('course');
 6485:     my $hiddenitems = '<input type="hidden" name="dcdomain" value="'.$dcdom.'" />'.
 6486:                       '<input type="hidden" name="origdom" value="'.$dcdom.'" />'.
 6487:                       '<input type="hidden" name="dccourse" value="" />';
 6488:     my $courseform=&Apache::loncommon::selectcourse_link
 6489:             ('cu','dccourse','dcdomain','coursedesc',undef,undef,'Select','crstype');
 6490:     my $cb_jscript = &Apache::loncommon::coursebrowser_javascript($dcdom,'currsec','cu','role','Course/Community Browser');
 6491:     my %lt=&Apache::lonlocal::texthash(
 6492:                     'rol'  => "Role",
 6493:                     'grs'  => "Section",
 6494:                     'exs'  => "Existing sections",
 6495:                     'new'  => "Define new section", 
 6496:                     'sta'  => "Start",
 6497:                     'end'  => "End",
 6498:                     'ssd'  => "Set Start Date",
 6499:                     'sed'  => "Set End Date",
 6500:                     'scc'  => "Course/Community"
 6501:                   );
 6502:     my $header = '<h4>'.&mt('Course/Community Level').'</h4>'.
 6503:                  &Apache::loncommon::start_data_table().
 6504:                  &Apache::loncommon::start_data_table_header_row().
 6505:                  '<th>'.$lt{'scc'}.'</th><th>'.$lt{'rol'}.'</th><th>'.$lt{'grs'}.'</th><th>'.$lt{'sta'}.'</th><th>'.$lt{'end'}.'</th>'.
 6506:                  &Apache::loncommon::end_data_table_header_row();
 6507:     my $otheritems = &Apache::loncommon::start_data_table_row()."\n".
 6508:                      '<td><br /><span class="LC_nobreak"><input type="text" name="coursedesc" value="" onfocus="this.blur();opencrsbrowser('."'cu','dccourse','dcdomain','coursedesc','','','','crstype'".')" />'.
 6509:                      $courseform.('&nbsp;' x4).'</span></td>'."\n".
 6510:                      '<td valign><br /><select name="role">'."\n";
 6511:     foreach my $role (@roles) {
 6512:         my $plrole=&Apache::lonnet::plaintext($role);
 6513:         $otheritems .= '  <option value="'.$role.'">'.$plrole;
 6514:     }
 6515:     if ( keys %customroles > 0) {
 6516:         foreach my $cust (sort keys %customroles) {
 6517:             my $custrole='cr_cr_'.$env{'user.domain'}.
 6518:                     '_'.$env{'user.name'}.'_'.$cust;
 6519:             $otheritems .= '  <option value="'.$custrole.'">'.$cust;
 6520:         }
 6521:     }
 6522:     $otheritems .= '</select></td><td>'.
 6523:                      '<table border="0" cellspacing="0" cellpadding="0">'.
 6524:                      '<tr><td valign="top"><b>'.$lt{'exs'}.'</b><br /><select name="currsec">'.
 6525:                      ' <option value=""><--'.&mt('Pick course first').'</select></td>'.
 6526:                      '<td>&nbsp;&nbsp;</td>'.
 6527:                      '<td valign="top">&nbsp;<b>'.$lt{'new'}.'</b><br />'.
 6528:                      '<input type="text" name="newsec" value="" />'.
 6529:                      '<input type="hidden" name="section" value="" />'.
 6530:                      '<input type="hidden" name="groups" value="" />'.
 6531:                      '<input type="hidden" name="crstype" value="" /></td>'.
 6532:                      '</tr></table></td>';
 6533:     $otheritems .= <<ENDTIMEENTRY;
 6534: <td><br /><input type="hidden" name="start" value='' />
 6535: <a href=
 6536: "javascript:pjump('date_start','Start Date',document.cu.start.value,'start','cu.pres','dateset')">$lt{'ssd'}</a></td>
 6537: <td><br /><input type="hidden" name="end" value='' />
 6538: <a href=
 6539: "javascript:pjump('date_end','End Date',document.cu.end.value,'end','cu.pres','dateset')">$lt{'sed'}</a></td>
 6540: ENDTIMEENTRY
 6541:     $otheritems .= &Apache::loncommon::end_data_table_row().
 6542:                    &Apache::loncommon::end_data_table()."\n";
 6543:     return $cb_jscript.$header.$hiddenitems.$otheritems;
 6544: }
 6545: 
 6546: sub update_selfenroll_config {
 6547:     my ($r,$context,$permission) = @_;
 6548:     my ($row,$lt) = &get_selfenroll_titles();
 6549:     my %curr_groups = &Apache::longroup::coursegroups();
 6550:     my (%changes,%warning);
 6551:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 6552:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 6553:     my $curr_types;
 6554:     if (ref($row) eq 'ARRAY') {
 6555:         foreach my $item (@{$row}) {
 6556:             if ($item eq 'enroll_dates') {
 6557:                 my (%currenrolldate,%newenrolldate);
 6558:                 foreach my $type ('start','end') {
 6559:                     $currenrolldate{$type} = $env{'course.'.$env{'request.course.id'}.'.internal.selfenroll_'.$type.'_date'};
 6560:                     $newenrolldate{$type} = &Apache::lonhtmlcommon::get_date_from_form('selfenroll_'.$type.'_date');
 6561:                     if ($newenrolldate{$type} ne $currenrolldate{$type}) {
 6562:                         $changes{'internal.selfenroll_'.$type.'_date'} = $newenrolldate{$type};
 6563:                     }
 6564:                 }
 6565:             } elsif ($item eq 'access_dates') {
 6566:                 my (%currdate,%newdate);
 6567:                 foreach my $type ('start','end') {
 6568:                     $currdate{$type} = $env{'course.'.$env{'request.course.id'}.'.internal.selfenroll_'.$type.'_access'};
 6569:                     $newdate{$type} = &Apache::lonhtmlcommon::get_date_from_form('selfenroll_'.$type.'_access');
 6570:                     if ($newdate{$type} ne $currdate{$type}) {
 6571:                         $changes{'internal.selfenroll_'.$type.'_access'} = $newdate{$type};
 6572:                     }
 6573:                 }
 6574:             } elsif ($item eq 'types') {
 6575:                 $curr_types =
 6576:                     $env{'course.'.$env{'request.course.id'}.'.internal.selfenroll_'.$item};
 6577:                 if ($env{'form.selfenroll_all'}) {
 6578:                     if ($curr_types ne '*') {
 6579:                         $changes{'internal.selfenroll_types'} = '*';
 6580:                     } else {
 6581:                         next;
 6582:                     }
 6583:                 } else {
 6584:                     my %currdoms;
 6585:                     my @entries = split(/;/,$curr_types);
 6586:                     my @deletedoms = &Apache::loncommon::get_env_multiple('form.selfenroll_delete');
 6587:                     my @activations = &Apache::loncommon::get_env_multiple('form.selfenroll_activate');
 6588:                     my $newnum = 0;
 6589:                     my @latesttypes;
 6590:                     foreach my $num (@activations) {
 6591:                         my @types = &Apache::loncommon::get_env_multiple('form.selfenroll_types_'.$num);
 6592:                         if (@types > 0) {
 6593:                             @types = sort(@types);
 6594:                             my $typestr = join(',',@types);
 6595:                             my $typedom = $env{'form.selfenroll_dom_'.$num};
 6596:                             $latesttypes[$newnum] = $typedom.':'.$typestr;
 6597:                             $currdoms{$typedom} = 1;
 6598:                             $newnum ++;
 6599:                         }
 6600:                     }
 6601:                     for (my $j=0; $j<$env{'form.selfenroll_types_total'}; $j++) {
 6602:                         if ((!grep(/^$j$/,@deletedoms)) && (!grep(/^$j$/,@activations))) {
 6603:                             my @types = &Apache::loncommon::get_env_multiple('form.selfenroll_types_'.$j);
 6604:                             if (@types > 0) {
 6605:                                 @types = sort(@types);
 6606:                                 my $typestr = join(',',@types);
 6607:                                 my $typedom = $env{'form.selfenroll_dom_'.$j};
 6608:                                 $latesttypes[$newnum] = $typedom.':'.$typestr;
 6609:                                 $currdoms{$typedom} = 1;
 6610:                                 $newnum ++;
 6611:                             }
 6612:                         }
 6613:                     }
 6614:                     if ($env{'form.selfenroll_newdom'} ne '') {
 6615:                         my $typedom = $env{'form.selfenroll_newdom'};
 6616:                         if ((!defined($currdoms{$typedom})) && 
 6617:                             (&Apache::lonnet::domain($typedom) ne '')) {
 6618:                             my $typestr;
 6619:                             my ($othertitle,$usertypes,$types) = 
 6620:                                 &Apache::loncommon::sorted_inst_types($typedom);
 6621:                             my $othervalue = 'any';
 6622:                             if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 6623:                                 if (@{$types} > 0) {
 6624:                                     my @esc_types = map { &escape($_); } @{$types};
 6625:                                     $othervalue = 'other';
 6626:                                     $typestr = join(',',(@esc_types,$othervalue));
 6627:                                 }
 6628:                                 $typestr = $othervalue;
 6629:                             } else {
 6630:                                 $typestr = $othervalue;
 6631:                             } 
 6632:                             $latesttypes[$newnum] = $typedom.':'.$typestr;
 6633:                             $newnum ++ ;
 6634:                         }
 6635:                     }
 6636:                     my $selfenroll_types = join(';',@latesttypes);
 6637:                     if ($selfenroll_types ne $curr_types) {
 6638:                         $changes{'internal.selfenroll_types'} = $selfenroll_types;
 6639:                     }
 6640:                 }
 6641:             } elsif ($item eq 'limit') {
 6642:                 my $newlimit = $env{'form.selfenroll_limit'};
 6643:                 my $newcap = $env{'form.selfenroll_cap'};
 6644:                 $newcap =~s/\s+//g;
 6645:                 my $currlimit =  $env{'course.'.$env{'request.course.id'}.'.internal.selfenroll_limit'};
 6646:                 $currlimit = 'none' if ($currlimit eq '');
 6647:                 my $currcap = $env{'course.'.$env{'request.course.id'}.'.internal.selfenroll_cap'};
 6648:                 if ($newlimit ne $currlimit) {
 6649:                     if ($newlimit ne 'none') {
 6650:                         if ($newcap =~ /^\d+$/) {
 6651:                             if ($newcap ne $currcap) {
 6652:                                 $changes{'internal.selfenroll_cap'} = $newcap;
 6653:                             }
 6654:                             $changes{'internal.selfenroll_limit'} = $newlimit;
 6655:                         } else {
 6656:                             $warning{$item} = &mt('Maximum enrollment setting unchanged.').'<br />'.&mt('The value provided was invalid - it must be a positive integer if enrollment is being limited.'); 
 6657:                         }
 6658:                     } elsif ($currcap ne '') {
 6659:                         $changes{'internal.selfenroll_cap'} = '';
 6660:                         $changes{'internal.selfenroll_limit'} = $newlimit; 
 6661:                     }
 6662:                 } elsif ($currlimit ne 'none') {
 6663:                     if ($newcap =~ /^\d+$/) {
 6664:                         if ($newcap ne $currcap) {
 6665:                             $changes{'internal.selfenroll_cap'} = $newcap;
 6666:                         }
 6667:                     } else {
 6668:                         $warning{$item} = &mt('Maximum enrollment setting unchanged.').'<br />'.&mt('The value provided was invalid - it must be a positive integer if enrollment is being limited.');
 6669:                     }
 6670:                 }
 6671:             } elsif ($item eq 'approval') {
 6672:                 my (@currnotified,@newnotified);
 6673:                 my $currapproval = $env{'course.'.$env{'request.course.id'}.'.internal.selfenroll_approval'};
 6674:                 my $currnotifylist = $env{'course.'.$env{'request.course.id'}.'.internal.selfenroll_notifylist'};
 6675:                 if ($currnotifylist ne '') {
 6676:                     @currnotified = split(/,/,$currnotifylist);
 6677:                     @currnotified = sort(@currnotified);
 6678:                 }
 6679:                 my $newapproval = $env{'form.selfenroll_approval'};
 6680:                 @newnotified = &Apache::loncommon::get_env_multiple('form.selfenroll_notify');
 6681:                 @newnotified = sort(@newnotified);
 6682:                 if ($newapproval ne $currapproval) {
 6683:                     $changes{'internal.selfenroll_approval'} = $newapproval;
 6684:                     if (!$newapproval) {
 6685:                         if ($currnotifylist ne '') {
 6686:                             $changes{'internal.selfenroll_notifylist'} = '';
 6687:                         }
 6688:                     } else {
 6689:                         my @differences =  
 6690:                             &Apache::loncommon::compare_arrays(\@currnotified,\@newnotified);
 6691:                         if (@differences > 0) {
 6692:                             if (@newnotified > 0) {
 6693:                                 $changes{'internal.selfenroll_notifylist'} = join(',',@newnotified);
 6694:                             } else {
 6695:                                 $changes{'internal.selfenroll_notifylist'} = join(',',@newnotified);
 6696:                             }
 6697:                         }
 6698:                     }
 6699:                 } else {
 6700:                     my @differences = &Apache::loncommon::compare_arrays(\@currnotified,\@newnotified);
 6701:                     if (@differences > 0) {
 6702:                         if (@newnotified > 0) {
 6703:                             $changes{'internal.selfenroll_notifylist'} = join(',',@newnotified);
 6704:                         } else {
 6705:                             $changes{'internal.selfenroll_notifylist'} = '';
 6706:                         }
 6707:                     }
 6708:                 }
 6709:             } else {
 6710:                 my $curr_val = 
 6711:                     $env{'course.'.$env{'request.course.id'}.'.internal.selfenroll_'.$item};
 6712:                 my $newval = $env{'form.selfenroll_'.$item};
 6713:                 if ($item eq 'section') {
 6714:                     $newval = $env{'form.sections'};
 6715:                     if (defined($curr_groups{$newval})) {
 6716:                         $newval = $curr_val;
 6717:                         $warning{$item} = &mt('Section for self-enrolled users unchanged as the proposed section is a group').'<br />'.&mt('Group names and section names must be distinct');
 6718:                     } elsif ($newval eq 'all') {
 6719:                         $newval = $curr_val;
 6720:                         $warning{$item} = &mt('Section for self-enrolled users unchanged, as "all" is a reserved section name.');
 6721:                     }
 6722:                     if ($newval eq '') {
 6723:                         $newval = 'none';
 6724:                     }
 6725:                 }
 6726:                 if ($newval ne $curr_val) {
 6727:                     $changes{'internal.selfenroll_'.$item} = $newval;
 6728:                 }
 6729:             }
 6730:         }
 6731:         if (keys(%warning) > 0) {
 6732:             foreach my $item (@{$row}) {
 6733:                 if (exists($warning{$item})) {
 6734:                     $r->print($warning{$item}.'<br />');
 6735:                 }
 6736:             } 
 6737:         }
 6738:         if (keys(%changes) > 0) {
 6739:             my $putresult = &Apache::lonnet::put('environment',\%changes,$cdom,$cnum);
 6740:             if ($putresult eq 'ok') {
 6741:                 if ((exists($changes{'internal.selfenroll_types'})) ||
 6742:                     (exists($changes{'internal.selfenroll_start_date'}))  ||
 6743:                     (exists($changes{'internal.selfenroll_end_date'}))) {
 6744:                     my %crsinfo = &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',
 6745:                                                                 $cnum,undef,undef,'Course');
 6746:                     my $chome = &Apache::lonnet::homeserver($cnum,$cdom);
 6747:                     if (ref($crsinfo{$env{'request.course.id'}}) eq 'HASH') {
 6748:                         foreach my $item ('selfenroll_types','selfenroll_start_date','selfenroll_end_date') {
 6749:                             if (exists($changes{'internal.'.$item})) {
 6750:                                 $crsinfo{$env{'request.course.id'}}{$item} = 
 6751:                                     $changes{'internal.'.$item};
 6752:                             }
 6753:                         }
 6754:                         my $crsputresult =
 6755:                             &Apache::lonnet::courseidput($cdom,\%crsinfo,
 6756:                                                          $chome,'notime');
 6757:                     }
 6758:                 }
 6759:                 $r->print(&mt('The following changes were made to self-enrollment settings:').'<ul>');
 6760:                 foreach my $item (@{$row}) {
 6761:                     my $title = $item;
 6762:                     if (ref($lt) eq 'HASH') {
 6763:                         $title = $lt->{$item};
 6764:                     }
 6765:                     if ($item eq 'enroll_dates') {
 6766:                         foreach my $type ('start','end') {
 6767:                             if (exists($changes{'internal.selfenroll_'.$type.'_date'})) {
 6768:                                 my $newdate = &Apache::lonlocal::locallocaltime($changes{'internal.selfenroll_'.$type.'_date'});
 6769:                                 $r->print('<li>'.&mt('[_1]: "[_2]" set to "[_3]".',
 6770:                                           $title,$type,$newdate).'</li>');
 6771:                             }
 6772:                         }
 6773:                     } elsif ($item eq 'access_dates') {
 6774:                         foreach my $type ('start','end') {
 6775:                             if (exists($changes{'internal.selfenroll_'.$type.'_access'})) {
 6776:                                 my $newdate = &Apache::lonlocal::locallocaltime($changes{'internal.selfenroll_'.$type.'_access'});
 6777:                                 $r->print('<li>'.&mt('[_1]: "[_2]" set to "[_3]".',
 6778:                                           $title,$type,$newdate).'</li>');
 6779:                             }
 6780:                         }
 6781:                     } elsif ($item eq 'limit') {
 6782:                         if ((exists($changes{'internal.selfenroll_limit'})) ||
 6783:                             (exists($changes{'internal.selfenroll_cap'}))) {
 6784:                             my ($newval,$newcap);
 6785:                             if ($changes{'internal.selfenroll_cap'} ne '') {
 6786:                                 $newcap = $changes{'internal.selfenroll_cap'}
 6787:                             } else {
 6788:                                 $newcap = $env{'course.'.$env{'request.course.id'}.'.internal.selfenroll_cap'};
 6789:                             }
 6790:                             if ($changes{'internal.selfenroll_limit'} eq 'none') {
 6791:                                 $newval = &mt('No limit');
 6792:                             } elsif ($changes{'internal.selfenroll_limit'} eq 
 6793:                                      'allstudents') {
 6794:                                 $newval = &mt('New self-enrollment no longer allowed when total (all students) reaches [_1].',$newcap);
 6795:                             } elsif ($changes{'internal.selfenroll_limit'} eq 'selfenrolled') {
 6796:                                 $newval = &mt('New self-enrollment no longer allowed when total number of self-enrolled students reaches [_1].',$newcap);
 6797:                             } else {
 6798:                                 my $currlimit =  $env{'course.'.$env{'request.course.id'}.'.internal.selfenroll_limit'};
 6799:                                 if ($currlimit eq 'allstudents') {
 6800:                                     $newval = &mt('New self-enrollment no longer allowed when total (all students) reaches [_1].',$newcap);
 6801:                                 } elsif ($changes{'internal.selfenroll_limit'} eq 'selfenrolled') {
 6802:                                     $newval =  &mt('New self-enrollment no longer allowed when total number of self-enrolled students reaches [_1].',$newcap);
 6803:                                 }
 6804:                             }
 6805:                             $r->print('<li>'.&mt('"[_1]" set to "[_2]".',$title,$newval).'</li>'."\n");
 6806:                         }
 6807:                     } elsif ($item eq 'approval') {
 6808:                         if ((exists($changes{'internal.selfenroll_approval'})) ||
 6809:                             (exists($changes{'internal.selfenroll_notifylist'}))) {
 6810:                             my ($newval,$newnotify);
 6811:                             if (exists($changes{'internal.selfenroll_notifylist'})) {
 6812:                                 $newnotify = $changes{'internal.selfenroll_notifylist'};
 6813:                             } else {   
 6814:                                 $newnotify = $env{'course.'.$env{'request.course.id'}.'.internal.selfenroll_notifylist'};
 6815:                             }
 6816:                             if ($changes{'internal.selfenroll_approval'}) {
 6817:                                 $newval = &mt('Yes');
 6818:                             } elsif ($changes{'internal.selfenroll_approval'} eq '0') {
 6819:                                 $newval = &mt('No');
 6820:                             } else {
 6821:                                 my $currapproval = 
 6822:                                     $env{'course.'.$env{'request.course.id'}.'.internal.selfenroll_approval'};
 6823:                                 if ($currapproval) {
 6824:                                     $newval = &mt('Yes');
 6825:                                 } else {
 6826:                                     $newval = &mt('No');
 6827:                                 }
 6828:                             }
 6829:                             $r->print('<li>'.&mt('"[_1]" set to "[_2]".',$title,$newval));
 6830:                             if ($newnotify) {
 6831:                                 $r->print('<br />'.&mt('The following will be notified when an enrollment request needs approval, or has been approved: [_1].',$newnotify));
 6832:                             } else {
 6833:                                 $r->print('<br />'.&mt('No notifications sent when an enrollment request needs approval, or has been approved.'));
 6834:                             }
 6835:                             $r->print('</li>'."\n");
 6836:                         }
 6837:                     } else {
 6838:                         if (exists($changes{'internal.selfenroll_'.$item})) {
 6839:                             my $newval = $changes{'internal.selfenroll_'.$item};
 6840:                             if ($item eq 'types') {
 6841:                                 if ($newval eq '') {
 6842:                                     $newval = &mt('None');
 6843:                                 } elsif ($newval eq '*') {
 6844:                                     $newval = &mt('Any user in any domain');
 6845:                                 }
 6846:                             } elsif ($item eq 'registered') {
 6847:                                 if ($newval eq '1') {
 6848:                                     $newval = &mt('Yes');
 6849:                                 } elsif ($newval eq '0') {
 6850:                                     $newval = &mt('No');
 6851:                                 }
 6852:                             }
 6853:                             $r->print('<li>'.&mt('"[_1]" set to "[_2]".',$title,$newval).'</li>'."\n");
 6854:                         }
 6855:                     }
 6856:                 }
 6857:                 $r->print('</ul>');
 6858:                 my %newenvhash;
 6859:                 foreach my $key (keys(%changes)) {
 6860:                     $newenvhash{'course.'.$env{'request.course.id'}.'.'.$key} = $changes{$key};
 6861:                 }
 6862:                 &Apache::lonnet::appenv(\%newenvhash);
 6863:             } else {
 6864:                 $r->print(&mt('An error occurred when saving changes to self-enrollment settings in this course.').'<br />'.&mt('The error was: [_1].',$putresult));
 6865:             }
 6866:         } else {
 6867:             $r->print(&mt('No changes were made to the existing self-enrollment settings in this course.'));
 6868:         }
 6869:     } else {
 6870:         $r->print(&mt('No changes were made to the existing self-enrollment settings in this course.'));
 6871:     }
 6872:     my ($visible,$cansetvis,$vismsgs,$visactions) = &visible_in_cat($cdom,$cnum);
 6873:     if (ref($visactions) eq 'HASH') {
 6874:         if (!$visible) {
 6875:             $r->print('<br />'.$visactions->{'miss'}.'<br />'.$visactions->{'yous'}.
 6876:                       '<br />');
 6877:             if (ref($vismsgs) eq 'ARRAY') {
 6878:                 $r->print('<br />'.$visactions->{'take'}.'<ul>');
 6879:                 foreach my $item (@{$vismsgs}) {
 6880:                     $r->print('<li>'.$visactions->{$item}.'</li>');
 6881:                 }
 6882:                 $r->print('</ul>');
 6883:             }
 6884:             $r->print($cansetvis);
 6885:         }
 6886:     } 
 6887:     return;
 6888: }
 6889: 
 6890: sub get_selfenroll_titles {
 6891:     my @row = ('types','registered','enroll_dates','access_dates','section',
 6892:                'approval','limit');
 6893:     my %lt = &Apache::lonlocal::texthash (
 6894:                 types        => 'Users allowed to self-enroll in this course',
 6895:                 registered   => 'Restrict self-enrollment to students officially registered for the course',
 6896:                 enroll_dates => 'Dates self-enrollment available',
 6897:                 access_dates => 'Course access dates assigned to self-enrolling users',
 6898:                 section      => 'Section assigned to self-enrolling users',
 6899:                 approval     => 'Self-enrollment requests need approval?',
 6900:                 limit        => 'Enrollment limit',
 6901:              );
 6902:     return (\@row,\%lt);
 6903: }
 6904: 
 6905: sub is_courseowner {
 6906:     my ($thiscourse,$courseowner) = @_;
 6907:     if ($courseowner eq '') {
 6908:         if ($env{'request.course.id'} eq $thiscourse) {
 6909:             $courseowner = $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 6910:         }
 6911:     }
 6912:     if ($courseowner ne '') {
 6913:         if ($courseowner eq $env{'user.name'}.':'.$env{'user.domain'}) {
 6914:             return 1;
 6915:         }
 6916:     }
 6917:     return;
 6918: }
 6919: 
 6920: #---------------------------------------------- end functions for &phase_two
 6921: 
 6922: #--------------------------------- functions for &phase_two and &phase_three
 6923: 
 6924: #--------------------------end of functions for &phase_two and &phase_three
 6925: 
 6926: 1;
 6927: __END__
 6928: 
 6929: 

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