File:  [LON-CAPA] / loncom / interface / loncreateuser.pm
Revision 1.406.2.4: download - view: text, annotated - select for diffs
Sat Oct 22 15:53:55 2016 UTC (7 years, 7 months ago) by raeburn
Branches: version_2_11_X
- For 2.11
  - Backport 1.413.

    1: # The LearningOnline Network with CAPA
    2: # Create a user
    3: #
    4: # $Id: loncreateuser.pm,v 1.406.2.4 2016/10/22 15:53:55 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: ###
   29: 
   30: package Apache::loncreateuser;
   31: 
   32: =pod
   33: 
   34: =head1 NAME
   35: 
   36: Apache::loncreateuser.pm
   37: 
   38: =head1 SYNOPSIS
   39: 
   40:     Handler to create users and custom roles
   41: 
   42:     Provides an Apache handler for creating users,
   43:     editing their login parameters, roles, and removing roles, and
   44:     also creating and assigning custom roles.
   45: 
   46: =head1 OVERVIEW
   47: 
   48: =head2 Custom Roles
   49: 
   50: In LON-CAPA, roles are actually collections of privileges. "Teaching
   51: Assistant", "Course Coordinator", and other such roles are really just
   52: collection of privileges that are useful in many circumstances.
   53: 
   54: Custom roles can be defined by a Domain Coordinator, Course Coordinator
   55: or Community Coordinator via the Manage User functionality.
   56: The custom role editor screen will show all privileges which can be
   57: assigned to users. For a complete list of privileges, please see 
   58: C</home/httpd/lonTabs/rolesplain.tab>.
   59: 
   60: Custom role definitions are stored in the C<roles.db> file of the creator
   61: of the role.
   62: 
   63: =cut
   64: 
   65: use strict;
   66: use Apache::Constants qw(:common :http);
   67: use Apache::lonnet;
   68: use Apache::loncommon;
   69: use Apache::lonlocal;
   70: use Apache::longroup;
   71: use Apache::lonuserutils;
   72: use Apache::loncoursequeueadmin;
   73: use LONCAPA qw(:DEFAULT :match);
   74: 
   75: my $loginscript; # piece of javascript used in two separate instances
   76: my $authformnop;
   77: my $authformkrb;
   78: my $authformint;
   79: my $authformfsys;
   80: my $authformloc;
   81: 
   82: sub initialize_authen_forms {
   83:     my ($dom,$formname,$curr_authtype,$mode) = @_;
   84:     my ($krbdef,$krbdefdom) = &Apache::loncommon::get_kerberos_defaults($dom);
   85:     my %param = ( formname => $formname,
   86:                   kerb_def_dom => $krbdefdom,
   87:                   kerb_def_auth => $krbdef,
   88:                   domain => $dom,
   89:                 );
   90:     my %abv_auth = &auth_abbrev();
   91:     if ($curr_authtype =~ /^(krb4|krb5|internal|localauth|unix):(.*)$/) {
   92:         my $long_auth = $1;
   93:         my $curr_autharg = $2;
   94:         my %abv_auth = &auth_abbrev();
   95:         $param{'curr_authtype'} = $abv_auth{$long_auth};
   96:         if ($long_auth =~ /^krb(4|5)$/) {
   97:             $param{'curr_kerb_ver'} = $1;
   98:             $param{'curr_autharg'} = $curr_autharg;
   99:         }
  100:         if ($mode eq 'modifyuser') {
  101:             $param{'mode'} = $mode;
  102:         }
  103:     }
  104:     $loginscript  = &Apache::loncommon::authform_header(%param);
  105:     $authformkrb  = &Apache::loncommon::authform_kerberos(%param);
  106:     $authformnop  = &Apache::loncommon::authform_nochange(%param);
  107:     $authformint  = &Apache::loncommon::authform_internal(%param);
  108:     $authformfsys = &Apache::loncommon::authform_filesystem(%param);
  109:     $authformloc  = &Apache::loncommon::authform_local(%param);
  110: }
  111: 
  112: sub auth_abbrev {
  113:     my %abv_auth = (
  114:                      krb5      => 'krb',
  115:                      krb4      => 'krb',
  116:                      internal  => 'int',
  117:                      localauth => 'loc',
  118:                      unix      => 'fsys',
  119:                    );
  120:     return %abv_auth;
  121: }
  122: 
  123: # ====================================================
  124: 
  125: sub user_quotas {
  126:     my ($ccuname,$ccdomain) = @_;
  127:     my %lt = &Apache::lonlocal::texthash(
  128:                    'usrt'      => "User Tools",
  129:                    'cust'      => "Custom quota",
  130:                    'chqu'      => "Change quota",
  131:     );
  132:    
  133:     my $quota_javascript = <<"END_SCRIPT";
  134: <script type="text/javascript">
  135: // <![CDATA[
  136: function quota_changes(caller,context) {
  137:     var customoff = document.getElementById('custom_'+context+'quota_off');
  138:     var customon = document.getElementById('custom_'+context+'quota_on');
  139:     var number = document.getElementById(context+'quota');
  140:     if (caller == "custom") {
  141:         if (customoff) {
  142:             if (customoff.checked) {
  143:                 number.value = "";
  144:             }
  145:         }
  146:     }
  147:     if (caller == "quota") {
  148:         if (customon) {
  149:             customon.checked = true;
  150:         }
  151:     }
  152:     return;
  153: }
  154: // ]]>
  155: </script>
  156: END_SCRIPT
  157:     my $longinsttype;
  158:     my ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($ccdomain);
  159:     my $output = $quota_javascript."\n".
  160:                  '<h3>'.$lt{'usrt'}.'</h3>'."\n".
  161:                  &Apache::loncommon::start_data_table();
  162: 
  163:     if (&Apache::lonnet::allowed('mut',$ccdomain)) {
  164:         $output .= &build_tools_display($ccuname,$ccdomain,'tools');
  165:     }
  166: 
  167:     my %titles = &Apache::lonlocal::texthash (
  168:                     portfolio => "Disk space allocated to user's portfolio files",
  169:                     author    => "Disk space allocated to user's Authoring Space (if role assigned)",
  170:                  );
  171:     foreach my $name ('portfolio','author') {
  172:         my ($currquota,$quotatype,$inststatus,$defquota) =
  173:             &Apache::loncommon::get_user_quota($ccuname,$ccdomain,$name);
  174:         if ($longinsttype eq '') { 
  175:             if ($inststatus ne '') {
  176:                 if ($usertypes->{$inststatus} ne '') {
  177:                     $longinsttype = $usertypes->{$inststatus};
  178:                 }
  179:             }
  180:         }
  181:         my ($showquota,$custom_on,$custom_off,$defaultinfo);
  182:         $custom_on = ' ';
  183:         $custom_off = ' checked="checked" ';
  184:         if ($quotatype eq 'custom') {
  185:             $custom_on = $custom_off;
  186:             $custom_off = ' ';
  187:             $showquota = $currquota;
  188:             if ($longinsttype eq '') {
  189:                 $defaultinfo = &mt('For this user, the default quota would be [_1]'
  190:                               .' MB.',$defquota);
  191:             } else {
  192:                 $defaultinfo = &mt("For this user, the default quota would be [_1]".
  193:                                    " MB, as determined by the user's institutional".
  194:                                    " affiliation ([_2]).",$defquota,$longinsttype);
  195:             }
  196:         } else {
  197:             if ($longinsttype eq '') {
  198:                 $defaultinfo = &mt('For this user, the default quota is [_1]'
  199:                               .' MB.',$defquota);
  200:             } else {
  201:                 $defaultinfo = &mt("For this user, the default quota of [_1]".
  202:                                    " MB, is determined by the user's institutional".
  203:                                    " affiliation ([_2]).",$defquota,$longinsttype);
  204:             }
  205:         }
  206: 
  207:         if (&Apache::lonnet::allowed('mpq',$ccdomain)) {
  208:             $output .= '<tr class="LC_info_row">'."\n".
  209:                        '    <td>'.$titles{$name}.'</td>'."\n".
  210:                        '  </tr>'."\n".
  211:                        &Apache::loncommon::start_data_table_row()."\n".
  212:                        '  <td><span class="LC_nobreak">'.
  213:                        &mt('Current quota: [_1] MB',$currquota).'</span>&nbsp;&nbsp;'.
  214:                        $defaultinfo.'</td>'."\n".
  215:                        &Apache::loncommon::end_data_table_row()."\n".
  216:                        &Apache::loncommon::start_data_table_row()."\n".
  217:                        '  <td><span class="LC_nobreak">'.$lt{'chqu'}.
  218:                        ': <label>'.
  219:                        '<input type="radio" name="custom_'.$name.'quota" id="custom_'.$name.'quota_off" '.
  220:                        'value="0" '.$custom_off.' onchange="javascript:quota_changes('."'custom','$name'".');"'.
  221:                        ' /><span class="LC_nobreak">'.
  222:                        &mt('Default ([_1] MB)',$defquota).'</span></label>&nbsp;'.
  223:                        '&nbsp;<label><input type="radio" name="custom_'.$name.'quota" id="custom_'.$name.'quota_on" '.
  224:                        'value="1" '.$custom_on.'  onchange="javascript:quota_changes('."'custom','$name'".');"'.
  225:                        ' />'.$lt{'cust'}.':</label>&nbsp;'.
  226:                        '<input type="text" name="'.$name.'quota" id="'.$name.'quota" size ="5" '.
  227:                        'value="'.$showquota.'" onfocus="javascript:quota_changes('."'quota','$name'".');"'.
  228:                        ' />&nbsp;'.&mt('MB').'</span></td>'."\n".
  229:                        &Apache::loncommon::end_data_table_row()."\n";
  230:         }
  231:     }
  232:     $output .= &Apache::loncommon::end_data_table();
  233:     return $output;
  234: }
  235: 
  236: sub build_tools_display {
  237:     my ($ccuname,$ccdomain,$context) = @_;
  238:     my (@usertools,%userenv,$output,@options,%validations,%reqtitles,%reqdisplay,
  239:         $colspan,$isadv,%domconfig);
  240:     my %lt = &Apache::lonlocal::texthash (
  241:                    'blog'       => "Personal User Blog",
  242:                    'aboutme'    => "Personal Information Page",
  243:                    'webdav'     => "WebDAV access to Authoring Spaces (if SSL and author/co-author)",
  244:                    'portfolio'  => "Personal User Portfolio",
  245:                    'avai'       => "Available",
  246:                    'cusa'       => "availability",
  247:                    'chse'       => "Change setting",
  248:                    'usde'       => "Use default",
  249:                    'uscu'       => "Use custom",
  250:                    'official'   => 'Can request creation of official courses',
  251:                    'unofficial' => 'Can request creation of unofficial courses',
  252:                    'community'  => 'Can request creation of communities',
  253:                    'textbook'   => 'Can request creation of textbook courses',
  254:                    'requestauthor'  => 'Can request author space',
  255:     );
  256:     if ($context eq 'requestcourses') {
  257:         %userenv = &Apache::lonnet::userenvironment($ccdomain,$ccuname,
  258:                       'requestcourses.official','requestcourses.unofficial',
  259:                       'requestcourses.community','requestcourses.textbook');
  260:         @usertools = ('official','unofficial','community','textbook');
  261:         @options =('norequest','approval','autolimit','validate');
  262:         %validations = &Apache::lonnet::auto_courserequest_checks($ccdomain);
  263:         %reqtitles = &courserequest_titles();
  264:         %reqdisplay = &courserequest_display();
  265:         $colspan = ' colspan="2"';
  266:         %domconfig =
  267:             &Apache::lonnet::get_dom('configuration',['requestcourses'],$ccdomain);
  268:         $isadv = &Apache::lonnet::is_advanced_user($ccuname,$ccdomain);
  269:     } elsif ($context eq 'requestauthor') {
  270:         %userenv = &Apache::lonnet::userenvironment($ccdomain,$ccuname,
  271:                                                     'requestauthor');
  272:         @usertools = ('requestauthor');
  273:         @options =('norequest','approval','automatic');
  274:         %reqtitles = &requestauthor_titles();
  275:         %reqdisplay = &requestauthor_display();
  276:         $colspan = ' colspan="2"';
  277:         %domconfig =
  278:             &Apache::lonnet::get_dom('configuration',['requestauthor'],$ccdomain);
  279:     } else {
  280:         %userenv = &Apache::lonnet::userenvironment($ccdomain,$ccuname,
  281:                           'tools.aboutme','tools.portfolio','tools.blog',
  282:                           'tools.webdav');
  283:         @usertools = ('aboutme','blog','webdav','portfolio');
  284:     }
  285:     foreach my $item (@usertools) {
  286:         my ($custom_access,$curr_access,$cust_on,$cust_off,$tool_on,$tool_off,
  287:             $currdisp,$custdisp,$custradio);
  288:         $cust_off = 'checked="checked" ';
  289:         $tool_on = 'checked="checked" ';
  290:         $curr_access =  
  291:             &Apache::lonnet::usertools_access($ccuname,$ccdomain,$item,undef,
  292:                                               $context);
  293:         if ($context eq 'requestauthor') {
  294:             if ($userenv{$context} ne '') {
  295:                 $cust_on = ' checked="checked" ';
  296:                 $cust_off = '';
  297:             }  
  298:         } elsif ($userenv{$context.'.'.$item} ne '') {
  299:             $cust_on = ' checked="checked" ';
  300:             $cust_off = '';
  301:         }
  302:         if ($context eq 'requestcourses') {
  303:             if ($userenv{$context.'.'.$item} eq '') {
  304:                 $custom_access = &mt('Currently from default setting.');
  305:             } else {
  306:                 $custom_access = &mt('Currently from custom setting.');
  307:             }
  308:         } elsif ($context eq 'requestauthor') {
  309:             if ($userenv{$context} eq '') {
  310:                 $custom_access = &mt('Currently from default setting.');
  311:             } else {
  312:                 $custom_access = &mt('Currently from custom setting.');
  313:             }
  314:         } else {
  315:             if ($userenv{$context.'.'.$item} eq '') {
  316:                 $custom_access =
  317:                     &mt('Availability determined currently from default setting.');
  318:                 if (!$curr_access) {
  319:                     $tool_off = 'checked="checked" ';
  320:                     $tool_on = '';
  321:                 }
  322:             } else {
  323:                 $custom_access =
  324:                     &mt('Availability determined currently from custom setting.');
  325:                 if ($userenv{$context.'.'.$item} == 0) {
  326:                     $tool_off = 'checked="checked" ';
  327:                     $tool_on = '';
  328:                 }
  329:             }
  330:         }
  331:         $output .= '  <tr class="LC_info_row">'."\n".
  332:                    '   <td'.$colspan.'>'.$lt{$item}.'</td>'."\n".
  333:                    '  </tr>'."\n".
  334:                    &Apache::loncommon::start_data_table_row()."\n";
  335:         if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
  336:             my ($curroption,$currlimit);
  337:             my $envkey = $context.'.'.$item;
  338:             if ($context eq 'requestauthor') {
  339:                 $envkey = $context;
  340:             }
  341:             if ($userenv{$envkey} ne '') {
  342:                 $curroption = $userenv{$envkey};
  343:             } else {
  344:                 my (@inststatuses);
  345:                 if ($context eq 'requestcourses') {
  346:                     $curroption =
  347:                         &Apache::loncoursequeueadmin::get_processtype('course',$ccuname,$ccdomain,
  348:                                                                       $isadv,$ccdomain,$item,
  349:                                                                       \@inststatuses,\%domconfig);
  350:                 } else {
  351:                      $curroption = 
  352:                          &Apache::loncoursequeueadmin::get_processtype('requestauthor',$ccuname,$ccdomain,
  353:                                                                        $isadv,$ccdomain,undef,
  354:                                                                        \@inststatuses,\%domconfig);
  355:                 }
  356:             }
  357:             if (!$curroption) {
  358:                 $curroption = 'norequest';
  359:             }
  360:             if ($curroption =~ /^autolimit=(\d*)$/) {
  361:                 $currlimit = $1;
  362:                 if ($currlimit eq '') {
  363:                     $currdisp = &mt('Yes, automatic creation');
  364:                 } else {
  365:                     $currdisp = &mt('Yes, up to [quant,_1,request]/user',$currlimit);
  366:                 }
  367:             } else {
  368:                 $currdisp = $reqdisplay{$curroption};
  369:             }
  370:             $custdisp = '<table>';
  371:             foreach my $option (@options) {
  372:                 my $val = $option;
  373:                 if ($option eq 'norequest') {
  374:                     $val = 0;
  375:                 }
  376:                 if ($option eq 'validate') {
  377:                     my $canvalidate = 0;
  378:                     if (ref($validations{$item}) eq 'HASH') {
  379:                         if ($validations{$item}{'_custom_'}) {
  380:                             $canvalidate = 1;
  381:                         }
  382:                     }
  383:                     next if (!$canvalidate);
  384:                 }
  385:                 my $checked = '';
  386:                 if ($option eq $curroption) {
  387:                     $checked = ' checked="checked"';
  388:                 } elsif ($option eq 'autolimit') {
  389:                     if ($curroption =~ /^autolimit/) {
  390:                         $checked = ' checked="checked"';
  391:                     }
  392:                 }
  393:                 my $name = 'crsreq_'.$item;
  394:                 if ($context eq 'requestauthor') {
  395:                     $name = $item;
  396:                 }
  397:                 $custdisp .= '<tr><td><span class="LC_nobreak"><label>'.
  398:                              '<input type="radio" name="'.$name.'" '.
  399:                              'value="'.$val.'"'.$checked.' />'.
  400:                              $reqtitles{$option}.'</label>&nbsp;';
  401:                 if ($option eq 'autolimit') {
  402:                     $custdisp .= '<input type="text" name="'.$name.
  403:                                  '_limit" size="1" '.
  404:                                  'value="'.$currlimit.'" /></span><br />'.
  405:                                  $reqtitles{'unlimited'};
  406:                 } else {
  407:                     $custdisp .= '</span>';
  408:                 }
  409:                 $custdisp .= '</td></tr>';
  410:             }
  411:             $custdisp .= '</table>';
  412:             $custradio = '</span></td><td>'.&mt('Custom setting').'<br />'.$custdisp;
  413:         } else {
  414:             $currdisp = ($curr_access?&mt('Yes'):&mt('No'));
  415:             my $name = $context.'_'.$item;
  416:             if ($context eq 'requestauthor') {
  417:                 $name = $context;
  418:             }
  419:             $custdisp = '<span class="LC_nobreak"><label>'.
  420:                         '<input type="radio" name="'.$name.'"'.
  421:                         ' value="1" '.$tool_on.'/>'.&mt('On').'</label>&nbsp;<label>'.
  422:                         '<input type="radio" name="'.$name.'" value="0" '.
  423:                         $tool_off.'/>'.&mt('Off').'</label></span>';
  424:             $custradio = ('&nbsp;'x2).'--'.$lt{'cusa'}.':&nbsp;'.$custdisp.
  425:                           '</span>';
  426:         }
  427:         $output .= '  <td'.$colspan.'>'.$custom_access.('&nbsp;'x4).
  428:                    $lt{'avai'}.': '.$currdisp.'</td>'."\n".
  429:                    &Apache::loncommon::end_data_table_row()."\n".
  430:                    &Apache::loncommon::start_data_table_row()."\n".
  431:                    '  <td style="vertical-align:top;"><span class="LC_nobreak">'.
  432:                    $lt{'chse'}.': <label>'.
  433:                    '<input type="radio" name="custom'.$item.'" value="0" '.
  434:                    $cust_off.'/>'.$lt{'usde'}.'</label>'.('&nbsp;' x3).
  435:                    '<label><input type="radio" name="custom'.$item.'" value="1" '.
  436:                    $cust_on.'/>'.$lt{'uscu'}.'</label>'.$custradio.'</td>'.
  437:                    &Apache::loncommon::end_data_table_row()."\n";
  438:     }
  439:     return $output;
  440: }
  441: 
  442: sub coursereq_externaluser {
  443:     my ($ccuname,$ccdomain,$cdom) = @_;
  444:     my (@usertools,@options,%validations,%userenv,$output);
  445:     my %lt = &Apache::lonlocal::texthash (
  446:                    'official'   => 'Can request creation of official courses',
  447:                    'unofficial' => 'Can request creation of unofficial courses',
  448:                    'community'  => 'Can request creation of communities',
  449:                    'textbook'   => 'Can request creation of textbook courses',
  450:     );
  451: 
  452:     %userenv = &Apache::lonnet::userenvironment($ccdomain,$ccuname,
  453:                       'reqcrsotherdom.official','reqcrsotherdom.unofficial',
  454:                       'reqcrsotherdom.community','reqcrsotherdom.textbook');
  455:     @usertools = ('official','unofficial','community','textbook');
  456:     @options = ('approval','validate','autolimit');
  457:     %validations = &Apache::lonnet::auto_courserequest_checks($cdom);
  458:     my $optregex = join('|',@options);
  459:     my %reqtitles = &courserequest_titles();
  460:     foreach my $item (@usertools) {
  461:         my ($curroption,$currlimit,$tooloff);
  462:         if ($userenv{'reqcrsotherdom.'.$item} ne '') {
  463:             my @curr = split(',',$userenv{'reqcrsotherdom.'.$item});
  464:             foreach my $req (@curr) {
  465:                 if ($req =~ /^\Q$cdom\E\:($optregex)=?(\d*)$/) {
  466:                     $curroption = $1;
  467:                     $currlimit = $2;
  468:                     last;
  469:                 }
  470:             }
  471:             if (!$curroption) {
  472:                 $curroption = 'norequest';
  473:                 $tooloff = ' checked="checked"';
  474:             }
  475:         } else {
  476:             $curroption = 'norequest';
  477:             $tooloff = ' checked="checked"';
  478:         }
  479:         $output.= &Apache::loncommon::start_data_table_row()."\n".
  480:                   '  <td><span class="LC_nobreak">'.$lt{$item}.': </span></td><td>'.
  481:                   '<table><tr><td valign="top">'."\n".
  482:                   '<label><input type="radio" name="reqcrsotherdom_'.$item.
  483:                   '" value=""'.$tooloff.' />'.$reqtitles{'norequest'}.
  484:                   '</label></td>';
  485:         foreach my $option (@options) {
  486:             if ($option eq 'validate') {
  487:                 my $canvalidate = 0;
  488:                 if (ref($validations{$item}) eq 'HASH') {
  489:                     if ($validations{$item}{'_external_'}) {
  490:                         $canvalidate = 1;
  491:                     }
  492:                 }
  493:                 next if (!$canvalidate);
  494:             }
  495:             my $checked = '';
  496:             if ($option eq $curroption) {
  497:                 $checked = ' checked="checked"';
  498:             }
  499:             $output .= '<td valign="top"><span class="LC_nobreak"><label>'.
  500:                        '<input type="radio" name="reqcrsotherdom_'.$item.
  501:                        '" value="'.$option.'"'.$checked.' />'.
  502:                        $reqtitles{$option}.'</label>';
  503:             if ($option eq 'autolimit') {
  504:                 $output .= '&nbsp;<input type="text" name="reqcrsotherdom_'.
  505:                            $item.'_limit" size="1" '.
  506:                            'value="'.$currlimit.'" /></span>'.
  507:                            '<br />'.$reqtitles{'unlimited'};
  508:             } else {
  509:                 $output .= '</span>';
  510:             }
  511:             $output .= '</td>';
  512:         }
  513:         $output .= '</td></tr></table></td>'."\n".
  514:                    &Apache::loncommon::end_data_table_row()."\n";
  515:     }
  516:     return $output;
  517: }
  518: 
  519: sub domainrole_req {
  520:     my ($ccuname,$ccdomain) = @_;
  521:     return '<br /><h3>'.
  522:            &mt('User Can Request Assignment of Domain Roles?').
  523:            '</h3>'."\n".
  524:            &Apache::loncommon::start_data_table().
  525:            &build_tools_display($ccuname,$ccdomain,
  526:                                 'requestauthor').
  527:            &Apache::loncommon::end_data_table();
  528: }
  529: 
  530: sub courserequest_titles {
  531:     my %titles = &Apache::lonlocal::texthash (
  532:                                    official   => 'Official',
  533:                                    unofficial => 'Unofficial',
  534:                                    community  => 'Communities',
  535:                                    textbook   => 'Textbook',
  536:                                    norequest  => 'Not allowed',
  537:                                    approval   => 'Approval by Dom. Coord.',
  538:                                    validate   => 'With validation',
  539:                                    autolimit  => 'Numerical limit',
  540:                                    unlimited  => '(blank for unlimited)',
  541:                  );
  542:     return %titles;
  543: }
  544: 
  545: sub courserequest_display {
  546:     my %titles = &Apache::lonlocal::texthash (
  547:                                    approval   => 'Yes, need approval',
  548:                                    validate   => 'Yes, with validation',
  549:                                    norequest  => 'No',
  550:    );
  551:    return %titles;
  552: }
  553: 
  554: sub requestauthor_titles {
  555:     my %titles = &Apache::lonlocal::texthash (
  556:                                    norequest  => 'Not allowed',
  557:                                    approval   => 'Approval by Dom. Coord.',
  558:                                    automatic  => 'Automatic approval',
  559:                  );
  560:     return %titles;
  561: 
  562: }
  563: 
  564: sub requestauthor_display {
  565:     my %titles = &Apache::lonlocal::texthash (
  566:                                    approval   => 'Yes, need approval',
  567:                                    automatic  => 'Yes, automatic approval',
  568:                                    norequest  => 'No',
  569:    );
  570:    return %titles;
  571: }
  572: 
  573: sub requestchange_display {
  574:     my %titles = &Apache::lonlocal::texthash (
  575:                                    approval   => "availability set to 'on' (approval required)", 
  576:                                    automatic  => "availability set to 'on' (automatic approval)",
  577:                                    norequest  => "availability set to 'off'",
  578:    );
  579:    return %titles;
  580: }
  581: 
  582: sub curr_requestauthor {
  583:     my ($uname,$udom,$isadv,$inststatuses,$domconfig) = @_;
  584:     return unless ((ref($inststatuses) eq 'ARRAY') && (ref($domconfig) eq 'HASH'));
  585:     if ($uname eq '' || $udom eq '') {
  586:         $uname = $env{'user.name'};
  587:         $udom = $env{'user.domain'};
  588:         $isadv = $env{'user.adv'};
  589:     }
  590:     my (%userenv,%settings,$val);
  591:     my @options = ('automatic','approval');
  592:     %userenv =
  593:         &Apache::lonnet::userenvironment($udom,$uname,'requestauthor','inststatus');
  594:     if ($userenv{'requestauthor'}) {
  595:         $val = $userenv{'requestauthor'};
  596:         @{$inststatuses} = ('_custom_');
  597:     } else {
  598:         my %alltasks;
  599:         if (ref($domconfig->{'requestauthor'}) eq 'HASH') {
  600:             %settings = %{$domconfig->{'requestauthor'}};
  601:             if (($isadv) && ($settings{'_LC_adv'} ne '')) {
  602:                 $val = $settings{'_LC_adv'};
  603:                 @{$inststatuses} = ('_LC_adv_');
  604:             } else {
  605:                 if ($userenv{'inststatus'} ne '') {
  606:                     @{$inststatuses} = split(',',$userenv{'inststatus'});
  607:                 } else {
  608:                     @{$inststatuses} = ('default');
  609:                 }
  610:                 foreach my $status (@{$inststatuses}) {
  611:                     if (exists($settings{$status})) {
  612:                         my $value = $settings{$status};
  613:                         next unless ($value);
  614:                         unless (exists($alltasks{$value})) {
  615:                             if (ref($alltasks{$value}) eq 'ARRAY') {
  616:                                 unless(grep(/^\Q$status\E$/,@{$alltasks{$value}})) {
  617:                                     push(@{$alltasks{$value}},$status);
  618:                                 }
  619:                             } else {
  620:                                 @{$alltasks{$value}} = ($status);
  621:                             }
  622:                         }
  623:                     }
  624:                 }
  625:                 foreach my $option (@options) {
  626:                     if ($alltasks{$option}) {
  627:                         $val = $option;
  628:                         last;
  629:                     }
  630:                 }
  631:             }
  632:         }
  633:     }
  634:     return $val;
  635: }
  636: 
  637: # =================================================================== Phase one
  638: 
  639: sub print_username_entry_form {
  640:     my ($r,$context,$response,$srch,$forcenewuser,$crstype,$brcrum) = @_;
  641:     my $defdom=$env{'request.role.domain'};
  642:     my $formtoset = 'crtuser';
  643:     if (exists($env{'form.startrolename'})) {
  644:         $formtoset = 'docustom';
  645:         $env{'form.rolename'} = $env{'form.startrolename'};
  646:     } elsif ($env{'form.origform'} eq 'crtusername') {
  647:         $formtoset =  $env{'form.origform'};
  648:     }
  649: 
  650:     my ($jsback,$elements) = &crumb_utilities();
  651: 
  652:     my $jscript = &Apache::loncommon::studentbrowser_javascript()."\n".
  653:         '<script type="text/javascript">'."\n".
  654:         '// <![CDATA['."\n".
  655:         &Apache::lonhtmlcommon::set_form_elements($elements->{$formtoset})."\n".
  656:         '// ]]>'."\n".
  657:         '</script>'."\n";
  658: 
  659:     my %existingroles=&Apache::lonuserutils::my_custom_roles($crstype);
  660:     if (($env{'form.action'} eq 'custom') && (keys(%existingroles) > 0)
  661:         && (&Apache::lonnet::allowed('mcr','/'))) {
  662:         $jscript .= &customrole_javascript();
  663:     }
  664:     my $helpitem = 'Course_Change_Privileges';
  665:     if ($env{'form.action'} eq 'custom') {
  666:         $helpitem = 'Course_Editing_Custom_Roles';
  667:     } elsif ($env{'form.action'} eq 'singlestudent') {
  668:         $helpitem = 'Course_Add_Student';
  669:     }
  670:     my %breadcrumb_text = &singleuser_breadcrumb($crstype);
  671:     if ($env{'form.action'} eq 'custom') {
  672:         push(@{$brcrum},
  673:                  {href=>"javascript:backPage(document.crtuser)",       
  674:                   text=>"Pick custom role",
  675:                   help => $helpitem,}
  676:                  );
  677:     } else {
  678:         push (@{$brcrum},
  679:                   {href => "javascript:backPage(document.crtuser)",
  680:                    text => $breadcrumb_text{'search'},
  681:                    help => $helpitem,
  682:                    faq  => 282,
  683:                    bug  => 'Instructor Interface',}
  684:                   );
  685:     }
  686:     my %loaditems = (
  687:                 'onload' => "javascript:setFormElements(document.$formtoset)",
  688:                     );
  689:     my $args = {bread_crumbs           => $brcrum,
  690:                 bread_crumbs_component => 'User Management',
  691:                 add_entries            => \%loaditems,};
  692:     $r->print(&Apache::loncommon::start_page('User Management',$jscript,$args));
  693: 
  694:     my %lt=&Apache::lonlocal::texthash(
  695:                     'srst' => 'Search for a user and enroll as a student',
  696:                     'srme' => 'Search for a user and enroll as a member',
  697:                     'srad' => 'Search for a user and modify/add user information or roles',
  698: 		    'usr'  => "Username",
  699:                     'dom'  => "Domain",
  700:                     'ecrp' => "Define or Edit Custom Role",
  701:                     'nr'   => "role name",
  702:                     'cre'  => "Next",
  703: 				       );
  704: 
  705:     if ($env{'form.action'} eq 'custom') {
  706:         if (&Apache::lonnet::allowed('mcr','/')) {
  707:             my $newroletext = &mt('Define new custom role:');
  708:             $r->print('<form action="/adm/createuser" method="post" name="docustom">'.
  709:                       '<input type="hidden" name="action" value="'.$env{'form.action'}.'" />'.
  710:                       '<input type="hidden" name="phase" value="selected_custom_edit" />'.
  711:                       '<h3>'.$lt{'ecrp'}.'</h3>'.
  712:                       &Apache::loncommon::start_data_table().
  713:                       &Apache::loncommon::start_data_table_row().
  714:                       '<td>');
  715:             if (keys(%existingroles) > 0) {
  716:                 $r->print('<br /><label><input type="radio" name="customroleaction" value="new" checked="checked" onclick="setCustomFields();" /><b>'.$newroletext.'</b></label>');
  717:             } else {
  718:                 $r->print('<br /><input type="hidden" name="customroleaction" value="new" /><b>'.$newroletext.'</b>');
  719:             }
  720:             $r->print('</td><td align="center">'.$lt{'nr'}.'<br /><input type="text" size="15" name="newrolename" onfocus="setCustomAction('."'new'".');" /></td>'.
  721:                       &Apache::loncommon::end_data_table_row());
  722:             if (keys(%existingroles) > 0) {
  723:                 $r->print(&Apache::loncommon::start_data_table_row().'<td><br />'.
  724:                           '<label><input type="radio" name="customroleaction" value="edit" onclick="setCustomFields();"/><b>'.
  725:                           &mt('View/Modify existing role:').'</b></label></td>'.
  726:                           '<td align="center"><br />'.
  727:                           '<select name="rolename" onchange="setCustomAction('."'edit'".');">'.
  728:                           '<option value="" selected="selected">'.
  729:                           &mt('Select'));
  730:                 foreach my $role (sort(keys(%existingroles))) {
  731:                     $r->print('<option value="'.$role.'">'.$role.'</option>');
  732:                 }
  733:                 $r->print('</select>'.
  734:                           '</td>'.
  735:                           &Apache::loncommon::end_data_table_row());
  736:             }
  737:             $r->print(&Apache::loncommon::end_data_table().'<p>'.
  738:                       '<input name="customeditor" type="submit" value="'.
  739:                       $lt{'cre'}.'" /></p>'.
  740:                       '</form>');
  741:         }
  742:     } else {
  743:         my $actiontext = $lt{'srad'};
  744:         if ($env{'form.action'} eq 'singlestudent') {
  745:             if ($crstype eq 'Community') {
  746:                 $actiontext = $lt{'srme'};
  747:             } else {
  748:                 $actiontext = $lt{'srst'};
  749:             }
  750:         }
  751:         $r->print("<h3>$actiontext</h3>");
  752:         if ($env{'form.origform'} ne 'crtusername') {
  753:             $r->print("\n".$response);
  754:         }
  755:         $r->print(&entry_form($defdom,$srch,$forcenewuser,$context,$response,$crstype));
  756:     }
  757: }
  758: 
  759: sub customrole_javascript {
  760:     my $js = <<"END";
  761: <script type="text/javascript">
  762: // <![CDATA[
  763: 
  764: function setCustomFields() {
  765:     if (document.docustom.customroleaction.length > 0) {
  766:         for (var i=0; i<document.docustom.customroleaction.length; i++) {
  767:             if (document.docustom.customroleaction[i].checked) {
  768:                 if (document.docustom.customroleaction[i].value == 'new') {
  769:                     document.docustom.rolename.selectedIndex = 0;
  770:                 } else {
  771:                     document.docustom.newrolename.value = '';
  772:                 }
  773:             }
  774:         }
  775:     }
  776:     return;
  777: }
  778: 
  779: function setCustomAction(caller) {
  780:     if (document.docustom.customroleaction.length > 0) {
  781:         for (var i=0; i<document.docustom.customroleaction.length; i++) {
  782:             if (document.docustom.customroleaction[i].value == caller) {
  783:                 document.docustom.customroleaction[i].checked = true;
  784:             }
  785:         }
  786:     }
  787:     setCustomFields();
  788:     return;
  789: }
  790: 
  791: // ]]>
  792: </script>
  793: END
  794:     return $js;
  795: }
  796: 
  797: sub entry_form {
  798:     my ($dom,$srch,$forcenewuser,$context,$responsemsg,$crstype) = @_;
  799:     my ($usertype,$inexact);
  800:     if (ref($srch) eq 'HASH') {
  801:         if (($srch->{'srchin'} eq 'dom') &&
  802:             ($srch->{'srchby'} eq 'uname') &&
  803:             ($srch->{'srchtype'} eq 'exact') &&
  804:             ($srch->{'srchdomain'} ne '') &&
  805:             ($srch->{'srchterm'} ne '')) {
  806:             my (%curr_rules,%got_rules);
  807:             my ($rules,$ruleorder) =
  808:                 &Apache::lonnet::inst_userrules($srch->{'srchdomain'},'username');
  809:             $usertype = &Apache::lonuserutils::check_usertype($srch->{'srchdomain'},$srch->{'srchterm'},$rules,\%curr_rules,\%got_rules);
  810:         } else {
  811:             $inexact = 1;
  812:         }
  813:     }
  814:     my $cancreate =
  815:         &Apache::lonuserutils::can_create_user($dom,$context,$usertype);
  816:     my ($userpicker,$cansearch) = 
  817:        &Apache::loncommon::user_picker($dom,$srch,$forcenewuser,
  818:                                        'document.crtuser',$cancreate,$usertype);
  819:     my $srchbutton = &mt('Search');
  820:     if ($env{'form.action'} eq 'singlestudent') {
  821:         $srchbutton = &mt('Search and Enroll');
  822:     } elsif ($cancreate && $responsemsg ne '' && $inexact) {
  823:         $srchbutton = &mt('Search or Add New User');
  824:     }
  825:     my $output;
  826:     if ($cansearch) {
  827:         $output = <<"ENDBLOCK";
  828: <form action="/adm/createuser" method="post" name="crtuser">
  829: <input type="hidden" name="action" value="$env{'form.action'}" />
  830: <input type="hidden" name="phase" value="get_user_info" />
  831: $userpicker
  832: <input name="userrole" type="button" value="$srchbutton" onclick="javascript:validateEntry(document.crtuser)" />
  833: </form>
  834: ENDBLOCK
  835:     } else {
  836:         $output = '<p>'.$userpicker.'</p>';
  837:     }
  838:     if ($env{'form.phase'} eq '') {
  839:         my $defdom=$env{'request.role.domain'};
  840:         my $domform = &Apache::loncommon::select_dom_form($defdom,'srchdomain');
  841:         my %lt=&Apache::lonlocal::texthash(
  842:                   'enro' => 'Enroll one student',
  843:                   'enrm' => 'Enroll one member',
  844:                   'admo' => 'Add/modify a single user',
  845:                   'crea' => 'create new user if required',
  846:                   'uskn' => "username is known",
  847:                   'crnu' => 'Create a new user',
  848:                   'usr'  => 'Username',
  849:                   'dom'  => 'in domain',
  850:                   'enrl' => 'Enroll',
  851:                   'cram'  => 'Create/Modify user',
  852:         );
  853:         my $sellink=&Apache::loncommon::selectstudent_link('crtusername','srchterm','srchdomain');
  854:         my ($title,$buttontext,$showresponse);
  855:         if ($env{'form.action'} eq 'singlestudent') {
  856:             if ($crstype eq 'Community') {
  857:                 $title = $lt{'enrm'};
  858:             } else {
  859:                 $title = $lt{'enro'};
  860:             }
  861:             $buttontext = $lt{'enrl'};
  862:         } else {
  863:             $title = $lt{'admo'};
  864:             $buttontext = $lt{'cram'};
  865:         }
  866:         if ($cancreate) {
  867:             $title .= ' <span class="LC_cusr_subheading">('.$lt{'crea'}.')</span>';
  868:         } else {
  869:             $title .= ' <span class="LC_cusr_subheading">('.$lt{'uskn'}.')</span>';
  870:         }
  871:         if ($env{'form.origform'} eq 'crtusername') {
  872:             $showresponse = $responsemsg;
  873:         }
  874:         $output .= <<"ENDDOCUMENT";
  875: <br />
  876: <form action="/adm/createuser" method="post" name="crtusername">
  877: <input type="hidden" name="action" value="$env{'form.action'}" />
  878: <input type="hidden" name="phase" value="createnewuser" />
  879: <input type="hidden" name="srchtype" value="exact" />
  880: <input type="hidden" name="srchby" value="uname" />
  881: <input type="hidden" name="srchin" value="dom" />
  882: <input type="hidden" name="forcenewuser" value="1" />
  883: <input type="hidden" name="origform" value="crtusername" />
  884: <h3>$title</h3>
  885: $showresponse
  886: <table>
  887:  <tr>
  888:   <td>$lt{'usr'}:</td>
  889:   <td><input type="text" size="15" name="srchterm" /></td>
  890:   <td>&nbsp;$lt{'dom'}:</td><td>$domform</td>
  891:   <td>&nbsp;$sellink&nbsp;</td>
  892:   <td>&nbsp;<input name="userrole" type="submit" value="$buttontext" /></td>
  893:  </tr>
  894: </table>
  895: </form>
  896: ENDDOCUMENT
  897:     }
  898:     return $output;
  899: }
  900: 
  901: sub user_modification_js {
  902:     my ($pjump_def,$dc_setcourse_code,$nondc_setsection_code,$groupslist)=@_;
  903:     
  904:     return <<END;
  905: <script type="text/javascript" language="Javascript">
  906: // <![CDATA[
  907: 
  908:     $pjump_def
  909:     $dc_setcourse_code
  910: 
  911:     function dateset() {
  912:         eval("document.cu."+document.cu.pres_marker.value+
  913:             ".value=document.cu.pres_value.value");
  914:         modalWindow.close();
  915:     }
  916: 
  917:     $nondc_setsection_code
  918: // ]]>
  919: </script>
  920: END
  921: }
  922: 
  923: # =================================================================== Phase two
  924: sub print_user_selection_page {
  925:     my ($r,$response,$srch,$srch_results,$srcharray,$context,$opener_elements,$crstype,$brcrum) = @_;
  926:     my @fields = ('username','domain','lastname','firstname','permanentemail');
  927:     my $sortby = $env{'form.sortby'};
  928: 
  929:     if (!grep(/^\Q$sortby\E$/,@fields)) {
  930:         $sortby = 'lastname';
  931:     }
  932: 
  933:     my ($jsback,$elements) = &crumb_utilities();
  934: 
  935:     my $jscript = (<<ENDSCRIPT);
  936: <script type="text/javascript">
  937: // <![CDATA[
  938: function pickuser(uname,udom) {
  939:     document.usersrchform.seluname.value=uname;
  940:     document.usersrchform.seludom.value=udom;
  941:     document.usersrchform.phase.value="userpicked";
  942:     document.usersrchform.submit();
  943: }
  944: 
  945: $jsback
  946: // ]]>
  947: </script>
  948: ENDSCRIPT
  949: 
  950:     my %lt=&Apache::lonlocal::texthash(
  951:                                        'usrch'          => "User Search to add/modify roles",
  952:                                        'stusrch'        => "User Search to enroll student",
  953:                                        'memsrch'        => "User Search to enroll member",
  954:                                        'usel'           => "Select a user to add/modify roles",
  955:                                        'stusel'         => "Select a user to enroll as a student",
  956:                                        'memsel'         => "Select a user to enroll as a member",
  957:                                        'username'       => "username",
  958:                                        'domain'         => "domain",
  959:                                        'lastname'       => "last name",
  960:                                        'firstname'      => "first name",
  961:                                        'permanentemail' => "permanent e-mail",
  962:                                       );
  963:     if ($context eq 'requestcrs') {
  964:         $r->print('<div>');
  965:     } else {
  966:         my %breadcrumb_text = &singleuser_breadcrumb($crstype);
  967:         my $helpitem;
  968:         if ($env{'form.action'} eq 'singleuser') {
  969:             $helpitem = 'Course_Change_Privileges';
  970:         } elsif ($env{'form.action'} eq 'singlestudent') {
  971:             $helpitem = 'Course_Add_Student';
  972:         }
  973:         push (@{$brcrum},
  974:                   {href => "javascript:backPage(document.usersrchform,'','')",
  975:                    text => $breadcrumb_text{'search'},
  976:                    faq  => 282,
  977:                    bug  => 'Instructor Interface',},
  978:                   {href => "javascript:backPage(document.usersrchform,'get_user_info','select')",
  979:                    text => $breadcrumb_text{'userpicked'},
  980:                    faq  => 282,
  981:                    bug  => 'Instructor Interface',
  982:                    help => $helpitem}
  983:                   );
  984:         $r->print(&Apache::loncommon::start_page('User Management',$jscript,{bread_crumbs => $brcrum}));
  985:         if ($env{'form.action'} eq 'singleuser') {
  986:             $r->print("<b>$lt{'usrch'}</b><br />");
  987:             $r->print(&entry_form($srch->{'srchdomain'},$srch,undef,$context,undef,$crstype));
  988:             $r->print('<h3>'.$lt{'usel'}.'</h3>');
  989:         } elsif ($env{'form.action'} eq 'singlestudent') {
  990:             $r->print($jscript."<b>");
  991:             if ($crstype eq 'Community') {
  992:                 $r->print($lt{'memsrch'});
  993:             } else {
  994:                 $r->print($lt{'stusrch'});
  995:             }
  996:             $r->print("</b><br />");
  997:             $r->print(&entry_form($srch->{'srchdomain'},$srch,undef,$context,undef,$crstype));
  998:             $r->print('</form><h3>');
  999:             if ($crstype eq 'Community') {
 1000:                 $r->print($lt{'memsel'});
 1001:             } else {
 1002:                 $r->print($lt{'stusel'});
 1003:             }
 1004:             $r->print('</h3>');
 1005:         }
 1006:     }
 1007:     $r->print('<form name="usersrchform" method="post" action="">'.
 1008:               &Apache::loncommon::start_data_table()."\n".
 1009:               &Apache::loncommon::start_data_table_header_row()."\n".
 1010:               ' <th> </th>'."\n");
 1011:     foreach my $field (@fields) {
 1012:         $r->print(' <th><a href="javascript:document.usersrchform.sortby.value='.
 1013:                   "'".$field."'".';document.usersrchform.submit();">'.
 1014:                   $lt{$field}.'</a></th>'."\n");
 1015:     }
 1016:     $r->print(&Apache::loncommon::end_data_table_header_row());
 1017: 
 1018:     my @sorted_users = sort {
 1019:         lc($srch_results->{$a}->{$sortby})   cmp lc($srch_results->{$b}->{$sortby})
 1020:             ||
 1021:         lc($srch_results->{$a}->{lastname})  cmp lc($srch_results->{$b}->{lastname})
 1022:             ||
 1023:         lc($srch_results->{$a}->{firstname}) cmp lc($srch_results->{$b}->{firstname})
 1024: 	    ||
 1025: 	lc($a) cmp lc($b)
 1026:         } (keys(%$srch_results));
 1027: 
 1028:     foreach my $user (@sorted_users) {
 1029:         my ($uname,$udom) = split(/:/,$user);
 1030:         my $onclick;
 1031:         if ($context eq 'requestcrs') {
 1032:             $onclick =
 1033:                 'onclick="javascript:gochoose('."'$uname','$udom',".
 1034:                                                "'$srch_results->{$user}->{firstname}',".
 1035:                                                "'$srch_results->{$user}->{lastname}',".
 1036:                                                "'$srch_results->{$user}->{permanentemail}'".');"';
 1037:         } else {
 1038:             $onclick =
 1039:                 ' onclick="javascript:pickuser('."'".$uname."'".','."'".$udom."'".');"';
 1040:         }
 1041:         $r->print(&Apache::loncommon::start_data_table_row().
 1042:                   '<td><input type="button" name="seluser" value="'.&mt('Select').'" '.
 1043:                   $onclick.' /></td>'.
 1044:                   '<td><tt>'.$uname.'</tt></td>'.
 1045:                   '<td><tt>'.$udom.'</tt></td>');
 1046:         foreach my $field ('lastname','firstname','permanentemail') {
 1047:             $r->print('<td>'.$srch_results->{$user}->{$field}.'</td>');
 1048:         }
 1049:         $r->print(&Apache::loncommon::end_data_table_row());
 1050:     }
 1051:     $r->print(&Apache::loncommon::end_data_table().'<br /><br />');
 1052:     if (ref($srcharray) eq 'ARRAY') {
 1053:         foreach my $item (@{$srcharray}) {
 1054:             $r->print('<input type="hidden" name="'.$item.'" value="'.$env{'form.'.$item}.'" />'."\n");
 1055:         }
 1056:     }
 1057:     $r->print(' <input type="hidden" name="sortby" value="'.$sortby.'" />'."\n".
 1058:               ' <input type="hidden" name="seluname" value="" />'."\n".
 1059:               ' <input type="hidden" name="seludom" value="" />'."\n".
 1060:               ' <input type="hidden" name="currstate" value="select" />'."\n".
 1061:               ' <input type="hidden" name="phase" value="get_user_info" />'."\n".
 1062:               ' <input type="hidden" name="action" value="'.$env{'form.action'}.'" />'."\n");
 1063:     if ($context eq 'requestcrs') {
 1064:         $r->print($opener_elements.'</form></div>');
 1065:     } else {
 1066:         $r->print($response.'</form>');
 1067:     }
 1068: }
 1069: 
 1070: sub print_user_query_page {
 1071:     my ($r,$caller,$brcrum) = @_;
 1072: # FIXME - this is for a network-wide name search (similar to catalog search)
 1073: # To use frames with similar behavior to catalog/portfolio search.
 1074: # To be implemented. 
 1075:     return;
 1076: }
 1077: 
 1078: sub print_user_modification_page {
 1079:     my ($r,$ccuname,$ccdomain,$srch,$response,$context,$permission,$crstype,
 1080:         $brcrum,$showcredits) = @_;
 1081:     if (($ccuname eq '') || ($ccdomain eq '')) {
 1082:         my $usermsg = &mt('No username and/or domain provided.');
 1083:         $env{'form.phase'} = '';
 1084: 	&print_username_entry_form($r,$context,$usermsg,'','',$crstype,$brcrum);
 1085:         return;
 1086:     }
 1087:     my ($form,$formname);
 1088:     if ($env{'form.action'} eq 'singlestudent') {
 1089:         $form = 'document.enrollstudent';
 1090:         $formname = 'enrollstudent';
 1091:     } else {
 1092:         $form = 'document.cu';
 1093:         $formname = 'cu';
 1094:     }
 1095:     my %abv_auth = &auth_abbrev();
 1096:     my (%rulematch,%inst_results,$newuser,%alerts,%curr_rules,%got_rules);
 1097:     my $uhome=&Apache::lonnet::homeserver($ccuname,$ccdomain);
 1098:     if ($uhome eq 'no_host') {
 1099:         my $usertype;
 1100:         my ($rules,$ruleorder) =
 1101:             &Apache::lonnet::inst_userrules($ccdomain,'username');
 1102:             $usertype =
 1103:                 &Apache::lonuserutils::check_usertype($ccdomain,$ccuname,$rules,
 1104:                                                       \%curr_rules,\%got_rules);
 1105:         my $cancreate =
 1106:             &Apache::lonuserutils::can_create_user($ccdomain,$context,
 1107:                                                    $usertype);
 1108:         if (!$cancreate) {
 1109:             my $helplink = 'javascript:helpMenu('."'display'".')';
 1110:             my %usertypetext = (
 1111:                 official   => 'institutional',
 1112:                 unofficial => 'non-institutional',
 1113:             );
 1114:             my $response;
 1115:             if ($env{'form.origform'} eq 'crtusername') {
 1116:                 $response = '<span class="LC_warning">'.
 1117:                             &mt('No match found for the username [_1] in LON-CAPA domain: [_2]',
 1118:                                 '<b>'.$ccuname.'</b>',$ccdomain).
 1119:                             '</span><br />';
 1120:             }
 1121:             $response .= '<p class="LC_warning">'
 1122:                         .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
 1123:                         .' '
 1124:                         .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
 1125:                             ,'<a href="'.$helplink.'">','</a>')
 1126:                         .'</p><br />';
 1127:             $env{'form.phase'} = '';
 1128:             &print_username_entry_form($r,$context,$response,undef,undef,$crstype,$brcrum);
 1129:             return;
 1130:         }
 1131:         $newuser = 1;
 1132:         my $checkhash;
 1133:         my $checks = { 'username' => 1 };
 1134:         $checkhash->{$ccuname.':'.$ccdomain} = { 'newuser' => $newuser };
 1135:         &Apache::loncommon::user_rule_check($checkhash,$checks,
 1136:             \%alerts,\%rulematch,\%inst_results,\%curr_rules,\%got_rules);
 1137:         if (ref($alerts{'username'}) eq 'HASH') {
 1138:             if (ref($alerts{'username'}{$ccdomain}) eq 'HASH') {
 1139:                 my $domdesc =
 1140:                     &Apache::lonnet::domain($ccdomain,'description');
 1141:                 if ($alerts{'username'}{$ccdomain}{$ccuname}) {
 1142:                     my $userchkmsg;
 1143:                     if (ref($curr_rules{$ccdomain}) eq 'HASH') {  
 1144:                         $userchkmsg = 
 1145:                             &Apache::loncommon::instrule_disallow_msg('username',
 1146:                                                                  $domdesc,1).
 1147:                         &Apache::loncommon::user_rule_formats($ccdomain,
 1148:                             $domdesc,$curr_rules{$ccdomain}{'username'},
 1149:                             'username');
 1150:                     }
 1151:                     $env{'form.phase'} = '';
 1152:                     &print_username_entry_form($r,$context,$userchkmsg,undef,undef,$crstype,$brcrum);
 1153:                     return;
 1154:                 }
 1155:             }
 1156:         }
 1157:     } else {
 1158:         $newuser = 0;
 1159:     }
 1160:     if ($response) {
 1161:         $response = '<br />'.$response;
 1162:     }
 1163: 
 1164:     my $pjump_def = &Apache::lonhtmlcommon::pjump_javascript_definition();
 1165:     my $dc_setcourse_code = '';
 1166:     my $nondc_setsection_code = '';                                        
 1167:     my %loaditem;
 1168: 
 1169:     my $groupslist = &Apache::lonuserutils::get_groupslist();
 1170: 
 1171:     my $js = &validation_javascript($context,$ccdomain,$pjump_def,$crstype,
 1172:                                $groupslist,$newuser,$formname,\%loaditem);
 1173:     my %breadcrumb_text = &singleuser_breadcrumb($crstype);
 1174:     my $helpitem = 'Course_Change_Privileges';
 1175:     if ($env{'form.action'} eq 'singlestudent') {
 1176:         $helpitem = 'Course_Add_Student';
 1177:     }
 1178:     push (@{$brcrum},
 1179:         {href => "javascript:backPage($form)",
 1180:          text => $breadcrumb_text{'search'},
 1181:          faq  => 282,
 1182:          bug  => 'Instructor Interface',});
 1183:     if ($env{'form.phase'} eq 'userpicked') {
 1184:        push(@{$brcrum},
 1185:               {href => "javascript:backPage($form,'get_user_info','select')",
 1186:                text => $breadcrumb_text{'userpicked'},
 1187:                faq  => 282,
 1188:                bug  => 'Instructor Interface',});
 1189:     }
 1190:     push(@{$brcrum},
 1191:             {href => "javascript:backPage($form,'$env{'form.phase'}','modify')",
 1192:              text => $breadcrumb_text{'modify'},
 1193:              faq  => 282,
 1194:              bug  => 'Instructor Interface',
 1195:              help => $helpitem});
 1196:     my $args = {'add_entries'           => \%loaditem,
 1197:                 'bread_crumbs'          => $brcrum,
 1198:                 'bread_crumbs_component' => 'User Management'};
 1199:     if ($env{'form.popup'}) {
 1200:         $args->{'no_nav_bar'} = 1;
 1201:     }
 1202:     my $start_page =
 1203:         &Apache::loncommon::start_page('User Management',$js,$args);
 1204: 
 1205:     my $forminfo =<<"ENDFORMINFO";
 1206: <form action="/adm/createuser" method="post" name="$formname">
 1207: <input type="hidden" name="phase" value="update_user_data" />
 1208: <input type="hidden" name="ccuname" value="$ccuname" />
 1209: <input type="hidden" name="ccdomain" value="$ccdomain" />
 1210: <input type="hidden" name="pres_value"  value="" />
 1211: <input type="hidden" name="pres_type"   value="" />
 1212: <input type="hidden" name="pres_marker" value="" />
 1213: ENDFORMINFO
 1214:     my (%inccourses,$roledom,$defaultcredits);
 1215:     if ($context eq 'course') {
 1216:         $inccourses{$env{'request.course.id'}}=1;
 1217:         $roledom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 1218:         if ($showcredits) {
 1219:             $defaultcredits = &Apache::lonuserutils::get_defaultcredits();
 1220:         }
 1221:     } elsif ($context eq 'author') {
 1222:         $roledom = $env{'request.role.domain'};
 1223:     } elsif ($context eq 'domain') {
 1224:         foreach my $key (keys(%env)) {
 1225:             $roledom = $env{'request.role.domain'};
 1226:             if ($key=~/^user\.priv\.cm\.\/($roledom)\/($match_username)/) {
 1227:                 $inccourses{$1.'_'.$2}=1;
 1228:             }
 1229:         }
 1230:     } else {
 1231:         foreach my $key (keys(%env)) {
 1232: 	    if ($key=~/^user\.priv\.cm\.\/($match_domain)\/($match_username)/) {
 1233: 	        $inccourses{$1.'_'.$2}=1;
 1234:             }
 1235:         }
 1236:     }
 1237:     my $title = '';
 1238:     if ($newuser) {
 1239:         my ($portfolioform,$domroleform);
 1240:         if ((&Apache::lonnet::allowed('mpq',$env{'request.role.domain'})) ||
 1241:             (&Apache::lonnet::allowed('mut',$env{'request.role.domain'}))) {
 1242:             # Current user has quota or user tools modification privileges
 1243:             $portfolioform = '<br />'.&user_quotas($ccuname,$ccdomain);
 1244:         }
 1245:         if ((&Apache::lonnet::allowed('cau',$env{'request.role.domain'})) &&
 1246:             ($ccdomain eq $env{'request.role.domain'})) {
 1247:             $domroleform = '<br />'.&domainrole_req($ccuname,$ccdomain);
 1248:         }
 1249:         &initialize_authen_forms($ccdomain,$formname);
 1250:         my %lt=&Apache::lonlocal::texthash(
 1251:                 'lg'             => 'Login Data',
 1252:                 'hs'             => "Home Server",
 1253:         );
 1254: 	$r->print(<<ENDTITLE);
 1255: $start_page
 1256: $response
 1257: $forminfo
 1258: <script type="text/javascript" language="Javascript">
 1259: // <![CDATA[
 1260: $loginscript
 1261: // ]]>
 1262: </script>
 1263: <input type='hidden' name='makeuser' value='1' />
 1264: ENDTITLE
 1265:         if ($env{'form.action'} eq 'singlestudent') {
 1266:             if ($crstype eq 'Community') {
 1267:                 $title = &mt('Create New User [_1] in domain [_2] as a member',
 1268:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1269:             } else {
 1270:                 $title = &mt('Create New User [_1] in domain [_2] as a student',
 1271:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1272:             }
 1273:         } else {
 1274:                 $title = &mt('Create New User [_1] in domain [_2]',
 1275:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1276:         }
 1277:         $r->print('<h2>'.$title.'</h2>'."\n");
 1278:         $r->print('<div class="LC_left_float">');
 1279:         $r->print(&personal_data_display($ccuname,$ccdomain,$newuser,$context,
 1280:                                          $inst_results{$ccuname.':'.$ccdomain}));
 1281:         # Option to disable student/employee ID conflict checking not offerred for new users.
 1282:         my ($home_server_pick,$numlib) = 
 1283:             &Apache::loncommon::home_server_form_item($ccdomain,'hserver',
 1284:                                                       'default','hide');
 1285:         if ($numlib > 1) {
 1286:             $r->print("
 1287: <br />
 1288: $lt{'hs'}: $home_server_pick
 1289: <br />");
 1290:         } else {
 1291:             $r->print($home_server_pick);
 1292:         }
 1293:         if (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) {
 1294:             $r->print('<br /><h3>'.
 1295:                       &mt('User Can Request Creation of Courses/Communities in this Domain?').'</h3>'.
 1296:                       &Apache::loncommon::start_data_table().
 1297:                       &build_tools_display($ccuname,$ccdomain,
 1298:                                            'requestcourses').
 1299:                       &Apache::loncommon::end_data_table());
 1300:         }
 1301:         $r->print('</div>'."\n".'<div class="LC_left_float"><h3>'.
 1302:                   $lt{'lg'}.'</h3>');
 1303:         my ($fixedauth,$varauth,$authmsg); 
 1304:         if (ref($rulematch{$ccuname.':'.$ccdomain}) eq 'HASH') {
 1305:             my $matchedrule = $rulematch{$ccuname.':'.$ccdomain}{'username'};
 1306:             my ($rules,$ruleorder) = 
 1307:                 &Apache::lonnet::inst_userrules($ccdomain,'username');
 1308:             if (ref($rules) eq 'HASH') {
 1309:                 if (ref($rules->{$matchedrule}) eq 'HASH') {
 1310:                     my $authtype = $rules->{$matchedrule}{'authtype'};
 1311:                     if ($authtype !~ /^(krb4|krb5|int|fsys|loc)$/) {
 1312:                         $r->print(&Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc));
 1313:                     } else { 
 1314:                         my $authparm = $rules->{$matchedrule}{'authparm'};
 1315:                         $authmsg = $rules->{$matchedrule}{'authmsg'};
 1316:                         if ($authtype =~ /^krb(4|5)$/) {
 1317:                             my $ver = $1;
 1318:                             if ($authparm ne '') {
 1319:                                 $fixedauth = <<"KERB"; 
 1320: <input type="hidden" name="login" value="krb" />
 1321: <input type="hidden" name="krbver" value="$ver" />
 1322: <input type="hidden" name="krbarg" value="$authparm" />
 1323: KERB
 1324:                             }
 1325:                         } else {
 1326:                             $fixedauth = 
 1327: '<input type="hidden" name="login" value="'.$authtype.'" />'."\n";
 1328:                             if ($rules->{$matchedrule}{'authparmfixed'}) {
 1329:                                 $fixedauth .=    
 1330: '<input type="hidden" name="'.$authtype.'arg" value="'.$authparm.'" />'."\n";
 1331:                             } else {
 1332:                                 if ($authtype eq 'int') {
 1333:                                     $varauth = '<br />'.
 1334: &mt('[_1] Internally authenticated (with initial password [_2])','','<input type="password" size="10" name="intarg" value="" />')."<label><input type=\"checkbox\" name=\"visible\" onclick='if (this.checked) { this.form.intarg.type=\"text\" } else { this.form.intarg.type=\"password\" }' />".&mt('Visible input').'</label>';
 1335:                                 } elsif ($authtype eq 'loc') {
 1336:                                     $varauth = '<br />'.
 1337: &mt('[_1] Local Authentication with argument [_2]','','<input type="text" name="'.$authtype.'arg" value="" />')."\n";
 1338:                                 } else {
 1339:                                     $varauth =
 1340: '<input type="text" name="'.$authtype.'arg" value="" />'."\n";
 1341:                                 }
 1342:                             }
 1343:                         }
 1344:                     }
 1345:                 } else {
 1346:                     $r->print(&Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc));
 1347:                 }
 1348:             }
 1349:             if ($authmsg) {
 1350:                 $r->print(<<ENDAUTH);
 1351: $fixedauth
 1352: $authmsg
 1353: $varauth
 1354: ENDAUTH
 1355:             }
 1356:         } else {
 1357:             $r->print(&Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc)); 
 1358:         }
 1359:         $r->print($portfolioform.$domroleform);
 1360:         if ($env{'form.action'} eq 'singlestudent') {
 1361:             $r->print(&date_sections_select($context,$newuser,$formname,
 1362:                                             $permission,$crstype,$ccuname,
 1363:                                             $ccdomain,$showcredits));
 1364:         }
 1365:         $r->print('</div><div class="LC_clear_float_footer"></div>');
 1366:     } else { # user already exists
 1367: 	$r->print($start_page.$forminfo);
 1368:         if ($env{'form.action'} eq 'singlestudent') {
 1369:             if ($crstype eq 'Community') {
 1370:                 $title = &mt('Enroll one member: [_1] in domain [_2]',
 1371:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1372:             } else {
 1373:                 $title = &mt('Enroll one student: [_1] in domain [_2]',
 1374:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1375:             }
 1376:         } else {
 1377:             $title = &mt('Modify existing user: [_1] in domain [_2]',
 1378:                              '"'.$ccuname.'"','"'.$ccdomain.'"');
 1379:         }
 1380:         $r->print('<h2>'.$title.'</h2>'."\n");
 1381:         $r->print('<div class="LC_left_float">');
 1382:         $r->print(&personal_data_display($ccuname,$ccdomain,$newuser,$context,
 1383:                                          $inst_results{$ccuname.':'.$ccdomain}));
 1384:         if (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) {
 1385:             $r->print('<br /><h3>'.&mt('User Can Request Creation of Courses/Communities in this Domain?').'</h3>'.
 1386:                       &Apache::loncommon::start_data_table());
 1387:             if ($env{'request.role.domain'} eq $ccdomain) {
 1388:                 $r->print(&build_tools_display($ccuname,$ccdomain,'requestcourses'));
 1389:             } else {
 1390:                 $r->print(&coursereq_externaluser($ccuname,$ccdomain,
 1391:                                                   $env{'request.role.domain'}));
 1392:             }
 1393:             $r->print(&Apache::loncommon::end_data_table());
 1394:         }
 1395:         $r->print('</div>');
 1396:         my @order = ('auth','quota','tools','requestauthor');
 1397:         my %user_text;
 1398:         my ($isadv,$isauthor) = 
 1399:             &Apache::lonnet::is_advanced_user($ccuname,$ccdomain);
 1400:         if ((!$isauthor) && 
 1401:             (&Apache::lonnet::allowed('cau',$env{'request.role.domain'}))
 1402:             && ($env{'request.role.domain'} eq $ccdomain)) {
 1403:             $user_text{'requestauthor'} = &domainrole_req($ccuname,$ccdomain);
 1404:         }
 1405:         $user_text{'auth'} =  &user_authentication($ccuname,$ccdomain,$formname);
 1406:         if ((&Apache::lonnet::allowed('mpq',$ccdomain)) ||
 1407:             (&Apache::lonnet::allowed('mut',$ccdomain))) {
 1408:             # Current user has quota modification privileges
 1409:             $user_text{'quota'} = &user_quotas($ccuname,$ccdomain);
 1410:         }
 1411:         if (!&Apache::lonnet::allowed('mpq',$ccdomain)) {
 1412:             if (&Apache::lonnet::allowed('mpq',$env{'request.role.domain'})) {
 1413:                 my %lt=&Apache::lonlocal::texthash(
 1414:                     'dska'  => "Disk quotas for user's portfolio and Authoring Space",
 1415:                     'youd'  => "You do not have privileges to modify the portfolio and/or Authoring Space quotas for this user.",
 1416:                     'ichr'  => "If a change is required, contact a domain coordinator for the domain",
 1417:                 );
 1418:                 $user_text{'quota'} = <<ENDNOPORTPRIV;
 1419: <h3>$lt{'dska'}</h3>
 1420: $lt{'youd'} $lt{'ichr'}: $ccdomain
 1421: ENDNOPORTPRIV
 1422:             }
 1423:         }
 1424:         if (!&Apache::lonnet::allowed('mut',$ccdomain)) {
 1425:             if (&Apache::lonnet::allowed('mut',$env{'request.role.domain'})) {
 1426:                 my %lt=&Apache::lonlocal::texthash(
 1427:                     'utav'  => "User Tools Availability",
 1428:                     'yodo'  => "You do not have privileges to modify Portfolio, Blog, WebDAV, or Personal Information Page settings for this user.",
 1429:                     'ifch'  => "If a change is required, contact a domain coordinator for the domain",
 1430:                 );
 1431:                 $user_text{'tools'} = <<ENDNOTOOLSPRIV;
 1432: <h3>$lt{'utav'}</h3>
 1433: $lt{'yodo'} $lt{'ifch'}: $ccdomain
 1434: ENDNOTOOLSPRIV
 1435:             }
 1436:         }
 1437:         my $gotdiv = 0; 
 1438:         foreach my $item (@order) {
 1439:             if ($user_text{$item} ne '') {
 1440:                 unless ($gotdiv) {
 1441:                     $r->print('<div class="LC_left_float">');
 1442:                     $gotdiv = 1;
 1443:                 }
 1444:                 $r->print('<br />'.$user_text{$item});
 1445:             }
 1446:         }
 1447:         if ($env{'form.action'} eq 'singlestudent') {
 1448:             unless ($gotdiv) {
 1449:                 $r->print('<div class="LC_left_float">');
 1450:             }
 1451:             my $credits;
 1452:             if ($showcredits) {
 1453:                 $credits = &get_user_credits($ccuname,$ccdomain,$defaultcredits);
 1454:                 if ($credits eq '') {
 1455:                     $credits = $defaultcredits;
 1456:                 }
 1457:             }
 1458:             $r->print(&date_sections_select($context,$newuser,$formname,
 1459:                                             $permission,$crstype,$ccuname,
 1460:                                             $ccdomain,$showcredits));
 1461:         }
 1462:         if ($gotdiv) {
 1463:             $r->print('</div><div class="LC_clear_float_footer"></div>');
 1464:         }
 1465:         if ($env{'form.action'} ne 'singlestudent') {
 1466:             &display_existing_roles($r,$ccuname,$ccdomain,\%inccourses,$context,
 1467:                                     $roledom,$crstype);
 1468:         }
 1469:     } ## End of new user/old user logic
 1470:     if ($env{'form.action'} eq 'singlestudent') {
 1471:         my $btntxt;
 1472:         if ($crstype eq 'Community') {
 1473:             $btntxt = &mt('Enroll Member');
 1474:         } else {
 1475:             $btntxt = &mt('Enroll Student');
 1476:         }
 1477:         $r->print('<br /><input type="button" value="'.$btntxt.'" onclick="setSections(this.form)" />'."\n");
 1478:     } else {
 1479:         $r->print('<div class="LC_left_float">'.
 1480:                   '<fieldset><legend>'.&mt('Add Roles').'</legend>');
 1481:         my $addrolesdisplay = 0;
 1482:         if ($context eq 'domain' || $context eq 'author') {
 1483:             $addrolesdisplay = &new_coauthor_roles($r,$ccuname,$ccdomain);
 1484:         }
 1485:         if ($context eq 'domain') {
 1486:             my $add_domainroles = &new_domain_roles($r,$ccdomain);
 1487:             if (!$addrolesdisplay) {
 1488:                 $addrolesdisplay = $add_domainroles;
 1489:             }
 1490:             $r->print(&course_level_dc($env{'request.role.domain'},$showcredits));
 1491:             $r->print('</fieldset></div><div class="LC_clear_float_footer"></div>'.
 1492:                       '<br /><input type="button" value="'.&mt('Save').'" onclick="setCourse()" />'."\n");
 1493:         } elsif ($context eq 'author') {
 1494:             if ($addrolesdisplay) {
 1495:                 $r->print('</fieldset></div><div class="LC_clear_float_footer"></div>'.
 1496:                           '<br /><input type="button" value="'.&mt('Save').'"');
 1497:                 if ($newuser) {
 1498:                     $r->print(' onclick="auth_check()" \>'."\n");
 1499:                 } else {
 1500:                     $r->print('onclick="this.form.submit()" \>'."\n");
 1501:                 }
 1502:             } else {
 1503:                 $r->print('</fieldset></div>'.
 1504:                           '<div class="LC_clear_float_footer"></div>'.
 1505:                           '<br /><a href="javascript:backPage(document.cu)">'.
 1506:                           &mt('Back to previous page').'</a>');
 1507:             }
 1508:         } else {
 1509:             $r->print(&course_level_table(\%inccourses,$showcredits,$defaultcredits));
 1510:             $r->print('</fieldset></div><div class="LC_clear_float_footer"></div>'.
 1511:                       '<br /><input type="button" value="'.&mt('Save').'" onclick="setSections(this.form)" />'."\n");
 1512:         }
 1513:     }
 1514:     $r->print(&Apache::lonhtmlcommon::echo_form_input(['phase','userrole','ccdomain','prevphase','currstate','ccuname','ccdomain']));
 1515:     $r->print('<input type="hidden" name="currstate" value="" />');
 1516:     $r->print('<input type="hidden" name="prevphase" value="'.$env{'form.phase'}.'" /></form><br /><br />');
 1517:     return;
 1518: }
 1519: 
 1520: sub singleuser_breadcrumb {
 1521:     my ($crstype) = @_;
 1522:     my %breadcrumb_text;
 1523:     if ($env{'form.action'} eq 'singlestudent') {
 1524:         if ($crstype eq 'Community') {
 1525:             $breadcrumb_text{'search'} = 'Enroll a member';
 1526:         } else {
 1527:             $breadcrumb_text{'search'} = 'Enroll a student';
 1528:         }
 1529:         $breadcrumb_text{'userpicked'} = 'Select a user',
 1530:         $breadcrumb_text{'modify'} = 'Set section/dates',
 1531:     } else {
 1532:         $breadcrumb_text{'search'} = 'Create/modify a user';
 1533:         $breadcrumb_text{'userpicked'} = 'Select a user',
 1534:         $breadcrumb_text{'modify'} = 'Set user role',
 1535:     }
 1536:     return %breadcrumb_text;
 1537: }
 1538: 
 1539: sub date_sections_select {
 1540:     my ($context,$newuser,$formname,$permission,$crstype,$ccuname,$ccdomain,
 1541:         $showcredits) = @_;
 1542:     my $credits;
 1543:     if ($showcredits) {
 1544:         my $defaultcredits = &Apache::lonuserutils::get_defaultcredits();
 1545:         $credits = &get_user_credits($ccuname,$ccdomain,$defaultcredits);
 1546:         if ($credits eq '') {
 1547:             $credits = $defaultcredits;
 1548:         }
 1549:     }
 1550:     my $cid = $env{'request.course.id'};
 1551:     my ($cnum,$cdom) = &Apache::lonuserutils::get_course_identity($cid);
 1552:     my $date_table = '<h3>'.&mt('Starting and Ending Dates').'</h3>'."\n".
 1553:         &Apache::lonuserutils::date_setting_table(undef,undef,$context,
 1554:                                                   undef,$formname,$permission);
 1555:     my $rowtitle = 'Section';
 1556:     my $secbox = '<h3>'.&mt('Section and Credits').'</h3>'."\n".
 1557:         &Apache::lonuserutils::section_picker($cdom,$cnum,'st',$rowtitle,
 1558:                                               $permission,$context,'',$crstype,
 1559:                                               $showcredits,$credits);
 1560:     my $output = $date_table.$secbox;
 1561:     return $output;
 1562: }
 1563: 
 1564: sub validation_javascript {
 1565:     my ($context,$ccdomain,$pjump_def,$crstype,$groupslist,$newuser,$formname,
 1566:         $loaditem) = @_;
 1567:     my $dc_setcourse_code = '';
 1568:     my $nondc_setsection_code = '';
 1569:     if ($context eq 'domain') {
 1570:         my $dcdom = $env{'request.role.domain'};
 1571:         $loaditem->{'onload'} = "document.cu.coursedesc.value='';";
 1572:         $dc_setcourse_code = 
 1573:             &Apache::lonuserutils::dc_setcourse_js('cu','singleuser',$context);
 1574:     } else {
 1575:         my $checkauth; 
 1576:         if (($newuser) || (&Apache::lonnet::allowed('mau',$ccdomain))) {
 1577:             $checkauth = 1;
 1578:         }
 1579:         if ($context eq 'course') {
 1580:             $nondc_setsection_code =
 1581:                 &Apache::lonuserutils::setsections_javascript($formname,$groupslist,
 1582:                                                               undef,$checkauth,
 1583:                                                               $crstype);
 1584:         }
 1585:         if ($checkauth) {
 1586:             $nondc_setsection_code .= 
 1587:                 &Apache::lonuserutils::verify_authen($formname,$context);
 1588:         }
 1589:     }
 1590:     my $js = &user_modification_js($pjump_def,$dc_setcourse_code,
 1591:                                    $nondc_setsection_code,$groupslist);
 1592:     my ($jsback,$elements) = &crumb_utilities();
 1593:     $js .= "\n".
 1594:            '<script type="text/javascript">'."\n".
 1595:            '// <![CDATA['."\n".
 1596:            $jsback."\n".
 1597:            '// ]]>'."\n".
 1598:            '</script>'."\n";
 1599:     return $js;
 1600: }
 1601: 
 1602: sub display_existing_roles {
 1603:     my ($r,$ccuname,$ccdomain,$inccourses,$context,$roledom,$crstype,
 1604:         $showcredits) = @_;
 1605:     my $now=time;
 1606:     my %lt=&Apache::lonlocal::texthash(
 1607:                     'rer'  => "Existing Roles",
 1608:                     'rev'  => "Revoke",
 1609:                     'del'  => "Delete",
 1610:                     'ren'  => "Re-Enable",
 1611:                     'rol'  => "Role",
 1612:                     'ext'  => "Extent",
 1613:                     'crd'  => "Credits",
 1614:                     'sta'  => "Start",
 1615:                     'end'  => "End",
 1616:                                        );
 1617:     my (%rolesdump,%roletext,%sortrole,%roleclass,%rolepriv);
 1618:     if ($context eq 'course' || $context eq 'author') {
 1619:         my @roles = &Apache::lonuserutils::roles_by_context($context,1,$crstype);
 1620:         my %roleshash = 
 1621:             &Apache::lonnet::get_my_roles($ccuname,$ccdomain,'userroles',
 1622:                               ['active','previous','future'],\@roles,$roledom,1);
 1623:         foreach my $key (keys(%roleshash)) {
 1624:             my ($start,$end) = split(':',$roleshash{$key});
 1625:             next if ($start eq '-1' || $end eq '-1');
 1626:             my ($rnum,$rdom,$role,$sec) = split(':',$key);
 1627:             if ($context eq 'course') {
 1628:                 next unless (($rnum eq $env{'course.'.$env{'request.course.id'}.'.num'})
 1629:                              && ($rdom eq $env{'course.'.$env{'request.course.id'}.'.domain'}));
 1630:             } elsif ($context eq 'author') {
 1631:                 next unless (($rnum eq $env{'user.name'}) && ($rdom eq $env{'request.role.domain'}));
 1632:             }
 1633:             my ($newkey,$newvalue,$newrole);
 1634:             $newkey = '/'.$rdom.'/'.$rnum;
 1635:             if ($sec ne '') {
 1636:                 $newkey .= '/'.$sec;
 1637:             }
 1638:             $newvalue = $role;
 1639:             if ($role =~ /^cr/) {
 1640:                 $newrole = 'cr';
 1641:             } else {
 1642:                 $newrole = $role;
 1643:             }
 1644:             $newkey .= '_'.$newrole;
 1645:             if ($start ne '' && $end ne '') {
 1646:                 $newvalue .= '_'.$end.'_'.$start;
 1647:             } elsif ($end ne '') {
 1648:                 $newvalue .= '_'.$end;
 1649:             }
 1650:             $rolesdump{$newkey} = $newvalue;
 1651:         }
 1652:     } else {
 1653:         %rolesdump=&Apache::lonnet::dump('roles',$ccdomain,$ccuname);
 1654:     }
 1655:     # Build up table of user roles to allow revocation and re-enabling of roles.
 1656:     my ($tmp) = keys(%rolesdump);
 1657:     return if ($tmp =~ /^(con_lost|error)/i);
 1658:     foreach my $area (sort { my $a1=join('_',(split('_',$a))[1,0]);
 1659:                                 my $b1=join('_',(split('_',$b))[1,0]);
 1660:                                 return $a1 cmp $b1;
 1661:                             } keys(%rolesdump)) {
 1662:         next if ($area =~ /^rolesdef/);
 1663:         my $envkey=$area;
 1664:         my $role = $rolesdump{$area};
 1665:         my $thisrole=$area;
 1666:         $area =~ s/\_\w\w$//;
 1667:         my ($role_code,$role_end_time,$role_start_time) =
 1668:             split(/_/,$role);
 1669: # Is this a custom role? Get role owner and title.
 1670:         my ($croleudom,$croleuname,$croletitle)=
 1671:             ($role_code=~m{^cr/($match_domain)/($match_username)/(\w+)$});
 1672:         my $allowed=0;
 1673:         my $delallowed=0;
 1674:         my $sortkey=$role_code;
 1675:         my $class='Unknown';
 1676:         my $credits='';
 1677:         if ($area =~ m{^/($match_domain)/($match_courseid)} ) {
 1678:             $class='Course';
 1679:             my ($coursedom,$coursedir) = ($1,$2);
 1680:             my $cid = $1.'_'.$2;
 1681:             # $1.'_'.$2 is the course id (eg. 103_12345abcef103l3).
 1682:             my %coursedata=
 1683:                 &Apache::lonnet::coursedescription($cid);
 1684:             if ($coursedir =~ /^$match_community$/) {
 1685:                 $class='Community';
 1686:             }
 1687:             $sortkey.="\0$coursedom";
 1688:             my $carea;
 1689:             if (defined($coursedata{'description'})) {
 1690:                 $carea=$coursedata{'description'}.
 1691:                     '<br />'.&mt('Domain').': '.$coursedom.('&nbsp;'x8).
 1692:     &Apache::loncommon::syllabuswrapper(&mt('Syllabus'),$coursedir,$coursedom);
 1693:                 $sortkey.="\0".$coursedata{'description'};
 1694:             } else {
 1695:                 if ($class eq 'Community') {
 1696:                     $carea=&mt('Unavailable community').': '.$area;
 1697:                     $sortkey.="\0".&mt('Unavailable community').': '.$area;
 1698:                 } else {
 1699:                     $carea=&mt('Unavailable course').': '.$area;
 1700:                     $sortkey.="\0".&mt('Unavailable course').': '.$area;
 1701:                 }
 1702:             }
 1703:             $sortkey.="\0$coursedir";
 1704:             $inccourses->{$cid}=1;
 1705:             if (($showcredits) && ($class eq 'Course') && ($role_code eq 'st')) {
 1706:                 my $defaultcredits = $coursedata{'internal.defaultcredits'};
 1707:                 $credits =
 1708:                     &get_user_credits($ccuname,$ccdomain,$defaultcredits,
 1709:                                       $coursedom,$coursedir);
 1710:                 if ($credits eq '') {
 1711:                     $credits = $defaultcredits;
 1712:                 }
 1713:             }
 1714:             if ((&Apache::lonnet::allowed('c'.$role_code,$coursedom.'/'.$coursedir)) ||
 1715:                 (&Apache::lonnet::allowed('c'.$role_code,$ccdomain))) {
 1716:                 $allowed=1;
 1717:             }
 1718:             unless ($allowed) {
 1719:                 my $isowner = &Apache::lonuserutils::is_courseowner($cid,$coursedata{'internal.courseowner'});
 1720:                 if ($isowner) {
 1721:                     if (($role_code eq 'co') && ($class eq 'Community')) {
 1722:                         $allowed = 1;
 1723:                     } elsif (($role_code eq 'cc') && ($class eq 'Course')) {
 1724:                         $allowed = 1;
 1725:                     }
 1726:                 }
 1727:             } 
 1728:             if ((&Apache::lonnet::allowed('dro',$coursedom)) ||
 1729:                 (&Apache::lonnet::allowed('dro',$ccdomain))) {
 1730:                 $delallowed=1;
 1731:             }
 1732: # - custom role. Needs more info, too
 1733:             if ($croletitle) {
 1734:                 if (&Apache::lonnet::allowed('ccr',$coursedom.'/'.$coursedir)) {
 1735:                     $allowed=1;
 1736:                     $thisrole.='.'.$role_code;
 1737:                 }
 1738:             }
 1739:             if ($area=~m{^/($match_domain)/($match_courseid)/(\w+)}) {
 1740:                 $carea.='<br />'.&mt('Section: [_1]',$3);
 1741:                 $sortkey.="\0$3";
 1742:                 if (!$allowed) {
 1743:                     if ($env{'request.course.sec'} eq $3) {
 1744:                         if (&Apache::lonnet::allowed('c'.$role_code,$1.'/'.$2.'/'.$3)) {
 1745:                             $allowed = 1;
 1746:                         }
 1747:                     }
 1748:                 }
 1749:             }
 1750:             $area=$carea;
 1751:         } else {
 1752:             $sortkey.="\0".$area;
 1753:             # Determine if current user is able to revoke privileges
 1754:             if ($area=~m{^/($match_domain)/}) {
 1755:                 if ((&Apache::lonnet::allowed('c'.$role_code,$1)) ||
 1756:                    (&Apache::lonnet::allowed('c'.$role_code,$ccdomain))) {
 1757:                    $allowed=1;
 1758:                 }
 1759:                 if (((&Apache::lonnet::allowed('dro',$1))  ||
 1760:                     (&Apache::lonnet::allowed('dro',$ccdomain))) &&
 1761:                     ($role_code ne 'dc')) {
 1762:                     $delallowed=1;
 1763:                 }
 1764:             } else {
 1765:                 if (&Apache::lonnet::allowed('c'.$role_code,'/')) {
 1766:                     $allowed=1;
 1767:                 }
 1768:             }
 1769:             if ($role_code eq 'ca' || $role_code eq 'au' || $role_code eq 'aa') {
 1770:                 $class='Authoring Space';
 1771:             } elsif ($role_code eq 'su') {
 1772:                 $class='System';
 1773:             } else {
 1774:                 $class='Domain';
 1775:             }
 1776:         }
 1777:         if (($role_code eq 'ca') || ($role_code eq 'aa')) {
 1778:             $area=~m{/($match_domain)/($match_username)};
 1779:             if (&Apache::lonuserutils::authorpriv($2,$1)) {
 1780:                 $allowed=1;
 1781:             } else {
 1782:                 $allowed=0;
 1783:             }
 1784:         }
 1785:         my $row = '';
 1786:         $row.= '<td>';
 1787:         my $active=1;
 1788:         $active=0 if (($role_end_time) && ($now>$role_end_time));
 1789:         if (($active) && ($allowed)) {
 1790:             $row.= '<input type="checkbox" name="rev:'.$thisrole.'" />';
 1791:         } else {
 1792:             if ($active) {
 1793:                $row.='&nbsp;';
 1794:             } else {
 1795:                $row.=&mt('expired or revoked');
 1796:             }
 1797:         }
 1798:         $row.='</td><td>';
 1799:         if ($allowed && !$active) {
 1800:             $row.= '<input type="checkbox" name="ren:'.$thisrole.'" />';
 1801:         } else {
 1802:             $row.='&nbsp;';
 1803:         }
 1804:         $row.='</td><td>';
 1805:         if ($delallowed) {
 1806:             $row.= '<input type="checkbox" name="del:'.$thisrole.'" />';
 1807:         } else {
 1808:             $row.='&nbsp;';
 1809:         }
 1810:         my $plaintext='';
 1811:         if (!$croletitle) {
 1812:             $plaintext=&Apache::lonnet::plaintext($role_code,$class);
 1813:             if (($showcredits) && ($credits ne '')) {
 1814:                 $plaintext .= '<br/ ><span class="LC_nobreak">'.
 1815:                               '<span class="LC_fontsize_small">'.
 1816:                               &mt('Credits: [_1]',$credits).
 1817:                               '</span></span>';
 1818:             }
 1819:         } else {
 1820:             $plaintext=
 1821:                 &mt('Custom role [_1][_2]defined by [_3]',
 1822:                         '"'.$croletitle.'"',
 1823:                         '<br />',
 1824:                         $croleuname.':'.$croleudom);
 1825:         }
 1826:         $row.= '</td><td>'.$plaintext.
 1827:                '</td><td>'.$area.
 1828:                '</td><td>'.($role_start_time?&Apache::lonlocal::locallocaltime($role_start_time)
 1829:                                             : '&nbsp;' ).
 1830:                '</td><td>'.($role_end_time  ?&Apache::lonlocal::locallocaltime($role_end_time)
 1831:                                             : '&nbsp;' )
 1832:                ."</td>";
 1833:         $sortrole{$sortkey}=$envkey;
 1834:         $roletext{$envkey}=$row;
 1835:         $roleclass{$envkey}=$class;
 1836:         $rolepriv{$envkey}=$allowed;
 1837:     } # end of foreach        (table building loop)
 1838: 
 1839:     my $rolesdisplay = 0;
 1840:     my %output = ();
 1841:     foreach my $type ('Authoring Space','Course','Community','Domain','System','Unknown') {
 1842:         $output{$type} = '';
 1843:         foreach my $which (sort {uc($a) cmp uc($b)} (keys(%sortrole))) {
 1844:             if ( ($roleclass{$sortrole{$which}} =~ /^\Q$type\E/ ) && ($rolepriv{$sortrole{$which}}) ) {
 1845:                  $output{$type}.=
 1846:                       &Apache::loncommon::start_data_table_row().
 1847:                       $roletext{$sortrole{$which}}.
 1848:                       &Apache::loncommon::end_data_table_row();
 1849:             }
 1850:         }
 1851:         unless($output{$type} eq '') {
 1852:             $output{$type} = '<tr class="LC_info_row">'.
 1853:                       "<td align='center' colspan='7'>".&mt($type)."</td></tr>".
 1854:                       $output{$type};
 1855:             $rolesdisplay = 1;
 1856:         }
 1857:     }
 1858:     if ($rolesdisplay == 1) {
 1859:         my $contextrole='';
 1860:         if ($env{'request.course.id'}) {
 1861:             if (&Apache::loncommon::course_type() eq 'Community') {
 1862:                 $contextrole = &mt('Existing Roles in this Community');
 1863:             } else {
 1864:                 $contextrole = &mt('Existing Roles in this Course');
 1865:             }
 1866:         } elsif ($env{'request.role'} =~ /^au\./) {
 1867:             $contextrole = &mt('Existing Co-Author Roles in your Authoring Space');
 1868:         } else {
 1869:             $contextrole = &mt('Existing Roles in this Domain');
 1870:         }
 1871:         $r->print('<div class="LC_left_float">'.
 1872: '<fieldset><legend>'.$contextrole.'</legend>'.
 1873: &Apache::loncommon::start_data_table("LC_createuser").
 1874: &Apache::loncommon::start_data_table_header_row().
 1875: '<th>'.$lt{'rev'}.'</th><th>'.$lt{'ren'}.'</th><th>'.$lt{'del'}.
 1876: '</th><th>'.$lt{'rol'}.'</th><th>'.$lt{'ext'}.
 1877: '</th><th>'.$lt{'sta'}.'</th><th>'.$lt{'end'}.'</th>'.
 1878: &Apache::loncommon::end_data_table_header_row());
 1879:         foreach my $type ('Authoring Space','Course','Community','Domain','System','Unknown') {
 1880:             if ($output{$type}) {
 1881:                 $r->print($output{$type}."\n");
 1882:             }
 1883:         }
 1884:         $r->print(&Apache::loncommon::end_data_table().
 1885:                   '</fieldset></div>');
 1886:     }
 1887:     return;
 1888: }
 1889: 
 1890: sub new_coauthor_roles {
 1891:     my ($r,$ccuname,$ccdomain) = @_;
 1892:     my $addrolesdisplay = 0;
 1893:     #
 1894:     # Co-Author
 1895:     #
 1896:     if (&Apache::lonuserutils::authorpriv($env{'user.name'},
 1897:                                           $env{'request.role.domain'}) &&
 1898:         ($env{'user.name'} ne $ccuname || $env{'user.domain'} ne $ccdomain)) {
 1899:         # No sense in assigning co-author role to yourself
 1900:         $addrolesdisplay = 1;
 1901:         my $cuname=$env{'user.name'};
 1902:         my $cudom=$env{'request.role.domain'};
 1903:         my %lt=&Apache::lonlocal::texthash(
 1904:                     'cs'   => "Authoring Space",
 1905:                     'act'  => "Activate",
 1906:                     'rol'  => "Role",
 1907:                     'ext'  => "Extent",
 1908:                     'sta'  => "Start",
 1909:                     'end'  => "End",
 1910:                     'cau'  => "Co-Author",
 1911:                     'caa'  => "Assistant Co-Author",
 1912:                     'ssd'  => "Set Start Date",
 1913:                     'sed'  => "Set End Date"
 1914:                                        );
 1915:         $r->print('<h4>'.$lt{'cs'}.'</h4>'."\n".
 1916:                   &Apache::loncommon::start_data_table()."\n".
 1917:                   &Apache::loncommon::start_data_table_header_row()."\n".
 1918:                   '<th>'.$lt{'act'}.'</th><th>'.$lt{'rol'}.'</th>'.
 1919:                   '<th>'.$lt{'ext'}.'</th><th>'.$lt{'sta'}.'</th>'.
 1920:                   '<th>'.$lt{'end'}.'</th>'."\n".
 1921:                   &Apache::loncommon::end_data_table_header_row()."\n".
 1922:                   &Apache::loncommon::start_data_table_row().'
 1923:            <td>
 1924:             <input type="checkbox" name="act_'.$cudom.'_'.$cuname.'_ca" />
 1925:            </td>
 1926:            <td>'.$lt{'cau'}.'</td>
 1927:            <td>'.$cudom.'_'.$cuname.'</td>
 1928:            <td><input type="hidden" name="start_'.$cudom.'_'.$cuname.'_ca" value="" />
 1929:              <a href=
 1930: "javascript:pjump('."'date_start','Start Date Co-Author',document.cu.start_$cudom\_$cuname\_ca.value,'start_$cudom\_$cuname\_ca','cu.pres','dateset'".')">'.$lt{'ssd'}.'</a></td>
 1931: <td><input type="hidden" name="end_'.$cudom.'_'.$cuname.'_ca" value="" />
 1932: <a href=
 1933: "javascript:pjump('."'date_end','End Date Co-Author',document.cu.end_$cudom\_$cuname\_ca.value,'end_$cudom\_$cuname\_ca','cu.pres','dateset'".')">'.$lt{'sed'}.'</a></td>'."\n".
 1934:               &Apache::loncommon::end_data_table_row()."\n".
 1935:               &Apache::loncommon::start_data_table_row()."\n".
 1936: '<td><input type="checkbox" name="act_'.$cudom.'_'.$cuname.'_aa" /></td>
 1937: <td>'.$lt{'caa'}.'</td>
 1938: <td>'.$cudom.'_'.$cuname.'</td>
 1939: <td><input type="hidden" name="start_'.$cudom.'_'.$cuname.'_aa" value="" />
 1940: <a href=
 1941: "javascript:pjump('."'date_start','Start Date Assistant Co-Author',document.cu.start_$cudom\_$cuname\_aa.value,'start_$cudom\_$cuname\_aa','cu.pres','dateset'".')">'.$lt{'ssd'}.'</a></td>
 1942: <td><input type="hidden" name="end_'.$cudom.'_'.$cuname.'_aa" value="" />
 1943: <a href=
 1944: "javascript:pjump('."'date_end','End Date Assistant Co-Author',document.cu.end_$cudom\_$cuname\_aa.value,'end_$cudom\_$cuname\_aa','cu.pres','dateset'".')">'.$lt{'sed'}.'</a></td>'."\n".
 1945:              &Apache::loncommon::end_data_table_row()."\n".
 1946:              &Apache::loncommon::end_data_table());
 1947:     } elsif ($env{'request.role'} =~ /^au\./) {
 1948:         if (!(&Apache::lonuserutils::authorpriv($env{'user.name'},
 1949:                                                 $env{'request.role.domain'}))) {
 1950:             $r->print('<span class="LC_error">'.
 1951:                       &mt('You do not have privileges to assign co-author roles.').
 1952:                       '</span>');
 1953:         } elsif (($env{'user.name'} eq $ccuname) &&
 1954:              ($env{'user.domain'} eq $ccdomain)) {
 1955:             $r->print(&mt('Assigning yourself a co-author or assistant co-author role in your own author area in Authoring Space is not permitted'));
 1956:         }
 1957:     }
 1958:     return $addrolesdisplay;;
 1959: }
 1960: 
 1961: sub new_domain_roles {
 1962:     my ($r,$ccdomain) = @_;
 1963:     my $addrolesdisplay = 0;
 1964:     #
 1965:     # Domain level
 1966:     #
 1967:     my $num_domain_level = 0;
 1968:     my $domaintext =
 1969:     '<h4>'.&mt('Domain Level').'</h4>'.
 1970:     &Apache::loncommon::start_data_table().
 1971:     &Apache::loncommon::start_data_table_header_row().
 1972:     '<th>'.&mt('Activate').'</th><th>'.&mt('Role').'</th><th>'.
 1973:     &mt('Extent').'</th>'.
 1974:     '<th>'.&mt('Start').'</th><th>'.&mt('End').'</th>'.
 1975:     &Apache::loncommon::end_data_table_header_row();
 1976:     my @allroles = &Apache::lonuserutils::roles_by_context('domain');
 1977:     foreach my $thisdomain (sort(&Apache::lonnet::all_domains())) {
 1978:         foreach my $role (@allroles) {
 1979:             next if ($role eq 'ad');
 1980:             next if (($role eq 'au') && ($ccdomain ne $thisdomain));
 1981:             if (&Apache::lonnet::allowed('c'.$role,$thisdomain)) {
 1982:                my $plrole=&Apache::lonnet::plaintext($role);
 1983:                my %lt=&Apache::lonlocal::texthash(
 1984:                     'ssd'  => "Set Start Date",
 1985:                     'sed'  => "Set End Date"
 1986:                                        );
 1987:                $num_domain_level ++;
 1988:                $domaintext .=
 1989: &Apache::loncommon::start_data_table_row().
 1990: '<td><input type="checkbox" name="act_'.$thisdomain.'_'.$role.'" /></td>
 1991: <td>'.$plrole.'</td>
 1992: <td>'.$thisdomain.'</td>
 1993: <td><input type="hidden" name="start_'.$thisdomain.'_'.$role.'" value="" />
 1994: <a href=
 1995: "javascript:pjump('."'date_start','Start Date $plrole',document.cu.start_$thisdomain\_$role.value,'start_$thisdomain\_$role','cu.pres','dateset'".')">'.$lt{'ssd'}.'</a></td>
 1996: <td><input type="hidden" name="end_'.$thisdomain.'_'.$role.'" value="" />
 1997: <a href=
 1998: "javascript:pjump('."'date_end','End Date $plrole',document.cu.end_$thisdomain\_$role.value,'end_$thisdomain\_$role','cu.pres','dateset'".')">'.$lt{'sed'}.'</a></td>'.
 1999: &Apache::loncommon::end_data_table_row();
 2000:             }
 2001:         }
 2002:     }
 2003:     $domaintext.= &Apache::loncommon::end_data_table();
 2004:     if ($num_domain_level > 0) {
 2005:         $r->print($domaintext);
 2006:         $addrolesdisplay = 1;
 2007:     }
 2008:     return $addrolesdisplay;
 2009: }
 2010: 
 2011: sub user_authentication {
 2012:     my ($ccuname,$ccdomain,$formname) = @_;
 2013:     my $currentauth=&Apache::lonnet::queryauthenticate($ccuname,$ccdomain);
 2014:     my $outcome;
 2015:     # Check for a bad authentication type
 2016:     if ($currentauth !~ /^(krb4|krb5|unix|internal|localauth):/) {
 2017:         # bad authentication scheme
 2018:         my %lt=&Apache::lonlocal::texthash(
 2019:                        'err'   => "ERROR",
 2020:                        'uuas'  => "This user has an unrecognized authentication scheme",
 2021:                        'adcs'  => "Please alert a domain coordinator of this situation",
 2022:                        'sldb'  => "Please specify login data below",
 2023:                        'ld'    => "Login Data"
 2024:         );
 2025:         if (&Apache::lonnet::allowed('mau',$ccdomain)) {
 2026:             &initialize_authen_forms($ccdomain,$formname);
 2027: 
 2028:             my $choices = &Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc);
 2029:             $outcome = <<ENDBADAUTH;
 2030: <script type="text/javascript" language="Javascript">
 2031: // <![CDATA[
 2032: $loginscript
 2033: // ]]>
 2034: </script>
 2035: <span class="LC_error">$lt{'err'}:
 2036: $lt{'uuas'} ($currentauth). $lt{'sldb'}.</span>
 2037: <h3>$lt{'ld'}</h3>
 2038: $choices
 2039: ENDBADAUTH
 2040:         } else {
 2041:             # This user is not allowed to modify the user's
 2042:             # authentication scheme, so just notify them of the problem
 2043:             $outcome = <<ENDBADAUTH;
 2044: <span class="LC_error"> $lt{'err'}: 
 2045: $lt{'uuas'} ($currentauth). $lt{'adcs'}.
 2046: </span>
 2047: ENDBADAUTH
 2048:         }
 2049:     } else { # Authentication type is valid
 2050:         &initialize_authen_forms($ccdomain,$formname,$currentauth,'modifyuser');
 2051:         my ($authformcurrent,$can_modify,@authform_others) =
 2052:             &modify_login_block($ccdomain,$currentauth);
 2053:         if (&Apache::lonnet::allowed('mau',$ccdomain)) {
 2054:             # Current user has login modification privileges
 2055:             my %lt=&Apache::lonlocal::texthash (
 2056:                            'ld'    => "Login Data",
 2057:                            'ccld'  => "Change Current Login Data",
 2058:                            'enld'  => "Enter New Login Data"
 2059:                                                );
 2060:             $outcome =
 2061:                        '<script type="text/javascript" language="Javascript">'."\n".
 2062:                        '// <![CDATA['."\n".
 2063:                        $loginscript."\n".
 2064:                        '// ]]>'."\n".
 2065:                        '</script>'."\n".
 2066:                        '<h3>'.$lt{'ld'}.'</h3>'.
 2067:                        &Apache::loncommon::start_data_table().
 2068:                        &Apache::loncommon::start_data_table_row().
 2069:                        '<td>'.$authformnop;
 2070:             if ($can_modify) {
 2071:                 $outcome .= '</td>'."\n".
 2072:                             &Apache::loncommon::end_data_table_row().
 2073:                             &Apache::loncommon::start_data_table_row().
 2074:                             '<td>'.$authformcurrent.'</td>'.
 2075:                             &Apache::loncommon::end_data_table_row()."\n";
 2076:             } else {
 2077:                 $outcome .= '&nbsp;('.$authformcurrent.')</td>'.
 2078:                             &Apache::loncommon::end_data_table_row()."\n";
 2079:             }
 2080:             foreach my $item (@authform_others) { 
 2081:                 $outcome .= &Apache::loncommon::start_data_table_row().
 2082:                             '<td>'.$item.'</td>'.
 2083:                             &Apache::loncommon::end_data_table_row()."\n";
 2084:             }
 2085:             $outcome .= &Apache::loncommon::end_data_table();
 2086:         } else {
 2087:             if (&Apache::lonnet::allowed('mau',$env{'request.role.domain'})) {
 2088:                 my %lt=&Apache::lonlocal::texthash(
 2089:                            'ccld'  => "Change Current Login Data",
 2090:                            'yodo'  => "You do not have privileges to modify the authentication configuration for this user.",
 2091:                            'ifch'  => "If a change is required, contact a domain coordinator for the domain",
 2092:                 );
 2093:                 $outcome .= <<ENDNOPRIV;
 2094: <h3>$lt{'ccld'}</h3>
 2095: $lt{'yodo'} $lt{'ifch'}: $ccdomain
 2096: <input type="hidden" name="login" value="nochange" />
 2097: ENDNOPRIV
 2098:             }
 2099:         }
 2100:     }  ## End of "check for bad authentication type" logic
 2101:     return $outcome;
 2102: }
 2103: 
 2104: sub modify_login_block {
 2105:     my ($dom,$currentauth) = @_;
 2106:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 2107:     my ($authnum,%can_assign) =
 2108:         &Apache::loncommon::get_assignable_auth($dom);
 2109:     my ($authformcurrent,@authform_others,$show_override_msg);
 2110:     if ($currentauth=~/^krb(4|5):/) {
 2111:         $authformcurrent=$authformkrb;
 2112:         if ($can_assign{'int'}) {
 2113:             push(@authform_others,$authformint);
 2114:         }
 2115:         if ($can_assign{'loc'}) {
 2116:             push(@authform_others,$authformloc);
 2117:         }
 2118:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2119:             $show_override_msg = 1;
 2120:         }
 2121:     } elsif ($currentauth=~/^internal:/) {
 2122:         $authformcurrent=$authformint;
 2123:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2124:             push(@authform_others,$authformkrb);
 2125:         }
 2126:         if ($can_assign{'loc'}) {
 2127:             push(@authform_others,$authformloc);
 2128:         }
 2129:         if ($can_assign{'int'}) {
 2130:             $show_override_msg = 1;
 2131:         }
 2132:     } elsif ($currentauth=~/^unix:/) {
 2133:         $authformcurrent=$authformfsys;
 2134:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2135:             push(@authform_others,$authformkrb);
 2136:         }
 2137:         if ($can_assign{'int'}) {
 2138:             push(@authform_others,$authformint);
 2139:         }
 2140:         if ($can_assign{'loc'}) {
 2141:             push(@authform_others,$authformloc);
 2142:         }
 2143:         if ($can_assign{'fsys'}) {
 2144:             $show_override_msg = 1;
 2145:         }
 2146:     } elsif ($currentauth=~/^localauth:/) {
 2147:         $authformcurrent=$authformloc;
 2148:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2149:             push(@authform_others,$authformkrb);
 2150:         }
 2151:         if ($can_assign{'int'}) {
 2152:             push(@authform_others,$authformint);
 2153:         }
 2154:         if ($can_assign{'loc'}) {
 2155:             $show_override_msg = 1;
 2156:         }
 2157:     }
 2158:     if ($show_override_msg) {
 2159:         $authformcurrent = '<table><tr><td colspan="3">'.$authformcurrent.
 2160:                            '</td></tr>'."\n".
 2161:                            '<tr><td>&nbsp;&nbsp;&nbsp;</td>'.
 2162:                            '<td><b>'.&mt('Currently in use').'</b></td>'.
 2163:                            '<td align="right"><span class="LC_cusr_emph">'.
 2164:                             &mt('will override current values').
 2165:                             '</span></td></tr></table>';
 2166:     }
 2167:     return ($authformcurrent,$show_override_msg,@authform_others); 
 2168: }
 2169: 
 2170: sub personal_data_display {
 2171:     my ($ccuname,$ccdomain,$newuser,$context,$inst_results,$rolesarray,
 2172:         $now,$captchaform,$emailusername,$usertype) = @_;
 2173:     my ($output,%userenv,%canmodify,%canmodify_status);
 2174:     my @userinfo = ('firstname','middlename','lastname','generation',
 2175:                     'permanentemail','id');
 2176:     my $rowcount = 0;
 2177:     my $editable = 0;
 2178:     my %textboxsize = (
 2179:                        firstname      => '15',
 2180:                        middlename     => '15',
 2181:                        lastname       => '15',
 2182:                        generation     => '5',
 2183:                        permanentemail => '25',
 2184:                        id             => '15',
 2185:                       );
 2186: 
 2187:     my %lt=&Apache::lonlocal::texthash(
 2188:                 'pd'             => "Personal Data",
 2189:                 'firstname'      => "First Name",
 2190:                 'middlename'     => "Middle Name",
 2191:                 'lastname'       => "Last Name",
 2192:                 'generation'     => "Generation",
 2193:                 'permanentemail' => "Permanent e-mail address",
 2194:                 'id'             => "Student/Employee ID",
 2195:                 'lg'             => "Login Data",
 2196:                 'inststatus'     => "Affiliation",
 2197:                 'email'          => 'E-mail address',
 2198:                 'valid'          => 'Validation',
 2199:     );
 2200: 
 2201:     %canmodify_status =
 2202:         &Apache::lonuserutils::can_modify_userinfo($context,$ccdomain,
 2203:                                                    ['inststatus'],$rolesarray);
 2204:     if (!$newuser) {
 2205:         # Get the users information
 2206:         %userenv = &Apache::lonnet::get('environment',
 2207:                    ['firstname','middlename','lastname','generation',
 2208:                     'permanentemail','id','inststatus'],$ccdomain,$ccuname);
 2209:         %canmodify =
 2210:             &Apache::lonuserutils::can_modify_userinfo($context,$ccdomain,
 2211:                                                        \@userinfo,$rolesarray);
 2212:     } elsif ($context eq 'selfcreate') {
 2213:         if ($newuser eq 'email') {
 2214:             if (ref($emailusername) eq 'HASH') {
 2215:                 if (ref($emailusername->{$usertype}) eq 'HASH') {
 2216:                     my ($infofields,$infotitles) = &Apache::loncommon::emailusername_info();
 2217:                     @userinfo = ();          
 2218:                     if ((ref($infofields) eq 'ARRAY') && (ref($infotitles) eq 'HASH')) {
 2219:                         foreach my $field (@{$infofields}) { 
 2220:                             if ($emailusername->{$usertype}->{$field}) {
 2221:                                 push(@userinfo,$field);
 2222:                                 $canmodify{$field} = 1;
 2223:                                 unless ($textboxsize{$field}) {
 2224:                                     $textboxsize{$field} = 25;
 2225:                                 }
 2226:                                 unless ($lt{$field}) {
 2227:                                     $lt{$field} = $infotitles->{$field};
 2228:                                 }
 2229:                                 if ($emailusername->{$usertype}->{$field} eq 'required') {
 2230:                                     $lt{$field} .= '<b>*</b>';
 2231:                                 }
 2232:                             }
 2233:                         }
 2234:                     }
 2235:                 }
 2236:             }
 2237:         } else {
 2238:             %canmodify = &selfcreate_canmodify($context,$ccdomain,\@userinfo,
 2239:                                                $inst_results,$rolesarray);
 2240:         }
 2241:     }
 2242: 
 2243:     my $genhelp=&Apache::loncommon::help_open_topic('Generation');
 2244:     $output = '<h3>'.$lt{'pd'}.'</h3>'.
 2245:               &Apache::lonhtmlcommon::start_pick_box();
 2246:     if (($context eq 'selfcreate') && ($newuser eq 'email')) {
 2247:         $output .= &Apache::lonhtmlcommon::row_title($lt{'email'}.'<b>*</b>',undef,
 2248:                                                      'LC_oddrow_value')."\n".
 2249:                    '<input type="text" name="uname" size="25" value="" autocomplete="off" />';
 2250:         $rowcount ++;
 2251:         $output .= &Apache::lonhtmlcommon::row_closure(1);
 2252:         my $upassone = '<input type="password" name="upass'.$now.'" size="20" autocomplete="off" />';
 2253:         my $upasstwo = '<input type="password" name="upasscheck'.$now.'" size="20" autocomplete="off" />';
 2254:         $output .= &Apache::lonhtmlcommon::row_title(&mt('Password').'<b>*</b>',
 2255:                                                     'LC_pick_box_title',
 2256:                                                     'LC_oddrow_value')."\n".
 2257:                    $upassone."\n".
 2258:                    &Apache::lonhtmlcommon::row_closure(1)."\n".
 2259:                    &Apache::lonhtmlcommon::row_title(&mt('Confirm password').'<b>*</b>',
 2260:                                                      'LC_pick_box_title',
 2261:                                                      'LC_oddrow_value')."\n".
 2262:                    $upasstwo.
 2263:                    &Apache::lonhtmlcommon::row_closure()."\n";
 2264:     }
 2265:     foreach my $item (@userinfo) {
 2266:         my $rowtitle = $lt{$item};
 2267:         my $hiderow = 0;
 2268:         if ($item eq 'generation') {
 2269:             $rowtitle = $genhelp.$rowtitle;
 2270:         }
 2271:         my $row = &Apache::lonhtmlcommon::row_title($rowtitle,undef,'LC_oddrow_value')."\n";
 2272:         if ($newuser) {
 2273:             if (ref($inst_results) eq 'HASH') {
 2274:                 if ($inst_results->{$item} ne '') {
 2275:                     $row .= '<input type="hidden" name="c'.$item.'" value="'.$inst_results->{$item}.'" />'.$inst_results->{$item};
 2276:                 } else {
 2277:                     if ($context eq 'selfcreate') {
 2278:                         if ($canmodify{$item}) {
 2279:                             $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="" autocomplete="off" />';
 2280:                             $editable ++;
 2281:                         } else {
 2282:                             $hiderow = 1;
 2283:                         }
 2284:                     } else {
 2285:                         $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="" />';
 2286:                     }
 2287:                 }
 2288:             } else {
 2289:                 if ($context eq 'selfcreate') {
 2290:                     if ($canmodify{$item}) {
 2291:                         if ($newuser eq 'email') {
 2292:                             $row .= '<input type="text" name="'.$item.'" size="'.$textboxsize{$item}.'" value="" autocomplete="off" />';
 2293:                         } else {
 2294:                             $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="" autocomplete="off" />';
 2295:                         }
 2296:                         $editable ++;
 2297:                     } else {
 2298:                         $hiderow = 1;
 2299:                     }
 2300:                 } else {
 2301:                     $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="" />';
 2302:                 }
 2303:             }
 2304:         } else {
 2305:             if ($canmodify{$item}) {
 2306:                 $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="'.$userenv{$item}.'" />';
 2307:                 if (($item eq 'id') && (!$newuser)) {
 2308:                     $row .= '<br />'.&Apache::lonuserutils::forceid_change($context);
 2309:                 }
 2310:             } else {
 2311:                 $row .= $userenv{$item};
 2312:             }
 2313:         }
 2314:         $row .= &Apache::lonhtmlcommon::row_closure(1);
 2315:         if (!$hiderow) {
 2316:             $output .= $row;
 2317:             $rowcount ++;
 2318:         }
 2319:     }
 2320:     if (($canmodify_status{'inststatus'}) || ($context ne 'selfcreate')) {
 2321:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($ccdomain);
 2322:         if (ref($types) eq 'ARRAY') {
 2323:             if (@{$types} > 0) {
 2324:                 my ($hiderow,$shown);
 2325:                 if ($canmodify_status{'inststatus'}) {
 2326:                     $shown = &pick_inst_statuses($userenv{'inststatus'},$usertypes,$types);
 2327:                 } else {
 2328:                     if ($userenv{'inststatus'} eq '') {
 2329:                         $hiderow = 1;
 2330:                     } else {
 2331:                         my @showitems;
 2332:                         foreach my $item ( map { &unescape($_); } split(':',$userenv{'inststatus'})) {
 2333:                             if (exists($usertypes->{$item})) {
 2334:                                 push(@showitems,$usertypes->{$item});
 2335:                             } else {
 2336:                                 push(@showitems,$item);
 2337:                             }
 2338:                         }
 2339:                         if (@showitems) {
 2340:                             $shown = join(', ',@showitems);
 2341:                         } else {
 2342:                             $hiderow = 1;
 2343:                         }
 2344:                     }
 2345:                 }
 2346:                 if (!$hiderow) {
 2347:                     my $row = &Apache::lonhtmlcommon::row_title(&mt('Affiliations'),undef,'LC_oddrow_value')."\n".
 2348:                               $shown.&Apache::lonhtmlcommon::row_closure(1); 
 2349:                     if ($context eq 'selfcreate') {
 2350:                         $rowcount ++;
 2351:                     }
 2352:                     $output .= $row;
 2353:                 }
 2354:             }
 2355:         }
 2356:     }
 2357:     if (($context eq 'selfcreate') && ($newuser eq 'email')) {
 2358:         if ($captchaform) {
 2359:             $output .= &Apache::lonhtmlcommon::row_title($lt{'valid'}.'*',
 2360:                                                          'LC_pick_box_title')."\n".
 2361:                        $captchaform."\n".'<br /><br />'.
 2362:                        &Apache::lonhtmlcommon::row_closure(1); 
 2363:             $rowcount ++;
 2364:         }
 2365:         my $submit_text = &mt('Create account');
 2366:         $output .= &Apache::lonhtmlcommon::row_title()."\n".
 2367:                    '<br /><input type="submit" name="createaccount" value="'.
 2368:                    $submit_text.'" />'.
 2369:                    '<input type="hidden" name="type" value="'.$usertype.'" />'.
 2370:                    &Apache::lonhtmlcommon::row_closure(1);
 2371:     }
 2372:     $output .= &Apache::lonhtmlcommon::end_pick_box();
 2373:     if (wantarray) {
 2374:         if ($context eq 'selfcreate') {
 2375:             return($output,$rowcount,$editable);
 2376:         } else {
 2377:             return $output;
 2378:         }
 2379:     } else {
 2380:         return $output;
 2381:     }
 2382: }
 2383: 
 2384: sub pick_inst_statuses {
 2385:     my ($curr,$usertypes,$types) = @_;
 2386:     my ($output,$rem,@currtypes);
 2387:     if ($curr ne '') {
 2388:         @currtypes = map { &unescape($_); } split(/:/,$curr);
 2389:     }
 2390:     my $numinrow = 2;
 2391:     if (ref($types) eq 'ARRAY') {
 2392:         $output = '<table>';
 2393:         my $lastcolspan; 
 2394:         for (my $i=0; $i<@{$types}; $i++) {
 2395:             if (defined($usertypes->{$types->[$i]})) {
 2396:                 my $rem = $i%($numinrow);
 2397:                 if ($rem == 0) {
 2398:                     if ($i<@{$types}-1) {
 2399:                         if ($i > 0) { 
 2400:                             $output .= '</tr>';
 2401:                         }
 2402:                         $output .= '<tr>';
 2403:                     }
 2404:                 } elsif ($i==@{$types}-1) {
 2405:                     my $colsleft = $numinrow - $rem;
 2406:                     if ($colsleft > 1) {
 2407:                         $lastcolspan = ' colspan="'.$colsleft.'"';
 2408:                     }
 2409:                 }
 2410:                 my $check = ' ';
 2411:                 if (grep(/^\Q$types->[$i]\E$/,@currtypes)) {
 2412:                     $check = ' checked="checked" ';
 2413:                 }
 2414:                 $output .= '<td class="LC_left_item"'.$lastcolspan.'>'.
 2415:                            '<span class="LC_nobreak"><label>'.
 2416:                            '<input type="checkbox" name="inststatus" '.
 2417:                            'value="'.$types->[$i].'"'.$check.'/>'.
 2418:                            $usertypes->{$types->[$i]}.'</label></span></td>';
 2419:             }
 2420:         }
 2421:         $output .= '</tr></table>';
 2422:     }
 2423:     return $output;
 2424: }
 2425: 
 2426: sub selfcreate_canmodify {
 2427:     my ($context,$dom,$userinfo,$inst_results,$rolesarray) = @_;
 2428:     if (ref($inst_results) eq 'HASH') {
 2429:         my @inststatuses = &get_inststatuses($inst_results);
 2430:         if (@inststatuses == 0) {
 2431:             @inststatuses = ('default');
 2432:         }
 2433:         $rolesarray = \@inststatuses;
 2434:     }
 2435:     my %canmodify =
 2436:         &Apache::lonuserutils::can_modify_userinfo($context,$dom,$userinfo,
 2437:                                                    $rolesarray);
 2438:     return %canmodify;
 2439: }
 2440: 
 2441: sub get_inststatuses {
 2442:     my ($insthashref) = @_;
 2443:     my @inststatuses = ();
 2444:     if (ref($insthashref) eq 'HASH') {
 2445:         if (ref($insthashref->{'inststatus'}) eq 'ARRAY') {
 2446:             @inststatuses = @{$insthashref->{'inststatus'}};
 2447:         }
 2448:     }
 2449:     return @inststatuses;
 2450: }
 2451: 
 2452: # ================================================================= Phase Three
 2453: sub update_user_data {
 2454:     my ($r,$context,$crstype,$brcrum,$showcredits) = @_; 
 2455:     my $uhome=&Apache::lonnet::homeserver($env{'form.ccuname'},
 2456:                                           $env{'form.ccdomain'});
 2457:     # Error messages
 2458:     my $error     = '<span class="LC_error">'.&mt('Error').': ';
 2459:     my $end       = '</span><br /><br />';
 2460:     my $rtnlink   = '<a href="javascript:backPage(document.userupdate,'.
 2461:                     "'$env{'form.prevphase'}','modify')".'" />'.
 2462:                     &mt('Return to previous page').'</a>'.
 2463:                     &Apache::loncommon::end_page();
 2464:     my $now = time;
 2465:     my $title;
 2466:     if (exists($env{'form.makeuser'})) {
 2467: 	$title='Set Privileges for New User';
 2468:     } else {
 2469:         $title='Modify User Privileges';
 2470:     }
 2471:     my $newuser = 0;
 2472:     my ($jsback,$elements) = &crumb_utilities();
 2473:     my $jscript = '<script type="text/javascript">'."\n".
 2474:                   '// <![CDATA['."\n".
 2475:                   $jsback."\n".
 2476:                   '// ]]>'."\n".
 2477:                   '</script>'."\n";
 2478:     my %breadcrumb_text = &singleuser_breadcrumb($crstype);
 2479:     push (@{$brcrum},
 2480:              {href => "javascript:backPage(document.userupdate)",
 2481:               text => $breadcrumb_text{'search'},
 2482:               faq  => 282,
 2483:               bug  => 'Instructor Interface',}
 2484:              );
 2485:     if ($env{'form.prevphase'} eq 'userpicked') {
 2486:         push(@{$brcrum},
 2487:                {href => "javascript:backPage(document.userupdate,'get_user_info','select')",
 2488:                 text => $breadcrumb_text{'userpicked'},
 2489:                 faq  => 282,
 2490:                 bug  => 'Instructor Interface',});
 2491:     }
 2492:     my $helpitem = 'Course_Change_Privileges';
 2493:     if ($env{'form.action'} eq 'singlestudent') {
 2494:         $helpitem = 'Course_Add_Student';
 2495:     }
 2496:     push(@{$brcrum}, 
 2497:             {href => "javascript:backPage(document.userupdate,'$env{'form.prevphase'}','modify')",
 2498:              text => $breadcrumb_text{'modify'},
 2499:              faq  => 282,
 2500:              bug  => 'Instructor Interface',},
 2501:             {href => "/adm/createuser",
 2502:              text => "Result",
 2503:              faq  => 282,
 2504:              bug  => 'Instructor Interface',
 2505:              help => $helpitem});
 2506:     my $args = {bread_crumbs          => $brcrum,
 2507:                 bread_crumbs_component => 'User Management'};
 2508:     if ($env{'form.popup'}) {
 2509:         $args->{'no_nav_bar'} = 1;
 2510:     }
 2511:     $r->print(&Apache::loncommon::start_page($title,$jscript,$args));
 2512:     $r->print(&update_result_form($uhome));
 2513:     # Check Inputs
 2514:     if (! $env{'form.ccuname'} ) {
 2515: 	$r->print($error.&mt('No login name specified').'.'.$end.$rtnlink);
 2516: 	return;
 2517:     }
 2518:     if (  $env{'form.ccuname'} ne 
 2519: 	  &LONCAPA::clean_username($env{'form.ccuname'}) ) {
 2520: 	$r->print($error.&mt('Invalid login name.').'  '.
 2521: 		  &mt('Only letters, numbers, periods, dashes, @, and underscores are valid.').
 2522: 		  $end.$rtnlink);
 2523: 	return;
 2524:     }
 2525:     if (! $env{'form.ccdomain'}       ) {
 2526: 	$r->print($error.&mt('No domain specified').'.'.$end.$rtnlink);
 2527: 	return;
 2528:     }
 2529:     if (  $env{'form.ccdomain'} ne
 2530: 	  &LONCAPA::clean_domain($env{'form.ccdomain'}) ) {
 2531: 	$r->print($error.&mt('Invalid domain name.').'  '.
 2532: 		  &mt('Only letters, numbers, periods, dashes, and underscores are valid.').
 2533: 		  $end.$rtnlink);
 2534: 	return;
 2535:     }
 2536:     if ($uhome eq 'no_host') {
 2537:         $newuser = 1;
 2538:     }
 2539:     if (! exists($env{'form.makeuser'})) {
 2540:         # Modifying an existing user, so check the validity of the name
 2541:         if ($uhome eq 'no_host') {
 2542:             $r->print(
 2543:                 $error
 2544:                .'<p class="LC_error">'
 2545:                .&mt('Unable to determine home server for [_1] in domain [_2].',
 2546:                         '"'.$env{'form.ccuname'}.'"','"'.$env{'form.ccdomain'}.'"')
 2547:                .'</p>');
 2548:             return;
 2549:         }
 2550:     }
 2551:     # Determine authentication method and password for the user being modified
 2552:     my $amode='';
 2553:     my $genpwd='';
 2554:     if ($env{'form.login'} eq 'krb') {
 2555: 	$amode='krb';
 2556: 	$amode.=$env{'form.krbver'};
 2557: 	$genpwd=$env{'form.krbarg'};
 2558:     } elsif ($env{'form.login'} eq 'int') {
 2559: 	$amode='internal';
 2560: 	$genpwd=$env{'form.intarg'};
 2561:     } elsif ($env{'form.login'} eq 'fsys') {
 2562: 	$amode='unix';
 2563: 	$genpwd=$env{'form.fsysarg'};
 2564:     } elsif ($env{'form.login'} eq 'loc') {
 2565: 	$amode='localauth';
 2566: 	$genpwd=$env{'form.locarg'};
 2567: 	$genpwd=" " if (!$genpwd);
 2568:     } elsif (($env{'form.login'} eq 'nochange') ||
 2569:              ($env{'form.login'} eq ''        )) { 
 2570:         # There is no need to tell the user we did not change what they
 2571:         # did not ask us to change.
 2572:         # If they are creating a new user but have not specified login
 2573:         # information this will be caught below.
 2574:     } else {
 2575:             $r->print($error.&mt('Invalid login mode or password').$end.$rtnlink);
 2576:             return;
 2577:     }
 2578: 
 2579:     $r->print('<h3>'.&mt('User [_1] in domain [_2]',
 2580:                         $env{'form.ccuname'}.' ('.&Apache::loncommon::plainname($env{'form.ccuname'},
 2581:                         $env{'form.ccdomain'}).')', $env{'form.ccdomain'}).'</h3>');
 2582:     my %prog_state = &Apache::lonhtmlcommon::Create_PrgWin($r,2);
 2583: 
 2584:     my (%alerts,%rulematch,%inst_results,%curr_rules);
 2585:     my @userinfo = ('firstname','middlename','lastname','generation','permanentemail','id');
 2586:     my @usertools = ('aboutme','blog','webdav','portfolio');
 2587:     my @requestcourses = ('official','unofficial','community','textbook');
 2588:     my @requestauthor = ('requestauthor');
 2589:     my ($othertitle,$usertypes,$types) = 
 2590:         &Apache::loncommon::sorted_inst_types($env{'form.ccdomain'});
 2591:     my %canmodify_status =
 2592:         &Apache::lonuserutils::can_modify_userinfo($context,$env{'form.ccdomain'},
 2593:                                                    ['inststatus']);
 2594:     if ($env{'form.makeuser'}) {
 2595: 	$r->print('<h3>'.&mt('Creating new account.').'</h3>');
 2596:         # Check for the authentication mode and password
 2597:         if (! $amode || ! $genpwd) {
 2598: 	    $r->print($error.&mt('Invalid login mode or password').$end.$rtnlink);    
 2599: 	    return;
 2600: 	}
 2601:         # Determine desired host
 2602:         my $desiredhost = $env{'form.hserver'};
 2603:         if (lc($desiredhost) eq 'default') {
 2604:             $desiredhost = undef;
 2605:         } else {
 2606:             my %home_servers = 
 2607: 		&Apache::lonnet::get_servers($env{'form.ccdomain'},'library');
 2608:             if (! exists($home_servers{$desiredhost})) {
 2609:                 $r->print($error.&mt('Invalid home server specified').$end.$rtnlink);
 2610:                 return;
 2611:             }
 2612:         }
 2613:         # Check ID format
 2614:         my %checkhash;
 2615:         my %checks = ('id' => 1);
 2616:         %{$checkhash{$env{'form.ccuname'}.':'.$env{'form.ccdomain'}}} = (
 2617:             'newuser' => $newuser, 
 2618:             'id' => $env{'form.cid'},
 2619:         );
 2620:         if ($env{'form.cid'} ne '') {
 2621:             &Apache::loncommon::user_rule_check(\%checkhash,\%checks,\%alerts,
 2622:                                           \%rulematch,\%inst_results,\%curr_rules);
 2623:             if (ref($alerts{'id'}) eq 'HASH') {
 2624:                 if (ref($alerts{'id'}{$env{'form.ccdomain'}}) eq 'HASH') {
 2625:                     my $domdesc =
 2626:                         &Apache::lonnet::domain($env{'form.ccdomain'},'description');
 2627:                     if ($alerts{'id'}{$env{'form.ccdomain'}}{$env{'form.cid'}}) {
 2628:                         my $userchkmsg;
 2629:                         if (ref($curr_rules{$env{'form.ccdomain'}}) eq 'HASH') {
 2630:                             $userchkmsg  = 
 2631:                                 &Apache::loncommon::instrule_disallow_msg('id',
 2632:                                                                     $domdesc,1).
 2633:                                 &Apache::loncommon::user_rule_formats($env{'form.ccdomain'},
 2634:                                     $domdesc,$curr_rules{$env{'form.ccdomain'}}{'id'},'id');
 2635:                         }
 2636:                         $r->print($error.&mt('Invalid ID format').$end.
 2637:                                   $userchkmsg.$rtnlink);
 2638:                         return;
 2639:                     }
 2640:                 }
 2641:             }
 2642:         }
 2643:         &Apache::lonhtmlcommon::Increment_PrgWin($r, \%prog_state);
 2644: 	# Call modifyuser
 2645: 	my $result = &Apache::lonnet::modifyuser
 2646: 	    ($env{'form.ccdomain'},$env{'form.ccuname'},$env{'form.cid'},
 2647:              $amode,$genpwd,$env{'form.cfirstname'},
 2648:              $env{'form.cmiddlename'},$env{'form.clastname'},
 2649:              $env{'form.cgeneration'},undef,$desiredhost,
 2650:              $env{'form.cpermanentemail'});
 2651: 	$r->print(&mt('Generating user').': '.$result);
 2652:         $uhome = &Apache::lonnet::homeserver($env{'form.ccuname'},
 2653:                                                $env{'form.ccdomain'});
 2654:         my (%changeHash,%newcustom,%changed,%changedinfo);
 2655:         if ($uhome ne 'no_host') {
 2656:             if ($context eq 'domain') {
 2657:                 foreach my $name ('portfolio','author') {
 2658:                     if ($env{'form.custom_'.$name.'quota'} == 1) {
 2659:                         if ($env{'form.'.$name.'quota'} eq '') {
 2660:                             $newcustom{$name.'quota'} = 0;
 2661:                         } else {
 2662:                             $newcustom{$name.'quota'} = $env{'form.'.$name.'quota'};
 2663:                             $newcustom{$name.'quota'} =~ s/[^\d\.]//g;
 2664:                         }
 2665:                         if (&quota_admin($newcustom{$name.'quota'},\%changeHash,$name)) {
 2666:                             $changed{$name.'quota'} = 1;
 2667:                         }
 2668:                     }
 2669:                 }
 2670:                 foreach my $item (@usertools) {
 2671:                     if ($env{'form.custom'.$item} == 1) {
 2672:                         $newcustom{$item} = $env{'form.tools_'.$item};
 2673:                         $changed{$item} = &tool_admin($item,$newcustom{$item},
 2674:                                                      \%changeHash,'tools');
 2675:                     }
 2676:                 }
 2677:                 foreach my $item (@requestcourses) {
 2678:                     if ($env{'form.custom'.$item} == 1) {
 2679:                         $newcustom{$item} = $env{'form.crsreq_'.$item};
 2680:                         if ($env{'form.crsreq_'.$item} eq 'autolimit') {
 2681:                             $newcustom{$item} .= '=';
 2682:                             $env{'form.crsreq_'.$item.'_limit'} =~ s/\D+//g;
 2683:                             if ($env{'form.crsreq_'.$item.'_limit'}) {
 2684:                                 $newcustom{$item} .= $env{'form.crsreq_'.$item.'_limit'};
 2685:                             }
 2686:                         }
 2687:                         $changed{$item} = &tool_admin($item,$newcustom{$item},
 2688:                                                       \%changeHash,'requestcourses');
 2689:                     }
 2690:                 }
 2691:                 if ($env{'form.customrequestauthor'} == 1) {
 2692:                     $newcustom{'requestauthor'} = $env{'form.requestauthor'};
 2693:                     $changed{'requestauthor'} = &tool_admin('requestauthor',
 2694:                                                     $newcustom{'requestauthor'},
 2695:                                                     \%changeHash,'requestauthor');
 2696:                 }
 2697:             }
 2698:             if ($canmodify_status{'inststatus'}) {
 2699:                 if (exists($env{'form.inststatus'})) {
 2700:                     my @inststatuses = &Apache::loncommon::get_env_multiple('form.inststatus');
 2701:                     if (@inststatuses > 0) {
 2702:                         $changeHash{'inststatus'} = join(',',@inststatuses);
 2703:                         $changed{'inststatus'} = $changeHash{'inststatus'};
 2704:                     }
 2705:                 }
 2706:             }
 2707:             if (keys(%changed)) {
 2708:                 foreach my $item (@userinfo) {
 2709:                     $changeHash{$item}  = $env{'form.c'.$item};
 2710:                 }
 2711:                 my $chgresult =
 2712:                      &Apache::lonnet::put('environment',\%changeHash,
 2713:                                           $env{'form.ccdomain'},$env{'form.ccuname'});
 2714:             } 
 2715:         }
 2716:         $r->print('<br />'.&mt('Home server').': '.$uhome.' '.
 2717:                   &Apache::lonnet::hostname($uhome));
 2718:     } elsif (($env{'form.login'} ne 'nochange') &&
 2719:              ($env{'form.login'} ne ''        )) {
 2720: 	# Modify user privileges
 2721:         if (! $amode || ! $genpwd) {
 2722: 	    $r->print($error.'Invalid login mode or password'.$end.$rtnlink);    
 2723: 	    return;
 2724: 	}
 2725: 	# Only allow authentication modification if the person has authority
 2726: 	if (&Apache::lonnet::allowed('mau',$env{'form.ccdomain'})) {
 2727: 	    $r->print('Modifying authentication: '.
 2728:                       &Apache::lonnet::modifyuserauth(
 2729: 		       $env{'form.ccdomain'},$env{'form.ccuname'},
 2730:                        $amode,$genpwd));
 2731:             $r->print('<br />'.&mt('Home server').': '.&Apache::lonnet::homeserver
 2732: 		  ($env{'form.ccuname'},$env{'form.ccdomain'}));
 2733: 	} else {
 2734: 	    # Okay, this is a non-fatal error.
 2735: 	    $r->print($error.&mt('You do not have the authority to modify this users authentication information.').$end);    
 2736: 	}
 2737:     }
 2738:     $r->rflush(); # Finish display of header before time consuming actions start
 2739:     &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state);
 2740:     ##
 2741:     my (@userroles,%userupdate,$cnum,$cdom,$defaultcredits,%namechanged);
 2742:     if ($context eq 'course') {
 2743:         ($cnum,$cdom) =
 2744:             &Apache::lonuserutils::get_course_identity();
 2745:         $crstype = &Apache::loncommon::course_type($cdom.'_'.$cnum);
 2746:         if ($showcredits) {
 2747:            $defaultcredits = &Apache::lonuserutils::get_defaultcredits($cdom,$cnum);
 2748:         }
 2749:     }
 2750:     if (! $env{'form.makeuser'} ) {
 2751:         # Check for need to change
 2752:         my %userenv = &Apache::lonnet::get
 2753:             ('environment',['firstname','middlename','lastname','generation',
 2754:              'id','permanentemail','portfolioquota','authorquota','inststatus',
 2755:              'tools.aboutme','tools.blog','tools.webdav','tools.portfolio',
 2756:              'requestcourses.official','requestcourses.unofficial',
 2757:              'requestcourses.community','requestcourses.textbook',
 2758:              'reqcrsotherdom.official','reqcrsotherdom.unofficial',
 2759:              'reqcrsotherdom.community','reqcrsotherdom.textbook',
 2760:              'requestauthor'],
 2761:               $env{'form.ccdomain'},$env{'form.ccuname'});
 2762:         my ($tmp) = keys(%userenv);
 2763:         if ($tmp =~ /^(con_lost|error)/i) { 
 2764:             %userenv = ();
 2765:         }
 2766:         my $no_forceid_alert;
 2767:         # Check to see if user information can be changed
 2768:         my %domconfig =
 2769:             &Apache::lonnet::get_dom('configuration',['usermodification'],
 2770:                                      $env{'form.ccdomain'});
 2771:         my @statuses = ('active','future');
 2772:         my %roles = &Apache::lonnet::get_my_roles($env{'form.ccuname'},$env{'form.ccdomain'},'userroles',\@statuses,undef,$env{'request.role.domain'});
 2773:         my ($auname,$audom);
 2774:         if ($context eq 'author') {
 2775:             $auname = $env{'user.name'};
 2776:             $audom = $env{'user.domain'};     
 2777:         }
 2778:         foreach my $item (keys(%roles)) {
 2779:             my ($rolenum,$roledom,$role) = split(/:/,$item,-1);
 2780:             if ($context eq 'course') {
 2781:                 if ($cnum ne '' && $cdom ne '') {
 2782:                     if ($rolenum eq $cnum && $roledom eq $cdom) {
 2783:                         if (!grep(/^\Q$role\E$/,@userroles)) {
 2784:                             push(@userroles,$role);
 2785:                         }
 2786:                     }
 2787:                 }
 2788:             } elsif ($context eq 'author') {
 2789:                 if ($rolenum eq $auname && $roledom eq $audom) {
 2790:                     if (!grep(/^\Q$role\E$/,@userroles)) { 
 2791:                         push(@userroles,$role);
 2792:                     }
 2793:                 }
 2794:             }
 2795:         }
 2796:         if ($env{'form.action'} eq 'singlestudent') {
 2797:             if (!grep(/^st$/,@userroles)) {
 2798:                 push(@userroles,'st');
 2799:             }
 2800:         } else {
 2801:             # Check for course or co-author roles being activated or re-enabled
 2802:             if ($context eq 'author' || $context eq 'course') {
 2803:                 foreach my $key (keys(%env)) {
 2804:                     if ($context eq 'author') {
 2805:                         if ($key=~/^form\.act_\Q$audom\E_\Q$auname\E_([^_]+)/) {
 2806:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 2807:                                 push(@userroles,$1);
 2808:                             }
 2809:                         } elsif ($key =~/^form\.ren\:\Q$audom\E\/\Q$auname\E_([^_]+)/) {
 2810:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 2811:                                 push(@userroles,$1);
 2812:                             }
 2813:                         }
 2814:                     } elsif ($context eq 'course') {
 2815:                         if ($key=~/^form\.act_\Q$cdom\E_\Q$cnum\E_([^_]+)/) {
 2816:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 2817:                                 push(@userroles,$1);
 2818:                             }
 2819:                         } elsif ($key =~/^form\.ren\:\Q$cdom\E\/\Q$cnum\E(\/?\w*)_([^_]+)/) {
 2820:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 2821:                                 push(@userroles,$1);
 2822:                             }
 2823:                         }
 2824:                     }
 2825:                 }
 2826:             }
 2827:         }
 2828:         #Check to see if we can change personal data for the user 
 2829:         my (@mod_disallowed,@longroles);
 2830:         foreach my $role (@userroles) {
 2831:             if ($role eq 'cr') {
 2832:                 push(@longroles,'Custom');
 2833:             } else {
 2834:                 push(@longroles,&Apache::lonnet::plaintext($role,$crstype)); 
 2835:             }
 2836:         }
 2837:         my %canmodify = &Apache::lonuserutils::can_modify_userinfo($context,$env{'form.ccdomain'},\@userinfo,\@userroles);
 2838:         foreach my $item (@userinfo) {
 2839:             # Strip leading and trailing whitespace
 2840:             $env{'form.c'.$item} =~ s/(\s+$|^\s+)//g;
 2841:             if (!$canmodify{$item}) {
 2842:                 if (defined($env{'form.c'.$item})) {
 2843:                     if ($env{'form.c'.$item} ne $userenv{$item}) {
 2844:                         push(@mod_disallowed,$item);
 2845:                     }
 2846:                 }
 2847:                 $env{'form.c'.$item} = $userenv{$item};
 2848:             }
 2849:         }
 2850:         # Check to see if we can change the Student/Employee ID
 2851:         my $forceid = $env{'form.forceid'};
 2852:         my $recurseid = $env{'form.recurseid'};
 2853:         my (%alerts,%rulematch,%idinst_results,%curr_rules,%got_rules);
 2854:         my %uidhash = &Apache::lonnet::idrget($env{'form.ccdomain'},
 2855:                                             $env{'form.ccuname'});
 2856:         if (($uidhash{$env{'form.ccuname'}}) && 
 2857:             ($uidhash{$env{'form.ccuname'}}!~/error\:/) && 
 2858:             (!$forceid)) {
 2859:             if ($env{'form.cid'} ne $uidhash{$env{'form.ccuname'}}) {
 2860:                 $env{'form.cid'} = $userenv{'id'};
 2861:                 $no_forceid_alert = &mt('New student/employee ID does not match existing ID for this user.')
 2862:                                    .'<br />'
 2863:                                    .&mt("Change is not permitted without checking the 'Force ID change' checkbox on the previous page.")
 2864:                                    .'<br />'."\n";
 2865:             }
 2866:         }
 2867:         if ($env{'form.cid'} ne $userenv{'id'}) {
 2868:             my $checkhash;
 2869:             my $checks = { 'id' => 1 };
 2870:             $checkhash->{$env{'form.ccuname'}.':'.$env{'form.ccdomain'}} = 
 2871:                    { 'newuser' => $newuser,
 2872:                      'id'  => $env{'form.cid'}, 
 2873:                    };
 2874:             &Apache::loncommon::user_rule_check($checkhash,$checks,
 2875:                 \%alerts,\%rulematch,\%idinst_results,\%curr_rules,\%got_rules);
 2876:             if (ref($alerts{'id'}) eq 'HASH') {
 2877:                 if (ref($alerts{'id'}{$env{'form.ccdomain'}}) eq 'HASH') {
 2878:                    $env{'form.cid'} = $userenv{'id'};
 2879:                 }
 2880:             }
 2881:         }
 2882:         my (%quotachanged,%oldquota,%newquota,%olddefquota,%newdefquota, 
 2883:             $oldinststatus,$newinststatus,%oldisdefault,%newisdefault,%oldsettings,
 2884:             %oldsettingstext,%newsettings,%newsettingstext,@disporder,
 2885:             %oldsettingstatus,%newsettingstatus);
 2886:         @disporder = ('inststatus');
 2887:         if ($env{'request.role.domain'} eq $env{'form.ccdomain'}) {
 2888:             push(@disporder,'requestcourses','requestauthor');
 2889:         } else {
 2890:             push(@disporder,'reqcrsotherdom');
 2891:         }
 2892:         push(@disporder,('quota','tools'));
 2893:         $oldinststatus = $userenv{'inststatus'};
 2894:         foreach my $name ('portfolio','author') {
 2895:             ($olddefquota{$name},$oldsettingstatus{$name}) = 
 2896:                 &Apache::loncommon::default_quota($env{'form.ccdomain'},$oldinststatus,$name);
 2897:             ($newdefquota{$name},$newsettingstatus{$name}) = ($olddefquota{$name},$oldsettingstatus{$name});
 2898:         }
 2899:         my %canshow;
 2900:         if (&Apache::lonnet::allowed('mpq',$env{'form.ccdomain'})) {
 2901:             $canshow{'quota'} = 1;
 2902:         }
 2903:         if (&Apache::lonnet::allowed('mut',$env{'form.ccdomain'})) {
 2904:             $canshow{'tools'} = 1;
 2905:         }
 2906:         if (&Apache::lonnet::allowed('ccc',$env{'form.ccdomain'})) {
 2907:             $canshow{'requestcourses'} = 1;
 2908:         } elsif (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) {
 2909:             $canshow{'reqcrsotherdom'} = 1;
 2910:         }
 2911:         if (&Apache::lonnet::allowed('mau',$env{'form.ccdomain'})) {
 2912:             $canshow{'inststatus'} = 1;
 2913:         }
 2914:         if (&Apache::lonnet::allowed('cau',$env{'form.ccdomain'})) {
 2915:             $canshow{'requestauthor'} = 1;
 2916:         }
 2917:         my (%changeHash,%changed);
 2918:         if ($oldinststatus eq '') {
 2919:             $oldsettings{'inststatus'} = $othertitle; 
 2920:         } else {
 2921:             if (ref($usertypes) eq 'HASH') {
 2922:                 $oldsettings{'inststatus'} = join(', ',map{ $usertypes->{ &unescape($_) }; } (split(/:/,$userenv{'inststatus'})));
 2923:             } else {
 2924:                 $oldsettings{'inststatus'} = join(', ',map{ &unescape($_); } (split(/:/,$userenv{'inststatus'})));
 2925:             }
 2926:         }
 2927:         $changeHash{'inststatus'} = $userenv{'inststatus'};
 2928:         if ($canmodify_status{'inststatus'}) {
 2929:             $canshow{'inststatus'} = 1;
 2930:             if (exists($env{'form.inststatus'})) {
 2931:                 my @inststatuses = &Apache::loncommon::get_env_multiple('form.inststatus');
 2932:                 if (@inststatuses > 0) {
 2933:                     $newinststatus = join(':',map { &escape($_); } @inststatuses);
 2934:                     $changeHash{'inststatus'} = $newinststatus;
 2935:                     if ($newinststatus ne $oldinststatus) {
 2936:                         $changed{'inststatus'} = $newinststatus;
 2937:                         foreach my $name ('portfolio','author') {
 2938:                             ($newdefquota{$name},$newsettingstatus{$name}) =
 2939:                                 &Apache::loncommon::default_quota($env{'form.ccdomain'},$newinststatus,$name);
 2940:                         }
 2941:                     }
 2942:                     if (ref($usertypes) eq 'HASH') {
 2943:                         $newsettings{'inststatus'} = join(', ',map{ $usertypes->{$_}; } (@inststatuses)); 
 2944:                     } else {
 2945:                         $newsettings{'inststatus'} = join(', ',@inststatuses);
 2946:                     }
 2947:                 }
 2948:             } else {
 2949:                 $newinststatus = '';
 2950:                 $changeHash{'inststatus'} = $newinststatus;
 2951:                 $newsettings{'inststatus'} = $othertitle;
 2952:                 if ($newinststatus ne $oldinststatus) {
 2953:                     $changed{'inststatus'} = $changeHash{'inststatus'};
 2954:                     foreach my $name ('portfolio','author') {
 2955:                         ($newdefquota{$name},$newsettingstatus{$name}) =
 2956:                             &Apache::loncommon::default_quota($env{'form.ccdomain'},$newinststatus,$name);
 2957:                     }
 2958:                 }
 2959:             }
 2960:         } elsif ($context ne 'selfcreate') {
 2961:             $canshow{'inststatus'} = 1;
 2962:             $newsettings{'inststatus'} = $oldsettings{'inststatus'};
 2963:         }
 2964:         foreach my $name ('portfolio','author') {
 2965:             $changeHash{$name.'quota'} = $userenv{$name.'quota'};
 2966:         }
 2967:         if ($context eq 'domain') {
 2968:             foreach my $name ('portfolio','author') {
 2969:                 if ($userenv{$name.'quota'} ne '') {
 2970:                     $oldquota{$name} = $userenv{$name.'quota'};
 2971:                     if ($env{'form.custom_'.$name.'quota'} == 1) {
 2972:                         if ($env{'form.'.$name.'quota'} eq '') {
 2973:                             $newquota{$name} = 0;
 2974:                         } else {
 2975:                             $newquota{$name} = $env{'form.'.$name.'quota'};
 2976:                             $newquota{$name} =~ s/[^\d\.]//g;
 2977:                         }
 2978:                         if ($newquota{$name} != $oldquota{$name}) {
 2979:                             if (&quota_admin($newquota{$name},\%changeHash,$name)) {
 2980:                                 $changed{$name.'quota'} = 1;
 2981:                             }
 2982:                         }
 2983:                     } else {
 2984:                         if (&quota_admin('',\%changeHash,$name)) {
 2985:                             $changed{$name.'quota'} = 1;
 2986:                             $newquota{$name} = $newdefquota{$name};
 2987:                             $newisdefault{$name} = 1;
 2988:                         }
 2989:                     }
 2990:                 } else {
 2991:                     $oldisdefault{$name} = 1;
 2992:                     $oldquota{$name} = $olddefquota{$name};
 2993:                     if ($env{'form.custom_'.$name.'quota'} == 1) {
 2994:                         if ($env{'form.'.$name.'quota'} eq '') {
 2995:                             $newquota{$name} = 0;
 2996:                         } else {
 2997:                             $newquota{$name} = $env{'form.'.$name.'quota'};
 2998:                             $newquota{$name} =~ s/[^\d\.]//g;
 2999:                         }
 3000:                         if (&quota_admin($newquota{$name},\%changeHash,$name)) {
 3001:                             $changed{$name.'quota'} = 1;
 3002:                         }
 3003:                     } else {
 3004:                         $newquota{$name} = $newdefquota{$name};
 3005:                         $newisdefault{$name} = 1;
 3006:                     }
 3007:                 }
 3008:                 if ($oldisdefault{$name}) {
 3009:                     $oldsettingstext{'quota'}{$name} = &get_defaultquota_text($oldsettingstatus{$name});
 3010:                 }  else {
 3011:                     $oldsettingstext{'quota'}{$name} = &mt('custom quota: [_1] MB',$oldquota{$name});
 3012:                 }
 3013:                 if ($newisdefault{$name}) {
 3014:                     $newsettingstext{'quota'}{$name} = &get_defaultquota_text($newsettingstatus{$name});
 3015:                 } else {
 3016:                     $newsettingstext{'quota'}{$name} = &mt('custom quota: [_1] MB',$newquota{$name});
 3017:                 }
 3018:             }
 3019:             &tool_changes('tools',\@usertools,\%oldsettings,\%oldsettingstext,\%userenv,
 3020:                           \%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3021:             if ($env{'form.ccdomain'} eq $env{'request.role.domain'}) {
 3022:                 &tool_changes('requestcourses',\@requestcourses,\%oldsettings,\%oldsettingstext,
 3023:                               \%userenv,\%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3024:                 &tool_changes('requestauthor',\@requestauthor,\%oldsettings,\%oldsettingstext,
 3025:                               \%userenv,\%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3026:             } else {
 3027:                 &tool_changes('reqcrsotherdom',\@requestcourses,\%oldsettings,\%oldsettingstext,
 3028:                               \%userenv,\%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3029:             }
 3030:         }
 3031:         foreach my $item (@userinfo) {
 3032:             if ($env{'form.c'.$item} ne $userenv{$item}) {
 3033:                 $namechanged{$item} = 1;
 3034:             }
 3035:         }
 3036:         foreach my $name ('portfolio','author') {
 3037:             $oldsettings{'quota'}{$name} = &mt('[_1] MB',$oldquota{$name});
 3038:             $newsettings{'quota'}{$name} = &mt('[_1] MB',$newquota{$name});
 3039:         }
 3040:         if ((keys(%namechanged) > 0) || (keys(%changed) > 0)) {
 3041:             my ($chgresult,$namechgresult);
 3042:             if (keys(%changed) > 0) {
 3043:                 $chgresult = 
 3044:                     &Apache::lonnet::put('environment',\%changeHash,
 3045:                                   $env{'form.ccdomain'},$env{'form.ccuname'});
 3046:                 if ($chgresult eq 'ok') {
 3047:                     if (($env{'user.name'} eq $env{'form.ccuname'}) &&
 3048:                         ($env{'user.domain'} eq $env{'form.ccdomain'})) {
 3049:                         my %newenvhash;
 3050:                         foreach my $key (keys(%changed)) {
 3051:                             if (($key eq 'official') || ($key eq 'unofficial')
 3052:                                 || ($key eq 'community') || ($key eq 'textbook')) {
 3053:                                 $newenvhash{'environment.requestcourses.'.$key} =
 3054:                                     $changeHash{'requestcourses.'.$key};
 3055:                                 if ($changeHash{'requestcourses.'.$key}) {
 3056:                                     $newenvhash{'environment.canrequest.'.$key} = 1;
 3057:                                 } else {
 3058:                                     $newenvhash{'environment.canrequest.'.$key} =
 3059:           &Apache::lonnet::usertools_access($env{'user.name'},$env{'user.domain'},
 3060:                                             $key,'reload','requestcourses');
 3061:                                 }
 3062:                             } elsif ($key eq 'requestauthor') {
 3063:                                 $newenvhash{'environment.'.$key} = $changeHash{$key};
 3064:                                 if ($changeHash{$key}) {
 3065:                                     $newenvhash{'environment.canrequest.author'} = 1;
 3066:                                 } else {
 3067:                                     $newenvhash{'environment.canrequest.author'} =
 3068:           &Apache::lonnet::usertools_access($env{'user.name'},$env{'user.domain'},
 3069:                                             $key,'reload','requestauthor');
 3070:                                 }
 3071:                             } elsif ($key ne 'quota') {
 3072:                                 $newenvhash{'environment.tools.'.$key} = 
 3073:                                     $changeHash{'tools.'.$key};
 3074:                                 if ($changeHash{'tools.'.$key} ne '') {
 3075:                                     $newenvhash{'environment.availabletools.'.$key} =
 3076:                                         $changeHash{'tools.'.$key};
 3077:                                 } else {
 3078:                                     $newenvhash{'environment.availabletools.'.$key} =
 3079:           &Apache::lonnet::usertools_access($env{'user.name'},$env{'user.domain'},
 3080:           $key,'reload','tools');
 3081:                                 }
 3082:                             }
 3083:                         }
 3084:                         if (keys(%newenvhash)) {
 3085:                             &Apache::lonnet::appenv(\%newenvhash);
 3086:                         }
 3087:                     }
 3088:                 }
 3089:             }
 3090:             if (keys(%namechanged) > 0) {
 3091:                 foreach my $field (@userinfo) {
 3092:                     $changeHash{$field}  = $env{'form.c'.$field};
 3093:                 }
 3094: # Make the change
 3095:                 $namechgresult =
 3096:                     &Apache::lonnet::modifyuser($env{'form.ccdomain'},
 3097:                         $env{'form.ccuname'},$changeHash{'id'},undef,undef,
 3098:                         $changeHash{'firstname'},$changeHash{'middlename'},
 3099:                         $changeHash{'lastname'},$changeHash{'generation'},
 3100:                         $changeHash{'id'},undef,$changeHash{'permanentemail'},undef,\@userinfo);
 3101:                 %userupdate = (
 3102:                                lastname   => $env{'form.clastname'},
 3103:                                middlename => $env{'form.cmiddlename'},
 3104:                                firstname  => $env{'form.cfirstname'},
 3105:                                generation => $env{'form.cgeneration'},
 3106:                                id         => $env{'form.cid'},
 3107:                              );
 3108:             }
 3109:             if (((keys(%namechanged) > 0) && $namechgresult eq 'ok') || 
 3110:                 ((keys(%changed) > 0) && $chgresult eq 'ok')) {
 3111:             # Tell the user we changed the name
 3112:                 &display_userinfo($r,1,\@disporder,\%canshow,\@requestcourses,
 3113:                                   \@usertools,\@requestauthor,\%userenv,\%changed,\%namechanged,
 3114:                                   \%oldsettings, \%oldsettingstext,\%newsettings,
 3115:                                   \%newsettingstext);
 3116:                 if ($env{'form.cid'} ne $userenv{'id'}) {
 3117:                     &Apache::lonnet::idput($env{'form.ccdomain'},
 3118:                          ($env{'form.ccuname'} => $env{'form.cid'}));
 3119:                     if (($recurseid) &&
 3120:                         (&Apache::lonnet::allowed('mau',$env{'form.ccdomain'}))) {
 3121:                         my $idresult = 
 3122:                             &Apache::lonuserutils::propagate_id_change(
 3123:                                 $env{'form.ccuname'},$env{'form.ccdomain'},
 3124:                                 \%userupdate);
 3125:                         $r->print('<br />'.$idresult.'<br />');
 3126:                     }
 3127:                 }
 3128:                 if (($env{'form.ccdomain'} eq $env{'user.domain'}) && 
 3129:                     ($env{'form.ccuname'} eq $env{'user.name'})) {
 3130:                     my %newenvhash;
 3131:                     foreach my $key (keys(%changeHash)) {
 3132:                         $newenvhash{'environment.'.$key} = $changeHash{$key};
 3133:                     }
 3134:                     &Apache::lonnet::appenv(\%newenvhash);
 3135:                 }
 3136:             } else { # error occurred
 3137:                 $r->print(
 3138:                     '<p class="LC_error">'
 3139:                    .&mt('Unable to successfully change environment for [_1] in domain [_2].',
 3140:                             '"'.$env{'form.ccuname'}.'"',
 3141:                             '"'.$env{'form.ccdomain'}.'"')
 3142:                    .'</p>');
 3143:             }
 3144:         } else { # End of if ($env ... ) logic
 3145:             # They did not want to change the users name, quota, tool availability,
 3146:             # or ability to request creation of courses, 
 3147:             # but we can still tell them what the name and quota and availabilities are  
 3148:             &display_userinfo($r,undef,\@disporder,\%canshow,\@requestcourses,
 3149:                               \@usertools,\@requestauthor,\%userenv,\%changed,\%namechanged,\%oldsettings,
 3150:                               \%oldsettingstext,\%newsettings,\%newsettingstext);
 3151:         }
 3152:         if (@mod_disallowed) {
 3153:             my ($rolestr,$contextname);
 3154:             if (@longroles > 0) {
 3155:                 $rolestr = join(', ',@longroles);
 3156:             } else {
 3157:                 $rolestr = &mt('No roles');
 3158:             }
 3159:             if ($context eq 'course') {
 3160:                 $contextname = 'course';
 3161:             } elsif ($context eq 'author') {
 3162:                 $contextname = 'co-author';
 3163:             }
 3164:             $r->print(&mt('The following fields were not updated: ').'<ul>');
 3165:             my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
 3166:             foreach my $field (@mod_disallowed) {
 3167:                 $r->print('<li>'.$fieldtitles{$field}.'</li>'."\n"); 
 3168:             }
 3169:             $r->print('</ul>');
 3170:             if (@mod_disallowed == 1) {
 3171:                 $r->print(&mt("You do not have the authority to change this field given the user's current set of active/future $contextname roles:"));
 3172:             } else {
 3173:                 $r->print(&mt("You do not have the authority to change these fields given the user's current set of active/future $contextname roles:"));
 3174:             }
 3175:             my $helplink = 'javascript:helpMenu('."'display'".')';
 3176:             $r->print('<span class="LC_cusr_emph">'.$rolestr.'</span><br />'
 3177:                      .&mt('Please contact your [_1]helpdesk[_2] for more information.'
 3178:                          ,'<a href="'.$helplink.'">','</a>')
 3179:                       .'<br />');
 3180:         }
 3181:         $r->print('<span class="LC_warning">'
 3182:                   .$no_forceid_alert
 3183:                   .&Apache::lonuserutils::print_namespacing_alerts($env{'form.ccdomain'},\%alerts,\%curr_rules)
 3184:                   .'</span>');
 3185:     }
 3186:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 3187:     if ($env{'form.action'} eq 'singlestudent') {
 3188:         &enroll_single_student($r,$uhome,$amode,$genpwd,$now,$newuser,$context,
 3189:                                $crstype,$showcredits,$defaultcredits);
 3190:         my $linktext = ($crstype eq 'Community' ?
 3191:             &mt('Enroll Another Member') : &mt('Enroll Another Student'));
 3192:         $r->print(
 3193:             &Apache::lonhtmlcommon::actionbox([
 3194:                 '<a href="javascript:backPage(document.userupdate)">'
 3195:                .($crstype eq 'Community' ? 
 3196:                     &mt('Enroll Another Member') : &mt('Enroll Another Student'))
 3197:                .'</a>']));
 3198:     } else {
 3199:         my @rolechanges = &update_roles($r,$context,$showcredits);
 3200:         if (keys(%namechanged) > 0) {
 3201:             if ($context eq 'course') {
 3202:                 if (@userroles > 0) {
 3203:                     if ((@rolechanges == 0) || 
 3204:                         (!(grep(/^st$/,@rolechanges)))) {
 3205:                         if (grep(/^st$/,@userroles)) {
 3206:                             my $classlistupdated =
 3207:                                 &Apache::lonuserutils::update_classlist($cdom,
 3208:                                               $cnum,$env{'form.ccdomain'},
 3209:                                        $env{'form.ccuname'},\%userupdate);
 3210:                         }
 3211:                     }
 3212:                 }
 3213:             }
 3214:         }
 3215:         my $userinfo = &Apache::loncommon::plainname($env{'form.ccuname'},
 3216:                                                      $env{'form.ccdomain'});
 3217:         if ($env{'form.popup'}) {
 3218:             $r->print('<p><a href="javascript:window.close()">'.&mt('Close window').'</a></p>');
 3219:         } else {
 3220:             $r->print('<br />'.&Apache::lonhtmlcommon::actionbox(['<a href="javascript:backPage(document.userupdate,'."'$env{'form.prevphase'}','modify'".')">'
 3221:                      .&mt('Modify this user: [_1]','<span class="LC_cusr_emph">'.$env{'form.ccuname'}.':'.$env{'form.ccdomain'}.' ('.$userinfo.')</span>').'</a>',
 3222:                      '<a href="javascript:backPage(document.userupdate)">'.&mt('Create/Modify Another User').'</a>']));
 3223:         }
 3224:     }
 3225: }
 3226: 
 3227: sub display_userinfo {
 3228:     my ($r,$changed,$order,$canshow,$requestcourses,$usertools,$requestauthor,
 3229:         $userenv,$changedhash,$namechangedhash,$oldsetting,$oldsettingtext,
 3230:         $newsetting,$newsettingtext) = @_;
 3231:     return unless (ref($order) eq 'ARRAY' &&
 3232:                    ref($canshow) eq 'HASH' && 
 3233:                    ref($requestcourses) eq 'ARRAY' && 
 3234:                    ref($requestauthor) eq 'ARRAY' &&
 3235:                    ref($usertools) eq 'ARRAY' && 
 3236:                    ref($userenv) eq 'HASH' &&
 3237:                    ref($changedhash) eq 'HASH' &&
 3238:                    ref($oldsetting) eq 'HASH' &&
 3239:                    ref($oldsettingtext) eq 'HASH' &&
 3240:                    ref($newsetting) eq 'HASH' &&
 3241:                    ref($newsettingtext) eq 'HASH');
 3242:     my %lt=&Apache::lonlocal::texthash(
 3243:          'ui'             => 'User Information',
 3244:          'uic'            => 'User Information Changed',
 3245:          'firstname'      => 'First Name',
 3246:          'middlename'     => 'Middle Name',
 3247:          'lastname'       => 'Last Name',
 3248:          'generation'     => 'Generation',
 3249:          'id'             => 'Student/Employee ID',
 3250:          'permanentemail' => 'Permanent e-mail address',
 3251:          'portfolioquota' => 'Disk space allocated to portfolio files',
 3252:          'authorquota'    => 'Disk space allocated to Authoring Space',
 3253:          'blog'           => 'Blog Availability',
 3254:          'webdav'         => 'WebDAV Availability',
 3255:          'aboutme'        => 'Personal Information Page Availability',
 3256:          'portfolio'      => 'Portfolio Availability',
 3257:          'official'       => 'Can Request Official Courses',
 3258:          'unofficial'     => 'Can Request Unofficial Courses',
 3259:          'community'      => 'Can Request Communities',
 3260:          'textbook'       => 'Can Request Textbook Courses',
 3261:          'requestauthor'  => 'Can Request Author Role',
 3262:          'inststatus'     => "Affiliation",
 3263:          'prvs'           => 'Previous Value:',
 3264:          'chto'           => 'Changed To:'
 3265:     );
 3266:     if ($changed) {
 3267:         $r->print('<h3>'.$lt{'uic'}.'</h3>'.
 3268:                 &Apache::loncommon::start_data_table().
 3269:                 &Apache::loncommon::start_data_table_header_row());
 3270:         $r->print("<th>&nbsp;</th>\n");
 3271:         $r->print('<th><b>'.$lt{'prvs'}.'</b></th>');
 3272:         $r->print('<th><span class="LC_nobreak"><b>'.$lt{'chto'}.'</b></span></th>');
 3273:         $r->print(&Apache::loncommon::end_data_table_header_row());
 3274:         my @userinfo = ('firstname','middlename','lastname','generation','permanentemail','id');
 3275: 
 3276:         foreach my $item (@userinfo) {
 3277:             my $value = $env{'form.c'.$item};
 3278:             #show changes only:
 3279:             unless ($value eq $userenv->{$item}){
 3280:                 $r->print(&Apache::loncommon::start_data_table_row());
 3281:                 $r->print("<td>$lt{$item}</td>\n");
 3282:                 $r->print("<td>".$userenv->{$item}."</td>\n");
 3283:                 $r->print("<td>$value </td>\n");
 3284:                 $r->print(&Apache::loncommon::end_data_table_row());
 3285:             }
 3286:         }
 3287:         foreach my $entry (@{$order}) {
 3288:             if ($canshow->{$entry}) {
 3289:                 if (($entry eq 'requestcourses') || ($entry eq 'reqcrsotherdom') || ($entry eq 'requestauthor')) {
 3290:                     my @items;
 3291:                     if ($entry eq 'requestauthor') {
 3292:                         @items = ($entry);
 3293:                     } else {
 3294:                         @items = @{$requestcourses};
 3295:                     }
 3296:                     foreach my $item (@items) {
 3297:                         if (($newsetting->{$item} ne $oldsetting->{$item}) || 
 3298:                             ($newsettingtext->{$item} ne $oldsettingtext->{$item})) {
 3299:                             $r->print(&Apache::loncommon::start_data_table_row()."\n");  
 3300:                             $r->print("<td>$lt{$item}</td>\n");
 3301:                             $r->print("<td>".$oldsetting->{$item});
 3302:                             if ($oldsettingtext->{$item}) {
 3303:                                 if ($oldsetting->{$item}) {
 3304:                                     $r->print(' -- ');
 3305:                                 }
 3306:                                 $r->print($oldsettingtext->{$item});
 3307:                             }
 3308:                             $r->print("</td>\n");
 3309:                             $r->print("<td>".$newsetting->{$item});
 3310:                             if ($newsettingtext->{$item}) {
 3311:                                 if ($newsetting->{$item}) {
 3312:                                     $r->print(' -- ');
 3313:                                 }
 3314:                                 $r->print($newsettingtext->{$item});
 3315:                             }
 3316:                             $r->print("</td>\n");
 3317:                             $r->print(&Apache::loncommon::end_data_table_row()."\n");
 3318:                         }
 3319:                     }
 3320:                 } elsif ($entry eq 'tools') {
 3321:                     foreach my $item (@{$usertools}) {
 3322:                         if ($newsetting->{$item} ne $oldsetting->{$item}) {
 3323:                             $r->print(&Apache::loncommon::start_data_table_row()."\n");
 3324:                             $r->print("<td>$lt{$item}</td>\n");
 3325:                             $r->print("<td>".$oldsetting->{$item}.' '.$oldsettingtext->{$item}."</td>\n");
 3326:                             $r->print("<td>".$newsetting->{$item}.' '.$newsettingtext->{$item}."</td>\n");
 3327:                             $r->print(&Apache::loncommon::end_data_table_row()."\n");
 3328:                         }
 3329:                     }
 3330:                 } elsif ($entry eq 'quota') {
 3331:                     if ((ref($oldsetting->{$entry}) eq 'HASH') && (ref($oldsettingtext->{$entry}) eq 'HASH') &&
 3332:                         (ref($newsetting->{$entry}) eq 'HASH') && (ref($newsettingtext->{$entry}) eq 'HASH')) {
 3333:                         foreach my $name ('portfolio','author') {
 3334:                             if ($newsetting->{$entry}->{$name} ne $oldsetting->{$entry}->{$name}) {
 3335:                                 $r->print(&Apache::loncommon::start_data_table_row()."\n");
 3336:                                 $r->print("<td>$lt{$name.$entry}</td>\n");
 3337:                                 $r->print("<td>".$oldsettingtext->{$entry}->{$name}."</td>\n");
 3338:                                 $r->print("<td>".$newsettingtext->{$entry}->{$name}."</td>\n");
 3339:                                 $r->print(&Apache::loncommon::end_data_table_row()."\n");
 3340:                             }
 3341:                         }
 3342:                     }
 3343:                 } else {
 3344:                     if ($newsetting->{$entry} ne $oldsetting->{$entry}) {
 3345:                         $r->print(&Apache::loncommon::start_data_table_row()."\n");
 3346:                         $r->print("<td>$lt{$entry}</td>\n");
 3347:                         $r->print("<td>".$oldsetting->{$entry}.' '.$oldsettingtext->{$entry}."</td>\n");
 3348:                         $r->print("<td>".$newsetting->{$entry}.' '.$newsettingtext->{$entry}."</td>\n");
 3349:                         $r->print(&Apache::loncommon::end_data_table_row()."\n");
 3350:                     }
 3351:                 }
 3352:             }
 3353:         }
 3354:         $r->print(&Apache::loncommon::end_data_table().'<br />');
 3355:     } else {
 3356:         $r->print('<h3>'.$lt{'ui'}.'</h3>'.
 3357:                   '<p>'.&mt('No changes made to user information').'</p>');
 3358:     }
 3359:     return;
 3360: }
 3361: 
 3362: sub tool_changes {
 3363:     my ($context,$usertools,$oldaccess,$oldaccesstext,$userenv,$changeHash,
 3364:         $changed,$newaccess,$newaccesstext) = @_;
 3365:     if (!((ref($usertools) eq 'ARRAY') && (ref($oldaccess) eq 'HASH') &&
 3366:           (ref($oldaccesstext) eq 'HASH') && (ref($userenv) eq 'HASH') &&
 3367:           (ref($changeHash) eq 'HASH') && (ref($changed) eq 'HASH') &&
 3368:           (ref($newaccess) eq 'HASH') && (ref($newaccesstext) eq 'HASH'))) {
 3369:         return;
 3370:     }
 3371:     my %reqdisplay = &requestchange_display();
 3372:     if ($context eq 'reqcrsotherdom') {
 3373:         my @options = ('approval','validate','autolimit');
 3374:         my $optregex = join('|',@options);
 3375:         my $cdom = $env{'request.role.domain'};
 3376:         foreach my $tool (@{$usertools}) {
 3377:             $oldaccesstext->{$tool} = &mt("availability set to 'off'");
 3378:             $newaccesstext->{$tool} = $oldaccesstext->{$tool};
 3379:             $changeHash->{$context.'.'.$tool} = $userenv->{$context.'.'.$tool};
 3380:             my ($newop,$limit);
 3381:             if ($env{'form.'.$context.'_'.$tool}) {
 3382:                 $newop = $env{'form.'.$context.'_'.$tool};
 3383:                 if ($newop eq 'autolimit') {
 3384:                     $limit = $env{'form.'.$context.'_'.$tool.'_limit'};
 3385:                     $limit =~ s/\D+//g;
 3386:                     $newop .= '='.$limit;
 3387:                 }
 3388:             }
 3389:             if ($userenv->{$context.'.'.$tool} eq '') {
 3390:                 if ($newop) {
 3391:                     $changed->{$tool}=&tool_admin($tool,$cdom.':'.$newop,
 3392:                                                   $changeHash,$context);
 3393:                     if ($changed->{$tool}) {
 3394:                         if ($newop =~ /^autolimit/) {
 3395:                             if ($limit) {
 3396:                                 $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3397:                             } else {
 3398:                                 $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3399:                             }
 3400:                         } else {
 3401:                             $newaccesstext->{$tool} = $reqdisplay{$newop};
 3402:                         }
 3403:                     } else {
 3404:                         $newaccesstext->{$tool} = $oldaccesstext->{$tool};
 3405:                     }
 3406:                 }
 3407:             } else {
 3408:                 my @curr = split(',',$userenv->{$context.'.'.$tool});
 3409:                 my @new;
 3410:                 my $changedoms;
 3411:                 foreach my $req (@curr) {
 3412:                     if ($req =~ /^\Q$cdom\E\:($optregex\=?\d*)$/) {
 3413:                         my $oldop = $1;
 3414:                         if ($oldop =~ /^autolimit=(\d*)/) {
 3415:                             my $limit = $1;
 3416:                             if ($limit) {
 3417:                                 $oldaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3418:                             } else {
 3419:                                 $oldaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3420:                             }
 3421:                         } else {
 3422:                             $oldaccesstext->{$tool} = $reqdisplay{$oldop};
 3423:                         }
 3424:                         if ($oldop ne $newop) {
 3425:                             $changedoms = 1;
 3426:                             foreach my $item (@curr) {
 3427:                                 my ($reqdom,$option) = split(':',$item);
 3428:                                 unless ($reqdom eq $cdom) {
 3429:                                     push(@new,$item);
 3430:                                 }
 3431:                             }
 3432:                             if ($newop) {
 3433:                                 push(@new,$cdom.':'.$newop);
 3434:                             }
 3435:                             @new = sort(@new);
 3436:                         }
 3437:                         last;
 3438:                     }
 3439:                 }
 3440:                 if ((!$changedoms) && ($newop)) {
 3441:                     $changedoms = 1;
 3442:                     @new = sort(@curr,$cdom.':'.$newop);
 3443:                 }
 3444:                 if ($changedoms) {
 3445:                     my $newdomstr;
 3446:                     if (@new) {
 3447:                         $newdomstr = join(',',@new);
 3448:                     }
 3449:                     $changed->{$tool}=&tool_admin($tool,$newdomstr,$changeHash,
 3450:                                                   $context);
 3451:                     if ($changed->{$tool}) {
 3452:                         if ($env{'form.'.$context.'_'.$tool}) {
 3453:                             if ($env{'form.'.$context.'_'.$tool} eq 'autolimit') {
 3454:                                 my $limit = $env{'form.'.$context.'_'.$tool.'_limit'};
 3455:                                 $limit =~ s/\D+//g;
 3456:                                 if ($limit) {
 3457:                                     $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3458:                                 } else {
 3459:                                     $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3460:                                 }
 3461:                             } else {
 3462:                                 $newaccesstext->{$tool} = $reqdisplay{$env{'form.'.$context.'_'.$tool}};
 3463:                             }
 3464:                         } else {
 3465:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3466:                         }
 3467:                     }
 3468:                 }
 3469:             }
 3470:         }
 3471:         return;
 3472:     }
 3473:     foreach my $tool (@{$usertools}) {
 3474:         my ($newval,$limit,$envkey);
 3475:         $envkey = $context.'.'.$tool;
 3476:         if ($context eq 'requestcourses') {
 3477:             $newval = $env{'form.crsreq_'.$tool};
 3478:             if ($newval eq 'autolimit') {
 3479:                 $limit = $env{'form.crsreq_'.$tool.'_limit'};
 3480:                 $limit =~ s/\D+//g;
 3481:                 $newval .= '='.$limit;
 3482:             }
 3483:         } elsif ($context eq 'requestauthor') {
 3484:             $newval = $env{'form.'.$context};
 3485:             $envkey = $context;
 3486:         } else {
 3487:             $newval = $env{'form.'.$context.'_'.$tool};
 3488:         }
 3489:         if ($userenv->{$envkey} ne '') {
 3490:             $oldaccess->{$tool} = &mt('custom');
 3491:             if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 3492:                 if ($userenv->{$envkey} =~ /^autolimit=(\d*)$/) {
 3493:                     my $currlimit = $1;
 3494:                     if ($currlimit eq '') {
 3495:                         $oldaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3496:                     } else {
 3497:                         $oldaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$currlimit);
 3498:                     }
 3499:                 } elsif ($userenv->{$envkey}) {
 3500:                     $oldaccesstext->{$tool} = $reqdisplay{$userenv->{$envkey}};
 3501:                 } else {
 3502:                     $oldaccesstext->{$tool} = &mt("availability set to 'off'");
 3503:                 }
 3504:             } else {
 3505:                 if ($userenv->{$envkey}) {
 3506:                     $oldaccesstext->{$tool} = &mt("availability set to 'on'");
 3507:                 } else {
 3508:                     $oldaccesstext->{$tool} = &mt("availability set to 'off'");
 3509:                 }
 3510:             }
 3511:             $changeHash->{$envkey} = $userenv->{$envkey};
 3512:             if ($env{'form.custom'.$tool} == 1) {
 3513:                 if ($newval ne $userenv->{$envkey}) {
 3514:                     $changed->{$tool} = &tool_admin($tool,$newval,$changeHash,
 3515:                                                     $context);
 3516:                     if ($changed->{$tool}) {
 3517:                         $newaccess->{$tool} = &mt('custom');
 3518:                         if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 3519:                             if ($newval =~ /^autolimit/) {
 3520:                                 if ($limit) {
 3521:                                     $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3522:                                 } else {
 3523:                                     $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3524:                                 }
 3525:                             } elsif ($newval) {
 3526:                                 $newaccesstext->{$tool} = $reqdisplay{$newval};
 3527:                             } else {
 3528:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3529:                             }
 3530:                         } else {
 3531:                             if ($newval) {
 3532:                                 $newaccesstext->{$tool} = &mt("availability set to 'on'");
 3533:                             } else {
 3534:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3535:                             }
 3536:                         }
 3537:                     } else {
 3538:                         $newaccess->{$tool} = $oldaccess->{$tool};
 3539:                         if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 3540:                             if ($newval =~ /^autolimit/) {
 3541:                                 if ($limit) {
 3542:                                     $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3543:                                 } else {
 3544:                                     $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3545:                                 }
 3546:                             } elsif ($newval) {
 3547:                                 $newaccesstext->{$tool} = $reqdisplay{$newval};
 3548:                             } else {
 3549:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3550:                             }
 3551:                         } else {
 3552:                             if ($userenv->{$context.'.'.$tool}) {
 3553:                                 $newaccesstext->{$tool} = &mt("availability set to 'on'");
 3554:                             } else {
 3555:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3556:                             }
 3557:                         }
 3558:                     }
 3559:                 } else {
 3560:                     $newaccess->{$tool} = $oldaccess->{$tool};
 3561:                     $newaccesstext->{$tool} = $oldaccesstext->{$tool};
 3562:                 }
 3563:             } else {
 3564:                 $changed->{$tool} = &tool_admin($tool,'',$changeHash,$context);
 3565:                 if ($changed->{$tool}) {
 3566:                     $newaccess->{$tool} = &mt('default');
 3567:                 } else {
 3568:                     $newaccess->{$tool} = $oldaccess->{$tool};
 3569:                     if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 3570:                         if ($newval =~ /^autolimit/) {
 3571:                             if ($limit) {
 3572:                                 $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3573:                             } else {
 3574:                                 $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3575:                             }
 3576:                         } elsif ($newval) {
 3577:                             $newaccesstext->{$tool} = $reqdisplay{$newval};
 3578:                         } else {
 3579:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3580:                         }
 3581:                     } else {
 3582:                         if ($userenv->{$context.'.'.$tool}) {
 3583:                             $newaccesstext->{$tool} = &mt("availability set to 'on'");
 3584:                         } else {
 3585:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3586:                         }
 3587:                     }
 3588:                 }
 3589:             }
 3590:         } else {
 3591:             $oldaccess->{$tool} = &mt('default');
 3592:             if ($env{'form.custom'.$tool} == 1) {
 3593:                 $changed->{$tool} = &tool_admin($tool,$newval,$changeHash,
 3594:                                                 $context);
 3595:                 if ($changed->{$tool}) {
 3596:                     $newaccess->{$tool} = &mt('custom');
 3597:                     if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 3598:                         if ($newval =~ /^autolimit/) {
 3599:                             if ($limit) {
 3600:                                 $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3601:                             } else {
 3602:                                 $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3603:                             }
 3604:                         } elsif ($newval) {
 3605:                             $newaccesstext->{$tool} = $reqdisplay{$newval};
 3606:                         } else {
 3607:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3608:                         }
 3609:                     } else {
 3610:                         if ($newval) {
 3611:                             $newaccesstext->{$tool} = &mt("availability set to 'on'");
 3612:                         } else {
 3613:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3614:                         }
 3615:                     }
 3616:                 } else {
 3617:                     $newaccess->{$tool} = $oldaccess->{$tool};
 3618:                 }
 3619:             } else {
 3620:                 $newaccess->{$tool} = $oldaccess->{$tool};
 3621:             }
 3622:         }
 3623:     }
 3624:     return;
 3625: }
 3626: 
 3627: sub update_roles {
 3628:     my ($r,$context,$showcredits) = @_;
 3629:     my $now=time;
 3630:     my @rolechanges;
 3631:     my %disallowed;
 3632:     $r->print('<h3>'.&mt('Modifying Roles').'</h3>');
 3633:     foreach my $key (keys(%env)) {
 3634: 	next if (! $env{$key});
 3635:         next if ($key eq 'form.action');
 3636: 	# Revoke roles
 3637: 	if ($key=~/^form\.rev/) {
 3638: 	    if ($key=~/^form\.rev\:([^\_]+)\_([^\_\.]+)$/) {
 3639: # Revoke standard role
 3640: 		my ($scope,$role) = ($1,$2);
 3641: 		my $result =
 3642: 		    &Apache::lonnet::revokerole($env{'form.ccdomain'},
 3643: 						$env{'form.ccuname'},
 3644: 						$scope,$role,'','',$context);
 3645:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
 3646:                             &mt('Revoking [_1] in [_2]',
 3647:                                 &Apache::lonnet::plaintext($role),
 3648:                                 &Apache::loncommon::show_role_extent($scope,$context,$role)),
 3649:                                 $result ne "ok").'<br />');
 3650:                 if ($result ne "ok") {
 3651:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 3652:                 }
 3653: 		if ($role eq 'st') {
 3654: 		    my $result = 
 3655:                         &Apache::lonuserutils::classlist_drop($scope,
 3656:                             $env{'form.ccuname'},$env{'form.ccdomain'},
 3657: 			    $now);
 3658:                     $r->print(&Apache::lonhtmlcommon::confirm_success($result));
 3659: 		}
 3660:                 if (!grep(/^\Q$role\E$/,@rolechanges)) {
 3661:                     push(@rolechanges,$role);
 3662:                 }
 3663: 	    }
 3664: 	    if ($key=~m{^form\.rev\:([^_]+)_cr\.cr/($match_domain)/($match_username)/(\w+)$}s) {
 3665: # Revoke custom role
 3666:                 my $result = &Apache::lonnet::revokecustomrole(
 3667:                     $env{'form.ccdomain'},$env{'form.ccuname'},$1,$2,$3,$4,'','',$context);
 3668:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
 3669:                             &mt('Revoking custom role [_1] by [_2] in [_3]',
 3670:                                 $4,$3.':'.$2,&Apache::loncommon::show_role_extent($1,$context,'cr')),
 3671:                             $result ne 'ok').'<br />');
 3672:                 if ($result ne "ok") {
 3673:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 3674:                 }
 3675:                 if (!grep(/^cr$/,@rolechanges)) {
 3676:                     push(@rolechanges,'cr');
 3677:                 }
 3678: 	    }
 3679: 	} elsif ($key=~/^form\.del/) {
 3680: 	    if ($key=~/^form\.del\:([^\_]+)\_([^\_\.]+)$/) {
 3681: # Delete standard role
 3682: 		my ($scope,$role) = ($1,$2);
 3683: 		my $result =
 3684: 		    &Apache::lonnet::assignrole($env{'form.ccdomain'},
 3685: 						$env{'form.ccuname'},
 3686: 						$scope,$role,$now,0,1,'',
 3687:                                                 $context);
 3688:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
 3689:                             &mt('Deleting [_1] in [_2]',
 3690:                                 &Apache::lonnet::plaintext($role),
 3691:                                 &Apache::loncommon::show_role_extent($scope,$context,$role)),
 3692:                             $result ne 'ok').'<br />');
 3693:                 if ($result ne "ok") {
 3694:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 3695:                 }
 3696: 
 3697: 		if ($role eq 'st') {
 3698: 		    my $result = 
 3699:                         &Apache::lonuserutils::classlist_drop($scope,
 3700:                             $env{'form.ccuname'},$env{'form.ccdomain'},
 3701: 			    $now);
 3702: 		    $r->print(&Apache::lonhtmlcommon::confirm_success($result));
 3703: 		}
 3704:                 if (!grep(/^\Q$role\E$/,@rolechanges)) {
 3705:                     push(@rolechanges,$role);
 3706:                 }
 3707:             }
 3708: 	    if ($key=~m{^form\.del\:([^_]+)_cr\.cr/($match_domain)/($match_username)/(\w+)$}) {
 3709:                 my ($url,$rdom,$rnam,$rolename) = ($1,$2,$3,$4);
 3710: # Delete custom role
 3711:                 my $result =
 3712:                     &Apache::lonnet::assigncustomrole($env{'form.ccdomain'},
 3713:                         $env{'form.ccuname'},$url,$rdom,$rnam,$rolename,$now,
 3714:                         0,1,$context);
 3715:                 $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('Deleting custom role [_1] by [_2] in [_3]',
 3716:                       $rolename,$rnam.':'.$rdom,&Apache::loncommon::show_role_extent($1,$context,'cr')),
 3717:                       $result ne "ok").'<br />');
 3718:                 if ($result ne "ok") {
 3719:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 3720:                 }
 3721: 
 3722:                 if (!grep(/^cr$/,@rolechanges)) {
 3723:                     push(@rolechanges,'cr');
 3724:                 }
 3725:             }
 3726: 	} elsif ($key=~/^form\.ren/) {
 3727:             my $udom = $env{'form.ccdomain'};
 3728:             my $uname = $env{'form.ccuname'};
 3729: # Re-enable standard role
 3730: 	    if ($key=~/^form\.ren\:([^\_]+)\_([^\_\.]+)$/) {
 3731:                 my $url = $1;
 3732:                 my $role = $2;
 3733:                 my $logmsg;
 3734:                 my $output;
 3735:                 if ($role eq 'st') {
 3736:                     if ($url =~ m-^/($match_domain)/($match_courseid)/?(\w*)$-) {
 3737:                         my ($cdom,$cnum,$csec) = ($1,$2,$3);
 3738:                         my $credits;
 3739:                         if ($showcredits) {
 3740:                             my $defaultcredits = 
 3741:                                 &Apache::lonuserutils::get_defaultcredits($cdom,$cnum);
 3742:                             $credits = &get_user_credits($defaultcredits,$cdom,$cnum);
 3743:                         }
 3744:                         my $result = &Apache::loncommon::commit_studentrole(\$logmsg,$udom,$uname,$url,$role,$now,0,$cdom,$cnum,$csec,$context,$credits);
 3745:                         if (($result =~ /^error/) || ($result eq 'not_in_class') || ($result eq 'unknown_course') || ($result eq 'refused')) {
 3746:                             if ($result eq 'refused' && $logmsg) {
 3747:                                 $output = $logmsg;
 3748:                             } else { 
 3749:                                 $output = &mt('Error: [_1]',$result)."\n";
 3750:                             }
 3751:                         } else {
 3752:                             $output = &Apache::lonhtmlcommon::confirm_success(&mt('Assigning [_1] in [_2] starting [_3]',
 3753:                                         &Apache::lonnet::plaintext($role),
 3754:                                         &Apache::loncommon::show_role_extent($url,$context,'st'),
 3755:                                         &Apache::lonlocal::locallocaltime($now))).'<br />'.$logmsg.'<br />';
 3756:                         }
 3757:                     }
 3758:                 } else {
 3759: 		    my $result=&Apache::lonnet::assignrole($env{'form.ccdomain'},
 3760:                                $env{'form.ccuname'},$url,$role,0,$now,'','',
 3761:                                $context);
 3762:                         $output = &Apache::lonhtmlcommon::confirm_success(&mt('Re-enabling [_1] in [_2]',
 3763:                                         &Apache::lonnet::plaintext($role),
 3764:                                         &Apache::loncommon::show_role_extent($url,$context,$role)),$result ne "ok").'<br />';
 3765:                     if ($result ne "ok") {
 3766:                         $output .= &mt('Error: [_1]',$result).'<br />';
 3767:                     }
 3768:                 }
 3769:                 $r->print($output);
 3770:                 if (!grep(/^\Q$role\E$/,@rolechanges)) {
 3771:                     push(@rolechanges,$role);
 3772:                 }
 3773: 	    }
 3774: # Re-enable custom role
 3775: 	    if ($key=~m{^form\.ren\:([^_]+)_cr\.cr/($match_domain)/($match_username)/(\w+)$}) {
 3776:                 my ($url,$rdom,$rnam,$rolename) = ($1,$2,$3,$4);
 3777:                 my $result = &Apache::lonnet::assigncustomrole(
 3778:                                $env{'form.ccdomain'}, $env{'form.ccuname'},
 3779:                                $url,$rdom,$rnam,$rolename,0,$now,undef,$context);
 3780:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
 3781:                     &mt('Re-enabling custom role [_1] by [_2] in [_3]',
 3782:                         $rolename,$rnam.':'.$rdom,&Apache::loncommon::show_role_extent($1,$context,'cr')),
 3783:                     $result ne "ok").'<br />');
 3784:                 if ($result ne "ok") {
 3785:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 3786:                 }
 3787:                 if (!grep(/^cr$/,@rolechanges)) {
 3788:                     push(@rolechanges,'cr');
 3789:                 }
 3790:             }
 3791: 	} elsif ($key=~/^form\.act/) {
 3792:             my $udom = $env{'form.ccdomain'};
 3793:             my $uname = $env{'form.ccuname'};
 3794: 	    if ($key=~/^form\.act\_($match_domain)\_($match_courseid)\_cr_cr_($match_domain)_($match_username)_([^\_]+)$/) {
 3795:                 # Activate a custom role
 3796: 		my ($one,$two,$three,$four,$five)=($1,$2,$3,$4,$5);
 3797: 		my $url='/'.$one.'/'.$two;
 3798: 		my $full=$one.'_'.$two.'_cr_cr_'.$three.'_'.$four.'_'.$five;
 3799: 
 3800:                 my $start = ( $env{'form.start_'.$full} ?
 3801:                               $env{'form.start_'.$full} :
 3802:                               $now );
 3803:                 my $end   = ( $env{'form.end_'.$full} ?
 3804:                               $env{'form.end_'.$full} :
 3805:                               0 );
 3806:                                                                                      
 3807:                 # split multiple sections
 3808:                 my %sections = ();
 3809:                 my $num_sections = &build_roles($env{'form.sec_'.$full},\%sections,$5);
 3810:                 if ($num_sections == 0) {
 3811:                     $r->print(&Apache::loncommon::commit_customrole($udom,$uname,$url,$three,$four,$five,$start,$end,$context));
 3812:                 } else {
 3813: 		    my %curr_groups =
 3814: 			&Apache::longroup::coursegroups($one,$two);
 3815:                     foreach my $sec (sort {$a cmp $b} keys(%sections)) {
 3816:                         if (($sec eq 'none') || ($sec eq 'all') || 
 3817:                             exists($curr_groups{$sec})) {
 3818:                             $disallowed{$sec} = $url;
 3819:                             next;
 3820:                         }
 3821:                         my $securl = $url.'/'.$sec;
 3822: 		        $r->print(&Apache::loncommon::commit_customrole($udom,$uname,$securl,$three,$four,$five,$start,$end,$context));
 3823:                     }
 3824:                 }
 3825:                 if (!grep(/^cr$/,@rolechanges)) {
 3826:                     push(@rolechanges,'cr');
 3827:                 }
 3828: 	    } elsif ($key=~/^form\.act\_($match_domain)\_($match_name)\_([^\_]+)$/) {
 3829: 		# Activate roles for sections with 3 id numbers
 3830: 		# set start, end times, and the url for the class
 3831: 		my ($one,$two,$three)=($1,$2,$3);
 3832: 		my $start = ( $env{'form.start_'.$one.'_'.$two.'_'.$three} ? 
 3833: 			      $env{'form.start_'.$one.'_'.$two.'_'.$three} : 
 3834: 			      $now );
 3835: 		my $end   = ( $env{'form.end_'.$one.'_'.$two.'_'.$three} ? 
 3836: 			      $env{'form.end_'.$one.'_'.$two.'_'.$three} :
 3837: 			      0 );
 3838: 		my $url='/'.$one.'/'.$two;
 3839:                 my $type = 'three';
 3840:                 # split multiple sections
 3841:                 my %sections = ();
 3842:                 my $num_sections = &build_roles($env{'form.sec_'.$one.'_'.$two.'_'.$three},\%sections,$three);
 3843:                 my $credits;
 3844:                 if ($three eq 'st') {
 3845:                     if ($showcredits) { 
 3846:                         my $defaultcredits = 
 3847:                             &Apache::lonuserutils::get_defaultcredits($one,$two);
 3848:                         $credits = $env{'form.credits_'.$one.'_'.$two.'_'.$three};
 3849:                         $credits =~ s/[^\d\.]//g;
 3850:                         if ($credits eq $defaultcredits) {
 3851:                             undef($credits);
 3852:                         }
 3853:                     }
 3854:                 }
 3855:                 if ($num_sections == 0) {
 3856:                     $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$three,$start,$end,$one,$two,'',$context,$credits));
 3857:                 } else {
 3858:                     my %curr_groups = 
 3859: 			&Apache::longroup::coursegroups($one,$two);
 3860:                     my $emptysec = 0;
 3861:                     foreach my $sec (sort {$a cmp $b} keys(%sections)) {
 3862:                         $sec =~ s/\W//g;
 3863:                         if ($sec ne '') {
 3864:                             if (($sec eq 'none') || ($sec eq 'all') || 
 3865:                                 exists($curr_groups{$sec})) {
 3866:                                 $disallowed{$sec} = $url;
 3867:                                 next;
 3868:                             }
 3869:                             my $securl = $url.'/'.$sec;
 3870:                             $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$securl,$three,$start,$end,$one,$two,$sec,$context,$credits));
 3871:                         } else {
 3872:                             $emptysec = 1;
 3873:                         }
 3874:                     }
 3875:                     if ($emptysec) {
 3876:                         $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$three,$start,$end,$one,$two,'',$context,$credits));
 3877:                     }
 3878:                 }
 3879:                 if (!grep(/^\Q$three\E$/,@rolechanges)) {
 3880:                     push(@rolechanges,$three);
 3881:                 }
 3882: 	    } elsif ($key=~/^form\.act\_([^\_]+)\_([^\_]+)$/) {
 3883: 		# Activate roles for sections with two id numbers
 3884: 		# set start, end times, and the url for the class
 3885: 		my $start = ( $env{'form.start_'.$1.'_'.$2} ? 
 3886: 			      $env{'form.start_'.$1.'_'.$2} : 
 3887: 			      $now );
 3888: 		my $end   = ( $env{'form.end_'.$1.'_'.$2} ? 
 3889: 			      $env{'form.end_'.$1.'_'.$2} :
 3890: 			      0 );
 3891:                 my $one = $1;
 3892:                 my $two = $2;
 3893: 		my $url='/'.$one.'/';
 3894:                 # split multiple sections
 3895:                 my %sections = ();
 3896:                 my $num_sections = &build_roles($env{'form.sec_'.$one.'_'.$two},\%sections,$two);
 3897:                 if ($num_sections == 0) {
 3898:                     $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$two,$start,$end,$one,undef,'',$context));
 3899:                 } else {
 3900:                     my $emptysec = 0;
 3901:                     foreach my $sec (sort {$a cmp $b} keys(%sections)) {
 3902:                         if ($sec ne '') {
 3903:                             my $securl = $url.'/'.$sec;
 3904:                             $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$securl,$two,$start,$end,$one,undef,$sec,$context));
 3905:                         } else {
 3906:                             $emptysec = 1;
 3907:                         }
 3908:                     }
 3909:                     if ($emptysec) {
 3910:                         $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$two,$start,$end,$one,undef,'',$context));
 3911:                     }
 3912:                 }
 3913:                 if (!grep(/^\Q$two\E$/,@rolechanges)) {
 3914:                     push(@rolechanges,$two);
 3915:                 }
 3916: 	    } else {
 3917: 		$r->print('<p><span class="LC_error">'.&mt('ERROR').': '.&mt('Unknown command').' <tt>'.$key.'</tt></span></p><br />');
 3918:             }
 3919:             foreach my $key (sort(keys(%disallowed))) {
 3920:                 $r->print('<p class="LC_warning">');
 3921:                 if (($key eq 'none') || ($key eq 'all')) {  
 3922:                     $r->print(&mt('[_1] may not be used as the name for a section, as it is a reserved word.','<tt>'.$key.'</tt>'));
 3923:                 } else {
 3924:                     $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>'));
 3925:                 }
 3926:                 $r->print('</p><p>'
 3927:                          .&mt('Please [_1]go back[_2] and choose a different section name.'
 3928:                              ,'<a href="javascript:history.go(-1)'
 3929:                              ,'</a>')
 3930:                          .'</p><br />'
 3931:                 );
 3932:             }
 3933: 	}
 3934:     } # End of foreach (keys(%env))
 3935: # Flush the course logs so reverse user roles immediately updated
 3936:     $r->register_cleanup(\&Apache::lonnet::flushcourselogs);
 3937:     if (@rolechanges == 0) {
 3938:         $r->print('<p>'.&mt('No roles to modify').'</p>');
 3939:     }
 3940:     return @rolechanges;
 3941: }
 3942: 
 3943: sub get_user_credits {
 3944:     my ($uname,$udom,$defaultcredits,$cdom,$cnum) = @_;
 3945:     if ($cdom eq '' || $cnum eq '') {
 3946:         return unless ($env{'request.course.id'});
 3947:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3948:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3949:     }
 3950:     my $credits;
 3951:     my %currhash =
 3952:         &Apache::lonnet::get('classlist',[$uname.':'.$udom],$cdom,$cnum);
 3953:     if (keys(%currhash) > 0) {
 3954:         my @items = split(/:/,$currhash{$uname.':'.$udom});
 3955:         my $crdidx = &Apache::loncoursedata::CL_CREDITS() - 3;
 3956:         $credits = $items[$crdidx];
 3957:         $credits =~ s/[^\d\.]//g;
 3958:     }
 3959:     if ($credits eq $defaultcredits) {
 3960:         undef($credits);
 3961:     }
 3962:     return $credits;
 3963: }
 3964: 
 3965: sub enroll_single_student {
 3966:     my ($r,$uhome,$amode,$genpwd,$now,$newuser,$context,$crstype,
 3967:         $showcredits,$defaultcredits) = @_;
 3968:     $r->print('<h3>');
 3969:     if ($crstype eq 'Community') {
 3970:         $r->print(&mt('Enrolling Member'));
 3971:     } else {
 3972:         $r->print(&mt('Enrolling Student'));
 3973:     }
 3974:     $r->print('</h3>');
 3975: 
 3976:     # Remove non alphanumeric values from section
 3977:     $env{'form.sections'}=~s/\W//g;
 3978: 
 3979:     my $credits;
 3980:     if (($showcredits) && ($env{'form.credits'} ne '')) {
 3981:         $credits = $env{'form.credits'};
 3982:         $credits =~ s/[^\d\.]//g;
 3983:         if ($credits ne '') {
 3984:             if ($credits eq $defaultcredits) {
 3985:                 undef($credits);
 3986:             }
 3987:         }
 3988:     }
 3989: 
 3990:     # Clean out any old student roles the user has in this class.
 3991:     &Apache::lonuserutils::modifystudent($env{'form.ccdomain'},
 3992:          $env{'form.ccuname'},$env{'request.course.id'},undef,$uhome);
 3993:     my ($startdate,$enddate) = &Apache::lonuserutils::get_dates_from_form();
 3994:     my $enroll_result =
 3995:         &Apache::lonnet::modify_student_enrollment($env{'form.ccdomain'},
 3996:             $env{'form.ccuname'},$env{'form.cid'},$env{'form.cfirstname'},
 3997:             $env{'form.cmiddlename'},$env{'form.clastname'},
 3998:             $env{'form.generation'},$env{'form.sections'},$enddate,
 3999:             $startdate,'manual',undef,$env{'request.course.id'},'',$context,
 4000:             $credits);
 4001:     if ($enroll_result =~ /^ok/) {
 4002:         $r->print(&mt('[_1] enrolled','<b>'.$env{'form.ccuname'}.':'.$env{'form.ccdomain'}.'</b>'));
 4003:         if ($env{'form.sections'} ne '') {
 4004:             $r->print(' '.&mt('in section [_1]',$env{'form.sections'}));
 4005:         }
 4006:         my ($showstart,$showend);
 4007:         if ($startdate <= $now) {
 4008:             $showstart = &mt('Access starts immediately');
 4009:         } else {
 4010:             $showstart = &mt('Access starts: ').&Apache::lonlocal::locallocaltime($startdate);
 4011:         }
 4012:         if ($enddate == 0) {
 4013:             $showend = &mt('ends: no ending date');
 4014:         } else {
 4015:             $showend = &mt('ends: ').&Apache::lonlocal::locallocaltime($enddate);
 4016:         }
 4017:         $r->print('.<br />'.$showstart.'; '.$showend);
 4018:         if ($startdate <= $now && !$newuser) {
 4019:             $r->print('<p class="LC_info">');
 4020:             if ($crstype eq 'Community') {
 4021:                 $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.'));
 4022:             } else {
 4023:                 $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.'));
 4024:            }
 4025:            $r->print('</p>');
 4026:         }
 4027:     } else {
 4028:         $r->print(&mt('unable to enroll').": ".$enroll_result);
 4029:     }
 4030:     return;
 4031: }
 4032: 
 4033: sub get_defaultquota_text {
 4034:     my ($settingstatus) = @_;
 4035:     my $defquotatext; 
 4036:     if ($settingstatus eq '') {
 4037:         $defquotatext = &mt('default');
 4038:     } else {
 4039:         my ($usertypes,$order) =
 4040:             &Apache::lonnet::retrieve_inst_usertypes($env{'form.ccdomain'});
 4041:         if ($usertypes->{$settingstatus} eq '') {
 4042:             $defquotatext = &mt('default');
 4043:         } else {
 4044:             $defquotatext = &mt('default for [_1]',$usertypes->{$settingstatus});
 4045:         }
 4046:     }
 4047:     return $defquotatext;
 4048: }
 4049: 
 4050: sub update_result_form {
 4051:     my ($uhome) = @_;
 4052:     my $outcome = 
 4053:     '<form name="userupdate" method="post" action="">'."\n";
 4054:     foreach my $item ('srchby','srchin','srchtype','srchterm','srchdomain','ccuname','ccdomain') {
 4055:         $outcome .= '<input type="hidden" name="'.$item.'" value="'.$env{'form.'.$item}.'" />'."\n";
 4056:     }
 4057:     if ($env{'form.origname'} ne '') {
 4058:         $outcome .= '<input type="hidden" name="origname" value="'.$env{'form.origname'}.'" />'."\n";
 4059:     }
 4060:     foreach my $item ('sortby','seluname','seludom') {
 4061:         if (exists($env{'form.'.$item})) {
 4062:             $outcome .= '<input type="hidden" name="'.$item.'" value="'.$env{'form.'.$item}.'" />'."\n";
 4063:         }
 4064:     }
 4065:     if ($uhome eq 'no_host') {
 4066:         $outcome .= '<input type="hidden" name="forcenewuser" value="1" />'."\n";
 4067:     }
 4068:     $outcome .= '<input type="hidden" name="phase" value="" />'."\n".
 4069:                 '<input type="hidden" name="currstate" value="" />'."\n".
 4070:                 '<input type="hidden" name="action" value="'.$env{'form.action'}.'" />'."\n".
 4071:                 '</form>';
 4072:     return $outcome;
 4073: }
 4074: 
 4075: sub quota_admin {
 4076:     my ($setquota,$changeHash,$name) = @_;
 4077:     my $quotachanged;
 4078:     if (&Apache::lonnet::allowed('mpq',$env{'form.ccdomain'})) {
 4079:         # Current user has quota modification privileges
 4080:         if (ref($changeHash) eq 'HASH') {
 4081:             $quotachanged = 1;
 4082:             $changeHash->{$name.'quota'} = $setquota;
 4083:         }
 4084:     }
 4085:     return $quotachanged;
 4086: }
 4087: 
 4088: sub tool_admin {
 4089:     my ($tool,$settool,$changeHash,$context) = @_;
 4090:     my $canchange = 0; 
 4091:     if ($context eq 'requestcourses') {
 4092:         if (&Apache::lonnet::allowed('ccc',$env{'form.ccdomain'})) {
 4093:             $canchange = 1;
 4094:         }
 4095:     } elsif ($context eq 'reqcrsotherdom') {
 4096:         if (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) {
 4097:             $canchange = 1;
 4098:         }
 4099:     } elsif ($context eq 'requestauthor') {
 4100:         if (&Apache::lonnet::allowed('cau',$env{'request.role.domain'})) {
 4101:             $canchange = 1;
 4102:         }
 4103:     } elsif (&Apache::lonnet::allowed('mut',$env{'form.ccdomain'})) {
 4104:         # Current user has quota modification privileges
 4105:         $canchange = 1;
 4106:     }
 4107:     my $toolchanged;
 4108:     if ($canchange) {
 4109:         if (ref($changeHash) eq 'HASH') {
 4110:             $toolchanged = 1;
 4111:             if ($tool eq 'requestauthor') {
 4112:                 $changeHash->{$context} = $settool;
 4113:             } else {
 4114:                 $changeHash->{$context.'.'.$tool} = $settool;
 4115:             }
 4116:         }
 4117:     }
 4118:     return $toolchanged;
 4119: }
 4120: 
 4121: sub build_roles {
 4122:     my ($sectionstr,$sections,$role) = @_;
 4123:     my $num_sections = 0;
 4124:     if ($sectionstr=~ /,/) {
 4125:         my @secnums = split/,/,$sectionstr;
 4126:         if ($role eq 'st') {
 4127:             $secnums[0] =~ s/\W//g;
 4128:             $$sections{$secnums[0]} = 1;
 4129:             $num_sections = 1;
 4130:         } else {
 4131:             foreach my $sec (@secnums) {
 4132:                 $sec =~ ~s/\W//g;
 4133:                 if (!($sec eq "")) {
 4134:                     if (exists($$sections{$sec})) {
 4135:                         $$sections{$sec} ++;
 4136:                     } else {
 4137:                         $$sections{$sec} = 1;
 4138:                         $num_sections ++;
 4139:                     }
 4140:                 }
 4141:             }
 4142:         }
 4143:     } else {
 4144:         $sectionstr=~s/\W//g;
 4145:         unless ($sectionstr eq '') {
 4146:             $$sections{$sectionstr} = 1;
 4147:             $num_sections ++;
 4148:         }
 4149:     }
 4150: 
 4151:     return $num_sections;
 4152: }
 4153: 
 4154: # ========================================================== Custom Role Editor
 4155: 
 4156: sub custom_role_editor {
 4157:     my ($r,$brcrum) = @_;
 4158:     my $action = $env{'form.customroleaction'};
 4159:     my $rolename; 
 4160:     if ($action eq 'new') {
 4161:         $rolename=$env{'form.newrolename'};
 4162:     } else {
 4163:         $rolename=$env{'form.rolename'};
 4164:     }
 4165: 
 4166:     my ($crstype,$context);
 4167:     if ($env{'request.course.id'}) {
 4168:         $crstype = &Apache::loncommon::course_type();
 4169:         $context = 'course';
 4170:     } else {
 4171:         $context = 'domain';
 4172:         $crstype = $env{'form.templatecrstype'};
 4173:     }
 4174: 
 4175:     $rolename=~s/[^A-Za-z0-9]//gs;
 4176:     if (!$rolename || $env{'form.phase'} eq 'pickrole') {
 4177: 	&print_username_entry_form($r,undef,undef,undef,undef,$crstype,$brcrum);
 4178:         return;
 4179:     }
 4180: 
 4181: # ------------------------------------------------------- What can be assigned?
 4182:     my %full=();
 4183:     my %courselevel=();
 4184:     my %courselevelcurrent=();
 4185:     my $syspriv='';
 4186:     my $dompriv='';
 4187:     my $coursepriv='';
 4188:     my $body_top;
 4189:     my $newrole;
 4190:     my ($rdummy,$roledef)=
 4191: 			 &Apache::lonnet::get('roles',["rolesdef_$rolename"]);
 4192: # ------------------------------------------------------- Does this role exist?
 4193:     $body_top .= '<h2>';
 4194:     if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 4195: 	$body_top .= &mt('Existing Role').' "';
 4196: # ------------------------------------------------- Get current role privileges
 4197: 	($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 4198:         if ($crstype eq 'Community') {
 4199:             $syspriv =~ s/bre\&S//;   
 4200:         }
 4201:     } else {
 4202:         $newrole = 1;
 4203: 	$body_top .= &mt('New Role').' "';
 4204: 	$roledef='';
 4205:     }
 4206:     $body_top .= $rolename.'"</h2>';
 4207:     foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
 4208: 	my ($priv,$restrict)=split(/\&/,$item);
 4209:         if (!$restrict) { $restrict='F'; }
 4210:         $courselevel{$priv}=$restrict;
 4211:         if ($coursepriv=~/\:$priv/) {
 4212: 	    $courselevelcurrent{$priv}=1;
 4213: 	}
 4214: 	$full{$priv}=1;
 4215:     }
 4216:     my %domainlevel=();
 4217:     my %domainlevelcurrent=();
 4218:     foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:d'})) {
 4219: 	my ($priv,$restrict)=split(/\&/,$item);
 4220:         if (!$restrict) { $restrict='F'; }
 4221:         $domainlevel{$priv}=$restrict;
 4222:         if ($dompriv=~/\:$priv/) {
 4223: 	    $domainlevelcurrent{$priv}=1;
 4224: 	}
 4225: 	$full{$priv}=1;
 4226:     }
 4227:     my %systemlevel=();
 4228:     my %systemlevelcurrent=();
 4229:     foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:s'})) {
 4230: 	my ($priv,$restrict)=split(/\&/,$item);
 4231:         if (!$restrict) { $restrict='F'; }
 4232:         $systemlevel{$priv}=$restrict;
 4233:         if ($syspriv=~/\:$priv/) {
 4234: 	    $systemlevelcurrent{$priv}=1;
 4235: 	}
 4236: 	$full{$priv}=1;
 4237:     }
 4238:     my ($jsback,$elements) = &crumb_utilities();
 4239:     my $button_code = "\n";
 4240:     my $head_script = "\n";
 4241:     $head_script .= '<script type="text/javascript">'."\n"
 4242:                    .'// <![CDATA['."\n";
 4243:     my @template_roles = ("in","ta","ep");
 4244:     if ($context eq 'domain') {
 4245:         push(@template_roles,"ad");
 4246:     }
 4247:     push(@template_roles,"st");
 4248:     if ($crstype eq 'Community') {
 4249:         unshift(@template_roles,'co');
 4250:     } else {
 4251:         unshift(@template_roles,'cc');
 4252:     }
 4253:     foreach my $role (@template_roles) {
 4254:         $head_script .= &make_script_template($role,$crstype);
 4255:         $button_code .= &make_button_code($role,$crstype).' ';
 4256:     }
 4257:     my $context_code;
 4258:     if ($context eq 'domain') {
 4259:         my $checkedCommunity = '';
 4260:         my $checkedCourse = ' checked="checked"';
 4261:         if ($env{'form.templatecrstype'} eq 'Community') {
 4262:             $checkedCommunity = $checkedCourse;
 4263:             $checkedCourse = '';
 4264:         }
 4265:         $context_code = '<label>'.
 4266:                         '<input type="radio" name="templatecrstype" value="Course"'.$checkedCourse.' onclick="this.form.submit();">'.
 4267:                         &mt('Course').
 4268:                         '</label>'.('&nbsp;' x2).
 4269:                         '<label>'.
 4270:                         '<input type="radio" name="templatecrstype" value="Community"'.$checkedCommunity.' onclick="this.form.submit();">'.
 4271:                         &mt('Community').
 4272:                         '</label>'.
 4273:                         '</fieldset>'.
 4274:                         '<input type="hidden" name="customroleaction" value="'.
 4275:                         $action.'" />';
 4276:         if ($env{'form.customroleaction'} eq 'new') {
 4277:             $context_code .= '<input type="hidden" name="newrolename" value="'.
 4278:                              $rolename.'" />';
 4279:         } else {
 4280:             $context_code .= '<input type="hidden" name="rolename" value="'.
 4281:                              $rolename.'" />';
 4282:         }
 4283:         $context_code .= '<input type="hidden" name="action" value="custom" />'.
 4284:                          '<input type="hidden" name="phase" value="selected_custom_edit" />';
 4285:     }
 4286: 
 4287:     $head_script .= "\n".$jsback."\n"
 4288:                    .'// ]]>'."\n"
 4289:                    .'</script>'."\n";
 4290:     push (@{$brcrum},
 4291:               {href => "javascript:backPage(document.form1,'pickrole','')",
 4292:                text => "Pick custom role",
 4293:                faq  => 282,bug=>'Instructor Interface',},
 4294:               {href => "javascript:backPage(document.form1,'','')",
 4295:                text => "Edit custom role",
 4296:                faq  => 282,
 4297:                bug  => 'Instructor Interface',
 4298:                help => 'Course_Editing_Custom_Roles'}
 4299:               );
 4300:     my $args = { bread_crumbs          => $brcrum,
 4301:                  bread_crumbs_component => 'User Management'};
 4302:  
 4303:     $r->print(&Apache::loncommon::start_page('Custom Role Editor',
 4304:                                              $head_script,$args).
 4305:               $body_top);
 4306:     my %lt=&Apache::lonlocal::texthash(
 4307: 		    'prv'  => "Privilege",
 4308: 		    'crl'  => "Course Level",
 4309:                     'dml'  => "Domain Level",
 4310:                     'ssl'  => "System Level");
 4311: 
 4312:     $r->print('<div class="LC_left_float">'
 4313:              .'<form action=""><fieldset>'
 4314:              .'<legend>'.&mt('Select a Template').'</legend>'
 4315:              .$button_code
 4316:              .'</fieldset></form></div>');
 4317:     if ($context_code) {
 4318:         $r->print('<div class="LC_left_float">'
 4319:                  .'<form action="/adm/createuser" method="post"><fieldset>'
 4320:                  .'<legend>'.&mt('Context').'</legend>'
 4321:                  .$context_code
 4322:                  .'</form>'
 4323:                  .'</div>'
 4324:         );
 4325:     }
 4326:     $r->print('<br clear="all" />');
 4327: 
 4328:     $r->print(<<ENDCCF);
 4329: <form name="form1" method="post" action="">
 4330: <input type="hidden" name="phase" value="set_custom_roles" />
 4331: <input type="hidden" name="rolename" value="$rolename" />
 4332: ENDCCF
 4333:     $r->print(&Apache::loncommon::start_data_table().
 4334:               &Apache::loncommon::start_data_table_header_row(). 
 4335: '<th>'.$lt{'prv'}.'</th><th>'.$lt{'crl'}.'</th><th>'.$lt{'dml'}.
 4336: '</th><th>'.$lt{'ssl'}.'</th>'.
 4337:               &Apache::loncommon::end_data_table_header_row());
 4338:     foreach my $priv (sort(keys(%full))) {
 4339:         my $privtext = &Apache::lonnet::plaintext($priv,$crstype);
 4340:         $r->print(&Apache::loncommon::start_data_table_row().
 4341: 	          '<td>'.$privtext.'</td><td>'.
 4342:     ($courselevel{$priv}?'<input type="checkbox" name="'.$priv.'_c"'.
 4343:     ($courselevelcurrent{$priv}?' checked="checked"':'').' />':'&nbsp;').
 4344:     '</td><td>'.
 4345:     ($domainlevel{$priv}?'<input type="checkbox" name="'.$priv.'_d"'.
 4346:     ($domainlevelcurrent{$priv}?' checked="checked"':'').' />':'&nbsp;').
 4347:     '</td><td>');
 4348:         if ($priv eq 'bre' && $crstype eq 'Community') {
 4349:             $r->print('&nbsp;');  
 4350:         } else {
 4351:             $r->print($systemlevel{$priv}?'<input type="checkbox" name="'.$priv.'_s"'.
 4352:                       ($systemlevelcurrent{$priv}?' checked="checked"':'').' />':'&nbsp;');
 4353:         }
 4354:         $r->print('</td>'.
 4355:                   &Apache::loncommon::end_data_table_row());
 4356:     }
 4357:     $r->print(&Apache::loncommon::end_data_table().
 4358:    '<input type="hidden" name="action" value="'.$env{'form.action'}.'" />'.
 4359:    '<input type="hidden" name="startrolename" value="'.$env{'form.rolename'}.
 4360:    '" />'."\n".'<input type="hidden" name="currstate" value="" />'."\n".   
 4361:    '<input type="reset" value="'.&mt("Reset").'" />'."\n".
 4362:    '<input type="submit" value="'.&mt('Save').'" /></form>');
 4363: }
 4364: # --------------------------------------------------------
 4365: sub make_script_template {
 4366:     my ($role,$crstype) = @_;
 4367:     my %full_c=();
 4368:     my %full_d=();
 4369:     my %full_s=();
 4370:     my $return_script;
 4371:     foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
 4372:         my ($priv,$restrict)=split(/\&/,$item);
 4373:         $full_c{$priv}=1;
 4374:     }
 4375:     foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:d'})) {
 4376:         my ($priv,$restrict)=split(/\&/,$item);
 4377:         $full_d{$priv}=1;
 4378:     }
 4379:     foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:s'})) {
 4380:         next if (($crstype eq 'Community') && ($item eq 'bre&S'));
 4381:         my ($priv,$restrict)=split(/\&/,$item);
 4382:         $full_s{$priv}=1;
 4383:     }
 4384:     $return_script .= 'function set_'.$role.'() {'."\n";
 4385:     my @temp = split(/:/,$Apache::lonnet::pr{$role.':c'});
 4386:     my %role_c;
 4387:     foreach my $priv (@temp) {
 4388:         my ($priv_item, $dummy) = split(/\&/,$priv);
 4389:         $role_c{$priv_item} = 1;
 4390:     }
 4391:     my %role_d;
 4392:     @temp = split(/:/,$Apache::lonnet::pr{$role.':d'});
 4393:     foreach my $priv(@temp) {
 4394:         my ($priv_item, $dummy) = split(/\&/,$priv);
 4395:         $role_d{$priv_item} = 1;
 4396:     }
 4397:     my %role_s;
 4398:     @temp = split(/:/,$Apache::lonnet::pr{$role.':s'});
 4399:     foreach my $priv(@temp) {
 4400:         my ($priv_item, $dummy) = split(/\&/,$priv);
 4401:         $role_s{$priv_item} = 1;
 4402:     }
 4403:     foreach my $priv_item (keys(%full_c)) {
 4404:         my ($priv, $dummy) = split(/\&/,$priv_item);
 4405:         if ((exists($role_c{$priv})) || (exists($role_d{$priv})) || 
 4406:             (exists($role_s{$priv}))) {
 4407:             $return_script .= "document.form1.$priv"."_c.checked = true;\n";
 4408:         } else {
 4409:             $return_script .= "document.form1.$priv"."_c.checked = false;\n";
 4410:         }
 4411:     }
 4412:     foreach my $priv_item (keys(%full_d)) {
 4413:         my ($priv, $dummy) = split(/\&/,$priv_item);
 4414:         if ((exists($role_d{$priv})) || (exists($role_s{$priv}))) {
 4415:             $return_script .= "document.form1.$priv"."_d.checked = true;\n";
 4416:         } else {
 4417:             $return_script .= "document.form1.$priv"."_d.checked = false;\n";
 4418:         }
 4419:     }
 4420:     foreach my $priv_item (keys(%full_s)) {
 4421:         my ($priv, $dummy) = split(/\&/,$priv_item);
 4422:         if (exists($role_s{$priv})) {
 4423:             $return_script .= "document.form1.$priv"."_s.checked = true;\n";
 4424:         } else {
 4425:             $return_script .= "document.form1.$priv"."_s.checked = false;\n";
 4426:         }
 4427:     }
 4428:     $return_script .= '}'."\n";
 4429:     return ($return_script);
 4430: }
 4431: # ----------------------------------------------------------
 4432: sub make_button_code {
 4433:     my ($role,$crstype) = @_;
 4434:     my $label = &Apache::lonnet::plaintext($role,$crstype);
 4435:     my $button_code = '<input type="button" onclick="set_'.$role.'()" value="'.$label.'" />';
 4436:     return ($button_code);
 4437: }
 4438: # ---------------------------------------------------------- Call to definerole
 4439: sub set_custom_role {
 4440:     my ($r,$context,$brcrum) = @_;
 4441:     my $rolename=$env{'form.rolename'};
 4442:     $rolename=~s/[^A-Za-z0-9]//gs;
 4443:     if (!$rolename) {
 4444: 	&custom_role_editor($r,$brcrum);
 4445:         return;
 4446:     }
 4447:     my ($jsback,$elements) = &crumb_utilities();
 4448:     my $jscript = '<script type="text/javascript">'
 4449:                  .'// <![CDATA['."\n"
 4450:                  .$jsback."\n"
 4451:                  .'// ]]>'."\n"
 4452:                  .'</script>'."\n";
 4453:     push(@{$brcrum},
 4454:         {href => "javascript:backPage(document.customresult,'pickrole','')",
 4455:          text => "Pick custom role",
 4456:          faq  => 282,
 4457:          bug  => 'Instructor Interface',},
 4458:         {href => "javascript:backPage(document.customresult,'selected_custom_edit','')",
 4459:          text => "Edit custom role",
 4460:          faq  => 282,
 4461:          bug  => 'Instructor Interface',},
 4462:         {href => "javascript:backPage(document.customresult,'set_custom_roles','')",
 4463:          text => "Result",
 4464:          faq  => 282,
 4465:          bug  => 'Instructor Interface',
 4466:          help => 'Course_Editing_Custom_Roles'},
 4467:         );
 4468:     my $args = { bread_crumbs           => $brcrum,
 4469:                  bread_crumbs_component => 'User Management'}; 
 4470:     $r->print(&Apache::loncommon::start_page('Save Custom Role',$jscript,$args));
 4471: 
 4472:     my $newrole;
 4473:     my ($rdummy,$roledef)=
 4474: 	&Apache::lonnet::get('roles',["rolesdef_$rolename"]);
 4475: 
 4476: # ------------------------------------------------------- Does this role exist?
 4477:     $r->print('<h3>');
 4478:     if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 4479: 	$r->print(&mt('Existing Role').' "');
 4480:     } else {
 4481: 	$r->print(&mt('New Role').' "');
 4482: 	$roledef='';
 4483:         $newrole = 1;
 4484:     }
 4485:     $r->print($rolename.'"</h3>');
 4486: # ------------------------------------------------------- What can be assigned?
 4487:     my $sysrole='';
 4488:     my $domrole='';
 4489:     my $courole='';
 4490: 
 4491:     foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
 4492: 	my ($priv,$restrict)=split(/\&/,$item);
 4493:         if (!$restrict) { $restrict=''; }
 4494:         if ($env{'form.'.$priv.'_c'}) {
 4495: 	    $courole.=':'.$item;
 4496: 	}
 4497:     }
 4498: 
 4499:     foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:d'})) {
 4500: 	my ($priv,$restrict)=split(/\&/,$item);
 4501:         if (!$restrict) { $restrict=''; }
 4502:         if ($env{'form.'.$priv.'_d'}) {
 4503: 	    $domrole.=':'.$item;
 4504: 	}
 4505:     }
 4506: 
 4507:     foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:s'})) {
 4508: 	my ($priv,$restrict)=split(/\&/,$item);
 4509:         if (!$restrict) { $restrict=''; }
 4510:         if ($env{'form.'.$priv.'_s'}) {
 4511: 	    $sysrole.=':'.$item;
 4512: 	}
 4513:     }
 4514:     # Assign role; Compile and show result
 4515:     my $errmsg;
 4516:     my $result =
 4517:         &Apache::lonnet::definerole($rolename,$sysrole,$domrole,$courole);
 4518:     if ($result ne 'ok') {
 4519:         $errmsg = ': '.$result;
 4520:     }
 4521:     my $message =
 4522:         &Apache::lonhtmlcommon::confirm_success(
 4523:             &mt('Defining Role').$errmsg, ($result eq 'ok' ? 0 : 1));
 4524:     if ($env{'request.course.id'}) {
 4525:         my $url='/'.$env{'request.course.id'};
 4526:         $url=~s/\_/\//g;
 4527:         $result =
 4528:             &Apache::lonnet::assigncustomrole(
 4529:                 $env{'user.domain'},$env{'user.name'},
 4530:                 $url,
 4531:                 $env{'user.domain'},$env{'user.name'},
 4532:                 $rolename,undef,undef,undef,$context);
 4533:         if ($result ne 'ok') {
 4534:             $errmsg = ': '.$result;
 4535:         }
 4536:         $message .=
 4537:             '<br />'
 4538:            .&Apache::lonhtmlcommon::confirm_success(
 4539:                 &mt('Assigning Role to Self').$errmsg, ($result eq 'ok' ? 0 : 1));
 4540:     }
 4541:     $r->print(
 4542:         &Apache::loncommon::confirmwrapper($message)
 4543:        .'<br />'
 4544:        .&Apache::lonhtmlcommon::actionbox([
 4545:             '<a href="javascript:backPage(document.customresult,'."'pickrole'".')">'
 4546:            .&mt('Create or edit another custom role')
 4547:            .'</a>'])
 4548:        .'<form name="customresult" method="post" action="">'
 4549:        .&Apache::lonhtmlcommon::echo_form_input([])
 4550:        .'</form>'
 4551:     );
 4552: }
 4553: 
 4554: # ================================================================ Main Handler
 4555: sub handler {
 4556:     my $r = shift;
 4557:     if ($r->header_only) {
 4558:        &Apache::loncommon::content_type($r,'text/html');
 4559:        $r->send_http_header;
 4560:        return OK;
 4561:     }
 4562:     my ($context,$crstype);
 4563:     if ($env{'request.course.id'}) {
 4564:         $context = 'course';
 4565:         $crstype = &Apache::loncommon::course_type();
 4566:     } elsif ($env{'request.role'} =~ /^au\./) {
 4567:         $context = 'author';
 4568:     } else {
 4569:         $context = 'domain';
 4570:     }
 4571: 
 4572:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 4573:         ['action','state','callingform','roletype','showrole','bulkaction','popup','phase',
 4574:          'username','domain','srchterm','srchdomain','srchin','srchby','srchtype','queue']);
 4575:     &Apache::lonhtmlcommon::clear_breadcrumbs();
 4576:     my $args;
 4577:     my $brcrum = [];
 4578:     my $bread_crumbs_component = 'User Management';
 4579:     if (($env{'form.action'} ne 'dateselect') && ($env{'form.action'} ne 'displayuserreq')) {
 4580:         $brcrum = [{href=>"/adm/createuser",
 4581:                     text=>"User Management",
 4582:                     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'}
 4583:                   ];
 4584:     }
 4585:     #SD Following files not added to help, because the corresponding .tex-files seem to
 4586:     #be missing: Course_Approve_Selfenroll,Course_User_Logs,
 4587:     my ($permission,$allowed) = 
 4588:         &Apache::lonuserutils::get_permission($context,$crstype);
 4589:     if (!$allowed) {
 4590:         if ($context eq 'course') {
 4591:             $r->internal_redirect('/adm/viewclasslist');
 4592:             return OK;
 4593:         }
 4594:         $env{'user.error.msg'}=
 4595:             "/adm/createuser:cst:0:0:Cannot create/modify user data ".
 4596:                                  "or view user status.";
 4597:         return HTTP_NOT_ACCEPTABLE;
 4598:     }
 4599: 
 4600:     &Apache::loncommon::content_type($r,'text/html');
 4601:     $r->send_http_header;
 4602: 
 4603:     my $showcredits;
 4604:     if ((($context eq 'course') && ($crstype eq 'Course')) || 
 4605:          ($context eq 'domain')) {
 4606:         my %domdefaults = 
 4607:             &Apache::lonnet::get_domain_defaults($env{'request.role.domain'});
 4608:         if ($domdefaults{'officialcredits'} || $domdefaults{'unofficialcredits'}) {
 4609:             $showcredits = 1;
 4610:         }
 4611:     }
 4612: 
 4613:     # Main switch on form.action and form.state, as appropriate
 4614:     if (! exists($env{'form.action'})) {
 4615:         $args = {bread_crumbs => $brcrum,
 4616:                  bread_crumbs_component => $bread_crumbs_component}; 
 4617:         $r->print(&header(undef,$args));
 4618:         $r->print(&print_main_menu($permission,$context,$crstype));
 4619:     } elsif ($env{'form.action'} eq 'upload' && $permission->{'cusr'}) {
 4620:         push(@{$brcrum},
 4621:               { href => '/adm/createuser?action=upload&state=',
 4622:                 text => 'Upload Users List',
 4623:                 help => 'Course_Create_Class_List',
 4624:               });
 4625:         $bread_crumbs_component = 'Upload Users List';
 4626:         $args = {bread_crumbs           => $brcrum,
 4627:                  bread_crumbs_component => $bread_crumbs_component};
 4628:         $r->print(&header(undef,$args));
 4629:         $r->print('<form name="studentform" method="post" '.
 4630:                   'enctype="multipart/form-data" '.
 4631:                   ' action="/adm/createuser">'."\n");
 4632:         if (! exists($env{'form.state'})) {
 4633:             &Apache::lonuserutils::print_first_users_upload_form($r,$context);
 4634:         } elsif ($env{'form.state'} eq 'got_file') {
 4635:             &Apache::lonuserutils::print_upload_manager_form($r,$context,$permission,
 4636:                                                              $crstype,$showcredits);
 4637:         } elsif ($env{'form.state'} eq 'enrolling') {
 4638:             if ($env{'form.datatoken'}) {
 4639:                 &Apache::lonuserutils::upfile_drop_add($r,$context,$permission,
 4640:                                                        $showcredits);
 4641:             }
 4642:         } else {
 4643:             &Apache::lonuserutils::print_first_users_upload_form($r,$context);
 4644:         }
 4645:     } elsif ((($env{'form.action'} eq 'singleuser') || ($env{'form.action'}
 4646:              eq 'singlestudent')) && ($permission->{'cusr'})) {
 4647:         my $phase = $env{'form.phase'};
 4648:         my @search = ('srchterm','srchby','srchin','srchtype','srchdomain');
 4649: 	&Apache::loncreateuser::restore_prev_selections();
 4650: 	my $srch;
 4651: 	foreach my $item (@search) {
 4652: 	    $srch->{$item} = $env{'form.'.$item};
 4653: 	}
 4654:         if (($phase eq 'get_user_info') || ($phase eq 'userpicked') ||
 4655:             ($phase eq 'createnewuser')) {
 4656:             if ($env{'form.phase'} eq 'createnewuser') {
 4657:                 my $response;
 4658:                 if ($env{'form.srchterm'} !~ /^$match_username$/) {
 4659:                     my $response =
 4660:                         '<span class="LC_warning">'
 4661:                        .&mt('You must specify a valid username. Only the following are allowed:'
 4662:                            .' letters numbers - . @')
 4663:                        .'</span>';
 4664:                     $env{'form.phase'} = '';
 4665:                     &print_username_entry_form($r,$context,$response,$srch,undef,
 4666:                                                $crstype,$brcrum,$showcredits);
 4667:                 } else {
 4668:                     my $ccuname =&LONCAPA::clean_username($srch->{'srchterm'});
 4669:                     my $ccdomain=&LONCAPA::clean_domain($srch->{'srchdomain'});
 4670:                     &print_user_modification_page($r,$ccuname,$ccdomain,
 4671:                                                   $srch,$response,$context,
 4672:                                                   $permission,$crstype,$brcrum,
 4673:                                                   $showcredits);
 4674:                 }
 4675:             } elsif ($env{'form.phase'} eq 'get_user_info') {
 4676:                 my ($currstate,$response,$forcenewuser,$results) = 
 4677:                     &user_search_result($context,$srch);
 4678:                 if ($env{'form.currstate'} eq 'modify') {
 4679:                     $currstate = $env{'form.currstate'};
 4680:                 }
 4681:                 if ($currstate eq 'select') {
 4682:                     &print_user_selection_page($r,$response,$srch,$results,
 4683:                                                \@search,$context,undef,$crstype,
 4684:                                                $brcrum);
 4685:                 } elsif ($currstate eq 'modify') {
 4686:                     my ($ccuname,$ccdomain);
 4687:                     if (($srch->{'srchby'} eq 'uname') && 
 4688:                         ($srch->{'srchtype'} eq 'exact')) {
 4689:                         $ccuname = $srch->{'srchterm'};
 4690:                         $ccdomain= $srch->{'srchdomain'};
 4691:                     } else {
 4692:                         my @matchedunames = keys(%{$results});
 4693:                         ($ccuname,$ccdomain) = split(/:/,$matchedunames[0]);
 4694:                     }
 4695:                     $ccuname =&LONCAPA::clean_username($ccuname);
 4696:                     $ccdomain=&LONCAPA::clean_domain($ccdomain);
 4697:                     if ($env{'form.forcenewuser'}) {
 4698:                         $response = '';
 4699:                     }
 4700:                     &print_user_modification_page($r,$ccuname,$ccdomain,
 4701:                                                   $srch,$response,$context,
 4702:                                                   $permission,$crstype,$brcrum);
 4703:                 } elsif ($currstate eq 'query') {
 4704:                     &print_user_query_page($r,'createuser',$brcrum);
 4705:                 } else {
 4706:                     $env{'form.phase'} = '';
 4707:                     &print_username_entry_form($r,$context,$response,$srch,
 4708:                                                $forcenewuser,$crstype,$brcrum);
 4709:                 }
 4710:             } elsif ($env{'form.phase'} eq 'userpicked') {
 4711:                 my $ccuname = &LONCAPA::clean_username($env{'form.seluname'});
 4712:                 my $ccdomain = &LONCAPA::clean_domain($env{'form.seludom'});
 4713:                 &print_user_modification_page($r,$ccuname,$ccdomain,$srch,'',
 4714:                                               $context,$permission,$crstype,
 4715:                                               $brcrum);
 4716:             }
 4717:         } elsif ($env{'form.phase'} eq 'update_user_data') {
 4718:             &update_user_data($r,$context,$crstype,$brcrum,$showcredits);
 4719:         } else {
 4720:             &print_username_entry_form($r,$context,undef,$srch,undef,$crstype,
 4721:                                        $brcrum);
 4722:         }
 4723:     } elsif ($env{'form.action'} eq 'custom' && $permission->{'custom'}) {
 4724:         if ($env{'form.phase'} eq 'set_custom_roles') {
 4725:             &set_custom_role($r,$context,$brcrum);
 4726:         } else {
 4727:             &custom_role_editor($r,$brcrum);
 4728:         }
 4729:     } elsif (($env{'form.action'} eq 'processauthorreq') &&
 4730:              ($permission->{'cusr'}) && 
 4731:              (&Apache::lonnet::allowed('cau',$env{'request.role.domain'}))) {
 4732:         push(@{$brcrum},
 4733:                  {href => '/adm/createuser?action=processauthorreq',
 4734:                   text => 'Authoring Space requests',
 4735:                   help => 'Domain_Role_Approvals'});
 4736:         $bread_crumbs_component = 'Authoring requests';
 4737:         if ($env{'form.state'} eq 'done') {
 4738:             push(@{$brcrum},
 4739:                      {href => '/adm/createuser?action=authorreqqueue',
 4740:                       text => 'Result',
 4741:                       help => 'Domain_Role_Approvals'});
 4742:             $bread_crumbs_component = 'Authoring request result';
 4743:         }
 4744:         $args = { bread_crumbs           => $brcrum,
 4745:                   bread_crumbs_component => $bread_crumbs_component};
 4746:         my $js = &usernamerequest_javascript();
 4747:         $r->print(&header(&add_script($js),$args));
 4748:         if (!exists($env{'form.state'})) {
 4749:             $r->print(&Apache::loncoursequeueadmin::display_queued_requests('requestauthor',
 4750:                                                                             $env{'request.role.domain'}));
 4751:         } elsif ($env{'form.state'} eq 'done') {
 4752:             $r->print('<h3>'.&mt('Authoring request processing').'</h3>'."\n");
 4753:             $r->print(&Apache::loncoursequeueadmin::update_request_queue('requestauthor',
 4754:                                                                          $env{'request.role.domain'}));
 4755:         }
 4756:     } elsif (($env{'form.action'} eq 'processusernamereq') &&
 4757:              ($permission->{'cusr'}) &&
 4758:              (&Apache::lonnet::allowed('cau',$env{'request.role.domain'}))) {
 4759:         push(@{$brcrum},
 4760:                  {href => '/adm/createuser?action=processusernamereq',
 4761:                   text => 'LON-CAPA account requests',
 4762:                   help => 'Domain_Username_Approvals'});
 4763:         $bread_crumbs_component = 'Account requests';
 4764:         if ($env{'form.state'} eq 'done') {
 4765:             push(@{$brcrum},
 4766:                      {href => '/adm/createuser?action=usernamereqqueue',
 4767:                       text => 'Result',
 4768:                       help => 'Domain_Username_Approvals'});
 4769:             $bread_crumbs_component = 'LON-CAPA account request result';
 4770:         }
 4771:         $args = { bread_crumbs           => $brcrum,
 4772:                   bread_crumbs_component => $bread_crumbs_component};
 4773:         my $js = &usernamerequest_javascript();
 4774:         $r->print(&header(&add_script($js),$args));
 4775:         if (!exists($env{'form.state'})) {
 4776:             $r->print(&Apache::loncoursequeueadmin::display_queued_requests('requestusername',
 4777:                                                                             $env{'request.role.domain'}));
 4778:         } elsif ($env{'form.state'} eq 'done') {
 4779:             $r->print('<h3>'.&mt('LON-CAPA account request processing').'</h3>'."\n");
 4780:             $r->print(&Apache::loncoursequeueadmin::update_request_queue('requestusername',
 4781:                                                                          $env{'request.role.domain'}));
 4782:         }
 4783:     } elsif (($env{'form.action'} eq 'displayuserreq') &&
 4784:              ($permission->{'cusr'})) {
 4785:         my $dom = $env{'form.domain'};
 4786:         my $uname = $env{'form.username'};
 4787:         my $warning;
 4788:         if (($dom =~ /^$match_domain$/) && (&Apache::lonnet::domain($dom) ne '')) {
 4789:             if (($dom eq $env{'request.role.domain'}) && (&Apache::lonnet::allowed('ccc',$dom))) {
 4790:                 if (($uname =~ /^$match_username$/) && ($env{'form.queue'} eq 'approval')) {
 4791:                     my $uhome = &Apache::lonnet::homeserver($uname,$dom);
 4792:                     if ($uhome eq 'no_host') {
 4793:                         my $queue = $env{'form.queue'};
 4794:                         my $reqkey = &escape($uname).'_'.$queue; 
 4795:                         my $namespace = 'usernamequeue';
 4796:                         my $domconfig = &Apache::lonnet::get_domainconfiguser($dom);
 4797:                         my %queued =
 4798:                             &Apache::lonnet::get($namespace,[$reqkey],$dom,$domconfig);
 4799:                         unless ($queued{$reqkey}) {
 4800:                             $warning = &mt('No information was found for this LON-CAPA account request.');
 4801:                         }
 4802:                     } else {
 4803:                         $warning = &mt('A LON-CAPA account already exists for the requested username and domain.');
 4804:                     }
 4805:                 } else {
 4806:                     $warning = &mt('LON-CAPA account request status check is for an invalid username.');
 4807:                 }
 4808:             } else {
 4809:                 $warning = &mt('You do not have rights to view LON-CAPA account requests in the domain specified.');
 4810:             }
 4811:         } else {
 4812:             $warning = &mt('LON-CAPA account request status check is for an invalid domain.');
 4813:         }
 4814:         my $args = { only_body => 1 };
 4815:         $r->print(&header(undef,$args).
 4816:                   '<h3>'.&mt('LON-CAPA Account Request Details').'</h3>');
 4817:         if ($warning ne '') {
 4818:             $r->print('<div class="LC_warning">'.$warning.'</div>');
 4819:         } else {
 4820:             my ($infofields,$infotitles) = &Apache::loncommon::emailusername_info();
 4821:             my $domconfiguser = &Apache::lonnet::get_domainconfiguser($dom);
 4822:             my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 4823:             if (ref($domconfig{'usercreation'}) eq 'HASH') {
 4824:                 if (ref($domconfig{'usercreation'}{'cancreate'}) eq 'HASH') {
 4825:                     if (ref($domconfig{'usercreation'}{'cancreate'}{'emailusername'}) eq 'HASH') {
 4826:                         my %info =
 4827:                             &Apache::lonnet::get('nohist_requestedusernames',[$uname],$dom,$domconfiguser);
 4828:                         if (ref($info{$uname}) eq 'HASH') {
 4829:                             my $usertype = $info{$uname}{'inststatus'};
 4830:                             unless ($usertype) {
 4831:                                 $usertype = 'default';
 4832:                             }
 4833:                             if (ref($domconfig{'usercreation'}{'cancreate'}{'emailusername'}{$usertype}) eq 'HASH') {
 4834:                                 if ((ref($infofields) eq 'ARRAY') && (ref($infotitles) eq 'HASH')) {
 4835:                                     $r->print('<div>'.&Apache::lonhtmlcommon::start_pick_box());
 4836:                                     my ($num,$count,$showstatus);
 4837:                                     $count = scalar(keys(%{$domconfig{'usercreation'}{'cancreate'}{'emailusername'}{$usertype}}));
 4838:                                     unless ($usertype eq 'default') {
 4839:                                         my ($othertitle,$usertypes,$types) = 
 4840:                                             &Apache::loncommon::sorted_inst_types($dom);
 4841:                                         if (ref($usertypes) eq 'HASH') {
 4842:                                             if ($usertypes->{$usertype}) {
 4843:                                                 $showstatus = $usertypes->{$usertype};
 4844:                                                 $count ++;
 4845:                                             }
 4846:                                         }
 4847:                                     }
 4848:                                     foreach my $field (@{$infofields}) {
 4849:                                         next unless ($domconfig{'usercreation'}{'cancreate'}{'emailusername'}{$usertype}{$field});
 4850:                                         next unless ($infotitles->{$field});
 4851:                                         $r->print(&Apache::lonhtmlcommon::row_title($infotitles->{$field}).
 4852:                                                   $info{$uname}{$field});
 4853:                                         $num ++;
 4854:                                         if ($count == $num) {
 4855:                                             $r->print(&Apache::lonhtmlcommon::row_closure(1));
 4856:                                         } else {
 4857:                                             $r->print(&Apache::lonhtmlcommon::row_closure());
 4858:                                         }
 4859:                                     }
 4860:                                     if ($showstatus) {
 4861:                                         $r->print(&Apache::lonhtmlcommon::row_title(&mt('Status type (self-reported)')).
 4862:                                                   $showstatus.
 4863:                                                   &Apache::lonhtmlcommon::row_closure(1));
 4864:                                     }
 4865:                                     $r->print(&Apache::lonhtmlcommon::end_pick_box().'</div>');
 4866:                                 }
 4867:                             }
 4868:                         }
 4869:                     }
 4870:                 }
 4871:             }
 4872:             $r->print(&close_popup_form());
 4873:         }
 4874:     } elsif (($env{'form.action'} eq 'listusers') && 
 4875:              ($permission->{'view'} || $permission->{'cusr'})) {
 4876:         if ($env{'form.phase'} eq 'bulkchange') {
 4877:             push(@{$brcrum},
 4878:                     {href => '/adm/createuser?action=listusers',
 4879:                      text => "List Users"},
 4880:                     {href => "/adm/createuser",
 4881:                      text => "Result",
 4882:                      help => 'Course_View_Class_List'});
 4883:             $bread_crumbs_component = 'Update Users';
 4884:             $args = {bread_crumbs           => $brcrum,
 4885:                      bread_crumbs_component => $bread_crumbs_component};
 4886:             $r->print(&header(undef,$args));
 4887:             my $setting = $env{'form.roletype'};
 4888:             my $choice = $env{'form.bulkaction'};
 4889:             if ($permission->{'cusr'}) {
 4890:                 &Apache::lonuserutils::update_user_list($r,$context,$setting,$choice,$crstype);
 4891:             } else {
 4892:                 $r->print(&mt('You are not authorized to make bulk changes to user roles'));
 4893:                 $r->print('<p><a href="/adm/createuser?action=listusers">'.&mt('Display User Lists').'</a>');
 4894:             }
 4895:         } else {
 4896:             push(@{$brcrum},
 4897:                     {href => '/adm/createuser?action=listusers',
 4898:                      text => "List Users",
 4899:                      help => 'Course_View_Class_List'});
 4900:             $bread_crumbs_component = 'List Users';
 4901:             $args = {bread_crumbs           => $brcrum,
 4902:                      bread_crumbs_component => $bread_crumbs_component};
 4903:             my ($cb_jscript,$jscript,$totcodes,$codetitles,$idlist,$idlist_titles);
 4904:             my $formname = 'studentform';
 4905:             my $hidecall = "hide_searching();";
 4906:             if (($context eq 'domain') && (($env{'form.roletype'} eq 'course') ||
 4907:                 ($env{'form.roletype'} eq 'community'))) {
 4908:                 if ($env{'form.roletype'} eq 'course') {
 4909:                     ($cb_jscript,$jscript,$totcodes,$codetitles,$idlist,$idlist_titles) = 
 4910:                         &Apache::lonuserutils::courses_selector($env{'request.role.domain'},
 4911:                                                                 $formname);
 4912:                 } elsif ($env{'form.roletype'} eq 'community') {
 4913:                     $cb_jscript = 
 4914:                         &Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'});
 4915:                     my %elements = (
 4916:                                       coursepick => 'radio',
 4917:                                       coursetotal => 'text',
 4918:                                       courselist => 'text',
 4919:                                    );
 4920:                     $jscript = &Apache::lonhtmlcommon::set_form_elements(\%elements);
 4921:                 }
 4922:                 $jscript .= &verify_user_display($context)."\n".
 4923:                             &Apache::loncommon::check_uncheck_jscript();
 4924:                 my $js = &add_script($jscript).$cb_jscript;
 4925:                 my $loadcode = 
 4926:                     &Apache::lonuserutils::course_selector_loadcode($formname);
 4927:                 if ($loadcode ne '') {
 4928:                     $args->{add_entries} = {onload => "$loadcode;$hidecall"};
 4929:                 } else {
 4930:                     $args->{add_entries} = {onload => $hidecall};
 4931:                 }
 4932:                 $r->print(&header($js,$args));
 4933:             } else {
 4934:                 $args->{add_entries} = {onload => $hidecall};
 4935:                 $jscript = &verify_user_display($context).
 4936:                            &Apache::loncommon::check_uncheck_jscript(); 
 4937:                 $r->print(&header(&add_script($jscript),$args));
 4938:             }
 4939:             &Apache::lonuserutils::print_userlist($r,undef,$permission,$context,
 4940:                          $formname,$totcodes,$codetitles,$idlist,$idlist_titles,
 4941:                          $showcredits);
 4942:         }
 4943:     } elsif ($env{'form.action'} eq 'drop' && $permission->{'cusr'}) {
 4944:         my $brtext;
 4945:         if ($crstype eq 'Community') {
 4946:             $brtext = 'Drop Members';
 4947:         } else {
 4948:             $brtext = 'Drop Students';
 4949:         }
 4950:         push(@{$brcrum},
 4951:                 {href => '/adm/createuser?action=drop',
 4952:                  text => $brtext,
 4953:                  help => 'Course_Drop_Student'});
 4954:         if ($env{'form.state'} eq 'done') {
 4955:             push(@{$brcrum},
 4956:                      {href=>'/adm/createuser?action=drop',
 4957:                       text=>"Result"});
 4958:         }
 4959:         $bread_crumbs_component = $brtext;
 4960:         $args = {bread_crumbs           => $brcrum,
 4961:                  bread_crumbs_component => $bread_crumbs_component}; 
 4962:         $r->print(&header(undef,$args));
 4963:         if (!exists($env{'form.state'})) {
 4964:             &Apache::lonuserutils::print_drop_menu($r,$context,$permission,$crstype);
 4965:         } elsif ($env{'form.state'} eq 'done') {
 4966:             &Apache::lonuserutils::update_user_list($r,$context,undef,
 4967:                                                     $env{'form.action'});
 4968:         }
 4969:     } elsif ($env{'form.action'} eq 'dateselect') {
 4970:         if ($permission->{'cusr'}) {
 4971:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 4972:                       &Apache::lonuserutils::date_section_selector($context,$permission,
 4973:                                                                    $crstype,$showcredits));
 4974:         } else {
 4975:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 4976:                      '<span class="LC_error">'.&mt('You do not have permission to modify dates or sections for users').'</span>'); 
 4977:         }
 4978:     } elsif ($env{'form.action'} eq 'selfenroll') {
 4979:         if ($permission->{selfenrolladmin}) {
 4980:             my $cid = $env{'request.course.id'};
 4981:             my $cdom = $env{'course.'.$cid.'.domain'};
 4982:             my $cnum = $env{'course.'.$cid.'.num'};
 4983:             my %currsettings = (
 4984:                 selfenroll_types              => $env{'course.'.$cid.'.internal.selfenroll_types'},
 4985:                 selfenroll_registered         => $env{'course.'.$cid.'.internal.selfenroll_registered'},
 4986:                 selfenroll_section            => $env{'course.'.$cid.'.internal.selfenroll_section'},
 4987:                 selfenroll_notifylist         => $env{'course.'.$cid.'.internal.selfenroll_notifylist'},
 4988:                 selfenroll_approval           => $env{'course.'.$cid.'.internal.selfenroll_approval'},
 4989:                 selfenroll_limit              => $env{'course.'.$cid.'.internal.selfenroll_limit'},
 4990:                 selfenroll_cap                => $env{'course.'.$cid.'.internal.selfenroll_cap'},
 4991:                 selfenroll_start_date         => $env{'course.'.$cid.'.internal.selfenroll_start_date'},
 4992:                 selfenroll_end_date           => $env{'course.'.$cid.'.internal.selfenroll_end_date'},
 4993:                 selfenroll_start_access       => $env{'course.'.$cid.'.internal.selfenroll_start_access'},
 4994:                 selfenroll_end_access         => $env{'course.'.$cid.'.internal.selfenroll_end_access'},
 4995:                 default_enrollment_start_date => $env{'course.'.$cid.'.default_enrollment_start_date'},
 4996:                 default_enrollment_end_date   => $env{'course.'.$cid.'.default_enrollment_end_date'},
 4997:                 uniquecode                    => $env{'course.'.$cid.'.internal.uniquecode'},
 4998:             );
 4999:             push(@{$brcrum},
 5000:                     {href => '/adm/createuser?action=selfenroll',
 5001:                      text => "Configure Self-enrollment",
 5002:                      help => 'Course_Self_Enrollment'});
 5003:             if (!exists($env{'form.state'})) {
 5004:                 $args = { bread_crumbs           => $brcrum,
 5005:                           bread_crumbs_component => 'Configure Self-enrollment'};
 5006:                 $r->print(&header(undef,$args));
 5007:                 $r->print('<h3>'.&mt('Self-enrollment with a student role').'</h3>'."\n");
 5008:                 &print_selfenroll_menu($r,'course',$cid,$cdom,$cnum,\%currsettings);
 5009:             } elsif ($env{'form.state'} eq 'done') {
 5010:                 push (@{$brcrum},
 5011:                           {href=>'/adm/createuser?action=selfenroll',
 5012:                            text=>"Result"});
 5013:                 $args = { bread_crumbs           => $brcrum,
 5014:                           bread_crumbs_component => 'Self-enrollment result'};
 5015:                 $r->print(&header(undef,$args));
 5016:                 $r->print('<h3>'.&mt('Self-enrollment with a student role').'</h3>'."\n");
 5017:                 &update_selfenroll_config($r,$cid,$cdom,$cnum,$context,$crstype,\%currsettings);
 5018:             }
 5019:         } else {
 5020:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 5021:                      '<span class="LC_error">'.&mt('You do not have permission to configure self-enrollment').'</span>');
 5022:         }
 5023:     } elsif ($env{'form.action'} eq 'selfenrollqueue') {
 5024:         push(@{$brcrum},
 5025:                  {href => '/adm/createuser?action=selfenrollqueue',
 5026:                   text => 'Enrollment requests',
 5027:                   help => 'Course_Self_Enrollment'});
 5028:         $bread_crumbs_component = 'Enrollment requests';
 5029:         if ($env{'form.state'} eq 'done') {
 5030:             push(@{$brcrum},
 5031:                      {href => '/adm/createuser?action=selfenrollqueue',
 5032:                       text => 'Result',
 5033:                       help => 'Course_Self_Enrollment'});
 5034:             $bread_crumbs_component = 'Enrollment result';
 5035:         }
 5036:         $args = { bread_crumbs           => $brcrum,
 5037:                   bread_crumbs_component => $bread_crumbs_component};
 5038:         $r->print(&header(undef,$args));
 5039:         my $cid = $env{'request.course.id'};
 5040:         my $cdom = $env{'course.'.$cid.'.domain'};
 5041:         my $cnum = $env{'course.'.$cid.'.num'};
 5042:         my $coursedesc = $env{'course.'.$cid.'.description'};
 5043:         if (!exists($env{'form.state'})) {
 5044:             $r->print('<h3>'.&mt('Pending enrollment requests').'</h3>'."\n");
 5045:             $r->print(&Apache::loncoursequeueadmin::display_queued_requests($context,
 5046:                                                                        $cdom,$cnum));
 5047:         } elsif ($env{'form.state'} eq 'done') {
 5048:             $r->print('<h3>'.&mt('Enrollment request processing').'</h3>'."\n");
 5049:             $r->print(&Apache::loncoursequeueadmin::update_request_queue($context,
 5050:                           $cdom,$cnum,$coursedesc));
 5051:         }
 5052:     } elsif ($env{'form.action'} eq 'changelogs') {
 5053:         my $helpitem;
 5054:         if ($context eq 'course') {
 5055:             $helpitem = 'Course_User_Logs';
 5056:         }
 5057:         push (@{$brcrum},
 5058:                  {href => '/adm/createuser?action=changelogs',
 5059:                   text => 'User Management Logs',
 5060:                   help => $helpitem});
 5061:         $bread_crumbs_component = 'User Changes';
 5062:         $args = { bread_crumbs           => $brcrum,
 5063:                   bread_crumbs_component => $bread_crumbs_component};
 5064:         $r->print(&header(undef,$args));
 5065:         &print_userchangelogs_display($r,$context,$permission);
 5066:     } else {
 5067:         $bread_crumbs_component = 'User Management';
 5068:         $args = { bread_crumbs           => $brcrum,
 5069:                   bread_crumbs_component => $bread_crumbs_component};
 5070:         $r->print(&header(undef,$args));
 5071:         $r->print(&print_main_menu($permission,$context,$crstype));
 5072:     }
 5073:     $r->print(&Apache::loncommon::end_page());
 5074:     return OK;
 5075: }
 5076: 
 5077: sub header {
 5078:     my ($jscript,$args) = @_;
 5079:     my $start_page;
 5080:     if (ref($args) eq 'HASH') {
 5081:         $start_page=&Apache::loncommon::start_page('User Management',$jscript,$args);
 5082:     } else {
 5083:         $start_page=&Apache::loncommon::start_page('User Management',$jscript);
 5084:     }
 5085:     return $start_page;
 5086: }
 5087: 
 5088: sub add_script {
 5089:     my ($js) = @_;
 5090:     return '<script type="text/javascript">'."\n"
 5091:           .'// <![CDATA['."\n"
 5092:           .$js."\n"
 5093:           .'// ]]>'."\n"
 5094:           .'</script>'."\n";
 5095: }
 5096: 
 5097: sub usernamerequest_javascript {
 5098:     my $js = <<ENDJS;
 5099: 
 5100: function openusernamereqdisplay(dom,uname,queue) {
 5101:     var url = '/adm/createuser?action=displayuserreq';
 5102:     url += '&domain='+dom+'&username='+uname+'&queue='+queue;
 5103:     var title = 'Account_Request_Browser';
 5104:     var options = 'scrollbars=1,resizable=1,menubar=0';
 5105:     options += ',width=700,height=600';
 5106:     var stdeditbrowser = open(url,title,options,'1');
 5107:     stdeditbrowser.focus();
 5108:     return;
 5109: }
 5110:  
 5111: ENDJS
 5112: }
 5113: 
 5114: sub close_popup_form {
 5115:     my $close= &mt('Close Window');
 5116:     return << "END";
 5117: <p><form name="displayreq" action="" method="post">
 5118: <input type="button" name="closeme" value="$close" onclick="javascript:self.close();" />
 5119: </form></p>
 5120: END
 5121: }
 5122: 
 5123: sub verify_user_display {
 5124:     my ($context) = @_;
 5125:     my %lt = &Apache::lonlocal::texthash (
 5126:         course    => 'course(s): description, section(s), status',
 5127:         community => 'community(s): description, section(s), status',
 5128:         author    => 'author',
 5129:     );
 5130:     my $photos;
 5131:     if (($context eq 'course') && $env{'request.course.id'}) {
 5132:         $photos = $env{'course.'.$env{'request.course.id'}.'.internal.showphoto'};
 5133:     }
 5134:     my $output = <<"END";
 5135: 
 5136: function hide_searching() {
 5137:     if (document.getElementById('searching')) {
 5138:         document.getElementById('searching').style.display = 'none';
 5139:     }
 5140:     return;
 5141: }
 5142: 
 5143: function display_update() {
 5144:     document.studentform.action.value = 'listusers';
 5145:     document.studentform.phase.value = 'display';
 5146:     document.studentform.submit();
 5147: }
 5148: 
 5149: function updateCols(caller) {
 5150:     var context = '$context';
 5151:     var photos = '$photos';
 5152:     if (caller == 'Status') {
 5153:         if ((context == 'domain') && 
 5154:             ((document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'course') ||
 5155:              (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'community'))) {
 5156:             document.getElementById('showcolstatus').checked = false;
 5157:             document.getElementById('showcolstatus').disabled = 'disabled';
 5158:             document.getElementById('showcolstart').checked = false;
 5159:             document.getElementById('showcolend').checked = false;
 5160:         } else {
 5161:             if (document.studentform.Status.options[document.studentform.Status.selectedIndex].value == 'Any') {
 5162:                 document.getElementById('showcolstatus').checked = true;
 5163:                 document.getElementById('showcolstatus').disabled = '';
 5164:                 document.getElementById('showcolstart').checked = true;
 5165:                 document.getElementById('showcolend').checked = true;
 5166:             } else {
 5167:                 document.getElementById('showcolstatus').checked = false;
 5168:                 document.getElementById('showcolstatus').disabled = 'disabled';
 5169:                 document.getElementById('showcolstart').checked = false;
 5170:                 document.getElementById('showcolend').checked = false;
 5171:             }
 5172:         }
 5173:     }
 5174:     if (caller == 'output') {
 5175:         if (photos == 1) {
 5176:             if (document.getElementById('showcolphoto')) {
 5177:                 var photoitem = document.getElementById('showcolphoto');
 5178:                 if (document.studentform.output.options[document.studentform.output.selectedIndex].value == 'html') {
 5179:                     photoitem.checked = true;
 5180:                     photoitem.disabled = '';
 5181:                 } else {
 5182:                     photoitem.checked = false;
 5183:                     photoitem.disabled = 'disabled';
 5184:                 }
 5185:             }
 5186:         }
 5187:     }
 5188:     if (caller == 'showrole') {
 5189:         if ((document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'Any') ||
 5190:             (document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'cr')) {
 5191:             document.getElementById('showcolrole').checked = true;
 5192:             document.getElementById('showcolrole').disabled = '';
 5193:         } else {
 5194:             document.getElementById('showcolrole').checked = false;
 5195:             document.getElementById('showcolrole').disabled = 'disabled';
 5196:         }
 5197:         if (context == 'domain') {
 5198:             var quotausageshow = 0;
 5199:             if ((document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'course') ||
 5200:                 (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'community')) {
 5201:                 document.getElementById('showcolstatus').checked = false;
 5202:                 document.getElementById('showcolstatus').disabled = 'disabled';
 5203:                 document.getElementById('showcolstart').checked = false;
 5204:                 document.getElementById('showcolend').checked = false;
 5205:             } else {
 5206:                 if (document.studentform.Status.options[document.studentform.Status.selectedIndex].value == 'Any') {
 5207:                     document.getElementById('showcolstatus').checked = true;
 5208:                     document.getElementById('showcolstatus').disabled = '';
 5209:                     document.getElementById('showcolstart').checked = true;
 5210:                     document.getElementById('showcolend').checked = true;
 5211:                 }
 5212:             }
 5213:             if (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'domain') {
 5214:                 document.getElementById('showcolextent').disabled = 'disabled';
 5215:                 document.getElementById('showcolextent').checked = 'false';
 5216:                 document.getElementById('showextent').style.display='none';
 5217:                 document.getElementById('showcoltextextent').innerHTML = '';
 5218:                 if ((document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'au') ||
 5219:                     (document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'Any')) {
 5220:                     if (document.getElementById('showcolauthorusage')) {
 5221:                         document.getElementById('showcolauthorusage').disabled = '';
 5222:                     }
 5223:                     if (document.getElementById('showcolauthorquota')) {
 5224:                         document.getElementById('showcolauthorquota').disabled = '';
 5225:                     }
 5226:                     quotausageshow = 1;
 5227:                 }
 5228:             } else {
 5229:                 document.getElementById('showextent').style.display='block';
 5230:                 document.getElementById('showextent').style.textAlign='left';
 5231:                 document.getElementById('showextent').style.textFace='normal';
 5232:                 if (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'author') {
 5233:                     document.getElementById('showcolextent').disabled = '';
 5234:                     document.getElementById('showcolextent').checked = 'true';
 5235:                     document.getElementById('showcoltextextent').innerHTML="$lt{'author'}";
 5236:                 } else {
 5237:                     document.getElementById('showcolextent').disabled = '';
 5238:                     document.getElementById('showcolextent').checked = 'true';
 5239:                     if (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'community') {
 5240:                         document.getElementById('showcoltextextent').innerHTML="$lt{'community'}";
 5241:                     } else {
 5242:                         document.getElementById('showcoltextextent').innerHTML="$lt{'course'}";
 5243:                     }
 5244:                 }
 5245:             }
 5246:             if (quotausageshow == 0)  {
 5247:                 if (document.getElementById('showcolauthorusage')) {
 5248:                     document.getElementById('showcolauthorusage').checked = false;
 5249:                     document.getElementById('showcolauthorusage').disabled = 'disabled';
 5250:                 }
 5251:                 if (document.getElementById('showcolauthorquota')) {
 5252:                     document.getElementById('showcolauthorquota').checked = false;
 5253:                     document.getElementById('showcolauthorquota').disabled = 'disabled';
 5254:                 }
 5255:             }
 5256:         }
 5257:     }
 5258:     return;
 5259: }
 5260: 
 5261: END
 5262:     return $output;
 5263: 
 5264: }
 5265: 
 5266: ###############################################################
 5267: ###############################################################
 5268: #  Menu Phase One
 5269: sub print_main_menu {
 5270:     my ($permission,$context,$crstype) = @_;
 5271:     my $linkcontext = $context;
 5272:     my $stuterm = lc(&Apache::lonnet::plaintext('st',$crstype));
 5273:     if (($context eq 'course') && ($crstype eq 'Community')) {
 5274:         $linkcontext = lc($crstype);
 5275:         $stuterm = 'Members';
 5276:     }
 5277:     my %links = (
 5278:                 domain => {
 5279:                             upload     => 'Upload a File of Users',
 5280:                             singleuser => 'Add/Modify a User',
 5281:                             listusers  => 'Manage Users',
 5282:                             },
 5283:                 author => {
 5284:                             upload     => 'Upload a File of Co-authors',
 5285:                             singleuser => 'Add/Modify a Co-author',
 5286:                             listusers  => 'Manage Co-authors',
 5287:                             },
 5288:                 course => {
 5289:                             upload     => 'Upload a File of Course Users',
 5290:                             singleuser => 'Add/Modify a Course User',
 5291:                             listusers  => 'List and Modify Multiple Course Users',
 5292:                             },
 5293:                 community => {
 5294:                             upload     => 'Upload a File of Community Users',
 5295:                             singleuser => 'Add/Modify a Community User',
 5296:                             listusers  => 'List and Modify Multiple Community Users',
 5297:                            },
 5298:                 );
 5299:      my %linktitles = (
 5300:                 domain => {
 5301:                             singleuser => 'Add a user to the domain, and/or a course or community in the domain.',
 5302:                             listusers  => 'Show and manage users in this domain.',
 5303:                             },
 5304:                 author => {
 5305:                             singleuser => 'Add a user with a co- or assistant author role.',
 5306:                             listusers  => 'Show and manage co- or assistant authors.',
 5307:                             },
 5308:                 course => {
 5309:                             singleuser => 'Add a user with a certain role to this course.',
 5310:                             listusers  => 'Show and manage users in this course.',
 5311:                             },
 5312:                 community => {
 5313:                             singleuser => 'Add a user with a certain role to this community.',
 5314:                             listusers  => 'Show and manage users in this community.',
 5315:                            },
 5316:                 );
 5317:   my @menu = ( {categorytitle => 'Single Users', 
 5318:          items =>
 5319:          [
 5320:             {
 5321:              linktext => $links{$linkcontext}{'singleuser'},
 5322:              icon => 'edit-redo.png',
 5323:              #help => 'Course_Change_Privileges',
 5324:              url => '/adm/createuser?action=singleuser',
 5325:              permission => $permission->{'cusr'},
 5326:              linktitle => $linktitles{$linkcontext}{'singleuser'},
 5327:             },
 5328:          ]},
 5329: 
 5330:          {categorytitle => 'Multiple Users',
 5331:          items => 
 5332:          [
 5333:             {
 5334:              linktext => $links{$linkcontext}{'upload'},
 5335:              icon => 'uplusr.png',
 5336:              #help => 'Course_Create_Class_List',
 5337:              url => '/adm/createuser?action=upload',
 5338:              permission => $permission->{'cusr'},
 5339:              linktitle => 'Upload a CSV or a text file containing users.',
 5340:             },
 5341:             {
 5342:              linktext => $links{$linkcontext}{'listusers'},
 5343:              icon => 'mngcu.png',
 5344:              #help => 'Course_View_Class_List',
 5345:              url => '/adm/createuser?action=listusers',
 5346:              permission => ($permission->{'view'} || $permission->{'cusr'}),
 5347:              linktitle => $linktitles{$linkcontext}{'listusers'}, 
 5348:             },
 5349: 
 5350:          ]},
 5351: 
 5352:          {categorytitle => 'Administration',
 5353:          items => [ ]},
 5354:        );
 5355:             
 5356:     if ($context eq 'domain'){
 5357:         
 5358:         push(@{ $menu[2]->{items} }, #Category: Administration
 5359:             {
 5360:              linktext => 'Custom Roles',
 5361:              icon => 'emblem-photos.png',
 5362:              #help => 'Course_Editing_Custom_Roles',
 5363:              url => '/adm/createuser?action=custom',
 5364:              permission => $permission->{'custom'},
 5365:              linktitle => 'Configure a custom role.',
 5366:             },
 5367:             {
 5368:              linktext => 'Authoring Space Requests',
 5369:              icon => 'selfenrl-queue.png',
 5370:              #help => 'Domain_Role_Approvals',
 5371:              url => '/adm/createuser?action=processauthorreq',
 5372:              permission => $permission->{'cusr'},
 5373:              linktitle => 'Approve or reject author role requests',
 5374:             },
 5375:             {
 5376:              linktext => 'LON-CAPA Account Requests',
 5377:              icon => 'list-add.png',
 5378:              #help => 'Domain_Username_Approvals',
 5379:              url => '/adm/createuser?action=processusernamereq',
 5380:              permission => $permission->{'cusr'},
 5381:              linktitle => 'Approve or reject LON-CAPA account requests',
 5382:             },
 5383:             {
 5384:              linktext => 'Change Log',
 5385:              icon => 'document-properties.png',
 5386:              #help => 'Course_User_Logs',
 5387:              url => '/adm/createuser?action=changelogs',
 5388:              permission => $permission->{'cusr'},
 5389:              linktitle => 'View change log.',
 5390:             },
 5391:         );
 5392:         
 5393:     }elsif ($context eq 'course'){
 5394:         my ($cnum,$cdom) = &Apache::lonuserutils::get_course_identity();
 5395: 
 5396:         my %linktext = (
 5397:                          'Course'    => {
 5398:                                           single => 'Add/Modify a Student', 
 5399:                                           drop   => 'Drop Students',
 5400:                                           groups => 'Course Groups',
 5401:                                         },
 5402:                          'Community' => {
 5403:                                           single => 'Add/Modify a Member', 
 5404:                                           drop   => 'Drop Members',
 5405:                                           groups => 'Community Groups',
 5406:                                         },
 5407:                        );
 5408: 
 5409:         my %linktitle = (
 5410:             'Course' => {
 5411:                   single => 'Add a user with the role of student to this course',
 5412:                   drop   => 'Remove a student from this course.',
 5413:                   groups => 'Manage course groups',
 5414:                         },
 5415:             'Community' => {
 5416:                   single => 'Add a user with the role of member to this community',
 5417:                   drop   => 'Remove a member from this community.',
 5418:                   groups => 'Manage community groups',
 5419:                            },
 5420:         );
 5421: 
 5422:         push(@{ $menu[0]->{items} }, #Category: Single Users
 5423:             {   
 5424:              linktext => $linktext{$crstype}{'single'},
 5425:              #help => 'Course_Add_Student',
 5426:              icon => 'list-add.png',
 5427:              url => '/adm/createuser?action=singlestudent',
 5428:              permission => $permission->{'cusr'},
 5429:              linktitle => $linktitle{$crstype}{'single'},
 5430:             },
 5431:         );
 5432:         
 5433:         push(@{ $menu[1]->{items} }, #Category: Multiple Users 
 5434:             {
 5435:              linktext => $linktext{$crstype}{'drop'},
 5436:              icon => 'edit-undo.png',
 5437:              #help => 'Course_Drop_Student',
 5438:              url => '/adm/createuser?action=drop',
 5439:              permission => $permission->{'cusr'},
 5440:              linktitle => $linktitle{$crstype}{'drop'},
 5441:             },
 5442:         );
 5443:         push(@{ $menu[2]->{items} }, #Category: Administration
 5444:             {    
 5445:              linktext => 'Custom Roles',
 5446:              icon => 'emblem-photos.png',
 5447:              #help => 'Course_Editing_Custom_Roles',
 5448:              url => '/adm/createuser?action=custom',
 5449:              permission => $permission->{'custom'},
 5450:              linktitle => 'Configure a custom role.',
 5451:             },
 5452:             {
 5453:              linktext => $linktext{$crstype}{'groups'},
 5454:              icon => 'grps.png',
 5455:              #help => 'Course_Manage_Group',
 5456:              url => '/adm/coursegroups?refpage=cusr',
 5457:              permission => $permission->{'grp_manage'},
 5458:              linktitle => $linktitle{$crstype}{'groups'},
 5459:             },
 5460:             {
 5461:              linktext => 'Change Log',
 5462:              icon => 'document-properties.png',
 5463:              #help => 'Course_User_Logs',
 5464:              url => '/adm/createuser?action=changelogs',
 5465:              permission => $permission->{'cusr'},
 5466:              linktitle => 'View change log.',
 5467:             },
 5468:         );
 5469:         if ($env{'course.'.$env{'request.course.id'}.'.internal.selfenroll_approval'}) {
 5470:             push(@{ $menu[2]->{items} },
 5471:                     {
 5472:                      linktext => 'Enrollment Requests',
 5473:                      icon => 'selfenrl-queue.png',
 5474:                      #help => 'Course_Approve_Selfenroll',
 5475:                      url => '/adm/createuser?action=selfenrollqueue',
 5476:                      permission => $permission->{'selfenrolladmin'},
 5477:                      linktitle =>'Approve or reject enrollment requests.',
 5478:                     },
 5479:             );
 5480:         }
 5481:         
 5482:         if (!exists($permission->{'cusr_section'})){
 5483:             if ($crstype ne 'Community') {
 5484:                 push(@{ $menu[2]->{items} },
 5485:                     {
 5486:                      linktext => 'Automated Enrollment',
 5487:                      icon => 'roles.png',
 5488:                      #help => 'Course_Automated_Enrollment',
 5489:                      permission => (&Apache::lonnet::auto_run($cnum,$cdom)
 5490:                                          && $permission->{'cusr'}),
 5491:                      url  => '/adm/populate',
 5492:                      linktitle => 'Automated enrollment manager.',
 5493:                     }
 5494:                 );
 5495:             }
 5496:             push(@{ $menu[2]->{items} }, 
 5497:                 {
 5498:                  linktext => 'User Self-Enrollment',
 5499:                  icon => 'self_enroll.png',
 5500:                  #help => 'Course_Self_Enrollment',
 5501:                  url => '/adm/createuser?action=selfenroll',
 5502:                  permission => $permission->{'selfenrolladmin'},
 5503:                  linktitle => 'Configure user self-enrollment.',
 5504:                 },
 5505:             );
 5506:         }
 5507:     } elsif ($context eq 'author') {
 5508:         push(@{ $menu[2]->{items} }, #Category: Administration
 5509:             {
 5510:              linktext => 'Change Log',
 5511:              icon => 'document-properties.png',
 5512:              #help => 'Course_User_Logs',
 5513:              url => '/adm/createuser?action=changelogs',
 5514:              permission => $permission->{'cusr'},
 5515:              linktitle => 'View change log.',
 5516:             },
 5517:         );
 5518:     }
 5519:     return Apache::lonhtmlcommon::generate_menu(@menu);
 5520: #               { text => 'View Log-in History',
 5521: #                 help => 'Course_User_Logins',
 5522: #                 action => 'logins',
 5523: #                 permission => $permission->{'cusr'},
 5524: #               });
 5525: }
 5526: 
 5527: sub restore_prev_selections {
 5528:     my %saveable_parameters = ('srchby'   => 'scalar',
 5529: 			       'srchin'   => 'scalar',
 5530: 			       'srchtype' => 'scalar',
 5531: 			       );
 5532:     &Apache::loncommon::store_settings('user','user_picker',
 5533: 				       \%saveable_parameters);
 5534:     &Apache::loncommon::restore_settings('user','user_picker',
 5535: 					 \%saveable_parameters);
 5536: }
 5537: 
 5538: sub print_selfenroll_menu {
 5539:     my ($r,$context,$cid,$cdom,$cnum,$currsettings,$additional) = @_;
 5540:     my $crstype = &Apache::loncommon::course_type();
 5541:     my $formname = 'selfenroll';
 5542:     my $nolink = 1;
 5543:     my ($row,$lt) = &Apache::lonuserutils::get_selfenroll_titles();
 5544:     my $groupslist = &Apache::lonuserutils::get_groupslist();
 5545:     my $setsec_js = 
 5546:         &Apache::lonuserutils::setsections_javascript($formname,$groupslist);
 5547:     my %alerts = &Apache::lonlocal::texthash(
 5548:         acto => 'Activation of self-enrollment was selected for the following domain(s)',
 5549:         butn => 'but no user types have been checked.',
 5550:         wilf => "Please uncheck 'activate' or check at least one type.",
 5551:     );
 5552:     &js_escape(\%alerts);
 5553:     my $selfenroll_js = <<"ENDSCRIPT";
 5554: function update_types(caller,num) {
 5555:     var delidx = getIndexByName('selfenroll_delete');
 5556:     var actidx = getIndexByName('selfenroll_activate');
 5557:     if (caller == 'selfenroll_all') {
 5558:         var selall;
 5559:         for (var i=0; i<document.$formname.selfenroll_all.length; i++) {
 5560:             if (document.$formname.selfenroll_all[i].checked) {
 5561:                 selall = document.$formname.selfenroll_all[i].value;
 5562:             }
 5563:         }
 5564:         if (selall == 1) {
 5565:             if (delidx != -1) {
 5566:                 if (document.$formname.selfenroll_delete.length) {
 5567:                     for (var j=0; j<document.$formname.selfenroll_delete.length; j++) {
 5568:                         document.$formname.selfenroll_delete[j].checked = true;
 5569:                     }
 5570:                 } else {
 5571:                     document.$formname.elements[delidx].checked = true;
 5572:                 }
 5573:             }
 5574:             if (actidx != -1) {
 5575:                 if (document.$formname.selfenroll_activate.length) {
 5576:                     for (var j=0; j<document.$formname.selfenroll_activate.length; j++) {
 5577:                         document.$formname.selfenroll_activate[j].checked = false;
 5578:                     }
 5579:                 } else {
 5580:                     document.$formname.elements[actidx].checked = false;
 5581:                 }
 5582:             }
 5583:             document.$formname.selfenroll_newdom.selectedIndex = 0; 
 5584:         }
 5585:     }
 5586:     if (caller == 'selfenroll_activate') {
 5587:         if (document.$formname.selfenroll_activate.length) {
 5588:             for (var j=0; j<document.$formname.selfenroll_activate.length; j++) {
 5589:                 if (document.$formname.selfenroll_activate[j].value == num) {
 5590:                     if (document.$formname.selfenroll_activate[j].checked) {
 5591:                         for (var i=0; i<document.$formname.selfenroll_all.length; i++) {
 5592:                             if (document.$formname.selfenroll_all[i].value == '1') {
 5593:                                 document.$formname.selfenroll_all[i].checked = false;
 5594:                             }
 5595:                             if (document.$formname.selfenroll_all[i].value == '0') {
 5596:                                 document.$formname.selfenroll_all[i].checked = true;
 5597:                             }
 5598:                         }
 5599:                     }
 5600:                 }
 5601:             }
 5602:         } else {
 5603:             for (var i=0; i<document.$formname.selfenroll_all.length; i++) {
 5604:                 if (document.$formname.selfenroll_all[i].value == '1') {
 5605:                     document.$formname.selfenroll_all[i].checked = false;
 5606:                 }
 5607:                 if (document.$formname.selfenroll_all[i].value == '0') {
 5608:                     document.$formname.selfenroll_all[i].checked = true;
 5609:                 }
 5610:             }
 5611:         }
 5612:     }
 5613:     if (caller == 'selfenroll_delete') {
 5614:         if (document.$formname.selfenroll_delete.length) {
 5615:             for (var j=0; j<document.$formname.selfenroll_delete.length; j++) {
 5616:                 if (document.$formname.selfenroll_delete[j].value == num) {
 5617:                     if (document.$formname.selfenroll_delete[j].checked) {
 5618:                         var delindex = getIndexByName('selfenroll_types_'+num);
 5619:                         if (delindex != -1) { 
 5620:                             if (document.$formname.elements[delindex].length) {
 5621:                                 for (var k=0; k<document.$formname.elements[delindex].length; k++) {
 5622:                                     document.$formname.elements[delindex][k].checked = false;
 5623:                                 }
 5624:                             } else {
 5625:                                 document.$formname.elements[delindex].checked = false;
 5626:                             }
 5627:                         }
 5628:                     }
 5629:                 }
 5630:             }
 5631:         } else {
 5632:             if (document.$formname.selfenroll_delete.checked) {
 5633:                 var delindex = getIndexByName('selfenroll_types_'+num);
 5634:                 if (delindex != -1) {
 5635:                     if (document.$formname.elements[delindex].length) {
 5636:                         for (var k=0; k<document.$formname.elements[delindex].length; k++) {
 5637:                             document.$formname.elements[delindex][k].checked = false;
 5638:                         }
 5639:                     } else {
 5640:                         document.$formname.elements[delindex].checked = false;
 5641:                     }
 5642:                 }
 5643:             }
 5644:         }
 5645:     }
 5646:     return;
 5647: }
 5648: 
 5649: function validate_types(form) {
 5650:     var needaction = new Array();
 5651:     var countfail = 0;
 5652:     var actidx = getIndexByName('selfenroll_activate');
 5653:     if (actidx != -1) {
 5654:         if (document.$formname.selfenroll_activate.length) {
 5655:             for (var j=0; j<document.$formname.selfenroll_activate.length; j++) {
 5656:                 var num = document.$formname.selfenroll_activate[j].value;
 5657:                 if (document.$formname.selfenroll_activate[j].checked) {
 5658:                     countfail = check_types(num,countfail,needaction)
 5659:                 }
 5660:             }
 5661:         } else {
 5662:             if (document.$formname.selfenroll_activate.checked) {
 5663:                 var num = document.$formname.selfenroll_activate.value;
 5664:                 countfail = check_types(num,countfail,needaction)
 5665:             }
 5666:         }
 5667:     }
 5668:     if (countfail > 0) {
 5669:         var msg = "$alerts{'acto'}\\n";
 5670:         var loopend = needaction.length -1;
 5671:         if (loopend > 0) {
 5672:             for (var m=0; m<loopend; m++) {
 5673:                 msg += needaction[m]+", ";
 5674:             }
 5675:         }
 5676:         msg += needaction[loopend]+"\\n$alerts{'butn'}\\n$alerts{'wilf'}";
 5677:         alert(msg);
 5678:         return; 
 5679:     }
 5680:     setSections(form);
 5681: }
 5682: 
 5683: function check_types(num,countfail,needaction) {
 5684:     var typeidx = getIndexByName('selfenroll_types_'+num);
 5685:     var count = 0;
 5686:     if (typeidx != -1) {
 5687:         if (document.$formname.elements[typeidx].length) {
 5688:             for (var k=0; k<document.$formname.elements[typeidx].length; k++) {
 5689:                 if (document.$formname.elements[typeidx][k].checked) {
 5690:                     count ++;
 5691:                 }
 5692:             }
 5693:         } else {
 5694:             if (document.$formname.elements[typeidx].checked) {
 5695:                 count ++;
 5696:             }
 5697:         }
 5698:         if (count == 0) {
 5699:             var domidx = getIndexByName('selfenroll_dom_'+num);
 5700:             if (domidx != -1) {
 5701:                 var domname = document.$formname.elements[domidx].value;
 5702:                 needaction[countfail] = domname;
 5703:                 countfail ++;
 5704:             }
 5705:         }
 5706:     }
 5707:     return countfail;
 5708: }
 5709: 
 5710: function toggleNotify() {
 5711:     var selfenrollApproval = 0;
 5712:     if (document.$formname.selfenroll_approval.length) {
 5713:         for (var i=0; i<document.$formname.selfenroll_approval.length; i++) {
 5714:             if (document.$formname.selfenroll_approval[i].checked) {
 5715:                 selfenrollApproval = document.$formname.selfenroll_approval[i].value;
 5716:                 break;        
 5717:             }
 5718:         }
 5719:     }
 5720:     if (document.getElementById('notified')) {
 5721:         if (selfenrollApproval == 0) {
 5722:             document.getElementById('notified').style.display='none';
 5723:         } else {
 5724:             document.getElementById('notified').style.display='block';
 5725:         }
 5726:     }
 5727:     return;
 5728: }
 5729: 
 5730: function getIndexByName(item) {
 5731:     for (var i=0;i<document.$formname.elements.length;i++) {
 5732:         if (document.$formname.elements[i].name == item) {
 5733:             return i;
 5734:         }
 5735:     }
 5736:     return -1;
 5737: }
 5738: ENDSCRIPT
 5739: 
 5740:     my $output = '<script type="text/javascript">'."\n".
 5741:                  '// <![CDATA['."\n".
 5742:                  $setsec_js."\n".$selfenroll_js."\n".
 5743:                  '// ]]>'."\n".
 5744:                  '</script>'."\n".
 5745:                  '<h3>'.$lt->{'selfenroll'}.'</h3>'."\n";
 5746:  
 5747:     my $visactions = &cat_visibility();
 5748:     my ($cathash,%cattype);
 5749:     my %domconfig = &Apache::lonnet::get_dom('configuration',['coursecategories'],$cdom);
 5750:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 5751:         $cathash = $domconfig{'coursecategories'}{'cats'};
 5752:         $cattype{'auth'} = $domconfig{'coursecategories'}{'auth'};
 5753:         $cattype{'unauth'} = $domconfig{'coursecategories'}{'unauth'};
 5754:         if ($cattype{'auth'} eq '') {
 5755:             $cattype{'auth'} = 'std';
 5756:         }
 5757:         if ($cattype{'unauth'} eq '') {
 5758:             $cattype{'unauth'} = 'std';
 5759:         }
 5760:     } else {
 5761:         $cathash = {};
 5762:         $cattype{'auth'} = 'std';
 5763:         $cattype{'unauth'} = 'std';
 5764:     }
 5765:     if (($cattype{'auth'} eq 'none') && ($cattype{'unauth'} eq 'none')) {
 5766:         $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
 5767:                   '<br />'.
 5768:                   '<br />'.$visactions->{'take'}.'<ul>'.
 5769:                   '<li>'.$visactions->{'dc_chgconf'}.'</li>'.
 5770:                   '</ul>');
 5771:     } elsif (($cattype{'auth'} !~ /^(std|domonly)$/) && ($cattype{'unauth'} !~ /^(std|domonly)$/)) {
 5772:         if ($currsettings->{'uniquecode'}) {
 5773:             $r->print('<span class="LC_info">'.$visactions->{'vis'}.'</span>');
 5774:         } else {
 5775:             $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
 5776:                   '<br />'.
 5777:                   '<br />'.$visactions->{'take'}.'<ul>'.
 5778:                   '<li>'.$visactions->{'dc_setcode'}.'</li>'.
 5779:                   '</ul><br />');
 5780:         }
 5781:     } else {
 5782:         my ($visible,$cansetvis,$vismsgs) = &visible_in_stdcat($cdom,$cnum,\%domconfig);
 5783:         if (ref($visactions) eq 'HASH') {
 5784:             if ($visible) {
 5785:                 $output .= '<p class="LC_info">'.$visactions->{'vis'}.'</p>';
 5786:            } else {
 5787:                 $output .= '<p class="LC_warning">'.$visactions->{'miss'}.'</p>'
 5788:                           .$visactions->{'yous'}.
 5789:                            '<p>'.$visactions->{'gen'}.'<br />'.$visactions->{'coca'};
 5790:                 if (ref($vismsgs) eq 'ARRAY') {
 5791:                     $output .= '<br />'.$visactions->{'make'}.'<ul>';
 5792:                     foreach my $item (@{$vismsgs}) {
 5793:                         $output .= '<li>'.$visactions->{$item}.'</li>';
 5794:                     }
 5795:                     $output .= '</ul>';
 5796:                 }
 5797:                 $output .= '</p>';
 5798:             }
 5799:         }
 5800:     }
 5801:     my $actionhref = '/adm/createuser';
 5802:     if ($context eq 'domain') {
 5803:         $actionhref = '/adm/modifycourse';
 5804:     }
 5805: 
 5806:     my %noedit;
 5807:     unless ($context eq 'domain') {
 5808:         %noedit = &get_noedit_fields($cdom,$cnum,$crstype,$row);
 5809:     }
 5810:     $output .= '<form name="'.$formname.'" method="post" action="'.$actionhref.'">'."\n".
 5811:                &Apache::lonhtmlcommon::start_pick_box();
 5812:     if (ref($row) eq 'ARRAY') {
 5813:         foreach my $item (@{$row}) {
 5814:             my $title = $item; 
 5815:             if (ref($lt) eq 'HASH') {
 5816:                 $title = $lt->{$item};
 5817:             }
 5818:             $output .= &Apache::lonhtmlcommon::row_title($title);
 5819:             if ($item eq 'types') {
 5820:                 my $curr_types;
 5821:                 if (ref($currsettings) eq 'HASH') {
 5822:                     $curr_types = $currsettings->{'selfenroll_types'};
 5823:                 }
 5824:                 if ($noedit{$item}) {
 5825:                     if ($curr_types eq '*') {
 5826:                         $output .= &mt('Any user in any domain');   
 5827:                     } else {
 5828:                         my @entries = split(/;/,$curr_types);
 5829:                         if (@entries > 0) {
 5830:                             $output .= '<ul>'; 
 5831:                             foreach my $entry (@entries) {
 5832:                                 my ($currdom,$typestr) = split(/:/,$entry);
 5833:                                 next if ($typestr eq '');
 5834:                                 my $domdesc = &Apache::lonnet::domain($currdom);
 5835:                                 my @currinsttypes = split(',',$typestr);
 5836:                                 my ($othertitle,$usertypes,$types) = 
 5837:                                     &Apache::loncommon::sorted_inst_types($currdom);
 5838:                                 if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 5839:                                     $usertypes->{'any'} = &mt('any user'); 
 5840:                                     if (keys(%{$usertypes}) > 0) {
 5841:                                         $usertypes->{'other'} = &mt('other users');
 5842:                                     }
 5843:                                     my @longinsttypes = map { $usertypes->{$_}; } @currinsttypes;
 5844:                                     $output .= '<li>'.$domdesc.':'.join(', ',@longinsttypes).'</li>';
 5845:                                  }
 5846:                             }
 5847:                             $output .= '</ul>';
 5848:                         } else {
 5849:                             $output .= &mt('None');
 5850:                         }
 5851:                     }
 5852:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 5853:                     next;
 5854:                 }
 5855:                 my $showdomdesc = 1;
 5856:                 my $includeempty = 1;
 5857:                 my $num = 0;
 5858:                 $output .= &Apache::loncommon::start_data_table().
 5859:                            &Apache::loncommon::start_data_table_row()
 5860:                            .'<td colspan="2"><span class="LC_nobreak"><label>'
 5861:                            .&mt('Any user in any domain:')
 5862:                            .'&nbsp;<input type="radio" name="selfenroll_all" value="1" ';
 5863:                 if ($curr_types eq '*') {
 5864:                     $output .= ' checked="checked" '; 
 5865:                 }
 5866:                 $output .= 'onchange="javascript:update_types('.
 5867:                            "'selfenroll_all'".');" />'.&mt('Yes').'</label>'.
 5868:                            '&nbsp;&nbsp;<input type="radio" name="selfenroll_all" value="0" ';
 5869:                 if ($curr_types ne '*') {
 5870:                     $output .= ' checked="checked" ';
 5871:                 }
 5872:                 $output .= ' onchange="javascript:update_types('.
 5873:                            "'selfenroll_all'".');"/>'.&mt('No').'</label></td>'.
 5874:                            &Apache::loncommon::end_data_table_row().
 5875:                            &Apache::loncommon::end_data_table().
 5876:                            &mt('Or').'<br />'.
 5877:                            &Apache::loncommon::start_data_table();
 5878:                 my %currdoms;
 5879:                 if ($curr_types eq '') {
 5880:                     $output .= &new_selfenroll_dom_row($cdom,'0');
 5881:                 } elsif ($curr_types ne '*') {
 5882:                     my @entries = split(/;/,$curr_types);
 5883:                     if (@entries > 0) {
 5884:                         foreach my $entry (@entries) {
 5885:                             my ($currdom,$typestr) = split(/:/,$entry);
 5886:                             $currdoms{$currdom} = 1;
 5887:                             my $domdesc = &Apache::lonnet::domain($currdom);
 5888:                             my @currinsttypes = split(',',$typestr);
 5889:                             $output .= &Apache::loncommon::start_data_table_row()
 5890:                                        .'<td valign="top"><span class="LC_nobreak">'.&mt('Domain:').'<b>'
 5891:                                        .'&nbsp;'.$domdesc.' ('.$currdom.')'
 5892:                                        .'</b><input type="hidden" name="selfenroll_dom_'.$num
 5893:                                        .'" value="'.$currdom.'" /></span><br />'
 5894:                                        .'<span class="LC_nobreak"><label><input type="checkbox" '
 5895:                                        .'name="selfenroll_delete" value="'.$num.'" onchange="javascript:update_types('."'selfenroll_delete','$num'".');" />'
 5896:                                        .&mt('Delete').'</label></span></td>';
 5897:                             $output .= '<td valign="top">&nbsp;&nbsp;'.&mt('User types:').'<br />'
 5898:                                        .&selfenroll_inst_types($num,$currdom,\@currinsttypes).'</td>'
 5899:                                        .&Apache::loncommon::end_data_table_row();
 5900:                             $num ++;
 5901:                         }
 5902:                     }
 5903:                 }
 5904:                 my $add_domtitle = &mt('Users in additional domain:');
 5905:                 if ($curr_types eq '*') { 
 5906:                     $add_domtitle = &mt('Users in specific domain:');
 5907:                 } elsif ($curr_types eq '') {
 5908:                     $add_domtitle = &mt('Users in other domain:');
 5909:                 }
 5910:                 $output .= &Apache::loncommon::start_data_table_row()
 5911:                            .'<td colspan="2"><span class="LC_nobreak">'.$add_domtitle.'</span><br />'
 5912:                            .&Apache::loncommon::select_dom_form('','selfenroll_newdom',
 5913:                                                                 $includeempty,$showdomdesc)
 5914:                            .'<input type="hidden" name="selfenroll_types_total" value="'.$num.'" />'
 5915:                            .'</td>'.&Apache::loncommon::end_data_table_row()
 5916:                            .&Apache::loncommon::end_data_table();
 5917:             } elsif ($item eq 'registered') {
 5918:                 my ($regon,$regoff);
 5919:                 my $registered;
 5920:                 if (ref($currsettings) eq 'HASH') {
 5921:                     $registered = $currsettings->{'selfenroll_registered'};
 5922:                 }
 5923:                 if ($noedit{$item}) {
 5924:                     if ($registered) {
 5925:                         $output .= &mt('Must be registered in course');
 5926:                     } else {
 5927:                         $output .= &mt('No requirement');
 5928:                     }
 5929:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 5930:                     next;
 5931:                 }
 5932:                 if ($registered) {
 5933:                     $regon = ' checked="checked" ';
 5934:                     $regoff = ' ';
 5935:                 } else {
 5936:                     $regon = ' ';
 5937:                     $regoff = ' checked="checked" ';
 5938:                 }
 5939:                 $output .= '<label>'.
 5940:                            '<input type="radio" name="selfenroll_registered" value="1"'.$regon.'/>'.
 5941:                            &mt('Yes').'</label>&nbsp;&nbsp;<label>'.
 5942:                            '<input type="radio" name="selfenroll_registered" value="0"'.$regoff.'/>'.
 5943:                            &mt('No').'</label>';
 5944:             } elsif ($item eq 'enroll_dates') {
 5945:                 my ($starttime,$endtime);
 5946:                 if (ref($currsettings) eq 'HASH') {
 5947:                     $starttime = $currsettings->{'selfenroll_start_date'};
 5948:                     $endtime = $currsettings->{'selfenroll_end_date'};
 5949:                     if ($starttime eq '') {
 5950:                         $starttime = $currsettings->{'default_enrollment_start_date'};
 5951:                     }
 5952:                     if ($endtime eq '') {
 5953:                         $endtime = $currsettings->{'default_enrollment_end_date'};
 5954:                     }
 5955:                 }
 5956:                 if ($noedit{$item}) {
 5957:                     $output .= &mt('From: [_1], to: [_2]',&Apache::lonlocal::locallocaltime($starttime),
 5958:                                                           &Apache::lonlocal::locallocaltime($endtime));
 5959:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 5960:                     next;
 5961:                 }
 5962:                 my $startform =
 5963:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_start_date',$starttime,
 5964:                                       undef,undef,undef,undef,undef,undef,undef,$nolink);
 5965:                 my $endform =
 5966:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_end_date',$endtime,
 5967:                                       undef,undef,undef,undef,undef,undef,undef,$nolink);
 5968:                 $output .= &selfenroll_date_forms($startform,$endform);
 5969:             } elsif ($item eq 'access_dates') {
 5970:                 my ($starttime,$endtime);
 5971:                 if (ref($currsettings) eq 'HASH') {
 5972:                     $starttime = $currsettings->{'selfenroll_start_access'};
 5973:                     $endtime = $currsettings->{'selfenroll_end_access'};
 5974:                     if ($starttime eq '') {
 5975:                         $starttime = $currsettings->{'default_enrollment_start_date'};
 5976:                     }
 5977:                     if ($endtime eq '') {
 5978:                         $endtime = $currsettings->{'default_enrollment_end_date'};
 5979:                     }
 5980:                 }
 5981:                 if ($noedit{$item}) {
 5982:                     $output .= &mt('From: [_1], to: [_2]',&Apache::lonlocal::locallocaltime($starttime),
 5983:                                                           &Apache::lonlocal::locallocaltime($endtime));
 5984:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 5985:                     next;
 5986:                 }
 5987:                 my $startform =
 5988:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_start_access',$starttime,
 5989:                                       undef,undef,undef,undef,undef,undef,undef,$nolink);
 5990:                 my $endform =
 5991:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_end_access',$endtime,
 5992:                                       undef,undef,undef,undef,undef,undef,undef,$nolink);
 5993:                 $output .= &selfenroll_date_forms($startform,$endform);
 5994:             } elsif ($item eq 'section') {
 5995:                 my $currsec;
 5996:                 if (ref($currsettings) eq 'HASH') {
 5997:                     $currsec = $currsettings->{'selfenroll_section'};
 5998:                 }
 5999:                 my %sections_count = &Apache::loncommon::get_sections($cdom,$cnum);
 6000:                 my $newsecval;
 6001:                 if ($currsec ne 'none' && $currsec ne '') {
 6002:                     if (!defined($sections_count{$currsec})) {
 6003:                         $newsecval = $currsec;
 6004:                     }
 6005:                 }
 6006:                 if ($noedit{$item}) {
 6007:                     if ($currsec ne '') {
 6008:                         $output .= $currsec;
 6009:                     } else {
 6010:                         $output .= &mt('No specific section');
 6011:                     }
 6012:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 6013:                     next;
 6014:                 }
 6015:                 my $sections_select = 
 6016:                     &Apache::lonuserutils::course_sections(\%sections_count,'st',$currsec);
 6017:                 $output .= '<table class="LC_createuser">'."\n".
 6018:                            '<tr class="LC_section_row">'."\n".
 6019:                            '<td align="center">'.&mt('Existing sections')."\n".
 6020:                            '<br />'.$sections_select.'</td><td align="center">'.
 6021:                            &mt('New section').'<br />'."\n".
 6022:                            '<input type="text" name="newsec" size="15" value="'.$newsecval.'" />'."\n".
 6023:                            '<input type="hidden" name="sections" value="" />'."\n".
 6024:                            '</td></tr></table>'."\n";
 6025:             } elsif ($item eq 'approval') {
 6026:                 my ($currnotified,$currapproval,%appchecked);
 6027:                 my %selfdescs = &Apache::lonuserutils::selfenroll_default_descs();
 6028:                 if (ref($currsettings) eq 'HASH') { 
 6029:                     $currnotified = $currsettings->{'selfenroll_notifylist'};
 6030:                     $currapproval = $currsettings->{'selfenroll_approval'};
 6031:                 }
 6032:                 if ($currapproval !~ /^[012]$/) {
 6033:                     $currapproval = 0;
 6034:                 }
 6035:                 if ($noedit{$item}) {
 6036:                     $output .=  $selfdescs{'approval'}{$currapproval}.
 6037:                                 '<br />'.&mt('(Set by Domain Coordinator)');
 6038:                     next;
 6039:                 }
 6040:                 $appchecked{$currapproval} = ' checked="checked"';
 6041:                 for my $i (0..2) {
 6042:                     $output .= '<label>'.
 6043:                                '<input type="radio" name="selfenroll_approval" value="'.$i.'"'.
 6044:                                $appchecked{$i}.' onclick="toggleNotify();" />'.$selfdescs{'approval'}{$i}.
 6045:                                '</label>'.('&nbsp;'x2);
 6046:                 }
 6047:                 my %advhash = &Apache::lonnet::get_course_adv_roles($cid,1);
 6048:                 my (@ccs,%notified);
 6049:                 my $ccrole = 'cc';
 6050:                 if ($crstype eq 'Community') {
 6051:                     $ccrole = 'co';
 6052:                 }
 6053:                 if ($advhash{$ccrole}) {
 6054:                     @ccs = split(/,/,$advhash{$ccrole});
 6055:                 }
 6056:                 if ($currnotified) {
 6057:                     foreach my $current (split(/,/,$currnotified)) {
 6058:                         $notified{$current} = 1;
 6059:                         if (!grep(/^\Q$current\E$/,@ccs)) {
 6060:                             push(@ccs,$current);
 6061:                         }
 6062:                     }
 6063:                 }
 6064:                 if (@ccs) {
 6065:                     my $style;
 6066:                     unless ($currapproval) {
 6067:                         $style = ' style="display: none;"'; 
 6068:                     }
 6069:                     $output .= '<br /><div id="notified"'.$style.'>'.
 6070:                                &mt('Personnel to be notified when an enrollment request needs approval, or has been approved:').'&nbsp;'.
 6071:                                &Apache::loncommon::start_data_table().
 6072:                                &Apache::loncommon::start_data_table_row();
 6073:                     my $count = 0;
 6074:                     my $numcols = 4;
 6075:                     foreach my $cc (sort(@ccs)) {
 6076:                         my $notifyon;
 6077:                         my ($ccuname,$ccudom) = split(/:/,$cc);
 6078:                         if ($notified{$cc}) {
 6079:                             $notifyon = ' checked="checked" ';
 6080:                         }
 6081:                         if ($count && !$count%$numcols) {
 6082:                             $output .= &Apache::loncommon::end_data_table_row().
 6083:                                        &Apache::loncommon::start_data_table_row()
 6084:                         }
 6085:                         $output .= '<td><span class="LC_nobreak"><label>'.
 6086:                                    '<input type="checkbox" name="selfenroll_notify"'.$notifyon.' value="'.$cc.'" />'.
 6087:                                    &Apache::loncommon::plainname($ccuname,$ccudom).
 6088:                                    '</label></span></td>';
 6089:                         $count ++;
 6090:                     }
 6091:                     my $rem = $count%$numcols;
 6092:                     if ($rem) {
 6093:                         my $emptycols = $numcols - $rem;
 6094:                         for (my $i=0; $i<$emptycols; $i++) { 
 6095:                             $output .= '<td>&nbsp;</td>';
 6096:                         }
 6097:                     }
 6098:                     $output .= &Apache::loncommon::end_data_table_row().
 6099:                                &Apache::loncommon::end_data_table().
 6100:                                '</div>';
 6101:                 }
 6102:             } elsif ($item eq 'limit') {
 6103:                 my ($crslimit,$selflimit,$nolimit,$currlim,$currcap);
 6104:                 if (ref($currsettings) eq 'HASH') {
 6105:                     $currlim = $currsettings->{'selfenroll_limit'};
 6106:                     $currcap = $currsettings->{'selfenroll_cap'};
 6107:                 }
 6108:                 if ($noedit{$item}) {
 6109:                     if (($currlim eq 'allstudents') || ($currlim eq 'selfenrolled')) {
 6110:                         if ($currlim eq 'allstudents') {
 6111:                             $output .= &mt('Limit by total students');
 6112:                         } elsif ($currlim eq 'selfenrolled') {
 6113:                             $output .= &mt('Limit by total self-enrolled students');
 6114:                         }
 6115:                         $output .= ' '.&mt('Maximum: [_1]',$currcap).
 6116:                                    '<br />'.&mt('(Set by Domain Coordinator)');
 6117:                     } else {
 6118:                         $output .= &mt('No limit').'<br />'.&mt('(Set by Domain Coordinator)');
 6119:                     }
 6120:                     next;
 6121:                 }
 6122:                 if ($currlim eq 'allstudents') {
 6123:                     $crslimit = ' checked="checked" ';
 6124:                     $selflimit = ' ';
 6125:                     $nolimit = ' ';
 6126:                 } elsif ($currlim eq 'selfenrolled') {
 6127:                     $crslimit = ' ';
 6128:                     $selflimit = ' checked="checked" ';
 6129:                     $nolimit = ' '; 
 6130:                 } else {
 6131:                     $crslimit = ' ';
 6132:                     $selflimit = ' ';
 6133:                     $nolimit = ' checked="checked" ';
 6134:                 }
 6135:                 $output .= '<table><tr><td><label>'.
 6136:                            '<input type="radio" name="selfenroll_limit" value="none"'.$nolimit.'/>'.
 6137:                            &mt('No limit').'</label></td><td><label>'.
 6138:                            '<input type="radio" name="selfenroll_limit" value="allstudents"'.$crslimit.'/>'.
 6139:                            &mt('Limit by total students').'</label></td><td><label>'.
 6140:                            '<input type="radio" name="selfenroll_limit" value="selfenrolled"'.$selflimit.'/>'.
 6141:                            &mt('Limit by total self-enrolled students').
 6142:                            '</td></tr><tr>'.
 6143:                            '<td>&nbsp;</td><td colspan="2"><span class="LC_nobreak">'.
 6144:                            ('&nbsp;'x3).&mt('Maximum number allowed: ').
 6145:                            '<input type="text" name="selfenroll_cap" size = "5" value="'.$currcap.'" /></td></tr></table>';
 6146:             }
 6147:             $output .= &Apache::lonhtmlcommon::row_closure(1);
 6148:         }
 6149:     }
 6150:     $output .= &Apache::lonhtmlcommon::end_pick_box().
 6151:                '<br /><input type="button" name="selfenrollconf" value="'
 6152:                .&mt('Save').'" onclick="validate_types(this.form);" />'
 6153:                .'<input type="hidden" name="action" value="selfenroll" />'
 6154:                .'<input type="hidden" name="state" value="done" />'."\n".
 6155:                $additional.'</form>';
 6156:     $r->print($output);
 6157:     return;
 6158: }
 6159: 
 6160: sub get_noedit_fields {
 6161:     my ($cdom,$cnum,$crstype,$row) = @_;
 6162:     my %noedit;
 6163:     if (ref($row) eq 'ARRAY') {
 6164:         my %settings = &Apache::lonnet::get('environment',['internal.coursecode','internal.textbook',
 6165:                                                            'internal.selfenrollmgrdc',
 6166:                                                            'internal.selfenrollmgrcc'],$cdom,$cnum);
 6167:         my $type = &Apache::lonuserutils::get_extended_type($cdom,$cnum,$crstype,\%settings);
 6168:         my (%specific_managebydc,%specific_managebycc,%default_managebydc);
 6169:         map { $specific_managebydc{$_} = 1; } (split(/,/,$settings{'internal.selfenrollmgrdc'}));
 6170:         map { $specific_managebycc{$_} = 1; } (split(/,/,$settings{'internal.selfenrollmgrcc'}));
 6171:         my %domdefaults = &Apache::lonnet::get_domain_defaults($cdom);
 6172:         map { $default_managebydc{$_} = 1; } (split(/,/,$domdefaults{$type.'selfenrolladmdc'}));
 6173: 
 6174:         foreach my $item (@{$row}) {
 6175:             next if ($specific_managebycc{$item});
 6176:             if (($specific_managebydc{$item}) || ($default_managebydc{$item})) {
 6177:                 $noedit{$item} = 1;
 6178:             }
 6179:         }
 6180:     }
 6181:     return %noedit;
 6182: } 
 6183: 
 6184: sub visible_in_stdcat {
 6185:     my ($cdom,$cnum,$domconf) = @_;
 6186:     my ($cathash,%settable,@vismsgs,$cansetvis,$visible);
 6187:     unless (ref($domconf) eq 'HASH') {
 6188:         return ($visible,$cansetvis,\@vismsgs);
 6189:     }
 6190:     if (ref($domconf->{'coursecategories'}) eq 'HASH') {
 6191:         if ($domconf->{'coursecategories'}{'togglecats'} eq 'crs') {
 6192:             $settable{'togglecats'} = 1;
 6193:         }
 6194:         if ($domconf->{'coursecategories'}{'categorize'} eq 'crs') {
 6195:             $settable{'categorize'} = 1;
 6196:         }
 6197:         $cathash = $domconf->{'coursecategories'}{'cats'};
 6198:     }
 6199:     if ($settable{'togglecats'} && $settable{'categorize'}) {
 6200:         $cansetvis = &mt('You are able to both assign a course category and choose to exclude this course from the catalog.');   
 6201:     } elsif ($settable{'togglecats'}) {
 6202:         $cansetvis = &mt('You are able to choose to exclude this course from the catalog, but only a Domain Coordinator may assign a course category.'); 
 6203:     } elsif ($settable{'categorize'}) {
 6204:         $cansetvis = &mt('You may assign a course category, but only a Domain Coordinator may choose to exclude this course from the catalog.');  
 6205:     } else {
 6206:         $cansetvis = &mt('Only a Domain Coordinator may assign a course category or choose to exclude this course from the catalog.'); 
 6207:     }
 6208:      
 6209:     my %currsettings =
 6210:         &Apache::lonnet::get('environment',['hidefromcat','categories','internal.coursecode'],
 6211:                              $cdom,$cnum);
 6212:     $visible = 0;
 6213:     if ($currsettings{'internal.coursecode'} ne '') {
 6214:         if (ref($domconf->{'coursecategories'}) eq 'HASH') {
 6215:             $cathash = $domconf->{'coursecategories'}{'cats'};
 6216:             if (ref($cathash) eq 'HASH') {
 6217:                 if ($cathash->{'instcode::0'} eq '') {
 6218:                     push(@vismsgs,'dc_addinst'); 
 6219:                 } else {
 6220:                     $visible = 1;
 6221:                 }
 6222:             } else {
 6223:                 $visible = 1;
 6224:             }
 6225:         } else {
 6226:             $visible = 1;
 6227:         }
 6228:     } else {
 6229:         if (ref($cathash) eq 'HASH') {
 6230:             if ($cathash->{'instcode::0'} ne '') {
 6231:                 push(@vismsgs,'dc_instcode');
 6232:             }
 6233:         } else {
 6234:             push(@vismsgs,'dc_instcode');
 6235:         }
 6236:     }
 6237:     if ($currsettings{'categories'} ne '') {
 6238:         my $cathash;
 6239:         if (ref($domconf->{'coursecategories'}) eq 'HASH') {
 6240:             $cathash = $domconf->{'coursecategories'}{'cats'};
 6241:             if (ref($cathash) eq 'HASH') {
 6242:                 if (keys(%{$cathash}) == 0) {
 6243:                     push(@vismsgs,'dc_catalog');
 6244:                 } elsif ((keys(%{$cathash}) == 1) && ($cathash->{'instcode::0'} ne '')) {
 6245:                     push(@vismsgs,'dc_categories');
 6246:                 } else {
 6247:                     my @currcategories = split('&',$currsettings{'categories'});
 6248:                     my $matched = 0;
 6249:                     foreach my $cat (@currcategories) {
 6250:                         if ($cathash->{$cat} ne '') {
 6251:                             $visible = 1;
 6252:                             $matched = 1;
 6253:                             last;
 6254:                         }
 6255:                     }
 6256:                     if (!$matched) {
 6257:                         if ($settable{'categorize'}) { 
 6258:                             push(@vismsgs,'chgcat');
 6259:                         } else {
 6260:                             push(@vismsgs,'dc_chgcat');
 6261:                         }
 6262:                     }
 6263:                 }
 6264:             }
 6265:         }
 6266:     } else {
 6267:         if (ref($cathash) eq 'HASH') {
 6268:             if ((keys(%{$cathash}) > 1) || 
 6269:                 (keys(%{$cathash}) == 1) && ($cathash->{'instcode::0'} eq '')) {
 6270:                 if ($settable{'categorize'}) {
 6271:                     push(@vismsgs,'addcat');
 6272:                 } else {
 6273:                     push(@vismsgs,'dc_addcat');
 6274:                 }
 6275:             }
 6276:         }
 6277:     }
 6278:     if ($currsettings{'hidefromcat'} eq 'yes') {
 6279:         $visible = 0;
 6280:         if ($settable{'togglecats'}) {
 6281:             unshift(@vismsgs,'unhide');
 6282:         } else {
 6283:             unshift(@vismsgs,'dc_unhide')
 6284:         }
 6285:     }
 6286:     return ($visible,$cansetvis,\@vismsgs);
 6287: }
 6288: 
 6289: sub cat_visibility {
 6290:     my %visactions = &Apache::lonlocal::texthash(
 6291:                    vis => 'This course/community currently appears in the Course/Community Catalog for this domain.',
 6292:                    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.',
 6293:                    miss => 'This course/community does not currently appear in the Course/Community Catalog for this domain.',
 6294:                    none => 'Display of a course catalog is disabled for this domain.',
 6295:                    yous => 'You should remedy this if you plan to allow self-enrollment, otherwise students will have difficulty finding this course.',
 6296:                    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.',
 6297:                    make => 'Make any changes to self-enrollment settings below, click "Save", then take action to include the course in the Catalog:',
 6298:                    take => 'Take the following action to ensure the course appears in the Catalog:',
 6299:                    dc_chgconf => 'Ask a domain coordinator to change the Catalog type for this domain.',
 6300:                    dc_setcode => 'Ask a domain coordinator to assign a six character code to the course',
 6301:                    dc_unhide  => 'Ask a domain coordinator to change the "Exclude from course catalog" setting.',
 6302:                    dc_addinst => 'Ask a domain coordinator to enable display the catalog of "Official courses (with institutional codes)".',
 6303:                    dc_instcode => 'Ask a domain coordinator to assign an institutional code (if this is an official course).',
 6304:                    dc_catalog  => 'Ask a domain coordinator to enable or create at least one course category in the domain.',
 6305:                    dc_categories => 'Ask a domain coordinator to create a hierarchy of categories and sub categories for courses in the domain.',
 6306:                    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',
 6307:                    dc_addcat => 'Ask a domain coordinator to assign a category to the course.',
 6308:     );
 6309:     $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>"');
 6310:     $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>"');
 6311:     $visactions{'addcat'} = &mt('Use [_1]Categorize course[_2] to assign a category to the course.','"<a href="/adm/courseprefs?phase=display&actions=courseinfo">','</a>"');
 6312:     return \%visactions;
 6313: }
 6314: 
 6315: sub new_selfenroll_dom_row {
 6316:     my ($newdom,$num) = @_;
 6317:     my $domdesc = &Apache::lonnet::domain($newdom);
 6318:     my $output;
 6319:     if ($domdesc ne '') {
 6320:         $output .= &Apache::loncommon::start_data_table_row()
 6321:                    .'<td valign="top"><span class="LC_nobreak">'.&mt('Domain:').'&nbsp;<b>'.$domdesc
 6322:                    .' ('.$newdom.')</b><input type="hidden" name="selfenroll_dom_'.$num
 6323:                    .'" value="'.$newdom.'" /></span><br />'
 6324:                    .'<span class="LC_nobreak"><label><input type="checkbox" '
 6325:                    .'name="selfenroll_activate" value="'.$num.'" '
 6326:                    .'onchange="javascript:update_types('
 6327:                    ."'selfenroll_activate','$num'".');" />'
 6328:                    .&mt('Activate').'</label></span></td>';
 6329:         my @currinsttypes;
 6330:         $output .= '<td>'.&mt('User types:').'<br />'
 6331:                    .&selfenroll_inst_types($num,$newdom,\@currinsttypes).'</td>'
 6332:                    .&Apache::loncommon::end_data_table_row();
 6333:     }
 6334:     return $output;
 6335: }
 6336: 
 6337: sub selfenroll_inst_types {
 6338:     my ($num,$currdom,$currinsttypes) = @_;
 6339:     my $output;
 6340:     my $numinrow = 4;
 6341:     my $count = 0;
 6342:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($currdom);
 6343:     my $othervalue = 'any';
 6344:     if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 6345:         if (keys(%{$usertypes}) > 0) {
 6346:             $othervalue = 'other';
 6347:         }
 6348:         $output .= '<table><tr>';
 6349:         foreach my $type (@{$types}) {
 6350:             if (($count > 0) && ($count%$numinrow == 0)) {
 6351:                 $output .= '</tr><tr>';
 6352:             }
 6353:             if (defined($usertypes->{$type})) {
 6354:                 my $esc_type = &escape($type);
 6355:                 $output .= '<td><span class="LC_nobreak"><label><input type = "checkbox" value="'.
 6356:                            $esc_type.'" ';
 6357:                 if (ref($currinsttypes) eq 'ARRAY') {
 6358:                     if (@{$currinsttypes} > 0) {
 6359:                         if (grep(/^any$/,@{$currinsttypes})) {
 6360:                             $output .= 'checked="checked"';
 6361:                         } elsif (grep(/^\Q$esc_type\E$/,@{$currinsttypes})) {
 6362:                             $output .= 'checked="checked"';
 6363:                         }
 6364:                     } else {
 6365:                         $output .= 'checked="checked"';
 6366:                     }
 6367:                 }
 6368:                 $output .= ' name="selfenroll_types_'.$num.'" />'.$usertypes->{$type}.'</label></span></td>';
 6369:             }
 6370:             $count ++;
 6371:         }
 6372:         if (($count > 0) && ($count%$numinrow == 0)) {
 6373:             $output .= '</tr><tr>';
 6374:         }
 6375:         $output .= '<td><span class="LC_nobreak"><label><input type = "checkbox" value="'.$othervalue.'"';
 6376:         if (ref($currinsttypes) eq 'ARRAY') {
 6377:             if (@{$currinsttypes} > 0) {
 6378:                 if (grep(/^any$/,@{$currinsttypes})) { 
 6379:                     $output .= ' checked="checked"';
 6380:                 } elsif ($othervalue eq 'other') {
 6381:                     if (grep(/^\Q$othervalue\E$/,@{$currinsttypes})) {
 6382:                         $output .= ' checked="checked"';
 6383:                     }
 6384:                 }
 6385:             } else {
 6386:                 $output .= ' checked="checked"';
 6387:             }
 6388:         } else {
 6389:             $output .= ' checked="checked"';
 6390:         }
 6391:         $output .= ' name="selfenroll_types_'.$num.'" />'.$othertitle.'</label></span></td></tr></table>';
 6392:     }
 6393:     return $output;
 6394: }
 6395: 
 6396: sub selfenroll_date_forms {
 6397:     my ($startform,$endform) = @_;
 6398:     my $output .= &Apache::lonhtmlcommon::start_pick_box()."\n".
 6399:                   &Apache::lonhtmlcommon::row_title(&mt('Start date'),
 6400:                                                     'LC_oddrow_value')."\n".
 6401:                   $startform."\n".
 6402:                   &Apache::lonhtmlcommon::row_closure(1).
 6403:                   &Apache::lonhtmlcommon::row_title(&mt('End date'),
 6404:                                                    'LC_oddrow_value')."\n".
 6405:                   $endform."\n".
 6406:                   &Apache::lonhtmlcommon::row_closure(1).
 6407:                   &Apache::lonhtmlcommon::end_pick_box();
 6408:     return $output;
 6409: }
 6410: 
 6411: sub print_userchangelogs_display {
 6412:     my ($r,$context,$permission) = @_;
 6413:     my $formname = 'rolelog';
 6414:     my ($username,$domain,$crstype,%roleslog);
 6415:     if ($context eq 'domain') {
 6416:         $domain = $env{'request.role.domain'};
 6417:         %roleslog=&Apache::lonnet::dump_dom('nohist_rolelog',$domain);
 6418:     } else {
 6419:         if ($context eq 'course') { 
 6420:             $domain = $env{'course.'.$env{'request.course.id'}.'.domain'};
 6421:             $username = $env{'course.'.$env{'request.course.id'}.'.num'};
 6422:             $crstype = &Apache::loncommon::course_type();
 6423:             my %saveable_parameters = ('show' => 'scalar',);
 6424:             &Apache::loncommon::store_course_settings('roles_log',
 6425:                                                       \%saveable_parameters);
 6426:             &Apache::loncommon::restore_course_settings('roles_log',
 6427:                                                         \%saveable_parameters);
 6428:         } elsif ($context eq 'author') {
 6429:             $domain = $env{'user.domain'}; 
 6430:             if ($env{'request.role'} =~ m{^au\./\Q$domain\E/$}) {
 6431:                 $username = $env{'user.name'};
 6432:             } else {
 6433:                 undef($domain);
 6434:             }
 6435:         }
 6436:         if ($domain ne '' && $username ne '') { 
 6437:             %roleslog=&Apache::lonnet::dump('nohist_rolelog',$domain,$username);
 6438:         }
 6439:     }
 6440:     if ((keys(%roleslog))[0]=~/^error\:/) { undef(%roleslog); }
 6441: 
 6442:     # set defaults
 6443:     my $now = time();
 6444:     my $defstart = $now - (7*24*3600); #7 days ago 
 6445:     my %defaults = (
 6446:                      page               => '1',
 6447:                      show               => '10',
 6448:                      role               => 'any',
 6449:                      chgcontext         => 'any',
 6450:                      rolelog_start_date => $defstart,
 6451:                      rolelog_end_date   => $now,
 6452:                    );
 6453:     my $more_records = 0;
 6454: 
 6455:     # set current
 6456:     my %curr;
 6457:     foreach my $item ('show','page','role','chgcontext') {
 6458:         $curr{$item} = $env{'form.'.$item};
 6459:     }
 6460:     my ($startdate,$enddate) = 
 6461:         &Apache::lonuserutils::get_dates_from_form('rolelog_start_date','rolelog_end_date');
 6462:     $curr{'rolelog_start_date'} = $startdate;
 6463:     $curr{'rolelog_end_date'} = $enddate;
 6464:     foreach my $key (keys(%defaults)) {
 6465:         if ($curr{$key} eq '') {
 6466:             $curr{$key} = $defaults{$key};
 6467:         }
 6468:     }
 6469:     my (%whodunit,%changed,$version);
 6470:     ($version) = ($r->dir_config('lonVersion') =~ /^([\d\.]+)\-/);
 6471:     my ($minshown,$maxshown);
 6472:     $minshown = 1;
 6473:     my $count = 0;
 6474:     if ($curr{'show'} ne &mt('all')) { 
 6475:         $maxshown = $curr{'page'} * $curr{'show'};
 6476:         if ($curr{'page'} > 1) {
 6477:             $minshown = 1 + ($curr{'page'} - 1) * $curr{'show'};
 6478:         }
 6479:     }
 6480: 
 6481:     # Form Header
 6482:     $r->print('<form action="/adm/createuser" method="post" name="'.$formname.'">'.
 6483:               &role_display_filter($context,$formname,$domain,$username,\%curr,
 6484:                                    $version,$crstype));
 6485: 
 6486:     # Create navigation
 6487:     my ($nav_script,$nav_links) = &userlogdisplay_nav($formname,\%curr,$more_records);
 6488:     my $showntableheader = 0;
 6489: 
 6490:     # Table Header
 6491:     my $tableheader = 
 6492:         &Apache::loncommon::start_data_table_header_row()
 6493:        .'<th>&nbsp;</th>'
 6494:        .'<th>'.&mt('When').'</th>'
 6495:        .'<th>'.&mt('Who made the change').'</th>'
 6496:        .'<th>'.&mt('Changed User').'</th>'
 6497:        .'<th>'.&mt('Role').'</th>';
 6498: 
 6499:     if ($context eq 'course') {
 6500:         $tableheader .= '<th>'.&mt('Section').'</th>';
 6501:     }
 6502:     $tableheader .=
 6503:         '<th>'.&mt('Context').'</th>'
 6504:        .'<th>'.&mt('Start').'</th>'
 6505:        .'<th>'.&mt('End').'</th>'
 6506:        .&Apache::loncommon::end_data_table_header_row();
 6507: 
 6508:     # Display user change log data
 6509:     foreach my $id (sort { $roleslog{$b}{'exe_time'}<=>$roleslog{$a}{'exe_time'} } (keys(%roleslog))) {
 6510:         next if (($roleslog{$id}{'exe_time'} < $curr{'rolelog_start_date'}) ||
 6511:                  ($roleslog{$id}{'exe_time'} > $curr{'rolelog_end_date'}));
 6512:         if ($curr{'show'} ne &mt('all')) {
 6513:             if ($count >= $curr{'page'} * $curr{'show'}) {
 6514:                 $more_records = 1;
 6515:                 last;
 6516:             }
 6517:         }
 6518:         if ($curr{'role'} ne 'any') {
 6519:             next if ($roleslog{$id}{'logentry'}{'role'} ne $curr{'role'}); 
 6520:         }
 6521:         if ($curr{'chgcontext'} ne 'any') {
 6522:             if ($curr{'chgcontext'} eq 'selfenroll') {
 6523:                 next if (!$roleslog{$id}{'logentry'}{'selfenroll'});
 6524:             } else {
 6525:                 next if ($roleslog{$id}{'logentry'}{'context'} ne $curr{'chgcontext'});
 6526:             }
 6527:         }
 6528:         $count ++;
 6529:         next if ($count < $minshown);
 6530:         unless ($showntableheader) {
 6531:             $r->print($nav_script
 6532:                      .$nav_links
 6533:                      .&Apache::loncommon::start_data_table()
 6534:                      .$tableheader);
 6535:             $r->rflush();
 6536:             $showntableheader = 1;
 6537:         }
 6538:         if ($whodunit{$roleslog{$id}{'exe_uname'}.':'.$roleslog{$id}{'exe_udom'}} eq '') {
 6539:             $whodunit{$roleslog{$id}{'exe_uname'}.':'.$roleslog{$id}{'exe_udom'}} =
 6540:                 &Apache::loncommon::plainname($roleslog{$id}{'exe_uname'},$roleslog{$id}{'exe_udom'});
 6541:         }
 6542:         if ($changed{$roleslog{$id}{'uname'}.':'.$roleslog{$id}{'udom'}} eq '') {
 6543:             $changed{$roleslog{$id}{'uname'}.':'.$roleslog{$id}{'udom'}} =
 6544:                 &Apache::loncommon::plainname($roleslog{$id}{'uname'},$roleslog{$id}{'udom'});
 6545:         }
 6546:         my $sec = $roleslog{$id}{'logentry'}{'section'};
 6547:         if ($sec eq '') {
 6548:             $sec = &mt('None');
 6549:         }
 6550:         my ($rolestart,$roleend);
 6551:         if ($roleslog{$id}{'delflag'}) {
 6552:             $rolestart = &mt('deleted');
 6553:             $roleend = &mt('deleted');
 6554:         } else {
 6555:             $rolestart = $roleslog{$id}{'logentry'}{'start'};
 6556:             $roleend = $roleslog{$id}{'logentry'}{'end'};
 6557:             if ($rolestart eq '' || $rolestart == 0) {
 6558:                 $rolestart = &mt('No start date'); 
 6559:             } else {
 6560:                 $rolestart = &Apache::lonlocal::locallocaltime($rolestart);
 6561:             }
 6562:             if ($roleend eq '' || $roleend == 0) { 
 6563:                 $roleend = &mt('No end date');
 6564:             } else {
 6565:                 $roleend = &Apache::lonlocal::locallocaltime($roleend);
 6566:             }
 6567:         }
 6568:         my $chgcontext = $roleslog{$id}{'logentry'}{'context'};
 6569:         if ($roleslog{$id}{'logentry'}{'selfenroll'}) {
 6570:             $chgcontext = 'selfenroll';
 6571:         }
 6572:         my %lt = &rolechg_contexts($context,$crstype);
 6573:         if ($chgcontext ne '' && $lt{$chgcontext} ne '') {
 6574:             $chgcontext = $lt{$chgcontext};
 6575:         }
 6576:         $r->print(
 6577:             &Apache::loncommon::start_data_table_row()
 6578:            .'<td>'.$count.'</td>'
 6579:            .'<td>'.&Apache::lonlocal::locallocaltime($roleslog{$id}{'exe_time'}).'</td>'
 6580:            .'<td>'.$whodunit{$roleslog{$id}{'exe_uname'}.':'.$roleslog{$id}{'exe_udom'}}.'</td>'
 6581:            .'<td>'.$changed{$roleslog{$id}{'uname'}.':'.$roleslog{$id}{'udom'}}.'</td>'
 6582:            .'<td>'.&Apache::lonnet::plaintext($roleslog{$id}{'logentry'}{'role'},$crstype).'</td>');
 6583:         if ($context eq 'course') { 
 6584:             $r->print('<td>'.$sec.'</td>');
 6585:         }
 6586:         $r->print(
 6587:             '<td>'.$chgcontext.'</td>'
 6588:            .'<td>'.$rolestart.'</td>'
 6589:            .'<td>'.$roleend.'</td>'
 6590:            .&Apache::loncommon::end_data_table_row()."\n");
 6591:     }
 6592: 
 6593:     if ($showntableheader) { # Table footer, if content displayed above
 6594:         $r->print(&Apache::loncommon::end_data_table()
 6595:                  .$nav_links);
 6596:     } else { # No content displayed above
 6597:         $r->print('<p class="LC_info">'
 6598:                  .&mt('There are no records to display.')
 6599:                  .'</p>'
 6600:         );
 6601:     }
 6602: 
 6603:     # Form Footer
 6604:     $r->print( 
 6605:         '<input type="hidden" name="page" value="'.$curr{'page'}.'" />'
 6606:        .'<input type="hidden" name="action" value="changelogs" />'
 6607:        .'</form>');
 6608:     return;
 6609: }
 6610: 
 6611: sub userlogdisplay_nav {
 6612:     my ($formname,$curr,$more_records) = @_;
 6613:     my ($nav_script,$nav_links);
 6614:     if (ref($curr) eq 'HASH') {
 6615:         # Create Navigation:
 6616:         # Navigation Script
 6617:         $nav_script = <<"ENDSCRIPT";
 6618: <script type="text/javascript">
 6619: // <![CDATA[
 6620: function chgPage(caller) {
 6621:     if (caller == 'previous') {
 6622:         document.$formname.page.value --;
 6623:     }
 6624:     if (caller == 'next') {
 6625:         document.$formname.page.value ++;
 6626:     }
 6627:     document.$formname.submit();
 6628:     return;
 6629: }
 6630: // ]]>
 6631: </script>
 6632: ENDSCRIPT
 6633:         # Navigation Buttons
 6634:         $nav_links = '<p>';
 6635:         if (($curr->{'page'} > 1) || ($more_records)) {
 6636:             if ($curr->{'page'} > 1) {
 6637:                 $nav_links .= '<input type="button"'
 6638:                              .' onclick="javascript:chgPage('."'previous'".');"'
 6639:                              .' value="'.&mt('Previous [_1] changes',$curr->{'show'})
 6640:                              .'" /> ';
 6641:             }
 6642:             if ($more_records) {
 6643:                 $nav_links .= '<input type="button"'
 6644:                              .' onclick="javascript:chgPage('."'next'".');"'
 6645:                              .' value="'.&mt('Next [_1] changes',$curr->{'show'})
 6646:                              .'" />';
 6647:             }
 6648:         }
 6649:         $nav_links .= '</p>';
 6650:     }
 6651:     return ($nav_script,$nav_links);
 6652: }
 6653: 
 6654: sub role_display_filter {
 6655:     my ($context,$formname,$cdom,$cnum,$curr,$version,$crstype) = @_;
 6656:     my $lctype;
 6657:     if ($context eq 'course') {
 6658:         $lctype = lc($crstype);
 6659:     }
 6660:     my $nolink = 1;
 6661:     my $output = '<table><tr><td valign="top">'.
 6662:                  '<span class="LC_nobreak"><b>'.&mt('Changes/page:').'</b></span><br />'.
 6663:                  &Apache::lonmeta::selectbox('show',$curr->{'show'},undef,
 6664:                                               (&mt('all'),5,10,20,50,100,1000,10000)).
 6665:                  '</td><td>&nbsp;&nbsp;</td>';
 6666:     my $startform =
 6667:         &Apache::lonhtmlcommon::date_setter($formname,'rolelog_start_date',
 6668:                                             $curr->{'rolelog_start_date'},undef,
 6669:                                             undef,undef,undef,undef,undef,undef,$nolink);
 6670:     my $endform =
 6671:         &Apache::lonhtmlcommon::date_setter($formname,'rolelog_end_date',
 6672:                                             $curr->{'rolelog_end_date'},undef,
 6673:                                             undef,undef,undef,undef,undef,undef,$nolink);
 6674:     my %lt = &rolechg_contexts($context,$crstype);
 6675:     $output .= '<td valign="top"><b>'.&mt('Window during which changes occurred:').'</b><br />'.
 6676:                '<table><tr><td>'.&mt('After:').
 6677:                '</td><td>'.$startform.'</td></tr>'.
 6678:                '<tr><td>'.&mt('Before:').'</td>'.
 6679:                '<td>'.$endform.'</td></tr></table>'.
 6680:                '</td>'.
 6681:                '<td>&nbsp;&nbsp;</td>'.
 6682:                '<td valign="top"><b>'.&mt('Role:').'</b><br />'.
 6683:                '<select name="role"><option value="any"';
 6684:     if ($curr->{'role'} eq 'any') {
 6685:         $output .= ' selected="selected"';
 6686:     }
 6687:     $output .=  '>'.&mt('Any').'</option>'."\n";
 6688:     my @roles = &Apache::lonuserutils::roles_by_context($context,1,$crstype);
 6689:     foreach my $role (@roles) {
 6690:         my $plrole;
 6691:         if ($role eq 'cr') {
 6692:             $plrole = &mt('Custom Role');
 6693:         } else {
 6694:             $plrole=&Apache::lonnet::plaintext($role,$crstype);
 6695:         }
 6696:         my $selstr = '';
 6697:         if ($role eq $curr->{'role'}) {
 6698:             $selstr = ' selected="selected"';
 6699:         }
 6700:         $output .= '  <option value="'.$role.'"'.$selstr.'>'.$plrole.'</option>';
 6701:     }
 6702:     $output .= '</select></td>'.
 6703:                '<td>&nbsp;&nbsp;</td>'.
 6704:                '<td valign="top"><b>'.
 6705:                &mt('Context:').'</b><br /><select name="chgcontext">';
 6706:     my @posscontexts;
 6707:     if ($context eq 'course') {
 6708:         @posscontexts = ('any','automated','updatenow','createcourse','course','domain','selfenroll','requestcourses');
 6709:     } elsif ($context eq 'domain') {
 6710:         @posscontexts = ('any','domain','requestauthor','domconfig','server');
 6711:     } else {
 6712:         @posscontexts = ('any','author','domain');
 6713:     } 
 6714:     foreach my $chgtype (@posscontexts) {
 6715:         my $selstr = '';
 6716:         if ($curr->{'chgcontext'} eq $chgtype) {
 6717:             $selstr = ' selected="selected"';
 6718:         }
 6719:         if ($context eq 'course') {
 6720:             if (($chgtype eq 'automated') || ($chgtype eq 'updatenow')) {
 6721:                 next if (!&Apache::lonnet::auto_run($cnum,$cdom));
 6722:             }
 6723:         }
 6724:         $output .= '<option value="'.$chgtype.'"'.$selstr.'>'.$lt{$chgtype}.'</option>'."\n";
 6725:     }
 6726:     $output .= '</select></td>'
 6727:               .'</tr></table>';
 6728: 
 6729:     # Update Display button
 6730:     $output .= '<p>'
 6731:               .'<input type="submit" value="'.&mt('Update Display').'" />'
 6732:               .'</p>';
 6733: 
 6734:     # Server version info
 6735:     my $needsrev = '2.11.0';
 6736:     if ($context eq 'course') {
 6737:         $needsrev = '2.7.0';
 6738:     }
 6739:     
 6740:     $output .= '<p class="LC_info">'
 6741:               .&mt('Only changes made from servers running LON-CAPA [_1] or later are displayed.'
 6742:                   ,$needsrev);
 6743:     if ($version) {
 6744:         $output .= ' '.&mt('This LON-CAPA server is version [_1]',$version);
 6745:     }
 6746:     $output .= '</p><hr />';
 6747:     return $output;
 6748: }
 6749: 
 6750: sub rolechg_contexts {
 6751:     my ($context,$crstype) = @_;
 6752:     my %lt;
 6753:     if ($context eq 'course') {
 6754:         %lt = &Apache::lonlocal::texthash (
 6755:                                              any          => 'Any',
 6756:                                              automated    => 'Automated Enrollment',
 6757:                                              updatenow    => 'Roster Update',
 6758:                                              createcourse => 'Course Creation',
 6759:                                              course       => 'User Management in course',
 6760:                                              domain       => 'User Management in domain',
 6761:                                              selfenroll   => 'Self-enrolled',
 6762:                                              requestcourses => 'Course Request',
 6763:                                          );
 6764:         if ($crstype eq 'Community') {
 6765:             $lt{'createcourse'} = &mt('Community Creation');
 6766:             $lt{'course'} = &mt('User Management in community');
 6767:             $lt{'requestcourses'} = &mt('Community Request');
 6768:         }
 6769:     } elsif ($context eq 'domain') {
 6770:         %lt = &Apache::lonlocal::texthash (
 6771:                                              any           => 'Any',
 6772:                                              domain        => 'User Management in domain',
 6773:                                              requestauthor => 'Authoring Request',
 6774:                                              server        => 'Command line script (DC role)',
 6775:                                              domconfig     => 'Self-enrolled',
 6776:                                          );
 6777:     } else {
 6778:         %lt = &Apache::lonlocal::texthash (
 6779:                                              any    => 'Any',
 6780:                                              domain => 'User Management in domain',
 6781:                                              author => 'User Management by author',
 6782:                                          );
 6783:     } 
 6784:     return %lt;
 6785: }
 6786: 
 6787: #-------------------------------------------------- functions for &phase_two
 6788: sub user_search_result {
 6789:     my ($context,$srch) = @_;
 6790:     my %allhomes;
 6791:     my %inst_matches;
 6792:     my %srch_results;
 6793:     my ($response,$currstate,$forcenewuser,$dirsrchres);
 6794:     $srch->{'srchterm'} =~ s/\s+/ /g;
 6795:     if ($srch->{'srchby'} !~ /^(uname|lastname|lastfirst)$/) {
 6796:         $response = &mt('Invalid search.');
 6797:     }
 6798:     if ($srch->{'srchin'} !~ /^(crs|dom|alc|instd)$/) {
 6799:         $response = &mt('Invalid search.');
 6800:     }
 6801:     if ($srch->{'srchtype'} !~ /^(exact|contains|begins)$/) {
 6802:         $response = &mt('Invalid search.');
 6803:     }
 6804:     if ($srch->{'srchterm'} eq '') {
 6805:         $response = &mt('You must enter a search term.');
 6806:     }
 6807:     if ($srch->{'srchterm'} =~ /^\s+$/) {
 6808:         $response = &mt('Your search term must contain more than just spaces.');
 6809:     }
 6810:     if (($srch->{'srchin'} eq 'dom') || ($srch->{'srchin'} eq 'instd')) {
 6811:         if (($srch->{'srchdomain'} eq '') || 
 6812: 	    ! (&Apache::lonnet::domain($srch->{'srchdomain'}))) {
 6813:             $response = &mt('You must specify a valid domain when searching in a domain or institutional directory.')
 6814:         }
 6815:     }
 6816:     if (($srch->{'srchin'} eq 'dom') || ($srch->{'srchin'} eq 'crs') ||
 6817:         ($srch->{'srchin'} eq 'alc')) {
 6818:         if ($srch->{'srchby'} eq 'uname') {
 6819:             my $unamecheck = $srch->{'srchterm'};
 6820:             if ($srch->{'srchtype'} eq 'contains') {
 6821:                 if ($unamecheck !~ /^\w/) {
 6822:                     $unamecheck = 'a'.$unamecheck; 
 6823:                 }
 6824:             }
 6825:             if ($unamecheck !~ /^$match_username$/) {
 6826:                 $response = &mt('You must specify a valid username. Only the following are allowed: letters numbers - . @');
 6827:             }
 6828:         }
 6829:     }
 6830:     if ($response ne '') {
 6831:         $response = '<span class="LC_warning">'.$response.'</span><br />';
 6832:     }
 6833:     if ($srch->{'srchin'} eq 'instd') {
 6834:         my $instd_chk = &instdirectorysrch_check($srch);
 6835:         if ($instd_chk ne 'ok') {
 6836:             my $domd_chk = &domdirectorysrch_check($srch);
 6837:             $response .= '<span class="LC_warning">'.$instd_chk.'</span><br />';
 6838:             if ($domd_chk eq 'ok') {
 6839:                 $response .= &mt('You may want to search in the LON-CAPA domain instead of the institutional directory.');
 6840:             }
 6841:             $response .= '<br /><br />';
 6842:         }
 6843:     } else {
 6844:         unless (($context eq 'requestcrs') && ($srch->{'srchtype'} eq 'exact')) {
 6845:             my $domd_chk = &domdirectorysrch_check($srch);
 6846:             if ($domd_chk ne 'ok') {
 6847:                 my $instd_chk = &instdirectorysrch_check($srch);
 6848:                 $response .= '<span class="LC_warning">'.$domd_chk.'</span><br />';
 6849:                 if ($instd_chk eq 'ok') {
 6850:                     $response .= &mt('You may want to search in the institutional directory instead of the LON-CAPA domain.');
 6851:                 }
 6852:                 $response .= '<br /><br />';
 6853:             }
 6854:         }
 6855:     }
 6856:     if ($response ne '') {
 6857:         return ($currstate,$response);
 6858:     }
 6859:     if ($srch->{'srchby'} eq 'uname') {
 6860:         if (($srch->{'srchin'} eq 'dom') || ($srch->{'srchin'} eq 'crs')) {
 6861:             if ($env{'form.forcenew'}) {
 6862:                 if ($srch->{'srchdomain'} ne $env{'request.role.domain'}) {
 6863:                     my $uhome=&Apache::lonnet::homeserver($srch->{'srchterm'},$srch->{'srchdomain'});
 6864:                     if ($uhome eq 'no_host') {
 6865:                         my $domdesc = &Apache::lonnet::domain($env{'request.role.domain'},'description');
 6866:                         my $showdom = &display_domain_info($env{'request.role.domain'});
 6867:                         $response = &mt('New users can only be created in the domain to which your current role belongs - [_1].',$showdom);
 6868:                     } else {
 6869:                         $currstate = 'modify';
 6870:                     }
 6871:                 } else {
 6872:                     $currstate = 'modify';
 6873:                 }
 6874:             } else {
 6875:                 if ($srch->{'srchin'} eq 'dom') {
 6876:                     if ($srch->{'srchtype'} eq 'exact') {
 6877:                         my $uhome=&Apache::lonnet::homeserver($srch->{'srchterm'},$srch->{'srchdomain'});
 6878:                         if ($uhome eq 'no_host') {
 6879:                             ($currstate,$response,$forcenewuser) =
 6880:                                 &build_search_response($context,$srch,%srch_results);
 6881:                         } else {
 6882:                             $currstate = 'modify';
 6883:                             my $uname = $srch->{'srchterm'};
 6884:                             my $udom = $srch->{'srchdomain'};
 6885:                             $srch_results{$uname.':'.$udom} =
 6886:                                 { &Apache::lonnet::get('environment',
 6887:                                                        ['firstname',
 6888:                                                         'lastname',
 6889:                                                         'permanentemail'],
 6890:                                                          $udom,$uname)
 6891:                                 };
 6892:                         }
 6893:                     } else {
 6894:                         %srch_results = &Apache::lonnet::usersearch($srch);
 6895:                         ($currstate,$response,$forcenewuser) =
 6896:                             &build_search_response($context,$srch,%srch_results);
 6897:                     }
 6898:                 } else {
 6899:                     my $courseusers = &get_courseusers();
 6900:                     if ($srch->{'srchtype'} eq 'exact') {
 6901:                         if (exists($courseusers->{$srch->{'srchterm'}.':'.$srch->{'srchdomain'}})) {
 6902:                             $currstate = 'modify';
 6903:                         } else {
 6904:                             ($currstate,$response,$forcenewuser) =
 6905:                                 &build_search_response($context,$srch,%srch_results);
 6906:                         }
 6907:                     } else {
 6908:                         foreach my $user (keys(%$courseusers)) {
 6909:                             my ($cuname,$cudomain) = split(/:/,$user);
 6910:                             if ($cudomain eq $srch->{'srchdomain'}) {
 6911:                                 my $matched = 0;
 6912:                                 if ($srch->{'srchtype'} eq 'begins') {
 6913:                                     if ($cuname =~ /^\Q$srch->{'srchterm'}\E/i) {
 6914:                                         $matched = 1;
 6915:                                     }
 6916:                                 } else {
 6917:                                     if ($cuname =~ /\Q$srch->{'srchterm'}\E/i) {
 6918:                                         $matched = 1;
 6919:                                     }
 6920:                                 }
 6921:                                 if ($matched) {
 6922:                                     $srch_results{$user} = 
 6923: 					{&Apache::lonnet::get('environment',
 6924: 							     ['firstname',
 6925: 							      'lastname',
 6926: 							      'permanentemail'],
 6927: 							      $cudomain,$cuname)};
 6928:                                 }
 6929:                             }
 6930:                         }
 6931:                         ($currstate,$response,$forcenewuser) =
 6932:                             &build_search_response($context,$srch,%srch_results);
 6933:                     }
 6934:                 }
 6935:             }
 6936:         } elsif ($srch->{'srchin'} eq 'alc') {
 6937:             $currstate = 'query';
 6938:         } elsif ($srch->{'srchin'} eq 'instd') {
 6939:             ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query($srch);
 6940:             if ($dirsrchres eq 'ok') {
 6941:                 ($currstate,$response,$forcenewuser) = 
 6942:                     &build_search_response($context,$srch,%srch_results);
 6943:             } else {
 6944:                 my $showdom = &display_domain_info($srch->{'srchdomain'});
 6945:                 $response = '<span class="LC_warning">'.
 6946:                     &mt('Institutional directory search is not available in domain: [_1]',$showdom).
 6947:                     '</span><br />'.
 6948:                     &mt('You may want to search in the LON-CAPA domain instead of the institutional directory.').
 6949:                     '<br /><br />'; 
 6950:             }
 6951:         }
 6952:     } else {
 6953:         if ($srch->{'srchin'} eq 'dom') {
 6954:             %srch_results = &Apache::lonnet::usersearch($srch);
 6955:             ($currstate,$response,$forcenewuser) = 
 6956:                 &build_search_response($context,$srch,%srch_results); 
 6957:         } elsif ($srch->{'srchin'} eq 'crs') {
 6958:             my $courseusers = &get_courseusers(); 
 6959:             foreach my $user (keys(%$courseusers)) {
 6960:                 my ($uname,$udom) = split(/:/,$user);
 6961:                 my %names = &Apache::loncommon::getnames($uname,$udom);
 6962:                 my %emails = &Apache::loncommon::getemails($uname,$udom);
 6963:                 if ($srch->{'srchby'} eq 'lastname') {
 6964:                     if ((($srch->{'srchtype'} eq 'exact') && 
 6965:                          ($names{'lastname'} eq $srch->{'srchterm'})) || 
 6966:                         (($srch->{'srchtype'} eq 'begins') &&
 6967:                          ($names{'lastname'} =~ /^\Q$srch->{'srchterm'}\E/i)) ||
 6968:                         (($srch->{'srchtype'} eq 'contains') &&
 6969:                          ($names{'lastname'} =~ /\Q$srch->{'srchterm'}\E/i))) {
 6970:                         $srch_results{$user} = {firstname => $names{'firstname'},
 6971:                                             lastname => $names{'lastname'},
 6972:                                             permanentemail => $emails{'permanentemail'},
 6973:                                            };
 6974:                     }
 6975:                 } elsif ($srch->{'srchby'} eq 'lastfirst') {
 6976:                     my ($srchlast,$srchfirst) = split(/,/,$srch->{'srchterm'});
 6977:                     $srchlast =~ s/\s+$//;
 6978:                     $srchfirst =~ s/^\s+//;
 6979:                     if ($srch->{'srchtype'} eq 'exact') {
 6980:                         if (($names{'lastname'} eq $srchlast) &&
 6981:                             ($names{'firstname'} eq $srchfirst)) {
 6982:                             $srch_results{$user} = {firstname => $names{'firstname'},
 6983:                                                 lastname => $names{'lastname'},
 6984:                                                 permanentemail => $emails{'permanentemail'},
 6985: 
 6986:                                            };
 6987:                         }
 6988:                     } elsif ($srch->{'srchtype'} eq 'begins') {
 6989:                         if (($names{'lastname'} =~ /^\Q$srchlast\E/i) &&
 6990:                             ($names{'firstname'} =~ /^\Q$srchfirst\E/i)) {
 6991:                             $srch_results{$user} = {firstname => $names{'firstname'},
 6992:                                                 lastname => $names{'lastname'},
 6993:                                                 permanentemail => $emails{'permanentemail'},
 6994:                                                };
 6995:                         }
 6996:                     } else {
 6997:                         if (($names{'lastname'} =~ /\Q$srchlast\E/i) && 
 6998:                             ($names{'firstname'} =~ /\Q$srchfirst\E/i)) {
 6999:                             $srch_results{$user} = {firstname => $names{'firstname'},
 7000:                                                 lastname => $names{'lastname'},
 7001:                                                 permanentemail => $emails{'permanentemail'},
 7002:                                                };
 7003:                         }
 7004:                     }
 7005:                 }
 7006:             }
 7007:             ($currstate,$response,$forcenewuser) = 
 7008:                 &build_search_response($context,$srch,%srch_results); 
 7009:         } elsif ($srch->{'srchin'} eq 'alc') {
 7010:             $currstate = 'query';
 7011:         } elsif ($srch->{'srchin'} eq 'instd') {
 7012:             ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query($srch); 
 7013:             if ($dirsrchres eq 'ok') {
 7014:                 ($currstate,$response,$forcenewuser) = 
 7015:                     &build_search_response($context,$srch,%srch_results);
 7016:             } else {
 7017:                 my $showdom = &display_domain_info($srch->{'srchdomain'});                $response = '<span class="LC_warning">'.
 7018:                     &mt('Institutional directory search is not available in domain: [_1]',$showdom).
 7019:                     '</span><br />'.
 7020:                     &mt('You may want to search in the LON-CAPA domain instead of the institutional directory.').
 7021:                     '<br /><br />';
 7022:             }
 7023:         }
 7024:     }
 7025:     return ($currstate,$response,$forcenewuser,\%srch_results);
 7026: }
 7027: 
 7028: sub domdirectorysrch_check {
 7029:     my ($srch) = @_;
 7030:     my $response;
 7031:     my %dom_inst_srch = &Apache::lonnet::get_dom('configuration',
 7032:                                              ['directorysrch'],$srch->{'srchdomain'});
 7033:     my $showdom = &display_domain_info($srch->{'srchdomain'});
 7034:     if (ref($dom_inst_srch{'directorysrch'}) eq 'HASH') {
 7035:         if ($dom_inst_srch{'directorysrch'}{'lcavailable'} eq '0') {
 7036:             return &mt('LON-CAPA directory search is not available in domain: [_1]',$showdom);
 7037:         }
 7038:         if ($dom_inst_srch{'directorysrch'}{'lclocalonly'}) {
 7039:             if ($env{'request.role.domain'} ne $srch->{'srchdomain'}) {
 7040:                 return &mt('LON-CAPA directory search in domain: [_1] is only allowed for users with a current role in the domain.',$showdom);
 7041:             }
 7042:         }
 7043:     }
 7044:     return 'ok';
 7045: }
 7046: 
 7047: sub instdirectorysrch_check {
 7048:     my ($srch) = @_;
 7049:     my $can_search = 0;
 7050:     my $response;
 7051:     my %dom_inst_srch = &Apache::lonnet::get_dom('configuration',
 7052:                                              ['directorysrch'],$srch->{'srchdomain'});
 7053:     my $showdom = &display_domain_info($srch->{'srchdomain'});
 7054:     if (ref($dom_inst_srch{'directorysrch'}) eq 'HASH') {
 7055:         if (!$dom_inst_srch{'directorysrch'}{'available'}) {
 7056:             return &mt('Institutional directory search is not available in domain: [_1]',$showdom); 
 7057:         }
 7058:         if ($dom_inst_srch{'directorysrch'}{'localonly'}) {
 7059:             if ($env{'request.role.domain'} ne $srch->{'srchdomain'}) {
 7060:                 return &mt('Institutional directory search in domain: [_1] is only allowed for users with a current role in the domain.',$showdom); 
 7061:             }
 7062:             my @usertypes = split(/:/,$env{'environment.inststatus'});
 7063:             if (!@usertypes) {
 7064:                 push(@usertypes,'default');
 7065:             }
 7066:             if (ref($dom_inst_srch{'directorysrch'}{'cansearch'}) eq 'ARRAY') {
 7067:                 foreach my $type (@usertypes) {
 7068:                     if (grep(/^\Q$type\E$/,@{$dom_inst_srch{'directorysrch'}{'cansearch'}})) {
 7069:                         $can_search = 1;
 7070:                         last;
 7071:                     }
 7072:                 }
 7073:             }
 7074:             if (!$can_search) {
 7075:                 my ($insttypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($srch->{'srchdomain'});
 7076:                 my @longtypes; 
 7077:                 foreach my $item (@usertypes) {
 7078:                     if (defined($insttypes->{$item})) { 
 7079:                         push (@longtypes,$insttypes->{$item});
 7080:                     } elsif ($item eq 'default') {
 7081:                         push (@longtypes,&mt('other')); 
 7082:                     }
 7083:                 }
 7084:                 my $insttype_str = join(', ',@longtypes); 
 7085:                 return &mt('Institutional directory search in domain: [_1] is not available to your user type: ',$showdom).$insttype_str;
 7086:             }
 7087:         } else {
 7088:             $can_search = 1;
 7089:         }
 7090:     } else {
 7091:         return &mt('Institutional directory search has not been configured for domain: [_1]',$showdom);
 7092:     }
 7093:     my %longtext = &Apache::lonlocal::texthash (
 7094:                        uname     => 'username',
 7095:                        lastfirst => 'last name, first name',
 7096:                        lastname  => 'last name',
 7097:                        contains  => 'contains',
 7098:                        exact     => 'as exact match to',
 7099:                        begins    => 'begins with',
 7100:                    );
 7101:     if ($can_search) {
 7102:         if (ref($dom_inst_srch{'directorysrch'}{'searchby'}) eq 'ARRAY') {
 7103:             if (!grep(/^\Q$srch->{'srchby'}\E$/,@{$dom_inst_srch{'directorysrch'}{'searchby'}})) {
 7104:                 return &mt('Institutional directory search in domain: [_1] is not available for searching by "[_2]"',$showdom,$longtext{$srch->{'srchby'}});
 7105:             }
 7106:         } else {
 7107:             return &mt('Institutional directory search in domain: [_1] is not available.', $showdom);
 7108:         }
 7109:     }
 7110:     if ($can_search) {
 7111:         if (ref($dom_inst_srch{'directorysrch'}{'searchtypes'}) eq 'ARRAY') {
 7112:             if (grep(/^\Q$srch->{'srchtype'}\E/,@{$dom_inst_srch{'directorysrch'}{'searchtypes'}})) {
 7113:                 return 'ok';
 7114:             } else {
 7115:                 return &mt('Institutional directory search in domain [_1] is not available for the requested search type: "[_2]"',$showdom,$longtext{$srch->{'srchtype'}});
 7116:             }
 7117:         } else {
 7118:             if ((($dom_inst_srch{'directorysrch'}{'searchtypes'} eq 'specify') &&
 7119:                  ($srch->{'srchtype'} eq 'exact' || $srch->{'srchtype'} eq 'contains')) ||
 7120:                 ($dom_inst_srch{'directorysrch'}{'searchtypes'} eq $srch->{'srchtype'})) {
 7121:                 return 'ok';
 7122:             } else {
 7123:                 return &mt('Institutional directory search in domain [_1] is not available for the requested search type: "[_2]"',$showdom,$longtext{$srch->{'srchtype'}});
 7124:             }
 7125:         }
 7126:     }
 7127: }
 7128: 
 7129: sub get_courseusers {
 7130:     my %advhash;
 7131:     my $classlist = &Apache::loncoursedata::get_classlist();
 7132:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles();
 7133:     foreach my $role (sort(keys(%coursepersonnel))) {
 7134:         foreach my $user (split(/\,/,$coursepersonnel{$role})) {
 7135: 	    if (!exists($classlist->{$user})) {
 7136: 		$classlist->{$user} = [];
 7137: 	    }
 7138:         }
 7139:     }
 7140:     return $classlist;
 7141: }
 7142: 
 7143: sub build_search_response {
 7144:     my ($context,$srch,%srch_results) = @_;
 7145:     my ($currstate,$response,$forcenewuser);
 7146:     my %names = (
 7147:           'uname'     => 'username',
 7148:           'lastname'  => 'last name',
 7149:           'lastfirst' => 'last name, first name',
 7150:           'crs'       => 'this course',
 7151:           'dom'       => 'LON-CAPA domain',
 7152:           'instd'     => 'the institutional directory for domain',
 7153:     );
 7154: 
 7155:     my %single = (
 7156:                    begins   => 'A match',
 7157:                    contains => 'A match',
 7158:                    exact    => 'An exact match',
 7159:                  );
 7160:     my %nomatch = (
 7161:                    begins   => 'No match',
 7162:                    contains => 'No match',
 7163:                    exact    => 'No exact match',
 7164:                   );
 7165:     if (keys(%srch_results) > 1) {
 7166:         $currstate = 'select';
 7167:     } else {
 7168:         if (keys(%srch_results) == 1) {
 7169:             $currstate = 'modify';
 7170:             $response = &mt("$single{$srch->{'srchtype'}} was found for the $names{$srch->{'srchby'}} ([_1]) in $names{$srch->{'srchin'}}.",$srch->{'srchterm'});
 7171:             if ($srch->{'srchin'} eq 'dom' || $srch->{'srchin'} eq 'instd') {
 7172:                 $response .= ': '.&display_domain_info($srch->{'srchdomain'});
 7173:             }
 7174:         } else { # Search has nothing found. Prepare message to user.
 7175:             $response = '<span class="LC_warning">';
 7176:             if ($srch->{'srchin'} eq 'dom' || $srch->{'srchin'} eq 'instd') {
 7177:                 $response .= &mt("$nomatch{$srch->{'srchtype'}} found for the $names{$srch->{'srchby'}} [_1] in $names{$srch->{'srchin'}}: [_2]",
 7178:                                  '<b>'.$srch->{'srchterm'}.'</b>',
 7179:                                  &display_domain_info($srch->{'srchdomain'}));
 7180:             } else {
 7181:                 $response .= &mt("$nomatch{$srch->{'srchtype'}} found for the $names{$srch->{'srchby'}} [_1] in $names{$srch->{'srchin'}}.",
 7182:                                  '<b>'.$srch->{'srchterm'}.'</b>');
 7183:             }
 7184:             $response .= '</span>';
 7185: 
 7186:             if ($srch->{'srchin'} ne 'alc') {
 7187:                 $forcenewuser = 1;
 7188:                 my $cansrchinst = 0; 
 7189:                 if ($srch->{'srchdomain'}) {
 7190:                     my %domconfig = &Apache::lonnet::get_dom('configuration',['directorysrch'],$srch->{'srchdomain'});
 7191:                     if (ref($domconfig{'directorysrch'}) eq 'HASH') {
 7192:                         if ($domconfig{'directorysrch'}{'available'}) {
 7193:                             $cansrchinst = 1;
 7194:                         } 
 7195:                     }
 7196:                 }
 7197:                 if ((($srch->{'srchby'} eq 'lastfirst') || 
 7198:                      ($srch->{'srchby'} eq 'lastname')) &&
 7199:                     ($srch->{'srchin'} eq 'dom')) {
 7200:                     if ($cansrchinst) {
 7201:                         $response .= '<br />'.&mt('You may want to broaden your search to a search of the institutional directory for the domain.');
 7202:                     }
 7203:                 }
 7204:                 if ($srch->{'srchin'} eq 'crs') {
 7205:                     $response .= '<br />'.&mt('You may want to broaden your search to the selected LON-CAPA domain.');
 7206:                 }
 7207:             }
 7208:             my $createdom = $env{'request.role.domain'};
 7209:             if ($context eq 'requestcrs') {
 7210:                 if ($env{'form.coursedom'} ne '') {
 7211:                     $createdom = $env{'form.coursedom'};
 7212:                 }
 7213:             }
 7214:             if (!($srch->{'srchby'} eq 'uname' && $srch->{'srchin'} eq 'dom' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchdomain'} eq $createdom)) {
 7215:                 my $cancreate =
 7216:                     &Apache::lonuserutils::can_create_user($createdom,$context);
 7217:                 my $targetdom = '<span class="LC_cusr_emph">'.$createdom.'</span>';
 7218:                 if ($cancreate) {
 7219:                     my $showdom = &display_domain_info($createdom); 
 7220:                     $response .= '<br /><br />'
 7221:                                 .'<b>'.&mt('To add a new user:').'</b>'
 7222:                                 .'<br />';
 7223:                     if ($context eq 'requestcrs') {
 7224:                         $response .= &mt("(You can only define new users in the new course's domain - [_1])",$targetdom);
 7225:                     } else {
 7226:                         $response .= &mt("(You can only create new users in your current role's domain - [_1])",$targetdom);
 7227:                     }
 7228:                     $response .='<ul><li>'
 7229:                                 .&mt("Set 'Domain/institution to search' to: [_1]",'<span class="LC_cusr_emph">'.$showdom.'</span>')
 7230:                                 .'</li><li>'
 7231:                                 .&mt("Set 'Search criteria' to: [_1]username is ..... in selected LON-CAPA domain[_2]",'<span class="LC_cusr_emph">','</span>')
 7232:                                 .'</li><li>'
 7233:                                 .&mt('Provide the proposed username')
 7234:                                 .'</li><li>'
 7235:                                 .&mt("Click 'Search'")
 7236:                                 .'</li></ul><br />';
 7237:                 } else {
 7238:                     my $helplink = ' href="javascript:helpMenu('."'display'".')"';
 7239:                     $response .= '<br /><br />';
 7240:                     if ($context eq 'requestcrs') {
 7241:                         $response .= &mt("You are not authorized to define new users in the new course's domain - [_1].",$targetdom);
 7242:                     } else {
 7243:                         $response .= &mt("You are not authorized to create new users in your current role's domain - [_1].",$targetdom);
 7244:                     }
 7245:                     $response .= '<br />'
 7246:                                  .&mt('Please contact the [_1]helpdesk[_2] if you need to create a new user.'
 7247:                                     ,' <a'.$helplink.'>'
 7248:                                     ,'</a>')
 7249:                                  .'<br /><br />';
 7250:                 }
 7251:             }
 7252:         }
 7253:     }
 7254:     return ($currstate,$response,$forcenewuser);
 7255: }
 7256: 
 7257: sub display_domain_info {
 7258:     my ($dom) = @_;
 7259:     my $output = $dom;
 7260:     if ($dom ne '') { 
 7261:         my $domdesc = &Apache::lonnet::domain($dom,'description');
 7262:         if ($domdesc ne '') {
 7263:             $output .= ' <span class="LC_cusr_emph">('.$domdesc.')</span>';
 7264:         }
 7265:     }
 7266:     return $output;
 7267: }
 7268: 
 7269: sub crumb_utilities {
 7270:     my %elements = (
 7271:        crtuser => {
 7272:            srchterm => 'text',
 7273:            srchin => 'selectbox',
 7274:            srchby => 'selectbox',
 7275:            srchtype => 'selectbox',
 7276:            srchdomain => 'selectbox',
 7277:        },
 7278:        crtusername => {
 7279:            srchterm => 'text',
 7280:            srchdomain => 'selectbox',
 7281:        },
 7282:        docustom => {
 7283:            rolename => 'selectbox',
 7284:            newrolename => 'textbox',
 7285:        },
 7286:        studentform => {
 7287:            srchterm => 'text',
 7288:            srchin => 'selectbox',
 7289:            srchby => 'selectbox',
 7290:            srchtype => 'selectbox',
 7291:            srchdomain => 'selectbox',
 7292:        },
 7293:     );
 7294: 
 7295:     my $jsback .= qq|
 7296: function backPage(formname,prevphase,prevstate) {
 7297:     if (typeof prevphase == 'undefined') {
 7298:         formname.phase.value = '';
 7299:     }
 7300:     else {  
 7301:         formname.phase.value = prevphase;
 7302:     }
 7303:     if (typeof prevstate == 'undefined') {
 7304:         formname.currstate.value = '';
 7305:     }
 7306:     else {
 7307:         formname.currstate.value = prevstate;
 7308:     }
 7309:     formname.submit();
 7310: }
 7311: |;
 7312:     return ($jsback,\%elements);
 7313: }
 7314: 
 7315: sub course_level_table {
 7316:     my ($inccourses,$showcredits,$defaultcredits) = @_;
 7317:     return unless (ref($inccourses) eq 'HASH');
 7318:     my $table = '';
 7319: # Custom Roles?
 7320: 
 7321:     my %customroles=&Apache::lonuserutils::my_custom_roles();
 7322:     my %lt=&Apache::lonlocal::texthash(
 7323:             'exs'  => "Existing sections",
 7324:             'new'  => "Define new section",
 7325:             'ssd'  => "Set Start Date",
 7326:             'sed'  => "Set End Date",
 7327:             'crl'  => "Course Level",
 7328:             'act'  => "Activate",
 7329:             'rol'  => "Role",
 7330:             'ext'  => "Extent",
 7331:             'grs'  => "Section",
 7332:             'crd'  => "Credits",
 7333:             'sta'  => "Start",
 7334:             'end'  => "End"
 7335:     );
 7336: 
 7337:     foreach my $protectedcourse (sort(keys(%{$inccourses}))) {
 7338: 	my $thiscourse=$protectedcourse;
 7339: 	$thiscourse=~s:_:/:g;
 7340: 	my %coursedata=&Apache::lonnet::coursedescription($thiscourse);
 7341:         my $isowner = &Apache::lonuserutils::is_courseowner($protectedcourse,$coursedata{'internal.courseowner'});
 7342: 	my $area=$coursedata{'description'};
 7343:         my $crstype=$coursedata{'type'};
 7344: 	if (!defined($area)) { $area=&mt('Unavailable course').': '.$protectedcourse; }
 7345: 	my ($domain,$cnum)=split(/\//,$thiscourse);
 7346:         my %sections_count;
 7347:         if (defined($env{'request.course.id'})) {
 7348:             if ($env{'request.course.id'} eq $domain.'_'.$cnum) {
 7349:                 %sections_count = 
 7350: 		    &Apache::loncommon::get_sections($domain,$cnum);
 7351:             }
 7352:         }
 7353:         my @roles = &Apache::lonuserutils::roles_by_context('course','',$crstype);
 7354: 	foreach my $role (@roles) {
 7355:             my $plrole=&Apache::lonnet::plaintext($role,$crstype);
 7356: 	    if ((&Apache::lonnet::allowed('c'.$role,$thiscourse)) ||
 7357:                 ((($role eq 'cc') || ($role eq 'co')) && ($isowner))) {
 7358:                 $table .= &course_level_row($protectedcourse,$role,$area,$domain,
 7359:                                             $plrole,\%sections_count,\%lt,
 7360:                                             $showcredits,$defaultcredits,$crstype);
 7361:             } elsif ($env{'request.course.sec'} ne '') {
 7362:                 if (&Apache::lonnet::allowed('c'.$role,$thiscourse.'/'.
 7363:                                              $env{'request.course.sec'})) {
 7364:                     $table .= &course_level_row($protectedcourse,$role,$area,$domain,
 7365:                                                 $plrole,\%sections_count,\%lt,
 7366:                                                 $showcredits,$defaultcredits,$crstype);
 7367:                 }
 7368:             }
 7369:         }
 7370:         if (&Apache::lonnet::allowed('ccr',$thiscourse)) {
 7371:             foreach my $cust (sort(keys(%customroles))) {
 7372:                 next if ($crstype eq 'Community' && $customroles{$cust} =~ /bre\&S/);
 7373:                 my $role = 'cr_cr_'.$env{'user.domain'}.'_'.$env{'user.name'}.'_'.$cust;
 7374:                 $table .= &course_level_row($protectedcourse,$role,$area,$domain,
 7375:                                             $cust,\%sections_count,\%lt,
 7376:                                             $showcredits,$defaultcredits,$crstype);
 7377:             }
 7378: 	}
 7379:     }
 7380:     return '' if ($table eq ''); # return nothing if there is nothing 
 7381:                                  # in the table
 7382:     my $result;
 7383:     if (!$env{'request.course.id'}) {
 7384:         $result = '<h4>'.$lt{'crl'}.'</h4>'."\n";
 7385:     }
 7386:     $result .= 
 7387: &Apache::loncommon::start_data_table().
 7388: &Apache::loncommon::start_data_table_header_row().
 7389: '<th>'.$lt{'act'}.'</th><th>'.$lt{'rol'}.'</th>'."\n".
 7390: '<th>'.$lt{'ext'}.'</th><th>'."\n";
 7391:     if ($showcredits) {
 7392:         $result .= $lt{'crd'}.'</th>';
 7393:     }
 7394:     $result .=
 7395: '<th>'.$lt{'grs'}.'</th><th>'.$lt{'sta'}.'</th>'."\n".
 7396: '<th>'.$lt{'end'}.'</th>'.
 7397: &Apache::loncommon::end_data_table_header_row().
 7398: $table.
 7399: &Apache::loncommon::end_data_table();
 7400:     return $result;
 7401: }
 7402: 
 7403: sub course_level_row {
 7404:     my ($protectedcourse,$role,$area,$domain,$plrole,$sections_count,
 7405:         $lt,$showcredits,$defaultcredits,$crstype) = @_;
 7406:     my $creditem;
 7407:     my $row = &Apache::loncommon::start_data_table_row().
 7408:               ' <td><input type="checkbox" name="act_'.
 7409:               $protectedcourse.'_'.$role.'" /></td>'."\n".
 7410:               ' <td>'.$plrole.'</td>'."\n".
 7411:               ' <td>'.$area.'<br />Domain: '.$domain.'</td>'."\n";
 7412:     if (($showcredits) && ($role eq 'st') && ($crstype eq 'Course')) {
 7413:         $row .= 
 7414:             '<td><input type="text" name="credits_'.$protectedcourse.'_'.
 7415:             $role.'" size="3" value="'.$defaultcredits.'" /></td>';
 7416:     } else {
 7417:         $row .= '<td>&nbsp;</td>';
 7418:     }
 7419:     if (($role eq 'cc') || ($role eq 'co')) {
 7420:         $row .= '<td>&nbsp;</td>';
 7421:     } elsif ($env{'request.course.sec'} ne '') {
 7422:         $row .= ' <td><input type="hidden" value="'.
 7423:                 $env{'request.course.sec'}.'" '.
 7424:                 'name="sec_'.$protectedcourse.'_'.$role.'" />'.
 7425:                 $env{'request.course.sec'}.'</td>';
 7426:     } else {
 7427:         if (ref($sections_count) eq 'HASH') {
 7428:             my $currsec = 
 7429:                 &Apache::lonuserutils::course_sections($sections_count,
 7430:                                                        $protectedcourse.'_'.$role);
 7431:             $row .= '<td><table class="LC_createuser">'."\n".
 7432:                     '<tr class="LC_section_row">'."\n".
 7433:                     ' <td valign="top">'.$lt->{'exs'}.'<br />'.
 7434:                        $currsec.'</td>'."\n".
 7435:                      ' <td>&nbsp;&nbsp;</td>'."\n".
 7436:                      ' <td valign="top">&nbsp;'.$lt->{'new'}.'<br />'.
 7437:                      '<input type="text" name="newsec_'.$protectedcourse.'_'.$role.
 7438:                      '" value="" />'.
 7439:                      '<input type="hidden" '.
 7440:                      'name="sec_'.$protectedcourse.'_'.$role.'" /></td>'."\n".
 7441:                      '</tr></table></td>'."\n";
 7442:         } else {
 7443:             $row .= '<td><input type="text" size="10" '.
 7444:                     'name="sec_'.$protectedcourse.'_'.$role.'" /></td>'."\n";
 7445:         }
 7446:     }
 7447:     $row .= <<ENDTIMEENTRY;
 7448: <td><input type="hidden" name="start_$protectedcourse\_$role" value="" />
 7449: <a href=
 7450: "javascript:pjump('date_start','Start Date $plrole',document.cu.start_$protectedcourse\_$role.value,'start_$protectedcourse\_$role','cu.pres','dateset')">$lt->{'ssd'}</a></td>
 7451: <td><input type="hidden" name="end_$protectedcourse\_$role" value="" />
 7452: <a href=
 7453: "javascript:pjump('date_end','End Date $plrole',document.cu.end_$protectedcourse\_$role.value,'end_$protectedcourse\_$role','cu.pres','dateset')">$lt->{'sed'}</a></td>
 7454: ENDTIMEENTRY
 7455:     $row .= &Apache::loncommon::end_data_table_row();
 7456:     return $row;
 7457: }
 7458: 
 7459: sub course_level_dc {
 7460:     my ($dcdom,$showcredits) = @_;
 7461:     my %customroles=&Apache::lonuserutils::my_custom_roles();
 7462:     my @roles = &Apache::lonuserutils::roles_by_context('course');
 7463:     my $hiddenitems = '<input type="hidden" name="dcdomain" value="'.$dcdom.'" />'.
 7464:                       '<input type="hidden" name="origdom" value="'.$dcdom.'" />'.
 7465:                       '<input type="hidden" name="dccourse" value="" />';
 7466:     my $courseform=&Apache::loncommon::selectcourse_link
 7467:             ('cu','dccourse','dcdomain','coursedesc',undef,undef,'Select','crstype');
 7468:     my $credit_elem;
 7469:     if ($showcredits) {
 7470:         $credit_elem = 'credits';
 7471:     }
 7472:     my $cb_jscript = &Apache::loncommon::coursebrowser_javascript($dcdom,'currsec','cu','role','Course/Community Browser',$credit_elem);
 7473:     my %lt=&Apache::lonlocal::texthash(
 7474:                     'rol'  => "Role",
 7475:                     'grs'  => "Section",
 7476:                     'exs'  => "Existing sections",
 7477:                     'new'  => "Define new section", 
 7478:                     'sta'  => "Start",
 7479:                     'end'  => "End",
 7480:                     'ssd'  => "Set Start Date",
 7481:                     'sed'  => "Set End Date",
 7482:                     'scc'  => "Course/Community",
 7483:                     'crd'  => "Credits",
 7484:                   );
 7485:     my $header = '<h4>'.&mt('Course/Community Level').'</h4>'.
 7486:                  &Apache::loncommon::start_data_table().
 7487:                  &Apache::loncommon::start_data_table_header_row().
 7488:                  '<th>'.$lt{'scc'}.'</th><th>'.$lt{'rol'}.'</th>'."\n".
 7489:                  '<th>'.$lt{'grs'}.'</th>'."\n";
 7490:     $header .=   '<th>'.$lt{'crd'}.'</th>'."\n" if ($showcredits);
 7491:     $header .=   '<th>'.$lt{'sta'}.'</th><th>'.$lt{'end'}.'</th>'."\n".
 7492:                  &Apache::loncommon::end_data_table_header_row();
 7493:     my $otheritems = &Apache::loncommon::start_data_table_row()."\n".
 7494:                      '<td><br /><span class="LC_nobreak"><input type="text" name="coursedesc" value="" onfocus="this.blur();opencrsbrowser('."'cu','dccourse','dcdomain','coursedesc','','','','crstype'".')" />'.
 7495:                      $courseform.('&nbsp;' x4).'</span></td>'."\n".
 7496:                      '<td valign="top"><br /><select name="role">'."\n";
 7497:     foreach my $role (@roles) {
 7498:         my $plrole=&Apache::lonnet::plaintext($role);
 7499:         $otheritems .= '  <option value="'.$role.'">'.$plrole.'</option>';
 7500:     }
 7501:     if ( keys(%customroles) > 0) {
 7502:         foreach my $cust (sort(keys(%customroles))) {
 7503:             my $custrole='cr_cr_'.$env{'user.domain'}.
 7504:                     '_'.$env{'user.name'}.'_'.$cust;
 7505:             $otheritems .= '  <option value="'.$custrole.'">'.$cust.'</option>';
 7506:         }
 7507:     }
 7508:     $otheritems .= '</select></td><td>'.
 7509:                      '<table border="0" cellspacing="0" cellpadding="0">'.
 7510:                      '<tr><td valign="top"><b>'.$lt{'exs'}.'</b><br /><select name="currsec">'.
 7511:                      ' <option value="">&lt;--'.&mt('Pick course first').'</option></select></td>'.
 7512:                      '<td>&nbsp;&nbsp;</td>'.
 7513:                      '<td valign="top">&nbsp;<b>'.$lt{'new'}.'</b><br />'.
 7514:                      '<input type="text" name="newsec" value="" />'.
 7515:                      '<input type="hidden" name="section" value="" />'.
 7516:                      '<input type="hidden" name="groups" value="" />'.
 7517:                      '<input type="hidden" name="crstype" value="" /></td>'.
 7518:                      '</tr></table></td>'."\n";
 7519:     if ($showcredits) {
 7520:         $otheritems .= '<td><br />'."\n".
 7521:                        '<input type="text" size="3" name="credits" value="" /></td>'."\n";
 7522:     }
 7523:     $otheritems .= <<ENDTIMEENTRY;
 7524: <td><br /><input type="hidden" name="start" value='' />
 7525: <a href=
 7526: "javascript:pjump('date_start','Start Date',document.cu.start.value,'start','cu.pres','dateset')">$lt{'ssd'}</a></td>
 7527: <td><br /><input type="hidden" name="end" value='' />
 7528: <a href=
 7529: "javascript:pjump('date_end','End Date',document.cu.end.value,'end','cu.pres','dateset')">$lt{'sed'}</a></td>
 7530: ENDTIMEENTRY
 7531:     $otheritems .= &Apache::loncommon::end_data_table_row().
 7532:                    &Apache::loncommon::end_data_table()."\n";
 7533:     return $cb_jscript.$header.$hiddenitems.$otheritems;
 7534: }
 7535: 
 7536: sub update_selfenroll_config {
 7537:     my ($r,$cid,$cdom,$cnum,$context,$crstype,$currsettings) = @_;
 7538:     return unless (ref($currsettings) eq 'HASH');
 7539:     my ($row,$lt) = &Apache::lonuserutils::get_selfenroll_titles();
 7540:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
 7541:     my (%changes,%warning);
 7542:     my $curr_types;
 7543:     my %noedit;
 7544:     unless ($context eq 'domain') {
 7545:         %noedit = &get_noedit_fields($cdom,$cnum,$crstype,$row);
 7546:     }
 7547:     if (ref($row) eq 'ARRAY') {
 7548:         foreach my $item (@{$row}) {
 7549:             next if ($noedit{$item});
 7550:             if ($item eq 'enroll_dates') {
 7551:                 my (%currenrolldate,%newenrolldate);
 7552:                 foreach my $type ('start','end') {
 7553:                     $currenrolldate{$type} = $currsettings->{'selfenroll_'.$type.'_date'};
 7554:                     $newenrolldate{$type} = &Apache::lonhtmlcommon::get_date_from_form('selfenroll_'.$type.'_date');
 7555:                     if ($newenrolldate{$type} ne $currenrolldate{$type}) {
 7556:                         $changes{'internal.selfenroll_'.$type.'_date'} = $newenrolldate{$type};
 7557:                     }
 7558:                 }
 7559:             } elsif ($item eq 'access_dates') {
 7560:                 my (%currdate,%newdate);
 7561:                 foreach my $type ('start','end') {
 7562:                     $currdate{$type} = $currsettings->{'selfenroll_'.$type.'_access'};
 7563:                     $newdate{$type} = &Apache::lonhtmlcommon::get_date_from_form('selfenroll_'.$type.'_access');
 7564:                     if ($newdate{$type} ne $currdate{$type}) {
 7565:                         $changes{'internal.selfenroll_'.$type.'_access'} = $newdate{$type};
 7566:                     }
 7567:                 }
 7568:             } elsif ($item eq 'types') {
 7569:                 $curr_types = $currsettings->{'selfenroll_'.$item};
 7570:                 if ($env{'form.selfenroll_all'}) {
 7571:                     if ($curr_types ne '*') {
 7572:                         $changes{'internal.selfenroll_types'} = '*';
 7573:                     } else {
 7574:                         next;
 7575:                     }
 7576:                 } else {
 7577:                     my %currdoms;
 7578:                     my @entries = split(/;/,$curr_types);
 7579:                     my @deletedoms = &Apache::loncommon::get_env_multiple('form.selfenroll_delete');
 7580:                     my @activations = &Apache::loncommon::get_env_multiple('form.selfenroll_activate');
 7581:                     my $newnum = 0;
 7582:                     my @latesttypes;
 7583:                     foreach my $num (@activations) {
 7584:                         my @types = &Apache::loncommon::get_env_multiple('form.selfenroll_types_'.$num);
 7585:                         if (@types > 0) {
 7586:                             @types = sort(@types);
 7587:                             my $typestr = join(',',@types);
 7588:                             my $typedom = $env{'form.selfenroll_dom_'.$num};
 7589:                             $latesttypes[$newnum] = $typedom.':'.$typestr;
 7590:                             $currdoms{$typedom} = 1;
 7591:                             $newnum ++;
 7592:                         }
 7593:                     }
 7594:                     for (my $j=0; $j<$env{'form.selfenroll_types_total'}; $j++) {
 7595:                         if ((!grep(/^$j$/,@deletedoms)) && (!grep(/^$j$/,@activations))) {
 7596:                             my @types = &Apache::loncommon::get_env_multiple('form.selfenroll_types_'.$j);
 7597:                             if (@types > 0) {
 7598:                                 @types = sort(@types);
 7599:                                 my $typestr = join(',',@types);
 7600:                                 my $typedom = $env{'form.selfenroll_dom_'.$j};
 7601:                                 $latesttypes[$newnum] = $typedom.':'.$typestr;
 7602:                                 $currdoms{$typedom} = 1;
 7603:                                 $newnum ++;
 7604:                             }
 7605:                         }
 7606:                     }
 7607:                     if ($env{'form.selfenroll_newdom'} ne '') {
 7608:                         my $typedom = $env{'form.selfenroll_newdom'};
 7609:                         if ((!defined($currdoms{$typedom})) && 
 7610:                             (&Apache::lonnet::domain($typedom) ne '')) {
 7611:                             my $typestr;
 7612:                             my ($othertitle,$usertypes,$types) = 
 7613:                                 &Apache::loncommon::sorted_inst_types($typedom);
 7614:                             my $othervalue = 'any';
 7615:                             if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 7616:                                 if (@{$types} > 0) {
 7617:                                     my @esc_types = map { &escape($_); } @{$types};
 7618:                                     $othervalue = 'other';
 7619:                                     $typestr = join(',',(@esc_types,$othervalue));
 7620:                                 }
 7621:                                 $typestr = $othervalue;
 7622:                             } else {
 7623:                                 $typestr = $othervalue;
 7624:                             } 
 7625:                             $latesttypes[$newnum] = $typedom.':'.$typestr;
 7626:                             $newnum ++ ;
 7627:                         }
 7628:                     }
 7629:                     my $selfenroll_types = join(';',@latesttypes);
 7630:                     if ($selfenroll_types ne $curr_types) {
 7631:                         $changes{'internal.selfenroll_types'} = $selfenroll_types;
 7632:                     }
 7633:                 }
 7634:             } elsif ($item eq 'limit') {
 7635:                 my $newlimit = $env{'form.selfenroll_limit'};
 7636:                 my $newcap = $env{'form.selfenroll_cap'};
 7637:                 $newcap =~s/\s+//g;
 7638:                 my $currlimit =  $currsettings->{'selfenroll_limit'};
 7639:                 $currlimit = 'none' if ($currlimit eq '');
 7640:                 my $currcap = $currsettings->{'selfenroll_cap'};
 7641:                 if ($newlimit ne $currlimit) {
 7642:                     if ($newlimit ne 'none') {
 7643:                         if ($newcap =~ /^\d+$/) {
 7644:                             if ($newcap ne $currcap) {
 7645:                                 $changes{'internal.selfenroll_cap'} = $newcap;
 7646:                             }
 7647:                             $changes{'internal.selfenroll_limit'} = $newlimit;
 7648:                         } else {
 7649:                             $warning{$item} = &mt('Maximum enrollment setting unchanged.').'<br />'.
 7650:                                 &mt('The value provided was invalid - it must be a positive integer if enrollment is being limited.'); 
 7651:                         }
 7652:                     } elsif ($currcap ne '') {
 7653:                         $changes{'internal.selfenroll_cap'} = '';
 7654:                         $changes{'internal.selfenroll_limit'} = $newlimit; 
 7655:                     }
 7656:                 } elsif ($currlimit ne 'none') {
 7657:                     if ($newcap =~ /^\d+$/) {
 7658:                         if ($newcap ne $currcap) {
 7659:                             $changes{'internal.selfenroll_cap'} = $newcap;
 7660:                         }
 7661:                     } else {
 7662:                         $warning{$item} = &mt('Maximum enrollment setting unchanged.').'<br />'.
 7663:                             &mt('The value provided was invalid - it must be a positive integer if enrollment is being limited.');
 7664:                     }
 7665:                 }
 7666:             } elsif ($item eq 'approval') {
 7667:                 my (@currnotified,@newnotified);
 7668:                 my $currapproval = $currsettings->{'selfenroll_approval'};
 7669:                 my $currnotifylist = $currsettings->{'selfenroll_notifylist'};
 7670:                 if ($currnotifylist ne '') {
 7671:                     @currnotified = split(/,/,$currnotifylist);
 7672:                     @currnotified = sort(@currnotified);
 7673:                 }
 7674:                 my $newapproval = $env{'form.selfenroll_approval'};
 7675:                 @newnotified = &Apache::loncommon::get_env_multiple('form.selfenroll_notify');
 7676:                 @newnotified = sort(@newnotified);
 7677:                 if ($newapproval ne $currapproval) {
 7678:                     $changes{'internal.selfenroll_approval'} = $newapproval;
 7679:                     if (!$newapproval) {
 7680:                         if ($currnotifylist ne '') {
 7681:                             $changes{'internal.selfenroll_notifylist'} = '';
 7682:                         }
 7683:                     } else {
 7684:                         my @differences =  
 7685:                             &Apache::loncommon::compare_arrays(\@currnotified,\@newnotified);
 7686:                         if (@differences > 0) {
 7687:                             if (@newnotified > 0) {
 7688:                                 $changes{'internal.selfenroll_notifylist'} = join(',',@newnotified);
 7689:                             } else {
 7690:                                 $changes{'internal.selfenroll_notifylist'} = join(',',@newnotified);
 7691:                             }
 7692:                         }
 7693:                     }
 7694:                 } else {
 7695:                     my @differences = &Apache::loncommon::compare_arrays(\@currnotified,\@newnotified);
 7696:                     if (@differences > 0) {
 7697:                         if (@newnotified > 0) {
 7698:                             $changes{'internal.selfenroll_notifylist'} = join(',',@newnotified);
 7699:                         } else {
 7700:                             $changes{'internal.selfenroll_notifylist'} = '';
 7701:                         }
 7702:                     }
 7703:                 }
 7704:             } else {
 7705:                 my $curr_val = $currsettings->{'selfenroll_'.$item};
 7706:                 my $newval = $env{'form.selfenroll_'.$item};
 7707:                 if ($item eq 'section') {
 7708:                     $newval = $env{'form.sections'};
 7709:                     if (defined($curr_groups{$newval})) {
 7710:                         $newval = $curr_val;
 7711:                         $warning{$item} = &mt('Section for self-enrolled users unchanged as the proposed section is a group').'<br />'.
 7712:                                           &mt('Group names and section names must be distinct');
 7713:                     } elsif ($newval eq 'all') {
 7714:                         $newval = $curr_val;
 7715:                         $warning{$item} = &mt('Section for self-enrolled users unchanged, as "all" is a reserved section name.');
 7716:                     }
 7717:                     if ($newval eq '') {
 7718:                         $newval = 'none';
 7719:                     }
 7720:                 }
 7721:                 if ($newval ne $curr_val) {
 7722:                     $changes{'internal.selfenroll_'.$item} = $newval;
 7723:                 }
 7724:             }
 7725:         }
 7726:         if (keys(%warning) > 0) {
 7727:             foreach my $item (@{$row}) {
 7728:                 if (exists($warning{$item})) {
 7729:                     $r->print($warning{$item}.'<br />');
 7730:                 }
 7731:             } 
 7732:         }
 7733:         if (keys(%changes) > 0) {
 7734:             my $putresult = &Apache::lonnet::put('environment',\%changes,$cdom,$cnum);
 7735:             if ($putresult eq 'ok') {
 7736:                 if ((exists($changes{'internal.selfenroll_types'})) ||
 7737:                     (exists($changes{'internal.selfenroll_start_date'}))  ||
 7738:                     (exists($changes{'internal.selfenroll_end_date'}))) {
 7739:                     my %crsinfo = &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',
 7740:                                                                 $cnum,undef,undef,'Course');
 7741:                     my $chome = &Apache::lonnet::homeserver($cnum,$cdom);
 7742:                     if (ref($crsinfo{$cid}) eq 'HASH') {
 7743:                         foreach my $item ('selfenroll_types','selfenroll_start_date','selfenroll_end_date') {
 7744:                             if (exists($changes{'internal.'.$item})) {
 7745:                                 $crsinfo{$cid}{$item} = $changes{'internal.'.$item};
 7746:                             }
 7747:                         }
 7748:                         my $crsputresult =
 7749:                             &Apache::lonnet::courseidput($cdom,\%crsinfo,
 7750:                                                          $chome,'notime');
 7751:                     }
 7752:                 }
 7753:                 $r->print(&mt('The following changes were made to self-enrollment settings:').'<ul>');
 7754:                 foreach my $item (@{$row}) {
 7755:                     my $title = $item;
 7756:                     if (ref($lt) eq 'HASH') {
 7757:                         $title = $lt->{$item};
 7758:                     }
 7759:                     if ($item eq 'enroll_dates') {
 7760:                         foreach my $type ('start','end') {
 7761:                             if (exists($changes{'internal.selfenroll_'.$type.'_date'})) {
 7762:                                 my $newdate = &Apache::lonlocal::locallocaltime($changes{'internal.selfenroll_'.$type.'_date'});
 7763:                                 $r->print('<li>'.&mt('[_1]: "[_2]" set to "[_3]".',
 7764:                                           $title,$type,$newdate).'</li>');
 7765:                             }
 7766:                         }
 7767:                     } elsif ($item eq 'access_dates') {
 7768:                         foreach my $type ('start','end') {
 7769:                             if (exists($changes{'internal.selfenroll_'.$type.'_access'})) {
 7770:                                 my $newdate = &Apache::lonlocal::locallocaltime($changes{'internal.selfenroll_'.$type.'_access'});
 7771:                                 $r->print('<li>'.&mt('[_1]: "[_2]" set to "[_3]".',
 7772:                                           $title,$type,$newdate).'</li>');
 7773:                             }
 7774:                         }
 7775:                     } elsif ($item eq 'limit') {
 7776:                         if ((exists($changes{'internal.selfenroll_limit'})) ||
 7777:                             (exists($changes{'internal.selfenroll_cap'}))) {
 7778:                             my ($newval,$newcap);
 7779:                             if ($changes{'internal.selfenroll_cap'} ne '') {
 7780:                                 $newcap = $changes{'internal.selfenroll_cap'}
 7781:                             } else {
 7782:                                 $newcap = $currsettings->{'selfenroll_cap'};
 7783:                             }
 7784:                             if ($changes{'internal.selfenroll_limit'} eq 'none') {
 7785:                                 $newval = &mt('No limit');
 7786:                             } elsif ($changes{'internal.selfenroll_limit'} eq 
 7787:                                      'allstudents') {
 7788:                                 $newval = &mt('New self-enrollment no longer allowed when total (all students) reaches [_1].',$newcap);
 7789:                             } elsif ($changes{'internal.selfenroll_limit'} eq 'selfenrolled') {
 7790:                                 $newval = &mt('New self-enrollment no longer allowed when total number of self-enrolled students reaches [_1].',$newcap);
 7791:                             } else {
 7792:                                 my $currlimit =  $currsettings->{'selfenroll_limit'};
 7793:                                 if ($currlimit eq 'allstudents') {
 7794:                                     $newval = &mt('New self-enrollment no longer allowed when total (all students) reaches [_1].',$newcap);
 7795:                                 } elsif ($changes{'internal.selfenroll_limit'} eq 'selfenrolled') {
 7796:                                     $newval =  &mt('New self-enrollment no longer allowed when total number of self-enrolled students reaches [_1].',$newcap);
 7797:                                 }
 7798:                             }
 7799:                             $r->print('<li>'.&mt('"[_1]" set to "[_2]".',$title,$newval).'</li>'."\n");
 7800:                         }
 7801:                     } elsif ($item eq 'approval') {
 7802:                         if ((exists($changes{'internal.selfenroll_approval'})) ||
 7803:                             (exists($changes{'internal.selfenroll_notifylist'}))) {
 7804:                             my %selfdescs = &Apache::lonuserutils::selfenroll_default_descs();
 7805:                             my ($newval,$newnotify);
 7806:                             if (exists($changes{'internal.selfenroll_notifylist'})) {
 7807:                                 $newnotify = $changes{'internal.selfenroll_notifylist'};
 7808:                             } else {   
 7809:                                 $newnotify = $currsettings->{'selfenroll_notifylist'};
 7810:                             }
 7811:                             if (exists($changes{'internal.selfenroll_approval'})) {
 7812:                                 if ($changes{'internal.selfenroll_approval'} !~ /^[012]$/) {
 7813:                                     $changes{'internal.selfenroll_approval'} = '0';
 7814:                                 }
 7815:                                 $newval = $selfdescs{'approval'}{$changes{'internal.selfenroll_approval'}};
 7816:                             } else {
 7817:                                 my $currapproval = $currsettings->{'selfenroll_approval'}; 
 7818:                                 if ($currapproval !~ /^[012]$/) {
 7819:                                     $currapproval = 0;
 7820:                                 }
 7821:                                 $newval = $selfdescs{'approval'}{$currapproval};
 7822:                             }
 7823:                             $r->print('<li>'.&mt('"[_1]" set to "[_2]".',$title,$newval));
 7824:                             if ($newnotify) {
 7825:                                 $r->print('<br />'.&mt('The following will be notified when an enrollment request needs approval, or has been approved: [_1].',$newnotify));
 7826:                             } else {
 7827:                                 $r->print('<br />'.&mt('No notifications sent when an enrollment request needs approval, or has been approved.'));
 7828:                             }
 7829:                             $r->print('</li>'."\n");
 7830:                         }
 7831:                     } else {
 7832:                         if (exists($changes{'internal.selfenroll_'.$item})) {
 7833:                             my $newval = $changes{'internal.selfenroll_'.$item};
 7834:                             if ($item eq 'types') {
 7835:                                 if ($newval eq '') {
 7836:                                     $newval = &mt('None');
 7837:                                 } elsif ($newval eq '*') {
 7838:                                     $newval = &mt('Any user in any domain');
 7839:                                 }
 7840:                             } elsif ($item eq 'registered') {
 7841:                                 if ($newval eq '1') {
 7842:                                     $newval = &mt('Yes');
 7843:                                 } elsif ($newval eq '0') {
 7844:                                     $newval = &mt('No');
 7845:                                 }
 7846:                             }
 7847:                             $r->print('<li>'.&mt('"[_1]" set to "[_2]".',$title,$newval).'</li>'."\n");
 7848:                         }
 7849:                     }
 7850:                 }
 7851:                 $r->print('</ul>');
 7852:                 if ($env{'course.'.$cid.'.description'} ne '') {
 7853:                     my %newenvhash;
 7854:                     foreach my $key (keys(%changes)) {
 7855:                         $newenvhash{'course.'.$cid.'.'.$key} = $changes{$key};
 7856:                     }
 7857:                     &Apache::lonnet::appenv(\%newenvhash);
 7858:                 }
 7859:             } else {
 7860:                 $r->print(&mt('An error occurred when saving changes to self-enrollment settings in this course.').'<br />'.
 7861:                           &mt('The error was: [_1].',$putresult));
 7862:             }
 7863:         } else {
 7864:             $r->print(&mt('No changes were made to the existing self-enrollment settings in this course.'));
 7865:         }
 7866:     } else {
 7867:         $r->print(&mt('No changes were made to the existing self-enrollment settings in this course.'));
 7868:     }
 7869:     my $visactions = &cat_visibility();
 7870:     my ($cathash,%cattype);
 7871:     my %domconfig = &Apache::lonnet::get_dom('configuration',['coursecategories'],$cdom);
 7872:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 7873:         $cathash = $domconfig{'coursecategories'}{'cats'};
 7874:         $cattype{'auth'} = $domconfig{'coursecategories'}{'auth'};
 7875:         $cattype{'unauth'} = $domconfig{'coursecategories'}{'unauth'};
 7876:     } else {
 7877:         $cathash = {};
 7878:         $cattype{'auth'} = 'std';
 7879:         $cattype{'unauth'} = 'std';
 7880:     }
 7881:     if (($cattype{'auth'} eq 'none') && ($cattype{'unauth'} eq 'none')) {
 7882:         $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
 7883:                   '<br />'.
 7884:                   '<br />'.$visactions->{'take'}.'<ul>'.
 7885:                   '<li>'.$visactions->{'dc_chgconf'}.'</li>'.
 7886:                   '</ul>');
 7887:     } elsif (($cattype{'auth'} !~ /^(std|domonly)$/) && ($cattype{'unauth'} !~ /^(std|domonly)$/)) {
 7888:         if ($currsettings->{'uniquecode'}) {
 7889:             $r->print('<span class="LC_info">'.$visactions->{'vis'}.'</span>');
 7890:         } else {
 7891:             $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
 7892:                   '<br />'.
 7893:                   '<br />'.$visactions->{'take'}.'<ul>'.
 7894:                   '<li>'.$visactions->{'dc_setcode'}.'</li>'.
 7895:                   '</ul><br />');
 7896:         }
 7897:     } else {
 7898:         my ($visible,$cansetvis,$vismsgs) = &visible_in_stdcat($cdom,$cnum,\%domconfig);
 7899:         if (ref($visactions) eq 'HASH') {
 7900:             if (!$visible) {
 7901:                 $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
 7902:                           '<br />');
 7903:                 if (ref($vismsgs) eq 'ARRAY') {
 7904:                     $r->print('<br />'.$visactions->{'take'}.'<ul>');
 7905:                     foreach my $item (@{$vismsgs}) {
 7906:                         $r->print('<li>'.$visactions->{$item}.'</li>');
 7907:                     }
 7908:                     $r->print('</ul>');
 7909:                 }
 7910:                 $r->print($cansetvis);
 7911:             }
 7912:         }
 7913:     } 
 7914:     return;
 7915: }
 7916: 
 7917: #---------------------------------------------- end functions for &phase_two
 7918: 
 7919: #--------------------------------- functions for &phase_two and &phase_three
 7920: 
 7921: #--------------------------end of functions for &phase_two and &phase_three
 7922: 
 7923: 1;
 7924: __END__
 7925: 
 7926: 

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