File:  [LON-CAPA] / loncom / interface / loncreateuser.pm
Revision 1.412: download - view: text, annotated - select for diffs
Mon Sep 5 01:46:07 2016 UTC (7 years, 9 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Domain Configuration for LON-CAPA Directory searches for user information
  for users in a domain.
  - Can disable for all, or can disable only for other domains.
  - Default: enabled for all domains.

    1: # The LearningOnline Network with CAPA
    2: # Create a user
    3: #
    4: # $Id: loncreateuser.pm,v 1.412 2016/09/05 01:46:07 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: ###
   29: 
   30: package Apache::loncreateuser;
   31: 
   32: =pod
   33: 
   34: =head1 NAME
   35: 
   36: Apache::loncreateuser.pm
   37: 
   38: =head1 SYNOPSIS
   39: 
   40:     Handler to create users and custom roles
   41: 
   42:     Provides an Apache handler for creating users,
   43:     editing their login parameters, roles, and removing roles, and
   44:     also creating and assigning custom roles.
   45: 
   46: =head1 OVERVIEW
   47: 
   48: =head2 Custom Roles
   49: 
   50: In LON-CAPA, roles are actually collections of privileges. "Teaching
   51: Assistant", "Course Coordinator", and other such roles are really just
   52: collection of privileges that are useful in many circumstances.
   53: 
   54: Custom roles can be defined by a Domain Coordinator, Course Coordinator
   55: or Community Coordinator via the Manage User functionality.
   56: The custom role editor screen will show all privileges which can be
   57: assigned to users. For a complete list of privileges, please see 
   58: C</home/httpd/lonTabs/rolesplain.tab>.
   59: 
   60: Custom role definitions are stored in the C<roles.db> file of the creator
   61: of the role.
   62: 
   63: =cut
   64: 
   65: use strict;
   66: use Apache::Constants qw(:common :http);
   67: use Apache::lonnet;
   68: use Apache::loncommon;
   69: use Apache::lonlocal;
   70: use Apache::longroup;
   71: use Apache::lonuserutils;
   72: use Apache::loncoursequeueadmin;
   73: use LONCAPA qw(:DEFAULT :match);
   74: 
   75: my $loginscript; # piece of javascript used in two separate instances
   76: my $authformnop;
   77: my $authformkrb;
   78: my $authformint;
   79: my $authformfsys;
   80: my $authformloc;
   81: 
   82: sub initialize_authen_forms {
   83:     my ($dom,$formname,$curr_authtype,$mode) = @_;
   84:     my ($krbdef,$krbdefdom) = &Apache::loncommon::get_kerberos_defaults($dom);
   85:     my %param = ( formname => $formname,
   86:                   kerb_def_dom => $krbdefdom,
   87:                   kerb_def_auth => $krbdef,
   88:                   domain => $dom,
   89:                 );
   90:     my %abv_auth = &auth_abbrev();
   91:     if ($curr_authtype =~ /^(krb4|krb5|internal|localauth|unix):(.*)$/) {
   92:         my $long_auth = $1;
   93:         my $curr_autharg = $2;
   94:         my %abv_auth = &auth_abbrev();
   95:         $param{'curr_authtype'} = $abv_auth{$long_auth};
   96:         if ($long_auth =~ /^krb(4|5)$/) {
   97:             $param{'curr_kerb_ver'} = $1;
   98:             $param{'curr_autharg'} = $curr_autharg;
   99:         }
  100:         if ($mode eq 'modifyuser') {
  101:             $param{'mode'} = $mode;
  102:         }
  103:     }
  104:     $loginscript  = &Apache::loncommon::authform_header(%param);
  105:     $authformkrb  = &Apache::loncommon::authform_kerberos(%param);
  106:     $authformnop  = &Apache::loncommon::authform_nochange(%param);
  107:     $authformint  = &Apache::loncommon::authform_internal(%param);
  108:     $authformfsys = &Apache::loncommon::authform_filesystem(%param);
  109:     $authformloc  = &Apache::loncommon::authform_local(%param);
  110: }
  111: 
  112: sub auth_abbrev {
  113:     my %abv_auth = (
  114:                      krb5      => 'krb',
  115:                      krb4      => 'krb',
  116:                      internal  => 'int',
  117:                      localauth => 'loc',
  118:                      unix      => 'fsys',
  119:                    );
  120:     return %abv_auth;
  121: }
  122: 
  123: # ====================================================
  124: 
  125: sub user_quotas {
  126:     my ($ccuname,$ccdomain) = @_;
  127:     my %lt = &Apache::lonlocal::texthash(
  128:                    'usrt'      => "User Tools",
  129:                    'cust'      => "Custom quota",
  130:                    'chqu'      => "Change quota",
  131:     );
  132:    
  133:     my $quota_javascript = <<"END_SCRIPT";
  134: <script type="text/javascript">
  135: // <![CDATA[
  136: function quota_changes(caller,context) {
  137:     var customoff = document.getElementById('custom_'+context+'quota_off');
  138:     var customon = document.getElementById('custom_'+context+'quota_on');
  139:     var number = document.getElementById(context+'quota');
  140:     if (caller == "custom") {
  141:         if (customoff) {
  142:             if (customoff.checked) {
  143:                 number.value = "";
  144:             }
  145:         }
  146:     }
  147:     if (caller == "quota") {
  148:         if (customon) {
  149:             customon.checked = true;
  150:         }
  151:     }
  152:     return;
  153: }
  154: // ]]>
  155: </script>
  156: END_SCRIPT
  157:     my $longinsttype;
  158:     my ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($ccdomain);
  159:     my $output = $quota_javascript."\n".
  160:                  '<h3>'.$lt{'usrt'}.'</h3>'."\n".
  161:                  &Apache::loncommon::start_data_table();
  162: 
  163:     if (&Apache::lonnet::allowed('mut',$ccdomain)) {
  164:         $output .= &build_tools_display($ccuname,$ccdomain,'tools');
  165:     }
  166: 
  167:     my %titles = &Apache::lonlocal::texthash (
  168:                     portfolio => "Disk space allocated to user's portfolio files",
  169:                     author    => "Disk space allocated to user's Authoring Space (if role assigned)",
  170:                  );
  171:     foreach my $name ('portfolio','author') {
  172:         my ($currquota,$quotatype,$inststatus,$defquota) =
  173:             &Apache::loncommon::get_user_quota($ccuname,$ccdomain,$name);
  174:         if ($longinsttype eq '') { 
  175:             if ($inststatus ne '') {
  176:                 if ($usertypes->{$inststatus} ne '') {
  177:                     $longinsttype = $usertypes->{$inststatus};
  178:                 }
  179:             }
  180:         }
  181:         my ($showquota,$custom_on,$custom_off,$defaultinfo);
  182:         $custom_on = ' ';
  183:         $custom_off = ' checked="checked" ';
  184:         if ($quotatype eq 'custom') {
  185:             $custom_on = $custom_off;
  186:             $custom_off = ' ';
  187:             $showquota = $currquota;
  188:             if ($longinsttype eq '') {
  189:                 $defaultinfo = &mt('For this user, the default quota would be [_1]'
  190:                               .' MB.',$defquota);
  191:             } else {
  192:                 $defaultinfo = &mt("For this user, the default quota would be [_1]".
  193:                                    " MB, as determined by the user's institutional".
  194:                                    " affiliation ([_2]).",$defquota,$longinsttype);
  195:             }
  196:         } else {
  197:             if ($longinsttype eq '') {
  198:                 $defaultinfo = &mt('For this user, the default quota is [_1]'
  199:                               .' MB.',$defquota);
  200:             } else {
  201:                 $defaultinfo = &mt("For this user, the default quota of [_1]".
  202:                                    " MB, is determined by the user's institutional".
  203:                                    " affiliation ([_2]).",$defquota,$longinsttype);
  204:             }
  205:         }
  206: 
  207:         if (&Apache::lonnet::allowed('mpq',$ccdomain)) {
  208:             $output .= '<tr class="LC_info_row">'."\n".
  209:                        '    <td>'.$titles{$name}.'</td>'."\n".
  210:                        '  </tr>'."\n".
  211:                        &Apache::loncommon::start_data_table_row()."\n".
  212:                        '  <td><span class="LC_nobreak">'.
  213:                        &mt('Current quota: [_1] MB',$currquota).'</span>&nbsp;&nbsp;'.
  214:                        $defaultinfo.'</td>'."\n".
  215:                        &Apache::loncommon::end_data_table_row()."\n".
  216:                        &Apache::loncommon::start_data_table_row()."\n".
  217:                        '  <td><span class="LC_nobreak">'.$lt{'chqu'}.
  218:                        ': <label>'.
  219:                        '<input type="radio" name="custom_'.$name.'quota" id="custom_'.$name.'quota_off" '.
  220:                        'value="0" '.$custom_off.' onchange="javascript:quota_changes('."'custom','$name'".');"'.
  221:                        ' /><span class="LC_nobreak">'.
  222:                        &mt('Default ([_1] MB)',$defquota).'</span></label>&nbsp;'.
  223:                        '&nbsp;<label><input type="radio" name="custom_'.$name.'quota" id="custom_'.$name.'quota_on" '.
  224:                        'value="1" '.$custom_on.'  onchange="javascript:quota_changes('."'custom','$name'".');"'.
  225:                        ' />'.$lt{'cust'}.':</label>&nbsp;'.
  226:                        '<input type="text" name="'.$name.'quota" id="'.$name.'quota" size ="5" '.
  227:                        'value="'.$showquota.'" onfocus="javascript:quota_changes('."'quota','$name'".');"'.
  228:                        ' />&nbsp;'.&mt('MB').'</span></td>'."\n".
  229:                        &Apache::loncommon::end_data_table_row()."\n";
  230:         }
  231:     }
  232:     $output .= &Apache::loncommon::end_data_table();
  233:     return $output;
  234: }
  235: 
  236: sub build_tools_display {
  237:     my ($ccuname,$ccdomain,$context) = @_;
  238:     my (@usertools,%userenv,$output,@options,%validations,%reqtitles,%reqdisplay,
  239:         $colspan,$isadv,%domconfig);
  240:     my %lt = &Apache::lonlocal::texthash (
  241:                    'blog'       => "Personal User Blog",
  242:                    'aboutme'    => "Personal Information Page",
  243:                    'webdav'     => "WebDAV access to Authoring Spaces (if SSL and author/co-author)",
  244:                    'portfolio'  => "Personal User Portfolio",
  245:                    'avai'       => "Available",
  246:                    'cusa'       => "availability",
  247:                    'chse'       => "Change setting",
  248:                    'usde'       => "Use default",
  249:                    'uscu'       => "Use custom",
  250:                    'official'   => 'Can request creation of official courses',
  251:                    'unofficial' => 'Can request creation of unofficial courses',
  252:                    'community'  => 'Can request creation of communities',
  253:                    'textbook'   => 'Can request creation of textbook courses',
  254:                    'placement'  => 'Can request creation of placement tests',
  255:                    'requestauthor'  => 'Can request author space',
  256:     );
  257:     if ($context eq 'requestcourses') {
  258:         %userenv = &Apache::lonnet::userenvironment($ccdomain,$ccuname,
  259:                       'requestcourses.official','requestcourses.unofficial',
  260:                       'requestcourses.community','requestcourses.textbook',
  261:                       'requestcourses.placement');
  262:         @usertools = ('official','unofficial','community','textbook','placement');
  263:         @options =('norequest','approval','autolimit','validate');
  264:         %validations = &Apache::lonnet::auto_courserequest_checks($ccdomain);
  265:         %reqtitles = &courserequest_titles();
  266:         %reqdisplay = &courserequest_display();
  267:         $colspan = ' colspan="2"';
  268:         %domconfig =
  269:             &Apache::lonnet::get_dom('configuration',['requestcourses'],$ccdomain);
  270:         $isadv = &Apache::lonnet::is_advanced_user($ccuname,$ccdomain);
  271:     } elsif ($context eq 'requestauthor') {
  272:         %userenv = &Apache::lonnet::userenvironment($ccdomain,$ccuname,
  273:                                                     'requestauthor');
  274:         @usertools = ('requestauthor');
  275:         @options =('norequest','approval','automatic');
  276:         %reqtitles = &requestauthor_titles();
  277:         %reqdisplay = &requestauthor_display();
  278:         $colspan = ' colspan="2"';
  279:         %domconfig =
  280:             &Apache::lonnet::get_dom('configuration',['requestauthor'],$ccdomain);
  281:     } else {
  282:         %userenv = &Apache::lonnet::userenvironment($ccdomain,$ccuname,
  283:                           'tools.aboutme','tools.portfolio','tools.blog',
  284:                           'tools.webdav');
  285:         @usertools = ('aboutme','blog','webdav','portfolio');
  286:     }
  287:     foreach my $item (@usertools) {
  288:         my ($custom_access,$curr_access,$cust_on,$cust_off,$tool_on,$tool_off,
  289:             $currdisp,$custdisp,$custradio);
  290:         $cust_off = 'checked="checked" ';
  291:         $tool_on = 'checked="checked" ';
  292:         $curr_access =  
  293:             &Apache::lonnet::usertools_access($ccuname,$ccdomain,$item,undef,
  294:                                               $context);
  295:         if ($context eq 'requestauthor') {
  296:             if ($userenv{$context} ne '') {
  297:                 $cust_on = ' checked="checked" ';
  298:                 $cust_off = '';
  299:             }  
  300:         } elsif ($userenv{$context.'.'.$item} ne '') {
  301:             $cust_on = ' checked="checked" ';
  302:             $cust_off = '';
  303:         }
  304:         if ($context eq 'requestcourses') {
  305:             if ($userenv{$context.'.'.$item} eq '') {
  306:                 $custom_access = &mt('Currently from default setting.');
  307:             } else {
  308:                 $custom_access = &mt('Currently from custom setting.');
  309:             }
  310:         } elsif ($context eq 'requestauthor') {
  311:             if ($userenv{$context} eq '') {
  312:                 $custom_access = &mt('Currently from default setting.');
  313:             } else {
  314:                 $custom_access = &mt('Currently from custom setting.');
  315:             }
  316:         } else {
  317:             if ($userenv{$context.'.'.$item} eq '') {
  318:                 $custom_access =
  319:                     &mt('Availability determined currently from default setting.');
  320:                 if (!$curr_access) {
  321:                     $tool_off = 'checked="checked" ';
  322:                     $tool_on = '';
  323:                 }
  324:             } else {
  325:                 $custom_access =
  326:                     &mt('Availability determined currently from custom setting.');
  327:                 if ($userenv{$context.'.'.$item} == 0) {
  328:                     $tool_off = 'checked="checked" ';
  329:                     $tool_on = '';
  330:                 }
  331:             }
  332:         }
  333:         $output .= '  <tr class="LC_info_row">'."\n".
  334:                    '   <td'.$colspan.'>'.$lt{$item}.'</td>'."\n".
  335:                    '  </tr>'."\n".
  336:                    &Apache::loncommon::start_data_table_row()."\n";
  337:         if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
  338:             my ($curroption,$currlimit);
  339:             my $envkey = $context.'.'.$item;
  340:             if ($context eq 'requestauthor') {
  341:                 $envkey = $context;
  342:             }
  343:             if ($userenv{$envkey} ne '') {
  344:                 $curroption = $userenv{$envkey};
  345:             } else {
  346:                 my (@inststatuses);
  347:                 if ($context eq 'requestcourses') {
  348:                     $curroption =
  349:                         &Apache::loncoursequeueadmin::get_processtype('course',$ccuname,$ccdomain,
  350:                                                                       $isadv,$ccdomain,$item,
  351:                                                                       \@inststatuses,\%domconfig);
  352:                 } else {
  353:                      $curroption = 
  354:                          &Apache::loncoursequeueadmin::get_processtype('requestauthor',$ccuname,$ccdomain,
  355:                                                                        $isadv,$ccdomain,undef,
  356:                                                                        \@inststatuses,\%domconfig);
  357:                 }
  358:             }
  359:             if (!$curroption) {
  360:                 $curroption = 'norequest';
  361:             }
  362:             if ($curroption =~ /^autolimit=(\d*)$/) {
  363:                 $currlimit = $1;
  364:                 if ($currlimit eq '') {
  365:                     $currdisp = &mt('Yes, automatic creation');
  366:                 } else {
  367:                     $currdisp = &mt('Yes, up to [quant,_1,request]/user',$currlimit);
  368:                 }
  369:             } else {
  370:                 $currdisp = $reqdisplay{$curroption};
  371:             }
  372:             $custdisp = '<table>';
  373:             foreach my $option (@options) {
  374:                 my $val = $option;
  375:                 if ($option eq 'norequest') {
  376:                     $val = 0;
  377:                 }
  378:                 if ($option eq 'validate') {
  379:                     my $canvalidate = 0;
  380:                     if (ref($validations{$item}) eq 'HASH') {
  381:                         if ($validations{$item}{'_custom_'}) {
  382:                             $canvalidate = 1;
  383:                         }
  384:                     }
  385:                     next if (!$canvalidate);
  386:                 }
  387:                 my $checked = '';
  388:                 if ($option eq $curroption) {
  389:                     $checked = ' checked="checked"';
  390:                 } elsif ($option eq 'autolimit') {
  391:                     if ($curroption =~ /^autolimit/) {
  392:                         $checked = ' checked="checked"';
  393:                     }
  394:                 }
  395:                 my $name = 'crsreq_'.$item;
  396:                 if ($context eq 'requestauthor') {
  397:                     $name = $item;
  398:                 }
  399:                 $custdisp .= '<tr><td><span class="LC_nobreak"><label>'.
  400:                              '<input type="radio" name="'.$name.'" '.
  401:                              'value="'.$val.'"'.$checked.' />'.
  402:                              $reqtitles{$option}.'</label>&nbsp;';
  403:                 if ($option eq 'autolimit') {
  404:                     $custdisp .= '<input type="text" name="'.$name.
  405:                                  '_limit" size="1" '.
  406:                                  'value="'.$currlimit.'" /></span><br />'.
  407:                                  $reqtitles{'unlimited'};
  408:                 } else {
  409:                     $custdisp .= '</span>';
  410:                 }
  411:                 $custdisp .= '</td></tr>';
  412:             }
  413:             $custdisp .= '</table>';
  414:             $custradio = '</span></td><td>'.&mt('Custom setting').'<br />'.$custdisp;
  415:         } else {
  416:             $currdisp = ($curr_access?&mt('Yes'):&mt('No'));
  417:             my $name = $context.'_'.$item;
  418:             if ($context eq 'requestauthor') {
  419:                 $name = $context;
  420:             }
  421:             $custdisp = '<span class="LC_nobreak"><label>'.
  422:                         '<input type="radio" name="'.$name.'"'.
  423:                         ' value="1" '.$tool_on.'/>'.&mt('On').'</label>&nbsp;<label>'.
  424:                         '<input type="radio" name="'.$name.'" value="0" '.
  425:                         $tool_off.'/>'.&mt('Off').'</label></span>';
  426:             $custradio = ('&nbsp;'x2).'--'.$lt{'cusa'}.':&nbsp;'.$custdisp.
  427:                           '</span>';
  428:         }
  429:         $output .= '  <td'.$colspan.'>'.$custom_access.('&nbsp;'x4).
  430:                    $lt{'avai'}.': '.$currdisp.'</td>'."\n".
  431:                    &Apache::loncommon::end_data_table_row()."\n".
  432:                    &Apache::loncommon::start_data_table_row()."\n".
  433:                    '  <td style="vertical-align:top;"><span class="LC_nobreak">'.
  434:                    $lt{'chse'}.': <label>'.
  435:                    '<input type="radio" name="custom'.$item.'" value="0" '.
  436:                    $cust_off.'/>'.$lt{'usde'}.'</label>'.('&nbsp;' x3).
  437:                    '<label><input type="radio" name="custom'.$item.'" value="1" '.
  438:                    $cust_on.'/>'.$lt{'uscu'}.'</label>'.$custradio.'</td>'.
  439:                    &Apache::loncommon::end_data_table_row()."\n";
  440:     }
  441:     return $output;
  442: }
  443: 
  444: sub coursereq_externaluser {
  445:     my ($ccuname,$ccdomain,$cdom) = @_;
  446:     my (@usertools,@options,%validations,%userenv,$output);
  447:     my %lt = &Apache::lonlocal::texthash (
  448:                    'official'   => 'Can request creation of official courses',
  449:                    'unofficial' => 'Can request creation of unofficial courses',
  450:                    'community'  => 'Can request creation of communities',
  451:                    'textbook'   => 'Can request creation of textbook courses',
  452:                    'placement'  => 'Can request creation of placement tests',
  453:     );
  454: 
  455:     %userenv = &Apache::lonnet::userenvironment($ccdomain,$ccuname,
  456:                       'reqcrsotherdom.official','reqcrsotherdom.unofficial',
  457:                       'reqcrsotherdom.community','reqcrsotherdom.textbook',
  458:                       'reqcrsotherdom.placement');
  459:     @usertools = ('official','unofficial','community','textbook','placement');
  460:     @options = ('approval','validate','autolimit');
  461:     %validations = &Apache::lonnet::auto_courserequest_checks($cdom);
  462:     my $optregex = join('|',@options);
  463:     my %reqtitles = &courserequest_titles();
  464:     foreach my $item (@usertools) {
  465:         my ($curroption,$currlimit,$tooloff);
  466:         if ($userenv{'reqcrsotherdom.'.$item} ne '') {
  467:             my @curr = split(',',$userenv{'reqcrsotherdom.'.$item});
  468:             foreach my $req (@curr) {
  469:                 if ($req =~ /^\Q$cdom\E\:($optregex)=?(\d*)$/) {
  470:                     $curroption = $1;
  471:                     $currlimit = $2;
  472:                     last;
  473:                 }
  474:             }
  475:             if (!$curroption) {
  476:                 $curroption = 'norequest';
  477:                 $tooloff = ' checked="checked"';
  478:             }
  479:         } else {
  480:             $curroption = 'norequest';
  481:             $tooloff = ' checked="checked"';
  482:         }
  483:         $output.= &Apache::loncommon::start_data_table_row()."\n".
  484:                   '  <td><span class="LC_nobreak">'.$lt{$item}.': </span></td><td>'.
  485:                   '<table><tr><td valign="top">'."\n".
  486:                   '<label><input type="radio" name="reqcrsotherdom_'.$item.
  487:                   '" value=""'.$tooloff.' />'.$reqtitles{'norequest'}.
  488:                   '</label></td>';
  489:         foreach my $option (@options) {
  490:             if ($option eq 'validate') {
  491:                 my $canvalidate = 0;
  492:                 if (ref($validations{$item}) eq 'HASH') {
  493:                     if ($validations{$item}{'_external_'}) {
  494:                         $canvalidate = 1;
  495:                     }
  496:                 }
  497:                 next if (!$canvalidate);
  498:             }
  499:             my $checked = '';
  500:             if ($option eq $curroption) {
  501:                 $checked = ' checked="checked"';
  502:             }
  503:             $output .= '<td valign="top"><span class="LC_nobreak"><label>'.
  504:                        '<input type="radio" name="reqcrsotherdom_'.$item.
  505:                        '" value="'.$option.'"'.$checked.' />'.
  506:                        $reqtitles{$option}.'</label>';
  507:             if ($option eq 'autolimit') {
  508:                 $output .= '&nbsp;<input type="text" name="reqcrsotherdom_'.
  509:                            $item.'_limit" size="1" '.
  510:                            'value="'.$currlimit.'" /></span>'.
  511:                            '<br />'.$reqtitles{'unlimited'};
  512:             } else {
  513:                 $output .= '</span>';
  514:             }
  515:             $output .= '</td>';
  516:         }
  517:         $output .= '</td></tr></table></td>'."\n".
  518:                    &Apache::loncommon::end_data_table_row()."\n";
  519:     }
  520:     return $output;
  521: }
  522: 
  523: sub domainrole_req {
  524:     my ($ccuname,$ccdomain) = @_;
  525:     return '<br /><h3>'.
  526:            &mt('User Can Request Assignment of Domain Roles?').
  527:            '</h3>'."\n".
  528:            &Apache::loncommon::start_data_table().
  529:            &build_tools_display($ccuname,$ccdomain,
  530:                                 'requestauthor').
  531:            &Apache::loncommon::end_data_table();
  532: }
  533: 
  534: sub courserequest_titles {
  535:     my %titles = &Apache::lonlocal::texthash (
  536:                                    official   => 'Official',
  537:                                    unofficial => 'Unofficial',
  538:                                    community  => 'Communities',
  539:                                    textbook   => 'Textbook',
  540:                                    placement  => 'Placement Tests',
  541:                                    norequest  => 'Not allowed',
  542:                                    approval   => 'Approval by Dom. Coord.',
  543:                                    validate   => 'With validation',
  544:                                    autolimit  => 'Numerical limit',
  545:                                    unlimited  => '(blank for unlimited)',
  546:                  );
  547:     return %titles;
  548: }
  549: 
  550: sub courserequest_display {
  551:     my %titles = &Apache::lonlocal::texthash (
  552:                                    approval   => 'Yes, need approval',
  553:                                    validate   => 'Yes, with validation',
  554:                                    norequest  => 'No',
  555:    );
  556:    return %titles;
  557: }
  558: 
  559: sub requestauthor_titles {
  560:     my %titles = &Apache::lonlocal::texthash (
  561:                                    norequest  => 'Not allowed',
  562:                                    approval   => 'Approval by Dom. Coord.',
  563:                                    automatic  => 'Automatic approval',
  564:                  );
  565:     return %titles;
  566: 
  567: }
  568: 
  569: sub requestauthor_display {
  570:     my %titles = &Apache::lonlocal::texthash (
  571:                                    approval   => 'Yes, need approval',
  572:                                    automatic  => 'Yes, automatic approval',
  573:                                    norequest  => 'No',
  574:    );
  575:    return %titles;
  576: }
  577: 
  578: sub requestchange_display {
  579:     my %titles = &Apache::lonlocal::texthash (
  580:                                    approval   => "availability set to 'on' (approval required)", 
  581:                                    automatic  => "availability set to 'on' (automatic approval)",
  582:                                    norequest  => "availability set to 'off'",
  583:    );
  584:    return %titles;
  585: }
  586: 
  587: sub curr_requestauthor {
  588:     my ($uname,$udom,$isadv,$inststatuses,$domconfig) = @_;
  589:     return unless ((ref($inststatuses) eq 'ARRAY') && (ref($domconfig) eq 'HASH'));
  590:     if ($uname eq '' || $udom eq '') {
  591:         $uname = $env{'user.name'};
  592:         $udom = $env{'user.domain'};
  593:         $isadv = $env{'user.adv'};
  594:     }
  595:     my (%userenv,%settings,$val);
  596:     my @options = ('automatic','approval');
  597:     %userenv =
  598:         &Apache::lonnet::userenvironment($udom,$uname,'requestauthor','inststatus');
  599:     if ($userenv{'requestauthor'}) {
  600:         $val = $userenv{'requestauthor'};
  601:         @{$inststatuses} = ('_custom_');
  602:     } else {
  603:         my %alltasks;
  604:         if (ref($domconfig->{'requestauthor'}) eq 'HASH') {
  605:             %settings = %{$domconfig->{'requestauthor'}};
  606:             if (($isadv) && ($settings{'_LC_adv'} ne '')) {
  607:                 $val = $settings{'_LC_adv'};
  608:                 @{$inststatuses} = ('_LC_adv_');
  609:             } else {
  610:                 if ($userenv{'inststatus'} ne '') {
  611:                     @{$inststatuses} = split(',',$userenv{'inststatus'});
  612:                 } else {
  613:                     @{$inststatuses} = ('default');
  614:                 }
  615:                 foreach my $status (@{$inststatuses}) {
  616:                     if (exists($settings{$status})) {
  617:                         my $value = $settings{$status};
  618:                         next unless ($value);
  619:                         unless (exists($alltasks{$value})) {
  620:                             if (ref($alltasks{$value}) eq 'ARRAY') {
  621:                                 unless(grep(/^\Q$status\E$/,@{$alltasks{$value}})) {
  622:                                     push(@{$alltasks{$value}},$status);
  623:                                 }
  624:                             } else {
  625:                                 @{$alltasks{$value}} = ($status);
  626:                             }
  627:                         }
  628:                     }
  629:                 }
  630:                 foreach my $option (@options) {
  631:                     if ($alltasks{$option}) {
  632:                         $val = $option;
  633:                         last;
  634:                     }
  635:                 }
  636:             }
  637:         }
  638:     }
  639:     return $val;
  640: }
  641: 
  642: # =================================================================== Phase one
  643: 
  644: sub print_username_entry_form {
  645:     my ($r,$context,$response,$srch,$forcenewuser,$crstype,$brcrum) = @_;
  646:     my $defdom=$env{'request.role.domain'};
  647:     my $formtoset = 'crtuser';
  648:     if (exists($env{'form.startrolename'})) {
  649:         $formtoset = 'docustom';
  650:         $env{'form.rolename'} = $env{'form.startrolename'};
  651:     } elsif ($env{'form.origform'} eq 'crtusername') {
  652:         $formtoset =  $env{'form.origform'};
  653:     }
  654: 
  655:     my ($jsback,$elements) = &crumb_utilities();
  656: 
  657:     my $jscript = &Apache::loncommon::studentbrowser_javascript()."\n".
  658:         '<script type="text/javascript">'."\n".
  659:         '// <![CDATA['."\n".
  660:         &Apache::lonhtmlcommon::set_form_elements($elements->{$formtoset})."\n".
  661:         '// ]]>'."\n".
  662:         '</script>'."\n";
  663: 
  664:     my %existingroles=&Apache::lonuserutils::my_custom_roles($crstype);
  665:     if (($env{'form.action'} eq 'custom') && (keys(%existingroles) > 0)
  666:         && (&Apache::lonnet::allowed('mcr','/'))) {
  667:         $jscript .= &customrole_javascript();
  668:     }
  669:     my $helpitem = 'Course_Change_Privileges';
  670:     if ($env{'form.action'} eq 'custom') {
  671:         $helpitem = 'Course_Editing_Custom_Roles';
  672:     } elsif ($env{'form.action'} eq 'singlestudent') {
  673:         $helpitem = 'Course_Add_Student';
  674:     }
  675:     my %breadcrumb_text = &singleuser_breadcrumb($crstype);
  676:     if ($env{'form.action'} eq 'custom') {
  677:         push(@{$brcrum},
  678:                  {href=>"javascript:backPage(document.crtuser)",       
  679:                   text=>"Pick custom role",
  680:                   help => $helpitem,}
  681:                  );
  682:     } else {
  683:         push (@{$brcrum},
  684:                   {href => "javascript:backPage(document.crtuser)",
  685:                    text => $breadcrumb_text{'search'},
  686:                    help => $helpitem,
  687:                    faq  => 282,
  688:                    bug  => 'Instructor Interface',}
  689:                   );
  690:     }
  691:     my %loaditems = (
  692:                 'onload' => "javascript:setFormElements(document.$formtoset)",
  693:                     );
  694:     my $args = {bread_crumbs           => $brcrum,
  695:                 bread_crumbs_component => 'User Management',
  696:                 add_entries            => \%loaditems,};
  697:     $r->print(&Apache::loncommon::start_page('User Management',$jscript,$args));
  698: 
  699:     my %lt=&Apache::lonlocal::texthash(
  700:                     'srst' => 'Search for a user and enroll as a student',
  701:                     'srme' => 'Search for a user and enroll as a member',
  702:                     'srad' => 'Search for a user and modify/add user information or roles',
  703: 		    'usr'  => "Username",
  704:                     'dom'  => "Domain",
  705:                     'ecrp' => "Define or Edit Custom Role",
  706:                     'nr'   => "role name",
  707:                     'cre'  => "Next",
  708: 				       );
  709: 
  710:     if ($env{'form.action'} eq 'custom') {
  711:         if (&Apache::lonnet::allowed('mcr','/')) {
  712:             my $newroletext = &mt('Define new custom role:');
  713:             $r->print('<form action="/adm/createuser" method="post" name="docustom">'.
  714:                       '<input type="hidden" name="action" value="'.$env{'form.action'}.'" />'.
  715:                       '<input type="hidden" name="phase" value="selected_custom_edit" />'.
  716:                       '<h3>'.$lt{'ecrp'}.'</h3>'.
  717:                       &Apache::loncommon::start_data_table().
  718:                       &Apache::loncommon::start_data_table_row().
  719:                       '<td>');
  720:             if (keys(%existingroles) > 0) {
  721:                 $r->print('<br /><label><input type="radio" name="customroleaction" value="new" checked="checked" onclick="setCustomFields();" /><b>'.$newroletext.'</b></label>');
  722:             } else {
  723:                 $r->print('<br /><input type="hidden" name="customroleaction" value="new" /><b>'.$newroletext.'</b>');
  724:             }
  725:             $r->print('</td><td align="center">'.$lt{'nr'}.'<br /><input type="text" size="15" name="newrolename" onfocus="setCustomAction('."'new'".');" /></td>'.
  726:                       &Apache::loncommon::end_data_table_row());
  727:             if (keys(%existingroles) > 0) {
  728:                 $r->print(&Apache::loncommon::start_data_table_row().'<td><br />'.
  729:                           '<label><input type="radio" name="customroleaction" value="edit" onclick="setCustomFields();"/><b>'.
  730:                           &mt('View/Modify existing role:').'</b></label></td>'.
  731:                           '<td align="center"><br />'.
  732:                           '<select name="rolename" onchange="setCustomAction('."'edit'".');">'.
  733:                           '<option value="" selected="selected">'.
  734:                           &mt('Select'));
  735:                 foreach my $role (sort(keys(%existingroles))) {
  736:                     $r->print('<option value="'.$role.'">'.$role.'</option>');
  737:                 }
  738:                 $r->print('</select>'.
  739:                           '</td>'.
  740:                           &Apache::loncommon::end_data_table_row());
  741:             }
  742:             $r->print(&Apache::loncommon::end_data_table().'<p>'.
  743:                       '<input name="customeditor" type="submit" value="'.
  744:                       $lt{'cre'}.'" /></p>'.
  745:                       '</form>');
  746:         }
  747:     } else {
  748:         my $actiontext = $lt{'srad'};
  749:         if ($env{'form.action'} eq 'singlestudent') {
  750:             if ($crstype eq 'Community') {
  751:                 $actiontext = $lt{'srme'};
  752:             } else {
  753:                 $actiontext = $lt{'srst'};
  754:             }
  755:         }
  756:         $r->print("<h3>$actiontext</h3>");
  757:         if ($env{'form.origform'} ne 'crtusername') {
  758:             $r->print("\n".$response);
  759:         }
  760:         $r->print(&entry_form($defdom,$srch,$forcenewuser,$context,$response,$crstype));
  761:     }
  762: }
  763: 
  764: sub customrole_javascript {
  765:     my $js = <<"END";
  766: <script type="text/javascript">
  767: // <![CDATA[
  768: 
  769: function setCustomFields() {
  770:     if (document.docustom.customroleaction.length > 0) {
  771:         for (var i=0; i<document.docustom.customroleaction.length; i++) {
  772:             if (document.docustom.customroleaction[i].checked) {
  773:                 if (document.docustom.customroleaction[i].value == 'new') {
  774:                     document.docustom.rolename.selectedIndex = 0;
  775:                 } else {
  776:                     document.docustom.newrolename.value = '';
  777:                 }
  778:             }
  779:         }
  780:     }
  781:     return;
  782: }
  783: 
  784: function setCustomAction(caller) {
  785:     if (document.docustom.customroleaction.length > 0) {
  786:         for (var i=0; i<document.docustom.customroleaction.length; i++) {
  787:             if (document.docustom.customroleaction[i].value == caller) {
  788:                 document.docustom.customroleaction[i].checked = true;
  789:             }
  790:         }
  791:     }
  792:     setCustomFields();
  793:     return;
  794: }
  795: 
  796: // ]]>
  797: </script>
  798: END
  799:     return $js;
  800: }
  801: 
  802: sub entry_form {
  803:     my ($dom,$srch,$forcenewuser,$context,$responsemsg,$crstype) = @_;
  804:     my ($usertype,$inexact);
  805:     if (ref($srch) eq 'HASH') {
  806:         if (($srch->{'srchin'} eq 'dom') &&
  807:             ($srch->{'srchby'} eq 'uname') &&
  808:             ($srch->{'srchtype'} eq 'exact') &&
  809:             ($srch->{'srchdomain'} ne '') &&
  810:             ($srch->{'srchterm'} ne '')) {
  811:             my (%curr_rules,%got_rules);
  812:             my ($rules,$ruleorder) =
  813:                 &Apache::lonnet::inst_userrules($srch->{'srchdomain'},'username');
  814:             $usertype = &Apache::lonuserutils::check_usertype($srch->{'srchdomain'},$srch->{'srchterm'},$rules,\%curr_rules,\%got_rules);
  815:         } else {
  816:             $inexact = 1;
  817:         }
  818:     }
  819:     my $cancreate =
  820:         &Apache::lonuserutils::can_create_user($dom,$context,$usertype);
  821:     my ($userpicker,$cansearch) = 
  822:        &Apache::loncommon::user_picker($dom,$srch,$forcenewuser,
  823:                                        'document.crtuser',$cancreate,$usertype);
  824:     my $srchbutton = &mt('Search');
  825:     if ($env{'form.action'} eq 'singlestudent') {
  826:         $srchbutton = &mt('Search and Enroll');
  827:     } elsif ($cancreate && $responsemsg ne '' && $inexact) {
  828:         $srchbutton = &mt('Search or Add New User');
  829:     }
  830:     my $output;
  831:     if ($cansearch) {
  832:         $output = <<"ENDBLOCK";
  833: <form action="/adm/createuser" method="post" name="crtuser">
  834: <input type="hidden" name="action" value="$env{'form.action'}" />
  835: <input type="hidden" name="phase" value="get_user_info" />
  836: $userpicker
  837: <input name="userrole" type="button" value="$srchbutton" onclick="javascript:validateEntry(document.crtuser)" />
  838: </form>
  839: ENDBLOCK
  840:     } else {
  841:         $output = '<p>'.$userpicker.'</p>';
  842:     }
  843:     if ($env{'form.phase'} eq '') {
  844:         my $defdom=$env{'request.role.domain'};
  845:         my $domform = &Apache::loncommon::select_dom_form($defdom,'srchdomain');
  846:         my %lt=&Apache::lonlocal::texthash(
  847:                   'enro' => 'Enroll one student',
  848:                   'enrm' => 'Enroll one member',
  849:                   'admo' => 'Add/modify a single user',
  850:                   'crea' => 'create new user if required',
  851:                   'uskn' => "username is known",
  852:                   'crnu' => 'Create a new user',
  853:                   'usr'  => 'Username',
  854:                   'dom'  => 'in domain',
  855:                   'enrl' => 'Enroll',
  856:                   'cram'  => 'Create/Modify user',
  857:         );
  858:         my $sellink=&Apache::loncommon::selectstudent_link('crtusername','srchterm','srchdomain');
  859:         my ($title,$buttontext,$showresponse);
  860:         if ($env{'form.action'} eq 'singlestudent') {
  861:             if ($crstype eq 'Community') {
  862:                 $title = $lt{'enrm'};
  863:             } else {
  864:                 $title = $lt{'enro'};
  865:             }
  866:             $buttontext = $lt{'enrl'};
  867:         } else {
  868:             $title = $lt{'admo'};
  869:             $buttontext = $lt{'cram'};
  870:         }
  871:         if ($cancreate) {
  872:             $title .= ' <span class="LC_cusr_subheading">('.$lt{'crea'}.')</span>';
  873:         } else {
  874:             $title .= ' <span class="LC_cusr_subheading">('.$lt{'uskn'}.')</span>';
  875:         }
  876:         if ($env{'form.origform'} eq 'crtusername') {
  877:             $showresponse = $responsemsg;
  878:         }
  879:         $output .= <<"ENDDOCUMENT";
  880: <br />
  881: <form action="/adm/createuser" method="post" name="crtusername">
  882: <input type="hidden" name="action" value="$env{'form.action'}" />
  883: <input type="hidden" name="phase" value="createnewuser" />
  884: <input type="hidden" name="srchtype" value="exact" />
  885: <input type="hidden" name="srchby" value="uname" />
  886: <input type="hidden" name="srchin" value="dom" />
  887: <input type="hidden" name="forcenewuser" value="1" />
  888: <input type="hidden" name="origform" value="crtusername" />
  889: <h3>$title</h3>
  890: $showresponse
  891: <table>
  892:  <tr>
  893:   <td>$lt{'usr'}:</td>
  894:   <td><input type="text" size="15" name="srchterm" /></td>
  895:   <td>&nbsp;$lt{'dom'}:</td><td>$domform</td>
  896:   <td>&nbsp;$sellink&nbsp;</td>
  897:   <td>&nbsp;<input name="userrole" type="submit" value="$buttontext" /></td>
  898:  </tr>
  899: </table>
  900: </form>
  901: ENDDOCUMENT
  902:     }
  903:     return $output;
  904: }
  905: 
  906: sub user_modification_js {
  907:     my ($pjump_def,$dc_setcourse_code,$nondc_setsection_code,$groupslist)=@_;
  908:     
  909:     return <<END;
  910: <script type="text/javascript" language="Javascript">
  911: // <![CDATA[
  912: 
  913:     $pjump_def
  914:     $dc_setcourse_code
  915: 
  916:     function dateset() {
  917:         eval("document.cu."+document.cu.pres_marker.value+
  918:             ".value=document.cu.pres_value.value");
  919:         modalWindow.close();
  920:     }
  921: 
  922:     $nondc_setsection_code
  923: // ]]>
  924: </script>
  925: END
  926: }
  927: 
  928: # =================================================================== Phase two
  929: sub print_user_selection_page {
  930:     my ($r,$response,$srch,$srch_results,$srcharray,$context,$opener_elements,$crstype,$brcrum) = @_;
  931:     my @fields = ('username','domain','lastname','firstname','permanentemail');
  932:     my $sortby = $env{'form.sortby'};
  933: 
  934:     if (!grep(/^\Q$sortby\E$/,@fields)) {
  935:         $sortby = 'lastname';
  936:     }
  937: 
  938:     my ($jsback,$elements) = &crumb_utilities();
  939: 
  940:     my $jscript = (<<ENDSCRIPT);
  941: <script type="text/javascript">
  942: // <![CDATA[
  943: function pickuser(uname,udom) {
  944:     document.usersrchform.seluname.value=uname;
  945:     document.usersrchform.seludom.value=udom;
  946:     document.usersrchform.phase.value="userpicked";
  947:     document.usersrchform.submit();
  948: }
  949: 
  950: $jsback
  951: // ]]>
  952: </script>
  953: ENDSCRIPT
  954: 
  955:     my %lt=&Apache::lonlocal::texthash(
  956:                                        'usrch'          => "User Search to add/modify roles",
  957:                                        'stusrch'        => "User Search to enroll student",
  958:                                        'memsrch'        => "User Search to enroll member",
  959:                                        'usel'           => "Select a user to add/modify roles",
  960:                                        'stusel'         => "Select a user to enroll as a student",
  961:                                        'memsel'         => "Select a user to enroll as a member",
  962:                                        'username'       => "username",
  963:                                        'domain'         => "domain",
  964:                                        'lastname'       => "last name",
  965:                                        'firstname'      => "first name",
  966:                                        'permanentemail' => "permanent e-mail",
  967:                                       );
  968:     if ($context eq 'requestcrs') {
  969:         $r->print('<div>');
  970:     } else {
  971:         my %breadcrumb_text = &singleuser_breadcrumb($crstype);
  972:         my $helpitem;
  973:         if ($env{'form.action'} eq 'singleuser') {
  974:             $helpitem = 'Course_Change_Privileges';
  975:         } elsif ($env{'form.action'} eq 'singlestudent') {
  976:             $helpitem = 'Course_Add_Student';
  977:         }
  978:         push (@{$brcrum},
  979:                   {href => "javascript:backPage(document.usersrchform,'','')",
  980:                    text => $breadcrumb_text{'search'},
  981:                    faq  => 282,
  982:                    bug  => 'Instructor Interface',},
  983:                   {href => "javascript:backPage(document.usersrchform,'get_user_info','select')",
  984:                    text => $breadcrumb_text{'userpicked'},
  985:                    faq  => 282,
  986:                    bug  => 'Instructor Interface',
  987:                    help => $helpitem}
  988:                   );
  989:         $r->print(&Apache::loncommon::start_page('User Management',$jscript,{bread_crumbs => $brcrum}));
  990:         if ($env{'form.action'} eq 'singleuser') {
  991:             $r->print("<b>$lt{'usrch'}</b><br />");
  992:             $r->print(&entry_form($srch->{'srchdomain'},$srch,undef,$context,undef,$crstype));
  993:             $r->print('<h3>'.$lt{'usel'}.'</h3>');
  994:         } elsif ($env{'form.action'} eq 'singlestudent') {
  995:             $r->print($jscript."<b>");
  996:             if ($crstype eq 'Community') {
  997:                 $r->print($lt{'memsrch'});
  998:             } else {
  999:                 $r->print($lt{'stusrch'});
 1000:             }
 1001:             $r->print("</b><br />");
 1002:             $r->print(&entry_form($srch->{'srchdomain'},$srch,undef,$context,undef,$crstype));
 1003:             $r->print('</form><h3>');
 1004:             if ($crstype eq 'Community') {
 1005:                 $r->print($lt{'memsel'});
 1006:             } else {
 1007:                 $r->print($lt{'stusel'});
 1008:             }
 1009:             $r->print('</h3>');
 1010:         }
 1011:     }
 1012:     $r->print('<form name="usersrchform" method="post" action="">'.
 1013:               &Apache::loncommon::start_data_table()."\n".
 1014:               &Apache::loncommon::start_data_table_header_row()."\n".
 1015:               ' <th> </th>'."\n");
 1016:     foreach my $field (@fields) {
 1017:         $r->print(' <th><a href="javascript:document.usersrchform.sortby.value='.
 1018:                   "'".$field."'".';document.usersrchform.submit();">'.
 1019:                   $lt{$field}.'</a></th>'."\n");
 1020:     }
 1021:     $r->print(&Apache::loncommon::end_data_table_header_row());
 1022: 
 1023:     my @sorted_users = sort {
 1024:         lc($srch_results->{$a}->{$sortby})   cmp lc($srch_results->{$b}->{$sortby})
 1025:             ||
 1026:         lc($srch_results->{$a}->{lastname})  cmp lc($srch_results->{$b}->{lastname})
 1027:             ||
 1028:         lc($srch_results->{$a}->{firstname}) cmp lc($srch_results->{$b}->{firstname})
 1029: 	    ||
 1030: 	lc($a) cmp lc($b)
 1031:         } (keys(%$srch_results));
 1032: 
 1033:     foreach my $user (@sorted_users) {
 1034:         my ($uname,$udom) = split(/:/,$user);
 1035:         my $onclick;
 1036:         if ($context eq 'requestcrs') {
 1037:             $onclick =
 1038:                 'onclick="javascript:gochoose('."'$uname','$udom',".
 1039:                                                "'$srch_results->{$user}->{firstname}',".
 1040:                                                "'$srch_results->{$user}->{lastname}',".
 1041:                                                "'$srch_results->{$user}->{permanentemail}'".');"';
 1042:         } else {
 1043:             $onclick =
 1044:                 ' onclick="javascript:pickuser('."'".$uname."'".','."'".$udom."'".');"';
 1045:         }
 1046:         $r->print(&Apache::loncommon::start_data_table_row().
 1047:                   '<td><input type="button" name="seluser" value="'.&mt('Select').'" '.
 1048:                   $onclick.' /></td>'.
 1049:                   '<td><tt>'.$uname.'</tt></td>'.
 1050:                   '<td><tt>'.$udom.'</tt></td>');
 1051:         foreach my $field ('lastname','firstname','permanentemail') {
 1052:             $r->print('<td>'.$srch_results->{$user}->{$field}.'</td>');
 1053:         }
 1054:         $r->print(&Apache::loncommon::end_data_table_row());
 1055:     }
 1056:     $r->print(&Apache::loncommon::end_data_table().'<br /><br />');
 1057:     if (ref($srcharray) eq 'ARRAY') {
 1058:         foreach my $item (@{$srcharray}) {
 1059:             $r->print('<input type="hidden" name="'.$item.'" value="'.$env{'form.'.$item}.'" />'."\n");
 1060:         }
 1061:     }
 1062:     $r->print(' <input type="hidden" name="sortby" value="'.$sortby.'" />'."\n".
 1063:               ' <input type="hidden" name="seluname" value="" />'."\n".
 1064:               ' <input type="hidden" name="seludom" value="" />'."\n".
 1065:               ' <input type="hidden" name="currstate" value="select" />'."\n".
 1066:               ' <input type="hidden" name="phase" value="get_user_info" />'."\n".
 1067:               ' <input type="hidden" name="action" value="'.$env{'form.action'}.'" />'."\n");
 1068:     if ($context eq 'requestcrs') {
 1069:         $r->print($opener_elements.'</form></div>');
 1070:     } else {
 1071:         $r->print($response.'</form>');
 1072:     }
 1073: }
 1074: 
 1075: sub print_user_query_page {
 1076:     my ($r,$caller,$brcrum) = @_;
 1077: # FIXME - this is for a network-wide name search (similar to catalog search)
 1078: # To use frames with similar behavior to catalog/portfolio search.
 1079: # To be implemented. 
 1080:     return;
 1081: }
 1082: 
 1083: sub print_user_modification_page {
 1084:     my ($r,$ccuname,$ccdomain,$srch,$response,$context,$permission,$crstype,
 1085:         $brcrum,$showcredits) = @_;
 1086:     if (($ccuname eq '') || ($ccdomain eq '')) {
 1087:         my $usermsg = &mt('No username and/or domain provided.');
 1088:         $env{'form.phase'} = '';
 1089: 	&print_username_entry_form($r,$context,$usermsg,'','',$crstype,$brcrum);
 1090:         return;
 1091:     }
 1092:     my ($form,$formname);
 1093:     if ($env{'form.action'} eq 'singlestudent') {
 1094:         $form = 'document.enrollstudent';
 1095:         $formname = 'enrollstudent';
 1096:     } else {
 1097:         $form = 'document.cu';
 1098:         $formname = 'cu';
 1099:     }
 1100:     my %abv_auth = &auth_abbrev();
 1101:     my (%rulematch,%inst_results,$newuser,%alerts,%curr_rules,%got_rules);
 1102:     my $uhome=&Apache::lonnet::homeserver($ccuname,$ccdomain);
 1103:     if ($uhome eq 'no_host') {
 1104:         my $usertype;
 1105:         my ($rules,$ruleorder) =
 1106:             &Apache::lonnet::inst_userrules($ccdomain,'username');
 1107:             $usertype =
 1108:                 &Apache::lonuserutils::check_usertype($ccdomain,$ccuname,$rules,
 1109:                                                       \%curr_rules,\%got_rules);
 1110:         my $cancreate =
 1111:             &Apache::lonuserutils::can_create_user($ccdomain,$context,
 1112:                                                    $usertype);
 1113:         if (!$cancreate) {
 1114:             my $helplink = 'javascript:helpMenu('."'display'".')';
 1115:             my %usertypetext = (
 1116:                 official   => 'institutional',
 1117:                 unofficial => 'non-institutional',
 1118:             );
 1119:             my $response;
 1120:             if ($env{'form.origform'} eq 'crtusername') {
 1121:                 $response = '<span class="LC_warning">'.
 1122:                             &mt('No match found for the username [_1] in LON-CAPA domain: [_2]',
 1123:                                 '<b>'.$ccuname.'</b>',$ccdomain).
 1124:                             '</span><br />';
 1125:             }
 1126:             $response .= '<p class="LC_warning">'
 1127:                         .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
 1128:                         .' '
 1129:                         .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
 1130:                             ,'<a href="'.$helplink.'">','</a>')
 1131:                         .'</p><br />';
 1132:             $env{'form.phase'} = '';
 1133:             &print_username_entry_form($r,$context,$response,undef,undef,$crstype,$brcrum);
 1134:             return;
 1135:         }
 1136:         $newuser = 1;
 1137:         my $checkhash;
 1138:         my $checks = { 'username' => 1 };
 1139:         $checkhash->{$ccuname.':'.$ccdomain} = { 'newuser' => $newuser };
 1140:         &Apache::loncommon::user_rule_check($checkhash,$checks,
 1141:             \%alerts,\%rulematch,\%inst_results,\%curr_rules,\%got_rules);
 1142:         if (ref($alerts{'username'}) eq 'HASH') {
 1143:             if (ref($alerts{'username'}{$ccdomain}) eq 'HASH') {
 1144:                 my $domdesc =
 1145:                     &Apache::lonnet::domain($ccdomain,'description');
 1146:                 if ($alerts{'username'}{$ccdomain}{$ccuname}) {
 1147:                     my $userchkmsg;
 1148:                     if (ref($curr_rules{$ccdomain}) eq 'HASH') {  
 1149:                         $userchkmsg = 
 1150:                             &Apache::loncommon::instrule_disallow_msg('username',
 1151:                                                                  $domdesc,1).
 1152:                         &Apache::loncommon::user_rule_formats($ccdomain,
 1153:                             $domdesc,$curr_rules{$ccdomain}{'username'},
 1154:                             'username');
 1155:                     }
 1156:                     $env{'form.phase'} = '';
 1157:                     &print_username_entry_form($r,$context,$userchkmsg,undef,undef,$crstype,$brcrum);
 1158:                     return;
 1159:                 }
 1160:             }
 1161:         }
 1162:     } else {
 1163:         $newuser = 0;
 1164:     }
 1165:     if ($response) {
 1166:         $response = '<br />'.$response;
 1167:     }
 1168: 
 1169:     my $pjump_def = &Apache::lonhtmlcommon::pjump_javascript_definition();
 1170:     my $dc_setcourse_code = '';
 1171:     my $nondc_setsection_code = '';                                        
 1172:     my %loaditem;
 1173: 
 1174:     my $groupslist = &Apache::lonuserutils::get_groupslist();
 1175: 
 1176:     my $js = &validation_javascript($context,$ccdomain,$pjump_def,$crstype,
 1177:                                $groupslist,$newuser,$formname,\%loaditem);
 1178:     my %breadcrumb_text = &singleuser_breadcrumb($crstype);
 1179:     my $helpitem = 'Course_Change_Privileges';
 1180:     if ($env{'form.action'} eq 'singlestudent') {
 1181:         $helpitem = 'Course_Add_Student';
 1182:     }
 1183:     push (@{$brcrum},
 1184:         {href => "javascript:backPage($form)",
 1185:          text => $breadcrumb_text{'search'},
 1186:          faq  => 282,
 1187:          bug  => 'Instructor Interface',});
 1188:     if ($env{'form.phase'} eq 'userpicked') {
 1189:        push(@{$brcrum},
 1190:               {href => "javascript:backPage($form,'get_user_info','select')",
 1191:                text => $breadcrumb_text{'userpicked'},
 1192:                faq  => 282,
 1193:                bug  => 'Instructor Interface',});
 1194:     }
 1195:     push(@{$brcrum},
 1196:             {href => "javascript:backPage($form,'$env{'form.phase'}','modify')",
 1197:              text => $breadcrumb_text{'modify'},
 1198:              faq  => 282,
 1199:              bug  => 'Instructor Interface',
 1200:              help => $helpitem});
 1201:     my $args = {'add_entries'           => \%loaditem,
 1202:                 'bread_crumbs'          => $brcrum,
 1203:                 'bread_crumbs_component' => 'User Management'};
 1204:     if ($env{'form.popup'}) {
 1205:         $args->{'no_nav_bar'} = 1;
 1206:     }
 1207:     my $start_page =
 1208:         &Apache::loncommon::start_page('User Management',$js,$args);
 1209: 
 1210:     my $forminfo =<<"ENDFORMINFO";
 1211: <form action="/adm/createuser" method="post" name="$formname">
 1212: <input type="hidden" name="phase" value="update_user_data" />
 1213: <input type="hidden" name="ccuname" value="$ccuname" />
 1214: <input type="hidden" name="ccdomain" value="$ccdomain" />
 1215: <input type="hidden" name="pres_value"  value="" />
 1216: <input type="hidden" name="pres_type"   value="" />
 1217: <input type="hidden" name="pres_marker" value="" />
 1218: ENDFORMINFO
 1219:     my (%inccourses,$roledom,$defaultcredits);
 1220:     if ($context eq 'course') {
 1221:         $inccourses{$env{'request.course.id'}}=1;
 1222:         $roledom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 1223:         if ($showcredits) {
 1224:             $defaultcredits = &Apache::lonuserutils::get_defaultcredits();
 1225:         }
 1226:     } elsif ($context eq 'author') {
 1227:         $roledom = $env{'request.role.domain'};
 1228:     } elsif ($context eq 'domain') {
 1229:         foreach my $key (keys(%env)) {
 1230:             $roledom = $env{'request.role.domain'};
 1231:             if ($key=~/^user\.priv\.cm\.\/($roledom)\/($match_username)/) {
 1232:                 $inccourses{$1.'_'.$2}=1;
 1233:             }
 1234:         }
 1235:     } else {
 1236:         foreach my $key (keys(%env)) {
 1237: 	    if ($key=~/^user\.priv\.cm\.\/($match_domain)\/($match_username)/) {
 1238: 	        $inccourses{$1.'_'.$2}=1;
 1239:             }
 1240:         }
 1241:     }
 1242:     my $title = '';
 1243:     if ($newuser) {
 1244:         my ($portfolioform,$domroleform);
 1245:         if ((&Apache::lonnet::allowed('mpq',$env{'request.role.domain'})) ||
 1246:             (&Apache::lonnet::allowed('mut',$env{'request.role.domain'}))) {
 1247:             # Current user has quota or user tools modification privileges
 1248:             $portfolioform = '<br />'.&user_quotas($ccuname,$ccdomain);
 1249:         }
 1250:         if ((&Apache::lonnet::allowed('cau',$env{'request.role.domain'})) &&
 1251:             ($ccdomain eq $env{'request.role.domain'})) {
 1252:             $domroleform = '<br />'.&domainrole_req($ccuname,$ccdomain);
 1253:         }
 1254:         &initialize_authen_forms($ccdomain,$formname);
 1255:         my %lt=&Apache::lonlocal::texthash(
 1256:                 'lg'             => 'Login Data',
 1257:                 'hs'             => "Home Server",
 1258:         );
 1259: 	$r->print(<<ENDTITLE);
 1260: $start_page
 1261: $response
 1262: $forminfo
 1263: <script type="text/javascript" language="Javascript">
 1264: // <![CDATA[
 1265: $loginscript
 1266: // ]]>
 1267: </script>
 1268: <input type='hidden' name='makeuser' value='1' />
 1269: ENDTITLE
 1270:         if ($env{'form.action'} eq 'singlestudent') {
 1271:             if ($crstype eq 'Community') {
 1272:                 $title = &mt('Create New User [_1] in domain [_2] as a member',
 1273:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1274:             } else {
 1275:                 $title = &mt('Create New User [_1] in domain [_2] as a student',
 1276:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1277:             }
 1278:         } else {
 1279:                 $title = &mt('Create New User [_1] in domain [_2]',
 1280:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1281:         }
 1282:         $r->print('<h2>'.$title.'</h2>'."\n");
 1283:         $r->print('<div class="LC_left_float">');
 1284:         $r->print(&personal_data_display($ccuname,$ccdomain,$newuser,$context,
 1285:                                          $inst_results{$ccuname.':'.$ccdomain}));
 1286:         # Option to disable student/employee ID conflict checking not offerred for new users.
 1287:         my ($home_server_pick,$numlib) = 
 1288:             &Apache::loncommon::home_server_form_item($ccdomain,'hserver',
 1289:                                                       'default','hide');
 1290:         if ($numlib > 1) {
 1291:             $r->print("
 1292: <br />
 1293: $lt{'hs'}: $home_server_pick
 1294: <br />");
 1295:         } else {
 1296:             $r->print($home_server_pick);
 1297:         }
 1298:         if (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) {
 1299:             $r->print('<br /><h3>'.
 1300:                       &mt('User Can Request Creation of Courses/Communities in this Domain?').'</h3>'.
 1301:                       &Apache::loncommon::start_data_table().
 1302:                       &build_tools_display($ccuname,$ccdomain,
 1303:                                            'requestcourses').
 1304:                       &Apache::loncommon::end_data_table());
 1305:         }
 1306:         $r->print('</div>'."\n".'<div class="LC_left_float"><h3>'.
 1307:                   $lt{'lg'}.'</h3>');
 1308:         my ($fixedauth,$varauth,$authmsg); 
 1309:         if (ref($rulematch{$ccuname.':'.$ccdomain}) eq 'HASH') {
 1310:             my $matchedrule = $rulematch{$ccuname.':'.$ccdomain}{'username'};
 1311:             my ($rules,$ruleorder) = 
 1312:                 &Apache::lonnet::inst_userrules($ccdomain,'username');
 1313:             if (ref($rules) eq 'HASH') {
 1314:                 if (ref($rules->{$matchedrule}) eq 'HASH') {
 1315:                     my $authtype = $rules->{$matchedrule}{'authtype'};
 1316:                     if ($authtype !~ /^(krb4|krb5|int|fsys|loc)$/) {
 1317:                         $r->print(&Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc));
 1318:                     } else { 
 1319:                         my $authparm = $rules->{$matchedrule}{'authparm'};
 1320:                         $authmsg = $rules->{$matchedrule}{'authmsg'};
 1321:                         if ($authtype =~ /^krb(4|5)$/) {
 1322:                             my $ver = $1;
 1323:                             if ($authparm ne '') {
 1324:                                 $fixedauth = <<"KERB"; 
 1325: <input type="hidden" name="login" value="krb" />
 1326: <input type="hidden" name="krbver" value="$ver" />
 1327: <input type="hidden" name="krbarg" value="$authparm" />
 1328: KERB
 1329:                             }
 1330:                         } else {
 1331:                             $fixedauth = 
 1332: '<input type="hidden" name="login" value="'.$authtype.'" />'."\n";
 1333:                             if ($rules->{$matchedrule}{'authparmfixed'}) {
 1334:                                 $fixedauth .=    
 1335: '<input type="hidden" name="'.$authtype.'arg" value="'.$authparm.'" />'."\n";
 1336:                             } else {
 1337:                                 if ($authtype eq 'int') {
 1338:                                     $varauth = '<br />'.
 1339: &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>';
 1340:                                 } elsif ($authtype eq 'loc') {
 1341:                                     $varauth = '<br />'.
 1342: &mt('[_1] Local Authentication with argument [_2]','','<input type="text" name="'.$authtype.'arg" value="" />')."\n";
 1343:                                 } else {
 1344:                                     $varauth =
 1345: '<input type="text" name="'.$authtype.'arg" value="" />'."\n";
 1346:                                 }
 1347:                             }
 1348:                         }
 1349:                     }
 1350:                 } else {
 1351:                     $r->print(&Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc));
 1352:                 }
 1353:             }
 1354:             if ($authmsg) {
 1355:                 $r->print(<<ENDAUTH);
 1356: $fixedauth
 1357: $authmsg
 1358: $varauth
 1359: ENDAUTH
 1360:             }
 1361:         } else {
 1362:             $r->print(&Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc)); 
 1363:         }
 1364:         $r->print($portfolioform.$domroleform);
 1365:         if ($env{'form.action'} eq 'singlestudent') {
 1366:             $r->print(&date_sections_select($context,$newuser,$formname,
 1367:                                             $permission,$crstype,$ccuname,
 1368:                                             $ccdomain,$showcredits));
 1369:         }
 1370:         $r->print('</div><div class="LC_clear_float_footer"></div>');
 1371:     } else { # user already exists
 1372: 	$r->print($start_page.$forminfo);
 1373:         if ($env{'form.action'} eq 'singlestudent') {
 1374:             if ($crstype eq 'Community') {
 1375:                 $title = &mt('Enroll one member: [_1] in domain [_2]',
 1376:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1377:             } else {
 1378:                 $title = &mt('Enroll one student: [_1] in domain [_2]',
 1379:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1380:             }
 1381:         } else {
 1382:             $title = &mt('Modify existing user: [_1] in domain [_2]',
 1383:                              '"'.$ccuname.'"','"'.$ccdomain.'"');
 1384:         }
 1385:         $r->print('<h2>'.$title.'</h2>'."\n");
 1386:         $r->print('<div class="LC_left_float">');
 1387:         $r->print(&personal_data_display($ccuname,$ccdomain,$newuser,$context,
 1388:                                          $inst_results{$ccuname.':'.$ccdomain}));
 1389:         if (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) {
 1390:             $r->print('<br /><h3>'.&mt('User Can Request Creation of Courses/Communities in this Domain?').'</h3>'.
 1391:                       &Apache::loncommon::start_data_table());
 1392:             if ($env{'request.role.domain'} eq $ccdomain) {
 1393:                 $r->print(&build_tools_display($ccuname,$ccdomain,'requestcourses'));
 1394:             } else {
 1395:                 $r->print(&coursereq_externaluser($ccuname,$ccdomain,
 1396:                                                   $env{'request.role.domain'}));
 1397:             }
 1398:             $r->print(&Apache::loncommon::end_data_table());
 1399:         }
 1400:         $r->print('</div>');
 1401:         my @order = ('auth','quota','tools','requestauthor');
 1402:         my %user_text;
 1403:         my ($isadv,$isauthor) = 
 1404:             &Apache::lonnet::is_advanced_user($ccuname,$ccdomain);
 1405:         if ((!$isauthor) && 
 1406:             (&Apache::lonnet::allowed('cau',$env{'request.role.domain'}))
 1407:             && ($env{'request.role.domain'} eq $ccdomain)) {
 1408:             $user_text{'requestauthor'} = &domainrole_req($ccuname,$ccdomain);
 1409:         }
 1410:         $user_text{'auth'} =  &user_authentication($ccuname,$ccdomain,$formname);
 1411:         if ((&Apache::lonnet::allowed('mpq',$ccdomain)) ||
 1412:             (&Apache::lonnet::allowed('mut',$ccdomain))) {
 1413:             # Current user has quota modification privileges
 1414:             $user_text{'quota'} = &user_quotas($ccuname,$ccdomain);
 1415:         }
 1416:         if (!&Apache::lonnet::allowed('mpq',$ccdomain)) {
 1417:             if (&Apache::lonnet::allowed('mpq',$env{'request.role.domain'})) {
 1418:                 my %lt=&Apache::lonlocal::texthash(
 1419:                     'dska'  => "Disk quotas for user's portfolio and Authoring Space",
 1420:                     'youd'  => "You do not have privileges to modify the portfolio and/or Authoring Space quotas for this user.",
 1421:                     'ichr'  => "If a change is required, contact a domain coordinator for the domain",
 1422:                 );
 1423:                 $user_text{'quota'} = <<ENDNOPORTPRIV;
 1424: <h3>$lt{'dska'}</h3>
 1425: $lt{'youd'} $lt{'ichr'}: $ccdomain
 1426: ENDNOPORTPRIV
 1427:             }
 1428:         }
 1429:         if (!&Apache::lonnet::allowed('mut',$ccdomain)) {
 1430:             if (&Apache::lonnet::allowed('mut',$env{'request.role.domain'})) {
 1431:                 my %lt=&Apache::lonlocal::texthash(
 1432:                     'utav'  => "User Tools Availability",
 1433:                     'yodo'  => "You do not have privileges to modify Portfolio, Blog, WebDAV, or Personal Information Page settings for this user.",
 1434:                     'ifch'  => "If a change is required, contact a domain coordinator for the domain",
 1435:                 );
 1436:                 $user_text{'tools'} = <<ENDNOTOOLSPRIV;
 1437: <h3>$lt{'utav'}</h3>
 1438: $lt{'yodo'} $lt{'ifch'}: $ccdomain
 1439: ENDNOTOOLSPRIV
 1440:             }
 1441:         }
 1442:         my $gotdiv = 0; 
 1443:         foreach my $item (@order) {
 1444:             if ($user_text{$item} ne '') {
 1445:                 unless ($gotdiv) {
 1446:                     $r->print('<div class="LC_left_float">');
 1447:                     $gotdiv = 1;
 1448:                 }
 1449:                 $r->print('<br />'.$user_text{$item});
 1450:             }
 1451:         }
 1452:         if ($env{'form.action'} eq 'singlestudent') {
 1453:             unless ($gotdiv) {
 1454:                 $r->print('<div class="LC_left_float">');
 1455:             }
 1456:             my $credits;
 1457:             if ($showcredits) {
 1458:                 $credits = &get_user_credits($ccuname,$ccdomain,$defaultcredits);
 1459:                 if ($credits eq '') {
 1460:                     $credits = $defaultcredits;
 1461:                 }
 1462:             }
 1463:             $r->print(&date_sections_select($context,$newuser,$formname,
 1464:                                             $permission,$crstype,$ccuname,
 1465:                                             $ccdomain,$showcredits));
 1466:         }
 1467:         if ($gotdiv) {
 1468:             $r->print('</div><div class="LC_clear_float_footer"></div>');
 1469:         }
 1470:         if ($env{'form.action'} ne 'singlestudent') {
 1471:             &display_existing_roles($r,$ccuname,$ccdomain,\%inccourses,$context,
 1472:                                     $roledom,$crstype);
 1473:         }
 1474:     } ## End of new user/old user logic
 1475:     if ($env{'form.action'} eq 'singlestudent') {
 1476:         my $btntxt;
 1477:         if ($crstype eq 'Community') {
 1478:             $btntxt = &mt('Enroll Member');
 1479:         } else {
 1480:             $btntxt = &mt('Enroll Student');
 1481:         }
 1482:         $r->print('<br /><input type="button" value="'.$btntxt.'" onclick="setSections(this.form)" />'."\n");
 1483:     } else {
 1484:         $r->print('<div class="LC_left_float">'.
 1485:                   '<fieldset><legend>'.&mt('Add Roles').'</legend>');
 1486:         my $addrolesdisplay = 0;
 1487:         if ($context eq 'domain' || $context eq 'author') {
 1488:             $addrolesdisplay = &new_coauthor_roles($r,$ccuname,$ccdomain);
 1489:         }
 1490:         if ($context eq 'domain') {
 1491:             my $add_domainroles = &new_domain_roles($r,$ccdomain);
 1492:             if (!$addrolesdisplay) {
 1493:                 $addrolesdisplay = $add_domainroles;
 1494:             }
 1495:             $r->print(&course_level_dc($env{'request.role.domain'},$showcredits));
 1496:             $r->print('</fieldset></div><div class="LC_clear_float_footer"></div>'.
 1497:                       '<br /><input type="button" value="'.&mt('Save').'" onclick="setCourse()" />'."\n");
 1498:         } elsif ($context eq 'author') {
 1499:             if ($addrolesdisplay) {
 1500:                 $r->print('</fieldset></div><div class="LC_clear_float_footer"></div>'.
 1501:                           '<br /><input type="button" value="'.&mt('Save').'"');
 1502:                 if ($newuser) {
 1503:                     $r->print(' onclick="auth_check()" \>'."\n");
 1504:                 } else {
 1505:                     $r->print('onclick="this.form.submit()" \>'."\n");
 1506:                 }
 1507:             } else {
 1508:                 $r->print('</fieldset></div>'.
 1509:                           '<div class="LC_clear_float_footer"></div>'.
 1510:                           '<br /><a href="javascript:backPage(document.cu)">'.
 1511:                           &mt('Back to previous page').'</a>');
 1512:             }
 1513:         } else {
 1514:             $r->print(&course_level_table(\%inccourses,$showcredits,$defaultcredits));
 1515:             $r->print('</fieldset></div><div class="LC_clear_float_footer"></div>'.
 1516:                       '<br /><input type="button" value="'.&mt('Save').'" onclick="setSections(this.form)" />'."\n");
 1517:         }
 1518:     }
 1519:     $r->print(&Apache::lonhtmlcommon::echo_form_input(['phase','userrole','ccdomain','prevphase','currstate','ccuname','ccdomain']));
 1520:     $r->print('<input type="hidden" name="currstate" value="" />');
 1521:     $r->print('<input type="hidden" name="prevphase" value="'.$env{'form.phase'}.'" /></form><br /><br />');
 1522:     return;
 1523: }
 1524: 
 1525: sub singleuser_breadcrumb {
 1526:     my ($crstype) = @_;
 1527:     my %breadcrumb_text;
 1528:     if ($env{'form.action'} eq 'singlestudent') {
 1529:         if ($crstype eq 'Community') {
 1530:             $breadcrumb_text{'search'} = 'Enroll a member';
 1531:         } else {
 1532:             $breadcrumb_text{'search'} = 'Enroll a student';
 1533:         }
 1534:         $breadcrumb_text{'userpicked'} = 'Select a user',
 1535:         $breadcrumb_text{'modify'} = 'Set section/dates',
 1536:     } else {
 1537:         $breadcrumb_text{'search'} = 'Create/modify a user';
 1538:         $breadcrumb_text{'userpicked'} = 'Select a user',
 1539:         $breadcrumb_text{'modify'} = 'Set user role',
 1540:     }
 1541:     return %breadcrumb_text;
 1542: }
 1543: 
 1544: sub date_sections_select {
 1545:     my ($context,$newuser,$formname,$permission,$crstype,$ccuname,$ccdomain,
 1546:         $showcredits) = @_;
 1547:     my $credits;
 1548:     if ($showcredits) {
 1549:         my $defaultcredits = &Apache::lonuserutils::get_defaultcredits();
 1550:         $credits = &get_user_credits($ccuname,$ccdomain,$defaultcredits);
 1551:         if ($credits eq '') {
 1552:             $credits = $defaultcredits;
 1553:         }
 1554:     }
 1555:     my $cid = $env{'request.course.id'};
 1556:     my ($cnum,$cdom) = &Apache::lonuserutils::get_course_identity($cid);
 1557:     my $date_table = '<h3>'.&mt('Starting and Ending Dates').'</h3>'."\n".
 1558:         &Apache::lonuserutils::date_setting_table(undef,undef,$context,
 1559:                                                   undef,$formname,$permission);
 1560:     my $rowtitle = 'Section';
 1561:     my $secbox = '<h3>'.&mt('Section and Credits').'</h3>'."\n".
 1562:         &Apache::lonuserutils::section_picker($cdom,$cnum,'st',$rowtitle,
 1563:                                               $permission,$context,'',$crstype,
 1564:                                               $showcredits,$credits);
 1565:     my $output = $date_table.$secbox;
 1566:     return $output;
 1567: }
 1568: 
 1569: sub validation_javascript {
 1570:     my ($context,$ccdomain,$pjump_def,$crstype,$groupslist,$newuser,$formname,
 1571:         $loaditem) = @_;
 1572:     my $dc_setcourse_code = '';
 1573:     my $nondc_setsection_code = '';
 1574:     if ($context eq 'domain') {
 1575:         my $dcdom = $env{'request.role.domain'};
 1576:         $loaditem->{'onload'} = "document.cu.coursedesc.value='';";
 1577:         $dc_setcourse_code = 
 1578:             &Apache::lonuserutils::dc_setcourse_js('cu','singleuser',$context);
 1579:     } else {
 1580:         my $checkauth; 
 1581:         if (($newuser) || (&Apache::lonnet::allowed('mau',$ccdomain))) {
 1582:             $checkauth = 1;
 1583:         }
 1584:         if ($context eq 'course') {
 1585:             $nondc_setsection_code =
 1586:                 &Apache::lonuserutils::setsections_javascript($formname,$groupslist,
 1587:                                                               undef,$checkauth,
 1588:                                                               $crstype);
 1589:         }
 1590:         if ($checkauth) {
 1591:             $nondc_setsection_code .= 
 1592:                 &Apache::lonuserutils::verify_authen($formname,$context);
 1593:         }
 1594:     }
 1595:     my $js = &user_modification_js($pjump_def,$dc_setcourse_code,
 1596:                                    $nondc_setsection_code,$groupslist);
 1597:     my ($jsback,$elements) = &crumb_utilities();
 1598:     $js .= "\n".
 1599:            '<script type="text/javascript">'."\n".
 1600:            '// <![CDATA['."\n".
 1601:            $jsback."\n".
 1602:            '// ]]>'."\n".
 1603:            '</script>'."\n";
 1604:     return $js;
 1605: }
 1606: 
 1607: sub display_existing_roles {
 1608:     my ($r,$ccuname,$ccdomain,$inccourses,$context,$roledom,$crstype,
 1609:         $showcredits) = @_;
 1610:     my $now=time;
 1611:     my %lt=&Apache::lonlocal::texthash(
 1612:                     'rer'  => "Existing Roles",
 1613:                     'rev'  => "Revoke",
 1614:                     'del'  => "Delete",
 1615:                     'ren'  => "Re-Enable",
 1616:                     'rol'  => "Role",
 1617:                     'ext'  => "Extent",
 1618:                     'crd'  => "Credits",
 1619:                     'sta'  => "Start",
 1620:                     'end'  => "End",
 1621:                                        );
 1622:     my (%rolesdump,%roletext,%sortrole,%roleclass,%rolepriv);
 1623:     if ($context eq 'course' || $context eq 'author') {
 1624:         my @roles = &Apache::lonuserutils::roles_by_context($context,1,$crstype);
 1625:         my %roleshash = 
 1626:             &Apache::lonnet::get_my_roles($ccuname,$ccdomain,'userroles',
 1627:                               ['active','previous','future'],\@roles,$roledom,1);
 1628:         foreach my $key (keys(%roleshash)) {
 1629:             my ($start,$end) = split(':',$roleshash{$key});
 1630:             next if ($start eq '-1' || $end eq '-1');
 1631:             my ($rnum,$rdom,$role,$sec) = split(':',$key);
 1632:             if ($context eq 'course') {
 1633:                 next unless (($rnum eq $env{'course.'.$env{'request.course.id'}.'.num'})
 1634:                              && ($rdom eq $env{'course.'.$env{'request.course.id'}.'.domain'}));
 1635:             } elsif ($context eq 'author') {
 1636:                 next unless (($rnum eq $env{'user.name'}) && ($rdom eq $env{'request.role.domain'}));
 1637:             }
 1638:             my ($newkey,$newvalue,$newrole);
 1639:             $newkey = '/'.$rdom.'/'.$rnum;
 1640:             if ($sec ne '') {
 1641:                 $newkey .= '/'.$sec;
 1642:             }
 1643:             $newvalue = $role;
 1644:             if ($role =~ /^cr/) {
 1645:                 $newrole = 'cr';
 1646:             } else {
 1647:                 $newrole = $role;
 1648:             }
 1649:             $newkey .= '_'.$newrole;
 1650:             if ($start ne '' && $end ne '') {
 1651:                 $newvalue .= '_'.$end.'_'.$start;
 1652:             } elsif ($end ne '') {
 1653:                 $newvalue .= '_'.$end;
 1654:             }
 1655:             $rolesdump{$newkey} = $newvalue;
 1656:         }
 1657:     } else {
 1658:         %rolesdump=&Apache::lonnet::dump('roles',$ccdomain,$ccuname);
 1659:     }
 1660:     # Build up table of user roles to allow revocation and re-enabling of roles.
 1661:     my ($tmp) = keys(%rolesdump);
 1662:     return if ($tmp =~ /^(con_lost|error)/i);
 1663:     foreach my $area (sort { my $a1=join('_',(split('_',$a))[1,0]);
 1664:                                 my $b1=join('_',(split('_',$b))[1,0]);
 1665:                                 return $a1 cmp $b1;
 1666:                             } keys(%rolesdump)) {
 1667:         next if ($area =~ /^rolesdef/);
 1668:         my $envkey=$area;
 1669:         my $role = $rolesdump{$area};
 1670:         my $thisrole=$area;
 1671:         $area =~ s/\_\w\w$//;
 1672:         my ($role_code,$role_end_time,$role_start_time) =
 1673:             split(/_/,$role);
 1674: # Is this a custom role? Get role owner and title.
 1675:         my ($croleudom,$croleuname,$croletitle)=
 1676:             ($role_code=~m{^cr/($match_domain)/($match_username)/(\w+)$});
 1677:         my $allowed=0;
 1678:         my $delallowed=0;
 1679:         my $sortkey=$role_code;
 1680:         my $class='Unknown';
 1681:         my $credits='';
 1682:         if ($area =~ m{^/($match_domain)/($match_courseid)} ) {
 1683:             $class='Course';
 1684:             my ($coursedom,$coursedir) = ($1,$2);
 1685:             my $cid = $1.'_'.$2;
 1686:             # $1.'_'.$2 is the course id (eg. 103_12345abcef103l3).
 1687:             my %coursedata=
 1688:                 &Apache::lonnet::coursedescription($cid);
 1689:             if ($coursedir =~ /^$match_community$/) {
 1690:                 $class='Community';
 1691:             }
 1692:             $sortkey.="\0$coursedom";
 1693:             my $carea;
 1694:             if (defined($coursedata{'description'})) {
 1695:                 $carea=$coursedata{'description'}.
 1696:                     '<br />'.&mt('Domain').': '.$coursedom.('&nbsp;'x8).
 1697:     &Apache::loncommon::syllabuswrapper(&mt('Syllabus'),$coursedir,$coursedom);
 1698:                 $sortkey.="\0".$coursedata{'description'};
 1699:             } else {
 1700:                 if ($class eq 'Community') {
 1701:                     $carea=&mt('Unavailable community').': '.$area;
 1702:                     $sortkey.="\0".&mt('Unavailable community').': '.$area;
 1703:                 } else {
 1704:                     $carea=&mt('Unavailable course').': '.$area;
 1705:                     $sortkey.="\0".&mt('Unavailable course').': '.$area;
 1706:                 }
 1707:             }
 1708:             $sortkey.="\0$coursedir";
 1709:             $inccourses->{$cid}=1;
 1710:             if (($showcredits) && ($class eq 'Course') && ($role_code eq 'st')) {
 1711:                 my $defaultcredits = $coursedata{'internal.defaultcredits'};
 1712:                 $credits =
 1713:                     &get_user_credits($ccuname,$ccdomain,$defaultcredits,
 1714:                                       $coursedom,$coursedir);
 1715:                 if ($credits eq '') {
 1716:                     $credits = $defaultcredits;
 1717:                 }
 1718:             }
 1719:             if ((&Apache::lonnet::allowed('c'.$role_code,$coursedom.'/'.$coursedir)) ||
 1720:                 (&Apache::lonnet::allowed('c'.$role_code,$ccdomain))) {
 1721:                 $allowed=1;
 1722:             }
 1723:             unless ($allowed) {
 1724:                 my $isowner = &Apache::lonuserutils::is_courseowner($cid,$coursedata{'internal.courseowner'});
 1725:                 if ($isowner) {
 1726:                     if (($role_code eq 'co') && ($class eq 'Community')) {
 1727:                         $allowed = 1;
 1728:                     } elsif (($role_code eq 'cc') && ($class eq 'Course')) {
 1729:                         $allowed = 1;
 1730:                     }
 1731:                 }
 1732:             } 
 1733:             if ((&Apache::lonnet::allowed('dro',$coursedom)) ||
 1734:                 (&Apache::lonnet::allowed('dro',$ccdomain))) {
 1735:                 $delallowed=1;
 1736:             }
 1737: # - custom role. Needs more info, too
 1738:             if ($croletitle) {
 1739:                 if (&Apache::lonnet::allowed('ccr',$coursedom.'/'.$coursedir)) {
 1740:                     $allowed=1;
 1741:                     $thisrole.='.'.$role_code;
 1742:                 }
 1743:             }
 1744:             if ($area=~m{^/($match_domain)/($match_courseid)/(\w+)}) {
 1745:                 $carea.='<br />'.&mt('Section: [_1]',$3);
 1746:                 $sortkey.="\0$3";
 1747:                 if (!$allowed) {
 1748:                     if ($env{'request.course.sec'} eq $3) {
 1749:                         if (&Apache::lonnet::allowed('c'.$role_code,$1.'/'.$2.'/'.$3)) {
 1750:                             $allowed = 1;
 1751:                         }
 1752:                     }
 1753:                 }
 1754:             }
 1755:             $area=$carea;
 1756:         } else {
 1757:             $sortkey.="\0".$area;
 1758:             # Determine if current user is able to revoke privileges
 1759:             if ($area=~m{^/($match_domain)/}) {
 1760:                 if ((&Apache::lonnet::allowed('c'.$role_code,$1)) ||
 1761:                    (&Apache::lonnet::allowed('c'.$role_code,$ccdomain))) {
 1762:                    $allowed=1;
 1763:                 }
 1764:                 if (((&Apache::lonnet::allowed('dro',$1))  ||
 1765:                     (&Apache::lonnet::allowed('dro',$ccdomain))) &&
 1766:                     ($role_code ne 'dc')) {
 1767:                     $delallowed=1;
 1768:                 }
 1769:             } else {
 1770:                 if (&Apache::lonnet::allowed('c'.$role_code,'/')) {
 1771:                     $allowed=1;
 1772:                 }
 1773:             }
 1774:             if ($role_code eq 'ca' || $role_code eq 'au' || $role_code eq 'aa') {
 1775:                 $class='Authoring Space';
 1776:             } elsif ($role_code eq 'su') {
 1777:                 $class='System';
 1778:             } else {
 1779:                 $class='Domain';
 1780:             }
 1781:         }
 1782:         if (($role_code eq 'ca') || ($role_code eq 'aa')) {
 1783:             $area=~m{/($match_domain)/($match_username)};
 1784:             if (&Apache::lonuserutils::authorpriv($2,$1)) {
 1785:                 $allowed=1;
 1786:             } else {
 1787:                 $allowed=0;
 1788:             }
 1789:         }
 1790:         my $row = '';
 1791:         $row.= '<td>';
 1792:         my $active=1;
 1793:         $active=0 if (($role_end_time) && ($now>$role_end_time));
 1794:         if (($active) && ($allowed)) {
 1795:             $row.= '<input type="checkbox" name="rev:'.$thisrole.'" />';
 1796:         } else {
 1797:             if ($active) {
 1798:                $row.='&nbsp;';
 1799:             } else {
 1800:                $row.=&mt('expired or revoked');
 1801:             }
 1802:         }
 1803:         $row.='</td><td>';
 1804:         if ($allowed && !$active) {
 1805:             $row.= '<input type="checkbox" name="ren:'.$thisrole.'" />';
 1806:         } else {
 1807:             $row.='&nbsp;';
 1808:         }
 1809:         $row.='</td><td>';
 1810:         if ($delallowed) {
 1811:             $row.= '<input type="checkbox" name="del:'.$thisrole.'" />';
 1812:         } else {
 1813:             $row.='&nbsp;';
 1814:         }
 1815:         my $plaintext='';
 1816:         if (!$croletitle) {
 1817:             $plaintext=&Apache::lonnet::plaintext($role_code,$class);
 1818:             if (($showcredits) && ($credits ne '')) {
 1819:                 $plaintext .= '<br/ ><span class="LC_nobreak">'.
 1820:                               '<span class="LC_fontsize_small">'.
 1821:                               &mt('Credits: [_1]',$credits).
 1822:                               '</span></span>';
 1823:             }
 1824:         } else {
 1825:             $plaintext=
 1826:                 &mt('Custom role [_1][_2]defined by [_3]',
 1827:                         '"'.$croletitle.'"',
 1828:                         '<br />',
 1829:                         $croleuname.':'.$croleudom);
 1830:         }
 1831:         $row.= '</td><td>'.$plaintext.
 1832:                '</td><td>'.$area.
 1833:                '</td><td>'.($role_start_time?&Apache::lonlocal::locallocaltime($role_start_time)
 1834:                                             : '&nbsp;' ).
 1835:                '</td><td>'.($role_end_time  ?&Apache::lonlocal::locallocaltime($role_end_time)
 1836:                                             : '&nbsp;' )
 1837:                ."</td>";
 1838:         $sortrole{$sortkey}=$envkey;
 1839:         $roletext{$envkey}=$row;
 1840:         $roleclass{$envkey}=$class;
 1841:         $rolepriv{$envkey}=$allowed;
 1842:     } # end of foreach        (table building loop)
 1843: 
 1844:     my $rolesdisplay = 0;
 1845:     my %output = ();
 1846:     foreach my $type ('Authoring Space','Course','Community','Domain','System','Unknown') {
 1847:         $output{$type} = '';
 1848:         foreach my $which (sort {uc($a) cmp uc($b)} (keys(%sortrole))) {
 1849:             if ( ($roleclass{$sortrole{$which}} =~ /^\Q$type\E/ ) && ($rolepriv{$sortrole{$which}}) ) {
 1850:                  $output{$type}.=
 1851:                       &Apache::loncommon::start_data_table_row().
 1852:                       $roletext{$sortrole{$which}}.
 1853:                       &Apache::loncommon::end_data_table_row();
 1854:             }
 1855:         }
 1856:         unless($output{$type} eq '') {
 1857:             $output{$type} = '<tr class="LC_info_row">'.
 1858:                       "<td align='center' colspan='7'>".&mt($type)."</td></tr>".
 1859:                       $output{$type};
 1860:             $rolesdisplay = 1;
 1861:         }
 1862:     }
 1863:     if ($rolesdisplay == 1) {
 1864:         my $contextrole='';
 1865:         if ($env{'request.course.id'}) {
 1866:             if (&Apache::loncommon::course_type() eq 'Community') {
 1867:                 $contextrole = &mt('Existing Roles in this Community');
 1868:             } else {
 1869:                 $contextrole = &mt('Existing Roles in this Course');
 1870:             }
 1871:         } elsif ($env{'request.role'} =~ /^au\./) {
 1872:             $contextrole = &mt('Existing Co-Author Roles in your Authoring Space');
 1873:         } else {
 1874:             $contextrole = &mt('Existing Roles in this Domain');
 1875:         }
 1876:         $r->print('<div class="LC_left_float">'.
 1877: '<fieldset><legend>'.$contextrole.'</legend>'.
 1878: &Apache::loncommon::start_data_table("LC_createuser").
 1879: &Apache::loncommon::start_data_table_header_row().
 1880: '<th>'.$lt{'rev'}.'</th><th>'.$lt{'ren'}.'</th><th>'.$lt{'del'}.
 1881: '</th><th>'.$lt{'rol'}.'</th><th>'.$lt{'ext'}.
 1882: '</th><th>'.$lt{'sta'}.'</th><th>'.$lt{'end'}.'</th>'.
 1883: &Apache::loncommon::end_data_table_header_row());
 1884:         foreach my $type ('Authoring Space','Course','Community','Domain','System','Unknown') {
 1885:             if ($output{$type}) {
 1886:                 $r->print($output{$type}."\n");
 1887:             }
 1888:         }
 1889:         $r->print(&Apache::loncommon::end_data_table().
 1890:                   '</fieldset></div>');
 1891:     }
 1892:     return;
 1893: }
 1894: 
 1895: sub new_coauthor_roles {
 1896:     my ($r,$ccuname,$ccdomain) = @_;
 1897:     my $addrolesdisplay = 0;
 1898:     #
 1899:     # Co-Author
 1900:     #
 1901:     if (&Apache::lonuserutils::authorpriv($env{'user.name'},
 1902:                                           $env{'request.role.domain'}) &&
 1903:         ($env{'user.name'} ne $ccuname || $env{'user.domain'} ne $ccdomain)) {
 1904:         # No sense in assigning co-author role to yourself
 1905:         $addrolesdisplay = 1;
 1906:         my $cuname=$env{'user.name'};
 1907:         my $cudom=$env{'request.role.domain'};
 1908:         my %lt=&Apache::lonlocal::texthash(
 1909:                     'cs'   => "Authoring Space",
 1910:                     'act'  => "Activate",
 1911:                     'rol'  => "Role",
 1912:                     'ext'  => "Extent",
 1913:                     'sta'  => "Start",
 1914:                     'end'  => "End",
 1915:                     'cau'  => "Co-Author",
 1916:                     'caa'  => "Assistant Co-Author",
 1917:                     'ssd'  => "Set Start Date",
 1918:                     'sed'  => "Set End Date"
 1919:                                        );
 1920:         $r->print('<h4>'.$lt{'cs'}.'</h4>'."\n".
 1921:                   &Apache::loncommon::start_data_table()."\n".
 1922:                   &Apache::loncommon::start_data_table_header_row()."\n".
 1923:                   '<th>'.$lt{'act'}.'</th><th>'.$lt{'rol'}.'</th>'.
 1924:                   '<th>'.$lt{'ext'}.'</th><th>'.$lt{'sta'}.'</th>'.
 1925:                   '<th>'.$lt{'end'}.'</th>'."\n".
 1926:                   &Apache::loncommon::end_data_table_header_row()."\n".
 1927:                   &Apache::loncommon::start_data_table_row().'
 1928:            <td>
 1929:             <input type="checkbox" name="act_'.$cudom.'_'.$cuname.'_ca" />
 1930:            </td>
 1931:            <td>'.$lt{'cau'}.'</td>
 1932:            <td>'.$cudom.'_'.$cuname.'</td>
 1933:            <td><input type="hidden" name="start_'.$cudom.'_'.$cuname.'_ca" value="" />
 1934:              <a href=
 1935: "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>
 1936: <td><input type="hidden" name="end_'.$cudom.'_'.$cuname.'_ca" value="" />
 1937: <a href=
 1938: "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".
 1939:               &Apache::loncommon::end_data_table_row()."\n".
 1940:               &Apache::loncommon::start_data_table_row()."\n".
 1941: '<td><input type="checkbox" name="act_'.$cudom.'_'.$cuname.'_aa" /></td>
 1942: <td>'.$lt{'caa'}.'</td>
 1943: <td>'.$cudom.'_'.$cuname.'</td>
 1944: <td><input type="hidden" name="start_'.$cudom.'_'.$cuname.'_aa" value="" />
 1945: <a href=
 1946: "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>
 1947: <td><input type="hidden" name="end_'.$cudom.'_'.$cuname.'_aa" value="" />
 1948: <a href=
 1949: "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".
 1950:              &Apache::loncommon::end_data_table_row()."\n".
 1951:              &Apache::loncommon::end_data_table());
 1952:     } elsif ($env{'request.role'} =~ /^au\./) {
 1953:         if (!(&Apache::lonuserutils::authorpriv($env{'user.name'},
 1954:                                                 $env{'request.role.domain'}))) {
 1955:             $r->print('<span class="LC_error">'.
 1956:                       &mt('You do not have privileges to assign co-author roles.').
 1957:                       '</span>');
 1958:         } elsif (($env{'user.name'} eq $ccuname) &&
 1959:              ($env{'user.domain'} eq $ccdomain)) {
 1960:             $r->print(&mt('Assigning yourself a co-author or assistant co-author role in your own author area in Authoring Space is not permitted'));
 1961:         }
 1962:     }
 1963:     return $addrolesdisplay;;
 1964: }
 1965: 
 1966: sub new_domain_roles {
 1967:     my ($r,$ccdomain) = @_;
 1968:     my $addrolesdisplay = 0;
 1969:     #
 1970:     # Domain level
 1971:     #
 1972:     my $num_domain_level = 0;
 1973:     my $domaintext =
 1974:     '<h4>'.&mt('Domain Level').'</h4>'.
 1975:     &Apache::loncommon::start_data_table().
 1976:     &Apache::loncommon::start_data_table_header_row().
 1977:     '<th>'.&mt('Activate').'</th><th>'.&mt('Role').'</th><th>'.
 1978:     &mt('Extent').'</th>'.
 1979:     '<th>'.&mt('Start').'</th><th>'.&mt('End').'</th>'.
 1980:     &Apache::loncommon::end_data_table_header_row();
 1981:     my @allroles = &Apache::lonuserutils::roles_by_context('domain');
 1982:     foreach my $thisdomain (sort(&Apache::lonnet::all_domains())) {
 1983:         foreach my $role (@allroles) {
 1984:             next if ($role eq 'ad');
 1985:             next if (($role eq 'au') && ($ccdomain ne $thisdomain));
 1986:             if (&Apache::lonnet::allowed('c'.$role,$thisdomain)) {
 1987:                my $plrole=&Apache::lonnet::plaintext($role);
 1988:                my %lt=&Apache::lonlocal::texthash(
 1989:                     'ssd'  => "Set Start Date",
 1990:                     'sed'  => "Set End Date"
 1991:                                        );
 1992:                $num_domain_level ++;
 1993:                $domaintext .=
 1994: &Apache::loncommon::start_data_table_row().
 1995: '<td><input type="checkbox" name="act_'.$thisdomain.'_'.$role.'" /></td>
 1996: <td>'.$plrole.'</td>
 1997: <td>'.$thisdomain.'</td>
 1998: <td><input type="hidden" name="start_'.$thisdomain.'_'.$role.'" value="" />
 1999: <a href=
 2000: "javascript:pjump('."'date_start','Start Date $plrole',document.cu.start_$thisdomain\_$role.value,'start_$thisdomain\_$role','cu.pres','dateset'".')">'.$lt{'ssd'}.'</a></td>
 2001: <td><input type="hidden" name="end_'.$thisdomain.'_'.$role.'" value="" />
 2002: <a href=
 2003: "javascript:pjump('."'date_end','End Date $plrole',document.cu.end_$thisdomain\_$role.value,'end_$thisdomain\_$role','cu.pres','dateset'".')">'.$lt{'sed'}.'</a></td>'.
 2004: &Apache::loncommon::end_data_table_row();
 2005:             }
 2006:         }
 2007:     }
 2008:     $domaintext.= &Apache::loncommon::end_data_table();
 2009:     if ($num_domain_level > 0) {
 2010:         $r->print($domaintext);
 2011:         $addrolesdisplay = 1;
 2012:     }
 2013:     return $addrolesdisplay;
 2014: }
 2015: 
 2016: sub user_authentication {
 2017:     my ($ccuname,$ccdomain,$formname) = @_;
 2018:     my $currentauth=&Apache::lonnet::queryauthenticate($ccuname,$ccdomain);
 2019:     my $outcome;
 2020:     # Check for a bad authentication type
 2021:     if ($currentauth !~ /^(krb4|krb5|unix|internal|localauth):/) {
 2022:         # bad authentication scheme
 2023:         my %lt=&Apache::lonlocal::texthash(
 2024:                        'err'   => "ERROR",
 2025:                        'uuas'  => "This user has an unrecognized authentication scheme",
 2026:                        'adcs'  => "Please alert a domain coordinator of this situation",
 2027:                        'sldb'  => "Please specify login data below",
 2028:                        'ld'    => "Login Data"
 2029:         );
 2030:         if (&Apache::lonnet::allowed('mau',$ccdomain)) {
 2031:             &initialize_authen_forms($ccdomain,$formname);
 2032: 
 2033:             my $choices = &Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc);
 2034:             $outcome = <<ENDBADAUTH;
 2035: <script type="text/javascript" language="Javascript">
 2036: // <![CDATA[
 2037: $loginscript
 2038: // ]]>
 2039: </script>
 2040: <span class="LC_error">$lt{'err'}:
 2041: $lt{'uuas'} ($currentauth). $lt{'sldb'}.</span>
 2042: <h3>$lt{'ld'}</h3>
 2043: $choices
 2044: ENDBADAUTH
 2045:         } else {
 2046:             # This user is not allowed to modify the user's
 2047:             # authentication scheme, so just notify them of the problem
 2048:             $outcome = <<ENDBADAUTH;
 2049: <span class="LC_error"> $lt{'err'}: 
 2050: $lt{'uuas'} ($currentauth). $lt{'adcs'}.
 2051: </span>
 2052: ENDBADAUTH
 2053:         }
 2054:     } else { # Authentication type is valid
 2055:         &initialize_authen_forms($ccdomain,$formname,$currentauth,'modifyuser');
 2056:         my ($authformcurrent,$can_modify,@authform_others) =
 2057:             &modify_login_block($ccdomain,$currentauth);
 2058:         if (&Apache::lonnet::allowed('mau',$ccdomain)) {
 2059:             # Current user has login modification privileges
 2060:             my %lt=&Apache::lonlocal::texthash (
 2061:                            'ld'    => "Login Data",
 2062:                            'ccld'  => "Change Current Login Data",
 2063:                            'enld'  => "Enter New Login Data"
 2064:                                                );
 2065:             $outcome =
 2066:                        '<script type="text/javascript" language="Javascript">'."\n".
 2067:                        '// <![CDATA['."\n".
 2068:                        $loginscript."\n".
 2069:                        '// ]]>'."\n".
 2070:                        '</script>'."\n".
 2071:                        '<h3>'.$lt{'ld'}.'</h3>'.
 2072:                        &Apache::loncommon::start_data_table().
 2073:                        &Apache::loncommon::start_data_table_row().
 2074:                        '<td>'.$authformnop;
 2075:             if ($can_modify) {
 2076:                 $outcome .= '</td>'."\n".
 2077:                             &Apache::loncommon::end_data_table_row().
 2078:                             &Apache::loncommon::start_data_table_row().
 2079:                             '<td>'.$authformcurrent.'</td>'.
 2080:                             &Apache::loncommon::end_data_table_row()."\n";
 2081:             } else {
 2082:                 $outcome .= '&nbsp;('.$authformcurrent.')</td>'.
 2083:                             &Apache::loncommon::end_data_table_row()."\n";
 2084:             }
 2085:             foreach my $item (@authform_others) { 
 2086:                 $outcome .= &Apache::loncommon::start_data_table_row().
 2087:                             '<td>'.$item.'</td>'.
 2088:                             &Apache::loncommon::end_data_table_row()."\n";
 2089:             }
 2090:             $outcome .= &Apache::loncommon::end_data_table();
 2091:         } else {
 2092:             if (&Apache::lonnet::allowed('mau',$env{'request.role.domain'})) {
 2093:                 my %lt=&Apache::lonlocal::texthash(
 2094:                            'ccld'  => "Change Current Login Data",
 2095:                            'yodo'  => "You do not have privileges to modify the authentication configuration for this user.",
 2096:                            'ifch'  => "If a change is required, contact a domain coordinator for the domain",
 2097:                 );
 2098:                 $outcome .= <<ENDNOPRIV;
 2099: <h3>$lt{'ccld'}</h3>
 2100: $lt{'yodo'} $lt{'ifch'}: $ccdomain
 2101: <input type="hidden" name="login" value="nochange" />
 2102: ENDNOPRIV
 2103:             }
 2104:         }
 2105:     }  ## End of "check for bad authentication type" logic
 2106:     return $outcome;
 2107: }
 2108: 
 2109: sub modify_login_block {
 2110:     my ($dom,$currentauth) = @_;
 2111:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 2112:     my ($authnum,%can_assign) =
 2113:         &Apache::loncommon::get_assignable_auth($dom);
 2114:     my ($authformcurrent,@authform_others,$show_override_msg);
 2115:     if ($currentauth=~/^krb(4|5):/) {
 2116:         $authformcurrent=$authformkrb;
 2117:         if ($can_assign{'int'}) {
 2118:             push(@authform_others,$authformint);
 2119:         }
 2120:         if ($can_assign{'loc'}) {
 2121:             push(@authform_others,$authformloc);
 2122:         }
 2123:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2124:             $show_override_msg = 1;
 2125:         }
 2126:     } elsif ($currentauth=~/^internal:/) {
 2127:         $authformcurrent=$authformint;
 2128:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2129:             push(@authform_others,$authformkrb);
 2130:         }
 2131:         if ($can_assign{'loc'}) {
 2132:             push(@authform_others,$authformloc);
 2133:         }
 2134:         if ($can_assign{'int'}) {
 2135:             $show_override_msg = 1;
 2136:         }
 2137:     } elsif ($currentauth=~/^unix:/) {
 2138:         $authformcurrent=$authformfsys;
 2139:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2140:             push(@authform_others,$authformkrb);
 2141:         }
 2142:         if ($can_assign{'int'}) {
 2143:             push(@authform_others,$authformint);
 2144:         }
 2145:         if ($can_assign{'loc'}) {
 2146:             push(@authform_others,$authformloc);
 2147:         }
 2148:         if ($can_assign{'fsys'}) {
 2149:             $show_override_msg = 1;
 2150:         }
 2151:     } elsif ($currentauth=~/^localauth:/) {
 2152:         $authformcurrent=$authformloc;
 2153:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2154:             push(@authform_others,$authformkrb);
 2155:         }
 2156:         if ($can_assign{'int'}) {
 2157:             push(@authform_others,$authformint);
 2158:         }
 2159:         if ($can_assign{'loc'}) {
 2160:             $show_override_msg = 1;
 2161:         }
 2162:     }
 2163:     if ($show_override_msg) {
 2164:         $authformcurrent = '<table><tr><td colspan="3">'.$authformcurrent.
 2165:                            '</td></tr>'."\n".
 2166:                            '<tr><td>&nbsp;&nbsp;&nbsp;</td>'.
 2167:                            '<td><b>'.&mt('Currently in use').'</b></td>'.
 2168:                            '<td align="right"><span class="LC_cusr_emph">'.
 2169:                             &mt('will override current values').
 2170:                             '</span></td></tr></table>';
 2171:     }
 2172:     return ($authformcurrent,$show_override_msg,@authform_others); 
 2173: }
 2174: 
 2175: sub personal_data_display {
 2176:     my ($ccuname,$ccdomain,$newuser,$context,$inst_results,$rolesarray,
 2177:         $now,$captchaform,$emailusername,$usertype) = @_;
 2178:     my ($output,%userenv,%canmodify,%canmodify_status);
 2179:     my @userinfo = ('firstname','middlename','lastname','generation',
 2180:                     'permanentemail','id');
 2181:     my $rowcount = 0;
 2182:     my $editable = 0;
 2183:     my %textboxsize = (
 2184:                        firstname      => '15',
 2185:                        middlename     => '15',
 2186:                        lastname       => '15',
 2187:                        generation     => '5',
 2188:                        permanentemail => '25',
 2189:                        id             => '15',
 2190:                       );
 2191: 
 2192:     my %lt=&Apache::lonlocal::texthash(
 2193:                 'pd'             => "Personal Data",
 2194:                 'firstname'      => "First Name",
 2195:                 'middlename'     => "Middle Name",
 2196:                 'lastname'       => "Last Name",
 2197:                 'generation'     => "Generation",
 2198:                 'permanentemail' => "Permanent e-mail address",
 2199:                 'id'             => "Student/Employee ID",
 2200:                 'lg'             => "Login Data",
 2201:                 'inststatus'     => "Affiliation",
 2202:                 'email'          => 'E-mail address',
 2203:                 'valid'          => 'Validation',
 2204:     );
 2205: 
 2206:     %canmodify_status =
 2207:         &Apache::lonuserutils::can_modify_userinfo($context,$ccdomain,
 2208:                                                    ['inststatus'],$rolesarray);
 2209:     if (!$newuser) {
 2210:         # Get the users information
 2211:         %userenv = &Apache::lonnet::get('environment',
 2212:                    ['firstname','middlename','lastname','generation',
 2213:                     'permanentemail','id','inststatus'],$ccdomain,$ccuname);
 2214:         %canmodify =
 2215:             &Apache::lonuserutils::can_modify_userinfo($context,$ccdomain,
 2216:                                                        \@userinfo,$rolesarray);
 2217:     } elsif ($context eq 'selfcreate') {
 2218:         if ($newuser eq 'email') {
 2219:             if (ref($emailusername) eq 'HASH') {
 2220:                 if (ref($emailusername->{$usertype}) eq 'HASH') {
 2221:                     my ($infofields,$infotitles) = &Apache::loncommon::emailusername_info();
 2222:                     @userinfo = ();          
 2223:                     if ((ref($infofields) eq 'ARRAY') && (ref($infotitles) eq 'HASH')) {
 2224:                         foreach my $field (@{$infofields}) { 
 2225:                             if ($emailusername->{$usertype}->{$field}) {
 2226:                                 push(@userinfo,$field);
 2227:                                 $canmodify{$field} = 1;
 2228:                                 unless ($textboxsize{$field}) {
 2229:                                     $textboxsize{$field} = 25;
 2230:                                 }
 2231:                                 unless ($lt{$field}) {
 2232:                                     $lt{$field} = $infotitles->{$field};
 2233:                                 }
 2234:                                 if ($emailusername->{$usertype}->{$field} eq 'required') {
 2235:                                     $lt{$field} .= '<b>*</b>';
 2236:                                 }
 2237:                             }
 2238:                         }
 2239:                     }
 2240:                 }
 2241:             }
 2242:         } else {
 2243:             %canmodify = &selfcreate_canmodify($context,$ccdomain,\@userinfo,
 2244:                                                $inst_results,$rolesarray);
 2245:         }
 2246:     }
 2247: 
 2248:     my $genhelp=&Apache::loncommon::help_open_topic('Generation');
 2249:     $output = '<h3>'.$lt{'pd'}.'</h3>'.
 2250:               &Apache::lonhtmlcommon::start_pick_box();
 2251:     if (($context eq 'selfcreate') && ($newuser eq 'email')) {
 2252:         $output .= &Apache::lonhtmlcommon::row_title($lt{'email'}.'<b>*</b>',undef,
 2253:                                                      'LC_oddrow_value')."\n".
 2254:                    '<input type="text" name="uname" size="25" value="" autocomplete="off" />';
 2255:         $rowcount ++;
 2256:         $output .= &Apache::lonhtmlcommon::row_closure(1);
 2257:         my $upassone = '<input type="password" name="upass'.$now.'" size="20" autocomplete="off" />';
 2258:         my $upasstwo = '<input type="password" name="upasscheck'.$now.'" size="20" autocomplete="off" />';
 2259:         $output .= &Apache::lonhtmlcommon::row_title(&mt('Password').'<b>*</b>',
 2260:                                                     'LC_pick_box_title',
 2261:                                                     'LC_oddrow_value')."\n".
 2262:                    $upassone."\n".
 2263:                    &Apache::lonhtmlcommon::row_closure(1)."\n".
 2264:                    &Apache::lonhtmlcommon::row_title(&mt('Confirm password').'<b>*</b>',
 2265:                                                      'LC_pick_box_title',
 2266:                                                      'LC_oddrow_value')."\n".
 2267:                    $upasstwo.
 2268:                    &Apache::lonhtmlcommon::row_closure()."\n";
 2269:     }
 2270:     foreach my $item (@userinfo) {
 2271:         my $rowtitle = $lt{$item};
 2272:         my $hiderow = 0;
 2273:         if ($item eq 'generation') {
 2274:             $rowtitle = $genhelp.$rowtitle;
 2275:         }
 2276:         my $row = &Apache::lonhtmlcommon::row_title($rowtitle,undef,'LC_oddrow_value')."\n";
 2277:         if ($newuser) {
 2278:             if (ref($inst_results) eq 'HASH') {
 2279:                 if ($inst_results->{$item} ne '') {
 2280:                     $row .= '<input type="hidden" name="c'.$item.'" value="'.$inst_results->{$item}.'" />'.$inst_results->{$item};
 2281:                 } else {
 2282:                     if ($context eq 'selfcreate') {
 2283:                         if ($canmodify{$item}) {
 2284:                             $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="" autocomplete="off" />';
 2285:                             $editable ++;
 2286:                         } else {
 2287:                             $hiderow = 1;
 2288:                         }
 2289:                     } else {
 2290:                         $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="" />';
 2291:                     }
 2292:                 }
 2293:             } else {
 2294:                 if ($context eq 'selfcreate') {
 2295:                     if ($canmodify{$item}) {
 2296:                         if ($newuser eq 'email') {
 2297:                             $row .= '<input type="text" name="'.$item.'" size="'.$textboxsize{$item}.'" value="" autocomplete="off" />';
 2298:                         } else {
 2299:                             $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="" autocomplete="off" />';
 2300:                         }
 2301:                         $editable ++;
 2302:                     } else {
 2303:                         $hiderow = 1;
 2304:                     }
 2305:                 } else {
 2306:                     $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="" />';
 2307:                 }
 2308:             }
 2309:         } else {
 2310:             if ($canmodify{$item}) {
 2311:                 $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="'.$userenv{$item}.'" />';
 2312:                 if (($item eq 'id') && (!$newuser)) {
 2313:                     $row .= '<br />'.&Apache::lonuserutils::forceid_change($context);
 2314:                 }
 2315:             } else {
 2316:                 $row .= $userenv{$item};
 2317:             }
 2318:         }
 2319:         $row .= &Apache::lonhtmlcommon::row_closure(1);
 2320:         if (!$hiderow) {
 2321:             $output .= $row;
 2322:             $rowcount ++;
 2323:         }
 2324:     }
 2325:     if (($canmodify_status{'inststatus'}) || ($context ne 'selfcreate')) {
 2326:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($ccdomain);
 2327:         if (ref($types) eq 'ARRAY') {
 2328:             if (@{$types} > 0) {
 2329:                 my ($hiderow,$shown);
 2330:                 if ($canmodify_status{'inststatus'}) {
 2331:                     $shown = &pick_inst_statuses($userenv{'inststatus'},$usertypes,$types);
 2332:                 } else {
 2333:                     if ($userenv{'inststatus'} eq '') {
 2334:                         $hiderow = 1;
 2335:                     } else {
 2336:                         my @showitems;
 2337:                         foreach my $item ( map { &unescape($_); } split(':',$userenv{'inststatus'})) {
 2338:                             if (exists($usertypes->{$item})) {
 2339:                                 push(@showitems,$usertypes->{$item});
 2340:                             } else {
 2341:                                 push(@showitems,$item);
 2342:                             }
 2343:                         }
 2344:                         if (@showitems) {
 2345:                             $shown = join(', ',@showitems);
 2346:                         } else {
 2347:                             $hiderow = 1;
 2348:                         }
 2349:                     }
 2350:                 }
 2351:                 if (!$hiderow) {
 2352:                     my $row = &Apache::lonhtmlcommon::row_title(&mt('Affiliations'),undef,'LC_oddrow_value')."\n".
 2353:                               $shown.&Apache::lonhtmlcommon::row_closure(1); 
 2354:                     if ($context eq 'selfcreate') {
 2355:                         $rowcount ++;
 2356:                     }
 2357:                     $output .= $row;
 2358:                 }
 2359:             }
 2360:         }
 2361:     }
 2362:     if (($context eq 'selfcreate') && ($newuser eq 'email')) {
 2363:         if ($captchaform) {
 2364:             $output .= &Apache::lonhtmlcommon::row_title($lt{'valid'}.'*',
 2365:                                                          'LC_pick_box_title')."\n".
 2366:                        $captchaform."\n".'<br /><br />'.
 2367:                        &Apache::lonhtmlcommon::row_closure(1); 
 2368:             $rowcount ++;
 2369:         }
 2370:         my $submit_text = &mt('Create account');
 2371:         $output .= &Apache::lonhtmlcommon::row_title()."\n".
 2372:                    '<br /><input type="submit" name="createaccount" value="'.
 2373:                    $submit_text.'" />'.
 2374:                    '<input type="hidden" name="type" value="'.$usertype.'" />'.
 2375:                    &Apache::lonhtmlcommon::row_closure(1);
 2376:     }
 2377:     $output .= &Apache::lonhtmlcommon::end_pick_box();
 2378:     if (wantarray) {
 2379:         if ($context eq 'selfcreate') {
 2380:             return($output,$rowcount,$editable);
 2381:         } else {
 2382:             return $output;
 2383:         }
 2384:     } else {
 2385:         return $output;
 2386:     }
 2387: }
 2388: 
 2389: sub pick_inst_statuses {
 2390:     my ($curr,$usertypes,$types) = @_;
 2391:     my ($output,$rem,@currtypes);
 2392:     if ($curr ne '') {
 2393:         @currtypes = map { &unescape($_); } split(/:/,$curr);
 2394:     }
 2395:     my $numinrow = 2;
 2396:     if (ref($types) eq 'ARRAY') {
 2397:         $output = '<table>';
 2398:         my $lastcolspan; 
 2399:         for (my $i=0; $i<@{$types}; $i++) {
 2400:             if (defined($usertypes->{$types->[$i]})) {
 2401:                 my $rem = $i%($numinrow);
 2402:                 if ($rem == 0) {
 2403:                     if ($i<@{$types}-1) {
 2404:                         if ($i > 0) { 
 2405:                             $output .= '</tr>';
 2406:                         }
 2407:                         $output .= '<tr>';
 2408:                     }
 2409:                 } elsif ($i==@{$types}-1) {
 2410:                     my $colsleft = $numinrow - $rem;
 2411:                     if ($colsleft > 1) {
 2412:                         $lastcolspan = ' colspan="'.$colsleft.'"';
 2413:                     }
 2414:                 }
 2415:                 my $check = ' ';
 2416:                 if (grep(/^\Q$types->[$i]\E$/,@currtypes)) {
 2417:                     $check = ' checked="checked" ';
 2418:                 }
 2419:                 $output .= '<td class="LC_left_item"'.$lastcolspan.'>'.
 2420:                            '<span class="LC_nobreak"><label>'.
 2421:                            '<input type="checkbox" name="inststatus" '.
 2422:                            'value="'.$types->[$i].'"'.$check.'/>'.
 2423:                            $usertypes->{$types->[$i]}.'</label></span></td>';
 2424:             }
 2425:         }
 2426:         $output .= '</tr></table>';
 2427:     }
 2428:     return $output;
 2429: }
 2430: 
 2431: sub selfcreate_canmodify {
 2432:     my ($context,$dom,$userinfo,$inst_results,$rolesarray) = @_;
 2433:     if (ref($inst_results) eq 'HASH') {
 2434:         my @inststatuses = &get_inststatuses($inst_results);
 2435:         if (@inststatuses == 0) {
 2436:             @inststatuses = ('default');
 2437:         }
 2438:         $rolesarray = \@inststatuses;
 2439:     }
 2440:     my %canmodify =
 2441:         &Apache::lonuserutils::can_modify_userinfo($context,$dom,$userinfo,
 2442:                                                    $rolesarray);
 2443:     return %canmodify;
 2444: }
 2445: 
 2446: sub get_inststatuses {
 2447:     my ($insthashref) = @_;
 2448:     my @inststatuses = ();
 2449:     if (ref($insthashref) eq 'HASH') {
 2450:         if (ref($insthashref->{'inststatus'}) eq 'ARRAY') {
 2451:             @inststatuses = @{$insthashref->{'inststatus'}};
 2452:         }
 2453:     }
 2454:     return @inststatuses;
 2455: }
 2456: 
 2457: # ================================================================= Phase Three
 2458: sub update_user_data {
 2459:     my ($r,$context,$crstype,$brcrum,$showcredits) = @_; 
 2460:     my $uhome=&Apache::lonnet::homeserver($env{'form.ccuname'},
 2461:                                           $env{'form.ccdomain'});
 2462:     # Error messages
 2463:     my $error     = '<span class="LC_error">'.&mt('Error').': ';
 2464:     my $end       = '</span><br /><br />';
 2465:     my $rtnlink   = '<a href="javascript:backPage(document.userupdate,'.
 2466:                     "'$env{'form.prevphase'}','modify')".'" />'.
 2467:                     &mt('Return to previous page').'</a>'.
 2468:                     &Apache::loncommon::end_page();
 2469:     my $now = time;
 2470:     my $title;
 2471:     if (exists($env{'form.makeuser'})) {
 2472: 	$title='Set Privileges for New User';
 2473:     } else {
 2474:         $title='Modify User Privileges';
 2475:     }
 2476:     my $newuser = 0;
 2477:     my ($jsback,$elements) = &crumb_utilities();
 2478:     my $jscript = '<script type="text/javascript">'."\n".
 2479:                   '// <![CDATA['."\n".
 2480:                   $jsback."\n".
 2481:                   '// ]]>'."\n".
 2482:                   '</script>'."\n";
 2483:     my %breadcrumb_text = &singleuser_breadcrumb($crstype);
 2484:     push (@{$brcrum},
 2485:              {href => "javascript:backPage(document.userupdate)",
 2486:               text => $breadcrumb_text{'search'},
 2487:               faq  => 282,
 2488:               bug  => 'Instructor Interface',}
 2489:              );
 2490:     if ($env{'form.prevphase'} eq 'userpicked') {
 2491:         push(@{$brcrum},
 2492:                {href => "javascript:backPage(document.userupdate,'get_user_info','select')",
 2493:                 text => $breadcrumb_text{'userpicked'},
 2494:                 faq  => 282,
 2495:                 bug  => 'Instructor Interface',});
 2496:     }
 2497:     my $helpitem = 'Course_Change_Privileges';
 2498:     if ($env{'form.action'} eq 'singlestudent') {
 2499:         $helpitem = 'Course_Add_Student';
 2500:     }
 2501:     push(@{$brcrum}, 
 2502:             {href => "javascript:backPage(document.userupdate,'$env{'form.prevphase'}','modify')",
 2503:              text => $breadcrumb_text{'modify'},
 2504:              faq  => 282,
 2505:              bug  => 'Instructor Interface',},
 2506:             {href => "/adm/createuser",
 2507:              text => "Result",
 2508:              faq  => 282,
 2509:              bug  => 'Instructor Interface',
 2510:              help => $helpitem});
 2511:     my $args = {bread_crumbs          => $brcrum,
 2512:                 bread_crumbs_component => 'User Management'};
 2513:     if ($env{'form.popup'}) {
 2514:         $args->{'no_nav_bar'} = 1;
 2515:     }
 2516:     $r->print(&Apache::loncommon::start_page($title,$jscript,$args));
 2517:     $r->print(&update_result_form($uhome));
 2518:     # Check Inputs
 2519:     if (! $env{'form.ccuname'} ) {
 2520: 	$r->print($error.&mt('No login name specified').'.'.$end.$rtnlink);
 2521: 	return;
 2522:     }
 2523:     if (  $env{'form.ccuname'} ne 
 2524: 	  &LONCAPA::clean_username($env{'form.ccuname'}) ) {
 2525: 	$r->print($error.&mt('Invalid login name.').'  '.
 2526: 		  &mt('Only letters, numbers, periods, dashes, @, and underscores are valid.').
 2527: 		  $end.$rtnlink);
 2528: 	return;
 2529:     }
 2530:     if (! $env{'form.ccdomain'}       ) {
 2531: 	$r->print($error.&mt('No domain specified').'.'.$end.$rtnlink);
 2532: 	return;
 2533:     }
 2534:     if (  $env{'form.ccdomain'} ne
 2535: 	  &LONCAPA::clean_domain($env{'form.ccdomain'}) ) {
 2536: 	$r->print($error.&mt('Invalid domain name.').'  '.
 2537: 		  &mt('Only letters, numbers, periods, dashes, and underscores are valid.').
 2538: 		  $end.$rtnlink);
 2539: 	return;
 2540:     }
 2541:     if ($uhome eq 'no_host') {
 2542:         $newuser = 1;
 2543:     }
 2544:     if (! exists($env{'form.makeuser'})) {
 2545:         # Modifying an existing user, so check the validity of the name
 2546:         if ($uhome eq 'no_host') {
 2547:             $r->print(
 2548:                 $error
 2549:                .'<p class="LC_error">'
 2550:                .&mt('Unable to determine home server for [_1] in domain [_2].',
 2551:                         '"'.$env{'form.ccuname'}.'"','"'.$env{'form.ccdomain'}.'"')
 2552:                .'</p>');
 2553:             return;
 2554:         }
 2555:     }
 2556:     # Determine authentication method and password for the user being modified
 2557:     my $amode='';
 2558:     my $genpwd='';
 2559:     if ($env{'form.login'} eq 'krb') {
 2560: 	$amode='krb';
 2561: 	$amode.=$env{'form.krbver'};
 2562: 	$genpwd=$env{'form.krbarg'};
 2563:     } elsif ($env{'form.login'} eq 'int') {
 2564: 	$amode='internal';
 2565: 	$genpwd=$env{'form.intarg'};
 2566:     } elsif ($env{'form.login'} eq 'fsys') {
 2567: 	$amode='unix';
 2568: 	$genpwd=$env{'form.fsysarg'};
 2569:     } elsif ($env{'form.login'} eq 'loc') {
 2570: 	$amode='localauth';
 2571: 	$genpwd=$env{'form.locarg'};
 2572: 	$genpwd=" " if (!$genpwd);
 2573:     } elsif (($env{'form.login'} eq 'nochange') ||
 2574:              ($env{'form.login'} eq ''        )) { 
 2575:         # There is no need to tell the user we did not change what they
 2576:         # did not ask us to change.
 2577:         # If they are creating a new user but have not specified login
 2578:         # information this will be caught below.
 2579:     } else {
 2580:             $r->print($error.&mt('Invalid login mode or password').$end.$rtnlink);
 2581:             return;
 2582:     }
 2583: 
 2584:     $r->print('<h3>'.&mt('User [_1] in domain [_2]',
 2585:                         $env{'form.ccuname'}.' ('.&Apache::loncommon::plainname($env{'form.ccuname'},
 2586:                         $env{'form.ccdomain'}).')', $env{'form.ccdomain'}).'</h3>');
 2587:     my %prog_state = &Apache::lonhtmlcommon::Create_PrgWin($r,2);
 2588: 
 2589:     my (%alerts,%rulematch,%inst_results,%curr_rules);
 2590:     my @userinfo = ('firstname','middlename','lastname','generation','permanentemail','id');
 2591:     my @usertools = ('aboutme','blog','webdav','portfolio');
 2592:     my @requestcourses = ('official','unofficial','community','textbook','placement');
 2593:     my @requestauthor = ('requestauthor');
 2594:     my ($othertitle,$usertypes,$types) = 
 2595:         &Apache::loncommon::sorted_inst_types($env{'form.ccdomain'});
 2596:     my %canmodify_status =
 2597:         &Apache::lonuserutils::can_modify_userinfo($context,$env{'form.ccdomain'},
 2598:                                                    ['inststatus']);
 2599:     if ($env{'form.makeuser'}) {
 2600: 	$r->print('<h3>'.&mt('Creating new account.').'</h3>');
 2601:         # Check for the authentication mode and password
 2602:         if (! $amode || ! $genpwd) {
 2603: 	    $r->print($error.&mt('Invalid login mode or password').$end.$rtnlink);    
 2604: 	    return;
 2605: 	}
 2606:         # Determine desired host
 2607:         my $desiredhost = $env{'form.hserver'};
 2608:         if (lc($desiredhost) eq 'default') {
 2609:             $desiredhost = undef;
 2610:         } else {
 2611:             my %home_servers = 
 2612: 		&Apache::lonnet::get_servers($env{'form.ccdomain'},'library');
 2613:             if (! exists($home_servers{$desiredhost})) {
 2614:                 $r->print($error.&mt('Invalid home server specified').$end.$rtnlink);
 2615:                 return;
 2616:             }
 2617:         }
 2618:         # Check ID format
 2619:         my %checkhash;
 2620:         my %checks = ('id' => 1);
 2621:         %{$checkhash{$env{'form.ccuname'}.':'.$env{'form.ccdomain'}}} = (
 2622:             'newuser' => $newuser, 
 2623:             'id' => $env{'form.cid'},
 2624:         );
 2625:         if ($env{'form.cid'} ne '') {
 2626:             &Apache::loncommon::user_rule_check(\%checkhash,\%checks,\%alerts,
 2627:                                           \%rulematch,\%inst_results,\%curr_rules);
 2628:             if (ref($alerts{'id'}) eq 'HASH') {
 2629:                 if (ref($alerts{'id'}{$env{'form.ccdomain'}}) eq 'HASH') {
 2630:                     my $domdesc =
 2631:                         &Apache::lonnet::domain($env{'form.ccdomain'},'description');
 2632:                     if ($alerts{'id'}{$env{'form.ccdomain'}}{$env{'form.cid'}}) {
 2633:                         my $userchkmsg;
 2634:                         if (ref($curr_rules{$env{'form.ccdomain'}}) eq 'HASH') {
 2635:                             $userchkmsg  = 
 2636:                                 &Apache::loncommon::instrule_disallow_msg('id',
 2637:                                                                     $domdesc,1).
 2638:                                 &Apache::loncommon::user_rule_formats($env{'form.ccdomain'},
 2639:                                     $domdesc,$curr_rules{$env{'form.ccdomain'}}{'id'},'id');
 2640:                         }
 2641:                         $r->print($error.&mt('Invalid ID format').$end.
 2642:                                   $userchkmsg.$rtnlink);
 2643:                         return;
 2644:                     }
 2645:                 }
 2646:             }
 2647:         }
 2648:         &Apache::lonhtmlcommon::Increment_PrgWin($r, \%prog_state);
 2649: 	# Call modifyuser
 2650: 	my $result = &Apache::lonnet::modifyuser
 2651: 	    ($env{'form.ccdomain'},$env{'form.ccuname'},$env{'form.cid'},
 2652:              $amode,$genpwd,$env{'form.cfirstname'},
 2653:              $env{'form.cmiddlename'},$env{'form.clastname'},
 2654:              $env{'form.cgeneration'},undef,$desiredhost,
 2655:              $env{'form.cpermanentemail'});
 2656: 	$r->print(&mt('Generating user').': '.$result);
 2657:         $uhome = &Apache::lonnet::homeserver($env{'form.ccuname'},
 2658:                                                $env{'form.ccdomain'});
 2659:         my (%changeHash,%newcustom,%changed,%changedinfo);
 2660:         if ($uhome ne 'no_host') {
 2661:             if ($context eq 'domain') {
 2662:                 foreach my $name ('portfolio','author') {
 2663:                     if ($env{'form.custom_'.$name.'quota'} == 1) {
 2664:                         if ($env{'form.'.$name.'quota'} eq '') {
 2665:                             $newcustom{$name.'quota'} = 0;
 2666:                         } else {
 2667:                             $newcustom{$name.'quota'} = $env{'form.'.$name.'quota'};
 2668:                             $newcustom{$name.'quota'} =~ s/[^\d\.]//g;
 2669:                         }
 2670:                         if (&quota_admin($newcustom{$name.'quota'},\%changeHash,$name)) {
 2671:                             $changed{$name.'quota'} = 1;
 2672:                         }
 2673:                     }
 2674:                 }
 2675:                 foreach my $item (@usertools) {
 2676:                     if ($env{'form.custom'.$item} == 1) {
 2677:                         $newcustom{$item} = $env{'form.tools_'.$item};
 2678:                         $changed{$item} = &tool_admin($item,$newcustom{$item},
 2679:                                                      \%changeHash,'tools');
 2680:                     }
 2681:                 }
 2682:                 foreach my $item (@requestcourses) {
 2683:                     if ($env{'form.custom'.$item} == 1) {
 2684:                         $newcustom{$item} = $env{'form.crsreq_'.$item};
 2685:                         if ($env{'form.crsreq_'.$item} eq 'autolimit') {
 2686:                             $newcustom{$item} .= '=';
 2687:                             $env{'form.crsreq_'.$item.'_limit'} =~ s/\D+//g;
 2688:                             if ($env{'form.crsreq_'.$item.'_limit'}) {
 2689:                                 $newcustom{$item} .= $env{'form.crsreq_'.$item.'_limit'};
 2690:                             }
 2691:                         }
 2692:                         $changed{$item} = &tool_admin($item,$newcustom{$item},
 2693:                                                       \%changeHash,'requestcourses');
 2694:                     }
 2695:                 }
 2696:                 if ($env{'form.customrequestauthor'} == 1) {
 2697:                     $newcustom{'requestauthor'} = $env{'form.requestauthor'};
 2698:                     $changed{'requestauthor'} = &tool_admin('requestauthor',
 2699:                                                     $newcustom{'requestauthor'},
 2700:                                                     \%changeHash,'requestauthor');
 2701:                 }
 2702:             }
 2703:             if ($canmodify_status{'inststatus'}) {
 2704:                 if (exists($env{'form.inststatus'})) {
 2705:                     my @inststatuses = &Apache::loncommon::get_env_multiple('form.inststatus');
 2706:                     if (@inststatuses > 0) {
 2707:                         $changeHash{'inststatus'} = join(',',@inststatuses);
 2708:                         $changed{'inststatus'} = $changeHash{'inststatus'};
 2709:                     }
 2710:                 }
 2711:             }
 2712:             if (keys(%changed)) {
 2713:                 foreach my $item (@userinfo) {
 2714:                     $changeHash{$item}  = $env{'form.c'.$item};
 2715:                 }
 2716:                 my $chgresult =
 2717:                      &Apache::lonnet::put('environment',\%changeHash,
 2718:                                           $env{'form.ccdomain'},$env{'form.ccuname'});
 2719:             } 
 2720:         }
 2721:         $r->print('<br />'.&mt('Home server').': '.$uhome.' '.
 2722:                   &Apache::lonnet::hostname($uhome));
 2723:     } elsif (($env{'form.login'} ne 'nochange') &&
 2724:              ($env{'form.login'} ne ''        )) {
 2725: 	# Modify user privileges
 2726:         if (! $amode || ! $genpwd) {
 2727: 	    $r->print($error.'Invalid login mode or password'.$end.$rtnlink);    
 2728: 	    return;
 2729: 	}
 2730: 	# Only allow authentication modification if the person has authority
 2731: 	if (&Apache::lonnet::allowed('mau',$env{'form.ccdomain'})) {
 2732: 	    $r->print('Modifying authentication: '.
 2733:                       &Apache::lonnet::modifyuserauth(
 2734: 		       $env{'form.ccdomain'},$env{'form.ccuname'},
 2735:                        $amode,$genpwd));
 2736:             $r->print('<br />'.&mt('Home server').': '.&Apache::lonnet::homeserver
 2737: 		  ($env{'form.ccuname'},$env{'form.ccdomain'}));
 2738: 	} else {
 2739: 	    # Okay, this is a non-fatal error.
 2740: 	    $r->print($error.&mt('You do not have the authority to modify this users authentication information.').$end);    
 2741: 	}
 2742:     }
 2743:     $r->rflush(); # Finish display of header before time consuming actions start
 2744:     &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state);
 2745:     ##
 2746:     my (@userroles,%userupdate,$cnum,$cdom,$defaultcredits,%namechanged);
 2747:     if ($context eq 'course') {
 2748:         ($cnum,$cdom) =
 2749:             &Apache::lonuserutils::get_course_identity();
 2750:         $crstype = &Apache::loncommon::course_type($cdom.'_'.$cnum);
 2751:         if ($showcredits) {
 2752:            $defaultcredits = &Apache::lonuserutils::get_defaultcredits($cdom,$cnum);
 2753:         }
 2754:     }
 2755:     if (! $env{'form.makeuser'} ) {
 2756:         # Check for need to change
 2757:         my %userenv = &Apache::lonnet::get
 2758:             ('environment',['firstname','middlename','lastname','generation',
 2759:              'id','permanentemail','portfolioquota','authorquota','inststatus',
 2760:              'tools.aboutme','tools.blog','tools.webdav','tools.portfolio',
 2761:              'requestcourses.official','requestcourses.unofficial',
 2762:              'requestcourses.community','requestcourses.textbook',
 2763:              'reqcrsotherdom.official','reqcrsotherdom.unofficial',
 2764:              'reqcrsotherdom.community','reqcrsotherdom.textbook',
 2765:              'reqcrsotherdom.placement','requestauthor'],
 2766:               $env{'form.ccdomain'},$env{'form.ccuname'});
 2767:         my ($tmp) = keys(%userenv);
 2768:         if ($tmp =~ /^(con_lost|error)/i) { 
 2769:             %userenv = ();
 2770:         }
 2771:         my $no_forceid_alert;
 2772:         # Check to see if user information can be changed
 2773:         my %domconfig =
 2774:             &Apache::lonnet::get_dom('configuration',['usermodification'],
 2775:                                      $env{'form.ccdomain'});
 2776:         my @statuses = ('active','future');
 2777:         my %roles = &Apache::lonnet::get_my_roles($env{'form.ccuname'},$env{'form.ccdomain'},'userroles',\@statuses,undef,$env{'request.role.domain'});
 2778:         my ($auname,$audom);
 2779:         if ($context eq 'author') {
 2780:             $auname = $env{'user.name'};
 2781:             $audom = $env{'user.domain'};     
 2782:         }
 2783:         foreach my $item (keys(%roles)) {
 2784:             my ($rolenum,$roledom,$role) = split(/:/,$item,-1);
 2785:             if ($context eq 'course') {
 2786:                 if ($cnum ne '' && $cdom ne '') {
 2787:                     if ($rolenum eq $cnum && $roledom eq $cdom) {
 2788:                         if (!grep(/^\Q$role\E$/,@userroles)) {
 2789:                             push(@userroles,$role);
 2790:                         }
 2791:                     }
 2792:                 }
 2793:             } elsif ($context eq 'author') {
 2794:                 if ($rolenum eq $auname && $roledom eq $audom) {
 2795:                     if (!grep(/^\Q$role\E$/,@userroles)) { 
 2796:                         push(@userroles,$role);
 2797:                     }
 2798:                 }
 2799:             }
 2800:         }
 2801:         if ($env{'form.action'} eq 'singlestudent') {
 2802:             if (!grep(/^st$/,@userroles)) {
 2803:                 push(@userroles,'st');
 2804:             }
 2805:         } else {
 2806:             # Check for course or co-author roles being activated or re-enabled
 2807:             if ($context eq 'author' || $context eq 'course') {
 2808:                 foreach my $key (keys(%env)) {
 2809:                     if ($context eq 'author') {
 2810:                         if ($key=~/^form\.act_\Q$audom\E_\Q$auname\E_([^_]+)/) {
 2811:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 2812:                                 push(@userroles,$1);
 2813:                             }
 2814:                         } elsif ($key =~/^form\.ren\:\Q$audom\E\/\Q$auname\E_([^_]+)/) {
 2815:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 2816:                                 push(@userroles,$1);
 2817:                             }
 2818:                         }
 2819:                     } elsif ($context eq 'course') {
 2820:                         if ($key=~/^form\.act_\Q$cdom\E_\Q$cnum\E_([^_]+)/) {
 2821:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 2822:                                 push(@userroles,$1);
 2823:                             }
 2824:                         } elsif ($key =~/^form\.ren\:\Q$cdom\E\/\Q$cnum\E(\/?\w*)_([^_]+)/) {
 2825:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 2826:                                 push(@userroles,$1);
 2827:                             }
 2828:                         }
 2829:                     }
 2830:                 }
 2831:             }
 2832:         }
 2833:         #Check to see if we can change personal data for the user 
 2834:         my (@mod_disallowed,@longroles);
 2835:         foreach my $role (@userroles) {
 2836:             if ($role eq 'cr') {
 2837:                 push(@longroles,'Custom');
 2838:             } else {
 2839:                 push(@longroles,&Apache::lonnet::plaintext($role,$crstype)); 
 2840:             }
 2841:         }
 2842:         my %canmodify = &Apache::lonuserutils::can_modify_userinfo($context,$env{'form.ccdomain'},\@userinfo,\@userroles);
 2843:         foreach my $item (@userinfo) {
 2844:             # Strip leading and trailing whitespace
 2845:             $env{'form.c'.$item} =~ s/(\s+$|^\s+)//g;
 2846:             if (!$canmodify{$item}) {
 2847:                 if (defined($env{'form.c'.$item})) {
 2848:                     if ($env{'form.c'.$item} ne $userenv{$item}) {
 2849:                         push(@mod_disallowed,$item);
 2850:                     }
 2851:                 }
 2852:                 $env{'form.c'.$item} = $userenv{$item};
 2853:             }
 2854:         }
 2855:         # Check to see if we can change the Student/Employee ID
 2856:         my $forceid = $env{'form.forceid'};
 2857:         my $recurseid = $env{'form.recurseid'};
 2858:         my (%alerts,%rulematch,%idinst_results,%curr_rules,%got_rules);
 2859:         my %uidhash = &Apache::lonnet::idrget($env{'form.ccdomain'},
 2860:                                             $env{'form.ccuname'});
 2861:         if (($uidhash{$env{'form.ccuname'}}) && 
 2862:             ($uidhash{$env{'form.ccuname'}}!~/error\:/) && 
 2863:             (!$forceid)) {
 2864:             if ($env{'form.cid'} ne $uidhash{$env{'form.ccuname'}}) {
 2865:                 $env{'form.cid'} = $userenv{'id'};
 2866:                 $no_forceid_alert = &mt('New student/employee ID does not match existing ID for this user.')
 2867:                                    .'<br />'
 2868:                                    .&mt("Change is not permitted without checking the 'Force ID change' checkbox on the previous page.")
 2869:                                    .'<br />'."\n";
 2870:             }
 2871:         }
 2872:         if ($env{'form.cid'} ne $userenv{'id'}) {
 2873:             my $checkhash;
 2874:             my $checks = { 'id' => 1 };
 2875:             $checkhash->{$env{'form.ccuname'}.':'.$env{'form.ccdomain'}} = 
 2876:                    { 'newuser' => $newuser,
 2877:                      'id'  => $env{'form.cid'}, 
 2878:                    };
 2879:             &Apache::loncommon::user_rule_check($checkhash,$checks,
 2880:                 \%alerts,\%rulematch,\%idinst_results,\%curr_rules,\%got_rules);
 2881:             if (ref($alerts{'id'}) eq 'HASH') {
 2882:                 if (ref($alerts{'id'}{$env{'form.ccdomain'}}) eq 'HASH') {
 2883:                    $env{'form.cid'} = $userenv{'id'};
 2884:                 }
 2885:             }
 2886:         }
 2887:         my (%quotachanged,%oldquota,%newquota,%olddefquota,%newdefquota, 
 2888:             $oldinststatus,$newinststatus,%oldisdefault,%newisdefault,%oldsettings,
 2889:             %oldsettingstext,%newsettings,%newsettingstext,@disporder,
 2890:             %oldsettingstatus,%newsettingstatus);
 2891:         @disporder = ('inststatus');
 2892:         if ($env{'request.role.domain'} eq $env{'form.ccdomain'}) {
 2893:             push(@disporder,'requestcourses','requestauthor');
 2894:         } else {
 2895:             push(@disporder,'reqcrsotherdom');
 2896:         }
 2897:         push(@disporder,('quota','tools'));
 2898:         $oldinststatus = $userenv{'inststatus'};
 2899:         foreach my $name ('portfolio','author') {
 2900:             ($olddefquota{$name},$oldsettingstatus{$name}) = 
 2901:                 &Apache::loncommon::default_quota($env{'form.ccdomain'},$oldinststatus,$name);
 2902:             ($newdefquota{$name},$newsettingstatus{$name}) = ($olddefquota{$name},$oldsettingstatus{$name});
 2903:         }
 2904:         my %canshow;
 2905:         if (&Apache::lonnet::allowed('mpq',$env{'form.ccdomain'})) {
 2906:             $canshow{'quota'} = 1;
 2907:         }
 2908:         if (&Apache::lonnet::allowed('mut',$env{'form.ccdomain'})) {
 2909:             $canshow{'tools'} = 1;
 2910:         }
 2911:         if (&Apache::lonnet::allowed('ccc',$env{'form.ccdomain'})) {
 2912:             $canshow{'requestcourses'} = 1;
 2913:         } elsif (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) {
 2914:             $canshow{'reqcrsotherdom'} = 1;
 2915:         }
 2916:         if (&Apache::lonnet::allowed('mau',$env{'form.ccdomain'})) {
 2917:             $canshow{'inststatus'} = 1;
 2918:         }
 2919:         if (&Apache::lonnet::allowed('cau',$env{'form.ccdomain'})) {
 2920:             $canshow{'requestauthor'} = 1;
 2921:         }
 2922:         my (%changeHash,%changed);
 2923:         if ($oldinststatus eq '') {
 2924:             $oldsettings{'inststatus'} = $othertitle; 
 2925:         } else {
 2926:             if (ref($usertypes) eq 'HASH') {
 2927:                 $oldsettings{'inststatus'} = join(', ',map{ $usertypes->{ &unescape($_) }; } (split(/:/,$userenv{'inststatus'})));
 2928:             } else {
 2929:                 $oldsettings{'inststatus'} = join(', ',map{ &unescape($_); } (split(/:/,$userenv{'inststatus'})));
 2930:             }
 2931:         }
 2932:         $changeHash{'inststatus'} = $userenv{'inststatus'};
 2933:         if ($canmodify_status{'inststatus'}) {
 2934:             $canshow{'inststatus'} = 1;
 2935:             if (exists($env{'form.inststatus'})) {
 2936:                 my @inststatuses = &Apache::loncommon::get_env_multiple('form.inststatus');
 2937:                 if (@inststatuses > 0) {
 2938:                     $newinststatus = join(':',map { &escape($_); } @inststatuses);
 2939:                     $changeHash{'inststatus'} = $newinststatus;
 2940:                     if ($newinststatus ne $oldinststatus) {
 2941:                         $changed{'inststatus'} = $newinststatus;
 2942:                         foreach my $name ('portfolio','author') {
 2943:                             ($newdefquota{$name},$newsettingstatus{$name}) =
 2944:                                 &Apache::loncommon::default_quota($env{'form.ccdomain'},$newinststatus,$name);
 2945:                         }
 2946:                     }
 2947:                     if (ref($usertypes) eq 'HASH') {
 2948:                         $newsettings{'inststatus'} = join(', ',map{ $usertypes->{$_}; } (@inststatuses)); 
 2949:                     } else {
 2950:                         $newsettings{'inststatus'} = join(', ',@inststatuses);
 2951:                     }
 2952:                 }
 2953:             } else {
 2954:                 $newinststatus = '';
 2955:                 $changeHash{'inststatus'} = $newinststatus;
 2956:                 $newsettings{'inststatus'} = $othertitle;
 2957:                 if ($newinststatus ne $oldinststatus) {
 2958:                     $changed{'inststatus'} = $changeHash{'inststatus'};
 2959:                     foreach my $name ('portfolio','author') {
 2960:                         ($newdefquota{$name},$newsettingstatus{$name}) =
 2961:                             &Apache::loncommon::default_quota($env{'form.ccdomain'},$newinststatus,$name);
 2962:                     }
 2963:                 }
 2964:             }
 2965:         } elsif ($context ne 'selfcreate') {
 2966:             $canshow{'inststatus'} = 1;
 2967:             $newsettings{'inststatus'} = $oldsettings{'inststatus'};
 2968:         }
 2969:         foreach my $name ('portfolio','author') {
 2970:             $changeHash{$name.'quota'} = $userenv{$name.'quota'};
 2971:         }
 2972:         if ($context eq 'domain') {
 2973:             foreach my $name ('portfolio','author') {
 2974:                 if ($userenv{$name.'quota'} ne '') {
 2975:                     $oldquota{$name} = $userenv{$name.'quota'};
 2976:                     if ($env{'form.custom_'.$name.'quota'} == 1) {
 2977:                         if ($env{'form.'.$name.'quota'} eq '') {
 2978:                             $newquota{$name} = 0;
 2979:                         } else {
 2980:                             $newquota{$name} = $env{'form.'.$name.'quota'};
 2981:                             $newquota{$name} =~ s/[^\d\.]//g;
 2982:                         }
 2983:                         if ($newquota{$name} != $oldquota{$name}) {
 2984:                             if (&quota_admin($newquota{$name},\%changeHash,$name)) {
 2985:                                 $changed{$name.'quota'} = 1;
 2986:                             }
 2987:                         }
 2988:                     } else {
 2989:                         if (&quota_admin('',\%changeHash,$name)) {
 2990:                             $changed{$name.'quota'} = 1;
 2991:                             $newquota{$name} = $newdefquota{$name};
 2992:                             $newisdefault{$name} = 1;
 2993:                         }
 2994:                     }
 2995:                 } else {
 2996:                     $oldisdefault{$name} = 1;
 2997:                     $oldquota{$name} = $olddefquota{$name};
 2998:                     if ($env{'form.custom_'.$name.'quota'} == 1) {
 2999:                         if ($env{'form.'.$name.'quota'} eq '') {
 3000:                             $newquota{$name} = 0;
 3001:                         } else {
 3002:                             $newquota{$name} = $env{'form.'.$name.'quota'};
 3003:                             $newquota{$name} =~ s/[^\d\.]//g;
 3004:                         }
 3005:                         if (&quota_admin($newquota{$name},\%changeHash,$name)) {
 3006:                             $changed{$name.'quota'} = 1;
 3007:                         }
 3008:                     } else {
 3009:                         $newquota{$name} = $newdefquota{$name};
 3010:                         $newisdefault{$name} = 1;
 3011:                     }
 3012:                 }
 3013:                 if ($oldisdefault{$name}) {
 3014:                     $oldsettingstext{'quota'}{$name} = &get_defaultquota_text($oldsettingstatus{$name});
 3015:                 }  else {
 3016:                     $oldsettingstext{'quota'}{$name} = &mt('custom quota: [_1] MB',$oldquota{$name});
 3017:                 }
 3018:                 if ($newisdefault{$name}) {
 3019:                     $newsettingstext{'quota'}{$name} = &get_defaultquota_text($newsettingstatus{$name});
 3020:                 } else {
 3021:                     $newsettingstext{'quota'}{$name} = &mt('custom quota: [_1] MB',$newquota{$name});
 3022:                 }
 3023:             }
 3024:             &tool_changes('tools',\@usertools,\%oldsettings,\%oldsettingstext,\%userenv,
 3025:                           \%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3026:             if ($env{'form.ccdomain'} eq $env{'request.role.domain'}) {
 3027:                 &tool_changes('requestcourses',\@requestcourses,\%oldsettings,\%oldsettingstext,
 3028:                               \%userenv,\%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3029:                 &tool_changes('requestauthor',\@requestauthor,\%oldsettings,\%oldsettingstext,
 3030:                               \%userenv,\%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3031:             } else {
 3032:                 &tool_changes('reqcrsotherdom',\@requestcourses,\%oldsettings,\%oldsettingstext,
 3033:                               \%userenv,\%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3034:             }
 3035:         }
 3036:         foreach my $item (@userinfo) {
 3037:             if ($env{'form.c'.$item} ne $userenv{$item}) {
 3038:                 $namechanged{$item} = 1;
 3039:             }
 3040:         }
 3041:         foreach my $name ('portfolio','author') {
 3042:             $oldsettings{'quota'}{$name} = &mt('[_1] MB',$oldquota{$name});
 3043:             $newsettings{'quota'}{$name} = &mt('[_1] MB',$newquota{$name});
 3044:         }
 3045:         if ((keys(%namechanged) > 0) || (keys(%changed) > 0)) {
 3046:             my ($chgresult,$namechgresult);
 3047:             if (keys(%changed) > 0) {
 3048:                 $chgresult = 
 3049:                     &Apache::lonnet::put('environment',\%changeHash,
 3050:                                   $env{'form.ccdomain'},$env{'form.ccuname'});
 3051:                 if ($chgresult eq 'ok') {
 3052:                     if (($env{'user.name'} eq $env{'form.ccuname'}) &&
 3053:                         ($env{'user.domain'} eq $env{'form.ccdomain'})) {
 3054:                         my %newenvhash;
 3055:                         foreach my $key (keys(%changed)) {
 3056:                             if (($key eq 'official') || ($key eq 'unofficial') ||
 3057:                                 ($key eq 'community') || ($key eq 'textbook') ||
 3058:                                 ($key eq 'placement')) {
 3059:                                 $newenvhash{'environment.requestcourses.'.$key} =
 3060:                                     $changeHash{'requestcourses.'.$key};
 3061:                                 if ($changeHash{'requestcourses.'.$key}) {
 3062:                                     $newenvhash{'environment.canrequest.'.$key} = 1;
 3063:                                 } else {
 3064:                                     $newenvhash{'environment.canrequest.'.$key} =
 3065:           &Apache::lonnet::usertools_access($env{'user.name'},$env{'user.domain'},
 3066:                                             $key,'reload','requestcourses');
 3067:                                 }
 3068:                             } elsif ($key eq 'requestauthor') {
 3069:                                 $newenvhash{'environment.'.$key} = $changeHash{$key};
 3070:                                 if ($changeHash{$key}) {
 3071:                                     $newenvhash{'environment.canrequest.author'} = 1;
 3072:                                 } else {
 3073:                                     $newenvhash{'environment.canrequest.author'} =
 3074:           &Apache::lonnet::usertools_access($env{'user.name'},$env{'user.domain'},
 3075:                                             $key,'reload','requestauthor');
 3076:                                 }
 3077:                             } elsif ($key ne 'quota') {
 3078:                                 $newenvhash{'environment.tools.'.$key} = 
 3079:                                     $changeHash{'tools.'.$key};
 3080:                                 if ($changeHash{'tools.'.$key} ne '') {
 3081:                                     $newenvhash{'environment.availabletools.'.$key} =
 3082:                                         $changeHash{'tools.'.$key};
 3083:                                 } else {
 3084:                                     $newenvhash{'environment.availabletools.'.$key} =
 3085:           &Apache::lonnet::usertools_access($env{'user.name'},$env{'user.domain'},
 3086:           $key,'reload','tools');
 3087:                                 }
 3088:                             }
 3089:                         }
 3090:                         if (keys(%newenvhash)) {
 3091:                             &Apache::lonnet::appenv(\%newenvhash);
 3092:                         }
 3093:                     }
 3094:                 }
 3095:             }
 3096:             if (keys(%namechanged) > 0) {
 3097:                 foreach my $field (@userinfo) {
 3098:                     $changeHash{$field}  = $env{'form.c'.$field};
 3099:                 }
 3100: # Make the change
 3101:                 $namechgresult =
 3102:                     &Apache::lonnet::modifyuser($env{'form.ccdomain'},
 3103:                         $env{'form.ccuname'},$changeHash{'id'},undef,undef,
 3104:                         $changeHash{'firstname'},$changeHash{'middlename'},
 3105:                         $changeHash{'lastname'},$changeHash{'generation'},
 3106:                         $changeHash{'id'},undef,$changeHash{'permanentemail'},undef,\@userinfo);
 3107:                 %userupdate = (
 3108:                                lastname   => $env{'form.clastname'},
 3109:                                middlename => $env{'form.cmiddlename'},
 3110:                                firstname  => $env{'form.cfirstname'},
 3111:                                generation => $env{'form.cgeneration'},
 3112:                                id         => $env{'form.cid'},
 3113:                              );
 3114:             }
 3115:             if (((keys(%namechanged) > 0) && $namechgresult eq 'ok') || 
 3116:                 ((keys(%changed) > 0) && $chgresult eq 'ok')) {
 3117:             # Tell the user we changed the name
 3118:                 &display_userinfo($r,1,\@disporder,\%canshow,\@requestcourses,
 3119:                                   \@usertools,\@requestauthor,\%userenv,\%changed,\%namechanged,
 3120:                                   \%oldsettings, \%oldsettingstext,\%newsettings,
 3121:                                   \%newsettingstext);
 3122:                 if ($env{'form.cid'} ne $userenv{'id'}) {
 3123:                     &Apache::lonnet::idput($env{'form.ccdomain'},
 3124:                          {$env{'form.ccuname'} => $env{'form.cid'}},$uhome,'ids');
 3125:                     if (($recurseid) &&
 3126:                         (&Apache::lonnet::allowed('mau',$env{'form.ccdomain'}))) {
 3127:                         my $idresult = 
 3128:                             &Apache::lonuserutils::propagate_id_change(
 3129:                                 $env{'form.ccuname'},$env{'form.ccdomain'},
 3130:                                 \%userupdate);
 3131:                         $r->print('<br />'.$idresult.'<br />');
 3132:                     }
 3133:                 }
 3134:                 if (($env{'form.ccdomain'} eq $env{'user.domain'}) && 
 3135:                     ($env{'form.ccuname'} eq $env{'user.name'})) {
 3136:                     my %newenvhash;
 3137:                     foreach my $key (keys(%changeHash)) {
 3138:                         $newenvhash{'environment.'.$key} = $changeHash{$key};
 3139:                     }
 3140:                     &Apache::lonnet::appenv(\%newenvhash);
 3141:                 }
 3142:             } else { # error occurred
 3143:                 $r->print(
 3144:                     '<p class="LC_error">'
 3145:                    .&mt('Unable to successfully change environment for [_1] in domain [_2].',
 3146:                             '"'.$env{'form.ccuname'}.'"',
 3147:                             '"'.$env{'form.ccdomain'}.'"')
 3148:                    .'</p>');
 3149:             }
 3150:         } else { # End of if ($env ... ) logic
 3151:             # They did not want to change the users name, quota, tool availability,
 3152:             # or ability to request creation of courses, 
 3153:             # but we can still tell them what the name and quota and availabilities are  
 3154:             &display_userinfo($r,undef,\@disporder,\%canshow,\@requestcourses,
 3155:                               \@usertools,\@requestauthor,\%userenv,\%changed,\%namechanged,\%oldsettings,
 3156:                               \%oldsettingstext,\%newsettings,\%newsettingstext);
 3157:         }
 3158:         if (@mod_disallowed) {
 3159:             my ($rolestr,$contextname);
 3160:             if (@longroles > 0) {
 3161:                 $rolestr = join(', ',@longroles);
 3162:             } else {
 3163:                 $rolestr = &mt('No roles');
 3164:             }
 3165:             if ($context eq 'course') {
 3166:                 $contextname = 'course';
 3167:             } elsif ($context eq 'author') {
 3168:                 $contextname = 'co-author';
 3169:             }
 3170:             $r->print(&mt('The following fields were not updated: ').'<ul>');
 3171:             my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
 3172:             foreach my $field (@mod_disallowed) {
 3173:                 $r->print('<li>'.$fieldtitles{$field}.'</li>'."\n"); 
 3174:             }
 3175:             $r->print('</ul>');
 3176:             if (@mod_disallowed == 1) {
 3177:                 $r->print(&mt("You do not have the authority to change this field given the user's current set of active/future $contextname roles:"));
 3178:             } else {
 3179:                 $r->print(&mt("You do not have the authority to change these fields given the user's current set of active/future $contextname roles:"));
 3180:             }
 3181:             my $helplink = 'javascript:helpMenu('."'display'".')';
 3182:             $r->print('<span class="LC_cusr_emph">'.$rolestr.'</span><br />'
 3183:                      .&mt('Please contact your [_1]helpdesk[_2] for more information.'
 3184:                          ,'<a href="'.$helplink.'">','</a>')
 3185:                       .'<br />');
 3186:         }
 3187:         $r->print('<span class="LC_warning">'
 3188:                   .$no_forceid_alert
 3189:                   .&Apache::lonuserutils::print_namespacing_alerts($env{'form.ccdomain'},\%alerts,\%curr_rules)
 3190:                   .'</span>');
 3191:     }
 3192:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 3193:     if ($env{'form.action'} eq 'singlestudent') {
 3194:         &enroll_single_student($r,$uhome,$amode,$genpwd,$now,$newuser,$context,
 3195:                                $crstype,$showcredits,$defaultcredits);
 3196:         my $linktext = ($crstype eq 'Community' ?
 3197:             &mt('Enroll Another Member') : &mt('Enroll Another Student'));
 3198:         $r->print(
 3199:             &Apache::lonhtmlcommon::actionbox([
 3200:                 '<a href="javascript:backPage(document.userupdate)">'
 3201:                .($crstype eq 'Community' ? 
 3202:                     &mt('Enroll Another Member') : &mt('Enroll Another Student'))
 3203:                .'</a>']));
 3204:     } else {
 3205:         my @rolechanges = &update_roles($r,$context,$showcredits);
 3206:         if (keys(%namechanged) > 0) {
 3207:             if ($context eq 'course') {
 3208:                 if (@userroles > 0) {
 3209:                     if ((@rolechanges == 0) || 
 3210:                         (!(grep(/^st$/,@rolechanges)))) {
 3211:                         if (grep(/^st$/,@userroles)) {
 3212:                             my $classlistupdated =
 3213:                                 &Apache::lonuserutils::update_classlist($cdom,
 3214:                                               $cnum,$env{'form.ccdomain'},
 3215:                                        $env{'form.ccuname'},\%userupdate);
 3216:                         }
 3217:                     }
 3218:                 }
 3219:             }
 3220:         }
 3221:         my $userinfo = &Apache::loncommon::plainname($env{'form.ccuname'},
 3222:                                                      $env{'form.ccdomain'});
 3223:         if ($env{'form.popup'}) {
 3224:             $r->print('<p><a href="javascript:window.close()">'.&mt('Close window').'</a></p>');
 3225:         } else {
 3226:             $r->print('<br />'.&Apache::lonhtmlcommon::actionbox(['<a href="javascript:backPage(document.userupdate,'."'$env{'form.prevphase'}','modify'".')">'
 3227:                      .&mt('Modify this user: [_1]','<span class="LC_cusr_emph">'.$env{'form.ccuname'}.':'.$env{'form.ccdomain'}.' ('.$userinfo.')</span>').'</a>',
 3228:                      '<a href="javascript:backPage(document.userupdate)">'.&mt('Create/Modify Another User').'</a>']));
 3229:         }
 3230:     }
 3231: }
 3232: 
 3233: sub display_userinfo {
 3234:     my ($r,$changed,$order,$canshow,$requestcourses,$usertools,$requestauthor,
 3235:         $userenv,$changedhash,$namechangedhash,$oldsetting,$oldsettingtext,
 3236:         $newsetting,$newsettingtext) = @_;
 3237:     return unless (ref($order) eq 'ARRAY' &&
 3238:                    ref($canshow) eq 'HASH' && 
 3239:                    ref($requestcourses) eq 'ARRAY' && 
 3240:                    ref($requestauthor) eq 'ARRAY' &&
 3241:                    ref($usertools) eq 'ARRAY' && 
 3242:                    ref($userenv) eq 'HASH' &&
 3243:                    ref($changedhash) eq 'HASH' &&
 3244:                    ref($oldsetting) eq 'HASH' &&
 3245:                    ref($oldsettingtext) eq 'HASH' &&
 3246:                    ref($newsetting) eq 'HASH' &&
 3247:                    ref($newsettingtext) eq 'HASH');
 3248:     my %lt=&Apache::lonlocal::texthash(
 3249:          'ui'             => 'User Information',
 3250:          'uic'            => 'User Information Changed',
 3251:          'firstname'      => 'First Name',
 3252:          'middlename'     => 'Middle Name',
 3253:          'lastname'       => 'Last Name',
 3254:          'generation'     => 'Generation',
 3255:          'id'             => 'Student/Employee ID',
 3256:          'permanentemail' => 'Permanent e-mail address',
 3257:          'portfolioquota' => 'Disk space allocated to portfolio files',
 3258:          'authorquota'    => 'Disk space allocated to Authoring Space',
 3259:          'blog'           => 'Blog Availability',
 3260:          'webdav'         => 'WebDAV Availability',
 3261:          'aboutme'        => 'Personal Information Page Availability',
 3262:          'portfolio'      => 'Portfolio Availability',
 3263:          'official'       => 'Can Request Official Courses',
 3264:          'unofficial'     => 'Can Request Unofficial Courses',
 3265:          'community'      => 'Can Request Communities',
 3266:          'textbook'       => 'Can Request Textbook Courses',
 3267:          'placement'      => 'Can Request Placement Tests',
 3268:          'requestauthor'  => 'Can Request Author Role',
 3269:          'inststatus'     => "Affiliation",
 3270:          'prvs'           => 'Previous Value:',
 3271:          'chto'           => 'Changed To:'
 3272:     );
 3273:     if ($changed) {
 3274:         $r->print('<h3>'.$lt{'uic'}.'</h3>'.
 3275:                 &Apache::loncommon::start_data_table().
 3276:                 &Apache::loncommon::start_data_table_header_row());
 3277:         $r->print("<th>&nbsp;</th>\n");
 3278:         $r->print('<th><b>'.$lt{'prvs'}.'</b></th>');
 3279:         $r->print('<th><span class="LC_nobreak"><b>'.$lt{'chto'}.'</b></span></th>');
 3280:         $r->print(&Apache::loncommon::end_data_table_header_row());
 3281:         my @userinfo = ('firstname','middlename','lastname','generation','permanentemail','id');
 3282: 
 3283:         foreach my $item (@userinfo) {
 3284:             my $value = $env{'form.c'.$item};
 3285:             #show changes only:
 3286:             unless ($value eq $userenv->{$item}){
 3287:                 $r->print(&Apache::loncommon::start_data_table_row());
 3288:                 $r->print("<td>$lt{$item}</td>\n");
 3289:                 $r->print("<td>".$userenv->{$item}."</td>\n");
 3290:                 $r->print("<td>$value </td>\n");
 3291:                 $r->print(&Apache::loncommon::end_data_table_row());
 3292:             }
 3293:         }
 3294:         foreach my $entry (@{$order}) {
 3295:             if ($canshow->{$entry}) {
 3296:                 if (($entry eq 'requestcourses') || ($entry eq 'reqcrsotherdom') || ($entry eq 'requestauthor')) {
 3297:                     my @items;
 3298:                     if ($entry eq 'requestauthor') {
 3299:                         @items = ($entry);
 3300:                     } else {
 3301:                         @items = @{$requestcourses};
 3302:                     }
 3303:                     foreach my $item (@items) {
 3304:                         if (($newsetting->{$item} ne $oldsetting->{$item}) || 
 3305:                             ($newsettingtext->{$item} ne $oldsettingtext->{$item})) {
 3306:                             $r->print(&Apache::loncommon::start_data_table_row()."\n");  
 3307:                             $r->print("<td>$lt{$item}</td>\n");
 3308:                             $r->print("<td>".$oldsetting->{$item});
 3309:                             if ($oldsettingtext->{$item}) {
 3310:                                 if ($oldsetting->{$item}) {
 3311:                                     $r->print(' -- ');
 3312:                                 }
 3313:                                 $r->print($oldsettingtext->{$item});
 3314:                             }
 3315:                             $r->print("</td>\n");
 3316:                             $r->print("<td>".$newsetting->{$item});
 3317:                             if ($newsettingtext->{$item}) {
 3318:                                 if ($newsetting->{$item}) {
 3319:                                     $r->print(' -- ');
 3320:                                 }
 3321:                                 $r->print($newsettingtext->{$item});
 3322:                             }
 3323:                             $r->print("</td>\n");
 3324:                             $r->print(&Apache::loncommon::end_data_table_row()."\n");
 3325:                         }
 3326:                     }
 3327:                 } elsif ($entry eq 'tools') {
 3328:                     foreach my $item (@{$usertools}) {
 3329:                         if ($newsetting->{$item} ne $oldsetting->{$item}) {
 3330:                             $r->print(&Apache::loncommon::start_data_table_row()."\n");
 3331:                             $r->print("<td>$lt{$item}</td>\n");
 3332:                             $r->print("<td>".$oldsetting->{$item}.' '.$oldsettingtext->{$item}."</td>\n");
 3333:                             $r->print("<td>".$newsetting->{$item}.' '.$newsettingtext->{$item}."</td>\n");
 3334:                             $r->print(&Apache::loncommon::end_data_table_row()."\n");
 3335:                         }
 3336:                     }
 3337:                 } elsif ($entry eq 'quota') {
 3338:                     if ((ref($oldsetting->{$entry}) eq 'HASH') && (ref($oldsettingtext->{$entry}) eq 'HASH') &&
 3339:                         (ref($newsetting->{$entry}) eq 'HASH') && (ref($newsettingtext->{$entry}) eq 'HASH')) {
 3340:                         foreach my $name ('portfolio','author') {
 3341:                             if ($newsetting->{$entry}->{$name} ne $oldsetting->{$entry}->{$name}) {
 3342:                                 $r->print(&Apache::loncommon::start_data_table_row()."\n");
 3343:                                 $r->print("<td>$lt{$name.$entry}</td>\n");
 3344:                                 $r->print("<td>".$oldsettingtext->{$entry}->{$name}."</td>\n");
 3345:                                 $r->print("<td>".$newsettingtext->{$entry}->{$name}."</td>\n");
 3346:                                 $r->print(&Apache::loncommon::end_data_table_row()."\n");
 3347:                             }
 3348:                         }
 3349:                     }
 3350:                 } else {
 3351:                     if ($newsetting->{$entry} ne $oldsetting->{$entry}) {
 3352:                         $r->print(&Apache::loncommon::start_data_table_row()."\n");
 3353:                         $r->print("<td>$lt{$entry}</td>\n");
 3354:                         $r->print("<td>".$oldsetting->{$entry}.' '.$oldsettingtext->{$entry}."</td>\n");
 3355:                         $r->print("<td>".$newsetting->{$entry}.' '.$newsettingtext->{$entry}."</td>\n");
 3356:                         $r->print(&Apache::loncommon::end_data_table_row()."\n");
 3357:                     }
 3358:                 }
 3359:             }
 3360:         }
 3361:         $r->print(&Apache::loncommon::end_data_table().'<br />');
 3362:     } else {
 3363:         $r->print('<h3>'.$lt{'ui'}.'</h3>'.
 3364:                   '<p>'.&mt('No changes made to user information').'</p>');
 3365:     }
 3366:     return;
 3367: }
 3368: 
 3369: sub tool_changes {
 3370:     my ($context,$usertools,$oldaccess,$oldaccesstext,$userenv,$changeHash,
 3371:         $changed,$newaccess,$newaccesstext) = @_;
 3372:     if (!((ref($usertools) eq 'ARRAY') && (ref($oldaccess) eq 'HASH') &&
 3373:           (ref($oldaccesstext) eq 'HASH') && (ref($userenv) eq 'HASH') &&
 3374:           (ref($changeHash) eq 'HASH') && (ref($changed) eq 'HASH') &&
 3375:           (ref($newaccess) eq 'HASH') && (ref($newaccesstext) eq 'HASH'))) {
 3376:         return;
 3377:     }
 3378:     my %reqdisplay = &requestchange_display();
 3379:     if ($context eq 'reqcrsotherdom') {
 3380:         my @options = ('approval','validate','autolimit');
 3381:         my $optregex = join('|',@options);
 3382:         my $cdom = $env{'request.role.domain'};
 3383:         foreach my $tool (@{$usertools}) {
 3384:             $oldaccesstext->{$tool} = &mt("availability set to 'off'");
 3385:             $newaccesstext->{$tool} = $oldaccesstext->{$tool};
 3386:             $changeHash->{$context.'.'.$tool} = $userenv->{$context.'.'.$tool};
 3387:             my ($newop,$limit);
 3388:             if ($env{'form.'.$context.'_'.$tool}) {
 3389:                 $newop = $env{'form.'.$context.'_'.$tool};
 3390:                 if ($newop eq 'autolimit') {
 3391:                     $limit = $env{'form.'.$context.'_'.$tool.'_limit'};
 3392:                     $limit =~ s/\D+//g;
 3393:                     $newop .= '='.$limit;
 3394:                 }
 3395:             }
 3396:             if ($userenv->{$context.'.'.$tool} eq '') {
 3397:                 if ($newop) {
 3398:                     $changed->{$tool}=&tool_admin($tool,$cdom.':'.$newop,
 3399:                                                   $changeHash,$context);
 3400:                     if ($changed->{$tool}) {
 3401:                         if ($newop =~ /^autolimit/) {
 3402:                             if ($limit) {
 3403:                                 $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3404:                             } else {
 3405:                                 $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3406:                             }
 3407:                         } else {
 3408:                             $newaccesstext->{$tool} = $reqdisplay{$newop};
 3409:                         }
 3410:                     } else {
 3411:                         $newaccesstext->{$tool} = $oldaccesstext->{$tool};
 3412:                     }
 3413:                 }
 3414:             } else {
 3415:                 my @curr = split(',',$userenv->{$context.'.'.$tool});
 3416:                 my @new;
 3417:                 my $changedoms;
 3418:                 foreach my $req (@curr) {
 3419:                     if ($req =~ /^\Q$cdom\E\:($optregex\=?\d*)$/) {
 3420:                         my $oldop = $1;
 3421:                         if ($oldop =~ /^autolimit=(\d*)/) {
 3422:                             my $limit = $1;
 3423:                             if ($limit) {
 3424:                                 $oldaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3425:                             } else {
 3426:                                 $oldaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3427:                             }
 3428:                         } else {
 3429:                             $oldaccesstext->{$tool} = $reqdisplay{$oldop};
 3430:                         }
 3431:                         if ($oldop ne $newop) {
 3432:                             $changedoms = 1;
 3433:                             foreach my $item (@curr) {
 3434:                                 my ($reqdom,$option) = split(':',$item);
 3435:                                 unless ($reqdom eq $cdom) {
 3436:                                     push(@new,$item);
 3437:                                 }
 3438:                             }
 3439:                             if ($newop) {
 3440:                                 push(@new,$cdom.':'.$newop);
 3441:                             }
 3442:                             @new = sort(@new);
 3443:                         }
 3444:                         last;
 3445:                     }
 3446:                 }
 3447:                 if ((!$changedoms) && ($newop)) {
 3448:                     $changedoms = 1;
 3449:                     @new = sort(@curr,$cdom.':'.$newop);
 3450:                 }
 3451:                 if ($changedoms) {
 3452:                     my $newdomstr;
 3453:                     if (@new) {
 3454:                         $newdomstr = join(',',@new);
 3455:                     }
 3456:                     $changed->{$tool}=&tool_admin($tool,$newdomstr,$changeHash,
 3457:                                                   $context);
 3458:                     if ($changed->{$tool}) {
 3459:                         if ($env{'form.'.$context.'_'.$tool}) {
 3460:                             if ($env{'form.'.$context.'_'.$tool} eq 'autolimit') {
 3461:                                 my $limit = $env{'form.'.$context.'_'.$tool.'_limit'};
 3462:                                 $limit =~ s/\D+//g;
 3463:                                 if ($limit) {
 3464:                                     $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3465:                                 } else {
 3466:                                     $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3467:                                 }
 3468:                             } else {
 3469:                                 $newaccesstext->{$tool} = $reqdisplay{$env{'form.'.$context.'_'.$tool}};
 3470:                             }
 3471:                         } else {
 3472:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3473:                         }
 3474:                     }
 3475:                 }
 3476:             }
 3477:         }
 3478:         return;
 3479:     }
 3480:     foreach my $tool (@{$usertools}) {
 3481:         my ($newval,$limit,$envkey);
 3482:         $envkey = $context.'.'.$tool;
 3483:         if ($context eq 'requestcourses') {
 3484:             $newval = $env{'form.crsreq_'.$tool};
 3485:             if ($newval eq 'autolimit') {
 3486:                 $limit = $env{'form.crsreq_'.$tool.'_limit'};
 3487:                 $limit =~ s/\D+//g;
 3488:                 $newval .= '='.$limit;
 3489:             }
 3490:         } elsif ($context eq 'requestauthor') {
 3491:             $newval = $env{'form.'.$context};
 3492:             $envkey = $context;
 3493:         } else {
 3494:             $newval = $env{'form.'.$context.'_'.$tool};
 3495:         }
 3496:         if ($userenv->{$envkey} ne '') {
 3497:             $oldaccess->{$tool} = &mt('custom');
 3498:             if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 3499:                 if ($userenv->{$envkey} =~ /^autolimit=(\d*)$/) {
 3500:                     my $currlimit = $1;
 3501:                     if ($currlimit eq '') {
 3502:                         $oldaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3503:                     } else {
 3504:                         $oldaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$currlimit);
 3505:                     }
 3506:                 } elsif ($userenv->{$envkey}) {
 3507:                     $oldaccesstext->{$tool} = $reqdisplay{$userenv->{$envkey}};
 3508:                 } else {
 3509:                     $oldaccesstext->{$tool} = &mt("availability set to 'off'");
 3510:                 }
 3511:             } else {
 3512:                 if ($userenv->{$envkey}) {
 3513:                     $oldaccesstext->{$tool} = &mt("availability set to 'on'");
 3514:                 } else {
 3515:                     $oldaccesstext->{$tool} = &mt("availability set to 'off'");
 3516:                 }
 3517:             }
 3518:             $changeHash->{$envkey} = $userenv->{$envkey};
 3519:             if ($env{'form.custom'.$tool} == 1) {
 3520:                 if ($newval ne $userenv->{$envkey}) {
 3521:                     $changed->{$tool} = &tool_admin($tool,$newval,$changeHash,
 3522:                                                     $context);
 3523:                     if ($changed->{$tool}) {
 3524:                         $newaccess->{$tool} = &mt('custom');
 3525:                         if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 3526:                             if ($newval =~ /^autolimit/) {
 3527:                                 if ($limit) {
 3528:                                     $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3529:                                 } else {
 3530:                                     $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3531:                                 }
 3532:                             } elsif ($newval) {
 3533:                                 $newaccesstext->{$tool} = $reqdisplay{$newval};
 3534:                             } else {
 3535:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3536:                             }
 3537:                         } else {
 3538:                             if ($newval) {
 3539:                                 $newaccesstext->{$tool} = &mt("availability set to 'on'");
 3540:                             } else {
 3541:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3542:                             }
 3543:                         }
 3544:                     } else {
 3545:                         $newaccess->{$tool} = $oldaccess->{$tool};
 3546:                         if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 3547:                             if ($newval =~ /^autolimit/) {
 3548:                                 if ($limit) {
 3549:                                     $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3550:                                 } else {
 3551:                                     $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3552:                                 }
 3553:                             } elsif ($newval) {
 3554:                                 $newaccesstext->{$tool} = $reqdisplay{$newval};
 3555:                             } else {
 3556:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3557:                             }
 3558:                         } else {
 3559:                             if ($userenv->{$context.'.'.$tool}) {
 3560:                                 $newaccesstext->{$tool} = &mt("availability set to 'on'");
 3561:                             } else {
 3562:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3563:                             }
 3564:                         }
 3565:                     }
 3566:                 } else {
 3567:                     $newaccess->{$tool} = $oldaccess->{$tool};
 3568:                     $newaccesstext->{$tool} = $oldaccesstext->{$tool};
 3569:                 }
 3570:             } else {
 3571:                 $changed->{$tool} = &tool_admin($tool,'',$changeHash,$context);
 3572:                 if ($changed->{$tool}) {
 3573:                     $newaccess->{$tool} = &mt('default');
 3574:                 } else {
 3575:                     $newaccess->{$tool} = $oldaccess->{$tool};
 3576:                     if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 3577:                         if ($newval =~ /^autolimit/) {
 3578:                             if ($limit) {
 3579:                                 $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3580:                             } else {
 3581:                                 $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3582:                             }
 3583:                         } elsif ($newval) {
 3584:                             $newaccesstext->{$tool} = $reqdisplay{$newval};
 3585:                         } else {
 3586:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3587:                         }
 3588:                     } else {
 3589:                         if ($userenv->{$context.'.'.$tool}) {
 3590:                             $newaccesstext->{$tool} = &mt("availability set to 'on'");
 3591:                         } else {
 3592:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3593:                         }
 3594:                     }
 3595:                 }
 3596:             }
 3597:         } else {
 3598:             $oldaccess->{$tool} = &mt('default');
 3599:             if ($env{'form.custom'.$tool} == 1) {
 3600:                 $changed->{$tool} = &tool_admin($tool,$newval,$changeHash,
 3601:                                                 $context);
 3602:                 if ($changed->{$tool}) {
 3603:                     $newaccess->{$tool} = &mt('custom');
 3604:                     if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 3605:                         if ($newval =~ /^autolimit/) {
 3606:                             if ($limit) {
 3607:                                 $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3608:                             } else {
 3609:                                 $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3610:                             }
 3611:                         } elsif ($newval) {
 3612:                             $newaccesstext->{$tool} = $reqdisplay{$newval};
 3613:                         } else {
 3614:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3615:                         }
 3616:                     } else {
 3617:                         if ($newval) {
 3618:                             $newaccesstext->{$tool} = &mt("availability set to 'on'");
 3619:                         } else {
 3620:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3621:                         }
 3622:                     }
 3623:                 } else {
 3624:                     $newaccess->{$tool} = $oldaccess->{$tool};
 3625:                 }
 3626:             } else {
 3627:                 $newaccess->{$tool} = $oldaccess->{$tool};
 3628:             }
 3629:         }
 3630:     }
 3631:     return;
 3632: }
 3633: 
 3634: sub update_roles {
 3635:     my ($r,$context,$showcredits) = @_;
 3636:     my $now=time;
 3637:     my @rolechanges;
 3638:     my %disallowed;
 3639:     $r->print('<h3>'.&mt('Modifying Roles').'</h3>');
 3640:     foreach my $key (keys(%env)) {
 3641: 	next if (! $env{$key});
 3642:         next if ($key eq 'form.action');
 3643: 	# Revoke roles
 3644: 	if ($key=~/^form\.rev/) {
 3645: 	    if ($key=~/^form\.rev\:([^\_]+)\_([^\_\.]+)$/) {
 3646: # Revoke standard role
 3647: 		my ($scope,$role) = ($1,$2);
 3648: 		my $result =
 3649: 		    &Apache::lonnet::revokerole($env{'form.ccdomain'},
 3650: 						$env{'form.ccuname'},
 3651: 						$scope,$role,'','',$context);
 3652:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
 3653:                             &mt('Revoking [_1] in [_2]',
 3654:                                 &Apache::lonnet::plaintext($role),
 3655:                                 &Apache::loncommon::show_role_extent($scope,$context,$role)),
 3656:                                 $result ne "ok").'<br />');
 3657:                 if ($result ne "ok") {
 3658:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 3659:                 }
 3660: 		if ($role eq 'st') {
 3661: 		    my $result = 
 3662:                         &Apache::lonuserutils::classlist_drop($scope,
 3663:                             $env{'form.ccuname'},$env{'form.ccdomain'},
 3664: 			    $now);
 3665:                     $r->print(&Apache::lonhtmlcommon::confirm_success($result));
 3666: 		}
 3667:                 if (!grep(/^\Q$role\E$/,@rolechanges)) {
 3668:                     push(@rolechanges,$role);
 3669:                 }
 3670: 	    }
 3671: 	    if ($key=~m{^form\.rev\:([^_]+)_cr\.cr/($match_domain)/($match_username)/(\w+)$}s) {
 3672: # Revoke custom role
 3673:                 my $result = &Apache::lonnet::revokecustomrole(
 3674:                     $env{'form.ccdomain'},$env{'form.ccuname'},$1,$2,$3,$4,'','',$context);
 3675:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
 3676:                             &mt('Revoking custom role [_1] by [_2] in [_3]',
 3677:                                 $4,$3.':'.$2,&Apache::loncommon::show_role_extent($1,$context,'cr')),
 3678:                             $result ne 'ok').'<br />');
 3679:                 if ($result ne "ok") {
 3680:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 3681:                 }
 3682:                 if (!grep(/^cr$/,@rolechanges)) {
 3683:                     push(@rolechanges,'cr');
 3684:                 }
 3685: 	    }
 3686: 	} elsif ($key=~/^form\.del/) {
 3687: 	    if ($key=~/^form\.del\:([^\_]+)\_([^\_\.]+)$/) {
 3688: # Delete standard role
 3689: 		my ($scope,$role) = ($1,$2);
 3690: 		my $result =
 3691: 		    &Apache::lonnet::assignrole($env{'form.ccdomain'},
 3692: 						$env{'form.ccuname'},
 3693: 						$scope,$role,$now,0,1,'',
 3694:                                                 $context);
 3695:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
 3696:                             &mt('Deleting [_1] in [_2]',
 3697:                                 &Apache::lonnet::plaintext($role),
 3698:                                 &Apache::loncommon::show_role_extent($scope,$context,$role)),
 3699:                             $result ne 'ok').'<br />');
 3700:                 if ($result ne "ok") {
 3701:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 3702:                 }
 3703: 
 3704: 		if ($role eq 'st') {
 3705: 		    my $result = 
 3706:                         &Apache::lonuserutils::classlist_drop($scope,
 3707:                             $env{'form.ccuname'},$env{'form.ccdomain'},
 3708: 			    $now);
 3709: 		    $r->print(&Apache::lonhtmlcommon::confirm_success($result));
 3710: 		}
 3711:                 if (!grep(/^\Q$role\E$/,@rolechanges)) {
 3712:                     push(@rolechanges,$role);
 3713:                 }
 3714:             }
 3715: 	    if ($key=~m{^form\.del\:([^_]+)_cr\.cr/($match_domain)/($match_username)/(\w+)$}) {
 3716:                 my ($url,$rdom,$rnam,$rolename) = ($1,$2,$3,$4);
 3717: # Delete custom role
 3718:                 my $result =
 3719:                     &Apache::lonnet::assigncustomrole($env{'form.ccdomain'},
 3720:                         $env{'form.ccuname'},$url,$rdom,$rnam,$rolename,$now,
 3721:                         0,1,$context);
 3722:                 $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('Deleting custom role [_1] by [_2] in [_3]',
 3723:                       $rolename,$rnam.':'.$rdom,&Apache::loncommon::show_role_extent($1,$context,'cr')),
 3724:                       $result ne "ok").'<br />');
 3725:                 if ($result ne "ok") {
 3726:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 3727:                 }
 3728: 
 3729:                 if (!grep(/^cr$/,@rolechanges)) {
 3730:                     push(@rolechanges,'cr');
 3731:                 }
 3732:             }
 3733: 	} elsif ($key=~/^form\.ren/) {
 3734:             my $udom = $env{'form.ccdomain'};
 3735:             my $uname = $env{'form.ccuname'};
 3736: # Re-enable standard role
 3737: 	    if ($key=~/^form\.ren\:([^\_]+)\_([^\_\.]+)$/) {
 3738:                 my $url = $1;
 3739:                 my $role = $2;
 3740:                 my $logmsg;
 3741:                 my $output;
 3742:                 if ($role eq 'st') {
 3743:                     if ($url =~ m-^/($match_domain)/($match_courseid)/?(\w*)$-) {
 3744:                         my ($cdom,$cnum,$csec) = ($1,$2,$3);
 3745:                         my $credits;
 3746:                         if ($showcredits) {
 3747:                             my $defaultcredits = 
 3748:                                 &Apache::lonuserutils::get_defaultcredits($cdom,$cnum);
 3749:                             $credits = &get_user_credits($defaultcredits,$cdom,$cnum);
 3750:                         }
 3751:                         my $result = &Apache::loncommon::commit_studentrole(\$logmsg,$udom,$uname,$url,$role,$now,0,$cdom,$cnum,$csec,$context,$credits);
 3752:                         if (($result =~ /^error/) || ($result eq 'not_in_class') || ($result eq 'unknown_course') || ($result eq 'refused')) {
 3753:                             if ($result eq 'refused' && $logmsg) {
 3754:                                 $output = $logmsg;
 3755:                             } else { 
 3756:                                 $output = &mt('Error: [_1]',$result)."\n";
 3757:                             }
 3758:                         } else {
 3759:                             $output = &Apache::lonhtmlcommon::confirm_success(&mt('Assigning [_1] in [_2] starting [_3]',
 3760:                                         &Apache::lonnet::plaintext($role),
 3761:                                         &Apache::loncommon::show_role_extent($url,$context,'st'),
 3762:                                         &Apache::lonlocal::locallocaltime($now))).'<br />'.$logmsg.'<br />';
 3763:                         }
 3764:                     }
 3765:                 } else {
 3766: 		    my $result=&Apache::lonnet::assignrole($env{'form.ccdomain'},
 3767:                                $env{'form.ccuname'},$url,$role,0,$now,'','',
 3768:                                $context);
 3769:                         $output = &Apache::lonhtmlcommon::confirm_success(&mt('Re-enabling [_1] in [_2]',
 3770:                                         &Apache::lonnet::plaintext($role),
 3771:                                         &Apache::loncommon::show_role_extent($url,$context,$role)),$result ne "ok").'<br />';
 3772:                     if ($result ne "ok") {
 3773:                         $output .= &mt('Error: [_1]',$result).'<br />';
 3774:                     }
 3775:                 }
 3776:                 $r->print($output);
 3777:                 if (!grep(/^\Q$role\E$/,@rolechanges)) {
 3778:                     push(@rolechanges,$role);
 3779:                 }
 3780: 	    }
 3781: # Re-enable custom role
 3782: 	    if ($key=~m{^form\.ren\:([^_]+)_cr\.cr/($match_domain)/($match_username)/(\w+)$}) {
 3783:                 my ($url,$rdom,$rnam,$rolename) = ($1,$2,$3,$4);
 3784:                 my $result = &Apache::lonnet::assigncustomrole(
 3785:                                $env{'form.ccdomain'}, $env{'form.ccuname'},
 3786:                                $url,$rdom,$rnam,$rolename,0,$now,undef,$context);
 3787:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
 3788:                     &mt('Re-enabling custom role [_1] by [_2] in [_3]',
 3789:                         $rolename,$rnam.':'.$rdom,&Apache::loncommon::show_role_extent($1,$context,'cr')),
 3790:                     $result ne "ok").'<br />');
 3791:                 if ($result ne "ok") {
 3792:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 3793:                 }
 3794:                 if (!grep(/^cr$/,@rolechanges)) {
 3795:                     push(@rolechanges,'cr');
 3796:                 }
 3797:             }
 3798: 	} elsif ($key=~/^form\.act/) {
 3799:             my $udom = $env{'form.ccdomain'};
 3800:             my $uname = $env{'form.ccuname'};
 3801: 	    if ($key=~/^form\.act\_($match_domain)\_($match_courseid)\_cr_cr_($match_domain)_($match_username)_([^\_]+)$/) {
 3802:                 # Activate a custom role
 3803: 		my ($one,$two,$three,$four,$five)=($1,$2,$3,$4,$5);
 3804: 		my $url='/'.$one.'/'.$two;
 3805: 		my $full=$one.'_'.$two.'_cr_cr_'.$three.'_'.$four.'_'.$five;
 3806: 
 3807:                 my $start = ( $env{'form.start_'.$full} ?
 3808:                               $env{'form.start_'.$full} :
 3809:                               $now );
 3810:                 my $end   = ( $env{'form.end_'.$full} ?
 3811:                               $env{'form.end_'.$full} :
 3812:                               0 );
 3813:                                                                                      
 3814:                 # split multiple sections
 3815:                 my %sections = ();
 3816:                 my $num_sections = &build_roles($env{'form.sec_'.$full},\%sections,$5);
 3817:                 if ($num_sections == 0) {
 3818:                     $r->print(&Apache::loncommon::commit_customrole($udom,$uname,$url,$three,$four,$five,$start,$end,$context));
 3819:                 } else {
 3820: 		    my %curr_groups =
 3821: 			&Apache::longroup::coursegroups($one,$two);
 3822:                     foreach my $sec (sort {$a cmp $b} keys(%sections)) {
 3823:                         if (($sec eq 'none') || ($sec eq 'all') || 
 3824:                             exists($curr_groups{$sec})) {
 3825:                             $disallowed{$sec} = $url;
 3826:                             next;
 3827:                         }
 3828:                         my $securl = $url.'/'.$sec;
 3829: 		        $r->print(&Apache::loncommon::commit_customrole($udom,$uname,$securl,$three,$four,$five,$start,$end,$context));
 3830:                     }
 3831:                 }
 3832:                 if (!grep(/^cr$/,@rolechanges)) {
 3833:                     push(@rolechanges,'cr');
 3834:                 }
 3835: 	    } elsif ($key=~/^form\.act\_($match_domain)\_($match_name)\_([^\_]+)$/) {
 3836: 		# Activate roles for sections with 3 id numbers
 3837: 		# set start, end times, and the url for the class
 3838: 		my ($one,$two,$three)=($1,$2,$3);
 3839: 		my $start = ( $env{'form.start_'.$one.'_'.$two.'_'.$three} ? 
 3840: 			      $env{'form.start_'.$one.'_'.$two.'_'.$three} : 
 3841: 			      $now );
 3842: 		my $end   = ( $env{'form.end_'.$one.'_'.$two.'_'.$three} ? 
 3843: 			      $env{'form.end_'.$one.'_'.$two.'_'.$three} :
 3844: 			      0 );
 3845: 		my $url='/'.$one.'/'.$two;
 3846:                 my $type = 'three';
 3847:                 # split multiple sections
 3848:                 my %sections = ();
 3849:                 my $num_sections = &build_roles($env{'form.sec_'.$one.'_'.$two.'_'.$three},\%sections,$three);
 3850:                 my $credits;
 3851:                 if ($three eq 'st') {
 3852:                     if ($showcredits) { 
 3853:                         my $defaultcredits = 
 3854:                             &Apache::lonuserutils::get_defaultcredits($one,$two);
 3855:                         $credits = $env{'form.credits_'.$one.'_'.$two.'_'.$three};
 3856:                         $credits =~ s/[^\d\.]//g;
 3857:                         if ($credits eq $defaultcredits) {
 3858:                             undef($credits);
 3859:                         }
 3860:                     }
 3861:                 }
 3862:                 if ($num_sections == 0) {
 3863:                     $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$three,$start,$end,$one,$two,'',$context,$credits));
 3864:                 } else {
 3865:                     my %curr_groups = 
 3866: 			&Apache::longroup::coursegroups($one,$two);
 3867:                     my $emptysec = 0;
 3868:                     foreach my $sec (sort {$a cmp $b} keys(%sections)) {
 3869:                         $sec =~ s/\W//g;
 3870:                         if ($sec ne '') {
 3871:                             if (($sec eq 'none') || ($sec eq 'all') || 
 3872:                                 exists($curr_groups{$sec})) {
 3873:                                 $disallowed{$sec} = $url;
 3874:                                 next;
 3875:                             }
 3876:                             my $securl = $url.'/'.$sec;
 3877:                             $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$securl,$three,$start,$end,$one,$two,$sec,$context,$credits));
 3878:                         } else {
 3879:                             $emptysec = 1;
 3880:                         }
 3881:                     }
 3882:                     if ($emptysec) {
 3883:                         $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$three,$start,$end,$one,$two,'',$context,$credits));
 3884:                     }
 3885:                 }
 3886:                 if (!grep(/^\Q$three\E$/,@rolechanges)) {
 3887:                     push(@rolechanges,$three);
 3888:                 }
 3889: 	    } elsif ($key=~/^form\.act\_([^\_]+)\_([^\_]+)$/) {
 3890: 		# Activate roles for sections with two id numbers
 3891: 		# set start, end times, and the url for the class
 3892: 		my $start = ( $env{'form.start_'.$1.'_'.$2} ? 
 3893: 			      $env{'form.start_'.$1.'_'.$2} : 
 3894: 			      $now );
 3895: 		my $end   = ( $env{'form.end_'.$1.'_'.$2} ? 
 3896: 			      $env{'form.end_'.$1.'_'.$2} :
 3897: 			      0 );
 3898:                 my $one = $1;
 3899:                 my $two = $2;
 3900: 		my $url='/'.$one.'/';
 3901:                 # split multiple sections
 3902:                 my %sections = ();
 3903:                 my $num_sections = &build_roles($env{'form.sec_'.$one.'_'.$two},\%sections,$two);
 3904:                 if ($num_sections == 0) {
 3905:                     $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$two,$start,$end,$one,undef,'',$context));
 3906:                 } else {
 3907:                     my $emptysec = 0;
 3908:                     foreach my $sec (sort {$a cmp $b} keys(%sections)) {
 3909:                         if ($sec ne '') {
 3910:                             my $securl = $url.'/'.$sec;
 3911:                             $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$securl,$two,$start,$end,$one,undef,$sec,$context));
 3912:                         } else {
 3913:                             $emptysec = 1;
 3914:                         }
 3915:                     }
 3916:                     if ($emptysec) {
 3917:                         $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$two,$start,$end,$one,undef,'',$context));
 3918:                     }
 3919:                 }
 3920:                 if (!grep(/^\Q$two\E$/,@rolechanges)) {
 3921:                     push(@rolechanges,$two);
 3922:                 }
 3923: 	    } else {
 3924: 		$r->print('<p><span class="LC_error">'.&mt('ERROR').': '.&mt('Unknown command').' <tt>'.$key.'</tt></span></p><br />');
 3925:             }
 3926:             foreach my $key (sort(keys(%disallowed))) {
 3927:                 $r->print('<p class="LC_warning">');
 3928:                 if (($key eq 'none') || ($key eq 'all')) {  
 3929:                     $r->print(&mt('[_1] may not be used as the name for a section, as it is a reserved word.','<tt>'.$key.'</tt>'));
 3930:                 } else {
 3931:                     $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>'));
 3932:                 }
 3933:                 $r->print('</p><p>'
 3934:                          .&mt('Please [_1]go back[_2] and choose a different section name.'
 3935:                              ,'<a href="javascript:history.go(-1)'
 3936:                              ,'</a>')
 3937:                          .'</p><br />'
 3938:                 );
 3939:             }
 3940: 	}
 3941:     } # End of foreach (keys(%env))
 3942: # Flush the course logs so reverse user roles immediately updated
 3943:     $r->register_cleanup(\&Apache::lonnet::flushcourselogs);
 3944:     if (@rolechanges == 0) {
 3945:         $r->print('<p>'.&mt('No roles to modify').'</p>');
 3946:     }
 3947:     return @rolechanges;
 3948: }
 3949: 
 3950: sub get_user_credits {
 3951:     my ($uname,$udom,$defaultcredits,$cdom,$cnum) = @_;
 3952:     if ($cdom eq '' || $cnum eq '') {
 3953:         return unless ($env{'request.course.id'});
 3954:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3955:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3956:     }
 3957:     my $credits;
 3958:     my %currhash =
 3959:         &Apache::lonnet::get('classlist',[$uname.':'.$udom],$cdom,$cnum);
 3960:     if (keys(%currhash) > 0) {
 3961:         my @items = split(/:/,$currhash{$uname.':'.$udom});
 3962:         my $crdidx = &Apache::loncoursedata::CL_CREDITS() - 3;
 3963:         $credits = $items[$crdidx];
 3964:         $credits =~ s/[^\d\.]//g;
 3965:     }
 3966:     if ($credits eq $defaultcredits) {
 3967:         undef($credits);
 3968:     }
 3969:     return $credits;
 3970: }
 3971: 
 3972: sub enroll_single_student {
 3973:     my ($r,$uhome,$amode,$genpwd,$now,$newuser,$context,$crstype,
 3974:         $showcredits,$defaultcredits) = @_;
 3975:     $r->print('<h3>');
 3976:     if ($crstype eq 'Community') {
 3977:         $r->print(&mt('Enrolling Member'));
 3978:     } else {
 3979:         $r->print(&mt('Enrolling Student'));
 3980:     }
 3981:     $r->print('</h3>');
 3982: 
 3983:     # Remove non alphanumeric values from section
 3984:     $env{'form.sections'}=~s/\W//g;
 3985: 
 3986:     my $credits;
 3987:     if (($showcredits) && ($env{'form.credits'} ne '')) {
 3988:         $credits = $env{'form.credits'};
 3989:         $credits =~ s/[^\d\.]//g;
 3990:         if ($credits ne '') {
 3991:             if ($credits eq $defaultcredits) {
 3992:                 undef($credits);
 3993:             }
 3994:         }
 3995:     }
 3996: 
 3997:     # Clean out any old student roles the user has in this class.
 3998:     &Apache::lonuserutils::modifystudent($env{'form.ccdomain'},
 3999:          $env{'form.ccuname'},$env{'request.course.id'},undef,$uhome);
 4000:     my ($startdate,$enddate) = &Apache::lonuserutils::get_dates_from_form();
 4001:     my $enroll_result =
 4002:         &Apache::lonnet::modify_student_enrollment($env{'form.ccdomain'},
 4003:             $env{'form.ccuname'},$env{'form.cid'},$env{'form.cfirstname'},
 4004:             $env{'form.cmiddlename'},$env{'form.clastname'},
 4005:             $env{'form.generation'},$env{'form.sections'},$enddate,
 4006:             $startdate,'manual',undef,$env{'request.course.id'},'',$context,
 4007:             $credits);
 4008:     if ($enroll_result =~ /^ok/) {
 4009:         $r->print(&mt('[_1] enrolled','<b>'.$env{'form.ccuname'}.':'.$env{'form.ccdomain'}.'</b>'));
 4010:         if ($env{'form.sections'} ne '') {
 4011:             $r->print(' '.&mt('in section [_1]',$env{'form.sections'}));
 4012:         }
 4013:         my ($showstart,$showend);
 4014:         if ($startdate <= $now) {
 4015:             $showstart = &mt('Access starts immediately');
 4016:         } else {
 4017:             $showstart = &mt('Access starts: ').&Apache::lonlocal::locallocaltime($startdate);
 4018:         }
 4019:         if ($enddate == 0) {
 4020:             $showend = &mt('ends: no ending date');
 4021:         } else {
 4022:             $showend = &mt('ends: ').&Apache::lonlocal::locallocaltime($enddate);
 4023:         }
 4024:         $r->print('.<br />'.$showstart.'; '.$showend);
 4025:         if ($startdate <= $now && !$newuser) {
 4026:             $r->print('<p class="LC_info">');
 4027:             if ($crstype eq 'Community') {
 4028:                 $r->print(&mt('If the member is currently logged-in to LON-CAPA, the new role can be displayed by using the "Check for changes" link on the Roles/Courses page.'));
 4029:             } else {
 4030:                 $r->print(&mt('If the student is currently logged-in to LON-CAPA, the new role can be displayed by using the "Check for changes" link on the Roles/Courses page.'));
 4031:            }
 4032:            $r->print('</p>');
 4033:         }
 4034:     } else {
 4035:         $r->print(&mt('unable to enroll').": ".$enroll_result);
 4036:     }
 4037:     return;
 4038: }
 4039: 
 4040: sub get_defaultquota_text {
 4041:     my ($settingstatus) = @_;
 4042:     my $defquotatext; 
 4043:     if ($settingstatus eq '') {
 4044:         $defquotatext = &mt('default');
 4045:     } else {
 4046:         my ($usertypes,$order) =
 4047:             &Apache::lonnet::retrieve_inst_usertypes($env{'form.ccdomain'});
 4048:         if ($usertypes->{$settingstatus} eq '') {
 4049:             $defquotatext = &mt('default');
 4050:         } else {
 4051:             $defquotatext = &mt('default for [_1]',$usertypes->{$settingstatus});
 4052:         }
 4053:     }
 4054:     return $defquotatext;
 4055: }
 4056: 
 4057: sub update_result_form {
 4058:     my ($uhome) = @_;
 4059:     my $outcome = 
 4060:     '<form name="userupdate" method="post" action="">'."\n";
 4061:     foreach my $item ('srchby','srchin','srchtype','srchterm','srchdomain','ccuname','ccdomain') {
 4062:         $outcome .= '<input type="hidden" name="'.$item.'" value="'.$env{'form.'.$item}.'" />'."\n";
 4063:     }
 4064:     if ($env{'form.origname'} ne '') {
 4065:         $outcome .= '<input type="hidden" name="origname" value="'.$env{'form.origname'}.'" />'."\n";
 4066:     }
 4067:     foreach my $item ('sortby','seluname','seludom') {
 4068:         if (exists($env{'form.'.$item})) {
 4069:             $outcome .= '<input type="hidden" name="'.$item.'" value="'.$env{'form.'.$item}.'" />'."\n";
 4070:         }
 4071:     }
 4072:     if ($uhome eq 'no_host') {
 4073:         $outcome .= '<input type="hidden" name="forcenewuser" value="1" />'."\n";
 4074:     }
 4075:     $outcome .= '<input type="hidden" name="phase" value="" />'."\n".
 4076:                 '<input type="hidden" name="currstate" value="" />'."\n".
 4077:                 '<input type="hidden" name="action" value="'.$env{'form.action'}.'" />'."\n".
 4078:                 '</form>';
 4079:     return $outcome;
 4080: }
 4081: 
 4082: sub quota_admin {
 4083:     my ($setquota,$changeHash,$name) = @_;
 4084:     my $quotachanged;
 4085:     if (&Apache::lonnet::allowed('mpq',$env{'form.ccdomain'})) {
 4086:         # Current user has quota modification privileges
 4087:         if (ref($changeHash) eq 'HASH') {
 4088:             $quotachanged = 1;
 4089:             $changeHash->{$name.'quota'} = $setquota;
 4090:         }
 4091:     }
 4092:     return $quotachanged;
 4093: }
 4094: 
 4095: sub tool_admin {
 4096:     my ($tool,$settool,$changeHash,$context) = @_;
 4097:     my $canchange = 0; 
 4098:     if ($context eq 'requestcourses') {
 4099:         if (&Apache::lonnet::allowed('ccc',$env{'form.ccdomain'})) {
 4100:             $canchange = 1;
 4101:         }
 4102:     } elsif ($context eq 'reqcrsotherdom') {
 4103:         if (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) {
 4104:             $canchange = 1;
 4105:         }
 4106:     } elsif ($context eq 'requestauthor') {
 4107:         if (&Apache::lonnet::allowed('cau',$env{'request.role.domain'})) {
 4108:             $canchange = 1;
 4109:         }
 4110:     } elsif (&Apache::lonnet::allowed('mut',$env{'form.ccdomain'})) {
 4111:         # Current user has quota modification privileges
 4112:         $canchange = 1;
 4113:     }
 4114:     my $toolchanged;
 4115:     if ($canchange) {
 4116:         if (ref($changeHash) eq 'HASH') {
 4117:             $toolchanged = 1;
 4118:             if ($tool eq 'requestauthor') {
 4119:                 $changeHash->{$context} = $settool;
 4120:             } else {
 4121:                 $changeHash->{$context.'.'.$tool} = $settool;
 4122:             }
 4123:         }
 4124:     }
 4125:     return $toolchanged;
 4126: }
 4127: 
 4128: sub build_roles {
 4129:     my ($sectionstr,$sections,$role) = @_;
 4130:     my $num_sections = 0;
 4131:     if ($sectionstr=~ /,/) {
 4132:         my @secnums = split/,/,$sectionstr;
 4133:         if ($role eq 'st') {
 4134:             $secnums[0] =~ s/\W//g;
 4135:             $$sections{$secnums[0]} = 1;
 4136:             $num_sections = 1;
 4137:         } else {
 4138:             foreach my $sec (@secnums) {
 4139:                 $sec =~ ~s/\W//g;
 4140:                 if (!($sec eq "")) {
 4141:                     if (exists($$sections{$sec})) {
 4142:                         $$sections{$sec} ++;
 4143:                     } else {
 4144:                         $$sections{$sec} = 1;
 4145:                         $num_sections ++;
 4146:                     }
 4147:                 }
 4148:             }
 4149:         }
 4150:     } else {
 4151:         $sectionstr=~s/\W//g;
 4152:         unless ($sectionstr eq '') {
 4153:             $$sections{$sectionstr} = 1;
 4154:             $num_sections ++;
 4155:         }
 4156:     }
 4157: 
 4158:     return $num_sections;
 4159: }
 4160: 
 4161: # ========================================================== Custom Role Editor
 4162: 
 4163: sub custom_role_editor {
 4164:     my ($r,$brcrum) = @_;
 4165:     my $action = $env{'form.customroleaction'};
 4166:     my $rolename; 
 4167:     if ($action eq 'new') {
 4168:         $rolename=$env{'form.newrolename'};
 4169:     } else {
 4170:         $rolename=$env{'form.rolename'};
 4171:     }
 4172: 
 4173:     my ($crstype,$context);
 4174:     if ($env{'request.course.id'}) {
 4175:         $crstype = &Apache::loncommon::course_type();
 4176:         $context = 'course';
 4177:     } else {
 4178:         $context = 'domain';
 4179:         $crstype = $env{'form.templatecrstype'};
 4180:     }
 4181: 
 4182:     $rolename=~s/[^A-Za-z0-9]//gs;
 4183:     if (!$rolename || $env{'form.phase'} eq 'pickrole') {
 4184: 	&print_username_entry_form($r,undef,undef,undef,undef,$crstype,$brcrum);
 4185:         return;
 4186:     }
 4187: 
 4188: # ------------------------------------------------------- What can be assigned?
 4189:     my %full=();
 4190:     my %courselevel=();
 4191:     my %courselevelcurrent=();
 4192:     my $syspriv='';
 4193:     my $dompriv='';
 4194:     my $coursepriv='';
 4195:     my $body_top;
 4196:     my $newrole;
 4197:     my ($rdummy,$roledef)=
 4198: 			 &Apache::lonnet::get('roles',["rolesdef_$rolename"]);
 4199: # ------------------------------------------------------- Does this role exist?
 4200:     $body_top .= '<h2>';
 4201:     if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 4202: 	$body_top .= &mt('Existing Role').' "';
 4203: # ------------------------------------------------- Get current role privileges
 4204: 	($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 4205:         if ($crstype eq 'Community') {
 4206:             $syspriv =~ s/bre\&S//;   
 4207:         }
 4208:     } else {
 4209:         $newrole = 1;
 4210: 	$body_top .= &mt('New Role').' "';
 4211: 	$roledef='';
 4212:     }
 4213:     $body_top .= $rolename.'"</h2>';
 4214:     foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
 4215: 	my ($priv,$restrict)=split(/\&/,$item);
 4216:         if (!$restrict) { $restrict='F'; }
 4217:         $courselevel{$priv}=$restrict;
 4218:         if ($coursepriv=~/\:$priv/) {
 4219: 	    $courselevelcurrent{$priv}=1;
 4220: 	}
 4221: 	$full{$priv}=1;
 4222:     }
 4223:     my %domainlevel=();
 4224:     my %domainlevelcurrent=();
 4225:     foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:d'})) {
 4226: 	my ($priv,$restrict)=split(/\&/,$item);
 4227:         if (!$restrict) { $restrict='F'; }
 4228:         $domainlevel{$priv}=$restrict;
 4229:         if ($dompriv=~/\:$priv/) {
 4230: 	    $domainlevelcurrent{$priv}=1;
 4231: 	}
 4232: 	$full{$priv}=1;
 4233:     }
 4234:     my %systemlevel=();
 4235:     my %systemlevelcurrent=();
 4236:     foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:s'})) {
 4237: 	my ($priv,$restrict)=split(/\&/,$item);
 4238:         if (!$restrict) { $restrict='F'; }
 4239:         $systemlevel{$priv}=$restrict;
 4240:         if ($syspriv=~/\:$priv/) {
 4241: 	    $systemlevelcurrent{$priv}=1;
 4242: 	}
 4243: 	$full{$priv}=1;
 4244:     }
 4245:     my ($jsback,$elements) = &crumb_utilities();
 4246:     my $button_code = "\n";
 4247:     my $head_script = "\n";
 4248:     $head_script .= '<script type="text/javascript">'."\n"
 4249:                    .'// <![CDATA['."\n";
 4250:     my @template_roles = ("in","ta","ep");
 4251:     if ($context eq 'domain') {
 4252:         push(@template_roles,"ad");
 4253:     }
 4254:     push(@template_roles,"st");
 4255:     if ($crstype eq 'Community') {
 4256:         unshift(@template_roles,'co');
 4257:     } else {
 4258:         unshift(@template_roles,'cc');
 4259:     }
 4260:     foreach my $role (@template_roles) {
 4261:         $head_script .= &make_script_template($role,$crstype);
 4262:         $button_code .= &make_button_code($role,$crstype).' ';
 4263:     }
 4264:     my $context_code;
 4265:     if ($context eq 'domain') {
 4266:         my $checkedCommunity = '';
 4267:         my $checkedCourse = ' checked="checked"';
 4268:         if ($env{'form.templatecrstype'} eq 'Community') {
 4269:             $checkedCommunity = $checkedCourse;
 4270:             $checkedCourse = '';
 4271:         }
 4272:         $context_code = '<label>'.
 4273:                         '<input type="radio" name="templatecrstype" value="Course"'.$checkedCourse.' onclick="this.form.submit();">'.
 4274:                         &mt('Course').
 4275:                         '</label>'.('&nbsp;' x2).
 4276:                         '<label>'.
 4277:                         '<input type="radio" name="templatecrstype" value="Community"'.$checkedCommunity.' onclick="this.form.submit();">'.
 4278:                         &mt('Community').
 4279:                         '</label>'.
 4280:                         '</fieldset>'.
 4281:                         '<input type="hidden" name="customroleaction" value="'.
 4282:                         $action.'" />';
 4283:         if ($env{'form.customroleaction'} eq 'new') {
 4284:             $context_code .= '<input type="hidden" name="newrolename" value="'.
 4285:                              $rolename.'" />';
 4286:         } else {
 4287:             $context_code .= '<input type="hidden" name="rolename" value="'.
 4288:                              $rolename.'" />';
 4289:         }
 4290:         $context_code .= '<input type="hidden" name="action" value="custom" />'.
 4291:                          '<input type="hidden" name="phase" value="selected_custom_edit" />';
 4292:     }
 4293: 
 4294:     $head_script .= "\n".$jsback."\n"
 4295:                    .'// ]]>'."\n"
 4296:                    .'</script>'."\n";
 4297:     push (@{$brcrum},
 4298:               {href => "javascript:backPage(document.form1,'pickrole','')",
 4299:                text => "Pick custom role",
 4300:                faq  => 282,bug=>'Instructor Interface',},
 4301:               {href => "javascript:backPage(document.form1,'','')",
 4302:                text => "Edit custom role",
 4303:                faq  => 282,
 4304:                bug  => 'Instructor Interface',
 4305:                help => 'Course_Editing_Custom_Roles'}
 4306:               );
 4307:     my $args = { bread_crumbs          => $brcrum,
 4308:                  bread_crumbs_component => 'User Management'};
 4309:  
 4310:     $r->print(&Apache::loncommon::start_page('Custom Role Editor',
 4311:                                              $head_script,$args).
 4312:               $body_top);
 4313:     my %lt=&Apache::lonlocal::texthash(
 4314: 		    'prv'  => "Privilege",
 4315: 		    'crl'  => "Course Level",
 4316:                     'dml'  => "Domain Level",
 4317:                     'ssl'  => "System Level");
 4318: 
 4319:     $r->print('<div class="LC_left_float">'
 4320:              .'<form action=""><fieldset>'
 4321:              .'<legend>'.&mt('Select a Template').'</legend>'
 4322:              .$button_code
 4323:              .'</fieldset></form></div>');
 4324:     if ($context_code) {
 4325:         $r->print('<div class="LC_left_float">'
 4326:                  .'<form action="/adm/createuser" method="post"><fieldset>'
 4327:                  .'<legend>'.&mt('Context').'</legend>'
 4328:                  .$context_code
 4329:                  .'</form>'
 4330:                  .'</div>'
 4331:         );
 4332:     }
 4333:     $r->print('<br clear="all" />');
 4334: 
 4335:     $r->print(<<ENDCCF);
 4336: <form name="form1" method="post" action="">
 4337: <input type="hidden" name="phase" value="set_custom_roles" />
 4338: <input type="hidden" name="rolename" value="$rolename" />
 4339: ENDCCF
 4340:     $r->print(&Apache::loncommon::start_data_table().
 4341:               &Apache::loncommon::start_data_table_header_row(). 
 4342: '<th>'.$lt{'prv'}.'</th><th>'.$lt{'crl'}.'</th><th>'.$lt{'dml'}.
 4343: '</th><th>'.$lt{'ssl'}.'</th>'.
 4344:               &Apache::loncommon::end_data_table_header_row());
 4345:     foreach my $priv (sort(keys(%full))) {
 4346:         my $privtext = &Apache::lonnet::plaintext($priv,$crstype);
 4347:         $r->print(&Apache::loncommon::start_data_table_row().
 4348: 	          '<td>'.$privtext.'</td><td>'.
 4349:     ($courselevel{$priv}?'<input type="checkbox" name="'.$priv.'_c"'.
 4350:     ($courselevelcurrent{$priv}?' checked="checked"':'').' />':'&nbsp;').
 4351:     '</td><td>'.
 4352:     ($domainlevel{$priv}?'<input type="checkbox" name="'.$priv.'_d"'.
 4353:     ($domainlevelcurrent{$priv}?' checked="checked"':'').' />':'&nbsp;').
 4354:     '</td><td>');
 4355:         if ($priv eq 'bre' && $crstype eq 'Community') {
 4356:             $r->print('&nbsp;');  
 4357:         } else {
 4358:             $r->print($systemlevel{$priv}?'<input type="checkbox" name="'.$priv.'_s"'.
 4359:                       ($systemlevelcurrent{$priv}?' checked="checked"':'').' />':'&nbsp;');
 4360:         }
 4361:         $r->print('</td>'.
 4362:                   &Apache::loncommon::end_data_table_row());
 4363:     }
 4364:     $r->print(&Apache::loncommon::end_data_table().
 4365:    '<input type="hidden" name="action" value="'.$env{'form.action'}.'" />'.
 4366:    '<input type="hidden" name="startrolename" value="'.$env{'form.rolename'}.
 4367:    '" />'."\n".'<input type="hidden" name="currstate" value="" />'."\n".   
 4368:    '<input type="reset" value="'.&mt("Reset").'" />'."\n".
 4369:    '<input type="submit" value="'.&mt('Save').'" /></form>');
 4370: }
 4371: # --------------------------------------------------------
 4372: sub make_script_template {
 4373:     my ($role,$crstype) = @_;
 4374:     my %full_c=();
 4375:     my %full_d=();
 4376:     my %full_s=();
 4377:     my $return_script;
 4378:     foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
 4379:         my ($priv,$restrict)=split(/\&/,$item);
 4380:         $full_c{$priv}=1;
 4381:     }
 4382:     foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:d'})) {
 4383:         my ($priv,$restrict)=split(/\&/,$item);
 4384:         $full_d{$priv}=1;
 4385:     }
 4386:     foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:s'})) {
 4387:         next if (($crstype eq 'Community') && ($item eq 'bre&S'));
 4388:         my ($priv,$restrict)=split(/\&/,$item);
 4389:         $full_s{$priv}=1;
 4390:     }
 4391:     $return_script .= 'function set_'.$role.'() {'."\n";
 4392:     my @temp = split(/:/,$Apache::lonnet::pr{$role.':c'});
 4393:     my %role_c;
 4394:     foreach my $priv (@temp) {
 4395:         my ($priv_item, $dummy) = split(/\&/,$priv);
 4396:         $role_c{$priv_item} = 1;
 4397:     }
 4398:     my %role_d;
 4399:     @temp = split(/:/,$Apache::lonnet::pr{$role.':d'});
 4400:     foreach my $priv(@temp) {
 4401:         my ($priv_item, $dummy) = split(/\&/,$priv);
 4402:         $role_d{$priv_item} = 1;
 4403:     }
 4404:     my %role_s;
 4405:     @temp = split(/:/,$Apache::lonnet::pr{$role.':s'});
 4406:     foreach my $priv(@temp) {
 4407:         my ($priv_item, $dummy) = split(/\&/,$priv);
 4408:         $role_s{$priv_item} = 1;
 4409:     }
 4410:     foreach my $priv_item (keys(%full_c)) {
 4411:         my ($priv, $dummy) = split(/\&/,$priv_item);
 4412:         if ((exists($role_c{$priv})) || (exists($role_d{$priv})) || 
 4413:             (exists($role_s{$priv}))) {
 4414:             $return_script .= "document.form1.$priv"."_c.checked = true;\n";
 4415:         } else {
 4416:             $return_script .= "document.form1.$priv"."_c.checked = false;\n";
 4417:         }
 4418:     }
 4419:     foreach my $priv_item (keys(%full_d)) {
 4420:         my ($priv, $dummy) = split(/\&/,$priv_item);
 4421:         if ((exists($role_d{$priv})) || (exists($role_s{$priv}))) {
 4422:             $return_script .= "document.form1.$priv"."_d.checked = true;\n";
 4423:         } else {
 4424:             $return_script .= "document.form1.$priv"."_d.checked = false;\n";
 4425:         }
 4426:     }
 4427:     foreach my $priv_item (keys(%full_s)) {
 4428:         my ($priv, $dummy) = split(/\&/,$priv_item);
 4429:         if (exists($role_s{$priv})) {
 4430:             $return_script .= "document.form1.$priv"."_s.checked = true;\n";
 4431:         } else {
 4432:             $return_script .= "document.form1.$priv"."_s.checked = false;\n";
 4433:         }
 4434:     }
 4435:     $return_script .= '}'."\n";
 4436:     return ($return_script);
 4437: }
 4438: # ----------------------------------------------------------
 4439: sub make_button_code {
 4440:     my ($role,$crstype) = @_;
 4441:     my $label = &Apache::lonnet::plaintext($role,$crstype);
 4442:     my $button_code = '<input type="button" onclick="set_'.$role.'()" value="'.$label.'" />';
 4443:     return ($button_code);
 4444: }
 4445: # ---------------------------------------------------------- Call to definerole
 4446: sub set_custom_role {
 4447:     my ($r,$context,$brcrum) = @_;
 4448:     my $rolename=$env{'form.rolename'};
 4449:     $rolename=~s/[^A-Za-z0-9]//gs;
 4450:     if (!$rolename) {
 4451: 	&custom_role_editor($r,$brcrum);
 4452:         return;
 4453:     }
 4454:     my ($jsback,$elements) = &crumb_utilities();
 4455:     my $jscript = '<script type="text/javascript">'
 4456:                  .'// <![CDATA['."\n"
 4457:                  .$jsback."\n"
 4458:                  .'// ]]>'."\n"
 4459:                  .'</script>'."\n";
 4460:     push(@{$brcrum},
 4461:         {href => "javascript:backPage(document.customresult,'pickrole','')",
 4462:          text => "Pick custom role",
 4463:          faq  => 282,
 4464:          bug  => 'Instructor Interface',},
 4465:         {href => "javascript:backPage(document.customresult,'selected_custom_edit','')",
 4466:          text => "Edit custom role",
 4467:          faq  => 282,
 4468:          bug  => 'Instructor Interface',},
 4469:         {href => "javascript:backPage(document.customresult,'set_custom_roles','')",
 4470:          text => "Result",
 4471:          faq  => 282,
 4472:          bug  => 'Instructor Interface',
 4473:          help => 'Course_Editing_Custom_Roles'},
 4474:         );
 4475:     my $args = { bread_crumbs           => $brcrum,
 4476:                  bread_crumbs_component => 'User Management'}; 
 4477:     $r->print(&Apache::loncommon::start_page('Save Custom Role',$jscript,$args));
 4478: 
 4479:     my $newrole;
 4480:     my ($rdummy,$roledef)=
 4481: 	&Apache::lonnet::get('roles',["rolesdef_$rolename"]);
 4482: 
 4483: # ------------------------------------------------------- Does this role exist?
 4484:     $r->print('<h3>');
 4485:     if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 4486: 	$r->print(&mt('Existing Role').' "');
 4487:     } else {
 4488: 	$r->print(&mt('New Role').' "');
 4489: 	$roledef='';
 4490:         $newrole = 1;
 4491:     }
 4492:     $r->print($rolename.'"</h3>');
 4493: # ------------------------------------------------------- What can be assigned?
 4494:     my $sysrole='';
 4495:     my $domrole='';
 4496:     my $courole='';
 4497: 
 4498:     foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
 4499: 	my ($priv,$restrict)=split(/\&/,$item);
 4500:         if (!$restrict) { $restrict=''; }
 4501:         if ($env{'form.'.$priv.'_c'}) {
 4502: 	    $courole.=':'.$item;
 4503: 	}
 4504:     }
 4505: 
 4506:     foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:d'})) {
 4507: 	my ($priv,$restrict)=split(/\&/,$item);
 4508:         if (!$restrict) { $restrict=''; }
 4509:         if ($env{'form.'.$priv.'_d'}) {
 4510: 	    $domrole.=':'.$item;
 4511: 	}
 4512:     }
 4513: 
 4514:     foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:s'})) {
 4515: 	my ($priv,$restrict)=split(/\&/,$item);
 4516:         if (!$restrict) { $restrict=''; }
 4517:         if ($env{'form.'.$priv.'_s'}) {
 4518: 	    $sysrole.=':'.$item;
 4519: 	}
 4520:     }
 4521:     # Assign role; Compile and show result
 4522:     my $errmsg;
 4523:     my $result =
 4524:         &Apache::lonnet::definerole($rolename,$sysrole,$domrole,$courole);
 4525:     if ($result ne 'ok') {
 4526:         $errmsg = ': '.$result;
 4527:     }
 4528:     my $message =
 4529:         &Apache::lonhtmlcommon::confirm_success(
 4530:             &mt('Defining Role').$errmsg, ($result eq 'ok' ? 0 : 1));
 4531:     if ($env{'request.course.id'}) {
 4532:         my $url='/'.$env{'request.course.id'};
 4533:         $url=~s/\_/\//g;
 4534:         $result =
 4535:             &Apache::lonnet::assigncustomrole(
 4536:                 $env{'user.domain'},$env{'user.name'},
 4537:                 $url,
 4538:                 $env{'user.domain'},$env{'user.name'},
 4539:                 $rolename,undef,undef,undef,$context);
 4540:         if ($result ne 'ok') {
 4541:             $errmsg = ': '.$result;
 4542:         }
 4543:         $message .=
 4544:             '<br />'
 4545:            .&Apache::lonhtmlcommon::confirm_success(
 4546:                 &mt('Assigning Role to Self').$errmsg, ($result eq 'ok' ? 0 : 1));
 4547:     }
 4548:     $r->print(
 4549:         &Apache::loncommon::confirmwrapper($message)
 4550:        .'<br />'
 4551:        .&Apache::lonhtmlcommon::actionbox([
 4552:             '<a href="javascript:backPage(document.customresult,'."'pickrole'".')">'
 4553:            .&mt('Create or edit another custom role')
 4554:            .'</a>'])
 4555:        .'<form name="customresult" method="post" action="">'
 4556:        .&Apache::lonhtmlcommon::echo_form_input([])
 4557:        .'</form>'
 4558:     );
 4559: }
 4560: 
 4561: # ================================================================ Main Handler
 4562: sub handler {
 4563:     my $r = shift;
 4564:     if ($r->header_only) {
 4565:        &Apache::loncommon::content_type($r,'text/html');
 4566:        $r->send_http_header;
 4567:        return OK;
 4568:     }
 4569:     my ($context,$crstype);
 4570:     if ($env{'request.course.id'}) {
 4571:         $context = 'course';
 4572:         $crstype = &Apache::loncommon::course_type();
 4573:     } elsif ($env{'request.role'} =~ /^au\./) {
 4574:         $context = 'author';
 4575:     } else {
 4576:         $context = 'domain';
 4577:     }
 4578: 
 4579:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 4580:         ['action','state','callingform','roletype','showrole','bulkaction','popup','phase',
 4581:          'username','domain','srchterm','srchdomain','srchin','srchby','srchtype','queue']);
 4582:     &Apache::lonhtmlcommon::clear_breadcrumbs();
 4583:     my $args;
 4584:     my $brcrum = [];
 4585:     my $bread_crumbs_component = 'User Management';
 4586:     if (($env{'form.action'} ne 'dateselect') && ($env{'form.action'} ne 'displayuserreq')) {
 4587:         $brcrum = [{href=>"/adm/createuser",
 4588:                     text=>"User Management",
 4589:                     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'}
 4590:                   ];
 4591:     }
 4592:     #SD Following files not added to help, because the corresponding .tex-files seem to
 4593:     #be missing: Course_Approve_Selfenroll,Course_User_Logs,
 4594:     my ($permission,$allowed) = 
 4595:         &Apache::lonuserutils::get_permission($context,$crstype);
 4596:     if (!$allowed) {
 4597:         if ($context eq 'course') {
 4598:             $r->internal_redirect('/adm/viewclasslist');
 4599:             return OK;
 4600:         }
 4601:         $env{'user.error.msg'}=
 4602:             "/adm/createuser:cst:0:0:Cannot create/modify user data ".
 4603:                                  "or view user status.";
 4604:         return HTTP_NOT_ACCEPTABLE;
 4605:     }
 4606: 
 4607:     &Apache::loncommon::content_type($r,'text/html');
 4608:     $r->send_http_header;
 4609: 
 4610:     my $showcredits;
 4611:     if ((($context eq 'course') && ($crstype eq 'Course')) || 
 4612:          ($context eq 'domain')) {
 4613:         my %domdefaults = 
 4614:             &Apache::lonnet::get_domain_defaults($env{'request.role.domain'});
 4615:         if ($domdefaults{'officialcredits'} || $domdefaults{'unofficialcredits'}) {
 4616:             $showcredits = 1;
 4617:         }
 4618:     }
 4619: 
 4620:     # Main switch on form.action and form.state, as appropriate
 4621:     if (! exists($env{'form.action'})) {
 4622:         $args = {bread_crumbs => $brcrum,
 4623:                  bread_crumbs_component => $bread_crumbs_component}; 
 4624:         $r->print(&header(undef,$args));
 4625:         $r->print(&print_main_menu($permission,$context,$crstype));
 4626:     } elsif ($env{'form.action'} eq 'upload' && $permission->{'cusr'}) {
 4627:         push(@{$brcrum},
 4628:               { href => '/adm/createuser?action=upload&state=',
 4629:                 text => 'Upload Users List',
 4630:                 help => 'Course_Create_Class_List',
 4631:               });
 4632:         $bread_crumbs_component = 'Upload Users List';
 4633:         $args = {bread_crumbs           => $brcrum,
 4634:                  bread_crumbs_component => $bread_crumbs_component};
 4635:         $r->print(&header(undef,$args));
 4636:         $r->print('<form name="studentform" method="post" '.
 4637:                   'enctype="multipart/form-data" '.
 4638:                   ' action="/adm/createuser">'."\n");
 4639:         if (! exists($env{'form.state'})) {
 4640:             &Apache::lonuserutils::print_first_users_upload_form($r,$context);
 4641:         } elsif ($env{'form.state'} eq 'got_file') {
 4642:             &Apache::lonuserutils::print_upload_manager_form($r,$context,$permission,
 4643:                                                              $crstype,$showcredits);
 4644:         } elsif ($env{'form.state'} eq 'enrolling') {
 4645:             if ($env{'form.datatoken'}) {
 4646:                 &Apache::lonuserutils::upfile_drop_add($r,$context,$permission,
 4647:                                                        $showcredits);
 4648:             }
 4649:         } else {
 4650:             &Apache::lonuserutils::print_first_users_upload_form($r,$context);
 4651:         }
 4652:     } elsif ((($env{'form.action'} eq 'singleuser') || ($env{'form.action'}
 4653:              eq 'singlestudent')) && ($permission->{'cusr'})) {
 4654:         my $phase = $env{'form.phase'};
 4655:         my @search = ('srchterm','srchby','srchin','srchtype','srchdomain');
 4656: 	&Apache::loncreateuser::restore_prev_selections();
 4657: 	my $srch;
 4658: 	foreach my $item (@search) {
 4659: 	    $srch->{$item} = $env{'form.'.$item};
 4660: 	}
 4661:         if (($phase eq 'get_user_info') || ($phase eq 'userpicked') ||
 4662:             ($phase eq 'createnewuser')) {
 4663:             if ($env{'form.phase'} eq 'createnewuser') {
 4664:                 my $response;
 4665:                 if ($env{'form.srchterm'} !~ /^$match_username$/) {
 4666:                     my $response =
 4667:                         '<span class="LC_warning">'
 4668:                        .&mt('You must specify a valid username. Only the following are allowed:'
 4669:                            .' letters numbers - . @')
 4670:                        .'</span>';
 4671:                     $env{'form.phase'} = '';
 4672:                     &print_username_entry_form($r,$context,$response,$srch,undef,
 4673:                                                $crstype,$brcrum,$showcredits);
 4674:                 } else {
 4675:                     my $ccuname =&LONCAPA::clean_username($srch->{'srchterm'});
 4676:                     my $ccdomain=&LONCAPA::clean_domain($srch->{'srchdomain'});
 4677:                     &print_user_modification_page($r,$ccuname,$ccdomain,
 4678:                                                   $srch,$response,$context,
 4679:                                                   $permission,$crstype,$brcrum,
 4680:                                                   $showcredits);
 4681:                 }
 4682:             } elsif ($env{'form.phase'} eq 'get_user_info') {
 4683:                 my ($currstate,$response,$forcenewuser,$results) = 
 4684:                     &user_search_result($context,$srch);
 4685:                 if ($env{'form.currstate'} eq 'modify') {
 4686:                     $currstate = $env{'form.currstate'};
 4687:                 }
 4688:                 if ($currstate eq 'select') {
 4689:                     &print_user_selection_page($r,$response,$srch,$results,
 4690:                                                \@search,$context,undef,$crstype,
 4691:                                                $brcrum);
 4692:                 } elsif ($currstate eq 'modify') {
 4693:                     my ($ccuname,$ccdomain);
 4694:                     if (($srch->{'srchby'} eq 'uname') && 
 4695:                         ($srch->{'srchtype'} eq 'exact')) {
 4696:                         $ccuname = $srch->{'srchterm'};
 4697:                         $ccdomain= $srch->{'srchdomain'};
 4698:                     } else {
 4699:                         my @matchedunames = keys(%{$results});
 4700:                         ($ccuname,$ccdomain) = split(/:/,$matchedunames[0]);
 4701:                     }
 4702:                     $ccuname =&LONCAPA::clean_username($ccuname);
 4703:                     $ccdomain=&LONCAPA::clean_domain($ccdomain);
 4704:                     if ($env{'form.forcenewuser'}) {
 4705:                         $response = '';
 4706:                     }
 4707:                     &print_user_modification_page($r,$ccuname,$ccdomain,
 4708:                                                   $srch,$response,$context,
 4709:                                                   $permission,$crstype,$brcrum);
 4710:                 } elsif ($currstate eq 'query') {
 4711:                     &print_user_query_page($r,'createuser',$brcrum);
 4712:                 } else {
 4713:                     $env{'form.phase'} = '';
 4714:                     &print_username_entry_form($r,$context,$response,$srch,
 4715:                                                $forcenewuser,$crstype,$brcrum);
 4716:                 }
 4717:             } elsif ($env{'form.phase'} eq 'userpicked') {
 4718:                 my $ccuname = &LONCAPA::clean_username($env{'form.seluname'});
 4719:                 my $ccdomain = &LONCAPA::clean_domain($env{'form.seludom'});
 4720:                 &print_user_modification_page($r,$ccuname,$ccdomain,$srch,'',
 4721:                                               $context,$permission,$crstype,
 4722:                                               $brcrum);
 4723:             }
 4724:         } elsif ($env{'form.phase'} eq 'update_user_data') {
 4725:             &update_user_data($r,$context,$crstype,$brcrum,$showcredits);
 4726:         } else {
 4727:             &print_username_entry_form($r,$context,undef,$srch,undef,$crstype,
 4728:                                        $brcrum);
 4729:         }
 4730:     } elsif ($env{'form.action'} eq 'custom' && $permission->{'custom'}) {
 4731:         if ($env{'form.phase'} eq 'set_custom_roles') {
 4732:             &set_custom_role($r,$context,$brcrum);
 4733:         } else {
 4734:             &custom_role_editor($r,$brcrum);
 4735:         }
 4736:     } elsif (($env{'form.action'} eq 'processauthorreq') &&
 4737:              ($permission->{'cusr'}) && 
 4738:              (&Apache::lonnet::allowed('cau',$env{'request.role.domain'}))) {
 4739:         push(@{$brcrum},
 4740:                  {href => '/adm/createuser?action=processauthorreq',
 4741:                   text => 'Authoring Space requests',
 4742:                   help => 'Domain_Role_Approvals'});
 4743:         $bread_crumbs_component = 'Authoring requests';
 4744:         if ($env{'form.state'} eq 'done') {
 4745:             push(@{$brcrum},
 4746:                      {href => '/adm/createuser?action=authorreqqueue',
 4747:                       text => 'Result',
 4748:                       help => 'Domain_Role_Approvals'});
 4749:             $bread_crumbs_component = 'Authoring request result';
 4750:         }
 4751:         $args = { bread_crumbs           => $brcrum,
 4752:                   bread_crumbs_component => $bread_crumbs_component};
 4753:         my $js = &usernamerequest_javascript();
 4754:         $r->print(&header(&add_script($js),$args));
 4755:         if (!exists($env{'form.state'})) {
 4756:             $r->print(&Apache::loncoursequeueadmin::display_queued_requests('requestauthor',
 4757:                                                                             $env{'request.role.domain'}));
 4758:         } elsif ($env{'form.state'} eq 'done') {
 4759:             $r->print('<h3>'.&mt('Authoring request processing').'</h3>'."\n");
 4760:             $r->print(&Apache::loncoursequeueadmin::update_request_queue('requestauthor',
 4761:                                                                          $env{'request.role.domain'}));
 4762:         }
 4763:     } elsif (($env{'form.action'} eq 'processusernamereq') &&
 4764:              ($permission->{'cusr'}) &&
 4765:              (&Apache::lonnet::allowed('cau',$env{'request.role.domain'}))) {
 4766:         push(@{$brcrum},
 4767:                  {href => '/adm/createuser?action=processusernamereq',
 4768:                   text => 'LON-CAPA account requests',
 4769:                   help => 'Domain_Username_Approvals'});
 4770:         $bread_crumbs_component = 'Account requests';
 4771:         if ($env{'form.state'} eq 'done') {
 4772:             push(@{$brcrum},
 4773:                      {href => '/adm/createuser?action=usernamereqqueue',
 4774:                       text => 'Result',
 4775:                       help => 'Domain_Username_Approvals'});
 4776:             $bread_crumbs_component = 'LON-CAPA account request result';
 4777:         }
 4778:         $args = { bread_crumbs           => $brcrum,
 4779:                   bread_crumbs_component => $bread_crumbs_component};
 4780:         my $js = &usernamerequest_javascript();
 4781:         $r->print(&header(&add_script($js),$args));
 4782:         if (!exists($env{'form.state'})) {
 4783:             $r->print(&Apache::loncoursequeueadmin::display_queued_requests('requestusername',
 4784:                                                                             $env{'request.role.domain'}));
 4785:         } elsif ($env{'form.state'} eq 'done') {
 4786:             $r->print('<h3>'.&mt('LON-CAPA account request processing').'</h3>'."\n");
 4787:             $r->print(&Apache::loncoursequeueadmin::update_request_queue('requestusername',
 4788:                                                                          $env{'request.role.domain'}));
 4789:         }
 4790:     } elsif (($env{'form.action'} eq 'displayuserreq') &&
 4791:              ($permission->{'cusr'})) {
 4792:         my $dom = $env{'form.domain'};
 4793:         my $uname = $env{'form.username'};
 4794:         my $warning;
 4795:         if (($dom =~ /^$match_domain$/) && (&Apache::lonnet::domain($dom) ne '')) {
 4796:             if (($dom eq $env{'request.role.domain'}) && (&Apache::lonnet::allowed('ccc',$dom))) {
 4797:                 if (($uname =~ /^$match_username$/) && ($env{'form.queue'} eq 'approval')) {
 4798:                     my $uhome = &Apache::lonnet::homeserver($uname,$dom);
 4799:                     if ($uhome eq 'no_host') {
 4800:                         my $queue = $env{'form.queue'};
 4801:                         my $reqkey = &escape($uname).'_'.$queue; 
 4802:                         my $namespace = 'usernamequeue';
 4803:                         my $domconfig = &Apache::lonnet::get_domainconfiguser($dom);
 4804:                         my %queued =
 4805:                             &Apache::lonnet::get($namespace,[$reqkey],$dom,$domconfig);
 4806:                         unless ($queued{$reqkey}) {
 4807:                             $warning = &mt('No information was found for this LON-CAPA account request.');
 4808:                         }
 4809:                     } else {
 4810:                         $warning = &mt('A LON-CAPA account already exists for the requested username and domain.');
 4811:                     }
 4812:                 } else {
 4813:                     $warning = &mt('LON-CAPA account request status check is for an invalid username.');
 4814:                 }
 4815:             } else {
 4816:                 $warning = &mt('You do not have rights to view LON-CAPA account requests in the domain specified.');
 4817:             }
 4818:         } else {
 4819:             $warning = &mt('LON-CAPA account request status check is for an invalid domain.');
 4820:         }
 4821:         my $args = { only_body => 1 };
 4822:         $r->print(&header(undef,$args).
 4823:                   '<h3>'.&mt('LON-CAPA Account Request Details').'</h3>');
 4824:         if ($warning ne '') {
 4825:             $r->print('<div class="LC_warning">'.$warning.'</div>');
 4826:         } else {
 4827:             my ($infofields,$infotitles) = &Apache::loncommon::emailusername_info();
 4828:             my $domconfiguser = &Apache::lonnet::get_domainconfiguser($dom);
 4829:             my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 4830:             if (ref($domconfig{'usercreation'}) eq 'HASH') {
 4831:                 if (ref($domconfig{'usercreation'}{'cancreate'}) eq 'HASH') {
 4832:                     if (ref($domconfig{'usercreation'}{'cancreate'}{'emailusername'}) eq 'HASH') {
 4833:                         my %info =
 4834:                             &Apache::lonnet::get('nohist_requestedusernames',[$uname],$dom,$domconfiguser);
 4835:                         if (ref($info{$uname}) eq 'HASH') {
 4836:                             my $usertype = $info{$uname}{'inststatus'};
 4837:                             unless ($usertype) {
 4838:                                 $usertype = 'default';
 4839:                             }
 4840:                             if (ref($domconfig{'usercreation'}{'cancreate'}{'emailusername'}{$usertype}) eq 'HASH') {
 4841:                                 if ((ref($infofields) eq 'ARRAY') && (ref($infotitles) eq 'HASH')) {
 4842:                                     $r->print('<div>'.&Apache::lonhtmlcommon::start_pick_box());
 4843:                                     my ($num,$count,$showstatus);
 4844:                                     $count = scalar(keys(%{$domconfig{'usercreation'}{'cancreate'}{'emailusername'}{$usertype}}));
 4845:                                     unless ($usertype eq 'default') {
 4846:                                         my ($othertitle,$usertypes,$types) = 
 4847:                                             &Apache::loncommon::sorted_inst_types($dom);
 4848:                                         if (ref($usertypes) eq 'HASH') {
 4849:                                             if ($usertypes->{$usertype}) {
 4850:                                                 $showstatus = $usertypes->{$usertype};
 4851:                                                 $count ++;
 4852:                                             }
 4853:                                         }
 4854:                                     }
 4855:                                     foreach my $field (@{$infofields}) {
 4856:                                         next unless ($domconfig{'usercreation'}{'cancreate'}{'emailusername'}{$usertype}{$field});
 4857:                                         next unless ($infotitles->{$field});
 4858:                                         $r->print(&Apache::lonhtmlcommon::row_title($infotitles->{$field}).
 4859:                                                   $info{$uname}{$field});
 4860:                                         $num ++;
 4861:                                         if ($count == $num) {
 4862:                                             $r->print(&Apache::lonhtmlcommon::row_closure(1));
 4863:                                         } else {
 4864:                                             $r->print(&Apache::lonhtmlcommon::row_closure());
 4865:                                         }
 4866:                                     }
 4867:                                     if ($showstatus) {
 4868:                                         $r->print(&Apache::lonhtmlcommon::row_title(&mt('Status type (self-reported)')).
 4869:                                                   $showstatus.
 4870:                                                   &Apache::lonhtmlcommon::row_closure(1));
 4871:                                     }
 4872:                                     $r->print(&Apache::lonhtmlcommon::end_pick_box().'</div>');
 4873:                                 }
 4874:                             }
 4875:                         }
 4876:                     }
 4877:                 }
 4878:             }
 4879:             $r->print(&close_popup_form());
 4880:         }
 4881:     } elsif (($env{'form.action'} eq 'listusers') && 
 4882:              ($permission->{'view'} || $permission->{'cusr'})) {
 4883:         if ($env{'form.phase'} eq 'bulkchange') {
 4884:             push(@{$brcrum},
 4885:                     {href => '/adm/createuser?action=listusers',
 4886:                      text => "List Users"},
 4887:                     {href => "/adm/createuser",
 4888:                      text => "Result",
 4889:                      help => 'Course_View_Class_List'});
 4890:             $bread_crumbs_component = 'Update Users';
 4891:             $args = {bread_crumbs           => $brcrum,
 4892:                      bread_crumbs_component => $bread_crumbs_component};
 4893:             $r->print(&header(undef,$args));
 4894:             my $setting = $env{'form.roletype'};
 4895:             my $choice = $env{'form.bulkaction'};
 4896:             if ($permission->{'cusr'}) {
 4897:                 &Apache::lonuserutils::update_user_list($r,$context,$setting,$choice,$crstype);
 4898:             } else {
 4899:                 $r->print(&mt('You are not authorized to make bulk changes to user roles'));
 4900:                 $r->print('<p><a href="/adm/createuser?action=listusers">'.&mt('Display User Lists').'</a>');
 4901:             }
 4902:         } else {
 4903:             push(@{$brcrum},
 4904:                     {href => '/adm/createuser?action=listusers',
 4905:                      text => "List Users",
 4906:                      help => 'Course_View_Class_List'});
 4907:             $bread_crumbs_component = 'List Users';
 4908:             $args = {bread_crumbs           => $brcrum,
 4909:                      bread_crumbs_component => $bread_crumbs_component};
 4910:             my ($cb_jscript,$jscript,$totcodes,$codetitles,$idlist,$idlist_titles);
 4911:             my $formname = 'studentform';
 4912:             my $hidecall = "hide_searching();";
 4913:             if (($context eq 'domain') && (($env{'form.roletype'} eq 'course') ||
 4914:                 ($env{'form.roletype'} eq 'community'))) {
 4915:                 if ($env{'form.roletype'} eq 'course') {
 4916:                     ($cb_jscript,$jscript,$totcodes,$codetitles,$idlist,$idlist_titles) = 
 4917:                         &Apache::lonuserutils::courses_selector($env{'request.role.domain'},
 4918:                                                                 $formname);
 4919:                 } elsif ($env{'form.roletype'} eq 'community') {
 4920:                     $cb_jscript = 
 4921:                         &Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'});
 4922:                     my %elements = (
 4923:                                       coursepick => 'radio',
 4924:                                       coursetotal => 'text',
 4925:                                       courselist => 'text',
 4926:                                    );
 4927:                     $jscript = &Apache::lonhtmlcommon::set_form_elements(\%elements);
 4928:                 }
 4929:                 $jscript .= &verify_user_display($context)."\n".
 4930:                             &Apache::loncommon::check_uncheck_jscript();
 4931:                 my $js = &add_script($jscript).$cb_jscript;
 4932:                 my $loadcode = 
 4933:                     &Apache::lonuserutils::course_selector_loadcode($formname);
 4934:                 if ($loadcode ne '') {
 4935:                     $args->{add_entries} = {onload => "$loadcode;$hidecall"};
 4936:                 } else {
 4937:                     $args->{add_entries} = {onload => $hidecall};
 4938:                 }
 4939:                 $r->print(&header($js,$args));
 4940:             } else {
 4941:                 $args->{add_entries} = {onload => $hidecall};
 4942:                 $jscript = &verify_user_display($context).
 4943:                            &Apache::loncommon::check_uncheck_jscript(); 
 4944:                 $r->print(&header(&add_script($jscript),$args));
 4945:             }
 4946:             &Apache::lonuserutils::print_userlist($r,undef,$permission,$context,
 4947:                          $formname,$totcodes,$codetitles,$idlist,$idlist_titles,
 4948:                          $showcredits);
 4949:         }
 4950:     } elsif ($env{'form.action'} eq 'drop' && $permission->{'cusr'}) {
 4951:         my $brtext;
 4952:         if ($crstype eq 'Community') {
 4953:             $brtext = 'Drop Members';
 4954:         } else {
 4955:             $brtext = 'Drop Students';
 4956:         }
 4957:         push(@{$brcrum},
 4958:                 {href => '/adm/createuser?action=drop',
 4959:                  text => $brtext,
 4960:                  help => 'Course_Drop_Student'});
 4961:         if ($env{'form.state'} eq 'done') {
 4962:             push(@{$brcrum},
 4963:                      {href=>'/adm/createuser?action=drop',
 4964:                       text=>"Result"});
 4965:         }
 4966:         $bread_crumbs_component = $brtext;
 4967:         $args = {bread_crumbs           => $brcrum,
 4968:                  bread_crumbs_component => $bread_crumbs_component}; 
 4969:         $r->print(&header(undef,$args));
 4970:         if (!exists($env{'form.state'})) {
 4971:             &Apache::lonuserutils::print_drop_menu($r,$context,$permission,$crstype);
 4972:         } elsif ($env{'form.state'} eq 'done') {
 4973:             &Apache::lonuserutils::update_user_list($r,$context,undef,
 4974:                                                     $env{'form.action'});
 4975:         }
 4976:     } elsif ($env{'form.action'} eq 'dateselect') {
 4977:         if ($permission->{'cusr'}) {
 4978:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 4979:                       &Apache::lonuserutils::date_section_selector($context,$permission,
 4980:                                                                    $crstype,$showcredits));
 4981:         } else {
 4982:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 4983:                      '<span class="LC_error">'.&mt('You do not have permission to modify dates or sections for users').'</span>'); 
 4984:         }
 4985:     } elsif ($env{'form.action'} eq 'selfenroll') {
 4986:         if ($permission->{selfenrolladmin}) {
 4987:             my $cid = $env{'request.course.id'};
 4988:             my $cdom = $env{'course.'.$cid.'.domain'};
 4989:             my $cnum = $env{'course.'.$cid.'.num'};
 4990:             my %currsettings = (
 4991:                 selfenroll_types              => $env{'course.'.$cid.'.internal.selfenroll_types'},
 4992:                 selfenroll_registered         => $env{'course.'.$cid.'.internal.selfenroll_registered'},
 4993:                 selfenroll_section            => $env{'course.'.$cid.'.internal.selfenroll_section'},
 4994:                 selfenroll_notifylist         => $env{'course.'.$cid.'.internal.selfenroll_notifylist'},
 4995:                 selfenroll_approval           => $env{'course.'.$cid.'.internal.selfenroll_approval'},
 4996:                 selfenroll_limit              => $env{'course.'.$cid.'.internal.selfenroll_limit'},
 4997:                 selfenroll_cap                => $env{'course.'.$cid.'.internal.selfenroll_cap'},
 4998:                 selfenroll_start_date         => $env{'course.'.$cid.'.internal.selfenroll_start_date'},
 4999:                 selfenroll_end_date           => $env{'course.'.$cid.'.internal.selfenroll_end_date'},
 5000:                 selfenroll_start_access       => $env{'course.'.$cid.'.internal.selfenroll_start_access'},
 5001:                 selfenroll_end_access         => $env{'course.'.$cid.'.internal.selfenroll_end_access'},
 5002:                 default_enrollment_start_date => $env{'course.'.$cid.'.default_enrollment_start_date'},
 5003:                 default_enrollment_end_date   => $env{'course.'.$cid.'.default_enrollment_end_date'},
 5004:                 uniquecode                    => $env{'course.'.$cid.'.internal.uniquecode'},
 5005:             );
 5006:             push(@{$brcrum},
 5007:                     {href => '/adm/createuser?action=selfenroll',
 5008:                      text => "Configure Self-enrollment",
 5009:                      help => 'Course_Self_Enrollment'});
 5010:             if (!exists($env{'form.state'})) {
 5011:                 $args = { bread_crumbs           => $brcrum,
 5012:                           bread_crumbs_component => 'Configure Self-enrollment'};
 5013:                 $r->print(&header(undef,$args));
 5014:                 $r->print('<h3>'.&mt('Self-enrollment with a student role').'</h3>'."\n");
 5015:                 &print_selfenroll_menu($r,'course',$cid,$cdom,$cnum,\%currsettings);
 5016:             } elsif ($env{'form.state'} eq 'done') {
 5017:                 push (@{$brcrum},
 5018:                           {href=>'/adm/createuser?action=selfenroll',
 5019:                            text=>"Result"});
 5020:                 $args = { bread_crumbs           => $brcrum,
 5021:                           bread_crumbs_component => 'Self-enrollment result'};
 5022:                 $r->print(&header(undef,$args));
 5023:                 $r->print('<h3>'.&mt('Self-enrollment with a student role').'</h3>'."\n");
 5024:                 &update_selfenroll_config($r,$cid,$cdom,$cnum,$context,$crstype,\%currsettings);
 5025:             }
 5026:         } else {
 5027:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 5028:                      '<span class="LC_error">'.&mt('You do not have permission to configure self-enrollment').'</span>');
 5029:         }
 5030:     } elsif ($env{'form.action'} eq 'selfenrollqueue') {
 5031:         push(@{$brcrum},
 5032:                  {href => '/adm/createuser?action=selfenrollqueue',
 5033:                   text => 'Enrollment requests',
 5034:                   help => 'Course_Self_Enrollment'});
 5035:         $bread_crumbs_component = 'Enrollment requests';
 5036:         if ($env{'form.state'} eq 'done') {
 5037:             push(@{$brcrum},
 5038:                      {href => '/adm/createuser?action=selfenrollqueue',
 5039:                       text => 'Result',
 5040:                       help => 'Course_Self_Enrollment'});
 5041:             $bread_crumbs_component = 'Enrollment result';
 5042:         }
 5043:         $args = { bread_crumbs           => $brcrum,
 5044:                   bread_crumbs_component => $bread_crumbs_component};
 5045:         $r->print(&header(undef,$args));
 5046:         my $cid = $env{'request.course.id'};
 5047:         my $cdom = $env{'course.'.$cid.'.domain'};
 5048:         my $cnum = $env{'course.'.$cid.'.num'};
 5049:         my $coursedesc = $env{'course.'.$cid.'.description'};
 5050:         if (!exists($env{'form.state'})) {
 5051:             $r->print('<h3>'.&mt('Pending enrollment requests').'</h3>'."\n");
 5052:             $r->print(&Apache::loncoursequeueadmin::display_queued_requests($context,
 5053:                                                                        $cdom,$cnum));
 5054:         } elsif ($env{'form.state'} eq 'done') {
 5055:             $r->print('<h3>'.&mt('Enrollment request processing').'</h3>'."\n");
 5056:             $r->print(&Apache::loncoursequeueadmin::update_request_queue($context,
 5057:                           $cdom,$cnum,$coursedesc));
 5058:         }
 5059:     } elsif ($env{'form.action'} eq 'changelogs') {
 5060:         my $helpitem;
 5061:         if ($context eq 'course') {
 5062:             $helpitem = 'Course_User_Logs';
 5063:         }
 5064:         push (@{$brcrum},
 5065:                  {href => '/adm/createuser?action=changelogs',
 5066:                   text => 'User Management Logs',
 5067:                   help => $helpitem});
 5068:         $bread_crumbs_component = 'User Changes';
 5069:         $args = { bread_crumbs           => $brcrum,
 5070:                   bread_crumbs_component => $bread_crumbs_component};
 5071:         $r->print(&header(undef,$args));
 5072:         &print_userchangelogs_display($r,$context,$permission);
 5073:     } else {
 5074:         $bread_crumbs_component = 'User Management';
 5075:         $args = { bread_crumbs           => $brcrum,
 5076:                   bread_crumbs_component => $bread_crumbs_component};
 5077:         $r->print(&header(undef,$args));
 5078:         $r->print(&print_main_menu($permission,$context,$crstype));
 5079:     }
 5080:     $r->print(&Apache::loncommon::end_page());
 5081:     return OK;
 5082: }
 5083: 
 5084: sub header {
 5085:     my ($jscript,$args) = @_;
 5086:     my $start_page;
 5087:     if (ref($args) eq 'HASH') {
 5088:         $start_page=&Apache::loncommon::start_page('User Management',$jscript,$args);
 5089:     } else {
 5090:         $start_page=&Apache::loncommon::start_page('User Management',$jscript);
 5091:     }
 5092:     return $start_page;
 5093: }
 5094: 
 5095: sub add_script {
 5096:     my ($js) = @_;
 5097:     return '<script type="text/javascript">'."\n"
 5098:           .'// <![CDATA['."\n"
 5099:           .$js."\n"
 5100:           .'// ]]>'."\n"
 5101:           .'</script>'."\n";
 5102: }
 5103: 
 5104: sub usernamerequest_javascript {
 5105:     my $js = <<ENDJS;
 5106: 
 5107: function openusernamereqdisplay(dom,uname,queue) {
 5108:     var url = '/adm/createuser?action=displayuserreq';
 5109:     url += '&domain='+dom+'&username='+uname+'&queue='+queue;
 5110:     var title = 'Account_Request_Browser';
 5111:     var options = 'scrollbars=1,resizable=1,menubar=0';
 5112:     options += ',width=700,height=600';
 5113:     var stdeditbrowser = open(url,title,options,'1');
 5114:     stdeditbrowser.focus();
 5115:     return;
 5116: }
 5117:  
 5118: ENDJS
 5119: }
 5120: 
 5121: sub close_popup_form {
 5122:     my $close= &mt('Close Window');
 5123:     return << "END";
 5124: <p><form name="displayreq" action="" method="post">
 5125: <input type="button" name="closeme" value="$close" onclick="javascript:self.close();" />
 5126: </form></p>
 5127: END
 5128: }
 5129: 
 5130: sub verify_user_display {
 5131:     my ($context) = @_;
 5132:     my %lt = &Apache::lonlocal::texthash (
 5133:         course    => 'course(s): description, section(s), status',
 5134:         community => 'community(s): description, section(s), status',
 5135:         author    => 'author',
 5136:     );
 5137:     my $photos;
 5138:     if (($context eq 'course') && $env{'request.course.id'}) {
 5139:         $photos = $env{'course.'.$env{'request.course.id'}.'.internal.showphoto'};
 5140:     }
 5141:     my $output = <<"END";
 5142: 
 5143: function hide_searching() {
 5144:     if (document.getElementById('searching')) {
 5145:         document.getElementById('searching').style.display = 'none';
 5146:     }
 5147:     return;
 5148: }
 5149: 
 5150: function display_update() {
 5151:     document.studentform.action.value = 'listusers';
 5152:     document.studentform.phase.value = 'display';
 5153:     document.studentform.submit();
 5154: }
 5155: 
 5156: function updateCols(caller) {
 5157:     var context = '$context';
 5158:     var photos = '$photos';
 5159:     if (caller == 'Status') {
 5160:         if ((context == 'domain') && 
 5161:             ((document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'course') ||
 5162:              (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'community'))) {
 5163:             document.getElementById('showcolstatus').checked = false;
 5164:             document.getElementById('showcolstatus').disabled = 'disabled';
 5165:             document.getElementById('showcolstart').checked = false;
 5166:             document.getElementById('showcolend').checked = false;
 5167:         } else {
 5168:             if (document.studentform.Status.options[document.studentform.Status.selectedIndex].value == 'Any') {
 5169:                 document.getElementById('showcolstatus').checked = true;
 5170:                 document.getElementById('showcolstatus').disabled = '';
 5171:                 document.getElementById('showcolstart').checked = true;
 5172:                 document.getElementById('showcolend').checked = true;
 5173:             } else {
 5174:                 document.getElementById('showcolstatus').checked = false;
 5175:                 document.getElementById('showcolstatus').disabled = 'disabled';
 5176:                 document.getElementById('showcolstart').checked = false;
 5177:                 document.getElementById('showcolend').checked = false;
 5178:             }
 5179:         }
 5180:     }
 5181:     if (caller == 'output') {
 5182:         if (photos == 1) {
 5183:             if (document.getElementById('showcolphoto')) {
 5184:                 var photoitem = document.getElementById('showcolphoto');
 5185:                 if (document.studentform.output.options[document.studentform.output.selectedIndex].value == 'html') {
 5186:                     photoitem.checked = true;
 5187:                     photoitem.disabled = '';
 5188:                 } else {
 5189:                     photoitem.checked = false;
 5190:                     photoitem.disabled = 'disabled';
 5191:                 }
 5192:             }
 5193:         }
 5194:     }
 5195:     if (caller == 'showrole') {
 5196:         if ((document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'Any') ||
 5197:             (document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'cr')) {
 5198:             document.getElementById('showcolrole').checked = true;
 5199:             document.getElementById('showcolrole').disabled = '';
 5200:         } else {
 5201:             document.getElementById('showcolrole').checked = false;
 5202:             document.getElementById('showcolrole').disabled = 'disabled';
 5203:         }
 5204:         if (context == 'domain') {
 5205:             var quotausageshow = 0;
 5206:             if ((document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'course') ||
 5207:                 (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'community')) {
 5208:                 document.getElementById('showcolstatus').checked = false;
 5209:                 document.getElementById('showcolstatus').disabled = 'disabled';
 5210:                 document.getElementById('showcolstart').checked = false;
 5211:                 document.getElementById('showcolend').checked = false;
 5212:             } else {
 5213:                 if (document.studentform.Status.options[document.studentform.Status.selectedIndex].value == 'Any') {
 5214:                     document.getElementById('showcolstatus').checked = true;
 5215:                     document.getElementById('showcolstatus').disabled = '';
 5216:                     document.getElementById('showcolstart').checked = true;
 5217:                     document.getElementById('showcolend').checked = true;
 5218:                 }
 5219:             }
 5220:             if (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'domain') {
 5221:                 document.getElementById('showcolextent').disabled = 'disabled';
 5222:                 document.getElementById('showcolextent').checked = 'false';
 5223:                 document.getElementById('showextent').style.display='none';
 5224:                 document.getElementById('showcoltextextent').innerHTML = '';
 5225:                 if ((document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'au') ||
 5226:                     (document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'Any')) {
 5227:                     if (document.getElementById('showcolauthorusage')) {
 5228:                         document.getElementById('showcolauthorusage').disabled = '';
 5229:                     }
 5230:                     if (document.getElementById('showcolauthorquota')) {
 5231:                         document.getElementById('showcolauthorquota').disabled = '';
 5232:                     }
 5233:                     quotausageshow = 1;
 5234:                 }
 5235:             } else {
 5236:                 document.getElementById('showextent').style.display='block';
 5237:                 document.getElementById('showextent').style.textAlign='left';
 5238:                 document.getElementById('showextent').style.textFace='normal';
 5239:                 if (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'author') {
 5240:                     document.getElementById('showcolextent').disabled = '';
 5241:                     document.getElementById('showcolextent').checked = 'true';
 5242:                     document.getElementById('showcoltextextent').innerHTML="$lt{'author'}";
 5243:                 } else {
 5244:                     document.getElementById('showcolextent').disabled = '';
 5245:                     document.getElementById('showcolextent').checked = 'true';
 5246:                     if (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'community') {
 5247:                         document.getElementById('showcoltextextent').innerHTML="$lt{'community'}";
 5248:                     } else {
 5249:                         document.getElementById('showcoltextextent').innerHTML="$lt{'course'}";
 5250:                     }
 5251:                 }
 5252:             }
 5253:             if (quotausageshow == 0)  {
 5254:                 if (document.getElementById('showcolauthorusage')) {
 5255:                     document.getElementById('showcolauthorusage').checked = false;
 5256:                     document.getElementById('showcolauthorusage').disabled = 'disabled';
 5257:                 }
 5258:                 if (document.getElementById('showcolauthorquota')) {
 5259:                     document.getElementById('showcolauthorquota').checked = false;
 5260:                     document.getElementById('showcolauthorquota').disabled = 'disabled';
 5261:                 }
 5262:             }
 5263:         }
 5264:     }
 5265:     return;
 5266: }
 5267: 
 5268: END
 5269:     return $output;
 5270: 
 5271: }
 5272: 
 5273: ###############################################################
 5274: ###############################################################
 5275: #  Menu Phase One
 5276: sub print_main_menu {
 5277:     my ($permission,$context,$crstype) = @_;
 5278:     my $linkcontext = $context;
 5279:     my $stuterm = lc(&Apache::lonnet::plaintext('st',$crstype));
 5280:     if (($context eq 'course') && ($crstype eq 'Community')) {
 5281:         $linkcontext = lc($crstype);
 5282:         $stuterm = 'Members';
 5283:     }
 5284:     my %links = (
 5285:                 domain => {
 5286:                             upload     => 'Upload a File of Users',
 5287:                             singleuser => 'Add/Modify a User',
 5288:                             listusers  => 'Manage Users',
 5289:                             },
 5290:                 author => {
 5291:                             upload     => 'Upload a File of Co-authors',
 5292:                             singleuser => 'Add/Modify a Co-author',
 5293:                             listusers  => 'Manage Co-authors',
 5294:                             },
 5295:                 course => {
 5296:                             upload     => 'Upload a File of Course Users',
 5297:                             singleuser => 'Add/Modify a Course User',
 5298:                             listusers  => 'List and Modify Multiple Course Users',
 5299:                             },
 5300:                 community => {
 5301:                             upload     => 'Upload a File of Community Users',
 5302:                             singleuser => 'Add/Modify a Community User',
 5303:                             listusers  => 'List and Modify Multiple Community Users',
 5304:                            },
 5305:                 );
 5306:      my %linktitles = (
 5307:                 domain => {
 5308:                             singleuser => 'Add a user to the domain, and/or a course or community in the domain.',
 5309:                             listusers  => 'Show and manage users in this domain.',
 5310:                             },
 5311:                 author => {
 5312:                             singleuser => 'Add a user with a co- or assistant author role.',
 5313:                             listusers  => 'Show and manage co- or assistant authors.',
 5314:                             },
 5315:                 course => {
 5316:                             singleuser => 'Add a user with a certain role to this course.',
 5317:                             listusers  => 'Show and manage users in this course.',
 5318:                             },
 5319:                 community => {
 5320:                             singleuser => 'Add a user with a certain role to this community.',
 5321:                             listusers  => 'Show and manage users in this community.',
 5322:                            },
 5323:                 );
 5324:   my @menu = ( {categorytitle => 'Single Users', 
 5325:          items =>
 5326:          [
 5327:             {
 5328:              linktext => $links{$linkcontext}{'singleuser'},
 5329:              icon => 'edit-redo.png',
 5330:              #help => 'Course_Change_Privileges',
 5331:              url => '/adm/createuser?action=singleuser',
 5332:              permission => $permission->{'cusr'},
 5333:              linktitle => $linktitles{$linkcontext}{'singleuser'},
 5334:             },
 5335:          ]},
 5336: 
 5337:          {categorytitle => 'Multiple Users',
 5338:          items => 
 5339:          [
 5340:             {
 5341:              linktext => $links{$linkcontext}{'upload'},
 5342:              icon => 'uplusr.png',
 5343:              #help => 'Course_Create_Class_List',
 5344:              url => '/adm/createuser?action=upload',
 5345:              permission => $permission->{'cusr'},
 5346:              linktitle => 'Upload a CSV or a text file containing users.',
 5347:             },
 5348:             {
 5349:              linktext => $links{$linkcontext}{'listusers'},
 5350:              icon => 'mngcu.png',
 5351:              #help => 'Course_View_Class_List',
 5352:              url => '/adm/createuser?action=listusers',
 5353:              permission => ($permission->{'view'} || $permission->{'cusr'}),
 5354:              linktitle => $linktitles{$linkcontext}{'listusers'}, 
 5355:             },
 5356: 
 5357:          ]},
 5358: 
 5359:          {categorytitle => 'Administration',
 5360:          items => [ ]},
 5361:        );
 5362:             
 5363:     if ($context eq 'domain'){
 5364:         
 5365:         push(@{ $menu[2]->{items} }, #Category: Administration
 5366:             {
 5367:              linktext => 'Custom Roles',
 5368:              icon => 'emblem-photos.png',
 5369:              #help => 'Course_Editing_Custom_Roles',
 5370:              url => '/adm/createuser?action=custom',
 5371:              permission => $permission->{'custom'},
 5372:              linktitle => 'Configure a custom role.',
 5373:             },
 5374:             {
 5375:              linktext => 'Authoring Space Requests',
 5376:              icon => 'selfenrl-queue.png',
 5377:              #help => 'Domain_Role_Approvals',
 5378:              url => '/adm/createuser?action=processauthorreq',
 5379:              permission => $permission->{'cusr'},
 5380:              linktitle => 'Approve or reject author role requests',
 5381:             },
 5382:             {
 5383:              linktext => 'LON-CAPA Account Requests',
 5384:              icon => 'list-add.png',
 5385:              #help => 'Domain_Username_Approvals',
 5386:              url => '/adm/createuser?action=processusernamereq',
 5387:              permission => $permission->{'cusr'},
 5388:              linktitle => 'Approve or reject LON-CAPA account requests',
 5389:             },
 5390:             {
 5391:              linktext => 'Change Log',
 5392:              icon => 'document-properties.png',
 5393:              #help => 'Course_User_Logs',
 5394:              url => '/adm/createuser?action=changelogs',
 5395:              permission => $permission->{'cusr'},
 5396:              linktitle => 'View change log.',
 5397:             },
 5398:         );
 5399:         
 5400:     }elsif ($context eq 'course'){
 5401:         my ($cnum,$cdom) = &Apache::lonuserutils::get_course_identity();
 5402: 
 5403:         my %linktext = (
 5404:                          'Course'    => {
 5405:                                           single => 'Add/Modify a Student', 
 5406:                                           drop   => 'Drop Students',
 5407:                                           groups => 'Course Groups',
 5408:                                         },
 5409:                          'Community' => {
 5410:                                           single => 'Add/Modify a Member', 
 5411:                                           drop   => 'Drop Members',
 5412:                                           groups => 'Community Groups',
 5413:                                         },
 5414:                        );
 5415:         $linktext{'Placement'} = $linktext{'Course'};
 5416: 
 5417:         my %linktitle = (
 5418:             'Course' => {
 5419:                   single => 'Add a user with the role of student to this course',
 5420:                   drop   => 'Remove a student from this course.',
 5421:                   groups => 'Manage course groups',
 5422:                         },
 5423:             'Community' => {
 5424:                   single => 'Add a user with the role of member to this community',
 5425:                   drop   => 'Remove a member from this community.',
 5426:                   groups => 'Manage community groups',
 5427:                            },
 5428:         );
 5429: 
 5430:         $linktitle{'Placement'} = $linktitle{'Course'};
 5431: 
 5432:         push(@{ $menu[0]->{items} }, #Category: Single Users
 5433:             {   
 5434:              linktext => $linktext{$crstype}{'single'},
 5435:              #help => 'Course_Add_Student',
 5436:              icon => 'list-add.png',
 5437:              url => '/adm/createuser?action=singlestudent',
 5438:              permission => $permission->{'cusr'},
 5439:              linktitle => $linktitle{$crstype}{'single'},
 5440:             },
 5441:         );
 5442:         
 5443:         push(@{ $menu[1]->{items} }, #Category: Multiple Users 
 5444:             {
 5445:              linktext => $linktext{$crstype}{'drop'},
 5446:              icon => 'edit-undo.png',
 5447:              #help => 'Course_Drop_Student',
 5448:              url => '/adm/createuser?action=drop',
 5449:              permission => $permission->{'cusr'},
 5450:              linktitle => $linktitle{$crstype}{'drop'},
 5451:             },
 5452:         );
 5453:         push(@{ $menu[2]->{items} }, #Category: Administration
 5454:             {    
 5455:              linktext => 'Custom Roles',
 5456:              icon => 'emblem-photos.png',
 5457:              #help => 'Course_Editing_Custom_Roles',
 5458:              url => '/adm/createuser?action=custom',
 5459:              permission => $permission->{'custom'},
 5460:              linktitle => 'Configure a custom role.',
 5461:             },
 5462:             {
 5463:              linktext => $linktext{$crstype}{'groups'},
 5464:              icon => 'grps.png',
 5465:              #help => 'Course_Manage_Group',
 5466:              url => '/adm/coursegroups?refpage=cusr',
 5467:              permission => $permission->{'grp_manage'},
 5468:              linktitle => $linktitle{$crstype}{'groups'},
 5469:             },
 5470:             {
 5471:              linktext => 'Change Log',
 5472:              icon => 'document-properties.png',
 5473:              #help => 'Course_User_Logs',
 5474:              url => '/adm/createuser?action=changelogs',
 5475:              permission => $permission->{'cusr'},
 5476:              linktitle => 'View change log.',
 5477:             },
 5478:         );
 5479:         if ($env{'course.'.$env{'request.course.id'}.'.internal.selfenroll_approval'}) {
 5480:             push(@{ $menu[2]->{items} },
 5481:                     {
 5482:                      linktext => 'Enrollment Requests',
 5483:                      icon => 'selfenrl-queue.png',
 5484:                      #help => 'Course_Approve_Selfenroll',
 5485:                      url => '/adm/createuser?action=selfenrollqueue',
 5486:                      permission => $permission->{'selfenrolladmin'},
 5487:                      linktitle =>'Approve or reject enrollment requests.',
 5488:                     },
 5489:             );
 5490:         }
 5491:         
 5492:         if (!exists($permission->{'cusr_section'})){
 5493:             if ($crstype ne 'Community') {
 5494:                 push(@{ $menu[2]->{items} },
 5495:                     {
 5496:                      linktext => 'Automated Enrollment',
 5497:                      icon => 'roles.png',
 5498:                      #help => 'Course_Automated_Enrollment',
 5499:                      permission => (&Apache::lonnet::auto_run($cnum,$cdom)
 5500:                                          && $permission->{'cusr'}),
 5501:                      url  => '/adm/populate',
 5502:                      linktitle => 'Automated enrollment manager.',
 5503:                     }
 5504:                 );
 5505:             }
 5506:             push(@{ $menu[2]->{items} }, 
 5507:                 {
 5508:                  linktext => 'User Self-Enrollment',
 5509:                  icon => 'self_enroll.png',
 5510:                  #help => 'Course_Self_Enrollment',
 5511:                  url => '/adm/createuser?action=selfenroll',
 5512:                  permission => $permission->{'selfenrolladmin'},
 5513:                  linktitle => 'Configure user self-enrollment.',
 5514:                 },
 5515:             );
 5516:         }
 5517:     } elsif ($context eq 'author') {
 5518:         push(@{ $menu[2]->{items} }, #Category: Administration
 5519:             {
 5520:              linktext => 'Change Log',
 5521:              icon => 'document-properties.png',
 5522:              #help => 'Course_User_Logs',
 5523:              url => '/adm/createuser?action=changelogs',
 5524:              permission => $permission->{'cusr'},
 5525:              linktitle => 'View change log.',
 5526:             },
 5527:         );
 5528:     }
 5529:     return Apache::lonhtmlcommon::generate_menu(@menu);
 5530: #               { text => 'View Log-in History',
 5531: #                 help => 'Course_User_Logins',
 5532: #                 action => 'logins',
 5533: #                 permission => $permission->{'cusr'},
 5534: #               });
 5535: }
 5536: 
 5537: sub restore_prev_selections {
 5538:     my %saveable_parameters = ('srchby'   => 'scalar',
 5539: 			       'srchin'   => 'scalar',
 5540: 			       'srchtype' => 'scalar',
 5541: 			       );
 5542:     &Apache::loncommon::store_settings('user','user_picker',
 5543: 				       \%saveable_parameters);
 5544:     &Apache::loncommon::restore_settings('user','user_picker',
 5545: 					 \%saveable_parameters);
 5546: }
 5547: 
 5548: sub print_selfenroll_menu {
 5549:     my ($r,$context,$cid,$cdom,$cnum,$currsettings,$additional) = @_;
 5550:     my $crstype = &Apache::loncommon::course_type();
 5551:     my $formname = 'selfenroll';
 5552:     my $nolink = 1;
 5553:     my ($row,$lt) = &Apache::lonuserutils::get_selfenroll_titles();
 5554:     my $groupslist = &Apache::lonuserutils::get_groupslist();
 5555:     my $setsec_js = 
 5556:         &Apache::lonuserutils::setsections_javascript($formname,$groupslist);
 5557:     my %alerts = &Apache::lonlocal::texthash(
 5558:         acto => 'Activation of self-enrollment was selected for the following domain(s)',
 5559:         butn => 'but no user types have been checked.',
 5560:         wilf => "Please uncheck 'activate' or check at least one type.",
 5561:     );
 5562:     &js_escape(\%alerts);
 5563:     my $selfenroll_js = <<"ENDSCRIPT";
 5564: function update_types(caller,num) {
 5565:     var delidx = getIndexByName('selfenroll_delete');
 5566:     var actidx = getIndexByName('selfenroll_activate');
 5567:     if (caller == 'selfenroll_all') {
 5568:         var selall;
 5569:         for (var i=0; i<document.$formname.selfenroll_all.length; i++) {
 5570:             if (document.$formname.selfenroll_all[i].checked) {
 5571:                 selall = document.$formname.selfenroll_all[i].value;
 5572:             }
 5573:         }
 5574:         if (selall == 1) {
 5575:             if (delidx != -1) {
 5576:                 if (document.$formname.selfenroll_delete.length) {
 5577:                     for (var j=0; j<document.$formname.selfenroll_delete.length; j++) {
 5578:                         document.$formname.selfenroll_delete[j].checked = true;
 5579:                     }
 5580:                 } else {
 5581:                     document.$formname.elements[delidx].checked = true;
 5582:                 }
 5583:             }
 5584:             if (actidx != -1) {
 5585:                 if (document.$formname.selfenroll_activate.length) {
 5586:                     for (var j=0; j<document.$formname.selfenroll_activate.length; j++) {
 5587:                         document.$formname.selfenroll_activate[j].checked = false;
 5588:                     }
 5589:                 } else {
 5590:                     document.$formname.elements[actidx].checked = false;
 5591:                 }
 5592:             }
 5593:             document.$formname.selfenroll_newdom.selectedIndex = 0; 
 5594:         }
 5595:     }
 5596:     if (caller == 'selfenroll_activate') {
 5597:         if (document.$formname.selfenroll_activate.length) {
 5598:             for (var j=0; j<document.$formname.selfenroll_activate.length; j++) {
 5599:                 if (document.$formname.selfenroll_activate[j].value == num) {
 5600:                     if (document.$formname.selfenroll_activate[j].checked) {
 5601:                         for (var i=0; i<document.$formname.selfenroll_all.length; i++) {
 5602:                             if (document.$formname.selfenroll_all[i].value == '1') {
 5603:                                 document.$formname.selfenroll_all[i].checked = false;
 5604:                             }
 5605:                             if (document.$formname.selfenroll_all[i].value == '0') {
 5606:                                 document.$formname.selfenroll_all[i].checked = true;
 5607:                             }
 5608:                         }
 5609:                     }
 5610:                 }
 5611:             }
 5612:         } else {
 5613:             for (var i=0; i<document.$formname.selfenroll_all.length; i++) {
 5614:                 if (document.$formname.selfenroll_all[i].value == '1') {
 5615:                     document.$formname.selfenroll_all[i].checked = false;
 5616:                 }
 5617:                 if (document.$formname.selfenroll_all[i].value == '0') {
 5618:                     document.$formname.selfenroll_all[i].checked = true;
 5619:                 }
 5620:             }
 5621:         }
 5622:     }
 5623:     if (caller == 'selfenroll_delete') {
 5624:         if (document.$formname.selfenroll_delete.length) {
 5625:             for (var j=0; j<document.$formname.selfenroll_delete.length; j++) {
 5626:                 if (document.$formname.selfenroll_delete[j].value == num) {
 5627:                     if (document.$formname.selfenroll_delete[j].checked) {
 5628:                         var delindex = getIndexByName('selfenroll_types_'+num);
 5629:                         if (delindex != -1) { 
 5630:                             if (document.$formname.elements[delindex].length) {
 5631:                                 for (var k=0; k<document.$formname.elements[delindex].length; k++) {
 5632:                                     document.$formname.elements[delindex][k].checked = false;
 5633:                                 }
 5634:                             } else {
 5635:                                 document.$formname.elements[delindex].checked = false;
 5636:                             }
 5637:                         }
 5638:                     }
 5639:                 }
 5640:             }
 5641:         } else {
 5642:             if (document.$formname.selfenroll_delete.checked) {
 5643:                 var delindex = getIndexByName('selfenroll_types_'+num);
 5644:                 if (delindex != -1) {
 5645:                     if (document.$formname.elements[delindex].length) {
 5646:                         for (var k=0; k<document.$formname.elements[delindex].length; k++) {
 5647:                             document.$formname.elements[delindex][k].checked = false;
 5648:                         }
 5649:                     } else {
 5650:                         document.$formname.elements[delindex].checked = false;
 5651:                     }
 5652:                 }
 5653:             }
 5654:         }
 5655:     }
 5656:     return;
 5657: }
 5658: 
 5659: function validate_types(form) {
 5660:     var needaction = new Array();
 5661:     var countfail = 0;
 5662:     var actidx = getIndexByName('selfenroll_activate');
 5663:     if (actidx != -1) {
 5664:         if (document.$formname.selfenroll_activate.length) {
 5665:             for (var j=0; j<document.$formname.selfenroll_activate.length; j++) {
 5666:                 var num = document.$formname.selfenroll_activate[j].value;
 5667:                 if (document.$formname.selfenroll_activate[j].checked) {
 5668:                     countfail = check_types(num,countfail,needaction)
 5669:                 }
 5670:             }
 5671:         } else {
 5672:             if (document.$formname.selfenroll_activate.checked) {
 5673:                 var num = document.$formname.selfenroll_activate.value;
 5674:                 countfail = check_types(num,countfail,needaction)
 5675:             }
 5676:         }
 5677:     }
 5678:     if (countfail > 0) {
 5679:         var msg = "$alerts{'acto'}\\n";
 5680:         var loopend = needaction.length -1;
 5681:         if (loopend > 0) {
 5682:             for (var m=0; m<loopend; m++) {
 5683:                 msg += needaction[m]+", ";
 5684:             }
 5685:         }
 5686:         msg += needaction[loopend]+"\\n$alerts{'butn'}\\n$alerts{'wilf'}";
 5687:         alert(msg);
 5688:         return; 
 5689:     }
 5690:     setSections(form);
 5691: }
 5692: 
 5693: function check_types(num,countfail,needaction) {
 5694:     var typeidx = getIndexByName('selfenroll_types_'+num);
 5695:     var count = 0;
 5696:     if (typeidx != -1) {
 5697:         if (document.$formname.elements[typeidx].length) {
 5698:             for (var k=0; k<document.$formname.elements[typeidx].length; k++) {
 5699:                 if (document.$formname.elements[typeidx][k].checked) {
 5700:                     count ++;
 5701:                 }
 5702:             }
 5703:         } else {
 5704:             if (document.$formname.elements[typeidx].checked) {
 5705:                 count ++;
 5706:             }
 5707:         }
 5708:         if (count == 0) {
 5709:             var domidx = getIndexByName('selfenroll_dom_'+num);
 5710:             if (domidx != -1) {
 5711:                 var domname = document.$formname.elements[domidx].value;
 5712:                 needaction[countfail] = domname;
 5713:                 countfail ++;
 5714:             }
 5715:         }
 5716:     }
 5717:     return countfail;
 5718: }
 5719: 
 5720: function toggleNotify() {
 5721:     var selfenrollApproval = 0;
 5722:     if (document.$formname.selfenroll_approval.length) {
 5723:         for (var i=0; i<document.$formname.selfenroll_approval.length; i++) {
 5724:             if (document.$formname.selfenroll_approval[i].checked) {
 5725:                 selfenrollApproval = document.$formname.selfenroll_approval[i].value;
 5726:                 break;        
 5727:             }
 5728:         }
 5729:     }
 5730:     if (document.getElementById('notified')) {
 5731:         if (selfenrollApproval == 0) {
 5732:             document.getElementById('notified').style.display='none';
 5733:         } else {
 5734:             document.getElementById('notified').style.display='block';
 5735:         }
 5736:     }
 5737:     return;
 5738: }
 5739: 
 5740: function getIndexByName(item) {
 5741:     for (var i=0;i<document.$formname.elements.length;i++) {
 5742:         if (document.$formname.elements[i].name == item) {
 5743:             return i;
 5744:         }
 5745:     }
 5746:     return -1;
 5747: }
 5748: ENDSCRIPT
 5749: 
 5750:     my $output = '<script type="text/javascript">'."\n".
 5751:                  '// <![CDATA['."\n".
 5752:                  $setsec_js."\n".$selfenroll_js."\n".
 5753:                  '// ]]>'."\n".
 5754:                  '</script>'."\n".
 5755:                  '<h3>'.$lt->{'selfenroll'}.'</h3>'."\n";
 5756:  
 5757:     my $visactions = &cat_visibility();
 5758:     my ($cathash,%cattype);
 5759:     my %domconfig = &Apache::lonnet::get_dom('configuration',['coursecategories'],$cdom);
 5760:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 5761:         $cathash = $domconfig{'coursecategories'}{'cats'};
 5762:         $cattype{'auth'} = $domconfig{'coursecategories'}{'auth'};
 5763:         $cattype{'unauth'} = $domconfig{'coursecategories'}{'unauth'};
 5764:         if ($cattype{'auth'} eq '') {
 5765:             $cattype{'auth'} = 'std';
 5766:         }
 5767:         if ($cattype{'unauth'} eq '') {
 5768:             $cattype{'unauth'} = 'std';
 5769:         }
 5770:     } else {
 5771:         $cathash = {};
 5772:         $cattype{'auth'} = 'std';
 5773:         $cattype{'unauth'} = 'std';
 5774:     }
 5775:     if (($cattype{'auth'} eq 'none') && ($cattype{'unauth'} eq 'none')) {
 5776:         $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
 5777:                   '<br />'.
 5778:                   '<br />'.$visactions->{'take'}.'<ul>'.
 5779:                   '<li>'.$visactions->{'dc_chgconf'}.'</li>'.
 5780:                   '</ul>');
 5781:     } elsif (($cattype{'auth'} !~ /^(std|domonly)$/) && ($cattype{'unauth'} !~ /^(std|domonly)$/)) {
 5782:         if ($currsettings->{'uniquecode'}) {
 5783:             $r->print('<span class="LC_info">'.$visactions->{'vis'}.'</span>');
 5784:         } else {
 5785:             $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
 5786:                   '<br />'.
 5787:                   '<br />'.$visactions->{'take'}.'<ul>'.
 5788:                   '<li>'.$visactions->{'dc_setcode'}.'</li>'.
 5789:                   '</ul><br />');
 5790:         }
 5791:     } else {
 5792:         my ($visible,$cansetvis,$vismsgs) = &visible_in_stdcat($cdom,$cnum,\%domconfig);
 5793:         if (ref($visactions) eq 'HASH') {
 5794:             if ($visible) {
 5795:                 $output .= '<p class="LC_info">'.$visactions->{'vis'}.'</p>';
 5796:            } else {
 5797:                 $output .= '<p class="LC_warning">'.$visactions->{'miss'}.'</p>'
 5798:                           .$visactions->{'yous'}.
 5799:                            '<p>'.$visactions->{'gen'}.'<br />'.$visactions->{'coca'};
 5800:                 if (ref($vismsgs) eq 'ARRAY') {
 5801:                     $output .= '<br />'.$visactions->{'make'}.'<ul>';
 5802:                     foreach my $item (@{$vismsgs}) {
 5803:                         $output .= '<li>'.$visactions->{$item}.'</li>';
 5804:                     }
 5805:                     $output .= '</ul>';
 5806:                 }
 5807:                 $output .= '</p>';
 5808:             }
 5809:         }
 5810:     }
 5811:     my $actionhref = '/adm/createuser';
 5812:     if ($context eq 'domain') {
 5813:         $actionhref = '/adm/modifycourse';
 5814:     }
 5815: 
 5816:     my %noedit;
 5817:     unless ($context eq 'domain') {
 5818:         %noedit = &get_noedit_fields($cdom,$cnum,$crstype,$row);
 5819:     }
 5820:     $output .= '<form name="'.$formname.'" method="post" action="'.$actionhref.'">'."\n".
 5821:                &Apache::lonhtmlcommon::start_pick_box();
 5822:     if (ref($row) eq 'ARRAY') {
 5823:         foreach my $item (@{$row}) {
 5824:             my $title = $item; 
 5825:             if (ref($lt) eq 'HASH') {
 5826:                 $title = $lt->{$item};
 5827:             }
 5828:             $output .= &Apache::lonhtmlcommon::row_title($title);
 5829:             if ($item eq 'types') {
 5830:                 my $curr_types;
 5831:                 if (ref($currsettings) eq 'HASH') {
 5832:                     $curr_types = $currsettings->{'selfenroll_types'};
 5833:                 }
 5834:                 if ($noedit{$item}) {
 5835:                     if ($curr_types eq '*') {
 5836:                         $output .= &mt('Any user in any domain');   
 5837:                     } else {
 5838:                         my @entries = split(/;/,$curr_types);
 5839:                         if (@entries > 0) {
 5840:                             $output .= '<ul>'; 
 5841:                             foreach my $entry (@entries) {
 5842:                                 my ($currdom,$typestr) = split(/:/,$entry);
 5843:                                 next if ($typestr eq '');
 5844:                                 my $domdesc = &Apache::lonnet::domain($currdom);
 5845:                                 my @currinsttypes = split(',',$typestr);
 5846:                                 my ($othertitle,$usertypes,$types) = 
 5847:                                     &Apache::loncommon::sorted_inst_types($currdom);
 5848:                                 if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 5849:                                     $usertypes->{'any'} = &mt('any user'); 
 5850:                                     if (keys(%{$usertypes}) > 0) {
 5851:                                         $usertypes->{'other'} = &mt('other users');
 5852:                                     }
 5853:                                     my @longinsttypes = map { $usertypes->{$_}; } @currinsttypes;
 5854:                                     $output .= '<li>'.$domdesc.':'.join(', ',@longinsttypes).'</li>';
 5855:                                  }
 5856:                             }
 5857:                             $output .= '</ul>';
 5858:                         } else {
 5859:                             $output .= &mt('None');
 5860:                         }
 5861:                     }
 5862:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 5863:                     next;
 5864:                 }
 5865:                 my $showdomdesc = 1;
 5866:                 my $includeempty = 1;
 5867:                 my $num = 0;
 5868:                 $output .= &Apache::loncommon::start_data_table().
 5869:                            &Apache::loncommon::start_data_table_row()
 5870:                            .'<td colspan="2"><span class="LC_nobreak"><label>'
 5871:                            .&mt('Any user in any domain:')
 5872:                            .'&nbsp;<input type="radio" name="selfenroll_all" value="1" ';
 5873:                 if ($curr_types eq '*') {
 5874:                     $output .= ' checked="checked" '; 
 5875:                 }
 5876:                 $output .= 'onchange="javascript:update_types('.
 5877:                            "'selfenroll_all'".');" />'.&mt('Yes').'</label>'.
 5878:                            '&nbsp;&nbsp;<input type="radio" name="selfenroll_all" value="0" ';
 5879:                 if ($curr_types ne '*') {
 5880:                     $output .= ' checked="checked" ';
 5881:                 }
 5882:                 $output .= ' onchange="javascript:update_types('.
 5883:                            "'selfenroll_all'".');"/>'.&mt('No').'</label></td>'.
 5884:                            &Apache::loncommon::end_data_table_row().
 5885:                            &Apache::loncommon::end_data_table().
 5886:                            &mt('Or').'<br />'.
 5887:                            &Apache::loncommon::start_data_table();
 5888:                 my %currdoms;
 5889:                 if ($curr_types eq '') {
 5890:                     $output .= &new_selfenroll_dom_row($cdom,'0');
 5891:                 } elsif ($curr_types ne '*') {
 5892:                     my @entries = split(/;/,$curr_types);
 5893:                     if (@entries > 0) {
 5894:                         foreach my $entry (@entries) {
 5895:                             my ($currdom,$typestr) = split(/:/,$entry);
 5896:                             $currdoms{$currdom} = 1;
 5897:                             my $domdesc = &Apache::lonnet::domain($currdom);
 5898:                             my @currinsttypes = split(',',$typestr);
 5899:                             $output .= &Apache::loncommon::start_data_table_row()
 5900:                                        .'<td valign="top"><span class="LC_nobreak">'.&mt('Domain:').'<b>'
 5901:                                        .'&nbsp;'.$domdesc.' ('.$currdom.')'
 5902:                                        .'</b><input type="hidden" name="selfenroll_dom_'.$num
 5903:                                        .'" value="'.$currdom.'" /></span><br />'
 5904:                                        .'<span class="LC_nobreak"><label><input type="checkbox" '
 5905:                                        .'name="selfenroll_delete" value="'.$num.'" onchange="javascript:update_types('."'selfenroll_delete','$num'".');" />'
 5906:                                        .&mt('Delete').'</label></span></td>';
 5907:                             $output .= '<td valign="top">&nbsp;&nbsp;'.&mt('User types:').'<br />'
 5908:                                        .&selfenroll_inst_types($num,$currdom,\@currinsttypes).'</td>'
 5909:                                        .&Apache::loncommon::end_data_table_row();
 5910:                             $num ++;
 5911:                         }
 5912:                     }
 5913:                 }
 5914:                 my $add_domtitle = &mt('Users in additional domain:');
 5915:                 if ($curr_types eq '*') { 
 5916:                     $add_domtitle = &mt('Users in specific domain:');
 5917:                 } elsif ($curr_types eq '') {
 5918:                     $add_domtitle = &mt('Users in other domain:');
 5919:                 }
 5920:                 $output .= &Apache::loncommon::start_data_table_row()
 5921:                            .'<td colspan="2"><span class="LC_nobreak">'.$add_domtitle.'</span><br />'
 5922:                            .&Apache::loncommon::select_dom_form('','selfenroll_newdom',
 5923:                                                                 $includeempty,$showdomdesc)
 5924:                            .'<input type="hidden" name="selfenroll_types_total" value="'.$num.'" />'
 5925:                            .'</td>'.&Apache::loncommon::end_data_table_row()
 5926:                            .&Apache::loncommon::end_data_table();
 5927:             } elsif ($item eq 'registered') {
 5928:                 my ($regon,$regoff);
 5929:                 my $registered;
 5930:                 if (ref($currsettings) eq 'HASH') {
 5931:                     $registered = $currsettings->{'selfenroll_registered'};
 5932:                 }
 5933:                 if ($noedit{$item}) {
 5934:                     if ($registered) {
 5935:                         $output .= &mt('Must be registered in course');
 5936:                     } else {
 5937:                         $output .= &mt('No requirement');
 5938:                     }
 5939:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 5940:                     next;
 5941:                 }
 5942:                 if ($registered) {
 5943:                     $regon = ' checked="checked" ';
 5944:                     $regoff = ' ';
 5945:                 } else {
 5946:                     $regon = ' ';
 5947:                     $regoff = ' checked="checked" ';
 5948:                 }
 5949:                 $output .= '<label>'.
 5950:                            '<input type="radio" name="selfenroll_registered" value="1"'.$regon.'/>'.
 5951:                            &mt('Yes').'</label>&nbsp;&nbsp;<label>'.
 5952:                            '<input type="radio" name="selfenroll_registered" value="0"'.$regoff.'/>'.
 5953:                            &mt('No').'</label>';
 5954:             } elsif ($item eq 'enroll_dates') {
 5955:                 my ($starttime,$endtime);
 5956:                 if (ref($currsettings) eq 'HASH') {
 5957:                     $starttime = $currsettings->{'selfenroll_start_date'};
 5958:                     $endtime = $currsettings->{'selfenroll_end_date'};
 5959:                     if ($starttime eq '') {
 5960:                         $starttime = $currsettings->{'default_enrollment_start_date'};
 5961:                     }
 5962:                     if ($endtime eq '') {
 5963:                         $endtime = $currsettings->{'default_enrollment_end_date'};
 5964:                     }
 5965:                 }
 5966:                 if ($noedit{$item}) {
 5967:                     $output .= &mt('From: [_1], to: [_2]',&Apache::lonlocal::locallocaltime($starttime),
 5968:                                                           &Apache::lonlocal::locallocaltime($endtime));
 5969:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 5970:                     next;
 5971:                 }
 5972:                 my $startform =
 5973:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_start_date',$starttime,
 5974:                                       undef,undef,undef,undef,undef,undef,undef,$nolink);
 5975:                 my $endform =
 5976:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_end_date',$endtime,
 5977:                                       undef,undef,undef,undef,undef,undef,undef,$nolink);
 5978:                 $output .= &selfenroll_date_forms($startform,$endform);
 5979:             } elsif ($item eq 'access_dates') {
 5980:                 my ($starttime,$endtime);
 5981:                 if (ref($currsettings) eq 'HASH') {
 5982:                     $starttime = $currsettings->{'selfenroll_start_access'};
 5983:                     $endtime = $currsettings->{'selfenroll_end_access'};
 5984:                     if ($starttime eq '') {
 5985:                         $starttime = $currsettings->{'default_enrollment_start_date'};
 5986:                     }
 5987:                     if ($endtime eq '') {
 5988:                         $endtime = $currsettings->{'default_enrollment_end_date'};
 5989:                     }
 5990:                 }
 5991:                 if ($noedit{$item}) {
 5992:                     $output .= &mt('From: [_1], to: [_2]',&Apache::lonlocal::locallocaltime($starttime),
 5993:                                                           &Apache::lonlocal::locallocaltime($endtime));
 5994:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 5995:                     next;
 5996:                 }
 5997:                 my $startform =
 5998:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_start_access',$starttime,
 5999:                                       undef,undef,undef,undef,undef,undef,undef,$nolink);
 6000:                 my $endform =
 6001:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_end_access',$endtime,
 6002:                                       undef,undef,undef,undef,undef,undef,undef,$nolink);
 6003:                 $output .= &selfenroll_date_forms($startform,$endform);
 6004:             } elsif ($item eq 'section') {
 6005:                 my $currsec;
 6006:                 if (ref($currsettings) eq 'HASH') {
 6007:                     $currsec = $currsettings->{'selfenroll_section'};
 6008:                 }
 6009:                 my %sections_count = &Apache::loncommon::get_sections($cdom,$cnum);
 6010:                 my $newsecval;
 6011:                 if ($currsec ne 'none' && $currsec ne '') {
 6012:                     if (!defined($sections_count{$currsec})) {
 6013:                         $newsecval = $currsec;
 6014:                     }
 6015:                 }
 6016:                 if ($noedit{$item}) {
 6017:                     if ($currsec ne '') {
 6018:                         $output .= $currsec;
 6019:                     } else {
 6020:                         $output .= &mt('No specific section');
 6021:                     }
 6022:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 6023:                     next;
 6024:                 }
 6025:                 my $sections_select = 
 6026:                     &Apache::lonuserutils::course_sections(\%sections_count,'st',$currsec);
 6027:                 $output .= '<table class="LC_createuser">'."\n".
 6028:                            '<tr class="LC_section_row">'."\n".
 6029:                            '<td align="center">'.&mt('Existing sections')."\n".
 6030:                            '<br />'.$sections_select.'</td><td align="center">'.
 6031:                            &mt('New section').'<br />'."\n".
 6032:                            '<input type="text" name="newsec" size="15" value="'.$newsecval.'" />'."\n".
 6033:                            '<input type="hidden" name="sections" value="" />'."\n".
 6034:                            '</td></tr></table>'."\n";
 6035:             } elsif ($item eq 'approval') {
 6036:                 my ($currnotified,$currapproval,%appchecked);
 6037:                 my %selfdescs = &Apache::lonuserutils::selfenroll_default_descs();
 6038:                 if (ref($currsettings) eq 'HASH') { 
 6039:                     $currnotified = $currsettings->{'selfenroll_notifylist'};
 6040:                     $currapproval = $currsettings->{'selfenroll_approval'};
 6041:                 }
 6042:                 if ($currapproval !~ /^[012]$/) {
 6043:                     $currapproval = 0;
 6044:                 }
 6045:                 if ($noedit{$item}) {
 6046:                     $output .=  $selfdescs{'approval'}{$currapproval}.
 6047:                                 '<br />'.&mt('(Set by Domain Coordinator)');
 6048:                     next;
 6049:                 }
 6050:                 $appchecked{$currapproval} = ' checked="checked"';
 6051:                 for my $i (0..2) {
 6052:                     $output .= '<label>'.
 6053:                                '<input type="radio" name="selfenroll_approval" value="'.$i.'"'.
 6054:                                $appchecked{$i}.' onclick="toggleNotify();" />'.$selfdescs{'approval'}{$i}.
 6055:                                '</label>'.('&nbsp;'x2);
 6056:                 }
 6057:                 my %advhash = &Apache::lonnet::get_course_adv_roles($cid,1);
 6058:                 my (@ccs,%notified);
 6059:                 my $ccrole = 'cc';
 6060:                 if ($crstype eq 'Community') {
 6061:                     $ccrole = 'co';
 6062:                 }
 6063:                 if ($advhash{$ccrole}) {
 6064:                     @ccs = split(/,/,$advhash{$ccrole});
 6065:                 }
 6066:                 if ($currnotified) {
 6067:                     foreach my $current (split(/,/,$currnotified)) {
 6068:                         $notified{$current} = 1;
 6069:                         if (!grep(/^\Q$current\E$/,@ccs)) {
 6070:                             push(@ccs,$current);
 6071:                         }
 6072:                     }
 6073:                 }
 6074:                 if (@ccs) {
 6075:                     my $style;
 6076:                     unless ($currapproval) {
 6077:                         $style = ' style="display: none;"'; 
 6078:                     }
 6079:                     $output .= '<br /><div id="notified"'.$style.'>'.
 6080:                                &mt('Personnel to be notified when an enrollment request needs approval, or has been approved:').'&nbsp;'.
 6081:                                &Apache::loncommon::start_data_table().
 6082:                                &Apache::loncommon::start_data_table_row();
 6083:                     my $count = 0;
 6084:                     my $numcols = 4;
 6085:                     foreach my $cc (sort(@ccs)) {
 6086:                         my $notifyon;
 6087:                         my ($ccuname,$ccudom) = split(/:/,$cc);
 6088:                         if ($notified{$cc}) {
 6089:                             $notifyon = ' checked="checked" ';
 6090:                         }
 6091:                         if ($count && !$count%$numcols) {
 6092:                             $output .= &Apache::loncommon::end_data_table_row().
 6093:                                        &Apache::loncommon::start_data_table_row()
 6094:                         }
 6095:                         $output .= '<td><span class="LC_nobreak"><label>'.
 6096:                                    '<input type="checkbox" name="selfenroll_notify"'.$notifyon.' value="'.$cc.'" />'.
 6097:                                    &Apache::loncommon::plainname($ccuname,$ccudom).
 6098:                                    '</label></span></td>';
 6099:                         $count ++;
 6100:                     }
 6101:                     my $rem = $count%$numcols;
 6102:                     if ($rem) {
 6103:                         my $emptycols = $numcols - $rem;
 6104:                         for (my $i=0; $i<$emptycols; $i++) { 
 6105:                             $output .= '<td>&nbsp;</td>';
 6106:                         }
 6107:                     }
 6108:                     $output .= &Apache::loncommon::end_data_table_row().
 6109:                                &Apache::loncommon::end_data_table().
 6110:                                '</div>';
 6111:                 }
 6112:             } elsif ($item eq 'limit') {
 6113:                 my ($crslimit,$selflimit,$nolimit,$currlim,$currcap);
 6114:                 if (ref($currsettings) eq 'HASH') {
 6115:                     $currlim = $currsettings->{'selfenroll_limit'};
 6116:                     $currcap = $currsettings->{'selfenroll_cap'};
 6117:                 }
 6118:                 if ($noedit{$item}) {
 6119:                     if (($currlim eq 'allstudents') || ($currlim eq 'selfenrolled')) {
 6120:                         if ($currlim eq 'allstudents') {
 6121:                             $output .= &mt('Limit by total students');
 6122:                         } elsif ($currlim eq 'selfenrolled') {
 6123:                             $output .= &mt('Limit by total self-enrolled students');
 6124:                         }
 6125:                         $output .= ' '.&mt('Maximum: [_1]',$currcap).
 6126:                                    '<br />'.&mt('(Set by Domain Coordinator)');
 6127:                     } else {
 6128:                         $output .= &mt('No limit').'<br />'.&mt('(Set by Domain Coordinator)');
 6129:                     }
 6130:                     next;
 6131:                 }
 6132:                 if ($currlim eq 'allstudents') {
 6133:                     $crslimit = ' checked="checked" ';
 6134:                     $selflimit = ' ';
 6135:                     $nolimit = ' ';
 6136:                 } elsif ($currlim eq 'selfenrolled') {
 6137:                     $crslimit = ' ';
 6138:                     $selflimit = ' checked="checked" ';
 6139:                     $nolimit = ' '; 
 6140:                 } else {
 6141:                     $crslimit = ' ';
 6142:                     $selflimit = ' ';
 6143:                     $nolimit = ' checked="checked" ';
 6144:                 }
 6145:                 $output .= '<table><tr><td><label>'.
 6146:                            '<input type="radio" name="selfenroll_limit" value="none"'.$nolimit.'/>'.
 6147:                            &mt('No limit').'</label></td><td><label>'.
 6148:                            '<input type="radio" name="selfenroll_limit" value="allstudents"'.$crslimit.'/>'.
 6149:                            &mt('Limit by total students').'</label></td><td><label>'.
 6150:                            '<input type="radio" name="selfenroll_limit" value="selfenrolled"'.$selflimit.'/>'.
 6151:                            &mt('Limit by total self-enrolled students').
 6152:                            '</td></tr><tr>'.
 6153:                            '<td>&nbsp;</td><td colspan="2"><span class="LC_nobreak">'.
 6154:                            ('&nbsp;'x3).&mt('Maximum number allowed: ').
 6155:                            '<input type="text" name="selfenroll_cap" size = "5" value="'.$currcap.'" /></td></tr></table>';
 6156:             }
 6157:             $output .= &Apache::lonhtmlcommon::row_closure(1);
 6158:         }
 6159:     }
 6160:     $output .= &Apache::lonhtmlcommon::end_pick_box().
 6161:                '<br /><input type="button" name="selfenrollconf" value="'
 6162:                .&mt('Save').'" onclick="validate_types(this.form);" />'
 6163:                .'<input type="hidden" name="action" value="selfenroll" />'
 6164:                .'<input type="hidden" name="state" value="done" />'."\n".
 6165:                $additional.'</form>';
 6166:     $r->print($output);
 6167:     return;
 6168: }
 6169: 
 6170: sub get_noedit_fields {
 6171:     my ($cdom,$cnum,$crstype,$row) = @_;
 6172:     my %noedit;
 6173:     if (ref($row) eq 'ARRAY') {
 6174:         my %settings = &Apache::lonnet::get('environment',['internal.coursecode','internal.textbook',
 6175:                                                            'internal.selfenrollmgrdc',
 6176:                                                            'internal.selfenrollmgrcc'],$cdom,$cnum);
 6177:         my $type = &Apache::lonuserutils::get_extended_type($cdom,$cnum,$crstype,\%settings);
 6178:         my (%specific_managebydc,%specific_managebycc,%default_managebydc);
 6179:         map { $specific_managebydc{$_} = 1; } (split(/,/,$settings{'internal.selfenrollmgrdc'}));
 6180:         map { $specific_managebycc{$_} = 1; } (split(/,/,$settings{'internal.selfenrollmgrcc'}));
 6181:         my %domdefaults = &Apache::lonnet::get_domain_defaults($cdom);
 6182:         map { $default_managebydc{$_} = 1; } (split(/,/,$domdefaults{$type.'selfenrolladmdc'}));
 6183: 
 6184:         foreach my $item (@{$row}) {
 6185:             next if ($specific_managebycc{$item});
 6186:             if (($specific_managebydc{$item}) || ($default_managebydc{$item})) {
 6187:                 $noedit{$item} = 1;
 6188:             }
 6189:         }
 6190:     }
 6191:     return %noedit;
 6192: } 
 6193: 
 6194: sub visible_in_stdcat {
 6195:     my ($cdom,$cnum,$domconf) = @_;
 6196:     my ($cathash,%settable,@vismsgs,$cansetvis,$visible);
 6197:     unless (ref($domconf) eq 'HASH') {
 6198:         return ($visible,$cansetvis,\@vismsgs);
 6199:     }
 6200:     if (ref($domconf->{'coursecategories'}) eq 'HASH') {
 6201:         if ($domconf->{'coursecategories'}{'togglecats'} eq 'crs') {
 6202:             $settable{'togglecats'} = 1;
 6203:         }
 6204:         if ($domconf->{'coursecategories'}{'categorize'} eq 'crs') {
 6205:             $settable{'categorize'} = 1;
 6206:         }
 6207:         $cathash = $domconf->{'coursecategories'}{'cats'};
 6208:     }
 6209:     if ($settable{'togglecats'} && $settable{'categorize'}) {
 6210:         $cansetvis = &mt('You are able to both assign a course category and choose to exclude this course from the catalog.');   
 6211:     } elsif ($settable{'togglecats'}) {
 6212:         $cansetvis = &mt('You are able to choose to exclude this course from the catalog, but only a Domain Coordinator may assign a course category.'); 
 6213:     } elsif ($settable{'categorize'}) {
 6214:         $cansetvis = &mt('You may assign a course category, but only a Domain Coordinator may choose to exclude this course from the catalog.');  
 6215:     } else {
 6216:         $cansetvis = &mt('Only a Domain Coordinator may assign a course category or choose to exclude this course from the catalog.'); 
 6217:     }
 6218:      
 6219:     my %currsettings =
 6220:         &Apache::lonnet::get('environment',['hidefromcat','categories','internal.coursecode'],
 6221:                              $cdom,$cnum);
 6222:     $visible = 0;
 6223:     if ($currsettings{'internal.coursecode'} ne '') {
 6224:         if (ref($domconf->{'coursecategories'}) eq 'HASH') {
 6225:             $cathash = $domconf->{'coursecategories'}{'cats'};
 6226:             if (ref($cathash) eq 'HASH') {
 6227:                 if ($cathash->{'instcode::0'} eq '') {
 6228:                     push(@vismsgs,'dc_addinst'); 
 6229:                 } else {
 6230:                     $visible = 1;
 6231:                 }
 6232:             } else {
 6233:                 $visible = 1;
 6234:             }
 6235:         } else {
 6236:             $visible = 1;
 6237:         }
 6238:     } else {
 6239:         if (ref($cathash) eq 'HASH') {
 6240:             if ($cathash->{'instcode::0'} ne '') {
 6241:                 push(@vismsgs,'dc_instcode');
 6242:             }
 6243:         } else {
 6244:             push(@vismsgs,'dc_instcode');
 6245:         }
 6246:     }
 6247:     if ($currsettings{'categories'} ne '') {
 6248:         my $cathash;
 6249:         if (ref($domconf->{'coursecategories'}) eq 'HASH') {
 6250:             $cathash = $domconf->{'coursecategories'}{'cats'};
 6251:             if (ref($cathash) eq 'HASH') {
 6252:                 if (keys(%{$cathash}) == 0) {
 6253:                     push(@vismsgs,'dc_catalog');
 6254:                 } elsif ((keys(%{$cathash}) == 1) && ($cathash->{'instcode::0'} ne '')) {
 6255:                     push(@vismsgs,'dc_categories');
 6256:                 } else {
 6257:                     my @currcategories = split('&',$currsettings{'categories'});
 6258:                     my $matched = 0;
 6259:                     foreach my $cat (@currcategories) {
 6260:                         if ($cathash->{$cat} ne '') {
 6261:                             $visible = 1;
 6262:                             $matched = 1;
 6263:                             last;
 6264:                         }
 6265:                     }
 6266:                     if (!$matched) {
 6267:                         if ($settable{'categorize'}) { 
 6268:                             push(@vismsgs,'chgcat');
 6269:                         } else {
 6270:                             push(@vismsgs,'dc_chgcat');
 6271:                         }
 6272:                     }
 6273:                 }
 6274:             }
 6275:         }
 6276:     } else {
 6277:         if (ref($cathash) eq 'HASH') {
 6278:             if ((keys(%{$cathash}) > 1) || 
 6279:                 (keys(%{$cathash}) == 1) && ($cathash->{'instcode::0'} eq '')) {
 6280:                 if ($settable{'categorize'}) {
 6281:                     push(@vismsgs,'addcat');
 6282:                 } else {
 6283:                     push(@vismsgs,'dc_addcat');
 6284:                 }
 6285:             }
 6286:         }
 6287:     }
 6288:     if ($currsettings{'hidefromcat'} eq 'yes') {
 6289:         $visible = 0;
 6290:         if ($settable{'togglecats'}) {
 6291:             unshift(@vismsgs,'unhide');
 6292:         } else {
 6293:             unshift(@vismsgs,'dc_unhide')
 6294:         }
 6295:     }
 6296:     return ($visible,$cansetvis,\@vismsgs);
 6297: }
 6298: 
 6299: sub cat_visibility {
 6300:     my %visactions = &Apache::lonlocal::texthash(
 6301:                    vis => 'This course/community currently appears in the Course/Community Catalog for this domain.',
 6302:                    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.',
 6303:                    miss => 'This course/community does not currently appear in the Course/Community Catalog for this domain.',
 6304:                    none => 'Display of a course catalog is disabled for this domain.',
 6305:                    yous => 'You should remedy this if you plan to allow self-enrollment, otherwise students will have difficulty finding this course.',
 6306:                    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.',
 6307:                    make => 'Make any changes to self-enrollment settings below, click "Save", then take action to include the course in the Catalog:',
 6308:                    take => 'Take the following action to ensure the course appears in the Catalog:',
 6309:                    dc_chgconf => 'Ask a domain coordinator to change the Catalog type for this domain.',
 6310:                    dc_setcode => 'Ask a domain coordinator to assign a six character code to the course',
 6311:                    dc_unhide  => 'Ask a domain coordinator to change the "Exclude from course catalog" setting.',
 6312:                    dc_addinst => 'Ask a domain coordinator to enable display the catalog of "Official courses (with institutional codes)".',
 6313:                    dc_instcode => 'Ask a domain coordinator to assign an institutional code (if this is an official course).',
 6314:                    dc_catalog  => 'Ask a domain coordinator to enable or create at least one course category in the domain.',
 6315:                    dc_categories => 'Ask a domain coordinator to create a hierarchy of categories and sub categories for courses in the domain.',
 6316:                    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',
 6317:                    dc_addcat => 'Ask a domain coordinator to assign a category to the course.',
 6318:     );
 6319:     $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>"');
 6320:     $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>"');
 6321:     $visactions{'addcat'} = &mt('Use [_1]Categorize course[_2] to assign a category to the course.','"<a href="/adm/courseprefs?phase=display&actions=courseinfo">','</a>"');
 6322:     return \%visactions;
 6323: }
 6324: 
 6325: sub new_selfenroll_dom_row {
 6326:     my ($newdom,$num) = @_;
 6327:     my $domdesc = &Apache::lonnet::domain($newdom);
 6328:     my $output;
 6329:     if ($domdesc ne '') {
 6330:         $output .= &Apache::loncommon::start_data_table_row()
 6331:                    .'<td valign="top"><span class="LC_nobreak">'.&mt('Domain:').'&nbsp;<b>'.$domdesc
 6332:                    .' ('.$newdom.')</b><input type="hidden" name="selfenroll_dom_'.$num
 6333:                    .'" value="'.$newdom.'" /></span><br />'
 6334:                    .'<span class="LC_nobreak"><label><input type="checkbox" '
 6335:                    .'name="selfenroll_activate" value="'.$num.'" '
 6336:                    .'onchange="javascript:update_types('
 6337:                    ."'selfenroll_activate','$num'".');" />'
 6338:                    .&mt('Activate').'</label></span></td>';
 6339:         my @currinsttypes;
 6340:         $output .= '<td>'.&mt('User types:').'<br />'
 6341:                    .&selfenroll_inst_types($num,$newdom,\@currinsttypes).'</td>'
 6342:                    .&Apache::loncommon::end_data_table_row();
 6343:     }
 6344:     return $output;
 6345: }
 6346: 
 6347: sub selfenroll_inst_types {
 6348:     my ($num,$currdom,$currinsttypes) = @_;
 6349:     my $output;
 6350:     my $numinrow = 4;
 6351:     my $count = 0;
 6352:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($currdom);
 6353:     my $othervalue = 'any';
 6354:     if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 6355:         if (keys(%{$usertypes}) > 0) {
 6356:             $othervalue = 'other';
 6357:         }
 6358:         $output .= '<table><tr>';
 6359:         foreach my $type (@{$types}) {
 6360:             if (($count > 0) && ($count%$numinrow == 0)) {
 6361:                 $output .= '</tr><tr>';
 6362:             }
 6363:             if (defined($usertypes->{$type})) {
 6364:                 my $esc_type = &escape($type);
 6365:                 $output .= '<td><span class="LC_nobreak"><label><input type = "checkbox" value="'.
 6366:                            $esc_type.'" ';
 6367:                 if (ref($currinsttypes) eq 'ARRAY') {
 6368:                     if (@{$currinsttypes} > 0) {
 6369:                         if (grep(/^any$/,@{$currinsttypes})) {
 6370:                             $output .= 'checked="checked"';
 6371:                         } elsif (grep(/^\Q$esc_type\E$/,@{$currinsttypes})) {
 6372:                             $output .= 'checked="checked"';
 6373:                         }
 6374:                     } else {
 6375:                         $output .= 'checked="checked"';
 6376:                     }
 6377:                 }
 6378:                 $output .= ' name="selfenroll_types_'.$num.'" />'.$usertypes->{$type}.'</label></span></td>';
 6379:             }
 6380:             $count ++;
 6381:         }
 6382:         if (($count > 0) && ($count%$numinrow == 0)) {
 6383:             $output .= '</tr><tr>';
 6384:         }
 6385:         $output .= '<td><span class="LC_nobreak"><label><input type = "checkbox" value="'.$othervalue.'"';
 6386:         if (ref($currinsttypes) eq 'ARRAY') {
 6387:             if (@{$currinsttypes} > 0) {
 6388:                 if (grep(/^any$/,@{$currinsttypes})) { 
 6389:                     $output .= ' checked="checked"';
 6390:                 } elsif ($othervalue eq 'other') {
 6391:                     if (grep(/^\Q$othervalue\E$/,@{$currinsttypes})) {
 6392:                         $output .= ' checked="checked"';
 6393:                     }
 6394:                 }
 6395:             } else {
 6396:                 $output .= ' checked="checked"';
 6397:             }
 6398:         } else {
 6399:             $output .= ' checked="checked"';
 6400:         }
 6401:         $output .= ' name="selfenroll_types_'.$num.'" />'.$othertitle.'</label></span></td></tr></table>';
 6402:     }
 6403:     return $output;
 6404: }
 6405: 
 6406: sub selfenroll_date_forms {
 6407:     my ($startform,$endform) = @_;
 6408:     my $output .= &Apache::lonhtmlcommon::start_pick_box()."\n".
 6409:                   &Apache::lonhtmlcommon::row_title(&mt('Start date'),
 6410:                                                     'LC_oddrow_value')."\n".
 6411:                   $startform."\n".
 6412:                   &Apache::lonhtmlcommon::row_closure(1).
 6413:                   &Apache::lonhtmlcommon::row_title(&mt('End date'),
 6414:                                                    'LC_oddrow_value')."\n".
 6415:                   $endform."\n".
 6416:                   &Apache::lonhtmlcommon::row_closure(1).
 6417:                   &Apache::lonhtmlcommon::end_pick_box();
 6418:     return $output;
 6419: }
 6420: 
 6421: sub print_userchangelogs_display {
 6422:     my ($r,$context,$permission) = @_;
 6423:     my $formname = 'rolelog';
 6424:     my ($username,$domain,$crstype,%roleslog);
 6425:     if ($context eq 'domain') {
 6426:         $domain = $env{'request.role.domain'};
 6427:         %roleslog=&Apache::lonnet::dump_dom('nohist_rolelog',$domain);
 6428:     } else {
 6429:         if ($context eq 'course') { 
 6430:             $domain = $env{'course.'.$env{'request.course.id'}.'.domain'};
 6431:             $username = $env{'course.'.$env{'request.course.id'}.'.num'};
 6432:             $crstype = &Apache::loncommon::course_type();
 6433:             my %saveable_parameters = ('show' => 'scalar',);
 6434:             &Apache::loncommon::store_course_settings('roles_log',
 6435:                                                       \%saveable_parameters);
 6436:             &Apache::loncommon::restore_course_settings('roles_log',
 6437:                                                         \%saveable_parameters);
 6438:         } elsif ($context eq 'author') {
 6439:             $domain = $env{'user.domain'}; 
 6440:             if ($env{'request.role'} =~ m{^au\./\Q$domain\E/$}) {
 6441:                 $username = $env{'user.name'};
 6442:             } else {
 6443:                 undef($domain);
 6444:             }
 6445:         }
 6446:         if ($domain ne '' && $username ne '') { 
 6447:             %roleslog=&Apache::lonnet::dump('nohist_rolelog',$domain,$username);
 6448:         }
 6449:     }
 6450:     if ((keys(%roleslog))[0]=~/^error\:/) { undef(%roleslog); }
 6451: 
 6452:     # set defaults
 6453:     my $now = time();
 6454:     my $defstart = $now - (7*24*3600); #7 days ago 
 6455:     my %defaults = (
 6456:                      page               => '1',
 6457:                      show               => '10',
 6458:                      role               => 'any',
 6459:                      chgcontext         => 'any',
 6460:                      rolelog_start_date => $defstart,
 6461:                      rolelog_end_date   => $now,
 6462:                    );
 6463:     my $more_records = 0;
 6464: 
 6465:     # set current
 6466:     my %curr;
 6467:     foreach my $item ('show','page','role','chgcontext') {
 6468:         $curr{$item} = $env{'form.'.$item};
 6469:     }
 6470:     my ($startdate,$enddate) = 
 6471:         &Apache::lonuserutils::get_dates_from_form('rolelog_start_date','rolelog_end_date');
 6472:     $curr{'rolelog_start_date'} = $startdate;
 6473:     $curr{'rolelog_end_date'} = $enddate;
 6474:     foreach my $key (keys(%defaults)) {
 6475:         if ($curr{$key} eq '') {
 6476:             $curr{$key} = $defaults{$key};
 6477:         }
 6478:     }
 6479:     my (%whodunit,%changed,$version);
 6480:     ($version) = ($r->dir_config('lonVersion') =~ /^([\d\.]+)\-/);
 6481:     my ($minshown,$maxshown);
 6482:     $minshown = 1;
 6483:     my $count = 0;
 6484:     if ($curr{'show'} ne &mt('all')) { 
 6485:         $maxshown = $curr{'page'} * $curr{'show'};
 6486:         if ($curr{'page'} > 1) {
 6487:             $minshown = 1 + ($curr{'page'} - 1) * $curr{'show'};
 6488:         }
 6489:     }
 6490: 
 6491:     # Form Header
 6492:     $r->print('<form action="/adm/createuser" method="post" name="'.$formname.'">'.
 6493:               &role_display_filter($context,$formname,$domain,$username,\%curr,
 6494:                                    $version,$crstype));
 6495: 
 6496:     # Create navigation
 6497:     my ($nav_script,$nav_links) = &userlogdisplay_nav($formname,\%curr,$more_records);
 6498:     my $showntableheader = 0;
 6499: 
 6500:     # Table Header
 6501:     my $tableheader = 
 6502:         &Apache::loncommon::start_data_table_header_row()
 6503:        .'<th>&nbsp;</th>'
 6504:        .'<th>'.&mt('When').'</th>'
 6505:        .'<th>'.&mt('Who made the change').'</th>'
 6506:        .'<th>'.&mt('Changed User').'</th>'
 6507:        .'<th>'.&mt('Role').'</th>';
 6508: 
 6509:     if ($context eq 'course') {
 6510:         $tableheader .= '<th>'.&mt('Section').'</th>';
 6511:     }
 6512:     $tableheader .=
 6513:         '<th>'.&mt('Context').'</th>'
 6514:        .'<th>'.&mt('Start').'</th>'
 6515:        .'<th>'.&mt('End').'</th>'
 6516:        .&Apache::loncommon::end_data_table_header_row();
 6517: 
 6518:     # Display user change log data
 6519:     foreach my $id (sort { $roleslog{$b}{'exe_time'}<=>$roleslog{$a}{'exe_time'} } (keys(%roleslog))) {
 6520:         next if (($roleslog{$id}{'exe_time'} < $curr{'rolelog_start_date'}) ||
 6521:                  ($roleslog{$id}{'exe_time'} > $curr{'rolelog_end_date'}));
 6522:         if ($curr{'show'} ne &mt('all')) {
 6523:             if ($count >= $curr{'page'} * $curr{'show'}) {
 6524:                 $more_records = 1;
 6525:                 last;
 6526:             }
 6527:         }
 6528:         if ($curr{'role'} ne 'any') {
 6529:             next if ($roleslog{$id}{'logentry'}{'role'} ne $curr{'role'}); 
 6530:         }
 6531:         if ($curr{'chgcontext'} ne 'any') {
 6532:             if ($curr{'chgcontext'} eq 'selfenroll') {
 6533:                 next if (!$roleslog{$id}{'logentry'}{'selfenroll'});
 6534:             } else {
 6535:                 next if ($roleslog{$id}{'logentry'}{'context'} ne $curr{'chgcontext'});
 6536:             }
 6537:         }
 6538:         $count ++;
 6539:         next if ($count < $minshown);
 6540:         unless ($showntableheader) {
 6541:             $r->print($nav_script
 6542:                      .$nav_links
 6543:                      .&Apache::loncommon::start_data_table()
 6544:                      .$tableheader);
 6545:             $r->rflush();
 6546:             $showntableheader = 1;
 6547:         }
 6548:         if ($whodunit{$roleslog{$id}{'exe_uname'}.':'.$roleslog{$id}{'exe_udom'}} eq '') {
 6549:             $whodunit{$roleslog{$id}{'exe_uname'}.':'.$roleslog{$id}{'exe_udom'}} =
 6550:                 &Apache::loncommon::plainname($roleslog{$id}{'exe_uname'},$roleslog{$id}{'exe_udom'});
 6551:         }
 6552:         if ($changed{$roleslog{$id}{'uname'}.':'.$roleslog{$id}{'udom'}} eq '') {
 6553:             $changed{$roleslog{$id}{'uname'}.':'.$roleslog{$id}{'udom'}} =
 6554:                 &Apache::loncommon::plainname($roleslog{$id}{'uname'},$roleslog{$id}{'udom'});
 6555:         }
 6556:         my $sec = $roleslog{$id}{'logentry'}{'section'};
 6557:         if ($sec eq '') {
 6558:             $sec = &mt('None');
 6559:         }
 6560:         my ($rolestart,$roleend);
 6561:         if ($roleslog{$id}{'delflag'}) {
 6562:             $rolestart = &mt('deleted');
 6563:             $roleend = &mt('deleted');
 6564:         } else {
 6565:             $rolestart = $roleslog{$id}{'logentry'}{'start'};
 6566:             $roleend = $roleslog{$id}{'logentry'}{'end'};
 6567:             if ($rolestart eq '' || $rolestart == 0) {
 6568:                 $rolestart = &mt('No start date'); 
 6569:             } else {
 6570:                 $rolestart = &Apache::lonlocal::locallocaltime($rolestart);
 6571:             }
 6572:             if ($roleend eq '' || $roleend == 0) { 
 6573:                 $roleend = &mt('No end date');
 6574:             } else {
 6575:                 $roleend = &Apache::lonlocal::locallocaltime($roleend);
 6576:             }
 6577:         }
 6578:         my $chgcontext = $roleslog{$id}{'logentry'}{'context'};
 6579:         if ($roleslog{$id}{'logentry'}{'selfenroll'}) {
 6580:             $chgcontext = 'selfenroll';
 6581:         }
 6582:         my %lt = &rolechg_contexts($context,$crstype);
 6583:         if ($chgcontext ne '' && $lt{$chgcontext} ne '') {
 6584:             $chgcontext = $lt{$chgcontext};
 6585:         }
 6586:         $r->print(
 6587:             &Apache::loncommon::start_data_table_row()
 6588:            .'<td>'.$count.'</td>'
 6589:            .'<td>'.&Apache::lonlocal::locallocaltime($roleslog{$id}{'exe_time'}).'</td>'
 6590:            .'<td>'.$whodunit{$roleslog{$id}{'exe_uname'}.':'.$roleslog{$id}{'exe_udom'}}.'</td>'
 6591:            .'<td>'.$changed{$roleslog{$id}{'uname'}.':'.$roleslog{$id}{'udom'}}.'</td>'
 6592:            .'<td>'.&Apache::lonnet::plaintext($roleslog{$id}{'logentry'}{'role'},$crstype).'</td>');
 6593:         if ($context eq 'course') { 
 6594:             $r->print('<td>'.$sec.'</td>');
 6595:         }
 6596:         $r->print(
 6597:             '<td>'.$chgcontext.'</td>'
 6598:            .'<td>'.$rolestart.'</td>'
 6599:            .'<td>'.$roleend.'</td>'
 6600:            .&Apache::loncommon::end_data_table_row()."\n");
 6601:     }
 6602: 
 6603:     if ($showntableheader) { # Table footer, if content displayed above
 6604:         $r->print(&Apache::loncommon::end_data_table()
 6605:                  .$nav_links);
 6606:     } else { # No content displayed above
 6607:         $r->print('<p class="LC_info">'
 6608:                  .&mt('There are no records to display.')
 6609:                  .'</p>'
 6610:         );
 6611:     }
 6612: 
 6613:     # Form Footer
 6614:     $r->print( 
 6615:         '<input type="hidden" name="page" value="'.$curr{'page'}.'" />'
 6616:        .'<input type="hidden" name="action" value="changelogs" />'
 6617:        .'</form>');
 6618:     return;
 6619: }
 6620: 
 6621: sub userlogdisplay_nav {
 6622:     my ($formname,$curr,$more_records) = @_;
 6623:     my ($nav_script,$nav_links);
 6624:     if (ref($curr) eq 'HASH') {
 6625:         # Create Navigation:
 6626:         # Navigation Script
 6627:         $nav_script = <<"ENDSCRIPT";
 6628: <script type="text/javascript">
 6629: // <![CDATA[
 6630: function chgPage(caller) {
 6631:     if (caller == 'previous') {
 6632:         document.$formname.page.value --;
 6633:     }
 6634:     if (caller == 'next') {
 6635:         document.$formname.page.value ++;
 6636:     }
 6637:     document.$formname.submit();
 6638:     return;
 6639: }
 6640: // ]]>
 6641: </script>
 6642: ENDSCRIPT
 6643:         # Navigation Buttons
 6644:         $nav_links = '<p>';
 6645:         if (($curr->{'page'} > 1) || ($more_records)) {
 6646:             if ($curr->{'page'} > 1) {
 6647:                 $nav_links .= '<input type="button"'
 6648:                              .' onclick="javascript:chgPage('."'previous'".');"'
 6649:                              .' value="'.&mt('Previous [_1] changes',$curr->{'show'})
 6650:                              .'" /> ';
 6651:             }
 6652:             if ($more_records) {
 6653:                 $nav_links .= '<input type="button"'
 6654:                              .' onclick="javascript:chgPage('."'next'".');"'
 6655:                              .' value="'.&mt('Next [_1] changes',$curr->{'show'})
 6656:                              .'" />';
 6657:             }
 6658:         }
 6659:         $nav_links .= '</p>';
 6660:     }
 6661:     return ($nav_script,$nav_links);
 6662: }
 6663: 
 6664: sub role_display_filter {
 6665:     my ($context,$formname,$cdom,$cnum,$curr,$version,$crstype) = @_;
 6666:     my $lctype;
 6667:     if ($context eq 'course') {
 6668:         $lctype = lc($crstype);
 6669:     }
 6670:     my $nolink = 1;
 6671:     my $output = '<table><tr><td valign="top">'.
 6672:                  '<span class="LC_nobreak"><b>'.&mt('Changes/page:').'</b></span><br />'.
 6673:                  &Apache::lonmeta::selectbox('show',$curr->{'show'},undef,
 6674:                                               (&mt('all'),5,10,20,50,100,1000,10000)).
 6675:                  '</td><td>&nbsp;&nbsp;</td>';
 6676:     my $startform =
 6677:         &Apache::lonhtmlcommon::date_setter($formname,'rolelog_start_date',
 6678:                                             $curr->{'rolelog_start_date'},undef,
 6679:                                             undef,undef,undef,undef,undef,undef,$nolink);
 6680:     my $endform =
 6681:         &Apache::lonhtmlcommon::date_setter($formname,'rolelog_end_date',
 6682:                                             $curr->{'rolelog_end_date'},undef,
 6683:                                             undef,undef,undef,undef,undef,undef,$nolink);
 6684:     my %lt = &rolechg_contexts($context,$crstype);
 6685:     $output .= '<td valign="top"><b>'.&mt('Window during which changes occurred:').'</b><br />'.
 6686:                '<table><tr><td>'.&mt('After:').
 6687:                '</td><td>'.$startform.'</td></tr>'.
 6688:                '<tr><td>'.&mt('Before:').'</td>'.
 6689:                '<td>'.$endform.'</td></tr></table>'.
 6690:                '</td>'.
 6691:                '<td>&nbsp;&nbsp;</td>'.
 6692:                '<td valign="top"><b>'.&mt('Role:').'</b><br />'.
 6693:                '<select name="role"><option value="any"';
 6694:     if ($curr->{'role'} eq 'any') {
 6695:         $output .= ' selected="selected"';
 6696:     }
 6697:     $output .=  '>'.&mt('Any').'</option>'."\n";
 6698:     my @roles = &Apache::lonuserutils::roles_by_context($context,1,$crstype);
 6699:     foreach my $role (@roles) {
 6700:         my $plrole;
 6701:         if ($role eq 'cr') {
 6702:             $plrole = &mt('Custom Role');
 6703:         } else {
 6704:             $plrole=&Apache::lonnet::plaintext($role,$crstype);
 6705:         }
 6706:         my $selstr = '';
 6707:         if ($role eq $curr->{'role'}) {
 6708:             $selstr = ' selected="selected"';
 6709:         }
 6710:         $output .= '  <option value="'.$role.'"'.$selstr.'>'.$plrole.'</option>';
 6711:     }
 6712:     $output .= '</select></td>'.
 6713:                '<td>&nbsp;&nbsp;</td>'.
 6714:                '<td valign="top"><b>'.
 6715:                &mt('Context:').'</b><br /><select name="chgcontext">';
 6716:     my @posscontexts;
 6717:     if ($context eq 'course') {
 6718:         @posscontexts = ('any','automated','updatenow','createcourse','course','domain','selfenroll','requestcourses');
 6719:     } elsif ($context eq 'domain') {
 6720:         @posscontexts = ('any','domain','requestauthor','domconfig','server');
 6721:     } else {
 6722:         @posscontexts = ('any','author','domain');
 6723:     } 
 6724:     foreach my $chgtype (@posscontexts) {
 6725:         my $selstr = '';
 6726:         if ($curr->{'chgcontext'} eq $chgtype) {
 6727:             $selstr = ' selected="selected"';
 6728:         }
 6729:         if ($context eq 'course') {
 6730:             if (($chgtype eq 'automated') || ($chgtype eq 'updatenow')) {
 6731:                 next if (!&Apache::lonnet::auto_run($cnum,$cdom));
 6732:             }
 6733:         }
 6734:         $output .= '<option value="'.$chgtype.'"'.$selstr.'>'.$lt{$chgtype}.'</option>'."\n";
 6735:     }
 6736:     $output .= '</select></td>'
 6737:               .'</tr></table>';
 6738: 
 6739:     # Update Display button
 6740:     $output .= '<p>'
 6741:               .'<input type="submit" value="'.&mt('Update Display').'" />'
 6742:               .'</p>';
 6743: 
 6744:     # Server version info
 6745:     my $needsrev = '2.11.0';
 6746:     if ($context eq 'course') {
 6747:         $needsrev = '2.7.0';
 6748:     }
 6749:     
 6750:     $output .= '<p class="LC_info">'
 6751:               .&mt('Only changes made from servers running LON-CAPA [_1] or later are displayed.'
 6752:                   ,$needsrev);
 6753:     if ($version) {
 6754:         $output .= ' '.&mt('This LON-CAPA server is version [_1]',$version);
 6755:     }
 6756:     $output .= '</p><hr />';
 6757:     return $output;
 6758: }
 6759: 
 6760: sub rolechg_contexts {
 6761:     my ($context,$crstype) = @_;
 6762:     my %lt;
 6763:     if ($context eq 'course') {
 6764:         %lt = &Apache::lonlocal::texthash (
 6765:                                              any          => 'Any',
 6766:                                              automated    => 'Automated Enrollment',
 6767:                                              updatenow    => 'Roster Update',
 6768:                                              createcourse => 'Course Creation',
 6769:                                              course       => 'User Management in course',
 6770:                                              domain       => 'User Management in domain',
 6771:                                              selfenroll   => 'Self-enrolled',
 6772:                                              requestcourses => 'Course Request',
 6773:                                          );
 6774:         if ($crstype eq 'Community') {
 6775:             $lt{'createcourse'} = &mt('Community Creation');
 6776:             $lt{'course'} = &mt('User Management in community');
 6777:             $lt{'requestcourses'} = &mt('Community Request');
 6778:         }
 6779:     } elsif ($context eq 'domain') {
 6780:         %lt = &Apache::lonlocal::texthash (
 6781:                                              any           => 'Any',
 6782:                                              domain        => 'User Management in domain',
 6783:                                              requestauthor => 'Authoring Request',
 6784:                                              server        => 'Command line script (DC role)',
 6785:                                              domconfig     => 'Self-enrolled',
 6786:                                          );
 6787:     } else {
 6788:         %lt = &Apache::lonlocal::texthash (
 6789:                                              any    => 'Any',
 6790:                                              domain => 'User Management in domain',
 6791:                                              author => 'User Management by author',
 6792:                                          );
 6793:     } 
 6794:     return %lt;
 6795: }
 6796: 
 6797: #-------------------------------------------------- functions for &phase_two
 6798: sub user_search_result {
 6799:     my ($context,$srch) = @_;
 6800:     my %allhomes;
 6801:     my %inst_matches;
 6802:     my %srch_results;
 6803:     my ($response,$currstate,$forcenewuser,$dirsrchres);
 6804:     $srch->{'srchterm'} =~ s/\s+/ /g;
 6805:     if ($srch->{'srchby'} !~ /^(uname|lastname|lastfirst)$/) {
 6806:         $response = &mt('Invalid search.');
 6807:     }
 6808:     if ($srch->{'srchin'} !~ /^(crs|dom|alc|instd)$/) {
 6809:         $response = &mt('Invalid search.');
 6810:     }
 6811:     if ($srch->{'srchtype'} !~ /^(exact|contains|begins)$/) {
 6812:         $response = &mt('Invalid search.');
 6813:     }
 6814:     if ($srch->{'srchterm'} eq '') {
 6815:         $response = &mt('You must enter a search term.');
 6816:     }
 6817:     if ($srch->{'srchterm'} =~ /^\s+$/) {
 6818:         $response = &mt('Your search term must contain more than just spaces.');
 6819:     }
 6820:     if (($srch->{'srchin'} eq 'dom') || ($srch->{'srchin'} eq 'instd')) {
 6821:         if (($srch->{'srchdomain'} eq '') || 
 6822: 	    ! (&Apache::lonnet::domain($srch->{'srchdomain'}))) {
 6823:             $response = &mt('You must specify a valid domain when searching in a domain or institutional directory.')
 6824:         }
 6825:     }
 6826:     if (($srch->{'srchin'} eq 'dom') || ($srch->{'srchin'} eq 'crs') ||
 6827:         ($srch->{'srchin'} eq 'alc')) {
 6828:         if ($srch->{'srchby'} eq 'uname') {
 6829:             my $unamecheck = $srch->{'srchterm'};
 6830:             if ($srch->{'srchtype'} eq 'contains') {
 6831:                 if ($unamecheck !~ /^\w/) {
 6832:                     $unamecheck = 'a'.$unamecheck; 
 6833:                 }
 6834:             }
 6835:             if ($unamecheck !~ /^$match_username$/) {
 6836:                 $response = &mt('You must specify a valid username. Only the following are allowed: letters numbers - . @');
 6837:             }
 6838:         }
 6839:     }
 6840:     if ($response ne '') {
 6841:         $response = '<span class="LC_warning">'.$response.'</span>';
 6842:     }
 6843:     if ($srch->{'srchin'} eq 'instd') {
 6844:         my $instd_chk = &instdirectorysrch_check($srch);
 6845:         if ($instd_chk ne 'ok') {
 6846:             my $domd_chk = &domdirectorysrch_check($srch);
 6847:             $response = '<span class="LC_warning">'.$instd_chk.'</span><br />';
 6848:             if ($domd_chk eq 'ok') {
 6849:                 $response = &mt('You may want to search in the LON-CAPA domain instead of the institutional directory.');
 6850:             }
 6851:             $response .= '<br /><br />';
 6852:         }
 6853:     } else {
 6854:         unless (($context eq 'requestcrs') && ($srch->{'srchtype'} eq 'exact')) { 
 6855:             my $domd_chk = &domdirectorysrch_check($srch);
 6856:             if ($domd_chk ne 'ok') {
 6857:                 my $instd_chk = &instdirectorysrch_check($srch);
 6858:                 $response = '<span class="LC_warning">'.$domd_chk.'</span><br />';
 6859:                 if ($instd_chk eq 'ok') {
 6860:                     $response = &mt('You may want to search in the institutional directory instead of the LON-CAPA domain.');
 6861:                 }
 6862:                 $response .= '<br /><br />';
 6863:             }
 6864:         }
 6865:     }
 6866:     if ($response ne '') {
 6867:         return ($currstate,$response);
 6868:     }
 6869:     if ($srch->{'srchby'} eq 'uname') {
 6870:         if (($srch->{'srchin'} eq 'dom') || ($srch->{'srchin'} eq 'crs')) {
 6871:             if ($env{'form.forcenew'}) {
 6872:                 if ($srch->{'srchdomain'} ne $env{'request.role.domain'}) {
 6873:                     my $uhome=&Apache::lonnet::homeserver($srch->{'srchterm'},$srch->{'srchdomain'});
 6874:                     if ($uhome eq 'no_host') {
 6875:                         my $domdesc = &Apache::lonnet::domain($env{'request.role.domain'},'description');
 6876:                         my $showdom = &display_domain_info($env{'request.role.domain'});
 6877:                         $response = &mt('New users can only be created in the domain to which your current role belongs - [_1].',$showdom);
 6878:                     } else {
 6879:                         $currstate = 'modify';
 6880:                     }
 6881:                 } else {
 6882:                     $currstate = 'modify';
 6883:                 }
 6884:             } else {
 6885:                 if ($srch->{'srchin'} eq 'dom') {
 6886:                     if ($srch->{'srchtype'} eq 'exact') {
 6887:                         my $uhome=&Apache::lonnet::homeserver($srch->{'srchterm'},$srch->{'srchdomain'});
 6888:                         if ($uhome eq 'no_host') {
 6889:                             ($currstate,$response,$forcenewuser) =
 6890:                                 &build_search_response($context,$srch,%srch_results);
 6891:                         } else {
 6892:                             $currstate = 'modify';
 6893:                             my $uname = $srch->{'srchterm'};
 6894:                             my $udom = $srch->{'srchdomain'};
 6895:                             $srch_results{$uname.':'.$udom} =
 6896:                                 { &Apache::lonnet::get('environment',
 6897:                                                        ['firstname',
 6898:                                                         'lastname',
 6899:                                                         'permanentemail'],
 6900:                                                          $udom,$uname)
 6901:                                 };
 6902:                         }
 6903:                     } else {
 6904:                         %srch_results = &Apache::lonnet::usersearch($srch);
 6905:                         ($currstate,$response,$forcenewuser) =
 6906:                             &build_search_response($context,$srch,%srch_results);
 6907:                     }
 6908:                 } else {
 6909:                     my $courseusers = &get_courseusers();
 6910:                     if ($srch->{'srchtype'} eq 'exact') {
 6911:                         if (exists($courseusers->{$srch->{'srchterm'}.':'.$srch->{'srchdomain'}})) {
 6912:                             $currstate = 'modify';
 6913:                         } else {
 6914:                             ($currstate,$response,$forcenewuser) =
 6915:                                 &build_search_response($context,$srch,%srch_results);
 6916:                         }
 6917:                     } else {
 6918:                         foreach my $user (keys(%$courseusers)) {
 6919:                             my ($cuname,$cudomain) = split(/:/,$user);
 6920:                             if ($cudomain eq $srch->{'srchdomain'}) {
 6921:                                 my $matched = 0;
 6922:                                 if ($srch->{'srchtype'} eq 'begins') {
 6923:                                     if ($cuname =~ /^\Q$srch->{'srchterm'}\E/i) {
 6924:                                         $matched = 1;
 6925:                                     }
 6926:                                 } else {
 6927:                                     if ($cuname =~ /\Q$srch->{'srchterm'}\E/i) {
 6928:                                         $matched = 1;
 6929:                                     }
 6930:                                 }
 6931:                                 if ($matched) {
 6932:                                     $srch_results{$user} = 
 6933: 					{&Apache::lonnet::get('environment',
 6934: 							     ['firstname',
 6935: 							      'lastname',
 6936: 							      'permanentemail'],
 6937: 							      $cudomain,$cuname)};
 6938:                                 }
 6939:                             }
 6940:                         }
 6941:                         ($currstate,$response,$forcenewuser) =
 6942:                             &build_search_response($context,$srch,%srch_results);
 6943:                     }
 6944:                 }
 6945:             }
 6946:         } elsif ($srch->{'srchin'} eq 'alc') {
 6947:             $currstate = 'query';
 6948:         } elsif ($srch->{'srchin'} eq 'instd') {
 6949:             ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query($srch);
 6950:             if ($dirsrchres eq 'ok') {
 6951:                 ($currstate,$response,$forcenewuser) = 
 6952:                     &build_search_response($context,$srch,%srch_results);
 6953:             } else {
 6954:                 my $showdom = &display_domain_info($srch->{'srchdomain'});
 6955:                 $response = '<span class="LC_warning">'.
 6956:                     &mt('Institutional directory search is not available in domain: [_1]',$showdom).
 6957:                     '</span><br />'.
 6958:                     &mt('You may want to search in the LON-CAPA domain instead of the institutional directory.').
 6959:                     '<br /><br />'; 
 6960:             }
 6961:         }
 6962:     } else {
 6963:         if ($srch->{'srchin'} eq 'dom') {
 6964:             %srch_results = &Apache::lonnet::usersearch($srch);
 6965:             ($currstate,$response,$forcenewuser) = 
 6966:                 &build_search_response($context,$srch,%srch_results); 
 6967:         } elsif ($srch->{'srchin'} eq 'crs') {
 6968:             my $courseusers = &get_courseusers(); 
 6969:             foreach my $user (keys(%$courseusers)) {
 6970:                 my ($uname,$udom) = split(/:/,$user);
 6971:                 my %names = &Apache::loncommon::getnames($uname,$udom);
 6972:                 my %emails = &Apache::loncommon::getemails($uname,$udom);
 6973:                 if ($srch->{'srchby'} eq 'lastname') {
 6974:                     if ((($srch->{'srchtype'} eq 'exact') && 
 6975:                          ($names{'lastname'} eq $srch->{'srchterm'})) || 
 6976:                         (($srch->{'srchtype'} eq 'begins') &&
 6977:                          ($names{'lastname'} =~ /^\Q$srch->{'srchterm'}\E/i)) ||
 6978:                         (($srch->{'srchtype'} eq 'contains') &&
 6979:                          ($names{'lastname'} =~ /\Q$srch->{'srchterm'}\E/i))) {
 6980:                         $srch_results{$user} = {firstname => $names{'firstname'},
 6981:                                             lastname => $names{'lastname'},
 6982:                                             permanentemail => $emails{'permanentemail'},
 6983:                                            };
 6984:                     }
 6985:                 } elsif ($srch->{'srchby'} eq 'lastfirst') {
 6986:                     my ($srchlast,$srchfirst) = split(/,/,$srch->{'srchterm'});
 6987:                     $srchlast =~ s/\s+$//;
 6988:                     $srchfirst =~ s/^\s+//;
 6989:                     if ($srch->{'srchtype'} eq 'exact') {
 6990:                         if (($names{'lastname'} eq $srchlast) &&
 6991:                             ($names{'firstname'} eq $srchfirst)) {
 6992:                             $srch_results{$user} = {firstname => $names{'firstname'},
 6993:                                                 lastname => $names{'lastname'},
 6994:                                                 permanentemail => $emails{'permanentemail'},
 6995: 
 6996:                                            };
 6997:                         }
 6998:                     } elsif ($srch->{'srchtype'} eq 'begins') {
 6999:                         if (($names{'lastname'} =~ /^\Q$srchlast\E/i) &&
 7000:                             ($names{'firstname'} =~ /^\Q$srchfirst\E/i)) {
 7001:                             $srch_results{$user} = {firstname => $names{'firstname'},
 7002:                                                 lastname => $names{'lastname'},
 7003:                                                 permanentemail => $emails{'permanentemail'},
 7004:                                                };
 7005:                         }
 7006:                     } else {
 7007:                         if (($names{'lastname'} =~ /\Q$srchlast\E/i) && 
 7008:                             ($names{'firstname'} =~ /\Q$srchfirst\E/i)) {
 7009:                             $srch_results{$user} = {firstname => $names{'firstname'},
 7010:                                                 lastname => $names{'lastname'},
 7011:                                                 permanentemail => $emails{'permanentemail'},
 7012:                                                };
 7013:                         }
 7014:                     }
 7015:                 }
 7016:             }
 7017:             ($currstate,$response,$forcenewuser) = 
 7018:                 &build_search_response($context,$srch,%srch_results); 
 7019:         } elsif ($srch->{'srchin'} eq 'alc') {
 7020:             $currstate = 'query';
 7021:         } elsif ($srch->{'srchin'} eq 'instd') {
 7022:             ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query($srch); 
 7023:             if ($dirsrchres eq 'ok') {
 7024:                 ($currstate,$response,$forcenewuser) = 
 7025:                     &build_search_response($context,$srch,%srch_results);
 7026:             } else {
 7027:                 my $showdom = &display_domain_info($srch->{'srchdomain'});
 7028:                 $response = '<span class="LC_warning">'.
 7029:                     &mt('Institutional directory search is not available in domain: [_1]',$showdom).
 7030:                     '</span><br />'.
 7031:                     &mt('You may want to search in the LON-CAPA domain instead of the institutional directory.').
 7032:                     '<br /><br />';
 7033:             }
 7034:         }
 7035:     }
 7036:     return ($currstate,$response,$forcenewuser,\%srch_results);
 7037: }
 7038: 
 7039: sub domdirectorysrch_check {
 7040:     my ($srch) = @_;
 7041:     my $response;
 7042:     my %dom_inst_srch = &Apache::lonnet::get_dom('configuration',
 7043:                                              ['directorysrch'],$srch->{'srchdomain'});
 7044:     my $showdom = &display_domain_info($srch->{'srchdomain'});
 7045:     if (ref($dom_inst_srch{'directorysrch'}) eq 'HASH') {
 7046:         if ($dom_inst_srch{'directorysrch'}{'lcavailable'} eq '0') {
 7047:             return &mt('LON-CAPA directory search is not available in domain: [_1]',$showdom);
 7048:         }
 7049:         if ($dom_inst_srch{'directorysrch'}{'lclocalonly'}) {
 7050:             if ($env{'request.role.domain'} ne $srch->{'srchdomain'}) {
 7051:                 return &mt('LON-CAPA directory search in domain: [_1] is only allowed for users with a current role in the domain.',$showdom);
 7052:             }
 7053:         }
 7054:     }
 7055:     return 'ok';
 7056: }
 7057: 
 7058: sub instdirectorysrch_check {
 7059:     my ($srch) = @_;
 7060:     my $can_search = 0;
 7061:     my $response;
 7062:     my %dom_inst_srch = &Apache::lonnet::get_dom('configuration',
 7063:                                              ['directorysrch'],$srch->{'srchdomain'});
 7064:     my $showdom = &display_domain_info($srch->{'srchdomain'});
 7065:     if (ref($dom_inst_srch{'directorysrch'}) eq 'HASH') {
 7066:         if (!$dom_inst_srch{'directorysrch'}{'available'}) {
 7067:             return &mt('Institutional directory search is not available in domain: [_1]',$showdom); 
 7068:         }
 7069:         if ($dom_inst_srch{'directorysrch'}{'localonly'}) {
 7070:             if ($env{'request.role.domain'} ne $srch->{'srchdomain'}) {
 7071:                 return &mt('Institutional directory search in domain: [_1] is only allowed for users with a current role in the domain.',$showdom); 
 7072:             }
 7073:             my @usertypes = split(/:/,$env{'environment.inststatus'});
 7074:             if (!@usertypes) {
 7075:                 push(@usertypes,'default');
 7076:             }
 7077:             if (ref($dom_inst_srch{'directorysrch'}{'cansearch'}) eq 'ARRAY') {
 7078:                 foreach my $type (@usertypes) {
 7079:                     if (grep(/^\Q$type\E$/,@{$dom_inst_srch{'directorysrch'}{'cansearch'}})) {
 7080:                         $can_search = 1;
 7081:                         last;
 7082:                     }
 7083:                 }
 7084:             }
 7085:             if (!$can_search) {
 7086:                 my ($insttypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($srch->{'srchdomain'});
 7087:                 my @longtypes; 
 7088:                 foreach my $item (@usertypes) {
 7089:                     if (defined($insttypes->{$item})) { 
 7090:                         push (@longtypes,$insttypes->{$item});
 7091:                     } elsif ($item eq 'default') {
 7092:                         push (@longtypes,&mt('other')); 
 7093:                     }
 7094:                 }
 7095:                 my $insttype_str = join(', ',@longtypes); 
 7096:                 return &mt('Institutional directory search in domain: [_1] is not available to your user type: ',$showdom).$insttype_str;
 7097:             }
 7098:         } else {
 7099:             $can_search = 1;
 7100:         }
 7101:     } else {
 7102:         return &mt('Institutional directory search has not been configured for domain: [_1]',$showdom);
 7103:     }
 7104:     my %longtext = &Apache::lonlocal::texthash (
 7105:                        uname     => 'username',
 7106:                        lastfirst => 'last name, first name',
 7107:                        lastname  => 'last name',
 7108:                        contains  => 'contains',
 7109:                        exact     => 'as exact match to',
 7110:                        begins    => 'begins with',
 7111:                    );
 7112:     if ($can_search) {
 7113:         if (ref($dom_inst_srch{'directorysrch'}{'searchby'}) eq 'ARRAY') {
 7114:             if (!grep(/^\Q$srch->{'srchby'}\E$/,@{$dom_inst_srch{'directorysrch'}{'searchby'}})) {
 7115:                 return &mt('Institutional directory search in domain: [_1] is not available for searching by "[_2]"',$showdom,$longtext{$srch->{'srchby'}});
 7116:             }
 7117:         } else {
 7118:             return &mt('Institutional directory search in domain: [_1] is not available.', $showdom);
 7119:         }
 7120:     }
 7121:     if ($can_search) {
 7122:         if (ref($dom_inst_srch{'directorysrch'}{'searchtypes'}) eq 'ARRAY') {
 7123:             if (grep(/^\Q$srch->{'srchtype'}\E/,@{$dom_inst_srch{'directorysrch'}{'searchtypes'}})) {
 7124:                 return 'ok';
 7125:             } else {
 7126:                 return &mt('Institutional directory search in domain [_1] is not available for the requested search type: "[_2]"',$showdom,$longtext{$srch->{'srchtype'}});
 7127:             }
 7128:         } else {
 7129:             if ((($dom_inst_srch{'directorysrch'}{'searchtypes'} eq 'specify') &&
 7130:                  ($srch->{'srchtype'} eq 'exact' || $srch->{'srchtype'} eq 'contains')) ||
 7131:                 ($dom_inst_srch{'directorysrch'}{'searchtypes'} eq $srch->{'srchtype'})) {
 7132:                 return 'ok';
 7133:             } else {
 7134:                 return &mt('Institutional directory search in domain [_1] is not available for the requested search type: "[_2]"',$showdom,$longtext{$srch->{'srchtype'}});
 7135:             }
 7136:         }
 7137:     }
 7138: }
 7139: 
 7140: sub get_courseusers {
 7141:     my %advhash;
 7142:     my $classlist = &Apache::loncoursedata::get_classlist();
 7143:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles();
 7144:     foreach my $role (sort(keys(%coursepersonnel))) {
 7145:         foreach my $user (split(/\,/,$coursepersonnel{$role})) {
 7146: 	    if (!exists($classlist->{$user})) {
 7147: 		$classlist->{$user} = [];
 7148: 	    }
 7149:         }
 7150:     }
 7151:     return $classlist;
 7152: }
 7153: 
 7154: sub build_search_response {
 7155:     my ($context,$srch,%srch_results) = @_;
 7156:     my ($currstate,$response,$forcenewuser);
 7157:     my %names = (
 7158:           'uname'     => 'username',
 7159:           'lastname'  => 'last name',
 7160:           'lastfirst' => 'last name, first name',
 7161:           'crs'       => 'this course',
 7162:           'dom'       => 'LON-CAPA domain',
 7163:           'instd'     => 'the institutional directory for domain',
 7164:     );
 7165: 
 7166:     my %single = (
 7167:                    begins   => 'A match',
 7168:                    contains => 'A match',
 7169:                    exact    => 'An exact match',
 7170:                  );
 7171:     my %nomatch = (
 7172:                    begins   => 'No match',
 7173:                    contains => 'No match',
 7174:                    exact    => 'No exact match',
 7175:                   );
 7176:     if (keys(%srch_results) > 1) {
 7177:         $currstate = 'select';
 7178:     } else {
 7179:         if (keys(%srch_results) == 1) {
 7180:             $currstate = 'modify';
 7181:             $response = &mt("$single{$srch->{'srchtype'}} was found for the $names{$srch->{'srchby'}} ([_1]) in $names{$srch->{'srchin'}}.",$srch->{'srchterm'});
 7182:             if ($srch->{'srchin'} eq 'dom' || $srch->{'srchin'} eq 'instd') {
 7183:                 $response .= ': '.&display_domain_info($srch->{'srchdomain'});
 7184:             }
 7185:         } else { # Search has nothing found. Prepare message to user.
 7186:             $response = '<span class="LC_warning">';
 7187:             if ($srch->{'srchin'} eq 'dom' || $srch->{'srchin'} eq 'instd') {
 7188:                 $response .= &mt("$nomatch{$srch->{'srchtype'}} found for the $names{$srch->{'srchby'}} [_1] in $names{$srch->{'srchin'}}: [_2]",
 7189:                                  '<b>'.$srch->{'srchterm'}.'</b>',
 7190:                                  &display_domain_info($srch->{'srchdomain'}));
 7191:             } else {
 7192:                 $response .= &mt("$nomatch{$srch->{'srchtype'}} found for the $names{$srch->{'srchby'}} [_1] in $names{$srch->{'srchin'}}.",
 7193:                                  '<b>'.$srch->{'srchterm'}.'</b>');
 7194:             }
 7195:             $response .= '</span>';
 7196: 
 7197:             if ($srch->{'srchin'} ne 'alc') {
 7198:                 $forcenewuser = 1;
 7199:                 my $cansrchinst = 0; 
 7200:                 if ($srch->{'srchdomain'}) {
 7201:                     my %domconfig = &Apache::lonnet::get_dom('configuration',['directorysrch'],$srch->{'srchdomain'});
 7202:                     if (ref($domconfig{'directorysrch'}) eq 'HASH') {
 7203:                         if ($domconfig{'directorysrch'}{'available'}) {
 7204:                             $cansrchinst = 1;
 7205:                         } 
 7206:                     }
 7207:                 }
 7208:                 if ((($srch->{'srchby'} eq 'lastfirst') || 
 7209:                      ($srch->{'srchby'} eq 'lastname')) &&
 7210:                     ($srch->{'srchin'} eq 'dom')) {
 7211:                     if ($cansrchinst) {
 7212:                         $response .= '<br />'.&mt('You may want to broaden your search to a search of the institutional directory for the domain.');
 7213:                     }
 7214:                 }
 7215:                 if ($srch->{'srchin'} eq 'crs') {
 7216:                     $response .= '<br />'.&mt('You may want to broaden your search to the selected LON-CAPA domain.');
 7217:                 }
 7218:             }
 7219:             my $createdom = $env{'request.role.domain'};
 7220:             if ($context eq 'requestcrs') {
 7221:                 if ($env{'form.coursedom'} ne '') {
 7222:                     $createdom = $env{'form.coursedom'};
 7223:                 }
 7224:             }
 7225:             if (!($srch->{'srchby'} eq 'uname' && $srch->{'srchin'} eq 'dom' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchdomain'} eq $createdom)) {
 7226:                 my $cancreate =
 7227:                     &Apache::lonuserutils::can_create_user($createdom,$context);
 7228:                 my $targetdom = '<span class="LC_cusr_emph">'.$createdom.'</span>';
 7229:                 if ($cancreate) {
 7230:                     my $showdom = &display_domain_info($createdom); 
 7231:                     $response .= '<br /><br />'
 7232:                                 .'<b>'.&mt('To add a new user:').'</b>'
 7233:                                 .'<br />';
 7234:                     if ($context eq 'requestcrs') {
 7235:                         $response .= &mt("(You can only define new users in the new course's domain - [_1])",$targetdom);
 7236:                     } else {
 7237:                         $response .= &mt("(You can only create new users in your current role's domain - [_1])",$targetdom);
 7238:                     }
 7239:                     $response .='<ul><li>'
 7240:                                 .&mt("Set 'Domain/institution to search' to: [_1]",'<span class="LC_cusr_emph">'.$showdom.'</span>')
 7241:                                 .'</li><li>'
 7242:                                 .&mt("Set 'Search criteria' to: [_1]username is ..... in selected LON-CAPA domain[_2]",'<span class="LC_cusr_emph">','</span>')
 7243:                                 .'</li><li>'
 7244:                                 .&mt('Provide the proposed username')
 7245:                                 .'</li><li>'
 7246:                                 .&mt("Click 'Search'")
 7247:                                 .'</li></ul><br />';
 7248:                 } else {
 7249:                     my $helplink = ' href="javascript:helpMenu('."'display'".')"';
 7250:                     $response .= '<br /><br />';
 7251:                     if ($context eq 'requestcrs') {
 7252:                         $response .= &mt("You are not authorized to define new users in the new course's domain - [_1].",$targetdom);
 7253:                     } else {
 7254:                         $response .= &mt("You are not authorized to create new users in your current role's domain - [_1].",$targetdom);
 7255:                     }
 7256:                     $response .= '<br />'
 7257:                                  .&mt('Please contact the [_1]helpdesk[_2] if you need to create a new user.'
 7258:                                     ,' <a'.$helplink.'>'
 7259:                                     ,'</a>')
 7260:                                  .'<br /><br />';
 7261:                 }
 7262:             }
 7263:         }
 7264:     }
 7265:     return ($currstate,$response,$forcenewuser);
 7266: }
 7267: 
 7268: sub display_domain_info {
 7269:     my ($dom) = @_;
 7270:     my $output = $dom;
 7271:     if ($dom ne '') { 
 7272:         my $domdesc = &Apache::lonnet::domain($dom,'description');
 7273:         if ($domdesc ne '') {
 7274:             $output .= ' <span class="LC_cusr_emph">('.$domdesc.')</span>';
 7275:         }
 7276:     }
 7277:     return $output;
 7278: }
 7279: 
 7280: sub crumb_utilities {
 7281:     my %elements = (
 7282:        crtuser => {
 7283:            srchterm => 'text',
 7284:            srchin => 'selectbox',
 7285:            srchby => 'selectbox',
 7286:            srchtype => 'selectbox',
 7287:            srchdomain => 'selectbox',
 7288:        },
 7289:        crtusername => {
 7290:            srchterm => 'text',
 7291:            srchdomain => 'selectbox',
 7292:        },
 7293:        docustom => {
 7294:            rolename => 'selectbox',
 7295:            newrolename => 'textbox',
 7296:        },
 7297:        studentform => {
 7298:            srchterm => 'text',
 7299:            srchin => 'selectbox',
 7300:            srchby => 'selectbox',
 7301:            srchtype => 'selectbox',
 7302:            srchdomain => 'selectbox',
 7303:        },
 7304:     );
 7305: 
 7306:     my $jsback .= qq|
 7307: function backPage(formname,prevphase,prevstate) {
 7308:     if (typeof prevphase == 'undefined') {
 7309:         formname.phase.value = '';
 7310:     }
 7311:     else {  
 7312:         formname.phase.value = prevphase;
 7313:     }
 7314:     if (typeof prevstate == 'undefined') {
 7315:         formname.currstate.value = '';
 7316:     }
 7317:     else {
 7318:         formname.currstate.value = prevstate;
 7319:     }
 7320:     formname.submit();
 7321: }
 7322: |;
 7323:     return ($jsback,\%elements);
 7324: }
 7325: 
 7326: sub course_level_table {
 7327:     my ($inccourses,$showcredits,$defaultcredits) = @_;
 7328:     return unless (ref($inccourses) eq 'HASH');
 7329:     my $table = '';
 7330: # Custom Roles?
 7331: 
 7332:     my %customroles=&Apache::lonuserutils::my_custom_roles();
 7333:     my %lt=&Apache::lonlocal::texthash(
 7334:             'exs'  => "Existing sections",
 7335:             'new'  => "Define new section",
 7336:             'ssd'  => "Set Start Date",
 7337:             'sed'  => "Set End Date",
 7338:             'crl'  => "Course Level",
 7339:             'act'  => "Activate",
 7340:             'rol'  => "Role",
 7341:             'ext'  => "Extent",
 7342:             'grs'  => "Section",
 7343:             'crd'  => "Credits",
 7344:             'sta'  => "Start",
 7345:             'end'  => "End"
 7346:     );
 7347: 
 7348:     foreach my $protectedcourse (sort(keys(%{$inccourses}))) {
 7349: 	my $thiscourse=$protectedcourse;
 7350: 	$thiscourse=~s:_:/:g;
 7351: 	my %coursedata=&Apache::lonnet::coursedescription($thiscourse);
 7352:         my $isowner = &Apache::lonuserutils::is_courseowner($protectedcourse,$coursedata{'internal.courseowner'});
 7353: 	my $area=$coursedata{'description'};
 7354:         my $crstype=$coursedata{'type'};
 7355: 	if (!defined($area)) { $area=&mt('Unavailable course').': '.$protectedcourse; }
 7356: 	my ($domain,$cnum)=split(/\//,$thiscourse);
 7357:         my %sections_count;
 7358:         if (defined($env{'request.course.id'})) {
 7359:             if ($env{'request.course.id'} eq $domain.'_'.$cnum) {
 7360:                 %sections_count = 
 7361: 		    &Apache::loncommon::get_sections($domain,$cnum);
 7362:             }
 7363:         }
 7364:         my @roles = &Apache::lonuserutils::roles_by_context('course','',$crstype);
 7365: 	foreach my $role (@roles) {
 7366:             my $plrole=&Apache::lonnet::plaintext($role,$crstype);
 7367: 	    if ((&Apache::lonnet::allowed('c'.$role,$thiscourse)) ||
 7368:                 ((($role eq 'cc') || ($role eq 'co')) && ($isowner))) {
 7369:                 $table .= &course_level_row($protectedcourse,$role,$area,$domain,
 7370:                                             $plrole,\%sections_count,\%lt,
 7371:                                             $showcredits,$defaultcredits,$crstype);
 7372:             } elsif ($env{'request.course.sec'} ne '') {
 7373:                 if (&Apache::lonnet::allowed('c'.$role,$thiscourse.'/'.
 7374:                                              $env{'request.course.sec'})) {
 7375:                     $table .= &course_level_row($protectedcourse,$role,$area,$domain,
 7376:                                                 $plrole,\%sections_count,\%lt,
 7377:                                                 $showcredits,$defaultcredits,$crstype);
 7378:                 }
 7379:             }
 7380:         }
 7381:         if (&Apache::lonnet::allowed('ccr',$thiscourse)) {
 7382:             foreach my $cust (sort(keys(%customroles))) {
 7383:                 next if ($crstype eq 'Community' && $customroles{$cust} =~ /bre\&S/);
 7384:                 my $role = 'cr_cr_'.$env{'user.domain'}.'_'.$env{'user.name'}.'_'.$cust;
 7385:                 $table .= &course_level_row($protectedcourse,$role,$area,$domain,
 7386:                                             $cust,\%sections_count,\%lt,
 7387:                                             $showcredits,$defaultcredits,$crstype);
 7388:             }
 7389: 	}
 7390:     }
 7391:     return '' if ($table eq ''); # return nothing if there is nothing 
 7392:                                  # in the table
 7393:     my $result;
 7394:     if (!$env{'request.course.id'}) {
 7395:         $result = '<h4>'.$lt{'crl'}.'</h4>'."\n";
 7396:     }
 7397:     $result .= 
 7398: &Apache::loncommon::start_data_table().
 7399: &Apache::loncommon::start_data_table_header_row().
 7400: '<th>'.$lt{'act'}.'</th><th>'.$lt{'rol'}.'</th>'."\n".
 7401: '<th>'.$lt{'ext'}.'</th><th>'."\n";
 7402:     if ($showcredits) {
 7403:         $result .= $lt{'crd'}.'</th>';
 7404:     }
 7405:     $result .=
 7406: '<th>'.$lt{'grs'}.'</th><th>'.$lt{'sta'}.'</th>'."\n".
 7407: '<th>'.$lt{'end'}.'</th>'.
 7408: &Apache::loncommon::end_data_table_header_row().
 7409: $table.
 7410: &Apache::loncommon::end_data_table();
 7411:     return $result;
 7412: }
 7413: 
 7414: sub course_level_row {
 7415:     my ($protectedcourse,$role,$area,$domain,$plrole,$sections_count,
 7416:         $lt,$showcredits,$defaultcredits,$crstype) = @_;
 7417:     my $creditem;
 7418:     my $row = &Apache::loncommon::start_data_table_row().
 7419:               ' <td><input type="checkbox" name="act_'.
 7420:               $protectedcourse.'_'.$role.'" /></td>'."\n".
 7421:               ' <td>'.$plrole.'</td>'."\n".
 7422:               ' <td>'.$area.'<br />Domain: '.$domain.'</td>'."\n";
 7423:     if (($showcredits) && ($role eq 'st') && ($crstype eq 'Course')) {
 7424:         $row .= 
 7425:             '<td><input type="text" name="credits_'.$protectedcourse.'_'.
 7426:             $role.'" size="3" value="'.$defaultcredits.'" /></td>';
 7427:     } else {
 7428:         $row .= '<td>&nbsp;</td>';
 7429:     }
 7430:     if (($role eq 'cc') || ($role eq 'co')) {
 7431:         $row .= '<td>&nbsp;</td>';
 7432:     } elsif ($env{'request.course.sec'} ne '') {
 7433:         $row .= ' <td><input type="hidden" value="'.
 7434:                 $env{'request.course.sec'}.'" '.
 7435:                 'name="sec_'.$protectedcourse.'_'.$role.'" />'.
 7436:                 $env{'request.course.sec'}.'</td>';
 7437:     } else {
 7438:         if (ref($sections_count) eq 'HASH') {
 7439:             my $currsec = 
 7440:                 &Apache::lonuserutils::course_sections($sections_count,
 7441:                                                        $protectedcourse.'_'.$role);
 7442:             $row .= '<td><table class="LC_createuser">'."\n".
 7443:                     '<tr class="LC_section_row">'."\n".
 7444:                     ' <td valign="top">'.$lt->{'exs'}.'<br />'.
 7445:                        $currsec.'</td>'."\n".
 7446:                      ' <td>&nbsp;&nbsp;</td>'."\n".
 7447:                      ' <td valign="top">&nbsp;'.$lt->{'new'}.'<br />'.
 7448:                      '<input type="text" name="newsec_'.$protectedcourse.'_'.$role.
 7449:                      '" value="" />'.
 7450:                      '<input type="hidden" '.
 7451:                      'name="sec_'.$protectedcourse.'_'.$role.'" /></td>'."\n".
 7452:                      '</tr></table></td>'."\n";
 7453:         } else {
 7454:             $row .= '<td><input type="text" size="10" '.
 7455:                     'name="sec_'.$protectedcourse.'_'.$role.'" /></td>'."\n";
 7456:         }
 7457:     }
 7458:     $row .= <<ENDTIMEENTRY;
 7459: <td><input type="hidden" name="start_$protectedcourse\_$role" value="" />
 7460: <a href=
 7461: "javascript:pjump('date_start','Start Date $plrole',document.cu.start_$protectedcourse\_$role.value,'start_$protectedcourse\_$role','cu.pres','dateset')">$lt->{'ssd'}</a></td>
 7462: <td><input type="hidden" name="end_$protectedcourse\_$role" value="" />
 7463: <a href=
 7464: "javascript:pjump('date_end','End Date $plrole',document.cu.end_$protectedcourse\_$role.value,'end_$protectedcourse\_$role','cu.pres','dateset')">$lt->{'sed'}</a></td>
 7465: ENDTIMEENTRY
 7466:     $row .= &Apache::loncommon::end_data_table_row();
 7467:     return $row;
 7468: }
 7469: 
 7470: sub course_level_dc {
 7471:     my ($dcdom,$showcredits) = @_;
 7472:     my %customroles=&Apache::lonuserutils::my_custom_roles();
 7473:     my @roles = &Apache::lonuserutils::roles_by_context('course');
 7474:     my $hiddenitems = '<input type="hidden" name="dcdomain" value="'.$dcdom.'" />'.
 7475:                       '<input type="hidden" name="origdom" value="'.$dcdom.'" />'.
 7476:                       '<input type="hidden" name="dccourse" value="" />';
 7477:     my $courseform=&Apache::loncommon::selectcourse_link
 7478:             ('cu','dccourse','dcdomain','coursedesc',undef,undef,'Select','crstype');
 7479:     my $credit_elem;
 7480:     if ($showcredits) {
 7481:         $credit_elem = 'credits';
 7482:     }
 7483:     my $cb_jscript = &Apache::loncommon::coursebrowser_javascript($dcdom,'currsec','cu','role','Course/Community Browser',$credit_elem);
 7484:     my %lt=&Apache::lonlocal::texthash(
 7485:                     'rol'  => "Role",
 7486:                     'grs'  => "Section",
 7487:                     'exs'  => "Existing sections",
 7488:                     'new'  => "Define new section", 
 7489:                     'sta'  => "Start",
 7490:                     'end'  => "End",
 7491:                     'ssd'  => "Set Start Date",
 7492:                     'sed'  => "Set End Date",
 7493:                     'scc'  => "Course/Community",
 7494:                     'crd'  => "Credits",
 7495:                   );
 7496:     my $header = '<h4>'.&mt('Course/Community Level').'</h4>'.
 7497:                  &Apache::loncommon::start_data_table().
 7498:                  &Apache::loncommon::start_data_table_header_row().
 7499:                  '<th>'.$lt{'scc'}.'</th><th>'.$lt{'rol'}.'</th>'."\n".
 7500:                  '<th>'.$lt{'grs'}.'</th>'."\n";
 7501:     $header .=   '<th>'.$lt{'crd'}.'</th>'."\n" if ($showcredits);
 7502:     $header .=   '<th>'.$lt{'sta'}.'</th><th>'.$lt{'end'}.'</th>'."\n".
 7503:                  &Apache::loncommon::end_data_table_header_row();
 7504:     my $otheritems = &Apache::loncommon::start_data_table_row()."\n".
 7505:                      '<td><br /><span class="LC_nobreak"><input type="text" name="coursedesc" value="" onfocus="this.blur();opencrsbrowser('."'cu','dccourse','dcdomain','coursedesc','','','','crstype'".')" />'.
 7506:                      $courseform.('&nbsp;' x4).'</span></td>'."\n".
 7507:                      '<td valign="top"><br /><select name="role">'."\n";
 7508:     foreach my $role (@roles) {
 7509:         my $plrole=&Apache::lonnet::plaintext($role);
 7510:         $otheritems .= '  <option value="'.$role.'">'.$plrole.'</option>';
 7511:     }
 7512:     if ( keys(%customroles) > 0) {
 7513:         foreach my $cust (sort(keys(%customroles))) {
 7514:             my $custrole='cr_cr_'.$env{'user.domain'}.
 7515:                     '_'.$env{'user.name'}.'_'.$cust;
 7516:             $otheritems .= '  <option value="'.$custrole.'">'.$cust.'</option>';
 7517:         }
 7518:     }
 7519:     $otheritems .= '</select></td><td>'.
 7520:                      '<table border="0" cellspacing="0" cellpadding="0">'.
 7521:                      '<tr><td valign="top"><b>'.$lt{'exs'}.'</b><br /><select name="currsec">'.
 7522:                      ' <option value="">&lt;--'.&mt('Pick course first').'</option></select></td>'.
 7523:                      '<td>&nbsp;&nbsp;</td>'.
 7524:                      '<td valign="top">&nbsp;<b>'.$lt{'new'}.'</b><br />'.
 7525:                      '<input type="text" name="newsec" value="" />'.
 7526:                      '<input type="hidden" name="section" value="" />'.
 7527:                      '<input type="hidden" name="groups" value="" />'.
 7528:                      '<input type="hidden" name="crstype" value="" /></td>'.
 7529:                      '</tr></table></td>'."\n";
 7530:     if ($showcredits) {
 7531:         $otheritems .= '<td><br />'."\n".
 7532:                        '<input type="text" size="3" name="credits" value="" /></td>'."\n";
 7533:     }
 7534:     $otheritems .= <<ENDTIMEENTRY;
 7535: <td><br /><input type="hidden" name="start" value='' />
 7536: <a href=
 7537: "javascript:pjump('date_start','Start Date',document.cu.start.value,'start','cu.pres','dateset')">$lt{'ssd'}</a></td>
 7538: <td><br /><input type="hidden" name="end" value='' />
 7539: <a href=
 7540: "javascript:pjump('date_end','End Date',document.cu.end.value,'end','cu.pres','dateset')">$lt{'sed'}</a></td>
 7541: ENDTIMEENTRY
 7542:     $otheritems .= &Apache::loncommon::end_data_table_row().
 7543:                    &Apache::loncommon::end_data_table()."\n";
 7544:     return $cb_jscript.$header.$hiddenitems.$otheritems;
 7545: }
 7546: 
 7547: sub update_selfenroll_config {
 7548:     my ($r,$cid,$cdom,$cnum,$context,$crstype,$currsettings) = @_;
 7549:     return unless (ref($currsettings) eq 'HASH');
 7550:     my ($row,$lt) = &Apache::lonuserutils::get_selfenroll_titles();
 7551:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
 7552:     my (%changes,%warning);
 7553:     my $curr_types;
 7554:     my %noedit;
 7555:     unless ($context eq 'domain') {
 7556:         %noedit = &get_noedit_fields($cdom,$cnum,$crstype,$row);
 7557:     }
 7558:     if (ref($row) eq 'ARRAY') {
 7559:         foreach my $item (@{$row}) {
 7560:             next if ($noedit{$item});
 7561:             if ($item eq 'enroll_dates') {
 7562:                 my (%currenrolldate,%newenrolldate);
 7563:                 foreach my $type ('start','end') {
 7564:                     $currenrolldate{$type} = $currsettings->{'selfenroll_'.$type.'_date'};
 7565:                     $newenrolldate{$type} = &Apache::lonhtmlcommon::get_date_from_form('selfenroll_'.$type.'_date');
 7566:                     if ($newenrolldate{$type} ne $currenrolldate{$type}) {
 7567:                         $changes{'internal.selfenroll_'.$type.'_date'} = $newenrolldate{$type};
 7568:                     }
 7569:                 }
 7570:             } elsif ($item eq 'access_dates') {
 7571:                 my (%currdate,%newdate);
 7572:                 foreach my $type ('start','end') {
 7573:                     $currdate{$type} = $currsettings->{'selfenroll_'.$type.'_access'};
 7574:                     $newdate{$type} = &Apache::lonhtmlcommon::get_date_from_form('selfenroll_'.$type.'_access');
 7575:                     if ($newdate{$type} ne $currdate{$type}) {
 7576:                         $changes{'internal.selfenroll_'.$type.'_access'} = $newdate{$type};
 7577:                     }
 7578:                 }
 7579:             } elsif ($item eq 'types') {
 7580:                 $curr_types = $currsettings->{'selfenroll_'.$item};
 7581:                 if ($env{'form.selfenroll_all'}) {
 7582:                     if ($curr_types ne '*') {
 7583:                         $changes{'internal.selfenroll_types'} = '*';
 7584:                     } else {
 7585:                         next;
 7586:                     }
 7587:                 } else {
 7588:                     my %currdoms;
 7589:                     my @entries = split(/;/,$curr_types);
 7590:                     my @deletedoms = &Apache::loncommon::get_env_multiple('form.selfenroll_delete');
 7591:                     my @activations = &Apache::loncommon::get_env_multiple('form.selfenroll_activate');
 7592:                     my $newnum = 0;
 7593:                     my @latesttypes;
 7594:                     foreach my $num (@activations) {
 7595:                         my @types = &Apache::loncommon::get_env_multiple('form.selfenroll_types_'.$num);
 7596:                         if (@types > 0) {
 7597:                             @types = sort(@types);
 7598:                             my $typestr = join(',',@types);
 7599:                             my $typedom = $env{'form.selfenroll_dom_'.$num};
 7600:                             $latesttypes[$newnum] = $typedom.':'.$typestr;
 7601:                             $currdoms{$typedom} = 1;
 7602:                             $newnum ++;
 7603:                         }
 7604:                     }
 7605:                     for (my $j=0; $j<$env{'form.selfenroll_types_total'}; $j++) {
 7606:                         if ((!grep(/^$j$/,@deletedoms)) && (!grep(/^$j$/,@activations))) {
 7607:                             my @types = &Apache::loncommon::get_env_multiple('form.selfenroll_types_'.$j);
 7608:                             if (@types > 0) {
 7609:                                 @types = sort(@types);
 7610:                                 my $typestr = join(',',@types);
 7611:                                 my $typedom = $env{'form.selfenroll_dom_'.$j};
 7612:                                 $latesttypes[$newnum] = $typedom.':'.$typestr;
 7613:                                 $currdoms{$typedom} = 1;
 7614:                                 $newnum ++;
 7615:                             }
 7616:                         }
 7617:                     }
 7618:                     if ($env{'form.selfenroll_newdom'} ne '') {
 7619:                         my $typedom = $env{'form.selfenroll_newdom'};
 7620:                         if ((!defined($currdoms{$typedom})) && 
 7621:                             (&Apache::lonnet::domain($typedom) ne '')) {
 7622:                             my $typestr;
 7623:                             my ($othertitle,$usertypes,$types) = 
 7624:                                 &Apache::loncommon::sorted_inst_types($typedom);
 7625:                             my $othervalue = 'any';
 7626:                             if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 7627:                                 if (@{$types} > 0) {
 7628:                                     my @esc_types = map { &escape($_); } @{$types};
 7629:                                     $othervalue = 'other';
 7630:                                     $typestr = join(',',(@esc_types,$othervalue));
 7631:                                 }
 7632:                                 $typestr = $othervalue;
 7633:                             } else {
 7634:                                 $typestr = $othervalue;
 7635:                             } 
 7636:                             $latesttypes[$newnum] = $typedom.':'.$typestr;
 7637:                             $newnum ++ ;
 7638:                         }
 7639:                     }
 7640:                     my $selfenroll_types = join(';',@latesttypes);
 7641:                     if ($selfenroll_types ne $curr_types) {
 7642:                         $changes{'internal.selfenroll_types'} = $selfenroll_types;
 7643:                     }
 7644:                 }
 7645:             } elsif ($item eq 'limit') {
 7646:                 my $newlimit = $env{'form.selfenroll_limit'};
 7647:                 my $newcap = $env{'form.selfenroll_cap'};
 7648:                 $newcap =~s/\s+//g;
 7649:                 my $currlimit =  $currsettings->{'selfenroll_limit'};
 7650:                 $currlimit = 'none' if ($currlimit eq '');
 7651:                 my $currcap = $currsettings->{'selfenroll_cap'};
 7652:                 if ($newlimit ne $currlimit) {
 7653:                     if ($newlimit ne 'none') {
 7654:                         if ($newcap =~ /^\d+$/) {
 7655:                             if ($newcap ne $currcap) {
 7656:                                 $changes{'internal.selfenroll_cap'} = $newcap;
 7657:                             }
 7658:                             $changes{'internal.selfenroll_limit'} = $newlimit;
 7659:                         } else {
 7660:                             $warning{$item} = &mt('Maximum enrollment setting unchanged.').'<br />'.
 7661:                                 &mt('The value provided was invalid - it must be a positive integer if enrollment is being limited.'); 
 7662:                         }
 7663:                     } elsif ($currcap ne '') {
 7664:                         $changes{'internal.selfenroll_cap'} = '';
 7665:                         $changes{'internal.selfenroll_limit'} = $newlimit; 
 7666:                     }
 7667:                 } elsif ($currlimit ne 'none') {
 7668:                     if ($newcap =~ /^\d+$/) {
 7669:                         if ($newcap ne $currcap) {
 7670:                             $changes{'internal.selfenroll_cap'} = $newcap;
 7671:                         }
 7672:                     } else {
 7673:                         $warning{$item} = &mt('Maximum enrollment setting unchanged.').'<br />'.
 7674:                             &mt('The value provided was invalid - it must be a positive integer if enrollment is being limited.');
 7675:                     }
 7676:                 }
 7677:             } elsif ($item eq 'approval') {
 7678:                 my (@currnotified,@newnotified);
 7679:                 my $currapproval = $currsettings->{'selfenroll_approval'};
 7680:                 my $currnotifylist = $currsettings->{'selfenroll_notifylist'};
 7681:                 if ($currnotifylist ne '') {
 7682:                     @currnotified = split(/,/,$currnotifylist);
 7683:                     @currnotified = sort(@currnotified);
 7684:                 }
 7685:                 my $newapproval = $env{'form.selfenroll_approval'};
 7686:                 @newnotified = &Apache::loncommon::get_env_multiple('form.selfenroll_notify');
 7687:                 @newnotified = sort(@newnotified);
 7688:                 if ($newapproval ne $currapproval) {
 7689:                     $changes{'internal.selfenroll_approval'} = $newapproval;
 7690:                     if (!$newapproval) {
 7691:                         if ($currnotifylist ne '') {
 7692:                             $changes{'internal.selfenroll_notifylist'} = '';
 7693:                         }
 7694:                     } else {
 7695:                         my @differences =  
 7696:                             &Apache::loncommon::compare_arrays(\@currnotified,\@newnotified);
 7697:                         if (@differences > 0) {
 7698:                             if (@newnotified > 0) {
 7699:                                 $changes{'internal.selfenroll_notifylist'} = join(',',@newnotified);
 7700:                             } else {
 7701:                                 $changes{'internal.selfenroll_notifylist'} = join(',',@newnotified);
 7702:                             }
 7703:                         }
 7704:                     }
 7705:                 } else {
 7706:                     my @differences = &Apache::loncommon::compare_arrays(\@currnotified,\@newnotified);
 7707:                     if (@differences > 0) {
 7708:                         if (@newnotified > 0) {
 7709:                             $changes{'internal.selfenroll_notifylist'} = join(',',@newnotified);
 7710:                         } else {
 7711:                             $changes{'internal.selfenroll_notifylist'} = '';
 7712:                         }
 7713:                     }
 7714:                 }
 7715:             } else {
 7716:                 my $curr_val = $currsettings->{'selfenroll_'.$item};
 7717:                 my $newval = $env{'form.selfenroll_'.$item};
 7718:                 if ($item eq 'section') {
 7719:                     $newval = $env{'form.sections'};
 7720:                     if (defined($curr_groups{$newval})) {
 7721:                         $newval = $curr_val;
 7722:                         $warning{$item} = &mt('Section for self-enrolled users unchanged as the proposed section is a group').'<br />'.
 7723:                                           &mt('Group names and section names must be distinct');
 7724:                     } elsif ($newval eq 'all') {
 7725:                         $newval = $curr_val;
 7726:                         $warning{$item} = &mt('Section for self-enrolled users unchanged, as "all" is a reserved section name.');
 7727:                     }
 7728:                     if ($newval eq '') {
 7729:                         $newval = 'none';
 7730:                     }
 7731:                 }
 7732:                 if ($newval ne $curr_val) {
 7733:                     $changes{'internal.selfenroll_'.$item} = $newval;
 7734:                 }
 7735:             }
 7736:         }
 7737:         if (keys(%warning) > 0) {
 7738:             foreach my $item (@{$row}) {
 7739:                 if (exists($warning{$item})) {
 7740:                     $r->print($warning{$item}.'<br />');
 7741:                 }
 7742:             } 
 7743:         }
 7744:         if (keys(%changes) > 0) {
 7745:             my $putresult = &Apache::lonnet::put('environment',\%changes,$cdom,$cnum);
 7746:             if ($putresult eq 'ok') {
 7747:                 if ((exists($changes{'internal.selfenroll_types'})) ||
 7748:                     (exists($changes{'internal.selfenroll_start_date'}))  ||
 7749:                     (exists($changes{'internal.selfenroll_end_date'}))) {
 7750:                     my %crsinfo = &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',
 7751:                                                                 $cnum,undef,undef,'Course');
 7752:                     my $chome = &Apache::lonnet::homeserver($cnum,$cdom);
 7753:                     if (ref($crsinfo{$cid}) eq 'HASH') {
 7754:                         foreach my $item ('selfenroll_types','selfenroll_start_date','selfenroll_end_date') {
 7755:                             if (exists($changes{'internal.'.$item})) {
 7756:                                 $crsinfo{$cid}{$item} = $changes{'internal.'.$item};
 7757:                             }
 7758:                         }
 7759:                         my $crsputresult =
 7760:                             &Apache::lonnet::courseidput($cdom,\%crsinfo,
 7761:                                                          $chome,'notime');
 7762:                     }
 7763:                 }
 7764:                 $r->print(&mt('The following changes were made to self-enrollment settings:').'<ul>');
 7765:                 foreach my $item (@{$row}) {
 7766:                     my $title = $item;
 7767:                     if (ref($lt) eq 'HASH') {
 7768:                         $title = $lt->{$item};
 7769:                     }
 7770:                     if ($item eq 'enroll_dates') {
 7771:                         foreach my $type ('start','end') {
 7772:                             if (exists($changes{'internal.selfenroll_'.$type.'_date'})) {
 7773:                                 my $newdate = &Apache::lonlocal::locallocaltime($changes{'internal.selfenroll_'.$type.'_date'});
 7774:                                 $r->print('<li>'.&mt('[_1]: "[_2]" set to "[_3]".',
 7775:                                           $title,$type,$newdate).'</li>');
 7776:                             }
 7777:                         }
 7778:                     } elsif ($item eq 'access_dates') {
 7779:                         foreach my $type ('start','end') {
 7780:                             if (exists($changes{'internal.selfenroll_'.$type.'_access'})) {
 7781:                                 my $newdate = &Apache::lonlocal::locallocaltime($changes{'internal.selfenroll_'.$type.'_access'});
 7782:                                 $r->print('<li>'.&mt('[_1]: "[_2]" set to "[_3]".',
 7783:                                           $title,$type,$newdate).'</li>');
 7784:                             }
 7785:                         }
 7786:                     } elsif ($item eq 'limit') {
 7787:                         if ((exists($changes{'internal.selfenroll_limit'})) ||
 7788:                             (exists($changes{'internal.selfenroll_cap'}))) {
 7789:                             my ($newval,$newcap);
 7790:                             if ($changes{'internal.selfenroll_cap'} ne '') {
 7791:                                 $newcap = $changes{'internal.selfenroll_cap'}
 7792:                             } else {
 7793:                                 $newcap = $currsettings->{'selfenroll_cap'};
 7794:                             }
 7795:                             if ($changes{'internal.selfenroll_limit'} eq 'none') {
 7796:                                 $newval = &mt('No limit');
 7797:                             } elsif ($changes{'internal.selfenroll_limit'} eq 
 7798:                                      'allstudents') {
 7799:                                 $newval = &mt('New self-enrollment no longer allowed when total (all students) reaches [_1].',$newcap);
 7800:                             } elsif ($changes{'internal.selfenroll_limit'} eq 'selfenrolled') {
 7801:                                 $newval = &mt('New self-enrollment no longer allowed when total number of self-enrolled students reaches [_1].',$newcap);
 7802:                             } else {
 7803:                                 my $currlimit =  $currsettings->{'selfenroll_limit'};
 7804:                                 if ($currlimit eq 'allstudents') {
 7805:                                     $newval = &mt('New self-enrollment no longer allowed when total (all students) reaches [_1].',$newcap);
 7806:                                 } elsif ($changes{'internal.selfenroll_limit'} eq 'selfenrolled') {
 7807:                                     $newval =  &mt('New self-enrollment no longer allowed when total number of self-enrolled students reaches [_1].',$newcap);
 7808:                                 }
 7809:                             }
 7810:                             $r->print('<li>'.&mt('"[_1]" set to "[_2]".',$title,$newval).'</li>'."\n");
 7811:                         }
 7812:                     } elsif ($item eq 'approval') {
 7813:                         if ((exists($changes{'internal.selfenroll_approval'})) ||
 7814:                             (exists($changes{'internal.selfenroll_notifylist'}))) {
 7815:                             my %selfdescs = &Apache::lonuserutils::selfenroll_default_descs();
 7816:                             my ($newval,$newnotify);
 7817:                             if (exists($changes{'internal.selfenroll_notifylist'})) {
 7818:                                 $newnotify = $changes{'internal.selfenroll_notifylist'};
 7819:                             } else {   
 7820:                                 $newnotify = $currsettings->{'selfenroll_notifylist'};
 7821:                             }
 7822:                             if (exists($changes{'internal.selfenroll_approval'})) {
 7823:                                 if ($changes{'internal.selfenroll_approval'} !~ /^[012]$/) {
 7824:                                     $changes{'internal.selfenroll_approval'} = '0';
 7825:                                 }
 7826:                                 $newval = $selfdescs{'approval'}{$changes{'internal.selfenroll_approval'}};
 7827:                             } else {
 7828:                                 my $currapproval = $currsettings->{'selfenroll_approval'}; 
 7829:                                 if ($currapproval !~ /^[012]$/) {
 7830:                                     $currapproval = 0;
 7831:                                 }
 7832:                                 $newval = $selfdescs{'approval'}{$currapproval};
 7833:                             }
 7834:                             $r->print('<li>'.&mt('"[_1]" set to "[_2]".',$title,$newval));
 7835:                             if ($newnotify) {
 7836:                                 $r->print('<br />'.&mt('The following will be notified when an enrollment request needs approval, or has been approved: [_1].',$newnotify));
 7837:                             } else {
 7838:                                 $r->print('<br />'.&mt('No notifications sent when an enrollment request needs approval, or has been approved.'));
 7839:                             }
 7840:                             $r->print('</li>'."\n");
 7841:                         }
 7842:                     } else {
 7843:                         if (exists($changes{'internal.selfenroll_'.$item})) {
 7844:                             my $newval = $changes{'internal.selfenroll_'.$item};
 7845:                             if ($item eq 'types') {
 7846:                                 if ($newval eq '') {
 7847:                                     $newval = &mt('None');
 7848:                                 } elsif ($newval eq '*') {
 7849:                                     $newval = &mt('Any user in any domain');
 7850:                                 }
 7851:                             } elsif ($item eq 'registered') {
 7852:                                 if ($newval eq '1') {
 7853:                                     $newval = &mt('Yes');
 7854:                                 } elsif ($newval eq '0') {
 7855:                                     $newval = &mt('No');
 7856:                                 }
 7857:                             }
 7858:                             $r->print('<li>'.&mt('"[_1]" set to "[_2]".',$title,$newval).'</li>'."\n");
 7859:                         }
 7860:                     }
 7861:                 }
 7862:                 $r->print('</ul>');
 7863:                 if ($env{'course.'.$cid.'.description'} ne '') {
 7864:                     my %newenvhash;
 7865:                     foreach my $key (keys(%changes)) {
 7866:                         $newenvhash{'course.'.$cid.'.'.$key} = $changes{$key};
 7867:                     }
 7868:                     &Apache::lonnet::appenv(\%newenvhash);
 7869:                 }
 7870:             } else {
 7871:                 $r->print(&mt('An error occurred when saving changes to self-enrollment settings in this course.').'<br />'.
 7872:                           &mt('The error was: [_1].',$putresult));
 7873:             }
 7874:         } else {
 7875:             $r->print(&mt('No changes were made to the existing self-enrollment settings in this course.'));
 7876:         }
 7877:     } else {
 7878:         $r->print(&mt('No changes were made to the existing self-enrollment settings in this course.'));
 7879:     }
 7880:     my $visactions = &cat_visibility();
 7881:     my ($cathash,%cattype);
 7882:     my %domconfig = &Apache::lonnet::get_dom('configuration',['coursecategories'],$cdom);
 7883:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 7884:         $cathash = $domconfig{'coursecategories'}{'cats'};
 7885:         $cattype{'auth'} = $domconfig{'coursecategories'}{'auth'};
 7886:         $cattype{'unauth'} = $domconfig{'coursecategories'}{'unauth'};
 7887:     } else {
 7888:         $cathash = {};
 7889:         $cattype{'auth'} = 'std';
 7890:         $cattype{'unauth'} = 'std';
 7891:     }
 7892:     if (($cattype{'auth'} eq 'none') && ($cattype{'unauth'} eq 'none')) {
 7893:         $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
 7894:                   '<br />'.
 7895:                   '<br />'.$visactions->{'take'}.'<ul>'.
 7896:                   '<li>'.$visactions->{'dc_chgconf'}.'</li>'.
 7897:                   '</ul>');
 7898:     } elsif (($cattype{'auth'} !~ /^(std|domonly)$/) && ($cattype{'unauth'} !~ /^(std|domonly)$/)) {
 7899:         if ($currsettings->{'uniquecode'}) {
 7900:             $r->print('<span class="LC_info">'.$visactions->{'vis'}.'</span>');
 7901:         } else {
 7902:             $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
 7903:                   '<br />'.
 7904:                   '<br />'.$visactions->{'take'}.'<ul>'.
 7905:                   '<li>'.$visactions->{'dc_setcode'}.'</li>'.
 7906:                   '</ul><br />');
 7907:         }
 7908:     } else {
 7909:         my ($visible,$cansetvis,$vismsgs) = &visible_in_stdcat($cdom,$cnum,\%domconfig);
 7910:         if (ref($visactions) eq 'HASH') {
 7911:             if (!$visible) {
 7912:                 $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
 7913:                           '<br />');
 7914:                 if (ref($vismsgs) eq 'ARRAY') {
 7915:                     $r->print('<br />'.$visactions->{'take'}.'<ul>');
 7916:                     foreach my $item (@{$vismsgs}) {
 7917:                         $r->print('<li>'.$visactions->{$item}.'</li>');
 7918:                     }
 7919:                     $r->print('</ul>');
 7920:                 }
 7921:                 $r->print($cansetvis);
 7922:             }
 7923:         }
 7924:     } 
 7925:     return;
 7926: }
 7927: 
 7928: #---------------------------------------------- end functions for &phase_two
 7929: 
 7930: #--------------------------------- functions for &phase_two and &phase_three
 7931: 
 7932: #--------------------------end of functions for &phase_two and &phase_three
 7933: 
 7934: 1;
 7935: __END__
 7936: 
 7937: 

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