File:  [LON-CAPA] / loncom / interface / loncreateuser.pm
Revision 1.415: download - view: text, annotated - select for diffs
Mon Oct 10 02:53:02 2016 UTC (7 years, 7 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- "Previous N changes" and "Next N changes" buttons available if changes/page
  set (N) such that results require more than 1 page.
  - javascript for chgPage() function is passed to start_page().
  - &userlogdisplay_navlinks() is called after looping over role log items
    so that $more_records value has been set.

    1: # The LearningOnline Network with CAPA
    2: # Create a user
    3: #
    4: # $Id: loncreateuser.pm,v 1.415 2016/10/10 02:53:02 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: ###
   29: 
   30: package Apache::loncreateuser;
   31: 
   32: =pod
   33: 
   34: =head1 NAME
   35: 
   36: Apache::loncreateuser.pm
   37: 
   38: =head1 SYNOPSIS
   39: 
   40:     Handler to create users and custom roles
   41: 
   42:     Provides an Apache handler for creating users,
   43:     editing their login parameters, roles, and removing roles, and
   44:     also creating and assigning custom roles.
   45: 
   46: =head1 OVERVIEW
   47: 
   48: =head2 Custom Roles
   49: 
   50: In LON-CAPA, roles are actually collections of privileges. "Teaching
   51: Assistant", "Course Coordinator", and other such roles are really just
   52: collection of privileges that are useful in many circumstances.
   53: 
   54: Custom roles can be defined by a Domain Coordinator, Course Coordinator
   55: or Community Coordinator via the Manage User functionality.
   56: The custom role editor screen will show all privileges which can be
   57: assigned to users. For a complete list of privileges, please see 
   58: C</home/httpd/lonTabs/rolesplain.tab>.
   59: 
   60: Custom role definitions are stored in the C<roles.db> file of the creator
   61: of the role.
   62: 
   63: =cut
   64: 
   65: use strict;
   66: use Apache::Constants qw(:common :http);
   67: use Apache::lonnet;
   68: use Apache::loncommon;
   69: use Apache::lonlocal;
   70: use Apache::longroup;
   71: use Apache::lonuserutils;
   72: use Apache::loncoursequeueadmin;
   73: use LONCAPA qw(:DEFAULT :match);
   74: 
   75: my $loginscript; # piece of javascript used in two separate instances
   76: my $authformnop;
   77: my $authformkrb;
   78: my $authformint;
   79: my $authformfsys;
   80: my $authformloc;
   81: 
   82: sub initialize_authen_forms {
   83:     my ($dom,$formname,$curr_authtype,$mode) = @_;
   84:     my ($krbdef,$krbdefdom) = &Apache::loncommon::get_kerberos_defaults($dom);
   85:     my %param = ( formname => $formname,
   86:                   kerb_def_dom => $krbdefdom,
   87:                   kerb_def_auth => $krbdef,
   88:                   domain => $dom,
   89:                 );
   90:     my %abv_auth = &auth_abbrev();
   91:     if ($curr_authtype =~ /^(krb4|krb5|internal|localauth|unix):(.*)$/) {
   92:         my $long_auth = $1;
   93:         my $curr_autharg = $2;
   94:         my %abv_auth = &auth_abbrev();
   95:         $param{'curr_authtype'} = $abv_auth{$long_auth};
   96:         if ($long_auth =~ /^krb(4|5)$/) {
   97:             $param{'curr_kerb_ver'} = $1;
   98:             $param{'curr_autharg'} = $curr_autharg;
   99:         }
  100:         if ($mode eq 'modifyuser') {
  101:             $param{'mode'} = $mode;
  102:         }
  103:     }
  104:     $loginscript  = &Apache::loncommon::authform_header(%param);
  105:     $authformkrb  = &Apache::loncommon::authform_kerberos(%param);
  106:     $authformnop  = &Apache::loncommon::authform_nochange(%param);
  107:     $authformint  = &Apache::loncommon::authform_internal(%param);
  108:     $authformfsys = &Apache::loncommon::authform_filesystem(%param);
  109:     $authformloc  = &Apache::loncommon::authform_local(%param);
  110: }
  111: 
  112: sub auth_abbrev {
  113:     my %abv_auth = (
  114:                      krb5      => 'krb',
  115:                      krb4      => 'krb',
  116:                      internal  => 'int',
  117:                      localauth => 'loc',
  118:                      unix      => 'fsys',
  119:                    );
  120:     return %abv_auth;
  121: }
  122: 
  123: # ====================================================
  124: 
  125: sub user_quotas {
  126:     my ($ccuname,$ccdomain) = @_;
  127:     my %lt = &Apache::lonlocal::texthash(
  128:                    'usrt'      => "User Tools",
  129:                    'cust'      => "Custom quota",
  130:                    'chqu'      => "Change quota",
  131:     );
  132:    
  133:     my $quota_javascript = <<"END_SCRIPT";
  134: <script type="text/javascript">
  135: // <![CDATA[
  136: function quota_changes(caller,context) {
  137:     var customoff = document.getElementById('custom_'+context+'quota_off');
  138:     var customon = document.getElementById('custom_'+context+'quota_on');
  139:     var number = document.getElementById(context+'quota');
  140:     if (caller == "custom") {
  141:         if (customoff) {
  142:             if (customoff.checked) {
  143:                 number.value = "";
  144:             }
  145:         }
  146:     }
  147:     if (caller == "quota") {
  148:         if (customon) {
  149:             customon.checked = true;
  150:         }
  151:     }
  152:     return;
  153: }
  154: // ]]>
  155: </script>
  156: END_SCRIPT
  157:     my $longinsttype;
  158:     my ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($ccdomain);
  159:     my $output = $quota_javascript."\n".
  160:                  '<h3>'.$lt{'usrt'}.'</h3>'."\n".
  161:                  &Apache::loncommon::start_data_table();
  162: 
  163:     if (&Apache::lonnet::allowed('mut',$ccdomain)) {
  164:         $output .= &build_tools_display($ccuname,$ccdomain,'tools');
  165:     }
  166: 
  167:     my %titles = &Apache::lonlocal::texthash (
  168:                     portfolio => "Disk space allocated to user's portfolio files",
  169:                     author    => "Disk space allocated to user's Authoring Space (if role assigned)",
  170:                  );
  171:     foreach my $name ('portfolio','author') {
  172:         my ($currquota,$quotatype,$inststatus,$defquota) =
  173:             &Apache::loncommon::get_user_quota($ccuname,$ccdomain,$name);
  174:         if ($longinsttype eq '') { 
  175:             if ($inststatus ne '') {
  176:                 if ($usertypes->{$inststatus} ne '') {
  177:                     $longinsttype = $usertypes->{$inststatus};
  178:                 }
  179:             }
  180:         }
  181:         my ($showquota,$custom_on,$custom_off,$defaultinfo);
  182:         $custom_on = ' ';
  183:         $custom_off = ' checked="checked" ';
  184:         if ($quotatype eq 'custom') {
  185:             $custom_on = $custom_off;
  186:             $custom_off = ' ';
  187:             $showquota = $currquota;
  188:             if ($longinsttype eq '') {
  189:                 $defaultinfo = &mt('For this user, the default quota would be [_1]'
  190:                               .' MB.',$defquota);
  191:             } else {
  192:                 $defaultinfo = &mt("For this user, the default quota would be [_1]".
  193:                                    " MB, as determined by the user's institutional".
  194:                                    " affiliation ([_2]).",$defquota,$longinsttype);
  195:             }
  196:         } else {
  197:             if ($longinsttype eq '') {
  198:                 $defaultinfo = &mt('For this user, the default quota is [_1]'
  199:                               .' MB.',$defquota);
  200:             } else {
  201:                 $defaultinfo = &mt("For this user, the default quota of [_1]".
  202:                                    " MB, is determined by the user's institutional".
  203:                                    " affiliation ([_2]).",$defquota,$longinsttype);
  204:             }
  205:         }
  206: 
  207:         if (&Apache::lonnet::allowed('mpq',$ccdomain)) {
  208:             $output .= '<tr class="LC_info_row">'."\n".
  209:                        '    <td>'.$titles{$name}.'</td>'."\n".
  210:                        '  </tr>'."\n".
  211:                        &Apache::loncommon::start_data_table_row()."\n".
  212:                        '  <td><span class="LC_nobreak">'.
  213:                        &mt('Current quota: [_1] MB',$currquota).'</span>&nbsp;&nbsp;'.
  214:                        $defaultinfo.'</td>'."\n".
  215:                        &Apache::loncommon::end_data_table_row()."\n".
  216:                        &Apache::loncommon::start_data_table_row()."\n".
  217:                        '  <td><span class="LC_nobreak">'.$lt{'chqu'}.
  218:                        ': <label>'.
  219:                        '<input type="radio" name="custom_'.$name.'quota" id="custom_'.$name.'quota_off" '.
  220:                        'value="0" '.$custom_off.' onchange="javascript:quota_changes('."'custom','$name'".');"'.
  221:                        ' /><span class="LC_nobreak">'.
  222:                        &mt('Default ([_1] MB)',$defquota).'</span></label>&nbsp;'.
  223:                        '&nbsp;<label><input type="radio" name="custom_'.$name.'quota" id="custom_'.$name.'quota_on" '.
  224:                        'value="1" '.$custom_on.'  onchange="javascript:quota_changes('."'custom','$name'".');"'.
  225:                        ' />'.$lt{'cust'}.':</label>&nbsp;'.
  226:                        '<input type="text" name="'.$name.'quota" id="'.$name.'quota" size ="5" '.
  227:                        'value="'.$showquota.'" onfocus="javascript:quota_changes('."'quota','$name'".');"'.
  228:                        ' />&nbsp;'.&mt('MB').'</span></td>'."\n".
  229:                        &Apache::loncommon::end_data_table_row()."\n";
  230:         }
  231:     }
  232:     $output .= &Apache::loncommon::end_data_table();
  233:     return $output;
  234: }
  235: 
  236: sub build_tools_display {
  237:     my ($ccuname,$ccdomain,$context) = @_;
  238:     my (@usertools,%userenv,$output,@options,%validations,%reqtitles,%reqdisplay,
  239:         $colspan,$isadv,%domconfig);
  240:     my %lt = &Apache::lonlocal::texthash (
  241:                    'blog'       => "Personal User Blog",
  242:                    'aboutme'    => "Personal Information Page",
  243:                    'webdav'     => "WebDAV access to Authoring Spaces (if SSL and author/co-author)",
  244:                    'portfolio'  => "Personal User Portfolio",
  245:                    'avai'       => "Available",
  246:                    'cusa'       => "availability",
  247:                    'chse'       => "Change setting",
  248:                    'usde'       => "Use default",
  249:                    'uscu'       => "Use custom",
  250:                    'official'   => 'Can request creation of official courses',
  251:                    'unofficial' => 'Can request creation of unofficial courses',
  252:                    'community'  => 'Can request creation of communities',
  253:                    'textbook'   => 'Can request creation of textbook courses',
  254:                    'placement'  => 'Can request creation of placement tests',
  255:                    'requestauthor'  => 'Can request author space',
  256:     );
  257:     if ($context eq 'requestcourses') {
  258:         %userenv = &Apache::lonnet::userenvironment($ccdomain,$ccuname,
  259:                       'requestcourses.official','requestcourses.unofficial',
  260:                       'requestcourses.community','requestcourses.textbook',
  261:                       'requestcourses.placement');
  262:         @usertools = ('official','unofficial','community','textbook','placement');
  263:         @options =('norequest','approval','autolimit','validate');
  264:         %validations = &Apache::lonnet::auto_courserequest_checks($ccdomain);
  265:         %reqtitles = &courserequest_titles();
  266:         %reqdisplay = &courserequest_display();
  267:         $colspan = ' colspan="2"';
  268:         %domconfig =
  269:             &Apache::lonnet::get_dom('configuration',['requestcourses'],$ccdomain);
  270:         $isadv = &Apache::lonnet::is_advanced_user($ccuname,$ccdomain);
  271:     } elsif ($context eq 'requestauthor') {
  272:         %userenv = &Apache::lonnet::userenvironment($ccdomain,$ccuname,
  273:                                                     'requestauthor');
  274:         @usertools = ('requestauthor');
  275:         @options =('norequest','approval','automatic');
  276:         %reqtitles = &requestauthor_titles();
  277:         %reqdisplay = &requestauthor_display();
  278:         $colspan = ' colspan="2"';
  279:         %domconfig =
  280:             &Apache::lonnet::get_dom('configuration',['requestauthor'],$ccdomain);
  281:     } else {
  282:         %userenv = &Apache::lonnet::userenvironment($ccdomain,$ccuname,
  283:                           'tools.aboutme','tools.portfolio','tools.blog',
  284:                           'tools.webdav');
  285:         @usertools = ('aboutme','blog','webdav','portfolio');
  286:     }
  287:     foreach my $item (@usertools) {
  288:         my ($custom_access,$curr_access,$cust_on,$cust_off,$tool_on,$tool_off,
  289:             $currdisp,$custdisp,$custradio);
  290:         $cust_off = 'checked="checked" ';
  291:         $tool_on = 'checked="checked" ';
  292:         $curr_access =  
  293:             &Apache::lonnet::usertools_access($ccuname,$ccdomain,$item,undef,
  294:                                               $context);
  295:         if ($context eq 'requestauthor') {
  296:             if ($userenv{$context} ne '') {
  297:                 $cust_on = ' checked="checked" ';
  298:                 $cust_off = '';
  299:             }  
  300:         } elsif ($userenv{$context.'.'.$item} ne '') {
  301:             $cust_on = ' checked="checked" ';
  302:             $cust_off = '';
  303:         }
  304:         if ($context eq 'requestcourses') {
  305:             if ($userenv{$context.'.'.$item} eq '') {
  306:                 $custom_access = &mt('Currently from default setting.');
  307:             } else {
  308:                 $custom_access = &mt('Currently from custom setting.');
  309:             }
  310:         } elsif ($context eq 'requestauthor') {
  311:             if ($userenv{$context} eq '') {
  312:                 $custom_access = &mt('Currently from default setting.');
  313:             } else {
  314:                 $custom_access = &mt('Currently from custom setting.');
  315:             }
  316:         } else {
  317:             if ($userenv{$context.'.'.$item} eq '') {
  318:                 $custom_access =
  319:                     &mt('Availability determined currently from default setting.');
  320:                 if (!$curr_access) {
  321:                     $tool_off = 'checked="checked" ';
  322:                     $tool_on = '';
  323:                 }
  324:             } else {
  325:                 $custom_access =
  326:                     &mt('Availability determined currently from custom setting.');
  327:                 if ($userenv{$context.'.'.$item} == 0) {
  328:                     $tool_off = 'checked="checked" ';
  329:                     $tool_on = '';
  330:                 }
  331:             }
  332:         }
  333:         $output .= '  <tr class="LC_info_row">'."\n".
  334:                    '   <td'.$colspan.'>'.$lt{$item}.'</td>'."\n".
  335:                    '  </tr>'."\n".
  336:                    &Apache::loncommon::start_data_table_row()."\n";
  337:         if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
  338:             my ($curroption,$currlimit);
  339:             my $envkey = $context.'.'.$item;
  340:             if ($context eq 'requestauthor') {
  341:                 $envkey = $context;
  342:             }
  343:             if ($userenv{$envkey} ne '') {
  344:                 $curroption = $userenv{$envkey};
  345:             } else {
  346:                 my (@inststatuses);
  347:                 if ($context eq 'requestcourses') {
  348:                     $curroption =
  349:                         &Apache::loncoursequeueadmin::get_processtype('course',$ccuname,$ccdomain,
  350:                                                                       $isadv,$ccdomain,$item,
  351:                                                                       \@inststatuses,\%domconfig);
  352:                 } else {
  353:                      $curroption = 
  354:                          &Apache::loncoursequeueadmin::get_processtype('requestauthor',$ccuname,$ccdomain,
  355:                                                                        $isadv,$ccdomain,undef,
  356:                                                                        \@inststatuses,\%domconfig);
  357:                 }
  358:             }
  359:             if (!$curroption) {
  360:                 $curroption = 'norequest';
  361:             }
  362:             if ($curroption =~ /^autolimit=(\d*)$/) {
  363:                 $currlimit = $1;
  364:                 if ($currlimit eq '') {
  365:                     $currdisp = &mt('Yes, automatic creation');
  366:                 } else {
  367:                     $currdisp = &mt('Yes, up to [quant,_1,request]/user',$currlimit);
  368:                 }
  369:             } else {
  370:                 $currdisp = $reqdisplay{$curroption};
  371:             }
  372:             $custdisp = '<table>';
  373:             foreach my $option (@options) {
  374:                 my $val = $option;
  375:                 if ($option eq 'norequest') {
  376:                     $val = 0;
  377:                 }
  378:                 if ($option eq 'validate') {
  379:                     my $canvalidate = 0;
  380:                     if (ref($validations{$item}) eq 'HASH') {
  381:                         if ($validations{$item}{'_custom_'}) {
  382:                             $canvalidate = 1;
  383:                         }
  384:                     }
  385:                     next if (!$canvalidate);
  386:                 }
  387:                 my $checked = '';
  388:                 if ($option eq $curroption) {
  389:                     $checked = ' checked="checked"';
  390:                 } elsif ($option eq 'autolimit') {
  391:                     if ($curroption =~ /^autolimit/) {
  392:                         $checked = ' checked="checked"';
  393:                     }
  394:                 }
  395:                 my $name = 'crsreq_'.$item;
  396:                 if ($context eq 'requestauthor') {
  397:                     $name = $item;
  398:                 }
  399:                 $custdisp .= '<tr><td><span class="LC_nobreak"><label>'.
  400:                              '<input type="radio" name="'.$name.'" '.
  401:                              'value="'.$val.'"'.$checked.' />'.
  402:                              $reqtitles{$option}.'</label>&nbsp;';
  403:                 if ($option eq 'autolimit') {
  404:                     $custdisp .= '<input type="text" name="'.$name.
  405:                                  '_limit" size="1" '.
  406:                                  'value="'.$currlimit.'" /></span><br />'.
  407:                                  $reqtitles{'unlimited'};
  408:                 } else {
  409:                     $custdisp .= '</span>';
  410:                 }
  411:                 $custdisp .= '</td></tr>';
  412:             }
  413:             $custdisp .= '</table>';
  414:             $custradio = '</span></td><td>'.&mt('Custom setting').'<br />'.$custdisp;
  415:         } else {
  416:             $currdisp = ($curr_access?&mt('Yes'):&mt('No'));
  417:             my $name = $context.'_'.$item;
  418:             if ($context eq 'requestauthor') {
  419:                 $name = $context;
  420:             }
  421:             $custdisp = '<span class="LC_nobreak"><label>'.
  422:                         '<input type="radio" name="'.$name.'"'.
  423:                         ' value="1" '.$tool_on.'/>'.&mt('On').'</label>&nbsp;<label>'.
  424:                         '<input type="radio" name="'.$name.'" value="0" '.
  425:                         $tool_off.'/>'.&mt('Off').'</label></span>';
  426:             $custradio = ('&nbsp;'x2).'--'.$lt{'cusa'}.':&nbsp;'.$custdisp.
  427:                           '</span>';
  428:         }
  429:         $output .= '  <td'.$colspan.'>'.$custom_access.('&nbsp;'x4).
  430:                    $lt{'avai'}.': '.$currdisp.'</td>'."\n".
  431:                    &Apache::loncommon::end_data_table_row()."\n".
  432:                    &Apache::loncommon::start_data_table_row()."\n".
  433:                    '  <td style="vertical-align:top;"><span class="LC_nobreak">'.
  434:                    $lt{'chse'}.': <label>'.
  435:                    '<input type="radio" name="custom'.$item.'" value="0" '.
  436:                    $cust_off.'/>'.$lt{'usde'}.'</label>'.('&nbsp;' x3).
  437:                    '<label><input type="radio" name="custom'.$item.'" value="1" '.
  438:                    $cust_on.'/>'.$lt{'uscu'}.'</label>'.$custradio.'</td>'.
  439:                    &Apache::loncommon::end_data_table_row()."\n";
  440:     }
  441:     return $output;
  442: }
  443: 
  444: sub coursereq_externaluser {
  445:     my ($ccuname,$ccdomain,$cdom) = @_;
  446:     my (@usertools,@options,%validations,%userenv,$output);
  447:     my %lt = &Apache::lonlocal::texthash (
  448:                    'official'   => 'Can request creation of official courses',
  449:                    'unofficial' => 'Can request creation of unofficial courses',
  450:                    'community'  => 'Can request creation of communities',
  451:                    'textbook'   => 'Can request creation of textbook courses',
  452:                    'placement'  => 'Can request creation of placement tests',
  453:     );
  454: 
  455:     %userenv = &Apache::lonnet::userenvironment($ccdomain,$ccuname,
  456:                       'reqcrsotherdom.official','reqcrsotherdom.unofficial',
  457:                       'reqcrsotherdom.community','reqcrsotherdom.textbook',
  458:                       'reqcrsotherdom.placement');
  459:     @usertools = ('official','unofficial','community','textbook','placement');
  460:     @options = ('approval','validate','autolimit');
  461:     %validations = &Apache::lonnet::auto_courserequest_checks($cdom);
  462:     my $optregex = join('|',@options);
  463:     my %reqtitles = &courserequest_titles();
  464:     foreach my $item (@usertools) {
  465:         my ($curroption,$currlimit,$tooloff);
  466:         if ($userenv{'reqcrsotherdom.'.$item} ne '') {
  467:             my @curr = split(',',$userenv{'reqcrsotherdom.'.$item});
  468:             foreach my $req (@curr) {
  469:                 if ($req =~ /^\Q$cdom\E\:($optregex)=?(\d*)$/) {
  470:                     $curroption = $1;
  471:                     $currlimit = $2;
  472:                     last;
  473:                 }
  474:             }
  475:             if (!$curroption) {
  476:                 $curroption = 'norequest';
  477:                 $tooloff = ' checked="checked"';
  478:             }
  479:         } else {
  480:             $curroption = 'norequest';
  481:             $tooloff = ' checked="checked"';
  482:         }
  483:         $output.= &Apache::loncommon::start_data_table_row()."\n".
  484:                   '  <td><span class="LC_nobreak">'.$lt{$item}.': </span></td><td>'.
  485:                   '<table><tr><td valign="top">'."\n".
  486:                   '<label><input type="radio" name="reqcrsotherdom_'.$item.
  487:                   '" value=""'.$tooloff.' />'.$reqtitles{'norequest'}.
  488:                   '</label></td>';
  489:         foreach my $option (@options) {
  490:             if ($option eq 'validate') {
  491:                 my $canvalidate = 0;
  492:                 if (ref($validations{$item}) eq 'HASH') {
  493:                     if ($validations{$item}{'_external_'}) {
  494:                         $canvalidate = 1;
  495:                     }
  496:                 }
  497:                 next if (!$canvalidate);
  498:             }
  499:             my $checked = '';
  500:             if ($option eq $curroption) {
  501:                 $checked = ' checked="checked"';
  502:             }
  503:             $output .= '<td valign="top"><span class="LC_nobreak"><label>'.
  504:                        '<input type="radio" name="reqcrsotherdom_'.$item.
  505:                        '" value="'.$option.'"'.$checked.' />'.
  506:                        $reqtitles{$option}.'</label>';
  507:             if ($option eq 'autolimit') {
  508:                 $output .= '&nbsp;<input type="text" name="reqcrsotherdom_'.
  509:                            $item.'_limit" size="1" '.
  510:                            'value="'.$currlimit.'" /></span>'.
  511:                            '<br />'.$reqtitles{'unlimited'};
  512:             } else {
  513:                 $output .= '</span>';
  514:             }
  515:             $output .= '</td>';
  516:         }
  517:         $output .= '</td></tr></table></td>'."\n".
  518:                    &Apache::loncommon::end_data_table_row()."\n";
  519:     }
  520:     return $output;
  521: }
  522: 
  523: sub domainrole_req {
  524:     my ($ccuname,$ccdomain) = @_;
  525:     return '<br /><h3>'.
  526:            &mt('User Can Request Assignment of Domain Roles?').
  527:            '</h3>'."\n".
  528:            &Apache::loncommon::start_data_table().
  529:            &build_tools_display($ccuname,$ccdomain,
  530:                                 'requestauthor').
  531:            &Apache::loncommon::end_data_table();
  532: }
  533: 
  534: sub domadhocroles {
  535:     my ($ccuname,$ccdomain) = @_;
  536:     my $confname = &Apache::lonnet::get_domainconfiguser($env{'request.role.domain'}); 
  537:     my %existing=&Apache::lonnet::dump('roles',$env{'request.role.domain'},
  538:                                        $confname,'rolesdef_');
  539:     my $output;
  540:     if (keys(%existing) > 0) {
  541:         my @current;
  542:         my $curradhoc = 'adhocroles.'.$env{'request.role.domain'}; 
  543:         my %userenv = &Apache::lonnet::userenvironment($ccdomain,$ccuname,$curradhoc);
  544:         if ($userenv{$curradhoc}) {
  545:             @current = split(/,/,$userenv{$curradhoc});
  546:         }
  547:         my %customroles;
  548:         foreach my $key (keys(%existing)) {
  549:             if ($key=~/^rolesdef\_(\w+)$/) {
  550:                 my $rolename = $1;
  551:                 my %privs;
  552:                 ($privs{'system'},$privs{'domain'},$privs{'course'}) = split(/\_/,$existing{$key});
  553:                 $customroles{$rolename} = \%privs;
  554:             }
  555:         }
  556:         $output = '<br /><h3>'.
  557:                   &mt('Ad Hoc Course Roles Selectable via Helpdesk Role').
  558:                   '</h3>'."\n".
  559:                   &Apache::loncommon::start_data_table().
  560:                   &Apache::loncommon::start_data_table_header_row().
  561:                   '<th>'.&mt('Action').'</th><th>'.&mt('Role').'</th>'.
  562:                   '<th>'.&mt('Privileges in Course').'<th>'.
  563:                   &Apache::loncommon::end_data_table_header_row(); 
  564:         foreach my $key (sort(keys(%customroles))) {
  565:             $output .= &Apache::loncommon::start_data_table_row();
  566:             if (grep(/^\Q$key\E$/,@current)) {
  567:                 $output .= '<td><label>'.
  568:                            '<input type="checkbox" name="adhocroledel" value="'.$key.'" />'.
  569:                            &mt('Delete').'</label>'.
  570:                            '</td>';
  571:             } else {
  572:                 $output .= '<td><label>'.
  573:                            '<input type="checkbox" name="adhocroleadd" value="'.$key.'" />'.
  574:                            &mt('Add').'</label>'.
  575:                            '</td>';
  576:             }
  577:             $output .= '<td>'.$key.'</td><td>';
  578:             foreach my $level ('course','domain','system') {
  579:                 if ($customroles{$key}{$level}) {
  580:                     my $suffix;
  581:                     if (($level eq 'domain') || ($level eq 'system')) {
  582:                         $suffix = '&nbsp;('.&mt($level).')';
  583:                     }
  584:                     my @privs = split(/:/,$customroles{$key}{$level});
  585:                     foreach my $item (@privs) {
  586:                         next if ($item eq ''); 
  587:                         my ($priv,$cond) = split(/\&/,$item);
  588:                         $output .= &Apache::lonnet::plaintext($priv,'Course').$suffix.'<br />';
  589:                     }
  590:                 }
  591:             }
  592:             $output .= '</td>'.
  593:                        &Apache::loncommon::end_data_table_row();
  594:         }
  595:         $output .= &Apache::loncommon::end_data_table();
  596:     }
  597:     return $output;
  598: }
  599: 
  600: sub courserequest_titles {
  601:     my %titles = &Apache::lonlocal::texthash (
  602:                                    official   => 'Official',
  603:                                    unofficial => 'Unofficial',
  604:                                    community  => 'Communities',
  605:                                    textbook   => 'Textbook',
  606:                                    placement  => 'Placement Tests',
  607:                                    norequest  => 'Not allowed',
  608:                                    approval   => 'Approval by Dom. Coord.',
  609:                                    validate   => 'With validation',
  610:                                    autolimit  => 'Numerical limit',
  611:                                    unlimited  => '(blank for unlimited)',
  612:                  );
  613:     return %titles;
  614: }
  615: 
  616: sub courserequest_display {
  617:     my %titles = &Apache::lonlocal::texthash (
  618:                                    approval   => 'Yes, need approval',
  619:                                    validate   => 'Yes, with validation',
  620:                                    norequest  => 'No',
  621:    );
  622:    return %titles;
  623: }
  624: 
  625: sub requestauthor_titles {
  626:     my %titles = &Apache::lonlocal::texthash (
  627:                                    norequest  => 'Not allowed',
  628:                                    approval   => 'Approval by Dom. Coord.',
  629:                                    automatic  => 'Automatic approval',
  630:                  );
  631:     return %titles;
  632: 
  633: }
  634: 
  635: sub requestauthor_display {
  636:     my %titles = &Apache::lonlocal::texthash (
  637:                                    approval   => 'Yes, need approval',
  638:                                    automatic  => 'Yes, automatic approval',
  639:                                    norequest  => 'No',
  640:    );
  641:    return %titles;
  642: }
  643: 
  644: sub requestchange_display {
  645:     my %titles = &Apache::lonlocal::texthash (
  646:                                    approval   => "availability set to 'on' (approval required)", 
  647:                                    automatic  => "availability set to 'on' (automatic approval)",
  648:                                    norequest  => "availability set to 'off'",
  649:    );
  650:    return %titles;
  651: }
  652: 
  653: sub curr_requestauthor {
  654:     my ($uname,$udom,$isadv,$inststatuses,$domconfig) = @_;
  655:     return unless ((ref($inststatuses) eq 'ARRAY') && (ref($domconfig) eq 'HASH'));
  656:     if ($uname eq '' || $udom eq '') {
  657:         $uname = $env{'user.name'};
  658:         $udom = $env{'user.domain'};
  659:         $isadv = $env{'user.adv'};
  660:     }
  661:     my (%userenv,%settings,$val);
  662:     my @options = ('automatic','approval');
  663:     %userenv =
  664:         &Apache::lonnet::userenvironment($udom,$uname,'requestauthor','inststatus');
  665:     if ($userenv{'requestauthor'}) {
  666:         $val = $userenv{'requestauthor'};
  667:         @{$inststatuses} = ('_custom_');
  668:     } else {
  669:         my %alltasks;
  670:         if (ref($domconfig->{'requestauthor'}) eq 'HASH') {
  671:             %settings = %{$domconfig->{'requestauthor'}};
  672:             if (($isadv) && ($settings{'_LC_adv'} ne '')) {
  673:                 $val = $settings{'_LC_adv'};
  674:                 @{$inststatuses} = ('_LC_adv_');
  675:             } else {
  676:                 if ($userenv{'inststatus'} ne '') {
  677:                     @{$inststatuses} = split(',',$userenv{'inststatus'});
  678:                 } else {
  679:                     @{$inststatuses} = ('default');
  680:                 }
  681:                 foreach my $status (@{$inststatuses}) {
  682:                     if (exists($settings{$status})) {
  683:                         my $value = $settings{$status};
  684:                         next unless ($value);
  685:                         unless (exists($alltasks{$value})) {
  686:                             if (ref($alltasks{$value}) eq 'ARRAY') {
  687:                                 unless(grep(/^\Q$status\E$/,@{$alltasks{$value}})) {
  688:                                     push(@{$alltasks{$value}},$status);
  689:                                 }
  690:                             } else {
  691:                                 @{$alltasks{$value}} = ($status);
  692:                             }
  693:                         }
  694:                     }
  695:                 }
  696:                 foreach my $option (@options) {
  697:                     if ($alltasks{$option}) {
  698:                         $val = $option;
  699:                         last;
  700:                     }
  701:                 }
  702:             }
  703:         }
  704:     }
  705:     return $val;
  706: }
  707: 
  708: # =================================================================== Phase one
  709: 
  710: sub print_username_entry_form {
  711:     my ($r,$context,$response,$srch,$forcenewuser,$crstype,$brcrum) = @_;
  712:     my $defdom=$env{'request.role.domain'};
  713:     my $formtoset = 'crtuser';
  714:     if (exists($env{'form.startrolename'})) {
  715:         $formtoset = 'docustom';
  716:         $env{'form.rolename'} = $env{'form.startrolename'};
  717:     } elsif ($env{'form.origform'} eq 'crtusername') {
  718:         $formtoset =  $env{'form.origform'};
  719:     }
  720: 
  721:     my ($jsback,$elements) = &crumb_utilities();
  722: 
  723:     my $jscript = &Apache::loncommon::studentbrowser_javascript()."\n".
  724:         '<script type="text/javascript">'."\n".
  725:         '// <![CDATA['."\n".
  726:         &Apache::lonhtmlcommon::set_form_elements($elements->{$formtoset})."\n".
  727:         '// ]]>'."\n".
  728:         '</script>'."\n";
  729: 
  730:     my %existingroles=&Apache::lonuserutils::my_custom_roles($crstype);
  731:     if (($env{'form.action'} eq 'custom') && (keys(%existingroles) > 0)
  732:         && (&Apache::lonnet::allowed('mcr','/'))) {
  733:         $jscript .= &customrole_javascript();
  734:     }
  735:     my $helpitem = 'Course_Change_Privileges';
  736:     if ($env{'form.action'} eq 'custom') {
  737:         $helpitem = 'Course_Editing_Custom_Roles';
  738:     } elsif ($env{'form.action'} eq 'singlestudent') {
  739:         $helpitem = 'Course_Add_Student';
  740:     }
  741:     my %breadcrumb_text = &singleuser_breadcrumb($crstype);
  742:     if ($env{'form.action'} eq 'custom') {
  743:         push(@{$brcrum},
  744:                  {href=>"javascript:backPage(document.crtuser)",       
  745:                   text=>"Pick custom role",
  746:                   help => $helpitem,}
  747:                  );
  748:     } else {
  749:         push (@{$brcrum},
  750:                   {href => "javascript:backPage(document.crtuser)",
  751:                    text => $breadcrumb_text{'search'},
  752:                    help => $helpitem,
  753:                    faq  => 282,
  754:                    bug  => 'Instructor Interface',}
  755:                   );
  756:     }
  757:     my %loaditems = (
  758:                 'onload' => "javascript:setFormElements(document.$formtoset)",
  759:                     );
  760:     my $args = {bread_crumbs           => $brcrum,
  761:                 bread_crumbs_component => 'User Management',
  762:                 add_entries            => \%loaditems,};
  763:     $r->print(&Apache::loncommon::start_page('User Management',$jscript,$args));
  764: 
  765:     my %lt=&Apache::lonlocal::texthash(
  766:                     'srst' => 'Search for a user and enroll as a student',
  767:                     'srme' => 'Search for a user and enroll as a member',
  768:                     'srad' => 'Search for a user and modify/add user information or roles',
  769: 		    'usr'  => "Username",
  770:                     'dom'  => "Domain",
  771:                     'ecrp' => "Define or Edit Custom Role",
  772:                     'nr'   => "role name",
  773:                     'cre'  => "Next",
  774: 				       );
  775: 
  776:     if ($env{'form.action'} eq 'custom') {
  777:         if (&Apache::lonnet::allowed('mcr','/')) {
  778:             my $newroletext = &mt('Define new custom role:');
  779:             $r->print('<form action="/adm/createuser" method="post" name="docustom">'.
  780:                       '<input type="hidden" name="action" value="'.$env{'form.action'}.'" />'.
  781:                       '<input type="hidden" name="phase" value="selected_custom_edit" />'.
  782:                       '<h3>'.$lt{'ecrp'}.'</h3>'.
  783:                       &Apache::loncommon::start_data_table().
  784:                       &Apache::loncommon::start_data_table_row().
  785:                       '<td>');
  786:             if (keys(%existingroles) > 0) {
  787:                 $r->print('<br /><label><input type="radio" name="customroleaction" value="new" checked="checked" onclick="setCustomFields();" /><b>'.$newroletext.'</b></label>');
  788:             } else {
  789:                 $r->print('<br /><input type="hidden" name="customroleaction" value="new" /><b>'.$newroletext.'</b>');
  790:             }
  791:             $r->print('</td><td align="center">'.$lt{'nr'}.'<br /><input type="text" size="15" name="newrolename" onfocus="setCustomAction('."'new'".');" /></td>'.
  792:                       &Apache::loncommon::end_data_table_row());
  793:             if (keys(%existingroles) > 0) {
  794:                 $r->print(&Apache::loncommon::start_data_table_row().'<td><br />'.
  795:                           '<label><input type="radio" name="customroleaction" value="edit" onclick="setCustomFields();"/><b>'.
  796:                           &mt('View/Modify existing role:').'</b></label></td>'.
  797:                           '<td align="center"><br />'.
  798:                           '<select name="rolename" onchange="setCustomAction('."'edit'".');">'.
  799:                           '<option value="" selected="selected">'.
  800:                           &mt('Select'));
  801:                 foreach my $role (sort(keys(%existingroles))) {
  802:                     $r->print('<option value="'.$role.'">'.$role.'</option>');
  803:                 }
  804:                 $r->print('</select>'.
  805:                           '</td>'.
  806:                           &Apache::loncommon::end_data_table_row());
  807:             }
  808:             $r->print(&Apache::loncommon::end_data_table().'<p>'.
  809:                       '<input name="customeditor" type="submit" value="'.
  810:                       $lt{'cre'}.'" /></p>'.
  811:                       '</form>');
  812:         }
  813:     } else {
  814:         my $actiontext = $lt{'srad'};
  815:         if ($env{'form.action'} eq 'singlestudent') {
  816:             if ($crstype eq 'Community') {
  817:                 $actiontext = $lt{'srme'};
  818:             } else {
  819:                 $actiontext = $lt{'srst'};
  820:             }
  821:         }
  822:         $r->print("<h3>$actiontext</h3>");
  823:         if ($env{'form.origform'} ne 'crtusername') {
  824:             if ($response) {
  825:                $r->print("\n<div>$response</div>".
  826:                          '<br clear="all" />');
  827:             }
  828:         }
  829:         $r->print(&entry_form($defdom,$srch,$forcenewuser,$context,$response,$crstype));
  830:     }
  831: }
  832: 
  833: sub customrole_javascript {
  834:     my $js = <<"END";
  835: <script type="text/javascript">
  836: // <![CDATA[
  837: 
  838: function setCustomFields() {
  839:     if (document.docustom.customroleaction.length > 0) {
  840:         for (var i=0; i<document.docustom.customroleaction.length; i++) {
  841:             if (document.docustom.customroleaction[i].checked) {
  842:                 if (document.docustom.customroleaction[i].value == 'new') {
  843:                     document.docustom.rolename.selectedIndex = 0;
  844:                 } else {
  845:                     document.docustom.newrolename.value = '';
  846:                 }
  847:             }
  848:         }
  849:     }
  850:     return;
  851: }
  852: 
  853: function setCustomAction(caller) {
  854:     if (document.docustom.customroleaction.length > 0) {
  855:         for (var i=0; i<document.docustom.customroleaction.length; i++) {
  856:             if (document.docustom.customroleaction[i].value == caller) {
  857:                 document.docustom.customroleaction[i].checked = true;
  858:             }
  859:         }
  860:     }
  861:     setCustomFields();
  862:     return;
  863: }
  864: 
  865: // ]]>
  866: </script>
  867: END
  868:     return $js;
  869: }
  870: 
  871: sub entry_form {
  872:     my ($dom,$srch,$forcenewuser,$context,$responsemsg,$crstype) = @_;
  873:     my ($usertype,$inexact);
  874:     if (ref($srch) eq 'HASH') {
  875:         if (($srch->{'srchin'} eq 'dom') &&
  876:             ($srch->{'srchby'} eq 'uname') &&
  877:             ($srch->{'srchtype'} eq 'exact') &&
  878:             ($srch->{'srchdomain'} ne '') &&
  879:             ($srch->{'srchterm'} ne '')) {
  880:             my (%curr_rules,%got_rules);
  881:             my ($rules,$ruleorder) =
  882:                 &Apache::lonnet::inst_userrules($srch->{'srchdomain'},'username');
  883:             $usertype = &Apache::lonuserutils::check_usertype($srch->{'srchdomain'},$srch->{'srchterm'},$rules,\%curr_rules,\%got_rules);
  884:         } else {
  885:             $inexact = 1;
  886:         }
  887:     }
  888:     my $cancreate =
  889:         &Apache::lonuserutils::can_create_user($dom,$context,$usertype);
  890:     my ($userpicker,$cansearch) = 
  891:        &Apache::loncommon::user_picker($dom,$srch,$forcenewuser,
  892:                                        'document.crtuser',$cancreate,$usertype);
  893:     my $srchbutton = &mt('Search');
  894:     if ($env{'form.action'} eq 'singlestudent') {
  895:         $srchbutton = &mt('Search and Enroll');
  896:     } elsif ($cancreate && $responsemsg ne '' && $inexact) {
  897:         $srchbutton = &mt('Search or Add New User');
  898:     }
  899:     my $output;
  900:     if ($cansearch) {
  901:         $output = <<"ENDBLOCK";
  902: <form action="/adm/createuser" method="post" name="crtuser">
  903: <input type="hidden" name="action" value="$env{'form.action'}" />
  904: <input type="hidden" name="phase" value="get_user_info" />
  905: $userpicker
  906: <input name="userrole" type="button" value="$srchbutton" onclick="javascript:validateEntry(document.crtuser)" />
  907: </form>
  908: ENDBLOCK
  909:     } else {
  910:         $output = '<p>'.$userpicker.'</p>';
  911:     }
  912:     if ($env{'form.phase'} eq '') {
  913:         my $defdom=$env{'request.role.domain'};
  914:         my $domform = &Apache::loncommon::select_dom_form($defdom,'srchdomain');
  915:         my %lt=&Apache::lonlocal::texthash(
  916:                   'enro' => 'Enroll one student',
  917:                   'enrm' => 'Enroll one member',
  918:                   'admo' => 'Add/modify a single user',
  919:                   'crea' => 'create new user if required',
  920:                   'uskn' => "username is known",
  921:                   'crnu' => 'Create a new user',
  922:                   'usr'  => 'Username',
  923:                   'dom'  => 'in domain',
  924:                   'enrl' => 'Enroll',
  925:                   'cram'  => 'Create/Modify user',
  926:         );
  927:         my $sellink=&Apache::loncommon::selectstudent_link('crtusername','srchterm','srchdomain');
  928:         my ($title,$buttontext,$showresponse);
  929:         if ($env{'form.action'} eq 'singlestudent') {
  930:             if ($crstype eq 'Community') {
  931:                 $title = $lt{'enrm'};
  932:             } else {
  933:                 $title = $lt{'enro'};
  934:             }
  935:             $buttontext = $lt{'enrl'};
  936:         } else {
  937:             $title = $lt{'admo'};
  938:             $buttontext = $lt{'cram'};
  939:         }
  940:         if ($cancreate) {
  941:             $title .= ' <span class="LC_cusr_subheading">('.$lt{'crea'}.')</span>';
  942:         } else {
  943:             $title .= ' <span class="LC_cusr_subheading">('.$lt{'uskn'}.')</span>';
  944:         }
  945:         if ($env{'form.origform'} eq 'crtusername') {
  946:             $showresponse = $responsemsg;
  947:         }
  948:         $output .= <<"ENDDOCUMENT";
  949: <br />
  950: <form action="/adm/createuser" method="post" name="crtusername">
  951: <input type="hidden" name="action" value="$env{'form.action'}" />
  952: <input type="hidden" name="phase" value="createnewuser" />
  953: <input type="hidden" name="srchtype" value="exact" />
  954: <input type="hidden" name="srchby" value="uname" />
  955: <input type="hidden" name="srchin" value="dom" />
  956: <input type="hidden" name="forcenewuser" value="1" />
  957: <input type="hidden" name="origform" value="crtusername" />
  958: <h3>$title</h3>
  959: $showresponse
  960: <table>
  961:  <tr>
  962:   <td>$lt{'usr'}:</td>
  963:   <td><input type="text" size="15" name="srchterm" /></td>
  964:   <td>&nbsp;$lt{'dom'}:</td><td>$domform</td>
  965:   <td>&nbsp;$sellink&nbsp;</td>
  966:   <td>&nbsp;<input name="userrole" type="submit" value="$buttontext" /></td>
  967:  </tr>
  968: </table>
  969: </form>
  970: ENDDOCUMENT
  971:     }
  972:     return $output;
  973: }
  974: 
  975: sub user_modification_js {
  976:     my ($pjump_def,$dc_setcourse_code,$nondc_setsection_code,$groupslist)=@_;
  977:     
  978:     return <<END;
  979: <script type="text/javascript" language="Javascript">
  980: // <![CDATA[
  981: 
  982:     $pjump_def
  983:     $dc_setcourse_code
  984: 
  985:     function dateset() {
  986:         eval("document.cu."+document.cu.pres_marker.value+
  987:             ".value=document.cu.pres_value.value");
  988:         modalWindow.close();
  989:     }
  990: 
  991:     $nondc_setsection_code
  992: // ]]>
  993: </script>
  994: END
  995: }
  996: 
  997: # =================================================================== Phase two
  998: sub print_user_selection_page {
  999:     my ($r,$response,$srch,$srch_results,$srcharray,$context,$opener_elements,$crstype,$brcrum) = @_;
 1000:     my @fields = ('username','domain','lastname','firstname','permanentemail');
 1001:     my $sortby = $env{'form.sortby'};
 1002: 
 1003:     if (!grep(/^\Q$sortby\E$/,@fields)) {
 1004:         $sortby = 'lastname';
 1005:     }
 1006: 
 1007:     my ($jsback,$elements) = &crumb_utilities();
 1008: 
 1009:     my $jscript = (<<ENDSCRIPT);
 1010: <script type="text/javascript">
 1011: // <![CDATA[
 1012: function pickuser(uname,udom) {
 1013:     document.usersrchform.seluname.value=uname;
 1014:     document.usersrchform.seludom.value=udom;
 1015:     document.usersrchform.phase.value="userpicked";
 1016:     document.usersrchform.submit();
 1017: }
 1018: 
 1019: $jsback
 1020: // ]]>
 1021: </script>
 1022: ENDSCRIPT
 1023: 
 1024:     my %lt=&Apache::lonlocal::texthash(
 1025:                                        'usrch'          => "User Search to add/modify roles",
 1026:                                        'stusrch'        => "User Search to enroll student",
 1027:                                        'memsrch'        => "User Search to enroll member",
 1028:                                        'usel'           => "Select a user to add/modify roles",
 1029:                                        'stusel'         => "Select a user to enroll as a student",
 1030:                                        'memsel'         => "Select a user to enroll as a member",
 1031:                                        'username'       => "username",
 1032:                                        'domain'         => "domain",
 1033:                                        'lastname'       => "last name",
 1034:                                        'firstname'      => "first name",
 1035:                                        'permanentemail' => "permanent e-mail",
 1036:                                       );
 1037:     if ($context eq 'requestcrs') {
 1038:         $r->print('<div>');
 1039:     } else {
 1040:         my %breadcrumb_text = &singleuser_breadcrumb($crstype);
 1041:         my $helpitem;
 1042:         if ($env{'form.action'} eq 'singleuser') {
 1043:             $helpitem = 'Course_Change_Privileges';
 1044:         } elsif ($env{'form.action'} eq 'singlestudent') {
 1045:             $helpitem = 'Course_Add_Student';
 1046:         }
 1047:         push (@{$brcrum},
 1048:                   {href => "javascript:backPage(document.usersrchform,'','')",
 1049:                    text => $breadcrumb_text{'search'},
 1050:                    faq  => 282,
 1051:                    bug  => 'Instructor Interface',},
 1052:                   {href => "javascript:backPage(document.usersrchform,'get_user_info','select')",
 1053:                    text => $breadcrumb_text{'userpicked'},
 1054:                    faq  => 282,
 1055:                    bug  => 'Instructor Interface',
 1056:                    help => $helpitem}
 1057:                   );
 1058:         $r->print(&Apache::loncommon::start_page('User Management',$jscript,{bread_crumbs => $brcrum}));
 1059:         if ($env{'form.action'} eq 'singleuser') {
 1060:             $r->print("<b>$lt{'usrch'}</b><br />");
 1061:             $r->print(&entry_form($srch->{'srchdomain'},$srch,undef,$context,undef,$crstype));
 1062:             $r->print('<h3>'.$lt{'usel'}.'</h3>');
 1063:         } elsif ($env{'form.action'} eq 'singlestudent') {
 1064:             $r->print($jscript."<b>");
 1065:             if ($crstype eq 'Community') {
 1066:                 $r->print($lt{'memsrch'});
 1067:             } else {
 1068:                 $r->print($lt{'stusrch'});
 1069:             }
 1070:             $r->print("</b><br />");
 1071:             $r->print(&entry_form($srch->{'srchdomain'},$srch,undef,$context,undef,$crstype));
 1072:             $r->print('</form><h3>');
 1073:             if ($crstype eq 'Community') {
 1074:                 $r->print($lt{'memsel'});
 1075:             } else {
 1076:                 $r->print($lt{'stusel'});
 1077:             }
 1078:             $r->print('</h3>');
 1079:         }
 1080:     }
 1081:     $r->print('<form name="usersrchform" method="post" action="">'.
 1082:               &Apache::loncommon::start_data_table()."\n".
 1083:               &Apache::loncommon::start_data_table_header_row()."\n".
 1084:               ' <th> </th>'."\n");
 1085:     foreach my $field (@fields) {
 1086:         $r->print(' <th><a href="javascript:document.usersrchform.sortby.value='.
 1087:                   "'".$field."'".';document.usersrchform.submit();">'.
 1088:                   $lt{$field}.'</a></th>'."\n");
 1089:     }
 1090:     $r->print(&Apache::loncommon::end_data_table_header_row());
 1091: 
 1092:     my @sorted_users = sort {
 1093:         lc($srch_results->{$a}->{$sortby})   cmp lc($srch_results->{$b}->{$sortby})
 1094:             ||
 1095:         lc($srch_results->{$a}->{lastname})  cmp lc($srch_results->{$b}->{lastname})
 1096:             ||
 1097:         lc($srch_results->{$a}->{firstname}) cmp lc($srch_results->{$b}->{firstname})
 1098: 	    ||
 1099: 	lc($a) cmp lc($b)
 1100:         } (keys(%$srch_results));
 1101: 
 1102:     foreach my $user (@sorted_users) {
 1103:         my ($uname,$udom) = split(/:/,$user);
 1104:         my $onclick;
 1105:         if ($context eq 'requestcrs') {
 1106:             $onclick =
 1107:                 'onclick="javascript:gochoose('."'$uname','$udom',".
 1108:                                                "'$srch_results->{$user}->{firstname}',".
 1109:                                                "'$srch_results->{$user}->{lastname}',".
 1110:                                                "'$srch_results->{$user}->{permanentemail}'".');"';
 1111:         } else {
 1112:             $onclick =
 1113:                 ' onclick="javascript:pickuser('."'".$uname."'".','."'".$udom."'".');"';
 1114:         }
 1115:         $r->print(&Apache::loncommon::start_data_table_row().
 1116:                   '<td><input type="button" name="seluser" value="'.&mt('Select').'" '.
 1117:                   $onclick.' /></td>'.
 1118:                   '<td><tt>'.$uname.'</tt></td>'.
 1119:                   '<td><tt>'.$udom.'</tt></td>');
 1120:         foreach my $field ('lastname','firstname','permanentemail') {
 1121:             $r->print('<td>'.$srch_results->{$user}->{$field}.'</td>');
 1122:         }
 1123:         $r->print(&Apache::loncommon::end_data_table_row());
 1124:     }
 1125:     $r->print(&Apache::loncommon::end_data_table().'<br /><br />');
 1126:     if (ref($srcharray) eq 'ARRAY') {
 1127:         foreach my $item (@{$srcharray}) {
 1128:             $r->print('<input type="hidden" name="'.$item.'" value="'.$env{'form.'.$item}.'" />'."\n");
 1129:         }
 1130:     }
 1131:     $r->print(' <input type="hidden" name="sortby" value="'.$sortby.'" />'."\n".
 1132:               ' <input type="hidden" name="seluname" value="" />'."\n".
 1133:               ' <input type="hidden" name="seludom" value="" />'."\n".
 1134:               ' <input type="hidden" name="currstate" value="select" />'."\n".
 1135:               ' <input type="hidden" name="phase" value="get_user_info" />'."\n".
 1136:               ' <input type="hidden" name="action" value="'.$env{'form.action'}.'" />'."\n");
 1137:     if ($context eq 'requestcrs') {
 1138:         $r->print($opener_elements.'</form></div>');
 1139:     } else {
 1140:         $r->print($response.'</form>');
 1141:     }
 1142: }
 1143: 
 1144: sub print_user_query_page {
 1145:     my ($r,$caller,$brcrum) = @_;
 1146: # FIXME - this is for a network-wide name search (similar to catalog search)
 1147: # To use frames with similar behavior to catalog/portfolio search.
 1148: # To be implemented. 
 1149:     return;
 1150: }
 1151: 
 1152: sub print_user_modification_page {
 1153:     my ($r,$ccuname,$ccdomain,$srch,$response,$context,$permission,$crstype,
 1154:         $brcrum,$showcredits) = @_;
 1155:     if (($ccuname eq '') || ($ccdomain eq '')) {
 1156:         my $usermsg = &mt('No username and/or domain provided.');
 1157:         $env{'form.phase'} = '';
 1158: 	&print_username_entry_form($r,$context,$usermsg,'','',$crstype,$brcrum);
 1159:         return;
 1160:     }
 1161:     my ($form,$formname);
 1162:     if ($env{'form.action'} eq 'singlestudent') {
 1163:         $form = 'document.enrollstudent';
 1164:         $formname = 'enrollstudent';
 1165:     } else {
 1166:         $form = 'document.cu';
 1167:         $formname = 'cu';
 1168:     }
 1169:     my %abv_auth = &auth_abbrev();
 1170:     my (%rulematch,%inst_results,$newuser,%alerts,%curr_rules,%got_rules);
 1171:     my $uhome=&Apache::lonnet::homeserver($ccuname,$ccdomain);
 1172:     if ($uhome eq 'no_host') {
 1173:         my $usertype;
 1174:         my ($rules,$ruleorder) =
 1175:             &Apache::lonnet::inst_userrules($ccdomain,'username');
 1176:             $usertype =
 1177:                 &Apache::lonuserutils::check_usertype($ccdomain,$ccuname,$rules,
 1178:                                                       \%curr_rules,\%got_rules);
 1179:         my $cancreate =
 1180:             &Apache::lonuserutils::can_create_user($ccdomain,$context,
 1181:                                                    $usertype);
 1182:         if (!$cancreate) {
 1183:             my $helplink = 'javascript:helpMenu('."'display'".')';
 1184:             my %usertypetext = (
 1185:                 official   => 'institutional',
 1186:                 unofficial => 'non-institutional',
 1187:             );
 1188:             my $response;
 1189:             if ($env{'form.origform'} eq 'crtusername') {
 1190:                 $response = '<span class="LC_warning">'.
 1191:                             &mt('No match found for the username [_1] in LON-CAPA domain: [_2]',
 1192:                                 '<b>'.$ccuname.'</b>',$ccdomain).
 1193:                             '</span><br />';
 1194:             }
 1195:             $response .= '<p class="LC_warning">'
 1196:                         .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
 1197:                         .' '
 1198:                         .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
 1199:                             ,'<a href="'.$helplink.'">','</a>')
 1200:                         .'</p><br />';
 1201:             $env{'form.phase'} = '';
 1202:             &print_username_entry_form($r,$context,$response,undef,undef,$crstype,$brcrum);
 1203:             return;
 1204:         }
 1205:         $newuser = 1;
 1206:         my $checkhash;
 1207:         my $checks = { 'username' => 1 };
 1208:         $checkhash->{$ccuname.':'.$ccdomain} = { 'newuser' => $newuser };
 1209:         &Apache::loncommon::user_rule_check($checkhash,$checks,
 1210:             \%alerts,\%rulematch,\%inst_results,\%curr_rules,\%got_rules);
 1211:         if (ref($alerts{'username'}) eq 'HASH') {
 1212:             if (ref($alerts{'username'}{$ccdomain}) eq 'HASH') {
 1213:                 my $domdesc =
 1214:                     &Apache::lonnet::domain($ccdomain,'description');
 1215:                 if ($alerts{'username'}{$ccdomain}{$ccuname}) {
 1216:                     my $userchkmsg;
 1217:                     if (ref($curr_rules{$ccdomain}) eq 'HASH') {  
 1218:                         $userchkmsg = 
 1219:                             &Apache::loncommon::instrule_disallow_msg('username',
 1220:                                                                  $domdesc,1).
 1221:                         &Apache::loncommon::user_rule_formats($ccdomain,
 1222:                             $domdesc,$curr_rules{$ccdomain}{'username'},
 1223:                             'username');
 1224:                     }
 1225:                     $env{'form.phase'} = '';
 1226:                     &print_username_entry_form($r,$context,$userchkmsg,undef,undef,$crstype,$brcrum);
 1227:                     return;
 1228:                 }
 1229:             }
 1230:         }
 1231:     } else {
 1232:         $newuser = 0;
 1233:     }
 1234:     if ($response) {
 1235:         $response = '<br />'.$response;
 1236:     }
 1237: 
 1238:     my $pjump_def = &Apache::lonhtmlcommon::pjump_javascript_definition();
 1239:     my $dc_setcourse_code = '';
 1240:     my $nondc_setsection_code = '';                                        
 1241:     my %loaditem;
 1242: 
 1243:     my $groupslist = &Apache::lonuserutils::get_groupslist();
 1244: 
 1245:     my $js = &validation_javascript($context,$ccdomain,$pjump_def,$crstype,
 1246:                                $groupslist,$newuser,$formname,\%loaditem);
 1247:     my %breadcrumb_text = &singleuser_breadcrumb($crstype);
 1248:     my $helpitem = 'Course_Change_Privileges';
 1249:     if ($env{'form.action'} eq 'singlestudent') {
 1250:         $helpitem = 'Course_Add_Student';
 1251:     }
 1252:     push (@{$brcrum},
 1253:         {href => "javascript:backPage($form)",
 1254:          text => $breadcrumb_text{'search'},
 1255:          faq  => 282,
 1256:          bug  => 'Instructor Interface',});
 1257:     if ($env{'form.phase'} eq 'userpicked') {
 1258:        push(@{$brcrum},
 1259:               {href => "javascript:backPage($form,'get_user_info','select')",
 1260:                text => $breadcrumb_text{'userpicked'},
 1261:                faq  => 282,
 1262:                bug  => 'Instructor Interface',});
 1263:     }
 1264:     push(@{$brcrum},
 1265:             {href => "javascript:backPage($form,'$env{'form.phase'}','modify')",
 1266:              text => $breadcrumb_text{'modify'},
 1267:              faq  => 282,
 1268:              bug  => 'Instructor Interface',
 1269:              help => $helpitem});
 1270:     my $args = {'add_entries'           => \%loaditem,
 1271:                 'bread_crumbs'          => $brcrum,
 1272:                 'bread_crumbs_component' => 'User Management'};
 1273:     if ($env{'form.popup'}) {
 1274:         $args->{'no_nav_bar'} = 1;
 1275:     }
 1276:     my $start_page =
 1277:         &Apache::loncommon::start_page('User Management',$js,$args);
 1278: 
 1279:     my $forminfo =<<"ENDFORMINFO";
 1280: <form action="/adm/createuser" method="post" name="$formname">
 1281: <input type="hidden" name="phase" value="update_user_data" />
 1282: <input type="hidden" name="ccuname" value="$ccuname" />
 1283: <input type="hidden" name="ccdomain" value="$ccdomain" />
 1284: <input type="hidden" name="pres_value"  value="" />
 1285: <input type="hidden" name="pres_type"   value="" />
 1286: <input type="hidden" name="pres_marker" value="" />
 1287: ENDFORMINFO
 1288:     my (%inccourses,$roledom,$defaultcredits);
 1289:     if ($context eq 'course') {
 1290:         $inccourses{$env{'request.course.id'}}=1;
 1291:         $roledom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 1292:         if ($showcredits) {
 1293:             $defaultcredits = &Apache::lonuserutils::get_defaultcredits();
 1294:         }
 1295:     } elsif ($context eq 'author') {
 1296:         $roledom = $env{'request.role.domain'};
 1297:     } elsif ($context eq 'domain') {
 1298:         foreach my $key (keys(%env)) {
 1299:             $roledom = $env{'request.role.domain'};
 1300:             if ($key=~/^user\.priv\.cm\.\/($roledom)\/($match_username)/) {
 1301:                 $inccourses{$1.'_'.$2}=1;
 1302:             }
 1303:         }
 1304:     } else {
 1305:         foreach my $key (keys(%env)) {
 1306: 	    if ($key=~/^user\.priv\.cm\.\/($match_domain)\/($match_username)/) {
 1307: 	        $inccourses{$1.'_'.$2}=1;
 1308:             }
 1309:         }
 1310:     }
 1311:     my $title = '';
 1312:     if ($newuser) {
 1313:         my ($portfolioform,$domroleform,$adhocroleform);
 1314:         if ((&Apache::lonnet::allowed('mpq',$env{'request.role.domain'})) ||
 1315:             (&Apache::lonnet::allowed('mut',$env{'request.role.domain'}))) {
 1316:             # Current user has quota or user tools modification privileges
 1317:             $portfolioform = '<br />'.&user_quotas($ccuname,$ccdomain);
 1318:         }
 1319:         if ((&Apache::lonnet::allowed('cau',$env{'request.role.domain'})) &&
 1320:             ($ccdomain eq $env{'request.role.domain'})) {
 1321:             $domroleform = '<br />'.&domainrole_req($ccuname,$ccdomain);
 1322:         }
 1323:         if (&Apache::lonnet::allowed('cdh',$env{'request.role.domain'})) {
 1324:             $adhocroleform = &domadhocroles($ccuname,$ccdomain);
 1325:             if ($adhocroleform) {
 1326:                 $adhocroleform = '<br />'.$adhocroleform;
 1327:             }
 1328:         }
 1329:         &initialize_authen_forms($ccdomain,$formname);
 1330:         my %lt=&Apache::lonlocal::texthash(
 1331:                 'lg'             => 'Login Data',
 1332:                 'hs'             => "Home Server",
 1333:         );
 1334: 	$r->print(<<ENDTITLE);
 1335: $start_page
 1336: $response
 1337: $forminfo
 1338: <script type="text/javascript" language="Javascript">
 1339: // <![CDATA[
 1340: $loginscript
 1341: // ]]>
 1342: </script>
 1343: <input type='hidden' name='makeuser' value='1' />
 1344: ENDTITLE
 1345:         if ($env{'form.action'} eq 'singlestudent') {
 1346:             if ($crstype eq 'Community') {
 1347:                 $title = &mt('Create New User [_1] in domain [_2] as a member',
 1348:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1349:             } else {
 1350:                 $title = &mt('Create New User [_1] in domain [_2] as a student',
 1351:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1352:             }
 1353:         } else {
 1354:                 $title = &mt('Create New User [_1] in domain [_2]',
 1355:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1356:         }
 1357:         $r->print('<h2>'.$title.'</h2>'."\n");
 1358:         $r->print('<div class="LC_left_float">');
 1359:         $r->print(&personal_data_display($ccuname,$ccdomain,$newuser,$context,
 1360:                                          $inst_results{$ccuname.':'.$ccdomain}));
 1361:         # Option to disable student/employee ID conflict checking not offerred for new users.
 1362:         my ($home_server_pick,$numlib) = 
 1363:             &Apache::loncommon::home_server_form_item($ccdomain,'hserver',
 1364:                                                       'default','hide');
 1365:         if ($numlib > 1) {
 1366:             $r->print("
 1367: <br />
 1368: $lt{'hs'}: $home_server_pick
 1369: <br />");
 1370:         } else {
 1371:             $r->print($home_server_pick);
 1372:         }
 1373:         if (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) {
 1374:             $r->print('<br /><h3>'.
 1375:                       &mt('User Can Request Creation of Courses/Communities in this Domain?').'</h3>'.
 1376:                       &Apache::loncommon::start_data_table().
 1377:                       &build_tools_display($ccuname,$ccdomain,
 1378:                                            'requestcourses').
 1379:                       &Apache::loncommon::end_data_table());
 1380:         }
 1381:         $r->print('</div>'."\n".'<div class="LC_left_float"><h3>'.
 1382:                   $lt{'lg'}.'</h3>');
 1383:         my ($fixedauth,$varauth,$authmsg); 
 1384:         if (ref($rulematch{$ccuname.':'.$ccdomain}) eq 'HASH') {
 1385:             my $matchedrule = $rulematch{$ccuname.':'.$ccdomain}{'username'};
 1386:             my ($rules,$ruleorder) = 
 1387:                 &Apache::lonnet::inst_userrules($ccdomain,'username');
 1388:             if (ref($rules) eq 'HASH') {
 1389:                 if (ref($rules->{$matchedrule}) eq 'HASH') {
 1390:                     my $authtype = $rules->{$matchedrule}{'authtype'};
 1391:                     if ($authtype !~ /^(krb4|krb5|int|fsys|loc)$/) {
 1392:                         $r->print(&Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc));
 1393:                     } else { 
 1394:                         my $authparm = $rules->{$matchedrule}{'authparm'};
 1395:                         $authmsg = $rules->{$matchedrule}{'authmsg'};
 1396:                         if ($authtype =~ /^krb(4|5)$/) {
 1397:                             my $ver = $1;
 1398:                             if ($authparm ne '') {
 1399:                                 $fixedauth = <<"KERB"; 
 1400: <input type="hidden" name="login" value="krb" />
 1401: <input type="hidden" name="krbver" value="$ver" />
 1402: <input type="hidden" name="krbarg" value="$authparm" />
 1403: KERB
 1404:                             }
 1405:                         } else {
 1406:                             $fixedauth = 
 1407: '<input type="hidden" name="login" value="'.$authtype.'" />'."\n";
 1408:                             if ($rules->{$matchedrule}{'authparmfixed'}) {
 1409:                                 $fixedauth .=    
 1410: '<input type="hidden" name="'.$authtype.'arg" value="'.$authparm.'" />'."\n";
 1411:                             } else {
 1412:                                 if ($authtype eq 'int') {
 1413:                                     $varauth = '<br />'.
 1414: &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>';
 1415:                                 } elsif ($authtype eq 'loc') {
 1416:                                     $varauth = '<br />'.
 1417: &mt('[_1] Local Authentication with argument [_2]','','<input type="text" name="'.$authtype.'arg" value="" />')."\n";
 1418:                                 } else {
 1419:                                     $varauth =
 1420: '<input type="text" name="'.$authtype.'arg" value="" />'."\n";
 1421:                                 }
 1422:                             }
 1423:                         }
 1424:                     }
 1425:                 } else {
 1426:                     $r->print(&Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc));
 1427:                 }
 1428:             }
 1429:             if ($authmsg) {
 1430:                 $r->print(<<ENDAUTH);
 1431: $fixedauth
 1432: $authmsg
 1433: $varauth
 1434: ENDAUTH
 1435:             }
 1436:         } else {
 1437:             $r->print(&Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc)); 
 1438:         }
 1439:         $r->print($portfolioform.$domroleform.$adhocroleform);
 1440:         if ($env{'form.action'} eq 'singlestudent') {
 1441:             $r->print(&date_sections_select($context,$newuser,$formname,
 1442:                                             $permission,$crstype,$ccuname,
 1443:                                             $ccdomain,$showcredits));
 1444:         }
 1445:         $r->print('</div><div class="LC_clear_float_footer"></div>');
 1446:     } else { # user already exists
 1447: 	$r->print($start_page.$forminfo);
 1448:         if ($env{'form.action'} eq 'singlestudent') {
 1449:             if ($crstype eq 'Community') {
 1450:                 $title = &mt('Enroll one member: [_1] in domain [_2]',
 1451:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1452:             } else {
 1453:                 $title = &mt('Enroll one student: [_1] in domain [_2]',
 1454:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1455:             }
 1456:         } else {
 1457:             $title = &mt('Modify existing user: [_1] in domain [_2]',
 1458:                              '"'.$ccuname.'"','"'.$ccdomain.'"');
 1459:         }
 1460:         $r->print('<h2>'.$title.'</h2>'."\n");
 1461:         $r->print('<div class="LC_left_float">');
 1462:         $r->print(&personal_data_display($ccuname,$ccdomain,$newuser,$context,
 1463:                                          $inst_results{$ccuname.':'.$ccdomain}));
 1464:         if (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) {
 1465:             $r->print('<br /><h3>'.&mt('User Can Request Creation of Courses/Communities in this Domain?').'</h3>'.
 1466:                       &Apache::loncommon::start_data_table());
 1467:             if ($env{'request.role.domain'} eq $ccdomain) {
 1468:                 $r->print(&build_tools_display($ccuname,$ccdomain,'requestcourses'));
 1469:             } else {
 1470:                 $r->print(&coursereq_externaluser($ccuname,$ccdomain,
 1471:                                                   $env{'request.role.domain'}));
 1472:             }
 1473:             $r->print(&Apache::loncommon::end_data_table());
 1474:         }
 1475:         $r->print('</div>');
 1476:         my @order = ('auth','quota','tools','requestauthor','adhocroles');
 1477:         my %user_text;
 1478:         my ($isadv,$isauthor) = 
 1479:             &Apache::lonnet::is_advanced_user($ccuname,$ccdomain);
 1480:         if ((!$isauthor) && 
 1481:             (&Apache::lonnet::allowed('cau',$env{'request.role.domain'}))
 1482:             && ($env{'request.role.domain'} eq $ccdomain)) {
 1483:             $user_text{'requestauthor'} = &domainrole_req($ccuname,$ccdomain);
 1484:         }
 1485:         if (&Apache::lonnet::allowed('cdh',$env{'request.role.domain'})) {
 1486:             $user_text{'adhocroles'} = &domadhocroles($ccuname,$ccdomain);
 1487:         }
 1488:         $user_text{'auth'} =  &user_authentication($ccuname,$ccdomain,$formname);
 1489:         if ((&Apache::lonnet::allowed('mpq',$ccdomain)) ||
 1490:             (&Apache::lonnet::allowed('mut',$ccdomain))) {
 1491:             # Current user has quota modification privileges
 1492:             $user_text{'quota'} = &user_quotas($ccuname,$ccdomain);
 1493:         }
 1494:         if (!&Apache::lonnet::allowed('mpq',$ccdomain)) {
 1495:             if (&Apache::lonnet::allowed('mpq',$env{'request.role.domain'})) {
 1496:                 my %lt=&Apache::lonlocal::texthash(
 1497:                     'dska'  => "Disk quotas for user's portfolio and Authoring Space",
 1498:                     'youd'  => "You do not have privileges to modify the portfolio and/or Authoring Space quotas for this user.",
 1499:                     'ichr'  => "If a change is required, contact a domain coordinator for the domain",
 1500:                 );
 1501:                 $user_text{'quota'} = <<ENDNOPORTPRIV;
 1502: <h3>$lt{'dska'}</h3>
 1503: $lt{'youd'} $lt{'ichr'}: $ccdomain
 1504: ENDNOPORTPRIV
 1505:             }
 1506:         }
 1507:         if (!&Apache::lonnet::allowed('mut',$ccdomain)) {
 1508:             if (&Apache::lonnet::allowed('mut',$env{'request.role.domain'})) {
 1509:                 my %lt=&Apache::lonlocal::texthash(
 1510:                     'utav'  => "User Tools Availability",
 1511:                     'yodo'  => "You do not have privileges to modify Portfolio, Blog, WebDAV, or Personal Information Page settings for this user.",
 1512:                     'ifch'  => "If a change is required, contact a domain coordinator for the domain",
 1513:                 );
 1514:                 $user_text{'tools'} = <<ENDNOTOOLSPRIV;
 1515: <h3>$lt{'utav'}</h3>
 1516: $lt{'yodo'} $lt{'ifch'}: $ccdomain
 1517: ENDNOTOOLSPRIV
 1518:             }
 1519:         }
 1520:         my $gotdiv = 0; 
 1521:         foreach my $item (@order) {
 1522:             if ($user_text{$item} ne '') {
 1523:                 unless ($gotdiv) {
 1524:                     $r->print('<div class="LC_left_float">');
 1525:                     $gotdiv = 1;
 1526:                 }
 1527:                 $r->print('<br />'.$user_text{$item});
 1528:             }
 1529:         }
 1530:         if ($env{'form.action'} eq 'singlestudent') {
 1531:             unless ($gotdiv) {
 1532:                 $r->print('<div class="LC_left_float">');
 1533:             }
 1534:             my $credits;
 1535:             if ($showcredits) {
 1536:                 $credits = &get_user_credits($ccuname,$ccdomain,$defaultcredits);
 1537:                 if ($credits eq '') {
 1538:                     $credits = $defaultcredits;
 1539:                 }
 1540:             }
 1541:             $r->print(&date_sections_select($context,$newuser,$formname,
 1542:                                             $permission,$crstype,$ccuname,
 1543:                                             $ccdomain,$showcredits));
 1544:         }
 1545:         if ($gotdiv) {
 1546:             $r->print('</div><div class="LC_clear_float_footer"></div>');
 1547:         }
 1548:         if ($env{'form.action'} ne 'singlestudent') {
 1549:             &display_existing_roles($r,$ccuname,$ccdomain,\%inccourses,$context,
 1550:                                     $roledom,$crstype);
 1551:         }
 1552:     } ## End of new user/old user logic
 1553:     if ($env{'form.action'} eq 'singlestudent') {
 1554:         my $btntxt;
 1555:         if ($crstype eq 'Community') {
 1556:             $btntxt = &mt('Enroll Member');
 1557:         } else {
 1558:             $btntxt = &mt('Enroll Student');
 1559:         }
 1560:         $r->print('<br /><input type="button" value="'.$btntxt.'" onclick="setSections(this.form)" />'."\n");
 1561:     } else {
 1562:         $r->print('<div class="LC_left_float">'.
 1563:                   '<fieldset><legend>'.&mt('Add Roles').'</legend>');
 1564:         my $addrolesdisplay = 0;
 1565:         if ($context eq 'domain' || $context eq 'author') {
 1566:             $addrolesdisplay = &new_coauthor_roles($r,$ccuname,$ccdomain);
 1567:         }
 1568:         if ($context eq 'domain') {
 1569:             my $add_domainroles = &new_domain_roles($r,$ccdomain);
 1570:             if (!$addrolesdisplay) {
 1571:                 $addrolesdisplay = $add_domainroles;
 1572:             }
 1573:             $r->print(&course_level_dc($env{'request.role.domain'},$showcredits));
 1574:             $r->print('</fieldset></div><div class="LC_clear_float_footer"></div>'.
 1575:                       '<br /><input type="button" value="'.&mt('Save').'" onclick="setCourse()" />'."\n");
 1576:         } elsif ($context eq 'author') {
 1577:             if ($addrolesdisplay) {
 1578:                 $r->print('</fieldset></div><div class="LC_clear_float_footer"></div>'.
 1579:                           '<br /><input type="button" value="'.&mt('Save').'"');
 1580:                 if ($newuser) {
 1581:                     $r->print(' onclick="auth_check()" \>'."\n");
 1582:                 } else {
 1583:                     $r->print('onclick="this.form.submit()" \>'."\n");
 1584:                 }
 1585:             } else {
 1586:                 $r->print('</fieldset></div>'.
 1587:                           '<div class="LC_clear_float_footer"></div>'.
 1588:                           '<br /><a href="javascript:backPage(document.cu)">'.
 1589:                           &mt('Back to previous page').'</a>');
 1590:             }
 1591:         } else {
 1592:             $r->print(&course_level_table(\%inccourses,$showcredits,$defaultcredits));
 1593:             $r->print('</fieldset></div><div class="LC_clear_float_footer"></div>'.
 1594:                       '<br /><input type="button" value="'.&mt('Save').'" onclick="setSections(this.form)" />'."\n");
 1595:         }
 1596:     }
 1597:     $r->print(&Apache::lonhtmlcommon::echo_form_input(['phase','userrole','ccdomain','prevphase','currstate','ccuname','ccdomain']));
 1598:     $r->print('<input type="hidden" name="currstate" value="" />');
 1599:     $r->print('<input type="hidden" name="prevphase" value="'.$env{'form.phase'}.'" /></form><br /><br />');
 1600:     return;
 1601: }
 1602: 
 1603: sub singleuser_breadcrumb {
 1604:     my ($crstype) = @_;
 1605:     my %breadcrumb_text;
 1606:     if ($env{'form.action'} eq 'singlestudent') {
 1607:         if ($crstype eq 'Community') {
 1608:             $breadcrumb_text{'search'} = 'Enroll a member';
 1609:         } else {
 1610:             $breadcrumb_text{'search'} = 'Enroll a student';
 1611:         }
 1612:         $breadcrumb_text{'userpicked'} = 'Select a user',
 1613:         $breadcrumb_text{'modify'} = 'Set section/dates',
 1614:     } else {
 1615:         $breadcrumb_text{'search'} = 'Create/modify a user';
 1616:         $breadcrumb_text{'userpicked'} = 'Select a user',
 1617:         $breadcrumb_text{'modify'} = 'Set user role',
 1618:     }
 1619:     return %breadcrumb_text;
 1620: }
 1621: 
 1622: sub date_sections_select {
 1623:     my ($context,$newuser,$formname,$permission,$crstype,$ccuname,$ccdomain,
 1624:         $showcredits) = @_;
 1625:     my $credits;
 1626:     if ($showcredits) {
 1627:         my $defaultcredits = &Apache::lonuserutils::get_defaultcredits();
 1628:         $credits = &get_user_credits($ccuname,$ccdomain,$defaultcredits);
 1629:         if ($credits eq '') {
 1630:             $credits = $defaultcredits;
 1631:         }
 1632:     }
 1633:     my $cid = $env{'request.course.id'};
 1634:     my ($cnum,$cdom) = &Apache::lonuserutils::get_course_identity($cid);
 1635:     my $date_table = '<h3>'.&mt('Starting and Ending Dates').'</h3>'."\n".
 1636:         &Apache::lonuserutils::date_setting_table(undef,undef,$context,
 1637:                                                   undef,$formname,$permission);
 1638:     my $rowtitle = 'Section';
 1639:     my $secbox = '<h3>'.&mt('Section and Credits').'</h3>'."\n".
 1640:         &Apache::lonuserutils::section_picker($cdom,$cnum,'st',$rowtitle,
 1641:                                               $permission,$context,'',$crstype,
 1642:                                               $showcredits,$credits);
 1643:     my $output = $date_table.$secbox;
 1644:     return $output;
 1645: }
 1646: 
 1647: sub validation_javascript {
 1648:     my ($context,$ccdomain,$pjump_def,$crstype,$groupslist,$newuser,$formname,
 1649:         $loaditem) = @_;
 1650:     my $dc_setcourse_code = '';
 1651:     my $nondc_setsection_code = '';
 1652:     if ($context eq 'domain') {
 1653:         my $dcdom = $env{'request.role.domain'};
 1654:         $loaditem->{'onload'} = "document.cu.coursedesc.value='';";
 1655:         $dc_setcourse_code = 
 1656:             &Apache::lonuserutils::dc_setcourse_js('cu','singleuser',$context);
 1657:     } else {
 1658:         my $checkauth; 
 1659:         if (($newuser) || (&Apache::lonnet::allowed('mau',$ccdomain))) {
 1660:             $checkauth = 1;
 1661:         }
 1662:         if ($context eq 'course') {
 1663:             $nondc_setsection_code =
 1664:                 &Apache::lonuserutils::setsections_javascript($formname,$groupslist,
 1665:                                                               undef,$checkauth,
 1666:                                                               $crstype);
 1667:         }
 1668:         if ($checkauth) {
 1669:             $nondc_setsection_code .= 
 1670:                 &Apache::lonuserutils::verify_authen($formname,$context);
 1671:         }
 1672:     }
 1673:     my $js = &user_modification_js($pjump_def,$dc_setcourse_code,
 1674:                                    $nondc_setsection_code,$groupslist);
 1675:     my ($jsback,$elements) = &crumb_utilities();
 1676:     $js .= "\n".
 1677:            '<script type="text/javascript">'."\n".
 1678:            '// <![CDATA['."\n".
 1679:            $jsback."\n".
 1680:            '// ]]>'."\n".
 1681:            '</script>'."\n";
 1682:     return $js;
 1683: }
 1684: 
 1685: sub display_existing_roles {
 1686:     my ($r,$ccuname,$ccdomain,$inccourses,$context,$roledom,$crstype,
 1687:         $showcredits) = @_;
 1688:     my $now=time;
 1689:     my %lt=&Apache::lonlocal::texthash(
 1690:                     'rer'  => "Existing Roles",
 1691:                     'rev'  => "Revoke",
 1692:                     'del'  => "Delete",
 1693:                     'ren'  => "Re-Enable",
 1694:                     'rol'  => "Role",
 1695:                     'ext'  => "Extent",
 1696:                     'crd'  => "Credits",
 1697:                     'sta'  => "Start",
 1698:                     'end'  => "End",
 1699:                                        );
 1700:     my (%rolesdump,%roletext,%sortrole,%roleclass,%rolepriv);
 1701:     if ($context eq 'course' || $context eq 'author') {
 1702:         my @roles = &Apache::lonuserutils::roles_by_context($context,1,$crstype);
 1703:         my %roleshash = 
 1704:             &Apache::lonnet::get_my_roles($ccuname,$ccdomain,'userroles',
 1705:                               ['active','previous','future'],\@roles,$roledom,1);
 1706:         foreach my $key (keys(%roleshash)) {
 1707:             my ($start,$end) = split(':',$roleshash{$key});
 1708:             next if ($start eq '-1' || $end eq '-1');
 1709:             my ($rnum,$rdom,$role,$sec) = split(':',$key);
 1710:             if ($context eq 'course') {
 1711:                 next unless (($rnum eq $env{'course.'.$env{'request.course.id'}.'.num'})
 1712:                              && ($rdom eq $env{'course.'.$env{'request.course.id'}.'.domain'}));
 1713:             } elsif ($context eq 'author') {
 1714:                 next unless (($rnum eq $env{'user.name'}) && ($rdom eq $env{'request.role.domain'}));
 1715:             }
 1716:             my ($newkey,$newvalue,$newrole);
 1717:             $newkey = '/'.$rdom.'/'.$rnum;
 1718:             if ($sec ne '') {
 1719:                 $newkey .= '/'.$sec;
 1720:             }
 1721:             $newvalue = $role;
 1722:             if ($role =~ /^cr/) {
 1723:                 $newrole = 'cr';
 1724:             } else {
 1725:                 $newrole = $role;
 1726:             }
 1727:             $newkey .= '_'.$newrole;
 1728:             if ($start ne '' && $end ne '') {
 1729:                 $newvalue .= '_'.$end.'_'.$start;
 1730:             } elsif ($end ne '') {
 1731:                 $newvalue .= '_'.$end;
 1732:             }
 1733:             $rolesdump{$newkey} = $newvalue;
 1734:         }
 1735:     } else {
 1736:         %rolesdump=&Apache::lonnet::dump('roles',$ccdomain,$ccuname);
 1737:     }
 1738:     # Build up table of user roles to allow revocation and re-enabling of roles.
 1739:     my ($tmp) = keys(%rolesdump);
 1740:     return if ($tmp =~ /^(con_lost|error)/i);
 1741:     foreach my $area (sort { my $a1=join('_',(split('_',$a))[1,0]);
 1742:                                 my $b1=join('_',(split('_',$b))[1,0]);
 1743:                                 return $a1 cmp $b1;
 1744:                             } keys(%rolesdump)) {
 1745:         next if ($area =~ /^rolesdef/);
 1746:         my $envkey=$area;
 1747:         my $role = $rolesdump{$area};
 1748:         my $thisrole=$area;
 1749:         $area =~ s/\_\w\w$//;
 1750:         my ($role_code,$role_end_time,$role_start_time) =
 1751:             split(/_/,$role);
 1752: # Is this a custom role? Get role owner and title.
 1753:         my ($croleudom,$croleuname,$croletitle)=
 1754:             ($role_code=~m{^cr/($match_domain)/($match_username)/(\w+)$});
 1755:         my $allowed=0;
 1756:         my $delallowed=0;
 1757:         my $sortkey=$role_code;
 1758:         my $class='Unknown';
 1759:         my $credits='';
 1760:         if ($area =~ m{^/($match_domain)/($match_courseid)} ) {
 1761:             $class='Course';
 1762:             my ($coursedom,$coursedir) = ($1,$2);
 1763:             my $cid = $1.'_'.$2;
 1764:             # $1.'_'.$2 is the course id (eg. 103_12345abcef103l3).
 1765:             my %coursedata=
 1766:                 &Apache::lonnet::coursedescription($cid);
 1767:             if ($coursedir =~ /^$match_community$/) {
 1768:                 $class='Community';
 1769:             }
 1770:             $sortkey.="\0$coursedom";
 1771:             my $carea;
 1772:             if (defined($coursedata{'description'})) {
 1773:                 $carea=$coursedata{'description'}.
 1774:                     '<br />'.&mt('Domain').': '.$coursedom.('&nbsp;'x8).
 1775:     &Apache::loncommon::syllabuswrapper(&mt('Syllabus'),$coursedir,$coursedom);
 1776:                 $sortkey.="\0".$coursedata{'description'};
 1777:             } else {
 1778:                 if ($class eq 'Community') {
 1779:                     $carea=&mt('Unavailable community').': '.$area;
 1780:                     $sortkey.="\0".&mt('Unavailable community').': '.$area;
 1781:                 } else {
 1782:                     $carea=&mt('Unavailable course').': '.$area;
 1783:                     $sortkey.="\0".&mt('Unavailable course').': '.$area;
 1784:                 }
 1785:             }
 1786:             $sortkey.="\0$coursedir";
 1787:             $inccourses->{$cid}=1;
 1788:             if (($showcredits) && ($class eq 'Course') && ($role_code eq 'st')) {
 1789:                 my $defaultcredits = $coursedata{'internal.defaultcredits'};
 1790:                 $credits =
 1791:                     &get_user_credits($ccuname,$ccdomain,$defaultcredits,
 1792:                                       $coursedom,$coursedir);
 1793:                 if ($credits eq '') {
 1794:                     $credits = $defaultcredits;
 1795:                 }
 1796:             }
 1797:             if ((&Apache::lonnet::allowed('c'.$role_code,$coursedom.'/'.$coursedir)) ||
 1798:                 (&Apache::lonnet::allowed('c'.$role_code,$ccdomain))) {
 1799:                 $allowed=1;
 1800:             }
 1801:             unless ($allowed) {
 1802:                 my $isowner = &Apache::lonuserutils::is_courseowner($cid,$coursedata{'internal.courseowner'});
 1803:                 if ($isowner) {
 1804:                     if (($role_code eq 'co') && ($class eq 'Community')) {
 1805:                         $allowed = 1;
 1806:                     } elsif (($role_code eq 'cc') && ($class eq 'Course')) {
 1807:                         $allowed = 1;
 1808:                     }
 1809:                 }
 1810:             } 
 1811:             if ((&Apache::lonnet::allowed('dro',$coursedom)) ||
 1812:                 (&Apache::lonnet::allowed('dro',$ccdomain))) {
 1813:                 $delallowed=1;
 1814:             }
 1815: # - custom role. Needs more info, too
 1816:             if ($croletitle) {
 1817:                 if (&Apache::lonnet::allowed('ccr',$coursedom.'/'.$coursedir)) {
 1818:                     $allowed=1;
 1819:                     $thisrole.='.'.$role_code;
 1820:                 }
 1821:             }
 1822:             if ($area=~m{^/($match_domain)/($match_courseid)/(\w+)}) {
 1823:                 $carea.='<br />'.&mt('Section: [_1]',$3);
 1824:                 $sortkey.="\0$3";
 1825:                 if (!$allowed) {
 1826:                     if ($env{'request.course.sec'} eq $3) {
 1827:                         if (&Apache::lonnet::allowed('c'.$role_code,$1.'/'.$2.'/'.$3)) {
 1828:                             $allowed = 1;
 1829:                         }
 1830:                     }
 1831:                 }
 1832:             }
 1833:             $area=$carea;
 1834:         } else {
 1835:             $sortkey.="\0".$area;
 1836:             # Determine if current user is able to revoke privileges
 1837:             if ($area=~m{^/($match_domain)/}) {
 1838:                 if ((&Apache::lonnet::allowed('c'.$role_code,$1)) ||
 1839:                    (&Apache::lonnet::allowed('c'.$role_code,$ccdomain))) {
 1840:                    $allowed=1;
 1841:                 }
 1842:                 if (((&Apache::lonnet::allowed('dro',$1))  ||
 1843:                     (&Apache::lonnet::allowed('dro',$ccdomain))) &&
 1844:                     ($role_code ne 'dc')) {
 1845:                     $delallowed=1;
 1846:                 }
 1847:             } else {
 1848:                 if (&Apache::lonnet::allowed('c'.$role_code,'/')) {
 1849:                     $allowed=1;
 1850:                 }
 1851:             }
 1852:             if ($role_code eq 'ca' || $role_code eq 'au' || $role_code eq 'aa') {
 1853:                 $class='Authoring Space';
 1854:             } elsif ($role_code eq 'su') {
 1855:                 $class='System';
 1856:             } else {
 1857:                 $class='Domain';
 1858:             }
 1859:         }
 1860:         if (($role_code eq 'ca') || ($role_code eq 'aa')) {
 1861:             $area=~m{/($match_domain)/($match_username)};
 1862:             if (&Apache::lonuserutils::authorpriv($2,$1)) {
 1863:                 $allowed=1;
 1864:             } else {
 1865:                 $allowed=0;
 1866:             }
 1867:         }
 1868:         my $row = '';
 1869:         $row.= '<td>';
 1870:         my $active=1;
 1871:         $active=0 if (($role_end_time) && ($now>$role_end_time));
 1872:         if (($active) && ($allowed)) {
 1873:             $row.= '<input type="checkbox" name="rev:'.$thisrole.'" />';
 1874:         } else {
 1875:             if ($active) {
 1876:                $row.='&nbsp;';
 1877:             } else {
 1878:                $row.=&mt('expired or revoked');
 1879:             }
 1880:         }
 1881:         $row.='</td><td>';
 1882:         if ($allowed && !$active) {
 1883:             $row.= '<input type="checkbox" name="ren:'.$thisrole.'" />';
 1884:         } else {
 1885:             $row.='&nbsp;';
 1886:         }
 1887:         $row.='</td><td>';
 1888:         if ($delallowed) {
 1889:             $row.= '<input type="checkbox" name="del:'.$thisrole.'" />';
 1890:         } else {
 1891:             $row.='&nbsp;';
 1892:         }
 1893:         my $plaintext='';
 1894:         if (!$croletitle) {
 1895:             $plaintext=&Apache::lonnet::plaintext($role_code,$class);
 1896:             if (($showcredits) && ($credits ne '')) {
 1897:                 $plaintext .= '<br/ ><span class="LC_nobreak">'.
 1898:                               '<span class="LC_fontsize_small">'.
 1899:                               &mt('Credits: [_1]',$credits).
 1900:                               '</span></span>';
 1901:             }
 1902:         } else {
 1903:             $plaintext=
 1904:                 &mt('Custom role [_1][_2]defined by [_3]',
 1905:                         '"'.$croletitle.'"',
 1906:                         '<br />',
 1907:                         $croleuname.':'.$croleudom);
 1908:         }
 1909:         $row.= '</td><td>'.$plaintext.
 1910:                '</td><td>'.$area.
 1911:                '</td><td>'.($role_start_time?&Apache::lonlocal::locallocaltime($role_start_time)
 1912:                                             : '&nbsp;' ).
 1913:                '</td><td>'.($role_end_time  ?&Apache::lonlocal::locallocaltime($role_end_time)
 1914:                                             : '&nbsp;' )
 1915:                ."</td>";
 1916:         $sortrole{$sortkey}=$envkey;
 1917:         $roletext{$envkey}=$row;
 1918:         $roleclass{$envkey}=$class;
 1919:         $rolepriv{$envkey}=$allowed;
 1920:     } # end of foreach        (table building loop)
 1921: 
 1922:     my $rolesdisplay = 0;
 1923:     my %output = ();
 1924:     foreach my $type ('Authoring Space','Course','Community','Domain','System','Unknown') {
 1925:         $output{$type} = '';
 1926:         foreach my $which (sort {uc($a) cmp uc($b)} (keys(%sortrole))) {
 1927:             if ( ($roleclass{$sortrole{$which}} =~ /^\Q$type\E/ ) && ($rolepriv{$sortrole{$which}}) ) {
 1928:                  $output{$type}.=
 1929:                       &Apache::loncommon::start_data_table_row().
 1930:                       $roletext{$sortrole{$which}}.
 1931:                       &Apache::loncommon::end_data_table_row();
 1932:             }
 1933:         }
 1934:         unless($output{$type} eq '') {
 1935:             $output{$type} = '<tr class="LC_info_row">'.
 1936:                       "<td align='center' colspan='7'>".&mt($type)."</td></tr>".
 1937:                       $output{$type};
 1938:             $rolesdisplay = 1;
 1939:         }
 1940:     }
 1941:     if ($rolesdisplay == 1) {
 1942:         my $contextrole='';
 1943:         if ($env{'request.course.id'}) {
 1944:             if (&Apache::loncommon::course_type() eq 'Community') {
 1945:                 $contextrole = &mt('Existing Roles in this Community');
 1946:             } else {
 1947:                 $contextrole = &mt('Existing Roles in this Course');
 1948:             }
 1949:         } elsif ($env{'request.role'} =~ /^au\./) {
 1950:             $contextrole = &mt('Existing Co-Author Roles in your Authoring Space');
 1951:         } else {
 1952:             $contextrole = &mt('Existing Roles in this Domain');
 1953:         }
 1954:         $r->print('<div class="LC_left_float">'.
 1955: '<fieldset><legend>'.$contextrole.'</legend>'.
 1956: &Apache::loncommon::start_data_table("LC_createuser").
 1957: &Apache::loncommon::start_data_table_header_row().
 1958: '<th>'.$lt{'rev'}.'</th><th>'.$lt{'ren'}.'</th><th>'.$lt{'del'}.
 1959: '</th><th>'.$lt{'rol'}.'</th><th>'.$lt{'ext'}.
 1960: '</th><th>'.$lt{'sta'}.'</th><th>'.$lt{'end'}.'</th>'.
 1961: &Apache::loncommon::end_data_table_header_row());
 1962:         foreach my $type ('Authoring Space','Course','Community','Domain','System','Unknown') {
 1963:             if ($output{$type}) {
 1964:                 $r->print($output{$type}."\n");
 1965:             }
 1966:         }
 1967:         $r->print(&Apache::loncommon::end_data_table().
 1968:                   '</fieldset></div>');
 1969:     }
 1970:     return;
 1971: }
 1972: 
 1973: sub new_coauthor_roles {
 1974:     my ($r,$ccuname,$ccdomain) = @_;
 1975:     my $addrolesdisplay = 0;
 1976:     #
 1977:     # Co-Author
 1978:     #
 1979:     if (&Apache::lonuserutils::authorpriv($env{'user.name'},
 1980:                                           $env{'request.role.domain'}) &&
 1981:         ($env{'user.name'} ne $ccuname || $env{'user.domain'} ne $ccdomain)) {
 1982:         # No sense in assigning co-author role to yourself
 1983:         $addrolesdisplay = 1;
 1984:         my $cuname=$env{'user.name'};
 1985:         my $cudom=$env{'request.role.domain'};
 1986:         my %lt=&Apache::lonlocal::texthash(
 1987:                     'cs'   => "Authoring Space",
 1988:                     'act'  => "Activate",
 1989:                     'rol'  => "Role",
 1990:                     'ext'  => "Extent",
 1991:                     'sta'  => "Start",
 1992:                     'end'  => "End",
 1993:                     'cau'  => "Co-Author",
 1994:                     'caa'  => "Assistant Co-Author",
 1995:                     'ssd'  => "Set Start Date",
 1996:                     'sed'  => "Set End Date"
 1997:                                        );
 1998:         $r->print('<h4>'.$lt{'cs'}.'</h4>'."\n".
 1999:                   &Apache::loncommon::start_data_table()."\n".
 2000:                   &Apache::loncommon::start_data_table_header_row()."\n".
 2001:                   '<th>'.$lt{'act'}.'</th><th>'.$lt{'rol'}.'</th>'.
 2002:                   '<th>'.$lt{'ext'}.'</th><th>'.$lt{'sta'}.'</th>'.
 2003:                   '<th>'.$lt{'end'}.'</th>'."\n".
 2004:                   &Apache::loncommon::end_data_table_header_row()."\n".
 2005:                   &Apache::loncommon::start_data_table_row().'
 2006:            <td>
 2007:             <input type="checkbox" name="act_'.$cudom.'_'.$cuname.'_ca" />
 2008:            </td>
 2009:            <td>'.$lt{'cau'}.'</td>
 2010:            <td>'.$cudom.'_'.$cuname.'</td>
 2011:            <td><input type="hidden" name="start_'.$cudom.'_'.$cuname.'_ca" value="" />
 2012:              <a href=
 2013: "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>
 2014: <td><input type="hidden" name="end_'.$cudom.'_'.$cuname.'_ca" value="" />
 2015: <a href=
 2016: "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".
 2017:               &Apache::loncommon::end_data_table_row()."\n".
 2018:               &Apache::loncommon::start_data_table_row()."\n".
 2019: '<td><input type="checkbox" name="act_'.$cudom.'_'.$cuname.'_aa" /></td>
 2020: <td>'.$lt{'caa'}.'</td>
 2021: <td>'.$cudom.'_'.$cuname.'</td>
 2022: <td><input type="hidden" name="start_'.$cudom.'_'.$cuname.'_aa" value="" />
 2023: <a href=
 2024: "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>
 2025: <td><input type="hidden" name="end_'.$cudom.'_'.$cuname.'_aa" value="" />
 2026: <a href=
 2027: "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".
 2028:              &Apache::loncommon::end_data_table_row()."\n".
 2029:              &Apache::loncommon::end_data_table());
 2030:     } elsif ($env{'request.role'} =~ /^au\./) {
 2031:         if (!(&Apache::lonuserutils::authorpriv($env{'user.name'},
 2032:                                                 $env{'request.role.domain'}))) {
 2033:             $r->print('<span class="LC_error">'.
 2034:                       &mt('You do not have privileges to assign co-author roles.').
 2035:                       '</span>');
 2036:         } elsif (($env{'user.name'} eq $ccuname) &&
 2037:              ($env{'user.domain'} eq $ccdomain)) {
 2038:             $r->print(&mt('Assigning yourself a co-author or assistant co-author role in your own author area in Authoring Space is not permitted'));
 2039:         }
 2040:     }
 2041:     return $addrolesdisplay;;
 2042: }
 2043: 
 2044: sub new_domain_roles {
 2045:     my ($r,$ccdomain) = @_;
 2046:     my $addrolesdisplay = 0;
 2047:     #
 2048:     # Domain level
 2049:     #
 2050:     my $num_domain_level = 0;
 2051:     my $domaintext =
 2052:     '<h4>'.&mt('Domain Level').'</h4>'.
 2053:     &Apache::loncommon::start_data_table().
 2054:     &Apache::loncommon::start_data_table_header_row().
 2055:     '<th>'.&mt('Activate').'</th><th>'.&mt('Role').'</th><th>'.
 2056:     &mt('Extent').'</th>'.
 2057:     '<th>'.&mt('Start').'</th><th>'.&mt('End').'</th>'.
 2058:     &Apache::loncommon::end_data_table_header_row();
 2059:     my @allroles = &Apache::lonuserutils::roles_by_context('domain');
 2060:     foreach my $thisdomain (sort(&Apache::lonnet::all_domains())) {
 2061:         foreach my $role (@allroles) {
 2062:             next if ($role eq 'ad');
 2063:             next if (($role eq 'au') && ($ccdomain ne $thisdomain));
 2064:             if (&Apache::lonnet::allowed('c'.$role,$thisdomain)) {
 2065:                my $plrole=&Apache::lonnet::plaintext($role);
 2066:                my %lt=&Apache::lonlocal::texthash(
 2067:                     'ssd'  => "Set Start Date",
 2068:                     'sed'  => "Set End Date"
 2069:                                        );
 2070:                $num_domain_level ++;
 2071:                $domaintext .=
 2072: &Apache::loncommon::start_data_table_row().
 2073: '<td><input type="checkbox" name="act_'.$thisdomain.'_'.$role.'" /></td>
 2074: <td>'.$plrole.'</td>
 2075: <td>'.$thisdomain.'</td>
 2076: <td><input type="hidden" name="start_'.$thisdomain.'_'.$role.'" value="" />
 2077: <a href=
 2078: "javascript:pjump('."'date_start','Start Date $plrole',document.cu.start_$thisdomain\_$role.value,'start_$thisdomain\_$role','cu.pres','dateset'".')">'.$lt{'ssd'}.'</a></td>
 2079: <td><input type="hidden" name="end_'.$thisdomain.'_'.$role.'" value="" />
 2080: <a href=
 2081: "javascript:pjump('."'date_end','End Date $plrole',document.cu.end_$thisdomain\_$role.value,'end_$thisdomain\_$role','cu.pres','dateset'".')">'.$lt{'sed'}.'</a></td>'.
 2082: &Apache::loncommon::end_data_table_row();
 2083:             }
 2084:         }
 2085:     }
 2086:     $domaintext.= &Apache::loncommon::end_data_table();
 2087:     if ($num_domain_level > 0) {
 2088:         $r->print($domaintext);
 2089:         $addrolesdisplay = 1;
 2090:     }
 2091:     return $addrolesdisplay;
 2092: }
 2093: 
 2094: sub user_authentication {
 2095:     my ($ccuname,$ccdomain,$formname) = @_;
 2096:     my $currentauth=&Apache::lonnet::queryauthenticate($ccuname,$ccdomain);
 2097:     my $outcome;
 2098:     # Check for a bad authentication type
 2099:     if ($currentauth !~ /^(krb4|krb5|unix|internal|localauth):/) {
 2100:         # bad authentication scheme
 2101:         my %lt=&Apache::lonlocal::texthash(
 2102:                        'err'   => "ERROR",
 2103:                        'uuas'  => "This user has an unrecognized authentication scheme",
 2104:                        'adcs'  => "Please alert a domain coordinator of this situation",
 2105:                        'sldb'  => "Please specify login data below",
 2106:                        'ld'    => "Login Data"
 2107:         );
 2108:         if (&Apache::lonnet::allowed('mau',$ccdomain)) {
 2109:             &initialize_authen_forms($ccdomain,$formname);
 2110: 
 2111:             my $choices = &Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc);
 2112:             $outcome = <<ENDBADAUTH;
 2113: <script type="text/javascript" language="Javascript">
 2114: // <![CDATA[
 2115: $loginscript
 2116: // ]]>
 2117: </script>
 2118: <span class="LC_error">$lt{'err'}:
 2119: $lt{'uuas'} ($currentauth). $lt{'sldb'}.</span>
 2120: <h3>$lt{'ld'}</h3>
 2121: $choices
 2122: ENDBADAUTH
 2123:         } else {
 2124:             # This user is not allowed to modify the user's
 2125:             # authentication scheme, so just notify them of the problem
 2126:             $outcome = <<ENDBADAUTH;
 2127: <span class="LC_error"> $lt{'err'}: 
 2128: $lt{'uuas'} ($currentauth). $lt{'adcs'}.
 2129: </span>
 2130: ENDBADAUTH
 2131:         }
 2132:     } else { # Authentication type is valid
 2133:         &initialize_authen_forms($ccdomain,$formname,$currentauth,'modifyuser');
 2134:         my ($authformcurrent,$can_modify,@authform_others) =
 2135:             &modify_login_block($ccdomain,$currentauth);
 2136:         if (&Apache::lonnet::allowed('mau',$ccdomain)) {
 2137:             # Current user has login modification privileges
 2138:             my %lt=&Apache::lonlocal::texthash (
 2139:                            'ld'    => "Login Data",
 2140:                            'ccld'  => "Change Current Login Data",
 2141:                            'enld'  => "Enter New Login Data"
 2142:                                                );
 2143:             $outcome =
 2144:                        '<script type="text/javascript" language="Javascript">'."\n".
 2145:                        '// <![CDATA['."\n".
 2146:                        $loginscript."\n".
 2147:                        '// ]]>'."\n".
 2148:                        '</script>'."\n".
 2149:                        '<h3>'.$lt{'ld'}.'</h3>'.
 2150:                        &Apache::loncommon::start_data_table().
 2151:                        &Apache::loncommon::start_data_table_row().
 2152:                        '<td>'.$authformnop;
 2153:             if ($can_modify) {
 2154:                 $outcome .= '</td>'."\n".
 2155:                             &Apache::loncommon::end_data_table_row().
 2156:                             &Apache::loncommon::start_data_table_row().
 2157:                             '<td>'.$authformcurrent.'</td>'.
 2158:                             &Apache::loncommon::end_data_table_row()."\n";
 2159:             } else {
 2160:                 $outcome .= '&nbsp;('.$authformcurrent.')</td>'.
 2161:                             &Apache::loncommon::end_data_table_row()."\n";
 2162:             }
 2163:             foreach my $item (@authform_others) { 
 2164:                 $outcome .= &Apache::loncommon::start_data_table_row().
 2165:                             '<td>'.$item.'</td>'.
 2166:                             &Apache::loncommon::end_data_table_row()."\n";
 2167:             }
 2168:             $outcome .= &Apache::loncommon::end_data_table();
 2169:         } else {
 2170:             if (&Apache::lonnet::allowed('mau',$env{'request.role.domain'})) {
 2171:                 my %lt=&Apache::lonlocal::texthash(
 2172:                            'ccld'  => "Change Current Login Data",
 2173:                            'yodo'  => "You do not have privileges to modify the authentication configuration for this user.",
 2174:                            'ifch'  => "If a change is required, contact a domain coordinator for the domain",
 2175:                 );
 2176:                 $outcome .= <<ENDNOPRIV;
 2177: <h3>$lt{'ccld'}</h3>
 2178: $lt{'yodo'} $lt{'ifch'}: $ccdomain
 2179: <input type="hidden" name="login" value="nochange" />
 2180: ENDNOPRIV
 2181:             }
 2182:         }
 2183:     }  ## End of "check for bad authentication type" logic
 2184:     return $outcome;
 2185: }
 2186: 
 2187: sub modify_login_block {
 2188:     my ($dom,$currentauth) = @_;
 2189:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 2190:     my ($authnum,%can_assign) =
 2191:         &Apache::loncommon::get_assignable_auth($dom);
 2192:     my ($authformcurrent,@authform_others,$show_override_msg);
 2193:     if ($currentauth=~/^krb(4|5):/) {
 2194:         $authformcurrent=$authformkrb;
 2195:         if ($can_assign{'int'}) {
 2196:             push(@authform_others,$authformint);
 2197:         }
 2198:         if ($can_assign{'loc'}) {
 2199:             push(@authform_others,$authformloc);
 2200:         }
 2201:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2202:             $show_override_msg = 1;
 2203:         }
 2204:     } elsif ($currentauth=~/^internal:/) {
 2205:         $authformcurrent=$authformint;
 2206:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2207:             push(@authform_others,$authformkrb);
 2208:         }
 2209:         if ($can_assign{'loc'}) {
 2210:             push(@authform_others,$authformloc);
 2211:         }
 2212:         if ($can_assign{'int'}) {
 2213:             $show_override_msg = 1;
 2214:         }
 2215:     } elsif ($currentauth=~/^unix:/) {
 2216:         $authformcurrent=$authformfsys;
 2217:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2218:             push(@authform_others,$authformkrb);
 2219:         }
 2220:         if ($can_assign{'int'}) {
 2221:             push(@authform_others,$authformint);
 2222:         }
 2223:         if ($can_assign{'loc'}) {
 2224:             push(@authform_others,$authformloc);
 2225:         }
 2226:         if ($can_assign{'fsys'}) {
 2227:             $show_override_msg = 1;
 2228:         }
 2229:     } elsif ($currentauth=~/^localauth:/) {
 2230:         $authformcurrent=$authformloc;
 2231:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2232:             push(@authform_others,$authformkrb);
 2233:         }
 2234:         if ($can_assign{'int'}) {
 2235:             push(@authform_others,$authformint);
 2236:         }
 2237:         if ($can_assign{'loc'}) {
 2238:             $show_override_msg = 1;
 2239:         }
 2240:     }
 2241:     if ($show_override_msg) {
 2242:         $authformcurrent = '<table><tr><td colspan="3">'.$authformcurrent.
 2243:                            '</td></tr>'."\n".
 2244:                            '<tr><td>&nbsp;&nbsp;&nbsp;</td>'.
 2245:                            '<td><b>'.&mt('Currently in use').'</b></td>'.
 2246:                            '<td align="right"><span class="LC_cusr_emph">'.
 2247:                             &mt('will override current values').
 2248:                             '</span></td></tr></table>';
 2249:     }
 2250:     return ($authformcurrent,$show_override_msg,@authform_others); 
 2251: }
 2252: 
 2253: sub personal_data_display {
 2254:     my ($ccuname,$ccdomain,$newuser,$context,$inst_results,$rolesarray,
 2255:         $now,$captchaform,$emailusername,$usertype) = @_;
 2256:     my ($output,%userenv,%canmodify,%canmodify_status);
 2257:     my @userinfo = ('firstname','middlename','lastname','generation',
 2258:                     'permanentemail','id');
 2259:     my $rowcount = 0;
 2260:     my $editable = 0;
 2261:     my %textboxsize = (
 2262:                        firstname      => '15',
 2263:                        middlename     => '15',
 2264:                        lastname       => '15',
 2265:                        generation     => '5',
 2266:                        permanentemail => '25',
 2267:                        id             => '15',
 2268:                       );
 2269: 
 2270:     my %lt=&Apache::lonlocal::texthash(
 2271:                 'pd'             => "Personal Data",
 2272:                 'firstname'      => "First Name",
 2273:                 'middlename'     => "Middle Name",
 2274:                 'lastname'       => "Last Name",
 2275:                 'generation'     => "Generation",
 2276:                 'permanentemail' => "Permanent e-mail address",
 2277:                 'id'             => "Student/Employee ID",
 2278:                 'lg'             => "Login Data",
 2279:                 'inststatus'     => "Affiliation",
 2280:                 'email'          => 'E-mail address',
 2281:                 'valid'          => 'Validation',
 2282:     );
 2283: 
 2284:     %canmodify_status =
 2285:         &Apache::lonuserutils::can_modify_userinfo($context,$ccdomain,
 2286:                                                    ['inststatus'],$rolesarray);
 2287:     if (!$newuser) {
 2288:         # Get the users information
 2289:         %userenv = &Apache::lonnet::get('environment',
 2290:                    ['firstname','middlename','lastname','generation',
 2291:                     'permanentemail','id','inststatus'],$ccdomain,$ccuname);
 2292:         %canmodify =
 2293:             &Apache::lonuserutils::can_modify_userinfo($context,$ccdomain,
 2294:                                                        \@userinfo,$rolesarray);
 2295:     } elsif ($context eq 'selfcreate') {
 2296:         if ($newuser eq 'email') {
 2297:             if (ref($emailusername) eq 'HASH') {
 2298:                 if (ref($emailusername->{$usertype}) eq 'HASH') {
 2299:                     my ($infofields,$infotitles) = &Apache::loncommon::emailusername_info();
 2300:                     @userinfo = ();          
 2301:                     if ((ref($infofields) eq 'ARRAY') && (ref($infotitles) eq 'HASH')) {
 2302:                         foreach my $field (@{$infofields}) { 
 2303:                             if ($emailusername->{$usertype}->{$field}) {
 2304:                                 push(@userinfo,$field);
 2305:                                 $canmodify{$field} = 1;
 2306:                                 unless ($textboxsize{$field}) {
 2307:                                     $textboxsize{$field} = 25;
 2308:                                 }
 2309:                                 unless ($lt{$field}) {
 2310:                                     $lt{$field} = $infotitles->{$field};
 2311:                                 }
 2312:                                 if ($emailusername->{$usertype}->{$field} eq 'required') {
 2313:                                     $lt{$field} .= '<b>*</b>';
 2314:                                 }
 2315:                             }
 2316:                         }
 2317:                     }
 2318:                 }
 2319:             }
 2320:         } else {
 2321:             %canmodify = &selfcreate_canmodify($context,$ccdomain,\@userinfo,
 2322:                                                $inst_results,$rolesarray);
 2323:         }
 2324:     }
 2325: 
 2326:     my $genhelp=&Apache::loncommon::help_open_topic('Generation');
 2327:     $output = '<h3>'.$lt{'pd'}.'</h3>'.
 2328:               &Apache::lonhtmlcommon::start_pick_box();
 2329:     if (($context eq 'selfcreate') && ($newuser eq 'email')) {
 2330:         $output .= &Apache::lonhtmlcommon::row_title($lt{'email'}.'<b>*</b>',undef,
 2331:                                                      'LC_oddrow_value')."\n".
 2332:                    '<input type="text" name="uname" size="25" value="" autocomplete="off" />';
 2333:         $rowcount ++;
 2334:         $output .= &Apache::lonhtmlcommon::row_closure(1);
 2335:         my $upassone = '<input type="password" name="upass'.$now.'" size="20" autocomplete="off" />';
 2336:         my $upasstwo = '<input type="password" name="upasscheck'.$now.'" size="20" autocomplete="off" />';
 2337:         $output .= &Apache::lonhtmlcommon::row_title(&mt('Password').'<b>*</b>',
 2338:                                                     'LC_pick_box_title',
 2339:                                                     'LC_oddrow_value')."\n".
 2340:                    $upassone."\n".
 2341:                    &Apache::lonhtmlcommon::row_closure(1)."\n".
 2342:                    &Apache::lonhtmlcommon::row_title(&mt('Confirm password').'<b>*</b>',
 2343:                                                      'LC_pick_box_title',
 2344:                                                      'LC_oddrow_value')."\n".
 2345:                    $upasstwo.
 2346:                    &Apache::lonhtmlcommon::row_closure()."\n";
 2347:     }
 2348:     foreach my $item (@userinfo) {
 2349:         my $rowtitle = $lt{$item};
 2350:         my $hiderow = 0;
 2351:         if ($item eq 'generation') {
 2352:             $rowtitle = $genhelp.$rowtitle;
 2353:         }
 2354:         my $row = &Apache::lonhtmlcommon::row_title($rowtitle,undef,'LC_oddrow_value')."\n";
 2355:         if ($newuser) {
 2356:             if (ref($inst_results) eq 'HASH') {
 2357:                 if ($inst_results->{$item} ne '') {
 2358:                     $row .= '<input type="hidden" name="c'.$item.'" value="'.$inst_results->{$item}.'" />'.$inst_results->{$item};
 2359:                 } else {
 2360:                     if ($context eq 'selfcreate') {
 2361:                         if ($canmodify{$item}) {
 2362:                             $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="" autocomplete="off" />';
 2363:                             $editable ++;
 2364:                         } else {
 2365:                             $hiderow = 1;
 2366:                         }
 2367:                     } else {
 2368:                         $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="" />';
 2369:                     }
 2370:                 }
 2371:             } else {
 2372:                 if ($context eq 'selfcreate') {
 2373:                     if ($canmodify{$item}) {
 2374:                         if ($newuser eq 'email') {
 2375:                             $row .= '<input type="text" name="'.$item.'" size="'.$textboxsize{$item}.'" value="" autocomplete="off" />';
 2376:                         } else {
 2377:                             $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="" autocomplete="off" />';
 2378:                         }
 2379:                         $editable ++;
 2380:                     } else {
 2381:                         $hiderow = 1;
 2382:                     }
 2383:                 } else {
 2384:                     $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="" />';
 2385:                 }
 2386:             }
 2387:         } else {
 2388:             if ($canmodify{$item}) {
 2389:                 $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="'.$userenv{$item}.'" />';
 2390:                 if (($item eq 'id') && (!$newuser)) {
 2391:                     $row .= '<br />'.&Apache::lonuserutils::forceid_change($context);
 2392:                 }
 2393:             } else {
 2394:                 $row .= $userenv{$item};
 2395:             }
 2396:         }
 2397:         $row .= &Apache::lonhtmlcommon::row_closure(1);
 2398:         if (!$hiderow) {
 2399:             $output .= $row;
 2400:             $rowcount ++;
 2401:         }
 2402:     }
 2403:     if (($canmodify_status{'inststatus'}) || ($context ne 'selfcreate')) {
 2404:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($ccdomain);
 2405:         if (ref($types) eq 'ARRAY') {
 2406:             if (@{$types} > 0) {
 2407:                 my ($hiderow,$shown);
 2408:                 if ($canmodify_status{'inststatus'}) {
 2409:                     $shown = &pick_inst_statuses($userenv{'inststatus'},$usertypes,$types);
 2410:                 } else {
 2411:                     if ($userenv{'inststatus'} eq '') {
 2412:                         $hiderow = 1;
 2413:                     } else {
 2414:                         my @showitems;
 2415:                         foreach my $item ( map { &unescape($_); } split(':',$userenv{'inststatus'})) {
 2416:                             if (exists($usertypes->{$item})) {
 2417:                                 push(@showitems,$usertypes->{$item});
 2418:                             } else {
 2419:                                 push(@showitems,$item);
 2420:                             }
 2421:                         }
 2422:                         if (@showitems) {
 2423:                             $shown = join(', ',@showitems);
 2424:                         } else {
 2425:                             $hiderow = 1;
 2426:                         }
 2427:                     }
 2428:                 }
 2429:                 if (!$hiderow) {
 2430:                     my $row = &Apache::lonhtmlcommon::row_title(&mt('Affiliations'),undef,'LC_oddrow_value')."\n".
 2431:                               $shown.&Apache::lonhtmlcommon::row_closure(1); 
 2432:                     if ($context eq 'selfcreate') {
 2433:                         $rowcount ++;
 2434:                     }
 2435:                     $output .= $row;
 2436:                 }
 2437:             }
 2438:         }
 2439:     }
 2440:     if (($context eq 'selfcreate') && ($newuser eq 'email')) {
 2441:         if ($captchaform) {
 2442:             $output .= &Apache::lonhtmlcommon::row_title($lt{'valid'}.'*',
 2443:                                                          'LC_pick_box_title')."\n".
 2444:                        $captchaform."\n".'<br /><br />'.
 2445:                        &Apache::lonhtmlcommon::row_closure(1); 
 2446:             $rowcount ++;
 2447:         }
 2448:         my $submit_text = &mt('Create account');
 2449:         $output .= &Apache::lonhtmlcommon::row_title()."\n".
 2450:                    '<br /><input type="submit" name="createaccount" value="'.
 2451:                    $submit_text.'" />'.
 2452:                    '<input type="hidden" name="type" value="'.$usertype.'" />'.
 2453:                    &Apache::lonhtmlcommon::row_closure(1);
 2454:     }
 2455:     $output .= &Apache::lonhtmlcommon::end_pick_box();
 2456:     if (wantarray) {
 2457:         if ($context eq 'selfcreate') {
 2458:             return($output,$rowcount,$editable);
 2459:         } else {
 2460:             return $output;
 2461:         }
 2462:     } else {
 2463:         return $output;
 2464:     }
 2465: }
 2466: 
 2467: sub pick_inst_statuses {
 2468:     my ($curr,$usertypes,$types) = @_;
 2469:     my ($output,$rem,@currtypes);
 2470:     if ($curr ne '') {
 2471:         @currtypes = map { &unescape($_); } split(/:/,$curr);
 2472:     }
 2473:     my $numinrow = 2;
 2474:     if (ref($types) eq 'ARRAY') {
 2475:         $output = '<table>';
 2476:         my $lastcolspan; 
 2477:         for (my $i=0; $i<@{$types}; $i++) {
 2478:             if (defined($usertypes->{$types->[$i]})) {
 2479:                 my $rem = $i%($numinrow);
 2480:                 if ($rem == 0) {
 2481:                     if ($i<@{$types}-1) {
 2482:                         if ($i > 0) { 
 2483:                             $output .= '</tr>';
 2484:                         }
 2485:                         $output .= '<tr>';
 2486:                     }
 2487:                 } elsif ($i==@{$types}-1) {
 2488:                     my $colsleft = $numinrow - $rem;
 2489:                     if ($colsleft > 1) {
 2490:                         $lastcolspan = ' colspan="'.$colsleft.'"';
 2491:                     }
 2492:                 }
 2493:                 my $check = ' ';
 2494:                 if (grep(/^\Q$types->[$i]\E$/,@currtypes)) {
 2495:                     $check = ' checked="checked" ';
 2496:                 }
 2497:                 $output .= '<td class="LC_left_item"'.$lastcolspan.'>'.
 2498:                            '<span class="LC_nobreak"><label>'.
 2499:                            '<input type="checkbox" name="inststatus" '.
 2500:                            'value="'.$types->[$i].'"'.$check.'/>'.
 2501:                            $usertypes->{$types->[$i]}.'</label></span></td>';
 2502:             }
 2503:         }
 2504:         $output .= '</tr></table>';
 2505:     }
 2506:     return $output;
 2507: }
 2508: 
 2509: sub selfcreate_canmodify {
 2510:     my ($context,$dom,$userinfo,$inst_results,$rolesarray) = @_;
 2511:     if (ref($inst_results) eq 'HASH') {
 2512:         my @inststatuses = &get_inststatuses($inst_results);
 2513:         if (@inststatuses == 0) {
 2514:             @inststatuses = ('default');
 2515:         }
 2516:         $rolesarray = \@inststatuses;
 2517:     }
 2518:     my %canmodify =
 2519:         &Apache::lonuserutils::can_modify_userinfo($context,$dom,$userinfo,
 2520:                                                    $rolesarray);
 2521:     return %canmodify;
 2522: }
 2523: 
 2524: sub get_inststatuses {
 2525:     my ($insthashref) = @_;
 2526:     my @inststatuses = ();
 2527:     if (ref($insthashref) eq 'HASH') {
 2528:         if (ref($insthashref->{'inststatus'}) eq 'ARRAY') {
 2529:             @inststatuses = @{$insthashref->{'inststatus'}};
 2530:         }
 2531:     }
 2532:     return @inststatuses;
 2533: }
 2534: 
 2535: # ================================================================= Phase Three
 2536: sub update_user_data {
 2537:     my ($r,$context,$crstype,$brcrum,$showcredits) = @_; 
 2538:     my $uhome=&Apache::lonnet::homeserver($env{'form.ccuname'},
 2539:                                           $env{'form.ccdomain'});
 2540:     # Error messages
 2541:     my $error     = '<span class="LC_error">'.&mt('Error').': ';
 2542:     my $end       = '</span><br /><br />';
 2543:     my $rtnlink   = '<a href="javascript:backPage(document.userupdate,'.
 2544:                     "'$env{'form.prevphase'}','modify')".'" />'.
 2545:                     &mt('Return to previous page').'</a>'.
 2546:                     &Apache::loncommon::end_page();
 2547:     my $now = time;
 2548:     my $title;
 2549:     if (exists($env{'form.makeuser'})) {
 2550: 	$title='Set Privileges for New User';
 2551:     } else {
 2552:         $title='Modify User Privileges';
 2553:     }
 2554:     my $newuser = 0;
 2555:     my ($jsback,$elements) = &crumb_utilities();
 2556:     my $jscript = '<script type="text/javascript">'."\n".
 2557:                   '// <![CDATA['."\n".
 2558:                   $jsback."\n".
 2559:                   '// ]]>'."\n".
 2560:                   '</script>'."\n";
 2561:     my %breadcrumb_text = &singleuser_breadcrumb($crstype);
 2562:     push (@{$brcrum},
 2563:              {href => "javascript:backPage(document.userupdate)",
 2564:               text => $breadcrumb_text{'search'},
 2565:               faq  => 282,
 2566:               bug  => 'Instructor Interface',}
 2567:              );
 2568:     if ($env{'form.prevphase'} eq 'userpicked') {
 2569:         push(@{$brcrum},
 2570:                {href => "javascript:backPage(document.userupdate,'get_user_info','select')",
 2571:                 text => $breadcrumb_text{'userpicked'},
 2572:                 faq  => 282,
 2573:                 bug  => 'Instructor Interface',});
 2574:     }
 2575:     my $helpitem = 'Course_Change_Privileges';
 2576:     if ($env{'form.action'} eq 'singlestudent') {
 2577:         $helpitem = 'Course_Add_Student';
 2578:     }
 2579:     push(@{$brcrum}, 
 2580:             {href => "javascript:backPage(document.userupdate,'$env{'form.prevphase'}','modify')",
 2581:              text => $breadcrumb_text{'modify'},
 2582:              faq  => 282,
 2583:              bug  => 'Instructor Interface',},
 2584:             {href => "/adm/createuser",
 2585:              text => "Result",
 2586:              faq  => 282,
 2587:              bug  => 'Instructor Interface',
 2588:              help => $helpitem});
 2589:     my $args = {bread_crumbs          => $brcrum,
 2590:                 bread_crumbs_component => 'User Management'};
 2591:     if ($env{'form.popup'}) {
 2592:         $args->{'no_nav_bar'} = 1;
 2593:     }
 2594:     $r->print(&Apache::loncommon::start_page($title,$jscript,$args));
 2595:     $r->print(&update_result_form($uhome));
 2596:     # Check Inputs
 2597:     if (! $env{'form.ccuname'} ) {
 2598: 	$r->print($error.&mt('No login name specified').'.'.$end.$rtnlink);
 2599: 	return;
 2600:     }
 2601:     if (  $env{'form.ccuname'} ne 
 2602: 	  &LONCAPA::clean_username($env{'form.ccuname'}) ) {
 2603: 	$r->print($error.&mt('Invalid login name.').'  '.
 2604: 		  &mt('Only letters, numbers, periods, dashes, @, and underscores are valid.').
 2605: 		  $end.$rtnlink);
 2606: 	return;
 2607:     }
 2608:     if (! $env{'form.ccdomain'}       ) {
 2609: 	$r->print($error.&mt('No domain specified').'.'.$end.$rtnlink);
 2610: 	return;
 2611:     }
 2612:     if (  $env{'form.ccdomain'} ne
 2613: 	  &LONCAPA::clean_domain($env{'form.ccdomain'}) ) {
 2614: 	$r->print($error.&mt('Invalid domain name.').'  '.
 2615: 		  &mt('Only letters, numbers, periods, dashes, and underscores are valid.').
 2616: 		  $end.$rtnlink);
 2617: 	return;
 2618:     }
 2619:     if ($uhome eq 'no_host') {
 2620:         $newuser = 1;
 2621:     }
 2622:     if (! exists($env{'form.makeuser'})) {
 2623:         # Modifying an existing user, so check the validity of the name
 2624:         if ($uhome eq 'no_host') {
 2625:             $r->print(
 2626:                 $error
 2627:                .'<p class="LC_error">'
 2628:                .&mt('Unable to determine home server for [_1] in domain [_2].',
 2629:                         '"'.$env{'form.ccuname'}.'"','"'.$env{'form.ccdomain'}.'"')
 2630:                .'</p>');
 2631:             return;
 2632:         }
 2633:     }
 2634:     # Determine authentication method and password for the user being modified
 2635:     my $amode='';
 2636:     my $genpwd='';
 2637:     if ($env{'form.login'} eq 'krb') {
 2638: 	$amode='krb';
 2639: 	$amode.=$env{'form.krbver'};
 2640: 	$genpwd=$env{'form.krbarg'};
 2641:     } elsif ($env{'form.login'} eq 'int') {
 2642: 	$amode='internal';
 2643: 	$genpwd=$env{'form.intarg'};
 2644:     } elsif ($env{'form.login'} eq 'fsys') {
 2645: 	$amode='unix';
 2646: 	$genpwd=$env{'form.fsysarg'};
 2647:     } elsif ($env{'form.login'} eq 'loc') {
 2648: 	$amode='localauth';
 2649: 	$genpwd=$env{'form.locarg'};
 2650: 	$genpwd=" " if (!$genpwd);
 2651:     } elsif (($env{'form.login'} eq 'nochange') ||
 2652:              ($env{'form.login'} eq ''        )) { 
 2653:         # There is no need to tell the user we did not change what they
 2654:         # did not ask us to change.
 2655:         # If they are creating a new user but have not specified login
 2656:         # information this will be caught below.
 2657:     } else {
 2658:             $r->print($error.&mt('Invalid login mode or password').$end.$rtnlink);
 2659:             return;
 2660:     }
 2661: 
 2662:     $r->print('<h3>'.&mt('User [_1] in domain [_2]',
 2663:                         $env{'form.ccuname'}.' ('.&Apache::loncommon::plainname($env{'form.ccuname'},
 2664:                         $env{'form.ccdomain'}).')', $env{'form.ccdomain'}).'</h3>');
 2665:     my %prog_state = &Apache::lonhtmlcommon::Create_PrgWin($r,2);
 2666: 
 2667:     my (%alerts,%rulematch,%inst_results,%curr_rules);
 2668:     my @userinfo = ('firstname','middlename','lastname','generation','permanentemail','id');
 2669:     my @usertools = ('aboutme','blog','webdav','portfolio');
 2670:     my @requestcourses = ('official','unofficial','community','textbook','placement');
 2671:     my @requestauthor = ('requestauthor');
 2672:     my ($othertitle,$usertypes,$types) = 
 2673:         &Apache::loncommon::sorted_inst_types($env{'form.ccdomain'});
 2674:     my %canmodify_status =
 2675:         &Apache::lonuserutils::can_modify_userinfo($context,$env{'form.ccdomain'},
 2676:                                                    ['inststatus']);
 2677:     if ($env{'form.makeuser'}) {
 2678: 	$r->print('<h3>'.&mt('Creating new account.').'</h3>');
 2679:         # Check for the authentication mode and password
 2680:         if (! $amode || ! $genpwd) {
 2681: 	    $r->print($error.&mt('Invalid login mode or password').$end.$rtnlink);    
 2682: 	    return;
 2683: 	}
 2684:         # Determine desired host
 2685:         my $desiredhost = $env{'form.hserver'};
 2686:         if (lc($desiredhost) eq 'default') {
 2687:             $desiredhost = undef;
 2688:         } else {
 2689:             my %home_servers = 
 2690: 		&Apache::lonnet::get_servers($env{'form.ccdomain'},'library');
 2691:             if (! exists($home_servers{$desiredhost})) {
 2692:                 $r->print($error.&mt('Invalid home server specified').$end.$rtnlink);
 2693:                 return;
 2694:             }
 2695:         }
 2696:         # Check ID format
 2697:         my %checkhash;
 2698:         my %checks = ('id' => 1);
 2699:         %{$checkhash{$env{'form.ccuname'}.':'.$env{'form.ccdomain'}}} = (
 2700:             'newuser' => $newuser, 
 2701:             'id' => $env{'form.cid'},
 2702:         );
 2703:         if ($env{'form.cid'} ne '') {
 2704:             &Apache::loncommon::user_rule_check(\%checkhash,\%checks,\%alerts,
 2705:                                           \%rulematch,\%inst_results,\%curr_rules);
 2706:             if (ref($alerts{'id'}) eq 'HASH') {
 2707:                 if (ref($alerts{'id'}{$env{'form.ccdomain'}}) eq 'HASH') {
 2708:                     my $domdesc =
 2709:                         &Apache::lonnet::domain($env{'form.ccdomain'},'description');
 2710:                     if ($alerts{'id'}{$env{'form.ccdomain'}}{$env{'form.cid'}}) {
 2711:                         my $userchkmsg;
 2712:                         if (ref($curr_rules{$env{'form.ccdomain'}}) eq 'HASH') {
 2713:                             $userchkmsg  = 
 2714:                                 &Apache::loncommon::instrule_disallow_msg('id',
 2715:                                                                     $domdesc,1).
 2716:                                 &Apache::loncommon::user_rule_formats($env{'form.ccdomain'},
 2717:                                     $domdesc,$curr_rules{$env{'form.ccdomain'}}{'id'},'id');
 2718:                         }
 2719:                         $r->print($error.&mt('Invalid ID format').$end.
 2720:                                   $userchkmsg.$rtnlink);
 2721:                         return;
 2722:                     }
 2723:                 }
 2724:             }
 2725:         }
 2726:         &Apache::lonhtmlcommon::Increment_PrgWin($r, \%prog_state);
 2727: 	# Call modifyuser
 2728: 	my $result = &Apache::lonnet::modifyuser
 2729: 	    ($env{'form.ccdomain'},$env{'form.ccuname'},$env{'form.cid'},
 2730:              $amode,$genpwd,$env{'form.cfirstname'},
 2731:              $env{'form.cmiddlename'},$env{'form.clastname'},
 2732:              $env{'form.cgeneration'},undef,$desiredhost,
 2733:              $env{'form.cpermanentemail'});
 2734: 	$r->print(&mt('Generating user').': '.$result);
 2735:         $uhome = &Apache::lonnet::homeserver($env{'form.ccuname'},
 2736:                                                $env{'form.ccdomain'});
 2737:         my (%changeHash,%newcustom,%changed,%changedinfo);
 2738:         if ($uhome ne 'no_host') {
 2739:             if ($context eq 'domain') {
 2740:                 foreach my $name ('portfolio','author') {
 2741:                     if ($env{'form.custom_'.$name.'quota'} == 1) {
 2742:                         if ($env{'form.'.$name.'quota'} eq '') {
 2743:                             $newcustom{$name.'quota'} = 0;
 2744:                         } else {
 2745:                             $newcustom{$name.'quota'} = $env{'form.'.$name.'quota'};
 2746:                             $newcustom{$name.'quota'} =~ s/[^\d\.]//g;
 2747:                         }
 2748:                         if (&quota_admin($newcustom{$name.'quota'},\%changeHash,$name)) {
 2749:                             $changed{$name.'quota'} = 1;
 2750:                         }
 2751:                     }
 2752:                 }
 2753:                 foreach my $item (@usertools) {
 2754:                     if ($env{'form.custom'.$item} == 1) {
 2755:                         $newcustom{$item} = $env{'form.tools_'.$item};
 2756:                         $changed{$item} = &tool_admin($item,$newcustom{$item},
 2757:                                                      \%changeHash,'tools');
 2758:                     }
 2759:                 }
 2760:                 foreach my $item (@requestcourses) {
 2761:                     if ($env{'form.custom'.$item} == 1) {
 2762:                         $newcustom{$item} = $env{'form.crsreq_'.$item};
 2763:                         if ($env{'form.crsreq_'.$item} eq 'autolimit') {
 2764:                             $newcustom{$item} .= '=';
 2765:                             $env{'form.crsreq_'.$item.'_limit'} =~ s/\D+//g;
 2766:                             if ($env{'form.crsreq_'.$item.'_limit'}) {
 2767:                                 $newcustom{$item} .= $env{'form.crsreq_'.$item.'_limit'};
 2768:                             }
 2769:                         }
 2770:                         $changed{$item} = &tool_admin($item,$newcustom{$item},
 2771:                                                       \%changeHash,'requestcourses');
 2772:                     }
 2773:                 }
 2774:                 if ($env{'form.customrequestauthor'} == 1) {
 2775:                     $newcustom{'requestauthor'} = $env{'form.requestauthor'};
 2776:                     $changed{'requestauthor'} = &tool_admin('requestauthor',
 2777:                                                     $newcustom{'requestauthor'},
 2778:                                                     \%changeHash,'requestauthor');
 2779:                 }
 2780:                 if (&Apache::lonnet::allowed('cdh',$env{'request.role.domain'})) {
 2781:                     my @adds = &Apache::loncommon::get_env_multiple('form.adhocroleadd');
 2782:                     if (&adhocrole_changes(\%changeHash)) {
 2783:                         $changed{'adhocroles.'.$env{'request.role.domain'}} = $changeHash{'adhocroles.'.$env{'request.role.domain'}};
 2784:                     }  
 2785:                 }
 2786:             }
 2787:             if ($canmodify_status{'inststatus'}) {
 2788:                 if (exists($env{'form.inststatus'})) {
 2789:                     my @inststatuses = &Apache::loncommon::get_env_multiple('form.inststatus');
 2790:                     if (@inststatuses > 0) {
 2791:                         $changeHash{'inststatus'} = join(',',@inststatuses);
 2792:                         $changed{'inststatus'} = $changeHash{'inststatus'};
 2793:                     }
 2794:                 }
 2795:             }
 2796:             if (keys(%changed)) {
 2797:                 foreach my $item (@userinfo) {
 2798:                     $changeHash{$item}  = $env{'form.c'.$item};
 2799:                 }
 2800:                 my $chgresult =
 2801:                      &Apache::lonnet::put('environment',\%changeHash,
 2802:                                           $env{'form.ccdomain'},$env{'form.ccuname'});
 2803:             } 
 2804:         }
 2805:         $r->print('<br />'.&mt('Home server').': '.$uhome.' '.
 2806:                   &Apache::lonnet::hostname($uhome));
 2807:     } elsif (($env{'form.login'} ne 'nochange') &&
 2808:              ($env{'form.login'} ne ''        )) {
 2809: 	# Modify user privileges
 2810:         if (! $amode || ! $genpwd) {
 2811: 	    $r->print($error.'Invalid login mode or password'.$end.$rtnlink);    
 2812: 	    return;
 2813: 	}
 2814: 	# Only allow authentication modification if the person has authority
 2815: 	if (&Apache::lonnet::allowed('mau',$env{'form.ccdomain'})) {
 2816: 	    $r->print('Modifying authentication: '.
 2817:                       &Apache::lonnet::modifyuserauth(
 2818: 		       $env{'form.ccdomain'},$env{'form.ccuname'},
 2819:                        $amode,$genpwd));
 2820:             $r->print('<br />'.&mt('Home server').': '.&Apache::lonnet::homeserver
 2821: 		  ($env{'form.ccuname'},$env{'form.ccdomain'}));
 2822: 	} else {
 2823: 	    # Okay, this is a non-fatal error.
 2824: 	    $r->print($error.&mt('You do not have the authority to modify this users authentication information.').$end);    
 2825: 	}
 2826:     }
 2827:     $r->rflush(); # Finish display of header before time consuming actions start
 2828:     &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state);
 2829:     ##
 2830:     my (@userroles,%userupdate,$cnum,$cdom,$defaultcredits,%namechanged);
 2831:     if ($context eq 'course') {
 2832:         ($cnum,$cdom) =
 2833:             &Apache::lonuserutils::get_course_identity();
 2834:         $crstype = &Apache::loncommon::course_type($cdom.'_'.$cnum);
 2835:         if ($showcredits) {
 2836:            $defaultcredits = &Apache::lonuserutils::get_defaultcredits($cdom,$cnum);
 2837:         }
 2838:     }
 2839:     if (! $env{'form.makeuser'} ) {
 2840:         # Check for need to change
 2841:         my %userenv = &Apache::lonnet::get
 2842:             ('environment',['firstname','middlename','lastname','generation',
 2843:              'id','permanentemail','portfolioquota','authorquota','inststatus',
 2844:              'tools.aboutme','tools.blog','tools.webdav','tools.portfolio',
 2845:              'requestcourses.official','requestcourses.unofficial',
 2846:              'requestcourses.community','requestcourses.textbook',
 2847:              'reqcrsotherdom.official','reqcrsotherdom.unofficial',
 2848:              'reqcrsotherdom.community','reqcrsotherdom.textbook',
 2849:              'reqcrsotherdom.placement','requestauthor',
 2850:              'adhocroles.'.$env{'request.role.domain'}],
 2851:               $env{'form.ccdomain'},$env{'form.ccuname'});
 2852:         my ($tmp) = keys(%userenv);
 2853:         if ($tmp =~ /^(con_lost|error)/i) { 
 2854:             %userenv = ();
 2855:         }
 2856:         my $no_forceid_alert;
 2857:         # Check to see if user information can be changed
 2858:         my %domconfig =
 2859:             &Apache::lonnet::get_dom('configuration',['usermodification'],
 2860:                                      $env{'form.ccdomain'});
 2861:         my @statuses = ('active','future');
 2862:         my %roles = &Apache::lonnet::get_my_roles($env{'form.ccuname'},$env{'form.ccdomain'},'userroles',\@statuses,undef,$env{'request.role.domain'});
 2863:         my ($auname,$audom);
 2864:         if ($context eq 'author') {
 2865:             $auname = $env{'user.name'};
 2866:             $audom = $env{'user.domain'};     
 2867:         }
 2868:         foreach my $item (keys(%roles)) {
 2869:             my ($rolenum,$roledom,$role) = split(/:/,$item,-1);
 2870:             if ($context eq 'course') {
 2871:                 if ($cnum ne '' && $cdom ne '') {
 2872:                     if ($rolenum eq $cnum && $roledom eq $cdom) {
 2873:                         if (!grep(/^\Q$role\E$/,@userroles)) {
 2874:                             push(@userroles,$role);
 2875:                         }
 2876:                     }
 2877:                 }
 2878:             } elsif ($context eq 'author') {
 2879:                 if ($rolenum eq $auname && $roledom eq $audom) {
 2880:                     if (!grep(/^\Q$role\E$/,@userroles)) { 
 2881:                         push(@userroles,$role);
 2882:                     }
 2883:                 }
 2884:             }
 2885:         }
 2886:         if ($env{'form.action'} eq 'singlestudent') {
 2887:             if (!grep(/^st$/,@userroles)) {
 2888:                 push(@userroles,'st');
 2889:             }
 2890:         } else {
 2891:             # Check for course or co-author roles being activated or re-enabled
 2892:             if ($context eq 'author' || $context eq 'course') {
 2893:                 foreach my $key (keys(%env)) {
 2894:                     if ($context eq 'author') {
 2895:                         if ($key=~/^form\.act_\Q$audom\E_\Q$auname\E_([^_]+)/) {
 2896:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 2897:                                 push(@userroles,$1);
 2898:                             }
 2899:                         } elsif ($key =~/^form\.ren\:\Q$audom\E\/\Q$auname\E_([^_]+)/) {
 2900:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 2901:                                 push(@userroles,$1);
 2902:                             }
 2903:                         }
 2904:                     } elsif ($context eq 'course') {
 2905:                         if ($key=~/^form\.act_\Q$cdom\E_\Q$cnum\E_([^_]+)/) {
 2906:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 2907:                                 push(@userroles,$1);
 2908:                             }
 2909:                         } elsif ($key =~/^form\.ren\:\Q$cdom\E\/\Q$cnum\E(\/?\w*)_([^_]+)/) {
 2910:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 2911:                                 push(@userroles,$1);
 2912:                             }
 2913:                         }
 2914:                     }
 2915:                 }
 2916:             }
 2917:         }
 2918:         #Check to see if we can change personal data for the user 
 2919:         my (@mod_disallowed,@longroles);
 2920:         foreach my $role (@userroles) {
 2921:             if ($role eq 'cr') {
 2922:                 push(@longroles,'Custom');
 2923:             } else {
 2924:                 push(@longroles,&Apache::lonnet::plaintext($role,$crstype)); 
 2925:             }
 2926:         }
 2927:         my %canmodify = &Apache::lonuserutils::can_modify_userinfo($context,$env{'form.ccdomain'},\@userinfo,\@userroles);
 2928:         foreach my $item (@userinfo) {
 2929:             # Strip leading and trailing whitespace
 2930:             $env{'form.c'.$item} =~ s/(\s+$|^\s+)//g;
 2931:             if (!$canmodify{$item}) {
 2932:                 if (defined($env{'form.c'.$item})) {
 2933:                     if ($env{'form.c'.$item} ne $userenv{$item}) {
 2934:                         push(@mod_disallowed,$item);
 2935:                     }
 2936:                 }
 2937:                 $env{'form.c'.$item} = $userenv{$item};
 2938:             }
 2939:         }
 2940:         # Check to see if we can change the Student/Employee ID
 2941:         my $forceid = $env{'form.forceid'};
 2942:         my $recurseid = $env{'form.recurseid'};
 2943:         my (%alerts,%rulematch,%idinst_results,%curr_rules,%got_rules);
 2944:         my %uidhash = &Apache::lonnet::idrget($env{'form.ccdomain'},
 2945:                                             $env{'form.ccuname'});
 2946:         if (($uidhash{$env{'form.ccuname'}}) && 
 2947:             ($uidhash{$env{'form.ccuname'}}!~/error\:/) && 
 2948:             (!$forceid)) {
 2949:             if ($env{'form.cid'} ne $uidhash{$env{'form.ccuname'}}) {
 2950:                 $env{'form.cid'} = $userenv{'id'};
 2951:                 $no_forceid_alert = &mt('New student/employee ID does not match existing ID for this user.')
 2952:                                    .'<br />'
 2953:                                    .&mt("Change is not permitted without checking the 'Force ID change' checkbox on the previous page.")
 2954:                                    .'<br />'."\n";
 2955:             }
 2956:         }
 2957:         if ($env{'form.cid'} ne $userenv{'id'}) {
 2958:             my $checkhash;
 2959:             my $checks = { 'id' => 1 };
 2960:             $checkhash->{$env{'form.ccuname'}.':'.$env{'form.ccdomain'}} = 
 2961:                    { 'newuser' => $newuser,
 2962:                      'id'  => $env{'form.cid'}, 
 2963:                    };
 2964:             &Apache::loncommon::user_rule_check($checkhash,$checks,
 2965:                 \%alerts,\%rulematch,\%idinst_results,\%curr_rules,\%got_rules);
 2966:             if (ref($alerts{'id'}) eq 'HASH') {
 2967:                 if (ref($alerts{'id'}{$env{'form.ccdomain'}}) eq 'HASH') {
 2968:                    $env{'form.cid'} = $userenv{'id'};
 2969:                 }
 2970:             }
 2971:         }
 2972:         my (%quotachanged,%oldquota,%newquota,%olddefquota,%newdefquota, 
 2973:             $oldinststatus,$newinststatus,%oldisdefault,%newisdefault,%oldsettings,
 2974:             %oldsettingstext,%newsettings,%newsettingstext,@disporder,
 2975:             %oldsettingstatus,%newsettingstatus);
 2976:         @disporder = ('inststatus');
 2977:         if ($env{'request.role.domain'} eq $env{'form.ccdomain'}) {
 2978:             push(@disporder,'requestcourses','requestauthor');
 2979:         } else {
 2980:             push(@disporder,'reqcrsotherdom');
 2981:         }
 2982:         push(@disporder,('quota','tools'));
 2983:         $oldinststatus = $userenv{'inststatus'};
 2984:         foreach my $name ('portfolio','author') {
 2985:             ($olddefquota{$name},$oldsettingstatus{$name}) = 
 2986:                 &Apache::loncommon::default_quota($env{'form.ccdomain'},$oldinststatus,$name);
 2987:             ($newdefquota{$name},$newsettingstatus{$name}) = ($olddefquota{$name},$oldsettingstatus{$name});
 2988:         }
 2989:         push(@disporder,'adhocroles');
 2990:         my %canshow;
 2991:         if (&Apache::lonnet::allowed('mpq',$env{'form.ccdomain'})) {
 2992:             $canshow{'quota'} = 1;
 2993:         }
 2994:         if (&Apache::lonnet::allowed('mut',$env{'form.ccdomain'})) {
 2995:             $canshow{'tools'} = 1;
 2996:         }
 2997:         if (&Apache::lonnet::allowed('ccc',$env{'form.ccdomain'})) {
 2998:             $canshow{'requestcourses'} = 1;
 2999:         } elsif (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) {
 3000:             $canshow{'reqcrsotherdom'} = 1;
 3001:         }
 3002:         if (&Apache::lonnet::allowed('mau',$env{'form.ccdomain'})) {
 3003:             $canshow{'inststatus'} = 1;
 3004:         }
 3005:         if (&Apache::lonnet::allowed('cau',$env{'form.ccdomain'})) {
 3006:             $canshow{'requestauthor'} = 1;
 3007:         }
 3008:         if (&Apache::lonnet::allowed('cdh',$env{'request.role.domain'})) {
 3009:             $canshow{'adhocroles'} = 1;
 3010:         }
 3011:         my (%changeHash,%changed);
 3012:         if ($oldinststatus eq '') {
 3013:             $oldsettings{'inststatus'} = $othertitle; 
 3014:         } else {
 3015:             if (ref($usertypes) eq 'HASH') {
 3016:                 $oldsettings{'inststatus'} = join(', ',map{ $usertypes->{ &unescape($_) }; } (split(/:/,$userenv{'inststatus'})));
 3017:             } else {
 3018:                 $oldsettings{'inststatus'} = join(', ',map{ &unescape($_); } (split(/:/,$userenv{'inststatus'})));
 3019:             }
 3020:         }
 3021:         $changeHash{'inststatus'} = $userenv{'inststatus'};
 3022:         if ($canmodify_status{'inststatus'}) {
 3023:             $canshow{'inststatus'} = 1;
 3024:             if (exists($env{'form.inststatus'})) {
 3025:                 my @inststatuses = &Apache::loncommon::get_env_multiple('form.inststatus');
 3026:                 if (@inststatuses > 0) {
 3027:                     $newinststatus = join(':',map { &escape($_); } @inststatuses);
 3028:                     $changeHash{'inststatus'} = $newinststatus;
 3029:                     if ($newinststatus ne $oldinststatus) {
 3030:                         $changed{'inststatus'} = $newinststatus;
 3031:                         foreach my $name ('portfolio','author') {
 3032:                             ($newdefquota{$name},$newsettingstatus{$name}) =
 3033:                                 &Apache::loncommon::default_quota($env{'form.ccdomain'},$newinststatus,$name);
 3034:                         }
 3035:                     }
 3036:                     if (ref($usertypes) eq 'HASH') {
 3037:                         $newsettings{'inststatus'} = join(', ',map{ $usertypes->{$_}; } (@inststatuses)); 
 3038:                     } else {
 3039:                         $newsettings{'inststatus'} = join(', ',@inststatuses);
 3040:                     }
 3041:                 }
 3042:             } else {
 3043:                 $newinststatus = '';
 3044:                 $changeHash{'inststatus'} = $newinststatus;
 3045:                 $newsettings{'inststatus'} = $othertitle;
 3046:                 if ($newinststatus ne $oldinststatus) {
 3047:                     $changed{'inststatus'} = $changeHash{'inststatus'};
 3048:                     foreach my $name ('portfolio','author') {
 3049:                         ($newdefquota{$name},$newsettingstatus{$name}) =
 3050:                             &Apache::loncommon::default_quota($env{'form.ccdomain'},$newinststatus,$name);
 3051:                     }
 3052:                 }
 3053:             }
 3054:         } elsif ($context ne 'selfcreate') {
 3055:             $canshow{'inststatus'} = 1;
 3056:             $newsettings{'inststatus'} = $oldsettings{'inststatus'};
 3057:         }
 3058:         foreach my $name ('portfolio','author') {
 3059:             $changeHash{$name.'quota'} = $userenv{$name.'quota'};
 3060:         }
 3061:         if ($context eq 'domain') {
 3062:             foreach my $name ('portfolio','author') {
 3063:                 if ($userenv{$name.'quota'} ne '') {
 3064:                     $oldquota{$name} = $userenv{$name.'quota'};
 3065:                     if ($env{'form.custom_'.$name.'quota'} == 1) {
 3066:                         if ($env{'form.'.$name.'quota'} eq '') {
 3067:                             $newquota{$name} = 0;
 3068:                         } else {
 3069:                             $newquota{$name} = $env{'form.'.$name.'quota'};
 3070:                             $newquota{$name} =~ s/[^\d\.]//g;
 3071:                         }
 3072:                         if ($newquota{$name} != $oldquota{$name}) {
 3073:                             if (&quota_admin($newquota{$name},\%changeHash,$name)) {
 3074:                                 $changed{$name.'quota'} = 1;
 3075:                             }
 3076:                         }
 3077:                     } else {
 3078:                         if (&quota_admin('',\%changeHash,$name)) {
 3079:                             $changed{$name.'quota'} = 1;
 3080:                             $newquota{$name} = $newdefquota{$name};
 3081:                             $newisdefault{$name} = 1;
 3082:                         }
 3083:                     }
 3084:                 } else {
 3085:                     $oldisdefault{$name} = 1;
 3086:                     $oldquota{$name} = $olddefquota{$name};
 3087:                     if ($env{'form.custom_'.$name.'quota'} == 1) {
 3088:                         if ($env{'form.'.$name.'quota'} eq '') {
 3089:                             $newquota{$name} = 0;
 3090:                         } else {
 3091:                             $newquota{$name} = $env{'form.'.$name.'quota'};
 3092:                             $newquota{$name} =~ s/[^\d\.]//g;
 3093:                         }
 3094:                         if (&quota_admin($newquota{$name},\%changeHash,$name)) {
 3095:                             $changed{$name.'quota'} = 1;
 3096:                         }
 3097:                     } else {
 3098:                         $newquota{$name} = $newdefquota{$name};
 3099:                         $newisdefault{$name} = 1;
 3100:                     }
 3101:                 }
 3102:                 if ($oldisdefault{$name}) {
 3103:                     $oldsettingstext{'quota'}{$name} = &get_defaultquota_text($oldsettingstatus{$name});
 3104:                 }  else {
 3105:                     $oldsettingstext{'quota'}{$name} = &mt('custom quota: [_1] MB',$oldquota{$name});
 3106:                 }
 3107:                 if ($newisdefault{$name}) {
 3108:                     $newsettingstext{'quota'}{$name} = &get_defaultquota_text($newsettingstatus{$name});
 3109:                 } else {
 3110:                     $newsettingstext{'quota'}{$name} = &mt('custom quota: [_1] MB',$newquota{$name});
 3111:                 }
 3112:             }
 3113:             &tool_changes('tools',\@usertools,\%oldsettings,\%oldsettingstext,\%userenv,
 3114:                           \%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3115:             if ($env{'form.ccdomain'} eq $env{'request.role.domain'}) {
 3116:                 &tool_changes('requestcourses',\@requestcourses,\%oldsettings,\%oldsettingstext,
 3117:                               \%userenv,\%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3118:                 &tool_changes('requestauthor',\@requestauthor,\%oldsettings,\%oldsettingstext,
 3119:                               \%userenv,\%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3120:             } else {
 3121:                 &tool_changes('reqcrsotherdom',\@requestcourses,\%oldsettings,\%oldsettingstext,
 3122:                               \%userenv,\%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3123:             }
 3124:             if ($userenv{'adhocroles.'.$env{'request.role.domain'}}) {
 3125:                 $changeHash{'adhocroles.'.$env{'request.role.domain'}} = $userenv{'adhocroles.'.$env{'request.role.domain'}};
 3126:             }
 3127:             if (&adhocrole_changes(\%changeHash,\%userenv)) {
 3128:                 $changed{'adhocroles'} = 1;
 3129:                 $oldsettings{'adhocroles'} = $userenv{'adhocroles.'.$env{'request.role.domain'}};
 3130:                 $newsettings{'adhocroles'} = $changeHash{'adhocroles.'.$env{'request.role.domain'}}; 
 3131:             }
 3132:         }
 3133:         foreach my $item (@userinfo) {
 3134:             if ($env{'form.c'.$item} ne $userenv{$item}) {
 3135:                 $namechanged{$item} = 1;
 3136:             }
 3137:         }
 3138:         foreach my $name ('portfolio','author') {
 3139:             $oldsettings{'quota'}{$name} = &mt('[_1] MB',$oldquota{$name});
 3140:             $newsettings{'quota'}{$name} = &mt('[_1] MB',$newquota{$name});
 3141:         }
 3142:         if ((keys(%namechanged) > 0) || (keys(%changed) > 0)) {
 3143:             my ($chgresult,$namechgresult);
 3144:             if (keys(%changed) > 0) {
 3145:                 $chgresult = 
 3146:                     &Apache::lonnet::put('environment',\%changeHash,
 3147:                                   $env{'form.ccdomain'},$env{'form.ccuname'});
 3148:                 if ($chgresult eq 'ok') {
 3149:                     if (($env{'user.name'} eq $env{'form.ccuname'}) &&
 3150:                         ($env{'user.domain'} eq $env{'form.ccdomain'})) {
 3151:                         my %newenvhash;
 3152:                         foreach my $key (keys(%changed)) {
 3153:                             if (($key eq 'official') || ($key eq 'unofficial') ||
 3154:                                 ($key eq 'community') || ($key eq 'textbook') ||
 3155:                                 ($key eq 'placement')) {
 3156:                                 $newenvhash{'environment.requestcourses.'.$key} =
 3157:                                     $changeHash{'requestcourses.'.$key};
 3158:                                 if ($changeHash{'requestcourses.'.$key}) {
 3159:                                     $newenvhash{'environment.canrequest.'.$key} = 1;
 3160:                                 } else {
 3161:                                     $newenvhash{'environment.canrequest.'.$key} =
 3162:           &Apache::lonnet::usertools_access($env{'user.name'},$env{'user.domain'},
 3163:                                             $key,'reload','requestcourses');
 3164:                                 }
 3165:                             } elsif ($key eq 'requestauthor') {
 3166:                                 $newenvhash{'environment.'.$key} = $changeHash{$key};
 3167:                                 if ($changeHash{$key}) {
 3168:                                     $newenvhash{'environment.canrequest.author'} = 1;
 3169:                                 } else {
 3170:                                     $newenvhash{'environment.canrequest.author'} =
 3171:           &Apache::lonnet::usertools_access($env{'user.name'},$env{'user.domain'},
 3172:                                             $key,'reload','requestauthor');
 3173:                                 }
 3174:                             } elsif ($key eq 'adhocroles') {
 3175:                                 $newenvhash{'adhocroles.'.$env{'request.role.domain'}} =
 3176:                                     $changeHash{'adhocroles.'.$env{'request.role.domain'}};
 3177:                             } elsif ($key ne 'quota') {
 3178:                                 $newenvhash{'environment.tools.'.$key} = 
 3179:                                     $changeHash{'tools.'.$key};
 3180:                                 if ($changeHash{'tools.'.$key} ne '') {
 3181:                                     $newenvhash{'environment.availabletools.'.$key} =
 3182:                                         $changeHash{'tools.'.$key};
 3183:                                 } else {
 3184:                                     $newenvhash{'environment.availabletools.'.$key} =
 3185:           &Apache::lonnet::usertools_access($env{'user.name'},$env{'user.domain'},
 3186:           $key,'reload','tools');
 3187:                                 }
 3188:                             }
 3189:                         }
 3190:                         if (keys(%newenvhash)) {
 3191:                             &Apache::lonnet::appenv(\%newenvhash);
 3192:                         }
 3193:                     }
 3194:                 }
 3195:             }
 3196:             if (keys(%namechanged) > 0) {
 3197:                 foreach my $field (@userinfo) {
 3198:                     $changeHash{$field}  = $env{'form.c'.$field};
 3199:                 }
 3200: # Make the change
 3201:                 $namechgresult =
 3202:                     &Apache::lonnet::modifyuser($env{'form.ccdomain'},
 3203:                         $env{'form.ccuname'},$changeHash{'id'},undef,undef,
 3204:                         $changeHash{'firstname'},$changeHash{'middlename'},
 3205:                         $changeHash{'lastname'},$changeHash{'generation'},
 3206:                         $changeHash{'id'},undef,$changeHash{'permanentemail'},undef,\@userinfo);
 3207:                 %userupdate = (
 3208:                                lastname   => $env{'form.clastname'},
 3209:                                middlename => $env{'form.cmiddlename'},
 3210:                                firstname  => $env{'form.cfirstname'},
 3211:                                generation => $env{'form.cgeneration'},
 3212:                                id         => $env{'form.cid'},
 3213:                              );
 3214:             }
 3215:             if (((keys(%namechanged) > 0) && $namechgresult eq 'ok') || 
 3216:                 ((keys(%changed) > 0) && $chgresult eq 'ok')) {
 3217:             # Tell the user we changed the name
 3218:                 &display_userinfo($r,1,\@disporder,\%canshow,\@requestcourses,
 3219:                                   \@usertools,\@requestauthor,\%userenv,\%changed,\%namechanged,
 3220:                                   \%oldsettings, \%oldsettingstext,\%newsettings,
 3221:                                   \%newsettingstext);
 3222:                 if ($env{'form.cid'} ne $userenv{'id'}) {
 3223:                     &Apache::lonnet::idput($env{'form.ccdomain'},
 3224:                          {$env{'form.ccuname'} => $env{'form.cid'}},$uhome,'ids');
 3225:                     if (($recurseid) &&
 3226:                         (&Apache::lonnet::allowed('mau',$env{'form.ccdomain'}))) {
 3227:                         my $idresult = 
 3228:                             &Apache::lonuserutils::propagate_id_change(
 3229:                                 $env{'form.ccuname'},$env{'form.ccdomain'},
 3230:                                 \%userupdate);
 3231:                         $r->print('<br />'.$idresult.'<br />');
 3232:                     }
 3233:                 }
 3234:                 if (($env{'form.ccdomain'} eq $env{'user.domain'}) && 
 3235:                     ($env{'form.ccuname'} eq $env{'user.name'})) {
 3236:                     my %newenvhash;
 3237:                     foreach my $key (keys(%changeHash)) {
 3238:                         $newenvhash{'environment.'.$key} = $changeHash{$key};
 3239:                     }
 3240:                     &Apache::lonnet::appenv(\%newenvhash);
 3241:                 }
 3242:             } else { # error occurred
 3243:                 $r->print(
 3244:                     '<p class="LC_error">'
 3245:                    .&mt('Unable to successfully change environment for [_1] in domain [_2].',
 3246:                             '"'.$env{'form.ccuname'}.'"',
 3247:                             '"'.$env{'form.ccdomain'}.'"')
 3248:                    .'</p>');
 3249:             }
 3250:         } else { # End of if ($env ... ) logic
 3251:             # They did not want to change the users name, quota, tool availability,
 3252:             # or ability to request creation of courses, 
 3253:             # but we can still tell them what the name and quota and availabilities are  
 3254:             &display_userinfo($r,undef,\@disporder,\%canshow,\@requestcourses,
 3255:                               \@usertools,\@requestauthor,\%userenv,\%changed,\%namechanged,\%oldsettings,
 3256:                               \%oldsettingstext,\%newsettings,\%newsettingstext);
 3257:         }
 3258:         if (@mod_disallowed) {
 3259:             my ($rolestr,$contextname);
 3260:             if (@longroles > 0) {
 3261:                 $rolestr = join(', ',@longroles);
 3262:             } else {
 3263:                 $rolestr = &mt('No roles');
 3264:             }
 3265:             if ($context eq 'course') {
 3266:                 $contextname = 'course';
 3267:             } elsif ($context eq 'author') {
 3268:                 $contextname = 'co-author';
 3269:             }
 3270:             $r->print(&mt('The following fields were not updated: ').'<ul>');
 3271:             my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
 3272:             foreach my $field (@mod_disallowed) {
 3273:                 $r->print('<li>'.$fieldtitles{$field}.'</li>'."\n"); 
 3274:             }
 3275:             $r->print('</ul>');
 3276:             if (@mod_disallowed == 1) {
 3277:                 $r->print(&mt("You do not have the authority to change this field given the user's current set of active/future $contextname roles:"));
 3278:             } else {
 3279:                 $r->print(&mt("You do not have the authority to change these fields given the user's current set of active/future $contextname roles:"));
 3280:             }
 3281:             my $helplink = 'javascript:helpMenu('."'display'".')';
 3282:             $r->print('<span class="LC_cusr_emph">'.$rolestr.'</span><br />'
 3283:                      .&mt('Please contact your [_1]helpdesk[_2] for more information.'
 3284:                          ,'<a href="'.$helplink.'">','</a>')
 3285:                       .'<br />');
 3286:         }
 3287:         $r->print('<span class="LC_warning">'
 3288:                   .$no_forceid_alert
 3289:                   .&Apache::lonuserutils::print_namespacing_alerts($env{'form.ccdomain'},\%alerts,\%curr_rules)
 3290:                   .'</span>');
 3291:     }
 3292:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 3293:     if ($env{'form.action'} eq 'singlestudent') {
 3294:         &enroll_single_student($r,$uhome,$amode,$genpwd,$now,$newuser,$context,
 3295:                                $crstype,$showcredits,$defaultcredits);
 3296:         my $linktext = ($crstype eq 'Community' ?
 3297:             &mt('Enroll Another Member') : &mt('Enroll Another Student'));
 3298:         $r->print(
 3299:             &Apache::lonhtmlcommon::actionbox([
 3300:                 '<a href="javascript:backPage(document.userupdate)">'
 3301:                .($crstype eq 'Community' ? 
 3302:                     &mt('Enroll Another Member') : &mt('Enroll Another Student'))
 3303:                .'</a>']));
 3304:     } else {
 3305:         my @rolechanges = &update_roles($r,$context,$showcredits);
 3306:         if (keys(%namechanged) > 0) {
 3307:             if ($context eq 'course') {
 3308:                 if (@userroles > 0) {
 3309:                     if ((@rolechanges == 0) || 
 3310:                         (!(grep(/^st$/,@rolechanges)))) {
 3311:                         if (grep(/^st$/,@userroles)) {
 3312:                             my $classlistupdated =
 3313:                                 &Apache::lonuserutils::update_classlist($cdom,
 3314:                                               $cnum,$env{'form.ccdomain'},
 3315:                                        $env{'form.ccuname'},\%userupdate);
 3316:                         }
 3317:                     }
 3318:                 }
 3319:             }
 3320:         }
 3321:         my $userinfo = &Apache::loncommon::plainname($env{'form.ccuname'},
 3322:                                                      $env{'form.ccdomain'});
 3323:         if ($env{'form.popup'}) {
 3324:             $r->print('<p><a href="javascript:window.close()">'.&mt('Close window').'</a></p>');
 3325:         } else {
 3326:             $r->print('<br />'.&Apache::lonhtmlcommon::actionbox(['<a href="javascript:backPage(document.userupdate,'."'$env{'form.prevphase'}','modify'".')">'
 3327:                      .&mt('Modify this user: [_1]','<span class="LC_cusr_emph">'.$env{'form.ccuname'}.':'.$env{'form.ccdomain'}.' ('.$userinfo.')</span>').'</a>',
 3328:                      '<a href="javascript:backPage(document.userupdate)">'.&mt('Create/Modify Another User').'</a>']));
 3329:         }
 3330:     }
 3331: }
 3332: 
 3333: sub display_userinfo {
 3334:     my ($r,$changed,$order,$canshow,$requestcourses,$usertools,$requestauthor,
 3335:         $userenv,$changedhash,$namechangedhash,$oldsetting,$oldsettingtext,
 3336:         $newsetting,$newsettingtext) = @_;
 3337:     return unless (ref($order) eq 'ARRAY' &&
 3338:                    ref($canshow) eq 'HASH' && 
 3339:                    ref($requestcourses) eq 'ARRAY' && 
 3340:                    ref($requestauthor) eq 'ARRAY' &&
 3341:                    ref($usertools) eq 'ARRAY' && 
 3342:                    ref($userenv) eq 'HASH' &&
 3343:                    ref($changedhash) eq 'HASH' &&
 3344:                    ref($oldsetting) eq 'HASH' &&
 3345:                    ref($oldsettingtext) eq 'HASH' &&
 3346:                    ref($newsetting) eq 'HASH' &&
 3347:                    ref($newsettingtext) eq 'HASH');
 3348:     my %lt=&Apache::lonlocal::texthash(
 3349:          'ui'             => 'User Information',
 3350:          'uic'            => 'User Information Changed',
 3351:          'firstname'      => 'First Name',
 3352:          'middlename'     => 'Middle Name',
 3353:          'lastname'       => 'Last Name',
 3354:          'generation'     => 'Generation',
 3355:          'id'             => 'Student/Employee ID',
 3356:          'permanentemail' => 'Permanent e-mail address',
 3357:          'portfolioquota' => 'Disk space allocated to portfolio files',
 3358:          'authorquota'    => 'Disk space allocated to Authoring Space',
 3359:          'blog'           => 'Blog Availability',
 3360:          'webdav'         => 'WebDAV Availability',
 3361:          'aboutme'        => 'Personal Information Page Availability',
 3362:          'portfolio'      => 'Portfolio Availability',
 3363:          'official'       => 'Can Request Official Courses',
 3364:          'unofficial'     => 'Can Request Unofficial Courses',
 3365:          'community'      => 'Can Request Communities',
 3366:          'textbook'       => 'Can Request Textbook Courses',
 3367:          'placement'      => 'Can Request Placement Tests',
 3368:          'requestauthor'  => 'Can Request Author Role',
 3369:          'adhocroles'     => 'Ad Hoc Roles Selectable via Helpdesk Role',
 3370:          'inststatus'     => "Affiliation",
 3371:          'prvs'           => 'Previous Value:',
 3372:          'chto'           => 'Changed To:'
 3373:     );
 3374:     if ($changed) {
 3375:         $r->print('<h3>'.$lt{'uic'}.'</h3>'.
 3376:                 &Apache::loncommon::start_data_table().
 3377:                 &Apache::loncommon::start_data_table_header_row());
 3378:         $r->print("<th>&nbsp;</th>\n");
 3379:         $r->print('<th><b>'.$lt{'prvs'}.'</b></th>');
 3380:         $r->print('<th><span class="LC_nobreak"><b>'.$lt{'chto'}.'</b></span></th>');
 3381:         $r->print(&Apache::loncommon::end_data_table_header_row());
 3382:         my @userinfo = ('firstname','middlename','lastname','generation','permanentemail','id');
 3383: 
 3384:         foreach my $item (@userinfo) {
 3385:             my $value = $env{'form.c'.$item};
 3386:             #show changes only:
 3387:             unless ($value eq $userenv->{$item}){
 3388:                 $r->print(&Apache::loncommon::start_data_table_row());
 3389:                 $r->print("<td>$lt{$item}</td>\n");
 3390:                 $r->print("<td>".$userenv->{$item}."</td>\n");
 3391:                 $r->print("<td>$value </td>\n");
 3392:                 $r->print(&Apache::loncommon::end_data_table_row());
 3393:             }
 3394:         }
 3395:         foreach my $entry (@{$order}) {
 3396:             if ($canshow->{$entry}) {
 3397:                 if (($entry eq 'requestcourses') || ($entry eq 'reqcrsotherdom') || ($entry eq 'requestauthor')) {
 3398:                     my @items;
 3399:                     if ($entry eq 'requestauthor') {
 3400:                         @items = ($entry);
 3401:                     } else {
 3402:                         @items = @{$requestcourses};
 3403:                     }
 3404:                     foreach my $item (@items) {
 3405:                         if (($newsetting->{$item} ne $oldsetting->{$item}) || 
 3406:                             ($newsettingtext->{$item} ne $oldsettingtext->{$item})) {
 3407:                             $r->print(&Apache::loncommon::start_data_table_row()."\n");  
 3408:                             $r->print("<td>$lt{$item}</td>\n");
 3409:                             $r->print("<td>".$oldsetting->{$item});
 3410:                             if ($oldsettingtext->{$item}) {
 3411:                                 if ($oldsetting->{$item}) {
 3412:                                     $r->print(' -- ');
 3413:                                 }
 3414:                                 $r->print($oldsettingtext->{$item});
 3415:                             }
 3416:                             $r->print("</td>\n");
 3417:                             $r->print("<td>".$newsetting->{$item});
 3418:                             if ($newsettingtext->{$item}) {
 3419:                                 if ($newsetting->{$item}) {
 3420:                                     $r->print(' -- ');
 3421:                                 }
 3422:                                 $r->print($newsettingtext->{$item});
 3423:                             }
 3424:                             $r->print("</td>\n");
 3425:                             $r->print(&Apache::loncommon::end_data_table_row()."\n");
 3426:                         }
 3427:                     }
 3428:                 } elsif ($entry eq 'tools') {
 3429:                     foreach my $item (@{$usertools}) {
 3430:                         if ($newsetting->{$item} ne $oldsetting->{$item}) {
 3431:                             $r->print(&Apache::loncommon::start_data_table_row()."\n");
 3432:                             $r->print("<td>$lt{$item}</td>\n");
 3433:                             $r->print("<td>".$oldsetting->{$item}.' '.$oldsettingtext->{$item}."</td>\n");
 3434:                             $r->print("<td>".$newsetting->{$item}.' '.$newsettingtext->{$item}."</td>\n");
 3435:                             $r->print(&Apache::loncommon::end_data_table_row()."\n");
 3436:                         }
 3437:                     }
 3438:                 } elsif ($entry eq 'quota') {
 3439:                     if ((ref($oldsetting->{$entry}) eq 'HASH') && (ref($oldsettingtext->{$entry}) eq 'HASH') &&
 3440:                         (ref($newsetting->{$entry}) eq 'HASH') && (ref($newsettingtext->{$entry}) eq 'HASH')) {
 3441:                         foreach my $name ('portfolio','author') {
 3442:                             if ($newsetting->{$entry}->{$name} ne $oldsetting->{$entry}->{$name}) {
 3443:                                 $r->print(&Apache::loncommon::start_data_table_row()."\n");
 3444:                                 $r->print("<td>$lt{$name.$entry}</td>\n");
 3445:                                 $r->print("<td>".$oldsettingtext->{$entry}->{$name}."</td>\n");
 3446:                                 $r->print("<td>".$newsettingtext->{$entry}->{$name}."</td>\n");
 3447:                                 $r->print(&Apache::loncommon::end_data_table_row()."\n");
 3448:                             }
 3449:                         }
 3450:                     }
 3451:                 } else {
 3452:                     if ($newsetting->{$entry} ne $oldsetting->{$entry}) {
 3453:                         $r->print(&Apache::loncommon::start_data_table_row()."\n");
 3454:                         $r->print("<td>$lt{$entry}</td>\n");
 3455:                         $r->print("<td>".$oldsetting->{$entry}.' '.$oldsettingtext->{$entry}."</td>\n");
 3456:                         $r->print("<td>".$newsetting->{$entry}.' '.$newsettingtext->{$entry}."</td>\n");
 3457:                         $r->print(&Apache::loncommon::end_data_table_row()."\n");
 3458:                     }
 3459:                 }
 3460:             }
 3461:         }
 3462:         $r->print(&Apache::loncommon::end_data_table().'<br />');
 3463:     } else {
 3464:         $r->print('<h3>'.$lt{'ui'}.'</h3>'.
 3465:                   '<p>'.&mt('No changes made to user information').'</p>');
 3466:     }
 3467:     return;
 3468: }
 3469: 
 3470: sub tool_changes {
 3471:     my ($context,$usertools,$oldaccess,$oldaccesstext,$userenv,$changeHash,
 3472:         $changed,$newaccess,$newaccesstext) = @_;
 3473:     if (!((ref($usertools) eq 'ARRAY') && (ref($oldaccess) eq 'HASH') &&
 3474:           (ref($oldaccesstext) eq 'HASH') && (ref($userenv) eq 'HASH') &&
 3475:           (ref($changeHash) eq 'HASH') && (ref($changed) eq 'HASH') &&
 3476:           (ref($newaccess) eq 'HASH') && (ref($newaccesstext) eq 'HASH'))) {
 3477:         return;
 3478:     }
 3479:     my %reqdisplay = &requestchange_display();
 3480:     if ($context eq 'reqcrsotherdom') {
 3481:         my @options = ('approval','validate','autolimit');
 3482:         my $optregex = join('|',@options);
 3483:         my $cdom = $env{'request.role.domain'};
 3484:         foreach my $tool (@{$usertools}) {
 3485:             $oldaccesstext->{$tool} = &mt("availability set to 'off'");
 3486:             $newaccesstext->{$tool} = $oldaccesstext->{$tool};
 3487:             $changeHash->{$context.'.'.$tool} = $userenv->{$context.'.'.$tool};
 3488:             my ($newop,$limit);
 3489:             if ($env{'form.'.$context.'_'.$tool}) {
 3490:                 $newop = $env{'form.'.$context.'_'.$tool};
 3491:                 if ($newop eq 'autolimit') {
 3492:                     $limit = $env{'form.'.$context.'_'.$tool.'_limit'};
 3493:                     $limit =~ s/\D+//g;
 3494:                     $newop .= '='.$limit;
 3495:                 }
 3496:             }
 3497:             if ($userenv->{$context.'.'.$tool} eq '') {
 3498:                 if ($newop) {
 3499:                     $changed->{$tool}=&tool_admin($tool,$cdom.':'.$newop,
 3500:                                                   $changeHash,$context);
 3501:                     if ($changed->{$tool}) {
 3502:                         if ($newop =~ /^autolimit/) {
 3503:                             if ($limit) {
 3504:                                 $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3505:                             } else {
 3506:                                 $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3507:                             }
 3508:                         } else {
 3509:                             $newaccesstext->{$tool} = $reqdisplay{$newop};
 3510:                         }
 3511:                     } else {
 3512:                         $newaccesstext->{$tool} = $oldaccesstext->{$tool};
 3513:                     }
 3514:                 }
 3515:             } else {
 3516:                 my @curr = split(',',$userenv->{$context.'.'.$tool});
 3517:                 my @new;
 3518:                 my $changedoms;
 3519:                 foreach my $req (@curr) {
 3520:                     if ($req =~ /^\Q$cdom\E\:($optregex\=?\d*)$/) {
 3521:                         my $oldop = $1;
 3522:                         if ($oldop =~ /^autolimit=(\d*)/) {
 3523:                             my $limit = $1;
 3524:                             if ($limit) {
 3525:                                 $oldaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3526:                             } else {
 3527:                                 $oldaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3528:                             }
 3529:                         } else {
 3530:                             $oldaccesstext->{$tool} = $reqdisplay{$oldop};
 3531:                         }
 3532:                         if ($oldop ne $newop) {
 3533:                             $changedoms = 1;
 3534:                             foreach my $item (@curr) {
 3535:                                 my ($reqdom,$option) = split(':',$item);
 3536:                                 unless ($reqdom eq $cdom) {
 3537:                                     push(@new,$item);
 3538:                                 }
 3539:                             }
 3540:                             if ($newop) {
 3541:                                 push(@new,$cdom.':'.$newop);
 3542:                             }
 3543:                             @new = sort(@new);
 3544:                         }
 3545:                         last;
 3546:                     }
 3547:                 }
 3548:                 if ((!$changedoms) && ($newop)) {
 3549:                     $changedoms = 1;
 3550:                     @new = sort(@curr,$cdom.':'.$newop);
 3551:                 }
 3552:                 if ($changedoms) {
 3553:                     my $newdomstr;
 3554:                     if (@new) {
 3555:                         $newdomstr = join(',',@new);
 3556:                     }
 3557:                     $changed->{$tool}=&tool_admin($tool,$newdomstr,$changeHash,
 3558:                                                   $context);
 3559:                     if ($changed->{$tool}) {
 3560:                         if ($env{'form.'.$context.'_'.$tool}) {
 3561:                             if ($env{'form.'.$context.'_'.$tool} eq 'autolimit') {
 3562:                                 my $limit = $env{'form.'.$context.'_'.$tool.'_limit'};
 3563:                                 $limit =~ s/\D+//g;
 3564:                                 if ($limit) {
 3565:                                     $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3566:                                 } else {
 3567:                                     $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3568:                                 }
 3569:                             } else {
 3570:                                 $newaccesstext->{$tool} = $reqdisplay{$env{'form.'.$context.'_'.$tool}};
 3571:                             }
 3572:                         } else {
 3573:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3574:                         }
 3575:                     }
 3576:                 }
 3577:             }
 3578:         }
 3579:         return;
 3580:     }
 3581:     foreach my $tool (@{$usertools}) {
 3582:         my ($newval,$limit,$envkey);
 3583:         $envkey = $context.'.'.$tool;
 3584:         if ($context eq 'requestcourses') {
 3585:             $newval = $env{'form.crsreq_'.$tool};
 3586:             if ($newval eq 'autolimit') {
 3587:                 $limit = $env{'form.crsreq_'.$tool.'_limit'};
 3588:                 $limit =~ s/\D+//g;
 3589:                 $newval .= '='.$limit;
 3590:             }
 3591:         } elsif ($context eq 'requestauthor') {
 3592:             $newval = $env{'form.'.$context};
 3593:             $envkey = $context;
 3594:         } else {
 3595:             $newval = $env{'form.'.$context.'_'.$tool};
 3596:         }
 3597:         if ($userenv->{$envkey} ne '') {
 3598:             $oldaccess->{$tool} = &mt('custom');
 3599:             if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 3600:                 if ($userenv->{$envkey} =~ /^autolimit=(\d*)$/) {
 3601:                     my $currlimit = $1;
 3602:                     if ($currlimit eq '') {
 3603:                         $oldaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3604:                     } else {
 3605:                         $oldaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$currlimit);
 3606:                     }
 3607:                 } elsif ($userenv->{$envkey}) {
 3608:                     $oldaccesstext->{$tool} = $reqdisplay{$userenv->{$envkey}};
 3609:                 } else {
 3610:                     $oldaccesstext->{$tool} = &mt("availability set to 'off'");
 3611:                 }
 3612:             } else {
 3613:                 if ($userenv->{$envkey}) {
 3614:                     $oldaccesstext->{$tool} = &mt("availability set to 'on'");
 3615:                 } else {
 3616:                     $oldaccesstext->{$tool} = &mt("availability set to 'off'");
 3617:                 }
 3618:             }
 3619:             $changeHash->{$envkey} = $userenv->{$envkey};
 3620:             if ($env{'form.custom'.$tool} == 1) {
 3621:                 if ($newval ne $userenv->{$envkey}) {
 3622:                     $changed->{$tool} = &tool_admin($tool,$newval,$changeHash,
 3623:                                                     $context);
 3624:                     if ($changed->{$tool}) {
 3625:                         $newaccess->{$tool} = &mt('custom');
 3626:                         if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 3627:                             if ($newval =~ /^autolimit/) {
 3628:                                 if ($limit) {
 3629:                                     $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3630:                                 } else {
 3631:                                     $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3632:                                 }
 3633:                             } elsif ($newval) {
 3634:                                 $newaccesstext->{$tool} = $reqdisplay{$newval};
 3635:                             } else {
 3636:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3637:                             }
 3638:                         } else {
 3639:                             if ($newval) {
 3640:                                 $newaccesstext->{$tool} = &mt("availability set to 'on'");
 3641:                             } else {
 3642:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3643:                             }
 3644:                         }
 3645:                     } else {
 3646:                         $newaccess->{$tool} = $oldaccess->{$tool};
 3647:                         if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 3648:                             if ($newval =~ /^autolimit/) {
 3649:                                 if ($limit) {
 3650:                                     $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3651:                                 } else {
 3652:                                     $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3653:                                 }
 3654:                             } elsif ($newval) {
 3655:                                 $newaccesstext->{$tool} = $reqdisplay{$newval};
 3656:                             } else {
 3657:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3658:                             }
 3659:                         } else {
 3660:                             if ($userenv->{$context.'.'.$tool}) {
 3661:                                 $newaccesstext->{$tool} = &mt("availability set to 'on'");
 3662:                             } else {
 3663:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3664:                             }
 3665:                         }
 3666:                     }
 3667:                 } else {
 3668:                     $newaccess->{$tool} = $oldaccess->{$tool};
 3669:                     $newaccesstext->{$tool} = $oldaccesstext->{$tool};
 3670:                 }
 3671:             } else {
 3672:                 $changed->{$tool} = &tool_admin($tool,'',$changeHash,$context);
 3673:                 if ($changed->{$tool}) {
 3674:                     $newaccess->{$tool} = &mt('default');
 3675:                 } else {
 3676:                     $newaccess->{$tool} = $oldaccess->{$tool};
 3677:                     if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 3678:                         if ($newval =~ /^autolimit/) {
 3679:                             if ($limit) {
 3680:                                 $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3681:                             } else {
 3682:                                 $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3683:                             }
 3684:                         } elsif ($newval) {
 3685:                             $newaccesstext->{$tool} = $reqdisplay{$newval};
 3686:                         } else {
 3687:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3688:                         }
 3689:                     } else {
 3690:                         if ($userenv->{$context.'.'.$tool}) {
 3691:                             $newaccesstext->{$tool} = &mt("availability set to 'on'");
 3692:                         } else {
 3693:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3694:                         }
 3695:                     }
 3696:                 }
 3697:             }
 3698:         } else {
 3699:             $oldaccess->{$tool} = &mt('default');
 3700:             if ($env{'form.custom'.$tool} == 1) {
 3701:                 $changed->{$tool} = &tool_admin($tool,$newval,$changeHash,
 3702:                                                 $context);
 3703:                 if ($changed->{$tool}) {
 3704:                     $newaccess->{$tool} = &mt('custom');
 3705:                     if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 3706:                         if ($newval =~ /^autolimit/) {
 3707:                             if ($limit) {
 3708:                                 $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3709:                             } else {
 3710:                                 $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3711:                             }
 3712:                         } elsif ($newval) {
 3713:                             $newaccesstext->{$tool} = $reqdisplay{$newval};
 3714:                         } else {
 3715:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3716:                         }
 3717:                     } else {
 3718:                         if ($newval) {
 3719:                             $newaccesstext->{$tool} = &mt("availability set to 'on'");
 3720:                         } else {
 3721:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3722:                         }
 3723:                     }
 3724:                 } else {
 3725:                     $newaccess->{$tool} = $oldaccess->{$tool};
 3726:                 }
 3727:             } else {
 3728:                 $newaccess->{$tool} = $oldaccess->{$tool};
 3729:             }
 3730:         }
 3731:     }
 3732:     return;
 3733: }
 3734: 
 3735: sub adhocrole_changes {
 3736:     my ($changehashref,$userenv) = @_;
 3737:     my @adds = &Apache::loncommon::get_env_multiple('form.adhocroleadd');
 3738:     my @dels = &Apache::loncommon::get_env_multiple('form.adhocroledel');
 3739:     my (@saved,@added,@alladhoc,$changed);
 3740:     my $adhoc_key = 'adhocroles.'.$env{'request.role.domain'};
 3741:     if (!$env{'form.makeuser'}) {
 3742:         if (ref($userenv) eq 'HASH') {
 3743:             my @current;
 3744:             if ($userenv->{$adhoc_key}) {
 3745:                 @current = split(/,/,$userenv->{$adhoc_key});
 3746:                 if (@dels) {
 3747:                     foreach my $curr (@current) {
 3748:                         next if ($curr eq ''); 
 3749:                         unless (grep(/\Q$curr\E$/,@dels)) {
 3750:                             push(@saved,$curr);
 3751:                         }
 3752:                     }
 3753:                     $changed = 1;
 3754:                 } else {
 3755:                     @saved = @current;
 3756:                 }
 3757:             }
 3758:         }
 3759:     }
 3760:     if (@adds) {
 3761:         my $confname = &Apache::lonnet::get_domainconfiguser($env{'request.role.domain'});
 3762:         my %existing=&Apache::lonnet::dump('roles',$env{'request.role.domain'},
 3763:                                            $confname,'rolesdef_');
 3764:         foreach my $poss (@adds) {
 3765:             if (exists($existing{'rolesdef_'.$poss})) {
 3766:                 push(@added,$poss);
 3767:                 $changed = 1;
 3768:             }
 3769:         }
 3770:     }
 3771:     if (@added) {
 3772:         if (@saved) {
 3773:             foreach my $add (@added) {
 3774:                 unless (grep(/^\Q$add\E$/,@saved)) {
 3775:                     push(@alladhoc,$add);
 3776:                 }
 3777:             }
 3778:         } else {
 3779:             push(@alladhoc,@added);
 3780:         }
 3781:     }
 3782:     if (@saved) {
 3783:         push(@alladhoc,@saved);
 3784:     }
 3785:     if (@alladhoc) {
 3786:         my $adhocstr = join(',',sort(@alladhoc)); 
 3787:         $changehashref->{$adhoc_key} = $adhocstr;
 3788:     } elsif (@dels) {
 3789:         &Apache::lonnet::del('environment',[$adhoc_key],$env{'form.ccdomain'},$env{'form.ccuname'});
 3790:         delete($changehashref->{$adhoc_key});
 3791:         if (($env{'form.ccdomain'} eq $env{'user.domain'}) &&
 3792:             ($env{'form.ccuname'} eq $env{'user.name'})) {
 3793:             &Apache::lonnet::delenv($adhoc_key);
 3794:         }
 3795:     }
 3796:     return $changed;
 3797: }
 3798: 
 3799: sub update_roles {
 3800:     my ($r,$context,$showcredits) = @_;
 3801:     my $now=time;
 3802:     my @rolechanges;
 3803:     my %disallowed;
 3804:     $r->print('<h3>'.&mt('Modifying Roles').'</h3>');
 3805:     foreach my $key (keys(%env)) {
 3806: 	next if (! $env{$key});
 3807:         next if ($key eq 'form.action');
 3808: 	# Revoke roles
 3809: 	if ($key=~/^form\.rev/) {
 3810: 	    if ($key=~/^form\.rev\:([^\_]+)\_([^\_\.]+)$/) {
 3811: # Revoke standard role
 3812: 		my ($scope,$role) = ($1,$2);
 3813: 		my $result =
 3814: 		    &Apache::lonnet::revokerole($env{'form.ccdomain'},
 3815: 						$env{'form.ccuname'},
 3816: 						$scope,$role,'','',$context);
 3817:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
 3818:                             &mt('Revoking [_1] in [_2]',
 3819:                                 &Apache::lonnet::plaintext($role),
 3820:                                 &Apache::loncommon::show_role_extent($scope,$context,$role)),
 3821:                                 $result ne "ok").'<br />');
 3822:                 if ($result ne "ok") {
 3823:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 3824:                 }
 3825: 		if ($role eq 'st') {
 3826: 		    my $result = 
 3827:                         &Apache::lonuserutils::classlist_drop($scope,
 3828:                             $env{'form.ccuname'},$env{'form.ccdomain'},
 3829: 			    $now);
 3830:                     $r->print(&Apache::lonhtmlcommon::confirm_success($result));
 3831: 		}
 3832:                 if (!grep(/^\Q$role\E$/,@rolechanges)) {
 3833:                     push(@rolechanges,$role);
 3834:                 }
 3835: 	    }
 3836: 	    if ($key=~m{^form\.rev\:([^_]+)_cr\.cr/($match_domain)/($match_username)/(\w+)$}s) {
 3837: # Revoke custom role
 3838:                 my $result = &Apache::lonnet::revokecustomrole(
 3839:                     $env{'form.ccdomain'},$env{'form.ccuname'},$1,$2,$3,$4,'','',$context);
 3840:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
 3841:                             &mt('Revoking custom role [_1] by [_2] in [_3]',
 3842:                                 $4,$3.':'.$2,&Apache::loncommon::show_role_extent($1,$context,'cr')),
 3843:                             $result ne 'ok').'<br />');
 3844:                 if ($result ne "ok") {
 3845:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 3846:                 }
 3847:                 if (!grep(/^cr$/,@rolechanges)) {
 3848:                     push(@rolechanges,'cr');
 3849:                 }
 3850: 	    }
 3851: 	} elsif ($key=~/^form\.del/) {
 3852: 	    if ($key=~/^form\.del\:([^\_]+)\_([^\_\.]+)$/) {
 3853: # Delete standard role
 3854: 		my ($scope,$role) = ($1,$2);
 3855: 		my $result =
 3856: 		    &Apache::lonnet::assignrole($env{'form.ccdomain'},
 3857: 						$env{'form.ccuname'},
 3858: 						$scope,$role,$now,0,1,'',
 3859:                                                 $context);
 3860:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
 3861:                             &mt('Deleting [_1] in [_2]',
 3862:                                 &Apache::lonnet::plaintext($role),
 3863:                                 &Apache::loncommon::show_role_extent($scope,$context,$role)),
 3864:                             $result ne 'ok').'<br />');
 3865:                 if ($result ne "ok") {
 3866:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 3867:                 }
 3868: 
 3869: 		if ($role eq 'st') {
 3870: 		    my $result = 
 3871:                         &Apache::lonuserutils::classlist_drop($scope,
 3872:                             $env{'form.ccuname'},$env{'form.ccdomain'},
 3873: 			    $now);
 3874: 		    $r->print(&Apache::lonhtmlcommon::confirm_success($result));
 3875: 		}
 3876:                 if (!grep(/^\Q$role\E$/,@rolechanges)) {
 3877:                     push(@rolechanges,$role);
 3878:                 }
 3879:             }
 3880: 	    if ($key=~m{^form\.del\:([^_]+)_cr\.cr/($match_domain)/($match_username)/(\w+)$}) {
 3881:                 my ($url,$rdom,$rnam,$rolename) = ($1,$2,$3,$4);
 3882: # Delete custom role
 3883:                 my $result =
 3884:                     &Apache::lonnet::assigncustomrole($env{'form.ccdomain'},
 3885:                         $env{'form.ccuname'},$url,$rdom,$rnam,$rolename,$now,
 3886:                         0,1,$context);
 3887:                 $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('Deleting custom role [_1] by [_2] in [_3]',
 3888:                       $rolename,$rnam.':'.$rdom,&Apache::loncommon::show_role_extent($1,$context,'cr')),
 3889:                       $result ne "ok").'<br />');
 3890:                 if ($result ne "ok") {
 3891:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 3892:                 }
 3893: 
 3894:                 if (!grep(/^cr$/,@rolechanges)) {
 3895:                     push(@rolechanges,'cr');
 3896:                 }
 3897:             }
 3898: 	} elsif ($key=~/^form\.ren/) {
 3899:             my $udom = $env{'form.ccdomain'};
 3900:             my $uname = $env{'form.ccuname'};
 3901: # Re-enable standard role
 3902: 	    if ($key=~/^form\.ren\:([^\_]+)\_([^\_\.]+)$/) {
 3903:                 my $url = $1;
 3904:                 my $role = $2;
 3905:                 my $logmsg;
 3906:                 my $output;
 3907:                 if ($role eq 'st') {
 3908:                     if ($url =~ m-^/($match_domain)/($match_courseid)/?(\w*)$-) {
 3909:                         my ($cdom,$cnum,$csec) = ($1,$2,$3);
 3910:                         my $credits;
 3911:                         if ($showcredits) {
 3912:                             my $defaultcredits = 
 3913:                                 &Apache::lonuserutils::get_defaultcredits($cdom,$cnum);
 3914:                             $credits = &get_user_credits($defaultcredits,$cdom,$cnum);
 3915:                         }
 3916:                         my $result = &Apache::loncommon::commit_studentrole(\$logmsg,$udom,$uname,$url,$role,$now,0,$cdom,$cnum,$csec,$context,$credits);
 3917:                         if (($result =~ /^error/) || ($result eq 'not_in_class') || ($result eq 'unknown_course') || ($result eq 'refused')) {
 3918:                             if ($result eq 'refused' && $logmsg) {
 3919:                                 $output = $logmsg;
 3920:                             } else { 
 3921:                                 $output = &mt('Error: [_1]',$result)."\n";
 3922:                             }
 3923:                         } else {
 3924:                             $output = &Apache::lonhtmlcommon::confirm_success(&mt('Assigning [_1] in [_2] starting [_3]',
 3925:                                         &Apache::lonnet::plaintext($role),
 3926:                                         &Apache::loncommon::show_role_extent($url,$context,'st'),
 3927:                                         &Apache::lonlocal::locallocaltime($now))).'<br />'.$logmsg.'<br />';
 3928:                         }
 3929:                     }
 3930:                 } else {
 3931: 		    my $result=&Apache::lonnet::assignrole($env{'form.ccdomain'},
 3932:                                $env{'form.ccuname'},$url,$role,0,$now,'','',
 3933:                                $context);
 3934:                         $output = &Apache::lonhtmlcommon::confirm_success(&mt('Re-enabling [_1] in [_2]',
 3935:                                         &Apache::lonnet::plaintext($role),
 3936:                                         &Apache::loncommon::show_role_extent($url,$context,$role)),$result ne "ok").'<br />';
 3937:                     if ($result ne "ok") {
 3938:                         $output .= &mt('Error: [_1]',$result).'<br />';
 3939:                     }
 3940:                 }
 3941:                 $r->print($output);
 3942:                 if (!grep(/^\Q$role\E$/,@rolechanges)) {
 3943:                     push(@rolechanges,$role);
 3944:                 }
 3945: 	    }
 3946: # Re-enable custom role
 3947: 	    if ($key=~m{^form\.ren\:([^_]+)_cr\.cr/($match_domain)/($match_username)/(\w+)$}) {
 3948:                 my ($url,$rdom,$rnam,$rolename) = ($1,$2,$3,$4);
 3949:                 my $result = &Apache::lonnet::assigncustomrole(
 3950:                                $env{'form.ccdomain'}, $env{'form.ccuname'},
 3951:                                $url,$rdom,$rnam,$rolename,0,$now,undef,$context);
 3952:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
 3953:                     &mt('Re-enabling custom role [_1] by [_2] in [_3]',
 3954:                         $rolename,$rnam.':'.$rdom,&Apache::loncommon::show_role_extent($1,$context,'cr')),
 3955:                     $result ne "ok").'<br />');
 3956:                 if ($result ne "ok") {
 3957:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 3958:                 }
 3959:                 if (!grep(/^cr$/,@rolechanges)) {
 3960:                     push(@rolechanges,'cr');
 3961:                 }
 3962:             }
 3963: 	} elsif ($key=~/^form\.act/) {
 3964:             my $udom = $env{'form.ccdomain'};
 3965:             my $uname = $env{'form.ccuname'};
 3966: 	    if ($key=~/^form\.act\_($match_domain)\_($match_courseid)\_cr_cr_($match_domain)_($match_username)_([^\_]+)$/) {
 3967:                 # Activate a custom role
 3968: 		my ($one,$two,$three,$four,$five)=($1,$2,$3,$4,$5);
 3969: 		my $url='/'.$one.'/'.$two;
 3970: 		my $full=$one.'_'.$two.'_cr_cr_'.$three.'_'.$four.'_'.$five;
 3971: 
 3972:                 my $start = ( $env{'form.start_'.$full} ?
 3973:                               $env{'form.start_'.$full} :
 3974:                               $now );
 3975:                 my $end   = ( $env{'form.end_'.$full} ?
 3976:                               $env{'form.end_'.$full} :
 3977:                               0 );
 3978:                                                                                      
 3979:                 # split multiple sections
 3980:                 my %sections = ();
 3981:                 my $num_sections = &build_roles($env{'form.sec_'.$full},\%sections,$5);
 3982:                 if ($num_sections == 0) {
 3983:                     $r->print(&Apache::loncommon::commit_customrole($udom,$uname,$url,$three,$four,$five,$start,$end,$context));
 3984:                 } else {
 3985: 		    my %curr_groups =
 3986: 			&Apache::longroup::coursegroups($one,$two);
 3987:                     foreach my $sec (sort {$a cmp $b} keys(%sections)) {
 3988:                         if (($sec eq 'none') || ($sec eq 'all') || 
 3989:                             exists($curr_groups{$sec})) {
 3990:                             $disallowed{$sec} = $url;
 3991:                             next;
 3992:                         }
 3993:                         my $securl = $url.'/'.$sec;
 3994: 		        $r->print(&Apache::loncommon::commit_customrole($udom,$uname,$securl,$three,$four,$five,$start,$end,$context));
 3995:                     }
 3996:                 }
 3997:                 if (!grep(/^cr$/,@rolechanges)) {
 3998:                     push(@rolechanges,'cr');
 3999:                 }
 4000: 	    } elsif ($key=~/^form\.act\_($match_domain)\_($match_name)\_([^\_]+)$/) {
 4001: 		# Activate roles for sections with 3 id numbers
 4002: 		# set start, end times, and the url for the class
 4003: 		my ($one,$two,$three)=($1,$2,$3);
 4004: 		my $start = ( $env{'form.start_'.$one.'_'.$two.'_'.$three} ? 
 4005: 			      $env{'form.start_'.$one.'_'.$two.'_'.$three} : 
 4006: 			      $now );
 4007: 		my $end   = ( $env{'form.end_'.$one.'_'.$two.'_'.$three} ? 
 4008: 			      $env{'form.end_'.$one.'_'.$two.'_'.$three} :
 4009: 			      0 );
 4010: 		my $url='/'.$one.'/'.$two;
 4011:                 my $type = 'three';
 4012:                 # split multiple sections
 4013:                 my %sections = ();
 4014:                 my $num_sections = &build_roles($env{'form.sec_'.$one.'_'.$two.'_'.$three},\%sections,$three);
 4015:                 my $credits;
 4016:                 if ($three eq 'st') {
 4017:                     if ($showcredits) { 
 4018:                         my $defaultcredits = 
 4019:                             &Apache::lonuserutils::get_defaultcredits($one,$two);
 4020:                         $credits = $env{'form.credits_'.$one.'_'.$two.'_'.$three};
 4021:                         $credits =~ s/[^\d\.]//g;
 4022:                         if ($credits eq $defaultcredits) {
 4023:                             undef($credits);
 4024:                         }
 4025:                     }
 4026:                 }
 4027:                 if ($num_sections == 0) {
 4028:                     $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$three,$start,$end,$one,$two,'',$context,$credits));
 4029:                 } else {
 4030:                     my %curr_groups = 
 4031: 			&Apache::longroup::coursegroups($one,$two);
 4032:                     my $emptysec = 0;
 4033:                     foreach my $sec (sort {$a cmp $b} keys(%sections)) {
 4034:                         $sec =~ s/\W//g;
 4035:                         if ($sec ne '') {
 4036:                             if (($sec eq 'none') || ($sec eq 'all') || 
 4037:                                 exists($curr_groups{$sec})) {
 4038:                                 $disallowed{$sec} = $url;
 4039:                                 next;
 4040:                             }
 4041:                             my $securl = $url.'/'.$sec;
 4042:                             $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$securl,$three,$start,$end,$one,$two,$sec,$context,$credits));
 4043:                         } else {
 4044:                             $emptysec = 1;
 4045:                         }
 4046:                     }
 4047:                     if ($emptysec) {
 4048:                         $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$three,$start,$end,$one,$two,'',$context,$credits));
 4049:                     }
 4050:                 }
 4051:                 if (!grep(/^\Q$three\E$/,@rolechanges)) {
 4052:                     push(@rolechanges,$three);
 4053:                 }
 4054: 	    } elsif ($key=~/^form\.act\_([^\_]+)\_([^\_]+)$/) {
 4055: 		# Activate roles for sections with two id numbers
 4056: 		# set start, end times, and the url for the class
 4057: 		my $start = ( $env{'form.start_'.$1.'_'.$2} ? 
 4058: 			      $env{'form.start_'.$1.'_'.$2} : 
 4059: 			      $now );
 4060: 		my $end   = ( $env{'form.end_'.$1.'_'.$2} ? 
 4061: 			      $env{'form.end_'.$1.'_'.$2} :
 4062: 			      0 );
 4063:                 my $one = $1;
 4064:                 my $two = $2;
 4065: 		my $url='/'.$one.'/';
 4066:                 # split multiple sections
 4067:                 my %sections = ();
 4068:                 my $num_sections = &build_roles($env{'form.sec_'.$one.'_'.$two},\%sections,$two);
 4069:                 if ($num_sections == 0) {
 4070:                     $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$two,$start,$end,$one,undef,'',$context));
 4071:                 } else {
 4072:                     my $emptysec = 0;
 4073:                     foreach my $sec (sort {$a cmp $b} keys(%sections)) {
 4074:                         if ($sec ne '') {
 4075:                             my $securl = $url.'/'.$sec;
 4076:                             $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$securl,$two,$start,$end,$one,undef,$sec,$context));
 4077:                         } else {
 4078:                             $emptysec = 1;
 4079:                         }
 4080:                     }
 4081:                     if ($emptysec) {
 4082:                         $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$two,$start,$end,$one,undef,'',$context));
 4083:                     }
 4084:                 }
 4085:                 if (!grep(/^\Q$two\E$/,@rolechanges)) {
 4086:                     push(@rolechanges,$two);
 4087:                 }
 4088: 	    } else {
 4089: 		$r->print('<p><span class="LC_error">'.&mt('ERROR').': '.&mt('Unknown command').' <tt>'.$key.'</tt></span></p><br />');
 4090:             }
 4091:             foreach my $key (sort(keys(%disallowed))) {
 4092:                 $r->print('<p class="LC_warning">');
 4093:                 if (($key eq 'none') || ($key eq 'all')) {  
 4094:                     $r->print(&mt('[_1] may not be used as the name for a section, as it is a reserved word.','<tt>'.$key.'</tt>'));
 4095:                 } else {
 4096:                     $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>'));
 4097:                 }
 4098:                 $r->print('</p><p>'
 4099:                          .&mt('Please [_1]go back[_2] and choose a different section name.'
 4100:                              ,'<a href="javascript:history.go(-1)'
 4101:                              ,'</a>')
 4102:                          .'</p><br />'
 4103:                 );
 4104:             }
 4105: 	}
 4106:     } # End of foreach (keys(%env))
 4107: # Flush the course logs so reverse user roles immediately updated
 4108:     $r->register_cleanup(\&Apache::lonnet::flushcourselogs);
 4109:     if (@rolechanges == 0) {
 4110:         $r->print('<p>'.&mt('No roles to modify').'</p>');
 4111:     }
 4112:     return @rolechanges;
 4113: }
 4114: 
 4115: sub get_user_credits {
 4116:     my ($uname,$udom,$defaultcredits,$cdom,$cnum) = @_;
 4117:     if ($cdom eq '' || $cnum eq '') {
 4118:         return unless ($env{'request.course.id'});
 4119:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4120:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4121:     }
 4122:     my $credits;
 4123:     my %currhash =
 4124:         &Apache::lonnet::get('classlist',[$uname.':'.$udom],$cdom,$cnum);
 4125:     if (keys(%currhash) > 0) {
 4126:         my @items = split(/:/,$currhash{$uname.':'.$udom});
 4127:         my $crdidx = &Apache::loncoursedata::CL_CREDITS() - 3;
 4128:         $credits = $items[$crdidx];
 4129:         $credits =~ s/[^\d\.]//g;
 4130:     }
 4131:     if ($credits eq $defaultcredits) {
 4132:         undef($credits);
 4133:     }
 4134:     return $credits;
 4135: }
 4136: 
 4137: sub enroll_single_student {
 4138:     my ($r,$uhome,$amode,$genpwd,$now,$newuser,$context,$crstype,
 4139:         $showcredits,$defaultcredits) = @_;
 4140:     $r->print('<h3>');
 4141:     if ($crstype eq 'Community') {
 4142:         $r->print(&mt('Enrolling Member'));
 4143:     } else {
 4144:         $r->print(&mt('Enrolling Student'));
 4145:     }
 4146:     $r->print('</h3>');
 4147: 
 4148:     # Remove non alphanumeric values from section
 4149:     $env{'form.sections'}=~s/\W//g;
 4150: 
 4151:     my $credits;
 4152:     if (($showcredits) && ($env{'form.credits'} ne '')) {
 4153:         $credits = $env{'form.credits'};
 4154:         $credits =~ s/[^\d\.]//g;
 4155:         if ($credits ne '') {
 4156:             if ($credits eq $defaultcredits) {
 4157:                 undef($credits);
 4158:             }
 4159:         }
 4160:     }
 4161: 
 4162:     # Clean out any old student roles the user has in this class.
 4163:     &Apache::lonuserutils::modifystudent($env{'form.ccdomain'},
 4164:          $env{'form.ccuname'},$env{'request.course.id'},undef,$uhome);
 4165:     my ($startdate,$enddate) = &Apache::lonuserutils::get_dates_from_form();
 4166:     my $enroll_result =
 4167:         &Apache::lonnet::modify_student_enrollment($env{'form.ccdomain'},
 4168:             $env{'form.ccuname'},$env{'form.cid'},$env{'form.cfirstname'},
 4169:             $env{'form.cmiddlename'},$env{'form.clastname'},
 4170:             $env{'form.generation'},$env{'form.sections'},$enddate,
 4171:             $startdate,'manual',undef,$env{'request.course.id'},'',$context,
 4172:             $credits);
 4173:     if ($enroll_result =~ /^ok/) {
 4174:         $r->print(&mt('[_1] enrolled','<b>'.$env{'form.ccuname'}.':'.$env{'form.ccdomain'}.'</b>'));
 4175:         if ($env{'form.sections'} ne '') {
 4176:             $r->print(' '.&mt('in section [_1]',$env{'form.sections'}));
 4177:         }
 4178:         my ($showstart,$showend);
 4179:         if ($startdate <= $now) {
 4180:             $showstart = &mt('Access starts immediately');
 4181:         } else {
 4182:             $showstart = &mt('Access starts: ').&Apache::lonlocal::locallocaltime($startdate);
 4183:         }
 4184:         if ($enddate == 0) {
 4185:             $showend = &mt('ends: no ending date');
 4186:         } else {
 4187:             $showend = &mt('ends: ').&Apache::lonlocal::locallocaltime($enddate);
 4188:         }
 4189:         $r->print('.<br />'.$showstart.'; '.$showend);
 4190:         if ($startdate <= $now && !$newuser) {
 4191:             $r->print('<p class="LC_info">');
 4192:             if ($crstype eq 'Community') {
 4193:                 $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.'));
 4194:             } else {
 4195:                 $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.'));
 4196:            }
 4197:            $r->print('</p>');
 4198:         }
 4199:     } else {
 4200:         $r->print(&mt('unable to enroll').": ".$enroll_result);
 4201:     }
 4202:     return;
 4203: }
 4204: 
 4205: sub get_defaultquota_text {
 4206:     my ($settingstatus) = @_;
 4207:     my $defquotatext; 
 4208:     if ($settingstatus eq '') {
 4209:         $defquotatext = &mt('default');
 4210:     } else {
 4211:         my ($usertypes,$order) =
 4212:             &Apache::lonnet::retrieve_inst_usertypes($env{'form.ccdomain'});
 4213:         if ($usertypes->{$settingstatus} eq '') {
 4214:             $defquotatext = &mt('default');
 4215:         } else {
 4216:             $defquotatext = &mt('default for [_1]',$usertypes->{$settingstatus});
 4217:         }
 4218:     }
 4219:     return $defquotatext;
 4220: }
 4221: 
 4222: sub update_result_form {
 4223:     my ($uhome) = @_;
 4224:     my $outcome = 
 4225:     '<form name="userupdate" method="post" action="">'."\n";
 4226:     foreach my $item ('srchby','srchin','srchtype','srchterm','srchdomain','ccuname','ccdomain') {
 4227:         $outcome .= '<input type="hidden" name="'.$item.'" value="'.$env{'form.'.$item}.'" />'."\n";
 4228:     }
 4229:     if ($env{'form.origname'} ne '') {
 4230:         $outcome .= '<input type="hidden" name="origname" value="'.$env{'form.origname'}.'" />'."\n";
 4231:     }
 4232:     foreach my $item ('sortby','seluname','seludom') {
 4233:         if (exists($env{'form.'.$item})) {
 4234:             $outcome .= '<input type="hidden" name="'.$item.'" value="'.$env{'form.'.$item}.'" />'."\n";
 4235:         }
 4236:     }
 4237:     if ($uhome eq 'no_host') {
 4238:         $outcome .= '<input type="hidden" name="forcenewuser" value="1" />'."\n";
 4239:     }
 4240:     $outcome .= '<input type="hidden" name="phase" value="" />'."\n".
 4241:                 '<input type="hidden" name="currstate" value="" />'."\n".
 4242:                 '<input type="hidden" name="action" value="'.$env{'form.action'}.'" />'."\n".
 4243:                 '</form>';
 4244:     return $outcome;
 4245: }
 4246: 
 4247: sub quota_admin {
 4248:     my ($setquota,$changeHash,$name) = @_;
 4249:     my $quotachanged;
 4250:     if (&Apache::lonnet::allowed('mpq',$env{'form.ccdomain'})) {
 4251:         # Current user has quota modification privileges
 4252:         if (ref($changeHash) eq 'HASH') {
 4253:             $quotachanged = 1;
 4254:             $changeHash->{$name.'quota'} = $setquota;
 4255:         }
 4256:     }
 4257:     return $quotachanged;
 4258: }
 4259: 
 4260: sub tool_admin {
 4261:     my ($tool,$settool,$changeHash,$context) = @_;
 4262:     my $canchange = 0; 
 4263:     if ($context eq 'requestcourses') {
 4264:         if (&Apache::lonnet::allowed('ccc',$env{'form.ccdomain'})) {
 4265:             $canchange = 1;
 4266:         }
 4267:     } elsif ($context eq 'reqcrsotherdom') {
 4268:         if (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) {
 4269:             $canchange = 1;
 4270:         }
 4271:     } elsif ($context eq 'requestauthor') {
 4272:         if (&Apache::lonnet::allowed('cau',$env{'request.role.domain'})) {
 4273:             $canchange = 1;
 4274:         }
 4275:     } elsif (&Apache::lonnet::allowed('mut',$env{'form.ccdomain'})) {
 4276:         # Current user has quota modification privileges
 4277:         $canchange = 1;
 4278:     }
 4279:     my $toolchanged;
 4280:     if ($canchange) {
 4281:         if (ref($changeHash) eq 'HASH') {
 4282:             $toolchanged = 1;
 4283:             if ($tool eq 'requestauthor') {
 4284:                 $changeHash->{$context} = $settool;
 4285:             } else {
 4286:                 $changeHash->{$context.'.'.$tool} = $settool;
 4287:             }
 4288:         }
 4289:     }
 4290:     return $toolchanged;
 4291: }
 4292: 
 4293: sub build_roles {
 4294:     my ($sectionstr,$sections,$role) = @_;
 4295:     my $num_sections = 0;
 4296:     if ($sectionstr=~ /,/) {
 4297:         my @secnums = split/,/,$sectionstr;
 4298:         if ($role eq 'st') {
 4299:             $secnums[0] =~ s/\W//g;
 4300:             $$sections{$secnums[0]} = 1;
 4301:             $num_sections = 1;
 4302:         } else {
 4303:             foreach my $sec (@secnums) {
 4304:                 $sec =~ ~s/\W//g;
 4305:                 if (!($sec eq "")) {
 4306:                     if (exists($$sections{$sec})) {
 4307:                         $$sections{$sec} ++;
 4308:                     } else {
 4309:                         $$sections{$sec} = 1;
 4310:                         $num_sections ++;
 4311:                     }
 4312:                 }
 4313:             }
 4314:         }
 4315:     } else {
 4316:         $sectionstr=~s/\W//g;
 4317:         unless ($sectionstr eq '') {
 4318:             $$sections{$sectionstr} = 1;
 4319:             $num_sections ++;
 4320:         }
 4321:     }
 4322: 
 4323:     return $num_sections;
 4324: }
 4325: 
 4326: # ========================================================== Custom Role Editor
 4327: 
 4328: sub custom_role_editor {
 4329:     my ($r,$brcrum,$prefix) = @_;
 4330:     my $action = $env{'form.customroleaction'};
 4331:     my $rolename; 
 4332:     if ($action eq 'new') {
 4333:         $rolename=$env{'form.newrolename'};
 4334:     } else {
 4335:         $rolename=$env{'form.rolename'};
 4336:     }
 4337: 
 4338:     my ($crstype,$context);
 4339:     if ($env{'request.course.id'}) {
 4340:         $crstype = &Apache::loncommon::course_type();
 4341:         $context = 'course';
 4342:     } else {
 4343:         $context = 'domain';
 4344:         $crstype = 'course';
 4345:     }
 4346: 
 4347:     $rolename=~s/[^A-Za-z0-9]//gs;
 4348:     if (!$rolename || $env{'form.phase'} eq 'pickrole') {
 4349: 	&print_username_entry_form($r,undef,undef,undef,undef,$crstype,$brcrum);
 4350:         return;
 4351:     }
 4352: 
 4353:     my $formname = 'form1';
 4354:     my %privs=();
 4355:     my $body_top = '<h2>';
 4356: # ------------------------------------------------------- Does this role exist?
 4357:     my ($rdummy,$roledef)=
 4358: 			 &Apache::lonnet::get('roles',["rolesdef_$rolename"]);
 4359:     if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 4360:         $body_top .= &mt('Existing Role').' "';
 4361: # ------------------------------------------------- Get current role privileges
 4362:         ($privs{'system'},$privs{'domain'},$privs{'course'})=split(/\_/,$roledef);
 4363:         if ($privs{'system'} =~ /bre\&S/) {
 4364:             if ($context eq 'domain') {
 4365:                 $crstype = 'Course'; 
 4366:             } elsif ($crstype eq 'Community') {
 4367:                 $privs{'system'} =~ s/bre\&S//;
 4368:             }
 4369:         } elsif ($context eq 'domain') {
 4370:             $crstype = 'Course';
 4371:         }
 4372:     } else {
 4373:         $body_top .= &mt('New Role').' "';
 4374:         $roledef='';
 4375:     }
 4376:     $body_top .= $rolename.'"</h2>';
 4377: 
 4378: # ------------------------------------------------------- What can be assigned?
 4379:     my %full=();
 4380:     my %levels=( 
 4381:                  course => {},
 4382:                  domain => {},
 4383:                  system => {},
 4384:                );
 4385:     my %levelscurrent=(
 4386:                         course => {},
 4387:                         domain => {},
 4388:                         system => {},
 4389:                       );
 4390:     &Apache::lonuserutils::custom_role_privs(\%privs,\%full,\%levels,\%levelscurrent);
 4391:     my ($jsback,$elements) = &crumb_utilities();
 4392:     my @templateroles = &Apache::lonuserutils::custom_template_roles($context,$crstype);
 4393:     my $head_script = 
 4394:         &Apache::lonuserutils::custom_roledefs_js($context,$crstype,$formname,
 4395:                                                   \%full,\@templateroles,$jsback);
 4396:     push (@{$brcrum},
 4397:               {href => "javascript:backPage(document.$formname,'pickrole','')",
 4398:                text => "Pick custom role",
 4399:                faq  => 282,bug=>'Instructor Interface',},
 4400:               {href => "javascript:backPage(document.$formname,'','')",
 4401:                text => "Edit custom role",
 4402:                faq  => 282,
 4403:                bug  => 'Instructor Interface',
 4404:                help => 'Course_Editing_Custom_Roles'}
 4405:               );
 4406:     my $args = { bread_crumbs          => $brcrum,
 4407:                  bread_crumbs_component => 'User Management'};
 4408:  
 4409:     $r->print(&Apache::loncommon::start_page('Custom Role Editor',
 4410:                                              $head_script,$args).
 4411:               $body_top);
 4412:     $r->print('<form name="'.$formname.'" method="post" action="">'."\n".
 4413:               &Apache::lonuserutils::custom_role_header($context,$crstype,
 4414:                                                         \@templateroles,$prefix));
 4415: 
 4416:     $r->print(<<ENDCCF);
 4417: <input type="hidden" name="phase" value="set_custom_roles" />
 4418: <input type="hidden" name="rolename" value="$rolename" />
 4419: ENDCCF
 4420:     $r->print(&Apache::lonuserutils::custom_role_table($crstype,\%full,\%levels,
 4421:                                                        \%levelscurrent,$prefix));
 4422:     $r->print(&Apache::loncommon::end_data_table().
 4423:    '<input type="hidden" name="action" value="'.$env{'form.action'}.'" />'.
 4424:    '<input type="hidden" name="startrolename" value="'.$env{'form.rolename'}.
 4425:    '" />'."\n".'<input type="hidden" name="currstate" value="" />'."\n".   
 4426:    '<input type="reset" value="'.&mt("Reset").'" />'."\n".
 4427:    '<input type="submit" value="'.&mt('Save').'" /></form>');
 4428: }
 4429: 
 4430: # ---------------------------------------------------------- Call to definerole
 4431: sub set_custom_role {
 4432:     my ($r,$context,$brcrum,$prefix) = @_;
 4433:     my $rolename=$env{'form.rolename'};
 4434:     $rolename=~s/[^A-Za-z0-9]//gs;
 4435:     if (!$rolename) {
 4436: 	&custom_role_editor($r,$brcrum,$prefix);
 4437:         return;
 4438:     }
 4439:     my ($jsback,$elements) = &crumb_utilities();
 4440:     my $jscript = '<script type="text/javascript">'
 4441:                  .'// <![CDATA['."\n"
 4442:                  .$jsback."\n"
 4443:                  .'// ]]>'."\n"
 4444:                  .'</script>'."\n";
 4445:     push(@{$brcrum},
 4446:         {href => "javascript:backPage(document.customresult,'pickrole','')",
 4447:          text => "Pick custom role",
 4448:          faq  => 282,
 4449:          bug  => 'Instructor Interface',},
 4450:         {href => "javascript:backPage(document.customresult,'selected_custom_edit','')",
 4451:          text => "Edit custom role",
 4452:          faq  => 282,
 4453:          bug  => 'Instructor Interface',},
 4454:         {href => "javascript:backPage(document.customresult,'set_custom_roles','')",
 4455:          text => "Result",
 4456:          faq  => 282,
 4457:          bug  => 'Instructor Interface',
 4458:          help => 'Course_Editing_Custom_Roles'},
 4459:         );
 4460:     my $args = { bread_crumbs           => $brcrum,
 4461:                  bread_crumbs_component => 'User Management'};
 4462:     $r->print(&Apache::loncommon::start_page('Save Custom Role',$jscript,$args));
 4463: 
 4464:     my $newrole;
 4465:     my ($rdummy,$roledef)=
 4466: 	&Apache::lonnet::get('roles',["rolesdef_$rolename"]);
 4467: 
 4468: # ------------------------------------------------------- Does this role exist?
 4469:     $r->print('<h3>');
 4470:     if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 4471: 	$r->print(&mt('Existing Role').' "');
 4472:     } else {
 4473: 	$r->print(&mt('New Role').' "');
 4474: 	$roledef='';
 4475:         $newrole = 1;
 4476:     }
 4477:     $r->print($rolename.'"</h3>');
 4478: # ------------------------------------------------- Assign role and show result
 4479: 
 4480:     my $errmsg;
 4481:     my %newprivs = &Apache::lonuserutils::custom_role_update($rolename,$prefix);
 4482:     # Assign role and return result
 4483:     my $result = &Apache::lonnet::definerole($rolename,$newprivs{'s'},$newprivs{'d'},
 4484:                                              $newprivs{'c'});
 4485:     if ($result ne 'ok') {
 4486:         $errmsg = ': '.$result;
 4487:     }
 4488:     my $message =
 4489:         &Apache::lonhtmlcommon::confirm_success(
 4490:             &mt('Defining Role').$errmsg, ($result eq 'ok' ? 0 : 1));
 4491:     if ($env{'request.course.id'}) {
 4492:         my $url='/'.$env{'request.course.id'};
 4493:         $url=~s/\_/\//g;
 4494:         $result =
 4495:             &Apache::lonnet::assigncustomrole(
 4496:                 $env{'user.domain'},$env{'user.name'},
 4497:                 $url,
 4498:                 $env{'user.domain'},$env{'user.name'},
 4499:                 $rolename,undef,undef,undef,$context);
 4500:         if ($result ne 'ok') {
 4501:             $errmsg = ': '.$result;
 4502:         }
 4503:         $message .=
 4504:             '<br />'
 4505:            .&Apache::lonhtmlcommon::confirm_success(
 4506:                 &mt('Assigning Role to Self').$errmsg, ($result eq 'ok' ? 0 : 1));
 4507:     }
 4508:     $r->print(
 4509:         &Apache::loncommon::confirmwrapper($message)
 4510:        .'<br />'
 4511:        .&Apache::lonhtmlcommon::actionbox([
 4512:             '<a href="javascript:backPage(document.customresult,'."'pickrole'".')">'
 4513:            .&mt('Create or edit another custom role')
 4514:            .'</a>'])
 4515:        .'<form name="customresult" method="post" action="">'
 4516:        .&Apache::lonhtmlcommon::echo_form_input([])
 4517:        .'</form>'
 4518:     );
 4519: }
 4520: 
 4521: # ================================================================ Main Handler
 4522: sub handler {
 4523:     my $r = shift;
 4524:     if ($r->header_only) {
 4525:        &Apache::loncommon::content_type($r,'text/html');
 4526:        $r->send_http_header;
 4527:        return OK;
 4528:     }
 4529:     my ($context,$crstype);
 4530:     if ($env{'request.course.id'}) {
 4531:         $context = 'course';
 4532:         $crstype = &Apache::loncommon::course_type();
 4533:     } elsif ($env{'request.role'} =~ /^au\./) {
 4534:         $context = 'author';
 4535:     } else {
 4536:         $context = 'domain';
 4537:     }
 4538: 
 4539:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 4540:         ['action','state','callingform','roletype','showrole','bulkaction','popup','phase',
 4541:          'username','domain','srchterm','srchdomain','srchin','srchby','srchtype','queue']);
 4542:     &Apache::lonhtmlcommon::clear_breadcrumbs();
 4543:     my $args;
 4544:     my $brcrum = [];
 4545:     my $bread_crumbs_component = 'User Management';
 4546:     if (($env{'form.action'} ne 'dateselect') && ($env{'form.action'} ne 'displayuserreq')) {
 4547:         $brcrum = [{href=>"/adm/createuser",
 4548:                     text=>"User Management",
 4549:                     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'}
 4550:                   ];
 4551:     }
 4552:     #SD Following files not added to help, because the corresponding .tex-files seem to
 4553:     #be missing: Course_Approve_Selfenroll,Course_User_Logs,
 4554:     my ($permission,$allowed) = 
 4555:         &Apache::lonuserutils::get_permission($context,$crstype);
 4556:     if (!$allowed) {
 4557:         if ($context eq 'course') {
 4558:             $r->internal_redirect('/adm/viewclasslist');
 4559:             return OK;
 4560:         }
 4561:         $env{'user.error.msg'}=
 4562:             "/adm/createuser:cst:0:0:Cannot create/modify user data ".
 4563:                                  "or view user status.";
 4564:         return HTTP_NOT_ACCEPTABLE;
 4565:     }
 4566: 
 4567:     &Apache::loncommon::content_type($r,'text/html');
 4568:     $r->send_http_header;
 4569: 
 4570:     my $showcredits;
 4571:     if ((($context eq 'course') && ($crstype eq 'Course')) || 
 4572:          ($context eq 'domain')) {
 4573:         my %domdefaults = 
 4574:             &Apache::lonnet::get_domain_defaults($env{'request.role.domain'});
 4575:         if ($domdefaults{'officialcredits'} || $domdefaults{'unofficialcredits'}) {
 4576:             $showcredits = 1;
 4577:         }
 4578:     }
 4579: 
 4580:     # Main switch on form.action and form.state, as appropriate
 4581:     if (! exists($env{'form.action'})) {
 4582:         $args = {bread_crumbs => $brcrum,
 4583:                  bread_crumbs_component => $bread_crumbs_component}; 
 4584:         $r->print(&header(undef,$args));
 4585:         $r->print(&print_main_menu($permission,$context,$crstype));
 4586:     } elsif ($env{'form.action'} eq 'upload' && $permission->{'cusr'}) {
 4587:         push(@{$brcrum},
 4588:               { href => '/adm/createuser?action=upload&state=',
 4589:                 text => 'Upload Users List',
 4590:                 help => 'Course_Create_Class_List',
 4591:               });
 4592:         $bread_crumbs_component = 'Upload Users List';
 4593:         $args = {bread_crumbs           => $brcrum,
 4594:                  bread_crumbs_component => $bread_crumbs_component};
 4595:         $r->print(&header(undef,$args));
 4596:         $r->print('<form name="studentform" method="post" '.
 4597:                   'enctype="multipart/form-data" '.
 4598:                   ' action="/adm/createuser">'."\n");
 4599:         if (! exists($env{'form.state'})) {
 4600:             &Apache::lonuserutils::print_first_users_upload_form($r,$context);
 4601:         } elsif ($env{'form.state'} eq 'got_file') {
 4602:             &Apache::lonuserutils::print_upload_manager_form($r,$context,$permission,
 4603:                                                              $crstype,$showcredits);
 4604:         } elsif ($env{'form.state'} eq 'enrolling') {
 4605:             if ($env{'form.datatoken'}) {
 4606:                 &Apache::lonuserutils::upfile_drop_add($r,$context,$permission,
 4607:                                                        $showcredits);
 4608:             }
 4609:         } else {
 4610:             &Apache::lonuserutils::print_first_users_upload_form($r,$context);
 4611:         }
 4612:     } elsif ((($env{'form.action'} eq 'singleuser') || ($env{'form.action'}
 4613:              eq 'singlestudent')) && ($permission->{'cusr'})) {
 4614:         my $phase = $env{'form.phase'};
 4615:         my @search = ('srchterm','srchby','srchin','srchtype','srchdomain');
 4616: 	&Apache::loncreateuser::restore_prev_selections();
 4617: 	my $srch;
 4618: 	foreach my $item (@search) {
 4619: 	    $srch->{$item} = $env{'form.'.$item};
 4620: 	}
 4621:         if (($phase eq 'get_user_info') || ($phase eq 'userpicked') ||
 4622:             ($phase eq 'createnewuser')) {
 4623:             if ($env{'form.phase'} eq 'createnewuser') {
 4624:                 my $response;
 4625:                 if ($env{'form.srchterm'} !~ /^$match_username$/) {
 4626:                     my $response =
 4627:                         '<span class="LC_warning">'
 4628:                        .&mt('You must specify a valid username. Only the following are allowed:'
 4629:                            .' letters numbers - . @')
 4630:                        .'</span>';
 4631:                     $env{'form.phase'} = '';
 4632:                     &print_username_entry_form($r,$context,$response,$srch,undef,
 4633:                                                $crstype,$brcrum,$showcredits);
 4634:                 } else {
 4635:                     my $ccuname =&LONCAPA::clean_username($srch->{'srchterm'});
 4636:                     my $ccdomain=&LONCAPA::clean_domain($srch->{'srchdomain'});
 4637:                     &print_user_modification_page($r,$ccuname,$ccdomain,
 4638:                                                   $srch,$response,$context,
 4639:                                                   $permission,$crstype,$brcrum,
 4640:                                                   $showcredits);
 4641:                 }
 4642:             } elsif ($env{'form.phase'} eq 'get_user_info') {
 4643:                 my ($currstate,$response,$forcenewuser,$results) = 
 4644:                     &user_search_result($context,$srch);
 4645:                 if ($env{'form.currstate'} eq 'modify') {
 4646:                     $currstate = $env{'form.currstate'};
 4647:                 }
 4648:                 if ($currstate eq 'select') {
 4649:                     &print_user_selection_page($r,$response,$srch,$results,
 4650:                                                \@search,$context,undef,$crstype,
 4651:                                                $brcrum);
 4652:                 } elsif ($currstate eq 'modify') {
 4653:                     my ($ccuname,$ccdomain);
 4654:                     if (($srch->{'srchby'} eq 'uname') && 
 4655:                         ($srch->{'srchtype'} eq 'exact')) {
 4656:                         $ccuname = $srch->{'srchterm'};
 4657:                         $ccdomain= $srch->{'srchdomain'};
 4658:                     } else {
 4659:                         my @matchedunames = keys(%{$results});
 4660:                         ($ccuname,$ccdomain) = split(/:/,$matchedunames[0]);
 4661:                     }
 4662:                     $ccuname =&LONCAPA::clean_username($ccuname);
 4663:                     $ccdomain=&LONCAPA::clean_domain($ccdomain);
 4664:                     if ($env{'form.forcenewuser'}) {
 4665:                         $response = '';
 4666:                     }
 4667:                     &print_user_modification_page($r,$ccuname,$ccdomain,
 4668:                                                   $srch,$response,$context,
 4669:                                                   $permission,$crstype,$brcrum);
 4670:                 } elsif ($currstate eq 'query') {
 4671:                     &print_user_query_page($r,'createuser',$brcrum);
 4672:                 } else {
 4673:                     $env{'form.phase'} = '';
 4674:                     &print_username_entry_form($r,$context,$response,$srch,
 4675:                                                $forcenewuser,$crstype,$brcrum);
 4676:                 }
 4677:             } elsif ($env{'form.phase'} eq 'userpicked') {
 4678:                 my $ccuname = &LONCAPA::clean_username($env{'form.seluname'});
 4679:                 my $ccdomain = &LONCAPA::clean_domain($env{'form.seludom'});
 4680:                 &print_user_modification_page($r,$ccuname,$ccdomain,$srch,'',
 4681:                                               $context,$permission,$crstype,
 4682:                                               $brcrum);
 4683:             }
 4684:         } elsif ($env{'form.phase'} eq 'update_user_data') {
 4685:             &update_user_data($r,$context,$crstype,$brcrum,$showcredits);
 4686:         } else {
 4687:             &print_username_entry_form($r,$context,undef,$srch,undef,$crstype,
 4688:                                        $brcrum);
 4689:         }
 4690:     } elsif ($env{'form.action'} eq 'custom' && $permission->{'custom'}) {
 4691:         my $prefix;
 4692:         if ($env{'form.phase'} eq 'set_custom_roles') {
 4693:             &set_custom_role($r,$context,$brcrum,$prefix);
 4694:         } else {
 4695:             &custom_role_editor($r,$brcrum,$prefix);
 4696:         }
 4697:     } elsif (($env{'form.action'} eq 'processauthorreq') &&
 4698:              ($permission->{'cusr'}) && 
 4699:              (&Apache::lonnet::allowed('cau',$env{'request.role.domain'}))) {
 4700:         push(@{$brcrum},
 4701:                  {href => '/adm/createuser?action=processauthorreq',
 4702:                   text => 'Authoring Space requests',
 4703:                   help => 'Domain_Role_Approvals'});
 4704:         $bread_crumbs_component = 'Authoring requests';
 4705:         if ($env{'form.state'} eq 'done') {
 4706:             push(@{$brcrum},
 4707:                      {href => '/adm/createuser?action=authorreqqueue',
 4708:                       text => 'Result',
 4709:                       help => 'Domain_Role_Approvals'});
 4710:             $bread_crumbs_component = 'Authoring request result';
 4711:         }
 4712:         $args = { bread_crumbs           => $brcrum,
 4713:                   bread_crumbs_component => $bread_crumbs_component};
 4714:         my $js = &usernamerequest_javascript();
 4715:         $r->print(&header(&add_script($js),$args));
 4716:         if (!exists($env{'form.state'})) {
 4717:             $r->print(&Apache::loncoursequeueadmin::display_queued_requests('requestauthor',
 4718:                                                                             $env{'request.role.domain'}));
 4719:         } elsif ($env{'form.state'} eq 'done') {
 4720:             $r->print('<h3>'.&mt('Authoring request processing').'</h3>'."\n");
 4721:             $r->print(&Apache::loncoursequeueadmin::update_request_queue('requestauthor',
 4722:                                                                          $env{'request.role.domain'}));
 4723:         }
 4724:     } elsif (($env{'form.action'} eq 'processusernamereq') &&
 4725:              ($permission->{'cusr'}) &&
 4726:              (&Apache::lonnet::allowed('cau',$env{'request.role.domain'}))) {
 4727:         push(@{$brcrum},
 4728:                  {href => '/adm/createuser?action=processusernamereq',
 4729:                   text => 'LON-CAPA account requests',
 4730:                   help => 'Domain_Username_Approvals'});
 4731:         $bread_crumbs_component = 'Account requests';
 4732:         if ($env{'form.state'} eq 'done') {
 4733:             push(@{$brcrum},
 4734:                      {href => '/adm/createuser?action=usernamereqqueue',
 4735:                       text => 'Result',
 4736:                       help => 'Domain_Username_Approvals'});
 4737:             $bread_crumbs_component = 'LON-CAPA account request result';
 4738:         }
 4739:         $args = { bread_crumbs           => $brcrum,
 4740:                   bread_crumbs_component => $bread_crumbs_component};
 4741:         my $js = &usernamerequest_javascript();
 4742:         $r->print(&header(&add_script($js),$args));
 4743:         if (!exists($env{'form.state'})) {
 4744:             $r->print(&Apache::loncoursequeueadmin::display_queued_requests('requestusername',
 4745:                                                                             $env{'request.role.domain'}));
 4746:         } elsif ($env{'form.state'} eq 'done') {
 4747:             $r->print('<h3>'.&mt('LON-CAPA account request processing').'</h3>'."\n");
 4748:             $r->print(&Apache::loncoursequeueadmin::update_request_queue('requestusername',
 4749:                                                                          $env{'request.role.domain'}));
 4750:         }
 4751:     } elsif (($env{'form.action'} eq 'displayuserreq') &&
 4752:              ($permission->{'cusr'})) {
 4753:         my $dom = $env{'form.domain'};
 4754:         my $uname = $env{'form.username'};
 4755:         my $warning;
 4756:         if (($dom =~ /^$match_domain$/) && (&Apache::lonnet::domain($dom) ne '')) {
 4757:             if (($dom eq $env{'request.role.domain'}) && (&Apache::lonnet::allowed('ccc',$dom))) {
 4758:                 if (($uname =~ /^$match_username$/) && ($env{'form.queue'} eq 'approval')) {
 4759:                     my $uhome = &Apache::lonnet::homeserver($uname,$dom);
 4760:                     if ($uhome eq 'no_host') {
 4761:                         my $queue = $env{'form.queue'};
 4762:                         my $reqkey = &escape($uname).'_'.$queue; 
 4763:                         my $namespace = 'usernamequeue';
 4764:                         my $domconfig = &Apache::lonnet::get_domainconfiguser($dom);
 4765:                         my %queued =
 4766:                             &Apache::lonnet::get($namespace,[$reqkey],$dom,$domconfig);
 4767:                         unless ($queued{$reqkey}) {
 4768:                             $warning = &mt('No information was found for this LON-CAPA account request.');
 4769:                         }
 4770:                     } else {
 4771:                         $warning = &mt('A LON-CAPA account already exists for the requested username and domain.');
 4772:                     }
 4773:                 } else {
 4774:                     $warning = &mt('LON-CAPA account request status check is for an invalid username.');
 4775:                 }
 4776:             } else {
 4777:                 $warning = &mt('You do not have rights to view LON-CAPA account requests in the domain specified.');
 4778:             }
 4779:         } else {
 4780:             $warning = &mt('LON-CAPA account request status check is for an invalid domain.');
 4781:         }
 4782:         my $args = { only_body => 1 };
 4783:         $r->print(&header(undef,$args).
 4784:                   '<h3>'.&mt('LON-CAPA Account Request Details').'</h3>');
 4785:         if ($warning ne '') {
 4786:             $r->print('<div class="LC_warning">'.$warning.'</div>');
 4787:         } else {
 4788:             my ($infofields,$infotitles) = &Apache::loncommon::emailusername_info();
 4789:             my $domconfiguser = &Apache::lonnet::get_domainconfiguser($dom);
 4790:             my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 4791:             if (ref($domconfig{'usercreation'}) eq 'HASH') {
 4792:                 if (ref($domconfig{'usercreation'}{'cancreate'}) eq 'HASH') {
 4793:                     if (ref($domconfig{'usercreation'}{'cancreate'}{'emailusername'}) eq 'HASH') {
 4794:                         my %info =
 4795:                             &Apache::lonnet::get('nohist_requestedusernames',[$uname],$dom,$domconfiguser);
 4796:                         if (ref($info{$uname}) eq 'HASH') {
 4797:                             my $usertype = $info{$uname}{'inststatus'};
 4798:                             unless ($usertype) {
 4799:                                 $usertype = 'default';
 4800:                             }
 4801:                             if (ref($domconfig{'usercreation'}{'cancreate'}{'emailusername'}{$usertype}) eq 'HASH') {
 4802:                                 if ((ref($infofields) eq 'ARRAY') && (ref($infotitles) eq 'HASH')) {
 4803:                                     $r->print('<div>'.&Apache::lonhtmlcommon::start_pick_box());
 4804:                                     my ($num,$count,$showstatus);
 4805:                                     $count = scalar(keys(%{$domconfig{'usercreation'}{'cancreate'}{'emailusername'}{$usertype}}));
 4806:                                     unless ($usertype eq 'default') {
 4807:                                         my ($othertitle,$usertypes,$types) = 
 4808:                                             &Apache::loncommon::sorted_inst_types($dom);
 4809:                                         if (ref($usertypes) eq 'HASH') {
 4810:                                             if ($usertypes->{$usertype}) {
 4811:                                                 $showstatus = $usertypes->{$usertype};
 4812:                                                 $count ++;
 4813:                                             }
 4814:                                         }
 4815:                                     }
 4816:                                     foreach my $field (@{$infofields}) {
 4817:                                         next unless ($domconfig{'usercreation'}{'cancreate'}{'emailusername'}{$usertype}{$field});
 4818:                                         next unless ($infotitles->{$field});
 4819:                                         $r->print(&Apache::lonhtmlcommon::row_title($infotitles->{$field}).
 4820:                                                   $info{$uname}{$field});
 4821:                                         $num ++;
 4822:                                         if ($count == $num) {
 4823:                                             $r->print(&Apache::lonhtmlcommon::row_closure(1));
 4824:                                         } else {
 4825:                                             $r->print(&Apache::lonhtmlcommon::row_closure());
 4826:                                         }
 4827:                                     }
 4828:                                     if ($showstatus) {
 4829:                                         $r->print(&Apache::lonhtmlcommon::row_title(&mt('Status type (self-reported)')).
 4830:                                                   $showstatus.
 4831:                                                   &Apache::lonhtmlcommon::row_closure(1));
 4832:                                     }
 4833:                                     $r->print(&Apache::lonhtmlcommon::end_pick_box().'</div>');
 4834:                                 }
 4835:                             }
 4836:                         }
 4837:                     }
 4838:                 }
 4839:             }
 4840:             $r->print(&close_popup_form());
 4841:         }
 4842:     } elsif (($env{'form.action'} eq 'listusers') && 
 4843:              ($permission->{'view'} || $permission->{'cusr'})) {
 4844:         if ($env{'form.phase'} eq 'bulkchange') {
 4845:             push(@{$brcrum},
 4846:                     {href => '/adm/createuser?action=listusers',
 4847:                      text => "List Users"},
 4848:                     {href => "/adm/createuser",
 4849:                      text => "Result",
 4850:                      help => 'Course_View_Class_List'});
 4851:             $bread_crumbs_component = 'Update Users';
 4852:             $args = {bread_crumbs           => $brcrum,
 4853:                      bread_crumbs_component => $bread_crumbs_component};
 4854:             $r->print(&header(undef,$args));
 4855:             my $setting = $env{'form.roletype'};
 4856:             my $choice = $env{'form.bulkaction'};
 4857:             if ($permission->{'cusr'}) {
 4858:                 &Apache::lonuserutils::update_user_list($r,$context,$setting,$choice,$crstype);
 4859:             } else {
 4860:                 $r->print(&mt('You are not authorized to make bulk changes to user roles'));
 4861:                 $r->print('<p><a href="/adm/createuser?action=listusers">'.&mt('Display User Lists').'</a>');
 4862:             }
 4863:         } else {
 4864:             push(@{$brcrum},
 4865:                     {href => '/adm/createuser?action=listusers',
 4866:                      text => "List Users",
 4867:                      help => 'Course_View_Class_List'});
 4868:             $bread_crumbs_component = 'List Users';
 4869:             $args = {bread_crumbs           => $brcrum,
 4870:                      bread_crumbs_component => $bread_crumbs_component};
 4871:             my ($cb_jscript,$jscript,$totcodes,$codetitles,$idlist,$idlist_titles);
 4872:             my $formname = 'studentform';
 4873:             my $hidecall = "hide_searching();";
 4874:             if (($context eq 'domain') && (($env{'form.roletype'} eq 'course') ||
 4875:                 ($env{'form.roletype'} eq 'community'))) {
 4876:                 if ($env{'form.roletype'} eq 'course') {
 4877:                     ($cb_jscript,$jscript,$totcodes,$codetitles,$idlist,$idlist_titles) = 
 4878:                         &Apache::lonuserutils::courses_selector($env{'request.role.domain'},
 4879:                                                                 $formname);
 4880:                 } elsif ($env{'form.roletype'} eq 'community') {
 4881:                     $cb_jscript = 
 4882:                         &Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'});
 4883:                     my %elements = (
 4884:                                       coursepick => 'radio',
 4885:                                       coursetotal => 'text',
 4886:                                       courselist => 'text',
 4887:                                    );
 4888:                     $jscript = &Apache::lonhtmlcommon::set_form_elements(\%elements);
 4889:                 }
 4890:                 $jscript .= &verify_user_display($context)."\n".
 4891:                             &Apache::loncommon::check_uncheck_jscript();
 4892:                 my $js = &add_script($jscript).$cb_jscript;
 4893:                 my $loadcode = 
 4894:                     &Apache::lonuserutils::course_selector_loadcode($formname);
 4895:                 if ($loadcode ne '') {
 4896:                     $args->{add_entries} = {onload => "$loadcode;$hidecall"};
 4897:                 } else {
 4898:                     $args->{add_entries} = {onload => $hidecall};
 4899:                 }
 4900:                 $r->print(&header($js,$args));
 4901:             } else {
 4902:                 $args->{add_entries} = {onload => $hidecall};
 4903:                 $jscript = &verify_user_display($context).
 4904:                            &Apache::loncommon::check_uncheck_jscript(); 
 4905:                 $r->print(&header(&add_script($jscript),$args));
 4906:             }
 4907:             &Apache::lonuserutils::print_userlist($r,undef,$permission,$context,
 4908:                          $formname,$totcodes,$codetitles,$idlist,$idlist_titles,
 4909:                          $showcredits);
 4910:         }
 4911:     } elsif ($env{'form.action'} eq 'drop' && $permission->{'cusr'}) {
 4912:         my $brtext;
 4913:         if ($crstype eq 'Community') {
 4914:             $brtext = 'Drop Members';
 4915:         } else {
 4916:             $brtext = 'Drop Students';
 4917:         }
 4918:         push(@{$brcrum},
 4919:                 {href => '/adm/createuser?action=drop',
 4920:                  text => $brtext,
 4921:                  help => 'Course_Drop_Student'});
 4922:         if ($env{'form.state'} eq 'done') {
 4923:             push(@{$brcrum},
 4924:                      {href=>'/adm/createuser?action=drop',
 4925:                       text=>"Result"});
 4926:         }
 4927:         $bread_crumbs_component = $brtext;
 4928:         $args = {bread_crumbs           => $brcrum,
 4929:                  bread_crumbs_component => $bread_crumbs_component}; 
 4930:         $r->print(&header(undef,$args));
 4931:         if (!exists($env{'form.state'})) {
 4932:             &Apache::lonuserutils::print_drop_menu($r,$context,$permission,$crstype);
 4933:         } elsif ($env{'form.state'} eq 'done') {
 4934:             &Apache::lonuserutils::update_user_list($r,$context,undef,
 4935:                                                     $env{'form.action'});
 4936:         }
 4937:     } elsif ($env{'form.action'} eq 'dateselect') {
 4938:         if ($permission->{'cusr'}) {
 4939:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 4940:                       &Apache::lonuserutils::date_section_selector($context,$permission,
 4941:                                                                    $crstype,$showcredits));
 4942:         } else {
 4943:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 4944:                      '<span class="LC_error">'.&mt('You do not have permission to modify dates or sections for users').'</span>'); 
 4945:         }
 4946:     } elsif ($env{'form.action'} eq 'selfenroll') {
 4947:         if ($permission->{selfenrolladmin}) {
 4948:             my $cid = $env{'request.course.id'};
 4949:             my $cdom = $env{'course.'.$cid.'.domain'};
 4950:             my $cnum = $env{'course.'.$cid.'.num'};
 4951:             my %currsettings = (
 4952:                 selfenroll_types              => $env{'course.'.$cid.'.internal.selfenroll_types'},
 4953:                 selfenroll_registered         => $env{'course.'.$cid.'.internal.selfenroll_registered'},
 4954:                 selfenroll_section            => $env{'course.'.$cid.'.internal.selfenroll_section'},
 4955:                 selfenroll_notifylist         => $env{'course.'.$cid.'.internal.selfenroll_notifylist'},
 4956:                 selfenroll_approval           => $env{'course.'.$cid.'.internal.selfenroll_approval'},
 4957:                 selfenroll_limit              => $env{'course.'.$cid.'.internal.selfenroll_limit'},
 4958:                 selfenroll_cap                => $env{'course.'.$cid.'.internal.selfenroll_cap'},
 4959:                 selfenroll_start_date         => $env{'course.'.$cid.'.internal.selfenroll_start_date'},
 4960:                 selfenroll_end_date           => $env{'course.'.$cid.'.internal.selfenroll_end_date'},
 4961:                 selfenroll_start_access       => $env{'course.'.$cid.'.internal.selfenroll_start_access'},
 4962:                 selfenroll_end_access         => $env{'course.'.$cid.'.internal.selfenroll_end_access'},
 4963:                 default_enrollment_start_date => $env{'course.'.$cid.'.default_enrollment_start_date'},
 4964:                 default_enrollment_end_date   => $env{'course.'.$cid.'.default_enrollment_end_date'},
 4965:                 uniquecode                    => $env{'course.'.$cid.'.internal.uniquecode'},
 4966:             );
 4967:             push(@{$brcrum},
 4968:                     {href => '/adm/createuser?action=selfenroll',
 4969:                      text => "Configure Self-enrollment",
 4970:                      help => 'Course_Self_Enrollment'});
 4971:             if (!exists($env{'form.state'})) {
 4972:                 $args = { bread_crumbs           => $brcrum,
 4973:                           bread_crumbs_component => 'Configure Self-enrollment'};
 4974:                 $r->print(&header(undef,$args));
 4975:                 $r->print('<h3>'.&mt('Self-enrollment with a student role').'</h3>'."\n");
 4976:                 &print_selfenroll_menu($r,'course',$cid,$cdom,$cnum,\%currsettings);
 4977:             } elsif ($env{'form.state'} eq 'done') {
 4978:                 push (@{$brcrum},
 4979:                           {href=>'/adm/createuser?action=selfenroll',
 4980:                            text=>"Result"});
 4981:                 $args = { bread_crumbs           => $brcrum,
 4982:                           bread_crumbs_component => 'Self-enrollment result'};
 4983:                 $r->print(&header(undef,$args));
 4984:                 $r->print('<h3>'.&mt('Self-enrollment with a student role').'</h3>'."\n");
 4985:                 &update_selfenroll_config($r,$cid,$cdom,$cnum,$context,$crstype,\%currsettings);
 4986:             }
 4987:         } else {
 4988:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 4989:                      '<span class="LC_error">'.&mt('You do not have permission to configure self-enrollment').'</span>');
 4990:         }
 4991:     } elsif ($env{'form.action'} eq 'selfenrollqueue') {
 4992:         push(@{$brcrum},
 4993:                  {href => '/adm/createuser?action=selfenrollqueue',
 4994:                   text => 'Enrollment requests',
 4995:                   help => 'Course_Self_Enrollment'});
 4996:         $bread_crumbs_component = 'Enrollment requests';
 4997:         if ($env{'form.state'} eq 'done') {
 4998:             push(@{$brcrum},
 4999:                      {href => '/adm/createuser?action=selfenrollqueue',
 5000:                       text => 'Result',
 5001:                       help => 'Course_Self_Enrollment'});
 5002:             $bread_crumbs_component = 'Enrollment result';
 5003:         }
 5004:         $args = { bread_crumbs           => $brcrum,
 5005:                   bread_crumbs_component => $bread_crumbs_component};
 5006:         $r->print(&header(undef,$args));
 5007:         my $cid = $env{'request.course.id'};
 5008:         my $cdom = $env{'course.'.$cid.'.domain'};
 5009:         my $cnum = $env{'course.'.$cid.'.num'};
 5010:         my $coursedesc = $env{'course.'.$cid.'.description'};
 5011:         if (!exists($env{'form.state'})) {
 5012:             $r->print('<h3>'.&mt('Pending enrollment requests').'</h3>'."\n");
 5013:             $r->print(&Apache::loncoursequeueadmin::display_queued_requests($context,
 5014:                                                                        $cdom,$cnum));
 5015:         } elsif ($env{'form.state'} eq 'done') {
 5016:             $r->print('<h3>'.&mt('Enrollment request processing').'</h3>'."\n");
 5017:             $r->print(&Apache::loncoursequeueadmin::update_request_queue($context,
 5018:                           $cdom,$cnum,$coursedesc));
 5019:         }
 5020:     } elsif ($env{'form.action'} eq 'changelogs') {
 5021:         &print_userchangelogs_display($r,$context,$permission,$brcrum);
 5022:     } else {
 5023:         $bread_crumbs_component = 'User Management';
 5024:         $args = { bread_crumbs           => $brcrum,
 5025:                   bread_crumbs_component => $bread_crumbs_component};
 5026:         $r->print(&header(undef,$args));
 5027:         $r->print(&print_main_menu($permission,$context,$crstype));
 5028:     }
 5029:     $r->print(&Apache::loncommon::end_page());
 5030:     return OK;
 5031: }
 5032: 
 5033: sub header {
 5034:     my ($jscript,$args) = @_;
 5035:     my $start_page;
 5036:     if (ref($args) eq 'HASH') {
 5037:         $start_page=&Apache::loncommon::start_page('User Management',$jscript,$args);
 5038:     } else {
 5039:         $start_page=&Apache::loncommon::start_page('User Management',$jscript);
 5040:     }
 5041:     return $start_page;
 5042: }
 5043: 
 5044: sub add_script {
 5045:     my ($js) = @_;
 5046:     return '<script type="text/javascript">'."\n"
 5047:           .'// <![CDATA['."\n"
 5048:           .$js."\n"
 5049:           .'// ]]>'."\n"
 5050:           .'</script>'."\n";
 5051: }
 5052: 
 5053: sub usernamerequest_javascript {
 5054:     my $js = <<ENDJS;
 5055: 
 5056: function openusernamereqdisplay(dom,uname,queue) {
 5057:     var url = '/adm/createuser?action=displayuserreq';
 5058:     url += '&domain='+dom+'&username='+uname+'&queue='+queue;
 5059:     var title = 'Account_Request_Browser';
 5060:     var options = 'scrollbars=1,resizable=1,menubar=0';
 5061:     options += ',width=700,height=600';
 5062:     var stdeditbrowser = open(url,title,options,'1');
 5063:     stdeditbrowser.focus();
 5064:     return;
 5065: }
 5066:  
 5067: ENDJS
 5068: }
 5069: 
 5070: sub close_popup_form {
 5071:     my $close= &mt('Close Window');
 5072:     return << "END";
 5073: <p><form name="displayreq" action="" method="post">
 5074: <input type="button" name="closeme" value="$close" onclick="javascript:self.close();" />
 5075: </form></p>
 5076: END
 5077: }
 5078: 
 5079: sub verify_user_display {
 5080:     my ($context) = @_;
 5081:     my %lt = &Apache::lonlocal::texthash (
 5082:         course    => 'course(s): description, section(s), status',
 5083:         community => 'community(s): description, section(s), status',
 5084:         author    => 'author',
 5085:     );
 5086:     my $photos;
 5087:     if (($context eq 'course') && $env{'request.course.id'}) {
 5088:         $photos = $env{'course.'.$env{'request.course.id'}.'.internal.showphoto'};
 5089:     }
 5090:     my $output = <<"END";
 5091: 
 5092: function hide_searching() {
 5093:     if (document.getElementById('searching')) {
 5094:         document.getElementById('searching').style.display = 'none';
 5095:     }
 5096:     return;
 5097: }
 5098: 
 5099: function display_update() {
 5100:     document.studentform.action.value = 'listusers';
 5101:     document.studentform.phase.value = 'display';
 5102:     document.studentform.submit();
 5103: }
 5104: 
 5105: function updateCols(caller) {
 5106:     var context = '$context';
 5107:     var photos = '$photos';
 5108:     if (caller == 'Status') {
 5109:         if ((context == 'domain') && 
 5110:             ((document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'course') ||
 5111:              (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'community'))) {
 5112:             document.getElementById('showcolstatus').checked = false;
 5113:             document.getElementById('showcolstatus').disabled = 'disabled';
 5114:             document.getElementById('showcolstart').checked = false;
 5115:             document.getElementById('showcolend').checked = false;
 5116:         } else {
 5117:             if (document.studentform.Status.options[document.studentform.Status.selectedIndex].value == 'Any') {
 5118:                 document.getElementById('showcolstatus').checked = true;
 5119:                 document.getElementById('showcolstatus').disabled = '';
 5120:                 document.getElementById('showcolstart').checked = true;
 5121:                 document.getElementById('showcolend').checked = true;
 5122:             } else {
 5123:                 document.getElementById('showcolstatus').checked = false;
 5124:                 document.getElementById('showcolstatus').disabled = 'disabled';
 5125:                 document.getElementById('showcolstart').checked = false;
 5126:                 document.getElementById('showcolend').checked = false;
 5127:             }
 5128:         }
 5129:     }
 5130:     if (caller == 'output') {
 5131:         if (photos == 1) {
 5132:             if (document.getElementById('showcolphoto')) {
 5133:                 var photoitem = document.getElementById('showcolphoto');
 5134:                 if (document.studentform.output.options[document.studentform.output.selectedIndex].value == 'html') {
 5135:                     photoitem.checked = true;
 5136:                     photoitem.disabled = '';
 5137:                 } else {
 5138:                     photoitem.checked = false;
 5139:                     photoitem.disabled = 'disabled';
 5140:                 }
 5141:             }
 5142:         }
 5143:     }
 5144:     if (caller == 'showrole') {
 5145:         if ((document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'Any') ||
 5146:             (document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'cr')) {
 5147:             document.getElementById('showcolrole').checked = true;
 5148:             document.getElementById('showcolrole').disabled = '';
 5149:         } else {
 5150:             document.getElementById('showcolrole').checked = false;
 5151:             document.getElementById('showcolrole').disabled = 'disabled';
 5152:         }
 5153:         if (context == 'domain') {
 5154:             var quotausageshow = 0;
 5155:             if ((document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'course') ||
 5156:                 (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'community')) {
 5157:                 document.getElementById('showcolstatus').checked = false;
 5158:                 document.getElementById('showcolstatus').disabled = 'disabled';
 5159:                 document.getElementById('showcolstart').checked = false;
 5160:                 document.getElementById('showcolend').checked = false;
 5161:             } else {
 5162:                 if (document.studentform.Status.options[document.studentform.Status.selectedIndex].value == 'Any') {
 5163:                     document.getElementById('showcolstatus').checked = true;
 5164:                     document.getElementById('showcolstatus').disabled = '';
 5165:                     document.getElementById('showcolstart').checked = true;
 5166:                     document.getElementById('showcolend').checked = true;
 5167:                 }
 5168:             }
 5169:             if (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'domain') {
 5170:                 document.getElementById('showcolextent').disabled = 'disabled';
 5171:                 document.getElementById('showcolextent').checked = 'false';
 5172:                 document.getElementById('showextent').style.display='none';
 5173:                 document.getElementById('showcoltextextent').innerHTML = '';
 5174:                 if ((document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'au') ||
 5175:                     (document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'Any')) {
 5176:                     if (document.getElementById('showcolauthorusage')) {
 5177:                         document.getElementById('showcolauthorusage').disabled = '';
 5178:                     }
 5179:                     if (document.getElementById('showcolauthorquota')) {
 5180:                         document.getElementById('showcolauthorquota').disabled = '';
 5181:                     }
 5182:                     quotausageshow = 1;
 5183:                 }
 5184:             } else {
 5185:                 document.getElementById('showextent').style.display='block';
 5186:                 document.getElementById('showextent').style.textAlign='left';
 5187:                 document.getElementById('showextent').style.textFace='normal';
 5188:                 if (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'author') {
 5189:                     document.getElementById('showcolextent').disabled = '';
 5190:                     document.getElementById('showcolextent').checked = 'true';
 5191:                     document.getElementById('showcoltextextent').innerHTML="$lt{'author'}";
 5192:                 } else {
 5193:                     document.getElementById('showcolextent').disabled = '';
 5194:                     document.getElementById('showcolextent').checked = 'true';
 5195:                     if (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'community') {
 5196:                         document.getElementById('showcoltextextent').innerHTML="$lt{'community'}";
 5197:                     } else {
 5198:                         document.getElementById('showcoltextextent').innerHTML="$lt{'course'}";
 5199:                     }
 5200:                 }
 5201:             }
 5202:             if (quotausageshow == 0)  {
 5203:                 if (document.getElementById('showcolauthorusage')) {
 5204:                     document.getElementById('showcolauthorusage').checked = false;
 5205:                     document.getElementById('showcolauthorusage').disabled = 'disabled';
 5206:                 }
 5207:                 if (document.getElementById('showcolauthorquota')) {
 5208:                     document.getElementById('showcolauthorquota').checked = false;
 5209:                     document.getElementById('showcolauthorquota').disabled = 'disabled';
 5210:                 }
 5211:             }
 5212:         }
 5213:     }
 5214:     return;
 5215: }
 5216: 
 5217: END
 5218:     return $output;
 5219: 
 5220: }
 5221: 
 5222: ###############################################################
 5223: ###############################################################
 5224: #  Menu Phase One
 5225: sub print_main_menu {
 5226:     my ($permission,$context,$crstype) = @_;
 5227:     my $linkcontext = $context;
 5228:     my $stuterm = lc(&Apache::lonnet::plaintext('st',$crstype));
 5229:     if (($context eq 'course') && ($crstype eq 'Community')) {
 5230:         $linkcontext = lc($crstype);
 5231:         $stuterm = 'Members';
 5232:     }
 5233:     my %links = (
 5234:                 domain => {
 5235:                             upload     => 'Upload a File of Users',
 5236:                             singleuser => 'Add/Modify a User',
 5237:                             listusers  => 'Manage Users',
 5238:                             },
 5239:                 author => {
 5240:                             upload     => 'Upload a File of Co-authors',
 5241:                             singleuser => 'Add/Modify a Co-author',
 5242:                             listusers  => 'Manage Co-authors',
 5243:                             },
 5244:                 course => {
 5245:                             upload     => 'Upload a File of Course Users',
 5246:                             singleuser => 'Add/Modify a Course User',
 5247:                             listusers  => 'List and Modify Multiple Course Users',
 5248:                             },
 5249:                 community => {
 5250:                             upload     => 'Upload a File of Community Users',
 5251:                             singleuser => 'Add/Modify a Community User',
 5252:                             listusers  => 'List and Modify Multiple Community Users',
 5253:                            },
 5254:                 );
 5255:      my %linktitles = (
 5256:                 domain => {
 5257:                             singleuser => 'Add a user to the domain, and/or a course or community in the domain.',
 5258:                             listusers  => 'Show and manage users in this domain.',
 5259:                             },
 5260:                 author => {
 5261:                             singleuser => 'Add a user with a co- or assistant author role.',
 5262:                             listusers  => 'Show and manage co- or assistant authors.',
 5263:                             },
 5264:                 course => {
 5265:                             singleuser => 'Add a user with a certain role to this course.',
 5266:                             listusers  => 'Show and manage users in this course.',
 5267:                             },
 5268:                 community => {
 5269:                             singleuser => 'Add a user with a certain role to this community.',
 5270:                             listusers  => 'Show and manage users in this community.',
 5271:                            },
 5272:                 );
 5273:   my @menu = ( {categorytitle => 'Single Users', 
 5274:          items =>
 5275:          [
 5276:             {
 5277:              linktext => $links{$linkcontext}{'singleuser'},
 5278:              icon => 'edit-redo.png',
 5279:              #help => 'Course_Change_Privileges',
 5280:              url => '/adm/createuser?action=singleuser',
 5281:              permission => $permission->{'cusr'},
 5282:              linktitle => $linktitles{$linkcontext}{'singleuser'},
 5283:             },
 5284:          ]},
 5285: 
 5286:          {categorytitle => 'Multiple Users',
 5287:          items => 
 5288:          [
 5289:             {
 5290:              linktext => $links{$linkcontext}{'upload'},
 5291:              icon => 'uplusr.png',
 5292:              #help => 'Course_Create_Class_List',
 5293:              url => '/adm/createuser?action=upload',
 5294:              permission => $permission->{'cusr'},
 5295:              linktitle => 'Upload a CSV or a text file containing users.',
 5296:             },
 5297:             {
 5298:              linktext => $links{$linkcontext}{'listusers'},
 5299:              icon => 'mngcu.png',
 5300:              #help => 'Course_View_Class_List',
 5301:              url => '/adm/createuser?action=listusers',
 5302:              permission => ($permission->{'view'} || $permission->{'cusr'}),
 5303:              linktitle => $linktitles{$linkcontext}{'listusers'}, 
 5304:             },
 5305: 
 5306:          ]},
 5307: 
 5308:          {categorytitle => 'Administration',
 5309:          items => [ ]},
 5310:        );
 5311: 
 5312:     if ($context eq 'domain'){
 5313:         
 5314:         push(@{ $menu[2]->{items} }, #Category: Administration
 5315:             {
 5316:              linktext => 'Custom Roles',
 5317:              icon => 'emblem-photos.png',
 5318:              #help => 'Course_Editing_Custom_Roles',
 5319:              url => '/adm/createuser?action=custom',
 5320:              permission => $permission->{'custom'},
 5321:              linktitle => 'Configure a custom role.',
 5322:             },
 5323:             {
 5324:              linktext => 'Authoring Space Requests',
 5325:              icon => 'selfenrl-queue.png',
 5326:              #help => 'Domain_Role_Approvals',
 5327:              url => '/adm/createuser?action=processauthorreq',
 5328:              permission => $permission->{'cusr'},
 5329:              linktitle => 'Approve or reject author role requests',
 5330:             },
 5331:             {
 5332:              linktext => 'LON-CAPA Account Requests',
 5333:              icon => 'list-add.png',
 5334:              #help => 'Domain_Username_Approvals',
 5335:              url => '/adm/createuser?action=processusernamereq',
 5336:              permission => $permission->{'cusr'},
 5337:              linktitle => 'Approve or reject LON-CAPA account requests',
 5338:             },
 5339:             {
 5340:              linktext => 'Change Log',
 5341:              icon => 'document-properties.png',
 5342:              #help => 'Course_User_Logs',
 5343:              url => '/adm/createuser?action=changelogs',
 5344:              permission => $permission->{'cusr'},
 5345:              linktitle => 'View change log.',
 5346:             },
 5347:         );
 5348:         
 5349:     }elsif ($context eq 'course'){
 5350:         my ($cnum,$cdom) = &Apache::lonuserutils::get_course_identity();
 5351: 
 5352:         my %linktext = (
 5353:                          'Course'    => {
 5354:                                           single => 'Add/Modify a Student', 
 5355:                                           drop   => 'Drop Students',
 5356:                                           groups => 'Course Groups',
 5357:                                         },
 5358:                          'Community' => {
 5359:                                           single => 'Add/Modify a Member', 
 5360:                                           drop   => 'Drop Members',
 5361:                                           groups => 'Community Groups',
 5362:                                         },
 5363:                        );
 5364:         $linktext{'Placement'} = $linktext{'Course'};
 5365: 
 5366:         my %linktitle = (
 5367:             'Course' => {
 5368:                   single => 'Add a user with the role of student to this course',
 5369:                   drop   => 'Remove a student from this course.',
 5370:                   groups => 'Manage course groups',
 5371:                         },
 5372:             'Community' => {
 5373:                   single => 'Add a user with the role of member to this community',
 5374:                   drop   => 'Remove a member from this community.',
 5375:                   groups => 'Manage community groups',
 5376:                            },
 5377:         );
 5378: 
 5379:         $linktitle{'Placement'} = $linktitle{'Course'};
 5380: 
 5381:         push(@{ $menu[0]->{items} }, #Category: Single Users
 5382:             {   
 5383:              linktext => $linktext{$crstype}{'single'},
 5384:              #help => 'Course_Add_Student',
 5385:              icon => 'list-add.png',
 5386:              url => '/adm/createuser?action=singlestudent',
 5387:              permission => $permission->{'cusr'},
 5388:              linktitle => $linktitle{$crstype}{'single'},
 5389:             },
 5390:         );
 5391:         
 5392:         push(@{ $menu[1]->{items} }, #Category: Multiple Users 
 5393:             {
 5394:              linktext => $linktext{$crstype}{'drop'},
 5395:              icon => 'edit-undo.png',
 5396:              #help => 'Course_Drop_Student',
 5397:              url => '/adm/createuser?action=drop',
 5398:              permission => $permission->{'cusr'},
 5399:              linktitle => $linktitle{$crstype}{'drop'},
 5400:             },
 5401:         );
 5402:         push(@{ $menu[2]->{items} }, #Category: Administration
 5403:             {    
 5404:              linktext => 'Custom Roles',
 5405:              icon => 'emblem-photos.png',
 5406:              #help => 'Course_Editing_Custom_Roles',
 5407:              url => '/adm/createuser?action=custom',
 5408:              permission => $permission->{'custom'},
 5409:              linktitle => 'Configure a custom role.',
 5410:             },
 5411:             {
 5412:              linktext => $linktext{$crstype}{'groups'},
 5413:              icon => 'grps.png',
 5414:              #help => 'Course_Manage_Group',
 5415:              url => '/adm/coursegroups?refpage=cusr',
 5416:              permission => $permission->{'grp_manage'},
 5417:              linktitle => $linktitle{$crstype}{'groups'},
 5418:             },
 5419:             {
 5420:              linktext => 'Change Log',
 5421:              icon => 'document-properties.png',
 5422:              #help => 'Course_User_Logs',
 5423:              url => '/adm/createuser?action=changelogs',
 5424:              permission => $permission->{'cusr'},
 5425:              linktitle => 'View change log.',
 5426:             },
 5427:         );
 5428:         if ($env{'course.'.$env{'request.course.id'}.'.internal.selfenroll_approval'}) {
 5429:             push(@{ $menu[2]->{items} },
 5430:                     {
 5431:                      linktext => 'Enrollment Requests',
 5432:                      icon => 'selfenrl-queue.png',
 5433:                      #help => 'Course_Approve_Selfenroll',
 5434:                      url => '/adm/createuser?action=selfenrollqueue',
 5435:                      permission => $permission->{'selfenrolladmin'},
 5436:                      linktitle =>'Approve or reject enrollment requests.',
 5437:                     },
 5438:             );
 5439:         }
 5440:         
 5441:         if (!exists($permission->{'cusr_section'})){
 5442:             if ($crstype ne 'Community') {
 5443:                 push(@{ $menu[2]->{items} },
 5444:                     {
 5445:                      linktext => 'Automated Enrollment',
 5446:                      icon => 'roles.png',
 5447:                      #help => 'Course_Automated_Enrollment',
 5448:                      permission => (&Apache::lonnet::auto_run($cnum,$cdom)
 5449:                                          && $permission->{'cusr'}),
 5450:                      url  => '/adm/populate',
 5451:                      linktitle => 'Automated enrollment manager.',
 5452:                     }
 5453:                 );
 5454:             }
 5455:             push(@{ $menu[2]->{items} }, 
 5456:                 {
 5457:                  linktext => 'User Self-Enrollment',
 5458:                  icon => 'self_enroll.png',
 5459:                  #help => 'Course_Self_Enrollment',
 5460:                  url => '/adm/createuser?action=selfenroll',
 5461:                  permission => $permission->{'selfenrolladmin'},
 5462:                  linktitle => 'Configure user self-enrollment.',
 5463:                 },
 5464:             );
 5465:         }
 5466:     } elsif ($context eq 'author') {
 5467:         push(@{ $menu[2]->{items} }, #Category: Administration
 5468:             {
 5469:              linktext => 'Change Log',
 5470:              icon => 'document-properties.png',
 5471:              #help => 'Course_User_Logs',
 5472:              url => '/adm/createuser?action=changelogs',
 5473:              permission => $permission->{'cusr'},
 5474:              linktitle => 'View change log.',
 5475:             },
 5476:         );
 5477:     }
 5478:     return Apache::lonhtmlcommon::generate_menu(@menu);
 5479: #               { text => 'View Log-in History',
 5480: #                 help => 'Course_User_Logins',
 5481: #                 action => 'logins',
 5482: #                 permission => $permission->{'cusr'},
 5483: #               });
 5484: }
 5485: 
 5486: sub restore_prev_selections {
 5487:     my %saveable_parameters = ('srchby'   => 'scalar',
 5488: 			       'srchin'   => 'scalar',
 5489: 			       'srchtype' => 'scalar',
 5490: 			       );
 5491:     &Apache::loncommon::store_settings('user','user_picker',
 5492: 				       \%saveable_parameters);
 5493:     &Apache::loncommon::restore_settings('user','user_picker',
 5494: 					 \%saveable_parameters);
 5495: }
 5496: 
 5497: sub print_selfenroll_menu {
 5498:     my ($r,$context,$cid,$cdom,$cnum,$currsettings,$additional) = @_;
 5499:     my $crstype = &Apache::loncommon::course_type();
 5500:     my $formname = 'selfenroll';
 5501:     my $nolink = 1;
 5502:     my ($row,$lt) = &Apache::lonuserutils::get_selfenroll_titles();
 5503:     my $groupslist = &Apache::lonuserutils::get_groupslist();
 5504:     my $setsec_js = 
 5505:         &Apache::lonuserutils::setsections_javascript($formname,$groupslist);
 5506:     my %alerts = &Apache::lonlocal::texthash(
 5507:         acto => 'Activation of self-enrollment was selected for the following domain(s)',
 5508:         butn => 'but no user types have been checked.',
 5509:         wilf => "Please uncheck 'activate' or check at least one type.",
 5510:     );
 5511:     &js_escape(\%alerts);
 5512:     my $selfenroll_js = <<"ENDSCRIPT";
 5513: function update_types(caller,num) {
 5514:     var delidx = getIndexByName('selfenroll_delete');
 5515:     var actidx = getIndexByName('selfenroll_activate');
 5516:     if (caller == 'selfenroll_all') {
 5517:         var selall;
 5518:         for (var i=0; i<document.$formname.selfenroll_all.length; i++) {
 5519:             if (document.$formname.selfenroll_all[i].checked) {
 5520:                 selall = document.$formname.selfenroll_all[i].value;
 5521:             }
 5522:         }
 5523:         if (selall == 1) {
 5524:             if (delidx != -1) {
 5525:                 if (document.$formname.selfenroll_delete.length) {
 5526:                     for (var j=0; j<document.$formname.selfenroll_delete.length; j++) {
 5527:                         document.$formname.selfenroll_delete[j].checked = true;
 5528:                     }
 5529:                 } else {
 5530:                     document.$formname.elements[delidx].checked = true;
 5531:                 }
 5532:             }
 5533:             if (actidx != -1) {
 5534:                 if (document.$formname.selfenroll_activate.length) {
 5535:                     for (var j=0; j<document.$formname.selfenroll_activate.length; j++) {
 5536:                         document.$formname.selfenroll_activate[j].checked = false;
 5537:                     }
 5538:                 } else {
 5539:                     document.$formname.elements[actidx].checked = false;
 5540:                 }
 5541:             }
 5542:             document.$formname.selfenroll_newdom.selectedIndex = 0; 
 5543:         }
 5544:     }
 5545:     if (caller == 'selfenroll_activate') {
 5546:         if (document.$formname.selfenroll_activate.length) {
 5547:             for (var j=0; j<document.$formname.selfenroll_activate.length; j++) {
 5548:                 if (document.$formname.selfenroll_activate[j].value == num) {
 5549:                     if (document.$formname.selfenroll_activate[j].checked) {
 5550:                         for (var i=0; i<document.$formname.selfenroll_all.length; i++) {
 5551:                             if (document.$formname.selfenroll_all[i].value == '1') {
 5552:                                 document.$formname.selfenroll_all[i].checked = false;
 5553:                             }
 5554:                             if (document.$formname.selfenroll_all[i].value == '0') {
 5555:                                 document.$formname.selfenroll_all[i].checked = true;
 5556:                             }
 5557:                         }
 5558:                     }
 5559:                 }
 5560:             }
 5561:         } else {
 5562:             for (var i=0; i<document.$formname.selfenroll_all.length; i++) {
 5563:                 if (document.$formname.selfenroll_all[i].value == '1') {
 5564:                     document.$formname.selfenroll_all[i].checked = false;
 5565:                 }
 5566:                 if (document.$formname.selfenroll_all[i].value == '0') {
 5567:                     document.$formname.selfenroll_all[i].checked = true;
 5568:                 }
 5569:             }
 5570:         }
 5571:     }
 5572:     if (caller == 'selfenroll_delete') {
 5573:         if (document.$formname.selfenroll_delete.length) {
 5574:             for (var j=0; j<document.$formname.selfenroll_delete.length; j++) {
 5575:                 if (document.$formname.selfenroll_delete[j].value == num) {
 5576:                     if (document.$formname.selfenroll_delete[j].checked) {
 5577:                         var delindex = getIndexByName('selfenroll_types_'+num);
 5578:                         if (delindex != -1) { 
 5579:                             if (document.$formname.elements[delindex].length) {
 5580:                                 for (var k=0; k<document.$formname.elements[delindex].length; k++) {
 5581:                                     document.$formname.elements[delindex][k].checked = false;
 5582:                                 }
 5583:                             } else {
 5584:                                 document.$formname.elements[delindex].checked = false;
 5585:                             }
 5586:                         }
 5587:                     }
 5588:                 }
 5589:             }
 5590:         } else {
 5591:             if (document.$formname.selfenroll_delete.checked) {
 5592:                 var delindex = getIndexByName('selfenroll_types_'+num);
 5593:                 if (delindex != -1) {
 5594:                     if (document.$formname.elements[delindex].length) {
 5595:                         for (var k=0; k<document.$formname.elements[delindex].length; k++) {
 5596:                             document.$formname.elements[delindex][k].checked = false;
 5597:                         }
 5598:                     } else {
 5599:                         document.$formname.elements[delindex].checked = false;
 5600:                     }
 5601:                 }
 5602:             }
 5603:         }
 5604:     }
 5605:     return;
 5606: }
 5607: 
 5608: function validate_types(form) {
 5609:     var needaction = new Array();
 5610:     var countfail = 0;
 5611:     var actidx = getIndexByName('selfenroll_activate');
 5612:     if (actidx != -1) {
 5613:         if (document.$formname.selfenroll_activate.length) {
 5614:             for (var j=0; j<document.$formname.selfenroll_activate.length; j++) {
 5615:                 var num = document.$formname.selfenroll_activate[j].value;
 5616:                 if (document.$formname.selfenroll_activate[j].checked) {
 5617:                     countfail = check_types(num,countfail,needaction)
 5618:                 }
 5619:             }
 5620:         } else {
 5621:             if (document.$formname.selfenroll_activate.checked) {
 5622:                 var num = document.$formname.selfenroll_activate.value;
 5623:                 countfail = check_types(num,countfail,needaction)
 5624:             }
 5625:         }
 5626:     }
 5627:     if (countfail > 0) {
 5628:         var msg = "$alerts{'acto'}\\n";
 5629:         var loopend = needaction.length -1;
 5630:         if (loopend > 0) {
 5631:             for (var m=0; m<loopend; m++) {
 5632:                 msg += needaction[m]+", ";
 5633:             }
 5634:         }
 5635:         msg += needaction[loopend]+"\\n$alerts{'butn'}\\n$alerts{'wilf'}";
 5636:         alert(msg);
 5637:         return; 
 5638:     }
 5639:     setSections(form);
 5640: }
 5641: 
 5642: function check_types(num,countfail,needaction) {
 5643:     var typeidx = getIndexByName('selfenroll_types_'+num);
 5644:     var count = 0;
 5645:     if (typeidx != -1) {
 5646:         if (document.$formname.elements[typeidx].length) {
 5647:             for (var k=0; k<document.$formname.elements[typeidx].length; k++) {
 5648:                 if (document.$formname.elements[typeidx][k].checked) {
 5649:                     count ++;
 5650:                 }
 5651:             }
 5652:         } else {
 5653:             if (document.$formname.elements[typeidx].checked) {
 5654:                 count ++;
 5655:             }
 5656:         }
 5657:         if (count == 0) {
 5658:             var domidx = getIndexByName('selfenroll_dom_'+num);
 5659:             if (domidx != -1) {
 5660:                 var domname = document.$formname.elements[domidx].value;
 5661:                 needaction[countfail] = domname;
 5662:                 countfail ++;
 5663:             }
 5664:         }
 5665:     }
 5666:     return countfail;
 5667: }
 5668: 
 5669: function toggleNotify() {
 5670:     var selfenrollApproval = 0;
 5671:     if (document.$formname.selfenroll_approval.length) {
 5672:         for (var i=0; i<document.$formname.selfenroll_approval.length; i++) {
 5673:             if (document.$formname.selfenroll_approval[i].checked) {
 5674:                 selfenrollApproval = document.$formname.selfenroll_approval[i].value;
 5675:                 break;        
 5676:             }
 5677:         }
 5678:     }
 5679:     if (document.getElementById('notified')) {
 5680:         if (selfenrollApproval == 0) {
 5681:             document.getElementById('notified').style.display='none';
 5682:         } else {
 5683:             document.getElementById('notified').style.display='block';
 5684:         }
 5685:     }
 5686:     return;
 5687: }
 5688: 
 5689: function getIndexByName(item) {
 5690:     for (var i=0;i<document.$formname.elements.length;i++) {
 5691:         if (document.$formname.elements[i].name == item) {
 5692:             return i;
 5693:         }
 5694:     }
 5695:     return -1;
 5696: }
 5697: ENDSCRIPT
 5698: 
 5699:     my $output = '<script type="text/javascript">'."\n".
 5700:                  '// <![CDATA['."\n".
 5701:                  $setsec_js."\n".$selfenroll_js."\n".
 5702:                  '// ]]>'."\n".
 5703:                  '</script>'."\n".
 5704:                  '<h3>'.$lt->{'selfenroll'}.'</h3>'."\n";
 5705:  
 5706:     my $visactions = &cat_visibility();
 5707:     my ($cathash,%cattype);
 5708:     my %domconfig = &Apache::lonnet::get_dom('configuration',['coursecategories'],$cdom);
 5709:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 5710:         $cathash = $domconfig{'coursecategories'}{'cats'};
 5711:         $cattype{'auth'} = $domconfig{'coursecategories'}{'auth'};
 5712:         $cattype{'unauth'} = $domconfig{'coursecategories'}{'unauth'};
 5713:         if ($cattype{'auth'} eq '') {
 5714:             $cattype{'auth'} = 'std';
 5715:         }
 5716:         if ($cattype{'unauth'} eq '') {
 5717:             $cattype{'unauth'} = 'std';
 5718:         }
 5719:     } else {
 5720:         $cathash = {};
 5721:         $cattype{'auth'} = 'std';
 5722:         $cattype{'unauth'} = 'std';
 5723:     }
 5724:     if (($cattype{'auth'} eq 'none') && ($cattype{'unauth'} eq 'none')) {
 5725:         $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
 5726:                   '<br />'.
 5727:                   '<br />'.$visactions->{'take'}.'<ul>'.
 5728:                   '<li>'.$visactions->{'dc_chgconf'}.'</li>'.
 5729:                   '</ul>');
 5730:     } elsif (($cattype{'auth'} !~ /^(std|domonly)$/) && ($cattype{'unauth'} !~ /^(std|domonly)$/)) {
 5731:         if ($currsettings->{'uniquecode'}) {
 5732:             $r->print('<span class="LC_info">'.$visactions->{'vis'}.'</span>');
 5733:         } else {
 5734:             $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
 5735:                   '<br />'.
 5736:                   '<br />'.$visactions->{'take'}.'<ul>'.
 5737:                   '<li>'.$visactions->{'dc_setcode'}.'</li>'.
 5738:                   '</ul><br />');
 5739:         }
 5740:     } else {
 5741:         my ($visible,$cansetvis,$vismsgs) = &visible_in_stdcat($cdom,$cnum,\%domconfig);
 5742:         if (ref($visactions) eq 'HASH') {
 5743:             if ($visible) {
 5744:                 $output .= '<p class="LC_info">'.$visactions->{'vis'}.'</p>';
 5745:            } else {
 5746:                 $output .= '<p class="LC_warning">'.$visactions->{'miss'}.'</p>'
 5747:                           .$visactions->{'yous'}.
 5748:                            '<p>'.$visactions->{'gen'}.'<br />'.$visactions->{'coca'};
 5749:                 if (ref($vismsgs) eq 'ARRAY') {
 5750:                     $output .= '<br />'.$visactions->{'make'}.'<ul>';
 5751:                     foreach my $item (@{$vismsgs}) {
 5752:                         $output .= '<li>'.$visactions->{$item}.'</li>';
 5753:                     }
 5754:                     $output .= '</ul>';
 5755:                 }
 5756:                 $output .= '</p>';
 5757:             }
 5758:         }
 5759:     }
 5760:     my $actionhref = '/adm/createuser';
 5761:     if ($context eq 'domain') {
 5762:         $actionhref = '/adm/modifycourse';
 5763:     }
 5764: 
 5765:     my %noedit;
 5766:     unless ($context eq 'domain') {
 5767:         %noedit = &get_noedit_fields($cdom,$cnum,$crstype,$row);
 5768:     }
 5769:     $output .= '<form name="'.$formname.'" method="post" action="'.$actionhref.'">'."\n".
 5770:                &Apache::lonhtmlcommon::start_pick_box();
 5771:     if (ref($row) eq 'ARRAY') {
 5772:         foreach my $item (@{$row}) {
 5773:             my $title = $item; 
 5774:             if (ref($lt) eq 'HASH') {
 5775:                 $title = $lt->{$item};
 5776:             }
 5777:             $output .= &Apache::lonhtmlcommon::row_title($title);
 5778:             if ($item eq 'types') {
 5779:                 my $curr_types;
 5780:                 if (ref($currsettings) eq 'HASH') {
 5781:                     $curr_types = $currsettings->{'selfenroll_types'};
 5782:                 }
 5783:                 if ($noedit{$item}) {
 5784:                     if ($curr_types eq '*') {
 5785:                         $output .= &mt('Any user in any domain');   
 5786:                     } else {
 5787:                         my @entries = split(/;/,$curr_types);
 5788:                         if (@entries > 0) {
 5789:                             $output .= '<ul>'; 
 5790:                             foreach my $entry (@entries) {
 5791:                                 my ($currdom,$typestr) = split(/:/,$entry);
 5792:                                 next if ($typestr eq '');
 5793:                                 my $domdesc = &Apache::lonnet::domain($currdom);
 5794:                                 my @currinsttypes = split(',',$typestr);
 5795:                                 my ($othertitle,$usertypes,$types) = 
 5796:                                     &Apache::loncommon::sorted_inst_types($currdom);
 5797:                                 if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 5798:                                     $usertypes->{'any'} = &mt('any user'); 
 5799:                                     if (keys(%{$usertypes}) > 0) {
 5800:                                         $usertypes->{'other'} = &mt('other users');
 5801:                                     }
 5802:                                     my @longinsttypes = map { $usertypes->{$_}; } @currinsttypes;
 5803:                                     $output .= '<li>'.$domdesc.':'.join(', ',@longinsttypes).'</li>';
 5804:                                  }
 5805:                             }
 5806:                             $output .= '</ul>';
 5807:                         } else {
 5808:                             $output .= &mt('None');
 5809:                         }
 5810:                     }
 5811:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 5812:                     next;
 5813:                 }
 5814:                 my $showdomdesc = 1;
 5815:                 my $includeempty = 1;
 5816:                 my $num = 0;
 5817:                 $output .= &Apache::loncommon::start_data_table().
 5818:                            &Apache::loncommon::start_data_table_row()
 5819:                            .'<td colspan="2"><span class="LC_nobreak"><label>'
 5820:                            .&mt('Any user in any domain:')
 5821:                            .'&nbsp;<input type="radio" name="selfenroll_all" value="1" ';
 5822:                 if ($curr_types eq '*') {
 5823:                     $output .= ' checked="checked" '; 
 5824:                 }
 5825:                 $output .= 'onchange="javascript:update_types('.
 5826:                            "'selfenroll_all'".');" />'.&mt('Yes').'</label>'.
 5827:                            '&nbsp;&nbsp;<input type="radio" name="selfenroll_all" value="0" ';
 5828:                 if ($curr_types ne '*') {
 5829:                     $output .= ' checked="checked" ';
 5830:                 }
 5831:                 $output .= ' onchange="javascript:update_types('.
 5832:                            "'selfenroll_all'".');"/>'.&mt('No').'</label></td>'.
 5833:                            &Apache::loncommon::end_data_table_row().
 5834:                            &Apache::loncommon::end_data_table().
 5835:                            &mt('Or').'<br />'.
 5836:                            &Apache::loncommon::start_data_table();
 5837:                 my %currdoms;
 5838:                 if ($curr_types eq '') {
 5839:                     $output .= &new_selfenroll_dom_row($cdom,'0');
 5840:                 } elsif ($curr_types ne '*') {
 5841:                     my @entries = split(/;/,$curr_types);
 5842:                     if (@entries > 0) {
 5843:                         foreach my $entry (@entries) {
 5844:                             my ($currdom,$typestr) = split(/:/,$entry);
 5845:                             $currdoms{$currdom} = 1;
 5846:                             my $domdesc = &Apache::lonnet::domain($currdom);
 5847:                             my @currinsttypes = split(',',$typestr);
 5848:                             $output .= &Apache::loncommon::start_data_table_row()
 5849:                                        .'<td valign="top"><span class="LC_nobreak">'.&mt('Domain:').'<b>'
 5850:                                        .'&nbsp;'.$domdesc.' ('.$currdom.')'
 5851:                                        .'</b><input type="hidden" name="selfenroll_dom_'.$num
 5852:                                        .'" value="'.$currdom.'" /></span><br />'
 5853:                                        .'<span class="LC_nobreak"><label><input type="checkbox" '
 5854:                                        .'name="selfenroll_delete" value="'.$num.'" onchange="javascript:update_types('."'selfenroll_delete','$num'".');" />'
 5855:                                        .&mt('Delete').'</label></span></td>';
 5856:                             $output .= '<td valign="top">&nbsp;&nbsp;'.&mt('User types:').'<br />'
 5857:                                        .&selfenroll_inst_types($num,$currdom,\@currinsttypes).'</td>'
 5858:                                        .&Apache::loncommon::end_data_table_row();
 5859:                             $num ++;
 5860:                         }
 5861:                     }
 5862:                 }
 5863:                 my $add_domtitle = &mt('Users in additional domain:');
 5864:                 if ($curr_types eq '*') { 
 5865:                     $add_domtitle = &mt('Users in specific domain:');
 5866:                 } elsif ($curr_types eq '') {
 5867:                     $add_domtitle = &mt('Users in other domain:');
 5868:                 }
 5869:                 $output .= &Apache::loncommon::start_data_table_row()
 5870:                            .'<td colspan="2"><span class="LC_nobreak">'.$add_domtitle.'</span><br />'
 5871:                            .&Apache::loncommon::select_dom_form('','selfenroll_newdom',
 5872:                                                                 $includeempty,$showdomdesc)
 5873:                            .'<input type="hidden" name="selfenroll_types_total" value="'.$num.'" />'
 5874:                            .'</td>'.&Apache::loncommon::end_data_table_row()
 5875:                            .&Apache::loncommon::end_data_table();
 5876:             } elsif ($item eq 'registered') {
 5877:                 my ($regon,$regoff);
 5878:                 my $registered;
 5879:                 if (ref($currsettings) eq 'HASH') {
 5880:                     $registered = $currsettings->{'selfenroll_registered'};
 5881:                 }
 5882:                 if ($noedit{$item}) {
 5883:                     if ($registered) {
 5884:                         $output .= &mt('Must be registered in course');
 5885:                     } else {
 5886:                         $output .= &mt('No requirement');
 5887:                     }
 5888:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 5889:                     next;
 5890:                 }
 5891:                 if ($registered) {
 5892:                     $regon = ' checked="checked" ';
 5893:                     $regoff = ' ';
 5894:                 } else {
 5895:                     $regon = ' ';
 5896:                     $regoff = ' checked="checked" ';
 5897:                 }
 5898:                 $output .= '<label>'.
 5899:                            '<input type="radio" name="selfenroll_registered" value="1"'.$regon.'/>'.
 5900:                            &mt('Yes').'</label>&nbsp;&nbsp;<label>'.
 5901:                            '<input type="radio" name="selfenroll_registered" value="0"'.$regoff.'/>'.
 5902:                            &mt('No').'</label>';
 5903:             } elsif ($item eq 'enroll_dates') {
 5904:                 my ($starttime,$endtime);
 5905:                 if (ref($currsettings) eq 'HASH') {
 5906:                     $starttime = $currsettings->{'selfenroll_start_date'};
 5907:                     $endtime = $currsettings->{'selfenroll_end_date'};
 5908:                     if ($starttime eq '') {
 5909:                         $starttime = $currsettings->{'default_enrollment_start_date'};
 5910:                     }
 5911:                     if ($endtime eq '') {
 5912:                         $endtime = $currsettings->{'default_enrollment_end_date'};
 5913:                     }
 5914:                 }
 5915:                 if ($noedit{$item}) {
 5916:                     $output .= &mt('From: [_1], to: [_2]',&Apache::lonlocal::locallocaltime($starttime),
 5917:                                                           &Apache::lonlocal::locallocaltime($endtime));
 5918:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 5919:                     next;
 5920:                 }
 5921:                 my $startform =
 5922:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_start_date',$starttime,
 5923:                                       undef,undef,undef,undef,undef,undef,undef,$nolink);
 5924:                 my $endform =
 5925:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_end_date',$endtime,
 5926:                                       undef,undef,undef,undef,undef,undef,undef,$nolink);
 5927:                 $output .= &selfenroll_date_forms($startform,$endform);
 5928:             } elsif ($item eq 'access_dates') {
 5929:                 my ($starttime,$endtime);
 5930:                 if (ref($currsettings) eq 'HASH') {
 5931:                     $starttime = $currsettings->{'selfenroll_start_access'};
 5932:                     $endtime = $currsettings->{'selfenroll_end_access'};
 5933:                     if ($starttime eq '') {
 5934:                         $starttime = $currsettings->{'default_enrollment_start_date'};
 5935:                     }
 5936:                     if ($endtime eq '') {
 5937:                         $endtime = $currsettings->{'default_enrollment_end_date'};
 5938:                     }
 5939:                 }
 5940:                 if ($noedit{$item}) {
 5941:                     $output .= &mt('From: [_1], to: [_2]',&Apache::lonlocal::locallocaltime($starttime),
 5942:                                                           &Apache::lonlocal::locallocaltime($endtime));
 5943:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 5944:                     next;
 5945:                 }
 5946:                 my $startform =
 5947:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_start_access',$starttime,
 5948:                                       undef,undef,undef,undef,undef,undef,undef,$nolink);
 5949:                 my $endform =
 5950:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_end_access',$endtime,
 5951:                                       undef,undef,undef,undef,undef,undef,undef,$nolink);
 5952:                 $output .= &selfenroll_date_forms($startform,$endform);
 5953:             } elsif ($item eq 'section') {
 5954:                 my $currsec;
 5955:                 if (ref($currsettings) eq 'HASH') {
 5956:                     $currsec = $currsettings->{'selfenroll_section'};
 5957:                 }
 5958:                 my %sections_count = &Apache::loncommon::get_sections($cdom,$cnum);
 5959:                 my $newsecval;
 5960:                 if ($currsec ne 'none' && $currsec ne '') {
 5961:                     if (!defined($sections_count{$currsec})) {
 5962:                         $newsecval = $currsec;
 5963:                     }
 5964:                 }
 5965:                 if ($noedit{$item}) {
 5966:                     if ($currsec ne '') {
 5967:                         $output .= $currsec;
 5968:                     } else {
 5969:                         $output .= &mt('No specific section');
 5970:                     }
 5971:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 5972:                     next;
 5973:                 }
 5974:                 my $sections_select = 
 5975:                     &Apache::lonuserutils::course_sections(\%sections_count,'st',$currsec);
 5976:                 $output .= '<table class="LC_createuser">'."\n".
 5977:                            '<tr class="LC_section_row">'."\n".
 5978:                            '<td align="center">'.&mt('Existing sections')."\n".
 5979:                            '<br />'.$sections_select.'</td><td align="center">'.
 5980:                            &mt('New section').'<br />'."\n".
 5981:                            '<input type="text" name="newsec" size="15" value="'.$newsecval.'" />'."\n".
 5982:                            '<input type="hidden" name="sections" value="" />'."\n".
 5983:                            '</td></tr></table>'."\n";
 5984:             } elsif ($item eq 'approval') {
 5985:                 my ($currnotified,$currapproval,%appchecked);
 5986:                 my %selfdescs = &Apache::lonuserutils::selfenroll_default_descs();
 5987:                 if (ref($currsettings) eq 'HASH') { 
 5988:                     $currnotified = $currsettings->{'selfenroll_notifylist'};
 5989:                     $currapproval = $currsettings->{'selfenroll_approval'};
 5990:                 }
 5991:                 if ($currapproval !~ /^[012]$/) {
 5992:                     $currapproval = 0;
 5993:                 }
 5994:                 if ($noedit{$item}) {
 5995:                     $output .=  $selfdescs{'approval'}{$currapproval}.
 5996:                                 '<br />'.&mt('(Set by Domain Coordinator)');
 5997:                     next;
 5998:                 }
 5999:                 $appchecked{$currapproval} = ' checked="checked"';
 6000:                 for my $i (0..2) {
 6001:                     $output .= '<label>'.
 6002:                                '<input type="radio" name="selfenroll_approval" value="'.$i.'"'.
 6003:                                $appchecked{$i}.' onclick="toggleNotify();" />'.$selfdescs{'approval'}{$i}.
 6004:                                '</label>'.('&nbsp;'x2);
 6005:                 }
 6006:                 my %advhash = &Apache::lonnet::get_course_adv_roles($cid,1);
 6007:                 my (@ccs,%notified);
 6008:                 my $ccrole = 'cc';
 6009:                 if ($crstype eq 'Community') {
 6010:                     $ccrole = 'co';
 6011:                 }
 6012:                 if ($advhash{$ccrole}) {
 6013:                     @ccs = split(/,/,$advhash{$ccrole});
 6014:                 }
 6015:                 if ($currnotified) {
 6016:                     foreach my $current (split(/,/,$currnotified)) {
 6017:                         $notified{$current} = 1;
 6018:                         if (!grep(/^\Q$current\E$/,@ccs)) {
 6019:                             push(@ccs,$current);
 6020:                         }
 6021:                     }
 6022:                 }
 6023:                 if (@ccs) {
 6024:                     my $style;
 6025:                     unless ($currapproval) {
 6026:                         $style = ' style="display: none;"'; 
 6027:                     }
 6028:                     $output .= '<br /><div id="notified"'.$style.'>'.
 6029:                                &mt('Personnel to be notified when an enrollment request needs approval, or has been approved:').'&nbsp;'.
 6030:                                &Apache::loncommon::start_data_table().
 6031:                                &Apache::loncommon::start_data_table_row();
 6032:                     my $count = 0;
 6033:                     my $numcols = 4;
 6034:                     foreach my $cc (sort(@ccs)) {
 6035:                         my $notifyon;
 6036:                         my ($ccuname,$ccudom) = split(/:/,$cc);
 6037:                         if ($notified{$cc}) {
 6038:                             $notifyon = ' checked="checked" ';
 6039:                         }
 6040:                         if ($count && !$count%$numcols) {
 6041:                             $output .= &Apache::loncommon::end_data_table_row().
 6042:                                        &Apache::loncommon::start_data_table_row()
 6043:                         }
 6044:                         $output .= '<td><span class="LC_nobreak"><label>'.
 6045:                                    '<input type="checkbox" name="selfenroll_notify"'.$notifyon.' value="'.$cc.'" />'.
 6046:                                    &Apache::loncommon::plainname($ccuname,$ccudom).
 6047:                                    '</label></span></td>';
 6048:                         $count ++;
 6049:                     }
 6050:                     my $rem = $count%$numcols;
 6051:                     if ($rem) {
 6052:                         my $emptycols = $numcols - $rem;
 6053:                         for (my $i=0; $i<$emptycols; $i++) { 
 6054:                             $output .= '<td>&nbsp;</td>';
 6055:                         }
 6056:                     }
 6057:                     $output .= &Apache::loncommon::end_data_table_row().
 6058:                                &Apache::loncommon::end_data_table().
 6059:                                '</div>';
 6060:                 }
 6061:             } elsif ($item eq 'limit') {
 6062:                 my ($crslimit,$selflimit,$nolimit,$currlim,$currcap);
 6063:                 if (ref($currsettings) eq 'HASH') {
 6064:                     $currlim = $currsettings->{'selfenroll_limit'};
 6065:                     $currcap = $currsettings->{'selfenroll_cap'};
 6066:                 }
 6067:                 if ($noedit{$item}) {
 6068:                     if (($currlim eq 'allstudents') || ($currlim eq 'selfenrolled')) {
 6069:                         if ($currlim eq 'allstudents') {
 6070:                             $output .= &mt('Limit by total students');
 6071:                         } elsif ($currlim eq 'selfenrolled') {
 6072:                             $output .= &mt('Limit by total self-enrolled students');
 6073:                         }
 6074:                         $output .= ' '.&mt('Maximum: [_1]',$currcap).
 6075:                                    '<br />'.&mt('(Set by Domain Coordinator)');
 6076:                     } else {
 6077:                         $output .= &mt('No limit').'<br />'.&mt('(Set by Domain Coordinator)');
 6078:                     }
 6079:                     next;
 6080:                 }
 6081:                 if ($currlim eq 'allstudents') {
 6082:                     $crslimit = ' checked="checked" ';
 6083:                     $selflimit = ' ';
 6084:                     $nolimit = ' ';
 6085:                 } elsif ($currlim eq 'selfenrolled') {
 6086:                     $crslimit = ' ';
 6087:                     $selflimit = ' checked="checked" ';
 6088:                     $nolimit = ' '; 
 6089:                 } else {
 6090:                     $crslimit = ' ';
 6091:                     $selflimit = ' ';
 6092:                     $nolimit = ' checked="checked" ';
 6093:                 }
 6094:                 $output .= '<table><tr><td><label>'.
 6095:                            '<input type="radio" name="selfenroll_limit" value="none"'.$nolimit.'/>'.
 6096:                            &mt('No limit').'</label></td><td><label>'.
 6097:                            '<input type="radio" name="selfenroll_limit" value="allstudents"'.$crslimit.'/>'.
 6098:                            &mt('Limit by total students').'</label></td><td><label>'.
 6099:                            '<input type="radio" name="selfenroll_limit" value="selfenrolled"'.$selflimit.'/>'.
 6100:                            &mt('Limit by total self-enrolled students').
 6101:                            '</td></tr><tr>'.
 6102:                            '<td>&nbsp;</td><td colspan="2"><span class="LC_nobreak">'.
 6103:                            ('&nbsp;'x3).&mt('Maximum number allowed: ').
 6104:                            '<input type="text" name="selfenroll_cap" size = "5" value="'.$currcap.'" /></td></tr></table>';
 6105:             }
 6106:             $output .= &Apache::lonhtmlcommon::row_closure(1);
 6107:         }
 6108:     }
 6109:     $output .= &Apache::lonhtmlcommon::end_pick_box().
 6110:                '<br /><input type="button" name="selfenrollconf" value="'
 6111:                .&mt('Save').'" onclick="validate_types(this.form);" />'
 6112:                .'<input type="hidden" name="action" value="selfenroll" />'
 6113:                .'<input type="hidden" name="state" value="done" />'."\n".
 6114:                $additional.'</form>';
 6115:     $r->print($output);
 6116:     return;
 6117: }
 6118: 
 6119: sub get_noedit_fields {
 6120:     my ($cdom,$cnum,$crstype,$row) = @_;
 6121:     my %noedit;
 6122:     if (ref($row) eq 'ARRAY') {
 6123:         my %settings = &Apache::lonnet::get('environment',['internal.coursecode','internal.textbook',
 6124:                                                            'internal.selfenrollmgrdc',
 6125:                                                            'internal.selfenrollmgrcc'],$cdom,$cnum);
 6126:         my $type = &Apache::lonuserutils::get_extended_type($cdom,$cnum,$crstype,\%settings);
 6127:         my (%specific_managebydc,%specific_managebycc,%default_managebydc);
 6128:         map { $specific_managebydc{$_} = 1; } (split(/,/,$settings{'internal.selfenrollmgrdc'}));
 6129:         map { $specific_managebycc{$_} = 1; } (split(/,/,$settings{'internal.selfenrollmgrcc'}));
 6130:         my %domdefaults = &Apache::lonnet::get_domain_defaults($cdom);
 6131:         map { $default_managebydc{$_} = 1; } (split(/,/,$domdefaults{$type.'selfenrolladmdc'}));
 6132: 
 6133:         foreach my $item (@{$row}) {
 6134:             next if ($specific_managebycc{$item});
 6135:             if (($specific_managebydc{$item}) || ($default_managebydc{$item})) {
 6136:                 $noedit{$item} = 1;
 6137:             }
 6138:         }
 6139:     }
 6140:     return %noedit;
 6141: } 
 6142: 
 6143: sub visible_in_stdcat {
 6144:     my ($cdom,$cnum,$domconf) = @_;
 6145:     my ($cathash,%settable,@vismsgs,$cansetvis,$visible);
 6146:     unless (ref($domconf) eq 'HASH') {
 6147:         return ($visible,$cansetvis,\@vismsgs);
 6148:     }
 6149:     if (ref($domconf->{'coursecategories'}) eq 'HASH') {
 6150:         if ($domconf->{'coursecategories'}{'togglecats'} eq 'crs') {
 6151:             $settable{'togglecats'} = 1;
 6152:         }
 6153:         if ($domconf->{'coursecategories'}{'categorize'} eq 'crs') {
 6154:             $settable{'categorize'} = 1;
 6155:         }
 6156:         $cathash = $domconf->{'coursecategories'}{'cats'};
 6157:     }
 6158:     if ($settable{'togglecats'} && $settable{'categorize'}) {
 6159:         $cansetvis = &mt('You are able to both assign a course category and choose to exclude this course from the catalog.');   
 6160:     } elsif ($settable{'togglecats'}) {
 6161:         $cansetvis = &mt('You are able to choose to exclude this course from the catalog, but only a Domain Coordinator may assign a course category.'); 
 6162:     } elsif ($settable{'categorize'}) {
 6163:         $cansetvis = &mt('You may assign a course category, but only a Domain Coordinator may choose to exclude this course from the catalog.');  
 6164:     } else {
 6165:         $cansetvis = &mt('Only a Domain Coordinator may assign a course category or choose to exclude this course from the catalog.'); 
 6166:     }
 6167:      
 6168:     my %currsettings =
 6169:         &Apache::lonnet::get('environment',['hidefromcat','categories','internal.coursecode'],
 6170:                              $cdom,$cnum);
 6171:     $visible = 0;
 6172:     if ($currsettings{'internal.coursecode'} ne '') {
 6173:         if (ref($domconf->{'coursecategories'}) eq 'HASH') {
 6174:             $cathash = $domconf->{'coursecategories'}{'cats'};
 6175:             if (ref($cathash) eq 'HASH') {
 6176:                 if ($cathash->{'instcode::0'} eq '') {
 6177:                     push(@vismsgs,'dc_addinst'); 
 6178:                 } else {
 6179:                     $visible = 1;
 6180:                 }
 6181:             } else {
 6182:                 $visible = 1;
 6183:             }
 6184:         } else {
 6185:             $visible = 1;
 6186:         }
 6187:     } else {
 6188:         if (ref($cathash) eq 'HASH') {
 6189:             if ($cathash->{'instcode::0'} ne '') {
 6190:                 push(@vismsgs,'dc_instcode');
 6191:             }
 6192:         } else {
 6193:             push(@vismsgs,'dc_instcode');
 6194:         }
 6195:     }
 6196:     if ($currsettings{'categories'} ne '') {
 6197:         my $cathash;
 6198:         if (ref($domconf->{'coursecategories'}) eq 'HASH') {
 6199:             $cathash = $domconf->{'coursecategories'}{'cats'};
 6200:             if (ref($cathash) eq 'HASH') {
 6201:                 if (keys(%{$cathash}) == 0) {
 6202:                     push(@vismsgs,'dc_catalog');
 6203:                 } elsif ((keys(%{$cathash}) == 1) && ($cathash->{'instcode::0'} ne '')) {
 6204:                     push(@vismsgs,'dc_categories');
 6205:                 } else {
 6206:                     my @currcategories = split('&',$currsettings{'categories'});
 6207:                     my $matched = 0;
 6208:                     foreach my $cat (@currcategories) {
 6209:                         if ($cathash->{$cat} ne '') {
 6210:                             $visible = 1;
 6211:                             $matched = 1;
 6212:                             last;
 6213:                         }
 6214:                     }
 6215:                     if (!$matched) {
 6216:                         if ($settable{'categorize'}) { 
 6217:                             push(@vismsgs,'chgcat');
 6218:                         } else {
 6219:                             push(@vismsgs,'dc_chgcat');
 6220:                         }
 6221:                     }
 6222:                 }
 6223:             }
 6224:         }
 6225:     } else {
 6226:         if (ref($cathash) eq 'HASH') {
 6227:             if ((keys(%{$cathash}) > 1) || 
 6228:                 (keys(%{$cathash}) == 1) && ($cathash->{'instcode::0'} eq '')) {
 6229:                 if ($settable{'categorize'}) {
 6230:                     push(@vismsgs,'addcat');
 6231:                 } else {
 6232:                     push(@vismsgs,'dc_addcat');
 6233:                 }
 6234:             }
 6235:         }
 6236:     }
 6237:     if ($currsettings{'hidefromcat'} eq 'yes') {
 6238:         $visible = 0;
 6239:         if ($settable{'togglecats'}) {
 6240:             unshift(@vismsgs,'unhide');
 6241:         } else {
 6242:             unshift(@vismsgs,'dc_unhide')
 6243:         }
 6244:     }
 6245:     return ($visible,$cansetvis,\@vismsgs);
 6246: }
 6247: 
 6248: sub cat_visibility {
 6249:     my %visactions = &Apache::lonlocal::texthash(
 6250:                    vis => 'This course/community currently appears in the Course/Community Catalog for this domain.',
 6251:                    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.',
 6252:                    miss => 'This course/community does not currently appear in the Course/Community Catalog for this domain.',
 6253:                    none => 'Display of a course catalog is disabled for this domain.',
 6254:                    yous => 'You should remedy this if you plan to allow self-enrollment, otherwise students will have difficulty finding this course.',
 6255:                    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.',
 6256:                    make => 'Make any changes to self-enrollment settings below, click "Save", then take action to include the course in the Catalog:',
 6257:                    take => 'Take the following action to ensure the course appears in the Catalog:',
 6258:                    dc_chgconf => 'Ask a domain coordinator to change the Catalog type for this domain.',
 6259:                    dc_setcode => 'Ask a domain coordinator to assign a six character code to the course',
 6260:                    dc_unhide  => 'Ask a domain coordinator to change the "Exclude from course catalog" setting.',
 6261:                    dc_addinst => 'Ask a domain coordinator to enable display the catalog of "Official courses (with institutional codes)".',
 6262:                    dc_instcode => 'Ask a domain coordinator to assign an institutional code (if this is an official course).',
 6263:                    dc_catalog  => 'Ask a domain coordinator to enable or create at least one course category in the domain.',
 6264:                    dc_categories => 'Ask a domain coordinator to create a hierarchy of categories and sub categories for courses in the domain.',
 6265:                    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',
 6266:                    dc_addcat => 'Ask a domain coordinator to assign a category to the course.',
 6267:     );
 6268:     $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>"');
 6269:     $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>"');
 6270:     $visactions{'addcat'} = &mt('Use [_1]Categorize course[_2] to assign a category to the course.','"<a href="/adm/courseprefs?phase=display&actions=courseinfo">','</a>"');
 6271:     return \%visactions;
 6272: }
 6273: 
 6274: sub new_selfenroll_dom_row {
 6275:     my ($newdom,$num) = @_;
 6276:     my $domdesc = &Apache::lonnet::domain($newdom);
 6277:     my $output;
 6278:     if ($domdesc ne '') {
 6279:         $output .= &Apache::loncommon::start_data_table_row()
 6280:                    .'<td valign="top"><span class="LC_nobreak">'.&mt('Domain:').'&nbsp;<b>'.$domdesc
 6281:                    .' ('.$newdom.')</b><input type="hidden" name="selfenroll_dom_'.$num
 6282:                    .'" value="'.$newdom.'" /></span><br />'
 6283:                    .'<span class="LC_nobreak"><label><input type="checkbox" '
 6284:                    .'name="selfenroll_activate" value="'.$num.'" '
 6285:                    .'onchange="javascript:update_types('
 6286:                    ."'selfenroll_activate','$num'".');" />'
 6287:                    .&mt('Activate').'</label></span></td>';
 6288:         my @currinsttypes;
 6289:         $output .= '<td>'.&mt('User types:').'<br />'
 6290:                    .&selfenroll_inst_types($num,$newdom,\@currinsttypes).'</td>'
 6291:                    .&Apache::loncommon::end_data_table_row();
 6292:     }
 6293:     return $output;
 6294: }
 6295: 
 6296: sub selfenroll_inst_types {
 6297:     my ($num,$currdom,$currinsttypes) = @_;
 6298:     my $output;
 6299:     my $numinrow = 4;
 6300:     my $count = 0;
 6301:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($currdom);
 6302:     my $othervalue = 'any';
 6303:     if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 6304:         if (keys(%{$usertypes}) > 0) {
 6305:             $othervalue = 'other';
 6306:         }
 6307:         $output .= '<table><tr>';
 6308:         foreach my $type (@{$types}) {
 6309:             if (($count > 0) && ($count%$numinrow == 0)) {
 6310:                 $output .= '</tr><tr>';
 6311:             }
 6312:             if (defined($usertypes->{$type})) {
 6313:                 my $esc_type = &escape($type);
 6314:                 $output .= '<td><span class="LC_nobreak"><label><input type = "checkbox" value="'.
 6315:                            $esc_type.'" ';
 6316:                 if (ref($currinsttypes) eq 'ARRAY') {
 6317:                     if (@{$currinsttypes} > 0) {
 6318:                         if (grep(/^any$/,@{$currinsttypes})) {
 6319:                             $output .= 'checked="checked"';
 6320:                         } elsif (grep(/^\Q$esc_type\E$/,@{$currinsttypes})) {
 6321:                             $output .= 'checked="checked"';
 6322:                         }
 6323:                     } else {
 6324:                         $output .= 'checked="checked"';
 6325:                     }
 6326:                 }
 6327:                 $output .= ' name="selfenroll_types_'.$num.'" />'.$usertypes->{$type}.'</label></span></td>';
 6328:             }
 6329:             $count ++;
 6330:         }
 6331:         if (($count > 0) && ($count%$numinrow == 0)) {
 6332:             $output .= '</tr><tr>';
 6333:         }
 6334:         $output .= '<td><span class="LC_nobreak"><label><input type = "checkbox" value="'.$othervalue.'"';
 6335:         if (ref($currinsttypes) eq 'ARRAY') {
 6336:             if (@{$currinsttypes} > 0) {
 6337:                 if (grep(/^any$/,@{$currinsttypes})) { 
 6338:                     $output .= ' checked="checked"';
 6339:                 } elsif ($othervalue eq 'other') {
 6340:                     if (grep(/^\Q$othervalue\E$/,@{$currinsttypes})) {
 6341:                         $output .= ' checked="checked"';
 6342:                     }
 6343:                 }
 6344:             } else {
 6345:                 $output .= ' checked="checked"';
 6346:             }
 6347:         } else {
 6348:             $output .= ' checked="checked"';
 6349:         }
 6350:         $output .= ' name="selfenroll_types_'.$num.'" />'.$othertitle.'</label></span></td></tr></table>';
 6351:     }
 6352:     return $output;
 6353: }
 6354: 
 6355: sub selfenroll_date_forms {
 6356:     my ($startform,$endform) = @_;
 6357:     my $output .= &Apache::lonhtmlcommon::start_pick_box()."\n".
 6358:                   &Apache::lonhtmlcommon::row_title(&mt('Start date'),
 6359:                                                     'LC_oddrow_value')."\n".
 6360:                   $startform."\n".
 6361:                   &Apache::lonhtmlcommon::row_closure(1).
 6362:                   &Apache::lonhtmlcommon::row_title(&mt('End date'),
 6363:                                                    'LC_oddrow_value')."\n".
 6364:                   $endform."\n".
 6365:                   &Apache::lonhtmlcommon::row_closure(1).
 6366:                   &Apache::lonhtmlcommon::end_pick_box();
 6367:     return $output;
 6368: }
 6369: 
 6370: sub print_userchangelogs_display {
 6371:     my ($r,$context,$permission,$brcrum) = @_;
 6372:     my $formname = 'rolelog';
 6373:     my ($username,$domain,$crstype,%roleslog);
 6374:     if ($context eq 'domain') {
 6375:         $domain = $env{'request.role.domain'};
 6376:         %roleslog=&Apache::lonnet::dump_dom('nohist_rolelog',$domain);
 6377:     } else {
 6378:         if ($context eq 'course') { 
 6379:             $domain = $env{'course.'.$env{'request.course.id'}.'.domain'};
 6380:             $username = $env{'course.'.$env{'request.course.id'}.'.num'};
 6381:             $crstype = &Apache::loncommon::course_type();
 6382:             my %saveable_parameters = ('show' => 'scalar',);
 6383:             &Apache::loncommon::store_course_settings('roles_log',
 6384:                                                       \%saveable_parameters);
 6385:             &Apache::loncommon::restore_course_settings('roles_log',
 6386:                                                         \%saveable_parameters);
 6387:         } elsif ($context eq 'author') {
 6388:             $domain = $env{'user.domain'}; 
 6389:             if ($env{'request.role'} =~ m{^au\./\Q$domain\E/$}) {
 6390:                 $username = $env{'user.name'};
 6391:             } else {
 6392:                 undef($domain);
 6393:             }
 6394:         }
 6395:         if ($domain ne '' && $username ne '') { 
 6396:             %roleslog=&Apache::lonnet::dump('nohist_rolelog',$domain,$username);
 6397:         }
 6398:     }
 6399:     if ((keys(%roleslog))[0]=~/^error\:/) { undef(%roleslog); }
 6400: 
 6401:     my $helpitem;
 6402:     if ($context eq 'course') {
 6403:         $helpitem = 'Course_User_Logs';
 6404:     }
 6405:     push (@{$brcrum},
 6406:              {href => '/adm/createuser?action=changelogs',
 6407:               text => 'User Management Logs',
 6408:               help => $helpitem});
 6409:     my $bread_crumbs_component = 'User Changes';
 6410:     my $args = { bread_crumbs           => $brcrum,
 6411:                  bread_crumbs_component => $bread_crumbs_component};
 6412: 
 6413:     # Create navigation javascript
 6414:     my $jsnav = &userlogdisplay_js($formname);
 6415: 
 6416:     my $jscript = (<<ENDSCRIPT);
 6417: <script type="text/javascript">
 6418: // <![CDATA[
 6419: $jsnav
 6420: // ]]>
 6421: </script>
 6422: ENDSCRIPT
 6423: 
 6424:     # print page header
 6425:     $r->print(&header($jscript,$args));
 6426: 
 6427:     # set defaults
 6428:     my $now = time();
 6429:     my $defstart = $now - (7*24*3600); #7 days ago 
 6430:     my %defaults = (
 6431:                      page               => '1',
 6432:                      show               => '10',
 6433:                      role               => 'any',
 6434:                      chgcontext         => 'any',
 6435:                      rolelog_start_date => $defstart,
 6436:                      rolelog_end_date   => $now,
 6437:                    );
 6438:     my $more_records = 0;
 6439: 
 6440:     # set current
 6441:     my %curr;
 6442:     foreach my $item ('show','page','role','chgcontext') {
 6443:         $curr{$item} = $env{'form.'.$item};
 6444:     }
 6445:     my ($startdate,$enddate) = 
 6446:         &Apache::lonuserutils::get_dates_from_form('rolelog_start_date','rolelog_end_date');
 6447:     $curr{'rolelog_start_date'} = $startdate;
 6448:     $curr{'rolelog_end_date'} = $enddate;
 6449:     foreach my $key (keys(%defaults)) {
 6450:         if ($curr{$key} eq '') {
 6451:             $curr{$key} = $defaults{$key};
 6452:         }
 6453:     }
 6454:     my (%whodunit,%changed,$version);
 6455:     ($version) = ($r->dir_config('lonVersion') =~ /^([\d\.]+)\-/);
 6456:     my ($minshown,$maxshown);
 6457:     $minshown = 1;
 6458:     my $count = 0;
 6459:     if ($curr{'show'} =~ /\D/) {
 6460:         $curr{'page'} = 1;
 6461:     } else {
 6462:         $maxshown = $curr{'page'} * $curr{'show'};
 6463:         if ($curr{'page'} > 1) {
 6464:             $minshown = 1 + ($curr{'page'} - 1) * $curr{'show'};
 6465:         }
 6466:     }
 6467: 
 6468:     # Form Header
 6469:     $r->print('<form action="/adm/createuser" method="post" name="'.$formname.'">'.
 6470:               &role_display_filter($context,$formname,$domain,$username,\%curr,
 6471:                                    $version,$crstype));
 6472: 
 6473:     my $showntableheader = 0;
 6474: 
 6475:     # Table Header
 6476:     my $tableheader = 
 6477:         &Apache::loncommon::start_data_table_header_row()
 6478:        .'<th>&nbsp;</th>'
 6479:        .'<th>'.&mt('When').'</th>'
 6480:        .'<th>'.&mt('Who made the change').'</th>'
 6481:        .'<th>'.&mt('Changed User').'</th>'
 6482:        .'<th>'.&mt('Role').'</th>';
 6483: 
 6484:     if ($context eq 'course') {
 6485:         $tableheader .= '<th>'.&mt('Section').'</th>';
 6486:     }
 6487:     $tableheader .=
 6488:         '<th>'.&mt('Context').'</th>'
 6489:        .'<th>'.&mt('Start').'</th>'
 6490:        .'<th>'.&mt('End').'</th>'
 6491:        .&Apache::loncommon::end_data_table_header_row();
 6492: 
 6493:     # Display user change log data
 6494:     foreach my $id (sort { $roleslog{$b}{'exe_time'}<=>$roleslog{$a}{'exe_time'} } (keys(%roleslog))) {
 6495:         next if (($roleslog{$id}{'exe_time'} < $curr{'rolelog_start_date'}) ||
 6496:                  ($roleslog{$id}{'exe_time'} > $curr{'rolelog_end_date'}));
 6497:         if ($curr{'show'} !~ /\D/) {
 6498:             if ($count >= $curr{'page'} * $curr{'show'}) {
 6499:                 $more_records = 1;
 6500:                 last;
 6501:             }
 6502:         }
 6503:         if ($curr{'role'} ne 'any') {
 6504:             next if ($roleslog{$id}{'logentry'}{'role'} ne $curr{'role'}); 
 6505:         }
 6506:         if ($curr{'chgcontext'} ne 'any') {
 6507:             if ($curr{'chgcontext'} eq 'selfenroll') {
 6508:                 next if (!$roleslog{$id}{'logentry'}{'selfenroll'});
 6509:             } else {
 6510:                 next if ($roleslog{$id}{'logentry'}{'context'} ne $curr{'chgcontext'});
 6511:             }
 6512:         }
 6513:         $count ++;
 6514:         next if ($count < $minshown);
 6515:         unless ($showntableheader) {
 6516:             $r->print(&Apache::loncommon::start_data_table()
 6517:                      .$tableheader);
 6518:             $r->rflush();
 6519:             $showntableheader = 1;
 6520:         }
 6521:         if ($whodunit{$roleslog{$id}{'exe_uname'}.':'.$roleslog{$id}{'exe_udom'}} eq '') {
 6522:             $whodunit{$roleslog{$id}{'exe_uname'}.':'.$roleslog{$id}{'exe_udom'}} =
 6523:                 &Apache::loncommon::plainname($roleslog{$id}{'exe_uname'},$roleslog{$id}{'exe_udom'});
 6524:         }
 6525:         if ($changed{$roleslog{$id}{'uname'}.':'.$roleslog{$id}{'udom'}} eq '') {
 6526:             $changed{$roleslog{$id}{'uname'}.':'.$roleslog{$id}{'udom'}} =
 6527:                 &Apache::loncommon::plainname($roleslog{$id}{'uname'},$roleslog{$id}{'udom'});
 6528:         }
 6529:         my $sec = $roleslog{$id}{'logentry'}{'section'};
 6530:         if ($sec eq '') {
 6531:             $sec = &mt('None');
 6532:         }
 6533:         my ($rolestart,$roleend);
 6534:         if ($roleslog{$id}{'delflag'}) {
 6535:             $rolestart = &mt('deleted');
 6536:             $roleend = &mt('deleted');
 6537:         } else {
 6538:             $rolestart = $roleslog{$id}{'logentry'}{'start'};
 6539:             $roleend = $roleslog{$id}{'logentry'}{'end'};
 6540:             if ($rolestart eq '' || $rolestart == 0) {
 6541:                 $rolestart = &mt('No start date'); 
 6542:             } else {
 6543:                 $rolestart = &Apache::lonlocal::locallocaltime($rolestart);
 6544:             }
 6545:             if ($roleend eq '' || $roleend == 0) { 
 6546:                 $roleend = &mt('No end date');
 6547:             } else {
 6548:                 $roleend = &Apache::lonlocal::locallocaltime($roleend);
 6549:             }
 6550:         }
 6551:         my $chgcontext = $roleslog{$id}{'logentry'}{'context'};
 6552:         if ($roleslog{$id}{'logentry'}{'selfenroll'}) {
 6553:             $chgcontext = 'selfenroll';
 6554:         }
 6555:         my %lt = &rolechg_contexts($context,$crstype);
 6556:         if ($chgcontext ne '' && $lt{$chgcontext} ne '') {
 6557:             $chgcontext = $lt{$chgcontext};
 6558:         }
 6559:         $r->print(
 6560:             &Apache::loncommon::start_data_table_row()
 6561:            .'<td>'.$count.'</td>'
 6562:            .'<td>'.&Apache::lonlocal::locallocaltime($roleslog{$id}{'exe_time'}).'</td>'
 6563:            .'<td>'.$whodunit{$roleslog{$id}{'exe_uname'}.':'.$roleslog{$id}{'exe_udom'}}.'</td>'
 6564:            .'<td>'.$changed{$roleslog{$id}{'uname'}.':'.$roleslog{$id}{'udom'}}.'</td>'
 6565:            .'<td>'.&Apache::lonnet::plaintext($roleslog{$id}{'logentry'}{'role'},$crstype).'</td>');
 6566:         if ($context eq 'course') { 
 6567:             $r->print('<td>'.$sec.'</td>');
 6568:         }
 6569:         $r->print(
 6570:             '<td>'.$chgcontext.'</td>'
 6571:            .'<td>'.$rolestart.'</td>'
 6572:            .'<td>'.$roleend.'</td>'
 6573:            .&Apache::loncommon::end_data_table_row()."\n");
 6574:     }
 6575: 
 6576:     if ($showntableheader) { # Table footer, if content displayed above
 6577:         $r->print(&Apache::loncommon::end_data_table().
 6578:                   &userlogdisplay_navlinks(\%curr,$more_records));
 6579:     } else { # No content displayed above
 6580:         $r->print('<p class="LC_info">'
 6581:                  .&mt('There are no records to display.')
 6582:                  .'</p>'
 6583:         );
 6584:     }
 6585: 
 6586:     # Form Footer
 6587:     $r->print( 
 6588:         '<input type="hidden" name="page" value="'.$curr{'page'}.'" />'
 6589:        .'<input type="hidden" name="action" value="changelogs" />'
 6590:        .'</form>');
 6591:     return;
 6592: }
 6593: 
 6594: sub userlogdisplay_js {
 6595:     my ($formname) = @_;
 6596:     return <<"ENDSCRIPT";
 6597: 
 6598: function chgPage(caller) {
 6599:     if (caller == 'previous') {
 6600:         document.$formname.page.value --;
 6601:     }
 6602:     if (caller == 'next') {
 6603:         document.$formname.page.value ++;
 6604:     }
 6605:     document.$formname.submit();
 6606:     return;
 6607: }
 6608: ENDSCRIPT
 6609: }
 6610: 
 6611: sub userlogdisplay_navlinks {
 6612:     my ($curr,$more_records) = @_;
 6613:     return unless(ref($curr) eq 'HASH');
 6614:     # Navigation Buttons
 6615:     my $nav_links = '<p>';
 6616:     if (($curr->{'page'} > 1) || ($more_records)) {
 6617:         if (($curr->{'page'} > 1) && ($curr->{'show'} !~ /\D/)) {
 6618:             $nav_links .= '<input type="button"'
 6619:                          .' onclick="javascript:chgPage('."'previous'".');"'
 6620:                          .' value="'.&mt('Previous [_1] changes',$curr->{'show'})
 6621:                          .'" /> ';
 6622:         }
 6623:         if ($more_records) {
 6624:             $nav_links .= '<input type="button"'
 6625:                          .' onclick="javascript:chgPage('."'next'".');"'
 6626:                          .' value="'.&mt('Next [_1] changes',$curr->{'show'})
 6627:                          .'" />';
 6628:         }
 6629:     }
 6630:     $nav_links .= '</p>';
 6631:     return $nav_links;
 6632: }
 6633: 
 6634: sub role_display_filter {
 6635:     my ($context,$formname,$cdom,$cnum,$curr,$version,$crstype) = @_;
 6636:     my $lctype;
 6637:     if ($context eq 'course') {
 6638:         $lctype = lc($crstype);
 6639:     }
 6640:     my $nolink = 1;
 6641:     my $output = '<table><tr><td valign="top">'.
 6642:                  '<span class="LC_nobreak"><b>'.&mt('Changes/page:').'</b></span><br />'.
 6643:                  &Apache::lonmeta::selectbox('show',$curr->{'show'},undef,
 6644:                                               (&mt('all'),5,10,20,50,100,1000,10000)).
 6645:                  '</td><td>&nbsp;&nbsp;</td>';
 6646:     my $startform =
 6647:         &Apache::lonhtmlcommon::date_setter($formname,'rolelog_start_date',
 6648:                                             $curr->{'rolelog_start_date'},undef,
 6649:                                             undef,undef,undef,undef,undef,undef,$nolink);
 6650:     my $endform =
 6651:         &Apache::lonhtmlcommon::date_setter($formname,'rolelog_end_date',
 6652:                                             $curr->{'rolelog_end_date'},undef,
 6653:                                             undef,undef,undef,undef,undef,undef,$nolink);
 6654:     my %lt = &rolechg_contexts($context,$crstype);
 6655:     $output .= '<td valign="top"><b>'.&mt('Window during which changes occurred:').'</b><br />'.
 6656:                '<table><tr><td>'.&mt('After:').
 6657:                '</td><td>'.$startform.'</td></tr>'.
 6658:                '<tr><td>'.&mt('Before:').'</td>'.
 6659:                '<td>'.$endform.'</td></tr></table>'.
 6660:                '</td>'.
 6661:                '<td>&nbsp;&nbsp;</td>'.
 6662:                '<td valign="top"><b>'.&mt('Role:').'</b><br />'.
 6663:                '<select name="role"><option value="any"';
 6664:     if ($curr->{'role'} eq 'any') {
 6665:         $output .= ' selected="selected"';
 6666:     }
 6667:     $output .=  '>'.&mt('Any').'</option>'."\n";
 6668:     my @roles = &Apache::lonuserutils::roles_by_context($context,1,$crstype);
 6669:     foreach my $role (@roles) {
 6670:         my $plrole;
 6671:         if ($role eq 'cr') {
 6672:             $plrole = &mt('Custom Role');
 6673:         } else {
 6674:             $plrole=&Apache::lonnet::plaintext($role,$crstype);
 6675:         }
 6676:         my $selstr = '';
 6677:         if ($role eq $curr->{'role'}) {
 6678:             $selstr = ' selected="selected"';
 6679:         }
 6680:         $output .= '  <option value="'.$role.'"'.$selstr.'>'.$plrole.'</option>';
 6681:     }
 6682:     $output .= '</select></td>'.
 6683:                '<td>&nbsp;&nbsp;</td>'.
 6684:                '<td valign="top"><b>'.
 6685:                &mt('Context:').'</b><br /><select name="chgcontext">';
 6686:     my @posscontexts;
 6687:     if ($context eq 'course') {
 6688:         @posscontexts = ('any','automated','updatenow','createcourse','course','domain','selfenroll','requestcourses');
 6689:     } elsif ($context eq 'domain') {
 6690:         @posscontexts = ('any','domain','requestauthor','domconfig','server');
 6691:     } else {
 6692:         @posscontexts = ('any','author','domain');
 6693:     } 
 6694:     foreach my $chgtype (@posscontexts) {
 6695:         my $selstr = '';
 6696:         if ($curr->{'chgcontext'} eq $chgtype) {
 6697:             $selstr = ' selected="selected"';
 6698:         }
 6699:         if ($context eq 'course') {
 6700:             if (($chgtype eq 'automated') || ($chgtype eq 'updatenow')) {
 6701:                 next if (!&Apache::lonnet::auto_run($cnum,$cdom));
 6702:             }
 6703:         }
 6704:         $output .= '<option value="'.$chgtype.'"'.$selstr.'>'.$lt{$chgtype}.'</option>'."\n";
 6705:     }
 6706:     $output .= '</select></td>'
 6707:               .'</tr></table>';
 6708: 
 6709:     # Update Display button
 6710:     $output .= '<p>'
 6711:               .'<input type="submit" value="'.&mt('Update Display').'" />'
 6712:               .'</p>';
 6713: 
 6714:     # Server version info
 6715:     my $needsrev = '2.11.0';
 6716:     if ($context eq 'course') {
 6717:         $needsrev = '2.7.0';
 6718:     }
 6719:     
 6720:     $output .= '<p class="LC_info">'
 6721:               .&mt('Only changes made from servers running LON-CAPA [_1] or later are displayed.'
 6722:                   ,$needsrev);
 6723:     if ($version) {
 6724:         $output .= ' '.&mt('This LON-CAPA server is version [_1]',$version);
 6725:     }
 6726:     $output .= '</p><hr />';
 6727:     return $output;
 6728: }
 6729: 
 6730: sub rolechg_contexts {
 6731:     my ($context,$crstype) = @_;
 6732:     my %lt;
 6733:     if ($context eq 'course') {
 6734:         %lt = &Apache::lonlocal::texthash (
 6735:                                              any          => 'Any',
 6736:                                              automated    => 'Automated Enrollment',
 6737:                                              updatenow    => 'Roster Update',
 6738:                                              createcourse => 'Course Creation',
 6739:                                              course       => 'User Management in course',
 6740:                                              domain       => 'User Management in domain',
 6741:                                              selfenroll   => 'Self-enrolled',
 6742:                                              requestcourses => 'Course Request',
 6743:                                          );
 6744:         if ($crstype eq 'Community') {
 6745:             $lt{'createcourse'} = &mt('Community Creation');
 6746:             $lt{'course'} = &mt('User Management in community');
 6747:             $lt{'requestcourses'} = &mt('Community Request');
 6748:         }
 6749:     } elsif ($context eq 'domain') {
 6750:         %lt = &Apache::lonlocal::texthash (
 6751:                                              any           => 'Any',
 6752:                                              domain        => 'User Management in domain',
 6753:                                              requestauthor => 'Authoring Request',
 6754:                                              server        => 'Command line script (DC role)',
 6755:                                              domconfig     => 'Self-enrolled',
 6756:                                          );
 6757:     } else {
 6758:         %lt = &Apache::lonlocal::texthash (
 6759:                                              any    => 'Any',
 6760:                                              domain => 'User Management in domain',
 6761:                                              author => 'User Management by author',
 6762:                                          );
 6763:     } 
 6764:     return %lt;
 6765: }
 6766: 
 6767: #-------------------------------------------------- functions for &phase_two
 6768: sub user_search_result {
 6769:     my ($context,$srch) = @_;
 6770:     my %allhomes;
 6771:     my %inst_matches;
 6772:     my %srch_results;
 6773:     my ($response,$currstate,$forcenewuser,$dirsrchres);
 6774:     $srch->{'srchterm'} =~ s/\s+/ /g;
 6775:     if ($srch->{'srchby'} !~ /^(uname|lastname|lastfirst)$/) {
 6776:         $response = &mt('Invalid search.');
 6777:     }
 6778:     if ($srch->{'srchin'} !~ /^(crs|dom|alc|instd)$/) {
 6779:         $response = &mt('Invalid search.');
 6780:     }
 6781:     if ($srch->{'srchtype'} !~ /^(exact|contains|begins)$/) {
 6782:         $response = &mt('Invalid search.');
 6783:     }
 6784:     if ($srch->{'srchterm'} eq '') {
 6785:         $response = &mt('You must enter a search term.');
 6786:     }
 6787:     if ($srch->{'srchterm'} =~ /^\s+$/) {
 6788:         $response = &mt('Your search term must contain more than just spaces.');
 6789:     }
 6790:     if (($srch->{'srchin'} eq 'dom') || ($srch->{'srchin'} eq 'instd')) {
 6791:         if (($srch->{'srchdomain'} eq '') || 
 6792: 	    ! (&Apache::lonnet::domain($srch->{'srchdomain'}))) {
 6793:             $response = &mt('You must specify a valid domain when searching in a domain or institutional directory.')
 6794:         }
 6795:     }
 6796:     if (($srch->{'srchin'} eq 'dom') || ($srch->{'srchin'} eq 'crs') ||
 6797:         ($srch->{'srchin'} eq 'alc')) {
 6798:         if ($srch->{'srchby'} eq 'uname') {
 6799:             my $unamecheck = $srch->{'srchterm'};
 6800:             if ($srch->{'srchtype'} eq 'contains') {
 6801:                 if ($unamecheck !~ /^\w/) {
 6802:                     $unamecheck = 'a'.$unamecheck; 
 6803:                 }
 6804:             }
 6805:             if ($unamecheck !~ /^$match_username$/) {
 6806:                 $response = &mt('You must specify a valid username. Only the following are allowed: letters numbers - . @');
 6807:             }
 6808:         }
 6809:     }
 6810:     if ($response ne '') {
 6811:         $response = '<span class="LC_warning">'.$response.'</span><br />';
 6812:     }
 6813:     if ($srch->{'srchin'} eq 'instd') {
 6814:         my $instd_chk = &instdirectorysrch_check($srch);
 6815:         if ($instd_chk ne 'ok') {
 6816:             my $domd_chk = &domdirectorysrch_check($srch);
 6817:             $response .= '<span class="LC_warning">'.$instd_chk.'</span><br />';
 6818:             if ($domd_chk eq 'ok') {
 6819:                 $response .= &mt('You may want to search in the LON-CAPA domain instead of the institutional directory.');
 6820:             }
 6821:             $response .= '<br />';
 6822:         }
 6823:     } else {
 6824:         unless (($context eq 'requestcrs') && ($srch->{'srchtype'} eq 'exact')) { 
 6825:             my $domd_chk = &domdirectorysrch_check($srch);
 6826:             if ($domd_chk ne 'ok') {
 6827:                 my $instd_chk = &instdirectorysrch_check($srch);
 6828:                 $response .= '<span class="LC_warning">'.$domd_chk.'</span><br />';
 6829:                 if ($instd_chk eq 'ok') {
 6830:                     $response .= &mt('You may want to search in the institutional directory instead of the LON-CAPA domain.');
 6831:                 }
 6832:                 $response .= '<br />';
 6833:             }
 6834:         }
 6835:     }
 6836:     if ($response ne '') {
 6837:         return ($currstate,$response);
 6838:     }
 6839:     if ($srch->{'srchby'} eq 'uname') {
 6840:         if (($srch->{'srchin'} eq 'dom') || ($srch->{'srchin'} eq 'crs')) {
 6841:             if ($env{'form.forcenew'}) {
 6842:                 if ($srch->{'srchdomain'} ne $env{'request.role.domain'}) {
 6843:                     my $uhome=&Apache::lonnet::homeserver($srch->{'srchterm'},$srch->{'srchdomain'});
 6844:                     if ($uhome eq 'no_host') {
 6845:                         my $domdesc = &Apache::lonnet::domain($env{'request.role.domain'},'description');
 6846:                         my $showdom = &display_domain_info($env{'request.role.domain'});
 6847:                         $response = &mt('New users can only be created in the domain to which your current role belongs - [_1].',$showdom);
 6848:                     } else {
 6849:                         $currstate = 'modify';
 6850:                     }
 6851:                 } else {
 6852:                     $currstate = 'modify';
 6853:                 }
 6854:             } else {
 6855:                 if ($srch->{'srchin'} eq 'dom') {
 6856:                     if ($srch->{'srchtype'} eq 'exact') {
 6857:                         my $uhome=&Apache::lonnet::homeserver($srch->{'srchterm'},$srch->{'srchdomain'});
 6858:                         if ($uhome eq 'no_host') {
 6859:                             ($currstate,$response,$forcenewuser) =
 6860:                                 &build_search_response($context,$srch,%srch_results);
 6861:                         } else {
 6862:                             $currstate = 'modify';
 6863:                             my $uname = $srch->{'srchterm'};
 6864:                             my $udom = $srch->{'srchdomain'};
 6865:                             $srch_results{$uname.':'.$udom} =
 6866:                                 { &Apache::lonnet::get('environment',
 6867:                                                        ['firstname',
 6868:                                                         'lastname',
 6869:                                                         'permanentemail'],
 6870:                                                          $udom,$uname)
 6871:                                 };
 6872:                         }
 6873:                     } else {
 6874:                         %srch_results = &Apache::lonnet::usersearch($srch);
 6875:                         ($currstate,$response,$forcenewuser) =
 6876:                             &build_search_response($context,$srch,%srch_results);
 6877:                     }
 6878:                 } else {
 6879:                     my $courseusers = &get_courseusers();
 6880:                     if ($srch->{'srchtype'} eq 'exact') {
 6881:                         if (exists($courseusers->{$srch->{'srchterm'}.':'.$srch->{'srchdomain'}})) {
 6882:                             $currstate = 'modify';
 6883:                         } else {
 6884:                             ($currstate,$response,$forcenewuser) =
 6885:                                 &build_search_response($context,$srch,%srch_results);
 6886:                         }
 6887:                     } else {
 6888:                         foreach my $user (keys(%$courseusers)) {
 6889:                             my ($cuname,$cudomain) = split(/:/,$user);
 6890:                             if ($cudomain eq $srch->{'srchdomain'}) {
 6891:                                 my $matched = 0;
 6892:                                 if ($srch->{'srchtype'} eq 'begins') {
 6893:                                     if ($cuname =~ /^\Q$srch->{'srchterm'}\E/i) {
 6894:                                         $matched = 1;
 6895:                                     }
 6896:                                 } else {
 6897:                                     if ($cuname =~ /\Q$srch->{'srchterm'}\E/i) {
 6898:                                         $matched = 1;
 6899:                                     }
 6900:                                 }
 6901:                                 if ($matched) {
 6902:                                     $srch_results{$user} = 
 6903: 					{&Apache::lonnet::get('environment',
 6904: 							     ['firstname',
 6905: 							      'lastname',
 6906: 							      'permanentemail'],
 6907: 							      $cudomain,$cuname)};
 6908:                                 }
 6909:                             }
 6910:                         }
 6911:                         ($currstate,$response,$forcenewuser) =
 6912:                             &build_search_response($context,$srch,%srch_results);
 6913:                     }
 6914:                 }
 6915:             }
 6916:         } elsif ($srch->{'srchin'} eq 'alc') {
 6917:             $currstate = 'query';
 6918:         } elsif ($srch->{'srchin'} eq 'instd') {
 6919:             ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query($srch);
 6920:             if ($dirsrchres eq 'ok') {
 6921:                 ($currstate,$response,$forcenewuser) = 
 6922:                     &build_search_response($context,$srch,%srch_results);
 6923:             } else {
 6924:                 my $showdom = &display_domain_info($srch->{'srchdomain'});
 6925:                 $response = '<span class="LC_warning">'.
 6926:                     &mt('Institutional directory search is not available in domain: [_1]',$showdom).
 6927:                     '</span><br />'.
 6928:                     &mt('You may want to search in the LON-CAPA domain instead of the institutional directory.').
 6929:                     '<br />'; 
 6930:             }
 6931:         }
 6932:     } else {
 6933:         if ($srch->{'srchin'} eq 'dom') {
 6934:             %srch_results = &Apache::lonnet::usersearch($srch);
 6935:             ($currstate,$response,$forcenewuser) = 
 6936:                 &build_search_response($context,$srch,%srch_results); 
 6937:         } elsif ($srch->{'srchin'} eq 'crs') {
 6938:             my $courseusers = &get_courseusers(); 
 6939:             foreach my $user (keys(%$courseusers)) {
 6940:                 my ($uname,$udom) = split(/:/,$user);
 6941:                 my %names = &Apache::loncommon::getnames($uname,$udom);
 6942:                 my %emails = &Apache::loncommon::getemails($uname,$udom);
 6943:                 if ($srch->{'srchby'} eq 'lastname') {
 6944:                     if ((($srch->{'srchtype'} eq 'exact') && 
 6945:                          ($names{'lastname'} eq $srch->{'srchterm'})) || 
 6946:                         (($srch->{'srchtype'} eq 'begins') &&
 6947:                          ($names{'lastname'} =~ /^\Q$srch->{'srchterm'}\E/i)) ||
 6948:                         (($srch->{'srchtype'} eq 'contains') &&
 6949:                          ($names{'lastname'} =~ /\Q$srch->{'srchterm'}\E/i))) {
 6950:                         $srch_results{$user} = {firstname => $names{'firstname'},
 6951:                                             lastname => $names{'lastname'},
 6952:                                             permanentemail => $emails{'permanentemail'},
 6953:                                            };
 6954:                     }
 6955:                 } elsif ($srch->{'srchby'} eq 'lastfirst') {
 6956:                     my ($srchlast,$srchfirst) = split(/,/,$srch->{'srchterm'});
 6957:                     $srchlast =~ s/\s+$//;
 6958:                     $srchfirst =~ s/^\s+//;
 6959:                     if ($srch->{'srchtype'} eq 'exact') {
 6960:                         if (($names{'lastname'} eq $srchlast) &&
 6961:                             ($names{'firstname'} eq $srchfirst)) {
 6962:                             $srch_results{$user} = {firstname => $names{'firstname'},
 6963:                                                 lastname => $names{'lastname'},
 6964:                                                 permanentemail => $emails{'permanentemail'},
 6965: 
 6966:                                            };
 6967:                         }
 6968:                     } elsif ($srch->{'srchtype'} eq 'begins') {
 6969:                         if (($names{'lastname'} =~ /^\Q$srchlast\E/i) &&
 6970:                             ($names{'firstname'} =~ /^\Q$srchfirst\E/i)) {
 6971:                             $srch_results{$user} = {firstname => $names{'firstname'},
 6972:                                                 lastname => $names{'lastname'},
 6973:                                                 permanentemail => $emails{'permanentemail'},
 6974:                                                };
 6975:                         }
 6976:                     } else {
 6977:                         if (($names{'lastname'} =~ /\Q$srchlast\E/i) && 
 6978:                             ($names{'firstname'} =~ /\Q$srchfirst\E/i)) {
 6979:                             $srch_results{$user} = {firstname => $names{'firstname'},
 6980:                                                 lastname => $names{'lastname'},
 6981:                                                 permanentemail => $emails{'permanentemail'},
 6982:                                                };
 6983:                         }
 6984:                     }
 6985:                 }
 6986:             }
 6987:             ($currstate,$response,$forcenewuser) = 
 6988:                 &build_search_response($context,$srch,%srch_results); 
 6989:         } elsif ($srch->{'srchin'} eq 'alc') {
 6990:             $currstate = 'query';
 6991:         } elsif ($srch->{'srchin'} eq 'instd') {
 6992:             ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query($srch); 
 6993:             if ($dirsrchres eq 'ok') {
 6994:                 ($currstate,$response,$forcenewuser) = 
 6995:                     &build_search_response($context,$srch,%srch_results);
 6996:             } else {
 6997:                 my $showdom = &display_domain_info($srch->{'srchdomain'});
 6998:                 $response = '<span class="LC_warning">'.
 6999:                     &mt('Institutional directory search is not available in domain: [_1]',$showdom).
 7000:                     '</span><br />'.
 7001:                     &mt('You may want to search in the LON-CAPA domain instead of the institutional directory.').
 7002:                     '<br />';
 7003:             }
 7004:         }
 7005:     }
 7006:     return ($currstate,$response,$forcenewuser,\%srch_results);
 7007: }
 7008: 
 7009: sub domdirectorysrch_check {
 7010:     my ($srch) = @_;
 7011:     my $response;
 7012:     my %dom_inst_srch = &Apache::lonnet::get_dom('configuration',
 7013:                                              ['directorysrch'],$srch->{'srchdomain'});
 7014:     my $showdom = &display_domain_info($srch->{'srchdomain'});
 7015:     if (ref($dom_inst_srch{'directorysrch'}) eq 'HASH') {
 7016:         if ($dom_inst_srch{'directorysrch'}{'lcavailable'} eq '0') {
 7017:             return &mt('LON-CAPA directory search is not available in domain: [_1]',$showdom);
 7018:         }
 7019:         if ($dom_inst_srch{'directorysrch'}{'lclocalonly'}) {
 7020:             if ($env{'request.role.domain'} ne $srch->{'srchdomain'}) {
 7021:                 return &mt('LON-CAPA directory search in domain: [_1] is only allowed for users with a current role in the domain.',$showdom);
 7022:             }
 7023:         }
 7024:     }
 7025:     return 'ok';
 7026: }
 7027: 
 7028: sub instdirectorysrch_check {
 7029:     my ($srch) = @_;
 7030:     my $can_search = 0;
 7031:     my $response;
 7032:     my %dom_inst_srch = &Apache::lonnet::get_dom('configuration',
 7033:                                              ['directorysrch'],$srch->{'srchdomain'});
 7034:     my $showdom = &display_domain_info($srch->{'srchdomain'});
 7035:     if (ref($dom_inst_srch{'directorysrch'}) eq 'HASH') {
 7036:         if (!$dom_inst_srch{'directorysrch'}{'available'}) {
 7037:             return &mt('Institutional directory search is not available in domain: [_1]',$showdom); 
 7038:         }
 7039:         if ($dom_inst_srch{'directorysrch'}{'localonly'}) {
 7040:             if ($env{'request.role.domain'} ne $srch->{'srchdomain'}) {
 7041:                 return &mt('Institutional directory search in domain: [_1] is only allowed for users with a current role in the domain.',$showdom); 
 7042:             }
 7043:             my @usertypes = split(/:/,$env{'environment.inststatus'});
 7044:             if (!@usertypes) {
 7045:                 push(@usertypes,'default');
 7046:             }
 7047:             if (ref($dom_inst_srch{'directorysrch'}{'cansearch'}) eq 'ARRAY') {
 7048:                 foreach my $type (@usertypes) {
 7049:                     if (grep(/^\Q$type\E$/,@{$dom_inst_srch{'directorysrch'}{'cansearch'}})) {
 7050:                         $can_search = 1;
 7051:                         last;
 7052:                     }
 7053:                 }
 7054:             }
 7055:             if (!$can_search) {
 7056:                 my ($insttypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($srch->{'srchdomain'});
 7057:                 my @longtypes; 
 7058:                 foreach my $item (@usertypes) {
 7059:                     if (defined($insttypes->{$item})) { 
 7060:                         push (@longtypes,$insttypes->{$item});
 7061:                     } elsif ($item eq 'default') {
 7062:                         push (@longtypes,&mt('other')); 
 7063:                     }
 7064:                 }
 7065:                 my $insttype_str = join(', ',@longtypes); 
 7066:                 return &mt('Institutional directory search in domain: [_1] is not available to your user type: ',$showdom).$insttype_str;
 7067:             }
 7068:         } else {
 7069:             $can_search = 1;
 7070:         }
 7071:     } else {
 7072:         return &mt('Institutional directory search has not been configured for domain: [_1]',$showdom);
 7073:     }
 7074:     my %longtext = &Apache::lonlocal::texthash (
 7075:                        uname     => 'username',
 7076:                        lastfirst => 'last name, first name',
 7077:                        lastname  => 'last name',
 7078:                        contains  => 'contains',
 7079:                        exact     => 'as exact match to',
 7080:                        begins    => 'begins with',
 7081:                    );
 7082:     if ($can_search) {
 7083:         if (ref($dom_inst_srch{'directorysrch'}{'searchby'}) eq 'ARRAY') {
 7084:             if (!grep(/^\Q$srch->{'srchby'}\E$/,@{$dom_inst_srch{'directorysrch'}{'searchby'}})) {
 7085:                 return &mt('Institutional directory search in domain: [_1] is not available for searching by "[_2]"',$showdom,$longtext{$srch->{'srchby'}});
 7086:             }
 7087:         } else {
 7088:             return &mt('Institutional directory search in domain: [_1] is not available.', $showdom);
 7089:         }
 7090:     }
 7091:     if ($can_search) {
 7092:         if (ref($dom_inst_srch{'directorysrch'}{'searchtypes'}) eq 'ARRAY') {
 7093:             if (grep(/^\Q$srch->{'srchtype'}\E/,@{$dom_inst_srch{'directorysrch'}{'searchtypes'}})) {
 7094:                 return 'ok';
 7095:             } else {
 7096:                 return &mt('Institutional directory search in domain [_1] is not available for the requested search type: "[_2]"',$showdom,$longtext{$srch->{'srchtype'}});
 7097:             }
 7098:         } else {
 7099:             if ((($dom_inst_srch{'directorysrch'}{'searchtypes'} eq 'specify') &&
 7100:                  ($srch->{'srchtype'} eq 'exact' || $srch->{'srchtype'} eq 'contains')) ||
 7101:                 ($dom_inst_srch{'directorysrch'}{'searchtypes'} eq $srch->{'srchtype'})) {
 7102:                 return 'ok';
 7103:             } else {
 7104:                 return &mt('Institutional directory search in domain [_1] is not available for the requested search type: "[_2]"',$showdom,$longtext{$srch->{'srchtype'}});
 7105:             }
 7106:         }
 7107:     }
 7108: }
 7109: 
 7110: sub get_courseusers {
 7111:     my %advhash;
 7112:     my $classlist = &Apache::loncoursedata::get_classlist();
 7113:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles();
 7114:     foreach my $role (sort(keys(%coursepersonnel))) {
 7115:         foreach my $user (split(/\,/,$coursepersonnel{$role})) {
 7116: 	    if (!exists($classlist->{$user})) {
 7117: 		$classlist->{$user} = [];
 7118: 	    }
 7119:         }
 7120:     }
 7121:     return $classlist;
 7122: }
 7123: 
 7124: sub build_search_response {
 7125:     my ($context,$srch,%srch_results) = @_;
 7126:     my ($currstate,$response,$forcenewuser);
 7127:     my %names = (
 7128:           'uname'     => 'username',
 7129:           'lastname'  => 'last name',
 7130:           'lastfirst' => 'last name, first name',
 7131:           'crs'       => 'this course',
 7132:           'dom'       => 'LON-CAPA domain',
 7133:           'instd'     => 'the institutional directory for domain',
 7134:     );
 7135: 
 7136:     my %single = (
 7137:                    begins   => 'A match',
 7138:                    contains => 'A match',
 7139:                    exact    => 'An exact match',
 7140:                  );
 7141:     my %nomatch = (
 7142:                    begins   => 'No match',
 7143:                    contains => 'No match',
 7144:                    exact    => 'No exact match',
 7145:                   );
 7146:     if (keys(%srch_results) > 1) {
 7147:         $currstate = 'select';
 7148:     } else {
 7149:         if (keys(%srch_results) == 1) {
 7150:             $currstate = 'modify';
 7151:             $response = &mt("$single{$srch->{'srchtype'}} was found for the $names{$srch->{'srchby'}} ([_1]) in $names{$srch->{'srchin'}}.",$srch->{'srchterm'});
 7152:             if ($srch->{'srchin'} eq 'dom' || $srch->{'srchin'} eq 'instd') {
 7153:                 $response .= ': '.&display_domain_info($srch->{'srchdomain'});
 7154:             }
 7155:         } else { # Search has nothing found. Prepare message to user.
 7156:             $response = '<span class="LC_warning">';
 7157:             if ($srch->{'srchin'} eq 'dom' || $srch->{'srchin'} eq 'instd') {
 7158:                 $response .= &mt("$nomatch{$srch->{'srchtype'}} found for the $names{$srch->{'srchby'}} [_1] in $names{$srch->{'srchin'}}: [_2]",
 7159:                                  '<b>'.$srch->{'srchterm'}.'</b>',
 7160:                                  &display_domain_info($srch->{'srchdomain'}));
 7161:             } else {
 7162:                 $response .= &mt("$nomatch{$srch->{'srchtype'}} found for the $names{$srch->{'srchby'}} [_1] in $names{$srch->{'srchin'}}.",
 7163:                                  '<b>'.$srch->{'srchterm'}.'</b>');
 7164:             }
 7165:             $response .= '</span>';
 7166: 
 7167:             if ($srch->{'srchin'} ne 'alc') {
 7168:                 $forcenewuser = 1;
 7169:                 my $cansrchinst = 0; 
 7170:                 if ($srch->{'srchdomain'}) {
 7171:                     my %domconfig = &Apache::lonnet::get_dom('configuration',['directorysrch'],$srch->{'srchdomain'});
 7172:                     if (ref($domconfig{'directorysrch'}) eq 'HASH') {
 7173:                         if ($domconfig{'directorysrch'}{'available'}) {
 7174:                             $cansrchinst = 1;
 7175:                         } 
 7176:                     }
 7177:                 }
 7178:                 if ((($srch->{'srchby'} eq 'lastfirst') || 
 7179:                      ($srch->{'srchby'} eq 'lastname')) &&
 7180:                     ($srch->{'srchin'} eq 'dom')) {
 7181:                     if ($cansrchinst) {
 7182:                         $response .= '<br />'.&mt('You may want to broaden your search to a search of the institutional directory for the domain.');
 7183:                     }
 7184:                 }
 7185:                 if ($srch->{'srchin'} eq 'crs') {
 7186:                     $response .= '<br />'.&mt('You may want to broaden your search to the selected LON-CAPA domain.');
 7187:                 }
 7188:             }
 7189:             my $createdom = $env{'request.role.domain'};
 7190:             if ($context eq 'requestcrs') {
 7191:                 if ($env{'form.coursedom'} ne '') {
 7192:                     $createdom = $env{'form.coursedom'};
 7193:                 }
 7194:             }
 7195:             if (!($srch->{'srchby'} eq 'uname' && $srch->{'srchin'} eq 'dom' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchdomain'} eq $createdom)) {
 7196:                 my $cancreate =
 7197:                     &Apache::lonuserutils::can_create_user($createdom,$context);
 7198:                 my $targetdom = '<span class="LC_cusr_emph">'.$createdom.'</span>';
 7199:                 if ($cancreate) {
 7200:                     my $showdom = &display_domain_info($createdom); 
 7201:                     $response .= '<br /><br />'
 7202:                                 .'<b>'.&mt('To add a new user:').'</b>'
 7203:                                 .'<br />';
 7204:                     if ($context eq 'requestcrs') {
 7205:                         $response .= &mt("(You can only define new users in the new course's domain - [_1])",$targetdom);
 7206:                     } else {
 7207:                         $response .= &mt("(You can only create new users in your current role's domain - [_1])",$targetdom);
 7208:                     }
 7209:                     $response .='<ul><li>'
 7210:                                 .&mt("Set 'Domain/institution to search' to: [_1]",'<span class="LC_cusr_emph">'.$showdom.'</span>')
 7211:                                 .'</li><li>'
 7212:                                 .&mt("Set 'Search criteria' to: [_1]username is ..... in selected LON-CAPA domain[_2]",'<span class="LC_cusr_emph">','</span>')
 7213:                                 .'</li><li>'
 7214:                                 .&mt('Provide the proposed username')
 7215:                                 .'</li><li>'
 7216:                                 .&mt("Click 'Search'")
 7217:                                 .'</li></ul><br />';
 7218:                 } else {
 7219:                     my $helplink = ' href="javascript:helpMenu('."'display'".')"';
 7220:                     $response .= '<br /><br />';
 7221:                     if ($context eq 'requestcrs') {
 7222:                         $response .= &mt("You are not authorized to define new users in the new course's domain - [_1].",$targetdom);
 7223:                     } else {
 7224:                         $response .= &mt("You are not authorized to create new users in your current role's domain - [_1].",$targetdom);
 7225:                     }
 7226:                     $response .= '<br />'
 7227:                                  .&mt('Please contact the [_1]helpdesk[_2] if you need to create a new user.'
 7228:                                     ,' <a'.$helplink.'>'
 7229:                                     ,'</a>')
 7230:                                  .'<br />';
 7231:                 }
 7232:             }
 7233:         }
 7234:     }
 7235:     return ($currstate,$response,$forcenewuser);
 7236: }
 7237: 
 7238: sub display_domain_info {
 7239:     my ($dom) = @_;
 7240:     my $output = $dom;
 7241:     if ($dom ne '') { 
 7242:         my $domdesc = &Apache::lonnet::domain($dom,'description');
 7243:         if ($domdesc ne '') {
 7244:             $output .= ' <span class="LC_cusr_emph">('.$domdesc.')</span>';
 7245:         }
 7246:     }
 7247:     return $output;
 7248: }
 7249: 
 7250: sub crumb_utilities {
 7251:     my %elements = (
 7252:        crtuser => {
 7253:            srchterm => 'text',
 7254:            srchin => 'selectbox',
 7255:            srchby => 'selectbox',
 7256:            srchtype => 'selectbox',
 7257:            srchdomain => 'selectbox',
 7258:        },
 7259:        crtusername => {
 7260:            srchterm => 'text',
 7261:            srchdomain => 'selectbox',
 7262:        },
 7263:        docustom => {
 7264:            rolename => 'selectbox',
 7265:            newrolename => 'textbox',
 7266:        },
 7267:        studentform => {
 7268:            srchterm => 'text',
 7269:            srchin => 'selectbox',
 7270:            srchby => 'selectbox',
 7271:            srchtype => 'selectbox',
 7272:            srchdomain => 'selectbox',
 7273:        },
 7274:     );
 7275: 
 7276:     my $jsback .= qq|
 7277: function backPage(formname,prevphase,prevstate) {
 7278:     if (typeof prevphase == 'undefined') {
 7279:         formname.phase.value = '';
 7280:     }
 7281:     else {  
 7282:         formname.phase.value = prevphase;
 7283:     }
 7284:     if (typeof prevstate == 'undefined') {
 7285:         formname.currstate.value = '';
 7286:     }
 7287:     else {
 7288:         formname.currstate.value = prevstate;
 7289:     }
 7290:     formname.submit();
 7291: }
 7292: |;
 7293:     return ($jsback,\%elements);
 7294: }
 7295: 
 7296: sub course_level_table {
 7297:     my ($inccourses,$showcredits,$defaultcredits) = @_;
 7298:     return unless (ref($inccourses) eq 'HASH');
 7299:     my $table = '';
 7300: # Custom Roles?
 7301: 
 7302:     my %customroles=&Apache::lonuserutils::my_custom_roles();
 7303:     my %lt=&Apache::lonlocal::texthash(
 7304:             'exs'  => "Existing sections",
 7305:             'new'  => "Define new section",
 7306:             'ssd'  => "Set Start Date",
 7307:             'sed'  => "Set End Date",
 7308:             'crl'  => "Course Level",
 7309:             'act'  => "Activate",
 7310:             'rol'  => "Role",
 7311:             'ext'  => "Extent",
 7312:             'grs'  => "Section",
 7313:             'crd'  => "Credits",
 7314:             'sta'  => "Start",
 7315:             'end'  => "End"
 7316:     );
 7317: 
 7318:     foreach my $protectedcourse (sort(keys(%{$inccourses}))) {
 7319: 	my $thiscourse=$protectedcourse;
 7320: 	$thiscourse=~s:_:/:g;
 7321: 	my %coursedata=&Apache::lonnet::coursedescription($thiscourse);
 7322:         my $isowner = &Apache::lonuserutils::is_courseowner($protectedcourse,$coursedata{'internal.courseowner'});
 7323: 	my $area=$coursedata{'description'};
 7324:         my $crstype=$coursedata{'type'};
 7325: 	if (!defined($area)) { $area=&mt('Unavailable course').': '.$protectedcourse; }
 7326: 	my ($domain,$cnum)=split(/\//,$thiscourse);
 7327:         my %sections_count;
 7328:         if (defined($env{'request.course.id'})) {
 7329:             if ($env{'request.course.id'} eq $domain.'_'.$cnum) {
 7330:                 %sections_count = 
 7331: 		    &Apache::loncommon::get_sections($domain,$cnum);
 7332:             }
 7333:         }
 7334:         my @roles = &Apache::lonuserutils::roles_by_context('course','',$crstype);
 7335: 	foreach my $role (@roles) {
 7336:             my $plrole=&Apache::lonnet::plaintext($role,$crstype);
 7337: 	    if ((&Apache::lonnet::allowed('c'.$role,$thiscourse)) ||
 7338:                 ((($role eq 'cc') || ($role eq 'co')) && ($isowner))) {
 7339:                 $table .= &course_level_row($protectedcourse,$role,$area,$domain,
 7340:                                             $plrole,\%sections_count,\%lt,
 7341:                                             $showcredits,$defaultcredits,$crstype);
 7342:             } elsif ($env{'request.course.sec'} ne '') {
 7343:                 if (&Apache::lonnet::allowed('c'.$role,$thiscourse.'/'.
 7344:                                              $env{'request.course.sec'})) {
 7345:                     $table .= &course_level_row($protectedcourse,$role,$area,$domain,
 7346:                                                 $plrole,\%sections_count,\%lt,
 7347:                                                 $showcredits,$defaultcredits,$crstype);
 7348:                 }
 7349:             }
 7350:         }
 7351:         if (&Apache::lonnet::allowed('ccr',$thiscourse)) {
 7352:             foreach my $cust (sort(keys(%customroles))) {
 7353:                 next if ($crstype eq 'Community' && $customroles{$cust} =~ /bre\&S/);
 7354:                 my $role = 'cr_cr_'.$env{'user.domain'}.'_'.$env{'user.name'}.'_'.$cust;
 7355:                 $table .= &course_level_row($protectedcourse,$role,$area,$domain,
 7356:                                             $cust,\%sections_count,\%lt,
 7357:                                             $showcredits,$defaultcredits,$crstype);
 7358:             }
 7359: 	}
 7360:     }
 7361:     return '' if ($table eq ''); # return nothing if there is nothing 
 7362:                                  # in the table
 7363:     my $result;
 7364:     if (!$env{'request.course.id'}) {
 7365:         $result = '<h4>'.$lt{'crl'}.'</h4>'."\n";
 7366:     }
 7367:     $result .= 
 7368: &Apache::loncommon::start_data_table().
 7369: &Apache::loncommon::start_data_table_header_row().
 7370: '<th>'.$lt{'act'}.'</th><th>'.$lt{'rol'}.'</th>'."\n".
 7371: '<th>'.$lt{'ext'}.'</th><th>'."\n";
 7372:     if ($showcredits) {
 7373:         $result .= $lt{'crd'}.'</th>';
 7374:     }
 7375:     $result .=
 7376: '<th>'.$lt{'grs'}.'</th><th>'.$lt{'sta'}.'</th>'."\n".
 7377: '<th>'.$lt{'end'}.'</th>'.
 7378: &Apache::loncommon::end_data_table_header_row().
 7379: $table.
 7380: &Apache::loncommon::end_data_table();
 7381:     return $result;
 7382: }
 7383: 
 7384: sub course_level_row {
 7385:     my ($protectedcourse,$role,$area,$domain,$plrole,$sections_count,
 7386:         $lt,$showcredits,$defaultcredits,$crstype) = @_;
 7387:     my $creditem;
 7388:     my $row = &Apache::loncommon::start_data_table_row().
 7389:               ' <td><input type="checkbox" name="act_'.
 7390:               $protectedcourse.'_'.$role.'" /></td>'."\n".
 7391:               ' <td>'.$plrole.'</td>'."\n".
 7392:               ' <td>'.$area.'<br />Domain: '.$domain.'</td>'."\n";
 7393:     if (($showcredits) && ($role eq 'st') && ($crstype eq 'Course')) {
 7394:         $row .= 
 7395:             '<td><input type="text" name="credits_'.$protectedcourse.'_'.
 7396:             $role.'" size="3" value="'.$defaultcredits.'" /></td>';
 7397:     } else {
 7398:         $row .= '<td>&nbsp;</td>';
 7399:     }
 7400:     if (($role eq 'cc') || ($role eq 'co')) {
 7401:         $row .= '<td>&nbsp;</td>';
 7402:     } elsif ($env{'request.course.sec'} ne '') {
 7403:         $row .= ' <td><input type="hidden" value="'.
 7404:                 $env{'request.course.sec'}.'" '.
 7405:                 'name="sec_'.$protectedcourse.'_'.$role.'" />'.
 7406:                 $env{'request.course.sec'}.'</td>';
 7407:     } else {
 7408:         if (ref($sections_count) eq 'HASH') {
 7409:             my $currsec = 
 7410:                 &Apache::lonuserutils::course_sections($sections_count,
 7411:                                                        $protectedcourse.'_'.$role);
 7412:             $row .= '<td><table class="LC_createuser">'."\n".
 7413:                     '<tr class="LC_section_row">'."\n".
 7414:                     ' <td valign="top">'.$lt->{'exs'}.'<br />'.
 7415:                        $currsec.'</td>'."\n".
 7416:                      ' <td>&nbsp;&nbsp;</td>'."\n".
 7417:                      ' <td valign="top">&nbsp;'.$lt->{'new'}.'<br />'.
 7418:                      '<input type="text" name="newsec_'.$protectedcourse.'_'.$role.
 7419:                      '" value="" />'.
 7420:                      '<input type="hidden" '.
 7421:                      'name="sec_'.$protectedcourse.'_'.$role.'" /></td>'."\n".
 7422:                      '</tr></table></td>'."\n";
 7423:         } else {
 7424:             $row .= '<td><input type="text" size="10" '.
 7425:                     'name="sec_'.$protectedcourse.'_'.$role.'" /></td>'."\n";
 7426:         }
 7427:     }
 7428:     $row .= <<ENDTIMEENTRY;
 7429: <td><input type="hidden" name="start_$protectedcourse\_$role" value="" />
 7430: <a href=
 7431: "javascript:pjump('date_start','Start Date $plrole',document.cu.start_$protectedcourse\_$role.value,'start_$protectedcourse\_$role','cu.pres','dateset')">$lt->{'ssd'}</a></td>
 7432: <td><input type="hidden" name="end_$protectedcourse\_$role" value="" />
 7433: <a href=
 7434: "javascript:pjump('date_end','End Date $plrole',document.cu.end_$protectedcourse\_$role.value,'end_$protectedcourse\_$role','cu.pres','dateset')">$lt->{'sed'}</a></td>
 7435: ENDTIMEENTRY
 7436:     $row .= &Apache::loncommon::end_data_table_row();
 7437:     return $row;
 7438: }
 7439: 
 7440: sub course_level_dc {
 7441:     my ($dcdom,$showcredits) = @_;
 7442:     my %customroles=&Apache::lonuserutils::my_custom_roles();
 7443:     my @roles = &Apache::lonuserutils::roles_by_context('course');
 7444:     my $hiddenitems = '<input type="hidden" name="dcdomain" value="'.$dcdom.'" />'.
 7445:                       '<input type="hidden" name="origdom" value="'.$dcdom.'" />'.
 7446:                       '<input type="hidden" name="dccourse" value="" />';
 7447:     my $courseform=&Apache::loncommon::selectcourse_link
 7448:             ('cu','dccourse','dcdomain','coursedesc',undef,undef,'Select','crstype');
 7449:     my $credit_elem;
 7450:     if ($showcredits) {
 7451:         $credit_elem = 'credits';
 7452:     }
 7453:     my $cb_jscript = &Apache::loncommon::coursebrowser_javascript($dcdom,'currsec','cu','role','Course/Community Browser',$credit_elem);
 7454:     my %lt=&Apache::lonlocal::texthash(
 7455:                     'rol'  => "Role",
 7456:                     'grs'  => "Section",
 7457:                     'exs'  => "Existing sections",
 7458:                     'new'  => "Define new section", 
 7459:                     'sta'  => "Start",
 7460:                     'end'  => "End",
 7461:                     'ssd'  => "Set Start Date",
 7462:                     'sed'  => "Set End Date",
 7463:                     'scc'  => "Course/Community",
 7464:                     'crd'  => "Credits",
 7465:                   );
 7466:     my $header = '<h4>'.&mt('Course/Community Level').'</h4>'.
 7467:                  &Apache::loncommon::start_data_table().
 7468:                  &Apache::loncommon::start_data_table_header_row().
 7469:                  '<th>'.$lt{'scc'}.'</th><th>'.$lt{'rol'}.'</th>'."\n".
 7470:                  '<th>'.$lt{'grs'}.'</th>'."\n";
 7471:     $header .=   '<th>'.$lt{'crd'}.'</th>'."\n" if ($showcredits);
 7472:     $header .=   '<th>'.$lt{'sta'}.'</th><th>'.$lt{'end'}.'</th>'."\n".
 7473:                  &Apache::loncommon::end_data_table_header_row();
 7474:     my $otheritems = &Apache::loncommon::start_data_table_row()."\n".
 7475:                      '<td><br /><span class="LC_nobreak"><input type="text" name="coursedesc" value="" onfocus="this.blur();opencrsbrowser('."'cu','dccourse','dcdomain','coursedesc','','','','crstype'".')" />'.
 7476:                      $courseform.('&nbsp;' x4).'</span></td>'."\n".
 7477:                      '<td valign="top"><br /><select name="role">'."\n";
 7478:     foreach my $role (@roles) {
 7479:         my $plrole=&Apache::lonnet::plaintext($role);
 7480:         $otheritems .= '  <option value="'.$role.'">'.$plrole.'</option>';
 7481:     }
 7482:     if ( keys(%customroles) > 0) {
 7483:         foreach my $cust (sort(keys(%customroles))) {
 7484:             my $custrole='cr_cr_'.$env{'user.domain'}.
 7485:                     '_'.$env{'user.name'}.'_'.$cust;
 7486:             $otheritems .= '  <option value="'.$custrole.'">'.$cust.'</option>';
 7487:         }
 7488:     }
 7489:     $otheritems .= '</select></td><td>'.
 7490:                      '<table border="0" cellspacing="0" cellpadding="0">'.
 7491:                      '<tr><td valign="top"><b>'.$lt{'exs'}.'</b><br /><select name="currsec">'.
 7492:                      ' <option value="">&lt;--'.&mt('Pick course first').'</option></select></td>'.
 7493:                      '<td>&nbsp;&nbsp;</td>'.
 7494:                      '<td valign="top">&nbsp;<b>'.$lt{'new'}.'</b><br />'.
 7495:                      '<input type="text" name="newsec" value="" />'.
 7496:                      '<input type="hidden" name="section" value="" />'.
 7497:                      '<input type="hidden" name="groups" value="" />'.
 7498:                      '<input type="hidden" name="crstype" value="" /></td>'.
 7499:                      '</tr></table></td>'."\n";
 7500:     if ($showcredits) {
 7501:         $otheritems .= '<td><br />'."\n".
 7502:                        '<input type="text" size="3" name="credits" value="" /></td>'."\n";
 7503:     }
 7504:     $otheritems .= <<ENDTIMEENTRY;
 7505: <td><br /><input type="hidden" name="start" value='' />
 7506: <a href=
 7507: "javascript:pjump('date_start','Start Date',document.cu.start.value,'start','cu.pres','dateset')">$lt{'ssd'}</a></td>
 7508: <td><br /><input type="hidden" name="end" value='' />
 7509: <a href=
 7510: "javascript:pjump('date_end','End Date',document.cu.end.value,'end','cu.pres','dateset')">$lt{'sed'}</a></td>
 7511: ENDTIMEENTRY
 7512:     $otheritems .= &Apache::loncommon::end_data_table_row().
 7513:                    &Apache::loncommon::end_data_table()."\n";
 7514:     return $cb_jscript.$header.$hiddenitems.$otheritems;
 7515: }
 7516: 
 7517: sub update_selfenroll_config {
 7518:     my ($r,$cid,$cdom,$cnum,$context,$crstype,$currsettings) = @_;
 7519:     return unless (ref($currsettings) eq 'HASH');
 7520:     my ($row,$lt) = &Apache::lonuserutils::get_selfenroll_titles();
 7521:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
 7522:     my (%changes,%warning);
 7523:     my $curr_types;
 7524:     my %noedit;
 7525:     unless ($context eq 'domain') {
 7526:         %noedit = &get_noedit_fields($cdom,$cnum,$crstype,$row);
 7527:     }
 7528:     if (ref($row) eq 'ARRAY') {
 7529:         foreach my $item (@{$row}) {
 7530:             next if ($noedit{$item});
 7531:             if ($item eq 'enroll_dates') {
 7532:                 my (%currenrolldate,%newenrolldate);
 7533:                 foreach my $type ('start','end') {
 7534:                     $currenrolldate{$type} = $currsettings->{'selfenroll_'.$type.'_date'};
 7535:                     $newenrolldate{$type} = &Apache::lonhtmlcommon::get_date_from_form('selfenroll_'.$type.'_date');
 7536:                     if ($newenrolldate{$type} ne $currenrolldate{$type}) {
 7537:                         $changes{'internal.selfenroll_'.$type.'_date'} = $newenrolldate{$type};
 7538:                     }
 7539:                 }
 7540:             } elsif ($item eq 'access_dates') {
 7541:                 my (%currdate,%newdate);
 7542:                 foreach my $type ('start','end') {
 7543:                     $currdate{$type} = $currsettings->{'selfenroll_'.$type.'_access'};
 7544:                     $newdate{$type} = &Apache::lonhtmlcommon::get_date_from_form('selfenroll_'.$type.'_access');
 7545:                     if ($newdate{$type} ne $currdate{$type}) {
 7546:                         $changes{'internal.selfenroll_'.$type.'_access'} = $newdate{$type};
 7547:                     }
 7548:                 }
 7549:             } elsif ($item eq 'types') {
 7550:                 $curr_types = $currsettings->{'selfenroll_'.$item};
 7551:                 if ($env{'form.selfenroll_all'}) {
 7552:                     if ($curr_types ne '*') {
 7553:                         $changes{'internal.selfenroll_types'} = '*';
 7554:                     } else {
 7555:                         next;
 7556:                     }
 7557:                 } else {
 7558:                     my %currdoms;
 7559:                     my @entries = split(/;/,$curr_types);
 7560:                     my @deletedoms = &Apache::loncommon::get_env_multiple('form.selfenroll_delete');
 7561:                     my @activations = &Apache::loncommon::get_env_multiple('form.selfenroll_activate');
 7562:                     my $newnum = 0;
 7563:                     my @latesttypes;
 7564:                     foreach my $num (@activations) {
 7565:                         my @types = &Apache::loncommon::get_env_multiple('form.selfenroll_types_'.$num);
 7566:                         if (@types > 0) {
 7567:                             @types = sort(@types);
 7568:                             my $typestr = join(',',@types);
 7569:                             my $typedom = $env{'form.selfenroll_dom_'.$num};
 7570:                             $latesttypes[$newnum] = $typedom.':'.$typestr;
 7571:                             $currdoms{$typedom} = 1;
 7572:                             $newnum ++;
 7573:                         }
 7574:                     }
 7575:                     for (my $j=0; $j<$env{'form.selfenroll_types_total'}; $j++) {
 7576:                         if ((!grep(/^$j$/,@deletedoms)) && (!grep(/^$j$/,@activations))) {
 7577:                             my @types = &Apache::loncommon::get_env_multiple('form.selfenroll_types_'.$j);
 7578:                             if (@types > 0) {
 7579:                                 @types = sort(@types);
 7580:                                 my $typestr = join(',',@types);
 7581:                                 my $typedom = $env{'form.selfenroll_dom_'.$j};
 7582:                                 $latesttypes[$newnum] = $typedom.':'.$typestr;
 7583:                                 $currdoms{$typedom} = 1;
 7584:                                 $newnum ++;
 7585:                             }
 7586:                         }
 7587:                     }
 7588:                     if ($env{'form.selfenroll_newdom'} ne '') {
 7589:                         my $typedom = $env{'form.selfenroll_newdom'};
 7590:                         if ((!defined($currdoms{$typedom})) && 
 7591:                             (&Apache::lonnet::domain($typedom) ne '')) {
 7592:                             my $typestr;
 7593:                             my ($othertitle,$usertypes,$types) = 
 7594:                                 &Apache::loncommon::sorted_inst_types($typedom);
 7595:                             my $othervalue = 'any';
 7596:                             if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 7597:                                 if (@{$types} > 0) {
 7598:                                     my @esc_types = map { &escape($_); } @{$types};
 7599:                                     $othervalue = 'other';
 7600:                                     $typestr = join(',',(@esc_types,$othervalue));
 7601:                                 }
 7602:                                 $typestr = $othervalue;
 7603:                             } else {
 7604:                                 $typestr = $othervalue;
 7605:                             } 
 7606:                             $latesttypes[$newnum] = $typedom.':'.$typestr;
 7607:                             $newnum ++ ;
 7608:                         }
 7609:                     }
 7610:                     my $selfenroll_types = join(';',@latesttypes);
 7611:                     if ($selfenroll_types ne $curr_types) {
 7612:                         $changes{'internal.selfenroll_types'} = $selfenroll_types;
 7613:                     }
 7614:                 }
 7615:             } elsif ($item eq 'limit') {
 7616:                 my $newlimit = $env{'form.selfenroll_limit'};
 7617:                 my $newcap = $env{'form.selfenroll_cap'};
 7618:                 $newcap =~s/\s+//g;
 7619:                 my $currlimit =  $currsettings->{'selfenroll_limit'};
 7620:                 $currlimit = 'none' if ($currlimit eq '');
 7621:                 my $currcap = $currsettings->{'selfenroll_cap'};
 7622:                 if ($newlimit ne $currlimit) {
 7623:                     if ($newlimit ne 'none') {
 7624:                         if ($newcap =~ /^\d+$/) {
 7625:                             if ($newcap ne $currcap) {
 7626:                                 $changes{'internal.selfenroll_cap'} = $newcap;
 7627:                             }
 7628:                             $changes{'internal.selfenroll_limit'} = $newlimit;
 7629:                         } else {
 7630:                             $warning{$item} = &mt('Maximum enrollment setting unchanged.').'<br />'.
 7631:                                 &mt('The value provided was invalid - it must be a positive integer if enrollment is being limited.'); 
 7632:                         }
 7633:                     } elsif ($currcap ne '') {
 7634:                         $changes{'internal.selfenroll_cap'} = '';
 7635:                         $changes{'internal.selfenroll_limit'} = $newlimit; 
 7636:                     }
 7637:                 } elsif ($currlimit ne 'none') {
 7638:                     if ($newcap =~ /^\d+$/) {
 7639:                         if ($newcap ne $currcap) {
 7640:                             $changes{'internal.selfenroll_cap'} = $newcap;
 7641:                         }
 7642:                     } else {
 7643:                         $warning{$item} = &mt('Maximum enrollment setting unchanged.').'<br />'.
 7644:                             &mt('The value provided was invalid - it must be a positive integer if enrollment is being limited.');
 7645:                     }
 7646:                 }
 7647:             } elsif ($item eq 'approval') {
 7648:                 my (@currnotified,@newnotified);
 7649:                 my $currapproval = $currsettings->{'selfenroll_approval'};
 7650:                 my $currnotifylist = $currsettings->{'selfenroll_notifylist'};
 7651:                 if ($currnotifylist ne '') {
 7652:                     @currnotified = split(/,/,$currnotifylist);
 7653:                     @currnotified = sort(@currnotified);
 7654:                 }
 7655:                 my $newapproval = $env{'form.selfenroll_approval'};
 7656:                 @newnotified = &Apache::loncommon::get_env_multiple('form.selfenroll_notify');
 7657:                 @newnotified = sort(@newnotified);
 7658:                 if ($newapproval ne $currapproval) {
 7659:                     $changes{'internal.selfenroll_approval'} = $newapproval;
 7660:                     if (!$newapproval) {
 7661:                         if ($currnotifylist ne '') {
 7662:                             $changes{'internal.selfenroll_notifylist'} = '';
 7663:                         }
 7664:                     } else {
 7665:                         my @differences =  
 7666:                             &Apache::loncommon::compare_arrays(\@currnotified,\@newnotified);
 7667:                         if (@differences > 0) {
 7668:                             if (@newnotified > 0) {
 7669:                                 $changes{'internal.selfenroll_notifylist'} = join(',',@newnotified);
 7670:                             } else {
 7671:                                 $changes{'internal.selfenroll_notifylist'} = join(',',@newnotified);
 7672:                             }
 7673:                         }
 7674:                     }
 7675:                 } else {
 7676:                     my @differences = &Apache::loncommon::compare_arrays(\@currnotified,\@newnotified);
 7677:                     if (@differences > 0) {
 7678:                         if (@newnotified > 0) {
 7679:                             $changes{'internal.selfenroll_notifylist'} = join(',',@newnotified);
 7680:                         } else {
 7681:                             $changes{'internal.selfenroll_notifylist'} = '';
 7682:                         }
 7683:                     }
 7684:                 }
 7685:             } else {
 7686:                 my $curr_val = $currsettings->{'selfenroll_'.$item};
 7687:                 my $newval = $env{'form.selfenroll_'.$item};
 7688:                 if ($item eq 'section') {
 7689:                     $newval = $env{'form.sections'};
 7690:                     if (defined($curr_groups{$newval})) {
 7691:                         $newval = $curr_val;
 7692:                         $warning{$item} = &mt('Section for self-enrolled users unchanged as the proposed section is a group').'<br />'.
 7693:                                           &mt('Group names and section names must be distinct');
 7694:                     } elsif ($newval eq 'all') {
 7695:                         $newval = $curr_val;
 7696:                         $warning{$item} = &mt('Section for self-enrolled users unchanged, as "all" is a reserved section name.');
 7697:                     }
 7698:                     if ($newval eq '') {
 7699:                         $newval = 'none';
 7700:                     }
 7701:                 }
 7702:                 if ($newval ne $curr_val) {
 7703:                     $changes{'internal.selfenroll_'.$item} = $newval;
 7704:                 }
 7705:             }
 7706:         }
 7707:         if (keys(%warning) > 0) {
 7708:             foreach my $item (@{$row}) {
 7709:                 if (exists($warning{$item})) {
 7710:                     $r->print($warning{$item}.'<br />');
 7711:                 }
 7712:             } 
 7713:         }
 7714:         if (keys(%changes) > 0) {
 7715:             my $putresult = &Apache::lonnet::put('environment',\%changes,$cdom,$cnum);
 7716:             if ($putresult eq 'ok') {
 7717:                 if ((exists($changes{'internal.selfenroll_types'})) ||
 7718:                     (exists($changes{'internal.selfenroll_start_date'}))  ||
 7719:                     (exists($changes{'internal.selfenroll_end_date'}))) {
 7720:                     my %crsinfo = &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',
 7721:                                                                 $cnum,undef,undef,'Course');
 7722:                     my $chome = &Apache::lonnet::homeserver($cnum,$cdom);
 7723:                     if (ref($crsinfo{$cid}) eq 'HASH') {
 7724:                         foreach my $item ('selfenroll_types','selfenroll_start_date','selfenroll_end_date') {
 7725:                             if (exists($changes{'internal.'.$item})) {
 7726:                                 $crsinfo{$cid}{$item} = $changes{'internal.'.$item};
 7727:                             }
 7728:                         }
 7729:                         my $crsputresult =
 7730:                             &Apache::lonnet::courseidput($cdom,\%crsinfo,
 7731:                                                          $chome,'notime');
 7732:                     }
 7733:                 }
 7734:                 $r->print(&mt('The following changes were made to self-enrollment settings:').'<ul>');
 7735:                 foreach my $item (@{$row}) {
 7736:                     my $title = $item;
 7737:                     if (ref($lt) eq 'HASH') {
 7738:                         $title = $lt->{$item};
 7739:                     }
 7740:                     if ($item eq 'enroll_dates') {
 7741:                         foreach my $type ('start','end') {
 7742:                             if (exists($changes{'internal.selfenroll_'.$type.'_date'})) {
 7743:                                 my $newdate = &Apache::lonlocal::locallocaltime($changes{'internal.selfenroll_'.$type.'_date'});
 7744:                                 $r->print('<li>'.&mt('[_1]: "[_2]" set to "[_3]".',
 7745:                                           $title,$type,$newdate).'</li>');
 7746:                             }
 7747:                         }
 7748:                     } elsif ($item eq 'access_dates') {
 7749:                         foreach my $type ('start','end') {
 7750:                             if (exists($changes{'internal.selfenroll_'.$type.'_access'})) {
 7751:                                 my $newdate = &Apache::lonlocal::locallocaltime($changes{'internal.selfenroll_'.$type.'_access'});
 7752:                                 $r->print('<li>'.&mt('[_1]: "[_2]" set to "[_3]".',
 7753:                                           $title,$type,$newdate).'</li>');
 7754:                             }
 7755:                         }
 7756:                     } elsif ($item eq 'limit') {
 7757:                         if ((exists($changes{'internal.selfenroll_limit'})) ||
 7758:                             (exists($changes{'internal.selfenroll_cap'}))) {
 7759:                             my ($newval,$newcap);
 7760:                             if ($changes{'internal.selfenroll_cap'} ne '') {
 7761:                                 $newcap = $changes{'internal.selfenroll_cap'}
 7762:                             } else {
 7763:                                 $newcap = $currsettings->{'selfenroll_cap'};
 7764:                             }
 7765:                             if ($changes{'internal.selfenroll_limit'} eq 'none') {
 7766:                                 $newval = &mt('No limit');
 7767:                             } elsif ($changes{'internal.selfenroll_limit'} eq 
 7768:                                      'allstudents') {
 7769:                                 $newval = &mt('New self-enrollment no longer allowed when total (all students) reaches [_1].',$newcap);
 7770:                             } elsif ($changes{'internal.selfenroll_limit'} eq 'selfenrolled') {
 7771:                                 $newval = &mt('New self-enrollment no longer allowed when total number of self-enrolled students reaches [_1].',$newcap);
 7772:                             } else {
 7773:                                 my $currlimit =  $currsettings->{'selfenroll_limit'};
 7774:                                 if ($currlimit eq 'allstudents') {
 7775:                                     $newval = &mt('New self-enrollment no longer allowed when total (all students) reaches [_1].',$newcap);
 7776:                                 } elsif ($changes{'internal.selfenroll_limit'} eq 'selfenrolled') {
 7777:                                     $newval =  &mt('New self-enrollment no longer allowed when total number of self-enrolled students reaches [_1].',$newcap);
 7778:                                 }
 7779:                             }
 7780:                             $r->print('<li>'.&mt('"[_1]" set to "[_2]".',$title,$newval).'</li>'."\n");
 7781:                         }
 7782:                     } elsif ($item eq 'approval') {
 7783:                         if ((exists($changes{'internal.selfenroll_approval'})) ||
 7784:                             (exists($changes{'internal.selfenroll_notifylist'}))) {
 7785:                             my %selfdescs = &Apache::lonuserutils::selfenroll_default_descs();
 7786:                             my ($newval,$newnotify);
 7787:                             if (exists($changes{'internal.selfenroll_notifylist'})) {
 7788:                                 $newnotify = $changes{'internal.selfenroll_notifylist'};
 7789:                             } else {   
 7790:                                 $newnotify = $currsettings->{'selfenroll_notifylist'};
 7791:                             }
 7792:                             if (exists($changes{'internal.selfenroll_approval'})) {
 7793:                                 if ($changes{'internal.selfenroll_approval'} !~ /^[012]$/) {
 7794:                                     $changes{'internal.selfenroll_approval'} = '0';
 7795:                                 }
 7796:                                 $newval = $selfdescs{'approval'}{$changes{'internal.selfenroll_approval'}};
 7797:                             } else {
 7798:                                 my $currapproval = $currsettings->{'selfenroll_approval'}; 
 7799:                                 if ($currapproval !~ /^[012]$/) {
 7800:                                     $currapproval = 0;
 7801:                                 }
 7802:                                 $newval = $selfdescs{'approval'}{$currapproval};
 7803:                             }
 7804:                             $r->print('<li>'.&mt('"[_1]" set to "[_2]".',$title,$newval));
 7805:                             if ($newnotify) {
 7806:                                 $r->print('<br />'.&mt('The following will be notified when an enrollment request needs approval, or has been approved: [_1].',$newnotify));
 7807:                             } else {
 7808:                                 $r->print('<br />'.&mt('No notifications sent when an enrollment request needs approval, or has been approved.'));
 7809:                             }
 7810:                             $r->print('</li>'."\n");
 7811:                         }
 7812:                     } else {
 7813:                         if (exists($changes{'internal.selfenroll_'.$item})) {
 7814:                             my $newval = $changes{'internal.selfenroll_'.$item};
 7815:                             if ($item eq 'types') {
 7816:                                 if ($newval eq '') {
 7817:                                     $newval = &mt('None');
 7818:                                 } elsif ($newval eq '*') {
 7819:                                     $newval = &mt('Any user in any domain');
 7820:                                 }
 7821:                             } elsif ($item eq 'registered') {
 7822:                                 if ($newval eq '1') {
 7823:                                     $newval = &mt('Yes');
 7824:                                 } elsif ($newval eq '0') {
 7825:                                     $newval = &mt('No');
 7826:                                 }
 7827:                             }
 7828:                             $r->print('<li>'.&mt('"[_1]" set to "[_2]".',$title,$newval).'</li>'."\n");
 7829:                         }
 7830:                     }
 7831:                 }
 7832:                 $r->print('</ul>');
 7833:                 if ($env{'course.'.$cid.'.description'} ne '') {
 7834:                     my %newenvhash;
 7835:                     foreach my $key (keys(%changes)) {
 7836:                         $newenvhash{'course.'.$cid.'.'.$key} = $changes{$key};
 7837:                     }
 7838:                     &Apache::lonnet::appenv(\%newenvhash);
 7839:                 }
 7840:             } else {
 7841:                 $r->print(&mt('An error occurred when saving changes to self-enrollment settings in this course.').'<br />'.
 7842:                           &mt('The error was: [_1].',$putresult));
 7843:             }
 7844:         } else {
 7845:             $r->print(&mt('No changes were made to the existing self-enrollment settings in this course.'));
 7846:         }
 7847:     } else {
 7848:         $r->print(&mt('No changes were made to the existing self-enrollment settings in this course.'));
 7849:     }
 7850:     my $visactions = &cat_visibility();
 7851:     my ($cathash,%cattype);
 7852:     my %domconfig = &Apache::lonnet::get_dom('configuration',['coursecategories'],$cdom);
 7853:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 7854:         $cathash = $domconfig{'coursecategories'}{'cats'};
 7855:         $cattype{'auth'} = $domconfig{'coursecategories'}{'auth'};
 7856:         $cattype{'unauth'} = $domconfig{'coursecategories'}{'unauth'};
 7857:     } else {
 7858:         $cathash = {};
 7859:         $cattype{'auth'} = 'std';
 7860:         $cattype{'unauth'} = 'std';
 7861:     }
 7862:     if (($cattype{'auth'} eq 'none') && ($cattype{'unauth'} eq 'none')) {
 7863:         $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
 7864:                   '<br />'.
 7865:                   '<br />'.$visactions->{'take'}.'<ul>'.
 7866:                   '<li>'.$visactions->{'dc_chgconf'}.'</li>'.
 7867:                   '</ul>');
 7868:     } elsif (($cattype{'auth'} !~ /^(std|domonly)$/) && ($cattype{'unauth'} !~ /^(std|domonly)$/)) {
 7869:         if ($currsettings->{'uniquecode'}) {
 7870:             $r->print('<span class="LC_info">'.$visactions->{'vis'}.'</span>');
 7871:         } else {
 7872:             $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
 7873:                   '<br />'.
 7874:                   '<br />'.$visactions->{'take'}.'<ul>'.
 7875:                   '<li>'.$visactions->{'dc_setcode'}.'</li>'.
 7876:                   '</ul><br />');
 7877:         }
 7878:     } else {
 7879:         my ($visible,$cansetvis,$vismsgs) = &visible_in_stdcat($cdom,$cnum,\%domconfig);
 7880:         if (ref($visactions) eq 'HASH') {
 7881:             if (!$visible) {
 7882:                 $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
 7883:                           '<br />');
 7884:                 if (ref($vismsgs) eq 'ARRAY') {
 7885:                     $r->print('<br />'.$visactions->{'take'}.'<ul>');
 7886:                     foreach my $item (@{$vismsgs}) {
 7887:                         $r->print('<li>'.$visactions->{$item}.'</li>');
 7888:                     }
 7889:                     $r->print('</ul>');
 7890:                 }
 7891:                 $r->print($cansetvis);
 7892:             }
 7893:         }
 7894:     } 
 7895:     return;
 7896: }
 7897: 
 7898: #---------------------------------------------- end functions for &phase_two
 7899: 
 7900: #--------------------------------- functions for &phase_two and &phase_three
 7901: 
 7902: #--------------------------end of functions for &phase_two and &phase_three
 7903: 
 7904: 1;
 7905: __END__
 7906: 
 7907: 

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