File:  [LON-CAPA] / loncom / interface / loncreateuser.pm
Revision 1.436: download - view: text, annotated - select for diffs
Sun Mar 26 22:11:54 2017 UTC (7 years, 2 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- coding style -- fixed domain for user access logs.

    1: # The LearningOnline Network with CAPA
    2: # Create a user
    3: #
    4: # $Id: loncreateuser.pm,v 1.436 2017/03/26 22:11:54 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:         (&Apache::lonnet::allowed('udp',$ccdomain))) {
  165:         $output .= &build_tools_display($ccuname,$ccdomain,'tools');
  166:     }
  167: 
  168:     my %titles = &Apache::lonlocal::texthash (
  169:                     portfolio => "Disk space allocated to user's portfolio files",
  170:                     author    => "Disk space allocated to user's Authoring Space (if role assigned)",
  171:                  );
  172:     foreach my $name ('portfolio','author') {
  173:         my ($currquota,$quotatype,$inststatus,$defquota) =
  174:             &Apache::loncommon::get_user_quota($ccuname,$ccdomain,$name);
  175:         if ($longinsttype eq '') { 
  176:             if ($inststatus ne '') {
  177:                 if ($usertypes->{$inststatus} ne '') {
  178:                     $longinsttype = $usertypes->{$inststatus};
  179:                 }
  180:             }
  181:         }
  182:         my ($showquota,$custom_on,$custom_off,$defaultinfo);
  183:         $custom_on = ' ';
  184:         $custom_off = ' checked="checked" ';
  185:         if ($quotatype eq 'custom') {
  186:             $custom_on = $custom_off;
  187:             $custom_off = ' ';
  188:             $showquota = $currquota;
  189:             if ($longinsttype eq '') {
  190:                 $defaultinfo = &mt('For this user, the default quota would be [_1]'
  191:                               .' MB.',$defquota);
  192:             } else {
  193:                 $defaultinfo = &mt("For this user, the default quota would be [_1]".
  194:                                    " MB, as determined by the user's institutional".
  195:                                    " affiliation ([_2]).",$defquota,$longinsttype);
  196:             }
  197:         } else {
  198:             if ($longinsttype eq '') {
  199:                 $defaultinfo = &mt('For this user, the default quota is [_1]'
  200:                               .' MB.',$defquota);
  201:             } else {
  202:                 $defaultinfo = &mt("For this user, the default quota of [_1]".
  203:                                    " MB, is determined by the user's institutional".
  204:                                    " affiliation ([_2]).",$defquota,$longinsttype);
  205:             }
  206:         }
  207: 
  208:         if (&Apache::lonnet::allowed('mpq',$ccdomain)) {
  209:             $output .= '<tr class="LC_info_row">'."\n".
  210:                        '    <td>'.$titles{$name}.'</td>'."\n".
  211:                        '  </tr>'."\n".
  212:                        &Apache::loncommon::start_data_table_row()."\n".
  213:                        '  <td><span class="LC_nobreak">'.
  214:                        &mt('Current quota: [_1] MB',$currquota).'</span>&nbsp;&nbsp;'.
  215:                        $defaultinfo.'</td>'."\n".
  216:                        &Apache::loncommon::end_data_table_row()."\n".
  217:                        &Apache::loncommon::start_data_table_row()."\n".
  218:                        '  <td><span class="LC_nobreak">'.$lt{'chqu'}.
  219:                        ': <label>'.
  220:                        '<input type="radio" name="custom_'.$name.'quota" id="custom_'.$name.'quota_off" '.
  221:                        'value="0" '.$custom_off.' onchange="javascript:quota_changes('."'custom','$name'".');"'.
  222:                        ' /><span class="LC_nobreak">'.
  223:                        &mt('Default ([_1] MB)',$defquota).'</span></label>&nbsp;'.
  224:                        '&nbsp;<label><input type="radio" name="custom_'.$name.'quota" id="custom_'.$name.'quota_on" '.
  225:                        'value="1" '.$custom_on.'  onchange="javascript:quota_changes('."'custom','$name'".');"'.
  226:                        ' />'.$lt{'cust'}.':</label>&nbsp;'.
  227:                        '<input type="text" name="'.$name.'quota" id="'.$name.'quota" size ="5" '.
  228:                        'value="'.$showquota.'" onfocus="javascript:quota_changes('."'quota','$name'".');"'.
  229:                        ' />&nbsp;'.&mt('MB').'</span></td>'."\n".
  230:                        &Apache::loncommon::end_data_table_row()."\n";
  231:         }
  232:     }
  233:     $output .= &Apache::loncommon::end_data_table();
  234:     return $output;
  235: }
  236: 
  237: sub build_tools_display {
  238:     my ($ccuname,$ccdomain,$context) = @_;
  239:     my (@usertools,%userenv,$output,@options,%validations,%reqtitles,%reqdisplay,
  240:         $colspan,$isadv,%domconfig);
  241:     my %lt = &Apache::lonlocal::texthash (
  242:                    'blog'       => "Personal User Blog",
  243:                    'aboutme'    => "Personal Information Page",
  244:                    'webdav'     => "WebDAV access to Authoring Spaces (if SSL and author/co-author)",
  245:                    'portfolio'  => "Personal User Portfolio",
  246:                    'avai'       => "Available",
  247:                    'cusa'       => "availability",
  248:                    'chse'       => "Change setting",
  249:                    'usde'       => "Use default",
  250:                    'uscu'       => "Use custom",
  251:                    'official'   => 'Can request creation of official courses',
  252:                    'unofficial' => 'Can request creation of unofficial courses',
  253:                    'community'  => 'Can request creation of communities',
  254:                    'textbook'   => 'Can request creation of textbook courses',
  255:                    'placement'  => 'Can request creation of placement tests',
  256:                    'requestauthor'  => 'Can request author space',
  257:     );
  258:     if ($context eq 'requestcourses') {
  259:         %userenv = &Apache::lonnet::userenvironment($ccdomain,$ccuname,
  260:                       'requestcourses.official','requestcourses.unofficial',
  261:                       'requestcourses.community','requestcourses.textbook',
  262:                       'requestcourses.placement');
  263:         @usertools = ('official','unofficial','community','textbook','placement');
  264:         @options =('norequest','approval','autolimit','validate');
  265:         %validations = &Apache::lonnet::auto_courserequest_checks($ccdomain);
  266:         %reqtitles = &courserequest_titles();
  267:         %reqdisplay = &courserequest_display();
  268:         $colspan = ' colspan="2"';
  269:         %domconfig =
  270:             &Apache::lonnet::get_dom('configuration',['requestcourses'],$ccdomain);
  271:         $isadv = &Apache::lonnet::is_advanced_user($ccdomain,$ccuname);
  272:     } elsif ($context eq 'requestauthor') {
  273:         %userenv = &Apache::lonnet::userenvironment($ccdomain,$ccuname,
  274:                                                     'requestauthor');
  275:         @usertools = ('requestauthor');
  276:         @options =('norequest','approval','automatic');
  277:         %reqtitles = &requestauthor_titles();
  278:         %reqdisplay = &requestauthor_display();
  279:         $colspan = ' colspan="2"';
  280:         %domconfig =
  281:             &Apache::lonnet::get_dom('configuration',['requestauthor'],$ccdomain);
  282:     } else {
  283:         %userenv = &Apache::lonnet::userenvironment($ccdomain,$ccuname,
  284:                           'tools.aboutme','tools.portfolio','tools.blog',
  285:                           'tools.webdav');
  286:         @usertools = ('aboutme','blog','webdav','portfolio');
  287:     }
  288:     foreach my $item (@usertools) {
  289:         my ($custom_access,$curr_access,$cust_on,$cust_off,$tool_on,$tool_off,
  290:             $currdisp,$custdisp,$custradio);
  291:         $cust_off = 'checked="checked" ';
  292:         $tool_on = 'checked="checked" ';
  293:         $curr_access =  
  294:             &Apache::lonnet::usertools_access($ccuname,$ccdomain,$item,undef,
  295:                                               $context);
  296:         if ($context eq 'requestauthor') {
  297:             if ($userenv{$context} ne '') {
  298:                 $cust_on = ' checked="checked" ';
  299:                 $cust_off = '';
  300:             }  
  301:         } elsif ($userenv{$context.'.'.$item} ne '') {
  302:             $cust_on = ' checked="checked" ';
  303:             $cust_off = '';
  304:         }
  305:         if ($context eq 'requestcourses') {
  306:             if ($userenv{$context.'.'.$item} eq '') {
  307:                 $custom_access = &mt('Currently from default setting.');
  308:             } else {
  309:                 $custom_access = &mt('Currently from custom setting.');
  310:             }
  311:         } elsif ($context eq 'requestauthor') {
  312:             if ($userenv{$context} eq '') {
  313:                 $custom_access = &mt('Currently from default setting.');
  314:             } else {
  315:                 $custom_access = &mt('Currently from custom setting.');
  316:             }
  317:         } else {
  318:             if ($userenv{$context.'.'.$item} eq '') {
  319:                 $custom_access =
  320:                     &mt('Availability determined currently from default setting.');
  321:                 if (!$curr_access) {
  322:                     $tool_off = 'checked="checked" ';
  323:                     $tool_on = '';
  324:                 }
  325:             } else {
  326:                 $custom_access =
  327:                     &mt('Availability determined currently from custom setting.');
  328:                 if ($userenv{$context.'.'.$item} == 0) {
  329:                     $tool_off = 'checked="checked" ';
  330:                     $tool_on = '';
  331:                 }
  332:             }
  333:         }
  334:         $output .= '  <tr class="LC_info_row">'."\n".
  335:                    '   <td'.$colspan.'>'.$lt{$item}.'</td>'."\n".
  336:                    '  </tr>'."\n".
  337:                    &Apache::loncommon::start_data_table_row()."\n";
  338:   
  339:         if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
  340:             my ($curroption,$currlimit);
  341:             my $envkey = $context.'.'.$item;
  342:             if ($context eq 'requestauthor') {
  343:                 $envkey = $context;
  344:             }
  345:             if ($userenv{$envkey} ne '') {
  346:                 $curroption = $userenv{$envkey};
  347:             } else {
  348:                 my (@inststatuses);
  349:                 if ($context eq 'requestcourses') {
  350:                     $curroption =
  351:                         &Apache::loncoursequeueadmin::get_processtype('course',$ccuname,$ccdomain,
  352:                                                                       $isadv,$ccdomain,$item,
  353:                                                                       \@inststatuses,\%domconfig);
  354:                 } else {
  355:                      $curroption = 
  356:                          &Apache::loncoursequeueadmin::get_processtype('requestauthor',$ccuname,$ccdomain,
  357:                                                                        $isadv,$ccdomain,undef,
  358:                                                                        \@inststatuses,\%domconfig);
  359:                 }
  360:             }
  361:             if (!$curroption) {
  362:                 $curroption = 'norequest';
  363:             }
  364:             if ($curroption =~ /^autolimit=(\d*)$/) {
  365:                 $currlimit = $1;
  366:                 if ($currlimit eq '') {
  367:                     $currdisp = &mt('Yes, automatic creation');
  368:                 } else {
  369:                     $currdisp = &mt('Yes, up to [quant,_1,request]/user',$currlimit);
  370:                 }
  371:             } else {
  372:                 $currdisp = $reqdisplay{$curroption};
  373:             }
  374:             $custdisp = '<table>';
  375:             foreach my $option (@options) {
  376:                 my $val = $option;
  377:                 if ($option eq 'norequest') {
  378:                     $val = 0;
  379:                 }
  380:                 if ($option eq 'validate') {
  381:                     my $canvalidate = 0;
  382:                     if (ref($validations{$item}) eq 'HASH') {
  383:                         if ($validations{$item}{'_custom_'}) {
  384:                             $canvalidate = 1;
  385:                         }
  386:                     }
  387:                     next if (!$canvalidate);
  388:                 }
  389:                 my $checked = '';
  390:                 if ($option eq $curroption) {
  391:                     $checked = ' checked="checked"';
  392:                 } elsif ($option eq 'autolimit') {
  393:                     if ($curroption =~ /^autolimit/) {
  394:                         $checked = ' checked="checked"';
  395:                     }
  396:                 }
  397:                 my $name = 'crsreq_'.$item;
  398:                 if ($context eq 'requestauthor') {
  399:                     $name = $item;
  400:                 }
  401:                 $custdisp .= '<tr><td><span class="LC_nobreak"><label>'.
  402:                              '<input type="radio" name="'.$name.'" '.
  403:                              'value="'.$val.'"'.$checked.' />'.
  404:                              $reqtitles{$option}.'</label>&nbsp;';
  405:                 if ($option eq 'autolimit') {
  406:                     $custdisp .= '<input type="text" name="'.$name.
  407:                                  '_limit" size="1" '.
  408:                                  'value="'.$currlimit.'" /></span><br />'.
  409:                                  $reqtitles{'unlimited'};
  410:                 } else {
  411:                     $custdisp .= '</span>';
  412:                 }
  413:                 $custdisp .= '</td></tr>';
  414:             }
  415:             $custdisp .= '</table>';
  416:             $custradio = '</span></td><td>'.&mt('Custom setting').'<br />'.$custdisp;
  417:         } else {
  418:             $currdisp = ($curr_access?&mt('Yes'):&mt('No'));
  419:             my $name = $context.'_'.$item;
  420:             if ($context eq 'requestauthor') {
  421:                 $name = $context;
  422:             }
  423:             $custdisp = '<span class="LC_nobreak"><label>'.
  424:                         '<input type="radio" name="'.$name.'"'.
  425:                         ' value="1" '.$tool_on.'/>'.&mt('On').'</label>&nbsp;<label>'.
  426:                         '<input type="radio" name="'.$name.'" value="0" '.
  427:                         $tool_off.'/>'.&mt('Off').'</label></span>';
  428:             $custradio = ('&nbsp;'x2).'--'.$lt{'cusa'}.':&nbsp;'.$custdisp.
  429:                           '</span>';
  430:         }
  431:         $output .= '  <td'.$colspan.'>'.$custom_access.('&nbsp;'x4).
  432:                    $lt{'avai'}.': '.$currdisp.'</td>'."\n".
  433:                    &Apache::loncommon::end_data_table_row()."\n";
  434:         unless (&Apache::lonnet::allowed('udp',$ccdomain)) {
  435:             $output .=
  436:                    &Apache::loncommon::start_data_table_row()."\n".
  437:                    '  <td style="vertical-align:top;"><span class="LC_nobreak">'.
  438:                    $lt{'chse'}.': <label>'.
  439:                    '<input type="radio" name="custom'.$item.'" value="0" '.
  440:                    $cust_off.'/>'.$lt{'usde'}.'</label>'.('&nbsp;' x3).
  441:                    '<label><input type="radio" name="custom'.$item.'" value="1" '.
  442:                    $cust_on.'/>'.$lt{'uscu'}.'</label>'.$custradio.'</td>'.
  443:                    &Apache::loncommon::end_data_table_row()."\n";
  444:         }
  445:     }
  446:     return $output;
  447: }
  448: 
  449: sub coursereq_externaluser {
  450:     my ($ccuname,$ccdomain,$cdom) = @_;
  451:     my (@usertools,@options,%validations,%userenv,$output);
  452:     my %lt = &Apache::lonlocal::texthash (
  453:                    'official'   => 'Can request creation of official courses',
  454:                    'unofficial' => 'Can request creation of unofficial courses',
  455:                    'community'  => 'Can request creation of communities',
  456:                    'textbook'   => 'Can request creation of textbook courses',
  457:                    'placement'  => 'Can request creation of placement tests',
  458:     );
  459: 
  460:     %userenv = &Apache::lonnet::userenvironment($ccdomain,$ccuname,
  461:                       'reqcrsotherdom.official','reqcrsotherdom.unofficial',
  462:                       'reqcrsotherdom.community','reqcrsotherdom.textbook',
  463:                       'reqcrsotherdom.placement');
  464:     @usertools = ('official','unofficial','community','textbook','placement');
  465:     @options = ('approval','validate','autolimit');
  466:     %validations = &Apache::lonnet::auto_courserequest_checks($cdom);
  467:     my $optregex = join('|',@options);
  468:     my %reqtitles = &courserequest_titles();
  469:     foreach my $item (@usertools) {
  470:         my ($curroption,$currlimit,$tooloff);
  471:         if ($userenv{'reqcrsotherdom.'.$item} ne '') {
  472:             my @curr = split(',',$userenv{'reqcrsotherdom.'.$item});
  473:             foreach my $req (@curr) {
  474:                 if ($req =~ /^\Q$cdom\E\:($optregex)=?(\d*)$/) {
  475:                     $curroption = $1;
  476:                     $currlimit = $2;
  477:                     last;
  478:                 }
  479:             }
  480:             if (!$curroption) {
  481:                 $curroption = 'norequest';
  482:                 $tooloff = ' checked="checked"';
  483:             }
  484:         } else {
  485:             $curroption = 'norequest';
  486:             $tooloff = ' checked="checked"';
  487:         }
  488:         $output.= &Apache::loncommon::start_data_table_row()."\n".
  489:                   '  <td><span class="LC_nobreak">'.$lt{$item}.': </span></td><td>'.
  490:                   '<table><tr><td valign="top">'."\n".
  491:                   '<label><input type="radio" name="reqcrsotherdom_'.$item.
  492:                   '" value=""'.$tooloff.' />'.$reqtitles{'norequest'}.
  493:                   '</label></td>';
  494:         foreach my $option (@options) {
  495:             if ($option eq 'validate') {
  496:                 my $canvalidate = 0;
  497:                 if (ref($validations{$item}) eq 'HASH') {
  498:                     if ($validations{$item}{'_external_'}) {
  499:                         $canvalidate = 1;
  500:                     }
  501:                 }
  502:                 next if (!$canvalidate);
  503:             }
  504:             my $checked = '';
  505:             if ($option eq $curroption) {
  506:                 $checked = ' checked="checked"';
  507:             }
  508:             $output .= '<td valign="top"><span class="LC_nobreak"><label>'.
  509:                        '<input type="radio" name="reqcrsotherdom_'.$item.
  510:                        '" value="'.$option.'"'.$checked.' />'.
  511:                        $reqtitles{$option}.'</label>';
  512:             if ($option eq 'autolimit') {
  513:                 $output .= '&nbsp;<input type="text" name="reqcrsotherdom_'.
  514:                            $item.'_limit" size="1" '.
  515:                            'value="'.$currlimit.'" /></span>'.
  516:                            '<br />'.$reqtitles{'unlimited'};
  517:             } else {
  518:                 $output .= '</span>';
  519:             }
  520:             $output .= '</td>';
  521:         }
  522:         $output .= '</td></tr></table></td>'."\n".
  523:                    &Apache::loncommon::end_data_table_row()."\n";
  524:     }
  525:     return $output;
  526: }
  527: 
  528: sub domainrole_req {
  529:     my ($ccuname,$ccdomain) = @_;
  530:     return '<br /><h3>'.
  531:            &mt('User Can Request Assignment of Domain Roles?').
  532:            '</h3>'."\n".
  533:            &Apache::loncommon::start_data_table().
  534:            &build_tools_display($ccuname,$ccdomain,
  535:                                 'requestauthor').
  536:            &Apache::loncommon::end_data_table();
  537: }
  538: 
  539: sub courserequest_titles {
  540:     my %titles = &Apache::lonlocal::texthash (
  541:                                    official   => 'Official',
  542:                                    unofficial => 'Unofficial',
  543:                                    community  => 'Communities',
  544:                                    textbook   => 'Textbook',
  545:                                    placement  => 'Placement Tests',
  546:                                    norequest  => 'Not allowed',
  547:                                    approval   => 'Approval by Dom. Coord.',
  548:                                    validate   => 'With validation',
  549:                                    autolimit  => 'Numerical limit',
  550:                                    unlimited  => '(blank for unlimited)',
  551:                  );
  552:     return %titles;
  553: }
  554: 
  555: sub courserequest_display {
  556:     my %titles = &Apache::lonlocal::texthash (
  557:                                    approval   => 'Yes, need approval',
  558:                                    validate   => 'Yes, with validation',
  559:                                    norequest  => 'No',
  560:    );
  561:    return %titles;
  562: }
  563: 
  564: sub requestauthor_titles {
  565:     my %titles = &Apache::lonlocal::texthash (
  566:                                    norequest  => 'Not allowed',
  567:                                    approval   => 'Approval by Dom. Coord.',
  568:                                    automatic  => 'Automatic approval',
  569:                  );
  570:     return %titles;
  571: 
  572: }
  573: 
  574: sub requestauthor_display {
  575:     my %titles = &Apache::lonlocal::texthash (
  576:                                    approval   => 'Yes, need approval',
  577:                                    automatic  => 'Yes, automatic approval',
  578:                                    norequest  => 'No',
  579:    );
  580:    return %titles;
  581: }
  582: 
  583: sub requestchange_display {
  584:     my %titles = &Apache::lonlocal::texthash (
  585:                                    approval   => "availability set to 'on' (approval required)", 
  586:                                    automatic  => "availability set to 'on' (automatic approval)",
  587:                                    norequest  => "availability set to 'off'",
  588:    );
  589:    return %titles;
  590: }
  591: 
  592: sub curr_requestauthor {
  593:     my ($uname,$udom,$isadv,$inststatuses,$domconfig) = @_;
  594:     return unless ((ref($inststatuses) eq 'ARRAY') && (ref($domconfig) eq 'HASH'));
  595:     if ($uname eq '' || $udom eq '') {
  596:         $uname = $env{'user.name'};
  597:         $udom = $env{'user.domain'};
  598:         $isadv = $env{'user.adv'};
  599:     }
  600:     my (%userenv,%settings,$val);
  601:     my @options = ('automatic','approval');
  602:     %userenv =
  603:         &Apache::lonnet::userenvironment($udom,$uname,'requestauthor','inststatus');
  604:     if ($userenv{'requestauthor'}) {
  605:         $val = $userenv{'requestauthor'};
  606:         @{$inststatuses} = ('_custom_');
  607:     } else {
  608:         my %alltasks;
  609:         if (ref($domconfig->{'requestauthor'}) eq 'HASH') {
  610:             %settings = %{$domconfig->{'requestauthor'}};
  611:             if (($isadv) && ($settings{'_LC_adv'} ne '')) {
  612:                 $val = $settings{'_LC_adv'};
  613:                 @{$inststatuses} = ('_LC_adv_');
  614:             } else {
  615:                 if ($userenv{'inststatus'} ne '') {
  616:                     @{$inststatuses} = split(',',$userenv{'inststatus'});
  617:                 } else {
  618:                     @{$inststatuses} = ('default');
  619:                 }
  620:                 foreach my $status (@{$inststatuses}) {
  621:                     if (exists($settings{$status})) {
  622:                         my $value = $settings{$status};
  623:                         next unless ($value);
  624:                         unless (exists($alltasks{$value})) {
  625:                             if (ref($alltasks{$value}) eq 'ARRAY') {
  626:                                 unless(grep(/^\Q$status\E$/,@{$alltasks{$value}})) {
  627:                                     push(@{$alltasks{$value}},$status);
  628:                                 }
  629:                             } else {
  630:                                 @{$alltasks{$value}} = ($status);
  631:                             }
  632:                         }
  633:                     }
  634:                 }
  635:                 foreach my $option (@options) {
  636:                     if ($alltasks{$option}) {
  637:                         $val = $option;
  638:                         last;
  639:                     }
  640:                 }
  641:             }
  642:         }
  643:     }
  644:     return $val;
  645: }
  646: 
  647: # =================================================================== Phase one
  648: 
  649: sub print_username_entry_form {
  650:     my ($r,$context,$response,$srch,$forcenewuser,$crstype,$brcrum) = @_;
  651:     my $defdom=$env{'request.role.domain'};
  652:     my $formtoset = 'crtuser';
  653:     if (exists($env{'form.startrolename'})) {
  654:         $formtoset = 'docustom';
  655:         $env{'form.rolename'} = $env{'form.startrolename'};
  656:     } elsif ($env{'form.origform'} eq 'crtusername') {
  657:         $formtoset =  $env{'form.origform'};
  658:     }
  659: 
  660:     my ($jsback,$elements) = &crumb_utilities();
  661: 
  662:     my $jscript = &Apache::loncommon::studentbrowser_javascript()."\n".
  663:         '<script type="text/javascript">'."\n".
  664:         '// <![CDATA['."\n".
  665:         &Apache::lonhtmlcommon::set_form_elements($elements->{$formtoset})."\n".
  666:         '// ]]>'."\n".
  667:         '</script>'."\n";
  668: 
  669:     my %existingroles=&Apache::lonuserutils::my_custom_roles($crstype);
  670:     if (($env{'form.action'} eq 'custom') && (keys(%existingroles) > 0)
  671:         && (&Apache::lonnet::allowed('mcr','/'))) {
  672:         $jscript .= &customrole_javascript();
  673:     }
  674:     my $helpitem = 'Course_Change_Privileges';
  675:     if ($env{'form.action'} eq 'custom') {
  676:         $helpitem = 'Course_Editing_Custom_Roles';
  677:     } elsif ($env{'form.action'} eq 'singlestudent') {
  678:         $helpitem = 'Course_Add_Student';
  679:     } elsif ($env{'form.action'} eq 'accesslogs') {
  680:         $helpitem = 'Domain_User_Access_Logs';
  681:     }
  682:     my %breadcrumb_text = &singleuser_breadcrumb($crstype,$context,$defdom);
  683:     if ($env{'form.action'} eq 'custom') {
  684:         push(@{$brcrum},
  685:                  {href=>"javascript:backPage(document.crtuser)",       
  686:                   text=>"Pick custom role",
  687:                   help => $helpitem,}
  688:                  );
  689:     } else {
  690:         push (@{$brcrum},
  691:                   {href => "javascript:backPage(document.crtuser)",
  692:                    text => $breadcrumb_text{'search'},
  693:                    help => $helpitem,
  694:                    faq  => 282,
  695:                    bug  => 'Instructor Interface',}
  696:                   );
  697:     }
  698:     my %loaditems = (
  699:                 'onload' => "javascript:setFormElements(document.$formtoset)",
  700:                     );
  701:     my $args = {bread_crumbs           => $brcrum,
  702:                 bread_crumbs_component => 'User Management',
  703:                 add_entries            => \%loaditems,};
  704:     $r->print(&Apache::loncommon::start_page('User Management',$jscript,$args));
  705: 
  706:     my %lt=&Apache::lonlocal::texthash(
  707:                     'srst' => 'Search for a user and enroll as a student',
  708:                     'srme' => 'Search for a user and enroll as a member',
  709:                     'srad' => 'Search for a user and modify/add user information or roles',
  710:                     'srvu' => 'Search for a user and view user information and roles',
  711:                     'srva' => 'Search for a user and view access log information',
  712: 		    'usr'  => "Username",
  713:                     'dom'  => "Domain",
  714:                     'ecrp' => "Define or Edit Custom Role",
  715:                     'nr'   => "role name",
  716:                     'cre'  => "Next",
  717: 				       );
  718: 
  719:     if ($env{'form.action'} eq 'custom') {
  720:         if (&Apache::lonnet::allowed('mcr','/')) {
  721:             my $newroletext = &mt('Define new custom role:');
  722:             $r->print('<form action="/adm/createuser" method="post" name="docustom">'.
  723:                       '<input type="hidden" name="action" value="'.$env{'form.action'}.'" />'.
  724:                       '<input type="hidden" name="phase" value="selected_custom_edit" />'.
  725:                       '<h3>'.$lt{'ecrp'}.'</h3>'.
  726:                       &Apache::loncommon::start_data_table().
  727:                       &Apache::loncommon::start_data_table_row().
  728:                       '<td>');
  729:             if (keys(%existingroles) > 0) {
  730:                 $r->print('<br /><label><input type="radio" name="customroleaction" value="new" checked="checked" onclick="setCustomFields();" /><b>'.$newroletext.'</b></label>');
  731:             } else {
  732:                 $r->print('<br /><input type="hidden" name="customroleaction" value="new" /><b>'.$newroletext.'</b>');
  733:             }
  734:             $r->print('</td><td align="center">'.$lt{'nr'}.'<br /><input type="text" size="15" name="newrolename" onfocus="setCustomAction('."'new'".');" /></td>'.
  735:                       &Apache::loncommon::end_data_table_row());
  736:             if (keys(%existingroles) > 0) {
  737:                 $r->print(&Apache::loncommon::start_data_table_row().'<td><br />'.
  738:                           '<label><input type="radio" name="customroleaction" value="edit" onclick="setCustomFields();"/><b>'.
  739:                           &mt('View/Modify existing role:').'</b></label></td>'.
  740:                           '<td align="center"><br />'.
  741:                           '<select name="rolename" onchange="setCustomAction('."'edit'".');">'.
  742:                           '<option value="" selected="selected">'.
  743:                           &mt('Select'));
  744:                 foreach my $role (sort(keys(%existingroles))) {
  745:                     $r->print('<option value="'.$role.'">'.$role.'</option>');
  746:                 }
  747:                 $r->print('</select>'.
  748:                           '</td>'.
  749:                           &Apache::loncommon::end_data_table_row());
  750:             }
  751:             $r->print(&Apache::loncommon::end_data_table().'<p>'.
  752:                       '<input name="customeditor" type="submit" value="'.
  753:                       $lt{'cre'}.'" /></p>'.
  754:                       '</form>');
  755:         }
  756:     } else {
  757:         my $actiontext = $lt{'srad'};
  758:         my $fixeddom;
  759:         if ($env{'form.action'} eq 'singlestudent') {
  760:             if ($crstype eq 'Community') {
  761:                 $actiontext = $lt{'srme'};
  762:             } else {
  763:                 $actiontext = $lt{'srst'};
  764:             }
  765:         } elsif ($env{'form.action'} eq 'accesslogs') {
  766:             $actiontext = $lt{'srva'};
  767:             $fixeddom = 1;
  768:         } elsif (($env{'form.action'} eq 'singleuser') &&
  769:                  ($context eq 'domain') && (!&Apache::lonnet::allowed('mau',$defdom))) {
  770:             $actiontext = $lt{'srvu'};
  771:         }
  772:         $r->print("<h3>$actiontext</h3>");
  773:         if ($env{'form.origform'} ne 'crtusername') {
  774:             if ($response) {
  775:                $r->print("\n<div>$response</div>".
  776:                          '<br clear="all" />');
  777:             }
  778:         }
  779:         $r->print(&entry_form($defdom,$srch,$forcenewuser,$context,$response,$crstype,$fixeddom));
  780:     }
  781: }
  782: 
  783: sub customrole_javascript {
  784:     my $js = <<"END";
  785: <script type="text/javascript">
  786: // <![CDATA[
  787: 
  788: function setCustomFields() {
  789:     if (document.docustom.customroleaction.length > 0) {
  790:         for (var i=0; i<document.docustom.customroleaction.length; i++) {
  791:             if (document.docustom.customroleaction[i].checked) {
  792:                 if (document.docustom.customroleaction[i].value == 'new') {
  793:                     document.docustom.rolename.selectedIndex = 0;
  794:                 } else {
  795:                     document.docustom.newrolename.value = '';
  796:                 }
  797:             }
  798:         }
  799:     }
  800:     return;
  801: }
  802: 
  803: function setCustomAction(caller) {
  804:     if (document.docustom.customroleaction.length > 0) {
  805:         for (var i=0; i<document.docustom.customroleaction.length; i++) {
  806:             if (document.docustom.customroleaction[i].value == caller) {
  807:                 document.docustom.customroleaction[i].checked = true;
  808:             }
  809:         }
  810:     }
  811:     setCustomFields();
  812:     return;
  813: }
  814: 
  815: // ]]>
  816: </script>
  817: END
  818:     return $js;
  819: }
  820: 
  821: sub entry_form {
  822:     my ($dom,$srch,$forcenewuser,$context,$responsemsg,$crstype,$fixeddom) = @_;
  823:     my ($usertype,$inexact);
  824:     if (ref($srch) eq 'HASH') {
  825:         if (($srch->{'srchin'} eq 'dom') &&
  826:             ($srch->{'srchby'} eq 'uname') &&
  827:             ($srch->{'srchtype'} eq 'exact') &&
  828:             ($srch->{'srchdomain'} ne '') &&
  829:             ($srch->{'srchterm'} ne '')) {
  830:             my (%curr_rules,%got_rules);
  831:             my ($rules,$ruleorder) =
  832:                 &Apache::lonnet::inst_userrules($srch->{'srchdomain'},'username');
  833:             $usertype = &Apache::lonuserutils::check_usertype($srch->{'srchdomain'},$srch->{'srchterm'},$rules,\%curr_rules,\%got_rules);
  834:         } else {
  835:             $inexact = 1;
  836:         }
  837:     }
  838:     my $cancreate =
  839:         &Apache::lonuserutils::can_create_user($dom,$context,$usertype);
  840:     my ($userpicker,$cansearch) = 
  841:        &Apache::loncommon::user_picker($dom,$srch,$forcenewuser,
  842:                                        'document.crtuser',$cancreate,$usertype,$context,$fixeddom);
  843:     my $srchbutton = &mt('Search');
  844:     if ($env{'form.action'} eq 'singlestudent') {
  845:         $srchbutton = &mt('Search and Enroll');
  846:     } elsif ($env{'form.action'} eq 'accesslogs') {
  847:         $srchbutton = &mt('Search');
  848:     } elsif ($cancreate && $responsemsg ne '' && $inexact) {
  849:         $srchbutton = &mt('Search or Add New User');
  850:     }
  851:     my $output;
  852:     if ($cansearch) {
  853:         $output = <<"ENDBLOCK";
  854: <form action="/adm/createuser" method="post" name="crtuser">
  855: <input type="hidden" name="action" value="$env{'form.action'}" />
  856: <input type="hidden" name="phase" value="get_user_info" />
  857: $userpicker
  858: <input name="userrole" type="button" value="$srchbutton" onclick="javascript:validateEntry(document.crtuser)" />
  859: </form>
  860: ENDBLOCK
  861:     } else {
  862:         $output = '<p>'.$userpicker.'</p>';
  863:     }
  864:     if (($env{'form.phase'} eq '') && ($env{'form.action'} ne 'accesslogs') &&
  865:         (!(($env{'form.action'} eq 'singleuser') && ($context eq 'domain') &&
  866:         (!&Apache::lonnet::allowed('mau',$env{'request.role.domain'}))))) {
  867:         my $defdom=$env{'request.role.domain'};
  868:         my $domform = &Apache::loncommon::select_dom_form($defdom,'srchdomain');
  869:         my %lt=&Apache::lonlocal::texthash(
  870:                   'enro' => 'Enroll one student',
  871:                   'enrm' => 'Enroll one member',
  872:                   'admo' => 'Add/modify a single user',
  873:                   'crea' => 'create new user if required',
  874:                   'uskn' => "username is known",
  875:                   'crnu' => 'Create a new user',
  876:                   'usr'  => 'Username',
  877:                   'dom'  => 'in domain',
  878:                   'enrl' => 'Enroll',
  879:                   'cram'  => 'Create/Modify user',
  880:         );
  881:         my $sellink=&Apache::loncommon::selectstudent_link('crtusername','srchterm','srchdomain');
  882:         my ($title,$buttontext,$showresponse);
  883:         if ($env{'form.action'} eq 'singlestudent') {
  884:             if ($crstype eq 'Community') {
  885:                 $title = $lt{'enrm'};
  886:             } else {
  887:                 $title = $lt{'enro'};
  888:             }
  889:             $buttontext = $lt{'enrl'};
  890:         } else {
  891:             $title = $lt{'admo'};
  892:             $buttontext = $lt{'cram'};
  893:         }
  894:         if ($cancreate) {
  895:             $title .= ' <span class="LC_cusr_subheading">('.$lt{'crea'}.')</span>';
  896:         } else {
  897:             $title .= ' <span class="LC_cusr_subheading">('.$lt{'uskn'}.')</span>';
  898:         }
  899:         if ($env{'form.origform'} eq 'crtusername') {
  900:             $showresponse = $responsemsg;
  901:         }
  902:         $output .= <<"ENDDOCUMENT";
  903: <br />
  904: <form action="/adm/createuser" method="post" name="crtusername">
  905: <input type="hidden" name="action" value="$env{'form.action'}" />
  906: <input type="hidden" name="phase" value="createnewuser" />
  907: <input type="hidden" name="srchtype" value="exact" />
  908: <input type="hidden" name="srchby" value="uname" />
  909: <input type="hidden" name="srchin" value="dom" />
  910: <input type="hidden" name="forcenewuser" value="1" />
  911: <input type="hidden" name="origform" value="crtusername" />
  912: <h3>$title</h3>
  913: $showresponse
  914: <table>
  915:  <tr>
  916:   <td>$lt{'usr'}:</td>
  917:   <td><input type="text" size="15" name="srchterm" /></td>
  918:   <td>&nbsp;$lt{'dom'}:</td><td>$domform</td>
  919:   <td>&nbsp;$sellink&nbsp;</td>
  920:   <td>&nbsp;<input name="userrole" type="submit" value="$buttontext" /></td>
  921:  </tr>
  922: </table>
  923: </form>
  924: ENDDOCUMENT
  925:     }
  926:     return $output;
  927: }
  928: 
  929: sub user_modification_js {
  930:     my ($pjump_def,$dc_setcourse_code,$nondc_setsection_code,$groupslist)=@_;
  931:     
  932:     return <<END;
  933: <script type="text/javascript" language="Javascript">
  934: // <![CDATA[
  935: 
  936:     $pjump_def
  937:     $dc_setcourse_code
  938: 
  939:     function dateset() {
  940:         eval("document.cu."+document.cu.pres_marker.value+
  941:             ".value=document.cu.pres_value.value");
  942:         modalWindow.close();
  943:     }
  944: 
  945:     $nondc_setsection_code
  946: // ]]>
  947: </script>
  948: END
  949: }
  950: 
  951: # =================================================================== Phase two
  952: sub print_user_selection_page {
  953:     my ($r,$response,$srch,$srch_results,$srcharray,$context,$opener_elements,$crstype,$brcrum) = @_;
  954:     my @fields = ('username','domain','lastname','firstname','permanentemail');
  955:     my $sortby = $env{'form.sortby'};
  956: 
  957:     if (!grep(/^\Q$sortby\E$/,@fields)) {
  958:         $sortby = 'lastname';
  959:     }
  960: 
  961:     my ($jsback,$elements) = &crumb_utilities();
  962: 
  963:     my $jscript = (<<ENDSCRIPT);
  964: <script type="text/javascript">
  965: // <![CDATA[
  966: function pickuser(uname,udom) {
  967:     document.usersrchform.seluname.value=uname;
  968:     document.usersrchform.seludom.value=udom;
  969:     document.usersrchform.phase.value="userpicked";
  970:     document.usersrchform.submit();
  971: }
  972: 
  973: $jsback
  974: // ]]>
  975: </script>
  976: ENDSCRIPT
  977: 
  978:     my %lt=&Apache::lonlocal::texthash(
  979:                                        'usrch'          => "User Search to add/modify roles",
  980:                                        'stusrch'        => "User Search to enroll student",
  981:                                        'memsrch'        => "User Search to enroll member",
  982:                                        'srcva'          => "Search for a user and view access log information",
  983:                                        'usrvu'          => "User Search to view user roles",
  984:                                        'usel'           => "Select a user to add/modify roles",
  985:                                        'suvr'           => "Select a user to view roles",
  986:                                        'stusel'         => "Select a user to enroll as a student",
  987:                                        'memsel'         => "Select a user to enroll as a member",
  988:                                        'vacsel'         => "Select a user to view access log",
  989:                                        'username'       => "username",
  990:                                        'domain'         => "domain",
  991:                                        'lastname'       => "last name",
  992:                                        'firstname'      => "first name",
  993:                                        'permanentemail' => "permanent e-mail",
  994:                                       );
  995:     if ($context eq 'requestcrs') {
  996:         $r->print('<div>');
  997:     } else {
  998:         my %breadcrumb_text = &singleuser_breadcrumb($crstype,$context,$srch->{'srchdomain'});
  999:         my $helpitem;
 1000:         if ($env{'form.action'} eq 'singleuser') {
 1001:             $helpitem = 'Course_Change_Privileges';
 1002:         } elsif ($env{'form.action'} eq 'singlestudent') {
 1003:             $helpitem = 'Course_Add_Student';
 1004:         }
 1005:         push (@{$brcrum},
 1006:                   {href => "javascript:backPage(document.usersrchform,'','')",
 1007:                    text => $breadcrumb_text{'search'},
 1008:                    faq  => 282,
 1009:                    bug  => 'Instructor Interface',},
 1010:                   {href => "javascript:backPage(document.usersrchform,'get_user_info','select')",
 1011:                    text => $breadcrumb_text{'userpicked'},
 1012:                    faq  => 282,
 1013:                    bug  => 'Instructor Interface',
 1014:                    help => $helpitem}
 1015:                   );
 1016:         $r->print(&Apache::loncommon::start_page('User Management',$jscript,{bread_crumbs => $brcrum}));
 1017:         if ($env{'form.action'} eq 'singleuser') {
 1018:             my $readonly;
 1019:             if (($context eq 'domain') && (!&Apache::lonnet::allowed('mau',$srch->{'srchdomain'}))) {
 1020:                 $readonly = 1;
 1021:                 $r->print("<b>$lt{'usrvu'}</b><br />");
 1022:             } else {
 1023:                 $r->print("<b>$lt{'usrch'}</b><br />");
 1024:             }
 1025:             $r->print(&entry_form($srch->{'srchdomain'},$srch,undef,$context,undef,$crstype));
 1026:             if ($readonly) {
 1027:                 $r->print('<h3>'.$lt{'suvr'}.'</h3>');
 1028:             } else {
 1029:                 $r->print('<h3>'.$lt{'usel'}.'</h3>');
 1030:             }
 1031:         } elsif ($env{'form.action'} eq 'singlestudent') {
 1032:             $r->print($jscript."<b>");
 1033:             if ($crstype eq 'Community') {
 1034:                 $r->print($lt{'memsrch'});
 1035:             } else {
 1036:                 $r->print($lt{'stusrch'});
 1037:             }
 1038:             $r->print("</b><br />");
 1039:             $r->print(&entry_form($srch->{'srchdomain'},$srch,undef,$context,undef,$crstype));
 1040:             $r->print('</form><h3>');
 1041:             if ($crstype eq 'Community') {
 1042:                 $r->print($lt{'memsel'});
 1043:             } else {
 1044:                 $r->print($lt{'stusel'});
 1045:             }
 1046:             $r->print('</h3>');
 1047:         } elsif ($env{'form.action'} eq 'accesslogs') {
 1048:             $r->print("<b>$lt{'srcva'}</b><br />");
 1049:             $r->print(&entry_form($srch->{'srchdomain'},$srch,undef,'accesslogs',undef,undef,1));
 1050:             $r->print('<h3>'.$lt{'vacsel'}.'</h3>');
 1051:         }
 1052:     }
 1053:     $r->print('<form name="usersrchform" method="post" action="">'.
 1054:               &Apache::loncommon::start_data_table()."\n".
 1055:               &Apache::loncommon::start_data_table_header_row()."\n".
 1056:               ' <th> </th>'."\n");
 1057:     foreach my $field (@fields) {
 1058:         $r->print(' <th><a href="javascript:document.usersrchform.sortby.value='.
 1059:                   "'".$field."'".';document.usersrchform.submit();">'.
 1060:                   $lt{$field}.'</a></th>'."\n");
 1061:     }
 1062:     $r->print(&Apache::loncommon::end_data_table_header_row());
 1063: 
 1064:     my @sorted_users = sort {
 1065:         lc($srch_results->{$a}->{$sortby})   cmp lc($srch_results->{$b}->{$sortby})
 1066:             ||
 1067:         lc($srch_results->{$a}->{lastname})  cmp lc($srch_results->{$b}->{lastname})
 1068:             ||
 1069:         lc($srch_results->{$a}->{firstname}) cmp lc($srch_results->{$b}->{firstname})
 1070: 	    ||
 1071: 	lc($a) cmp lc($b)
 1072:         } (keys(%$srch_results));
 1073: 
 1074:     foreach my $user (@sorted_users) {
 1075:         my ($uname,$udom) = split(/:/,$user);
 1076:         my $onclick;
 1077:         if ($context eq 'requestcrs') {
 1078:             $onclick =
 1079:                 'onclick="javascript:gochoose('."'$uname','$udom',".
 1080:                                                "'$srch_results->{$user}->{firstname}',".
 1081:                                                "'$srch_results->{$user}->{lastname}',".
 1082:                                                "'$srch_results->{$user}->{permanentemail}'".');"';
 1083:         } else {
 1084:             $onclick =
 1085:                 ' onclick="javascript:pickuser('."'".$uname."'".','."'".$udom."'".');"';
 1086:         }
 1087:         $r->print(&Apache::loncommon::start_data_table_row().
 1088:                   '<td><input type="button" name="seluser" value="'.&mt('Select').'" '.
 1089:                   $onclick.' /></td>'.
 1090:                   '<td><tt>'.$uname.'</tt></td>'.
 1091:                   '<td><tt>'.$udom.'</tt></td>');
 1092:         foreach my $field ('lastname','firstname','permanentemail') {
 1093:             $r->print('<td>'.$srch_results->{$user}->{$field}.'</td>');
 1094:         }
 1095:         $r->print(&Apache::loncommon::end_data_table_row());
 1096:     }
 1097:     $r->print(&Apache::loncommon::end_data_table().'<br /><br />');
 1098:     if (ref($srcharray) eq 'ARRAY') {
 1099:         foreach my $item (@{$srcharray}) {
 1100:             $r->print('<input type="hidden" name="'.$item.'" value="'.$env{'form.'.$item}.'" />'."\n");
 1101:         }
 1102:     }
 1103:     $r->print(' <input type="hidden" name="sortby" value="'.$sortby.'" />'."\n".
 1104:               ' <input type="hidden" name="seluname" value="" />'."\n".
 1105:               ' <input type="hidden" name="seludom" value="" />'."\n".
 1106:               ' <input type="hidden" name="currstate" value="select" />'."\n".
 1107:               ' <input type="hidden" name="phase" value="get_user_info" />'."\n".
 1108:               ' <input type="hidden" name="action" value="'.$env{'form.action'}.'" />'."\n");
 1109:     if ($context eq 'requestcrs') {
 1110:         $r->print($opener_elements.'</form></div>');
 1111:     } else {
 1112:         $r->print($response.'</form>');
 1113:     }
 1114: }
 1115: 
 1116: sub print_user_query_page {
 1117:     my ($r,$caller,$brcrum) = @_;
 1118: # FIXME - this is for a network-wide name search (similar to catalog search)
 1119: # To use frames with similar behavior to catalog/portfolio search.
 1120: # To be implemented. 
 1121:     return;
 1122: }
 1123: 
 1124: sub print_user_modification_page {
 1125:     my ($r,$ccuname,$ccdomain,$srch,$response,$context,$permission,$crstype,
 1126:         $brcrum,$showcredits) = @_;
 1127:     if (($ccuname eq '') || ($ccdomain eq '')) {
 1128:         my $usermsg = &mt('No username and/or domain provided.');
 1129:         $env{'form.phase'} = '';
 1130: 	&print_username_entry_form($r,$context,$usermsg,'','',$crstype,$brcrum);
 1131:         return;
 1132:     }
 1133:     my ($form,$formname);
 1134:     if ($env{'form.action'} eq 'singlestudent') {
 1135:         $form = 'document.enrollstudent';
 1136:         $formname = 'enrollstudent';
 1137:     } else {
 1138:         $form = 'document.cu';
 1139:         $formname = 'cu';
 1140:     }
 1141:     my %abv_auth = &auth_abbrev();
 1142:     my (%rulematch,%inst_results,$newuser,%alerts,%curr_rules,%got_rules);
 1143:     my $uhome=&Apache::lonnet::homeserver($ccuname,$ccdomain);
 1144:     if ($uhome eq 'no_host') {
 1145:         my $usertype;
 1146:         my ($rules,$ruleorder) =
 1147:             &Apache::lonnet::inst_userrules($ccdomain,'username');
 1148:             $usertype =
 1149:                 &Apache::lonuserutils::check_usertype($ccdomain,$ccuname,$rules,
 1150:                                                       \%curr_rules,\%got_rules);
 1151:         my $cancreate =
 1152:             &Apache::lonuserutils::can_create_user($ccdomain,$context,
 1153:                                                    $usertype);
 1154:         if (!$cancreate) {
 1155:             my $helplink = 'javascript:helpMenu('."'display'".')';
 1156:             my %usertypetext = (
 1157:                 official   => 'institutional',
 1158:                 unofficial => 'non-institutional',
 1159:             );
 1160:             my $response;
 1161:             if ($env{'form.origform'} eq 'crtusername') {
 1162:                 $response = '<span class="LC_warning">'.
 1163:                             &mt('No match found for the username [_1] in LON-CAPA domain: [_2]',
 1164:                                 '<b>'.$ccuname.'</b>',$ccdomain).
 1165:                             '</span><br />';
 1166:             }
 1167:             $response .= '<p class="LC_warning">'
 1168:                         .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
 1169:                         .' ';
 1170:             if ($context eq 'domain') {
 1171:                 $response .= &mt('Please contact a [_1] for assistance.',
 1172:                                  &Apache::lonnet::plaintext('dc'));
 1173:             } else {
 1174:                 $response .= &mt('Please contact the [_1]helpdesk[_2] for assistance.'
 1175:                                 ,'<a href="'.$helplink.'">','</a>');
 1176:             }
 1177:             $response .= '</p><br />';
 1178:             $env{'form.phase'} = '';
 1179:             &print_username_entry_form($r,$context,$response,undef,undef,$crstype,$brcrum);
 1180:             return;
 1181:         }
 1182:         $newuser = 1;
 1183:         my $checkhash;
 1184:         my $checks = { 'username' => 1 };
 1185:         $checkhash->{$ccuname.':'.$ccdomain} = { 'newuser' => $newuser };
 1186:         &Apache::loncommon::user_rule_check($checkhash,$checks,
 1187:             \%alerts,\%rulematch,\%inst_results,\%curr_rules,\%got_rules);
 1188:         if (ref($alerts{'username'}) eq 'HASH') {
 1189:             if (ref($alerts{'username'}{$ccdomain}) eq 'HASH') {
 1190:                 my $domdesc =
 1191:                     &Apache::lonnet::domain($ccdomain,'description');
 1192:                 if ($alerts{'username'}{$ccdomain}{$ccuname}) {
 1193:                     my $userchkmsg;
 1194:                     if (ref($curr_rules{$ccdomain}) eq 'HASH') {  
 1195:                         $userchkmsg = 
 1196:                             &Apache::loncommon::instrule_disallow_msg('username',
 1197:                                                                  $domdesc,1).
 1198:                         &Apache::loncommon::user_rule_formats($ccdomain,
 1199:                             $domdesc,$curr_rules{$ccdomain}{'username'},
 1200:                             'username');
 1201:                     }
 1202:                     $env{'form.phase'} = '';
 1203:                     &print_username_entry_form($r,$context,$userchkmsg,undef,undef,$crstype,$brcrum);
 1204:                     return;
 1205:                 }
 1206:             }
 1207:         }
 1208:     } else {
 1209:         $newuser = 0;
 1210:     }
 1211:     if ($response) {
 1212:         $response = '<br />'.$response;
 1213:     }
 1214: 
 1215:     my $pjump_def = &Apache::lonhtmlcommon::pjump_javascript_definition();
 1216:     my $dc_setcourse_code = '';
 1217:     my $nondc_setsection_code = '';                                        
 1218:     my %loaditem;
 1219: 
 1220:     my $groupslist = &Apache::lonuserutils::get_groupslist();
 1221: 
 1222:     my $js = &validation_javascript($context,$ccdomain,$pjump_def,$crstype,
 1223:                                $groupslist,$newuser,$formname,\%loaditem);
 1224:     my %breadcrumb_text = &singleuser_breadcrumb($crstype,$context,$ccdomain);
 1225:     my $helpitem = 'Course_Change_Privileges';
 1226:     if ($env{'form.action'} eq 'singlestudent') {
 1227:         $helpitem = 'Course_Add_Student';
 1228:     }
 1229:     push (@{$brcrum},
 1230:         {href => "javascript:backPage($form)",
 1231:          text => $breadcrumb_text{'search'},
 1232:          faq  => 282,
 1233:          bug  => 'Instructor Interface',});
 1234:     if ($env{'form.phase'} eq 'userpicked') {
 1235:        push(@{$brcrum},
 1236:               {href => "javascript:backPage($form,'get_user_info','select')",
 1237:                text => $breadcrumb_text{'userpicked'},
 1238:                faq  => 282,
 1239:                bug  => 'Instructor Interface',});
 1240:     }
 1241:     push(@{$brcrum},
 1242:             {href => "javascript:backPage($form,'$env{'form.phase'}','modify')",
 1243:              text => $breadcrumb_text{'modify'},
 1244:              faq  => 282,
 1245:              bug  => 'Instructor Interface',
 1246:              help => $helpitem});
 1247:     my $args = {'add_entries'           => \%loaditem,
 1248:                 'bread_crumbs'          => $brcrum,
 1249:                 'bread_crumbs_component' => 'User Management'};
 1250:     if ($env{'form.popup'}) {
 1251:         $args->{'no_nav_bar'} = 1;
 1252:     }
 1253:     my $start_page =
 1254:         &Apache::loncommon::start_page('User Management',$js,$args);
 1255: 
 1256:     my $forminfo =<<"ENDFORMINFO";
 1257: <form action="/adm/createuser" method="post" name="$formname">
 1258: <input type="hidden" name="phase" value="update_user_data" />
 1259: <input type="hidden" name="ccuname" value="$ccuname" />
 1260: <input type="hidden" name="ccdomain" value="$ccdomain" />
 1261: <input type="hidden" name="pres_value"  value="" />
 1262: <input type="hidden" name="pres_type"   value="" />
 1263: <input type="hidden" name="pres_marker" value="" />
 1264: ENDFORMINFO
 1265:     my (%inccourses,$roledom,$defaultcredits);
 1266:     if ($context eq 'course') {
 1267:         $inccourses{$env{'request.course.id'}}=1;
 1268:         $roledom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 1269:         if ($showcredits) {
 1270:             $defaultcredits = &Apache::lonuserutils::get_defaultcredits();
 1271:         }
 1272:     } elsif ($context eq 'author') {
 1273:         $roledom = $env{'request.role.domain'};
 1274:     } elsif ($context eq 'domain') {
 1275:         foreach my $key (keys(%env)) {
 1276:             $roledom = $env{'request.role.domain'};
 1277:             if ($key=~/^user\.priv\.cm\.\/($roledom)\/($match_username)/) {
 1278:                 $inccourses{$1.'_'.$2}=1;
 1279:             }
 1280:         }
 1281:     } else {
 1282:         foreach my $key (keys(%env)) {
 1283: 	    if ($key=~/^user\.priv\.cm\.\/($match_domain)\/($match_username)/) {
 1284: 	        $inccourses{$1.'_'.$2}=1;
 1285:             }
 1286:         }
 1287:     }
 1288:     my $title = '';
 1289:     if ($newuser) {
 1290:         my ($portfolioform,$domroleform);
 1291:         if ((&Apache::lonnet::allowed('mpq',$env{'request.role.domain'})) ||
 1292:             (&Apache::lonnet::allowed('mut',$env{'request.role.domain'}))) {
 1293:             # Current user has quota or user tools modification privileges
 1294:             $portfolioform = '<br />'.&user_quotas($ccuname,$ccdomain);
 1295:         }
 1296:         if ((&Apache::lonnet::allowed('cau',$env{'request.role.domain'})) &&
 1297:             ($ccdomain eq $env{'request.role.domain'})) {
 1298:             $domroleform = '<br />'.&domainrole_req($ccuname,$ccdomain);
 1299:         }
 1300:         &initialize_authen_forms($ccdomain,$formname);
 1301:         my %lt=&Apache::lonlocal::texthash(
 1302:                 'lg'             => 'Login Data',
 1303:                 'hs'             => "Home Server",
 1304:         );
 1305: 	$r->print(<<ENDTITLE);
 1306: $start_page
 1307: $response
 1308: $forminfo
 1309: <script type="text/javascript" language="Javascript">
 1310: // <![CDATA[
 1311: $loginscript
 1312: // ]]>
 1313: </script>
 1314: <input type='hidden' name='makeuser' value='1' />
 1315: ENDTITLE
 1316:         if ($env{'form.action'} eq 'singlestudent') {
 1317:             if ($crstype eq 'Community') {
 1318:                 $title = &mt('Create New User [_1] in domain [_2] as a member',
 1319:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1320:             } else {
 1321:                 $title = &mt('Create New User [_1] in domain [_2] as a student',
 1322:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1323:             }
 1324:         } else {
 1325:                 $title = &mt('Create New User [_1] in domain [_2]',
 1326:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1327:         }
 1328:         $r->print('<h2>'.$title.'</h2>'."\n");
 1329:         $r->print('<div class="LC_left_float">');
 1330:         $r->print(&personal_data_display($ccuname,$ccdomain,$newuser,$context,
 1331:                                          $inst_results{$ccuname.':'.$ccdomain}));
 1332:         # Option to disable student/employee ID conflict checking not offerred for new users.
 1333:         my ($home_server_pick,$numlib) = 
 1334:             &Apache::loncommon::home_server_form_item($ccdomain,'hserver',
 1335:                                                       'default','hide');
 1336:         if ($numlib > 1) {
 1337:             $r->print("
 1338: <br />
 1339: $lt{'hs'}: $home_server_pick
 1340: <br />");
 1341:         } else {
 1342:             $r->print($home_server_pick);
 1343:         }
 1344:         if (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) {
 1345:             $r->print('<br /><h3>'.
 1346:                       &mt('User Can Request Creation of Courses/Communities in this Domain?').'</h3>'.
 1347:                       &Apache::loncommon::start_data_table().
 1348:                       &build_tools_display($ccuname,$ccdomain,
 1349:                                            'requestcourses').
 1350:                       &Apache::loncommon::end_data_table());
 1351:         }
 1352:         $r->print('</div>'."\n".'<div class="LC_left_float"><h3>'.
 1353:                   $lt{'lg'}.'</h3>');
 1354:         my ($fixedauth,$varauth,$authmsg); 
 1355:         if (ref($rulematch{$ccuname.':'.$ccdomain}) eq 'HASH') {
 1356:             my $matchedrule = $rulematch{$ccuname.':'.$ccdomain}{'username'};
 1357:             my ($rules,$ruleorder) = 
 1358:                 &Apache::lonnet::inst_userrules($ccdomain,'username');
 1359:             if (ref($rules) eq 'HASH') {
 1360:                 if (ref($rules->{$matchedrule}) eq 'HASH') {
 1361:                     my $authtype = $rules->{$matchedrule}{'authtype'};
 1362:                     if ($authtype !~ /^(krb4|krb5|int|fsys|loc)$/) {
 1363:                         $r->print(&Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc));
 1364:                     } else { 
 1365:                         my $authparm = $rules->{$matchedrule}{'authparm'};
 1366:                         $authmsg = $rules->{$matchedrule}{'authmsg'};
 1367:                         if ($authtype =~ /^krb(4|5)$/) {
 1368:                             my $ver = $1;
 1369:                             if ($authparm ne '') {
 1370:                                 $fixedauth = <<"KERB"; 
 1371: <input type="hidden" name="login" value="krb" />
 1372: <input type="hidden" name="krbver" value="$ver" />
 1373: <input type="hidden" name="krbarg" value="$authparm" />
 1374: KERB
 1375:                             }
 1376:                         } else {
 1377:                             $fixedauth = 
 1378: '<input type="hidden" name="login" value="'.$authtype.'" />'."\n";
 1379:                             if ($rules->{$matchedrule}{'authparmfixed'}) {
 1380:                                 $fixedauth .=    
 1381: '<input type="hidden" name="'.$authtype.'arg" value="'.$authparm.'" />'."\n";
 1382:                             } else {
 1383:                                 if ($authtype eq 'int') {
 1384:                                     $varauth = '<br />'.
 1385: &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>';
 1386:                                 } elsif ($authtype eq 'loc') {
 1387:                                     $varauth = '<br />'.
 1388: &mt('[_1] Local Authentication with argument [_2]','','<input type="text" name="'.$authtype.'arg" value="" />')."\n";
 1389:                                 } else {
 1390:                                     $varauth =
 1391: '<input type="text" name="'.$authtype.'arg" value="" />'."\n";
 1392:                                 }
 1393:                             }
 1394:                         }
 1395:                     }
 1396:                 } else {
 1397:                     $r->print(&Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc));
 1398:                 }
 1399:             }
 1400:             if ($authmsg) {
 1401:                 $r->print(<<ENDAUTH);
 1402: $fixedauth
 1403: $authmsg
 1404: $varauth
 1405: ENDAUTH
 1406:             }
 1407:         } else {
 1408:             $r->print(&Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc)); 
 1409:         }
 1410:         $r->print($portfolioform.$domroleform);
 1411:         if ($env{'form.action'} eq 'singlestudent') {
 1412:             $r->print(&date_sections_select($context,$newuser,$formname,
 1413:                                             $permission,$crstype,$ccuname,
 1414:                                             $ccdomain,$showcredits));
 1415:         }
 1416:         $r->print('</div><div class="LC_clear_float_footer"></div>');
 1417:     } else { # user already exists
 1418: 	$r->print($start_page.$forminfo);
 1419:         if ($env{'form.action'} eq 'singlestudent') {
 1420:             if ($crstype eq 'Community') {
 1421:                 $title = &mt('Enroll one member: [_1] in domain [_2]',
 1422:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1423:             } else {
 1424:                 $title = &mt('Enroll one student: [_1] in domain [_2]',
 1425:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1426:             }
 1427:         } else {
 1428:             if ($permission->{'cusr'}) {
 1429:                 $title = &mt('Modify existing user: [_1] in domain [_2]',
 1430:                              '"'.$ccuname.'"','"'.$ccdomain.'"');
 1431:             } else {
 1432:                 $title = &mt('Existing user: [_1] in domain [_2]',
 1433:                              '"'.$ccuname.'"','"'.$ccdomain.'"');
 1434:             }
 1435:         }
 1436:         $r->print('<h2>'.$title.'</h2>'."\n");
 1437:         $r->print('<div class="LC_left_float">');
 1438:         $r->print(&personal_data_display($ccuname,$ccdomain,$newuser,$context,
 1439:                                          $inst_results{$ccuname.':'.$ccdomain}));
 1440:         if ((&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) ||
 1441:             (&Apache::lonnet::allowed('udp',$env{'request.role.domain'}))) {
 1442:             $r->print('<br /><h3>'.&mt('User Can Request Creation of Courses/Communities in this Domain?').'</h3>'.
 1443:                       &Apache::loncommon::start_data_table());
 1444:             if ($env{'request.role.domain'} eq $ccdomain) {
 1445:                 $r->print(&build_tools_display($ccuname,$ccdomain,'requestcourses'));
 1446:             } else {
 1447:                 $r->print(&coursereq_externaluser($ccuname,$ccdomain,
 1448:                                                   $env{'request.role.domain'}));
 1449:             }
 1450:             $r->print(&Apache::loncommon::end_data_table());
 1451:         }
 1452:         $r->print('</div>');
 1453:         my @order = ('auth','quota','tools','requestauthor');
 1454:         my %user_text;
 1455:         my ($isadv,$isauthor) = 
 1456:             &Apache::lonnet::is_advanced_user($ccdomain,$ccuname);
 1457:         if ((!$isauthor) && 
 1458:             ((&Apache::lonnet::allowed('cau',$env{'request.role.domain'})) ||
 1459:              (&Apache::lonnet::allowed('udp',$env{'request.role.domain'}))) &&
 1460:              ($env{'request.role.domain'} eq $ccdomain)) {
 1461:             $user_text{'requestauthor'} = &domainrole_req($ccuname,$ccdomain);
 1462:         }
 1463:         $user_text{'auth'} =  &user_authentication($ccuname,$ccdomain,$formname);
 1464:         if ((&Apache::lonnet::allowed('mpq',$ccdomain)) ||
 1465:             (&Apache::lonnet::allowed('mut',$ccdomain)) ||
 1466:             (&Apache::lonnet::allowed('udp',$ccdomain))) {
 1467:             # Current user has quota modification privileges
 1468:             $user_text{'quota'} = &user_quotas($ccuname,$ccdomain);
 1469:         }
 1470:         if (!&Apache::lonnet::allowed('mpq',$ccdomain)) {
 1471:             if (&Apache::lonnet::allowed('mpq',$env{'request.role.domain'})) {
 1472:                 my %lt=&Apache::lonlocal::texthash(
 1473:                     'dska'  => "Disk quotas for user's portfolio and Authoring Space",
 1474:                     'youd'  => "You do not have privileges to modify the portfolio and/or Authoring Space quotas for this user.",
 1475:                     'ichr'  => "If a change is required, contact a domain coordinator for the domain",
 1476:                 );
 1477:                 $user_text{'quota'} = <<ENDNOPORTPRIV;
 1478: <h3>$lt{'dska'}</h3>
 1479: $lt{'youd'} $lt{'ichr'}: $ccdomain
 1480: ENDNOPORTPRIV
 1481:             }
 1482:         }
 1483:         if (!&Apache::lonnet::allowed('mut',$ccdomain)) {
 1484:             if (&Apache::lonnet::allowed('mut',$env{'request.role.domain'})) {
 1485:                 my %lt=&Apache::lonlocal::texthash(
 1486:                     'utav'  => "User Tools Availability",
 1487:                     'yodo'  => "You do not have privileges to modify Portfolio, Blog, WebDAV, or Personal Information Page settings for this user.",
 1488:                     'ifch'  => "If a change is required, contact a domain coordinator for the domain",
 1489:                 );
 1490:                 $user_text{'tools'} = <<ENDNOTOOLSPRIV;
 1491: <h3>$lt{'utav'}</h3>
 1492: $lt{'yodo'} $lt{'ifch'}: $ccdomain
 1493: ENDNOTOOLSPRIV
 1494:             }
 1495:         }
 1496:         my $gotdiv = 0; 
 1497:         foreach my $item (@order) {
 1498:             if ($user_text{$item} ne '') {
 1499:                 unless ($gotdiv) {
 1500:                     $r->print('<div class="LC_left_float">');
 1501:                     $gotdiv = 1;
 1502:                 }
 1503:                 $r->print('<br />'.$user_text{$item});
 1504:             }
 1505:         }
 1506:         if ($env{'form.action'} eq 'singlestudent') {
 1507:             unless ($gotdiv) {
 1508:                 $r->print('<div class="LC_left_float">');
 1509:             }
 1510:             my $credits;
 1511:             if ($showcredits) {
 1512:                 $credits = &get_user_credits($ccuname,$ccdomain,$defaultcredits);
 1513:                 if ($credits eq '') {
 1514:                     $credits = $defaultcredits;
 1515:                 }
 1516:             }
 1517:             $r->print(&date_sections_select($context,$newuser,$formname,
 1518:                                             $permission,$crstype,$ccuname,
 1519:                                             $ccdomain,$showcredits));
 1520:         }
 1521:         if ($gotdiv) {
 1522:             $r->print('</div><div class="LC_clear_float_footer"></div>');
 1523:         }
 1524:         my $statuses;
 1525:         if (($context eq 'domain') && (&Apache::lonnet::allowed('udp',$ccdomain)) &&
 1526:             (!&Apache::lonnet::allowed('mau',$ccdomain))) {
 1527:             $statuses = ['active'];
 1528:         } elsif (($context eq 'course') && ((&Apache::lonnet::allowed('vcl',$env{'request.course.id'})) ||
 1529:                  ($env{'request.course.sec'} &&
 1530:                   &Apache::lonnet::allowed('vcl',$env{'request.course.id'}.'/'.$env{'request.course.sec'})))) {
 1531:             $statuses = ['active'];
 1532:         }
 1533:         if ($env{'form.action'} ne 'singlestudent') {
 1534:             &display_existing_roles($r,$ccuname,$ccdomain,\%inccourses,$context,
 1535:                                     $roledom,$crstype,$showcredits,$statuses);
 1536:         }
 1537:     } ## End of new user/old user logic
 1538:     if ($env{'form.action'} eq 'singlestudent') {
 1539:         my $btntxt;
 1540:         if ($crstype eq 'Community') {
 1541:             $btntxt = &mt('Enroll Member');
 1542:         } else {
 1543:             $btntxt = &mt('Enroll Student');
 1544:         }
 1545:         $r->print('<br /><input type="button" value="'.$btntxt.'" onclick="setSections(this.form)" />'."\n");
 1546:     } elsif ($permission->{'cusr'}) {
 1547:         $r->print('<div class="LC_left_float">'.
 1548:                   '<fieldset><legend>'.&mt('Add Roles').'</legend>');
 1549:         my $addrolesdisplay = 0;
 1550:         if ($context eq 'domain' || $context eq 'author') {
 1551:             $addrolesdisplay = &new_coauthor_roles($r,$ccuname,$ccdomain);
 1552:         }
 1553:         if ($context eq 'domain') {
 1554:             my $add_domainroles = &new_domain_roles($r,$ccdomain);
 1555:             if (!$addrolesdisplay) {
 1556:                 $addrolesdisplay = $add_domainroles;
 1557:             }
 1558:             $r->print(&course_level_dc($env{'request.role.domain'},$showcredits));
 1559:             $r->print('</fieldset></div><div class="LC_clear_float_footer"></div>'.
 1560:                       '<br /><input type="button" value="'.&mt('Save').'" onclick="setCourse()" />'."\n");
 1561:         } elsif ($context eq 'author') {
 1562:             if ($addrolesdisplay) {
 1563:                 $r->print('</fieldset></div><div class="LC_clear_float_footer"></div>'.
 1564:                           '<br /><input type="button" value="'.&mt('Save').'"');
 1565:                 if ($newuser) {
 1566:                     $r->print(' onclick="auth_check()" \>'."\n");
 1567:                 } else {
 1568:                     $r->print('onclick="this.form.submit()" \>'."\n");
 1569:                 }
 1570:             } else {
 1571:                 $r->print('</fieldset></div>'.
 1572:                           '<div class="LC_clear_float_footer"></div>'.
 1573:                           '<br /><a href="javascript:backPage(document.cu)">'.
 1574:                           &mt('Back to previous page').'</a>');
 1575:             }
 1576:         } else {
 1577:             $r->print(&course_level_table(\%inccourses,$showcredits,$defaultcredits));
 1578:             $r->print('</fieldset></div><div class="LC_clear_float_footer"></div>'.
 1579:                       '<br /><input type="button" value="'.&mt('Save').'" onclick="setSections(this.form)" />'."\n");
 1580:         }
 1581:     }
 1582:     $r->print(&Apache::lonhtmlcommon::echo_form_input(['phase','userrole','ccdomain','prevphase','currstate','ccuname','ccdomain']));
 1583:     $r->print('<input type="hidden" name="currstate" value="" />');
 1584:     $r->print('<input type="hidden" name="prevphase" value="'.$env{'form.phase'}.'" /></form><br /><br />');
 1585:     return;
 1586: }
 1587: 
 1588: sub singleuser_breadcrumb {
 1589:     my ($crstype,$context,$domain) = @_;
 1590:     my %breadcrumb_text;
 1591:     if ($env{'form.action'} eq 'singlestudent') {
 1592:         if ($crstype eq 'Community') {
 1593:             $breadcrumb_text{'search'} = 'Enroll a member';
 1594:         } else {
 1595:             $breadcrumb_text{'search'} = 'Enroll a student';
 1596:         }
 1597:         $breadcrumb_text{'userpicked'} = 'Select a user';
 1598:         $breadcrumb_text{'modify'} = 'Set section/dates';
 1599:     } elsif ($env{'form.action'} eq 'accesslogs') {
 1600:         $breadcrumb_text{'search'} = 'View access logs for a user';
 1601:         $breadcrumb_text{'userpicked'} = 'Select a user';
 1602:         $breadcrumb_text{'activity'} = 'Activity';
 1603:     } elsif (($env{'form.action'} eq 'singleuser') && ($context eq 'domain') &&
 1604:              (!&Apache::lonnet::allowed('mau',$domain))) {
 1605:         $breadcrumb_text{'search'} = "View user's roles";
 1606:         $breadcrumb_text{'userpicked'} = 'Select a user';
 1607:         $breadcrumb_text{'modify'} = 'User roles';
 1608:     } else {
 1609:         $breadcrumb_text{'search'} = 'Create/modify a user';
 1610:         $breadcrumb_text{'userpicked'} = 'Select a user';
 1611:         $breadcrumb_text{'modify'} = 'Set user role';
 1612:     }
 1613:     return %breadcrumb_text;
 1614: }
 1615: 
 1616: sub date_sections_select {
 1617:     my ($context,$newuser,$formname,$permission,$crstype,$ccuname,$ccdomain,
 1618:         $showcredits) = @_;
 1619:     my $credits;
 1620:     if ($showcredits) {
 1621:         my $defaultcredits = &Apache::lonuserutils::get_defaultcredits();
 1622:         $credits = &get_user_credits($ccuname,$ccdomain,$defaultcredits);
 1623:         if ($credits eq '') {
 1624:             $credits = $defaultcredits;
 1625:         }
 1626:     }
 1627:     my $cid = $env{'request.course.id'};
 1628:     my ($cnum,$cdom) = &Apache::lonuserutils::get_course_identity($cid);
 1629:     my $date_table = '<h3>'.&mt('Starting and Ending Dates').'</h3>'."\n".
 1630:         &Apache::lonuserutils::date_setting_table(undef,undef,$context,
 1631:                                                   undef,$formname,$permission);
 1632:     my $rowtitle = 'Section';
 1633:     my $secbox = '<h3>'.&mt('Section and Credits').'</h3>'."\n".
 1634:         &Apache::lonuserutils::section_picker($cdom,$cnum,'st',$rowtitle,
 1635:                                               $permission,$context,'',$crstype,
 1636:                                               $showcredits,$credits);
 1637:     my $output = $date_table.$secbox;
 1638:     return $output;
 1639: }
 1640: 
 1641: sub validation_javascript {
 1642:     my ($context,$ccdomain,$pjump_def,$crstype,$groupslist,$newuser,$formname,
 1643:         $loaditem) = @_;
 1644:     my $dc_setcourse_code = '';
 1645:     my $nondc_setsection_code = '';
 1646:     if ($context eq 'domain') {
 1647:         my $dcdom = $env{'request.role.domain'};
 1648:         $loaditem->{'onload'} = "document.cu.coursedesc.value='';";
 1649:         $dc_setcourse_code = 
 1650:             &Apache::lonuserutils::dc_setcourse_js('cu','singleuser',$context);
 1651:     } else {
 1652:         my $checkauth; 
 1653:         if (($newuser) || (&Apache::lonnet::allowed('mau',$ccdomain))) {
 1654:             $checkauth = 1;
 1655:         }
 1656:         if ($context eq 'course') {
 1657:             $nondc_setsection_code =
 1658:                 &Apache::lonuserutils::setsections_javascript($formname,$groupslist,
 1659:                                                               undef,$checkauth,
 1660:                                                               $crstype);
 1661:         }
 1662:         if ($checkauth) {
 1663:             $nondc_setsection_code .= 
 1664:                 &Apache::lonuserutils::verify_authen($formname,$context);
 1665:         }
 1666:     }
 1667:     my $js = &user_modification_js($pjump_def,$dc_setcourse_code,
 1668:                                    $nondc_setsection_code,$groupslist);
 1669:     my ($jsback,$elements) = &crumb_utilities();
 1670:     $js .= "\n".
 1671:            '<script type="text/javascript">'."\n".
 1672:            '// <![CDATA['."\n".
 1673:            $jsback."\n".
 1674:            '// ]]>'."\n".
 1675:            '</script>'."\n";
 1676:     return $js;
 1677: }
 1678: 
 1679: sub display_existing_roles {
 1680:     my ($r,$ccuname,$ccdomain,$inccourses,$context,$roledom,$crstype,
 1681:         $showcredits,$statuses) = @_;
 1682:     my $now=time;
 1683:     my $showall = 1;
 1684:     my ($showexpired,$showactive);
 1685:     if ((ref($statuses) eq 'ARRAY') && (@{$statuses} > 0)) {
 1686:         $showall = 0;
 1687:         if (grep(/^expired$/,@{$statuses})) {
 1688:             $showexpired = 1;
 1689:         }
 1690:         if (grep(/^active$/,@{$statuses})) {
 1691:             $showactive = 1;
 1692:         }
 1693:         if ($showexpired && $showactive) {
 1694:             $showall = 1;
 1695:         }
 1696:     }
 1697:     my %lt=&Apache::lonlocal::texthash(
 1698:                     'rer'  => "Existing Roles",
 1699:                     'rev'  => "Revoke",
 1700:                     'del'  => "Delete",
 1701:                     'ren'  => "Re-Enable",
 1702:                     'rol'  => "Role",
 1703:                     'ext'  => "Extent",
 1704:                     'crd'  => "Credits",
 1705:                     'sta'  => "Start",
 1706:                     'end'  => "End",
 1707:                                        );
 1708:     my (%rolesdump,%roletext,%sortrole,%roleclass,%rolepriv);
 1709:     if ($context eq 'course' || $context eq 'author') {
 1710:         my @roles = &Apache::lonuserutils::roles_by_context($context,1,$crstype);
 1711:         my %roleshash = 
 1712:             &Apache::lonnet::get_my_roles($ccuname,$ccdomain,'userroles',
 1713:                               ['active','previous','future'],\@roles,$roledom,1);
 1714:         foreach my $key (keys(%roleshash)) {
 1715:             my ($start,$end) = split(':',$roleshash{$key});
 1716:             next if ($start eq '-1' || $end eq '-1');
 1717:             my ($rnum,$rdom,$role,$sec) = split(':',$key);
 1718:             if ($context eq 'course') {
 1719:                 next unless (($rnum eq $env{'course.'.$env{'request.course.id'}.'.num'})
 1720:                              && ($rdom eq $env{'course.'.$env{'request.course.id'}.'.domain'}));
 1721:             } elsif ($context eq 'author') {
 1722:                 next unless (($rnum eq $env{'user.name'}) && ($rdom eq $env{'request.role.domain'}));
 1723:             }
 1724:             my ($newkey,$newvalue,$newrole);
 1725:             $newkey = '/'.$rdom.'/'.$rnum;
 1726:             if ($sec ne '') {
 1727:                 $newkey .= '/'.$sec;
 1728:             }
 1729:             $newvalue = $role;
 1730:             if ($role =~ /^cr/) {
 1731:                 $newrole = 'cr';
 1732:             } else {
 1733:                 $newrole = $role;
 1734:             }
 1735:             $newkey .= '_'.$newrole;
 1736:             if ($start ne '' && $end ne '') {
 1737:                 $newvalue .= '_'.$end.'_'.$start;
 1738:             } elsif ($end ne '') {
 1739:                 $newvalue .= '_'.$end;
 1740:             }
 1741:             $rolesdump{$newkey} = $newvalue;
 1742:         }
 1743:     } else {
 1744:         %rolesdump=&Apache::lonnet::dump('roles',$ccdomain,$ccuname);
 1745:     }
 1746:     # Build up table of user roles to allow revocation and re-enabling of roles.
 1747:     my ($tmp) = keys(%rolesdump);
 1748:     return if ($tmp =~ /^(con_lost|error)/i);
 1749:     foreach my $area (sort { my $a1=join('_',(split('_',$a))[1,0]);
 1750:                                 my $b1=join('_',(split('_',$b))[1,0]);
 1751:                                 return $a1 cmp $b1;
 1752:                             } keys(%rolesdump)) {
 1753:         next if ($area =~ /^rolesdef/);
 1754:         my $envkey=$area;
 1755:         my $role = $rolesdump{$area};
 1756:         my $thisrole=$area;
 1757:         $area =~ s/\_\w\w$//;
 1758:         my ($role_code,$role_end_time,$role_start_time) =
 1759:             split(/_/,$role);
 1760:         my $active=1;
 1761:         $active=0 if (($role_end_time) && ($now>$role_end_time));
 1762:         if ($active) {
 1763:             next unless($showall || $showactive);
 1764:         } else {
 1765:             next unless($showall || $showexpired);
 1766:         }
 1767: # Is this a custom role? Get role owner and title.
 1768:         my ($croleudom,$croleuname,$croletitle)=
 1769:             ($role_code=~m{^cr/($match_domain)/($match_username)/(\w+)$});
 1770:         my $allowed=0;
 1771:         my $delallowed=0;
 1772:         my $sortkey=$role_code;
 1773:         my $class='Unknown';
 1774:         my $credits='';
 1775:         my $csec;
 1776:         if ($area =~ m{^/($match_domain)/($match_courseid)}) {
 1777:             $class='Course';
 1778:             my ($coursedom,$coursedir) = ($1,$2);
 1779:             my $cid = $1.'_'.$2;
 1780:             # $1.'_'.$2 is the course id (eg. 103_12345abcef103l3).
 1781:             next if ($envkey =~ m{^/$match_domain/$match_courseid/[A-Za-z0-9]+_gr$});
 1782:             my %coursedata=
 1783:                 &Apache::lonnet::coursedescription($cid);
 1784:             if ($coursedir =~ /^$match_community$/) {
 1785:                 $class='Community';
 1786:             }
 1787:             $sortkey.="\0$coursedom";
 1788:             my $carea;
 1789:             if (defined($coursedata{'description'})) {
 1790:                 $carea=$coursedata{'description'}.
 1791:                     '<br />'.&mt('Domain').': '.$coursedom.('&nbsp;'x8).
 1792:     &Apache::loncommon::syllabuswrapper(&mt('Syllabus'),$coursedir,$coursedom);
 1793:                 $sortkey.="\0".$coursedata{'description'};
 1794:             } else {
 1795:                 if ($class eq 'Community') {
 1796:                     $carea=&mt('Unavailable community').': '.$area;
 1797:                     $sortkey.="\0".&mt('Unavailable community').': '.$area;
 1798:                 } else {
 1799:                     $carea=&mt('Unavailable course').': '.$area;
 1800:                     $sortkey.="\0".&mt('Unavailable course').': '.$area;
 1801:                 }
 1802:             }
 1803:             $sortkey.="\0$coursedir";
 1804:             $inccourses->{$cid}=1;
 1805:             if (($showcredits) && ($class eq 'Course') && ($role_code eq 'st')) {
 1806:                 my $defaultcredits = $coursedata{'internal.defaultcredits'};
 1807:                 $credits =
 1808:                     &get_user_credits($ccuname,$ccdomain,$defaultcredits,
 1809:                                       $coursedom,$coursedir);
 1810:                 if ($credits eq '') {
 1811:                     $credits = $defaultcredits;
 1812:                 }
 1813:             }
 1814:             if ((&Apache::lonnet::allowed('c'.$role_code,$coursedom.'/'.$coursedir)) ||
 1815:                 (&Apache::lonnet::allowed('c'.$role_code,$ccdomain))) {
 1816:                 $allowed=1;
 1817:             }
 1818:             unless ($allowed) {
 1819:                 my $isowner = &Apache::lonuserutils::is_courseowner($cid,$coursedata{'internal.courseowner'});
 1820:                 if ($isowner) {
 1821:                     if (($role_code eq 'co') && ($class eq 'Community')) {
 1822:                         $allowed = 1;
 1823:                     } elsif (($role_code eq 'cc') && ($class eq 'Course')) {
 1824:                         $allowed = 1;
 1825:                     }
 1826:                 }
 1827:             } 
 1828:             if ((&Apache::lonnet::allowed('dro',$coursedom)) ||
 1829:                 (&Apache::lonnet::allowed('dro',$ccdomain))) {
 1830:                 $delallowed=1;
 1831:             }
 1832: # - custom role. Needs more info, too
 1833:             if ($croletitle) {
 1834:                 if (&Apache::lonnet::allowed('ccr',$coursedom.'/'.$coursedir)) {
 1835:                     $allowed=1;
 1836:                     $thisrole.='.'.$role_code;
 1837:                 }
 1838:             }
 1839:             if ($area=~m{^/($match_domain/$match_courseid/(\w+))}) {
 1840:                 $csec = $2;
 1841:                 $carea.='<br />'.&mt('Section: [_1]',$csec);
 1842:                 $sortkey.="\0$csec";
 1843:                 if (!$allowed) {
 1844:                     if ($env{'request.course.sec'} eq $csec) {
 1845:                         if (&Apache::lonnet::allowed('c'.$role_code,$1)) {
 1846:                             $allowed = 1;
 1847:                         }
 1848:                     }
 1849:                 }
 1850:             }
 1851:             $area=$carea;
 1852:         } else {
 1853:             $sortkey.="\0".$area;
 1854:             # Determine if current user is able to revoke privileges
 1855:             if ($area=~m{^/($match_domain)/}) {
 1856:                 if ((&Apache::lonnet::allowed('c'.$role_code,$1)) ||
 1857:                    (&Apache::lonnet::allowed('c'.$role_code,$ccdomain))) {
 1858:                    $allowed=1;
 1859:                 }
 1860:                 if (((&Apache::lonnet::allowed('dro',$1))  ||
 1861:                     (&Apache::lonnet::allowed('dro',$ccdomain))) &&
 1862:                     ($role_code ne 'dc')) {
 1863:                     $delallowed=1;
 1864:                 }
 1865:             } else {
 1866:                 if (&Apache::lonnet::allowed('c'.$role_code,'/')) {
 1867:                     $allowed=1;
 1868:                 }
 1869:             }
 1870:             if ($role_code eq 'ca' || $role_code eq 'au' || $role_code eq 'aa') {
 1871:                 $class='Authoring Space';
 1872:             } elsif ($role_code eq 'su') {
 1873:                 $class='System';
 1874:             } else {
 1875:                 $class='Domain';
 1876:             }
 1877:         }
 1878:         if (($role_code eq 'ca') || ($role_code eq 'aa')) {
 1879:             $area=~m{/($match_domain)/($match_username)};
 1880:             if (&Apache::lonuserutils::authorpriv($2,$1)) {
 1881:                 $allowed=1;
 1882:             } else {
 1883:                 $allowed=0;
 1884:             }
 1885:         }
 1886:         my $row = '';
 1887:         if ($showall) {
 1888:             $row.= '<td>';
 1889:             if (($active) && ($allowed)) {
 1890:                 $row.= '<input type="checkbox" name="rev:'.$thisrole.'" />';
 1891:             } else {
 1892:                 if ($active) {
 1893:                     $row.='&nbsp;';
 1894:                 } else {
 1895:                     $row.=&mt('expired or revoked');
 1896:                 }
 1897:             }
 1898:             $row.='</td><td>';
 1899:             if ($allowed && !$active) {
 1900:                 $row.= '<input type="checkbox" name="ren:'.$thisrole.'" />';
 1901:             } else {
 1902:                 $row.='&nbsp;';
 1903:             }
 1904:             $row.='</td><td>';
 1905:             if ($delallowed) {
 1906:                 $row.= '<input type="checkbox" name="del:'.$thisrole.'" />';
 1907:             } else {
 1908:                 $row.='&nbsp;';
 1909:             }
 1910:             $row.= '</td>';
 1911:         }
 1912:         my $plaintext='';
 1913:         if (!$croletitle) {
 1914:             $plaintext=&Apache::lonnet::plaintext($role_code,$class);
 1915:             if (($showcredits) && ($credits ne '')) {
 1916:                 $plaintext .= '<br/ ><span class="LC_nobreak">'.
 1917:                               '<span class="LC_fontsize_small">'.
 1918:                               &mt('Credits: [_1]',$credits).
 1919:                               '</span></span>';
 1920:             }
 1921:         } else {
 1922:             $plaintext=
 1923:                 &mt('Custom role [_1][_2]defined by [_3]',
 1924:                         '"'.$croletitle.'"',
 1925:                         '<br />',
 1926:                         $croleuname.':'.$croleudom);
 1927:         }
 1928:         $row.= '<td>'.$plaintext.'</td>'.
 1929:                '<td>'.$area.'</td>'.
 1930:                '<td>'.($role_start_time?&Apache::lonlocal::locallocaltime($role_start_time)
 1931:                                             : '&nbsp;' ).'</td>'.
 1932:                '<td>'.($role_end_time  ?&Apache::lonlocal::locallocaltime($role_end_time)
 1933:                                             : '&nbsp;' ).'</td>';
 1934:         $sortrole{$sortkey}=$envkey;
 1935:         $roletext{$envkey}=$row;
 1936:         $roleclass{$envkey}=$class;
 1937:         if ($allowed) {
 1938:             $rolepriv{$envkey}='edit';
 1939:         } else {
 1940:             if ($context eq 'domain') {
 1941:                 if ((&Apache::lonnet::allowed('vur',$ccdomain)) &&
 1942:                     ($envkey=~m{^/$ccdomain/})) {
 1943:                     $rolepriv{$envkey}='view';
 1944:                 }
 1945:             } elsif ($context eq 'course') {
 1946:                 if ((&Apache::lonnet::allowed('vcl',$env{'request.course.id'})) ||
 1947:                     ($env{'request.course.sec'} && ($env{'request.course.sec'} eq $csec) &&
 1948:                      &Apache::lonnet::allowed('vcl',$env{'request.course.id'}.'/'.$env{'request.course.sec'}))) {
 1949:                     $rolepriv{$envkey}='view';
 1950:                 }
 1951:             }
 1952:         }
 1953:     } # end of foreach        (table building loop)
 1954: 
 1955:     my $rolesdisplay = 0;
 1956:     my %output = ();
 1957:     foreach my $type ('Authoring Space','Course','Community','Domain','System','Unknown') {
 1958:         $output{$type} = '';
 1959:         foreach my $which (sort {uc($a) cmp uc($b)} (keys(%sortrole))) {
 1960:             if ( ($roleclass{$sortrole{$which}} =~ /^\Q$type\E/ ) && ($rolepriv{$sortrole{$which}}) ) {
 1961:                  $output{$type}.=
 1962:                       &Apache::loncommon::start_data_table_row().
 1963:                       $roletext{$sortrole{$which}}.
 1964:                       &Apache::loncommon::end_data_table_row();
 1965:             }
 1966:         }
 1967:         unless($output{$type} eq '') {
 1968:             $output{$type} = '<tr class="LC_info_row">'.
 1969:                       "<td align='center' colspan='7'>".&mt($type)."</td></tr>".
 1970:                       $output{$type};
 1971:             $rolesdisplay = 1;
 1972:         }
 1973:     }
 1974:     if ($rolesdisplay == 1) {
 1975:         my $contextrole='';
 1976:         if ($env{'request.course.id'}) {
 1977:             if (&Apache::loncommon::course_type() eq 'Community') {
 1978:                 $contextrole = &mt('Existing Roles in this Community');
 1979:             } else {
 1980:                 $contextrole = &mt('Existing Roles in this Course');
 1981:             }
 1982:         } elsif ($env{'request.role'} =~ /^au\./) {
 1983:             $contextrole = &mt('Existing Co-Author Roles in your Authoring Space');
 1984:         } else {
 1985:             if ($showall) {
 1986:                 $contextrole = &mt('Existing Roles in this Domain');
 1987:             } elsif ($showactive) {
 1988:                 $contextrole = &mt('Unexpired Roles in this Domain');
 1989:             } elsif ($showexpired) {
 1990:                 $contextrole = &mt('Expired or Revoked Roles in this Domain');
 1991:             }
 1992:         }
 1993:         $r->print('<div class="LC_left_float">'.
 1994: '<fieldset><legend>'.$contextrole.'</legend>'.
 1995: &Apache::loncommon::start_data_table("LC_createuser").
 1996: &Apache::loncommon::start_data_table_header_row());
 1997:         if ($showall) {
 1998:             $r->print(
 1999: '<th>'.$lt{'rev'}.'</th><th>'.$lt{'ren'}.'</th><th>'.$lt{'del'}.'</th>'
 2000:             );
 2001:         } elsif ($showexpired) {
 2002:             $r->print('<th>'.$lt{'rev'}.'</th>');
 2003:         }
 2004:         $r->print(
 2005: '<th>'.$lt{'rol'}.'</th><th>'.$lt{'ext'}.'</th>'.
 2006: '<th>'.$lt{'sta'}.'</th><th>'.$lt{'end'}.'</th>'.
 2007: &Apache::loncommon::end_data_table_header_row());
 2008:         foreach my $type ('Authoring Space','Course','Community','Domain','System','Unknown') {
 2009:             if ($output{$type}) {
 2010:                 $r->print($output{$type}."\n");
 2011:             }
 2012:         }
 2013:         $r->print(&Apache::loncommon::end_data_table().
 2014:                   '</fieldset></div>');
 2015:     }
 2016:     return;
 2017: }
 2018: 
 2019: sub new_coauthor_roles {
 2020:     my ($r,$ccuname,$ccdomain) = @_;
 2021:     my $addrolesdisplay = 0;
 2022:     #
 2023:     # Co-Author
 2024:     #
 2025:     if (&Apache::lonuserutils::authorpriv($env{'user.name'},
 2026:                                           $env{'request.role.domain'}) &&
 2027:         ($env{'user.name'} ne $ccuname || $env{'user.domain'} ne $ccdomain)) {
 2028:         # No sense in assigning co-author role to yourself
 2029:         $addrolesdisplay = 1;
 2030:         my $cuname=$env{'user.name'};
 2031:         my $cudom=$env{'request.role.domain'};
 2032:         my %lt=&Apache::lonlocal::texthash(
 2033:                     'cs'   => "Authoring Space",
 2034:                     'act'  => "Activate",
 2035:                     'rol'  => "Role",
 2036:                     'ext'  => "Extent",
 2037:                     'sta'  => "Start",
 2038:                     'end'  => "End",
 2039:                     'cau'  => "Co-Author",
 2040:                     'caa'  => "Assistant Co-Author",
 2041:                     'ssd'  => "Set Start Date",
 2042:                     'sed'  => "Set End Date"
 2043:                                        );
 2044:         $r->print('<h4>'.$lt{'cs'}.'</h4>'."\n".
 2045:                   &Apache::loncommon::start_data_table()."\n".
 2046:                   &Apache::loncommon::start_data_table_header_row()."\n".
 2047:                   '<th>'.$lt{'act'}.'</th><th>'.$lt{'rol'}.'</th>'.
 2048:                   '<th>'.$lt{'ext'}.'</th><th>'.$lt{'sta'}.'</th>'.
 2049:                   '<th>'.$lt{'end'}.'</th>'."\n".
 2050:                   &Apache::loncommon::end_data_table_header_row()."\n".
 2051:                   &Apache::loncommon::start_data_table_row().'
 2052:            <td>
 2053:             <input type="checkbox" name="act_'.$cudom.'_'.$cuname.'_ca" />
 2054:            </td>
 2055:            <td>'.$lt{'cau'}.'</td>
 2056:            <td>'.$cudom.'_'.$cuname.'</td>
 2057:            <td><input type="hidden" name="start_'.$cudom.'_'.$cuname.'_ca" value="" />
 2058:              <a href=
 2059: "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>
 2060: <td><input type="hidden" name="end_'.$cudom.'_'.$cuname.'_ca" value="" />
 2061: <a href=
 2062: "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".
 2063:               &Apache::loncommon::end_data_table_row()."\n".
 2064:               &Apache::loncommon::start_data_table_row()."\n".
 2065: '<td><input type="checkbox" name="act_'.$cudom.'_'.$cuname.'_aa" /></td>
 2066: <td>'.$lt{'caa'}.'</td>
 2067: <td>'.$cudom.'_'.$cuname.'</td>
 2068: <td><input type="hidden" name="start_'.$cudom.'_'.$cuname.'_aa" value="" />
 2069: <a href=
 2070: "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>
 2071: <td><input type="hidden" name="end_'.$cudom.'_'.$cuname.'_aa" value="" />
 2072: <a href=
 2073: "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".
 2074:              &Apache::loncommon::end_data_table_row()."\n".
 2075:              &Apache::loncommon::end_data_table());
 2076:     } elsif ($env{'request.role'} =~ /^au\./) {
 2077:         if (!(&Apache::lonuserutils::authorpriv($env{'user.name'},
 2078:                                                 $env{'request.role.domain'}))) {
 2079:             $r->print('<span class="LC_error">'.
 2080:                       &mt('You do not have privileges to assign co-author roles.').
 2081:                       '</span>');
 2082:         } elsif (($env{'user.name'} eq $ccuname) &&
 2083:              ($env{'user.domain'} eq $ccdomain)) {
 2084:             $r->print(&mt('Assigning yourself a co-author or assistant co-author role in your own author area in Authoring Space is not permitted'));
 2085:         }
 2086:     }
 2087:     return $addrolesdisplay;;
 2088: }
 2089: 
 2090: sub new_domain_roles {
 2091:     my ($r,$ccdomain) = @_;
 2092:     my $addrolesdisplay = 0;
 2093:     #
 2094:     # Domain level
 2095:     #
 2096:     my $num_domain_level = 0;
 2097:     my $domaintext =
 2098:     '<h4>'.&mt('Domain Level').'</h4>'.
 2099:     &Apache::loncommon::start_data_table().
 2100:     &Apache::loncommon::start_data_table_header_row().
 2101:     '<th>'.&mt('Activate').'</th><th>'.&mt('Role').'</th><th>'.
 2102:     &mt('Extent').'</th>'.
 2103:     '<th>'.&mt('Start').'</th><th>'.&mt('End').'</th>'.
 2104:     &Apache::loncommon::end_data_table_header_row();
 2105:     my @allroles = &Apache::lonuserutils::roles_by_context('domain');
 2106:     foreach my $thisdomain (sort(&Apache::lonnet::all_domains())) {
 2107:         foreach my $role (@allroles) {
 2108:             next if ($role eq 'ad');
 2109:             next if (($role eq 'au') && ($ccdomain ne $thisdomain));
 2110:             if (&Apache::lonnet::allowed('c'.$role,$thisdomain)) {
 2111:                my $plrole=&Apache::lonnet::plaintext($role);
 2112:                my %lt=&Apache::lonlocal::texthash(
 2113:                     'ssd'  => "Set Start Date",
 2114:                     'sed'  => "Set End Date"
 2115:                                        );
 2116:                $num_domain_level ++;
 2117:                $domaintext .=
 2118: &Apache::loncommon::start_data_table_row().
 2119: '<td><input type="checkbox" name="act_'.$thisdomain.'_'.$role.'" /></td>
 2120: <td>'.$plrole.'</td>
 2121: <td>'.$thisdomain.'</td>
 2122: <td><input type="hidden" name="start_'.$thisdomain.'_'.$role.'" value="" />
 2123: <a href=
 2124: "javascript:pjump('."'date_start','Start Date $plrole',document.cu.start_$thisdomain\_$role.value,'start_$thisdomain\_$role','cu.pres','dateset'".')">'.$lt{'ssd'}.'</a></td>
 2125: <td><input type="hidden" name="end_'.$thisdomain.'_'.$role.'" value="" />
 2126: <a href=
 2127: "javascript:pjump('."'date_end','End Date $plrole',document.cu.end_$thisdomain\_$role.value,'end_$thisdomain\_$role','cu.pres','dateset'".')">'.$lt{'sed'}.'</a></td>'.
 2128: &Apache::loncommon::end_data_table_row();
 2129:             }
 2130:         }
 2131:     }
 2132:     $domaintext.= &Apache::loncommon::end_data_table();
 2133:     if ($num_domain_level > 0) {
 2134:         $r->print($domaintext);
 2135:         $addrolesdisplay = 1;
 2136:     }
 2137:     return $addrolesdisplay;
 2138: }
 2139: 
 2140: sub user_authentication {
 2141:     my ($ccuname,$ccdomain,$formname) = @_;
 2142:     my $currentauth=&Apache::lonnet::queryauthenticate($ccuname,$ccdomain);
 2143:     my $outcome;
 2144:     my %lt=&Apache::lonlocal::texthash(
 2145:                    'err'   => "ERROR",
 2146:                    'uuas'  => "This user has an unrecognized authentication scheme",
 2147:                    'adcs'  => "Please alert a domain coordinator of this situation",
 2148:                    'sldb'  => "Please specify login data below",
 2149:                    'ld'    => "Login Data"
 2150:     );
 2151:     # Check for a bad authentication type
 2152:     if ($currentauth !~ /^(krb4|krb5|unix|internal|localauth):/) {
 2153:         # bad authentication scheme
 2154:         if (&Apache::lonnet::allowed('mau',$ccdomain)) {
 2155:             &initialize_authen_forms($ccdomain,$formname);
 2156: 
 2157:             my $choices = &Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc);
 2158:             $outcome = <<ENDBADAUTH;
 2159: <script type="text/javascript" language="Javascript">
 2160: // <![CDATA[
 2161: $loginscript
 2162: // ]]>
 2163: </script>
 2164: <span class="LC_error">$lt{'err'}:
 2165: $lt{'uuas'} ($currentauth). $lt{'sldb'}.</span>
 2166: <h3>$lt{'ld'}</h3>
 2167: $choices
 2168: ENDBADAUTH
 2169:         } else {
 2170:             # This user is not allowed to modify the user's
 2171:             # authentication scheme, so just notify them of the problem
 2172:             $outcome = <<ENDBADAUTH;
 2173: <span class="LC_error"> $lt{'err'}: 
 2174: $lt{'uuas'} ($currentauth). $lt{'adcs'}.
 2175: </span>
 2176: ENDBADAUTH
 2177:         }
 2178:     } else { # Authentication type is valid
 2179:         
 2180:         &initialize_authen_forms($ccdomain,$formname,$currentauth,'modifyuser');
 2181:         my ($authformcurrent,$can_modify,@authform_others) =
 2182:             &modify_login_block($ccdomain,$currentauth);
 2183:         if (&Apache::lonnet::allowed('mau',$ccdomain)) {
 2184:             # Current user has login modification privileges
 2185:             $outcome =
 2186:                        '<script type="text/javascript" language="Javascript">'."\n".
 2187:                        '// <![CDATA['."\n".
 2188:                        $loginscript."\n".
 2189:                        '// ]]>'."\n".
 2190:                        '</script>'."\n".
 2191:                        '<h3>'.$lt{'ld'}.'</h3>'.
 2192:                        &Apache::loncommon::start_data_table().
 2193:                        &Apache::loncommon::start_data_table_row().
 2194:                        '<td>'.$authformnop;
 2195:             if (($can_modify) && (&Apache::lonnet::allowed('mau',$ccdomain))) {
 2196:                 $outcome .= '</td>'."\n".
 2197:                             &Apache::loncommon::end_data_table_row().
 2198:                             &Apache::loncommon::start_data_table_row().
 2199:                             '<td>'.$authformcurrent.'</td>'.
 2200:                             &Apache::loncommon::end_data_table_row()."\n";
 2201:             } else {
 2202:                 $outcome .= '&nbsp;('.$authformcurrent.')</td>'.
 2203:                             &Apache::loncommon::end_data_table_row()."\n";
 2204:             }
 2205:             if (&Apache::lonnet::allowed('mau',$ccdomain)) {
 2206:                 foreach my $item (@authform_others) { 
 2207:                     $outcome .= &Apache::loncommon::start_data_table_row().
 2208:                                 '<td>'.$item.'</td>'.
 2209:                                 &Apache::loncommon::end_data_table_row()."\n";
 2210:                 }
 2211:             }
 2212:             $outcome .= &Apache::loncommon::end_data_table();
 2213:         } else {
 2214:             if (&Apache::lonnet::allowed('udp',$ccdomain)) {
 2215:                 # Current user has rights to view domain preferences for user's domain
 2216:                 my $result;
 2217:                 if ($currentauth =~ /^krb(4|5):([^:]*)$/) {
 2218:                     my ($krbver,$krbrealm) = ($1,$2);
 2219:                     if ($krbrealm eq '') {
 2220:                         $result = &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
 2221:                     } else {
 2222:                         $result = &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
 2223:                                       $krbrealm,$krbver);
 2224:                     }
 2225:                 } elsif ($currentauth =~ /^internal:/) {
 2226:                     $result = &mt('Currently internally authenticated.');
 2227:                 } elsif ($currentauth =~ /^localauth:/) {
 2228:                     $result = &mt('Currently using local (institutional) authentication.');
 2229:                 } elsif ($currentauth =~ /^unix:/) {
 2230:                     $result = &mt('Currently Filesystem Authenticated.');
 2231:                 }
 2232:                 $outcome = '<h3>'.$lt{'ld'}.'</h3>'.
 2233:                            &Apache::loncommon::start_data_table().
 2234:                            &Apache::loncommon::start_data_table_row().
 2235:                            '<td>'.$result.'</td>'.
 2236:                            &Apache::loncommon::end_data_table_row()."\n".
 2237:                            &Apache::loncommon::end_data_table();
 2238:             } elsif (&Apache::lonnet::allowed('mau',$env{'request.role.domain'})) {
 2239:                 my %lt=&Apache::lonlocal::texthash(
 2240:                            'ccld'  => "Change Current Login Data",
 2241:                            'yodo'  => "You do not have privileges to modify the authentication configuration for this user.",
 2242:                            'ifch'  => "If a change is required, contact a domain coordinator for the domain",
 2243:                 );
 2244:                 $outcome .= <<ENDNOPRIV;
 2245: <h3>$lt{'ccld'}</h3>
 2246: $lt{'yodo'} $lt{'ifch'}: $ccdomain
 2247: <input type="hidden" name="login" value="nochange" />
 2248: ENDNOPRIV
 2249:             }
 2250:         }
 2251:     }  ## End of "check for bad authentication type" logic
 2252:     return $outcome;
 2253: }
 2254: 
 2255: sub modify_login_block {
 2256:     my ($dom,$currentauth) = @_;
 2257:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 2258:     my ($authnum,%can_assign) =
 2259:         &Apache::loncommon::get_assignable_auth($dom);
 2260:     my ($authformcurrent,@authform_others,$show_override_msg);
 2261:     if ($currentauth=~/^krb(4|5):/) {
 2262:         $authformcurrent=$authformkrb;
 2263:         if ($can_assign{'int'}) {
 2264:             push(@authform_others,$authformint);
 2265:         }
 2266:         if ($can_assign{'loc'}) {
 2267:             push(@authform_others,$authformloc);
 2268:         }
 2269:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2270:             $show_override_msg = 1;
 2271:         }
 2272:     } elsif ($currentauth=~/^internal:/) {
 2273:         $authformcurrent=$authformint;
 2274:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2275:             push(@authform_others,$authformkrb);
 2276:         }
 2277:         if ($can_assign{'loc'}) {
 2278:             push(@authform_others,$authformloc);
 2279:         }
 2280:         if ($can_assign{'int'}) {
 2281:             $show_override_msg = 1;
 2282:         }
 2283:     } elsif ($currentauth=~/^unix:/) {
 2284:         $authformcurrent=$authformfsys;
 2285:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2286:             push(@authform_others,$authformkrb);
 2287:         }
 2288:         if ($can_assign{'int'}) {
 2289:             push(@authform_others,$authformint);
 2290:         }
 2291:         if ($can_assign{'loc'}) {
 2292:             push(@authform_others,$authformloc);
 2293:         }
 2294:         if ($can_assign{'fsys'}) {
 2295:             $show_override_msg = 1;
 2296:         }
 2297:     } elsif ($currentauth=~/^localauth:/) {
 2298:         $authformcurrent=$authformloc;
 2299:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2300:             push(@authform_others,$authformkrb);
 2301:         }
 2302:         if ($can_assign{'int'}) {
 2303:             push(@authform_others,$authformint);
 2304:         }
 2305:         if ($can_assign{'loc'}) {
 2306:             $show_override_msg = 1;
 2307:         }
 2308:     }
 2309:     if ($show_override_msg) {
 2310:         $authformcurrent = '<table><tr><td colspan="3">'.$authformcurrent.
 2311:                            '</td></tr>'."\n".
 2312:                            '<tr><td>&nbsp;&nbsp;&nbsp;</td>'.
 2313:                            '<td><b>'.&mt('Currently in use').'</b></td>'.
 2314:                            '<td align="right"><span class="LC_cusr_emph">'.
 2315:                             &mt('will override current values').
 2316:                             '</span></td></tr></table>';
 2317:     }
 2318:     return ($authformcurrent,$show_override_msg,@authform_others); 
 2319: }
 2320: 
 2321: sub personal_data_display {
 2322:     my ($ccuname,$ccdomain,$newuser,$context,$inst_results,$rolesarray,
 2323:         $now,$captchaform,$emailusername,$usertype) = @_;
 2324:     my ($output,%userenv,%canmodify,%canmodify_status);
 2325:     my @userinfo = ('firstname','middlename','lastname','generation',
 2326:                     'permanentemail','id');
 2327:     my $rowcount = 0;
 2328:     my $editable = 0;
 2329:     my %textboxsize = (
 2330:                        firstname      => '15',
 2331:                        middlename     => '15',
 2332:                        lastname       => '15',
 2333:                        generation     => '5',
 2334:                        permanentemail => '25',
 2335:                        id             => '15',
 2336:                       );
 2337: 
 2338:     my %lt=&Apache::lonlocal::texthash(
 2339:                 'pd'             => "Personal Data",
 2340:                 'firstname'      => "First Name",
 2341:                 'middlename'     => "Middle Name",
 2342:                 'lastname'       => "Last Name",
 2343:                 'generation'     => "Generation",
 2344:                 'permanentemail' => "Permanent e-mail address",
 2345:                 'id'             => "Student/Employee ID",
 2346:                 'lg'             => "Login Data",
 2347:                 'inststatus'     => "Affiliation",
 2348:                 'email'          => 'E-mail address',
 2349:                 'valid'          => 'Validation',
 2350:     );
 2351: 
 2352:     %canmodify_status =
 2353:         &Apache::lonuserutils::can_modify_userinfo($context,$ccdomain,
 2354:                                                    ['inststatus'],$rolesarray);
 2355:     if (!$newuser) {
 2356:         # Get the users information
 2357:         %userenv = &Apache::lonnet::get('environment',
 2358:                    ['firstname','middlename','lastname','generation',
 2359:                     'permanentemail','id','inststatus'],$ccdomain,$ccuname);
 2360:         %canmodify =
 2361:             &Apache::lonuserutils::can_modify_userinfo($context,$ccdomain,
 2362:                                                        \@userinfo,$rolesarray);
 2363:     } elsif ($context eq 'selfcreate') {
 2364:         if ($newuser eq 'email') {
 2365:             if (ref($emailusername) eq 'HASH') {
 2366:                 if (ref($emailusername->{$usertype}) eq 'HASH') {
 2367:                     my ($infofields,$infotitles) = &Apache::loncommon::emailusername_info();
 2368:                     @userinfo = ();          
 2369:                     if ((ref($infofields) eq 'ARRAY') && (ref($infotitles) eq 'HASH')) {
 2370:                         foreach my $field (@{$infofields}) { 
 2371:                             if ($emailusername->{$usertype}->{$field}) {
 2372:                                 push(@userinfo,$field);
 2373:                                 $canmodify{$field} = 1;
 2374:                                 unless ($textboxsize{$field}) {
 2375:                                     $textboxsize{$field} = 25;
 2376:                                 }
 2377:                                 unless ($lt{$field}) {
 2378:                                     $lt{$field} = $infotitles->{$field};
 2379:                                 }
 2380:                                 if ($emailusername->{$usertype}->{$field} eq 'required') {
 2381:                                     $lt{$field} .= '<b>*</b>';
 2382:                                 }
 2383:                             }
 2384:                         }
 2385:                     }
 2386:                 }
 2387:             }
 2388:         } else {
 2389:             %canmodify = &selfcreate_canmodify($context,$ccdomain,\@userinfo,
 2390:                                                $inst_results,$rolesarray);
 2391:         }
 2392:     }
 2393: 
 2394:     my $genhelp=&Apache::loncommon::help_open_topic('Generation');
 2395:     $output = '<h3>'.$lt{'pd'}.'</h3>'.
 2396:               &Apache::lonhtmlcommon::start_pick_box();
 2397:     if (($context eq 'selfcreate') && ($newuser eq 'email')) {
 2398:         $output .= &Apache::lonhtmlcommon::row_title($lt{'email'}.'<b>*</b>',undef,
 2399:                                                      'LC_oddrow_value')."\n".
 2400:                    '<input type="text" name="uname" size="25" value="" autocomplete="off" />';
 2401:         $rowcount ++;
 2402:         $output .= &Apache::lonhtmlcommon::row_closure(1);
 2403:         my $upassone = '<input type="password" name="upass'.$now.'" size="20" autocomplete="off" />';
 2404:         my $upasstwo = '<input type="password" name="upasscheck'.$now.'" size="20" autocomplete="off" />';
 2405:         $output .= &Apache::lonhtmlcommon::row_title(&mt('Password').'<b>*</b>',
 2406:                                                     'LC_pick_box_title',
 2407:                                                     'LC_oddrow_value')."\n".
 2408:                    $upassone."\n".
 2409:                    &Apache::lonhtmlcommon::row_closure(1)."\n".
 2410:                    &Apache::lonhtmlcommon::row_title(&mt('Confirm password').'<b>*</b>',
 2411:                                                      'LC_pick_box_title',
 2412:                                                      'LC_oddrow_value')."\n".
 2413:                    $upasstwo.
 2414:                    &Apache::lonhtmlcommon::row_closure()."\n";
 2415:     }
 2416:     foreach my $item (@userinfo) {
 2417:         my $rowtitle = $lt{$item};
 2418:         my $hiderow = 0;
 2419:         if ($item eq 'generation') {
 2420:             $rowtitle = $genhelp.$rowtitle;
 2421:         }
 2422:         my $row = &Apache::lonhtmlcommon::row_title($rowtitle,undef,'LC_oddrow_value')."\n";
 2423:         if ($newuser) {
 2424:             if (ref($inst_results) eq 'HASH') {
 2425:                 if ($inst_results->{$item} ne '') {
 2426:                     $row .= '<input type="hidden" name="c'.$item.'" value="'.$inst_results->{$item}.'" />'.$inst_results->{$item};
 2427:                 } else {
 2428:                     if ($context eq 'selfcreate') {
 2429:                         if ($canmodify{$item}) {
 2430:                             $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="" autocomplete="off" />';
 2431:                             $editable ++;
 2432:                         } else {
 2433:                             $hiderow = 1;
 2434:                         }
 2435:                     } else {
 2436:                         $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="" />';
 2437:                     }
 2438:                 }
 2439:             } else {
 2440:                 if ($context eq 'selfcreate') {
 2441:                     if ($canmodify{$item}) {
 2442:                         if ($newuser eq 'email') {
 2443:                             $row .= '<input type="text" name="'.$item.'" size="'.$textboxsize{$item}.'" value="" autocomplete="off" />';
 2444:                         } else {
 2445:                             $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="" autocomplete="off" />';
 2446:                         }
 2447:                         $editable ++;
 2448:                     } else {
 2449:                         $hiderow = 1;
 2450:                     }
 2451:                 } else {
 2452:                     $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="" />';
 2453:                 }
 2454:             }
 2455:         } else {
 2456:             if ($canmodify{$item}) {
 2457:                 $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="'.$userenv{$item}.'" />';
 2458:                 if (($item eq 'id') && (!$newuser)) {
 2459:                     $row .= '<br />'.&Apache::lonuserutils::forceid_change($context);
 2460:                 }
 2461:             } else {
 2462:                 $row .= $userenv{$item};
 2463:             }
 2464:         }
 2465:         $row .= &Apache::lonhtmlcommon::row_closure(1);
 2466:         if (!$hiderow) {
 2467:             $output .= $row;
 2468:             $rowcount ++;
 2469:         }
 2470:     }
 2471:     if (($canmodify_status{'inststatus'}) || ($context ne 'selfcreate')) {
 2472:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($ccdomain);
 2473:         if (ref($types) eq 'ARRAY') {
 2474:             if (@{$types} > 0) {
 2475:                 my ($hiderow,$shown);
 2476:                 if ($canmodify_status{'inststatus'}) {
 2477:                     $shown = &pick_inst_statuses($userenv{'inststatus'},$usertypes,$types);
 2478:                 } else {
 2479:                     if ($userenv{'inststatus'} eq '') {
 2480:                         $hiderow = 1;
 2481:                     } else {
 2482:                         my @showitems;
 2483:                         foreach my $item ( map { &unescape($_); } split(':',$userenv{'inststatus'})) {
 2484:                             if (exists($usertypes->{$item})) {
 2485:                                 push(@showitems,$usertypes->{$item});
 2486:                             } else {
 2487:                                 push(@showitems,$item);
 2488:                             }
 2489:                         }
 2490:                         if (@showitems) {
 2491:                             $shown = join(', ',@showitems);
 2492:                         } else {
 2493:                             $hiderow = 1;
 2494:                         }
 2495:                     }
 2496:                 }
 2497:                 if (!$hiderow) {
 2498:                     my $row = &Apache::lonhtmlcommon::row_title(&mt('Affiliations'),undef,'LC_oddrow_value')."\n".
 2499:                               $shown.&Apache::lonhtmlcommon::row_closure(1); 
 2500:                     if ($context eq 'selfcreate') {
 2501:                         $rowcount ++;
 2502:                     }
 2503:                     $output .= $row;
 2504:                 }
 2505:             }
 2506:         }
 2507:     }
 2508:     if (($context eq 'selfcreate') && ($newuser eq 'email')) {
 2509:         if ($captchaform) {
 2510:             $output .= &Apache::lonhtmlcommon::row_title($lt{'valid'}.'*',
 2511:                                                          'LC_pick_box_title')."\n".
 2512:                        $captchaform."\n".'<br /><br />'.
 2513:                        &Apache::lonhtmlcommon::row_closure(1); 
 2514:             $rowcount ++;
 2515:         }
 2516:         my $submit_text = &mt('Create account');
 2517:         $output .= &Apache::lonhtmlcommon::row_title()."\n".
 2518:                    '<br /><input type="submit" name="createaccount" value="'.
 2519:                    $submit_text.'" />'.
 2520:                    '<input type="hidden" name="type" value="'.$usertype.'" />'.
 2521:                    &Apache::lonhtmlcommon::row_closure(1);
 2522:     }
 2523:     $output .= &Apache::lonhtmlcommon::end_pick_box();
 2524:     if (wantarray) {
 2525:         if ($context eq 'selfcreate') {
 2526:             return($output,$rowcount,$editable);
 2527:         } else {
 2528:             return $output;
 2529:         }
 2530:     } else {
 2531:         return $output;
 2532:     }
 2533: }
 2534: 
 2535: sub pick_inst_statuses {
 2536:     my ($curr,$usertypes,$types) = @_;
 2537:     my ($output,$rem,@currtypes);
 2538:     if ($curr ne '') {
 2539:         @currtypes = map { &unescape($_); } split(/:/,$curr);
 2540:     }
 2541:     my $numinrow = 2;
 2542:     if (ref($types) eq 'ARRAY') {
 2543:         $output = '<table>';
 2544:         my $lastcolspan; 
 2545:         for (my $i=0; $i<@{$types}; $i++) {
 2546:             if (defined($usertypes->{$types->[$i]})) {
 2547:                 my $rem = $i%($numinrow);
 2548:                 if ($rem == 0) {
 2549:                     if ($i<@{$types}-1) {
 2550:                         if ($i > 0) { 
 2551:                             $output .= '</tr>';
 2552:                         }
 2553:                         $output .= '<tr>';
 2554:                     }
 2555:                 } elsif ($i==@{$types}-1) {
 2556:                     my $colsleft = $numinrow - $rem;
 2557:                     if ($colsleft > 1) {
 2558:                         $lastcolspan = ' colspan="'.$colsleft.'"';
 2559:                     }
 2560:                 }
 2561:                 my $check = ' ';
 2562:                 if (grep(/^\Q$types->[$i]\E$/,@currtypes)) {
 2563:                     $check = ' checked="checked" ';
 2564:                 }
 2565:                 $output .= '<td class="LC_left_item"'.$lastcolspan.'>'.
 2566:                            '<span class="LC_nobreak"><label>'.
 2567:                            '<input type="checkbox" name="inststatus" '.
 2568:                            'value="'.$types->[$i].'"'.$check.'/>'.
 2569:                            $usertypes->{$types->[$i]}.'</label></span></td>';
 2570:             }
 2571:         }
 2572:         $output .= '</tr></table>';
 2573:     }
 2574:     return $output;
 2575: }
 2576: 
 2577: sub selfcreate_canmodify {
 2578:     my ($context,$dom,$userinfo,$inst_results,$rolesarray) = @_;
 2579:     if (ref($inst_results) eq 'HASH') {
 2580:         my @inststatuses = &get_inststatuses($inst_results);
 2581:         if (@inststatuses == 0) {
 2582:             @inststatuses = ('default');
 2583:         }
 2584:         $rolesarray = \@inststatuses;
 2585:     }
 2586:     my %canmodify =
 2587:         &Apache::lonuserutils::can_modify_userinfo($context,$dom,$userinfo,
 2588:                                                    $rolesarray);
 2589:     return %canmodify;
 2590: }
 2591: 
 2592: sub get_inststatuses {
 2593:     my ($insthashref) = @_;
 2594:     my @inststatuses = ();
 2595:     if (ref($insthashref) eq 'HASH') {
 2596:         if (ref($insthashref->{'inststatus'}) eq 'ARRAY') {
 2597:             @inststatuses = @{$insthashref->{'inststatus'}};
 2598:         }
 2599:     }
 2600:     return @inststatuses;
 2601: }
 2602: 
 2603: # ================================================================= Phase Three
 2604: sub update_user_data {
 2605:     my ($r,$context,$crstype,$brcrum,$showcredits) = @_; 
 2606:     my $uhome=&Apache::lonnet::homeserver($env{'form.ccuname'},
 2607:                                           $env{'form.ccdomain'});
 2608:     # Error messages
 2609:     my $error     = '<span class="LC_error">'.&mt('Error').': ';
 2610:     my $end       = '</span><br /><br />';
 2611:     my $rtnlink   = '<a href="javascript:backPage(document.userupdate,'.
 2612:                     "'$env{'form.prevphase'}','modify')".'" />'.
 2613:                     &mt('Return to previous page').'</a>'.
 2614:                     &Apache::loncommon::end_page();
 2615:     my $now = time;
 2616:     my $title;
 2617:     if (exists($env{'form.makeuser'})) {
 2618: 	$title='Set Privileges for New User';
 2619:     } else {
 2620:         $title='Modify User Privileges';
 2621:     }
 2622:     my $newuser = 0;
 2623:     my ($jsback,$elements) = &crumb_utilities();
 2624:     my $jscript = '<script type="text/javascript">'."\n".
 2625:                   '// <![CDATA['."\n".
 2626:                   $jsback."\n".
 2627:                   '// ]]>'."\n".
 2628:                   '</script>'."\n";
 2629:     my %breadcrumb_text = &singleuser_breadcrumb($crstype,$context,$env{'form.ccdomain'});
 2630:     push (@{$brcrum},
 2631:              {href => "javascript:backPage(document.userupdate)",
 2632:               text => $breadcrumb_text{'search'},
 2633:               faq  => 282,
 2634:               bug  => 'Instructor Interface',}
 2635:              );
 2636:     if ($env{'form.prevphase'} eq 'userpicked') {
 2637:         push(@{$brcrum},
 2638:                {href => "javascript:backPage(document.userupdate,'get_user_info','select')",
 2639:                 text => $breadcrumb_text{'userpicked'},
 2640:                 faq  => 282,
 2641:                 bug  => 'Instructor Interface',});
 2642:     }
 2643:     my $helpitem = 'Course_Change_Privileges';
 2644:     if ($env{'form.action'} eq 'singlestudent') {
 2645:         $helpitem = 'Course_Add_Student';
 2646:     }
 2647:     push(@{$brcrum}, 
 2648:             {href => "javascript:backPage(document.userupdate,'$env{'form.prevphase'}','modify')",
 2649:              text => $breadcrumb_text{'modify'},
 2650:              faq  => 282,
 2651:              bug  => 'Instructor Interface',},
 2652:             {href => "/adm/createuser",
 2653:              text => "Result",
 2654:              faq  => 282,
 2655:              bug  => 'Instructor Interface',
 2656:              help => $helpitem});
 2657:     my $args = {bread_crumbs          => $brcrum,
 2658:                 bread_crumbs_component => 'User Management'};
 2659:     if ($env{'form.popup'}) {
 2660:         $args->{'no_nav_bar'} = 1;
 2661:     }
 2662:     $r->print(&Apache::loncommon::start_page($title,$jscript,$args));
 2663:     $r->print(&update_result_form($uhome));
 2664:     # Check Inputs
 2665:     if (! $env{'form.ccuname'} ) {
 2666: 	$r->print($error.&mt('No login name specified').'.'.$end.$rtnlink);
 2667: 	return;
 2668:     }
 2669:     if (  $env{'form.ccuname'} ne 
 2670: 	  &LONCAPA::clean_username($env{'form.ccuname'}) ) {
 2671: 	$r->print($error.&mt('Invalid login name.').'  '.
 2672: 		  &mt('Only letters, numbers, periods, dashes, @, and underscores are valid.').
 2673: 		  $end.$rtnlink);
 2674: 	return;
 2675:     }
 2676:     if (! $env{'form.ccdomain'}       ) {
 2677: 	$r->print($error.&mt('No domain specified').'.'.$end.$rtnlink);
 2678: 	return;
 2679:     }
 2680:     if (  $env{'form.ccdomain'} ne
 2681: 	  &LONCAPA::clean_domain($env{'form.ccdomain'}) ) {
 2682: 	$r->print($error.&mt('Invalid domain name.').'  '.
 2683: 		  &mt('Only letters, numbers, periods, dashes, and underscores are valid.').
 2684: 		  $end.$rtnlink);
 2685: 	return;
 2686:     }
 2687:     if ($uhome eq 'no_host') {
 2688:         $newuser = 1;
 2689:     }
 2690:     if (! exists($env{'form.makeuser'})) {
 2691:         # Modifying an existing user, so check the validity of the name
 2692:         if ($uhome eq 'no_host') {
 2693:             $r->print(
 2694:                 $error
 2695:                .'<p class="LC_error">'
 2696:                .&mt('Unable to determine home server for [_1] in domain [_2].',
 2697:                         '"'.$env{'form.ccuname'}.'"','"'.$env{'form.ccdomain'}.'"')
 2698:                .'</p>');
 2699:             return;
 2700:         }
 2701:     }
 2702:     # Determine authentication method and password for the user being modified
 2703:     my $amode='';
 2704:     my $genpwd='';
 2705:     if ($env{'form.login'} eq 'krb') {
 2706: 	$amode='krb';
 2707: 	$amode.=$env{'form.krbver'};
 2708: 	$genpwd=$env{'form.krbarg'};
 2709:     } elsif ($env{'form.login'} eq 'int') {
 2710: 	$amode='internal';
 2711: 	$genpwd=$env{'form.intarg'};
 2712:     } elsif ($env{'form.login'} eq 'fsys') {
 2713: 	$amode='unix';
 2714: 	$genpwd=$env{'form.fsysarg'};
 2715:     } elsif ($env{'form.login'} eq 'loc') {
 2716: 	$amode='localauth';
 2717: 	$genpwd=$env{'form.locarg'};
 2718: 	$genpwd=" " if (!$genpwd);
 2719:     } elsif (($env{'form.login'} eq 'nochange') ||
 2720:              ($env{'form.login'} eq ''        )) { 
 2721:         # There is no need to tell the user we did not change what they
 2722:         # did not ask us to change.
 2723:         # If they are creating a new user but have not specified login
 2724:         # information this will be caught below.
 2725:     } else {
 2726:             $r->print($error.&mt('Invalid login mode or password').$end.$rtnlink);
 2727:             return;
 2728:     }
 2729: 
 2730:     $r->print('<h3>'.&mt('User [_1] in domain [_2]',
 2731:                         $env{'form.ccuname'}.' ('.&Apache::loncommon::plainname($env{'form.ccuname'},
 2732:                         $env{'form.ccdomain'}).')', $env{'form.ccdomain'}).'</h3>');
 2733:     my %prog_state = &Apache::lonhtmlcommon::Create_PrgWin($r,2);
 2734: 
 2735:     my (%alerts,%rulematch,%inst_results,%curr_rules);
 2736:     my @userinfo = ('firstname','middlename','lastname','generation','permanentemail','id');
 2737:     my @usertools = ('aboutme','blog','webdav','portfolio');
 2738:     my @requestcourses = ('official','unofficial','community','textbook','placement');
 2739:     my @requestauthor = ('requestauthor');
 2740:     my ($othertitle,$usertypes,$types) = 
 2741:         &Apache::loncommon::sorted_inst_types($env{'form.ccdomain'});
 2742:     my %canmodify_status =
 2743:         &Apache::lonuserutils::can_modify_userinfo($context,$env{'form.ccdomain'},
 2744:                                                    ['inststatus']);
 2745:     if ($env{'form.makeuser'}) {
 2746: 	$r->print('<h3>'.&mt('Creating new account.').'</h3>');
 2747:         # Check for the authentication mode and password
 2748:         if (! $amode || ! $genpwd) {
 2749: 	    $r->print($error.&mt('Invalid login mode or password').$end.$rtnlink);    
 2750: 	    return;
 2751: 	}
 2752:         # Determine desired host
 2753:         my $desiredhost = $env{'form.hserver'};
 2754:         if (lc($desiredhost) eq 'default') {
 2755:             $desiredhost = undef;
 2756:         } else {
 2757:             my %home_servers = 
 2758: 		&Apache::lonnet::get_servers($env{'form.ccdomain'},'library');
 2759:             if (! exists($home_servers{$desiredhost})) {
 2760:                 $r->print($error.&mt('Invalid home server specified').$end.$rtnlink);
 2761:                 return;
 2762:             }
 2763:         }
 2764:         # Check ID format
 2765:         my %checkhash;
 2766:         my %checks = ('id' => 1);
 2767:         %{$checkhash{$env{'form.ccuname'}.':'.$env{'form.ccdomain'}}} = (
 2768:             'newuser' => $newuser, 
 2769:             'id' => $env{'form.cid'},
 2770:         );
 2771:         if ($env{'form.cid'} ne '') {
 2772:             &Apache::loncommon::user_rule_check(\%checkhash,\%checks,\%alerts,
 2773:                                           \%rulematch,\%inst_results,\%curr_rules);
 2774:             if (ref($alerts{'id'}) eq 'HASH') {
 2775:                 if (ref($alerts{'id'}{$env{'form.ccdomain'}}) eq 'HASH') {
 2776:                     my $domdesc =
 2777:                         &Apache::lonnet::domain($env{'form.ccdomain'},'description');
 2778:                     if ($alerts{'id'}{$env{'form.ccdomain'}}{$env{'form.cid'}}) {
 2779:                         my $userchkmsg;
 2780:                         if (ref($curr_rules{$env{'form.ccdomain'}}) eq 'HASH') {
 2781:                             $userchkmsg  = 
 2782:                                 &Apache::loncommon::instrule_disallow_msg('id',
 2783:                                                                     $domdesc,1).
 2784:                                 &Apache::loncommon::user_rule_formats($env{'form.ccdomain'},
 2785:                                     $domdesc,$curr_rules{$env{'form.ccdomain'}}{'id'},'id');
 2786:                         }
 2787:                         $r->print($error.&mt('Invalid ID format').$end.
 2788:                                   $userchkmsg.$rtnlink);
 2789:                         return;
 2790:                     }
 2791:                 }
 2792:             }
 2793:         }
 2794:         &Apache::lonhtmlcommon::Increment_PrgWin($r, \%prog_state);
 2795: 	# Call modifyuser
 2796: 	my $result = &Apache::lonnet::modifyuser
 2797: 	    ($env{'form.ccdomain'},$env{'form.ccuname'},$env{'form.cid'},
 2798:              $amode,$genpwd,$env{'form.cfirstname'},
 2799:              $env{'form.cmiddlename'},$env{'form.clastname'},
 2800:              $env{'form.cgeneration'},undef,$desiredhost,
 2801:              $env{'form.cpermanentemail'});
 2802: 	$r->print(&mt('Generating user').': '.$result);
 2803:         $uhome = &Apache::lonnet::homeserver($env{'form.ccuname'},
 2804:                                                $env{'form.ccdomain'});
 2805:         my (%changeHash,%newcustom,%changed,%changedinfo);
 2806:         if ($uhome ne 'no_host') {
 2807:             if ($context eq 'domain') {
 2808:                 foreach my $name ('portfolio','author') {
 2809:                     if ($env{'form.custom_'.$name.'quota'} == 1) {
 2810:                         if ($env{'form.'.$name.'quota'} eq '') {
 2811:                             $newcustom{$name.'quota'} = 0;
 2812:                         } else {
 2813:                             $newcustom{$name.'quota'} = $env{'form.'.$name.'quota'};
 2814:                             $newcustom{$name.'quota'} =~ s/[^\d\.]//g;
 2815:                         }
 2816:                         if (&quota_admin($newcustom{$name.'quota'},\%changeHash,$name)) {
 2817:                             $changed{$name.'quota'} = 1;
 2818:                         }
 2819:                     }
 2820:                 }
 2821:                 foreach my $item (@usertools) {
 2822:                     if ($env{'form.custom'.$item} == 1) {
 2823:                         $newcustom{$item} = $env{'form.tools_'.$item};
 2824:                         $changed{$item} = &tool_admin($item,$newcustom{$item},
 2825:                                                      \%changeHash,'tools');
 2826:                     }
 2827:                 }
 2828:                 foreach my $item (@requestcourses) {
 2829:                     if ($env{'form.custom'.$item} == 1) {
 2830:                         $newcustom{$item} = $env{'form.crsreq_'.$item};
 2831:                         if ($env{'form.crsreq_'.$item} eq 'autolimit') {
 2832:                             $newcustom{$item} .= '=';
 2833:                             $env{'form.crsreq_'.$item.'_limit'} =~ s/\D+//g;
 2834:                             if ($env{'form.crsreq_'.$item.'_limit'}) {
 2835:                                 $newcustom{$item} .= $env{'form.crsreq_'.$item.'_limit'};
 2836:                             }
 2837:                         }
 2838:                         $changed{$item} = &tool_admin($item,$newcustom{$item},
 2839:                                                       \%changeHash,'requestcourses');
 2840:                     }
 2841:                 }
 2842:                 if ($env{'form.customrequestauthor'} == 1) {
 2843:                     $newcustom{'requestauthor'} = $env{'form.requestauthor'};
 2844:                     $changed{'requestauthor'} = &tool_admin('requestauthor',
 2845:                                                     $newcustom{'requestauthor'},
 2846:                                                     \%changeHash,'requestauthor');
 2847:                 }
 2848:             }
 2849:             if ($canmodify_status{'inststatus'}) {
 2850:                 if (exists($env{'form.inststatus'})) {
 2851:                     my @inststatuses = &Apache::loncommon::get_env_multiple('form.inststatus');
 2852:                     if (@inststatuses > 0) {
 2853:                         $changeHash{'inststatus'} = join(',',@inststatuses);
 2854:                         $changed{'inststatus'} = $changeHash{'inststatus'};
 2855:                     }
 2856:                 }
 2857:             }
 2858:             if (keys(%changed)) {
 2859:                 foreach my $item (@userinfo) {
 2860:                     $changeHash{$item}  = $env{'form.c'.$item};
 2861:                 }
 2862:                 my $chgresult =
 2863:                      &Apache::lonnet::put('environment',\%changeHash,
 2864:                                           $env{'form.ccdomain'},$env{'form.ccuname'});
 2865:             } 
 2866:         }
 2867:         $r->print('<br />'.&mt('Home server').': '.$uhome.' '.
 2868:                   &Apache::lonnet::hostname($uhome));
 2869:     } elsif (($env{'form.login'} ne 'nochange') &&
 2870:              ($env{'form.login'} ne ''        )) {
 2871: 	# Modify user privileges
 2872:         if (! $amode || ! $genpwd) {
 2873: 	    $r->print($error.'Invalid login mode or password'.$end.$rtnlink);    
 2874: 	    return;
 2875: 	}
 2876: 	# Only allow authentication modification if the person has authority
 2877: 	if (&Apache::lonnet::allowed('mau',$env{'form.ccdomain'})) {
 2878: 	    $r->print('Modifying authentication: '.
 2879:                       &Apache::lonnet::modifyuserauth(
 2880: 		       $env{'form.ccdomain'},$env{'form.ccuname'},
 2881:                        $amode,$genpwd));
 2882:             $r->print('<br />'.&mt('Home server').': '.&Apache::lonnet::homeserver
 2883: 		  ($env{'form.ccuname'},$env{'form.ccdomain'}));
 2884: 	} else {
 2885: 	    # Okay, this is a non-fatal error.
 2886: 	    $r->print($error.&mt('You do not have the authority to modify this users authentication information.').$end);    
 2887: 	}
 2888:     }
 2889:     $r->rflush(); # Finish display of header before time consuming actions start
 2890:     &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state);
 2891:     ##
 2892:     my (@userroles,%userupdate,$cnum,$cdom,$defaultcredits,%namechanged);
 2893:     if ($context eq 'course') {
 2894:         ($cnum,$cdom) =
 2895:             &Apache::lonuserutils::get_course_identity();
 2896:         $crstype = &Apache::loncommon::course_type($cdom.'_'.$cnum);
 2897:         if ($showcredits) {
 2898:            $defaultcredits = &Apache::lonuserutils::get_defaultcredits($cdom,$cnum);
 2899:         }
 2900:     }
 2901:     if (! $env{'form.makeuser'} ) {
 2902:         # Check for need to change
 2903:         my %userenv = &Apache::lonnet::get
 2904:             ('environment',['firstname','middlename','lastname','generation',
 2905:              'id','permanentemail','portfolioquota','authorquota','inststatus',
 2906:              'tools.aboutme','tools.blog','tools.webdav','tools.portfolio',
 2907:              'requestcourses.official','requestcourses.unofficial',
 2908:              'requestcourses.community','requestcourses.textbook',
 2909:              'reqcrsotherdom.official','reqcrsotherdom.unofficial',
 2910:              'reqcrsotherdom.community','reqcrsotherdom.textbook',
 2911:              'reqcrsotherdom.placement','requestauthor'],
 2912:               $env{'form.ccdomain'},$env{'form.ccuname'});
 2913:         my ($tmp) = keys(%userenv);
 2914:         if ($tmp =~ /^(con_lost|error)/i) { 
 2915:             %userenv = ();
 2916:         }
 2917:         my $no_forceid_alert;
 2918:         # Check to see if user information can be changed
 2919:         my %domconfig =
 2920:             &Apache::lonnet::get_dom('configuration',['usermodification'],
 2921:                                      $env{'form.ccdomain'});
 2922:         my @statuses = ('active','future');
 2923:         my %roles = &Apache::lonnet::get_my_roles($env{'form.ccuname'},$env{'form.ccdomain'},'userroles',\@statuses,undef,$env{'request.role.domain'});
 2924:         my ($auname,$audom);
 2925:         if ($context eq 'author') {
 2926:             $auname = $env{'user.name'};
 2927:             $audom = $env{'user.domain'};     
 2928:         }
 2929:         foreach my $item (keys(%roles)) {
 2930:             my ($rolenum,$roledom,$role) = split(/:/,$item,-1);
 2931:             if ($context eq 'course') {
 2932:                 if ($cnum ne '' && $cdom ne '') {
 2933:                     if ($rolenum eq $cnum && $roledom eq $cdom) {
 2934:                         if (!grep(/^\Q$role\E$/,@userroles)) {
 2935:                             push(@userroles,$role);
 2936:                         }
 2937:                     }
 2938:                 }
 2939:             } elsif ($context eq 'author') {
 2940:                 if ($rolenum eq $auname && $roledom eq $audom) {
 2941:                     if (!grep(/^\Q$role\E$/,@userroles)) { 
 2942:                         push(@userroles,$role);
 2943:                     }
 2944:                 }
 2945:             }
 2946:         }
 2947:         if ($env{'form.action'} eq 'singlestudent') {
 2948:             if (!grep(/^st$/,@userroles)) {
 2949:                 push(@userroles,'st');
 2950:             }
 2951:         } else {
 2952:             # Check for course or co-author roles being activated or re-enabled
 2953:             if ($context eq 'author' || $context eq 'course') {
 2954:                 foreach my $key (keys(%env)) {
 2955:                     if ($context eq 'author') {
 2956:                         if ($key=~/^form\.act_\Q$audom\E_\Q$auname\E_([^_]+)/) {
 2957:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 2958:                                 push(@userroles,$1);
 2959:                             }
 2960:                         } elsif ($key =~/^form\.ren\:\Q$audom\E\/\Q$auname\E_([^_]+)/) {
 2961:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 2962:                                 push(@userroles,$1);
 2963:                             }
 2964:                         }
 2965:                     } elsif ($context eq 'course') {
 2966:                         if ($key=~/^form\.act_\Q$cdom\E_\Q$cnum\E_([^_]+)/) {
 2967:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 2968:                                 push(@userroles,$1);
 2969:                             }
 2970:                         } elsif ($key =~/^form\.ren\:\Q$cdom\E\/\Q$cnum\E(\/?\w*)_([^_]+)/) {
 2971:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 2972:                                 push(@userroles,$1);
 2973:                             }
 2974:                         }
 2975:                     }
 2976:                 }
 2977:             }
 2978:         }
 2979:         #Check to see if we can change personal data for the user 
 2980:         my (@mod_disallowed,@longroles);
 2981:         foreach my $role (@userroles) {
 2982:             if ($role eq 'cr') {
 2983:                 push(@longroles,'Custom');
 2984:             } else {
 2985:                 push(@longroles,&Apache::lonnet::plaintext($role,$crstype)); 
 2986:             }
 2987:         }
 2988:         my %canmodify = &Apache::lonuserutils::can_modify_userinfo($context,$env{'form.ccdomain'},\@userinfo,\@userroles);
 2989:         foreach my $item (@userinfo) {
 2990:             # Strip leading and trailing whitespace
 2991:             $env{'form.c'.$item} =~ s/(\s+$|^\s+)//g;
 2992:             if (!$canmodify{$item}) {
 2993:                 if (defined($env{'form.c'.$item})) {
 2994:                     if ($env{'form.c'.$item} ne $userenv{$item}) {
 2995:                         push(@mod_disallowed,$item);
 2996:                     }
 2997:                 }
 2998:                 $env{'form.c'.$item} = $userenv{$item};
 2999:             }
 3000:         }
 3001:         # Check to see if we can change the Student/Employee ID
 3002:         my $forceid = $env{'form.forceid'};
 3003:         my $recurseid = $env{'form.recurseid'};
 3004:         my (%alerts,%rulematch,%idinst_results,%curr_rules,%got_rules);
 3005:         my %uidhash = &Apache::lonnet::idrget($env{'form.ccdomain'},
 3006:                                             $env{'form.ccuname'});
 3007:         if (($uidhash{$env{'form.ccuname'}}) && 
 3008:             ($uidhash{$env{'form.ccuname'}}!~/error\:/) && 
 3009:             (!$forceid)) {
 3010:             if ($env{'form.cid'} ne $uidhash{$env{'form.ccuname'}}) {
 3011:                 $env{'form.cid'} = $userenv{'id'};
 3012:                 $no_forceid_alert = &mt('New student/employee ID does not match existing ID for this user.')
 3013:                                    .'<br />'
 3014:                                    .&mt("Change is not permitted without checking the 'Force ID change' checkbox on the previous page.")
 3015:                                    .'<br />'."\n";
 3016:             }
 3017:         }
 3018:         if ($env{'form.cid'} ne $userenv{'id'}) {
 3019:             my $checkhash;
 3020:             my $checks = { 'id' => 1 };
 3021:             $checkhash->{$env{'form.ccuname'}.':'.$env{'form.ccdomain'}} = 
 3022:                    { 'newuser' => $newuser,
 3023:                      'id'  => $env{'form.cid'}, 
 3024:                    };
 3025:             &Apache::loncommon::user_rule_check($checkhash,$checks,
 3026:                 \%alerts,\%rulematch,\%idinst_results,\%curr_rules,\%got_rules);
 3027:             if (ref($alerts{'id'}) eq 'HASH') {
 3028:                 if (ref($alerts{'id'}{$env{'form.ccdomain'}}) eq 'HASH') {
 3029:                    $env{'form.cid'} = $userenv{'id'};
 3030:                 }
 3031:             }
 3032:         }
 3033:         my (%quotachanged,%oldquota,%newquota,%olddefquota,%newdefquota, 
 3034:             $oldinststatus,$newinststatus,%oldisdefault,%newisdefault,%oldsettings,
 3035:             %oldsettingstext,%newsettings,%newsettingstext,@disporder,
 3036:             %oldsettingstatus,%newsettingstatus);
 3037:         @disporder = ('inststatus');
 3038:         if ($env{'request.role.domain'} eq $env{'form.ccdomain'}) {
 3039:             push(@disporder,'requestcourses','requestauthor');
 3040:         } else {
 3041:             push(@disporder,'reqcrsotherdom');
 3042:         }
 3043:         push(@disporder,('quota','tools'));
 3044:         $oldinststatus = $userenv{'inststatus'};
 3045:         foreach my $name ('portfolio','author') {
 3046:             ($olddefquota{$name},$oldsettingstatus{$name}) = 
 3047:                 &Apache::loncommon::default_quota($env{'form.ccdomain'},$oldinststatus,$name);
 3048:             ($newdefquota{$name},$newsettingstatus{$name}) = ($olddefquota{$name},$oldsettingstatus{$name});
 3049:         }
 3050:         my %canshow;
 3051:         if (&Apache::lonnet::allowed('mpq',$env{'form.ccdomain'})) {
 3052:             $canshow{'quota'} = 1;
 3053:         }
 3054:         if (&Apache::lonnet::allowed('mut',$env{'form.ccdomain'})) {
 3055:             $canshow{'tools'} = 1;
 3056:         }
 3057:         if (&Apache::lonnet::allowed('ccc',$env{'form.ccdomain'})) {
 3058:             $canshow{'requestcourses'} = 1;
 3059:         } elsif (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) {
 3060:             $canshow{'reqcrsotherdom'} = 1;
 3061:         }
 3062:         if (&Apache::lonnet::allowed('mau',$env{'form.ccdomain'})) {
 3063:             $canshow{'inststatus'} = 1;
 3064:         }
 3065:         if (&Apache::lonnet::allowed('cau',$env{'form.ccdomain'})) {
 3066:             $canshow{'requestauthor'} = 1;
 3067:         }
 3068:         my (%changeHash,%changed);
 3069:         if ($oldinststatus eq '') {
 3070:             $oldsettings{'inststatus'} = $othertitle; 
 3071:         } else {
 3072:             if (ref($usertypes) eq 'HASH') {
 3073:                 $oldsettings{'inststatus'} = join(', ',map{ $usertypes->{ &unescape($_) }; } (split(/:/,$userenv{'inststatus'})));
 3074:             } else {
 3075:                 $oldsettings{'inststatus'} = join(', ',map{ &unescape($_); } (split(/:/,$userenv{'inststatus'})));
 3076:             }
 3077:         }
 3078:         $changeHash{'inststatus'} = $userenv{'inststatus'};
 3079:         if ($canmodify_status{'inststatus'}) {
 3080:             $canshow{'inststatus'} = 1;
 3081:             if (exists($env{'form.inststatus'})) {
 3082:                 my @inststatuses = &Apache::loncommon::get_env_multiple('form.inststatus');
 3083:                 if (@inststatuses > 0) {
 3084:                     $newinststatus = join(':',map { &escape($_); } @inststatuses);
 3085:                     $changeHash{'inststatus'} = $newinststatus;
 3086:                     if ($newinststatus ne $oldinststatus) {
 3087:                         $changed{'inststatus'} = $newinststatus;
 3088:                         foreach my $name ('portfolio','author') {
 3089:                             ($newdefquota{$name},$newsettingstatus{$name}) =
 3090:                                 &Apache::loncommon::default_quota($env{'form.ccdomain'},$newinststatus,$name);
 3091:                         }
 3092:                     }
 3093:                     if (ref($usertypes) eq 'HASH') {
 3094:                         $newsettings{'inststatus'} = join(', ',map{ $usertypes->{$_}; } (@inststatuses)); 
 3095:                     } else {
 3096:                         $newsettings{'inststatus'} = join(', ',@inststatuses);
 3097:                     }
 3098:                 }
 3099:             } else {
 3100:                 $newinststatus = '';
 3101:                 $changeHash{'inststatus'} = $newinststatus;
 3102:                 $newsettings{'inststatus'} = $othertitle;
 3103:                 if ($newinststatus ne $oldinststatus) {
 3104:                     $changed{'inststatus'} = $changeHash{'inststatus'};
 3105:                     foreach my $name ('portfolio','author') {
 3106:                         ($newdefquota{$name},$newsettingstatus{$name}) =
 3107:                             &Apache::loncommon::default_quota($env{'form.ccdomain'},$newinststatus,$name);
 3108:                     }
 3109:                 }
 3110:             }
 3111:         } elsif ($context ne 'selfcreate') {
 3112:             $canshow{'inststatus'} = 1;
 3113:             $newsettings{'inststatus'} = $oldsettings{'inststatus'};
 3114:         }
 3115:         foreach my $name ('portfolio','author') {
 3116:             $changeHash{$name.'quota'} = $userenv{$name.'quota'};
 3117:         }
 3118:         if ($context eq 'domain') {
 3119:             foreach my $name ('portfolio','author') {
 3120:                 if ($userenv{$name.'quota'} ne '') {
 3121:                     $oldquota{$name} = $userenv{$name.'quota'};
 3122:                     if ($env{'form.custom_'.$name.'quota'} == 1) {
 3123:                         if ($env{'form.'.$name.'quota'} eq '') {
 3124:                             $newquota{$name} = 0;
 3125:                         } else {
 3126:                             $newquota{$name} = $env{'form.'.$name.'quota'};
 3127:                             $newquota{$name} =~ s/[^\d\.]//g;
 3128:                         }
 3129:                         if ($newquota{$name} != $oldquota{$name}) {
 3130:                             if (&quota_admin($newquota{$name},\%changeHash,$name)) {
 3131:                                 $changed{$name.'quota'} = 1;
 3132:                             }
 3133:                         }
 3134:                     } else {
 3135:                         if (&quota_admin('',\%changeHash,$name)) {
 3136:                             $changed{$name.'quota'} = 1;
 3137:                             $newquota{$name} = $newdefquota{$name};
 3138:                             $newisdefault{$name} = 1;
 3139:                         }
 3140:                     }
 3141:                 } else {
 3142:                     $oldisdefault{$name} = 1;
 3143:                     $oldquota{$name} = $olddefquota{$name};
 3144:                     if ($env{'form.custom_'.$name.'quota'} == 1) {
 3145:                         if ($env{'form.'.$name.'quota'} eq '') {
 3146:                             $newquota{$name} = 0;
 3147:                         } else {
 3148:                             $newquota{$name} = $env{'form.'.$name.'quota'};
 3149:                             $newquota{$name} =~ s/[^\d\.]//g;
 3150:                         }
 3151:                         if (&quota_admin($newquota{$name},\%changeHash,$name)) {
 3152:                             $changed{$name.'quota'} = 1;
 3153:                         }
 3154:                     } else {
 3155:                         $newquota{$name} = $newdefquota{$name};
 3156:                         $newisdefault{$name} = 1;
 3157:                     }
 3158:                 }
 3159:                 if ($oldisdefault{$name}) {
 3160:                     $oldsettingstext{'quota'}{$name} = &get_defaultquota_text($oldsettingstatus{$name});
 3161:                 }  else {
 3162:                     $oldsettingstext{'quota'}{$name} = &mt('custom quota: [_1] MB',$oldquota{$name});
 3163:                 }
 3164:                 if ($newisdefault{$name}) {
 3165:                     $newsettingstext{'quota'}{$name} = &get_defaultquota_text($newsettingstatus{$name});
 3166:                 } else {
 3167:                     $newsettingstext{'quota'}{$name} = &mt('custom quota: [_1] MB',$newquota{$name});
 3168:                 }
 3169:             }
 3170:             &tool_changes('tools',\@usertools,\%oldsettings,\%oldsettingstext,\%userenv,
 3171:                           \%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3172:             if ($env{'form.ccdomain'} eq $env{'request.role.domain'}) {
 3173:                 &tool_changes('requestcourses',\@requestcourses,\%oldsettings,\%oldsettingstext,
 3174:                               \%userenv,\%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3175:                 &tool_changes('requestauthor',\@requestauthor,\%oldsettings,\%oldsettingstext,
 3176:                               \%userenv,\%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3177:             } else {
 3178:                 &tool_changes('reqcrsotherdom',\@requestcourses,\%oldsettings,\%oldsettingstext,
 3179:                               \%userenv,\%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3180:             }
 3181:         }
 3182:         foreach my $item (@userinfo) {
 3183:             if ($env{'form.c'.$item} ne $userenv{$item}) {
 3184:                 $namechanged{$item} = 1;
 3185:             }
 3186:         }
 3187:         foreach my $name ('portfolio','author') {
 3188:             $oldsettings{'quota'}{$name} = &mt('[_1] MB',$oldquota{$name});
 3189:             $newsettings{'quota'}{$name} = &mt('[_1] MB',$newquota{$name});
 3190:         }
 3191:         if ((keys(%namechanged) > 0) || (keys(%changed) > 0)) {
 3192:             my ($chgresult,$namechgresult);
 3193:             if (keys(%changed) > 0) {
 3194:                 $chgresult = 
 3195:                     &Apache::lonnet::put('environment',\%changeHash,
 3196:                                   $env{'form.ccdomain'},$env{'form.ccuname'});
 3197:                 if ($chgresult eq 'ok') {
 3198:                     if (($env{'user.name'} eq $env{'form.ccuname'}) &&
 3199:                         ($env{'user.domain'} eq $env{'form.ccdomain'})) {
 3200:                         my %newenvhash;
 3201:                         foreach my $key (keys(%changed)) {
 3202:                             if (($key eq 'official') || ($key eq 'unofficial') ||
 3203:                                 ($key eq 'community') || ($key eq 'textbook') ||
 3204:                                 ($key eq 'placement')) {
 3205:                                 $newenvhash{'environment.requestcourses.'.$key} =
 3206:                                     $changeHash{'requestcourses.'.$key};
 3207:                                 if ($changeHash{'requestcourses.'.$key}) {
 3208:                                     $newenvhash{'environment.canrequest.'.$key} = 1;
 3209:                                 } else {
 3210:                                     $newenvhash{'environment.canrequest.'.$key} =
 3211:           &Apache::lonnet::usertools_access($env{'user.name'},$env{'user.domain'},
 3212:                                             $key,'reload','requestcourses');
 3213:                                 }
 3214:                             } elsif ($key eq 'requestauthor') {
 3215:                                 $newenvhash{'environment.'.$key} = $changeHash{$key};
 3216:                                 if ($changeHash{$key}) {
 3217:                                     $newenvhash{'environment.canrequest.author'} = 1;
 3218:                                 } else {
 3219:                                     $newenvhash{'environment.canrequest.author'} =
 3220:           &Apache::lonnet::usertools_access($env{'user.name'},$env{'user.domain'},
 3221:                                             $key,'reload','requestauthor');
 3222:                                 }
 3223:                             } elsif ($key ne 'quota') {
 3224:                                 $newenvhash{'environment.tools.'.$key} = 
 3225:                                     $changeHash{'tools.'.$key};
 3226:                                 if ($changeHash{'tools.'.$key} ne '') {
 3227:                                     $newenvhash{'environment.availabletools.'.$key} =
 3228:                                         $changeHash{'tools.'.$key};
 3229:                                 } else {
 3230:                                     $newenvhash{'environment.availabletools.'.$key} =
 3231:           &Apache::lonnet::usertools_access($env{'user.name'},$env{'user.domain'},
 3232:           $key,'reload','tools');
 3233:                                 }
 3234:                             }
 3235:                         }
 3236:                         if (keys(%newenvhash)) {
 3237:                             &Apache::lonnet::appenv(\%newenvhash);
 3238:                         }
 3239:                     }
 3240:                 }
 3241:             }
 3242:             if (keys(%namechanged) > 0) {
 3243:                 foreach my $field (@userinfo) {
 3244:                     $changeHash{$field}  = $env{'form.c'.$field};
 3245:                 }
 3246: # Make the change
 3247:                 $namechgresult =
 3248:                     &Apache::lonnet::modifyuser($env{'form.ccdomain'},
 3249:                         $env{'form.ccuname'},$changeHash{'id'},undef,undef,
 3250:                         $changeHash{'firstname'},$changeHash{'middlename'},
 3251:                         $changeHash{'lastname'},$changeHash{'generation'},
 3252:                         $changeHash{'id'},undef,$changeHash{'permanentemail'},undef,\@userinfo);
 3253:                 %userupdate = (
 3254:                                lastname   => $env{'form.clastname'},
 3255:                                middlename => $env{'form.cmiddlename'},
 3256:                                firstname  => $env{'form.cfirstname'},
 3257:                                generation => $env{'form.cgeneration'},
 3258:                                id         => $env{'form.cid'},
 3259:                              );
 3260:             }
 3261:             if (((keys(%namechanged) > 0) && $namechgresult eq 'ok') || 
 3262:                 ((keys(%changed) > 0) && $chgresult eq 'ok')) {
 3263:             # Tell the user we changed the name
 3264:                 &display_userinfo($r,1,\@disporder,\%canshow,\@requestcourses,
 3265:                                   \@usertools,\@requestauthor,\%userenv,\%changed,\%namechanged,
 3266:                                   \%oldsettings, \%oldsettingstext,\%newsettings,
 3267:                                   \%newsettingstext);
 3268:                 if ($env{'form.cid'} ne $userenv{'id'}) {
 3269:                     &Apache::lonnet::idput($env{'form.ccdomain'},
 3270:                          {$env{'form.ccuname'} => $env{'form.cid'}},$uhome,'ids');
 3271:                     if (($recurseid) &&
 3272:                         (&Apache::lonnet::allowed('mau',$env{'form.ccdomain'}))) {
 3273:                         my $idresult = 
 3274:                             &Apache::lonuserutils::propagate_id_change(
 3275:                                 $env{'form.ccuname'},$env{'form.ccdomain'},
 3276:                                 \%userupdate);
 3277:                         $r->print('<br />'.$idresult.'<br />');
 3278:                     }
 3279:                 }
 3280:                 if (($env{'form.ccdomain'} eq $env{'user.domain'}) && 
 3281:                     ($env{'form.ccuname'} eq $env{'user.name'})) {
 3282:                     my %newenvhash;
 3283:                     foreach my $key (keys(%changeHash)) {
 3284:                         $newenvhash{'environment.'.$key} = $changeHash{$key};
 3285:                     }
 3286:                     &Apache::lonnet::appenv(\%newenvhash);
 3287:                 }
 3288:             } else { # error occurred
 3289:                 $r->print(
 3290:                     '<p class="LC_error">'
 3291:                    .&mt('Unable to successfully change environment for [_1] in domain [_2].',
 3292:                             '"'.$env{'form.ccuname'}.'"',
 3293:                             '"'.$env{'form.ccdomain'}.'"')
 3294:                    .'</p>');
 3295:             }
 3296:         } else { # End of if ($env ... ) logic
 3297:             # They did not want to change the users name, quota, tool availability,
 3298:             # or ability to request creation of courses, 
 3299:             # but we can still tell them what the name and quota and availabilities are  
 3300:             &display_userinfo($r,undef,\@disporder,\%canshow,\@requestcourses,
 3301:                               \@usertools,\@requestauthor,\%userenv,\%changed,\%namechanged,\%oldsettings,
 3302:                               \%oldsettingstext,\%newsettings,\%newsettingstext);
 3303:         }
 3304:         if (@mod_disallowed) {
 3305:             my ($rolestr,$contextname);
 3306:             if (@longroles > 0) {
 3307:                 $rolestr = join(', ',@longroles);
 3308:             } else {
 3309:                 $rolestr = &mt('No roles');
 3310:             }
 3311:             if ($context eq 'course') {
 3312:                 $contextname = 'course';
 3313:             } elsif ($context eq 'author') {
 3314:                 $contextname = 'co-author';
 3315:             }
 3316:             $r->print(&mt('The following fields were not updated: ').'<ul>');
 3317:             my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
 3318:             foreach my $field (@mod_disallowed) {
 3319:                 $r->print('<li>'.$fieldtitles{$field}.'</li>'."\n"); 
 3320:             }
 3321:             $r->print('</ul>');
 3322:             if (@mod_disallowed == 1) {
 3323:                 $r->print(&mt("You do not have the authority to change this field given the user's current set of active/future $contextname roles:"));
 3324:             } else {
 3325:                 $r->print(&mt("You do not have the authority to change these fields given the user's current set of active/future $contextname roles:"));
 3326:             }
 3327:             my $helplink = 'javascript:helpMenu('."'display'".')';
 3328:             $r->print('<span class="LC_cusr_emph">'.$rolestr.'</span><br />'
 3329:                      .&mt('Please contact your [_1]helpdesk[_2] for more information.'
 3330:                          ,'<a href="'.$helplink.'">','</a>')
 3331:                       .'<br />');
 3332:         }
 3333:         $r->print('<span class="LC_warning">'
 3334:                   .$no_forceid_alert
 3335:                   .&Apache::lonuserutils::print_namespacing_alerts($env{'form.ccdomain'},\%alerts,\%curr_rules)
 3336:                   .'</span>');
 3337:     }
 3338:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 3339:     if ($env{'form.action'} eq 'singlestudent') {
 3340:         &enroll_single_student($r,$uhome,$amode,$genpwd,$now,$newuser,$context,
 3341:                                $crstype,$showcredits,$defaultcredits);
 3342:         my $linktext = ($crstype eq 'Community' ?
 3343:             &mt('Enroll Another Member') : &mt('Enroll Another Student'));
 3344:         $r->print(
 3345:             &Apache::lonhtmlcommon::actionbox([
 3346:                 '<a href="javascript:backPage(document.userupdate)">'
 3347:                .($crstype eq 'Community' ? 
 3348:                     &mt('Enroll Another Member') : &mt('Enroll Another Student'))
 3349:                .'</a>']));
 3350:     } else {
 3351:         my @rolechanges = &update_roles($r,$context,$showcredits);
 3352:         if (keys(%namechanged) > 0) {
 3353:             if ($context eq 'course') {
 3354:                 if (@userroles > 0) {
 3355:                     if ((@rolechanges == 0) || 
 3356:                         (!(grep(/^st$/,@rolechanges)))) {
 3357:                         if (grep(/^st$/,@userroles)) {
 3358:                             my $classlistupdated =
 3359:                                 &Apache::lonuserutils::update_classlist($cdom,
 3360:                                               $cnum,$env{'form.ccdomain'},
 3361:                                        $env{'form.ccuname'},\%userupdate);
 3362:                         }
 3363:                     }
 3364:                 }
 3365:             }
 3366:         }
 3367:         my $userinfo = &Apache::loncommon::plainname($env{'form.ccuname'},
 3368:                                                      $env{'form.ccdomain'});
 3369:         if ($env{'form.popup'}) {
 3370:             $r->print('<p><a href="javascript:window.close()">'.&mt('Close window').'</a></p>');
 3371:         } else {
 3372:             $r->print('<br />'.&Apache::lonhtmlcommon::actionbox(['<a href="javascript:backPage(document.userupdate,'."'$env{'form.prevphase'}','modify'".')">'
 3373:                      .&mt('Modify this user: [_1]','<span class="LC_cusr_emph">'.$env{'form.ccuname'}.':'.$env{'form.ccdomain'}.' ('.$userinfo.')</span>').'</a>',
 3374:                      '<a href="javascript:backPage(document.userupdate)">'.&mt('Create/Modify Another User').'</a>']));
 3375:         }
 3376:     }
 3377: }
 3378: 
 3379: sub display_userinfo {
 3380:     my ($r,$changed,$order,$canshow,$requestcourses,$usertools,$requestauthor,
 3381:         $userenv,$changedhash,$namechangedhash,$oldsetting,$oldsettingtext,
 3382:         $newsetting,$newsettingtext) = @_;
 3383:     return unless (ref($order) eq 'ARRAY' &&
 3384:                    ref($canshow) eq 'HASH' && 
 3385:                    ref($requestcourses) eq 'ARRAY' && 
 3386:                    ref($requestauthor) eq 'ARRAY' &&
 3387:                    ref($usertools) eq 'ARRAY' && 
 3388:                    ref($userenv) eq 'HASH' &&
 3389:                    ref($changedhash) eq 'HASH' &&
 3390:                    ref($oldsetting) eq 'HASH' &&
 3391:                    ref($oldsettingtext) eq 'HASH' &&
 3392:                    ref($newsetting) eq 'HASH' &&
 3393:                    ref($newsettingtext) eq 'HASH');
 3394:     my %lt=&Apache::lonlocal::texthash(
 3395:          'ui'             => 'User Information',
 3396:          'uic'            => 'User Information Changed',
 3397:          'firstname'      => 'First Name',
 3398:          'middlename'     => 'Middle Name',
 3399:          'lastname'       => 'Last Name',
 3400:          'generation'     => 'Generation',
 3401:          'id'             => 'Student/Employee ID',
 3402:          'permanentemail' => 'Permanent e-mail address',
 3403:          'portfolioquota' => 'Disk space allocated to portfolio files',
 3404:          'authorquota'    => 'Disk space allocated to Authoring Space',
 3405:          'blog'           => 'Blog Availability',
 3406:          'webdav'         => 'WebDAV Availability',
 3407:          'aboutme'        => 'Personal Information Page Availability',
 3408:          'portfolio'      => 'Portfolio Availability',
 3409:          'official'       => 'Can Request Official Courses',
 3410:          'unofficial'     => 'Can Request Unofficial Courses',
 3411:          'community'      => 'Can Request Communities',
 3412:          'textbook'       => 'Can Request Textbook Courses',
 3413:          'placement'      => 'Can Request Placement Tests',
 3414:          'requestauthor'  => 'Can Request Author Role',
 3415:          'inststatus'     => "Affiliation",
 3416:          'prvs'           => 'Previous Value:',
 3417:          'chto'           => 'Changed To:'
 3418:     );
 3419:     if ($changed) {
 3420:         $r->print('<h3>'.$lt{'uic'}.'</h3>'.
 3421:                 &Apache::loncommon::start_data_table().
 3422:                 &Apache::loncommon::start_data_table_header_row());
 3423:         $r->print("<th>&nbsp;</th>\n");
 3424:         $r->print('<th><b>'.$lt{'prvs'}.'</b></th>');
 3425:         $r->print('<th><span class="LC_nobreak"><b>'.$lt{'chto'}.'</b></span></th>');
 3426:         $r->print(&Apache::loncommon::end_data_table_header_row());
 3427:         my @userinfo = ('firstname','middlename','lastname','generation','permanentemail','id');
 3428: 
 3429:         foreach my $item (@userinfo) {
 3430:             my $value = $env{'form.c'.$item};
 3431:             #show changes only:
 3432:             unless ($value eq $userenv->{$item}){
 3433:                 $r->print(&Apache::loncommon::start_data_table_row());
 3434:                 $r->print("<td>$lt{$item}</td>\n");
 3435:                 $r->print("<td>".$userenv->{$item}."</td>\n");
 3436:                 $r->print("<td>$value </td>\n");
 3437:                 $r->print(&Apache::loncommon::end_data_table_row());
 3438:             }
 3439:         }
 3440:         foreach my $entry (@{$order}) {
 3441:             if ($canshow->{$entry}) {
 3442:                 if (($entry eq 'requestcourses') || ($entry eq 'reqcrsotherdom') || ($entry eq 'requestauthor')) {
 3443:                     my @items;
 3444:                     if ($entry eq 'requestauthor') {
 3445:                         @items = ($entry);
 3446:                     } else {
 3447:                         @items = @{$requestcourses};
 3448:                     }
 3449:                     foreach my $item (@items) {
 3450:                         if (($newsetting->{$item} ne $oldsetting->{$item}) || 
 3451:                             ($newsettingtext->{$item} ne $oldsettingtext->{$item})) {
 3452:                             $r->print(&Apache::loncommon::start_data_table_row()."\n");  
 3453:                             $r->print("<td>$lt{$item}</td>\n");
 3454:                             $r->print("<td>".$oldsetting->{$item});
 3455:                             if ($oldsettingtext->{$item}) {
 3456:                                 if ($oldsetting->{$item}) {
 3457:                                     $r->print(' -- ');
 3458:                                 }
 3459:                                 $r->print($oldsettingtext->{$item});
 3460:                             }
 3461:                             $r->print("</td>\n");
 3462:                             $r->print("<td>".$newsetting->{$item});
 3463:                             if ($newsettingtext->{$item}) {
 3464:                                 if ($newsetting->{$item}) {
 3465:                                     $r->print(' -- ');
 3466:                                 }
 3467:                                 $r->print($newsettingtext->{$item});
 3468:                             }
 3469:                             $r->print("</td>\n");
 3470:                             $r->print(&Apache::loncommon::end_data_table_row()."\n");
 3471:                         }
 3472:                     }
 3473:                 } elsif ($entry eq 'tools') {
 3474:                     foreach my $item (@{$usertools}) {
 3475:                         if ($newsetting->{$item} ne $oldsetting->{$item}) {
 3476:                             $r->print(&Apache::loncommon::start_data_table_row()."\n");
 3477:                             $r->print("<td>$lt{$item}</td>\n");
 3478:                             $r->print("<td>".$oldsetting->{$item}.' '.$oldsettingtext->{$item}."</td>\n");
 3479:                             $r->print("<td>".$newsetting->{$item}.' '.$newsettingtext->{$item}."</td>\n");
 3480:                             $r->print(&Apache::loncommon::end_data_table_row()."\n");
 3481:                         }
 3482:                     }
 3483:                 } elsif ($entry eq 'quota') {
 3484:                     if ((ref($oldsetting->{$entry}) eq 'HASH') && (ref($oldsettingtext->{$entry}) eq 'HASH') &&
 3485:                         (ref($newsetting->{$entry}) eq 'HASH') && (ref($newsettingtext->{$entry}) eq 'HASH')) {
 3486:                         foreach my $name ('portfolio','author') {
 3487:                             if ($newsetting->{$entry}->{$name} ne $oldsetting->{$entry}->{$name}) {
 3488:                                 $r->print(&Apache::loncommon::start_data_table_row()."\n");
 3489:                                 $r->print("<td>$lt{$name.$entry}</td>\n");
 3490:                                 $r->print("<td>".$oldsettingtext->{$entry}->{$name}."</td>\n");
 3491:                                 $r->print("<td>".$newsettingtext->{$entry}->{$name}."</td>\n");
 3492:                                 $r->print(&Apache::loncommon::end_data_table_row()."\n");
 3493:                             }
 3494:                         }
 3495:                     }
 3496:                 } else {
 3497:                     if ($newsetting->{$entry} ne $oldsetting->{$entry}) {
 3498:                         $r->print(&Apache::loncommon::start_data_table_row()."\n");
 3499:                         $r->print("<td>$lt{$entry}</td>\n");
 3500:                         $r->print("<td>".$oldsetting->{$entry}.' '.$oldsettingtext->{$entry}."</td>\n");
 3501:                         $r->print("<td>".$newsetting->{$entry}.' '.$newsettingtext->{$entry}."</td>\n");
 3502:                         $r->print(&Apache::loncommon::end_data_table_row()."\n");
 3503:                     }
 3504:                 }
 3505:             }
 3506:         }
 3507:         $r->print(&Apache::loncommon::end_data_table().'<br />');
 3508:     } else {
 3509:         $r->print('<h3>'.$lt{'ui'}.'</h3>'.
 3510:                   '<p>'.&mt('No changes made to user information').'</p>');
 3511:     }
 3512:     return;
 3513: }
 3514: 
 3515: sub tool_changes {
 3516:     my ($context,$usertools,$oldaccess,$oldaccesstext,$userenv,$changeHash,
 3517:         $changed,$newaccess,$newaccesstext) = @_;
 3518:     if (!((ref($usertools) eq 'ARRAY') && (ref($oldaccess) eq 'HASH') &&
 3519:           (ref($oldaccesstext) eq 'HASH') && (ref($userenv) eq 'HASH') &&
 3520:           (ref($changeHash) eq 'HASH') && (ref($changed) eq 'HASH') &&
 3521:           (ref($newaccess) eq 'HASH') && (ref($newaccesstext) eq 'HASH'))) {
 3522:         return;
 3523:     }
 3524:     my %reqdisplay = &requestchange_display();
 3525:     if ($context eq 'reqcrsotherdom') {
 3526:         my @options = ('approval','validate','autolimit');
 3527:         my $optregex = join('|',@options);
 3528:         my $cdom = $env{'request.role.domain'};
 3529:         foreach my $tool (@{$usertools}) {
 3530:             $oldaccesstext->{$tool} = &mt("availability set to 'off'");
 3531:             $newaccesstext->{$tool} = $oldaccesstext->{$tool};
 3532:             $changeHash->{$context.'.'.$tool} = $userenv->{$context.'.'.$tool};
 3533:             my ($newop,$limit);
 3534:             if ($env{'form.'.$context.'_'.$tool}) {
 3535:                 $newop = $env{'form.'.$context.'_'.$tool};
 3536:                 if ($newop eq 'autolimit') {
 3537:                     $limit = $env{'form.'.$context.'_'.$tool.'_limit'};
 3538:                     $limit =~ s/\D+//g;
 3539:                     $newop .= '='.$limit;
 3540:                 }
 3541:             }
 3542:             if ($userenv->{$context.'.'.$tool} eq '') {
 3543:                 if ($newop) {
 3544:                     $changed->{$tool}=&tool_admin($tool,$cdom.':'.$newop,
 3545:                                                   $changeHash,$context);
 3546:                     if ($changed->{$tool}) {
 3547:                         if ($newop =~ /^autolimit/) {
 3548:                             if ($limit) {
 3549:                                 $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3550:                             } else {
 3551:                                 $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3552:                             }
 3553:                         } else {
 3554:                             $newaccesstext->{$tool} = $reqdisplay{$newop};
 3555:                         }
 3556:                     } else {
 3557:                         $newaccesstext->{$tool} = $oldaccesstext->{$tool};
 3558:                     }
 3559:                 }
 3560:             } else {
 3561:                 my @curr = split(',',$userenv->{$context.'.'.$tool});
 3562:                 my @new;
 3563:                 my $changedoms;
 3564:                 foreach my $req (@curr) {
 3565:                     if ($req =~ /^\Q$cdom\E\:($optregex\=?\d*)$/) {
 3566:                         my $oldop = $1;
 3567:                         if ($oldop =~ /^autolimit=(\d*)/) {
 3568:                             my $limit = $1;
 3569:                             if ($limit) {
 3570:                                 $oldaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3571:                             } else {
 3572:                                 $oldaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3573:                             }
 3574:                         } else {
 3575:                             $oldaccesstext->{$tool} = $reqdisplay{$oldop};
 3576:                         }
 3577:                         if ($oldop ne $newop) {
 3578:                             $changedoms = 1;
 3579:                             foreach my $item (@curr) {
 3580:                                 my ($reqdom,$option) = split(':',$item);
 3581:                                 unless ($reqdom eq $cdom) {
 3582:                                     push(@new,$item);
 3583:                                 }
 3584:                             }
 3585:                             if ($newop) {
 3586:                                 push(@new,$cdom.':'.$newop);
 3587:                             }
 3588:                             @new = sort(@new);
 3589:                         }
 3590:                         last;
 3591:                     }
 3592:                 }
 3593:                 if ((!$changedoms) && ($newop)) {
 3594:                     $changedoms = 1;
 3595:                     @new = sort(@curr,$cdom.':'.$newop);
 3596:                 }
 3597:                 if ($changedoms) {
 3598:                     my $newdomstr;
 3599:                     if (@new) {
 3600:                         $newdomstr = join(',',@new);
 3601:                     }
 3602:                     $changed->{$tool}=&tool_admin($tool,$newdomstr,$changeHash,
 3603:                                                   $context);
 3604:                     if ($changed->{$tool}) {
 3605:                         if ($env{'form.'.$context.'_'.$tool}) {
 3606:                             if ($env{'form.'.$context.'_'.$tool} eq 'autolimit') {
 3607:                                 my $limit = $env{'form.'.$context.'_'.$tool.'_limit'};
 3608:                                 $limit =~ s/\D+//g;
 3609:                                 if ($limit) {
 3610:                                     $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3611:                                 } else {
 3612:                                     $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3613:                                 }
 3614:                             } else {
 3615:                                 $newaccesstext->{$tool} = $reqdisplay{$env{'form.'.$context.'_'.$tool}};
 3616:                             }
 3617:                         } else {
 3618:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3619:                         }
 3620:                     }
 3621:                 }
 3622:             }
 3623:         }
 3624:         return;
 3625:     }
 3626:     foreach my $tool (@{$usertools}) {
 3627:         my ($newval,$limit,$envkey);
 3628:         $envkey = $context.'.'.$tool;
 3629:         if ($context eq 'requestcourses') {
 3630:             $newval = $env{'form.crsreq_'.$tool};
 3631:             if ($newval eq 'autolimit') {
 3632:                 $limit = $env{'form.crsreq_'.$tool.'_limit'};
 3633:                 $limit =~ s/\D+//g;
 3634:                 $newval .= '='.$limit;
 3635:             }
 3636:         } elsif ($context eq 'requestauthor') {
 3637:             $newval = $env{'form.'.$context};
 3638:             $envkey = $context;
 3639:         } else {
 3640:             $newval = $env{'form.'.$context.'_'.$tool};
 3641:         }
 3642:         if ($userenv->{$envkey} ne '') {
 3643:             $oldaccess->{$tool} = &mt('custom');
 3644:             if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 3645:                 if ($userenv->{$envkey} =~ /^autolimit=(\d*)$/) {
 3646:                     my $currlimit = $1;
 3647:                     if ($currlimit eq '') {
 3648:                         $oldaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3649:                     } else {
 3650:                         $oldaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$currlimit);
 3651:                     }
 3652:                 } elsif ($userenv->{$envkey}) {
 3653:                     $oldaccesstext->{$tool} = $reqdisplay{$userenv->{$envkey}};
 3654:                 } else {
 3655:                     $oldaccesstext->{$tool} = &mt("availability set to 'off'");
 3656:                 }
 3657:             } else {
 3658:                 if ($userenv->{$envkey}) {
 3659:                     $oldaccesstext->{$tool} = &mt("availability set to 'on'");
 3660:                 } else {
 3661:                     $oldaccesstext->{$tool} = &mt("availability set to 'off'");
 3662:                 }
 3663:             }
 3664:             $changeHash->{$envkey} = $userenv->{$envkey};
 3665:             if ($env{'form.custom'.$tool} == 1) {
 3666:                 if ($newval ne $userenv->{$envkey}) {
 3667:                     $changed->{$tool} = &tool_admin($tool,$newval,$changeHash,
 3668:                                                     $context);
 3669:                     if ($changed->{$tool}) {
 3670:                         $newaccess->{$tool} = &mt('custom');
 3671:                         if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 3672:                             if ($newval =~ /^autolimit/) {
 3673:                                 if ($limit) {
 3674:                                     $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3675:                                 } else {
 3676:                                     $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3677:                                 }
 3678:                             } elsif ($newval) {
 3679:                                 $newaccesstext->{$tool} = $reqdisplay{$newval};
 3680:                             } else {
 3681:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3682:                             }
 3683:                         } else {
 3684:                             if ($newval) {
 3685:                                 $newaccesstext->{$tool} = &mt("availability set to 'on'");
 3686:                             } else {
 3687:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3688:                             }
 3689:                         }
 3690:                     } else {
 3691:                         $newaccess->{$tool} = $oldaccess->{$tool};
 3692:                         if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 3693:                             if ($newval =~ /^autolimit/) {
 3694:                                 if ($limit) {
 3695:                                     $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3696:                                 } else {
 3697:                                     $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3698:                                 }
 3699:                             } elsif ($newval) {
 3700:                                 $newaccesstext->{$tool} = $reqdisplay{$newval};
 3701:                             } else {
 3702:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3703:                             }
 3704:                         } else {
 3705:                             if ($userenv->{$context.'.'.$tool}) {
 3706:                                 $newaccesstext->{$tool} = &mt("availability set to 'on'");
 3707:                             } else {
 3708:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3709:                             }
 3710:                         }
 3711:                     }
 3712:                 } else {
 3713:                     $newaccess->{$tool} = $oldaccess->{$tool};
 3714:                     $newaccesstext->{$tool} = $oldaccesstext->{$tool};
 3715:                 }
 3716:             } else {
 3717:                 $changed->{$tool} = &tool_admin($tool,'',$changeHash,$context);
 3718:                 if ($changed->{$tool}) {
 3719:                     $newaccess->{$tool} = &mt('default');
 3720:                 } else {
 3721:                     $newaccess->{$tool} = $oldaccess->{$tool};
 3722:                     if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 3723:                         if ($newval =~ /^autolimit/) {
 3724:                             if ($limit) {
 3725:                                 $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3726:                             } else {
 3727:                                 $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3728:                             }
 3729:                         } elsif ($newval) {
 3730:                             $newaccesstext->{$tool} = $reqdisplay{$newval};
 3731:                         } else {
 3732:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3733:                         }
 3734:                     } else {
 3735:                         if ($userenv->{$context.'.'.$tool}) {
 3736:                             $newaccesstext->{$tool} = &mt("availability set to 'on'");
 3737:                         } else {
 3738:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3739:                         }
 3740:                     }
 3741:                 }
 3742:             }
 3743:         } else {
 3744:             $oldaccess->{$tool} = &mt('default');
 3745:             if ($env{'form.custom'.$tool} == 1) {
 3746:                 $changed->{$tool} = &tool_admin($tool,$newval,$changeHash,
 3747:                                                 $context);
 3748:                 if ($changed->{$tool}) {
 3749:                     $newaccess->{$tool} = &mt('custom');
 3750:                     if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 3751:                         if ($newval =~ /^autolimit/) {
 3752:                             if ($limit) {
 3753:                                 $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3754:                             } else {
 3755:                                 $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3756:                             }
 3757:                         } elsif ($newval) {
 3758:                             $newaccesstext->{$tool} = $reqdisplay{$newval};
 3759:                         } else {
 3760:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3761:                         }
 3762:                     } else {
 3763:                         if ($newval) {
 3764:                             $newaccesstext->{$tool} = &mt("availability set to 'on'");
 3765:                         } else {
 3766:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3767:                         }
 3768:                     }
 3769:                 } else {
 3770:                     $newaccess->{$tool} = $oldaccess->{$tool};
 3771:                 }
 3772:             } else {
 3773:                 $newaccess->{$tool} = $oldaccess->{$tool};
 3774:             }
 3775:         }
 3776:     }
 3777:     return;
 3778: }
 3779: 
 3780: sub update_roles {
 3781:     my ($r,$context,$showcredits) = @_;
 3782:     my $now=time;
 3783:     my @rolechanges;
 3784:     my %disallowed;
 3785:     $r->print('<h3>'.&mt('Modifying Roles').'</h3>');
 3786:     foreach my $key (keys(%env)) {
 3787: 	next if (! $env{$key});
 3788:         next if ($key eq 'form.action');
 3789: 	# Revoke roles
 3790: 	if ($key=~/^form\.rev/) {
 3791: 	    if ($key=~/^form\.rev\:([^\_]+)\_([^\_\.]+)$/) {
 3792: # Revoke standard role
 3793: 		my ($scope,$role) = ($1,$2);
 3794: 		my $result =
 3795: 		    &Apache::lonnet::revokerole($env{'form.ccdomain'},
 3796: 						$env{'form.ccuname'},
 3797: 						$scope,$role,'','',$context);
 3798:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
 3799:                             &mt('Revoking [_1] in [_2]',
 3800:                                 &Apache::lonnet::plaintext($role),
 3801:                                 &Apache::loncommon::show_role_extent($scope,$context,$role)),
 3802:                                 $result ne "ok").'<br />');
 3803:                 if ($result ne "ok") {
 3804:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 3805:                 }
 3806: 		if ($role eq 'st') {
 3807: 		    my $result = 
 3808:                         &Apache::lonuserutils::classlist_drop($scope,
 3809:                             $env{'form.ccuname'},$env{'form.ccdomain'},
 3810: 			    $now);
 3811:                     $r->print(&Apache::lonhtmlcommon::confirm_success($result));
 3812: 		}
 3813:                 if (!grep(/^\Q$role\E$/,@rolechanges)) {
 3814:                     push(@rolechanges,$role);
 3815:                 }
 3816: 	    }
 3817: 	    if ($key=~m{^form\.rev\:([^_]+)_cr\.cr/($match_domain)/($match_username)/(\w+)$}s) {
 3818: # Revoke custom role
 3819:                 my $result = &Apache::lonnet::revokecustomrole(
 3820:                     $env{'form.ccdomain'},$env{'form.ccuname'},$1,$2,$3,$4,'','',$context);
 3821:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
 3822:                             &mt('Revoking custom role [_1] by [_2] in [_3]',
 3823:                                 $4,$3.':'.$2,&Apache::loncommon::show_role_extent($1,$context,'cr')),
 3824:                             $result ne 'ok').'<br />');
 3825:                 if ($result ne "ok") {
 3826:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 3827:                 }
 3828:                 if (!grep(/^cr$/,@rolechanges)) {
 3829:                     push(@rolechanges,'cr');
 3830:                 }
 3831: 	    }
 3832: 	} elsif ($key=~/^form\.del/) {
 3833: 	    if ($key=~/^form\.del\:([^\_]+)\_([^\_\.]+)$/) {
 3834: # Delete standard role
 3835: 		my ($scope,$role) = ($1,$2);
 3836: 		my $result =
 3837: 		    &Apache::lonnet::assignrole($env{'form.ccdomain'},
 3838: 						$env{'form.ccuname'},
 3839: 						$scope,$role,$now,0,1,'',
 3840:                                                 $context);
 3841:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
 3842:                             &mt('Deleting [_1] in [_2]',
 3843:                                 &Apache::lonnet::plaintext($role),
 3844:                                 &Apache::loncommon::show_role_extent($scope,$context,$role)),
 3845:                             $result ne 'ok').'<br />');
 3846:                 if ($result ne "ok") {
 3847:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 3848:                 }
 3849: 
 3850: 		if ($role eq 'st') {
 3851: 		    my $result = 
 3852:                         &Apache::lonuserutils::classlist_drop($scope,
 3853:                             $env{'form.ccuname'},$env{'form.ccdomain'},
 3854: 			    $now);
 3855: 		    $r->print(&Apache::lonhtmlcommon::confirm_success($result));
 3856: 		}
 3857:                 if (!grep(/^\Q$role\E$/,@rolechanges)) {
 3858:                     push(@rolechanges,$role);
 3859:                 }
 3860:             }
 3861: 	    if ($key=~m{^form\.del\:([^_]+)_cr\.cr/($match_domain)/($match_username)/(\w+)$}) {
 3862:                 my ($url,$rdom,$rnam,$rolename) = ($1,$2,$3,$4);
 3863: # Delete custom role
 3864:                 my $result =
 3865:                     &Apache::lonnet::assigncustomrole($env{'form.ccdomain'},
 3866:                         $env{'form.ccuname'},$url,$rdom,$rnam,$rolename,$now,
 3867:                         0,1,$context);
 3868:                 $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('Deleting custom role [_1] by [_2] in [_3]',
 3869:                       $rolename,$rnam.':'.$rdom,&Apache::loncommon::show_role_extent($1,$context,'cr')),
 3870:                       $result ne "ok").'<br />');
 3871:                 if ($result ne "ok") {
 3872:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 3873:                 }
 3874: 
 3875:                 if (!grep(/^cr$/,@rolechanges)) {
 3876:                     push(@rolechanges,'cr');
 3877:                 }
 3878:             }
 3879: 	} elsif ($key=~/^form\.ren/) {
 3880:             my $udom = $env{'form.ccdomain'};
 3881:             my $uname = $env{'form.ccuname'};
 3882: # Re-enable standard role
 3883: 	    if ($key=~/^form\.ren\:([^\_]+)\_([^\_\.]+)$/) {
 3884:                 my $url = $1;
 3885:                 my $role = $2;
 3886:                 my $logmsg;
 3887:                 my $output;
 3888:                 if ($role eq 'st') {
 3889:                     if ($url =~ m-^/($match_domain)/($match_courseid)/?(\w*)$-) {
 3890:                         my ($cdom,$cnum,$csec) = ($1,$2,$3);
 3891:                         my $credits;
 3892:                         if ($showcredits) {
 3893:                             my $defaultcredits = 
 3894:                                 &Apache::lonuserutils::get_defaultcredits($cdom,$cnum);
 3895:                             $credits = &get_user_credits($defaultcredits,$cdom,$cnum);
 3896:                         }
 3897:                         my $result = &Apache::loncommon::commit_studentrole(\$logmsg,$udom,$uname,$url,$role,$now,0,$cdom,$cnum,$csec,$context,$credits);
 3898:                         if (($result =~ /^error/) || ($result eq 'not_in_class') || ($result eq 'unknown_course') || ($result eq 'refused')) {
 3899:                             if ($result eq 'refused' && $logmsg) {
 3900:                                 $output = $logmsg;
 3901:                             } else { 
 3902:                                 $output = &mt('Error: [_1]',$result)."\n";
 3903:                             }
 3904:                         } else {
 3905:                             $output = &Apache::lonhtmlcommon::confirm_success(&mt('Assigning [_1] in [_2] starting [_3]',
 3906:                                         &Apache::lonnet::plaintext($role),
 3907:                                         &Apache::loncommon::show_role_extent($url,$context,'st'),
 3908:                                         &Apache::lonlocal::locallocaltime($now))).'<br />'.$logmsg.'<br />';
 3909:                         }
 3910:                     }
 3911:                 } else {
 3912: 		    my $result=&Apache::lonnet::assignrole($env{'form.ccdomain'},
 3913:                                $env{'form.ccuname'},$url,$role,0,$now,'','',
 3914:                                $context);
 3915:                         $output = &Apache::lonhtmlcommon::confirm_success(&mt('Re-enabling [_1] in [_2]',
 3916:                                         &Apache::lonnet::plaintext($role),
 3917:                                         &Apache::loncommon::show_role_extent($url,$context,$role)),$result ne "ok").'<br />';
 3918:                     if ($result ne "ok") {
 3919:                         $output .= &mt('Error: [_1]',$result).'<br />';
 3920:                     }
 3921:                 }
 3922:                 $r->print($output);
 3923:                 if (!grep(/^\Q$role\E$/,@rolechanges)) {
 3924:                     push(@rolechanges,$role);
 3925:                 }
 3926: 	    }
 3927: # Re-enable custom role
 3928: 	    if ($key=~m{^form\.ren\:([^_]+)_cr\.cr/($match_domain)/($match_username)/(\w+)$}) {
 3929:                 my ($url,$rdom,$rnam,$rolename) = ($1,$2,$3,$4);
 3930:                 my $result = &Apache::lonnet::assigncustomrole(
 3931:                                $env{'form.ccdomain'}, $env{'form.ccuname'},
 3932:                                $url,$rdom,$rnam,$rolename,0,$now,undef,$context);
 3933:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
 3934:                     &mt('Re-enabling custom role [_1] by [_2] in [_3]',
 3935:                         $rolename,$rnam.':'.$rdom,&Apache::loncommon::show_role_extent($1,$context,'cr')),
 3936:                     $result ne "ok").'<br />');
 3937:                 if ($result ne "ok") {
 3938:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 3939:                 }
 3940:                 if (!grep(/^cr$/,@rolechanges)) {
 3941:                     push(@rolechanges,'cr');
 3942:                 }
 3943:             }
 3944: 	} elsif ($key=~/^form\.act/) {
 3945:             my $udom = $env{'form.ccdomain'};
 3946:             my $uname = $env{'form.ccuname'};
 3947: 	    if ($key=~/^form\.act\_($match_domain)\_($match_courseid)\_cr_cr_($match_domain)_($match_username)_([^\_]+)$/) {
 3948:                 # Activate a custom role
 3949: 		my ($one,$two,$three,$four,$five)=($1,$2,$3,$4,$5);
 3950: 		my $url='/'.$one.'/'.$two;
 3951: 		my $full=$one.'_'.$two.'_cr_cr_'.$three.'_'.$four.'_'.$five;
 3952: 
 3953:                 my $start = ( $env{'form.start_'.$full} ?
 3954:                               $env{'form.start_'.$full} :
 3955:                               $now );
 3956:                 my $end   = ( $env{'form.end_'.$full} ?
 3957:                               $env{'form.end_'.$full} :
 3958:                               0 );
 3959:                                                                                      
 3960:                 # split multiple sections
 3961:                 my %sections = ();
 3962:                 my $num_sections = &build_roles($env{'form.sec_'.$full},\%sections,$5);
 3963:                 if ($num_sections == 0) {
 3964:                     $r->print(&Apache::loncommon::commit_customrole($udom,$uname,$url,$three,$four,$five,$start,$end,$context));
 3965:                 } else {
 3966: 		    my %curr_groups =
 3967: 			&Apache::longroup::coursegroups($one,$two);
 3968:                     foreach my $sec (sort {$a cmp $b} keys(%sections)) {
 3969:                         if (($sec eq 'none') || ($sec eq 'all') || 
 3970:                             exists($curr_groups{$sec})) {
 3971:                             $disallowed{$sec} = $url;
 3972:                             next;
 3973:                         }
 3974:                         my $securl = $url.'/'.$sec;
 3975: 		        $r->print(&Apache::loncommon::commit_customrole($udom,$uname,$securl,$three,$four,$five,$start,$end,$context));
 3976:                     }
 3977:                 }
 3978:                 if (!grep(/^cr$/,@rolechanges)) {
 3979:                     push(@rolechanges,'cr');
 3980:                 }
 3981: 	    } elsif ($key=~/^form\.act\_($match_domain)\_($match_name)\_([^\_]+)$/) {
 3982: 		# Activate roles for sections with 3 id numbers
 3983: 		# set start, end times, and the url for the class
 3984: 		my ($one,$two,$three)=($1,$2,$3);
 3985: 		my $start = ( $env{'form.start_'.$one.'_'.$two.'_'.$three} ? 
 3986: 			      $env{'form.start_'.$one.'_'.$two.'_'.$three} : 
 3987: 			      $now );
 3988: 		my $end   = ( $env{'form.end_'.$one.'_'.$two.'_'.$three} ? 
 3989: 			      $env{'form.end_'.$one.'_'.$two.'_'.$three} :
 3990: 			      0 );
 3991: 		my $url='/'.$one.'/'.$two;
 3992:                 my $type = 'three';
 3993:                 # split multiple sections
 3994:                 my %sections = ();
 3995:                 my $num_sections = &build_roles($env{'form.sec_'.$one.'_'.$two.'_'.$three},\%sections,$three);
 3996:                 my $credits;
 3997:                 if ($three eq 'st') {
 3998:                     if ($showcredits) { 
 3999:                         my $defaultcredits = 
 4000:                             &Apache::lonuserutils::get_defaultcredits($one,$two);
 4001:                         $credits = $env{'form.credits_'.$one.'_'.$two.'_'.$three};
 4002:                         $credits =~ s/[^\d\.]//g;
 4003:                         if ($credits eq $defaultcredits) {
 4004:                             undef($credits);
 4005:                         }
 4006:                     }
 4007:                 }
 4008:                 if ($num_sections == 0) {
 4009:                     $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$three,$start,$end,$one,$two,'',$context,$credits));
 4010:                 } else {
 4011:                     my %curr_groups = 
 4012: 			&Apache::longroup::coursegroups($one,$two);
 4013:                     my $emptysec = 0;
 4014:                     foreach my $sec (sort {$a cmp $b} keys(%sections)) {
 4015:                         $sec =~ s/\W//g;
 4016:                         if ($sec ne '') {
 4017:                             if (($sec eq 'none') || ($sec eq 'all') || 
 4018:                                 exists($curr_groups{$sec})) {
 4019:                                 $disallowed{$sec} = $url;
 4020:                                 next;
 4021:                             }
 4022:                             my $securl = $url.'/'.$sec;
 4023:                             $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$securl,$three,$start,$end,$one,$two,$sec,$context,$credits));
 4024:                         } else {
 4025:                             $emptysec = 1;
 4026:                         }
 4027:                     }
 4028:                     if ($emptysec) {
 4029:                         $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$three,$start,$end,$one,$two,'',$context,$credits));
 4030:                     }
 4031:                 }
 4032:                 if (!grep(/^\Q$three\E$/,@rolechanges)) {
 4033:                     push(@rolechanges,$three);
 4034:                 }
 4035: 	    } elsif ($key=~/^form\.act\_([^\_]+)\_([^\_]+)$/) {
 4036: 		# Activate roles for sections with two id numbers
 4037: 		# set start, end times, and the url for the class
 4038: 		my $start = ( $env{'form.start_'.$1.'_'.$2} ? 
 4039: 			      $env{'form.start_'.$1.'_'.$2} : 
 4040: 			      $now );
 4041: 		my $end   = ( $env{'form.end_'.$1.'_'.$2} ? 
 4042: 			      $env{'form.end_'.$1.'_'.$2} :
 4043: 			      0 );
 4044:                 my $one = $1;
 4045:                 my $two = $2;
 4046: 		my $url='/'.$one.'/';
 4047:                 # split multiple sections
 4048:                 my %sections = ();
 4049:                 my $num_sections = &build_roles($env{'form.sec_'.$one.'_'.$two},\%sections,$two);
 4050:                 if ($num_sections == 0) {
 4051:                     $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$two,$start,$end,$one,undef,'',$context));
 4052:                 } else {
 4053:                     my $emptysec = 0;
 4054:                     foreach my $sec (sort {$a cmp $b} keys(%sections)) {
 4055:                         if ($sec ne '') {
 4056:                             my $securl = $url.'/'.$sec;
 4057:                             $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$securl,$two,$start,$end,$one,undef,$sec,$context));
 4058:                         } else {
 4059:                             $emptysec = 1;
 4060:                         }
 4061:                     }
 4062:                     if ($emptysec) {
 4063:                         $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$two,$start,$end,$one,undef,'',$context));
 4064:                     }
 4065:                 }
 4066:                 if (!grep(/^\Q$two\E$/,@rolechanges)) {
 4067:                     push(@rolechanges,$two);
 4068:                 }
 4069: 	    } else {
 4070: 		$r->print('<p><span class="LC_error">'.&mt('ERROR').': '.&mt('Unknown command').' <tt>'.$key.'</tt></span></p><br />');
 4071:             }
 4072:             foreach my $key (sort(keys(%disallowed))) {
 4073:                 $r->print('<p class="LC_warning">');
 4074:                 if (($key eq 'none') || ($key eq 'all')) {  
 4075:                     $r->print(&mt('[_1] may not be used as the name for a section, as it is a reserved word.','<tt>'.$key.'</tt>'));
 4076:                 } else {
 4077:                     $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>'));
 4078:                 }
 4079:                 $r->print('</p><p>'
 4080:                          .&mt('Please [_1]go back[_2] and choose a different section name.'
 4081:                              ,'<a href="javascript:history.go(-1)'
 4082:                              ,'</a>')
 4083:                          .'</p><br />'
 4084:                 );
 4085:             }
 4086: 	}
 4087:     } # End of foreach (keys(%env))
 4088: # Flush the course logs so reverse user roles immediately updated
 4089:     $r->register_cleanup(\&Apache::lonnet::flushcourselogs);
 4090:     if (@rolechanges == 0) {
 4091:         $r->print('<p>'.&mt('No roles to modify').'</p>');
 4092:     }
 4093:     return @rolechanges;
 4094: }
 4095: 
 4096: sub get_user_credits {
 4097:     my ($uname,$udom,$defaultcredits,$cdom,$cnum) = @_;
 4098:     if ($cdom eq '' || $cnum eq '') {
 4099:         return unless ($env{'request.course.id'});
 4100:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4101:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4102:     }
 4103:     my $credits;
 4104:     my %currhash =
 4105:         &Apache::lonnet::get('classlist',[$uname.':'.$udom],$cdom,$cnum);
 4106:     if (keys(%currhash) > 0) {
 4107:         my @items = split(/:/,$currhash{$uname.':'.$udom});
 4108:         my $crdidx = &Apache::loncoursedata::CL_CREDITS() - 3;
 4109:         $credits = $items[$crdidx];
 4110:         $credits =~ s/[^\d\.]//g;
 4111:     }
 4112:     if ($credits eq $defaultcredits) {
 4113:         undef($credits);
 4114:     }
 4115:     return $credits;
 4116: }
 4117: 
 4118: sub enroll_single_student {
 4119:     my ($r,$uhome,$amode,$genpwd,$now,$newuser,$context,$crstype,
 4120:         $showcredits,$defaultcredits) = @_;
 4121:     $r->print('<h3>');
 4122:     if ($crstype eq 'Community') {
 4123:         $r->print(&mt('Enrolling Member'));
 4124:     } else {
 4125:         $r->print(&mt('Enrolling Student'));
 4126:     }
 4127:     $r->print('</h3>');
 4128: 
 4129:     # Remove non alphanumeric values from section
 4130:     $env{'form.sections'}=~s/\W//g;
 4131: 
 4132:     my $credits;
 4133:     if (($showcredits) && ($env{'form.credits'} ne '')) {
 4134:         $credits = $env{'form.credits'};
 4135:         $credits =~ s/[^\d\.]//g;
 4136:         if ($credits ne '') {
 4137:             if ($credits eq $defaultcredits) {
 4138:                 undef($credits);
 4139:             }
 4140:         }
 4141:     }
 4142: 
 4143:     # Clean out any old student roles the user has in this class.
 4144:     &Apache::lonuserutils::modifystudent($env{'form.ccdomain'},
 4145:          $env{'form.ccuname'},$env{'request.course.id'},undef,$uhome);
 4146:     my ($startdate,$enddate) = &Apache::lonuserutils::get_dates_from_form();
 4147:     my $enroll_result =
 4148:         &Apache::lonnet::modify_student_enrollment($env{'form.ccdomain'},
 4149:             $env{'form.ccuname'},$env{'form.cid'},$env{'form.cfirstname'},
 4150:             $env{'form.cmiddlename'},$env{'form.clastname'},
 4151:             $env{'form.generation'},$env{'form.sections'},$enddate,
 4152:             $startdate,'manual',undef,$env{'request.course.id'},'',$context,
 4153:             $credits);
 4154:     if ($enroll_result =~ /^ok/) {
 4155:         $r->print(&mt('[_1] enrolled','<b>'.$env{'form.ccuname'}.':'.$env{'form.ccdomain'}.'</b>'));
 4156:         if ($env{'form.sections'} ne '') {
 4157:             $r->print(' '.&mt('in section [_1]',$env{'form.sections'}));
 4158:         }
 4159:         my ($showstart,$showend);
 4160:         if ($startdate <= $now) {
 4161:             $showstart = &mt('Access starts immediately');
 4162:         } else {
 4163:             $showstart = &mt('Access starts: ').&Apache::lonlocal::locallocaltime($startdate);
 4164:         }
 4165:         if ($enddate == 0) {
 4166:             $showend = &mt('ends: no ending date');
 4167:         } else {
 4168:             $showend = &mt('ends: ').&Apache::lonlocal::locallocaltime($enddate);
 4169:         }
 4170:         $r->print('.<br />'.$showstart.'; '.$showend);
 4171:         if ($startdate <= $now && !$newuser) {
 4172:             $r->print('<p class="LC_info">');
 4173:             if ($crstype eq 'Community') {
 4174:                 $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.'));
 4175:             } else {
 4176:                 $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.'));
 4177:            }
 4178:            $r->print('</p>');
 4179:         }
 4180:     } else {
 4181:         $r->print(&mt('unable to enroll').": ".$enroll_result);
 4182:     }
 4183:     return;
 4184: }
 4185: 
 4186: sub get_defaultquota_text {
 4187:     my ($settingstatus) = @_;
 4188:     my $defquotatext; 
 4189:     if ($settingstatus eq '') {
 4190:         $defquotatext = &mt('default');
 4191:     } else {
 4192:         my ($usertypes,$order) =
 4193:             &Apache::lonnet::retrieve_inst_usertypes($env{'form.ccdomain'});
 4194:         if ($usertypes->{$settingstatus} eq '') {
 4195:             $defquotatext = &mt('default');
 4196:         } else {
 4197:             $defquotatext = &mt('default for [_1]',$usertypes->{$settingstatus});
 4198:         }
 4199:     }
 4200:     return $defquotatext;
 4201: }
 4202: 
 4203: sub update_result_form {
 4204:     my ($uhome) = @_;
 4205:     my $outcome = 
 4206:     '<form name="userupdate" method="post" action="">'."\n";
 4207:     foreach my $item ('srchby','srchin','srchtype','srchterm','srchdomain','ccuname','ccdomain') {
 4208:         $outcome .= '<input type="hidden" name="'.$item.'" value="'.$env{'form.'.$item}.'" />'."\n";
 4209:     }
 4210:     if ($env{'form.origname'} ne '') {
 4211:         $outcome .= '<input type="hidden" name="origname" value="'.$env{'form.origname'}.'" />'."\n";
 4212:     }
 4213:     foreach my $item ('sortby','seluname','seludom') {
 4214:         if (exists($env{'form.'.$item})) {
 4215:             $outcome .= '<input type="hidden" name="'.$item.'" value="'.$env{'form.'.$item}.'" />'."\n";
 4216:         }
 4217:     }
 4218:     if ($uhome eq 'no_host') {
 4219:         $outcome .= '<input type="hidden" name="forcenewuser" value="1" />'."\n";
 4220:     }
 4221:     $outcome .= '<input type="hidden" name="phase" value="" />'."\n".
 4222:                 '<input type="hidden" name="currstate" value="" />'."\n".
 4223:                 '<input type="hidden" name="action" value="'.$env{'form.action'}.'" />'."\n".
 4224:                 '</form>';
 4225:     return $outcome;
 4226: }
 4227: 
 4228: sub quota_admin {
 4229:     my ($setquota,$changeHash,$name) = @_;
 4230:     my $quotachanged;
 4231:     if (&Apache::lonnet::allowed('mpq',$env{'form.ccdomain'})) {
 4232:         # Current user has quota modification privileges
 4233:         if (ref($changeHash) eq 'HASH') {
 4234:             $quotachanged = 1;
 4235:             $changeHash->{$name.'quota'} = $setquota;
 4236:         }
 4237:     }
 4238:     return $quotachanged;
 4239: }
 4240: 
 4241: sub tool_admin {
 4242:     my ($tool,$settool,$changeHash,$context) = @_;
 4243:     my $canchange = 0; 
 4244:     if ($context eq 'requestcourses') {
 4245:         if (&Apache::lonnet::allowed('ccc',$env{'form.ccdomain'})) {
 4246:             $canchange = 1;
 4247:         }
 4248:     } elsif ($context eq 'reqcrsotherdom') {
 4249:         if (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) {
 4250:             $canchange = 1;
 4251:         }
 4252:     } elsif ($context eq 'requestauthor') {
 4253:         if (&Apache::lonnet::allowed('cau',$env{'request.role.domain'})) {
 4254:             $canchange = 1;
 4255:         }
 4256:     } elsif (&Apache::lonnet::allowed('mut',$env{'form.ccdomain'})) {
 4257:         # Current user has quota modification privileges
 4258:         $canchange = 1;
 4259:     }
 4260:     my $toolchanged;
 4261:     if ($canchange) {
 4262:         if (ref($changeHash) eq 'HASH') {
 4263:             $toolchanged = 1;
 4264:             if ($tool eq 'requestauthor') {
 4265:                 $changeHash->{$context} = $settool;
 4266:             } else {
 4267:                 $changeHash->{$context.'.'.$tool} = $settool;
 4268:             }
 4269:         }
 4270:     }
 4271:     return $toolchanged;
 4272: }
 4273: 
 4274: sub build_roles {
 4275:     my ($sectionstr,$sections,$role) = @_;
 4276:     my $num_sections = 0;
 4277:     if ($sectionstr=~ /,/) {
 4278:         my @secnums = split/,/,$sectionstr;
 4279:         if ($role eq 'st') {
 4280:             $secnums[0] =~ s/\W//g;
 4281:             $$sections{$secnums[0]} = 1;
 4282:             $num_sections = 1;
 4283:         } else {
 4284:             foreach my $sec (@secnums) {
 4285:                 $sec =~ ~s/\W//g;
 4286:                 if (!($sec eq "")) {
 4287:                     if (exists($$sections{$sec})) {
 4288:                         $$sections{$sec} ++;
 4289:                     } else {
 4290:                         $$sections{$sec} = 1;
 4291:                         $num_sections ++;
 4292:                     }
 4293:                 }
 4294:             }
 4295:         }
 4296:     } else {
 4297:         $sectionstr=~s/\W//g;
 4298:         unless ($sectionstr eq '') {
 4299:             $$sections{$sectionstr} = 1;
 4300:             $num_sections ++;
 4301:         }
 4302:     }
 4303: 
 4304:     return $num_sections;
 4305: }
 4306: 
 4307: # ========================================================== Custom Role Editor
 4308: 
 4309: sub custom_role_editor {
 4310:     my ($r,$brcrum,$prefix) = @_;
 4311:     my $action = $env{'form.customroleaction'};
 4312:     my $rolename; 
 4313:     if ($action eq 'new') {
 4314:         $rolename=$env{'form.newrolename'};
 4315:     } else {
 4316:         $rolename=$env{'form.rolename'};
 4317:     }
 4318: 
 4319:     my ($crstype,$context);
 4320:     if ($env{'request.course.id'}) {
 4321:         $crstype = &Apache::loncommon::course_type();
 4322:         $context = 'course';
 4323:     } else {
 4324:         $context = 'domain';
 4325:         $crstype = 'course';
 4326:     }
 4327: 
 4328:     $rolename=~s/[^A-Za-z0-9]//gs;
 4329:     if (!$rolename || $env{'form.phase'} eq 'pickrole') {
 4330: 	&print_username_entry_form($r,undef,undef,undef,undef,$crstype,$brcrum);
 4331:         return;
 4332:     }
 4333: 
 4334:     my $formname = 'form1';
 4335:     my %privs=();
 4336:     my $body_top = '<h2>';
 4337: # ------------------------------------------------------- Does this role exist?
 4338:     my ($rdummy,$roledef)=
 4339: 			 &Apache::lonnet::get('roles',["rolesdef_$rolename"]);
 4340:     if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 4341:         $body_top .= &mt('Existing Role').' "';
 4342: # ------------------------------------------------- Get current role privileges
 4343:         ($privs{'system'},$privs{'domain'},$privs{'course'})=split(/\_/,$roledef);
 4344:         if ($privs{'system'} =~ /bre\&S/) {
 4345:             if ($context eq 'domain') {
 4346:                 $crstype = 'Course';
 4347:             } elsif ($crstype eq 'Community') {
 4348:                 $privs{'system'} =~ s/bre\&S//;
 4349:             }
 4350:         } elsif ($context eq 'domain') {
 4351:             $crstype = 'Course';
 4352:         }
 4353:     } else {
 4354:         $body_top .= &mt('New Role').' "';
 4355:         $roledef='';
 4356:     }
 4357:     $body_top .= $rolename.'"</h2>';
 4358: 
 4359: # ------------------------------------------------------- What can be assigned?
 4360:     my %full=();
 4361:     my %levels=(
 4362:                  course => {},
 4363:                  domain => {},
 4364:                  system => {},
 4365:                );
 4366:     my %levelscurrent=(
 4367:                         course => {},
 4368:                         domain => {},
 4369:                         system => {},
 4370:                       );
 4371:     &Apache::lonuserutils::custom_role_privs(\%privs,\%full,\%levels,\%levelscurrent);
 4372:     my ($jsback,$elements) = &crumb_utilities();
 4373:     my @templateroles = &Apache::lonuserutils::custom_template_roles($context,$crstype);
 4374:     my $head_script =
 4375:         &Apache::lonuserutils::custom_roledefs_js($context,$crstype,$formname,
 4376:                                                   \%full,\@templateroles,$jsback);
 4377:     push (@{$brcrum},
 4378:               {href => "javascript:backPage(document.$formname,'pickrole','')",
 4379:                text => "Pick custom role",
 4380:                faq  => 282,bug=>'Instructor Interface',},
 4381:               {href => "javascript:backPage(document.$formname,'','')",
 4382:                text => "Edit custom role",
 4383:                faq  => 282,
 4384:                bug  => 'Instructor Interface',
 4385:                help => 'Course_Editing_Custom_Roles'}
 4386:               );
 4387:     my $args = { bread_crumbs          => $brcrum,
 4388:                  bread_crumbs_component => 'User Management'};
 4389:     $r->print(&Apache::loncommon::start_page('Custom Role Editor',
 4390:                                              $head_script,$args).
 4391:               $body_top);
 4392:     $r->print('<form name="'.$formname.'" method="post" action="">'."\n".
 4393:               &Apache::lonuserutils::custom_role_header($context,$crstype,
 4394:                                                         \@templateroles,$prefix));
 4395: 
 4396:     $r->print(<<ENDCCF);
 4397: <input type="hidden" name="phase" value="set_custom_roles" />
 4398: <input type="hidden" name="rolename" value="$rolename" />
 4399: ENDCCF
 4400:     $r->print(&Apache::lonuserutils::custom_role_table($crstype,\%full,\%levels,
 4401:                                                        \%levelscurrent,$prefix));
 4402:     $r->print(&Apache::loncommon::end_data_table().
 4403:    '<input type="hidden" name="action" value="'.$env{'form.action'}.'" />'.
 4404:    '<input type="hidden" name="startrolename" value="'.$env{'form.rolename'}.
 4405:    '" />'."\n".'<input type="hidden" name="currstate" value="" />'."\n".
 4406:    '<input type="reset" value="'.&mt("Reset").'" />'."\n".
 4407:    '<input type="submit" value="'.&mt('Save').'" /></form>');
 4408: }
 4409: 
 4410: # ---------------------------------------------------------- Call to definerole
 4411: sub set_custom_role {
 4412:     my ($r,$context,$brcrum,$prefix) = @_;
 4413:     my $rolename=$env{'form.rolename'};
 4414:     $rolename=~s/[^A-Za-z0-9]//gs;
 4415:     if (!$rolename) {
 4416: 	&custom_role_editor($r,$brcrum,$prefix);
 4417:         return;
 4418:     }
 4419:     my ($jsback,$elements) = &crumb_utilities();
 4420:     my $jscript = '<script type="text/javascript">'
 4421:                  .'// <![CDATA['."\n"
 4422:                  .$jsback."\n"
 4423:                  .'// ]]>'."\n"
 4424:                  .'</script>'."\n";
 4425:     push(@{$brcrum},
 4426:         {href => "javascript:backPage(document.customresult,'pickrole','')",
 4427:          text => "Pick custom role",
 4428:          faq  => 282,
 4429:          bug  => 'Instructor Interface',},
 4430:         {href => "javascript:backPage(document.customresult,'selected_custom_edit','')",
 4431:          text => "Edit custom role",
 4432:          faq  => 282,
 4433:          bug  => 'Instructor Interface',},
 4434:         {href => "javascript:backPage(document.customresult,'set_custom_roles','')",
 4435:          text => "Result",
 4436:          faq  => 282,
 4437:          bug  => 'Instructor Interface',
 4438:          help => 'Course_Editing_Custom_Roles'},
 4439:         );
 4440:     my $args = { bread_crumbs           => $brcrum,
 4441:                  bread_crumbs_component => 'User Management'};
 4442:     $r->print(&Apache::loncommon::start_page('Save Custom Role',$jscript,$args));
 4443: 
 4444:     my $newrole;
 4445:     my ($rdummy,$roledef)=
 4446: 	&Apache::lonnet::get('roles',["rolesdef_$rolename"]);
 4447: 
 4448: # ------------------------------------------------------- Does this role exist?
 4449:     $r->print('<h3>');
 4450:     if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 4451: 	$r->print(&mt('Existing Role').' "');
 4452:     } else {
 4453: 	$r->print(&mt('New Role').' "');
 4454: 	$roledef='';
 4455:         $newrole = 1;
 4456:     }
 4457:     $r->print($rolename.'"</h3>');
 4458: # ------------------------------------------------- Assign role and show result
 4459: 
 4460:     my $errmsg;
 4461:     my %newprivs = &Apache::lonuserutils::custom_role_update($rolename,$prefix);
 4462:     # Assign role and return result
 4463:     my $result = &Apache::lonnet::definerole($rolename,$newprivs{'s'},$newprivs{'d'},
 4464:                                              $newprivs{'c'});
 4465:     if ($result ne 'ok') {
 4466:         $errmsg = ': '.$result;
 4467:     }
 4468:     my $message =
 4469:         &Apache::lonhtmlcommon::confirm_success(
 4470:             &mt('Defining Role').$errmsg, ($result eq 'ok' ? 0 : 1));
 4471:     if ($env{'request.course.id'}) {
 4472:         my $url='/'.$env{'request.course.id'};
 4473:         $url=~s/\_/\//g;
 4474:         $result =
 4475:             &Apache::lonnet::assigncustomrole(
 4476:                 $env{'user.domain'},$env{'user.name'},
 4477:                 $url,
 4478:                 $env{'user.domain'},$env{'user.name'},
 4479:                 $rolename,undef,undef,undef,$context);
 4480:         if ($result ne 'ok') {
 4481:             $errmsg = ': '.$result;
 4482:         }
 4483:         $message .=
 4484:             '<br />'
 4485:            .&Apache::lonhtmlcommon::confirm_success(
 4486:                 &mt('Assigning Role to Self').$errmsg, ($result eq 'ok' ? 0 : 1));
 4487:     }
 4488:     $r->print(
 4489:         &Apache::loncommon::confirmwrapper($message)
 4490:        .'<br />'
 4491:        .&Apache::lonhtmlcommon::actionbox([
 4492:             '<a href="javascript:backPage(document.customresult,'."'pickrole'".')">'
 4493:            .&mt('Create or edit another custom role')
 4494:            .'</a>'])
 4495:        .'<form name="customresult" method="post" action="">'
 4496:        .&Apache::lonhtmlcommon::echo_form_input([])
 4497:        .'</form>'
 4498:     );
 4499: }
 4500: 
 4501: # ================================================================ Main Handler
 4502: sub handler {
 4503:     my $r = shift;
 4504:     if ($r->header_only) {
 4505:        &Apache::loncommon::content_type($r,'text/html');
 4506:        $r->send_http_header;
 4507:        return OK;
 4508:     }
 4509:     my ($context,$crstype);
 4510:     if ($env{'request.course.id'}) {
 4511:         $context = 'course';
 4512:         $crstype = &Apache::loncommon::course_type();
 4513:     } elsif ($env{'request.role'} =~ /^au\./) {
 4514:         $context = 'author';
 4515:     } else {
 4516:         $context = 'domain';
 4517:     }
 4518: 
 4519:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 4520:         ['action','state','callingform','roletype','showrole','bulkaction','popup','phase',
 4521:          'username','domain','srchterm','srchdomain','srchin','srchby','srchtype','queue']);
 4522:     &Apache::lonhtmlcommon::clear_breadcrumbs();
 4523:     my $args;
 4524:     my $brcrum = [];
 4525:     my $bread_crumbs_component = 'User Management';
 4526:     if (($env{'form.action'} ne 'dateselect') && ($env{'form.action'} ne 'displayuserreq')) {
 4527:         $brcrum = [{href=>"/adm/createuser",
 4528:                     text=>"User Management",
 4529:                     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'}
 4530:                   ];
 4531:     }
 4532:     #SD Following files not added to help, because the corresponding .tex-files seem to
 4533:     #be missing: Course_Approve_Selfenroll,Course_User_Logs,
 4534:     my ($permission,$allowed) = 
 4535:         &Apache::lonuserutils::get_permission($context,$crstype);
 4536:     if (!$allowed) {
 4537:         if ($context eq 'course') {
 4538:             $r->internal_redirect('/adm/viewclasslist');
 4539:             return OK;
 4540:         }
 4541:         $env{'user.error.msg'}=
 4542:             "/adm/createuser:cst:0:0:Cannot create/modify user data ".
 4543:                                  "or view user status.";
 4544:         return HTTP_NOT_ACCEPTABLE;
 4545:     }
 4546: 
 4547:     &Apache::loncommon::content_type($r,'text/html');
 4548:     $r->send_http_header;
 4549: 
 4550:     my $showcredits;
 4551:     if ((($context eq 'course') && ($crstype eq 'Course')) || 
 4552:          ($context eq 'domain')) {
 4553:         my %domdefaults = 
 4554:             &Apache::lonnet::get_domain_defaults($env{'request.role.domain'});
 4555:         if ($domdefaults{'officialcredits'} || $domdefaults{'unofficialcredits'}) {
 4556:             $showcredits = 1;
 4557:         }
 4558:     }
 4559: 
 4560:     # Main switch on form.action and form.state, as appropriate
 4561:     if (! exists($env{'form.action'})) {
 4562:         $args = {bread_crumbs => $brcrum,
 4563:                  bread_crumbs_component => $bread_crumbs_component}; 
 4564:         $r->print(&header(undef,$args));
 4565:         $r->print(&print_main_menu($permission,$context,$crstype));
 4566:     } elsif ($env{'form.action'} eq 'upload' && $permission->{'cusr'}) {
 4567:         push(@{$brcrum},
 4568:               { href => '/adm/createuser?action=upload&state=',
 4569:                 text => 'Upload Users List',
 4570:                 help => 'Course_Create_Class_List',
 4571:               });
 4572:         $bread_crumbs_component = 'Upload Users List';
 4573:         $args = {bread_crumbs           => $brcrum,
 4574:                  bread_crumbs_component => $bread_crumbs_component};
 4575:         $r->print(&header(undef,$args));
 4576:         $r->print('<form name="studentform" method="post" '.
 4577:                   'enctype="multipart/form-data" '.
 4578:                   ' action="/adm/createuser">'."\n");
 4579:         if (! exists($env{'form.state'})) {
 4580:             &Apache::lonuserutils::print_first_users_upload_form($r,$context);
 4581:         } elsif ($env{'form.state'} eq 'got_file') {
 4582:             &Apache::lonuserutils::print_upload_manager_form($r,$context,$permission,
 4583:                                                              $crstype,$showcredits);
 4584:         } elsif ($env{'form.state'} eq 'enrolling') {
 4585:             if ($env{'form.datatoken'}) {
 4586:                 &Apache::lonuserutils::upfile_drop_add($r,$context,$permission,
 4587:                                                        $showcredits);
 4588:             }
 4589:         } else {
 4590:             &Apache::lonuserutils::print_first_users_upload_form($r,$context);
 4591:         }
 4592:     } elsif (((($env{'form.action'} eq 'singleuser') || ($env{'form.action'}
 4593:               eq 'singlestudent')) && ($permission->{'cusr'})) ||
 4594:              (($env{'form.action'} eq 'singleuser') && ($permission->{'view'})) ||
 4595:              (($env{'form.action'} eq 'accesslogs') && ($permission->{'activity'}))) {
 4596:         my $phase = $env{'form.phase'};
 4597:         my @search = ('srchterm','srchby','srchin','srchtype','srchdomain');
 4598: 	&Apache::loncreateuser::restore_prev_selections();
 4599: 	my $srch;
 4600: 	foreach my $item (@search) {
 4601: 	    $srch->{$item} = $env{'form.'.$item};
 4602: 	}
 4603:         if (($phase eq 'get_user_info') || ($phase eq 'userpicked') ||
 4604:             ($phase eq 'createnewuser') || ($phase eq 'activity')) {
 4605:             if ($env{'form.phase'} eq 'createnewuser') {
 4606:                 my $response;
 4607:                 if ($env{'form.srchterm'} !~ /^$match_username$/) {
 4608:                     my $response =
 4609:                         '<span class="LC_warning">'
 4610:                        .&mt('You must specify a valid username. Only the following are allowed:'
 4611:                            .' letters numbers - . @')
 4612:                        .'</span>';
 4613:                     $env{'form.phase'} = '';
 4614:                     &print_username_entry_form($r,$context,$response,$srch,undef,
 4615:                                                $crstype,$brcrum,$showcredits);
 4616:                 } else {
 4617:                     my $ccuname =&LONCAPA::clean_username($srch->{'srchterm'});
 4618:                     my $ccdomain=&LONCAPA::clean_domain($srch->{'srchdomain'});
 4619:                     &print_user_modification_page($r,$ccuname,$ccdomain,
 4620:                                                   $srch,$response,$context,
 4621:                                                   $permission,$crstype,$brcrum,
 4622:                                                   $showcredits);
 4623:                 }
 4624:             } elsif ($env{'form.phase'} eq 'get_user_info') {
 4625:                 my ($currstate,$response,$forcenewuser,$results) = 
 4626:                     &user_search_result($context,$srch);
 4627:                 if ($env{'form.currstate'} eq 'modify') {
 4628:                     $currstate = $env{'form.currstate'};
 4629:                 }
 4630:                 if ($currstate eq 'select') {
 4631:                     &print_user_selection_page($r,$response,$srch,$results,
 4632:                                                \@search,$context,undef,$crstype,
 4633:                                                $brcrum);
 4634:                 } elsif (($currstate eq 'modify') || ($env{'form.action'} eq 'accesslogs')) {
 4635:                     my ($ccuname,$ccdomain,$uhome);
 4636:                     if (($srch->{'srchby'} eq 'uname') && 
 4637:                         ($srch->{'srchtype'} eq 'exact')) {
 4638:                         $ccuname = $srch->{'srchterm'};
 4639:                         $ccdomain= $srch->{'srchdomain'};
 4640:                     } else {
 4641:                         my @matchedunames = keys(%{$results});
 4642:                         ($ccuname,$ccdomain) = split(/:/,$matchedunames[0]);
 4643:                     }
 4644:                     $ccuname =&LONCAPA::clean_username($ccuname);
 4645:                     $ccdomain=&LONCAPA::clean_domain($ccdomain);
 4646:                     if ($env{'form.action'} eq 'accesslogs') {
 4647:                         my $uhome;
 4648:                         if (($ccuname ne '') && ($ccdomain ne '')) {
 4649:                            $uhome = &Apache::lonnet::homeserver($ccuname,$ccdomain);
 4650:                         }
 4651:                         if (($uhome eq '') || ($uhome eq 'no_host')) {
 4652:                             $env{'form.phase'} = '';
 4653:                             undef($forcenewuser);
 4654:                             #if ($response) {
 4655:                             #    unless ($response =~ m{\Q<br /><br />\E$}) {
 4656:                             #        $response .= '<br /><br />';
 4657:                             #    }
 4658:                             #}
 4659:                             &print_username_entry_form($r,$context,$response,$srch,
 4660:                                                        $forcenewuser,$crstype,$brcrum);
 4661:                         } else {
 4662:                             &print_useraccesslogs_display($r,$ccuname,$ccdomain,$permission,$brcrum);
 4663:                         }
 4664:                     } else {
 4665:                         if ($env{'form.forcenewuser'}) {
 4666:                             $response = '';
 4667:                         }
 4668:                         &print_user_modification_page($r,$ccuname,$ccdomain,
 4669:                                                       $srch,$response,$context,
 4670:                                                       $permission,$crstype,$brcrum);
 4671:                     }
 4672:                 } elsif ($currstate eq 'query') {
 4673:                     &print_user_query_page($r,'createuser',$brcrum);
 4674:                 } else {
 4675:                     $env{'form.phase'} = '';
 4676:                     &print_username_entry_form($r,$context,$response,$srch,
 4677:                                                $forcenewuser,$crstype,$brcrum);
 4678:                 }
 4679:             } elsif ($env{'form.phase'} eq 'userpicked') {
 4680:                 my $ccuname = &LONCAPA::clean_username($env{'form.seluname'});
 4681:                 my $ccdomain = &LONCAPA::clean_domain($env{'form.seludom'});
 4682:                 if ($env{'form.action'} eq 'accesslogs') {
 4683:                     &print_useraccesslogs_display($r,$ccuname,$ccdomain,$permission,$brcrum);
 4684:                 } else {
 4685:                     &print_user_modification_page($r,$ccuname,$ccdomain,$srch,'',
 4686:                                                   $context,$permission,$crstype,
 4687:                                                   $brcrum);
 4688:                 }
 4689:             } elsif ($env{'form.action'} eq 'accesslogs') {
 4690:                 my $ccuname = &LONCAPA::clean_username($env{'form.accessuname'});
 4691:                 my $ccdomain = &LONCAPA::clean_domain($env{'form.accessudom'});
 4692:                 &print_useraccesslogs_display($r,$ccuname,$ccdomain,$permission,$brcrum);
 4693:             }
 4694:         } elsif ($env{'form.phase'} eq 'update_user_data') {
 4695:             &update_user_data($r,$context,$crstype,$brcrum,$showcredits);
 4696:         } else {
 4697:             &print_username_entry_form($r,$context,undef,$srch,undef,$crstype,
 4698:                                        $brcrum);
 4699:         }
 4700:     } elsif ($env{'form.action'} eq 'custom' && $permission->{'custom'}) {
 4701:         my $prefix;
 4702:         if ($env{'form.phase'} eq 'set_custom_roles') {
 4703:             &set_custom_role($r,$context,$brcrum,$prefix);
 4704:         } else {
 4705:             &custom_role_editor($r,$brcrum,$prefix);
 4706:         }
 4707:     } elsif (($env{'form.action'} eq 'processauthorreq') &&
 4708:              ($permission->{'cusr'}) && 
 4709:              (&Apache::lonnet::allowed('cau',$env{'request.role.domain'}))) {
 4710:         push(@{$brcrum},
 4711:                  {href => '/adm/createuser?action=processauthorreq',
 4712:                   text => 'Authoring Space requests',
 4713:                   help => 'Domain_Role_Approvals'});
 4714:         $bread_crumbs_component = 'Authoring requests';
 4715:         if ($env{'form.state'} eq 'done') {
 4716:             push(@{$brcrum},
 4717:                      {href => '/adm/createuser?action=authorreqqueue',
 4718:                       text => 'Result',
 4719:                       help => 'Domain_Role_Approvals'});
 4720:             $bread_crumbs_component = 'Authoring request result';
 4721:         }
 4722:         $args = { bread_crumbs           => $brcrum,
 4723:                   bread_crumbs_component => $bread_crumbs_component};
 4724:         my $js = &usernamerequest_javascript();
 4725:         $r->print(&header(&add_script($js),$args));
 4726:         if (!exists($env{'form.state'})) {
 4727:             $r->print(&Apache::loncoursequeueadmin::display_queued_requests('requestauthor',
 4728:                                                                             $env{'request.role.domain'}));
 4729:         } elsif ($env{'form.state'} eq 'done') {
 4730:             $r->print('<h3>'.&mt('Authoring request processing').'</h3>'."\n");
 4731:             $r->print(&Apache::loncoursequeueadmin::update_request_queue('requestauthor',
 4732:                                                                          $env{'request.role.domain'}));
 4733:         }
 4734:     } elsif (($env{'form.action'} eq 'processusernamereq') &&
 4735:              ($permission->{'cusr'}) &&
 4736:              (&Apache::lonnet::allowed('cau',$env{'request.role.domain'}))) {
 4737:         push(@{$brcrum},
 4738:                  {href => '/adm/createuser?action=processusernamereq',
 4739:                   text => 'LON-CAPA account requests',
 4740:                   help => 'Domain_Username_Approvals'});
 4741:         $bread_crumbs_component = 'Account requests';
 4742:         if ($env{'form.state'} eq 'done') {
 4743:             push(@{$brcrum},
 4744:                      {href => '/adm/createuser?action=usernamereqqueue',
 4745:                       text => 'Result',
 4746:                       help => 'Domain_Username_Approvals'});
 4747:             $bread_crumbs_component = 'LON-CAPA account request result';
 4748:         }
 4749:         $args = { bread_crumbs           => $brcrum,
 4750:                   bread_crumbs_component => $bread_crumbs_component};
 4751:         my $js = &usernamerequest_javascript();
 4752:         $r->print(&header(&add_script($js),$args));
 4753:         if (!exists($env{'form.state'})) {
 4754:             $r->print(&Apache::loncoursequeueadmin::display_queued_requests('requestusername',
 4755:                                                                             $env{'request.role.domain'}));
 4756:         } elsif ($env{'form.state'} eq 'done') {
 4757:             $r->print('<h3>'.&mt('LON-CAPA account request processing').'</h3>'."\n");
 4758:             $r->print(&Apache::loncoursequeueadmin::update_request_queue('requestusername',
 4759:                                                                          $env{'request.role.domain'}));
 4760:         }
 4761:     } elsif (($env{'form.action'} eq 'displayuserreq') &&
 4762:              ($permission->{'cusr'})) {
 4763:         my $dom = $env{'form.domain'};
 4764:         my $uname = $env{'form.username'};
 4765:         my $warning;
 4766:         if (($dom =~ /^$match_domain$/) && (&Apache::lonnet::domain($dom) ne '')) {
 4767:             if (($dom eq $env{'request.role.domain'}) && (&Apache::lonnet::allowed('ccc',$dom))) {
 4768:                 if (($uname =~ /^$match_username$/) && ($env{'form.queue'} eq 'approval')) {
 4769:                     my $uhome = &Apache::lonnet::homeserver($uname,$dom);
 4770:                     if ($uhome eq 'no_host') {
 4771:                         my $queue = $env{'form.queue'};
 4772:                         my $reqkey = &escape($uname).'_'.$queue; 
 4773:                         my $namespace = 'usernamequeue';
 4774:                         my $domconfig = &Apache::lonnet::get_domainconfiguser($dom);
 4775:                         my %queued =
 4776:                             &Apache::lonnet::get($namespace,[$reqkey],$dom,$domconfig);
 4777:                         unless ($queued{$reqkey}) {
 4778:                             $warning = &mt('No information was found for this LON-CAPA account request.');
 4779:                         }
 4780:                     } else {
 4781:                         $warning = &mt('A LON-CAPA account already exists for the requested username and domain.');
 4782:                     }
 4783:                 } else {
 4784:                     $warning = &mt('LON-CAPA account request status check is for an invalid username.');
 4785:                 }
 4786:             } else {
 4787:                 $warning = &mt('You do not have rights to view LON-CAPA account requests in the domain specified.');
 4788:             }
 4789:         } else {
 4790:             $warning = &mt('LON-CAPA account request status check is for an invalid domain.');
 4791:         }
 4792:         my $args = { only_body => 1 };
 4793:         $r->print(&header(undef,$args).
 4794:                   '<h3>'.&mt('LON-CAPA Account Request Details').'</h3>');
 4795:         if ($warning ne '') {
 4796:             $r->print('<div class="LC_warning">'.$warning.'</div>');
 4797:         } else {
 4798:             my ($infofields,$infotitles) = &Apache::loncommon::emailusername_info();
 4799:             my $domconfiguser = &Apache::lonnet::get_domainconfiguser($dom);
 4800:             my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 4801:             if (ref($domconfig{'usercreation'}) eq 'HASH') {
 4802:                 if (ref($domconfig{'usercreation'}{'cancreate'}) eq 'HASH') {
 4803:                     if (ref($domconfig{'usercreation'}{'cancreate'}{'emailusername'}) eq 'HASH') {
 4804:                         my %info =
 4805:                             &Apache::lonnet::get('nohist_requestedusernames',[$uname],$dom,$domconfiguser);
 4806:                         if (ref($info{$uname}) eq 'HASH') {
 4807:                             my $usertype = $info{$uname}{'inststatus'};
 4808:                             unless ($usertype) {
 4809:                                 $usertype = 'default';
 4810:                             }
 4811:                             if (ref($domconfig{'usercreation'}{'cancreate'}{'emailusername'}{$usertype}) eq 'HASH') {
 4812:                                 if ((ref($infofields) eq 'ARRAY') && (ref($infotitles) eq 'HASH')) {
 4813:                                     $r->print('<div>'.&Apache::lonhtmlcommon::start_pick_box());
 4814:                                     my ($num,$count,$showstatus);
 4815:                                     $count = scalar(keys(%{$domconfig{'usercreation'}{'cancreate'}{'emailusername'}{$usertype}}));
 4816:                                     unless ($usertype eq 'default') {
 4817:                                         my ($othertitle,$usertypes,$types) = 
 4818:                                             &Apache::loncommon::sorted_inst_types($dom);
 4819:                                         if (ref($usertypes) eq 'HASH') {
 4820:                                             if ($usertypes->{$usertype}) {
 4821:                                                 $showstatus = $usertypes->{$usertype};
 4822:                                                 $count ++;
 4823:                                             }
 4824:                                         }
 4825:                                     }
 4826:                                     foreach my $field (@{$infofields}) {
 4827:                                         next unless ($domconfig{'usercreation'}{'cancreate'}{'emailusername'}{$usertype}{$field});
 4828:                                         next unless ($infotitles->{$field});
 4829:                                         $r->print(&Apache::lonhtmlcommon::row_title($infotitles->{$field}).
 4830:                                                   $info{$uname}{$field});
 4831:                                         $num ++;
 4832:                                         if ($count == $num) {
 4833:                                             $r->print(&Apache::lonhtmlcommon::row_closure(1));
 4834:                                         } else {
 4835:                                             $r->print(&Apache::lonhtmlcommon::row_closure());
 4836:                                         }
 4837:                                     }
 4838:                                     if ($showstatus) {
 4839:                                         $r->print(&Apache::lonhtmlcommon::row_title(&mt('Status type (self-reported)')).
 4840:                                                   $showstatus.
 4841:                                                   &Apache::lonhtmlcommon::row_closure(1));
 4842:                                     }
 4843:                                     $r->print(&Apache::lonhtmlcommon::end_pick_box().'</div>');
 4844:                                 }
 4845:                             }
 4846:                         }
 4847:                     }
 4848:                 }
 4849:             }
 4850:             $r->print(&close_popup_form());
 4851:         }
 4852:     } elsif (($env{'form.action'} eq 'listusers') && 
 4853:              ($permission->{'view'} || $permission->{'cusr'})) {
 4854:         if ($env{'form.phase'} eq 'bulkchange') {
 4855:             push(@{$brcrum},
 4856:                     {href => '/adm/createuser?action=listusers',
 4857:                      text => "List Users"},
 4858:                     {href => "/adm/createuser",
 4859:                      text => "Result",
 4860:                      help => 'Course_View_Class_List'});
 4861:             $bread_crumbs_component = 'Update Users';
 4862:             $args = {bread_crumbs           => $brcrum,
 4863:                      bread_crumbs_component => $bread_crumbs_component};
 4864:             $r->print(&header(undef,$args));
 4865:             my $setting = $env{'form.roletype'};
 4866:             my $choice = $env{'form.bulkaction'};
 4867:             if ($permission->{'cusr'}) {
 4868:                 &Apache::lonuserutils::update_user_list($r,$context,$setting,$choice,$crstype);
 4869:             } else {
 4870:                 $r->print(&mt('You are not authorized to make bulk changes to user roles'));
 4871:                 $r->print('<p><a href="/adm/createuser?action=listusers">'.&mt('Display User Lists').'</a>');
 4872:             }
 4873:         } else {
 4874:             push(@{$brcrum},
 4875:                     {href => '/adm/createuser?action=listusers',
 4876:                      text => "List Users",
 4877:                      help => 'Course_View_Class_List'});
 4878:             $bread_crumbs_component = 'List Users';
 4879:             $args = {bread_crumbs           => $brcrum,
 4880:                      bread_crumbs_component => $bread_crumbs_component};
 4881:             my ($cb_jscript,$jscript,$totcodes,$codetitles,$idlist,$idlist_titles);
 4882:             my $formname = 'studentform';
 4883:             my $hidecall = "hide_searching();";
 4884:             if (($context eq 'domain') && (($env{'form.roletype'} eq 'course') ||
 4885:                 ($env{'form.roletype'} eq 'community'))) {
 4886:                 if ($env{'form.roletype'} eq 'course') {
 4887:                     ($cb_jscript,$jscript,$totcodes,$codetitles,$idlist,$idlist_titles) = 
 4888:                         &Apache::lonuserutils::courses_selector($env{'request.role.domain'},
 4889:                                                                 $formname);
 4890:                 } elsif ($env{'form.roletype'} eq 'community') {
 4891:                     $cb_jscript = 
 4892:                         &Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'});
 4893:                     my %elements = (
 4894:                                       coursepick => 'radio',
 4895:                                       coursetotal => 'text',
 4896:                                       courselist => 'text',
 4897:                                    );
 4898:                     $jscript = &Apache::lonhtmlcommon::set_form_elements(\%elements);
 4899:                 }
 4900:                 $jscript .= &verify_user_display($context)."\n".
 4901:                             &Apache::loncommon::check_uncheck_jscript();
 4902:                 my $js = &add_script($jscript).$cb_jscript;
 4903:                 my $loadcode = 
 4904:                     &Apache::lonuserutils::course_selector_loadcode($formname);
 4905:                 if ($loadcode ne '') {
 4906:                     $args->{add_entries} = {onload => "$loadcode;$hidecall"};
 4907:                 } else {
 4908:                     $args->{add_entries} = {onload => $hidecall};
 4909:                 }
 4910:                 $r->print(&header($js,$args));
 4911:             } else {
 4912:                 $args->{add_entries} = {onload => $hidecall};
 4913:                 $jscript = &verify_user_display($context).
 4914:                            &Apache::loncommon::check_uncheck_jscript(); 
 4915:                 $r->print(&header(&add_script($jscript),$args));
 4916:             }
 4917:             &Apache::lonuserutils::print_userlist($r,undef,$permission,$context,
 4918:                          $formname,$totcodes,$codetitles,$idlist,$idlist_titles,
 4919:                          $showcredits);
 4920:         }
 4921:     } elsif ($env{'form.action'} eq 'drop' && $permission->{'cusr'}) {
 4922:         my $brtext;
 4923:         if ($crstype eq 'Community') {
 4924:             $brtext = 'Drop Members';
 4925:         } else {
 4926:             $brtext = 'Drop Students';
 4927:         }
 4928:         push(@{$brcrum},
 4929:                 {href => '/adm/createuser?action=drop',
 4930:                  text => $brtext,
 4931:                  help => 'Course_Drop_Student'});
 4932:         if ($env{'form.state'} eq 'done') {
 4933:             push(@{$brcrum},
 4934:                      {href=>'/adm/createuser?action=drop',
 4935:                       text=>"Result"});
 4936:         }
 4937:         $bread_crumbs_component = $brtext;
 4938:         $args = {bread_crumbs           => $brcrum,
 4939:                  bread_crumbs_component => $bread_crumbs_component}; 
 4940:         $r->print(&header(undef,$args));
 4941:         if (!exists($env{'form.state'})) {
 4942:             &Apache::lonuserutils::print_drop_menu($r,$context,$permission,$crstype);
 4943:         } elsif ($env{'form.state'} eq 'done') {
 4944:             &Apache::lonuserutils::update_user_list($r,$context,undef,
 4945:                                                     $env{'form.action'});
 4946:         }
 4947:     } elsif ($env{'form.action'} eq 'dateselect') {
 4948:         if ($permission->{'cusr'}) {
 4949:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 4950:                       &Apache::lonuserutils::date_section_selector($context,$permission,
 4951:                                                                    $crstype,$showcredits));
 4952:         } else {
 4953:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 4954:                      '<span class="LC_error">'.&mt('You do not have permission to modify dates or sections for users').'</span>'); 
 4955:         }
 4956:     } elsif ($env{'form.action'} eq 'selfenroll') {
 4957:         if ($permission->{selfenrolladmin}) {
 4958:             my $cid = $env{'request.course.id'};
 4959:             my $cdom = $env{'course.'.$cid.'.domain'};
 4960:             my $cnum = $env{'course.'.$cid.'.num'};
 4961:             my %currsettings = (
 4962:                 selfenroll_types              => $env{'course.'.$cid.'.internal.selfenroll_types'},
 4963:                 selfenroll_registered         => $env{'course.'.$cid.'.internal.selfenroll_registered'},
 4964:                 selfenroll_section            => $env{'course.'.$cid.'.internal.selfenroll_section'},
 4965:                 selfenroll_notifylist         => $env{'course.'.$cid.'.internal.selfenroll_notifylist'},
 4966:                 selfenroll_approval           => $env{'course.'.$cid.'.internal.selfenroll_approval'},
 4967:                 selfenroll_limit              => $env{'course.'.$cid.'.internal.selfenroll_limit'},
 4968:                 selfenroll_cap                => $env{'course.'.$cid.'.internal.selfenroll_cap'},
 4969:                 selfenroll_start_date         => $env{'course.'.$cid.'.internal.selfenroll_start_date'},
 4970:                 selfenroll_end_date           => $env{'course.'.$cid.'.internal.selfenroll_end_date'},
 4971:                 selfenroll_start_access       => $env{'course.'.$cid.'.internal.selfenroll_start_access'},
 4972:                 selfenroll_end_access         => $env{'course.'.$cid.'.internal.selfenroll_end_access'},
 4973:                 default_enrollment_start_date => $env{'course.'.$cid.'.default_enrollment_start_date'},
 4974:                 default_enrollment_end_date   => $env{'course.'.$cid.'.default_enrollment_end_date'},
 4975:                 uniquecode                    => $env{'course.'.$cid.'.internal.uniquecode'},
 4976:             );
 4977:             push(@{$brcrum},
 4978:                     {href => '/adm/createuser?action=selfenroll',
 4979:                      text => "Configure Self-enrollment",
 4980:                      help => 'Course_Self_Enrollment'});
 4981:             if (!exists($env{'form.state'})) {
 4982:                 $args = { bread_crumbs           => $brcrum,
 4983:                           bread_crumbs_component => 'Configure Self-enrollment'};
 4984:                 $r->print(&header(undef,$args));
 4985:                 $r->print('<h3>'.&mt('Self-enrollment with a student role').'</h3>'."\n");
 4986:                 &print_selfenroll_menu($r,'course',$cid,$cdom,$cnum,\%currsettings);
 4987:             } elsif ($env{'form.state'} eq 'done') {
 4988:                 push (@{$brcrum},
 4989:                           {href=>'/adm/createuser?action=selfenroll',
 4990:                            text=>"Result"});
 4991:                 $args = { bread_crumbs           => $brcrum,
 4992:                           bread_crumbs_component => 'Self-enrollment result'};
 4993:                 $r->print(&header(undef,$args));
 4994:                 $r->print('<h3>'.&mt('Self-enrollment with a student role').'</h3>'."\n");
 4995:                 &update_selfenroll_config($r,$cid,$cdom,$cnum,$context,$crstype,\%currsettings);
 4996:             }
 4997:         } else {
 4998:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 4999:                      '<span class="LC_error">'.&mt('You do not have permission to configure self-enrollment').'</span>');
 5000:         }
 5001:     } elsif ($env{'form.action'} eq 'selfenrollqueue') {
 5002:         if ($permission->{selfenrolladmin}) {
 5003:             push(@{$brcrum},
 5004:                      {href => '/adm/createuser?action=selfenrollqueue',
 5005:                       text => 'Enrollment requests',
 5006:                       help => 'Course_Self_Enrollment'});
 5007:             $bread_crumbs_component = 'Enrollment requests';
 5008:             if ($env{'form.state'} eq 'done') {
 5009:                 push(@{$brcrum},
 5010:                          {href => '/adm/createuser?action=selfenrollqueue',
 5011:                           text => 'Result',
 5012:                           help => 'Course_Self_Enrollment'});
 5013:                 $bread_crumbs_component = 'Enrollment result';
 5014:             }
 5015:             $args = { bread_crumbs           => $brcrum,
 5016:                       bread_crumbs_component => $bread_crumbs_component};
 5017:             $r->print(&header(undef,$args));
 5018:             my $cid = $env{'request.course.id'};
 5019:             my $cdom = $env{'course.'.$cid.'.domain'};
 5020:             my $cnum = $env{'course.'.$cid.'.num'};
 5021:             my $coursedesc = $env{'course.'.$cid.'.description'};
 5022:             if (!exists($env{'form.state'})) {
 5023:                 $r->print('<h3>'.&mt('Pending enrollment requests').'</h3>'."\n");
 5024:                 $r->print(&Apache::loncoursequeueadmin::display_queued_requests($context,
 5025:                                                                                 $cdom,$cnum));
 5026:             } elsif ($env{'form.state'} eq 'done') {
 5027:                 $r->print('<h3>'.&mt('Enrollment request processing').'</h3>'."\n");
 5028:                 $r->print(&Apache::loncoursequeueadmin::update_request_queue($context,
 5029:                               $cdom,$cnum,$coursedesc));
 5030:             }
 5031:         } else {
 5032:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 5033:                      '<span class="LC_error">'.&mt('You do not have permission to manage self-enrollment').'</span>');
 5034:         }
 5035:     } elsif ($env{'form.action'} eq 'changelogs') {
 5036:         if ($permission->{cusr} || $permission->{view}) {
 5037:             &print_userchangelogs_display($r,$context,$permission,$brcrum);
 5038:         } else {
 5039:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 5040:                      '<span class="LC_error">'.&mt('You do not have permission to view change logs').'</span>');
 5041:         }
 5042:     } elsif ($env{'form.action'} eq 'helpdesk') {
 5043:         if (($permission->{'owner'}) || ($permission->{'co-owner'})) {
 5044:             if ($env{'form.state'} eq 'process') {
 5045:                 if ($permission->{'owner'}) {
 5046:                     &update_helpdeskaccess($r,$permission,$brcrum);
 5047:                 } else {
 5048:                     &print_helpdeskaccess_display($r,$permission,$brcrum);
 5049:                 }
 5050:             } else {
 5051:                 &print_helpdeskaccess_display($r,$permission,$brcrum);
 5052:             }
 5053:         } else {
 5054:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 5055:                       '<span class="LC_error">'.&mt('You do not have permission to view helpdesk access').'</span>');
 5056:         }
 5057:     } else {
 5058:         $bread_crumbs_component = 'User Management';
 5059:         $args = { bread_crumbs           => $brcrum,
 5060:                   bread_crumbs_component => $bread_crumbs_component};
 5061:         $r->print(&header(undef,$args));
 5062:         $r->print(&print_main_menu($permission,$context,$crstype));
 5063:     }
 5064:     $r->print(&Apache::loncommon::end_page());
 5065:     return OK;
 5066: }
 5067: 
 5068: sub header {
 5069:     my ($jscript,$args) = @_;
 5070:     my $start_page;
 5071:     if (ref($args) eq 'HASH') {
 5072:         $start_page=&Apache::loncommon::start_page('User Management',$jscript,$args);
 5073:     } else {
 5074:         $start_page=&Apache::loncommon::start_page('User Management',$jscript);
 5075:     }
 5076:     return $start_page;
 5077: }
 5078: 
 5079: sub add_script {
 5080:     my ($js) = @_;
 5081:     return '<script type="text/javascript">'."\n"
 5082:           .'// <![CDATA['."\n"
 5083:           .$js."\n"
 5084:           .'// ]]>'."\n"
 5085:           .'</script>'."\n";
 5086: }
 5087: 
 5088: sub usernamerequest_javascript {
 5089:     my $js = <<ENDJS;
 5090: 
 5091: function openusernamereqdisplay(dom,uname,queue) {
 5092:     var url = '/adm/createuser?action=displayuserreq';
 5093:     url += '&domain='+dom+'&username='+uname+'&queue='+queue;
 5094:     var title = 'Account_Request_Browser';
 5095:     var options = 'scrollbars=1,resizable=1,menubar=0';
 5096:     options += ',width=700,height=600';
 5097:     var stdeditbrowser = open(url,title,options,'1');
 5098:     stdeditbrowser.focus();
 5099:     return;
 5100: }
 5101:  
 5102: ENDJS
 5103: }
 5104: 
 5105: sub close_popup_form {
 5106:     my $close= &mt('Close Window');
 5107:     return << "END";
 5108: <p><form name="displayreq" action="" method="post">
 5109: <input type="button" name="closeme" value="$close" onclick="javascript:self.close();" />
 5110: </form></p>
 5111: END
 5112: }
 5113: 
 5114: sub verify_user_display {
 5115:     my ($context) = @_;
 5116:     my %lt = &Apache::lonlocal::texthash (
 5117:         course    => 'course(s): description, section(s), status',
 5118:         community => 'community(s): description, section(s), status',
 5119:         author    => 'author',
 5120:     );
 5121:     my $photos;
 5122:     if (($context eq 'course') && $env{'request.course.id'}) {
 5123:         $photos = $env{'course.'.$env{'request.course.id'}.'.internal.showphoto'};
 5124:     }
 5125:     my $output = <<"END";
 5126: 
 5127: function hide_searching() {
 5128:     if (document.getElementById('searching')) {
 5129:         document.getElementById('searching').style.display = 'none';
 5130:     }
 5131:     return;
 5132: }
 5133: 
 5134: function display_update() {
 5135:     document.studentform.action.value = 'listusers';
 5136:     document.studentform.phase.value = 'display';
 5137:     document.studentform.submit();
 5138: }
 5139: 
 5140: function updateCols(caller) {
 5141:     var context = '$context';
 5142:     var photos = '$photos';
 5143:     if (caller == 'Status') {
 5144:         if ((context == 'domain') && 
 5145:             ((document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'course') ||
 5146:              (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'community'))) {
 5147:             document.getElementById('showcolstatus').checked = false;
 5148:             document.getElementById('showcolstatus').disabled = 'disabled';
 5149:             document.getElementById('showcolstart').checked = false;
 5150:             document.getElementById('showcolend').checked = false;
 5151:         } else {
 5152:             if (document.studentform.Status.options[document.studentform.Status.selectedIndex].value == 'Any') {
 5153:                 document.getElementById('showcolstatus').checked = true;
 5154:                 document.getElementById('showcolstatus').disabled = '';
 5155:                 document.getElementById('showcolstart').checked = true;
 5156:                 document.getElementById('showcolend').checked = true;
 5157:             } else {
 5158:                 document.getElementById('showcolstatus').checked = false;
 5159:                 document.getElementById('showcolstatus').disabled = 'disabled';
 5160:                 document.getElementById('showcolstart').checked = false;
 5161:                 document.getElementById('showcolend').checked = false;
 5162:             }
 5163:         }
 5164:     }
 5165:     if (caller == 'output') {
 5166:         if (photos == 1) {
 5167:             if (document.getElementById('showcolphoto')) {
 5168:                 var photoitem = document.getElementById('showcolphoto');
 5169:                 if (document.studentform.output.options[document.studentform.output.selectedIndex].value == 'html') {
 5170:                     photoitem.checked = true;
 5171:                     photoitem.disabled = '';
 5172:                 } else {
 5173:                     photoitem.checked = false;
 5174:                     photoitem.disabled = 'disabled';
 5175:                 }
 5176:             }
 5177:         }
 5178:     }
 5179:     if (caller == 'showrole') {
 5180:         if ((document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'Any') ||
 5181:             (document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'cr')) {
 5182:             document.getElementById('showcolrole').checked = true;
 5183:             document.getElementById('showcolrole').disabled = '';
 5184:         } else {
 5185:             document.getElementById('showcolrole').checked = false;
 5186:             document.getElementById('showcolrole').disabled = 'disabled';
 5187:         }
 5188:         if (context == 'domain') {
 5189:             var quotausageshow = 0;
 5190:             if ((document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'course') ||
 5191:                 (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'community')) {
 5192:                 document.getElementById('showcolstatus').checked = false;
 5193:                 document.getElementById('showcolstatus').disabled = 'disabled';
 5194:                 document.getElementById('showcolstart').checked = false;
 5195:                 document.getElementById('showcolend').checked = false;
 5196:             } else {
 5197:                 if (document.studentform.Status.options[document.studentform.Status.selectedIndex].value == 'Any') {
 5198:                     document.getElementById('showcolstatus').checked = true;
 5199:                     document.getElementById('showcolstatus').disabled = '';
 5200:                     document.getElementById('showcolstart').checked = true;
 5201:                     document.getElementById('showcolend').checked = true;
 5202:                 }
 5203:             }
 5204:             if (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'domain') {
 5205:                 document.getElementById('showcolextent').disabled = 'disabled';
 5206:                 document.getElementById('showcolextent').checked = 'false';
 5207:                 document.getElementById('showextent').style.display='none';
 5208:                 document.getElementById('showcoltextextent').innerHTML = '';
 5209:                 if ((document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'au') ||
 5210:                     (document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'Any')) {
 5211:                     if (document.getElementById('showcolauthorusage')) {
 5212:                         document.getElementById('showcolauthorusage').disabled = '';
 5213:                     }
 5214:                     if (document.getElementById('showcolauthorquota')) {
 5215:                         document.getElementById('showcolauthorquota').disabled = '';
 5216:                     }
 5217:                     quotausageshow = 1;
 5218:                 }
 5219:             } else {
 5220:                 document.getElementById('showextent').style.display='block';
 5221:                 document.getElementById('showextent').style.textAlign='left';
 5222:                 document.getElementById('showextent').style.textFace='normal';
 5223:                 if (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'author') {
 5224:                     document.getElementById('showcolextent').disabled = '';
 5225:                     document.getElementById('showcolextent').checked = 'true';
 5226:                     document.getElementById('showcoltextextent').innerHTML="$lt{'author'}";
 5227:                 } else {
 5228:                     document.getElementById('showcolextent').disabled = '';
 5229:                     document.getElementById('showcolextent').checked = 'true';
 5230:                     if (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'community') {
 5231:                         document.getElementById('showcoltextextent').innerHTML="$lt{'community'}";
 5232:                     } else {
 5233:                         document.getElementById('showcoltextextent').innerHTML="$lt{'course'}";
 5234:                     }
 5235:                 }
 5236:             }
 5237:             if (quotausageshow == 0)  {
 5238:                 if (document.getElementById('showcolauthorusage')) {
 5239:                     document.getElementById('showcolauthorusage').checked = false;
 5240:                     document.getElementById('showcolauthorusage').disabled = 'disabled';
 5241:                 }
 5242:                 if (document.getElementById('showcolauthorquota')) {
 5243:                     document.getElementById('showcolauthorquota').checked = false;
 5244:                     document.getElementById('showcolauthorquota').disabled = 'disabled';
 5245:                 }
 5246:             }
 5247:         }
 5248:     }
 5249:     return;
 5250: }
 5251: 
 5252: END
 5253:     return $output;
 5254: 
 5255: }
 5256: 
 5257: ###############################################################
 5258: ###############################################################
 5259: #  Menu Phase One
 5260: sub print_main_menu {
 5261:     my ($permission,$context,$crstype) = @_;
 5262:     my $linkcontext = $context;
 5263:     my $stuterm = lc(&Apache::lonnet::plaintext('st',$crstype));
 5264:     if (($context eq 'course') && ($crstype eq 'Community')) {
 5265:         $linkcontext = lc($crstype);
 5266:         $stuterm = 'Members';
 5267:     }
 5268:     my %links = (
 5269:                 domain => {
 5270:                             upload     => 'Upload a File of Users',
 5271:                             singleuser => 'Add/Modify a User',
 5272:                             listusers  => 'Manage Users',
 5273:                             },
 5274:                 author => {
 5275:                             upload     => 'Upload a File of Co-authors',
 5276:                             singleuser => 'Add/Modify a Co-author',
 5277:                             listusers  => 'Manage Co-authors',
 5278:                             },
 5279:                 course => {
 5280:                             upload     => 'Upload a File of Course Users',
 5281:                             singleuser => 'Add/Modify a Course User',
 5282:                             listusers  => 'List and Modify Multiple Course Users',
 5283:                             },
 5284:                 community => {
 5285:                             upload     => 'Upload a File of Community Users',
 5286:                             singleuser => 'Add/Modify a Community User',
 5287:                             listusers  => 'List and Modify Multiple Community Users',
 5288:                            },
 5289:                 );
 5290:      my %linktitles = (
 5291:                 domain => {
 5292:                             singleuser => 'Add a user to the domain, and/or a course or community in the domain.',
 5293:                             listusers  => 'Show and manage users in this domain.',
 5294:                             },
 5295:                 author => {
 5296:                             singleuser => 'Add a user with a co- or assistant author role.',
 5297:                             listusers  => 'Show and manage co- or assistant authors.',
 5298:                             },
 5299:                 course => {
 5300:                             singleuser => 'Add a user with a certain role to this course.',
 5301:                             listusers  => 'Show and manage users in this course.',
 5302:                             },
 5303:                 community => {
 5304:                             singleuser => 'Add a user with a certain role to this community.',
 5305:                             listusers  => 'Show and manage users in this community.',
 5306:                            },
 5307:                 );
 5308:   if ($linkcontext eq 'domain') {
 5309:       unless ($permission->{'cusr'}) {
 5310:           $links{'domain'}{'singleuser'} = 'View a User';
 5311:           $linktitles{'domain'}{'singleuser'} = 'View information about a user in the domain';
 5312:       }
 5313:   } elsif ($linkcontext eq 'course') {
 5314:       unless ($permission->{'cusr'}) {
 5315:           $links{'course'}{'singleuser'} = 'View a Course User';
 5316:           $linktitles{'course'}{'singleuser'} = 'View information about a user in this course';
 5317:           $links{'course'}{'listusers'} = 'List Course Users';
 5318:           $linktitles{'course'}{'listusers'} = 'Show information about users in this course';
 5319:       }
 5320:   } elsif ($linkcontext eq 'community') {
 5321:       unless ($permission->{'cusr'}) {
 5322:           $links{'community'}{'singleuser'} = 'View a Community User';
 5323:           $linktitles{'community'}{'singleuser'} = 'View information about a user in this community';
 5324:           $links{'community'}{'listusers'} = 'List Community Users';
 5325:           $linktitles{'community'}{'listusers'} = 'Show information about users in this community';
 5326:       }
 5327:   }
 5328:   my @menu = ( {categorytitle => 'Single Users', 
 5329:          items =>
 5330:          [
 5331:             {
 5332:              linktext => $links{$linkcontext}{'singleuser'},
 5333:              icon => 'edit-redo.png',
 5334:              #help => 'Course_Change_Privileges',
 5335:              url => '/adm/createuser?action=singleuser',
 5336:              permission => ($permission->{'view'} || $permission->{'cusr'}),
 5337:              linktitle => $linktitles{$linkcontext}{'singleuser'},
 5338:             },
 5339:          ]},
 5340: 
 5341:          {categorytitle => 'Multiple Users',
 5342:          items => 
 5343:          [
 5344:             {
 5345:              linktext => $links{$linkcontext}{'upload'},
 5346:              icon => 'uplusr.png',
 5347:              #help => 'Course_Create_Class_List',
 5348:              url => '/adm/createuser?action=upload',
 5349:              permission => $permission->{'cusr'},
 5350:              linktitle => 'Upload a CSV or a text file containing users.',
 5351:             },
 5352:             {
 5353:              linktext => $links{$linkcontext}{'listusers'},
 5354:              icon => 'mngcu.png',
 5355:              #help => 'Course_View_Class_List',
 5356:              url => '/adm/createuser?action=listusers',
 5357:              permission => ($permission->{'view'} || $permission->{'cusr'}),
 5358:              linktitle => $linktitles{$linkcontext}{'listusers'}, 
 5359:             },
 5360: 
 5361:          ]},
 5362: 
 5363:          {categorytitle => 'Administration',
 5364:          items => [ ]},
 5365:        );
 5366: 
 5367:     if ($context eq 'domain'){
 5368:         push(@{  $menu[0]->{items} }, # Single Users
 5369:             {
 5370:              linktext => 'User Access Log',
 5371:              icon => 'document-properties.png',
 5372:              #help => 'Domain_User_Access_Logs',
 5373:              url => '/adm/createuser?action=accesslogs',
 5374:              permission => $permission->{'activity'},
 5375:              linktitle => 'View user access log.',
 5376:             }
 5377:         );
 5378:         
 5379:         push(@{ $menu[2]->{items} }, #Category: Administration
 5380:             {
 5381:              linktext => 'Custom Roles',
 5382:              icon => 'emblem-photos.png',
 5383:              #help => 'Course_Editing_Custom_Roles',
 5384:              url => '/adm/createuser?action=custom',
 5385:              permission => $permission->{'custom'},
 5386:              linktitle => 'Configure a custom role.',
 5387:             },
 5388:             {
 5389:              linktext => 'Authoring Space Requests',
 5390:              icon => 'selfenrl-queue.png',
 5391:              #help => 'Domain_Role_Approvals',
 5392:              url => '/adm/createuser?action=processauthorreq',
 5393:              permission => $permission->{'cusr'},
 5394:              linktitle => 'Approve or reject author role requests',
 5395:             },
 5396:             {
 5397:              linktext => 'LON-CAPA Account Requests',
 5398:              icon => 'list-add.png',
 5399:              #help => 'Domain_Username_Approvals',
 5400:              url => '/adm/createuser?action=processusernamereq',
 5401:              permission => $permission->{'cusr'},
 5402:              linktitle => 'Approve or reject LON-CAPA account requests',
 5403:             },
 5404:             {
 5405:              linktext => 'Change Log',
 5406:              icon => 'document-properties.png',
 5407:              #help => 'Course_User_Logs',
 5408:              url => '/adm/createuser?action=changelogs',
 5409:              permission => ($permission->{'cusr'} || $permission->{'view'}),
 5410:              linktitle => 'View change log.',
 5411:             },
 5412:         );
 5413:         
 5414:     }elsif ($context eq 'course'){
 5415:         my ($cnum,$cdom) = &Apache::lonuserutils::get_course_identity();
 5416: 
 5417:         my %linktext = (
 5418:                          'Course'    => {
 5419:                                           single => 'Add/Modify a Student', 
 5420:                                           drop   => 'Drop Students',
 5421:                                           groups => 'Course Groups',
 5422:                                         },
 5423:                          'Community' => {
 5424:                                           single => 'Add/Modify a Member', 
 5425:                                           drop   => 'Drop Members',
 5426:                                           groups => 'Community Groups',
 5427:                                         },
 5428:                        );
 5429:         $linktext{'Placement'} = $linktext{'Course'};
 5430: 
 5431:         my %linktitle = (
 5432:             'Course' => {
 5433:                   single => 'Add a user with the role of student to this course',
 5434:                   drop   => 'Remove a student from this course.',
 5435:                   groups => 'Manage course groups',
 5436:                         },
 5437:             'Community' => {
 5438:                   single => 'Add a user with the role of member to this community',
 5439:                   drop   => 'Remove a member from this community.',
 5440:                   groups => 'Manage community groups',
 5441:                            },
 5442:         );
 5443: 
 5444:         $linktitle{'Placement'} = $linktitle{'Course'};
 5445: 
 5446:         push(@{ $menu[0]->{items} }, #Category: Single Users
 5447:             {   
 5448:              linktext => $linktext{$crstype}{'single'},
 5449:              #help => 'Course_Add_Student',
 5450:              icon => 'list-add.png',
 5451:              url => '/adm/createuser?action=singlestudent',
 5452:              permission => $permission->{'cusr'},
 5453:              linktitle => $linktitle{$crstype}{'single'},
 5454:             },
 5455:         );
 5456:         
 5457:         push(@{ $menu[1]->{items} }, #Category: Multiple Users 
 5458:             {
 5459:              linktext => $linktext{$crstype}{'drop'},
 5460:              icon => 'edit-undo.png',
 5461:              #help => 'Course_Drop_Student',
 5462:              url => '/adm/createuser?action=drop',
 5463:              permission => $permission->{'cusr'},
 5464:              linktitle => $linktitle{$crstype}{'drop'},
 5465:             },
 5466:         );
 5467:         push(@{ $menu[2]->{items} }, #Category: Administration
 5468:             {
 5469:              linktext => 'Helpdesk Access',
 5470:              icon => 'helpdesk-access.png',
 5471:              #help => 'Course_Helpdesk_Access',
 5472:              url => '/adm/createuser?action=helpdesk',
 5473:              permission => ($permission->{'owner'} || $permission->{'co-owner'}),
 5474:              linktitle => 'Helpdesk access options',
 5475:             },
 5476:             {
 5477:              linktext => 'Custom Roles',
 5478:              icon => 'emblem-photos.png',
 5479:              #help => 'Course_Editing_Custom_Roles',
 5480:              url => '/adm/createuser?action=custom',
 5481:              permission => $permission->{'custom'},
 5482:              linktitle => 'Configure a custom role.',
 5483:             },
 5484:             {
 5485:              linktext => $linktext{$crstype}{'groups'},
 5486:              icon => 'grps.png',
 5487:              #help => 'Course_Manage_Group',
 5488:              url => '/adm/coursegroups?refpage=cusr',
 5489:              permission => $permission->{'grp_manage'},
 5490:              linktitle => $linktitle{$crstype}{'groups'},
 5491:             },
 5492:             {
 5493:              linktext => 'Change Log',
 5494:              icon => 'document-properties.png',
 5495:              #help => 'Course_User_Logs',
 5496:              url => '/adm/createuser?action=changelogs',
 5497:              permission => ($permission->{'view'} || $permission->{'cusr'}),
 5498:              linktitle => 'View change log.',
 5499:             },
 5500:         );
 5501:         if ($env{'course.'.$env{'request.course.id'}.'.internal.selfenroll_approval'}) {
 5502:             push(@{ $menu[2]->{items} },
 5503:                     {
 5504:                      linktext => 'Enrollment Requests',
 5505:                      icon => 'selfenrl-queue.png',
 5506:                      #help => 'Course_Approve_Selfenroll',
 5507:                      url => '/adm/createuser?action=selfenrollqueue',
 5508:                      permission => $permission->{'selfenrolladmin'},
 5509:                      linktitle =>'Approve or reject enrollment requests.',
 5510:                     },
 5511:             );
 5512:         }
 5513:         
 5514:         if (!exists($permission->{'cusr_section'})){
 5515:             if ($crstype ne 'Community') {
 5516:                 push(@{ $menu[2]->{items} },
 5517:                     {
 5518:                      linktext => 'Automated Enrollment',
 5519:                      icon => 'roles.png',
 5520:                      #help => 'Course_Automated_Enrollment',
 5521:                      permission => (&Apache::lonnet::auto_run($cnum,$cdom)
 5522:                                          && (($permission->{'cusr'}) ||
 5523:                                              ($permission->{'view'}))),
 5524:                      url  => '/adm/populate',
 5525:                      linktitle => 'Automated enrollment manager.',
 5526:                     }
 5527:                 );
 5528:             }
 5529:             push(@{ $menu[2]->{items} }, 
 5530:                 {
 5531:                  linktext => 'User Self-Enrollment',
 5532:                  icon => 'self_enroll.png',
 5533:                  #help => 'Course_Self_Enrollment',
 5534:                  url => '/adm/createuser?action=selfenroll',
 5535:                  permission => $permission->{'selfenrolladmin'},
 5536:                  linktitle => 'Configure user self-enrollment.',
 5537:                 },
 5538:             );
 5539:         }
 5540:     } elsif ($context eq 'author') {
 5541:         push(@{ $menu[2]->{items} }, #Category: Administration
 5542:             {
 5543:              linktext => 'Change Log',
 5544:              icon => 'document-properties.png',
 5545:              #help => 'Course_User_Logs',
 5546:              url => '/adm/createuser?action=changelogs',
 5547:              permission => $permission->{'cusr'},
 5548:              linktitle => 'View change log.',
 5549:             },
 5550:         );
 5551:     }
 5552:     return Apache::lonhtmlcommon::generate_menu(@menu);
 5553: #               { text => 'View Log-in History',
 5554: #                 help => 'Course_User_Logins',
 5555: #                 action => 'logins',
 5556: #                 permission => $permission->{'cusr'},
 5557: #               });
 5558: }
 5559: 
 5560: sub restore_prev_selections {
 5561:     my %saveable_parameters = ('srchby'   => 'scalar',
 5562: 			       'srchin'   => 'scalar',
 5563: 			       'srchtype' => 'scalar',
 5564: 			       );
 5565:     &Apache::loncommon::store_settings('user','user_picker',
 5566: 				       \%saveable_parameters);
 5567:     &Apache::loncommon::restore_settings('user','user_picker',
 5568: 					 \%saveable_parameters);
 5569: }
 5570: 
 5571: sub print_selfenroll_menu {
 5572:     my ($r,$context,$cid,$cdom,$cnum,$currsettings,$additional,$readonly) = @_;
 5573:     my $crstype = &Apache::loncommon::course_type();
 5574:     my $formname = 'selfenroll';
 5575:     my $nolink = 1;
 5576:     my ($row,$lt) = &Apache::lonuserutils::get_selfenroll_titles();
 5577:     my $groupslist = &Apache::lonuserutils::get_groupslist();
 5578:     my $setsec_js = 
 5579:         &Apache::lonuserutils::setsections_javascript($formname,$groupslist);
 5580:     my %alerts = &Apache::lonlocal::texthash(
 5581:         acto => 'Activation of self-enrollment was selected for the following domain(s)',
 5582:         butn => 'but no user types have been checked.',
 5583:         wilf => "Please uncheck 'activate' or check at least one type.",
 5584:     );
 5585:     my $disabled;
 5586:     if ($readonly) {
 5587:        $disabled = ' disabled="disabled"';
 5588:     }
 5589:     &js_escape(\%alerts);
 5590:     my $selfenroll_js = <<"ENDSCRIPT";
 5591: function update_types(caller,num) {
 5592:     var delidx = getIndexByName('selfenroll_delete');
 5593:     var actidx = getIndexByName('selfenroll_activate');
 5594:     if (caller == 'selfenroll_all') {
 5595:         var selall;
 5596:         for (var i=0; i<document.$formname.selfenroll_all.length; i++) {
 5597:             if (document.$formname.selfenroll_all[i].checked) {
 5598:                 selall = document.$formname.selfenroll_all[i].value;
 5599:             }
 5600:         }
 5601:         if (selall == 1) {
 5602:             if (delidx != -1) {
 5603:                 if (document.$formname.selfenroll_delete.length) {
 5604:                     for (var j=0; j<document.$formname.selfenroll_delete.length; j++) {
 5605:                         document.$formname.selfenroll_delete[j].checked = true;
 5606:                     }
 5607:                 } else {
 5608:                     document.$formname.elements[delidx].checked = true;
 5609:                 }
 5610:             }
 5611:             if (actidx != -1) {
 5612:                 if (document.$formname.selfenroll_activate.length) {
 5613:                     for (var j=0; j<document.$formname.selfenroll_activate.length; j++) {
 5614:                         document.$formname.selfenroll_activate[j].checked = false;
 5615:                     }
 5616:                 } else {
 5617:                     document.$formname.elements[actidx].checked = false;
 5618:                 }
 5619:             }
 5620:             document.$formname.selfenroll_newdom.selectedIndex = 0; 
 5621:         }
 5622:     }
 5623:     if (caller == 'selfenroll_activate') {
 5624:         if (document.$formname.selfenroll_activate.length) {
 5625:             for (var j=0; j<document.$formname.selfenroll_activate.length; j++) {
 5626:                 if (document.$formname.selfenroll_activate[j].value == num) {
 5627:                     if (document.$formname.selfenroll_activate[j].checked) {
 5628:                         for (var i=0; i<document.$formname.selfenroll_all.length; i++) {
 5629:                             if (document.$formname.selfenroll_all[i].value == '1') {
 5630:                                 document.$formname.selfenroll_all[i].checked = false;
 5631:                             }
 5632:                             if (document.$formname.selfenroll_all[i].value == '0') {
 5633:                                 document.$formname.selfenroll_all[i].checked = true;
 5634:                             }
 5635:                         }
 5636:                     }
 5637:                 }
 5638:             }
 5639:         } else {
 5640:             for (var i=0; i<document.$formname.selfenroll_all.length; i++) {
 5641:                 if (document.$formname.selfenroll_all[i].value == '1') {
 5642:                     document.$formname.selfenroll_all[i].checked = false;
 5643:                 }
 5644:                 if (document.$formname.selfenroll_all[i].value == '0') {
 5645:                     document.$formname.selfenroll_all[i].checked = true;
 5646:                 }
 5647:             }
 5648:         }
 5649:     }
 5650:     if (caller == 'selfenroll_delete') {
 5651:         if (document.$formname.selfenroll_delete.length) {
 5652:             for (var j=0; j<document.$formname.selfenroll_delete.length; j++) {
 5653:                 if (document.$formname.selfenroll_delete[j].value == num) {
 5654:                     if (document.$formname.selfenroll_delete[j].checked) {
 5655:                         var delindex = getIndexByName('selfenroll_types_'+num);
 5656:                         if (delindex != -1) { 
 5657:                             if (document.$formname.elements[delindex].length) {
 5658:                                 for (var k=0; k<document.$formname.elements[delindex].length; k++) {
 5659:                                     document.$formname.elements[delindex][k].checked = false;
 5660:                                 }
 5661:                             } else {
 5662:                                 document.$formname.elements[delindex].checked = false;
 5663:                             }
 5664:                         }
 5665:                     }
 5666:                 }
 5667:             }
 5668:         } else {
 5669:             if (document.$formname.selfenroll_delete.checked) {
 5670:                 var delindex = getIndexByName('selfenroll_types_'+num);
 5671:                 if (delindex != -1) {
 5672:                     if (document.$formname.elements[delindex].length) {
 5673:                         for (var k=0; k<document.$formname.elements[delindex].length; k++) {
 5674:                             document.$formname.elements[delindex][k].checked = false;
 5675:                         }
 5676:                     } else {
 5677:                         document.$formname.elements[delindex].checked = false;
 5678:                     }
 5679:                 }
 5680:             }
 5681:         }
 5682:     }
 5683:     return;
 5684: }
 5685: 
 5686: function validate_types(form) {
 5687:     var needaction = new Array();
 5688:     var countfail = 0;
 5689:     var actidx = getIndexByName('selfenroll_activate');
 5690:     if (actidx != -1) {
 5691:         if (document.$formname.selfenroll_activate.length) {
 5692:             for (var j=0; j<document.$formname.selfenroll_activate.length; j++) {
 5693:                 var num = document.$formname.selfenroll_activate[j].value;
 5694:                 if (document.$formname.selfenroll_activate[j].checked) {
 5695:                     countfail = check_types(num,countfail,needaction)
 5696:                 }
 5697:             }
 5698:         } else {
 5699:             if (document.$formname.selfenroll_activate.checked) {
 5700:                 var num = document.$formname.selfenroll_activate.value;
 5701:                 countfail = check_types(num,countfail,needaction)
 5702:             }
 5703:         }
 5704:     }
 5705:     if (countfail > 0) {
 5706:         var msg = "$alerts{'acto'}\\n";
 5707:         var loopend = needaction.length -1;
 5708:         if (loopend > 0) {
 5709:             for (var m=0; m<loopend; m++) {
 5710:                 msg += needaction[m]+", ";
 5711:             }
 5712:         }
 5713:         msg += needaction[loopend]+"\\n$alerts{'butn'}\\n$alerts{'wilf'}";
 5714:         alert(msg);
 5715:         return; 
 5716:     }
 5717:     setSections(form);
 5718: }
 5719: 
 5720: function check_types(num,countfail,needaction) {
 5721:     var typeidx = getIndexByName('selfenroll_types_'+num);
 5722:     var count = 0;
 5723:     if (typeidx != -1) {
 5724:         if (document.$formname.elements[typeidx].length) {
 5725:             for (var k=0; k<document.$formname.elements[typeidx].length; k++) {
 5726:                 if (document.$formname.elements[typeidx][k].checked) {
 5727:                     count ++;
 5728:                 }
 5729:             }
 5730:         } else {
 5731:             if (document.$formname.elements[typeidx].checked) {
 5732:                 count ++;
 5733:             }
 5734:         }
 5735:         if (count == 0) {
 5736:             var domidx = getIndexByName('selfenroll_dom_'+num);
 5737:             if (domidx != -1) {
 5738:                 var domname = document.$formname.elements[domidx].value;
 5739:                 needaction[countfail] = domname;
 5740:                 countfail ++;
 5741:             }
 5742:         }
 5743:     }
 5744:     return countfail;
 5745: }
 5746: 
 5747: function toggleNotify() {
 5748:     var selfenrollApproval = 0;
 5749:     if (document.$formname.selfenroll_approval.length) {
 5750:         for (var i=0; i<document.$formname.selfenroll_approval.length; i++) {
 5751:             if (document.$formname.selfenroll_approval[i].checked) {
 5752:                 selfenrollApproval = document.$formname.selfenroll_approval[i].value;
 5753:                 break;        
 5754:             }
 5755:         }
 5756:     }
 5757:     if (document.getElementById('notified')) {
 5758:         if (selfenrollApproval == 0) {
 5759:             document.getElementById('notified').style.display='none';
 5760:         } else {
 5761:             document.getElementById('notified').style.display='block';
 5762:         }
 5763:     }
 5764:     return;
 5765: }
 5766: 
 5767: function getIndexByName(item) {
 5768:     for (var i=0;i<document.$formname.elements.length;i++) {
 5769:         if (document.$formname.elements[i].name == item) {
 5770:             return i;
 5771:         }
 5772:     }
 5773:     return -1;
 5774: }
 5775: ENDSCRIPT
 5776: 
 5777:     my $output = '<script type="text/javascript">'."\n".
 5778:                  '// <![CDATA['."\n".
 5779:                  $setsec_js."\n".$selfenroll_js."\n".
 5780:                  '// ]]>'."\n".
 5781:                  '</script>'."\n".
 5782:                  '<h3>'.$lt->{'selfenroll'}.'</h3>'."\n";
 5783:  
 5784:     my $visactions = &cat_visibility();
 5785:     my ($cathash,%cattype);
 5786:     my %domconfig = &Apache::lonnet::get_dom('configuration',['coursecategories'],$cdom);
 5787:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 5788:         $cathash = $domconfig{'coursecategories'}{'cats'};
 5789:         $cattype{'auth'} = $domconfig{'coursecategories'}{'auth'};
 5790:         $cattype{'unauth'} = $domconfig{'coursecategories'}{'unauth'};
 5791:         if ($cattype{'auth'} eq '') {
 5792:             $cattype{'auth'} = 'std';
 5793:         }
 5794:         if ($cattype{'unauth'} eq '') {
 5795:             $cattype{'unauth'} = 'std';
 5796:         }
 5797:     } else {
 5798:         $cathash = {};
 5799:         $cattype{'auth'} = 'std';
 5800:         $cattype{'unauth'} = 'std';
 5801:     }
 5802:     if (($cattype{'auth'} eq 'none') && ($cattype{'unauth'} eq 'none')) {
 5803:         $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
 5804:                   '<br />'.
 5805:                   '<br />'.$visactions->{'take'}.'<ul>'.
 5806:                   '<li>'.$visactions->{'dc_chgconf'}.'</li>'.
 5807:                   '</ul>');
 5808:     } elsif (($cattype{'auth'} !~ /^(std|domonly)$/) && ($cattype{'unauth'} !~ /^(std|domonly)$/)) {
 5809:         if ($currsettings->{'uniquecode'}) {
 5810:             $r->print('<span class="LC_info">'.$visactions->{'vis'}.'</span>');
 5811:         } else {
 5812:             $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
 5813:                   '<br />'.
 5814:                   '<br />'.$visactions->{'take'}.'<ul>'.
 5815:                   '<li>'.$visactions->{'dc_setcode'}.'</li>'.
 5816:                   '</ul><br />');
 5817:         }
 5818:     } else {
 5819:         my ($visible,$cansetvis,$vismsgs) = &visible_in_stdcat($cdom,$cnum,\%domconfig);
 5820:         if (ref($visactions) eq 'HASH') {
 5821:             if ($visible) {
 5822:                 $output .= '<p class="LC_info">'.$visactions->{'vis'}.'</p>';
 5823:            } else {
 5824:                 $output .= '<p class="LC_warning">'.$visactions->{'miss'}.'</p>'
 5825:                           .$visactions->{'yous'}.
 5826:                            '<p>'.$visactions->{'gen'}.'<br />'.$visactions->{'coca'};
 5827:                 if (ref($vismsgs) eq 'ARRAY') {
 5828:                     $output .= '<br />'.$visactions->{'make'}.'<ul>';
 5829:                     foreach my $item (@{$vismsgs}) {
 5830:                         $output .= '<li>'.$visactions->{$item}.'</li>';
 5831:                     }
 5832:                     $output .= '</ul>';
 5833:                 }
 5834:                 $output .= '</p>';
 5835:             }
 5836:         }
 5837:     }
 5838:     my $actionhref = '/adm/createuser';
 5839:     if ($context eq 'domain') {
 5840:         $actionhref = '/adm/modifycourse';
 5841:     }
 5842: 
 5843:     my %noedit;
 5844:     unless ($context eq 'domain') {
 5845:         %noedit = &get_noedit_fields($cdom,$cnum,$crstype,$row);
 5846:     }
 5847:     $output .= '<form name="'.$formname.'" method="post" action="'.$actionhref.'">'."\n".
 5848:                &Apache::lonhtmlcommon::start_pick_box();
 5849:     if (ref($row) eq 'ARRAY') {
 5850:         foreach my $item (@{$row}) {
 5851:             my $title = $item; 
 5852:             if (ref($lt) eq 'HASH') {
 5853:                 $title = $lt->{$item};
 5854:             }
 5855:             $output .= &Apache::lonhtmlcommon::row_title($title);
 5856:             if ($item eq 'types') {
 5857:                 my $curr_types;
 5858:                 if (ref($currsettings) eq 'HASH') {
 5859:                     $curr_types = $currsettings->{'selfenroll_types'};
 5860:                 }
 5861:                 if ($noedit{$item}) {
 5862:                     if ($curr_types eq '*') {
 5863:                         $output .= &mt('Any user in any domain');   
 5864:                     } else {
 5865:                         my @entries = split(/;/,$curr_types);
 5866:                         if (@entries > 0) {
 5867:                             $output .= '<ul>'; 
 5868:                             foreach my $entry (@entries) {
 5869:                                 my ($currdom,$typestr) = split(/:/,$entry);
 5870:                                 next if ($typestr eq '');
 5871:                                 my $domdesc = &Apache::lonnet::domain($currdom);
 5872:                                 my @currinsttypes = split(',',$typestr);
 5873:                                 my ($othertitle,$usertypes,$types) = 
 5874:                                     &Apache::loncommon::sorted_inst_types($currdom);
 5875:                                 if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 5876:                                     $usertypes->{'any'} = &mt('any user'); 
 5877:                                     if (keys(%{$usertypes}) > 0) {
 5878:                                         $usertypes->{'other'} = &mt('other users');
 5879:                                     }
 5880:                                     my @longinsttypes = map { $usertypes->{$_}; } @currinsttypes;
 5881:                                     $output .= '<li>'.$domdesc.':'.join(', ',@longinsttypes).'</li>';
 5882:                                  }
 5883:                             }
 5884:                             $output .= '</ul>';
 5885:                         } else {
 5886:                             $output .= &mt('None');
 5887:                         }
 5888:                     }
 5889:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 5890:                     next;
 5891:                 }
 5892:                 my $showdomdesc = 1;
 5893:                 my $includeempty = 1;
 5894:                 my $num = 0;
 5895:                 $output .= &Apache::loncommon::start_data_table().
 5896:                            &Apache::loncommon::start_data_table_row()
 5897:                            .'<td colspan="2"><span class="LC_nobreak"><label>'
 5898:                            .&mt('Any user in any domain:')
 5899:                            .'&nbsp;<input type="radio" name="selfenroll_all" value="1" ';
 5900:                 if ($curr_types eq '*') {
 5901:                     $output .= ' checked="checked" '; 
 5902:                 }
 5903:                 $output .= 'onchange="javascript:update_types('.
 5904:                            "'selfenroll_all'".');"'.$disabled.' />'.&mt('Yes').'</label>'.
 5905:                            '&nbsp;&nbsp;<input type="radio" name="selfenroll_all" value="0" ';
 5906:                 if ($curr_types ne '*') {
 5907:                     $output .= ' checked="checked" ';
 5908:                 }
 5909:                 $output .= ' onchange="javascript:update_types('.
 5910:                            "'selfenroll_all'".');"'.$disabled.' />'.&mt('No').'</label></td>'.
 5911:                            &Apache::loncommon::end_data_table_row().
 5912:                            &Apache::loncommon::end_data_table().
 5913:                            &mt('Or').'<br />'.
 5914:                            &Apache::loncommon::start_data_table();
 5915:                 my %currdoms;
 5916:                 if ($curr_types eq '') {
 5917:                     $output .= &new_selfenroll_dom_row($cdom,'0');
 5918:                 } elsif ($curr_types ne '*') {
 5919:                     my @entries = split(/;/,$curr_types);
 5920:                     if (@entries > 0) {
 5921:                         foreach my $entry (@entries) {
 5922:                             my ($currdom,$typestr) = split(/:/,$entry);
 5923:                             $currdoms{$currdom} = 1;
 5924:                             my $domdesc = &Apache::lonnet::domain($currdom);
 5925:                             my @currinsttypes = split(',',$typestr);
 5926:                             $output .= &Apache::loncommon::start_data_table_row()
 5927:                                        .'<td valign="top"><span class="LC_nobreak">'.&mt('Domain:').'<b>'
 5928:                                        .'&nbsp;'.$domdesc.' ('.$currdom.')'
 5929:                                        .'</b><input type="hidden" name="selfenroll_dom_'.$num
 5930:                                        .'" value="'.$currdom.'" /></span><br />'
 5931:                                        .'<span class="LC_nobreak"><label><input type="checkbox" '
 5932:                                        .'name="selfenroll_delete" value="'.$num.'" onchange="javascript:update_types('."'selfenroll_delete','$num'".');"'.$disabled.' />'
 5933:                                        .&mt('Delete').'</label></span></td>';
 5934:                             $output .= '<td valign="top">&nbsp;&nbsp;'.&mt('User types:').'<br />'
 5935:                                        .&selfenroll_inst_types($num,$currdom,\@currinsttypes,$readonly).'</td>'
 5936:                                        .&Apache::loncommon::end_data_table_row();
 5937:                             $num ++;
 5938:                         }
 5939:                     }
 5940:                 }
 5941:                 my $add_domtitle = &mt('Users in additional domain:');
 5942:                 if ($curr_types eq '*') { 
 5943:                     $add_domtitle = &mt('Users in specific domain:');
 5944:                 } elsif ($curr_types eq '') {
 5945:                     $add_domtitle = &mt('Users in other domain:');
 5946:                 }
 5947:                 $output .= &Apache::loncommon::start_data_table_row()
 5948:                            .'<td colspan="2"><span class="LC_nobreak">'.$add_domtitle.'</span><br />'
 5949:                            .&Apache::loncommon::select_dom_form('','selfenroll_newdom',
 5950:                                                                 $includeempty,$showdomdesc,'','','',$readonly)
 5951:                            .'<input type="hidden" name="selfenroll_types_total" value="'.$num.'" />'
 5952:                            .'</td>'.&Apache::loncommon::end_data_table_row()
 5953:                            .&Apache::loncommon::end_data_table();
 5954:             } elsif ($item eq 'registered') {
 5955:                 my ($regon,$regoff);
 5956:                 my $registered;
 5957:                 if (ref($currsettings) eq 'HASH') {
 5958:                     $registered = $currsettings->{'selfenroll_registered'};
 5959:                 }
 5960:                 if ($noedit{$item}) {
 5961:                     if ($registered) {
 5962:                         $output .= &mt('Must be registered in course');
 5963:                     } else {
 5964:                         $output .= &mt('No requirement');
 5965:                     }
 5966:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 5967:                     next;
 5968:                 }
 5969:                 if ($registered) {
 5970:                     $regon = ' checked="checked" ';
 5971:                     $regoff = '';
 5972:                 } else {
 5973:                     $regon = '';
 5974:                     $regoff = ' checked="checked" ';
 5975:                 }
 5976:                 $output .= '<label>'.
 5977:                            '<input type="radio" name="selfenroll_registered" value="1"'.$regon.$disabled.' />'.
 5978:                            &mt('Yes').'</label>&nbsp;&nbsp;<label>'.
 5979:                            '<input type="radio" name="selfenroll_registered" value="0"'.$regoff.$disabled.' />'.
 5980:                            &mt('No').'</label>';
 5981:             } elsif ($item eq 'enroll_dates') {
 5982:                 my ($starttime,$endtime);
 5983:                 if (ref($currsettings) eq 'HASH') {
 5984:                     $starttime = $currsettings->{'selfenroll_start_date'};
 5985:                     $endtime = $currsettings->{'selfenroll_end_date'};
 5986:                     if ($starttime eq '') {
 5987:                         $starttime = $currsettings->{'default_enrollment_start_date'};
 5988:                     }
 5989:                     if ($endtime eq '') {
 5990:                         $endtime = $currsettings->{'default_enrollment_end_date'};
 5991:                     }
 5992:                 }
 5993:                 if ($noedit{$item}) {
 5994:                     $output .= &mt('From: [_1], to: [_2]',&Apache::lonlocal::locallocaltime($starttime),
 5995:                                                           &Apache::lonlocal::locallocaltime($endtime));
 5996:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 5997:                     next;
 5998:                 }
 5999:                 my $startform =
 6000:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_start_date',$starttime,
 6001:                                       $disabled,undef,undef,undef,undef,undef,undef,$nolink);
 6002:                 my $endform =
 6003:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_end_date',$endtime,
 6004:                                       $disabled,undef,undef,undef,undef,undef,undef,$nolink);
 6005:                 $output .= &selfenroll_date_forms($startform,$endform);
 6006:             } elsif ($item eq 'access_dates') {
 6007:                 my ($starttime,$endtime);
 6008:                 if (ref($currsettings) eq 'HASH') {
 6009:                     $starttime = $currsettings->{'selfenroll_start_access'};
 6010:                     $endtime = $currsettings->{'selfenroll_end_access'};
 6011:                     if ($starttime eq '') {
 6012:                         $starttime = $currsettings->{'default_enrollment_start_date'};
 6013:                     }
 6014:                     if ($endtime eq '') {
 6015:                         $endtime = $currsettings->{'default_enrollment_end_date'};
 6016:                     }
 6017:                 }
 6018:                 if ($noedit{$item}) {
 6019:                     $output .= &mt('From: [_1], to: [_2]',&Apache::lonlocal::locallocaltime($starttime),
 6020:                                                           &Apache::lonlocal::locallocaltime($endtime));
 6021:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 6022:                     next;
 6023:                 }
 6024:                 my $startform =
 6025:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_start_access',$starttime,
 6026:                                       $disabled,undef,undef,undef,undef,undef,undef,$nolink);
 6027:                 my $endform =
 6028:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_end_access',$endtime,
 6029:                                       $disabled,undef,undef,undef,undef,undef,undef,$nolink);
 6030:                 $output .= &selfenroll_date_forms($startform,$endform);
 6031:             } elsif ($item eq 'section') {
 6032:                 my $currsec;
 6033:                 if (ref($currsettings) eq 'HASH') {
 6034:                     $currsec = $currsettings->{'selfenroll_section'};
 6035:                 }
 6036:                 my %sections_count = &Apache::loncommon::get_sections($cdom,$cnum);
 6037:                 my $newsecval;
 6038:                 if ($currsec ne 'none' && $currsec ne '') {
 6039:                     if (!defined($sections_count{$currsec})) {
 6040:                         $newsecval = $currsec;
 6041:                     }
 6042:                 }
 6043:                 if ($noedit{$item}) {
 6044:                     if ($currsec ne '') {
 6045:                         $output .= $currsec;
 6046:                     } else {
 6047:                         $output .= &mt('No specific section');
 6048:                     }
 6049:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 6050:                     next;
 6051:                 }
 6052:                 my $sections_select = 
 6053:                     &Apache::lonuserutils::course_sections(\%sections_count,'st',$currsec,$disabled);
 6054:                 $output .= '<table class="LC_createuser">'."\n".
 6055:                            '<tr class="LC_section_row">'."\n".
 6056:                            '<td align="center">'.&mt('Existing sections')."\n".
 6057:                            '<br />'.$sections_select.'</td><td align="center">'.
 6058:                            &mt('New section').'<br />'."\n".
 6059:                            '<input type="text" name="newsec" size="15" value="'.$newsecval.'"'.$disabled.' />'."\n".
 6060:                            '<input type="hidden" name="sections" value="" />'."\n".
 6061:                            '</td></tr></table>'."\n";
 6062:             } elsif ($item eq 'approval') {
 6063:                 my ($currnotified,$currapproval,%appchecked);
 6064:                 my %selfdescs = &Apache::lonuserutils::selfenroll_default_descs();
 6065:                 if (ref($currsettings) eq 'HASH') {
 6066:                     $currnotified = $currsettings->{'selfenroll_notifylist'};
 6067:                     $currapproval = $currsettings->{'selfenroll_approval'};
 6068:                 }
 6069:                 if ($currapproval !~ /^[012]$/) {
 6070:                     $currapproval = 0;
 6071:                 }
 6072:                 if ($noedit{$item}) {
 6073:                     $output .=  $selfdescs{'approval'}{$currapproval}.
 6074:                                 '<br />'.&mt('(Set by Domain Coordinator)');
 6075:                     next;
 6076:                 }
 6077:                 $appchecked{$currapproval} = ' checked="checked"';
 6078:                 for my $i (0..2) {
 6079:                     $output .= '<label>'.
 6080:                                '<input type="radio" name="selfenroll_approval" value="'.$i.'"'.
 6081:                                $appchecked{$i}.' onclick="toggleNotify();"'.$disabled.' />'.
 6082:                                $selfdescs{'approval'}{$i}.'</label>'.('&nbsp;'x2);
 6083:                 }
 6084:                 my %advhash = &Apache::lonnet::get_course_adv_roles($cid,1);
 6085:                 my (@ccs,%notified);
 6086:                 my $ccrole = 'cc';
 6087:                 if ($crstype eq 'Community') {
 6088:                     $ccrole = 'co';
 6089:                 }
 6090:                 if ($advhash{$ccrole}) {
 6091:                     @ccs = split(/,/,$advhash{$ccrole});
 6092:                 }
 6093:                 if ($currnotified) {
 6094:                     foreach my $current (split(/,/,$currnotified)) {
 6095:                         $notified{$current} = 1;
 6096:                         if (!grep(/^\Q$current\E$/,@ccs)) {
 6097:                             push(@ccs,$current);
 6098:                         }
 6099:                     }
 6100:                 }
 6101:                 if (@ccs) {
 6102:                     my $style;
 6103:                     unless ($currapproval) {
 6104:                         $style = ' style="display: none;"'; 
 6105:                     }
 6106:                     $output .= '<br /><div id="notified"'.$style.'>'.
 6107:                                &mt('Personnel to be notified when an enrollment request needs approval, or has been approved:').'&nbsp;'.
 6108:                                &Apache::loncommon::start_data_table().
 6109:                                &Apache::loncommon::start_data_table_row();
 6110:                     my $count = 0;
 6111:                     my $numcols = 4;
 6112:                     foreach my $cc (sort(@ccs)) {
 6113:                         my $notifyon;
 6114:                         my ($ccuname,$ccudom) = split(/:/,$cc);
 6115:                         if ($notified{$cc}) {
 6116:                             $notifyon = ' checked="checked" ';
 6117:                         }
 6118:                         if ($count && !$count%$numcols) {
 6119:                             $output .= &Apache::loncommon::end_data_table_row().
 6120:                                        &Apache::loncommon::start_data_table_row()
 6121:                         }
 6122:                         $output .= '<td><span class="LC_nobreak"><label>'.
 6123:                                    '<input type="checkbox" name="selfenroll_notify"'.$notifyon.' value="'.$cc.'"'.$disabled.' />'.
 6124:                                    &Apache::loncommon::plainname($ccuname,$ccudom).
 6125:                                    '</label></span></td>';
 6126:                         $count ++;
 6127:                     }
 6128:                     my $rem = $count%$numcols;
 6129:                     if ($rem) {
 6130:                         my $emptycols = $numcols - $rem;
 6131:                         for (my $i=0; $i<$emptycols; $i++) { 
 6132:                             $output .= '<td>&nbsp;</td>';
 6133:                         }
 6134:                     }
 6135:                     $output .= &Apache::loncommon::end_data_table_row().
 6136:                                &Apache::loncommon::end_data_table().
 6137:                                '</div>';
 6138:                 }
 6139:             } elsif ($item eq 'limit') {
 6140:                 my ($crslimit,$selflimit,$nolimit,$currlim,$currcap);
 6141:                 if (ref($currsettings) eq 'HASH') {
 6142:                     $currlim = $currsettings->{'selfenroll_limit'};
 6143:                     $currcap = $currsettings->{'selfenroll_cap'};
 6144:                 }
 6145:                 if ($noedit{$item}) {
 6146:                     if (($currlim eq 'allstudents') || ($currlim eq 'selfenrolled')) {
 6147:                         if ($currlim eq 'allstudents') {
 6148:                             $output .= &mt('Limit by total students');
 6149:                         } elsif ($currlim eq 'selfenrolled') {
 6150:                             $output .= &mt('Limit by total self-enrolled students');
 6151:                         }
 6152:                         $output .= ' '.&mt('Maximum: [_1]',$currcap).
 6153:                                    '<br />'.&mt('(Set by Domain Coordinator)');
 6154:                     } else {
 6155:                         $output .= &mt('No limit').'<br />'.&mt('(Set by Domain Coordinator)');
 6156:                     }
 6157:                     next;
 6158:                 }
 6159:                 if ($currlim eq 'allstudents') {
 6160:                     $crslimit = ' checked="checked" ';
 6161:                     $selflimit = ' ';
 6162:                     $nolimit = ' ';
 6163:                 } elsif ($currlim eq 'selfenrolled') {
 6164:                     $crslimit = ' ';
 6165:                     $selflimit = ' checked="checked" ';
 6166:                     $nolimit = ' '; 
 6167:                 } else {
 6168:                     $crslimit = ' ';
 6169:                     $selflimit = ' ';
 6170:                     $nolimit = ' checked="checked" ';
 6171:                 }
 6172:                 $output .= '<table><tr><td><label>'.
 6173:                            '<input type="radio" name="selfenroll_limit" value="none"'.$nolimit.$disabled.'/>'.
 6174:                            &mt('No limit').'</label></td><td><label>'.
 6175:                            '<input type="radio" name="selfenroll_limit" value="allstudents"'.$crslimit.$disabled.'/>'.
 6176:                            &mt('Limit by total students').'</label></td><td><label>'.
 6177:                            '<input type="radio" name="selfenroll_limit" value="selfenrolled"'.$selflimit.$disabled.'/>'.
 6178:                            &mt('Limit by total self-enrolled students').
 6179:                            '</td></tr><tr>'.
 6180:                            '<td>&nbsp;</td><td colspan="2"><span class="LC_nobreak">'.
 6181:                            ('&nbsp;'x3).&mt('Maximum number allowed: ').
 6182:                            '<input type="text" name="selfenroll_cap" size = "5" value="'.$currcap.'"'.$disabled.' /></td></tr></table>';
 6183:             }
 6184:             $output .= &Apache::lonhtmlcommon::row_closure(1);
 6185:         }
 6186:     }
 6187:     $output .= &Apache::lonhtmlcommon::end_pick_box().'<br />';
 6188:     unless ($readonly) {
 6189:         $output .= '<input type="button" name="selfenrollconf" value="'
 6190:                    .&mt('Save').'" onclick="validate_types(this.form);" />';
 6191:     }
 6192:     $output .= '<input type="hidden" name="action" value="selfenroll" />'
 6193:               .'<input type="hidden" name="state" value="done" />'."\n"
 6194:               .$additional.'</form>';
 6195:     $r->print($output);
 6196:     return;
 6197: }
 6198: 
 6199: sub get_noedit_fields {
 6200:     my ($cdom,$cnum,$crstype,$row) = @_;
 6201:     my %noedit;
 6202:     if (ref($row) eq 'ARRAY') {
 6203:         my %settings = &Apache::lonnet::get('environment',['internal.coursecode','internal.textbook',
 6204:                                                            'internal.selfenrollmgrdc',
 6205:                                                            'internal.selfenrollmgrcc'],$cdom,$cnum);
 6206:         my $type = &Apache::lonuserutils::get_extended_type($cdom,$cnum,$crstype,\%settings);
 6207:         my (%specific_managebydc,%specific_managebycc,%default_managebydc);
 6208:         map { $specific_managebydc{$_} = 1; } (split(/,/,$settings{'internal.selfenrollmgrdc'}));
 6209:         map { $specific_managebycc{$_} = 1; } (split(/,/,$settings{'internal.selfenrollmgrcc'}));
 6210:         my %domdefaults = &Apache::lonnet::get_domain_defaults($cdom);
 6211:         map { $default_managebydc{$_} = 1; } (split(/,/,$domdefaults{$type.'selfenrolladmdc'}));
 6212: 
 6213:         foreach my $item (@{$row}) {
 6214:             next if ($specific_managebycc{$item});
 6215:             if (($specific_managebydc{$item}) || ($default_managebydc{$item})) {
 6216:                 $noedit{$item} = 1;
 6217:             }
 6218:         }
 6219:     }
 6220:     return %noedit;
 6221: } 
 6222: 
 6223: sub visible_in_stdcat {
 6224:     my ($cdom,$cnum,$domconf) = @_;
 6225:     my ($cathash,%settable,@vismsgs,$cansetvis,$visible);
 6226:     unless (ref($domconf) eq 'HASH') {
 6227:         return ($visible,$cansetvis,\@vismsgs);
 6228:     }
 6229:     if (ref($domconf->{'coursecategories'}) eq 'HASH') {
 6230:         if ($domconf->{'coursecategories'}{'togglecats'} eq 'crs') {
 6231:             $settable{'togglecats'} = 1;
 6232:         }
 6233:         if ($domconf->{'coursecategories'}{'categorize'} eq 'crs') {
 6234:             $settable{'categorize'} = 1;
 6235:         }
 6236:         $cathash = $domconf->{'coursecategories'}{'cats'};
 6237:     }
 6238:     if ($settable{'togglecats'} && $settable{'categorize'}) {
 6239:         $cansetvis = &mt('You are able to both assign a course category and choose to exclude this course from the catalog.');   
 6240:     } elsif ($settable{'togglecats'}) {
 6241:         $cansetvis = &mt('You are able to choose to exclude this course from the catalog, but only a Domain Coordinator may assign a course category.'); 
 6242:     } elsif ($settable{'categorize'}) {
 6243:         $cansetvis = &mt('You may assign a course category, but only a Domain Coordinator may choose to exclude this course from the catalog.');  
 6244:     } else {
 6245:         $cansetvis = &mt('Only a Domain Coordinator may assign a course category or choose to exclude this course from the catalog.'); 
 6246:     }
 6247:      
 6248:     my %currsettings =
 6249:         &Apache::lonnet::get('environment',['hidefromcat','categories','internal.coursecode'],
 6250:                              $cdom,$cnum);
 6251:     $visible = 0;
 6252:     if ($currsettings{'internal.coursecode'} ne '') {
 6253:         if (ref($domconf->{'coursecategories'}) eq 'HASH') {
 6254:             $cathash = $domconf->{'coursecategories'}{'cats'};
 6255:             if (ref($cathash) eq 'HASH') {
 6256:                 if ($cathash->{'instcode::0'} eq '') {
 6257:                     push(@vismsgs,'dc_addinst'); 
 6258:                 } else {
 6259:                     $visible = 1;
 6260:                 }
 6261:             } else {
 6262:                 $visible = 1;
 6263:             }
 6264:         } else {
 6265:             $visible = 1;
 6266:         }
 6267:     } else {
 6268:         if (ref($cathash) eq 'HASH') {
 6269:             if ($cathash->{'instcode::0'} ne '') {
 6270:                 push(@vismsgs,'dc_instcode');
 6271:             }
 6272:         } else {
 6273:             push(@vismsgs,'dc_instcode');
 6274:         }
 6275:     }
 6276:     if ($currsettings{'categories'} ne '') {
 6277:         my $cathash;
 6278:         if (ref($domconf->{'coursecategories'}) eq 'HASH') {
 6279:             $cathash = $domconf->{'coursecategories'}{'cats'};
 6280:             if (ref($cathash) eq 'HASH') {
 6281:                 if (keys(%{$cathash}) == 0) {
 6282:                     push(@vismsgs,'dc_catalog');
 6283:                 } elsif ((keys(%{$cathash}) == 1) && ($cathash->{'instcode::0'} ne '')) {
 6284:                     push(@vismsgs,'dc_categories');
 6285:                 } else {
 6286:                     my @currcategories = split('&',$currsettings{'categories'});
 6287:                     my $matched = 0;
 6288:                     foreach my $cat (@currcategories) {
 6289:                         if ($cathash->{$cat} ne '') {
 6290:                             $visible = 1;
 6291:                             $matched = 1;
 6292:                             last;
 6293:                         }
 6294:                     }
 6295:                     if (!$matched) {
 6296:                         if ($settable{'categorize'}) { 
 6297:                             push(@vismsgs,'chgcat');
 6298:                         } else {
 6299:                             push(@vismsgs,'dc_chgcat');
 6300:                         }
 6301:                     }
 6302:                 }
 6303:             }
 6304:         }
 6305:     } else {
 6306:         if (ref($cathash) eq 'HASH') {
 6307:             if ((keys(%{$cathash}) > 1) || 
 6308:                 (keys(%{$cathash}) == 1) && ($cathash->{'instcode::0'} eq '')) {
 6309:                 if ($settable{'categorize'}) {
 6310:                     push(@vismsgs,'addcat');
 6311:                 } else {
 6312:                     push(@vismsgs,'dc_addcat');
 6313:                 }
 6314:             }
 6315:         }
 6316:     }
 6317:     if ($currsettings{'hidefromcat'} eq 'yes') {
 6318:         $visible = 0;
 6319:         if ($settable{'togglecats'}) {
 6320:             unshift(@vismsgs,'unhide');
 6321:         } else {
 6322:             unshift(@vismsgs,'dc_unhide')
 6323:         }
 6324:     }
 6325:     return ($visible,$cansetvis,\@vismsgs);
 6326: }
 6327: 
 6328: sub cat_visibility {
 6329:     my %visactions = &Apache::lonlocal::texthash(
 6330:                    vis => 'This course/community currently appears in the Course/Community Catalog for this domain.',
 6331:                    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.',
 6332:                    miss => 'This course/community does not currently appear in the Course/Community Catalog for this domain.',
 6333:                    none => 'Display of a course catalog is disabled for this domain.',
 6334:                    yous => 'You should remedy this if you plan to allow self-enrollment, otherwise students will have difficulty finding this course.',
 6335:                    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.',
 6336:                    make => 'Make any changes to self-enrollment settings below, click "Save", then take action to include the course in the Catalog:',
 6337:                    take => 'Take the following action to ensure the course appears in the Catalog:',
 6338:                    dc_chgconf => 'Ask a domain coordinator to change the Catalog type for this domain.',
 6339:                    dc_setcode => 'Ask a domain coordinator to assign a six character code to the course',
 6340:                    dc_unhide  => 'Ask a domain coordinator to change the "Exclude from course catalog" setting.',
 6341:                    dc_addinst => 'Ask a domain coordinator to enable display the catalog of "Official courses (with institutional codes)".',
 6342:                    dc_instcode => 'Ask a domain coordinator to assign an institutional code (if this is an official course).',
 6343:                    dc_catalog  => 'Ask a domain coordinator to enable or create at least one course category in the domain.',
 6344:                    dc_categories => 'Ask a domain coordinator to create a hierarchy of categories and sub categories for courses in the domain.',
 6345:                    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',
 6346:                    dc_addcat => 'Ask a domain coordinator to assign a category to the course.',
 6347:     );
 6348:     $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>"');
 6349:     $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>"');
 6350:     $visactions{'addcat'} = &mt('Use [_1]Categorize course[_2] to assign a category to the course.','"<a href="/adm/courseprefs?phase=display&actions=courseinfo">','</a>"');
 6351:     return \%visactions;
 6352: }
 6353: 
 6354: sub new_selfenroll_dom_row {
 6355:     my ($newdom,$num) = @_;
 6356:     my $domdesc = &Apache::lonnet::domain($newdom);
 6357:     my $output;
 6358:     if ($domdesc ne '') {
 6359:         $output .= &Apache::loncommon::start_data_table_row()
 6360:                    .'<td valign="top"><span class="LC_nobreak">'.&mt('Domain:').'&nbsp;<b>'.$domdesc
 6361:                    .' ('.$newdom.')</b><input type="hidden" name="selfenroll_dom_'.$num
 6362:                    .'" value="'.$newdom.'" /></span><br />'
 6363:                    .'<span class="LC_nobreak"><label><input type="checkbox" '
 6364:                    .'name="selfenroll_activate" value="'.$num.'" '
 6365:                    .'onchange="javascript:update_types('
 6366:                    ."'selfenroll_activate','$num'".');" />'
 6367:                    .&mt('Activate').'</label></span></td>';
 6368:         my @currinsttypes;
 6369:         $output .= '<td>'.&mt('User types:').'<br />'
 6370:                    .&selfenroll_inst_types($num,$newdom,\@currinsttypes).'</td>'
 6371:                    .&Apache::loncommon::end_data_table_row();
 6372:     }
 6373:     return $output;
 6374: }
 6375: 
 6376: sub selfenroll_inst_types {
 6377:     my ($num,$currdom,$currinsttypes,$readonly) = @_;
 6378:     my $output;
 6379:     my $numinrow = 4;
 6380:     my $count = 0;
 6381:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($currdom);
 6382:     my $othervalue = 'any';
 6383:     my $disabled;
 6384:     if ($readonly) {
 6385:         $disabled = ' disabled="disabled"';
 6386:     }
 6387:     if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 6388:         if (keys(%{$usertypes}) > 0) {
 6389:             $othervalue = 'other';
 6390:         }
 6391:         $output .= '<table><tr>';
 6392:         foreach my $type (@{$types}) {
 6393:             if (($count > 0) && ($count%$numinrow == 0)) {
 6394:                 $output .= '</tr><tr>';
 6395:             }
 6396:             if (defined($usertypes->{$type})) {
 6397:                 my $esc_type = &escape($type);
 6398:                 $output .= '<td><span class="LC_nobreak"><label><input type = "checkbox" value="'.
 6399:                            $esc_type.'" ';
 6400:                 if (ref($currinsttypes) eq 'ARRAY') {
 6401:                     if (@{$currinsttypes} > 0) {
 6402:                         if (grep(/^any$/,@{$currinsttypes})) {
 6403:                             $output .= 'checked="checked"';
 6404:                         } elsif (grep(/^\Q$esc_type\E$/,@{$currinsttypes})) {
 6405:                             $output .= 'checked="checked"';
 6406:                         }
 6407:                     } else {
 6408:                         $output .= 'checked="checked"';
 6409:                     }
 6410:                 }
 6411:                 $output .= ' name="selfenroll_types_'.$num.'"'.$disabled.' />'.$usertypes->{$type}.'</label></span></td>';
 6412:             }
 6413:             $count ++;
 6414:         }
 6415:         if (($count > 0) && ($count%$numinrow == 0)) {
 6416:             $output .= '</tr><tr>';
 6417:         }
 6418:         $output .= '<td><span class="LC_nobreak"><label><input type = "checkbox" value="'.$othervalue.'"';
 6419:         if (ref($currinsttypes) eq 'ARRAY') {
 6420:             if (@{$currinsttypes} > 0) {
 6421:                 if (grep(/^any$/,@{$currinsttypes})) { 
 6422:                     $output .= ' checked="checked"';
 6423:                 } elsif ($othervalue eq 'other') {
 6424:                     if (grep(/^\Q$othervalue\E$/,@{$currinsttypes})) {
 6425:                         $output .= ' checked="checked"';
 6426:                     }
 6427:                 }
 6428:             } else {
 6429:                 $output .= ' checked="checked"';
 6430:             }
 6431:         } else {
 6432:             $output .= ' checked="checked"';
 6433:         }
 6434:         $output .= ' name="selfenroll_types_'.$num.'"'.$disabled.' />'.$othertitle.'</label></span></td></tr></table>';
 6435:     }
 6436:     return $output;
 6437: }
 6438: 
 6439: sub selfenroll_date_forms {
 6440:     my ($startform,$endform) = @_;
 6441:     my $output .= &Apache::lonhtmlcommon::start_pick_box()."\n".
 6442:                   &Apache::lonhtmlcommon::row_title(&mt('Start date'),
 6443:                                                     'LC_oddrow_value')."\n".
 6444:                   $startform."\n".
 6445:                   &Apache::lonhtmlcommon::row_closure(1).
 6446:                   &Apache::lonhtmlcommon::row_title(&mt('End date'),
 6447:                                                    'LC_oddrow_value')."\n".
 6448:                   $endform."\n".
 6449:                   &Apache::lonhtmlcommon::row_closure(1).
 6450:                   &Apache::lonhtmlcommon::end_pick_box();
 6451:     return $output;
 6452: }
 6453: 
 6454: sub print_userchangelogs_display {
 6455:     my ($r,$context,$permission,$brcrum) = @_;
 6456:     my $formname = 'rolelog';
 6457:     my ($username,$domain,$crstype,$viewablesec,%roleslog);
 6458:     if ($context eq 'domain') {
 6459:         $domain = $env{'request.role.domain'};
 6460:         %roleslog=&Apache::lonnet::dump_dom('nohist_rolelog',$domain);
 6461:     } else {
 6462:         if ($context eq 'course') { 
 6463:             $domain = $env{'course.'.$env{'request.course.id'}.'.domain'};
 6464:             $username = $env{'course.'.$env{'request.course.id'}.'.num'};
 6465:             $crstype = &Apache::loncommon::course_type();
 6466:             $viewablesec = &Apache::lonuserutils::viewable_section($permission);
 6467:             my %saveable_parameters = ('show' => 'scalar',);
 6468:             &Apache::loncommon::store_course_settings('roles_log',
 6469:                                                       \%saveable_parameters);
 6470:             &Apache::loncommon::restore_course_settings('roles_log',
 6471:                                                         \%saveable_parameters);
 6472:         } elsif ($context eq 'author') {
 6473:             $domain = $env{'user.domain'}; 
 6474:             if ($env{'request.role'} =~ m{^au\./\Q$domain\E/$}) {
 6475:                 $username = $env{'user.name'};
 6476:             } else {
 6477:                 undef($domain);
 6478:             }
 6479:         }
 6480:         if ($domain ne '' && $username ne '') { 
 6481:             %roleslog=&Apache::lonnet::dump('nohist_rolelog',$domain,$username);
 6482:         }
 6483:     }
 6484:     if ((keys(%roleslog))[0]=~/^error\:/) { undef(%roleslog); }
 6485: 
 6486:     my $helpitem;
 6487:     if ($context eq 'course') {
 6488:         $helpitem = 'Course_User_Logs';
 6489:     }
 6490:     push (@{$brcrum},
 6491:              {href => '/adm/createuser?action=changelogs',
 6492:               text => 'User Management Logs',
 6493:               help => $helpitem});
 6494:     my $bread_crumbs_component = 'User Changes';
 6495:     my $args = { bread_crumbs           => $brcrum,
 6496:                  bread_crumbs_component => $bread_crumbs_component};
 6497: 
 6498:     # Create navigation javascript
 6499:     my $jsnav = &userlogdisplay_js($formname);
 6500: 
 6501:     my $jscript = (<<ENDSCRIPT);
 6502: <script type="text/javascript">
 6503: // <![CDATA[
 6504: $jsnav
 6505: // ]]>
 6506: </script>
 6507: ENDSCRIPT
 6508: 
 6509:     # print page header
 6510:     $r->print(&header($jscript,$args));
 6511: 
 6512:     # set defaults
 6513:     my $now = time();
 6514:     my $defstart = $now - (7*24*3600); #7 days ago 
 6515:     my %defaults = (
 6516:                      page               => '1',
 6517:                      show               => '10',
 6518:                      role               => 'any',
 6519:                      chgcontext         => 'any',
 6520:                      rolelog_start_date => $defstart,
 6521:                      rolelog_end_date   => $now,
 6522:                    );
 6523:     my $more_records = 0;
 6524: 
 6525:     # set current
 6526:     my %curr;
 6527:     foreach my $item ('show','page','role','chgcontext') {
 6528:         $curr{$item} = $env{'form.'.$item};
 6529:     }
 6530:     my ($startdate,$enddate) = 
 6531:         &Apache::lonuserutils::get_dates_from_form('rolelog_start_date','rolelog_end_date');
 6532:     $curr{'rolelog_start_date'} = $startdate;
 6533:     $curr{'rolelog_end_date'} = $enddate;
 6534:     foreach my $key (keys(%defaults)) {
 6535:         if ($curr{$key} eq '') {
 6536:             $curr{$key} = $defaults{$key};
 6537:         }
 6538:     }
 6539:     my (%whodunit,%changed,$version);
 6540:     ($version) = ($r->dir_config('lonVersion') =~ /^([\d\.]+)\-/);
 6541:     my ($minshown,$maxshown);
 6542:     $minshown = 1;
 6543:     my $count = 0;
 6544:     if ($curr{'show'} =~ /\D/) {
 6545:         $curr{'page'} = 1;
 6546:     } else {
 6547:         $maxshown = $curr{'page'} * $curr{'show'};
 6548:         if ($curr{'page'} > 1) {
 6549:             $minshown = 1 + ($curr{'page'} - 1) * $curr{'show'};
 6550:         }
 6551:     }
 6552: 
 6553:     # Form Header
 6554:     $r->print('<form action="/adm/createuser" method="post" name="'.$formname.'">'.
 6555:               &role_display_filter($context,$formname,$domain,$username,\%curr,
 6556:                                    $version,$crstype));
 6557: 
 6558:     my $showntableheader = 0;
 6559: 
 6560:     # Table Header
 6561:     my $tableheader = 
 6562:         &Apache::loncommon::start_data_table_header_row()
 6563:        .'<th>&nbsp;</th>'
 6564:        .'<th>'.&mt('When').'</th>'
 6565:        .'<th>'.&mt('Who made the change').'</th>'
 6566:        .'<th>'.&mt('Changed User').'</th>'
 6567:        .'<th>'.&mt('Role').'</th>';
 6568: 
 6569:     if ($context eq 'course') {
 6570:         $tableheader .= '<th>'.&mt('Section').'</th>';
 6571:     }
 6572:     $tableheader .=
 6573:         '<th>'.&mt('Context').'</th>'
 6574:        .'<th>'.&mt('Start').'</th>'
 6575:        .'<th>'.&mt('End').'</th>'
 6576:        .&Apache::loncommon::end_data_table_header_row();
 6577: 
 6578:     # Display user change log data
 6579:     foreach my $id (sort { $roleslog{$b}{'exe_time'}<=>$roleslog{$a}{'exe_time'} } (keys(%roleslog))) {
 6580:         next if (($roleslog{$id}{'exe_time'} < $curr{'rolelog_start_date'}) ||
 6581:                  ($roleslog{$id}{'exe_time'} > $curr{'rolelog_end_date'}));
 6582:         if ($curr{'show'} !~ /\D/) {
 6583:             if ($count >= $curr{'page'} * $curr{'show'}) {
 6584:                 $more_records = 1;
 6585:                 last;
 6586:             }
 6587:         }
 6588:         if ($curr{'role'} ne 'any') {
 6589:             next if ($roleslog{$id}{'logentry'}{'role'} ne $curr{'role'}); 
 6590:         }
 6591:         if ($curr{'chgcontext'} ne 'any') {
 6592:             if ($curr{'chgcontext'} eq 'selfenroll') {
 6593:                 next if (!$roleslog{$id}{'logentry'}{'selfenroll'});
 6594:             } else {
 6595:                 next if ($roleslog{$id}{'logentry'}{'context'} ne $curr{'chgcontext'});
 6596:             }
 6597:         }
 6598:         if (($context eq 'course') && ($viewablesec ne '')) {
 6599:             next if ($roleslog{$id}{'logentry'}{'section'} ne $viewablesec);
 6600:         }
 6601:         $count ++;
 6602:         next if ($count < $minshown);
 6603:         unless ($showntableheader) {
 6604:             $r->print(&Apache::loncommon::start_data_table()
 6605:                      .$tableheader);
 6606:             $r->rflush();
 6607:             $showntableheader = 1;
 6608:         }
 6609:         if ($whodunit{$roleslog{$id}{'exe_uname'}.':'.$roleslog{$id}{'exe_udom'}} eq '') {
 6610:             $whodunit{$roleslog{$id}{'exe_uname'}.':'.$roleslog{$id}{'exe_udom'}} =
 6611:                 &Apache::loncommon::plainname($roleslog{$id}{'exe_uname'},$roleslog{$id}{'exe_udom'});
 6612:         }
 6613:         if ($changed{$roleslog{$id}{'uname'}.':'.$roleslog{$id}{'udom'}} eq '') {
 6614:             $changed{$roleslog{$id}{'uname'}.':'.$roleslog{$id}{'udom'}} =
 6615:                 &Apache::loncommon::plainname($roleslog{$id}{'uname'},$roleslog{$id}{'udom'});
 6616:         }
 6617:         my $sec = $roleslog{$id}{'logentry'}{'section'};
 6618:         if ($sec eq '') {
 6619:             $sec = &mt('None');
 6620:         }
 6621:         my ($rolestart,$roleend);
 6622:         if ($roleslog{$id}{'delflag'}) {
 6623:             $rolestart = &mt('deleted');
 6624:             $roleend = &mt('deleted');
 6625:         } else {
 6626:             $rolestart = $roleslog{$id}{'logentry'}{'start'};
 6627:             $roleend = $roleslog{$id}{'logentry'}{'end'};
 6628:             if ($rolestart eq '' || $rolestart == 0) {
 6629:                 $rolestart = &mt('No start date'); 
 6630:             } else {
 6631:                 $rolestart = &Apache::lonlocal::locallocaltime($rolestart);
 6632:             }
 6633:             if ($roleend eq '' || $roleend == 0) { 
 6634:                 $roleend = &mt('No end date');
 6635:             } else {
 6636:                 $roleend = &Apache::lonlocal::locallocaltime($roleend);
 6637:             }
 6638:         }
 6639:         my $chgcontext = $roleslog{$id}{'logentry'}{'context'};
 6640:         if ($roleslog{$id}{'logentry'}{'selfenroll'}) {
 6641:             $chgcontext = 'selfenroll';
 6642:         }
 6643:         my %lt = &rolechg_contexts($context,$crstype);
 6644:         if ($chgcontext ne '' && $lt{$chgcontext} ne '') {
 6645:             $chgcontext = $lt{$chgcontext};
 6646:         }
 6647:         $r->print(
 6648:             &Apache::loncommon::start_data_table_row()
 6649:            .'<td>'.$count.'</td>'
 6650:            .'<td>'.&Apache::lonlocal::locallocaltime($roleslog{$id}{'exe_time'}).'</td>'
 6651:            .'<td>'.$whodunit{$roleslog{$id}{'exe_uname'}.':'.$roleslog{$id}{'exe_udom'}}.'</td>'
 6652:            .'<td>'.$changed{$roleslog{$id}{'uname'}.':'.$roleslog{$id}{'udom'}}.'</td>'
 6653:            .'<td>'.&Apache::lonnet::plaintext($roleslog{$id}{'logentry'}{'role'},$crstype).'</td>');
 6654:         if ($context eq 'course') { 
 6655:             $r->print('<td>'.$sec.'</td>');
 6656:         }
 6657:         $r->print(
 6658:             '<td>'.$chgcontext.'</td>'
 6659:            .'<td>'.$rolestart.'</td>'
 6660:            .'<td>'.$roleend.'</td>'
 6661:            .&Apache::loncommon::end_data_table_row()."\n");
 6662:     }
 6663: 
 6664:     if ($showntableheader) { # Table footer, if content displayed above
 6665:         $r->print(&Apache::loncommon::end_data_table().
 6666:                   &userlogdisplay_navlinks(\%curr,$more_records));
 6667:     } else { # No content displayed above
 6668:         $r->print('<p class="LC_info">'
 6669:                  .&mt('There are no records to display.')
 6670:                  .'</p>'
 6671:         );
 6672:     }
 6673: 
 6674:     # Form Footer
 6675:     $r->print( 
 6676:         '<input type="hidden" name="page" value="'.$curr{'page'}.'" />'
 6677:        .'<input type="hidden" name="action" value="changelogs" />'
 6678:        .'</form>');
 6679:     return;
 6680: }
 6681: 
 6682: sub print_useraccesslogs_display {
 6683:     my ($r,$uname,$udom,$permission,$brcrum) = @_;
 6684:     my $formname = 'accesslog';
 6685:     my $form = 'document.accesslog';
 6686: 
 6687: # set breadcrumbs
 6688:     my %breadcrumb_text = &singleuser_breadcrumb('','domain',$udom);
 6689:     my $prevphasestr;
 6690:     if ($env{'form.popup'}) {
 6691:         $brcrum = [];
 6692:     } else {
 6693:         push (@{$brcrum},
 6694:             {href => "javascript:backPage($form)",
 6695:              text => $breadcrumb_text{'search'}});
 6696:         my @prevphases;
 6697:         if ($env{'form.prevphases'}) {
 6698:             @prevphases = split(/,/,$env{'form.prevphases'});
 6699:             $prevphasestr = $env{'form.prevphases'};
 6700:         }
 6701:         if (($env{'form.phase'} eq 'userpicked') || (grep(/^userpicked$/,@prevphases))) {
 6702:             push(@{$brcrum},
 6703:                   {href => "javascript:backPage($form,'get_user_info','select')",
 6704:                    text => $breadcrumb_text{'userpicked'}});
 6705:             if ($env{'form.phase'} eq 'userpicked') {
 6706:                 $prevphasestr = 'userpicked';
 6707:             }
 6708:         }
 6709:     }
 6710:     push(@{$brcrum},
 6711:              {href => '/adm/createuser?action=accesslogs',
 6712:               text => 'User access logs',
 6713:               help => 'Domain_User_Access_Logs'});
 6714:     my $bread_crumbs_component = 'User Access Logs';
 6715:     my $args = { bread_crumbs           => $brcrum,
 6716:                  bread_crumbs_component => 'User Management'};
 6717:     if ($env{'form.popup'}) {
 6718:         $args->{'no_nav_bar'} = 1;
 6719:         $args->{'bread_crumbs_nomenu'} = 1;
 6720:     }
 6721: 
 6722: # set javascript
 6723:     my ($jsback,$elements) = &crumb_utilities();
 6724:     my $jsnav = &userlogdisplay_js($formname);
 6725: 
 6726:     my $jscript = (<<ENDSCRIPT);
 6727: <script type="text/javascript">
 6728: // <![CDATA[
 6729: 
 6730: $jsback
 6731: $jsnav
 6732: 
 6733: // ]]>
 6734: </script>
 6735: 
 6736: ENDSCRIPT
 6737: 
 6738: # print page header
 6739:     $r->print(&header($jscript,$args));
 6740: 
 6741: # early out unless log data can be displayed.
 6742:     unless ($permission->{'activity'}) {
 6743:         $r->print('<p class="LC_warning">'
 6744:                  .&mt('You do not have rights to display user access logs.')
 6745:                  .'</p>');
 6746:         if ($env{'form.popup'}) {
 6747:             $r->print('<p><a href="javascript:window.close()">'.&mt('Close window').'</a></p>');
 6748:         } else {
 6749:             $r->print(&earlyout_accesslog_form($formname,$prevphasestr,$udom));
 6750:         }
 6751:         return;
 6752:     }
 6753: 
 6754:     unless ($udom eq $env{'request.role.domain'}) {
 6755:         $r->print('<p class="LC_warning">'
 6756:                  .&mt("User's domain must match role's domain")
 6757:                  .'</p>'
 6758:                  .&earlyout_accesslog_form($formname,$prevphasestr,$udom));
 6759:         return;
 6760:     }
 6761: 
 6762:     if (($uname eq '') || ($udom eq '')) {
 6763:         $r->print('<p class="LC_warning">'
 6764:                  .&mt('Invalid username or domain')
 6765:                  .'</p>'
 6766:                  .&earlyout_accesslog_form($formname,$prevphasestr,$udom));
 6767:         return;
 6768:     }
 6769: 
 6770: # set defaults
 6771:     my $now = time();
 6772:     my $defstart = $now - (7*24*3600);
 6773:     my %defaults = (
 6774:                      page                 => '1',
 6775:                      show                 => '10',
 6776:                      activity             => 'any',
 6777:                      accesslog_start_date => $defstart,
 6778:                      accesslog_end_date   => $now,
 6779:                    );
 6780:     my $more_records = 0;
 6781: 
 6782: # set current
 6783:     my %curr;
 6784:     foreach my $item ('show','page','activity') {
 6785:         $curr{$item} = $env{'form.'.$item};
 6786:     }
 6787:     my ($startdate,$enddate) =
 6788:         &Apache::lonuserutils::get_dates_from_form('accesslog_start_date','accesslog_end_date');
 6789:     $curr{'accesslog_start_date'} = $startdate;
 6790:     $curr{'accesslog_end_date'} = $enddate;
 6791:     foreach my $key (keys(%defaults)) {
 6792:         if ($curr{$key} eq '') {
 6793:             $curr{$key} = $defaults{$key};
 6794:         }
 6795:     }
 6796:     my ($minshown,$maxshown);
 6797:     $minshown = 1;
 6798:     my $count = 0;
 6799:     if ($curr{'show'} =~ /\D/) {
 6800:         $curr{'page'} = 1;
 6801:     } else {
 6802:         $maxshown = $curr{'page'} * $curr{'show'};
 6803:         if ($curr{'page'} > 1) {
 6804:             $minshown = 1 + ($curr{'page'} - 1) * $curr{'show'};
 6805:         }
 6806:     }
 6807: 
 6808: # form header
 6809:     $r->print('<form action="/adm/createuser" method="post" name="'.$formname.'">'.
 6810:               &activity_display_filter($formname,\%curr));
 6811: 
 6812:     my $showntableheader = 0;
 6813:     my ($nav_script,$nav_links);
 6814: 
 6815: # table header
 6816:     my $tableheader = '<h3>'.
 6817:         &mt('User access logs for: [_1]',
 6818:             &Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($uname,$udom),$uname,$udom)).'</h3>'
 6819:        .&Apache::loncommon::start_data_table_header_row()
 6820:        .'<th>&nbsp;</th>'
 6821:        .'<th>'.&mt('When').'</th>'
 6822:        .'<th>'.&mt('HostID').'</th>'
 6823:        .'<th>'.&mt('Event').'</th>'
 6824:        .'<th>'.&mt('Other data').'</th>'
 6825:        .&Apache::loncommon::end_data_table_header_row();
 6826: 
 6827:     my %filters=(
 6828:         start  => $curr{'accesslog_start_date'},
 6829:         end    => $curr{'accesslog_end_date'},
 6830:         action => $curr{'activity'},
 6831:     );
 6832: 
 6833:     my $reply = &Apache::lonnet::userlog_query($uname,$udom,%filters);
 6834:     unless ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 6835:         my (%courses,%missing);
 6836:         my @results = split(/\&/,$reply);
 6837:         foreach my $item (reverse(@results)) {
 6838:             my ($timestamp,$host,$event) = split(/:/,$item);
 6839:             next unless ($event =~ /^(Log|Role)/);
 6840:             if ($curr{'show'} !~ /\D/) {
 6841:                 if ($count >= $curr{'page'} * $curr{'show'}) {
 6842:                     $more_records = 1;
 6843:                     last;
 6844:                 }
 6845:             }
 6846:             $count ++;
 6847:             next if ($count < $minshown);
 6848:             unless ($showntableheader) {
 6849:                 $r->print($nav_script
 6850:                          .&Apache::loncommon::start_data_table()
 6851:                          .$tableheader);
 6852:                 $r->rflush();
 6853:                 $showntableheader = 1;
 6854:             }
 6855:             my ($shown,$extra);
 6856:             my ($event,$data) = split(/\s+/,&unescape($event));
 6857:             if ($event eq 'Role') {
 6858:                 my ($rolecode,$extent) = split(/\./,$data,2);
 6859:                 next if ($extent eq '');
 6860:                 my ($crstype,$desc,$info);
 6861:                 if ($extent =~ m{^/($match_domain)/($match_courseid)(?:/(\w+)|)$}) {
 6862:                     my ($cdom,$cnum,$sec) = ($1,$2,$3);
 6863:                     my $cid = $cdom.'_'.$cnum;
 6864:                     if (exists($courses{$cid})) {
 6865:                         $crstype = $courses{$cid}{'type'};
 6866:                         $desc = $courses{$cid}{'description'};
 6867:                     } elsif ($missing{$cid}) {
 6868:                         $crstype = 'Course';
 6869:                         $desc = 'Course/Community';
 6870:                     } else {
 6871:                         my %crsinfo = &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 6872:                         if (ref($crsinfo{$cdom.'_'.$cnum}) eq 'HASH') {
 6873:                             $courses{$cid} = $crsinfo{$cid};
 6874:                             $crstype = $crsinfo{$cid}{'type'};
 6875:                             $desc = $crsinfo{$cid}{'description'};
 6876:                         } else {
 6877:                             $missing{$cid} = 1;
 6878:                         }
 6879:                     }
 6880:                     $extra = &mt($crstype).': <a href="/public/'.$cdom.'/'.$cnum.'/syllabus">'.$desc.'</a>';
 6881:                     if ($sec ne '') {
 6882:                        $extra .= ' ('.&mt('Section: [_1]',$sec).')';
 6883:                     }
 6884:                 } elsif ($extent =~ m{^/($match_domain)/($match_username|$)}) {
 6885:                     my ($dom,$name) = ($1,$2);
 6886:                     if ($rolecode eq 'au') {
 6887:                         $extra = '';
 6888:                     } elsif ($rolecode =~ /^(ca|aa)$/) {
 6889:                         $extra = &mt('Authoring Space: [_1]',$name.':'.$dom);
 6890:                     } elsif ($rolecode =~ /^(li|dg|dh|dc|sc)$/) {
 6891:                         $extra = &mt('Domain: [_1]',$dom);
 6892:                     }
 6893:                 }
 6894:                 my $rolename;
 6895:                 if ($rolecode =~ m{^cr/($match_domain)/($match_username)/(\w+)}) {
 6896:                     my $role = $3;
 6897:                     my $owner = "($2:$1)";
 6898:                     if ($2 eq $1.'-domainconfig') {
 6899:                         $owner = '(ad hoc)';
 6900:                     }
 6901:                     $rolename = &mt('Custom role: [_1]',$role.' '.$owner);
 6902:                 } else {
 6903:                     $rolename = &Apache::lonnet::plaintext($rolecode,$crstype);
 6904:                 }
 6905:                 $shown = &mt('Role selection: [_1]',$rolename);
 6906:             } else {
 6907:                 $shown = &mt($event);
 6908:                 if ($data ne '') {
 6909:                    $extra = &mt('Client IP address: [_1]',$data);
 6910:                 }
 6911:             }
 6912:             $r->print(
 6913:             &Apache::loncommon::start_data_table_row()
 6914:            .'<td>'.$count.'</td>'
 6915:            .'<td>'.&Apache::lonlocal::locallocaltime($timestamp).'</td>'
 6916:            .'<td>'.$host.'</td>'
 6917:            .'<td>'.$shown.'</td>'
 6918:            .'<td>'.$extra.'</td>'
 6919:            .&Apache::loncommon::end_data_table_row()."\n");
 6920:         }
 6921:     }
 6922: 
 6923:     if ($showntableheader) { # Table footer, if content displayed above
 6924:         $r->print(&Apache::loncommon::end_data_table().
 6925:                   &userlogdisplay_navlinks(\%curr,$more_records));
 6926:     } else { # No content displayed above
 6927:         $r->print('<p class="LC_info">'
 6928:                  .&mt('There are no records to display.')
 6929:                  .'</p>');
 6930:     }
 6931: 
 6932:     if ($env{'form.popup'} == 1) {
 6933:         $r->print('<input type="hidden" name="popup" value="1" />'."\n");
 6934:     }
 6935: 
 6936:     # Form Footer
 6937:     $r->print(
 6938:         '<input type="hidden" name="currstate" value="" />'
 6939:        .'<input type="hidden" name="accessuname" value="'.$uname.'" />'
 6940:        .'<input type="hidden" name="accessudom" value="'.$udom.'" />'
 6941:        .'<input type="hidden" name="page" value="'.$curr{'page'}.'" />'
 6942:        .'<input type="hidden" name="prevphases" value="'.$prevphasestr.'" />'
 6943:        .'<input type="hidden" name="phase" value="activity" />'
 6944:        .'<input type="hidden" name="action" value="accesslogs" />'
 6945:        .'<input type="hidden" name="srchdomain" value="'.$udom.'" />'
 6946:        .'<input type="hidden" name="srchby" value="'.$env{'form.srchby'}.'" />'
 6947:        .'<input type="hidden" name="srchtype" value="'.$env{'form.srchtype'}.'" />'
 6948:        .'<input type="hidden" name="srchterm" value="'.&HTML::Entities::encode($env{'form.srchterm'},'<>"&').'" />'
 6949:        .'<input type="hidden" name="srchin" value="'.$env{'form.srchin'}.'" />'
 6950:        .'</form>');
 6951:     return;
 6952: }
 6953: 
 6954: sub earlyout_accesslog_form {
 6955:     my ($formname,$prevphasestr,$udom) = @_;
 6956:     my $srchterm = &HTML::Entities::encode($env{'form.srchterm'},'<>"&');
 6957:    return <<"END";
 6958: <form action="/adm/createuser" method="post" name="$formname">
 6959: <input type="hidden" name="currstate" value="" />
 6960: <input type="hidden" name="prevphases" value="$prevphasestr" />
 6961: <input type="hidden" name="phase" value="activity" />
 6962: <input type="hidden" name="action" value="accesslogs" />
 6963: <input type="hidden" name="srchdomain" value="$udom" />
 6964: <input type="hidden" name="srchby" value="$env{'form.srchby'}" />
 6965: <input type="hidden" name="srchtype" value="$env{'form.srchtype'}" />
 6966: <input type="hidden" name="srchterm" value="$srchterm" />
 6967: <input type="hidden" name="srchin" value="$env{'form.srchin'}" />
 6968: </form>
 6969: END
 6970: }
 6971: 
 6972: sub activity_display_filter {
 6973:     my ($formname,$curr) = @_;
 6974:     my $nolink = 1;
 6975:     my $output = '<table><tr><td valign="top">'.
 6976:                  '<span class="LC_nobreak"><b>'.&mt('Actions/page:').'</b></span><br />'.
 6977:                  &Apache::lonmeta::selectbox('show',$curr->{'show'},undef,
 6978:                                               (&mt('all'),5,10,20,50,100,1000,10000)).
 6979:                  '</td><td>&nbsp;&nbsp;</td>';
 6980:     my $startform =
 6981:         &Apache::lonhtmlcommon::date_setter($formname,'accesslog_start_date',
 6982:                                             $curr->{'accesslog_start_date'},undef,
 6983:                                             undef,undef,undef,undef,undef,undef,$nolink);
 6984:     my $endform =
 6985:         &Apache::lonhtmlcommon::date_setter($formname,'accesslog_end_date',
 6986:                                             $curr->{'accesslog_end_date'},undef,
 6987:                                             undef,undef,undef,undef,undef,undef,$nolink);
 6988:     my %lt = &Apache::lonlocal::texthash (
 6989:                                           activity => 'Activity',
 6990:                                           Role     => 'Role selection',
 6991:                                           log      => 'Log-in or Logout',
 6992:     );
 6993:     $output .= '<td valign="top"><b>'.&mt('Window during which actions occurred:').'</b><br />'.
 6994:                '<table><tr><td>'.&mt('After:').
 6995:                '</td><td>'.$startform.'</td></tr>'.
 6996:                '<tr><td>'.&mt('Before:').'</td>'.
 6997:                '<td>'.$endform.'</td></tr></table>'.
 6998:                '</td>'.
 6999:                '<td>&nbsp;&nbsp;</td>'.
 7000:                '<td valign="top"><b>'.&mt('Activities').'</b><br />'.
 7001:                '<select name="activity"><option value="any"';
 7002:     if ($curr->{'activity'} eq 'any') {
 7003:         $output .= ' selected="selected"';
 7004:     }
 7005:     $output .= '>'.&mt('Any').'</option>'."\n";
 7006:     foreach my $activity ('Role','log') {
 7007:         my $selstr = '';
 7008:         if ($activity eq $curr->{'activity'}) {
 7009:             $selstr = ' selected="selected"';
 7010:         }
 7011:         $output .= '<option value="'.$activity.'"'.$selstr.'>'.$lt{$activity}.'</option>';
 7012:     }
 7013:     $output .= '</select></td>'.
 7014:                '</tr></table>';
 7015:     # Update Display button
 7016:     $output .= '<p>'
 7017:               .'<input type="submit" value="'.&mt('Update Display').'" />'
 7018:               .'</p><hr />';
 7019:     return $output;
 7020: }
 7021: 
 7022: sub userlogdisplay_js {
 7023:     my ($formname) = @_;
 7024:     return <<"ENDSCRIPT";
 7025: 
 7026: function chgPage(caller) {
 7027:     if (caller == 'previous') {
 7028:         document.$formname.page.value --;
 7029:     }
 7030:     if (caller == 'next') {
 7031:         document.$formname.page.value ++;
 7032:     }
 7033:     document.$formname.submit();
 7034:     return;
 7035: }
 7036: ENDSCRIPT
 7037: }
 7038: 
 7039: sub userlogdisplay_navlinks {
 7040:     my ($curr,$more_records) = @_;
 7041:     return unless(ref($curr) eq 'HASH');
 7042:     # Navigation Buttons
 7043:     my $nav_links = '<p>';
 7044:     if (($curr->{'page'} > 1) || ($more_records)) {
 7045:         if (($curr->{'page'} > 1) && ($curr->{'show'} !~ /\D/)) {
 7046:             $nav_links .= '<input type="button"'
 7047:                          .' onclick="javascript:chgPage('."'previous'".');"'
 7048:                          .' value="'.&mt('Previous [_1] changes',$curr->{'show'})
 7049:                          .'" /> ';
 7050:         }
 7051:         if ($more_records) {
 7052:             $nav_links .= '<input type="button"'
 7053:                          .' onclick="javascript:chgPage('."'next'".');"'
 7054:                          .' value="'.&mt('Next [_1] changes',$curr->{'show'})
 7055:                          .'" />';
 7056:         }
 7057:     }
 7058:     $nav_links .= '</p>';
 7059:     return $nav_links;
 7060: }
 7061: 
 7062: sub role_display_filter {
 7063:     my ($context,$formname,$cdom,$cnum,$curr,$version,$crstype) = @_;
 7064:     my $lctype;
 7065:     if ($context eq 'course') {
 7066:         $lctype = lc($crstype);
 7067:     }
 7068:     my $nolink = 1;
 7069:     my $output = '<table><tr><td valign="top">'.
 7070:                  '<span class="LC_nobreak"><b>'.&mt('Changes/page:').'</b></span><br />'.
 7071:                  &Apache::lonmeta::selectbox('show',$curr->{'show'},undef,
 7072:                                               (&mt('all'),5,10,20,50,100,1000,10000)).
 7073:                  '</td><td>&nbsp;&nbsp;</td>';
 7074:     my $startform =
 7075:         &Apache::lonhtmlcommon::date_setter($formname,'rolelog_start_date',
 7076:                                             $curr->{'rolelog_start_date'},undef,
 7077:                                             undef,undef,undef,undef,undef,undef,$nolink);
 7078:     my $endform =
 7079:         &Apache::lonhtmlcommon::date_setter($formname,'rolelog_end_date',
 7080:                                             $curr->{'rolelog_end_date'},undef,
 7081:                                             undef,undef,undef,undef,undef,undef,$nolink);
 7082:     my %lt = &rolechg_contexts($context,$crstype);
 7083:     $output .= '<td valign="top"><b>'.&mt('Window during which changes occurred:').'</b><br />'.
 7084:                '<table><tr><td>'.&mt('After:').
 7085:                '</td><td>'.$startform.'</td></tr>'.
 7086:                '<tr><td>'.&mt('Before:').'</td>'.
 7087:                '<td>'.$endform.'</td></tr></table>'.
 7088:                '</td>'.
 7089:                '<td>&nbsp;&nbsp;</td>'.
 7090:                '<td valign="top"><b>'.&mt('Role:').'</b><br />'.
 7091:                '<select name="role"><option value="any"';
 7092:     if ($curr->{'role'} eq 'any') {
 7093:         $output .= ' selected="selected"';
 7094:     }
 7095:     $output .=  '>'.&mt('Any').'</option>'."\n";
 7096:     my @roles = &Apache::lonuserutils::roles_by_context($context,1,$crstype);
 7097:     foreach my $role (@roles) {
 7098:         my $plrole;
 7099:         if ($role eq 'cr') {
 7100:             $plrole = &mt('Custom Role');
 7101:         } else {
 7102:             $plrole=&Apache::lonnet::plaintext($role,$crstype);
 7103:         }
 7104:         my $selstr = '';
 7105:         if ($role eq $curr->{'role'}) {
 7106:             $selstr = ' selected="selected"';
 7107:         }
 7108:         $output .= '  <option value="'.$role.'"'.$selstr.'>'.$plrole.'</option>';
 7109:     }
 7110:     $output .= '</select></td>'.
 7111:                '<td>&nbsp;&nbsp;</td>'.
 7112:                '<td valign="top"><b>'.
 7113:                &mt('Context:').'</b><br /><select name="chgcontext">';
 7114:     my @posscontexts;
 7115:     if ($context eq 'course') {
 7116:         @posscontexts = ('any','automated','updatenow','createcourse','course','domain','selfenroll','requestcourses');
 7117:     } elsif ($context eq 'domain') {
 7118:         @posscontexts = ('any','domain','requestauthor','domconfig','server');
 7119:     } else {
 7120:         @posscontexts = ('any','author','domain');
 7121:     } 
 7122:     foreach my $chgtype (@posscontexts) {
 7123:         my $selstr = '';
 7124:         if ($curr->{'chgcontext'} eq $chgtype) {
 7125:             $selstr = ' selected="selected"';
 7126:         }
 7127:         if ($context eq 'course') {
 7128:             if (($chgtype eq 'automated') || ($chgtype eq 'updatenow')) {
 7129:                 next if (!&Apache::lonnet::auto_run($cnum,$cdom));
 7130:             }
 7131:         }
 7132:         $output .= '<option value="'.$chgtype.'"'.$selstr.'>'.$lt{$chgtype}.'</option>'."\n";
 7133:     }
 7134:     $output .= '</select></td>'
 7135:               .'</tr></table>';
 7136: 
 7137:     # Update Display button
 7138:     $output .= '<p>'
 7139:               .'<input type="submit" value="'.&mt('Update Display').'" />'
 7140:               .'</p>';
 7141: 
 7142:     # Server version info
 7143:     my $needsrev = '2.11.0';
 7144:     if ($context eq 'course') {
 7145:         $needsrev = '2.7.0';
 7146:     }
 7147:     
 7148:     $output .= '<p class="LC_info">'
 7149:               .&mt('Only changes made from servers running LON-CAPA [_1] or later are displayed.'
 7150:                   ,$needsrev);
 7151:     if ($version) {
 7152:         $output .= ' '.&mt('This LON-CAPA server is version [_1]',$version);
 7153:     }
 7154:     $output .= '</p><hr />';
 7155:     return $output;
 7156: }
 7157: 
 7158: sub rolechg_contexts {
 7159:     my ($context,$crstype) = @_;
 7160:     my %lt;
 7161:     if ($context eq 'course') {
 7162:         %lt = &Apache::lonlocal::texthash (
 7163:                                              any          => 'Any',
 7164:                                              automated    => 'Automated Enrollment',
 7165:                                              updatenow    => 'Roster Update',
 7166:                                              createcourse => 'Course Creation',
 7167:                                              course       => 'User Management in course',
 7168:                                              domain       => 'User Management in domain',
 7169:                                              selfenroll   => 'Self-enrolled',
 7170:                                              requestcourses => 'Course Request',
 7171:                                          );
 7172:         if ($crstype eq 'Community') {
 7173:             $lt{'createcourse'} = &mt('Community Creation');
 7174:             $lt{'course'} = &mt('User Management in community');
 7175:             $lt{'requestcourses'} = &mt('Community Request');
 7176:         }
 7177:     } elsif ($context eq 'domain') {
 7178:         %lt = &Apache::lonlocal::texthash (
 7179:                                              any           => 'Any',
 7180:                                              domain        => 'User Management in domain',
 7181:                                              requestauthor => 'Authoring Request',
 7182:                                              server        => 'Command line script (DC role)',
 7183:                                              domconfig     => 'Self-enrolled',
 7184:                                          );
 7185:     } else {
 7186:         %lt = &Apache::lonlocal::texthash (
 7187:                                              any    => 'Any',
 7188:                                              domain => 'User Management in domain',
 7189:                                              author => 'User Management by author',
 7190:                                          );
 7191:     } 
 7192:     return %lt;
 7193: }
 7194: 
 7195: sub print_helpdeskaccess_display {
 7196:     my ($r,$permission,$brcrum) = @_;
 7197:     my $formname = 'helpdeskaccess';
 7198:     my $helpitem = 'Course_Helpdesk_Access';
 7199:     push (@{$brcrum},
 7200:              {href => '/adm/createuser?action=helpdesk',
 7201:               text => 'Helpdesk Access',
 7202:               help => $helpitem});
 7203:     my $bread_crumbs_component = 'Helpdesk Staff Access';
 7204:     my $args = { bread_crumbs           => $brcrum,
 7205:                  bread_crumbs_component => $bread_crumbs_component};
 7206: 
 7207:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7208:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7209:     my $confname = $cdom.'-domainconfig';
 7210:     my $crstype = &Apache::loncommon::course_type();
 7211: 
 7212:     my @accesstypes = ('all','dh','da','none');
 7213:     my ($numstatustypes,@jsarray);
 7214:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($cdom);
 7215:     if (ref($types) eq 'ARRAY') {
 7216:         if (@{$types} > 0) {
 7217:             $numstatustypes = scalar(@{$types});
 7218:             push(@accesstypes,'status');
 7219:             @jsarray = ('bystatus');
 7220:         }
 7221:     }
 7222:     my %customroles = &get_domain_customroles($cdom,$confname);
 7223:     my %domhelpdesk = &Apache::lonnet::get_active_domroles($cdom,['dh','da']);
 7224:     if (keys(%domhelpdesk)) {
 7225:        push(@accesstypes,('inc','exc'));
 7226:        push(@jsarray,('notinc','notexc'));
 7227:     }
 7228:     push(@jsarray,'privs');
 7229:     my $hiddenstr = join("','",@jsarray);
 7230:     my $rolestr = join("','",sort(keys(%customroles)));
 7231: 
 7232:     my $jscript;
 7233:     my (%settings,%overridden);
 7234:     if (keys(%customroles)) {
 7235:         &get_adhocrole_settings($env{'request.course.id'},\@accesstypes,
 7236:                                 $types,\%customroles,\%settings,\%overridden);
 7237:         my %jsfull=();
 7238:         my %jslevels= (
 7239:                      course => {},
 7240:                      domain => {},
 7241:                      system => {},
 7242:                     );
 7243:         my %jslevelscurrent=(
 7244:                            course => {},
 7245:                            domain => {},
 7246:                            system => {},
 7247:                           );
 7248:         my (%privs,%jsprivs);
 7249:         &Apache::lonuserutils::custom_role_privs(\%privs,\%jsfull,\%jslevels,\%jslevelscurrent);
 7250:         foreach my $priv (keys(%jsfull)) {
 7251:             if ($jslevels{'course'}{$priv}) {
 7252:                 $jsprivs{$priv} = 1;
 7253:             }
 7254:         }
 7255:         my (%elements,%stored);
 7256:         foreach my $role (keys(%customroles)) {
 7257:             $elements{$role.'_access'} = 'radio';
 7258:             $elements{$role.'_incrs'} = 'radio';
 7259:             if ($numstatustypes) {
 7260:                 $elements{$role.'_status'} = 'checkbox';
 7261:             }
 7262:             if (keys(%domhelpdesk) > 0) {
 7263:                 $elements{$role.'_staff_inc'} = 'checkbox';
 7264:                 $elements{$role.'_staff_exc'} = 'checkbox';
 7265:             }
 7266:             $elements{$role.'_override'} = 'checkbox';
 7267:             if (ref($settings{$role}) eq 'HASH') {
 7268:                 if ($settings{$role}{'access'} ne '') {
 7269:                     my $curraccess = $settings{$role}{'access'};
 7270:                     $stored{$role.'_access'} = $curraccess;
 7271:                     $stored{$role.'_incrs'} = 1;
 7272:                     if ($curraccess eq 'status') {
 7273:                         if (ref($settings{$role}{'status'}) eq 'ARRAY') {
 7274:                             $stored{$role.'_status'} = $settings{$role}{'status'};
 7275:                         }
 7276:                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 7277:                         if (ref($settings{$role}{$curraccess}) eq 'ARRAY') {
 7278:                             $stored{$role.'_staff_'.$curraccess} = $settings{$role}{$curraccess};
 7279:                         }
 7280:                     }
 7281:                 } else {
 7282:                     $stored{$role.'_incrs'} = 0;
 7283:                 }
 7284:                 $stored{$role.'_override'} = [];
 7285:                 if ($env{'course.'.$env{'request.course.id'}.'.internal.adhocpriv.'.$role}) {
 7286:                     if (ref($settings{$role}{'off'}) eq 'ARRAY') {
 7287:                         foreach my $priv (@{$settings{$role}{'off'}}) {
 7288:                             push(@{$stored{$role.'_override'}},$priv);
 7289:                         }
 7290:                     }
 7291:                     if (ref($settings{$role}{'on'}) eq 'ARRAY') {
 7292:                         foreach my $priv (@{$settings{$role}{'on'}}) {
 7293:                             unless (grep(/^$priv$/,@{$stored{$role.'_override'}})) {
 7294:                                 push(@{$stored{$role.'_override'}},$priv);
 7295:                             }
 7296:                         }
 7297:                     }
 7298:                 }
 7299:             } else {
 7300:                 $stored{$role.'_incrs'} = 0;
 7301:             }
 7302:         }
 7303:         $jscript = &Apache::lonhtmlcommon::set_form_elements(\%elements,\%stored);
 7304:     }
 7305: 
 7306:     my $js = <<"ENDJS";
 7307: <script type="text/javascript">
 7308: // <![CDATA[
 7309: $jscript;
 7310: 
 7311: function switchRoleTab(caller,role) {
 7312:     if (document.getElementById(role+'_maindiv')) {
 7313:         if (caller.id != 'LC_current_minitab') {
 7314:             if (document.getElementById('LC_current_minitab')) {
 7315:                 document.getElementById('LC_current_minitab').id=null;
 7316:             }
 7317:             var roledivs = Array('$rolestr');
 7318:             if (roledivs.length > 0) {
 7319:                 for (var i=0; i<roledivs.length; i++) {
 7320:                     if (document.getElementById(roledivs[i]+'_maindiv')) {
 7321:                         document.getElementById(roledivs[i]+'_maindiv').style.display='none';
 7322:                     }
 7323:                 }
 7324:             }
 7325:             caller.id = 'LC_current_minitab';
 7326:             document.getElementById(role+'_maindiv').style.display='block';
 7327:         }
 7328:     }
 7329:     return false;
 7330: }
 7331: 
 7332: function helpdeskAccess(role) {
 7333:     var curraccess = null;
 7334:     if (document.$formname.elements[role+'_access'].length) {
 7335:         for (var i=0; i<document.$formname.elements[role+'_access'].length; i++) {
 7336:             if (document.$formname.elements[role+'_access'][i].checked) {
 7337:                 curraccess = document.$formname.elements[role+'_access'][i].value;
 7338:             }
 7339:         }
 7340:     }
 7341:     var shown = Array();
 7342:     var hidden = Array();
 7343:     if (curraccess == 'none') {
 7344:         hidden = Array ('$hiddenstr');
 7345:     } else {
 7346:         if (curraccess == 'status') {
 7347:             shown = Array ('bystatus','privs');
 7348:             hidden = Array ('notinc','notexc');
 7349:         } else {
 7350:             if (curraccess == 'exc') {
 7351:                 shown = Array ('notexc','privs');
 7352:                 hidden = Array ('notinc','bystatus');
 7353:             }
 7354:             if (curraccess == 'inc') {
 7355:                 shown = Array ('notinc','privs');
 7356:                 hidden = Array ('notexc','bystatus');
 7357:             }
 7358:             if (curraccess == 'all') {
 7359:                 shown = Array ('privs');
 7360:                 hidden = Array ('notinc','notexc','bystatus');
 7361:             }
 7362:         }
 7363:     }
 7364:     if (hidden.length > 0) {
 7365:         for (var i=0; i<hidden.length; i++) {
 7366:             if (document.getElementById(role+'_'+hidden[i])) {
 7367:                 document.getElementById(role+'_'+hidden[i]).style.display = 'none';
 7368:             }
 7369:         }
 7370:     }
 7371:     if (shown.length > 0) {
 7372:         for (var i=0; i<shown.length; i++) {
 7373:             if (document.getElementById(role+'_'+shown[i])) {
 7374:                 if (shown[i] == 'privs') {
 7375:                     document.getElementById(role+'_'+shown[i]).style.display = 'block';
 7376:                 } else {
 7377:                     document.getElementById(role+'_'+shown[i]).style.display = 'inline';
 7378:                 }
 7379:             }
 7380:         }
 7381:     }
 7382:     return;
 7383: }
 7384: 
 7385: function toggleAccess(role) {
 7386:     if ((document.getElementById(role+'_setincrs')) &&
 7387:         (document.getElementById(role+'_setindom'))) {
 7388:         for (var i=0; i<document.$formname.elements[role+'_incrs'].length; i++) {
 7389:             if (document.$formname.elements[role+'_incrs'][i].checked) {
 7390:                 if (document.$formname.elements[role+'_incrs'][i].value == 1) {
 7391:                     document.getElementById(role+'_setindom').style.display = 'none';
 7392:                     document.getElementById(role+'_setincrs').style.display = 'block';
 7393:                 } else {
 7394:                     document.getElementById(role+'_setincrs').style.display = 'none';
 7395:                     document.getElementById(role+'_setindom').style.display = 'block';
 7396:                 }
 7397:                 break;
 7398:             }
 7399:         }
 7400:     }
 7401:     return;
 7402: }
 7403: 
 7404: // ]]>
 7405: </script>
 7406: ENDJS
 7407: 
 7408:     $args->{add_entries} = {onload => "javascript:setFormElements(document.$formname)"};
 7409: 
 7410:     # print page header
 7411:     $r->print(&header($js,$args));
 7412:     # print form header
 7413:     $r->print('<form action="/adm/createuser" method="post" name="'.$formname.'">');
 7414: 
 7415:     if (keys(%customroles)) {
 7416:         my %lt = &Apache::lonlocal::texthash(
 7417:                     'aco'    => 'As course owner you may override the defaults set in the domain for role usage and/or privileges.',
 7418:                     'rou'    => 'Role usage',
 7419:                     'whi'    => 'Which helpdesk personnel may use this role?',
 7420:                     'udd'    => 'Use domain default',
 7421:                     'all'    => 'All with domain helpdesk or helpdesk assistant role',
 7422:                     'dh'     => 'All with domain helpdesk role',
 7423:                     'da'     => 'All with domain helpdesk assistant role',
 7424:                     'none'   => 'None',
 7425:                     'status' => 'Determined based on institutional status',
 7426:                     'inc'    => 'Include all, but exclude specific personnel',
 7427:                     'exc'    => 'Exclude all, but include specific personnel',
 7428:                     'hel'    => 'Helpdesk',
 7429:                     'rpr'    => 'Role privileges',
 7430:                  );
 7431:         $lt{'tfh'} = &mt("Custom [_1]ad hoc[_2] course roles available for use by the domain's helpdesk are as follows",'<i>','</i>');
 7432:         my %domconfig = &Apache::lonnet::get_dom('configuration',['helpsettings'],$cdom);
 7433:         my (%domcurrent,%ordered,%description,%domusage,$disabled);
 7434:         if (ref($domconfig{'helpsettings'}) eq 'HASH') {
 7435:             if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
 7436:                 %domcurrent = %{$domconfig{'helpsettings'}{'adhoc'}};
 7437:             }
 7438:         }
 7439:         my $count = 0;
 7440:         foreach my $role (sort(keys(%customroles))) {
 7441:             my ($order,$desc,$access_in_dom);
 7442:             if (ref($domcurrent{$role}) eq 'HASH') {
 7443:                 $order = $domcurrent{$role}{'order'};
 7444:                 $desc = $domcurrent{$role}{'desc'};
 7445:                 $access_in_dom = $domcurrent{$role}{'access'};
 7446:             }
 7447:             if ($order eq '') {
 7448:                 $order = $count;
 7449:             }
 7450:             $ordered{$order} = $role;
 7451:             if ($desc ne '') {
 7452:                 $description{$role} = $desc;
 7453:             } else {
 7454:                 $description{$role}= $role;
 7455:             }
 7456:             $count++;
 7457:         }
 7458:         %domusage = &domain_adhoc_access(\%customroles,\%domcurrent,\@accesstypes,$usertypes,$othertitle);
 7459:         my @roles_by_num = ();
 7460:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 7461:             push(@roles_by_num,$ordered{$item});
 7462:         }
 7463:         $r->print('<p>'.$lt{'tfh'}.': <i>'.join('</i>, <i>',map { $description{$_}; } @roles_by_num).'</i>.');
 7464:         if ($permission->{'owner'}) {
 7465:             $r->print('<br />'.$lt{'aco'}.'</p><p>');
 7466:             $r->print('<input type="hidden" name="state" value="process" />'.
 7467:                       '<input type="submit" value="'.&mt('Save changes').'" />');
 7468:         } else {
 7469:             if ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'}) {
 7470:                 my ($ownername,$ownerdom) = split(/:/,$env{'course.'.$env{'request.course.id'}.'.internal.courseowner'});
 7471:                 $r->print('<br />'.&mt('The course owner -- [_1] -- can override the default access and/or privileges for these ad hoc roles.',
 7472:                                     &Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($ownername,$ownerdom),$ownername,$ownerdom)));
 7473:             }
 7474:             $disabled = ' disabled="disabled"';
 7475:         }
 7476:         $r->print('</p>');
 7477: 
 7478:         $r->print('<div id="LC_minitab_header"><ul>');
 7479:         my $count = 0;
 7480:         my %visibility;
 7481:         foreach my $role (@roles_by_num) {
 7482:             my $id;
 7483:             if ($count == 0) {
 7484:                 $id=' id="LC_current_minitab"';
 7485:                 $visibility{$role} = ' style="display:block"';
 7486:             } else {
 7487:                 $visibility{$role} = ' style="display:none"';
 7488:             }
 7489:             $count ++;
 7490:             $r->print('<li'.$id.'><a href="#" onclick="javascript:switchRoleTab(this.parentNode,'."'$role'".');">'.$description{$role}.'</a></li>');
 7491:         }
 7492:         $r->print('</ul></div>');
 7493: 
 7494:         foreach my $role (@roles_by_num) {
 7495:             my %usecheck = (
 7496:                              all => ' checked="checked"',
 7497:                            );
 7498:             my %displaydiv = (
 7499:                                 status => 'none',
 7500:                                 inc    => 'none',
 7501:                                 exc    => 'none',
 7502:                                 priv   => 'block',
 7503:                              );
 7504:             my (%selected,$overridden,$incrscheck,$indomcheck,$indomvis,$incrsvis);
 7505:             if (ref($settings{$role}) eq 'HASH') {
 7506:                 if ($settings{$role}{'access'} ne '') {
 7507:                     $indomvis = ' style="display:none"';
 7508:                     $incrsvis = ' style="display:block"';
 7509:                     $incrscheck = ' checked="checked"';
 7510:                     if ($settings{$role}{'access'} ne 'all') {
 7511:                         $usecheck{$settings{$role}{'access'}} = $usecheck{'all'};
 7512:                         delete($usecheck{'all'});
 7513:                         if ($settings{$role}{'access'} eq 'status') {
 7514:                             my $access = 'status';
 7515:                             $displaydiv{$access} = 'inline';
 7516:                             if (ref($settings{$role}{$access}) eq 'ARRAY') {
 7517:                                 $selected{$access} = $settings{$role}{$access};
 7518:                             }
 7519:                         } elsif ($settings{$role}{'access'} =~ /^(inc|exc)$/) {
 7520:                             my $access = $1;
 7521:                             $displaydiv{$access} = 'inline';
 7522:                             if (ref($settings{$role}{$access}) eq 'ARRAY') {
 7523:                                 $selected{$access} = $settings{$role}{$access};
 7524:                             }
 7525:                         } elsif ($settings{$role}{'access'} eq 'none') {
 7526:                             $displaydiv{'priv'} = 'none';
 7527:                         }
 7528:                     }
 7529:                 } else {
 7530:                     $indomcheck = ' checked="checked"';
 7531:                     $indomvis = ' style="display:block"';
 7532:                     $incrsvis = ' style="display:none"';
 7533:                 }
 7534:             } else {
 7535:                 $indomcheck = ' checked="checked"';
 7536:                 $indomvis = ' style="display:block"';
 7537:                 $incrsvis = ' style="display:none"';
 7538:             }
 7539:             $r->print('<div class="LC_left_float" id="'.$role.'_maindiv"'.$visibility{$role}.'>'.
 7540:                       '<fieldset><legend>'.$lt{'rou'}.'</legend>'.
 7541:                       '<p>'.$lt{'whi'}.' <span class="LC_nobreak">'.
 7542:                       '<label><input type="radio" name="'.$role.'_incrs" value="1"'.$incrscheck.' onclick="toggleAccess('."'$role'".');"'.$disabled.'>'.
 7543:                       &mt('Set here in [_1]',lc($crstype)).'</label>'.
 7544:                       '<span>'.('&nbsp;'x2).
 7545:                       '<label><input type="radio" name="'.$role.'_incrs" value="0"'.$indomcheck.' onclick="toggleAccess('."'$role'".');"'.$disabled.'>'.
 7546:                       $lt{'udd'}.'</label><span></p>'.
 7547:                       '<div id="'.$role.'_setindom"'.$indomvis.'>'.
 7548:                       '<span class="LC_cusr_emph">'.$domusage{$role}.'</span></div>'.
 7549:                       '<div id="'.$role.'_setincrs"'.$incrsvis.'>');
 7550:             foreach my $access (@accesstypes) {
 7551:                 $r->print('<p><label><input type="radio" name="'.$role.'_access" value="'.$access.'" '.$usecheck{$access}.
 7552:                           ' onclick="helpdeskAccess('."'$role'".');"'.$disabled.' />'.$lt{$access}.'</label>');
 7553:                 if ($access eq 'status') {
 7554:                     $r->print('<div id="'.$role.'_bystatus" style="display:'.$displaydiv{$access}.'">'.
 7555:                               &Apache::lonuserutils::adhoc_status_types($cdom,undef,$role,$selected{$access},
 7556:                                                                         $othertitle,$usertypes,$types,$disabled).
 7557:                               '</div>');
 7558:                 } elsif (($access eq 'inc') && (keys(%domhelpdesk) > 0)) {
 7559:                     $r->print('<div id="'.$role.'_notinc" style="display:'.$displaydiv{$access}.'">'.
 7560:                               &Apache::lonuserutils::adhoc_staff($access,undef,$role,$selected{$access},
 7561:                                                                  \%domhelpdesk,$disabled).
 7562:                               '</div>');
 7563:                 } elsif (($access eq 'exc') && (keys(%domhelpdesk) > 0)) {
 7564:                     $r->print('<div id="'.$role.'_notexc" style="display:'.$displaydiv{$access}.'">'.
 7565:                               &Apache::lonuserutils::adhoc_staff($access,undef,$role,$selected{$access},
 7566:                                                                  \%domhelpdesk,$disabled).
 7567:                               '</div>');
 7568:                 }
 7569:                 $r->print('</p>');
 7570:             }
 7571:             $r->print('</div></fieldset>');
 7572:             my %full=();
 7573:             my %levels= (
 7574:                          course => {},
 7575:                          domain => {},
 7576:                          system => {},
 7577:                         );
 7578:             my %levelscurrent=(
 7579:                                course => {},
 7580:                                domain => {},
 7581:                                system => {},
 7582:                               );
 7583:             &Apache::lonuserutils::custom_role_privs($customroles{$role},\%full,\%levels,\%levelscurrent);
 7584:             $r->print('<fieldset id="'.$role.'_privs" style="display:'.$displaydiv{'priv'}.'">'.
 7585:                       '<legend>'.$lt{'rpr'}.'</legend>'.
 7586:                       &role_priv_table($role,$permission,$crstype,\%full,\%levels,\%levelscurrent,$overridden{$role}).
 7587:                       '</fieldset></div><div style="padding:0;clear:both;margin:0;border:0"></div>');
 7588:         }
 7589:         if ($permission->{'owner'}) {
 7590:             $r->print('<p><input type="submit" value="'.&mt('Save changes').'" /></p>');
 7591:         }
 7592:     } else {
 7593:         $r->print(&mt('Helpdesk roles have not yet been created in this domain.'));
 7594:     }
 7595:     # Form Footer
 7596:     $r->print('<input type="hidden" name="action" value="helpdesk" />'
 7597:              .'</form>');
 7598:     return;
 7599: }
 7600: 
 7601: sub domain_adhoc_access {
 7602:     my ($roles,$domcurrent,$accesstypes,$usertypes,$othertitle) = @_;
 7603:     my %domusage;
 7604:     return unless ((ref($roles) eq 'HASH') && (ref($domcurrent) eq 'HASH') && (ref($accesstypes) eq 'ARRAY'));
 7605:     foreach my $role (keys(%{$roles})) {
 7606:         if (ref($domcurrent->{$role}) eq 'HASH') {
 7607:             my $access = $domcurrent->{$role}{'access'};
 7608:             if (($access eq '') || (!grep(/^\Q$access\E$/,@{$accesstypes}))) {
 7609:                 $access = 'all';
 7610:                 $domusage{$role} = &mt('Any user in domain with active [_1] or [_2] role',&Apache::lonnet::plaintext('dh'),
 7611:                                                                                           &Apache::lonnet::plaintext('da'));
 7612:             } elsif ($access eq 'status') {
 7613:                 if (ref($domcurrent->{$role}{$access}) eq 'ARRAY') {
 7614:                     my @shown;
 7615:                     foreach my $type (@{$domcurrent->{$role}{$access}}) {
 7616:                         unless ($type eq 'default') {
 7617:                             if ($usertypes->{$type}) {
 7618:                                 push(@shown,$usertypes->{$type});
 7619:                             }
 7620:                         }
 7621:                     }
 7622:                     if (grep(/^default$/,@{$domcurrent->{$role}{$access}})) {
 7623:                         push(@shown,$othertitle);
 7624:                     }
 7625:                     if (@shown) {
 7626:                         my $shownstatus = join(' '.&mt('or').' ',@shown);
 7627:                         $domusage{$role} = &mt('Any user in domain with active [_1] or [_2] role, and institutional status: [_3]',
 7628:                                                &Apache::lonnet::plaintext('dh'),&Apache::lonnet::plaintext('da'),$shownstatus);
 7629:                     } else {
 7630:                         $domusage{$role} = &mt('No one in the domain');
 7631:                     }
 7632:                 }
 7633:             } elsif ($access eq 'inc') {
 7634:                 my @dominc = ();
 7635:                 if (ref($domcurrent->{$role}{'inc'}) eq 'ARRAY') {
 7636:                     foreach my $user (@{$domcurrent->{$role}{'inc'}}) {
 7637:                         my ($uname,$udom) = split(/:/,$user);
 7638:                         push(@dominc,&Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($uname,$udom),$uname,$udom));
 7639:                     }
 7640:                     my $showninc = join(', ',@dominc);
 7641:                     if ($showninc ne '') {
 7642:                         $domusage{$role} = &mt('Include any user in domain with active [_1] or [_2] role, except: [_3]',
 7643:                                                &Apache::lonnet::plaintext('dh'),&Apache::lonnet::plaintext('da'),$showninc);
 7644:                     } else {
 7645:                         $domusage{$role} = &mt('Any user in domain with active [_1] or [_2] role',
 7646:                                                &Apache::lonnet::plaintext('dh'),&Apache::lonnet::plaintext('da'));
 7647:                     }
 7648:                 }
 7649:             } elsif ($access eq 'exc') {
 7650:                 my @domexc = ();
 7651:                 if (ref($domcurrent->{$role}{'exc'}) eq 'ARRAY') {
 7652:                     foreach my $user (@{$domcurrent->{$role}{'exc'}}) {
 7653:                         my ($uname,$udom) = split(/:/,$user);
 7654:                         push(@domexc,&Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($uname,$udom),$uname,$udom));
 7655:                     }
 7656:                 }
 7657:                 my $shownexc = join(', ',@domexc);
 7658:                 if ($shownexc ne '') {
 7659:                     $domusage{$role} = &mt('Only the following in the domain with active [_1] or [_2] role: [_3]',
 7660:                                            &Apache::lonnet::plaintext('dh'),&Apache::lonnet::plaintext('da'),$shownexc);
 7661:                 } else {
 7662:                     $domusage{$role} = &mt('No one in the domain');
 7663:                 }
 7664:             } elsif ($access eq 'none') {
 7665:                 $domusage{$role} = &mt('No one in the domain');
 7666:             } elsif ($access eq 'dh') {
 7667:                 $domusage{$role} = &mt('Any user in domain with active [_1] role',&Apache::lonnet::plaintext('dh'));
 7668:             } elsif ($access eq 'da') {
 7669:                 $domusage{$role} = &mt('Any user in domain with active [_1] role',&Apache::lonnet::plaintext('da'));
 7670:             } elsif ($access eq 'all') {
 7671:                 $domusage{$role} = &mt('Any user in domain with active [_1] or [_2] role',
 7672:                                        &Apache::lonnet::plaintext('dh'),&Apache::lonnet::plaintext('da'));
 7673:             }
 7674:         } else {
 7675:             $domusage{$role} = &mt('Any user in domain with active [_1] or [_2] role',
 7676:                                    &Apache::lonnet::plaintext('dh'),&Apache::lonnet::plaintext('da'));
 7677:         }
 7678:     }
 7679:     return %domusage;
 7680: }
 7681: 
 7682: sub get_domain_customroles {
 7683:     my ($cdom,$confname) = @_;
 7684:     my %existing=&Apache::lonnet::dump('roles',$cdom,$confname,'rolesdef_');
 7685:     my %customroles;
 7686:     foreach my $key (keys(%existing)) {
 7687:         if ($key=~/^rolesdef\_(\w+)$/) {
 7688:             my $rolename = $1;
 7689:             my %privs;
 7690:             ($privs{'system'},$privs{'domain'},$privs{'course'}) = split(/\_/,$existing{$key});
 7691:             $customroles{$rolename} = \%privs;
 7692:         }
 7693:     }
 7694:     return %customroles;
 7695: }
 7696: 
 7697: sub role_priv_table {
 7698:     my ($role,$permission,$crstype,$full,$levels,$levelscurrent,$overridden) = @_;
 7699:     return unless ((ref($full) eq 'HASH') && (ref($levels) eq 'HASH') &&
 7700:                    (ref($levelscurrent) eq 'HASH'));
 7701:     my %lt=&Apache::lonlocal::texthash (
 7702:                     'crl'  => 'Course Level Privilege',
 7703:                     'def'  => 'Domain Defaults',
 7704:                     'ove'  => 'Override in Course',
 7705:                     'ine'  => 'In effect',
 7706:                     'dis'  => 'Disabled',
 7707:                     'ena'  => 'Enabled',
 7708:                    );
 7709:     if ($crstype eq 'Community') {
 7710:         $lt{'ove'} = 'Override in Community',
 7711:     }
 7712:     my @status = ('Disabled','Enabled');
 7713:     my (%on,%off);
 7714:     if (ref($overridden) eq 'HASH') {
 7715:         if (ref($overridden->{'on'}) eq 'ARRAY') {
 7716:             map { $on{$_} = 1; } (@{$overridden->{'on'}});
 7717:         }
 7718:         if (ref($overridden->{'off'}) eq 'ARRAY') {
 7719:             map { $off{$_} = 1; } (@{$overridden->{'off'}});
 7720:         }
 7721:     }
 7722:     my $output=&Apache::loncommon::start_data_table().
 7723:                &Apache::loncommon::start_data_table_header_row().
 7724:                '<th>'.$lt{'crl'}.'</th><th>'.$lt{'def'}.'</th><th>'.$lt{'ove'}.
 7725:                '</th><th>'.$lt{'ine'}.'</th>'.
 7726:                &Apache::loncommon::end_data_table_header_row();
 7727:     foreach my $priv (sort(keys(%{$full}))) {
 7728:         next unless ($levels->{'course'}{$priv});
 7729:         my $privtext = &Apache::lonnet::plaintext($priv,$crstype);
 7730:         my ($default,$ineffect);
 7731:         if ($levelscurrent->{'course'}{$priv}) {
 7732:             $default = '<img src="/adm/lonIcons/navmap.correct.gif" alt="'.$lt{'ena'}.'" />';
 7733:             $ineffect = $default;
 7734:         }
 7735:         my ($customstatus,$checked);
 7736:         $output .= &Apache::loncommon::start_data_table_row().
 7737:                    '<td>'.$privtext.'</td>'.
 7738:                    '<td>'.$default.'</td><td>';
 7739:         if (($levelscurrent->{'course'}{$priv}) && ($off{$priv})) {
 7740:             if ($permission->{'owner'}) {
 7741:                 $checked = ' checked="checked"';
 7742:             }
 7743:             $customstatus = '<img src="/adm/lonIcons/navmap.wrong.gif" alt="'.$lt{'dis'}.'" />';
 7744:             $ineffect = $customstatus;
 7745:         } elsif ((!$levelscurrent->{'course'}{$priv}) && ($on{$priv})) {
 7746:             if ($permission->{'owner'}) {
 7747:                 $checked = ' checked="checked"';
 7748:             }
 7749:             $customstatus = '<img src="/adm/lonIcons/navmap.correct.gif" alt="'.$lt{'ena'}.'" />';
 7750:             $ineffect = $customstatus;
 7751:         }
 7752:         if ($permission->{'owner'}) {
 7753:             $output .= '<input type="checkbox" name="'.$role.'_override" value="'.$priv.'"'.$checked.' />';
 7754:         } else {
 7755:             $output .= $customstatus;
 7756:         }
 7757:         $output .= '</td><td>'.$ineffect.'</td>'.
 7758:                    &Apache::loncommon::end_data_table_row();
 7759:     }
 7760:     $output .= &Apache::loncommon::end_data_table();
 7761:     return $output;
 7762: }
 7763: 
 7764: sub get_adhocrole_settings {
 7765:     my ($cid,$accesstypes,$types,$customroles,$settings,$overridden) = @_;
 7766:     return unless ((ref($accesstypes) eq 'ARRAY') && (ref($customroles) eq 'HASH') &&
 7767:                    (ref($settings) eq 'HASH') && (ref($overridden) eq 'HASH'));
 7768:     foreach my $role (split(/,/,$env{'course.'.$cid.'.internal.adhocaccess'})) {
 7769:         my ($curraccess,$rest) = split(/=/,$env{'course.'.$cid.'.internal.adhoc.'.$role});
 7770:         if (($curraccess ne '') && (grep(/^\Q$curraccess\E$/,@{$accesstypes}))) {
 7771:             $settings->{$role}{'access'} = $curraccess;
 7772:             if (($curraccess eq 'status') && (ref($types) eq 'ARRAY')) {
 7773:                 my @status = split(/,/,$rest);
 7774:                 my @currstatus;
 7775:                 foreach my $type (@status) {
 7776:                     if ($type eq 'default') {
 7777:                         push(@currstatus,$type);
 7778:                     } elsif (grep(/^\Q$type\E$/,@{$types})) {
 7779:                         push(@currstatus,$type);
 7780:                     }
 7781:                 }
 7782:                 if (@currstatus) {
 7783:                     $settings->{$role}{$curraccess} = \@currstatus;
 7784:                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 7785:                     my @personnel = split(/,/,$rest);
 7786:                     $settings->{$role}{$curraccess} = \@personnel;
 7787:                 }
 7788:             }
 7789:         }
 7790:     }
 7791:     foreach my $role (keys(%{$customroles})) {
 7792:         if ($env{'course.'.$cid.'.internal.adhocpriv.'.$role}) {
 7793:             my %currentprivs;
 7794:             if (ref($customroles->{$role}) eq 'HASH') {
 7795:                 if (exists($customroles->{$role}{'course'})) {
 7796:                     my %full=();
 7797:                     my %levels= (
 7798:                                   course => {},
 7799:                                   domain => {},
 7800:                                   system => {},
 7801:                                 );
 7802:                     my %levelscurrent=(
 7803:                                         course => {},
 7804:                                         domain => {},
 7805:                                         system => {},
 7806:                                       );
 7807:                     &Apache::lonuserutils::custom_role_privs($customroles->{$role},\%full,\%levels,\%levelscurrent);
 7808:                     %currentprivs = %{$levelscurrent{'course'}};
 7809:                 }
 7810:             }
 7811:             foreach my $item (split(/,/,$env{'course.'.$cid.'.internal.adhocpriv.'.$role})) {
 7812:                 next if ($item eq '');
 7813:                 my ($rule,$rest) = split(/=/,$item);
 7814:                 next unless (($rule eq 'off') || ($rule eq 'on'));
 7815:                 foreach my $priv (split(/:/,$rest)) {
 7816:                     if ($priv ne '') {
 7817:                         if ($rule eq 'off') {
 7818:                             push(@{$overridden->{$role}{'off'}},$priv);
 7819:                             if ($currentprivs{$priv}) {
 7820:                                 push(@{$settings->{$role}{'off'}},$priv);
 7821:                             }
 7822:                         } else {
 7823:                             push(@{$overridden->{$role}{'on'}},$priv);
 7824:                             unless ($currentprivs{$priv}) {
 7825:                                 push(@{$settings->{$role}{'on'}},$priv);
 7826:                             }
 7827:                         }
 7828:                     }
 7829:                 }
 7830:             }
 7831:         }
 7832:     }
 7833:     return;
 7834: }
 7835: 
 7836: sub update_helpdeskaccess {
 7837:     my ($r,$permission,$brcrum) = @_;
 7838:     my $helpitem = 'Course_Helpdesk_Access';
 7839:     push (@{$brcrum},
 7840:              {href => '/adm/createuser?action=helpdesk',
 7841:               text => 'Helpdesk Access',
 7842:               help => $helpitem},
 7843:              {href => '/adm/createuser?action=helpdesk',
 7844:               text => 'Result',
 7845:               help => $helpitem}
 7846:          );
 7847:     my $bread_crumbs_component = 'Helpdesk Staff Access';
 7848:     my $args = { bread_crumbs           => $brcrum,
 7849:                  bread_crumbs_component => $bread_crumbs_component};
 7850: 
 7851:     # print page header
 7852:     $r->print(&header('',$args));
 7853:     unless ((ref($permission) eq 'HASH') && ($permission->{'owner'})) {
 7854:         $r->print('<p class="LC_error">'.&mt('You do not have permission to change helpdesk access.').'</p>');
 7855:         return;
 7856:     }
 7857:     my @accesstypes = ('all','dh','da','none','status','inc','exc');
 7858:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7859:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7860:     my $confname = $cdom.'-domainconfig';
 7861:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($cdom);
 7862:     my $crstype = &Apache::loncommon::course_type();
 7863:     my %customroles = &get_domain_customroles($cdom,$confname);
 7864:     my (%settings,%overridden);
 7865:     &get_adhocrole_settings($env{'request.course.id'},\@accesstypes,
 7866:                             $types,\%customroles,\%settings,\%overridden);
 7867:     my %domhelpdesk = &Apache::lonnet::get_active_domroles($cdom,['dh','da']);
 7868:     my (%changed,%storehash,@todelete);
 7869: 
 7870:     if (keys(%customroles)) {
 7871:         my (%newsettings,@incrs);
 7872:         foreach my $role (keys(%customroles)) {
 7873:             $newsettings{$role} = {
 7874:                                     access => '',
 7875:                                     status => '',
 7876:                                     exc    => '',
 7877:                                     inc    => '',
 7878:                                     on     => '',
 7879:                                     off    => '',
 7880:                                   };
 7881:             my %current;
 7882:             if (ref($settings{$role}) eq 'HASH') {
 7883:                 %current = %{$settings{$role}};
 7884:             }
 7885:             if (ref($overridden{$role}) eq 'HASH') {
 7886:                 $current{'overridden'} = $overridden{$role};
 7887:             }
 7888:             if ($env{'form.'.$role.'_incrs'}) {
 7889:                 my $access = $env{'form.'.$role.'_access'};
 7890:                 if (grep(/^\Q$access\E$/,@accesstypes)) {
 7891:                     push(@incrs,$role);
 7892:                     unless ($current{'access'} eq $access) {
 7893:                         $changed{$role}{'access'} = 1;
 7894:                         $storehash{'internal.adhoc.'.$role} = $access;
 7895:                     }
 7896:                     if ($access eq 'status') {
 7897:                         my @statuses = &Apache::loncommon::get_env_multiple('form.'.$role.'_status');
 7898:                         my @stored;
 7899:                         my @shownstatus;
 7900:                         if (ref($types) eq 'ARRAY') {
 7901:                             foreach my $type (sort(@statuses)) {
 7902:                                 if ($type eq 'default') {
 7903:                                     push(@stored,$type);
 7904:                                 } elsif (grep(/^\Q$type\E$/,@{$types})) {
 7905:                                     push(@stored,$type);
 7906:                                     push(@shownstatus,$usertypes->{$type});
 7907:                                 }
 7908:                             }
 7909:                             if (grep(/^default$/,@statuses)) {
 7910:                                 push(@shownstatus,$othertitle);
 7911:                             }
 7912:                             $storehash{'internal.adhoc.'.$role} .= '='.join(',',@stored);
 7913:                         }
 7914:                         $newsettings{$role}{'status'} = join(' '.&mt('or').' ',@shownstatus);
 7915:                         if (ref($current{'status'}) eq 'ARRAY') {
 7916:                             my @diffs = &Apache::loncommon::compare_arrays(\@stored,$current{'status'});
 7917:                             if (@diffs) {
 7918:                                 $changed{$role}{'status'} = 1;
 7919:                             }
 7920:                         } elsif (@stored) {
 7921:                             $changed{$role}{'status'} = 1;
 7922:                         }
 7923:                     } elsif (($access eq 'inc') || ($access eq 'exc')) {
 7924:                         my @personnel = &Apache::loncommon::get_env_multiple('form.'.$role.'_staff_'.$access);
 7925:                         my @newspecstaff;
 7926:                         my @stored;
 7927:                         my @currstaff;
 7928:                         foreach my $person (sort(@personnel)) {
 7929:                             if ($domhelpdesk{$person}) {
 7930:                                 push(@stored,$person);
 7931:                             }
 7932:                         }
 7933:                         if (ref($current{$access}) eq 'ARRAY') {
 7934:                             my @diffs = &Apache::loncommon::compare_arrays(\@stored,$current{$access});
 7935:                             if (@diffs) {
 7936:                                 $changed{$role}{$access} = 1;
 7937:                             }
 7938:                         } elsif (@stored) {
 7939:                             $changed{$role}{$access} = 1;
 7940:                         }
 7941:                         $storehash{'internal.adhoc.'.$role} .= '='.join(',',@stored);
 7942:                         foreach my $person (@stored) {
 7943:                             my ($uname,$udom) = split(/:/,$person);
 7944:                             push(@newspecstaff,&Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($uname,$udom,'lastname'),$uname,$udom));
 7945:                         }
 7946:                         $newsettings{$role}{$access} = join(', ',sort(@newspecstaff));
 7947:                     }
 7948:                     $newsettings{$role}{'access'} = $access;
 7949:                 }
 7950:             } else {
 7951:                 if (($current{'access'} ne '') && (grep(/^\Q$current{'access'}\E$/,@accesstypes))) {
 7952:                     $changed{$role}{'access'} = 1;
 7953:                     $newsettings{$role} = {};
 7954:                     push(@todelete,'internal.adhoc.'.$role);
 7955:                 }
 7956:             }
 7957:             if (($env{'form.'.$role.'_incrs'}) && ($env{'form.'.$role.'_access'} eq 'none')) {
 7958:                 if (ref($current{'overridden'}) eq 'HASH') {
 7959:                     push(@todelete,'internal.adhocpriv.'.$role);
 7960:                 }
 7961:             } else {
 7962:                 my %full=();
 7963:                 my %levels= (
 7964:                              course => {},
 7965:                              domain => {},
 7966:                              system => {},
 7967:                             );
 7968:                 my %levelscurrent=(
 7969:                                    course => {},
 7970:                                    domain => {},
 7971:                                    system => {},
 7972:                                   );
 7973:                 &Apache::lonuserutils::custom_role_privs($customroles{$role},\%full,\%levels,\%levelscurrent);
 7974:                 my (@updatedon,@updatedoff,@override);
 7975:                 @override = &Apache::loncommon::get_env_multiple('form.'.$role.'_override');
 7976:                 if (@override) {
 7977:                     foreach my $priv (sort(keys(%full))) {
 7978:                         next unless ($levels{'course'}{$priv});
 7979:                         if (grep(/^\Q$priv\E$/,@override)) {
 7980:                             if ($levelscurrent{'course'}{$priv}) {
 7981:                                 push(@updatedoff,$priv);
 7982:                             } else {
 7983:                                 push(@updatedon,$priv);
 7984:                             }
 7985:                         }
 7986:                     }
 7987:                 }
 7988:                 if (@updatedon) {
 7989:                     $newsettings{$role}{'on'} = join('</li><li>', map { &Apache::lonnet::plaintext($_,$crstype) } (@updatedon));
 7990:                 }
 7991:                 if (@updatedoff) {
 7992:                     $newsettings{$role}{'off'} = join('</li><li>', map { &Apache::lonnet::plaintext($_,$crstype) } (@updatedoff));
 7993:                 }
 7994:                 if (ref($current{'overridden'}) eq 'HASH') {
 7995:                     if (ref($current{'overridden'}{'on'}) eq 'ARRAY') {
 7996:                         if (@updatedon) {
 7997:                             my @diffs = &Apache::loncommon::compare_arrays(\@updatedon,$current{'overridden'}{'on'});
 7998:                             if (@diffs) {
 7999:                                 $changed{$role}{'on'} = 1;
 8000:                             }
 8001:                         } else {
 8002:                             $changed{$role}{'on'} = 1;
 8003:                         }
 8004:                     } elsif (@updatedon) {
 8005:                         $changed{$role}{'on'} = 1;
 8006:                     }
 8007:                     if (ref($current{'overridden'}{'off'}) eq 'ARRAY') {
 8008:                         if (@updatedoff) {
 8009:                             my @diffs = &Apache::loncommon::compare_arrays(\@updatedoff,$current{'overridden'}{'off'});
 8010:                             if (@diffs) {
 8011:                                 $changed{$role}{'off'} = 1;
 8012:                             }
 8013:                         } else {
 8014:                             $changed{$role}{'off'} = 1;
 8015:                         }
 8016:                     } elsif (@updatedoff) {
 8017:                         $changed{$role}{'off'} = 1;
 8018:                     }
 8019:                 } else {
 8020:                     if (@updatedon) {
 8021:                         $changed{$role}{'on'} = 1;
 8022:                     }
 8023:                     if (@updatedoff) {
 8024:                         $changed{$role}{'off'} = 1;
 8025:                     }
 8026:                 }
 8027:                 if (ref($changed{$role}) eq 'HASH') {
 8028:                     if (($changed{$role}{'on'} || $changed{$role}{'off'})) {
 8029:                         my $newpriv;
 8030:                         if (@updatedon) {
 8031:                             $newpriv = 'on='.join(':',@updatedon);
 8032:                         }
 8033:                         if (@updatedoff) {
 8034:                             $newpriv .= ($newpriv ? ',' : '' ).'off='.join(':',@updatedoff);
 8035:                         }
 8036:                         if ($newpriv eq '') {
 8037:                             push(@todelete,'internal.adhocpriv.'.$role);
 8038:                         } else {
 8039:                             $storehash{'internal.adhocpriv.'.$role} = $newpriv;
 8040:                         }
 8041:                     }
 8042:                 }
 8043:             }
 8044:         }
 8045:         if (@incrs) {
 8046:             $storehash{'internal.adhocaccess'} = join(',',@incrs);
 8047:         } elsif (@todelete) {
 8048:             push(@todelete,'internal.adhocaccess');
 8049:         }
 8050:         if (keys(%changed)) {
 8051:             my ($putres,$delres);
 8052:             if (keys(%storehash)) {
 8053:                 $putres = &Apache::lonnet::put('environment',\%storehash,$cdom,$cnum);
 8054:                 my %newenvhash;
 8055:                 foreach my $key (keys(%storehash)) {
 8056:                     $newenvhash{'course.'.$env{'request.course.id'}.'.'.$key} = $storehash{$key};
 8057:                 }
 8058:                 &Apache::lonnet::appenv(\%newenvhash);
 8059:             }
 8060:             if (@todelete) {
 8061:                 $delres = &Apache::lonnet::del('environment',\@todelete,$cdom,$cnum);
 8062:                 foreach my $key (@todelete) {
 8063:                     &Apache::lonnet::delenv('course.'.$env{'request.course.id'}.'.'.$key);
 8064:                 }
 8065:             }
 8066:             if (($putres eq 'ok') || ($delres eq 'ok')) {
 8067:                 my %domconfig = &Apache::lonnet::get_dom('configuration',['helpsettings'],$cdom);
 8068:                 my (%domcurrent,%ordered,%description,%domusage);
 8069:                 if (ref($domconfig{'helpsettings'}) eq 'HASH') {
 8070:                     if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
 8071:                         %domcurrent = %{$domconfig{'helpsettings'}{'adhoc'}};
 8072:                     }
 8073:                 }
 8074:                 my $count = 0;
 8075:                 foreach my $role (sort(keys(%customroles))) {
 8076:                     my ($order,$desc);
 8077:                     if (ref($domcurrent{$role}) eq 'HASH') {
 8078:                         $order = $domcurrent{$role}{'order'};
 8079:                         $desc = $domcurrent{$role}{'desc'};
 8080:                     }
 8081:                     if ($order eq '') {
 8082:                         $order = $count;
 8083:                     }
 8084:                     $ordered{$order} = $role;
 8085:                     if ($desc ne '') {
 8086:                         $description{$role} = $desc;
 8087:                     } else {
 8088:                         $description{$role}= $role;
 8089:                     }
 8090:                     $count++;
 8091:                 }
 8092:                 my @roles_by_num = ();
 8093:                 foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 8094:                     push(@roles_by_num,$ordered{$item});
 8095:                 }
 8096:                 %domusage = &domain_adhoc_access(\%changed,\%domcurrent,\@accesstypes,$usertypes,$othertitle);
 8097:                 $r->print(&mt('Helpdesk access settings have been changed as follows').'<br />');
 8098:                 $r->print('<ul>');
 8099:                 foreach my $role (@roles_by_num) {
 8100:                     next unless (ref($changed{$role}) eq 'HASH');
 8101:                     $r->print('<li>'.&mt('Ad hoc role').': <b>'.$description{$role}.'</b>'.
 8102:                               '<ul>');
 8103:                     if ($changed{$role}{'access'} || $changed{$role}{'status'} || $changed{$role}{'inc'} || $changed{$role}{'exc'}) {
 8104:                         $r->print('<li>');
 8105:                         if ($env{'form.'.$role.'_incrs'}) {
 8106:                             if ($newsettings{$role}{'access'} eq 'all') {
 8107:                                 $r->print(&mt('All helpdesk staff can access '.lc($crstype).' with this role.'));
 8108:                             } elsif ($newsettings{$role}{'access'} eq 'dh') {
 8109:                                 $r->print(&mt('Helpdesk staff can use this role if they have an active [_1] role',
 8110:                                               &Apache::lonnet::plaintext('dh')));
 8111:                             } elsif ($newsettings{$role}{'access'} eq 'da') {
 8112:                                 $r->print(&mt('Helpdesk staff can use this role if they have an active [_1] role',
 8113:                                               &Apache::lonnet::plaintext('da')));
 8114:                             } elsif ($newsettings{$role}{'access'} eq 'none') {
 8115:                                 $r->print(&mt('No helpdesk staff can access '.lc($crstype).' with this role.'));
 8116:                             } elsif ($newsettings{$role}{'access'} eq 'status') {
 8117:                                 if ($newsettings{$role}{'status'}) {
 8118:                                     my ($access,$rest) = split(/=/,$storehash{'internal.adhoc.'.$role});
 8119:                                     if (split(/,/,$rest) > 1) {
 8120:                                         $r->print(&mt('Helpdesk staff can use this role if their institutional type is one of: [_1].',
 8121:                                                       $newsettings{$role}{'status'}));
 8122:                                     } else {
 8123:                                         $r->print(&mt('Helpdesk staff can use this role if their institutional type is: [_1].',
 8124:                                                       $newsettings{$role}{'status'}));
 8125:                                     }
 8126:                                 } else {
 8127:                                     $r->print(&mt('No helpdesk staff can access '.lc($crstype).' with this role.'));
 8128:                                 }
 8129:                             } elsif ($newsettings{$role}{'access'} eq 'exc') {
 8130:                                 if ($newsettings{$role}{'exc'}) {
 8131:                                     $r->print(&mt('Helpdesk staff who can use this role are as follows:').' '.$newsettings{$role}{'exc'}.'.');
 8132:                                 } else {
 8133:                                     $r->print(&mt('No helpdesk staff can access '.lc($crstype).' with this role.'));
 8134:                                 }
 8135:                             } elsif ($newsettings{$role}{'access'} eq 'inc') {
 8136:                                 if ($newsettings{$role}{'inc'}) {
 8137:                                     $r->print(&mt('All helpdesk staff may use this role except the following:').' '.$newsettings{$role}{'inc'}.'.');
 8138:                                 } else {
 8139:                                     $r->print(&mt('All helpdesk staff may use this role.'));
 8140:                                 }
 8141:                             }
 8142:                         } else {
 8143:                             $r->print(&mt('Default access set in the domain now applies.').'<br />'.
 8144:                                       '<span class="LC_cusr_emph">'.$domusage{$role}.'</span>');
 8145:                         }
 8146:                         $r->print('</li>');
 8147:                     }
 8148:                     unless ($newsettings{$role}{'access'} eq 'none') {
 8149:                         if ($changed{$role}{'off'}) {
 8150:                             if ($newsettings{$role}{'off'}) {
 8151:                                 $r->print('<li>'.&mt('Privileges which are available by default for this ad hoc role, but are disabled for this specific '.lc($crstype).':').
 8152:                                           '<ul><li>'.$newsettings{$role}{'off'}.'</li></ul></li>');
 8153:                             } else {
 8154:                                 $r->print('<li>'.&mt('All privileges available by default for this ad hoc role are enabled.').'</li>');
 8155:                             }
 8156:                         }
 8157:                         if ($changed{$role}{'on'}) {
 8158:                             if ($newsettings{$role}{'on'}) {
 8159:                                 $r->print('<li>'.&mt('Privileges which are not available by default for this ad hoc role, but are enabled for this specific '.lc($crstype).':').
 8160:                                           '<ul><li>'.$newsettings{$role}{'on'}.'</li></ul></li>');
 8161:                             } else {
 8162:                                 $r->print('<li>'.&mt('None of the privileges unavailable by default for this ad hoc role are enabled.').'</li>');
 8163:                             }
 8164:                         }
 8165:                     }
 8166:                     $r->print('</ul></li>');
 8167:                 }
 8168:                 $r->print('</ul>');
 8169:             }
 8170:         } else {
 8171:             $r->print(&mt('No changes made to helpdesk access settings.'));
 8172:         }
 8173:     }
 8174:     return;
 8175: }
 8176: 
 8177: #-------------------------------------------------- functions for &phase_two
 8178: sub user_search_result {
 8179:     my ($context,$srch) = @_;
 8180:     my %allhomes;
 8181:     my %inst_matches;
 8182:     my %srch_results;
 8183:     my ($response,$currstate,$forcenewuser,$dirsrchres);
 8184:     $srch->{'srchterm'} =~ s/\s+/ /g;
 8185:     if ($srch->{'srchby'} !~ /^(uname|lastname|lastfirst)$/) {
 8186:         $response = &mt('Invalid search.');
 8187:     }
 8188:     if ($srch->{'srchin'} !~ /^(crs|dom|alc|instd)$/) {
 8189:         $response = &mt('Invalid search.');
 8190:     }
 8191:     if ($srch->{'srchtype'} !~ /^(exact|contains|begins)$/) {
 8192:         $response = &mt('Invalid search.');
 8193:     }
 8194:     if ($srch->{'srchterm'} eq '') {
 8195:         $response = &mt('You must enter a search term.');
 8196:     }
 8197:     if ($srch->{'srchterm'} =~ /^\s+$/) {
 8198:         $response = &mt('Your search term must contain more than just spaces.');
 8199:     }
 8200:     if (($srch->{'srchin'} eq 'dom') || ($srch->{'srchin'} eq 'instd')) {
 8201:         if (($srch->{'srchdomain'} eq '') || 
 8202: 	    ! (&Apache::lonnet::domain($srch->{'srchdomain'}))) {
 8203:             $response = &mt('You must specify a valid domain when searching in a domain or institutional directory.')
 8204:         }
 8205:     }
 8206:     if (($srch->{'srchin'} eq 'dom') || ($srch->{'srchin'} eq 'crs') ||
 8207:         ($srch->{'srchin'} eq 'alc')) {
 8208:         if ($srch->{'srchby'} eq 'uname') {
 8209:             my $unamecheck = $srch->{'srchterm'};
 8210:             if ($srch->{'srchtype'} eq 'contains') {
 8211:                 if ($unamecheck !~ /^\w/) {
 8212:                     $unamecheck = 'a'.$unamecheck; 
 8213:                 }
 8214:             }
 8215:             if ($unamecheck !~ /^$match_username$/) {
 8216:                 $response = &mt('You must specify a valid username. Only the following are allowed: letters numbers - . @');
 8217:             }
 8218:         }
 8219:     }
 8220:     if ($response ne '') {
 8221:         $response = '<span class="LC_warning">'.$response.'</span><br />';
 8222:     }
 8223:     if ($srch->{'srchin'} eq 'instd') {
 8224:         my $instd_chk = &instdirectorysrch_check($srch);
 8225:         if ($instd_chk ne 'ok') {
 8226:             my $domd_chk = &domdirectorysrch_check($srch);
 8227:             $response .= '<span class="LC_warning">'.$instd_chk.'</span><br />';
 8228:             if ($domd_chk eq 'ok') {
 8229:                 $response .= &mt('You may want to search in the LON-CAPA domain instead of in the institutional directory.');
 8230:             }
 8231:             $response .= '<br />';
 8232:         }
 8233:     } else {
 8234:         unless (($context eq 'requestcrs') && ($srch->{'srchtype'} eq 'exact')) {
 8235:             my $domd_chk = &domdirectorysrch_check($srch);
 8236:             if ($domd_chk ne 'ok') {
 8237:                 my $instd_chk = &instdirectorysrch_check($srch);
 8238:                 $response .= '<span class="LC_warning">'.$domd_chk.'</span><br />';
 8239:                 if ($instd_chk eq 'ok') {
 8240:                     $response .= &mt('You may want to search in the institutional directory instead of in the LON-CAPA domain.');
 8241:                 }
 8242:                 $response .= '<br />';
 8243:             }
 8244:         }
 8245:     }
 8246:     if ($response ne '') {
 8247:         return ($currstate,$response);
 8248:     }
 8249:     if ($srch->{'srchby'} eq 'uname') {
 8250:         if (($srch->{'srchin'} eq 'dom') || ($srch->{'srchin'} eq 'crs')) {
 8251:             if ($env{'form.forcenew'}) {
 8252:                 if ($srch->{'srchdomain'} ne $env{'request.role.domain'}) {
 8253:                     my $uhome=&Apache::lonnet::homeserver($srch->{'srchterm'},$srch->{'srchdomain'});
 8254:                     if ($uhome eq 'no_host') {
 8255:                         my $domdesc = &Apache::lonnet::domain($env{'request.role.domain'},'description');
 8256:                         my $showdom = &display_domain_info($env{'request.role.domain'});
 8257:                         $response = &mt('New users can only be created in the domain to which your current role belongs - [_1].',$showdom);
 8258:                     } else {
 8259:                         $currstate = 'modify';
 8260:                     }
 8261:                 } else {
 8262:                     $currstate = 'modify';
 8263:                 }
 8264:             } else {
 8265:                 if ($srch->{'srchin'} eq 'dom') {
 8266:                     if ($srch->{'srchtype'} eq 'exact') {
 8267:                         my $uhome=&Apache::lonnet::homeserver($srch->{'srchterm'},$srch->{'srchdomain'});
 8268:                         if ($uhome eq 'no_host') {
 8269:                             ($currstate,$response,$forcenewuser) =
 8270:                                 &build_search_response($context,$srch,%srch_results);
 8271:                         } else {
 8272:                             $currstate = 'modify';
 8273:                             if ($env{'form.action'} eq 'accesslogs') {
 8274:                                 $currstate = 'activity';
 8275:                             }
 8276:                             my $uname = $srch->{'srchterm'};
 8277:                             my $udom = $srch->{'srchdomain'};
 8278:                             $srch_results{$uname.':'.$udom} =
 8279:                                 { &Apache::lonnet::get('environment',
 8280:                                                        ['firstname',
 8281:                                                         'lastname',
 8282:                                                         'permanentemail'],
 8283:                                                          $udom,$uname)
 8284:                                 };
 8285:                         }
 8286:                     } else {
 8287:                         %srch_results = &Apache::lonnet::usersearch($srch);
 8288:                         ($currstate,$response,$forcenewuser) =
 8289:                             &build_search_response($context,$srch,%srch_results);
 8290:                     }
 8291:                 } else {
 8292:                     my $courseusers = &get_courseusers();
 8293:                     if ($srch->{'srchtype'} eq 'exact') {
 8294:                         if (exists($courseusers->{$srch->{'srchterm'}.':'.$srch->{'srchdomain'}})) {
 8295:                             $currstate = 'modify';
 8296:                         } else {
 8297:                             ($currstate,$response,$forcenewuser) =
 8298:                                 &build_search_response($context,$srch,%srch_results);
 8299:                         }
 8300:                     } else {
 8301:                         foreach my $user (keys(%$courseusers)) {
 8302:                             my ($cuname,$cudomain) = split(/:/,$user);
 8303:                             if ($cudomain eq $srch->{'srchdomain'}) {
 8304:                                 my $matched = 0;
 8305:                                 if ($srch->{'srchtype'} eq 'begins') {
 8306:                                     if ($cuname =~ /^\Q$srch->{'srchterm'}\E/i) {
 8307:                                         $matched = 1;
 8308:                                     }
 8309:                                 } else {
 8310:                                     if ($cuname =~ /\Q$srch->{'srchterm'}\E/i) {
 8311:                                         $matched = 1;
 8312:                                     }
 8313:                                 }
 8314:                                 if ($matched) {
 8315:                                     $srch_results{$user} = 
 8316: 					{&Apache::lonnet::get('environment',
 8317: 							     ['firstname',
 8318: 							      'lastname',
 8319: 							      'permanentemail'],
 8320: 							      $cudomain,$cuname)};
 8321:                                 }
 8322:                             }
 8323:                         }
 8324:                         ($currstate,$response,$forcenewuser) =
 8325:                             &build_search_response($context,$srch,%srch_results);
 8326:                     }
 8327:                 }
 8328:             }
 8329:         } elsif ($srch->{'srchin'} eq 'alc') {
 8330:             $currstate = 'query';
 8331:         } elsif ($srch->{'srchin'} eq 'instd') {
 8332:             ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query($srch);
 8333:             if ($dirsrchres eq 'ok') {
 8334:                 ($currstate,$response,$forcenewuser) = 
 8335:                     &build_search_response($context,$srch,%srch_results);
 8336:             } else {
 8337:                 my $showdom = &display_domain_info($srch->{'srchdomain'});
 8338:                 $response = '<span class="LC_warning">'.
 8339:                     &mt('Institutional directory search is not available in domain: [_1]',$showdom).
 8340:                     '</span><br />'.
 8341:                     &mt('You may want to search in the LON-CAPA domain instead of in the institutional directory.').
 8342:                     '<br />'; 
 8343:             }
 8344:         }
 8345:     } else {
 8346:         if ($srch->{'srchin'} eq 'dom') {
 8347:             %srch_results = &Apache::lonnet::usersearch($srch);
 8348:             ($currstate,$response,$forcenewuser) = 
 8349:                 &build_search_response($context,$srch,%srch_results); 
 8350:         } elsif ($srch->{'srchin'} eq 'crs') {
 8351:             my $courseusers = &get_courseusers(); 
 8352:             foreach my $user (keys(%$courseusers)) {
 8353:                 my ($uname,$udom) = split(/:/,$user);
 8354:                 my %names = &Apache::loncommon::getnames($uname,$udom);
 8355:                 my %emails = &Apache::loncommon::getemails($uname,$udom);
 8356:                 if ($srch->{'srchby'} eq 'lastname') {
 8357:                     if ((($srch->{'srchtype'} eq 'exact') && 
 8358:                          ($names{'lastname'} eq $srch->{'srchterm'})) || 
 8359:                         (($srch->{'srchtype'} eq 'begins') &&
 8360:                          ($names{'lastname'} =~ /^\Q$srch->{'srchterm'}\E/i)) ||
 8361:                         (($srch->{'srchtype'} eq 'contains') &&
 8362:                          ($names{'lastname'} =~ /\Q$srch->{'srchterm'}\E/i))) {
 8363:                         $srch_results{$user} = {firstname => $names{'firstname'},
 8364:                                             lastname => $names{'lastname'},
 8365:                                             permanentemail => $emails{'permanentemail'},
 8366:                                            };
 8367:                     }
 8368:                 } elsif ($srch->{'srchby'} eq 'lastfirst') {
 8369:                     my ($srchlast,$srchfirst) = split(/,/,$srch->{'srchterm'});
 8370:                     $srchlast =~ s/\s+$//;
 8371:                     $srchfirst =~ s/^\s+//;
 8372:                     if ($srch->{'srchtype'} eq 'exact') {
 8373:                         if (($names{'lastname'} eq $srchlast) &&
 8374:                             ($names{'firstname'} eq $srchfirst)) {
 8375:                             $srch_results{$user} = {firstname => $names{'firstname'},
 8376:                                                 lastname => $names{'lastname'},
 8377:                                                 permanentemail => $emails{'permanentemail'},
 8378: 
 8379:                                            };
 8380:                         }
 8381:                     } elsif ($srch->{'srchtype'} eq 'begins') {
 8382:                         if (($names{'lastname'} =~ /^\Q$srchlast\E/i) &&
 8383:                             ($names{'firstname'} =~ /^\Q$srchfirst\E/i)) {
 8384:                             $srch_results{$user} = {firstname => $names{'firstname'},
 8385:                                                 lastname => $names{'lastname'},
 8386:                                                 permanentemail => $emails{'permanentemail'},
 8387:                                                };
 8388:                         }
 8389:                     } else {
 8390:                         if (($names{'lastname'} =~ /\Q$srchlast\E/i) && 
 8391:                             ($names{'firstname'} =~ /\Q$srchfirst\E/i)) {
 8392:                             $srch_results{$user} = {firstname => $names{'firstname'},
 8393:                                                 lastname => $names{'lastname'},
 8394:                                                 permanentemail => $emails{'permanentemail'},
 8395:                                                };
 8396:                         }
 8397:                     }
 8398:                 }
 8399:             }
 8400:             ($currstate,$response,$forcenewuser) = 
 8401:                 &build_search_response($context,$srch,%srch_results); 
 8402:         } elsif ($srch->{'srchin'} eq 'alc') {
 8403:             $currstate = 'query';
 8404:         } elsif ($srch->{'srchin'} eq 'instd') {
 8405:             ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query($srch); 
 8406:             if ($dirsrchres eq 'ok') {
 8407:                 ($currstate,$response,$forcenewuser) = 
 8408:                     &build_search_response($context,$srch,%srch_results);
 8409:             } else {
 8410:                 my $showdom = &display_domain_info($srch->{'srchdomain'});
 8411:                 $response = '<span class="LC_warning">'.
 8412:                     &mt('Institutional directory search is not available in domain: [_1]',$showdom).
 8413:                     '</span><br />'.
 8414:                     &mt('You may want to search in the LON-CAPA domain instead of in the institutional directory.').
 8415:                     '<br />';
 8416:             }
 8417:         }
 8418:     }
 8419:     return ($currstate,$response,$forcenewuser,\%srch_results);
 8420: }
 8421: 
 8422: sub domdirectorysrch_check {
 8423:     my ($srch) = @_;
 8424:     my $response;
 8425:     my %dom_inst_srch = &Apache::lonnet::get_dom('configuration',
 8426:                                              ['directorysrch'],$srch->{'srchdomain'});
 8427:     my $showdom = &display_domain_info($srch->{'srchdomain'});
 8428:     if (ref($dom_inst_srch{'directorysrch'}) eq 'HASH') {
 8429:         if ($dom_inst_srch{'directorysrch'}{'lcavailable'} eq '0') {
 8430:             return &mt('LON-CAPA directory search is not available in domain: [_1]',$showdom);
 8431:         }
 8432:         if ($dom_inst_srch{'directorysrch'}{'lclocalonly'}) {
 8433:             if ($env{'request.role.domain'} ne $srch->{'srchdomain'}) {
 8434:                 return &mt('LON-CAPA directory search in domain: [_1] is only allowed for users with a current role in the domain.',$showdom);
 8435:             }
 8436:         }
 8437:     }
 8438:     return 'ok';
 8439: }
 8440: 
 8441: sub instdirectorysrch_check {
 8442:     my ($srch) = @_;
 8443:     my $can_search = 0;
 8444:     my $response;
 8445:     my %dom_inst_srch = &Apache::lonnet::get_dom('configuration',
 8446:                                              ['directorysrch'],$srch->{'srchdomain'});
 8447:     my $showdom = &display_domain_info($srch->{'srchdomain'});
 8448:     if (ref($dom_inst_srch{'directorysrch'}) eq 'HASH') {
 8449:         if (!$dom_inst_srch{'directorysrch'}{'available'}) {
 8450:             return &mt('Institutional directory search is not available in domain: [_1]',$showdom); 
 8451:         }
 8452:         if ($dom_inst_srch{'directorysrch'}{'localonly'}) {
 8453:             if ($env{'request.role.domain'} ne $srch->{'srchdomain'}) {
 8454:                 return &mt('Institutional directory search in domain: [_1] is only allowed for users with a current role in the domain.',$showdom); 
 8455:             }
 8456:             my @usertypes = split(/:/,$env{'environment.inststatus'});
 8457:             if (!@usertypes) {
 8458:                 push(@usertypes,'default');
 8459:             }
 8460:             if (ref($dom_inst_srch{'directorysrch'}{'cansearch'}) eq 'ARRAY') {
 8461:                 foreach my $type (@usertypes) {
 8462:                     if (grep(/^\Q$type\E$/,@{$dom_inst_srch{'directorysrch'}{'cansearch'}})) {
 8463:                         $can_search = 1;
 8464:                         last;
 8465:                     }
 8466:                 }
 8467:             }
 8468:             if (!$can_search) {
 8469:                 my ($insttypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($srch->{'srchdomain'});
 8470:                 my @longtypes; 
 8471:                 foreach my $item (@usertypes) {
 8472:                     if (defined($insttypes->{$item})) { 
 8473:                         push (@longtypes,$insttypes->{$item});
 8474:                     } elsif ($item eq 'default') {
 8475:                         push (@longtypes,&mt('other')); 
 8476:                     }
 8477:                 }
 8478:                 my $insttype_str = join(', ',@longtypes); 
 8479:                 return &mt('Institutional directory search in domain: [_1] is not available to your user type: ',$showdom).$insttype_str;
 8480:             }
 8481:         } else {
 8482:             $can_search = 1;
 8483:         }
 8484:     } else {
 8485:         return &mt('Institutional directory search has not been configured for domain: [_1]',$showdom);
 8486:     }
 8487:     my %longtext = &Apache::lonlocal::texthash (
 8488:                        uname     => 'username',
 8489:                        lastfirst => 'last name, first name',
 8490:                        lastname  => 'last name',
 8491:                        contains  => 'contains',
 8492:                        exact     => 'as exact match to',
 8493:                        begins    => 'begins with',
 8494:                    );
 8495:     if ($can_search) {
 8496:         if (ref($dom_inst_srch{'directorysrch'}{'searchby'}) eq 'ARRAY') {
 8497:             if (!grep(/^\Q$srch->{'srchby'}\E$/,@{$dom_inst_srch{'directorysrch'}{'searchby'}})) {
 8498:                 return &mt('Institutional directory search in domain: [_1] is not available for searching by "[_2]"',$showdom,$longtext{$srch->{'srchby'}});
 8499:             }
 8500:         } else {
 8501:             return &mt('Institutional directory search in domain: [_1] is not available.', $showdom);
 8502:         }
 8503:     }
 8504:     if ($can_search) {
 8505:         if (ref($dom_inst_srch{'directorysrch'}{'searchtypes'}) eq 'ARRAY') {
 8506:             if (grep(/^\Q$srch->{'srchtype'}\E/,@{$dom_inst_srch{'directorysrch'}{'searchtypes'}})) {
 8507:                 return 'ok';
 8508:             } else {
 8509:                 return &mt('Institutional directory search in domain [_1] is not available for the requested search type: "[_2]"',$showdom,$longtext{$srch->{'srchtype'}});
 8510:             }
 8511:         } else {
 8512:             if ((($dom_inst_srch{'directorysrch'}{'searchtypes'} eq 'specify') &&
 8513:                  ($srch->{'srchtype'} eq 'exact' || $srch->{'srchtype'} eq 'contains')) ||
 8514:                 ($dom_inst_srch{'directorysrch'}{'searchtypes'} eq $srch->{'srchtype'})) {
 8515:                 return 'ok';
 8516:             } else {
 8517:                 return &mt('Institutional directory search in domain [_1] is not available for the requested search type: "[_2]"',$showdom,$longtext{$srch->{'srchtype'}});
 8518:             }
 8519:         }
 8520:     }
 8521: }
 8522: 
 8523: sub get_courseusers {
 8524:     my %advhash;
 8525:     my $classlist = &Apache::loncoursedata::get_classlist();
 8526:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles();
 8527:     foreach my $role (sort(keys(%coursepersonnel))) {
 8528:         foreach my $user (split(/\,/,$coursepersonnel{$role})) {
 8529: 	    if (!exists($classlist->{$user})) {
 8530: 		$classlist->{$user} = [];
 8531: 	    }
 8532:         }
 8533:     }
 8534:     return $classlist;
 8535: }
 8536: 
 8537: sub build_search_response {
 8538:     my ($context,$srch,%srch_results) = @_;
 8539:     my ($currstate,$response,$forcenewuser);
 8540:     my %names = (
 8541:           'uname'     => 'username',
 8542:           'lastname'  => 'last name',
 8543:           'lastfirst' => 'last name, first name',
 8544:           'crs'       => 'this course',
 8545:           'dom'       => 'LON-CAPA domain',
 8546:           'instd'     => 'the institutional directory for domain',
 8547:     );
 8548: 
 8549:     my %single = (
 8550:                    begins   => 'A match',
 8551:                    contains => 'A match',
 8552:                    exact    => 'An exact match',
 8553:                  );
 8554:     my %nomatch = (
 8555:                    begins   => 'No match',
 8556:                    contains => 'No match',
 8557:                    exact    => 'No exact match',
 8558:                   );
 8559:     if (keys(%srch_results) > 1) {
 8560:         $currstate = 'select';
 8561:     } else {
 8562:         if (keys(%srch_results) == 1) {
 8563:             if ($env{'form.action'} eq 'accesslogs') {
 8564:                 $currstate = 'activity';
 8565:             } else {
 8566:                 $currstate = 'modify';
 8567:             }
 8568:             $response = &mt("$single{$srch->{'srchtype'}} was found for the $names{$srch->{'srchby'}} ([_1]) in $names{$srch->{'srchin'}}.",$srch->{'srchterm'});
 8569:             if ($srch->{'srchin'} eq 'dom' || $srch->{'srchin'} eq 'instd') {
 8570:                 $response .= ': '.&display_domain_info($srch->{'srchdomain'});
 8571:             }
 8572:         } else { # Search has nothing found. Prepare message to user.
 8573:             $response = '<span class="LC_warning">';
 8574:             if ($srch->{'srchin'} eq 'dom' || $srch->{'srchin'} eq 'instd') {
 8575:                 $response .= &mt("$nomatch{$srch->{'srchtype'}} found for the $names{$srch->{'srchby'}} [_1] in $names{$srch->{'srchin'}}: [_2]",
 8576:                                  '<b>'.$srch->{'srchterm'}.'</b>',
 8577:                                  &display_domain_info($srch->{'srchdomain'}));
 8578:             } else {
 8579:                 $response .= &mt("$nomatch{$srch->{'srchtype'}} found for the $names{$srch->{'srchby'}} [_1] in $names{$srch->{'srchin'}}.",
 8580:                                  '<b>'.$srch->{'srchterm'}.'</b>');
 8581:             }
 8582:             $response .= '</span>';
 8583: 
 8584:             if ($srch->{'srchin'} ne 'alc') {
 8585:                 $forcenewuser = 1;
 8586:                 my $cansrchinst = 0; 
 8587:                 if ($srch->{'srchdomain'}) {
 8588:                     my %domconfig = &Apache::lonnet::get_dom('configuration',['directorysrch'],$srch->{'srchdomain'});
 8589:                     if (ref($domconfig{'directorysrch'}) eq 'HASH') {
 8590:                         if ($domconfig{'directorysrch'}{'available'}) {
 8591:                             $cansrchinst = 1;
 8592:                         } 
 8593:                     }
 8594:                 }
 8595:                 if ((($srch->{'srchby'} eq 'lastfirst') || 
 8596:                      ($srch->{'srchby'} eq 'lastname')) &&
 8597:                     ($srch->{'srchin'} eq 'dom')) {
 8598:                     if ($cansrchinst) {
 8599:                         $response .= '<br />'.&mt('You may want to broaden your search to a search of the institutional directory for the domain.');
 8600:                     }
 8601:                 }
 8602:                 if ($srch->{'srchin'} eq 'crs') {
 8603:                     $response .= '<br />'.&mt('You may want to broaden your search to the selected LON-CAPA domain.');
 8604:                 }
 8605:             }
 8606:             my $createdom = $env{'request.role.domain'};
 8607:             if ($context eq 'requestcrs') {
 8608:                 if ($env{'form.coursedom'} ne '') {
 8609:                     $createdom = $env{'form.coursedom'};
 8610:                 }
 8611:             }
 8612:             unless (($env{'form.action'} eq 'accesslogs') || (($srch->{'srchby'} eq 'uname') && ($srch->{'srchin'} eq 'dom') &&
 8613:                     ($srch->{'srchtype'} eq 'exact') && ($srch->{'srchdomain'} eq $createdom))) {
 8614:                 my $cancreate =
 8615:                     &Apache::lonuserutils::can_create_user($createdom,$context);
 8616:                 my $targetdom = '<span class="LC_cusr_emph">'.$createdom.'</span>';
 8617:                 if ($cancreate) {
 8618:                     my $showdom = &display_domain_info($createdom); 
 8619:                     $response .= '<br /><br />'
 8620:                                 .'<b>'.&mt('To add a new user:').'</b>'
 8621:                                 .'<br />';
 8622:                     if ($context eq 'requestcrs') {
 8623:                         $response .= &mt("(You can only define new users in the new course's domain - [_1])",$targetdom);
 8624:                     } else {
 8625:                         $response .= &mt("(You can only create new users in your current role's domain - [_1])",$targetdom);
 8626:                     }
 8627:                     $response .='<ul><li>'
 8628:                                 .&mt("Set 'Domain/institution to search' to: [_1]",'<span class="LC_cusr_emph">'.$showdom.'</span>')
 8629:                                 .'</li><li>'
 8630:                                 .&mt("Set 'Search criteria' to: [_1]username is ..... in selected LON-CAPA domain[_2]",'<span class="LC_cusr_emph">','</span>')
 8631:                                 .'</li><li>'
 8632:                                 .&mt('Provide the proposed username')
 8633:                                 .'</li><li>'
 8634:                                 .&mt("Click 'Search'")
 8635:                                 .'</li></ul><br />';
 8636:                 } else {
 8637:                     unless (($context eq 'domain') && ($env{'form.action'} eq 'singleuser')) {
 8638:                         my $helplink = ' href="javascript:helpMenu('."'display'".')"';
 8639:                         $response .= '<br /><br />';
 8640:                         if ($context eq 'requestcrs') {
 8641:                             $response .= &mt("You are not authorized to define new users in the new course's domain - [_1].",$targetdom);
 8642:                         } else {
 8643:                             $response .= &mt("You are not authorized to create new users in your current role's domain - [_1].",$targetdom);
 8644:                         }
 8645:                         $response .= '<br />'
 8646:                                      .&mt('Please contact the [_1]helpdesk[_2] if you need to create a new user.'
 8647:                                         ,' <a'.$helplink.'>'
 8648:                                         ,'</a>')
 8649:                                      .'<br />';
 8650:                     }
 8651:                 }
 8652:             }
 8653:         }
 8654:     }
 8655:     return ($currstate,$response,$forcenewuser);
 8656: }
 8657: 
 8658: sub display_domain_info {
 8659:     my ($dom) = @_;
 8660:     my $output = $dom;
 8661:     if ($dom ne '') { 
 8662:         my $domdesc = &Apache::lonnet::domain($dom,'description');
 8663:         if ($domdesc ne '') {
 8664:             $output .= ' <span class="LC_cusr_emph">('.$domdesc.')</span>';
 8665:         }
 8666:     }
 8667:     return $output;
 8668: }
 8669: 
 8670: sub crumb_utilities {
 8671:     my %elements = (
 8672:        crtuser => {
 8673:            srchterm => 'text',
 8674:            srchin => 'selectbox',
 8675:            srchby => 'selectbox',
 8676:            srchtype => 'selectbox',
 8677:            srchdomain => 'selectbox',
 8678:        },
 8679:        crtusername => {
 8680:            srchterm => 'text',
 8681:            srchdomain => 'selectbox',
 8682:        },
 8683:        docustom => {
 8684:            rolename => 'selectbox',
 8685:            newrolename => 'textbox',
 8686:        },
 8687:        studentform => {
 8688:            srchterm => 'text',
 8689:            srchin => 'selectbox',
 8690:            srchby => 'selectbox',
 8691:            srchtype => 'selectbox',
 8692:            srchdomain => 'selectbox',
 8693:        },
 8694:     );
 8695: 
 8696:     my $jsback .= qq|
 8697: function backPage(formname,prevphase,prevstate) {
 8698:     if (typeof prevphase == 'undefined') {
 8699:         formname.phase.value = '';
 8700:     }
 8701:     else {  
 8702:         formname.phase.value = prevphase;
 8703:     }
 8704:     if (typeof prevstate == 'undefined') {
 8705:         formname.currstate.value = '';
 8706:     }
 8707:     else {
 8708:         formname.currstate.value = prevstate;
 8709:     }
 8710:     formname.submit();
 8711: }
 8712: |;
 8713:     return ($jsback,\%elements);
 8714: }
 8715: 
 8716: sub course_level_table {
 8717:     my ($inccourses,$showcredits,$defaultcredits) = @_;
 8718:     return unless (ref($inccourses) eq 'HASH');
 8719:     my $table = '';
 8720: # Custom Roles?
 8721: 
 8722:     my %customroles=&Apache::lonuserutils::my_custom_roles();
 8723:     my %lt=&Apache::lonlocal::texthash(
 8724:             'exs'  => "Existing sections",
 8725:             'new'  => "Define new section",
 8726:             'ssd'  => "Set Start Date",
 8727:             'sed'  => "Set End Date",
 8728:             'crl'  => "Course Level",
 8729:             'act'  => "Activate",
 8730:             'rol'  => "Role",
 8731:             'ext'  => "Extent",
 8732:             'grs'  => "Section",
 8733:             'crd'  => "Credits",
 8734:             'sta'  => "Start",
 8735:             'end'  => "End"
 8736:     );
 8737: 
 8738:     foreach my $protectedcourse (sort(keys(%{$inccourses}))) {
 8739: 	my $thiscourse=$protectedcourse;
 8740: 	$thiscourse=~s:_:/:g;
 8741: 	my %coursedata=&Apache::lonnet::coursedescription($thiscourse);
 8742:         my $isowner = &Apache::lonuserutils::is_courseowner($protectedcourse,$coursedata{'internal.courseowner'});
 8743: 	my $area=$coursedata{'description'};
 8744:         my $crstype=$coursedata{'type'};
 8745: 	if (!defined($area)) { $area=&mt('Unavailable course').': '.$protectedcourse; }
 8746: 	my ($domain,$cnum)=split(/\//,$thiscourse);
 8747:         my %sections_count;
 8748:         if (defined($env{'request.course.id'})) {
 8749:             if ($env{'request.course.id'} eq $domain.'_'.$cnum) {
 8750:                 %sections_count = 
 8751: 		    &Apache::loncommon::get_sections($domain,$cnum);
 8752:             }
 8753:         }
 8754:         my @roles = &Apache::lonuserutils::roles_by_context('course','',$crstype);
 8755: 	foreach my $role (@roles) {
 8756:             my $plrole=&Apache::lonnet::plaintext($role,$crstype);
 8757: 	    if ((&Apache::lonnet::allowed('c'.$role,$thiscourse)) ||
 8758:                 ((($role eq 'cc') || ($role eq 'co')) && ($isowner))) {
 8759:                 $table .= &course_level_row($protectedcourse,$role,$area,$domain,
 8760:                                             $plrole,\%sections_count,\%lt,
 8761:                                             $showcredits,$defaultcredits,$crstype);
 8762:             } elsif ($env{'request.course.sec'} ne '') {
 8763:                 if (&Apache::lonnet::allowed('c'.$role,$thiscourse.'/'.
 8764:                                              $env{'request.course.sec'})) {
 8765:                     $table .= &course_level_row($protectedcourse,$role,$area,$domain,
 8766:                                                 $plrole,\%sections_count,\%lt,
 8767:                                                 $showcredits,$defaultcredits,$crstype);
 8768:                 }
 8769:             }
 8770:         }
 8771:         if (&Apache::lonnet::allowed('ccr',$thiscourse)) {
 8772:             foreach my $cust (sort(keys(%customroles))) {
 8773:                 next if ($crstype eq 'Community' && $customroles{$cust} =~ /bre\&S/);
 8774:                 my $role = 'cr_cr_'.$env{'user.domain'}.'_'.$env{'user.name'}.'_'.$cust;
 8775:                 $table .= &course_level_row($protectedcourse,$role,$area,$domain,
 8776:                                             $cust,\%sections_count,\%lt,
 8777:                                             $showcredits,$defaultcredits,$crstype);
 8778:             }
 8779: 	}
 8780:     }
 8781:     return '' if ($table eq ''); # return nothing if there is nothing 
 8782:                                  # in the table
 8783:     my $result;
 8784:     if (!$env{'request.course.id'}) {
 8785:         $result = '<h4>'.$lt{'crl'}.'</h4>'."\n";
 8786:     }
 8787:     $result .= 
 8788: &Apache::loncommon::start_data_table().
 8789: &Apache::loncommon::start_data_table_header_row().
 8790: '<th>'.$lt{'act'}.'</th><th>'.$lt{'rol'}.'</th>'."\n".
 8791: '<th>'.$lt{'ext'}.'</th><th>'."\n";
 8792:     if ($showcredits) {
 8793:         $result .= $lt{'crd'}.'</th>';
 8794:     }
 8795:     $result .=
 8796: '<th>'.$lt{'grs'}.'</th><th>'.$lt{'sta'}.'</th>'."\n".
 8797: '<th>'.$lt{'end'}.'</th>'.
 8798: &Apache::loncommon::end_data_table_header_row().
 8799: $table.
 8800: &Apache::loncommon::end_data_table();
 8801:     return $result;
 8802: }
 8803: 
 8804: sub course_level_row {
 8805:     my ($protectedcourse,$role,$area,$domain,$plrole,$sections_count,
 8806:         $lt,$showcredits,$defaultcredits,$crstype) = @_;
 8807:     my $creditem;
 8808:     my $row = &Apache::loncommon::start_data_table_row().
 8809:               ' <td><input type="checkbox" name="act_'.
 8810:               $protectedcourse.'_'.$role.'" /></td>'."\n".
 8811:               ' <td>'.$plrole.'</td>'."\n".
 8812:               ' <td>'.$area.'<br />Domain: '.$domain.'</td>'."\n";
 8813:     if (($showcredits) && ($role eq 'st') && ($crstype eq 'Course')) {
 8814:         $row .= 
 8815:             '<td><input type="text" name="credits_'.$protectedcourse.'_'.
 8816:             $role.'" size="3" value="'.$defaultcredits.'" /></td>';
 8817:     } else {
 8818:         $row .= '<td>&nbsp;</td>';
 8819:     }
 8820:     if (($role eq 'cc') || ($role eq 'co')) {
 8821:         $row .= '<td>&nbsp;</td>';
 8822:     } elsif ($env{'request.course.sec'} ne '') {
 8823:         $row .= ' <td><input type="hidden" value="'.
 8824:                 $env{'request.course.sec'}.'" '.
 8825:                 'name="sec_'.$protectedcourse.'_'.$role.'" />'.
 8826:                 $env{'request.course.sec'}.'</td>';
 8827:     } else {
 8828:         if (ref($sections_count) eq 'HASH') {
 8829:             my $currsec = 
 8830:                 &Apache::lonuserutils::course_sections($sections_count,
 8831:                                                        $protectedcourse.'_'.$role);
 8832:             $row .= '<td><table class="LC_createuser">'."\n".
 8833:                     '<tr class="LC_section_row">'."\n".
 8834:                     ' <td valign="top">'.$lt->{'exs'}.'<br />'.
 8835:                        $currsec.'</td>'."\n".
 8836:                      ' <td>&nbsp;&nbsp;</td>'."\n".
 8837:                      ' <td valign="top">&nbsp;'.$lt->{'new'}.'<br />'.
 8838:                      '<input type="text" name="newsec_'.$protectedcourse.'_'.$role.
 8839:                      '" value="" />'.
 8840:                      '<input type="hidden" '.
 8841:                      'name="sec_'.$protectedcourse.'_'.$role.'" /></td>'."\n".
 8842:                      '</tr></table></td>'."\n";
 8843:         } else {
 8844:             $row .= '<td><input type="text" size="10" '.
 8845:                     'name="sec_'.$protectedcourse.'_'.$role.'" /></td>'."\n";
 8846:         }
 8847:     }
 8848:     $row .= <<ENDTIMEENTRY;
 8849: <td><input type="hidden" name="start_$protectedcourse\_$role" value="" />
 8850: <a href=
 8851: "javascript:pjump('date_start','Start Date $plrole',document.cu.start_$protectedcourse\_$role.value,'start_$protectedcourse\_$role','cu.pres','dateset')">$lt->{'ssd'}</a></td>
 8852: <td><input type="hidden" name="end_$protectedcourse\_$role" value="" />
 8853: <a href=
 8854: "javascript:pjump('date_end','End Date $plrole',document.cu.end_$protectedcourse\_$role.value,'end_$protectedcourse\_$role','cu.pres','dateset')">$lt->{'sed'}</a></td>
 8855: ENDTIMEENTRY
 8856:     $row .= &Apache::loncommon::end_data_table_row();
 8857:     return $row;
 8858: }
 8859: 
 8860: sub course_level_dc {
 8861:     my ($dcdom,$showcredits) = @_;
 8862:     my %customroles=&Apache::lonuserutils::my_custom_roles();
 8863:     my @roles = &Apache::lonuserutils::roles_by_context('course');
 8864:     my $hiddenitems = '<input type="hidden" name="dcdomain" value="'.$dcdom.'" />'.
 8865:                       '<input type="hidden" name="origdom" value="'.$dcdom.'" />'.
 8866:                       '<input type="hidden" name="dccourse" value="" />';
 8867:     my $courseform=&Apache::loncommon::selectcourse_link
 8868:             ('cu','dccourse','dcdomain','coursedesc',undef,undef,'Select','crstype');
 8869:     my $credit_elem;
 8870:     if ($showcredits) {
 8871:         $credit_elem = 'credits';
 8872:     }
 8873:     my $cb_jscript = &Apache::loncommon::coursebrowser_javascript($dcdom,'currsec','cu','role','Course/Community Browser',$credit_elem);
 8874:     my %lt=&Apache::lonlocal::texthash(
 8875:                     'rol'  => "Role",
 8876:                     'grs'  => "Section",
 8877:                     'exs'  => "Existing sections",
 8878:                     'new'  => "Define new section", 
 8879:                     'sta'  => "Start",
 8880:                     'end'  => "End",
 8881:                     'ssd'  => "Set Start Date",
 8882:                     'sed'  => "Set End Date",
 8883:                     'scc'  => "Course/Community",
 8884:                     'crd'  => "Credits",
 8885:                   );
 8886:     my $header = '<h4>'.&mt('Course/Community Level').'</h4>'.
 8887:                  &Apache::loncommon::start_data_table().
 8888:                  &Apache::loncommon::start_data_table_header_row().
 8889:                  '<th>'.$lt{'scc'}.'</th><th>'.$lt{'rol'}.'</th>'."\n".
 8890:                  '<th>'.$lt{'grs'}.'</th>'."\n";
 8891:     $header .=   '<th>'.$lt{'crd'}.'</th>'."\n" if ($showcredits);
 8892:     $header .=   '<th>'.$lt{'sta'}.'</th><th>'.$lt{'end'}.'</th>'."\n".
 8893:                  &Apache::loncommon::end_data_table_header_row();
 8894:     my $otheritems = &Apache::loncommon::start_data_table_row()."\n".
 8895:                      '<td><br /><span class="LC_nobreak"><input type="text" name="coursedesc" value="" onfocus="this.blur();opencrsbrowser('."'cu','dccourse','dcdomain','coursedesc','','','','crstype'".')" />'.
 8896:                      $courseform.('&nbsp;' x4).'</span></td>'."\n".
 8897:                      '<td valign="top"><br /><select name="role">'."\n";
 8898:     foreach my $role (@roles) {
 8899:         my $plrole=&Apache::lonnet::plaintext($role);
 8900:         $otheritems .= '  <option value="'.$role.'">'.$plrole.'</option>';
 8901:     }
 8902:     if ( keys(%customroles) > 0) {
 8903:         foreach my $cust (sort(keys(%customroles))) {
 8904:             my $custrole='cr_cr_'.$env{'user.domain'}.
 8905:                     '_'.$env{'user.name'}.'_'.$cust;
 8906:             $otheritems .= '  <option value="'.$custrole.'">'.$cust.'</option>';
 8907:         }
 8908:     }
 8909:     $otheritems .= '</select></td><td>'.
 8910:                      '<table border="0" cellspacing="0" cellpadding="0">'.
 8911:                      '<tr><td valign="top"><b>'.$lt{'exs'}.'</b><br /><select name="currsec">'.
 8912:                      ' <option value="">&lt;--'.&mt('Pick course first').'</option></select></td>'.
 8913:                      '<td>&nbsp;&nbsp;</td>'.
 8914:                      '<td valign="top">&nbsp;<b>'.$lt{'new'}.'</b><br />'.
 8915:                      '<input type="text" name="newsec" value="" />'.
 8916:                      '<input type="hidden" name="section" value="" />'.
 8917:                      '<input type="hidden" name="groups" value="" />'.
 8918:                      '<input type="hidden" name="crstype" value="" /></td>'.
 8919:                      '</tr></table></td>'."\n";
 8920:     if ($showcredits) {
 8921:         $otheritems .= '<td><br />'."\n".
 8922:                        '<input type="text" size="3" name="credits" value="" /></td>'."\n";
 8923:     }
 8924:     $otheritems .= <<ENDTIMEENTRY;
 8925: <td><br /><input type="hidden" name="start" value='' />
 8926: <a href=
 8927: "javascript:pjump('date_start','Start Date',document.cu.start.value,'start','cu.pres','dateset')">$lt{'ssd'}</a></td>
 8928: <td><br /><input type="hidden" name="end" value='' />
 8929: <a href=
 8930: "javascript:pjump('date_end','End Date',document.cu.end.value,'end','cu.pres','dateset')">$lt{'sed'}</a></td>
 8931: ENDTIMEENTRY
 8932:     $otheritems .= &Apache::loncommon::end_data_table_row().
 8933:                    &Apache::loncommon::end_data_table()."\n";
 8934:     return $cb_jscript.$header.$hiddenitems.$otheritems;
 8935: }
 8936: 
 8937: sub update_selfenroll_config {
 8938:     my ($r,$cid,$cdom,$cnum,$context,$crstype,$currsettings) = @_;
 8939:     return unless (ref($currsettings) eq 'HASH');
 8940:     my ($row,$lt) = &Apache::lonuserutils::get_selfenroll_titles();
 8941:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
 8942:     my (%changes,%warning);
 8943:     my $curr_types;
 8944:     my %noedit;
 8945:     unless ($context eq 'domain') {
 8946:         %noedit = &get_noedit_fields($cdom,$cnum,$crstype,$row);
 8947:     }
 8948:     if (ref($row) eq 'ARRAY') {
 8949:         foreach my $item (@{$row}) {
 8950:             next if ($noedit{$item});
 8951:             if ($item eq 'enroll_dates') {
 8952:                 my (%currenrolldate,%newenrolldate);
 8953:                 foreach my $type ('start','end') {
 8954:                     $currenrolldate{$type} = $currsettings->{'selfenroll_'.$type.'_date'};
 8955:                     $newenrolldate{$type} = &Apache::lonhtmlcommon::get_date_from_form('selfenroll_'.$type.'_date');
 8956:                     if ($newenrolldate{$type} ne $currenrolldate{$type}) {
 8957:                         $changes{'internal.selfenroll_'.$type.'_date'} = $newenrolldate{$type};
 8958:                     }
 8959:                 }
 8960:             } elsif ($item eq 'access_dates') {
 8961:                 my (%currdate,%newdate);
 8962:                 foreach my $type ('start','end') {
 8963:                     $currdate{$type} = $currsettings->{'selfenroll_'.$type.'_access'};
 8964:                     $newdate{$type} = &Apache::lonhtmlcommon::get_date_from_form('selfenroll_'.$type.'_access');
 8965:                     if ($newdate{$type} ne $currdate{$type}) {
 8966:                         $changes{'internal.selfenroll_'.$type.'_access'} = $newdate{$type};
 8967:                     }
 8968:                 }
 8969:             } elsif ($item eq 'types') {
 8970:                 $curr_types = $currsettings->{'selfenroll_'.$item};
 8971:                 if ($env{'form.selfenroll_all'}) {
 8972:                     if ($curr_types ne '*') {
 8973:                         $changes{'internal.selfenroll_types'} = '*';
 8974:                     } else {
 8975:                         next;
 8976:                     }
 8977:                 } else {
 8978:                     my %currdoms;
 8979:                     my @entries = split(/;/,$curr_types);
 8980:                     my @deletedoms = &Apache::loncommon::get_env_multiple('form.selfenroll_delete');
 8981:                     my @activations = &Apache::loncommon::get_env_multiple('form.selfenroll_activate');
 8982:                     my $newnum = 0;
 8983:                     my @latesttypes;
 8984:                     foreach my $num (@activations) {
 8985:                         my @types = &Apache::loncommon::get_env_multiple('form.selfenroll_types_'.$num);
 8986:                         if (@types > 0) {
 8987:                             @types = sort(@types);
 8988:                             my $typestr = join(',',@types);
 8989:                             my $typedom = $env{'form.selfenroll_dom_'.$num};
 8990:                             $latesttypes[$newnum] = $typedom.':'.$typestr;
 8991:                             $currdoms{$typedom} = 1;
 8992:                             $newnum ++;
 8993:                         }
 8994:                     }
 8995:                     for (my $j=0; $j<$env{'form.selfenroll_types_total'}; $j++) {
 8996:                         if ((!grep(/^$j$/,@deletedoms)) && (!grep(/^$j$/,@activations))) {
 8997:                             my @types = &Apache::loncommon::get_env_multiple('form.selfenroll_types_'.$j);
 8998:                             if (@types > 0) {
 8999:                                 @types = sort(@types);
 9000:                                 my $typestr = join(',',@types);
 9001:                                 my $typedom = $env{'form.selfenroll_dom_'.$j};
 9002:                                 $latesttypes[$newnum] = $typedom.':'.$typestr;
 9003:                                 $currdoms{$typedom} = 1;
 9004:                                 $newnum ++;
 9005:                             }
 9006:                         }
 9007:                     }
 9008:                     if ($env{'form.selfenroll_newdom'} ne '') {
 9009:                         my $typedom = $env{'form.selfenroll_newdom'};
 9010:                         if ((!defined($currdoms{$typedom})) && 
 9011:                             (&Apache::lonnet::domain($typedom) ne '')) {
 9012:                             my $typestr;
 9013:                             my ($othertitle,$usertypes,$types) = 
 9014:                                 &Apache::loncommon::sorted_inst_types($typedom);
 9015:                             my $othervalue = 'any';
 9016:                             if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 9017:                                 if (@{$types} > 0) {
 9018:                                     my @esc_types = map { &escape($_); } @{$types};
 9019:                                     $othervalue = 'other';
 9020:                                     $typestr = join(',',(@esc_types,$othervalue));
 9021:                                 }
 9022:                                 $typestr = $othervalue;
 9023:                             } else {
 9024:                                 $typestr = $othervalue;
 9025:                             } 
 9026:                             $latesttypes[$newnum] = $typedom.':'.$typestr;
 9027:                             $newnum ++ ;
 9028:                         }
 9029:                     }
 9030:                     my $selfenroll_types = join(';',@latesttypes);
 9031:                     if ($selfenroll_types ne $curr_types) {
 9032:                         $changes{'internal.selfenroll_types'} = $selfenroll_types;
 9033:                     }
 9034:                 }
 9035:             } elsif ($item eq 'limit') {
 9036:                 my $newlimit = $env{'form.selfenroll_limit'};
 9037:                 my $newcap = $env{'form.selfenroll_cap'};
 9038:                 $newcap =~s/\s+//g;
 9039:                 my $currlimit =  $currsettings->{'selfenroll_limit'};
 9040:                 $currlimit = 'none' if ($currlimit eq '');
 9041:                 my $currcap = $currsettings->{'selfenroll_cap'};
 9042:                 if ($newlimit ne $currlimit) {
 9043:                     if ($newlimit ne 'none') {
 9044:                         if ($newcap =~ /^\d+$/) {
 9045:                             if ($newcap ne $currcap) {
 9046:                                 $changes{'internal.selfenroll_cap'} = $newcap;
 9047:                             }
 9048:                             $changes{'internal.selfenroll_limit'} = $newlimit;
 9049:                         } else {
 9050:                             $warning{$item} = &mt('Maximum enrollment setting unchanged.').'<br />'.
 9051:                                 &mt('The value provided was invalid - it must be a positive integer if enrollment is being limited.'); 
 9052:                         }
 9053:                     } elsif ($currcap ne '') {
 9054:                         $changes{'internal.selfenroll_cap'} = '';
 9055:                         $changes{'internal.selfenroll_limit'} = $newlimit; 
 9056:                     }
 9057:                 } elsif ($currlimit ne 'none') {
 9058:                     if ($newcap =~ /^\d+$/) {
 9059:                         if ($newcap ne $currcap) {
 9060:                             $changes{'internal.selfenroll_cap'} = $newcap;
 9061:                         }
 9062:                     } else {
 9063:                         $warning{$item} = &mt('Maximum enrollment setting unchanged.').'<br />'.
 9064:                             &mt('The value provided was invalid - it must be a positive integer if enrollment is being limited.');
 9065:                     }
 9066:                 }
 9067:             } elsif ($item eq 'approval') {
 9068:                 my (@currnotified,@newnotified);
 9069:                 my $currapproval = $currsettings->{'selfenroll_approval'};
 9070:                 my $currnotifylist = $currsettings->{'selfenroll_notifylist'};
 9071:                 if ($currnotifylist ne '') {
 9072:                     @currnotified = split(/,/,$currnotifylist);
 9073:                     @currnotified = sort(@currnotified);
 9074:                 }
 9075:                 my $newapproval = $env{'form.selfenroll_approval'};
 9076:                 @newnotified = &Apache::loncommon::get_env_multiple('form.selfenroll_notify');
 9077:                 @newnotified = sort(@newnotified);
 9078:                 if ($newapproval ne $currapproval) {
 9079:                     $changes{'internal.selfenroll_approval'} = $newapproval;
 9080:                     if (!$newapproval) {
 9081:                         if ($currnotifylist ne '') {
 9082:                             $changes{'internal.selfenroll_notifylist'} = '';
 9083:                         }
 9084:                     } else {
 9085:                         my @differences =  
 9086:                             &Apache::loncommon::compare_arrays(\@currnotified,\@newnotified);
 9087:                         if (@differences > 0) {
 9088:                             if (@newnotified > 0) {
 9089:                                 $changes{'internal.selfenroll_notifylist'} = join(',',@newnotified);
 9090:                             } else {
 9091:                                 $changes{'internal.selfenroll_notifylist'} = join(',',@newnotified);
 9092:                             }
 9093:                         }
 9094:                     }
 9095:                 } else {
 9096:                     my @differences = &Apache::loncommon::compare_arrays(\@currnotified,\@newnotified);
 9097:                     if (@differences > 0) {
 9098:                         if (@newnotified > 0) {
 9099:                             $changes{'internal.selfenroll_notifylist'} = join(',',@newnotified);
 9100:                         } else {
 9101:                             $changes{'internal.selfenroll_notifylist'} = '';
 9102:                         }
 9103:                     }
 9104:                 }
 9105:             } else {
 9106:                 my $curr_val = $currsettings->{'selfenroll_'.$item};
 9107:                 my $newval = $env{'form.selfenroll_'.$item};
 9108:                 if ($item eq 'section') {
 9109:                     $newval = $env{'form.sections'};
 9110:                     if (defined($curr_groups{$newval})) {
 9111:                         $newval = $curr_val;
 9112:                         $warning{$item} = &mt('Section for self-enrolled users unchanged as the proposed section is a group').'<br />'.
 9113:                                           &mt('Group names and section names must be distinct');
 9114:                     } elsif ($newval eq 'all') {
 9115:                         $newval = $curr_val;
 9116:                         $warning{$item} = &mt('Section for self-enrolled users unchanged, as "all" is a reserved section name.');
 9117:                     }
 9118:                     if ($newval eq '') {
 9119:                         $newval = 'none';
 9120:                     }
 9121:                 }
 9122:                 if ($newval ne $curr_val) {
 9123:                     $changes{'internal.selfenroll_'.$item} = $newval;
 9124:                 }
 9125:             }
 9126:         }
 9127:         if (keys(%warning) > 0) {
 9128:             foreach my $item (@{$row}) {
 9129:                 if (exists($warning{$item})) {
 9130:                     $r->print($warning{$item}.'<br />');
 9131:                 }
 9132:             } 
 9133:         }
 9134:         if (keys(%changes) > 0) {
 9135:             my $putresult = &Apache::lonnet::put('environment',\%changes,$cdom,$cnum);
 9136:             if ($putresult eq 'ok') {
 9137:                 if ((exists($changes{'internal.selfenroll_types'})) ||
 9138:                     (exists($changes{'internal.selfenroll_start_date'}))  ||
 9139:                     (exists($changes{'internal.selfenroll_end_date'}))) {
 9140:                     my %crsinfo = &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',
 9141:                                                                 $cnum,undef,undef,'Course');
 9142:                     my $chome = &Apache::lonnet::homeserver($cnum,$cdom);
 9143:                     if (ref($crsinfo{$cid}) eq 'HASH') {
 9144:                         foreach my $item ('selfenroll_types','selfenroll_start_date','selfenroll_end_date') {
 9145:                             if (exists($changes{'internal.'.$item})) {
 9146:                                 $crsinfo{$cid}{$item} = $changes{'internal.'.$item};
 9147:                             }
 9148:                         }
 9149:                         my $crsputresult =
 9150:                             &Apache::lonnet::courseidput($cdom,\%crsinfo,
 9151:                                                          $chome,'notime');
 9152:                     }
 9153:                 }
 9154:                 $r->print(&mt('The following changes were made to self-enrollment settings:').'<ul>');
 9155:                 foreach my $item (@{$row}) {
 9156:                     my $title = $item;
 9157:                     if (ref($lt) eq 'HASH') {
 9158:                         $title = $lt->{$item};
 9159:                     }
 9160:                     if ($item eq 'enroll_dates') {
 9161:                         foreach my $type ('start','end') {
 9162:                             if (exists($changes{'internal.selfenroll_'.$type.'_date'})) {
 9163:                                 my $newdate = &Apache::lonlocal::locallocaltime($changes{'internal.selfenroll_'.$type.'_date'});
 9164:                                 $r->print('<li>'.&mt('[_1]: "[_2]" set to "[_3]".',
 9165:                                           $title,$type,$newdate).'</li>');
 9166:                             }
 9167:                         }
 9168:                     } elsif ($item eq 'access_dates') {
 9169:                         foreach my $type ('start','end') {
 9170:                             if (exists($changes{'internal.selfenroll_'.$type.'_access'})) {
 9171:                                 my $newdate = &Apache::lonlocal::locallocaltime($changes{'internal.selfenroll_'.$type.'_access'});
 9172:                                 $r->print('<li>'.&mt('[_1]: "[_2]" set to "[_3]".',
 9173:                                           $title,$type,$newdate).'</li>');
 9174:                             }
 9175:                         }
 9176:                     } elsif ($item eq 'limit') {
 9177:                         if ((exists($changes{'internal.selfenroll_limit'})) ||
 9178:                             (exists($changes{'internal.selfenroll_cap'}))) {
 9179:                             my ($newval,$newcap);
 9180:                             if ($changes{'internal.selfenroll_cap'} ne '') {
 9181:                                 $newcap = $changes{'internal.selfenroll_cap'}
 9182:                             } else {
 9183:                                 $newcap = $currsettings->{'selfenroll_cap'};
 9184:                             }
 9185:                             if ($changes{'internal.selfenroll_limit'} eq 'none') {
 9186:                                 $newval = &mt('No limit');
 9187:                             } elsif ($changes{'internal.selfenroll_limit'} eq 
 9188:                                      'allstudents') {
 9189:                                 $newval = &mt('New self-enrollment no longer allowed when total (all students) reaches [_1].',$newcap);
 9190:                             } elsif ($changes{'internal.selfenroll_limit'} eq 'selfenrolled') {
 9191:                                 $newval = &mt('New self-enrollment no longer allowed when total number of self-enrolled students reaches [_1].',$newcap);
 9192:                             } else {
 9193:                                 my $currlimit =  $currsettings->{'selfenroll_limit'};
 9194:                                 if ($currlimit eq 'allstudents') {
 9195:                                     $newval = &mt('New self-enrollment no longer allowed when total (all students) reaches [_1].',$newcap);
 9196:                                 } elsif ($changes{'internal.selfenroll_limit'} eq 'selfenrolled') {
 9197:                                     $newval =  &mt('New self-enrollment no longer allowed when total number of self-enrolled students reaches [_1].',$newcap);
 9198:                                 }
 9199:                             }
 9200:                             $r->print('<li>'.&mt('"[_1]" set to "[_2]".',$title,$newval).'</li>'."\n");
 9201:                         }
 9202:                     } elsif ($item eq 'approval') {
 9203:                         if ((exists($changes{'internal.selfenroll_approval'})) ||
 9204:                             (exists($changes{'internal.selfenroll_notifylist'}))) {
 9205:                             my %selfdescs = &Apache::lonuserutils::selfenroll_default_descs();
 9206:                             my ($newval,$newnotify);
 9207:                             if (exists($changes{'internal.selfenroll_notifylist'})) {
 9208:                                 $newnotify = $changes{'internal.selfenroll_notifylist'};
 9209:                             } else {   
 9210:                                 $newnotify = $currsettings->{'selfenroll_notifylist'};
 9211:                             }
 9212:                             if (exists($changes{'internal.selfenroll_approval'})) {
 9213:                                 if ($changes{'internal.selfenroll_approval'} !~ /^[012]$/) {
 9214:                                     $changes{'internal.selfenroll_approval'} = '0';
 9215:                                 }
 9216:                                 $newval = $selfdescs{'approval'}{$changes{'internal.selfenroll_approval'}};
 9217:                             } else {
 9218:                                 my $currapproval = $currsettings->{'selfenroll_approval'}; 
 9219:                                 if ($currapproval !~ /^[012]$/) {
 9220:                                     $currapproval = 0;
 9221:                                 }
 9222:                                 $newval = $selfdescs{'approval'}{$currapproval};
 9223:                             }
 9224:                             $r->print('<li>'.&mt('"[_1]" set to "[_2]".',$title,$newval));
 9225:                             if ($newnotify) {
 9226:                                 $r->print('<br />'.&mt('The following will be notified when an enrollment request needs approval, or has been approved: [_1].',$newnotify));
 9227:                             } else {
 9228:                                 $r->print('<br />'.&mt('No notifications sent when an enrollment request needs approval, or has been approved.'));
 9229:                             }
 9230:                             $r->print('</li>'."\n");
 9231:                         }
 9232:                     } else {
 9233:                         if (exists($changes{'internal.selfenroll_'.$item})) {
 9234:                             my $newval = $changes{'internal.selfenroll_'.$item};
 9235:                             if ($item eq 'types') {
 9236:                                 if ($newval eq '') {
 9237:                                     $newval = &mt('None');
 9238:                                 } elsif ($newval eq '*') {
 9239:                                     $newval = &mt('Any user in any domain');
 9240:                                 }
 9241:                             } elsif ($item eq 'registered') {
 9242:                                 if ($newval eq '1') {
 9243:                                     $newval = &mt('Yes');
 9244:                                 } elsif ($newval eq '0') {
 9245:                                     $newval = &mt('No');
 9246:                                 }
 9247:                             }
 9248:                             $r->print('<li>'.&mt('"[_1]" set to "[_2]".',$title,$newval).'</li>'."\n");
 9249:                         }
 9250:                     }
 9251:                 }
 9252:                 $r->print('</ul>');
 9253:                 if ($env{'course.'.$cid.'.description'} ne '') {
 9254:                     my %newenvhash;
 9255:                     foreach my $key (keys(%changes)) {
 9256:                         $newenvhash{'course.'.$cid.'.'.$key} = $changes{$key};
 9257:                     }
 9258:                     &Apache::lonnet::appenv(\%newenvhash);
 9259:                 }
 9260:             } else {
 9261:                 $r->print(&mt('An error occurred when saving changes to self-enrollment settings in this course.').'<br />'.
 9262:                           &mt('The error was: [_1].',$putresult));
 9263:             }
 9264:         } else {
 9265:             $r->print(&mt('No changes were made to the existing self-enrollment settings in this course.'));
 9266:         }
 9267:     } else {
 9268:         $r->print(&mt('No changes were made to the existing self-enrollment settings in this course.'));
 9269:     }
 9270:     my $visactions = &cat_visibility();
 9271:     my ($cathash,%cattype);
 9272:     my %domconfig = &Apache::lonnet::get_dom('configuration',['coursecategories'],$cdom);
 9273:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 9274:         $cathash = $domconfig{'coursecategories'}{'cats'};
 9275:         $cattype{'auth'} = $domconfig{'coursecategories'}{'auth'};
 9276:         $cattype{'unauth'} = $domconfig{'coursecategories'}{'unauth'};
 9277:     } else {
 9278:         $cathash = {};
 9279:         $cattype{'auth'} = 'std';
 9280:         $cattype{'unauth'} = 'std';
 9281:     }
 9282:     if (($cattype{'auth'} eq 'none') && ($cattype{'unauth'} eq 'none')) {
 9283:         $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
 9284:                   '<br />'.
 9285:                   '<br />'.$visactions->{'take'}.'<ul>'.
 9286:                   '<li>'.$visactions->{'dc_chgconf'}.'</li>'.
 9287:                   '</ul>');
 9288:     } elsif (($cattype{'auth'} !~ /^(std|domonly)$/) && ($cattype{'unauth'} !~ /^(std|domonly)$/)) {
 9289:         if ($currsettings->{'uniquecode'}) {
 9290:             $r->print('<span class="LC_info">'.$visactions->{'vis'}.'</span>');
 9291:         } else {
 9292:             $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
 9293:                   '<br />'.
 9294:                   '<br />'.$visactions->{'take'}.'<ul>'.
 9295:                   '<li>'.$visactions->{'dc_setcode'}.'</li>'.
 9296:                   '</ul><br />');
 9297:         }
 9298:     } else {
 9299:         my ($visible,$cansetvis,$vismsgs) = &visible_in_stdcat($cdom,$cnum,\%domconfig);
 9300:         if (ref($visactions) eq 'HASH') {
 9301:             if (!$visible) {
 9302:                 $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
 9303:                           '<br />');
 9304:                 if (ref($vismsgs) eq 'ARRAY') {
 9305:                     $r->print('<br />'.$visactions->{'take'}.'<ul>');
 9306:                     foreach my $item (@{$vismsgs}) {
 9307:                         $r->print('<li>'.$visactions->{$item}.'</li>');
 9308:                     }
 9309:                     $r->print('</ul>');
 9310:                 }
 9311:                 $r->print($cansetvis);
 9312:             }
 9313:         }
 9314:     } 
 9315:     return;
 9316: }
 9317: 
 9318: #---------------------------------------------- end functions for &phase_two
 9319: 
 9320: #--------------------------------- functions for &phase_two and &phase_three
 9321: 
 9322: #--------------------------end of functions for &phase_two and &phase_three
 9323: 
 9324: 1;
 9325: __END__
 9326: 
 9327: 

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