File:  [LON-CAPA] / loncom / interface / loncreateuser.pm
Revision 1.422: download - view: text, annotated - select for diffs
Sat Nov 12 00:39:39 2016 UTC (7 years, 6 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Appropriate text for breadcrumbs and header lines when Domain Helpdesk role
  is searching for a user for whom to display roles and user information.

    1: # The LearningOnline Network with CAPA
    2: # Create a user
    3: #
    4: # $Id: loncreateuser.pm,v 1.422 2016/11/12 00:39:39 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 domadhocroles {
  540:     my ($ccuname,$ccdomain) = @_;
  541:     my $confname = &Apache::lonnet::get_domainconfiguser($env{'request.role.domain'});
  542:     my %existing=&Apache::lonnet::dump('roles',$env{'request.role.domain'},
  543:                                        $confname,'rolesdef_');
  544:     my ($output,$canmodify);
  545:     if (&Apache::lonnet::allowed('cdh',$env{'request.role.domain'})) {
  546:         $canmodify = 1;
  547:     }
  548:     if (keys(%existing) > 0) {
  549:         my @current;
  550:         my $curradhoc = 'adhocroles.'.$env{'request.role.domain'};
  551:         my %userenv = &Apache::lonnet::userenvironment($ccdomain,$ccuname,$curradhoc);
  552:         if ($userenv{$curradhoc}) {
  553:             @current = split(/,/,$userenv{$curradhoc});
  554:         }
  555:         if (!$canmodify && !@current) {
  556:             return;
  557:         }
  558:         my %customroles;
  559:         foreach my $key (keys(%existing)) {
  560:             if ($key=~/^rolesdef\_(\w+)$/) {
  561:                 my $rolename = $1;
  562:                 my %privs;
  563:                 ($privs{'system'},$privs{'domain'},$privs{'course'}) = split(/\_/,$existing{$key});
  564:                 $customroles{$rolename} = \%privs;
  565:             }
  566:         }
  567:         $output = '<br /><h3>'.
  568:                   &mt('Ad Hoc Course Roles Selectable via Helpdesk Role').
  569:                   '</h3>'."\n".
  570:                   &Apache::loncommon::start_data_table().
  571:                   &Apache::loncommon::start_data_table_header_row();
  572:         if ($canmodify) {
  573:             $output .= '<th>'.&mt('Action').'</th>';
  574:         }
  575:         $output .= '<th>'.&mt('Role').'</th>'.
  576:                    '<th>'.&mt('Privileges in Course').'<th>'.
  577:                    &Apache::loncommon::end_data_table_header_row();
  578:         foreach my $key (sort(keys(%customroles))) {
  579:             next if ((!$canmodify) && (!grep(/^\Q$key\E$/,@current)));
  580:             $output .= &Apache::loncommon::start_data_table_row();
  581:             if ($canmodify) {
  582:                 if (grep(/^\Q$key\E$/,@current)) {
  583:                     $output .= '<td><label>'.
  584:                                '<input type="checkbox" name="adhocroledel" value="'.$key.'" />'.
  585:                                &mt('Delete').'</label>'.
  586:                                '</td>';
  587:                 } else {
  588:                     $output .= '<td><label>'.
  589:                                '<input type="checkbox" name="adhocroleadd" value="'.$key.'" />'.
  590:                                &mt('Add').'</label>'.
  591:                                '</td>';
  592:                 }
  593:             }
  594:             $output .= '<td>'.$key.'</td><td>';
  595:             foreach my $level ('course','domain','system') {
  596:                 if ($customroles{$key}{$level}) {
  597:                     my $suffix;
  598:                     if (($level eq 'domain') || ($level eq 'system')) {
  599:                         $suffix = '&nbsp;('.&mt($level).')';
  600:                     }
  601:                     my @privs = split(/:/,$customroles{$key}{$level});
  602:                     foreach my $item (@privs) {
  603:                         next if ($item eq '');
  604:                         my ($priv,$cond) = split(/\&/,$item);
  605:                         $output .= &Apache::lonnet::plaintext($priv,'Course').$suffix.'<br />';
  606:                     }
  607:                 }
  608:             }
  609:             $output .= '</td>'.
  610:                        &Apache::loncommon::end_data_table_row();
  611:         }
  612:         $output .= &Apache::loncommon::end_data_table();
  613:     }
  614:     return $output;
  615: }
  616: 
  617: sub courserequest_titles {
  618:     my %titles = &Apache::lonlocal::texthash (
  619:                                    official   => 'Official',
  620:                                    unofficial => 'Unofficial',
  621:                                    community  => 'Communities',
  622:                                    textbook   => 'Textbook',
  623:                                    placement  => 'Placement Tests',
  624:                                    norequest  => 'Not allowed',
  625:                                    approval   => 'Approval by Dom. Coord.',
  626:                                    validate   => 'With validation',
  627:                                    autolimit  => 'Numerical limit',
  628:                                    unlimited  => '(blank for unlimited)',
  629:                  );
  630:     return %titles;
  631: }
  632: 
  633: sub courserequest_display {
  634:     my %titles = &Apache::lonlocal::texthash (
  635:                                    approval   => 'Yes, need approval',
  636:                                    validate   => 'Yes, with validation',
  637:                                    norequest  => 'No',
  638:    );
  639:    return %titles;
  640: }
  641: 
  642: sub requestauthor_titles {
  643:     my %titles = &Apache::lonlocal::texthash (
  644:                                    norequest  => 'Not allowed',
  645:                                    approval   => 'Approval by Dom. Coord.',
  646:                                    automatic  => 'Automatic approval',
  647:                  );
  648:     return %titles;
  649: 
  650: }
  651: 
  652: sub requestauthor_display {
  653:     my %titles = &Apache::lonlocal::texthash (
  654:                                    approval   => 'Yes, need approval',
  655:                                    automatic  => 'Yes, automatic approval',
  656:                                    norequest  => 'No',
  657:    );
  658:    return %titles;
  659: }
  660: 
  661: sub requestchange_display {
  662:     my %titles = &Apache::lonlocal::texthash (
  663:                                    approval   => "availability set to 'on' (approval required)", 
  664:                                    automatic  => "availability set to 'on' (automatic approval)",
  665:                                    norequest  => "availability set to 'off'",
  666:    );
  667:    return %titles;
  668: }
  669: 
  670: sub curr_requestauthor {
  671:     my ($uname,$udom,$isadv,$inststatuses,$domconfig) = @_;
  672:     return unless ((ref($inststatuses) eq 'ARRAY') && (ref($domconfig) eq 'HASH'));
  673:     if ($uname eq '' || $udom eq '') {
  674:         $uname = $env{'user.name'};
  675:         $udom = $env{'user.domain'};
  676:         $isadv = $env{'user.adv'};
  677:     }
  678:     my (%userenv,%settings,$val);
  679:     my @options = ('automatic','approval');
  680:     %userenv =
  681:         &Apache::lonnet::userenvironment($udom,$uname,'requestauthor','inststatus');
  682:     if ($userenv{'requestauthor'}) {
  683:         $val = $userenv{'requestauthor'};
  684:         @{$inststatuses} = ('_custom_');
  685:     } else {
  686:         my %alltasks;
  687:         if (ref($domconfig->{'requestauthor'}) eq 'HASH') {
  688:             %settings = %{$domconfig->{'requestauthor'}};
  689:             if (($isadv) && ($settings{'_LC_adv'} ne '')) {
  690:                 $val = $settings{'_LC_adv'};
  691:                 @{$inststatuses} = ('_LC_adv_');
  692:             } else {
  693:                 if ($userenv{'inststatus'} ne '') {
  694:                     @{$inststatuses} = split(',',$userenv{'inststatus'});
  695:                 } else {
  696:                     @{$inststatuses} = ('default');
  697:                 }
  698:                 foreach my $status (@{$inststatuses}) {
  699:                     if (exists($settings{$status})) {
  700:                         my $value = $settings{$status};
  701:                         next unless ($value);
  702:                         unless (exists($alltasks{$value})) {
  703:                             if (ref($alltasks{$value}) eq 'ARRAY') {
  704:                                 unless(grep(/^\Q$status\E$/,@{$alltasks{$value}})) {
  705:                                     push(@{$alltasks{$value}},$status);
  706:                                 }
  707:                             } else {
  708:                                 @{$alltasks{$value}} = ($status);
  709:                             }
  710:                         }
  711:                     }
  712:                 }
  713:                 foreach my $option (@options) {
  714:                     if ($alltasks{$option}) {
  715:                         $val = $option;
  716:                         last;
  717:                     }
  718:                 }
  719:             }
  720:         }
  721:     }
  722:     return $val;
  723: }
  724: 
  725: # =================================================================== Phase one
  726: 
  727: sub print_username_entry_form {
  728:     my ($r,$context,$response,$srch,$forcenewuser,$crstype,$brcrum) = @_;
  729:     my $defdom=$env{'request.role.domain'};
  730:     my $formtoset = 'crtuser';
  731:     if (exists($env{'form.startrolename'})) {
  732:         $formtoset = 'docustom';
  733:         $env{'form.rolename'} = $env{'form.startrolename'};
  734:     } elsif ($env{'form.origform'} eq 'crtusername') {
  735:         $formtoset =  $env{'form.origform'};
  736:     }
  737: 
  738:     my ($jsback,$elements) = &crumb_utilities();
  739: 
  740:     my $jscript = &Apache::loncommon::studentbrowser_javascript()."\n".
  741:         '<script type="text/javascript">'."\n".
  742:         '// <![CDATA['."\n".
  743:         &Apache::lonhtmlcommon::set_form_elements($elements->{$formtoset})."\n".
  744:         '// ]]>'."\n".
  745:         '</script>'."\n";
  746: 
  747:     my %existingroles=&Apache::lonuserutils::my_custom_roles($crstype);
  748:     if (($env{'form.action'} eq 'custom') && (keys(%existingroles) > 0)
  749:         && (&Apache::lonnet::allowed('mcr','/'))) {
  750:         $jscript .= &customrole_javascript();
  751:     }
  752:     my $helpitem = 'Course_Change_Privileges';
  753:     if ($env{'form.action'} eq 'custom') {
  754:         $helpitem = 'Course_Editing_Custom_Roles';
  755:     } elsif ($env{'form.action'} eq 'singlestudent') {
  756:         $helpitem = 'Course_Add_Student';
  757:     } elsif ($env{'form.action'} eq 'accesslogs') {
  758:         $helpitem = 'Domain_User_Access_Logs';
  759:     }
  760:     my %breadcrumb_text = &singleuser_breadcrumb($crstype,$context,$defdom);
  761:     if ($env{'form.action'} eq 'custom') {
  762:         push(@{$brcrum},
  763:                  {href=>"javascript:backPage(document.crtuser)",       
  764:                   text=>"Pick custom role",
  765:                   help => $helpitem,}
  766:                  );
  767:     } else {
  768:         push (@{$brcrum},
  769:                   {href => "javascript:backPage(document.crtuser)",
  770:                    text => $breadcrumb_text{'search'},
  771:                    help => $helpitem,
  772:                    faq  => 282,
  773:                    bug  => 'Instructor Interface',}
  774:                   );
  775:     }
  776:     my %loaditems = (
  777:                 'onload' => "javascript:setFormElements(document.$formtoset)",
  778:                     );
  779:     my $args = {bread_crumbs           => $brcrum,
  780:                 bread_crumbs_component => 'User Management',
  781:                 add_entries            => \%loaditems,};
  782:     $r->print(&Apache::loncommon::start_page('User Management',$jscript,$args));
  783: 
  784:     my %lt=&Apache::lonlocal::texthash(
  785:                     'srst' => 'Search for a user and enroll as a student',
  786:                     'srme' => 'Search for a user and enroll as a member',
  787:                     'srad' => 'Search for a user and modify/add user information or roles',
  788:                     'srvu' => 'Search for a user and view user information and roles',
  789:                     'srva' => 'Search for a user and view access log information',
  790: 		    'usr'  => "Username",
  791:                     'dom'  => "Domain",
  792:                     'ecrp' => "Define or Edit Custom Role",
  793:                     'nr'   => "role name",
  794:                     'cre'  => "Next",
  795: 				       );
  796: 
  797:     if ($env{'form.action'} eq 'custom') {
  798:         if (&Apache::lonnet::allowed('mcr','/')) {
  799:             my $newroletext = &mt('Define new custom role:');
  800:             $r->print('<form action="/adm/createuser" method="post" name="docustom">'.
  801:                       '<input type="hidden" name="action" value="'.$env{'form.action'}.'" />'.
  802:                       '<input type="hidden" name="phase" value="selected_custom_edit" />'.
  803:                       '<h3>'.$lt{'ecrp'}.'</h3>'.
  804:                       &Apache::loncommon::start_data_table().
  805:                       &Apache::loncommon::start_data_table_row().
  806:                       '<td>');
  807:             if (keys(%existingroles) > 0) {
  808:                 $r->print('<br /><label><input type="radio" name="customroleaction" value="new" checked="checked" onclick="setCustomFields();" /><b>'.$newroletext.'</b></label>');
  809:             } else {
  810:                 $r->print('<br /><input type="hidden" name="customroleaction" value="new" /><b>'.$newroletext.'</b>');
  811:             }
  812:             $r->print('</td><td align="center">'.$lt{'nr'}.'<br /><input type="text" size="15" name="newrolename" onfocus="setCustomAction('."'new'".');" /></td>'.
  813:                       &Apache::loncommon::end_data_table_row());
  814:             if (keys(%existingroles) > 0) {
  815:                 $r->print(&Apache::loncommon::start_data_table_row().'<td><br />'.
  816:                           '<label><input type="radio" name="customroleaction" value="edit" onclick="setCustomFields();"/><b>'.
  817:                           &mt('View/Modify existing role:').'</b></label></td>'.
  818:                           '<td align="center"><br />'.
  819:                           '<select name="rolename" onchange="setCustomAction('."'edit'".');">'.
  820:                           '<option value="" selected="selected">'.
  821:                           &mt('Select'));
  822:                 foreach my $role (sort(keys(%existingroles))) {
  823:                     $r->print('<option value="'.$role.'">'.$role.'</option>');
  824:                 }
  825:                 $r->print('</select>'.
  826:                           '</td>'.
  827:                           &Apache::loncommon::end_data_table_row());
  828:             }
  829:             $r->print(&Apache::loncommon::end_data_table().'<p>'.
  830:                       '<input name="customeditor" type="submit" value="'.
  831:                       $lt{'cre'}.'" /></p>'.
  832:                       '</form>');
  833:         }
  834:     } else {
  835:         my $actiontext = $lt{'srad'};
  836:         if ($env{'form.action'} eq 'singlestudent') {
  837:             if ($crstype eq 'Community') {
  838:                 $actiontext = $lt{'srme'};
  839:             } else {
  840:                 $actiontext = $lt{'srst'};
  841:             }
  842:         } elsif ($env{'form.action'} eq 'accesslogs') {
  843:             $actiontext = $lt{'srva'};
  844:         } elsif (($env{'form.action'} eq 'singleuser') &&
  845:                  ($context eq 'domain') && (!&Apache::lonnet::allowed('mau',$defdom))) {
  846:             $actiontext = $lt{'srvu'};
  847:         }
  848:         $r->print("<h3>$actiontext</h3>");
  849:         if ($env{'form.origform'} ne 'crtusername') {
  850:             if ($response) {
  851:                $r->print("\n<div>$response</div>".
  852:                          '<br clear="all" />');
  853:             }
  854:         }
  855:         $r->print(&entry_form($defdom,$srch,$forcenewuser,$context,$response,$crstype,1));
  856:     }
  857: }
  858: 
  859: sub customrole_javascript {
  860:     my $js = <<"END";
  861: <script type="text/javascript">
  862: // <![CDATA[
  863: 
  864: function setCustomFields() {
  865:     if (document.docustom.customroleaction.length > 0) {
  866:         for (var i=0; i<document.docustom.customroleaction.length; i++) {
  867:             if (document.docustom.customroleaction[i].checked) {
  868:                 if (document.docustom.customroleaction[i].value == 'new') {
  869:                     document.docustom.rolename.selectedIndex = 0;
  870:                 } else {
  871:                     document.docustom.newrolename.value = '';
  872:                 }
  873:             }
  874:         }
  875:     }
  876:     return;
  877: }
  878: 
  879: function setCustomAction(caller) {
  880:     if (document.docustom.customroleaction.length > 0) {
  881:         for (var i=0; i<document.docustom.customroleaction.length; i++) {
  882:             if (document.docustom.customroleaction[i].value == caller) {
  883:                 document.docustom.customroleaction[i].checked = true;
  884:             }
  885:         }
  886:     }
  887:     setCustomFields();
  888:     return;
  889: }
  890: 
  891: // ]]>
  892: </script>
  893: END
  894:     return $js;
  895: }
  896: 
  897: sub entry_form {
  898:     my ($dom,$srch,$forcenewuser,$context,$responsemsg,$crstype,$fixeddom) = @_;
  899:     my ($usertype,$inexact);
  900:     if (ref($srch) eq 'HASH') {
  901:         if (($srch->{'srchin'} eq 'dom') &&
  902:             ($srch->{'srchby'} eq 'uname') &&
  903:             ($srch->{'srchtype'} eq 'exact') &&
  904:             ($srch->{'srchdomain'} ne '') &&
  905:             ($srch->{'srchterm'} ne '')) {
  906:             my (%curr_rules,%got_rules);
  907:             my ($rules,$ruleorder) =
  908:                 &Apache::lonnet::inst_userrules($srch->{'srchdomain'},'username');
  909:             $usertype = &Apache::lonuserutils::check_usertype($srch->{'srchdomain'},$srch->{'srchterm'},$rules,\%curr_rules,\%got_rules);
  910:         } else {
  911:             $inexact = 1;
  912:         }
  913:     }
  914:     my $cancreate =
  915:         &Apache::lonuserutils::can_create_user($dom,$context,$usertype);
  916:     my ($userpicker,$cansearch) = 
  917:        &Apache::loncommon::user_picker($dom,$srch,$forcenewuser,
  918:                                        'document.crtuser',$cancreate,$usertype,$context,$fixeddom);
  919:     my $srchbutton = &mt('Search');
  920:     if ($env{'form.action'} eq 'singlestudent') {
  921:         $srchbutton = &mt('Search and Enroll');
  922:     } elsif ($env{'form.action'} eq 'accesslogs') {
  923:         $srchbutton = &mt('Search');
  924:     } elsif ($cancreate && $responsemsg ne '' && $inexact) {
  925:         $srchbutton = &mt('Search or Add New User');
  926:     }
  927:     my $output;
  928:     if ($cansearch) {
  929:         $output = <<"ENDBLOCK";
  930: <form action="/adm/createuser" method="post" name="crtuser">
  931: <input type="hidden" name="action" value="$env{'form.action'}" />
  932: <input type="hidden" name="phase" value="get_user_info" />
  933: $userpicker
  934: <input name="userrole" type="button" value="$srchbutton" onclick="javascript:validateEntry(document.crtuser)" />
  935: </form>
  936: ENDBLOCK
  937:     } else {
  938:         $output = '<p>'.$userpicker.'</p>';
  939:     }
  940:     if (($env{'form.phase'} eq '') && ($env{'form.action'} ne 'accesslogs') &&
  941:         (!(($env{'form.action'} eq 'singleuser') && ($context eq 'domain') && 
  942:         (!&Apache::lonnet::allowed('mau',$env{'request.role.domain'}))))) {
  943:         my $defdom=$env{'request.role.domain'};
  944:         my $domform = &Apache::loncommon::select_dom_form($defdom,'srchdomain');
  945:         my %lt=&Apache::lonlocal::texthash(
  946:                   'enro' => 'Enroll one student',
  947:                   'enrm' => 'Enroll one member',
  948:                   'admo' => 'Add/modify a single user',
  949:                   'crea' => 'create new user if required',
  950:                   'uskn' => "username is known",
  951:                   'crnu' => 'Create a new user',
  952:                   'usr'  => 'Username',
  953:                   'dom'  => 'in domain',
  954:                   'enrl' => 'Enroll',
  955:                   'cram'  => 'Create/Modify user',
  956:         );
  957:         my $sellink=&Apache::loncommon::selectstudent_link('crtusername','srchterm','srchdomain');
  958:         my ($title,$buttontext,$showresponse);
  959:         if ($env{'form.action'} eq 'singlestudent') {
  960:             if ($crstype eq 'Community') {
  961:                 $title = $lt{'enrm'};
  962:             } else {
  963:                 $title = $lt{'enro'};
  964:             }
  965:             $buttontext = $lt{'enrl'};
  966:         } else {
  967:             $title = $lt{'admo'};
  968:             $buttontext = $lt{'cram'};
  969:         }
  970:         if ($cancreate) {
  971:             $title .= ' <span class="LC_cusr_subheading">('.$lt{'crea'}.')</span>';
  972:         } else {
  973:             $title .= ' <span class="LC_cusr_subheading">('.$lt{'uskn'}.')</span>';
  974:         }
  975:         if ($env{'form.origform'} eq 'crtusername') {
  976:             $showresponse = $responsemsg;
  977:         }
  978:         $output .= <<"ENDDOCUMENT";
  979: <br />
  980: <form action="/adm/createuser" method="post" name="crtusername">
  981: <input type="hidden" name="action" value="$env{'form.action'}" />
  982: <input type="hidden" name="phase" value="createnewuser" />
  983: <input type="hidden" name="srchtype" value="exact" />
  984: <input type="hidden" name="srchby" value="uname" />
  985: <input type="hidden" name="srchin" value="dom" />
  986: <input type="hidden" name="forcenewuser" value="1" />
  987: <input type="hidden" name="origform" value="crtusername" />
  988: <h3>$title</h3>
  989: $showresponse
  990: <table>
  991:  <tr>
  992:   <td>$lt{'usr'}:</td>
  993:   <td><input type="text" size="15" name="srchterm" /></td>
  994:   <td>&nbsp;$lt{'dom'}:</td><td>$domform</td>
  995:   <td>&nbsp;$sellink&nbsp;</td>
  996:   <td>&nbsp;<input name="userrole" type="submit" value="$buttontext" /></td>
  997:  </tr>
  998: </table>
  999: </form>
 1000: ENDDOCUMENT
 1001:     }
 1002:     return $output;
 1003: }
 1004: 
 1005: sub user_modification_js {
 1006:     my ($pjump_def,$dc_setcourse_code,$nondc_setsection_code,$groupslist)=@_;
 1007:     
 1008:     return <<END;
 1009: <script type="text/javascript" language="Javascript">
 1010: // <![CDATA[
 1011: 
 1012:     $pjump_def
 1013:     $dc_setcourse_code
 1014: 
 1015:     function dateset() {
 1016:         eval("document.cu."+document.cu.pres_marker.value+
 1017:             ".value=document.cu.pres_value.value");
 1018:         modalWindow.close();
 1019:     }
 1020: 
 1021:     $nondc_setsection_code
 1022: // ]]>
 1023: </script>
 1024: END
 1025: }
 1026: 
 1027: # =================================================================== Phase two
 1028: sub print_user_selection_page {
 1029:     my ($r,$response,$srch,$srch_results,$srcharray,$context,$opener_elements,$crstype,$brcrum) = @_;
 1030:     my @fields = ('username','domain','lastname','firstname','permanentemail');
 1031:     my $sortby = $env{'form.sortby'};
 1032: 
 1033:     if (!grep(/^\Q$sortby\E$/,@fields)) {
 1034:         $sortby = 'lastname';
 1035:     }
 1036: 
 1037:     my ($jsback,$elements) = &crumb_utilities();
 1038: 
 1039:     my $jscript = (<<ENDSCRIPT);
 1040: <script type="text/javascript">
 1041: // <![CDATA[
 1042: function pickuser(uname,udom) {
 1043:     document.usersrchform.seluname.value=uname;
 1044:     document.usersrchform.seludom.value=udom;
 1045:     document.usersrchform.phase.value="userpicked";
 1046:     document.usersrchform.submit();
 1047: }
 1048: 
 1049: $jsback
 1050: // ]]>
 1051: </script>
 1052: ENDSCRIPT
 1053: 
 1054:     my %lt=&Apache::lonlocal::texthash(
 1055:                                        'usrch'          => "User Search to add/modify roles",
 1056:                                        'stusrch'        => "User Search to enroll student",
 1057:                                        'memsrch'        => "User Search to enroll member",
 1058:                                        'srcva'          => "Search for a user and view access log information",
 1059:                                        'usrvu'          => "User Search to view user roles",
 1060:                                        'usel'           => "Select a user to add/modify roles",
 1061:                                        'suvr'           => "Select a user to view roles",
 1062:                                        'stusel'         => "Select a user to enroll as a student",
 1063:                                        'memsel'         => "Select a user to enroll as a member",
 1064:                                        'vacsel'         => "Select a user to view access log",
 1065:                                        'username'       => "username",
 1066:                                        'domain'         => "domain",
 1067:                                        'lastname'       => "last name",
 1068:                                        'firstname'      => "first name",
 1069:                                        'permanentemail' => "permanent e-mail",
 1070:                                       );
 1071:     if ($context eq 'requestcrs') {
 1072:         $r->print('<div>');
 1073:     } else {
 1074:         my %breadcrumb_text = &singleuser_breadcrumb($crstype,$context,$srch->{'srchdomain'});
 1075:         my $helpitem;
 1076:         if ($env{'form.action'} eq 'singleuser') {
 1077:             $helpitem = 'Course_Change_Privileges';
 1078:         } elsif ($env{'form.action'} eq 'singlestudent') {
 1079:             $helpitem = 'Course_Add_Student';
 1080:         }
 1081:         push (@{$brcrum},
 1082:                   {href => "javascript:backPage(document.usersrchform,'','')",
 1083:                    text => $breadcrumb_text{'search'},
 1084:                    faq  => 282,
 1085:                    bug  => 'Instructor Interface',},
 1086:                   {href => "javascript:backPage(document.usersrchform,'get_user_info','select')",
 1087:                    text => $breadcrumb_text{'userpicked'},
 1088:                    faq  => 282,
 1089:                    bug  => 'Instructor Interface',
 1090:                    help => $helpitem}
 1091:                   );
 1092:         $r->print(&Apache::loncommon::start_page('User Management',$jscript,{bread_crumbs => $brcrum}));
 1093:         if ($env{'form.action'} eq 'singleuser') {
 1094:             my $readonly;
 1095:             if (($context eq 'domain') && (!&Apache::lonnet::allowed('mau',$srch->{'srchdomain'}))) {
 1096:                 $readonly = 1;
 1097:                 $r->print("<b>$lt{'usrvu'}</b><br />");
 1098:             } else {
 1099:                 $r->print("<b>$lt{'usrch'}</b><br />");
 1100:             }
 1101:             $r->print(&entry_form($srch->{'srchdomain'},$srch,undef,$context,undef,$crstype));
 1102:             if ($readonly) {
 1103:                 $r->print('<h3>'.$lt{'suvr'}.'</h3>');
 1104:             } else {
 1105:                 $r->print('<h3>'.$lt{'usel'}.'</h3>');
 1106:             }
 1107:         } elsif ($env{'form.action'} eq 'singlestudent') {
 1108:             $r->print($jscript."<b>");
 1109:             if ($crstype eq 'Community') {
 1110:                 $r->print($lt{'memsrch'});
 1111:             } else {
 1112:                 $r->print($lt{'stusrch'});
 1113:             }
 1114:             $r->print("</b><br />");
 1115:             $r->print(&entry_form($srch->{'srchdomain'},$srch,undef,$context,undef,$crstype));
 1116:             $r->print('</form><h3>');
 1117:             if ($crstype eq 'Community') {
 1118:                 $r->print($lt{'memsel'});
 1119:             } else {
 1120:                 $r->print($lt{'stusel'});
 1121:             }
 1122:             $r->print('</h3>');
 1123:         } elsif ($env{'form.action'} eq 'accesslogs') {
 1124:             $r->print("<b>$lt{'srcva'}</b><br />");
 1125:             $r->print(&entry_form($srch->{'srchdomain'},$srch,undef,'accesslogs',undef,undef,1));
 1126:             $r->print('<h3>'.$lt{'vacsel'}.'</h3>');
 1127:         }
 1128:     }
 1129:     $r->print('<form name="usersrchform" method="post" action="">'.
 1130:               &Apache::loncommon::start_data_table()."\n".
 1131:               &Apache::loncommon::start_data_table_header_row()."\n".
 1132:               ' <th> </th>'."\n");
 1133:     foreach my $field (@fields) {
 1134:         $r->print(' <th><a href="javascript:document.usersrchform.sortby.value='.
 1135:                   "'".$field."'".';document.usersrchform.submit();">'.
 1136:                   $lt{$field}.'</a></th>'."\n");
 1137:     }
 1138:     $r->print(&Apache::loncommon::end_data_table_header_row());
 1139: 
 1140:     my @sorted_users = sort {
 1141:         lc($srch_results->{$a}->{$sortby})   cmp lc($srch_results->{$b}->{$sortby})
 1142:             ||
 1143:         lc($srch_results->{$a}->{lastname})  cmp lc($srch_results->{$b}->{lastname})
 1144:             ||
 1145:         lc($srch_results->{$a}->{firstname}) cmp lc($srch_results->{$b}->{firstname})
 1146: 	    ||
 1147: 	lc($a) cmp lc($b)
 1148:         } (keys(%$srch_results));
 1149: 
 1150:     foreach my $user (@sorted_users) {
 1151:         my ($uname,$udom) = split(/:/,$user);
 1152:         my $onclick;
 1153:         if ($context eq 'requestcrs') {
 1154:             $onclick =
 1155:                 'onclick="javascript:gochoose('."'$uname','$udom',".
 1156:                                                "'$srch_results->{$user}->{firstname}',".
 1157:                                                "'$srch_results->{$user}->{lastname}',".
 1158:                                                "'$srch_results->{$user}->{permanentemail}'".');"';
 1159:         } else {
 1160:             $onclick =
 1161:                 ' onclick="javascript:pickuser('."'".$uname."'".','."'".$udom."'".');"';
 1162:         }
 1163:         $r->print(&Apache::loncommon::start_data_table_row().
 1164:                   '<td><input type="button" name="seluser" value="'.&mt('Select').'" '.
 1165:                   $onclick.' /></td>'.
 1166:                   '<td><tt>'.$uname.'</tt></td>'.
 1167:                   '<td><tt>'.$udom.'</tt></td>');
 1168:         foreach my $field ('lastname','firstname','permanentemail') {
 1169:             $r->print('<td>'.$srch_results->{$user}->{$field}.'</td>');
 1170:         }
 1171:         $r->print(&Apache::loncommon::end_data_table_row());
 1172:     }
 1173:     $r->print(&Apache::loncommon::end_data_table().'<br /><br />');
 1174:     if (ref($srcharray) eq 'ARRAY') {
 1175:         foreach my $item (@{$srcharray}) {
 1176:             $r->print('<input type="hidden" name="'.$item.'" value="'.$env{'form.'.$item}.'" />'."\n");
 1177:         }
 1178:     }
 1179:     $r->print(' <input type="hidden" name="sortby" value="'.$sortby.'" />'."\n".
 1180:               ' <input type="hidden" name="seluname" value="" />'."\n".
 1181:               ' <input type="hidden" name="seludom" value="" />'."\n".
 1182:               ' <input type="hidden" name="currstate" value="select" />'."\n".
 1183:               ' <input type="hidden" name="phase" value="get_user_info" />'."\n".
 1184:               ' <input type="hidden" name="action" value="'.$env{'form.action'}.'" />'."\n");
 1185:     if ($context eq 'requestcrs') {
 1186:         $r->print($opener_elements.'</form></div>');
 1187:     } else {
 1188:         $r->print($response.'</form>');
 1189:     }
 1190: }
 1191: 
 1192: sub print_user_query_page {
 1193:     my ($r,$caller,$brcrum) = @_;
 1194: # FIXME - this is for a network-wide name search (similar to catalog search)
 1195: # To use frames with similar behavior to catalog/portfolio search.
 1196: # To be implemented. 
 1197:     return;
 1198: }
 1199: 
 1200: sub print_user_modification_page {
 1201:     my ($r,$ccuname,$ccdomain,$srch,$response,$context,$permission,$crstype,
 1202:         $brcrum,$showcredits) = @_;
 1203:     if (($ccuname eq '') || ($ccdomain eq '')) {
 1204:         my $usermsg = &mt('No username and/or domain provided.');
 1205:         $env{'form.phase'} = '';
 1206: 	&print_username_entry_form($r,$context,$usermsg,'','',$crstype,$brcrum);
 1207:         return;
 1208:     }
 1209:     my ($form,$formname);
 1210:     if ($env{'form.action'} eq 'singlestudent') {
 1211:         $form = 'document.enrollstudent';
 1212:         $formname = 'enrollstudent';
 1213:     } else {
 1214:         $form = 'document.cu';
 1215:         $formname = 'cu';
 1216:     }
 1217:     my %abv_auth = &auth_abbrev();
 1218:     my (%rulematch,%inst_results,$newuser,%alerts,%curr_rules,%got_rules);
 1219:     my $uhome=&Apache::lonnet::homeserver($ccuname,$ccdomain);
 1220:     if ($uhome eq 'no_host') {
 1221:         my $usertype;
 1222:         my ($rules,$ruleorder) =
 1223:             &Apache::lonnet::inst_userrules($ccdomain,'username');
 1224:             $usertype =
 1225:                 &Apache::lonuserutils::check_usertype($ccdomain,$ccuname,$rules,
 1226:                                                       \%curr_rules,\%got_rules);
 1227:         my $cancreate =
 1228:             &Apache::lonuserutils::can_create_user($ccdomain,$context,
 1229:                                                    $usertype);
 1230:         if (!$cancreate) {
 1231:             my $helplink = 'javascript:helpMenu('."'display'".')';
 1232:             my %usertypetext = (
 1233:                 official   => 'institutional',
 1234:                 unofficial => 'non-institutional',
 1235:             );
 1236:             my $response;
 1237:             if ($env{'form.origform'} eq 'crtusername') {
 1238:                 $response = '<span class="LC_warning">'.
 1239:                             &mt('No match found for the username [_1] in LON-CAPA domain: [_2]',
 1240:                                 '<b>'.$ccuname.'</b>',$ccdomain).
 1241:                             '</span><br />';
 1242:             }
 1243:             $response .= '<p class="LC_warning">'
 1244:                         .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
 1245:                         .' ';
 1246:             if ($context eq 'domain') {
 1247:                 $response .= &mt('Please contact a [_1] for assistance.',
 1248:                                  &Apache::lonnet::plaintext('dc'));
 1249:             } else {
 1250:                 $response .= &mt('Please contact the [_1]helpdesk[_2] for assistance.'
 1251:                                 ,'<a href="'.$helplink.'">','</a>');
 1252:             }
 1253:             $response .= '</p><br />';
 1254:             $env{'form.phase'} = '';
 1255:             &print_username_entry_form($r,$context,$response,undef,undef,$crstype,$brcrum);
 1256:             return;
 1257:         }
 1258:         $newuser = 1;
 1259:         my $checkhash;
 1260:         my $checks = { 'username' => 1 };
 1261:         $checkhash->{$ccuname.':'.$ccdomain} = { 'newuser' => $newuser };
 1262:         &Apache::loncommon::user_rule_check($checkhash,$checks,
 1263:             \%alerts,\%rulematch,\%inst_results,\%curr_rules,\%got_rules);
 1264:         if (ref($alerts{'username'}) eq 'HASH') {
 1265:             if (ref($alerts{'username'}{$ccdomain}) eq 'HASH') {
 1266:                 my $domdesc =
 1267:                     &Apache::lonnet::domain($ccdomain,'description');
 1268:                 if ($alerts{'username'}{$ccdomain}{$ccuname}) {
 1269:                     my $userchkmsg;
 1270:                     if (ref($curr_rules{$ccdomain}) eq 'HASH') {  
 1271:                         $userchkmsg = 
 1272:                             &Apache::loncommon::instrule_disallow_msg('username',
 1273:                                                                  $domdesc,1).
 1274:                         &Apache::loncommon::user_rule_formats($ccdomain,
 1275:                             $domdesc,$curr_rules{$ccdomain}{'username'},
 1276:                             'username');
 1277:                     }
 1278:                     $env{'form.phase'} = '';
 1279:                     &print_username_entry_form($r,$context,$userchkmsg,undef,undef,$crstype,$brcrum);
 1280:                     return;
 1281:                 }
 1282:             }
 1283:         }
 1284:     } else {
 1285:         $newuser = 0;
 1286:     }
 1287:     if ($response) {
 1288:         $response = '<br />'.$response;
 1289:     }
 1290: 
 1291:     my $pjump_def = &Apache::lonhtmlcommon::pjump_javascript_definition();
 1292:     my $dc_setcourse_code = '';
 1293:     my $nondc_setsection_code = '';                                        
 1294:     my %loaditem;
 1295: 
 1296:     my $groupslist = &Apache::lonuserutils::get_groupslist();
 1297: 
 1298:     my $js = &validation_javascript($context,$ccdomain,$pjump_def,$crstype,
 1299:                                $groupslist,$newuser,$formname,\%loaditem);
 1300:     my %breadcrumb_text = &singleuser_breadcrumb($crstype,$context,$ccdomain);
 1301:     my $helpitem = 'Course_Change_Privileges';
 1302:     if ($env{'form.action'} eq 'singlestudent') {
 1303:         $helpitem = 'Course_Add_Student';
 1304:     }
 1305:     push (@{$brcrum},
 1306:         {href => "javascript:backPage($form)",
 1307:          text => $breadcrumb_text{'search'},
 1308:          faq  => 282,
 1309:          bug  => 'Instructor Interface',});
 1310:     if ($env{'form.phase'} eq 'userpicked') {
 1311:        push(@{$brcrum},
 1312:               {href => "javascript:backPage($form,'get_user_info','select')",
 1313:                text => $breadcrumb_text{'userpicked'},
 1314:                faq  => 282,
 1315:                bug  => 'Instructor Interface',});
 1316:     }
 1317:     push(@{$brcrum},
 1318:             {href => "javascript:backPage($form,'$env{'form.phase'}','modify')",
 1319:              text => $breadcrumb_text{'modify'},
 1320:              faq  => 282,
 1321:              bug  => 'Instructor Interface',
 1322:              help => $helpitem});
 1323:     my $args = {'add_entries'           => \%loaditem,
 1324:                 'bread_crumbs'          => $brcrum,
 1325:                 'bread_crumbs_component' => 'User Management'};
 1326:     if ($env{'form.popup'}) {
 1327:         $args->{'no_nav_bar'} = 1;
 1328:     }
 1329:     my $start_page =
 1330:         &Apache::loncommon::start_page('User Management',$js,$args);
 1331: 
 1332:     my $forminfo =<<"ENDFORMINFO";
 1333: <form action="/adm/createuser" method="post" name="$formname">
 1334: <input type="hidden" name="phase" value="update_user_data" />
 1335: <input type="hidden" name="ccuname" value="$ccuname" />
 1336: <input type="hidden" name="ccdomain" value="$ccdomain" />
 1337: <input type="hidden" name="pres_value"  value="" />
 1338: <input type="hidden" name="pres_type"   value="" />
 1339: <input type="hidden" name="pres_marker" value="" />
 1340: ENDFORMINFO
 1341:     my (%inccourses,$roledom,$defaultcredits);
 1342:     if ($context eq 'course') {
 1343:         $inccourses{$env{'request.course.id'}}=1;
 1344:         $roledom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 1345:         if ($showcredits) {
 1346:             $defaultcredits = &Apache::lonuserutils::get_defaultcredits();
 1347:         }
 1348:     } elsif ($context eq 'author') {
 1349:         $roledom = $env{'request.role.domain'};
 1350:     } elsif ($context eq 'domain') {
 1351:         foreach my $key (keys(%env)) {
 1352:             $roledom = $env{'request.role.domain'};
 1353:             if ($key=~/^user\.priv\.cm\.\/($roledom)\/($match_username)/) {
 1354:                 $inccourses{$1.'_'.$2}=1;
 1355:             }
 1356:         }
 1357:     } else {
 1358:         foreach my $key (keys(%env)) {
 1359: 	    if ($key=~/^user\.priv\.cm\.\/($match_domain)\/($match_username)/) {
 1360: 	        $inccourses{$1.'_'.$2}=1;
 1361:             }
 1362:         }
 1363:     }
 1364:     my $title = '';
 1365:     if ($newuser) {
 1366:         my ($portfolioform,$domroleform,$adhocroleform);
 1367:         if ((&Apache::lonnet::allowed('mpq',$env{'request.role.domain'})) ||
 1368:             (&Apache::lonnet::allowed('mut',$env{'request.role.domain'}))) {
 1369:             # Current user has quota or user tools modification privileges
 1370:             $portfolioform = '<br />'.&user_quotas($ccuname,$ccdomain);
 1371:         }
 1372:         if ((&Apache::lonnet::allowed('cau',$env{'request.role.domain'})) &&
 1373:             ($ccdomain eq $env{'request.role.domain'})) {
 1374:             $domroleform = '<br />'.&domainrole_req($ccuname,$ccdomain);
 1375:         }
 1376:         if (&Apache::lonnet::allowed('cdh',$env{'request.role.domain'})) {
 1377:             $adhocroleform = &domadhocroles($ccuname,$ccdomain);
 1378:             if ($adhocroleform) {
 1379:                 $adhocroleform = '<br />'.$adhocroleform;
 1380:             }
 1381:         }
 1382:         &initialize_authen_forms($ccdomain,$formname);
 1383:         my %lt=&Apache::lonlocal::texthash(
 1384:                 'lg'             => 'Login Data',
 1385:                 'hs'             => "Home Server",
 1386:         );
 1387: 	$r->print(<<ENDTITLE);
 1388: $start_page
 1389: $response
 1390: $forminfo
 1391: <script type="text/javascript" language="Javascript">
 1392: // <![CDATA[
 1393: $loginscript
 1394: // ]]>
 1395: </script>
 1396: <input type='hidden' name='makeuser' value='1' />
 1397: ENDTITLE
 1398:         if ($env{'form.action'} eq 'singlestudent') {
 1399:             if ($crstype eq 'Community') {
 1400:                 $title = &mt('Create New User [_1] in domain [_2] as a member',
 1401:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1402:             } else {
 1403:                 $title = &mt('Create New User [_1] in domain [_2] as a student',
 1404:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1405:             }
 1406:         } else {
 1407:                 $title = &mt('Create New User [_1] in domain [_2]',
 1408:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1409:         }
 1410:         $r->print('<h2>'.$title.'</h2>'."\n");
 1411:         $r->print('<div class="LC_left_float">');
 1412:         $r->print(&personal_data_display($ccuname,$ccdomain,$newuser,$context,
 1413:                                          $inst_results{$ccuname.':'.$ccdomain}));
 1414:         # Option to disable student/employee ID conflict checking not offerred for new users.
 1415:         my ($home_server_pick,$numlib) = 
 1416:             &Apache::loncommon::home_server_form_item($ccdomain,'hserver',
 1417:                                                       'default','hide');
 1418:         if ($numlib > 1) {
 1419:             $r->print("
 1420: <br />
 1421: $lt{'hs'}: $home_server_pick
 1422: <br />");
 1423:         } else {
 1424:             $r->print($home_server_pick);
 1425:         }
 1426:         if (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) {
 1427:             $r->print('<br /><h3>'.
 1428:                       &mt('User Can Request Creation of Courses/Communities in this Domain?').'</h3>'.
 1429:                       &Apache::loncommon::start_data_table().
 1430:                       &build_tools_display($ccuname,$ccdomain,
 1431:                                            'requestcourses').
 1432:                       &Apache::loncommon::end_data_table());
 1433:         }
 1434:         $r->print('</div>'."\n".'<div class="LC_left_float"><h3>'.
 1435:                   $lt{'lg'}.'</h3>');
 1436:         my ($fixedauth,$varauth,$authmsg); 
 1437:         if (ref($rulematch{$ccuname.':'.$ccdomain}) eq 'HASH') {
 1438:             my $matchedrule = $rulematch{$ccuname.':'.$ccdomain}{'username'};
 1439:             my ($rules,$ruleorder) = 
 1440:                 &Apache::lonnet::inst_userrules($ccdomain,'username');
 1441:             if (ref($rules) eq 'HASH') {
 1442:                 if (ref($rules->{$matchedrule}) eq 'HASH') {
 1443:                     my $authtype = $rules->{$matchedrule}{'authtype'};
 1444:                     if ($authtype !~ /^(krb4|krb5|int|fsys|loc)$/) {
 1445:                         $r->print(&Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc));
 1446:                     } else { 
 1447:                         my $authparm = $rules->{$matchedrule}{'authparm'};
 1448:                         $authmsg = $rules->{$matchedrule}{'authmsg'};
 1449:                         if ($authtype =~ /^krb(4|5)$/) {
 1450:                             my $ver = $1;
 1451:                             if ($authparm ne '') {
 1452:                                 $fixedauth = <<"KERB"; 
 1453: <input type="hidden" name="login" value="krb" />
 1454: <input type="hidden" name="krbver" value="$ver" />
 1455: <input type="hidden" name="krbarg" value="$authparm" />
 1456: KERB
 1457:                             }
 1458:                         } else {
 1459:                             $fixedauth = 
 1460: '<input type="hidden" name="login" value="'.$authtype.'" />'."\n";
 1461:                             if ($rules->{$matchedrule}{'authparmfixed'}) {
 1462:                                 $fixedauth .=    
 1463: '<input type="hidden" name="'.$authtype.'arg" value="'.$authparm.'" />'."\n";
 1464:                             } else {
 1465:                                 if ($authtype eq 'int') {
 1466:                                     $varauth = '<br />'.
 1467: &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>';
 1468:                                 } elsif ($authtype eq 'loc') {
 1469:                                     $varauth = '<br />'.
 1470: &mt('[_1] Local Authentication with argument [_2]','','<input type="text" name="'.$authtype.'arg" value="" />')."\n";
 1471:                                 } else {
 1472:                                     $varauth =
 1473: '<input type="text" name="'.$authtype.'arg" value="" />'."\n";
 1474:                                 }
 1475:                             }
 1476:                         }
 1477:                     }
 1478:                 } else {
 1479:                     $r->print(&Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc));
 1480:                 }
 1481:             }
 1482:             if ($authmsg) {
 1483:                 $r->print(<<ENDAUTH);
 1484: $fixedauth
 1485: $authmsg
 1486: $varauth
 1487: ENDAUTH
 1488:             }
 1489:         } else {
 1490:             $r->print(&Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc)); 
 1491:         }
 1492:         $r->print($portfolioform.$domroleform.$adhocroleform);
 1493:         if ($env{'form.action'} eq 'singlestudent') {
 1494:             $r->print(&date_sections_select($context,$newuser,$formname,
 1495:                                             $permission,$crstype,$ccuname,
 1496:                                             $ccdomain,$showcredits));
 1497:         }
 1498:         $r->print('</div><div class="LC_clear_float_footer"></div>');
 1499:     } else { # user already exists
 1500: 	$r->print($start_page.$forminfo);
 1501:         if ($env{'form.action'} eq 'singlestudent') {
 1502:             if ($crstype eq 'Community') {
 1503:                 $title = &mt('Enroll one member: [_1] in domain [_2]',
 1504:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1505:             } else {
 1506:                 $title = &mt('Enroll one student: [_1] in domain [_2]',
 1507:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1508:             }
 1509:         } else {
 1510:             if ($permission->{'cusr'}) {
 1511:                 $title = &mt('Modify existing user: [_1] in domain [_2]',
 1512:                              '"'.$ccuname.'"','"'.$ccdomain.'"');
 1513:             } else {
 1514:                 $title = &mt('Existing user: [_1] in domain [_2]',
 1515:                              '"'.$ccuname.'"','"'.$ccdomain.'"');
 1516:             }
 1517:         }
 1518:         $r->print('<h2>'.$title.'</h2>'."\n");
 1519:         $r->print('<div class="LC_left_float">');
 1520:         $r->print(&personal_data_display($ccuname,$ccdomain,$newuser,$context,
 1521:                                          $inst_results{$ccuname.':'.$ccdomain}));
 1522:         if ((&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) || 
 1523:             (&Apache::lonnet::allowed('udp',$env{'request.role.domain'}))) {
 1524:             $r->print('<br /><h3>'.&mt('User Can Request Creation of Courses/Communities in this Domain?').'</h3>'.
 1525:                       &Apache::loncommon::start_data_table());
 1526:             if ($env{'request.role.domain'} eq $ccdomain) {
 1527:                 $r->print(&build_tools_display($ccuname,$ccdomain,'requestcourses'));
 1528:             } else {
 1529:                 $r->print(&coursereq_externaluser($ccuname,$ccdomain,
 1530:                                                   $env{'request.role.domain'}));
 1531:             }
 1532:             $r->print(&Apache::loncommon::end_data_table());
 1533:         }
 1534:         $r->print('</div>');
 1535:         my @order = ('auth','quota','tools','requestauthor','adhocroles');
 1536:         my %user_text;
 1537:         my ($isadv,$isauthor) = 
 1538:             &Apache::lonnet::is_advanced_user($ccdomain,$ccuname);
 1539:         if ((!$isauthor) && 
 1540:             ((&Apache::lonnet::allowed('cau',$env{'request.role.domain'})) ||
 1541:              (&Apache::lonnet::allowed('udp',$env{'request.role.domain'}))) &&
 1542:             ($env{'request.role.domain'} eq $ccdomain)) {
 1543:             $user_text{'requestauthor'} = &domainrole_req($ccuname,$ccdomain);
 1544:         }
 1545:         if ((&Apache::lonnet::allowed('cdh',$env{'request.role.domain'})) || 
 1546:             (&Apache::lonnet::allowed('udp',$env{'request.role.domain'}))) {
 1547:             $user_text{'adhocroles'} = &domadhocroles($ccuname,$ccdomain);
 1548:         }
 1549:         $user_text{'auth'} =  &user_authentication($ccuname,$ccdomain,$formname);
 1550:         if ((&Apache::lonnet::allowed('mpq',$ccdomain)) ||
 1551:             (&Apache::lonnet::allowed('mut',$ccdomain)) ||
 1552:             (&Apache::lonnet::allowed('udp',$ccdomain))) {
 1553:             # Current user has quota modification privileges
 1554:             $user_text{'quota'} = &user_quotas($ccuname,$ccdomain);
 1555:         }
 1556:         if (!&Apache::lonnet::allowed('mpq',$ccdomain)) {
 1557:             if (&Apache::lonnet::allowed('mpq',$env{'request.role.domain'})) {
 1558:                 my %lt=&Apache::lonlocal::texthash(
 1559:                     'dska'  => "Disk quotas for user's portfolio and Authoring Space",
 1560:                     'youd'  => "You do not have privileges to modify the portfolio and/or Authoring Space quotas for this user.",
 1561:                     'ichr'  => "If a change is required, contact a domain coordinator for the domain",
 1562:                 );
 1563:                 $user_text{'quota'} = <<ENDNOPORTPRIV;
 1564: <h3>$lt{'dska'}</h3>
 1565: $lt{'youd'} $lt{'ichr'}: $ccdomain
 1566: ENDNOPORTPRIV
 1567:             }
 1568:         }
 1569:         if (!&Apache::lonnet::allowed('mut',$ccdomain)) {
 1570:             if (&Apache::lonnet::allowed('mut',$env{'request.role.domain'})) {
 1571:                 my %lt=&Apache::lonlocal::texthash(
 1572:                     'utav'  => "User Tools Availability",
 1573:                     'yodo'  => "You do not have privileges to modify Portfolio, Blog, WebDAV, or Personal Information Page settings for this user.",
 1574:                     'ifch'  => "If a change is required, contact a domain coordinator for the domain",
 1575:                 );
 1576:                 $user_text{'tools'} = <<ENDNOTOOLSPRIV;
 1577: <h3>$lt{'utav'}</h3>
 1578: $lt{'yodo'} $lt{'ifch'}: $ccdomain
 1579: ENDNOTOOLSPRIV
 1580:             }
 1581:         }
 1582:         my $gotdiv = 0; 
 1583:         foreach my $item (@order) {
 1584:             if ($user_text{$item} ne '') {
 1585:                 unless ($gotdiv) {
 1586:                     $r->print('<div class="LC_left_float">');
 1587:                     $gotdiv = 1;
 1588:                 }
 1589:                 $r->print('<br />'.$user_text{$item});
 1590:             }
 1591:         }
 1592:         if ($env{'form.action'} eq 'singlestudent') {
 1593:             unless ($gotdiv) {
 1594:                 $r->print('<div class="LC_left_float">');
 1595:             }
 1596:             my $credits;
 1597:             if ($showcredits) {
 1598:                 $credits = &get_user_credits($ccuname,$ccdomain,$defaultcredits);
 1599:                 if ($credits eq '') {
 1600:                     $credits = $defaultcredits;
 1601:                 }
 1602:             }
 1603:             $r->print(&date_sections_select($context,$newuser,$formname,
 1604:                                             $permission,$crstype,$ccuname,
 1605:                                             $ccdomain,$showcredits));
 1606:         }
 1607:         if ($gotdiv) {
 1608:             $r->print('</div><div class="LC_clear_float_footer"></div>');
 1609:         }
 1610:         my $statuses;
 1611:         if (($context eq 'domain') && (&Apache::lonnet::allowed('udp',$ccdomain)) &&
 1612:             (!&Apache::lonnet::allowed('mau',$ccdomain))) {
 1613:             $statuses = ['active'];
 1614:         } elsif (($context eq 'course') && ((&Apache::lonnet::allowed('vcl',$env{'request.course.id'})) ||
 1615:                  ($env{'request.course.sec'} &&
 1616:                   &Apache::lonnet::allowed('vcl',$env{'request.course.id'}.'/'.$env{'request.course.sec'})))) {
 1617:             $statuses = ['active'];   
 1618:         }
 1619:         if ($env{'form.action'} ne 'singlestudent') {
 1620:             &display_existing_roles($r,$ccuname,$ccdomain,\%inccourses,$context,
 1621:                                     $roledom,$crstype,$showcredits,$statuses);
 1622:         }
 1623:     } ## End of new user/old user logic
 1624:     if ($env{'form.action'} eq 'singlestudent') {
 1625:         my $btntxt;
 1626:         if ($crstype eq 'Community') {
 1627:             $btntxt = &mt('Enroll Member');
 1628:         } else {
 1629:             $btntxt = &mt('Enroll Student');
 1630:         }
 1631:         $r->print('<br /><input type="button" value="'.$btntxt.'" onclick="setSections(this.form)" />'."\n");
 1632:     } elsif ($permission->{'cusr'}) {
 1633:         $r->print('<div class="LC_left_float">'.
 1634:                   '<fieldset><legend>'.&mt('Add Roles').'</legend>');
 1635:         my $addrolesdisplay = 0;
 1636:         if ($context eq 'domain' || $context eq 'author') {
 1637:             $addrolesdisplay = &new_coauthor_roles($r,$ccuname,$ccdomain);
 1638:         }
 1639:         if ($context eq 'domain') {
 1640:             my $add_domainroles = &new_domain_roles($r,$ccdomain);
 1641:             if (!$addrolesdisplay) {
 1642:                 $addrolesdisplay = $add_domainroles;
 1643:             }
 1644:             $r->print(&course_level_dc($env{'request.role.domain'},$showcredits));
 1645:             $r->print('</fieldset></div><div class="LC_clear_float_footer"></div>'.
 1646:                       '<br /><input type="button" value="'.&mt('Save').'" onclick="setCourse()" />'."\n");
 1647:         } elsif ($context eq 'author') {
 1648:             if ($addrolesdisplay) {
 1649:                 $r->print('</fieldset></div><div class="LC_clear_float_footer"></div>'.
 1650:                           '<br /><input type="button" value="'.&mt('Save').'"');
 1651:                 if ($newuser) {
 1652:                     $r->print(' onclick="auth_check()" \>'."\n");
 1653:                 } else {
 1654:                     $r->print('onclick="this.form.submit()" \>'."\n");
 1655:                 }
 1656:             } else {
 1657:                 $r->print('</fieldset></div>'.
 1658:                           '<div class="LC_clear_float_footer"></div>'.
 1659:                           '<br /><a href="javascript:backPage(document.cu)">'.
 1660:                           &mt('Back to previous page').'</a>');
 1661:             }
 1662:         } else {
 1663:             $r->print(&course_level_table(\%inccourses,$showcredits,$defaultcredits));
 1664:             $r->print('</fieldset></div><div class="LC_clear_float_footer"></div>'.
 1665:                       '<br /><input type="button" value="'.&mt('Save').'" onclick="setSections(this.form)" />'."\n");
 1666:         }
 1667:     }
 1668:     $r->print(&Apache::lonhtmlcommon::echo_form_input(['phase','userrole','ccdomain','prevphase','currstate','ccuname','ccdomain']));
 1669:     $r->print('<input type="hidden" name="currstate" value="" />');
 1670:     $r->print('<input type="hidden" name="prevphase" value="'.$env{'form.phase'}.'" /></form><br /><br />');
 1671:     return;
 1672: }
 1673: 
 1674: sub singleuser_breadcrumb {
 1675:     my ($crstype,$context,$domain) = @_;
 1676:     my %breadcrumb_text;
 1677:     if ($env{'form.action'} eq 'singlestudent') {
 1678:         if ($crstype eq 'Community') {
 1679:             $breadcrumb_text{'search'} = 'Enroll a member';
 1680:         } else {
 1681:             $breadcrumb_text{'search'} = 'Enroll a student';
 1682:         }
 1683:         $breadcrumb_text{'userpicked'} = 'Select a user';
 1684:         $breadcrumb_text{'modify'} = 'Set section/dates';
 1685:     } elsif ($env{'form.action'} eq 'accesslogs') {
 1686:         $breadcrumb_text{'search'} = 'View access logs for a user';
 1687:         $breadcrumb_text{'userpicked'} = 'Select a user';
 1688:         $breadcrumb_text{'activity'} = 'Activity';
 1689:     } elsif (($env{'form.action'} eq 'singleuser') && ($context eq 'domain') &&
 1690:              (!&Apache::lonnet::allowed('mau',$domain))) {
 1691:         $breadcrumb_text{'search'} = "View user's roles";
 1692:         $breadcrumb_text{'userpicked'} = 'Select a user';
 1693:         $breadcrumb_text{'modify'} = 'User roles';
 1694:     } else {
 1695:         $breadcrumb_text{'search'} = 'Create/modify a user';
 1696:         $breadcrumb_text{'userpicked'} = 'Select a user';
 1697:         $breadcrumb_text{'modify'} = 'Set user role';
 1698:     }
 1699:     return %breadcrumb_text;
 1700: }
 1701: 
 1702: sub date_sections_select {
 1703:     my ($context,$newuser,$formname,$permission,$crstype,$ccuname,$ccdomain,
 1704:         $showcredits) = @_;
 1705:     my $credits;
 1706:     if ($showcredits) {
 1707:         my $defaultcredits = &Apache::lonuserutils::get_defaultcredits();
 1708:         $credits = &get_user_credits($ccuname,$ccdomain,$defaultcredits);
 1709:         if ($credits eq '') {
 1710:             $credits = $defaultcredits;
 1711:         }
 1712:     }
 1713:     my $cid = $env{'request.course.id'};
 1714:     my ($cnum,$cdom) = &Apache::lonuserutils::get_course_identity($cid);
 1715:     my $date_table = '<h3>'.&mt('Starting and Ending Dates').'</h3>'."\n".
 1716:         &Apache::lonuserutils::date_setting_table(undef,undef,$context,
 1717:                                                   undef,$formname,$permission);
 1718:     my $rowtitle = 'Section';
 1719:     my $secbox = '<h3>'.&mt('Section and Credits').'</h3>'."\n".
 1720:         &Apache::lonuserutils::section_picker($cdom,$cnum,'st',$rowtitle,
 1721:                                               $permission,$context,'',$crstype,
 1722:                                               $showcredits,$credits);
 1723:     my $output = $date_table.$secbox;
 1724:     return $output;
 1725: }
 1726: 
 1727: sub validation_javascript {
 1728:     my ($context,$ccdomain,$pjump_def,$crstype,$groupslist,$newuser,$formname,
 1729:         $loaditem) = @_;
 1730:     my $dc_setcourse_code = '';
 1731:     my $nondc_setsection_code = '';
 1732:     if ($context eq 'domain') {
 1733:         my $dcdom = $env{'request.role.domain'};
 1734:         $loaditem->{'onload'} = "document.cu.coursedesc.value='';";
 1735:         $dc_setcourse_code = 
 1736:             &Apache::lonuserutils::dc_setcourse_js('cu','singleuser',$context);
 1737:     } else {
 1738:         my $checkauth; 
 1739:         if (($newuser) || (&Apache::lonnet::allowed('mau',$ccdomain))) {
 1740:             $checkauth = 1;
 1741:         }
 1742:         if ($context eq 'course') {
 1743:             $nondc_setsection_code =
 1744:                 &Apache::lonuserutils::setsections_javascript($formname,$groupslist,
 1745:                                                               undef,$checkauth,
 1746:                                                               $crstype);
 1747:         }
 1748:         if ($checkauth) {
 1749:             $nondc_setsection_code .= 
 1750:                 &Apache::lonuserutils::verify_authen($formname,$context);
 1751:         }
 1752:     }
 1753:     my $js = &user_modification_js($pjump_def,$dc_setcourse_code,
 1754:                                    $nondc_setsection_code,$groupslist);
 1755:     my ($jsback,$elements) = &crumb_utilities();
 1756:     $js .= "\n".
 1757:            '<script type="text/javascript">'."\n".
 1758:            '// <![CDATA['."\n".
 1759:            $jsback."\n".
 1760:            '// ]]>'."\n".
 1761:            '</script>'."\n";
 1762:     return $js;
 1763: }
 1764: 
 1765: sub display_existing_roles {
 1766:     my ($r,$ccuname,$ccdomain,$inccourses,$context,$roledom,$crstype,
 1767:         $showcredits,$statuses) = @_;
 1768:     my $now=time;
 1769:     my $showall = 1;
 1770:     my ($showexpired,$showactive);
 1771:     if ((ref($statuses) eq 'ARRAY') && (@{$statuses} > 0)) {
 1772:         $showall = 0;
 1773:         if (grep(/^expired$/,@{$statuses})) {
 1774:             $showexpired = 1;
 1775:         }
 1776:         if (grep(/^active$/,@{$statuses})) {
 1777:             $showactive = 1;
 1778:         }
 1779:         if ($showexpired && $showactive) {
 1780:             $showall = 1;
 1781:         }
 1782:     }
 1783:     my %lt=&Apache::lonlocal::texthash(
 1784:                     'rer'  => "Existing Roles",
 1785:                     'rev'  => "Revoke",
 1786:                     'del'  => "Delete",
 1787:                     'ren'  => "Re-Enable",
 1788:                     'rol'  => "Role",
 1789:                     'ext'  => "Extent",
 1790:                     'crd'  => "Credits",
 1791:                     'sta'  => "Start",
 1792:                     'end'  => "End",
 1793:                                        );
 1794:     my (%rolesdump,%roletext,%sortrole,%roleclass,%rolepriv);
 1795:     if ($context eq 'course' || $context eq 'author') {
 1796:         my @roles = &Apache::lonuserutils::roles_by_context($context,1,$crstype);
 1797:         my %roleshash = 
 1798:             &Apache::lonnet::get_my_roles($ccuname,$ccdomain,'userroles',
 1799:                               ['active','previous','future'],\@roles,$roledom,1);
 1800:         foreach my $key (keys(%roleshash)) {
 1801:             my ($start,$end) = split(':',$roleshash{$key});
 1802:             next if ($start eq '-1' || $end eq '-1');
 1803:             my ($rnum,$rdom,$role,$sec) = split(':',$key);
 1804:             if ($context eq 'course') {
 1805:                 next unless (($rnum eq $env{'course.'.$env{'request.course.id'}.'.num'})
 1806:                              && ($rdom eq $env{'course.'.$env{'request.course.id'}.'.domain'}));
 1807:             } elsif ($context eq 'author') {
 1808:                 next unless (($rnum eq $env{'user.name'}) && ($rdom eq $env{'request.role.domain'}));
 1809:             }
 1810:             my ($newkey,$newvalue,$newrole);
 1811:             $newkey = '/'.$rdom.'/'.$rnum;
 1812:             if ($sec ne '') {
 1813:                 $newkey .= '/'.$sec;
 1814:             }
 1815:             $newvalue = $role;
 1816:             if ($role =~ /^cr/) {
 1817:                 $newrole = 'cr';
 1818:             } else {
 1819:                 $newrole = $role;
 1820:             }
 1821:             $newkey .= '_'.$newrole;
 1822:             if ($start ne '' && $end ne '') {
 1823:                 $newvalue .= '_'.$end.'_'.$start;
 1824:             } elsif ($end ne '') {
 1825:                 $newvalue .= '_'.$end;
 1826:             }
 1827:             $rolesdump{$newkey} = $newvalue;
 1828:         }
 1829:     } else {
 1830:         %rolesdump=&Apache::lonnet::dump('roles',$ccdomain,$ccuname);
 1831:     }
 1832:     # Build up table of user roles to allow revocation and re-enabling of roles.
 1833:     my ($tmp) = keys(%rolesdump);
 1834:     return if ($tmp =~ /^(con_lost|error)/i);
 1835:     foreach my $area (sort { my $a1=join('_',(split('_',$a))[1,0]);
 1836:                                 my $b1=join('_',(split('_',$b))[1,0]);
 1837:                                 return $a1 cmp $b1;
 1838:                             } keys(%rolesdump)) {
 1839:         next if ($area =~ /^rolesdef/);
 1840:         my $envkey=$area;
 1841:         my $role = $rolesdump{$area};
 1842:         my $thisrole=$area;
 1843:         $area =~ s/\_\w\w$//;
 1844:         my ($role_code,$role_end_time,$role_start_time) =
 1845:             split(/_/,$role);
 1846:         my $active=1;
 1847:         $active=0 if (($role_end_time) && ($now>$role_end_time));
 1848:         if ($active) {
 1849:             next unless($showall || $showactive);
 1850:         } else {
 1851:             next unless($showall || $showexpired); 
 1852:         }
 1853: # Is this a custom role? Get role owner and title.
 1854:         my ($croleudom,$croleuname,$croletitle)=
 1855:             ($role_code=~m{^cr/($match_domain)/($match_username)/(\w+)$});
 1856:         my $allowed=0;
 1857:         my $delallowed=0;
 1858:         my $sortkey=$role_code;
 1859:         my $class='Unknown';
 1860:         my $credits='';
 1861:         my $csec;
 1862:         if ($area =~ m{^/($match_domain)/($match_courseid)}) {
 1863:             $class='Course';
 1864:             my ($coursedom,$coursedir) = ($1,$2);
 1865:             my $cid = $1.'_'.$2;
 1866:             # $1.'_'.$2 is the course id (eg. 103_12345abcef103l3).
 1867:             next if ($envkey =~ m{^/$match_domain/$match_courseid/[A-Za-z0-9]+_gr$});
 1868:             my %coursedata=
 1869:                 &Apache::lonnet::coursedescription($cid);
 1870:             if ($coursedir =~ /^$match_community$/) {
 1871:                 $class='Community';
 1872:             }
 1873:             $sortkey.="\0$coursedom";
 1874:             my $carea;
 1875:             if (defined($coursedata{'description'})) {
 1876:                 $carea=$coursedata{'description'}.
 1877:                     '<br />'.&mt('Domain').': '.$coursedom.('&nbsp;'x8).
 1878:     &Apache::loncommon::syllabuswrapper(&mt('Syllabus'),$coursedir,$coursedom);
 1879:                 $sortkey.="\0".$coursedata{'description'};
 1880:             } else {
 1881:                 if ($class eq 'Community') {
 1882:                     $carea=&mt('Unavailable community').': '.$area;
 1883:                     $sortkey.="\0".&mt('Unavailable community').': '.$area;
 1884:                 } else {
 1885:                     $carea=&mt('Unavailable course').': '.$area;
 1886:                     $sortkey.="\0".&mt('Unavailable course').': '.$area;
 1887:                 }
 1888:             }
 1889:             $sortkey.="\0$coursedir";
 1890:             $inccourses->{$cid}=1;
 1891:             if (($showcredits) && ($class eq 'Course') && ($role_code eq 'st')) {
 1892:                 my $defaultcredits = $coursedata{'internal.defaultcredits'};
 1893:                 $credits =
 1894:                     &get_user_credits($ccuname,$ccdomain,$defaultcredits,
 1895:                                       $coursedom,$coursedir);
 1896:                 if ($credits eq '') {
 1897:                     $credits = $defaultcredits;
 1898:                 }
 1899:             }
 1900:             if ((&Apache::lonnet::allowed('c'.$role_code,$coursedom.'/'.$coursedir)) ||
 1901:                 (&Apache::lonnet::allowed('c'.$role_code,$ccdomain))) {
 1902:                 $allowed=1;
 1903:             }
 1904:             unless ($allowed) {
 1905:                 my $isowner = &Apache::lonuserutils::is_courseowner($cid,$coursedata{'internal.courseowner'});
 1906:                 if ($isowner) {
 1907:                     if (($role_code eq 'co') && ($class eq 'Community')) {
 1908:                         $allowed = 1;
 1909:                     } elsif (($role_code eq 'cc') && ($class eq 'Course')) {
 1910:                         $allowed = 1;
 1911:                     }
 1912:                 }
 1913:             } 
 1914:             if ((&Apache::lonnet::allowed('dro',$coursedom)) ||
 1915:                 (&Apache::lonnet::allowed('dro',$ccdomain))) {
 1916:                 $delallowed=1;
 1917:             }
 1918: # - custom role. Needs more info, too
 1919:             if ($croletitle) {
 1920:                 if (&Apache::lonnet::allowed('ccr',$coursedom.'/'.$coursedir)) {
 1921:                     $allowed=1;
 1922:                     $thisrole.='.'.$role_code;
 1923:                 }
 1924:             }
 1925:             if ($area=~m{^/($match_domain/$match_courseid/(\w+))}) {
 1926:                 $csec = $2;
 1927:                 $carea.='<br />'.&mt('Section: [_1]',$csec);
 1928:                 $sortkey.="\0$csec";
 1929:                 if (!$allowed) {
 1930:                     if ($env{'request.course.sec'} eq $csec) {
 1931:                         if (&Apache::lonnet::allowed('c'.$role_code,$1)) {
 1932:                             $allowed = 1;
 1933:                         }
 1934:                     }
 1935:                 }
 1936:             }
 1937:             $area=$carea;
 1938:         } else {
 1939:             $sortkey.="\0".$area;
 1940:             # Determine if current user is able to revoke privileges
 1941:             if ($area=~m{^/($match_domain)/}) {
 1942:                 if ((&Apache::lonnet::allowed('c'.$role_code,$1)) ||
 1943:                    (&Apache::lonnet::allowed('c'.$role_code,$ccdomain))) {
 1944:                    $allowed=1;
 1945:                 }
 1946:                 if (((&Apache::lonnet::allowed('dro',$1))  ||
 1947:                     (&Apache::lonnet::allowed('dro',$ccdomain))) &&
 1948:                     ($role_code ne 'dc')) {
 1949:                     $delallowed=1;
 1950:                 }
 1951:             } else {
 1952:                 if (&Apache::lonnet::allowed('c'.$role_code,'/')) {
 1953:                     $allowed=1;
 1954:                 }
 1955:             }
 1956:             if ($role_code eq 'ca' || $role_code eq 'au' || $role_code eq 'aa') {
 1957:                 $class='Authoring Space';
 1958:             } elsif ($role_code eq 'su') {
 1959:                 $class='System';
 1960:             } else {
 1961:                 $class='Domain';
 1962:             }
 1963:         }
 1964:         if (($role_code eq 'ca') || ($role_code eq 'aa')) {
 1965:             $area=~m{/($match_domain)/($match_username)};
 1966:             if (&Apache::lonuserutils::authorpriv($2,$1)) {
 1967:                 $allowed=1;
 1968:             } else {
 1969:                 $allowed=0;
 1970:             }
 1971:         }
 1972:         my $row = '';
 1973:         if ($showall) {
 1974:             $row.= '<td>';
 1975:             if (($active) && ($allowed)) {
 1976:                 $row.= '<input type="checkbox" name="rev:'.$thisrole.'" />';
 1977:             } else {
 1978:                 if ($active) {
 1979:                     $row.='&nbsp;';
 1980:                 } else {
 1981:                     $row.=&mt('expired or revoked');
 1982:                 }
 1983:             }
 1984:             $row.='</td><td>';
 1985:             if ($allowed && !$active) {
 1986:                 $row.= '<input type="checkbox" name="ren:'.$thisrole.'" />';
 1987:             } else {
 1988:                 $row.='&nbsp;';
 1989:             }
 1990:             $row.='</td><td>';
 1991:             if ($delallowed) {
 1992:                 $row.= '<input type="checkbox" name="del:'.$thisrole.'" />';
 1993:             } else {
 1994:                 $row.='&nbsp;';
 1995:             }
 1996:             $row.= '</td>'; 
 1997:         }
 1998:         my $plaintext='';
 1999:         if (!$croletitle) {
 2000:             $plaintext=&Apache::lonnet::plaintext($role_code,$class);
 2001:             if (($showcredits) && ($credits ne '')) {
 2002:                 $plaintext .= '<br/ ><span class="LC_nobreak">'.
 2003:                               '<span class="LC_fontsize_small">'.
 2004:                               &mt('Credits: [_1]',$credits).
 2005:                               '</span></span>';
 2006:             }
 2007:         } else {
 2008:             $plaintext=
 2009:                 &mt('Custom role [_1][_2]defined by [_3]',
 2010:                         '"'.$croletitle.'"',
 2011:                         '<br />',
 2012:                         $croleuname.':'.$croleudom);
 2013:         }
 2014:         $row.= '<td>'.$plaintext.'</td>'.
 2015:                '<td>'.$area.'</td>'.
 2016:                '<td>'.($role_start_time?&Apache::lonlocal::locallocaltime($role_start_time)
 2017:                                             : '&nbsp;' ).'</td>'.
 2018:                '<td>'.($role_end_time  ?&Apache::lonlocal::locallocaltime($role_end_time)
 2019:                                             : '&nbsp;' ).'</td>';
 2020:         $sortrole{$sortkey}=$envkey;
 2021:         $roletext{$envkey}=$row;
 2022:         $roleclass{$envkey}=$class;
 2023:         if ($allowed) {
 2024:             $rolepriv{$envkey}='edit';
 2025:         } else {
 2026:             if ($context eq 'domain') {
 2027:                 if ((&Apache::lonnet::allowed('vur',$ccdomain)) &&
 2028:                     ($envkey=~m{^/$ccdomain/})) {
 2029:                     $rolepriv{$envkey}='view';
 2030:                 }
 2031:             } elsif ($context eq 'course') {
 2032:                 if ((&Apache::lonnet::allowed('vcl',$env{'request.course.id'})) ||
 2033:                     ($env{'request.course.sec'} && ($env{'request.course.sec'} eq $csec) &&
 2034:                      &Apache::lonnet::allowed('vcl',$env{'request.course.id'}.'/'.$env{'request.course.sec'}))) {
 2035:                     $rolepriv{$envkey}='view';
 2036:                 }
 2037:             }
 2038:         }
 2039:     } # end of foreach        (table building loop)
 2040: 
 2041:     my $rolesdisplay = 0;
 2042:     my %output = ();
 2043:     foreach my $type ('Authoring Space','Course','Community','Domain','System','Unknown') {
 2044:         $output{$type} = '';
 2045:         foreach my $which (sort {uc($a) cmp uc($b)} (keys(%sortrole))) {
 2046:             if ( ($roleclass{$sortrole{$which}} =~ /^\Q$type\E/ ) && ($rolepriv{$sortrole{$which}}) ) {
 2047:                  $output{$type}.=
 2048:                       &Apache::loncommon::start_data_table_row().
 2049:                       $roletext{$sortrole{$which}}.
 2050:                       &Apache::loncommon::end_data_table_row();
 2051:             }
 2052:         }
 2053:         unless($output{$type} eq '') {
 2054:             $output{$type} = '<tr class="LC_info_row">'.
 2055:                       "<td align='center' colspan='7'>".&mt($type)."</td></tr>".
 2056:                       $output{$type};
 2057:             $rolesdisplay = 1;
 2058:         }
 2059:     }
 2060:     if ($rolesdisplay == 1) {
 2061:         my $contextrole='';
 2062:         if ($env{'request.course.id'}) {
 2063:             if (&Apache::loncommon::course_type() eq 'Community') {
 2064:                 $contextrole = &mt('Existing Roles in this Community');
 2065:             } else {
 2066:                 $contextrole = &mt('Existing Roles in this Course');
 2067:             }
 2068:         } elsif ($env{'request.role'} =~ /^au\./) {
 2069:             $contextrole = &mt('Existing Co-Author Roles in your Authoring Space');
 2070:         } else {
 2071:             if ($showall) {
 2072:                 $contextrole = &mt('Existing Roles in this Domain');
 2073:             } elsif ($showactive) {
 2074:                 $contextrole = &mt('Unexpired Roles in this Domain');
 2075:             } elsif ($showexpired) {
 2076:                 $contextrole = &mt('Expired or Revoked Roles in this Domain');
 2077:             }
 2078:         }
 2079:         $r->print('<div class="LC_left_float">'.
 2080: '<fieldset><legend>'.$contextrole.'</legend>'.
 2081: &Apache::loncommon::start_data_table("LC_createuser").
 2082: &Apache::loncommon::start_data_table_header_row());
 2083:         if ($showall) {
 2084:             $r->print(
 2085: '<th>'.$lt{'rev'}.'</th><th>'.$lt{'ren'}.'</th><th>'.$lt{'del'}.'</th>'
 2086:             );
 2087:         } elsif ($showexpired) {
 2088:             $r->print('<th>'.$lt{'rev'}.'</th>');
 2089:         }
 2090:         $r->print(
 2091: '<th>'.$lt{'rol'}.'</th><th>'.$lt{'ext'}.'</th>'.
 2092: '<th>'.$lt{'sta'}.'</th><th>'.$lt{'end'}.'</th>'.
 2093: &Apache::loncommon::end_data_table_header_row());
 2094:         foreach my $type ('Authoring Space','Course','Community','Domain','System','Unknown') {
 2095:             if ($output{$type}) {
 2096:                 $r->print($output{$type}."\n");
 2097:             }
 2098:         }
 2099:         $r->print(&Apache::loncommon::end_data_table().
 2100:                   '</fieldset></div>');
 2101:     }
 2102:     return;
 2103: }
 2104: 
 2105: sub new_coauthor_roles {
 2106:     my ($r,$ccuname,$ccdomain) = @_;
 2107:     my $addrolesdisplay = 0;
 2108:     #
 2109:     # Co-Author
 2110:     #
 2111:     if (&Apache::lonuserutils::authorpriv($env{'user.name'},
 2112:                                           $env{'request.role.domain'}) &&
 2113:         ($env{'user.name'} ne $ccuname || $env{'user.domain'} ne $ccdomain)) {
 2114:         # No sense in assigning co-author role to yourself
 2115:         $addrolesdisplay = 1;
 2116:         my $cuname=$env{'user.name'};
 2117:         my $cudom=$env{'request.role.domain'};
 2118:         my %lt=&Apache::lonlocal::texthash(
 2119:                     'cs'   => "Authoring Space",
 2120:                     'act'  => "Activate",
 2121:                     'rol'  => "Role",
 2122:                     'ext'  => "Extent",
 2123:                     'sta'  => "Start",
 2124:                     'end'  => "End",
 2125:                     'cau'  => "Co-Author",
 2126:                     'caa'  => "Assistant Co-Author",
 2127:                     'ssd'  => "Set Start Date",
 2128:                     'sed'  => "Set End Date"
 2129:                                        );
 2130:         $r->print('<h4>'.$lt{'cs'}.'</h4>'."\n".
 2131:                   &Apache::loncommon::start_data_table()."\n".
 2132:                   &Apache::loncommon::start_data_table_header_row()."\n".
 2133:                   '<th>'.$lt{'act'}.'</th><th>'.$lt{'rol'}.'</th>'.
 2134:                   '<th>'.$lt{'ext'}.'</th><th>'.$lt{'sta'}.'</th>'.
 2135:                   '<th>'.$lt{'end'}.'</th>'."\n".
 2136:                   &Apache::loncommon::end_data_table_header_row()."\n".
 2137:                   &Apache::loncommon::start_data_table_row().'
 2138:            <td>
 2139:             <input type="checkbox" name="act_'.$cudom.'_'.$cuname.'_ca" />
 2140:            </td>
 2141:            <td>'.$lt{'cau'}.'</td>
 2142:            <td>'.$cudom.'_'.$cuname.'</td>
 2143:            <td><input type="hidden" name="start_'.$cudom.'_'.$cuname.'_ca" value="" />
 2144:              <a href=
 2145: "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>
 2146: <td><input type="hidden" name="end_'.$cudom.'_'.$cuname.'_ca" value="" />
 2147: <a href=
 2148: "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".
 2149:               &Apache::loncommon::end_data_table_row()."\n".
 2150:               &Apache::loncommon::start_data_table_row()."\n".
 2151: '<td><input type="checkbox" name="act_'.$cudom.'_'.$cuname.'_aa" /></td>
 2152: <td>'.$lt{'caa'}.'</td>
 2153: <td>'.$cudom.'_'.$cuname.'</td>
 2154: <td><input type="hidden" name="start_'.$cudom.'_'.$cuname.'_aa" value="" />
 2155: <a href=
 2156: "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>
 2157: <td><input type="hidden" name="end_'.$cudom.'_'.$cuname.'_aa" value="" />
 2158: <a href=
 2159: "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".
 2160:              &Apache::loncommon::end_data_table_row()."\n".
 2161:              &Apache::loncommon::end_data_table());
 2162:     } elsif ($env{'request.role'} =~ /^au\./) {
 2163:         if (!(&Apache::lonuserutils::authorpriv($env{'user.name'},
 2164:                                                 $env{'request.role.domain'}))) {
 2165:             $r->print('<span class="LC_error">'.
 2166:                       &mt('You do not have privileges to assign co-author roles.').
 2167:                       '</span>');
 2168:         } elsif (($env{'user.name'} eq $ccuname) &&
 2169:              ($env{'user.domain'} eq $ccdomain)) {
 2170:             $r->print(&mt('Assigning yourself a co-author or assistant co-author role in your own author area in Authoring Space is not permitted'));
 2171:         }
 2172:     }
 2173:     return $addrolesdisplay;;
 2174: }
 2175: 
 2176: sub new_domain_roles {
 2177:     my ($r,$ccdomain) = @_;
 2178:     my $addrolesdisplay = 0;
 2179:     #
 2180:     # Domain level
 2181:     #
 2182:     my $num_domain_level = 0;
 2183:     my $domaintext =
 2184:     '<h4>'.&mt('Domain Level').'</h4>'.
 2185:     &Apache::loncommon::start_data_table().
 2186:     &Apache::loncommon::start_data_table_header_row().
 2187:     '<th>'.&mt('Activate').'</th><th>'.&mt('Role').'</th><th>'.
 2188:     &mt('Extent').'</th>'.
 2189:     '<th>'.&mt('Start').'</th><th>'.&mt('End').'</th>'.
 2190:     &Apache::loncommon::end_data_table_header_row();
 2191:     my @allroles = &Apache::lonuserutils::roles_by_context('domain');
 2192:     foreach my $thisdomain (sort(&Apache::lonnet::all_domains())) {
 2193:         foreach my $role (@allroles) {
 2194:             next if ($role eq 'ad');
 2195:             next if (($role eq 'au') && ($ccdomain ne $thisdomain));
 2196:             if (&Apache::lonnet::allowed('c'.$role,$thisdomain)) {
 2197:                my $plrole=&Apache::lonnet::plaintext($role);
 2198:                my %lt=&Apache::lonlocal::texthash(
 2199:                     'ssd'  => "Set Start Date",
 2200:                     'sed'  => "Set End Date"
 2201:                                        );
 2202:                $num_domain_level ++;
 2203:                $domaintext .=
 2204: &Apache::loncommon::start_data_table_row().
 2205: '<td><input type="checkbox" name="act_'.$thisdomain.'_'.$role.'" /></td>
 2206: <td>'.$plrole.'</td>
 2207: <td>'.$thisdomain.'</td>
 2208: <td><input type="hidden" name="start_'.$thisdomain.'_'.$role.'" value="" />
 2209: <a href=
 2210: "javascript:pjump('."'date_start','Start Date $plrole',document.cu.start_$thisdomain\_$role.value,'start_$thisdomain\_$role','cu.pres','dateset'".')">'.$lt{'ssd'}.'</a></td>
 2211: <td><input type="hidden" name="end_'.$thisdomain.'_'.$role.'" value="" />
 2212: <a href=
 2213: "javascript:pjump('."'date_end','End Date $plrole',document.cu.end_$thisdomain\_$role.value,'end_$thisdomain\_$role','cu.pres','dateset'".')">'.$lt{'sed'}.'</a></td>'.
 2214: &Apache::loncommon::end_data_table_row();
 2215:             }
 2216:         }
 2217:     }
 2218:     $domaintext.= &Apache::loncommon::end_data_table();
 2219:     if ($num_domain_level > 0) {
 2220:         $r->print($domaintext);
 2221:         $addrolesdisplay = 1;
 2222:     }
 2223:     return $addrolesdisplay;
 2224: }
 2225: 
 2226: sub user_authentication {
 2227:     my ($ccuname,$ccdomain,$formname) = @_;
 2228:     my $currentauth=&Apache::lonnet::queryauthenticate($ccuname,$ccdomain);
 2229:     my $outcome;
 2230:     my %lt=&Apache::lonlocal::texthash(
 2231:                    'err'   => "ERROR",
 2232:                    'uuas'  => "This user has an unrecognized authentication scheme",
 2233:                    'adcs'  => "Please alert a domain coordinator of this situation",
 2234:                    'sldb'  => "Please specify login data below",
 2235:                    'ld'    => "Login Data"
 2236:     );
 2237:     # Check for a bad authentication type
 2238:     if ($currentauth !~ /^(krb4|krb5|unix|internal|localauth):/) {
 2239:         # bad authentication scheme
 2240:         if (&Apache::lonnet::allowed('mau',$ccdomain)) {
 2241:             &initialize_authen_forms($ccdomain,$formname);
 2242: 
 2243:             my $choices = &Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc);
 2244:             $outcome = <<ENDBADAUTH;
 2245: <script type="text/javascript" language="Javascript">
 2246: // <![CDATA[
 2247: $loginscript
 2248: // ]]>
 2249: </script>
 2250: <span class="LC_error">$lt{'err'}:
 2251: $lt{'uuas'} ($currentauth). $lt{'sldb'}.</span>
 2252: <h3>$lt{'ld'}</h3>
 2253: $choices
 2254: ENDBADAUTH
 2255:         } else {
 2256:             # This user is not allowed to modify the user's
 2257:             # authentication scheme, so just notify them of the problem
 2258:             $outcome = <<ENDBADAUTH;
 2259: <span class="LC_error"> $lt{'err'}: 
 2260: $lt{'uuas'} ($currentauth). $lt{'adcs'}.
 2261: </span>
 2262: ENDBADAUTH
 2263:         }
 2264:     } else { # Authentication type is valid
 2265:         
 2266:         &initialize_authen_forms($ccdomain,$formname,$currentauth,'modifyuser');
 2267:         my ($authformcurrent,$can_modify,@authform_others) =
 2268:             &modify_login_block($ccdomain,$currentauth);
 2269:         if (&Apache::lonnet::allowed('mau',$ccdomain)) {
 2270:             # Current user has login modification privileges
 2271:             $outcome =
 2272:                        '<script type="text/javascript" language="Javascript">'."\n".
 2273:                        '// <![CDATA['."\n".
 2274:                        $loginscript."\n".
 2275:                        '// ]]>'."\n".
 2276:                        '</script>'."\n".
 2277:                        '<h3>'.$lt{'ld'}.'</h3>'.
 2278:                        &Apache::loncommon::start_data_table().
 2279:                        &Apache::loncommon::start_data_table_row().
 2280:                        '<td>'.$authformnop;
 2281:             if (($can_modify) && (&Apache::lonnet::allowed('mau',$ccdomain))) {
 2282:                 $outcome .= '</td>'."\n".
 2283:                             &Apache::loncommon::end_data_table_row().
 2284:                             &Apache::loncommon::start_data_table_row().
 2285:                             '<td>'.$authformcurrent.'</td>'.
 2286:                             &Apache::loncommon::end_data_table_row()."\n";
 2287:             } else {
 2288:                 $outcome .= '&nbsp;('.$authformcurrent.')</td>'.
 2289:                             &Apache::loncommon::end_data_table_row()."\n";
 2290:             }
 2291:             if (&Apache::lonnet::allowed('mau',$ccdomain)) {
 2292:                 foreach my $item (@authform_others) { 
 2293:                     $outcome .= &Apache::loncommon::start_data_table_row().
 2294:                                 '<td>'.$item.'</td>'.
 2295:                                 &Apache::loncommon::end_data_table_row()."\n";
 2296:                 }
 2297:             }
 2298:             $outcome .= &Apache::loncommon::end_data_table();
 2299:         } else {
 2300:             if (&Apache::lonnet::allowed('udp',$ccdomain)) {
 2301:                 # Current user has rights to view domain preferences for user's domain
 2302:                 my $result;
 2303:                 if ($currentauth =~ /^krb(4|5):([^:]*)$/) {
 2304:                     my ($krbver,$krbrealm) = ($1,$2);
 2305:                     if ($krbrealm eq '') {
 2306:                         $result = &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
 2307:                     } else {
 2308:                         $result = &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
 2309:                                       $krbver,$krbrealm);
 2310:                     }
 2311:                 } elsif ($currentauth =~ /^internal:/) {
 2312:                     $result = &mt('Currently internally authenticated.');
 2313:                 } elsif ($currentauth =~ /^localauth:/) {
 2314:                     $result = &mt('Currently using local (institutional) authentication.');
 2315:                 } elsif ($currentauth =~ /^unix:/) {
 2316:                     $result = &mt('Currently Filesystem Authenticated.');
 2317:                 }
 2318:                 $outcome = '<h3>'.$lt{'ld'}.'</h3>'.
 2319:                            &Apache::loncommon::start_data_table().
 2320:                            &Apache::loncommon::start_data_table_row().
 2321:                            '<td>'.$result.'</td>'.
 2322:                            &Apache::loncommon::end_data_table_row()."\n".
 2323:                            &Apache::loncommon::end_data_table();
 2324:             } elsif (&Apache::lonnet::allowed('mau',$env{'request.role.domain'})) {
 2325:                 my %lt=&Apache::lonlocal::texthash(
 2326:                            'ccld'  => "Change Current Login Data",
 2327:                            'yodo'  => "You do not have privileges to modify the authentication configuration for this user.",
 2328:                            'ifch'  => "If a change is required, contact a domain coordinator for the domain",
 2329:                 );
 2330:                 $outcome .= <<ENDNOPRIV;
 2331: <h3>$lt{'ccld'}</h3>
 2332: $lt{'yodo'} $lt{'ifch'}: $ccdomain
 2333: <input type="hidden" name="login" value="nochange" />
 2334: ENDNOPRIV
 2335:             }
 2336:         }
 2337:     }  ## End of "check for bad authentication type" logic
 2338:     return $outcome;
 2339: }
 2340: 
 2341: sub modify_login_block {
 2342:     my ($dom,$currentauth) = @_;
 2343:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 2344:     my ($authnum,%can_assign) =
 2345:         &Apache::loncommon::get_assignable_auth($dom);
 2346:     my ($authformcurrent,@authform_others,$show_override_msg);
 2347:     if ($currentauth=~/^krb(4|5):/) {
 2348:         $authformcurrent=$authformkrb;
 2349:         if ($can_assign{'int'}) {
 2350:             push(@authform_others,$authformint);
 2351:         }
 2352:         if ($can_assign{'loc'}) {
 2353:             push(@authform_others,$authformloc);
 2354:         }
 2355:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2356:             $show_override_msg = 1;
 2357:         }
 2358:     } elsif ($currentauth=~/^internal:/) {
 2359:         $authformcurrent=$authformint;
 2360:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2361:             push(@authform_others,$authformkrb);
 2362:         }
 2363:         if ($can_assign{'loc'}) {
 2364:             push(@authform_others,$authformloc);
 2365:         }
 2366:         if ($can_assign{'int'}) {
 2367:             $show_override_msg = 1;
 2368:         }
 2369:     } elsif ($currentauth=~/^unix:/) {
 2370:         $authformcurrent=$authformfsys;
 2371:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2372:             push(@authform_others,$authformkrb);
 2373:         }
 2374:         if ($can_assign{'int'}) {
 2375:             push(@authform_others,$authformint);
 2376:         }
 2377:         if ($can_assign{'loc'}) {
 2378:             push(@authform_others,$authformloc);
 2379:         }
 2380:         if ($can_assign{'fsys'}) {
 2381:             $show_override_msg = 1;
 2382:         }
 2383:     } elsif ($currentauth=~/^localauth:/) {
 2384:         $authformcurrent=$authformloc;
 2385:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2386:             push(@authform_others,$authformkrb);
 2387:         }
 2388:         if ($can_assign{'int'}) {
 2389:             push(@authform_others,$authformint);
 2390:         }
 2391:         if ($can_assign{'loc'}) {
 2392:             $show_override_msg = 1;
 2393:         }
 2394:     }
 2395:     if ($show_override_msg) {
 2396:         $authformcurrent = '<table><tr><td colspan="3">'.$authformcurrent.
 2397:                            '</td></tr>'."\n".
 2398:                            '<tr><td>&nbsp;&nbsp;&nbsp;</td>'.
 2399:                            '<td><b>'.&mt('Currently in use').'</b></td>'.
 2400:                            '<td align="right"><span class="LC_cusr_emph">'.
 2401:                             &mt('will override current values').
 2402:                             '</span></td></tr></table>';
 2403:     }
 2404:     return ($authformcurrent,$show_override_msg,@authform_others); 
 2405: }
 2406: 
 2407: sub personal_data_display {
 2408:     my ($ccuname,$ccdomain,$newuser,$context,$inst_results,$rolesarray,
 2409:         $now,$captchaform,$emailusername,$usertype) = @_;
 2410:     my ($output,%userenv,%canmodify,%canmodify_status);
 2411:     my @userinfo = ('firstname','middlename','lastname','generation',
 2412:                     'permanentemail','id');
 2413:     my $rowcount = 0;
 2414:     my $editable = 0;
 2415:     my %textboxsize = (
 2416:                        firstname      => '15',
 2417:                        middlename     => '15',
 2418:                        lastname       => '15',
 2419:                        generation     => '5',
 2420:                        permanentemail => '25',
 2421:                        id             => '15',
 2422:                       );
 2423: 
 2424:     my %lt=&Apache::lonlocal::texthash(
 2425:                 'pd'             => "Personal Data",
 2426:                 'firstname'      => "First Name",
 2427:                 'middlename'     => "Middle Name",
 2428:                 'lastname'       => "Last Name",
 2429:                 'generation'     => "Generation",
 2430:                 'permanentemail' => "Permanent e-mail address",
 2431:                 'id'             => "Student/Employee ID",
 2432:                 'lg'             => "Login Data",
 2433:                 'inststatus'     => "Affiliation",
 2434:                 'email'          => 'E-mail address',
 2435:                 'valid'          => 'Validation',
 2436:     );
 2437: 
 2438:     %canmodify_status =
 2439:         &Apache::lonuserutils::can_modify_userinfo($context,$ccdomain,
 2440:                                                    ['inststatus'],$rolesarray);
 2441:     if (!$newuser) {
 2442:         # Get the users information
 2443:         %userenv = &Apache::lonnet::get('environment',
 2444:                    ['firstname','middlename','lastname','generation',
 2445:                     'permanentemail','id','inststatus'],$ccdomain,$ccuname);
 2446:         %canmodify =
 2447:             &Apache::lonuserutils::can_modify_userinfo($context,$ccdomain,
 2448:                                                        \@userinfo,$rolesarray);
 2449:     } elsif ($context eq 'selfcreate') {
 2450:         if ($newuser eq 'email') {
 2451:             if (ref($emailusername) eq 'HASH') {
 2452:                 if (ref($emailusername->{$usertype}) eq 'HASH') {
 2453:                     my ($infofields,$infotitles) = &Apache::loncommon::emailusername_info();
 2454:                     @userinfo = ();          
 2455:                     if ((ref($infofields) eq 'ARRAY') && (ref($infotitles) eq 'HASH')) {
 2456:                         foreach my $field (@{$infofields}) { 
 2457:                             if ($emailusername->{$usertype}->{$field}) {
 2458:                                 push(@userinfo,$field);
 2459:                                 $canmodify{$field} = 1;
 2460:                                 unless ($textboxsize{$field}) {
 2461:                                     $textboxsize{$field} = 25;
 2462:                                 }
 2463:                                 unless ($lt{$field}) {
 2464:                                     $lt{$field} = $infotitles->{$field};
 2465:                                 }
 2466:                                 if ($emailusername->{$usertype}->{$field} eq 'required') {
 2467:                                     $lt{$field} .= '<b>*</b>';
 2468:                                 }
 2469:                             }
 2470:                         }
 2471:                     }
 2472:                 }
 2473:             }
 2474:         } else {
 2475:             %canmodify = &selfcreate_canmodify($context,$ccdomain,\@userinfo,
 2476:                                                $inst_results,$rolesarray);
 2477:         }
 2478:     }
 2479: 
 2480:     my $genhelp=&Apache::loncommon::help_open_topic('Generation');
 2481:     $output = '<h3>'.$lt{'pd'}.'</h3>'.
 2482:               &Apache::lonhtmlcommon::start_pick_box();
 2483:     if (($context eq 'selfcreate') && ($newuser eq 'email')) {
 2484:         $output .= &Apache::lonhtmlcommon::row_title($lt{'email'}.'<b>*</b>',undef,
 2485:                                                      'LC_oddrow_value')."\n".
 2486:                    '<input type="text" name="uname" size="25" value="" autocomplete="off" />';
 2487:         $rowcount ++;
 2488:         $output .= &Apache::lonhtmlcommon::row_closure(1);
 2489:         my $upassone = '<input type="password" name="upass'.$now.'" size="20" autocomplete="off" />';
 2490:         my $upasstwo = '<input type="password" name="upasscheck'.$now.'" size="20" autocomplete="off" />';
 2491:         $output .= &Apache::lonhtmlcommon::row_title(&mt('Password').'<b>*</b>',
 2492:                                                     'LC_pick_box_title',
 2493:                                                     'LC_oddrow_value')."\n".
 2494:                    $upassone."\n".
 2495:                    &Apache::lonhtmlcommon::row_closure(1)."\n".
 2496:                    &Apache::lonhtmlcommon::row_title(&mt('Confirm password').'<b>*</b>',
 2497:                                                      'LC_pick_box_title',
 2498:                                                      'LC_oddrow_value')."\n".
 2499:                    $upasstwo.
 2500:                    &Apache::lonhtmlcommon::row_closure()."\n";
 2501:     }
 2502:     foreach my $item (@userinfo) {
 2503:         my $rowtitle = $lt{$item};
 2504:         my $hiderow = 0;
 2505:         if ($item eq 'generation') {
 2506:             $rowtitle = $genhelp.$rowtitle;
 2507:         }
 2508:         my $row = &Apache::lonhtmlcommon::row_title($rowtitle,undef,'LC_oddrow_value')."\n";
 2509:         if ($newuser) {
 2510:             if (ref($inst_results) eq 'HASH') {
 2511:                 if ($inst_results->{$item} ne '') {
 2512:                     $row .= '<input type="hidden" name="c'.$item.'" value="'.$inst_results->{$item}.'" />'.$inst_results->{$item};
 2513:                 } else {
 2514:                     if ($context eq 'selfcreate') {
 2515:                         if ($canmodify{$item}) {
 2516:                             $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="" autocomplete="off" />';
 2517:                             $editable ++;
 2518:                         } else {
 2519:                             $hiderow = 1;
 2520:                         }
 2521:                     } else {
 2522:                         $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="" />';
 2523:                     }
 2524:                 }
 2525:             } else {
 2526:                 if ($context eq 'selfcreate') {
 2527:                     if ($canmodify{$item}) {
 2528:                         if ($newuser eq 'email') {
 2529:                             $row .= '<input type="text" name="'.$item.'" size="'.$textboxsize{$item}.'" value="" autocomplete="off" />';
 2530:                         } else {
 2531:                             $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="" autocomplete="off" />';
 2532:                         }
 2533:                         $editable ++;
 2534:                     } else {
 2535:                         $hiderow = 1;
 2536:                     }
 2537:                 } else {
 2538:                     $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="" />';
 2539:                 }
 2540:             }
 2541:         } else {
 2542:             if ($canmodify{$item}) {
 2543:                 $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="'.$userenv{$item}.'" />';
 2544:                 if (($item eq 'id') && (!$newuser)) {
 2545:                     $row .= '<br />'.&Apache::lonuserutils::forceid_change($context);
 2546:                 }
 2547:             } else {
 2548:                 $row .= $userenv{$item};
 2549:             }
 2550:         }
 2551:         $row .= &Apache::lonhtmlcommon::row_closure(1);
 2552:         if (!$hiderow) {
 2553:             $output .= $row;
 2554:             $rowcount ++;
 2555:         }
 2556:     }
 2557:     if (($canmodify_status{'inststatus'}) || ($context ne 'selfcreate')) {
 2558:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($ccdomain);
 2559:         if (ref($types) eq 'ARRAY') {
 2560:             if (@{$types} > 0) {
 2561:                 my ($hiderow,$shown);
 2562:                 if ($canmodify_status{'inststatus'}) {
 2563:                     $shown = &pick_inst_statuses($userenv{'inststatus'},$usertypes,$types);
 2564:                 } else {
 2565:                     if ($userenv{'inststatus'} eq '') {
 2566:                         $hiderow = 1;
 2567:                     } else {
 2568:                         my @showitems;
 2569:                         foreach my $item ( map { &unescape($_); } split(':',$userenv{'inststatus'})) {
 2570:                             if (exists($usertypes->{$item})) {
 2571:                                 push(@showitems,$usertypes->{$item});
 2572:                             } else {
 2573:                                 push(@showitems,$item);
 2574:                             }
 2575:                         }
 2576:                         if (@showitems) {
 2577:                             $shown = join(', ',@showitems);
 2578:                         } else {
 2579:                             $hiderow = 1;
 2580:                         }
 2581:                     }
 2582:                 }
 2583:                 if (!$hiderow) {
 2584:                     my $row = &Apache::lonhtmlcommon::row_title(&mt('Affiliations'),undef,'LC_oddrow_value')."\n".
 2585:                               $shown.&Apache::lonhtmlcommon::row_closure(1); 
 2586:                     if ($context eq 'selfcreate') {
 2587:                         $rowcount ++;
 2588:                     }
 2589:                     $output .= $row;
 2590:                 }
 2591:             }
 2592:         }
 2593:     }
 2594:     if (($context eq 'selfcreate') && ($newuser eq 'email')) {
 2595:         if ($captchaform) {
 2596:             $output .= &Apache::lonhtmlcommon::row_title($lt{'valid'}.'*',
 2597:                                                          'LC_pick_box_title')."\n".
 2598:                        $captchaform."\n".'<br /><br />'.
 2599:                        &Apache::lonhtmlcommon::row_closure(1); 
 2600:             $rowcount ++;
 2601:         }
 2602:         my $submit_text = &mt('Create account');
 2603:         $output .= &Apache::lonhtmlcommon::row_title()."\n".
 2604:                    '<br /><input type="submit" name="createaccount" value="'.
 2605:                    $submit_text.'" />'.
 2606:                    '<input type="hidden" name="type" value="'.$usertype.'" />'.
 2607:                    &Apache::lonhtmlcommon::row_closure(1);
 2608:     }
 2609:     $output .= &Apache::lonhtmlcommon::end_pick_box();
 2610:     if (wantarray) {
 2611:         if ($context eq 'selfcreate') {
 2612:             return($output,$rowcount,$editable);
 2613:         } else {
 2614:             return $output;
 2615:         }
 2616:     } else {
 2617:         return $output;
 2618:     }
 2619: }
 2620: 
 2621: sub pick_inst_statuses {
 2622:     my ($curr,$usertypes,$types) = @_;
 2623:     my ($output,$rem,@currtypes);
 2624:     if ($curr ne '') {
 2625:         @currtypes = map { &unescape($_); } split(/:/,$curr);
 2626:     }
 2627:     my $numinrow = 2;
 2628:     if (ref($types) eq 'ARRAY') {
 2629:         $output = '<table>';
 2630:         my $lastcolspan; 
 2631:         for (my $i=0; $i<@{$types}; $i++) {
 2632:             if (defined($usertypes->{$types->[$i]})) {
 2633:                 my $rem = $i%($numinrow);
 2634:                 if ($rem == 0) {
 2635:                     if ($i<@{$types}-1) {
 2636:                         if ($i > 0) { 
 2637:                             $output .= '</tr>';
 2638:                         }
 2639:                         $output .= '<tr>';
 2640:                     }
 2641:                 } elsif ($i==@{$types}-1) {
 2642:                     my $colsleft = $numinrow - $rem;
 2643:                     if ($colsleft > 1) {
 2644:                         $lastcolspan = ' colspan="'.$colsleft.'"';
 2645:                     }
 2646:                 }
 2647:                 my $check = ' ';
 2648:                 if (grep(/^\Q$types->[$i]\E$/,@currtypes)) {
 2649:                     $check = ' checked="checked" ';
 2650:                 }
 2651:                 $output .= '<td class="LC_left_item"'.$lastcolspan.'>'.
 2652:                            '<span class="LC_nobreak"><label>'.
 2653:                            '<input type="checkbox" name="inststatus" '.
 2654:                            'value="'.$types->[$i].'"'.$check.'/>'.
 2655:                            $usertypes->{$types->[$i]}.'</label></span></td>';
 2656:             }
 2657:         }
 2658:         $output .= '</tr></table>';
 2659:     }
 2660:     return $output;
 2661: }
 2662: 
 2663: sub selfcreate_canmodify {
 2664:     my ($context,$dom,$userinfo,$inst_results,$rolesarray) = @_;
 2665:     if (ref($inst_results) eq 'HASH') {
 2666:         my @inststatuses = &get_inststatuses($inst_results);
 2667:         if (@inststatuses == 0) {
 2668:             @inststatuses = ('default');
 2669:         }
 2670:         $rolesarray = \@inststatuses;
 2671:     }
 2672:     my %canmodify =
 2673:         &Apache::lonuserutils::can_modify_userinfo($context,$dom,$userinfo,
 2674:                                                    $rolesarray);
 2675:     return %canmodify;
 2676: }
 2677: 
 2678: sub get_inststatuses {
 2679:     my ($insthashref) = @_;
 2680:     my @inststatuses = ();
 2681:     if (ref($insthashref) eq 'HASH') {
 2682:         if (ref($insthashref->{'inststatus'}) eq 'ARRAY') {
 2683:             @inststatuses = @{$insthashref->{'inststatus'}};
 2684:         }
 2685:     }
 2686:     return @inststatuses;
 2687: }
 2688: 
 2689: # ================================================================= Phase Three
 2690: sub update_user_data {
 2691:     my ($r,$context,$crstype,$brcrum,$showcredits) = @_; 
 2692:     my $uhome=&Apache::lonnet::homeserver($env{'form.ccuname'},
 2693:                                           $env{'form.ccdomain'});
 2694:     # Error messages
 2695:     my $error     = '<span class="LC_error">'.&mt('Error').': ';
 2696:     my $end       = '</span><br /><br />';
 2697:     my $rtnlink   = '<a href="javascript:backPage(document.userupdate,'.
 2698:                     "'$env{'form.prevphase'}','modify')".'" />'.
 2699:                     &mt('Return to previous page').'</a>'.
 2700:                     &Apache::loncommon::end_page();
 2701:     my $now = time;
 2702:     my $title;
 2703:     if (exists($env{'form.makeuser'})) {
 2704: 	$title='Set Privileges for New User';
 2705:     } else {
 2706:         $title='Modify User Privileges';
 2707:     }
 2708:     my $newuser = 0;
 2709:     my ($jsback,$elements) = &crumb_utilities();
 2710:     my $jscript = '<script type="text/javascript">'."\n".
 2711:                   '// <![CDATA['."\n".
 2712:                   $jsback."\n".
 2713:                   '// ]]>'."\n".
 2714:                   '</script>'."\n";
 2715:     my %breadcrumb_text = &singleuser_breadcrumb($crstype,$context,$env{'form.ccdomain'});
 2716:     push (@{$brcrum},
 2717:              {href => "javascript:backPage(document.userupdate)",
 2718:               text => $breadcrumb_text{'search'},
 2719:               faq  => 282,
 2720:               bug  => 'Instructor Interface',}
 2721:              );
 2722:     if ($env{'form.prevphase'} eq 'userpicked') {
 2723:         push(@{$brcrum},
 2724:                {href => "javascript:backPage(document.userupdate,'get_user_info','select')",
 2725:                 text => $breadcrumb_text{'userpicked'},
 2726:                 faq  => 282,
 2727:                 bug  => 'Instructor Interface',});
 2728:     }
 2729:     my $helpitem = 'Course_Change_Privileges';
 2730:     if ($env{'form.action'} eq 'singlestudent') {
 2731:         $helpitem = 'Course_Add_Student';
 2732:     }
 2733:     push(@{$brcrum}, 
 2734:             {href => "javascript:backPage(document.userupdate,'$env{'form.prevphase'}','modify')",
 2735:              text => $breadcrumb_text{'modify'},
 2736:              faq  => 282,
 2737:              bug  => 'Instructor Interface',},
 2738:             {href => "/adm/createuser",
 2739:              text => "Result",
 2740:              faq  => 282,
 2741:              bug  => 'Instructor Interface',
 2742:              help => $helpitem});
 2743:     my $args = {bread_crumbs          => $brcrum,
 2744:                 bread_crumbs_component => 'User Management'};
 2745:     if ($env{'form.popup'}) {
 2746:         $args->{'no_nav_bar'} = 1;
 2747:     }
 2748:     $r->print(&Apache::loncommon::start_page($title,$jscript,$args));
 2749:     $r->print(&update_result_form($uhome));
 2750:     # Check Inputs
 2751:     if (! $env{'form.ccuname'} ) {
 2752: 	$r->print($error.&mt('No login name specified').'.'.$end.$rtnlink);
 2753: 	return;
 2754:     }
 2755:     if (  $env{'form.ccuname'} ne 
 2756: 	  &LONCAPA::clean_username($env{'form.ccuname'}) ) {
 2757: 	$r->print($error.&mt('Invalid login name.').'  '.
 2758: 		  &mt('Only letters, numbers, periods, dashes, @, and underscores are valid.').
 2759: 		  $end.$rtnlink);
 2760: 	return;
 2761:     }
 2762:     if (! $env{'form.ccdomain'}       ) {
 2763: 	$r->print($error.&mt('No domain specified').'.'.$end.$rtnlink);
 2764: 	return;
 2765:     }
 2766:     if (  $env{'form.ccdomain'} ne
 2767: 	  &LONCAPA::clean_domain($env{'form.ccdomain'}) ) {
 2768: 	$r->print($error.&mt('Invalid domain name.').'  '.
 2769: 		  &mt('Only letters, numbers, periods, dashes, and underscores are valid.').
 2770: 		  $end.$rtnlink);
 2771: 	return;
 2772:     }
 2773:     if ($uhome eq 'no_host') {
 2774:         $newuser = 1;
 2775:     }
 2776:     if (! exists($env{'form.makeuser'})) {
 2777:         # Modifying an existing user, so check the validity of the name
 2778:         if ($uhome eq 'no_host') {
 2779:             $r->print(
 2780:                 $error
 2781:                .'<p class="LC_error">'
 2782:                .&mt('Unable to determine home server for [_1] in domain [_2].',
 2783:                         '"'.$env{'form.ccuname'}.'"','"'.$env{'form.ccdomain'}.'"')
 2784:                .'</p>');
 2785:             return;
 2786:         }
 2787:     }
 2788:     # Determine authentication method and password for the user being modified
 2789:     my $amode='';
 2790:     my $genpwd='';
 2791:     if ($env{'form.login'} eq 'krb') {
 2792: 	$amode='krb';
 2793: 	$amode.=$env{'form.krbver'};
 2794: 	$genpwd=$env{'form.krbarg'};
 2795:     } elsif ($env{'form.login'} eq 'int') {
 2796: 	$amode='internal';
 2797: 	$genpwd=$env{'form.intarg'};
 2798:     } elsif ($env{'form.login'} eq 'fsys') {
 2799: 	$amode='unix';
 2800: 	$genpwd=$env{'form.fsysarg'};
 2801:     } elsif ($env{'form.login'} eq 'loc') {
 2802: 	$amode='localauth';
 2803: 	$genpwd=$env{'form.locarg'};
 2804: 	$genpwd=" " if (!$genpwd);
 2805:     } elsif (($env{'form.login'} eq 'nochange') ||
 2806:              ($env{'form.login'} eq ''        )) { 
 2807:         # There is no need to tell the user we did not change what they
 2808:         # did not ask us to change.
 2809:         # If they are creating a new user but have not specified login
 2810:         # information this will be caught below.
 2811:     } else {
 2812:             $r->print($error.&mt('Invalid login mode or password').$end.$rtnlink);
 2813:             return;
 2814:     }
 2815: 
 2816:     $r->print('<h3>'.&mt('User [_1] in domain [_2]',
 2817:                         $env{'form.ccuname'}.' ('.&Apache::loncommon::plainname($env{'form.ccuname'},
 2818:                         $env{'form.ccdomain'}).')', $env{'form.ccdomain'}).'</h3>');
 2819:     my %prog_state = &Apache::lonhtmlcommon::Create_PrgWin($r,2);
 2820: 
 2821:     my (%alerts,%rulematch,%inst_results,%curr_rules);
 2822:     my @userinfo = ('firstname','middlename','lastname','generation','permanentemail','id');
 2823:     my @usertools = ('aboutme','blog','webdav','portfolio');
 2824:     my @requestcourses = ('official','unofficial','community','textbook','placement');
 2825:     my @requestauthor = ('requestauthor');
 2826:     my ($othertitle,$usertypes,$types) = 
 2827:         &Apache::loncommon::sorted_inst_types($env{'form.ccdomain'});
 2828:     my %canmodify_status =
 2829:         &Apache::lonuserutils::can_modify_userinfo($context,$env{'form.ccdomain'},
 2830:                                                    ['inststatus']);
 2831:     if ($env{'form.makeuser'}) {
 2832: 	$r->print('<h3>'.&mt('Creating new account.').'</h3>');
 2833:         # Check for the authentication mode and password
 2834:         if (! $amode || ! $genpwd) {
 2835: 	    $r->print($error.&mt('Invalid login mode or password').$end.$rtnlink);    
 2836: 	    return;
 2837: 	}
 2838:         # Determine desired host
 2839:         my $desiredhost = $env{'form.hserver'};
 2840:         if (lc($desiredhost) eq 'default') {
 2841:             $desiredhost = undef;
 2842:         } else {
 2843:             my %home_servers = 
 2844: 		&Apache::lonnet::get_servers($env{'form.ccdomain'},'library');
 2845:             if (! exists($home_servers{$desiredhost})) {
 2846:                 $r->print($error.&mt('Invalid home server specified').$end.$rtnlink);
 2847:                 return;
 2848:             }
 2849:         }
 2850:         # Check ID format
 2851:         my %checkhash;
 2852:         my %checks = ('id' => 1);
 2853:         %{$checkhash{$env{'form.ccuname'}.':'.$env{'form.ccdomain'}}} = (
 2854:             'newuser' => $newuser, 
 2855:             'id' => $env{'form.cid'},
 2856:         );
 2857:         if ($env{'form.cid'} ne '') {
 2858:             &Apache::loncommon::user_rule_check(\%checkhash,\%checks,\%alerts,
 2859:                                           \%rulematch,\%inst_results,\%curr_rules);
 2860:             if (ref($alerts{'id'}) eq 'HASH') {
 2861:                 if (ref($alerts{'id'}{$env{'form.ccdomain'}}) eq 'HASH') {
 2862:                     my $domdesc =
 2863:                         &Apache::lonnet::domain($env{'form.ccdomain'},'description');
 2864:                     if ($alerts{'id'}{$env{'form.ccdomain'}}{$env{'form.cid'}}) {
 2865:                         my $userchkmsg;
 2866:                         if (ref($curr_rules{$env{'form.ccdomain'}}) eq 'HASH') {
 2867:                             $userchkmsg  = 
 2868:                                 &Apache::loncommon::instrule_disallow_msg('id',
 2869:                                                                     $domdesc,1).
 2870:                                 &Apache::loncommon::user_rule_formats($env{'form.ccdomain'},
 2871:                                     $domdesc,$curr_rules{$env{'form.ccdomain'}}{'id'},'id');
 2872:                         }
 2873:                         $r->print($error.&mt('Invalid ID format').$end.
 2874:                                   $userchkmsg.$rtnlink);
 2875:                         return;
 2876:                     }
 2877:                 }
 2878:             }
 2879:         }
 2880:         &Apache::lonhtmlcommon::Increment_PrgWin($r, \%prog_state);
 2881: 	# Call modifyuser
 2882: 	my $result = &Apache::lonnet::modifyuser
 2883: 	    ($env{'form.ccdomain'},$env{'form.ccuname'},$env{'form.cid'},
 2884:              $amode,$genpwd,$env{'form.cfirstname'},
 2885:              $env{'form.cmiddlename'},$env{'form.clastname'},
 2886:              $env{'form.cgeneration'},undef,$desiredhost,
 2887:              $env{'form.cpermanentemail'});
 2888: 	$r->print(&mt('Generating user').': '.$result);
 2889:         $uhome = &Apache::lonnet::homeserver($env{'form.ccuname'},
 2890:                                                $env{'form.ccdomain'});
 2891:         my (%changeHash,%newcustom,%changed,%changedinfo);
 2892:         if ($uhome ne 'no_host') {
 2893:             if ($context eq 'domain') {
 2894:                 foreach my $name ('portfolio','author') {
 2895:                     if ($env{'form.custom_'.$name.'quota'} == 1) {
 2896:                         if ($env{'form.'.$name.'quota'} eq '') {
 2897:                             $newcustom{$name.'quota'} = 0;
 2898:                         } else {
 2899:                             $newcustom{$name.'quota'} = $env{'form.'.$name.'quota'};
 2900:                             $newcustom{$name.'quota'} =~ s/[^\d\.]//g;
 2901:                         }
 2902:                         if (&quota_admin($newcustom{$name.'quota'},\%changeHash,$name)) {
 2903:                             $changed{$name.'quota'} = 1;
 2904:                         }
 2905:                     }
 2906:                 }
 2907:                 foreach my $item (@usertools) {
 2908:                     if ($env{'form.custom'.$item} == 1) {
 2909:                         $newcustom{$item} = $env{'form.tools_'.$item};
 2910:                         $changed{$item} = &tool_admin($item,$newcustom{$item},
 2911:                                                      \%changeHash,'tools');
 2912:                     }
 2913:                 }
 2914:                 foreach my $item (@requestcourses) {
 2915:                     if ($env{'form.custom'.$item} == 1) {
 2916:                         $newcustom{$item} = $env{'form.crsreq_'.$item};
 2917:                         if ($env{'form.crsreq_'.$item} eq 'autolimit') {
 2918:                             $newcustom{$item} .= '=';
 2919:                             $env{'form.crsreq_'.$item.'_limit'} =~ s/\D+//g;
 2920:                             if ($env{'form.crsreq_'.$item.'_limit'}) {
 2921:                                 $newcustom{$item} .= $env{'form.crsreq_'.$item.'_limit'};
 2922:                             }
 2923:                         }
 2924:                         $changed{$item} = &tool_admin($item,$newcustom{$item},
 2925:                                                       \%changeHash,'requestcourses');
 2926:                     }
 2927:                 }
 2928:                 if ($env{'form.customrequestauthor'} == 1) {
 2929:                     $newcustom{'requestauthor'} = $env{'form.requestauthor'};
 2930:                     $changed{'requestauthor'} = &tool_admin('requestauthor',
 2931:                                                     $newcustom{'requestauthor'},
 2932:                                                     \%changeHash,'requestauthor');
 2933:                 }
 2934:                 if (&Apache::lonnet::allowed('cdh',$env{'request.role.domain'})) {
 2935:                     my @adds = &Apache::loncommon::get_env_multiple('form.adhocroleadd');
 2936:                     if (&adhocrole_changes(\%changeHash)) {
 2937:                         $changed{'adhocroles.'.$env{'request.role.domain'}} = $changeHash{'adhocroles.'.$env{'request.role.domain'}};
 2938:                     }
 2939:                 }
 2940:             }
 2941:             if ($canmodify_status{'inststatus'}) {
 2942:                 if (exists($env{'form.inststatus'})) {
 2943:                     my @inststatuses = &Apache::loncommon::get_env_multiple('form.inststatus');
 2944:                     if (@inststatuses > 0) {
 2945:                         $changeHash{'inststatus'} = join(',',@inststatuses);
 2946:                         $changed{'inststatus'} = $changeHash{'inststatus'};
 2947:                     }
 2948:                 }
 2949:             }
 2950:             if (keys(%changed)) {
 2951:                 foreach my $item (@userinfo) {
 2952:                     $changeHash{$item}  = $env{'form.c'.$item};
 2953:                 }
 2954:                 my $chgresult =
 2955:                      &Apache::lonnet::put('environment',\%changeHash,
 2956:                                           $env{'form.ccdomain'},$env{'form.ccuname'});
 2957:             } 
 2958:         }
 2959:         $r->print('<br />'.&mt('Home server').': '.$uhome.' '.
 2960:                   &Apache::lonnet::hostname($uhome));
 2961:     } elsif (($env{'form.login'} ne 'nochange') &&
 2962:              ($env{'form.login'} ne ''        )) {
 2963: 	# Modify user privileges
 2964:         if (! $amode || ! $genpwd) {
 2965: 	    $r->print($error.'Invalid login mode or password'.$end.$rtnlink);    
 2966: 	    return;
 2967: 	}
 2968: 	# Only allow authentication modification if the person has authority
 2969: 	if (&Apache::lonnet::allowed('mau',$env{'form.ccdomain'})) {
 2970: 	    $r->print('Modifying authentication: '.
 2971:                       &Apache::lonnet::modifyuserauth(
 2972: 		       $env{'form.ccdomain'},$env{'form.ccuname'},
 2973:                        $amode,$genpwd));
 2974:             $r->print('<br />'.&mt('Home server').': '.&Apache::lonnet::homeserver
 2975: 		  ($env{'form.ccuname'},$env{'form.ccdomain'}));
 2976: 	} else {
 2977: 	    # Okay, this is a non-fatal error.
 2978: 	    $r->print($error.&mt('You do not have the authority to modify this users authentication information.').$end);    
 2979: 	}
 2980:     }
 2981:     $r->rflush(); # Finish display of header before time consuming actions start
 2982:     &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state);
 2983:     ##
 2984:     my (@userroles,%userupdate,$cnum,$cdom,$defaultcredits,%namechanged);
 2985:     if ($context eq 'course') {
 2986:         ($cnum,$cdom) =
 2987:             &Apache::lonuserutils::get_course_identity();
 2988:         $crstype = &Apache::loncommon::course_type($cdom.'_'.$cnum);
 2989:         if ($showcredits) {
 2990:            $defaultcredits = &Apache::lonuserutils::get_defaultcredits($cdom,$cnum);
 2991:         }
 2992:     }
 2993:     if (! $env{'form.makeuser'} ) {
 2994:         # Check for need to change
 2995:         my %userenv = &Apache::lonnet::get
 2996:             ('environment',['firstname','middlename','lastname','generation',
 2997:              'id','permanentemail','portfolioquota','authorquota','inststatus',
 2998:              'tools.aboutme','tools.blog','tools.webdav','tools.portfolio',
 2999:              'requestcourses.official','requestcourses.unofficial',
 3000:              'requestcourses.community','requestcourses.textbook',
 3001:              'reqcrsotherdom.official','reqcrsotherdom.unofficial',
 3002:              'reqcrsotherdom.community','reqcrsotherdom.textbook',
 3003:              'reqcrsotherdom.placement','requestauthor',
 3004:              'adhocroles.'.$env{'request.role.domain'}],
 3005:               $env{'form.ccdomain'},$env{'form.ccuname'});
 3006:         my ($tmp) = keys(%userenv);
 3007:         if ($tmp =~ /^(con_lost|error)/i) { 
 3008:             %userenv = ();
 3009:         }
 3010:         my $no_forceid_alert;
 3011:         # Check to see if user information can be changed
 3012:         my %domconfig =
 3013:             &Apache::lonnet::get_dom('configuration',['usermodification'],
 3014:                                      $env{'form.ccdomain'});
 3015:         my @statuses = ('active','future');
 3016:         my %roles = &Apache::lonnet::get_my_roles($env{'form.ccuname'},$env{'form.ccdomain'},'userroles',\@statuses,undef,$env{'request.role.domain'});
 3017:         my ($auname,$audom);
 3018:         if ($context eq 'author') {
 3019:             $auname = $env{'user.name'};
 3020:             $audom = $env{'user.domain'};     
 3021:         }
 3022:         foreach my $item (keys(%roles)) {
 3023:             my ($rolenum,$roledom,$role) = split(/:/,$item,-1);
 3024:             if ($context eq 'course') {
 3025:                 if ($cnum ne '' && $cdom ne '') {
 3026:                     if ($rolenum eq $cnum && $roledom eq $cdom) {
 3027:                         if (!grep(/^\Q$role\E$/,@userroles)) {
 3028:                             push(@userroles,$role);
 3029:                         }
 3030:                     }
 3031:                 }
 3032:             } elsif ($context eq 'author') {
 3033:                 if ($rolenum eq $auname && $roledom eq $audom) {
 3034:                     if (!grep(/^\Q$role\E$/,@userroles)) { 
 3035:                         push(@userroles,$role);
 3036:                     }
 3037:                 }
 3038:             }
 3039:         }
 3040:         if ($env{'form.action'} eq 'singlestudent') {
 3041:             if (!grep(/^st$/,@userroles)) {
 3042:                 push(@userroles,'st');
 3043:             }
 3044:         } else {
 3045:             # Check for course or co-author roles being activated or re-enabled
 3046:             if ($context eq 'author' || $context eq 'course') {
 3047:                 foreach my $key (keys(%env)) {
 3048:                     if ($context eq 'author') {
 3049:                         if ($key=~/^form\.act_\Q$audom\E_\Q$auname\E_([^_]+)/) {
 3050:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 3051:                                 push(@userroles,$1);
 3052:                             }
 3053:                         } elsif ($key =~/^form\.ren\:\Q$audom\E\/\Q$auname\E_([^_]+)/) {
 3054:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 3055:                                 push(@userroles,$1);
 3056:                             }
 3057:                         }
 3058:                     } elsif ($context eq 'course') {
 3059:                         if ($key=~/^form\.act_\Q$cdom\E_\Q$cnum\E_([^_]+)/) {
 3060:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 3061:                                 push(@userroles,$1);
 3062:                             }
 3063:                         } elsif ($key =~/^form\.ren\:\Q$cdom\E\/\Q$cnum\E(\/?\w*)_([^_]+)/) {
 3064:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 3065:                                 push(@userroles,$1);
 3066:                             }
 3067:                         }
 3068:                     }
 3069:                 }
 3070:             }
 3071:         }
 3072:         #Check to see if we can change personal data for the user 
 3073:         my (@mod_disallowed,@longroles);
 3074:         foreach my $role (@userroles) {
 3075:             if ($role eq 'cr') {
 3076:                 push(@longroles,'Custom');
 3077:             } else {
 3078:                 push(@longroles,&Apache::lonnet::plaintext($role,$crstype)); 
 3079:             }
 3080:         }
 3081:         my %canmodify = &Apache::lonuserutils::can_modify_userinfo($context,$env{'form.ccdomain'},\@userinfo,\@userroles);
 3082:         foreach my $item (@userinfo) {
 3083:             # Strip leading and trailing whitespace
 3084:             $env{'form.c'.$item} =~ s/(\s+$|^\s+)//g;
 3085:             if (!$canmodify{$item}) {
 3086:                 if (defined($env{'form.c'.$item})) {
 3087:                     if ($env{'form.c'.$item} ne $userenv{$item}) {
 3088:                         push(@mod_disallowed,$item);
 3089:                     }
 3090:                 }
 3091:                 $env{'form.c'.$item} = $userenv{$item};
 3092:             }
 3093:         }
 3094:         # Check to see if we can change the Student/Employee ID
 3095:         my $forceid = $env{'form.forceid'};
 3096:         my $recurseid = $env{'form.recurseid'};
 3097:         my (%alerts,%rulematch,%idinst_results,%curr_rules,%got_rules);
 3098:         my %uidhash = &Apache::lonnet::idrget($env{'form.ccdomain'},
 3099:                                             $env{'form.ccuname'});
 3100:         if (($uidhash{$env{'form.ccuname'}}) && 
 3101:             ($uidhash{$env{'form.ccuname'}}!~/error\:/) && 
 3102:             (!$forceid)) {
 3103:             if ($env{'form.cid'} ne $uidhash{$env{'form.ccuname'}}) {
 3104:                 $env{'form.cid'} = $userenv{'id'};
 3105:                 $no_forceid_alert = &mt('New student/employee ID does not match existing ID for this user.')
 3106:                                    .'<br />'
 3107:                                    .&mt("Change is not permitted without checking the 'Force ID change' checkbox on the previous page.")
 3108:                                    .'<br />'."\n";
 3109:             }
 3110:         }
 3111:         if ($env{'form.cid'} ne $userenv{'id'}) {
 3112:             my $checkhash;
 3113:             my $checks = { 'id' => 1 };
 3114:             $checkhash->{$env{'form.ccuname'}.':'.$env{'form.ccdomain'}} = 
 3115:                    { 'newuser' => $newuser,
 3116:                      'id'  => $env{'form.cid'}, 
 3117:                    };
 3118:             &Apache::loncommon::user_rule_check($checkhash,$checks,
 3119:                 \%alerts,\%rulematch,\%idinst_results,\%curr_rules,\%got_rules);
 3120:             if (ref($alerts{'id'}) eq 'HASH') {
 3121:                 if (ref($alerts{'id'}{$env{'form.ccdomain'}}) eq 'HASH') {
 3122:                    $env{'form.cid'} = $userenv{'id'};
 3123:                 }
 3124:             }
 3125:         }
 3126:         my (%quotachanged,%oldquota,%newquota,%olddefquota,%newdefquota, 
 3127:             $oldinststatus,$newinststatus,%oldisdefault,%newisdefault,%oldsettings,
 3128:             %oldsettingstext,%newsettings,%newsettingstext,@disporder,
 3129:             %oldsettingstatus,%newsettingstatus);
 3130:         @disporder = ('inststatus');
 3131:         if ($env{'request.role.domain'} eq $env{'form.ccdomain'}) {
 3132:             push(@disporder,'requestcourses','requestauthor');
 3133:         } else {
 3134:             push(@disporder,'reqcrsotherdom');
 3135:         }
 3136:         push(@disporder,('quota','tools'));
 3137:         $oldinststatus = $userenv{'inststatus'};
 3138:         foreach my $name ('portfolio','author') {
 3139:             ($olddefquota{$name},$oldsettingstatus{$name}) = 
 3140:                 &Apache::loncommon::default_quota($env{'form.ccdomain'},$oldinststatus,$name);
 3141:             ($newdefquota{$name},$newsettingstatus{$name}) = ($olddefquota{$name},$oldsettingstatus{$name});
 3142:         }
 3143:         push(@disporder,'adhocroles');
 3144:         my %canshow;
 3145:         if (&Apache::lonnet::allowed('mpq',$env{'form.ccdomain'})) {
 3146:             $canshow{'quota'} = 1;
 3147:         }
 3148:         if (&Apache::lonnet::allowed('mut',$env{'form.ccdomain'})) {
 3149:             $canshow{'tools'} = 1;
 3150:         }
 3151:         if (&Apache::lonnet::allowed('ccc',$env{'form.ccdomain'})) {
 3152:             $canshow{'requestcourses'} = 1;
 3153:         } elsif (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) {
 3154:             $canshow{'reqcrsotherdom'} = 1;
 3155:         }
 3156:         if (&Apache::lonnet::allowed('mau',$env{'form.ccdomain'})) {
 3157:             $canshow{'inststatus'} = 1;
 3158:         }
 3159:         if (&Apache::lonnet::allowed('cau',$env{'form.ccdomain'})) {
 3160:             $canshow{'requestauthor'} = 1;
 3161:         }
 3162:         if (&Apache::lonnet::allowed('cdh',$env{'request.role.domain'})) {
 3163:             $canshow{'adhocroles'} = 1;
 3164:         }
 3165:         my (%changeHash,%changed);
 3166:         if ($oldinststatus eq '') {
 3167:             $oldsettings{'inststatus'} = $othertitle; 
 3168:         } else {
 3169:             if (ref($usertypes) eq 'HASH') {
 3170:                 $oldsettings{'inststatus'} = join(', ',map{ $usertypes->{ &unescape($_) }; } (split(/:/,$userenv{'inststatus'})));
 3171:             } else {
 3172:                 $oldsettings{'inststatus'} = join(', ',map{ &unescape($_); } (split(/:/,$userenv{'inststatus'})));
 3173:             }
 3174:         }
 3175:         $changeHash{'inststatus'} = $userenv{'inststatus'};
 3176:         if ($canmodify_status{'inststatus'}) {
 3177:             $canshow{'inststatus'} = 1;
 3178:             if (exists($env{'form.inststatus'})) {
 3179:                 my @inststatuses = &Apache::loncommon::get_env_multiple('form.inststatus');
 3180:                 if (@inststatuses > 0) {
 3181:                     $newinststatus = join(':',map { &escape($_); } @inststatuses);
 3182:                     $changeHash{'inststatus'} = $newinststatus;
 3183:                     if ($newinststatus ne $oldinststatus) {
 3184:                         $changed{'inststatus'} = $newinststatus;
 3185:                         foreach my $name ('portfolio','author') {
 3186:                             ($newdefquota{$name},$newsettingstatus{$name}) =
 3187:                                 &Apache::loncommon::default_quota($env{'form.ccdomain'},$newinststatus,$name);
 3188:                         }
 3189:                     }
 3190:                     if (ref($usertypes) eq 'HASH') {
 3191:                         $newsettings{'inststatus'} = join(', ',map{ $usertypes->{$_}; } (@inststatuses)); 
 3192:                     } else {
 3193:                         $newsettings{'inststatus'} = join(', ',@inststatuses);
 3194:                     }
 3195:                 }
 3196:             } else {
 3197:                 $newinststatus = '';
 3198:                 $changeHash{'inststatus'} = $newinststatus;
 3199:                 $newsettings{'inststatus'} = $othertitle;
 3200:                 if ($newinststatus ne $oldinststatus) {
 3201:                     $changed{'inststatus'} = $changeHash{'inststatus'};
 3202:                     foreach my $name ('portfolio','author') {
 3203:                         ($newdefquota{$name},$newsettingstatus{$name}) =
 3204:                             &Apache::loncommon::default_quota($env{'form.ccdomain'},$newinststatus,$name);
 3205:                     }
 3206:                 }
 3207:             }
 3208:         } elsif ($context ne 'selfcreate') {
 3209:             $canshow{'inststatus'} = 1;
 3210:             $newsettings{'inststatus'} = $oldsettings{'inststatus'};
 3211:         }
 3212:         foreach my $name ('portfolio','author') {
 3213:             $changeHash{$name.'quota'} = $userenv{$name.'quota'};
 3214:         }
 3215:         if ($context eq 'domain') {
 3216:             foreach my $name ('portfolio','author') {
 3217:                 if ($userenv{$name.'quota'} ne '') {
 3218:                     $oldquota{$name} = $userenv{$name.'quota'};
 3219:                     if ($env{'form.custom_'.$name.'quota'} == 1) {
 3220:                         if ($env{'form.'.$name.'quota'} eq '') {
 3221:                             $newquota{$name} = 0;
 3222:                         } else {
 3223:                             $newquota{$name} = $env{'form.'.$name.'quota'};
 3224:                             $newquota{$name} =~ s/[^\d\.]//g;
 3225:                         }
 3226:                         if ($newquota{$name} != $oldquota{$name}) {
 3227:                             if (&quota_admin($newquota{$name},\%changeHash,$name)) {
 3228:                                 $changed{$name.'quota'} = 1;
 3229:                             }
 3230:                         }
 3231:                     } else {
 3232:                         if (&quota_admin('',\%changeHash,$name)) {
 3233:                             $changed{$name.'quota'} = 1;
 3234:                             $newquota{$name} = $newdefquota{$name};
 3235:                             $newisdefault{$name} = 1;
 3236:                         }
 3237:                     }
 3238:                 } else {
 3239:                     $oldisdefault{$name} = 1;
 3240:                     $oldquota{$name} = $olddefquota{$name};
 3241:                     if ($env{'form.custom_'.$name.'quota'} == 1) {
 3242:                         if ($env{'form.'.$name.'quota'} eq '') {
 3243:                             $newquota{$name} = 0;
 3244:                         } else {
 3245:                             $newquota{$name} = $env{'form.'.$name.'quota'};
 3246:                             $newquota{$name} =~ s/[^\d\.]//g;
 3247:                         }
 3248:                         if (&quota_admin($newquota{$name},\%changeHash,$name)) {
 3249:                             $changed{$name.'quota'} = 1;
 3250:                         }
 3251:                     } else {
 3252:                         $newquota{$name} = $newdefquota{$name};
 3253:                         $newisdefault{$name} = 1;
 3254:                     }
 3255:                 }
 3256:                 if ($oldisdefault{$name}) {
 3257:                     $oldsettingstext{'quota'}{$name} = &get_defaultquota_text($oldsettingstatus{$name});
 3258:                 }  else {
 3259:                     $oldsettingstext{'quota'}{$name} = &mt('custom quota: [_1] MB',$oldquota{$name});
 3260:                 }
 3261:                 if ($newisdefault{$name}) {
 3262:                     $newsettingstext{'quota'}{$name} = &get_defaultquota_text($newsettingstatus{$name});
 3263:                 } else {
 3264:                     $newsettingstext{'quota'}{$name} = &mt('custom quota: [_1] MB',$newquota{$name});
 3265:                 }
 3266:             }
 3267:             &tool_changes('tools',\@usertools,\%oldsettings,\%oldsettingstext,\%userenv,
 3268:                           \%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3269:             if ($env{'form.ccdomain'} eq $env{'request.role.domain'}) {
 3270:                 &tool_changes('requestcourses',\@requestcourses,\%oldsettings,\%oldsettingstext,
 3271:                               \%userenv,\%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3272:                 &tool_changes('requestauthor',\@requestauthor,\%oldsettings,\%oldsettingstext,
 3273:                               \%userenv,\%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3274:             } else {
 3275:                 &tool_changes('reqcrsotherdom',\@requestcourses,\%oldsettings,\%oldsettingstext,
 3276:                               \%userenv,\%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3277:             }
 3278:             if ($userenv{'adhocroles.'.$env{'request.role.domain'}}) {
 3279:                 $changeHash{'adhocroles.'.$env{'request.role.domain'}} = $userenv{'adhocroles.'.$env{'request.role.domain'}};
 3280:             }
 3281:             if (&adhocrole_changes(\%changeHash,\%userenv)) {
 3282:                 $changed{'adhocroles'} = 1;
 3283:                 $oldsettings{'adhocroles'} = $userenv{'adhocroles.'.$env{'request.role.domain'}};
 3284:                 $newsettings{'adhocroles'} = $changeHash{'adhocroles.'.$env{'request.role.domain'}};
 3285:             }
 3286:         }
 3287:         foreach my $item (@userinfo) {
 3288:             if ($env{'form.c'.$item} ne $userenv{$item}) {
 3289:                 $namechanged{$item} = 1;
 3290:             }
 3291:         }
 3292:         foreach my $name ('portfolio','author') {
 3293:             $oldsettings{'quota'}{$name} = &mt('[_1] MB',$oldquota{$name});
 3294:             $newsettings{'quota'}{$name} = &mt('[_1] MB',$newquota{$name});
 3295:         }
 3296:         if ((keys(%namechanged) > 0) || (keys(%changed) > 0)) {
 3297:             my ($chgresult,$namechgresult);
 3298:             if (keys(%changed) > 0) {
 3299:                 $chgresult = 
 3300:                     &Apache::lonnet::put('environment',\%changeHash,
 3301:                                   $env{'form.ccdomain'},$env{'form.ccuname'});
 3302:                 if ($chgresult eq 'ok') {
 3303:                     if (($env{'user.name'} eq $env{'form.ccuname'}) &&
 3304:                         ($env{'user.domain'} eq $env{'form.ccdomain'})) {
 3305:                         my %newenvhash;
 3306:                         foreach my $key (keys(%changed)) {
 3307:                             if (($key eq 'official') || ($key eq 'unofficial') ||
 3308:                                 ($key eq 'community') || ($key eq 'textbook') ||
 3309:                                 ($key eq 'placement')) {
 3310:                                 $newenvhash{'environment.requestcourses.'.$key} =
 3311:                                     $changeHash{'requestcourses.'.$key};
 3312:                                 if ($changeHash{'requestcourses.'.$key}) {
 3313:                                     $newenvhash{'environment.canrequest.'.$key} = 1;
 3314:                                 } else {
 3315:                                     $newenvhash{'environment.canrequest.'.$key} =
 3316:           &Apache::lonnet::usertools_access($env{'user.name'},$env{'user.domain'},
 3317:                                             $key,'reload','requestcourses');
 3318:                                 }
 3319:                             } elsif ($key eq 'requestauthor') {
 3320:                                 $newenvhash{'environment.'.$key} = $changeHash{$key};
 3321:                                 if ($changeHash{$key}) {
 3322:                                     $newenvhash{'environment.canrequest.author'} = 1;
 3323:                                 } else {
 3324:                                     $newenvhash{'environment.canrequest.author'} =
 3325:           &Apache::lonnet::usertools_access($env{'user.name'},$env{'user.domain'},
 3326:                                             $key,'reload','requestauthor');
 3327:                                 }
 3328:                             } elsif ($key eq 'adhocroles') {
 3329:                                 $newenvhash{'adhocroles.'.$env{'request.role.domain'}} =
 3330:                                     $changeHash{'adhocroles.'.$env{'request.role.domain'}};
 3331:                             } elsif ($key ne 'quota') {
 3332:                                 $newenvhash{'environment.tools.'.$key} = 
 3333:                                     $changeHash{'tools.'.$key};
 3334:                                 if ($changeHash{'tools.'.$key} ne '') {
 3335:                                     $newenvhash{'environment.availabletools.'.$key} =
 3336:                                         $changeHash{'tools.'.$key};
 3337:                                 } else {
 3338:                                     $newenvhash{'environment.availabletools.'.$key} =
 3339:           &Apache::lonnet::usertools_access($env{'user.name'},$env{'user.domain'},
 3340:           $key,'reload','tools');
 3341:                                 }
 3342:                             }
 3343:                         }
 3344:                         if (keys(%newenvhash)) {
 3345:                             &Apache::lonnet::appenv(\%newenvhash);
 3346:                         }
 3347:                     }
 3348:                 }
 3349:             }
 3350:             if (keys(%namechanged) > 0) {
 3351:                 foreach my $field (@userinfo) {
 3352:                     $changeHash{$field}  = $env{'form.c'.$field};
 3353:                 }
 3354: # Make the change
 3355:                 $namechgresult =
 3356:                     &Apache::lonnet::modifyuser($env{'form.ccdomain'},
 3357:                         $env{'form.ccuname'},$changeHash{'id'},undef,undef,
 3358:                         $changeHash{'firstname'},$changeHash{'middlename'},
 3359:                         $changeHash{'lastname'},$changeHash{'generation'},
 3360:                         $changeHash{'id'},undef,$changeHash{'permanentemail'},undef,\@userinfo);
 3361:                 %userupdate = (
 3362:                                lastname   => $env{'form.clastname'},
 3363:                                middlename => $env{'form.cmiddlename'},
 3364:                                firstname  => $env{'form.cfirstname'},
 3365:                                generation => $env{'form.cgeneration'},
 3366:                                id         => $env{'form.cid'},
 3367:                              );
 3368:             }
 3369:             if (((keys(%namechanged) > 0) && $namechgresult eq 'ok') || 
 3370:                 ((keys(%changed) > 0) && $chgresult eq 'ok')) {
 3371:             # Tell the user we changed the name
 3372:                 &display_userinfo($r,1,\@disporder,\%canshow,\@requestcourses,
 3373:                                   \@usertools,\@requestauthor,\%userenv,\%changed,\%namechanged,
 3374:                                   \%oldsettings, \%oldsettingstext,\%newsettings,
 3375:                                   \%newsettingstext);
 3376:                 if ($env{'form.cid'} ne $userenv{'id'}) {
 3377:                     &Apache::lonnet::idput($env{'form.ccdomain'},
 3378:                          {$env{'form.ccuname'} => $env{'form.cid'}},$uhome,'ids');
 3379:                     if (($recurseid) &&
 3380:                         (&Apache::lonnet::allowed('mau',$env{'form.ccdomain'}))) {
 3381:                         my $idresult = 
 3382:                             &Apache::lonuserutils::propagate_id_change(
 3383:                                 $env{'form.ccuname'},$env{'form.ccdomain'},
 3384:                                 \%userupdate);
 3385:                         $r->print('<br />'.$idresult.'<br />');
 3386:                     }
 3387:                 }
 3388:                 if (($env{'form.ccdomain'} eq $env{'user.domain'}) && 
 3389:                     ($env{'form.ccuname'} eq $env{'user.name'})) {
 3390:                     my %newenvhash;
 3391:                     foreach my $key (keys(%changeHash)) {
 3392:                         $newenvhash{'environment.'.$key} = $changeHash{$key};
 3393:                     }
 3394:                     &Apache::lonnet::appenv(\%newenvhash);
 3395:                 }
 3396:             } else { # error occurred
 3397:                 $r->print(
 3398:                     '<p class="LC_error">'
 3399:                    .&mt('Unable to successfully change environment for [_1] in domain [_2].',
 3400:                             '"'.$env{'form.ccuname'}.'"',
 3401:                             '"'.$env{'form.ccdomain'}.'"')
 3402:                    .'</p>');
 3403:             }
 3404:         } else { # End of if ($env ... ) logic
 3405:             # They did not want to change the users name, quota, tool availability,
 3406:             # or ability to request creation of courses, 
 3407:             # but we can still tell them what the name and quota and availabilities are  
 3408:             &display_userinfo($r,undef,\@disporder,\%canshow,\@requestcourses,
 3409:                               \@usertools,\@requestauthor,\%userenv,\%changed,\%namechanged,\%oldsettings,
 3410:                               \%oldsettingstext,\%newsettings,\%newsettingstext);
 3411:         }
 3412:         if (@mod_disallowed) {
 3413:             my ($rolestr,$contextname);
 3414:             if (@longroles > 0) {
 3415:                 $rolestr = join(', ',@longroles);
 3416:             } else {
 3417:                 $rolestr = &mt('No roles');
 3418:             }
 3419:             if ($context eq 'course') {
 3420:                 $contextname = 'course';
 3421:             } elsif ($context eq 'author') {
 3422:                 $contextname = 'co-author';
 3423:             }
 3424:             $r->print(&mt('The following fields were not updated: ').'<ul>');
 3425:             my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
 3426:             foreach my $field (@mod_disallowed) {
 3427:                 $r->print('<li>'.$fieldtitles{$field}.'</li>'."\n"); 
 3428:             }
 3429:             $r->print('</ul>');
 3430:             if (@mod_disallowed == 1) {
 3431:                 $r->print(&mt("You do not have the authority to change this field given the user's current set of active/future $contextname roles:"));
 3432:             } else {
 3433:                 $r->print(&mt("You do not have the authority to change these fields given the user's current set of active/future $contextname roles:"));
 3434:             }
 3435:             my $helplink = 'javascript:helpMenu('."'display'".')';
 3436:             $r->print('<span class="LC_cusr_emph">'.$rolestr.'</span><br />'
 3437:                      .&mt('Please contact your [_1]helpdesk[_2] for more information.'
 3438:                          ,'<a href="'.$helplink.'">','</a>')
 3439:                       .'<br />');
 3440:         }
 3441:         $r->print('<span class="LC_warning">'
 3442:                   .$no_forceid_alert
 3443:                   .&Apache::lonuserutils::print_namespacing_alerts($env{'form.ccdomain'},\%alerts,\%curr_rules)
 3444:                   .'</span>');
 3445:     }
 3446:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 3447:     if ($env{'form.action'} eq 'singlestudent') {
 3448:         &enroll_single_student($r,$uhome,$amode,$genpwd,$now,$newuser,$context,
 3449:                                $crstype,$showcredits,$defaultcredits);
 3450:         my $linktext = ($crstype eq 'Community' ?
 3451:             &mt('Enroll Another Member') : &mt('Enroll Another Student'));
 3452:         $r->print(
 3453:             &Apache::lonhtmlcommon::actionbox([
 3454:                 '<a href="javascript:backPage(document.userupdate)">'
 3455:                .($crstype eq 'Community' ? 
 3456:                     &mt('Enroll Another Member') : &mt('Enroll Another Student'))
 3457:                .'</a>']));
 3458:     } else {
 3459:         my @rolechanges = &update_roles($r,$context,$showcredits);
 3460:         if (keys(%namechanged) > 0) {
 3461:             if ($context eq 'course') {
 3462:                 if (@userroles > 0) {
 3463:                     if ((@rolechanges == 0) || 
 3464:                         (!(grep(/^st$/,@rolechanges)))) {
 3465:                         if (grep(/^st$/,@userroles)) {
 3466:                             my $classlistupdated =
 3467:                                 &Apache::lonuserutils::update_classlist($cdom,
 3468:                                               $cnum,$env{'form.ccdomain'},
 3469:                                        $env{'form.ccuname'},\%userupdate);
 3470:                         }
 3471:                     }
 3472:                 }
 3473:             }
 3474:         }
 3475:         my $userinfo = &Apache::loncommon::plainname($env{'form.ccuname'},
 3476:                                                      $env{'form.ccdomain'});
 3477:         if ($env{'form.popup'}) {
 3478:             $r->print('<p><a href="javascript:window.close()">'.&mt('Close window').'</a></p>');
 3479:         } else {
 3480:             $r->print('<br />'.&Apache::lonhtmlcommon::actionbox(['<a href="javascript:backPage(document.userupdate,'."'$env{'form.prevphase'}','modify'".')">'
 3481:                      .&mt('Modify this user: [_1]','<span class="LC_cusr_emph">'.$env{'form.ccuname'}.':'.$env{'form.ccdomain'}.' ('.$userinfo.')</span>').'</a>',
 3482:                      '<a href="javascript:backPage(document.userupdate)">'.&mt('Create/Modify Another User').'</a>']));
 3483:         }
 3484:     }
 3485: }
 3486: 
 3487: sub display_userinfo {
 3488:     my ($r,$changed,$order,$canshow,$requestcourses,$usertools,$requestauthor,
 3489:         $userenv,$changedhash,$namechangedhash,$oldsetting,$oldsettingtext,
 3490:         $newsetting,$newsettingtext) = @_;
 3491:     return unless (ref($order) eq 'ARRAY' &&
 3492:                    ref($canshow) eq 'HASH' && 
 3493:                    ref($requestcourses) eq 'ARRAY' && 
 3494:                    ref($requestauthor) eq 'ARRAY' &&
 3495:                    ref($usertools) eq 'ARRAY' && 
 3496:                    ref($userenv) eq 'HASH' &&
 3497:                    ref($changedhash) eq 'HASH' &&
 3498:                    ref($oldsetting) eq 'HASH' &&
 3499:                    ref($oldsettingtext) eq 'HASH' &&
 3500:                    ref($newsetting) eq 'HASH' &&
 3501:                    ref($newsettingtext) eq 'HASH');
 3502:     my %lt=&Apache::lonlocal::texthash(
 3503:          'ui'             => 'User Information',
 3504:          'uic'            => 'User Information Changed',
 3505:          'firstname'      => 'First Name',
 3506:          'middlename'     => 'Middle Name',
 3507:          'lastname'       => 'Last Name',
 3508:          'generation'     => 'Generation',
 3509:          'id'             => 'Student/Employee ID',
 3510:          'permanentemail' => 'Permanent e-mail address',
 3511:          'portfolioquota' => 'Disk space allocated to portfolio files',
 3512:          'authorquota'    => 'Disk space allocated to Authoring Space',
 3513:          'blog'           => 'Blog Availability',
 3514:          'webdav'         => 'WebDAV Availability',
 3515:          'aboutme'        => 'Personal Information Page Availability',
 3516:          'portfolio'      => 'Portfolio Availability',
 3517:          'official'       => 'Can Request Official Courses',
 3518:          'unofficial'     => 'Can Request Unofficial Courses',
 3519:          'community'      => 'Can Request Communities',
 3520:          'textbook'       => 'Can Request Textbook Courses',
 3521:          'placement'      => 'Can Request Placement Tests',
 3522:          'requestauthor'  => 'Can Request Author Role',
 3523:          'adhocroles'     => 'Ad Hoc Roles Selectable via Helpdesk Role',
 3524:          'inststatus'     => "Affiliation",
 3525:          'prvs'           => 'Previous Value:',
 3526:          'chto'           => 'Changed To:'
 3527:     );
 3528:     if ($changed) {
 3529:         $r->print('<h3>'.$lt{'uic'}.'</h3>'.
 3530:                 &Apache::loncommon::start_data_table().
 3531:                 &Apache::loncommon::start_data_table_header_row());
 3532:         $r->print("<th>&nbsp;</th>\n");
 3533:         $r->print('<th><b>'.$lt{'prvs'}.'</b></th>');
 3534:         $r->print('<th><span class="LC_nobreak"><b>'.$lt{'chto'}.'</b></span></th>');
 3535:         $r->print(&Apache::loncommon::end_data_table_header_row());
 3536:         my @userinfo = ('firstname','middlename','lastname','generation','permanentemail','id');
 3537: 
 3538:         foreach my $item (@userinfo) {
 3539:             my $value = $env{'form.c'.$item};
 3540:             #show changes only:
 3541:             unless ($value eq $userenv->{$item}){
 3542:                 $r->print(&Apache::loncommon::start_data_table_row());
 3543:                 $r->print("<td>$lt{$item}</td>\n");
 3544:                 $r->print("<td>".$userenv->{$item}."</td>\n");
 3545:                 $r->print("<td>$value </td>\n");
 3546:                 $r->print(&Apache::loncommon::end_data_table_row());
 3547:             }
 3548:         }
 3549:         foreach my $entry (@{$order}) {
 3550:             if ($canshow->{$entry}) {
 3551:                 if (($entry eq 'requestcourses') || ($entry eq 'reqcrsotherdom') || ($entry eq 'requestauthor')) {
 3552:                     my @items;
 3553:                     if ($entry eq 'requestauthor') {
 3554:                         @items = ($entry);
 3555:                     } else {
 3556:                         @items = @{$requestcourses};
 3557:                     }
 3558:                     foreach my $item (@items) {
 3559:                         if (($newsetting->{$item} ne $oldsetting->{$item}) || 
 3560:                             ($newsettingtext->{$item} ne $oldsettingtext->{$item})) {
 3561:                             $r->print(&Apache::loncommon::start_data_table_row()."\n");  
 3562:                             $r->print("<td>$lt{$item}</td>\n");
 3563:                             $r->print("<td>".$oldsetting->{$item});
 3564:                             if ($oldsettingtext->{$item}) {
 3565:                                 if ($oldsetting->{$item}) {
 3566:                                     $r->print(' -- ');
 3567:                                 }
 3568:                                 $r->print($oldsettingtext->{$item});
 3569:                             }
 3570:                             $r->print("</td>\n");
 3571:                             $r->print("<td>".$newsetting->{$item});
 3572:                             if ($newsettingtext->{$item}) {
 3573:                                 if ($newsetting->{$item}) {
 3574:                                     $r->print(' -- ');
 3575:                                 }
 3576:                                 $r->print($newsettingtext->{$item});
 3577:                             }
 3578:                             $r->print("</td>\n");
 3579:                             $r->print(&Apache::loncommon::end_data_table_row()."\n");
 3580:                         }
 3581:                     }
 3582:                 } elsif ($entry eq 'tools') {
 3583:                     foreach my $item (@{$usertools}) {
 3584:                         if ($newsetting->{$item} ne $oldsetting->{$item}) {
 3585:                             $r->print(&Apache::loncommon::start_data_table_row()."\n");
 3586:                             $r->print("<td>$lt{$item}</td>\n");
 3587:                             $r->print("<td>".$oldsetting->{$item}.' '.$oldsettingtext->{$item}."</td>\n");
 3588:                             $r->print("<td>".$newsetting->{$item}.' '.$newsettingtext->{$item}."</td>\n");
 3589:                             $r->print(&Apache::loncommon::end_data_table_row()."\n");
 3590:                         }
 3591:                     }
 3592:                 } elsif ($entry eq 'quota') {
 3593:                     if ((ref($oldsetting->{$entry}) eq 'HASH') && (ref($oldsettingtext->{$entry}) eq 'HASH') &&
 3594:                         (ref($newsetting->{$entry}) eq 'HASH') && (ref($newsettingtext->{$entry}) eq 'HASH')) {
 3595:                         foreach my $name ('portfolio','author') {
 3596:                             if ($newsetting->{$entry}->{$name} ne $oldsetting->{$entry}->{$name}) {
 3597:                                 $r->print(&Apache::loncommon::start_data_table_row()."\n");
 3598:                                 $r->print("<td>$lt{$name.$entry}</td>\n");
 3599:                                 $r->print("<td>".$oldsettingtext->{$entry}->{$name}."</td>\n");
 3600:                                 $r->print("<td>".$newsettingtext->{$entry}->{$name}."</td>\n");
 3601:                                 $r->print(&Apache::loncommon::end_data_table_row()."\n");
 3602:                             }
 3603:                         }
 3604:                     }
 3605:                 } else {
 3606:                     if ($newsetting->{$entry} ne $oldsetting->{$entry}) {
 3607:                         $r->print(&Apache::loncommon::start_data_table_row()."\n");
 3608:                         $r->print("<td>$lt{$entry}</td>\n");
 3609:                         $r->print("<td>".$oldsetting->{$entry}.' '.$oldsettingtext->{$entry}."</td>\n");
 3610:                         $r->print("<td>".$newsetting->{$entry}.' '.$newsettingtext->{$entry}."</td>\n");
 3611:                         $r->print(&Apache::loncommon::end_data_table_row()."\n");
 3612:                     }
 3613:                 }
 3614:             }
 3615:         }
 3616:         $r->print(&Apache::loncommon::end_data_table().'<br />');
 3617:     } else {
 3618:         $r->print('<h3>'.$lt{'ui'}.'</h3>'.
 3619:                   '<p>'.&mt('No changes made to user information').'</p>');
 3620:     }
 3621:     return;
 3622: }
 3623: 
 3624: sub tool_changes {
 3625:     my ($context,$usertools,$oldaccess,$oldaccesstext,$userenv,$changeHash,
 3626:         $changed,$newaccess,$newaccesstext) = @_;
 3627:     if (!((ref($usertools) eq 'ARRAY') && (ref($oldaccess) eq 'HASH') &&
 3628:           (ref($oldaccesstext) eq 'HASH') && (ref($userenv) eq 'HASH') &&
 3629:           (ref($changeHash) eq 'HASH') && (ref($changed) eq 'HASH') &&
 3630:           (ref($newaccess) eq 'HASH') && (ref($newaccesstext) eq 'HASH'))) {
 3631:         return;
 3632:     }
 3633:     my %reqdisplay = &requestchange_display();
 3634:     if ($context eq 'reqcrsotherdom') {
 3635:         my @options = ('approval','validate','autolimit');
 3636:         my $optregex = join('|',@options);
 3637:         my $cdom = $env{'request.role.domain'};
 3638:         foreach my $tool (@{$usertools}) {
 3639:             $oldaccesstext->{$tool} = &mt("availability set to 'off'");
 3640:             $newaccesstext->{$tool} = $oldaccesstext->{$tool};
 3641:             $changeHash->{$context.'.'.$tool} = $userenv->{$context.'.'.$tool};
 3642:             my ($newop,$limit);
 3643:             if ($env{'form.'.$context.'_'.$tool}) {
 3644:                 $newop = $env{'form.'.$context.'_'.$tool};
 3645:                 if ($newop eq 'autolimit') {
 3646:                     $limit = $env{'form.'.$context.'_'.$tool.'_limit'};
 3647:                     $limit =~ s/\D+//g;
 3648:                     $newop .= '='.$limit;
 3649:                 }
 3650:             }
 3651:             if ($userenv->{$context.'.'.$tool} eq '') {
 3652:                 if ($newop) {
 3653:                     $changed->{$tool}=&tool_admin($tool,$cdom.':'.$newop,
 3654:                                                   $changeHash,$context);
 3655:                     if ($changed->{$tool}) {
 3656:                         if ($newop =~ /^autolimit/) {
 3657:                             if ($limit) {
 3658:                                 $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3659:                             } else {
 3660:                                 $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3661:                             }
 3662:                         } else {
 3663:                             $newaccesstext->{$tool} = $reqdisplay{$newop};
 3664:                         }
 3665:                     } else {
 3666:                         $newaccesstext->{$tool} = $oldaccesstext->{$tool};
 3667:                     }
 3668:                 }
 3669:             } else {
 3670:                 my @curr = split(',',$userenv->{$context.'.'.$tool});
 3671:                 my @new;
 3672:                 my $changedoms;
 3673:                 foreach my $req (@curr) {
 3674:                     if ($req =~ /^\Q$cdom\E\:($optregex\=?\d*)$/) {
 3675:                         my $oldop = $1;
 3676:                         if ($oldop =~ /^autolimit=(\d*)/) {
 3677:                             my $limit = $1;
 3678:                             if ($limit) {
 3679:                                 $oldaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3680:                             } else {
 3681:                                 $oldaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3682:                             }
 3683:                         } else {
 3684:                             $oldaccesstext->{$tool} = $reqdisplay{$oldop};
 3685:                         }
 3686:                         if ($oldop ne $newop) {
 3687:                             $changedoms = 1;
 3688:                             foreach my $item (@curr) {
 3689:                                 my ($reqdom,$option) = split(':',$item);
 3690:                                 unless ($reqdom eq $cdom) {
 3691:                                     push(@new,$item);
 3692:                                 }
 3693:                             }
 3694:                             if ($newop) {
 3695:                                 push(@new,$cdom.':'.$newop);
 3696:                             }
 3697:                             @new = sort(@new);
 3698:                         }
 3699:                         last;
 3700:                     }
 3701:                 }
 3702:                 if ((!$changedoms) && ($newop)) {
 3703:                     $changedoms = 1;
 3704:                     @new = sort(@curr,$cdom.':'.$newop);
 3705:                 }
 3706:                 if ($changedoms) {
 3707:                     my $newdomstr;
 3708:                     if (@new) {
 3709:                         $newdomstr = join(',',@new);
 3710:                     }
 3711:                     $changed->{$tool}=&tool_admin($tool,$newdomstr,$changeHash,
 3712:                                                   $context);
 3713:                     if ($changed->{$tool}) {
 3714:                         if ($env{'form.'.$context.'_'.$tool}) {
 3715:                             if ($env{'form.'.$context.'_'.$tool} eq 'autolimit') {
 3716:                                 my $limit = $env{'form.'.$context.'_'.$tool.'_limit'};
 3717:                                 $limit =~ s/\D+//g;
 3718:                                 if ($limit) {
 3719:                                     $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3720:                                 } else {
 3721:                                     $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3722:                                 }
 3723:                             } else {
 3724:                                 $newaccesstext->{$tool} = $reqdisplay{$env{'form.'.$context.'_'.$tool}};
 3725:                             }
 3726:                         } else {
 3727:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3728:                         }
 3729:                     }
 3730:                 }
 3731:             }
 3732:         }
 3733:         return;
 3734:     }
 3735:     foreach my $tool (@{$usertools}) {
 3736:         my ($newval,$limit,$envkey);
 3737:         $envkey = $context.'.'.$tool;
 3738:         if ($context eq 'requestcourses') {
 3739:             $newval = $env{'form.crsreq_'.$tool};
 3740:             if ($newval eq 'autolimit') {
 3741:                 $limit = $env{'form.crsreq_'.$tool.'_limit'};
 3742:                 $limit =~ s/\D+//g;
 3743:                 $newval .= '='.$limit;
 3744:             }
 3745:         } elsif ($context eq 'requestauthor') {
 3746:             $newval = $env{'form.'.$context};
 3747:             $envkey = $context;
 3748:         } else {
 3749:             $newval = $env{'form.'.$context.'_'.$tool};
 3750:         }
 3751:         if ($userenv->{$envkey} ne '') {
 3752:             $oldaccess->{$tool} = &mt('custom');
 3753:             if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 3754:                 if ($userenv->{$envkey} =~ /^autolimit=(\d*)$/) {
 3755:                     my $currlimit = $1;
 3756:                     if ($currlimit eq '') {
 3757:                         $oldaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3758:                     } else {
 3759:                         $oldaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$currlimit);
 3760:                     }
 3761:                 } elsif ($userenv->{$envkey}) {
 3762:                     $oldaccesstext->{$tool} = $reqdisplay{$userenv->{$envkey}};
 3763:                 } else {
 3764:                     $oldaccesstext->{$tool} = &mt("availability set to 'off'");
 3765:                 }
 3766:             } else {
 3767:                 if ($userenv->{$envkey}) {
 3768:                     $oldaccesstext->{$tool} = &mt("availability set to 'on'");
 3769:                 } else {
 3770:                     $oldaccesstext->{$tool} = &mt("availability set to 'off'");
 3771:                 }
 3772:             }
 3773:             $changeHash->{$envkey} = $userenv->{$envkey};
 3774:             if ($env{'form.custom'.$tool} == 1) {
 3775:                 if ($newval ne $userenv->{$envkey}) {
 3776:                     $changed->{$tool} = &tool_admin($tool,$newval,$changeHash,
 3777:                                                     $context);
 3778:                     if ($changed->{$tool}) {
 3779:                         $newaccess->{$tool} = &mt('custom');
 3780:                         if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 3781:                             if ($newval =~ /^autolimit/) {
 3782:                                 if ($limit) {
 3783:                                     $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3784:                                 } else {
 3785:                                     $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3786:                                 }
 3787:                             } elsif ($newval) {
 3788:                                 $newaccesstext->{$tool} = $reqdisplay{$newval};
 3789:                             } else {
 3790:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3791:                             }
 3792:                         } else {
 3793:                             if ($newval) {
 3794:                                 $newaccesstext->{$tool} = &mt("availability set to 'on'");
 3795:                             } else {
 3796:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3797:                             }
 3798:                         }
 3799:                     } else {
 3800:                         $newaccess->{$tool} = $oldaccess->{$tool};
 3801:                         if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 3802:                             if ($newval =~ /^autolimit/) {
 3803:                                 if ($limit) {
 3804:                                     $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3805:                                 } else {
 3806:                                     $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3807:                                 }
 3808:                             } elsif ($newval) {
 3809:                                 $newaccesstext->{$tool} = $reqdisplay{$newval};
 3810:                             } else {
 3811:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3812:                             }
 3813:                         } else {
 3814:                             if ($userenv->{$context.'.'.$tool}) {
 3815:                                 $newaccesstext->{$tool} = &mt("availability set to 'on'");
 3816:                             } else {
 3817:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3818:                             }
 3819:                         }
 3820:                     }
 3821:                 } else {
 3822:                     $newaccess->{$tool} = $oldaccess->{$tool};
 3823:                     $newaccesstext->{$tool} = $oldaccesstext->{$tool};
 3824:                 }
 3825:             } else {
 3826:                 $changed->{$tool} = &tool_admin($tool,'',$changeHash,$context);
 3827:                 if ($changed->{$tool}) {
 3828:                     $newaccess->{$tool} = &mt('default');
 3829:                 } else {
 3830:                     $newaccess->{$tool} = $oldaccess->{$tool};
 3831:                     if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 3832:                         if ($newval =~ /^autolimit/) {
 3833:                             if ($limit) {
 3834:                                 $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3835:                             } else {
 3836:                                 $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3837:                             }
 3838:                         } elsif ($newval) {
 3839:                             $newaccesstext->{$tool} = $reqdisplay{$newval};
 3840:                         } else {
 3841:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3842:                         }
 3843:                     } else {
 3844:                         if ($userenv->{$context.'.'.$tool}) {
 3845:                             $newaccesstext->{$tool} = &mt("availability set to 'on'");
 3846:                         } else {
 3847:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3848:                         }
 3849:                     }
 3850:                 }
 3851:             }
 3852:         } else {
 3853:             $oldaccess->{$tool} = &mt('default');
 3854:             if ($env{'form.custom'.$tool} == 1) {
 3855:                 $changed->{$tool} = &tool_admin($tool,$newval,$changeHash,
 3856:                                                 $context);
 3857:                 if ($changed->{$tool}) {
 3858:                     $newaccess->{$tool} = &mt('custom');
 3859:                     if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 3860:                         if ($newval =~ /^autolimit/) {
 3861:                             if ($limit) {
 3862:                                 $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3863:                             } else {
 3864:                                 $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3865:                             }
 3866:                         } elsif ($newval) {
 3867:                             $newaccesstext->{$tool} = $reqdisplay{$newval};
 3868:                         } else {
 3869:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3870:                         }
 3871:                     } else {
 3872:                         if ($newval) {
 3873:                             $newaccesstext->{$tool} = &mt("availability set to 'on'");
 3874:                         } else {
 3875:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3876:                         }
 3877:                     }
 3878:                 } else {
 3879:                     $newaccess->{$tool} = $oldaccess->{$tool};
 3880:                 }
 3881:             } else {
 3882:                 $newaccess->{$tool} = $oldaccess->{$tool};
 3883:             }
 3884:         }
 3885:     }
 3886:     return;
 3887: }
 3888: 
 3889: sub adhocrole_changes {
 3890:     my ($changehashref,$userenv) = @_;
 3891:     my @adds = &Apache::loncommon::get_env_multiple('form.adhocroleadd');
 3892:     my @dels = &Apache::loncommon::get_env_multiple('form.adhocroledel');
 3893:     my (@saved,@added,@alladhoc,$changed);
 3894:     my $adhoc_key = 'adhocroles.'.$env{'request.role.domain'};
 3895:     if (!$env{'form.makeuser'}) {
 3896:         if (ref($userenv) eq 'HASH') {
 3897:             my @current;
 3898:             if ($userenv->{$adhoc_key}) {
 3899:                 @current = split(/,/,$userenv->{$adhoc_key});
 3900:                 if (@dels) {
 3901:                     foreach my $curr (@current) {
 3902:                         next if ($curr eq '');
 3903:                         unless (grep(/\Q$curr\E$/,@dels)) {
 3904:                             push(@saved,$curr);
 3905:                         }
 3906:                     }
 3907:                     $changed = 1;
 3908:                 } else {
 3909:                     @saved = @current;
 3910:                 }
 3911:             }
 3912:         }
 3913:     }
 3914:     if (@adds) {
 3915:         my $confname = &Apache::lonnet::get_domainconfiguser($env{'request.role.domain'});
 3916:         my %existing=&Apache::lonnet::dump('roles',$env{'request.role.domain'},
 3917:                                            $confname,'rolesdef_');
 3918:         foreach my $poss (@adds) {
 3919:             if (exists($existing{'rolesdef_'.$poss})) {
 3920:                 push(@added,$poss);
 3921:                 $changed = 1;
 3922:             }
 3923:         }
 3924:     }
 3925:     if (@added) {
 3926:         if (@saved) {
 3927:             foreach my $add (@added) {
 3928:                 unless (grep(/^\Q$add\E$/,@saved)) {
 3929:                     push(@alladhoc,$add);
 3930:                 }
 3931:             }
 3932:         } else {
 3933:             push(@alladhoc,@added);
 3934:         }
 3935:     }
 3936:     if (@saved) {
 3937:         push(@alladhoc,@saved);
 3938:     }
 3939:     if (@alladhoc) {
 3940:         my $adhocstr = join(',',sort(@alladhoc));
 3941:         $changehashref->{$adhoc_key} = $adhocstr;
 3942:     } elsif (@dels) {
 3943:         &Apache::lonnet::del('environment',[$adhoc_key],$env{'form.ccdomain'},$env{'form.ccuname'});
 3944:         delete($changehashref->{$adhoc_key});
 3945:         if (($env{'form.ccdomain'} eq $env{'user.domain'}) &&
 3946:             ($env{'form.ccuname'} eq $env{'user.name'})) {
 3947:             &Apache::lonnet::delenv($adhoc_key);
 3948:         }
 3949:     }
 3950:     return $changed;
 3951: }
 3952: 
 3953: sub update_roles {
 3954:     my ($r,$context,$showcredits) = @_;
 3955:     my $now=time;
 3956:     my @rolechanges;
 3957:     my %disallowed;
 3958:     $r->print('<h3>'.&mt('Modifying Roles').'</h3>');
 3959:     foreach my $key (keys(%env)) {
 3960: 	next if (! $env{$key});
 3961:         next if ($key eq 'form.action');
 3962: 	# Revoke roles
 3963: 	if ($key=~/^form\.rev/) {
 3964: 	    if ($key=~/^form\.rev\:([^\_]+)\_([^\_\.]+)$/) {
 3965: # Revoke standard role
 3966: 		my ($scope,$role) = ($1,$2);
 3967: 		my $result =
 3968: 		    &Apache::lonnet::revokerole($env{'form.ccdomain'},
 3969: 						$env{'form.ccuname'},
 3970: 						$scope,$role,'','',$context);
 3971:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
 3972:                             &mt('Revoking [_1] in [_2]',
 3973:                                 &Apache::lonnet::plaintext($role),
 3974:                                 &Apache::loncommon::show_role_extent($scope,$context,$role)),
 3975:                                 $result ne "ok").'<br />');
 3976:                 if ($result ne "ok") {
 3977:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 3978:                 }
 3979: 		if ($role eq 'st') {
 3980: 		    my $result = 
 3981:                         &Apache::lonuserutils::classlist_drop($scope,
 3982:                             $env{'form.ccuname'},$env{'form.ccdomain'},
 3983: 			    $now);
 3984:                     $r->print(&Apache::lonhtmlcommon::confirm_success($result));
 3985: 		}
 3986:                 if (!grep(/^\Q$role\E$/,@rolechanges)) {
 3987:                     push(@rolechanges,$role);
 3988:                 }
 3989: 	    }
 3990: 	    if ($key=~m{^form\.rev\:([^_]+)_cr\.cr/($match_domain)/($match_username)/(\w+)$}s) {
 3991: # Revoke custom role
 3992:                 my $result = &Apache::lonnet::revokecustomrole(
 3993:                     $env{'form.ccdomain'},$env{'form.ccuname'},$1,$2,$3,$4,'','',$context);
 3994:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
 3995:                             &mt('Revoking custom role [_1] by [_2] in [_3]',
 3996:                                 $4,$3.':'.$2,&Apache::loncommon::show_role_extent($1,$context,'cr')),
 3997:                             $result ne 'ok').'<br />');
 3998:                 if ($result ne "ok") {
 3999:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 4000:                 }
 4001:                 if (!grep(/^cr$/,@rolechanges)) {
 4002:                     push(@rolechanges,'cr');
 4003:                 }
 4004: 	    }
 4005: 	} elsif ($key=~/^form\.del/) {
 4006: 	    if ($key=~/^form\.del\:([^\_]+)\_([^\_\.]+)$/) {
 4007: # Delete standard role
 4008: 		my ($scope,$role) = ($1,$2);
 4009: 		my $result =
 4010: 		    &Apache::lonnet::assignrole($env{'form.ccdomain'},
 4011: 						$env{'form.ccuname'},
 4012: 						$scope,$role,$now,0,1,'',
 4013:                                                 $context);
 4014:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
 4015:                             &mt('Deleting [_1] in [_2]',
 4016:                                 &Apache::lonnet::plaintext($role),
 4017:                                 &Apache::loncommon::show_role_extent($scope,$context,$role)),
 4018:                             $result ne 'ok').'<br />');
 4019:                 if ($result ne "ok") {
 4020:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 4021:                 }
 4022: 
 4023: 		if ($role eq 'st') {
 4024: 		    my $result = 
 4025:                         &Apache::lonuserutils::classlist_drop($scope,
 4026:                             $env{'form.ccuname'},$env{'form.ccdomain'},
 4027: 			    $now);
 4028: 		    $r->print(&Apache::lonhtmlcommon::confirm_success($result));
 4029: 		}
 4030:                 if (!grep(/^\Q$role\E$/,@rolechanges)) {
 4031:                     push(@rolechanges,$role);
 4032:                 }
 4033:             }
 4034: 	    if ($key=~m{^form\.del\:([^_]+)_cr\.cr/($match_domain)/($match_username)/(\w+)$}) {
 4035:                 my ($url,$rdom,$rnam,$rolename) = ($1,$2,$3,$4);
 4036: # Delete custom role
 4037:                 my $result =
 4038:                     &Apache::lonnet::assigncustomrole($env{'form.ccdomain'},
 4039:                         $env{'form.ccuname'},$url,$rdom,$rnam,$rolename,$now,
 4040:                         0,1,$context);
 4041:                 $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('Deleting custom role [_1] by [_2] in [_3]',
 4042:                       $rolename,$rnam.':'.$rdom,&Apache::loncommon::show_role_extent($1,$context,'cr')),
 4043:                       $result ne "ok").'<br />');
 4044:                 if ($result ne "ok") {
 4045:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 4046:                 }
 4047: 
 4048:                 if (!grep(/^cr$/,@rolechanges)) {
 4049:                     push(@rolechanges,'cr');
 4050:                 }
 4051:             }
 4052: 	} elsif ($key=~/^form\.ren/) {
 4053:             my $udom = $env{'form.ccdomain'};
 4054:             my $uname = $env{'form.ccuname'};
 4055: # Re-enable standard role
 4056: 	    if ($key=~/^form\.ren\:([^\_]+)\_([^\_\.]+)$/) {
 4057:                 my $url = $1;
 4058:                 my $role = $2;
 4059:                 my $logmsg;
 4060:                 my $output;
 4061:                 if ($role eq 'st') {
 4062:                     if ($url =~ m-^/($match_domain)/($match_courseid)/?(\w*)$-) {
 4063:                         my ($cdom,$cnum,$csec) = ($1,$2,$3);
 4064:                         my $credits;
 4065:                         if ($showcredits) {
 4066:                             my $defaultcredits = 
 4067:                                 &Apache::lonuserutils::get_defaultcredits($cdom,$cnum);
 4068:                             $credits = &get_user_credits($defaultcredits,$cdom,$cnum);
 4069:                         }
 4070:                         my $result = &Apache::loncommon::commit_studentrole(\$logmsg,$udom,$uname,$url,$role,$now,0,$cdom,$cnum,$csec,$context,$credits);
 4071:                         if (($result =~ /^error/) || ($result eq 'not_in_class') || ($result eq 'unknown_course') || ($result eq 'refused')) {
 4072:                             if ($result eq 'refused' && $logmsg) {
 4073:                                 $output = $logmsg;
 4074:                             } else { 
 4075:                                 $output = &mt('Error: [_1]',$result)."\n";
 4076:                             }
 4077:                         } else {
 4078:                             $output = &Apache::lonhtmlcommon::confirm_success(&mt('Assigning [_1] in [_2] starting [_3]',
 4079:                                         &Apache::lonnet::plaintext($role),
 4080:                                         &Apache::loncommon::show_role_extent($url,$context,'st'),
 4081:                                         &Apache::lonlocal::locallocaltime($now))).'<br />'.$logmsg.'<br />';
 4082:                         }
 4083:                     }
 4084:                 } else {
 4085: 		    my $result=&Apache::lonnet::assignrole($env{'form.ccdomain'},
 4086:                                $env{'form.ccuname'},$url,$role,0,$now,'','',
 4087:                                $context);
 4088:                         $output = &Apache::lonhtmlcommon::confirm_success(&mt('Re-enabling [_1] in [_2]',
 4089:                                         &Apache::lonnet::plaintext($role),
 4090:                                         &Apache::loncommon::show_role_extent($url,$context,$role)),$result ne "ok").'<br />';
 4091:                     if ($result ne "ok") {
 4092:                         $output .= &mt('Error: [_1]',$result).'<br />';
 4093:                     }
 4094:                 }
 4095:                 $r->print($output);
 4096:                 if (!grep(/^\Q$role\E$/,@rolechanges)) {
 4097:                     push(@rolechanges,$role);
 4098:                 }
 4099: 	    }
 4100: # Re-enable custom role
 4101: 	    if ($key=~m{^form\.ren\:([^_]+)_cr\.cr/($match_domain)/($match_username)/(\w+)$}) {
 4102:                 my ($url,$rdom,$rnam,$rolename) = ($1,$2,$3,$4);
 4103:                 my $result = &Apache::lonnet::assigncustomrole(
 4104:                                $env{'form.ccdomain'}, $env{'form.ccuname'},
 4105:                                $url,$rdom,$rnam,$rolename,0,$now,undef,$context);
 4106:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
 4107:                     &mt('Re-enabling custom role [_1] by [_2] in [_3]',
 4108:                         $rolename,$rnam.':'.$rdom,&Apache::loncommon::show_role_extent($1,$context,'cr')),
 4109:                     $result ne "ok").'<br />');
 4110:                 if ($result ne "ok") {
 4111:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 4112:                 }
 4113:                 if (!grep(/^cr$/,@rolechanges)) {
 4114:                     push(@rolechanges,'cr');
 4115:                 }
 4116:             }
 4117: 	} elsif ($key=~/^form\.act/) {
 4118:             my $udom = $env{'form.ccdomain'};
 4119:             my $uname = $env{'form.ccuname'};
 4120: 	    if ($key=~/^form\.act\_($match_domain)\_($match_courseid)\_cr_cr_($match_domain)_($match_username)_([^\_]+)$/) {
 4121:                 # Activate a custom role
 4122: 		my ($one,$two,$three,$four,$five)=($1,$2,$3,$4,$5);
 4123: 		my $url='/'.$one.'/'.$two;
 4124: 		my $full=$one.'_'.$two.'_cr_cr_'.$three.'_'.$four.'_'.$five;
 4125: 
 4126:                 my $start = ( $env{'form.start_'.$full} ?
 4127:                               $env{'form.start_'.$full} :
 4128:                               $now );
 4129:                 my $end   = ( $env{'form.end_'.$full} ?
 4130:                               $env{'form.end_'.$full} :
 4131:                               0 );
 4132:                                                                                      
 4133:                 # split multiple sections
 4134:                 my %sections = ();
 4135:                 my $num_sections = &build_roles($env{'form.sec_'.$full},\%sections,$5);
 4136:                 if ($num_sections == 0) {
 4137:                     $r->print(&Apache::loncommon::commit_customrole($udom,$uname,$url,$three,$four,$five,$start,$end,$context));
 4138:                 } else {
 4139: 		    my %curr_groups =
 4140: 			&Apache::longroup::coursegroups($one,$two);
 4141:                     foreach my $sec (sort {$a cmp $b} keys(%sections)) {
 4142:                         if (($sec eq 'none') || ($sec eq 'all') || 
 4143:                             exists($curr_groups{$sec})) {
 4144:                             $disallowed{$sec} = $url;
 4145:                             next;
 4146:                         }
 4147:                         my $securl = $url.'/'.$sec;
 4148: 		        $r->print(&Apache::loncommon::commit_customrole($udom,$uname,$securl,$three,$four,$five,$start,$end,$context));
 4149:                     }
 4150:                 }
 4151:                 if (!grep(/^cr$/,@rolechanges)) {
 4152:                     push(@rolechanges,'cr');
 4153:                 }
 4154: 	    } elsif ($key=~/^form\.act\_($match_domain)\_($match_name)\_([^\_]+)$/) {
 4155: 		# Activate roles for sections with 3 id numbers
 4156: 		# set start, end times, and the url for the class
 4157: 		my ($one,$two,$three)=($1,$2,$3);
 4158: 		my $start = ( $env{'form.start_'.$one.'_'.$two.'_'.$three} ? 
 4159: 			      $env{'form.start_'.$one.'_'.$two.'_'.$three} : 
 4160: 			      $now );
 4161: 		my $end   = ( $env{'form.end_'.$one.'_'.$two.'_'.$three} ? 
 4162: 			      $env{'form.end_'.$one.'_'.$two.'_'.$three} :
 4163: 			      0 );
 4164: 		my $url='/'.$one.'/'.$two;
 4165:                 my $type = 'three';
 4166:                 # split multiple sections
 4167:                 my %sections = ();
 4168:                 my $num_sections = &build_roles($env{'form.sec_'.$one.'_'.$two.'_'.$three},\%sections,$three);
 4169:                 my $credits;
 4170:                 if ($three eq 'st') {
 4171:                     if ($showcredits) { 
 4172:                         my $defaultcredits = 
 4173:                             &Apache::lonuserutils::get_defaultcredits($one,$two);
 4174:                         $credits = $env{'form.credits_'.$one.'_'.$two.'_'.$three};
 4175:                         $credits =~ s/[^\d\.]//g;
 4176:                         if ($credits eq $defaultcredits) {
 4177:                             undef($credits);
 4178:                         }
 4179:                     }
 4180:                 }
 4181:                 if ($num_sections == 0) {
 4182:                     $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$three,$start,$end,$one,$two,'',$context,$credits));
 4183:                 } else {
 4184:                     my %curr_groups = 
 4185: 			&Apache::longroup::coursegroups($one,$two);
 4186:                     my $emptysec = 0;
 4187:                     foreach my $sec (sort {$a cmp $b} keys(%sections)) {
 4188:                         $sec =~ s/\W//g;
 4189:                         if ($sec ne '') {
 4190:                             if (($sec eq 'none') || ($sec eq 'all') || 
 4191:                                 exists($curr_groups{$sec})) {
 4192:                                 $disallowed{$sec} = $url;
 4193:                                 next;
 4194:                             }
 4195:                             my $securl = $url.'/'.$sec;
 4196:                             $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$securl,$three,$start,$end,$one,$two,$sec,$context,$credits));
 4197:                         } else {
 4198:                             $emptysec = 1;
 4199:                         }
 4200:                     }
 4201:                     if ($emptysec) {
 4202:                         $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$three,$start,$end,$one,$two,'',$context,$credits));
 4203:                     }
 4204:                 }
 4205:                 if (!grep(/^\Q$three\E$/,@rolechanges)) {
 4206:                     push(@rolechanges,$three);
 4207:                 }
 4208: 	    } elsif ($key=~/^form\.act\_([^\_]+)\_([^\_]+)$/) {
 4209: 		# Activate roles for sections with two id numbers
 4210: 		# set start, end times, and the url for the class
 4211: 		my $start = ( $env{'form.start_'.$1.'_'.$2} ? 
 4212: 			      $env{'form.start_'.$1.'_'.$2} : 
 4213: 			      $now );
 4214: 		my $end   = ( $env{'form.end_'.$1.'_'.$2} ? 
 4215: 			      $env{'form.end_'.$1.'_'.$2} :
 4216: 			      0 );
 4217:                 my $one = $1;
 4218:                 my $two = $2;
 4219: 		my $url='/'.$one.'/';
 4220:                 # split multiple sections
 4221:                 my %sections = ();
 4222:                 my $num_sections = &build_roles($env{'form.sec_'.$one.'_'.$two},\%sections,$two);
 4223:                 if ($num_sections == 0) {
 4224:                     $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$two,$start,$end,$one,undef,'',$context));
 4225:                 } else {
 4226:                     my $emptysec = 0;
 4227:                     foreach my $sec (sort {$a cmp $b} keys(%sections)) {
 4228:                         if ($sec ne '') {
 4229:                             my $securl = $url.'/'.$sec;
 4230:                             $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$securl,$two,$start,$end,$one,undef,$sec,$context));
 4231:                         } else {
 4232:                             $emptysec = 1;
 4233:                         }
 4234:                     }
 4235:                     if ($emptysec) {
 4236:                         $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$two,$start,$end,$one,undef,'',$context));
 4237:                     }
 4238:                 }
 4239:                 if (!grep(/^\Q$two\E$/,@rolechanges)) {
 4240:                     push(@rolechanges,$two);
 4241:                 }
 4242: 	    } else {
 4243: 		$r->print('<p><span class="LC_error">'.&mt('ERROR').': '.&mt('Unknown command').' <tt>'.$key.'</tt></span></p><br />');
 4244:             }
 4245:             foreach my $key (sort(keys(%disallowed))) {
 4246:                 $r->print('<p class="LC_warning">');
 4247:                 if (($key eq 'none') || ($key eq 'all')) {  
 4248:                     $r->print(&mt('[_1] may not be used as the name for a section, as it is a reserved word.','<tt>'.$key.'</tt>'));
 4249:                 } else {
 4250:                     $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>'));
 4251:                 }
 4252:                 $r->print('</p><p>'
 4253:                          .&mt('Please [_1]go back[_2] and choose a different section name.'
 4254:                              ,'<a href="javascript:history.go(-1)'
 4255:                              ,'</a>')
 4256:                          .'</p><br />'
 4257:                 );
 4258:             }
 4259: 	}
 4260:     } # End of foreach (keys(%env))
 4261: # Flush the course logs so reverse user roles immediately updated
 4262:     $r->register_cleanup(\&Apache::lonnet::flushcourselogs);
 4263:     if (@rolechanges == 0) {
 4264:         $r->print('<p>'.&mt('No roles to modify').'</p>');
 4265:     }
 4266:     return @rolechanges;
 4267: }
 4268: 
 4269: sub get_user_credits {
 4270:     my ($uname,$udom,$defaultcredits,$cdom,$cnum) = @_;
 4271:     if ($cdom eq '' || $cnum eq '') {
 4272:         return unless ($env{'request.course.id'});
 4273:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4274:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4275:     }
 4276:     my $credits;
 4277:     my %currhash =
 4278:         &Apache::lonnet::get('classlist',[$uname.':'.$udom],$cdom,$cnum);
 4279:     if (keys(%currhash) > 0) {
 4280:         my @items = split(/:/,$currhash{$uname.':'.$udom});
 4281:         my $crdidx = &Apache::loncoursedata::CL_CREDITS() - 3;
 4282:         $credits = $items[$crdidx];
 4283:         $credits =~ s/[^\d\.]//g;
 4284:     }
 4285:     if ($credits eq $defaultcredits) {
 4286:         undef($credits);
 4287:     }
 4288:     return $credits;
 4289: }
 4290: 
 4291: sub enroll_single_student {
 4292:     my ($r,$uhome,$amode,$genpwd,$now,$newuser,$context,$crstype,
 4293:         $showcredits,$defaultcredits) = @_;
 4294:     $r->print('<h3>');
 4295:     if ($crstype eq 'Community') {
 4296:         $r->print(&mt('Enrolling Member'));
 4297:     } else {
 4298:         $r->print(&mt('Enrolling Student'));
 4299:     }
 4300:     $r->print('</h3>');
 4301: 
 4302:     # Remove non alphanumeric values from section
 4303:     $env{'form.sections'}=~s/\W//g;
 4304: 
 4305:     my $credits;
 4306:     if (($showcredits) && ($env{'form.credits'} ne '')) {
 4307:         $credits = $env{'form.credits'};
 4308:         $credits =~ s/[^\d\.]//g;
 4309:         if ($credits ne '') {
 4310:             if ($credits eq $defaultcredits) {
 4311:                 undef($credits);
 4312:             }
 4313:         }
 4314:     }
 4315: 
 4316:     # Clean out any old student roles the user has in this class.
 4317:     &Apache::lonuserutils::modifystudent($env{'form.ccdomain'},
 4318:          $env{'form.ccuname'},$env{'request.course.id'},undef,$uhome);
 4319:     my ($startdate,$enddate) = &Apache::lonuserutils::get_dates_from_form();
 4320:     my $enroll_result =
 4321:         &Apache::lonnet::modify_student_enrollment($env{'form.ccdomain'},
 4322:             $env{'form.ccuname'},$env{'form.cid'},$env{'form.cfirstname'},
 4323:             $env{'form.cmiddlename'},$env{'form.clastname'},
 4324:             $env{'form.generation'},$env{'form.sections'},$enddate,
 4325:             $startdate,'manual',undef,$env{'request.course.id'},'',$context,
 4326:             $credits);
 4327:     if ($enroll_result =~ /^ok/) {
 4328:         $r->print(&mt('[_1] enrolled','<b>'.$env{'form.ccuname'}.':'.$env{'form.ccdomain'}.'</b>'));
 4329:         if ($env{'form.sections'} ne '') {
 4330:             $r->print(' '.&mt('in section [_1]',$env{'form.sections'}));
 4331:         }
 4332:         my ($showstart,$showend);
 4333:         if ($startdate <= $now) {
 4334:             $showstart = &mt('Access starts immediately');
 4335:         } else {
 4336:             $showstart = &mt('Access starts: ').&Apache::lonlocal::locallocaltime($startdate);
 4337:         }
 4338:         if ($enddate == 0) {
 4339:             $showend = &mt('ends: no ending date');
 4340:         } else {
 4341:             $showend = &mt('ends: ').&Apache::lonlocal::locallocaltime($enddate);
 4342:         }
 4343:         $r->print('.<br />'.$showstart.'; '.$showend);
 4344:         if ($startdate <= $now && !$newuser) {
 4345:             $r->print('<p class="LC_info">');
 4346:             if ($crstype eq 'Community') {
 4347:                 $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.'));
 4348:             } else {
 4349:                 $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.'));
 4350:            }
 4351:            $r->print('</p>');
 4352:         }
 4353:     } else {
 4354:         $r->print(&mt('unable to enroll').": ".$enroll_result);
 4355:     }
 4356:     return;
 4357: }
 4358: 
 4359: sub get_defaultquota_text {
 4360:     my ($settingstatus) = @_;
 4361:     my $defquotatext; 
 4362:     if ($settingstatus eq '') {
 4363:         $defquotatext = &mt('default');
 4364:     } else {
 4365:         my ($usertypes,$order) =
 4366:             &Apache::lonnet::retrieve_inst_usertypes($env{'form.ccdomain'});
 4367:         if ($usertypes->{$settingstatus} eq '') {
 4368:             $defquotatext = &mt('default');
 4369:         } else {
 4370:             $defquotatext = &mt('default for [_1]',$usertypes->{$settingstatus});
 4371:         }
 4372:     }
 4373:     return $defquotatext;
 4374: }
 4375: 
 4376: sub update_result_form {
 4377:     my ($uhome) = @_;
 4378:     my $outcome = 
 4379:     '<form name="userupdate" method="post" action="">'."\n";
 4380:     foreach my $item ('srchby','srchin','srchtype','srchterm','srchdomain','ccuname','ccdomain') {
 4381:         $outcome .= '<input type="hidden" name="'.$item.'" value="'.$env{'form.'.$item}.'" />'."\n";
 4382:     }
 4383:     if ($env{'form.origname'} ne '') {
 4384:         $outcome .= '<input type="hidden" name="origname" value="'.$env{'form.origname'}.'" />'."\n";
 4385:     }
 4386:     foreach my $item ('sortby','seluname','seludom') {
 4387:         if (exists($env{'form.'.$item})) {
 4388:             $outcome .= '<input type="hidden" name="'.$item.'" value="'.$env{'form.'.$item}.'" />'."\n";
 4389:         }
 4390:     }
 4391:     if ($uhome eq 'no_host') {
 4392:         $outcome .= '<input type="hidden" name="forcenewuser" value="1" />'."\n";
 4393:     }
 4394:     $outcome .= '<input type="hidden" name="phase" value="" />'."\n".
 4395:                 '<input type="hidden" name="currstate" value="" />'."\n".
 4396:                 '<input type="hidden" name="action" value="'.$env{'form.action'}.'" />'."\n".
 4397:                 '</form>';
 4398:     return $outcome;
 4399: }
 4400: 
 4401: sub quota_admin {
 4402:     my ($setquota,$changeHash,$name) = @_;
 4403:     my $quotachanged;
 4404:     if (&Apache::lonnet::allowed('mpq',$env{'form.ccdomain'})) {
 4405:         # Current user has quota modification privileges
 4406:         if (ref($changeHash) eq 'HASH') {
 4407:             $quotachanged = 1;
 4408:             $changeHash->{$name.'quota'} = $setquota;
 4409:         }
 4410:     }
 4411:     return $quotachanged;
 4412: }
 4413: 
 4414: sub tool_admin {
 4415:     my ($tool,$settool,$changeHash,$context) = @_;
 4416:     my $canchange = 0; 
 4417:     if ($context eq 'requestcourses') {
 4418:         if (&Apache::lonnet::allowed('ccc',$env{'form.ccdomain'})) {
 4419:             $canchange = 1;
 4420:         }
 4421:     } elsif ($context eq 'reqcrsotherdom') {
 4422:         if (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) {
 4423:             $canchange = 1;
 4424:         }
 4425:     } elsif ($context eq 'requestauthor') {
 4426:         if (&Apache::lonnet::allowed('cau',$env{'request.role.domain'})) {
 4427:             $canchange = 1;
 4428:         }
 4429:     } elsif (&Apache::lonnet::allowed('mut',$env{'form.ccdomain'})) {
 4430:         # Current user has quota modification privileges
 4431:         $canchange = 1;
 4432:     }
 4433:     my $toolchanged;
 4434:     if ($canchange) {
 4435:         if (ref($changeHash) eq 'HASH') {
 4436:             $toolchanged = 1;
 4437:             if ($tool eq 'requestauthor') {
 4438:                 $changeHash->{$context} = $settool;
 4439:             } else {
 4440:                 $changeHash->{$context.'.'.$tool} = $settool;
 4441:             }
 4442:         }
 4443:     }
 4444:     return $toolchanged;
 4445: }
 4446: 
 4447: sub build_roles {
 4448:     my ($sectionstr,$sections,$role) = @_;
 4449:     my $num_sections = 0;
 4450:     if ($sectionstr=~ /,/) {
 4451:         my @secnums = split/,/,$sectionstr;
 4452:         if ($role eq 'st') {
 4453:             $secnums[0] =~ s/\W//g;
 4454:             $$sections{$secnums[0]} = 1;
 4455:             $num_sections = 1;
 4456:         } else {
 4457:             foreach my $sec (@secnums) {
 4458:                 $sec =~ ~s/\W//g;
 4459:                 if (!($sec eq "")) {
 4460:                     if (exists($$sections{$sec})) {
 4461:                         $$sections{$sec} ++;
 4462:                     } else {
 4463:                         $$sections{$sec} = 1;
 4464:                         $num_sections ++;
 4465:                     }
 4466:                 }
 4467:             }
 4468:         }
 4469:     } else {
 4470:         $sectionstr=~s/\W//g;
 4471:         unless ($sectionstr eq '') {
 4472:             $$sections{$sectionstr} = 1;
 4473:             $num_sections ++;
 4474:         }
 4475:     }
 4476: 
 4477:     return $num_sections;
 4478: }
 4479: 
 4480: # ========================================================== Custom Role Editor
 4481: 
 4482: sub custom_role_editor {
 4483:     my ($r,$brcrum,$prefix) = @_;
 4484:     my $action = $env{'form.customroleaction'};
 4485:     my $rolename; 
 4486:     if ($action eq 'new') {
 4487:         $rolename=$env{'form.newrolename'};
 4488:     } else {
 4489:         $rolename=$env{'form.rolename'};
 4490:     }
 4491: 
 4492:     my ($crstype,$context);
 4493:     if ($env{'request.course.id'}) {
 4494:         $crstype = &Apache::loncommon::course_type();
 4495:         $context = 'course';
 4496:     } else {
 4497:         $context = 'domain';
 4498:         $crstype = 'course';
 4499:     }
 4500: 
 4501:     $rolename=~s/[^A-Za-z0-9]//gs;
 4502:     if (!$rolename || $env{'form.phase'} eq 'pickrole') {
 4503: 	&print_username_entry_form($r,undef,undef,undef,undef,$crstype,$brcrum);
 4504:         return;
 4505:     }
 4506: 
 4507:     my $formname = 'form1';
 4508:     my %privs=();
 4509:     my $body_top = '<h2>';
 4510: # ------------------------------------------------------- Does this role exist?
 4511:     my ($rdummy,$roledef)=
 4512: 			 &Apache::lonnet::get('roles',["rolesdef_$rolename"]);
 4513:     if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 4514:         $body_top .= &mt('Existing Role').' "';
 4515: # ------------------------------------------------- Get current role privileges
 4516:         ($privs{'system'},$privs{'domain'},$privs{'course'})=split(/\_/,$roledef);
 4517:         if ($privs{'system'} =~ /bre\&S/) {
 4518:             if ($context eq 'domain') {
 4519:                 $crstype = 'Course';
 4520:             } elsif ($crstype eq 'Community') {
 4521:                 $privs{'system'} =~ s/bre\&S//;
 4522:             }
 4523:         } elsif ($context eq 'domain') {
 4524:             $crstype = 'Course';
 4525:         }
 4526:     } else {
 4527:         $body_top .= &mt('New Role').' "';
 4528:         $roledef='';
 4529:     }
 4530:     $body_top .= $rolename.'"</h2>';
 4531: 
 4532: # ------------------------------------------------------- What can be assigned?
 4533:     my %full=();
 4534:     my %levels=(
 4535:                  course => {},
 4536:                  domain => {},
 4537:                  system => {},
 4538:                );
 4539:     my %levelscurrent=(
 4540:                         course => {},
 4541:                         domain => {},
 4542:                         system => {},
 4543:                       );
 4544:     &Apache::lonuserutils::custom_role_privs(\%privs,\%full,\%levels,\%levelscurrent);
 4545:     my ($jsback,$elements) = &crumb_utilities();
 4546:     my @templateroles = &Apache::lonuserutils::custom_template_roles($context,$crstype);
 4547:     my $head_script =
 4548:         &Apache::lonuserutils::custom_roledefs_js($context,$crstype,$formname,
 4549:                                                   \%full,\@templateroles,$jsback);
 4550:     push (@{$brcrum},
 4551:               {href => "javascript:backPage(document.$formname,'pickrole','')",
 4552:                text => "Pick custom role",
 4553:                faq  => 282,bug=>'Instructor Interface',},
 4554:               {href => "javascript:backPage(document.$formname,'','')",
 4555:                text => "Edit custom role",
 4556:                faq  => 282,
 4557:                bug  => 'Instructor Interface',
 4558:                help => 'Course_Editing_Custom_Roles'}
 4559:               );
 4560:     my $args = { bread_crumbs          => $brcrum,
 4561:                  bread_crumbs_component => 'User Management'};
 4562:  
 4563:     $r->print(&Apache::loncommon::start_page('Custom Role Editor',
 4564:                                              $head_script,$args).
 4565:               $body_top);
 4566:     $r->print('<form name="'.$formname.'" method="post" action="">'."\n".
 4567:               &Apache::lonuserutils::custom_role_header($context,$crstype,
 4568:                                                         \@templateroles,$prefix));
 4569: 
 4570:     $r->print(<<ENDCCF);
 4571: <input type="hidden" name="phase" value="set_custom_roles" />
 4572: <input type="hidden" name="rolename" value="$rolename" />
 4573: ENDCCF
 4574:     $r->print(&Apache::lonuserutils::custom_role_table($crstype,\%full,\%levels,
 4575:                                                        \%levelscurrent,$prefix));
 4576:     $r->print(&Apache::loncommon::end_data_table().
 4577:    '<input type="hidden" name="action" value="'.$env{'form.action'}.'" />'.
 4578:    '<input type="hidden" name="startrolename" value="'.$env{'form.rolename'}.
 4579:    '" />'."\n".'<input type="hidden" name="currstate" value="" />'."\n".
 4580:    '<input type="reset" value="'.&mt("Reset").'" />'."\n".
 4581:    '<input type="submit" value="'.&mt('Save').'" /></form>');
 4582: }
 4583: 
 4584: # ---------------------------------------------------------- Call to definerole
 4585: sub set_custom_role {
 4586:     my ($r,$context,$brcrum,$prefix) = @_;
 4587:     my $rolename=$env{'form.rolename'};
 4588:     $rolename=~s/[^A-Za-z0-9]//gs;
 4589:     if (!$rolename) {
 4590: 	&custom_role_editor($r,$brcrum,$prefix);
 4591:         return;
 4592:     }
 4593:     my ($jsback,$elements) = &crumb_utilities();
 4594:     my $jscript = '<script type="text/javascript">'
 4595:                  .'// <![CDATA['."\n"
 4596:                  .$jsback."\n"
 4597:                  .'// ]]>'."\n"
 4598:                  .'</script>'."\n";
 4599:     push(@{$brcrum},
 4600:         {href => "javascript:backPage(document.customresult,'pickrole','')",
 4601:          text => "Pick custom role",
 4602:          faq  => 282,
 4603:          bug  => 'Instructor Interface',},
 4604:         {href => "javascript:backPage(document.customresult,'selected_custom_edit','')",
 4605:          text => "Edit custom role",
 4606:          faq  => 282,
 4607:          bug  => 'Instructor Interface',},
 4608:         {href => "javascript:backPage(document.customresult,'set_custom_roles','')",
 4609:          text => "Result",
 4610:          faq  => 282,
 4611:          bug  => 'Instructor Interface',
 4612:          help => 'Course_Editing_Custom_Roles'},
 4613:         );
 4614:     my $args = { bread_crumbs           => $brcrum,
 4615:                  bread_crumbs_component => 'User Management'};
 4616:     $r->print(&Apache::loncommon::start_page('Save Custom Role',$jscript,$args));
 4617: 
 4618:     my $newrole;
 4619:     my ($rdummy,$roledef)=
 4620: 	&Apache::lonnet::get('roles',["rolesdef_$rolename"]);
 4621: 
 4622: # ------------------------------------------------------- Does this role exist?
 4623:     $r->print('<h3>');
 4624:     if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 4625: 	$r->print(&mt('Existing Role').' "');
 4626:     } else {
 4627: 	$r->print(&mt('New Role').' "');
 4628: 	$roledef='';
 4629:         $newrole = 1;
 4630:     }
 4631:     $r->print($rolename.'"</h3>');
 4632: # ------------------------------------------------- Assign role and show result
 4633: 
 4634:     my $errmsg;
 4635:     my %newprivs = &Apache::lonuserutils::custom_role_update($rolename,$prefix);
 4636:     # Assign role and return result
 4637:     my $result = &Apache::lonnet::definerole($rolename,$newprivs{'s'},$newprivs{'d'},
 4638:                                              $newprivs{'c'});
 4639:     if ($result ne 'ok') {
 4640:         $errmsg = ': '.$result;
 4641:     }
 4642:     my $message =
 4643:         &Apache::lonhtmlcommon::confirm_success(
 4644:             &mt('Defining Role').$errmsg, ($result eq 'ok' ? 0 : 1));
 4645:     if ($env{'request.course.id'}) {
 4646:         my $url='/'.$env{'request.course.id'};
 4647:         $url=~s/\_/\//g;
 4648:         $result =
 4649:             &Apache::lonnet::assigncustomrole(
 4650:                 $env{'user.domain'},$env{'user.name'},
 4651:                 $url,
 4652:                 $env{'user.domain'},$env{'user.name'},
 4653:                 $rolename,undef,undef,undef,$context);
 4654:         if ($result ne 'ok') {
 4655:             $errmsg = ': '.$result;
 4656:         }
 4657:         $message .=
 4658:             '<br />'
 4659:            .&Apache::lonhtmlcommon::confirm_success(
 4660:                 &mt('Assigning Role to Self').$errmsg, ($result eq 'ok' ? 0 : 1));
 4661:     }
 4662:     $r->print(
 4663:         &Apache::loncommon::confirmwrapper($message)
 4664:        .'<br />'
 4665:        .&Apache::lonhtmlcommon::actionbox([
 4666:             '<a href="javascript:backPage(document.customresult,'."'pickrole'".')">'
 4667:            .&mt('Create or edit another custom role')
 4668:            .'</a>'])
 4669:        .'<form name="customresult" method="post" action="">'
 4670:        .&Apache::lonhtmlcommon::echo_form_input([])
 4671:        .'</form>'
 4672:     );
 4673: }
 4674: 
 4675: # ================================================================ Main Handler
 4676: sub handler {
 4677:     my $r = shift;
 4678:     if ($r->header_only) {
 4679:        &Apache::loncommon::content_type($r,'text/html');
 4680:        $r->send_http_header;
 4681:        return OK;
 4682:     }
 4683:     my ($context,$crstype);
 4684:     if ($env{'request.course.id'}) {
 4685:         $context = 'course';
 4686:         $crstype = &Apache::loncommon::course_type();
 4687:     } elsif ($env{'request.role'} =~ /^au\./) {
 4688:         $context = 'author';
 4689:     } else {
 4690:         $context = 'domain';
 4691:     }
 4692: 
 4693:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 4694:         ['action','state','callingform','roletype','showrole','bulkaction','popup','phase',
 4695:          'username','domain','srchterm','srchdomain','srchin','srchby','srchtype','queue']);
 4696:     &Apache::lonhtmlcommon::clear_breadcrumbs();
 4697:     my $args;
 4698:     my $brcrum = [];
 4699:     my $bread_crumbs_component = 'User Management';
 4700:     if (($env{'form.action'} ne 'dateselect') && ($env{'form.action'} ne 'displayuserreq')) {
 4701:         $brcrum = [{href=>"/adm/createuser",
 4702:                     text=>"User Management",
 4703:                     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'}
 4704:                   ];
 4705:     }
 4706:     #SD Following files not added to help, because the corresponding .tex-files seem to
 4707:     #be missing: Course_Approve_Selfenroll,Course_User_Logs,
 4708:     my ($permission,$allowed) = 
 4709:         &Apache::lonuserutils::get_permission($context,$crstype);
 4710:     if (!$allowed) {
 4711:         if ($context eq 'course') {
 4712:             $r->internal_redirect('/adm/viewclasslist');
 4713:             return OK;
 4714:         }
 4715:         $env{'user.error.msg'}=
 4716:             "/adm/createuser:cst:0:0:Cannot create/modify user data ".
 4717:                                  "or view user status.";
 4718:         return HTTP_NOT_ACCEPTABLE;
 4719:     }
 4720: 
 4721:     &Apache::loncommon::content_type($r,'text/html');
 4722:     $r->send_http_header;
 4723: 
 4724:     my $showcredits;
 4725:     if ((($context eq 'course') && ($crstype eq 'Course')) || 
 4726:          ($context eq 'domain')) {
 4727:         my %domdefaults = 
 4728:             &Apache::lonnet::get_domain_defaults($env{'request.role.domain'});
 4729:         if ($domdefaults{'officialcredits'} || $domdefaults{'unofficialcredits'}) {
 4730:             $showcredits = 1;
 4731:         }
 4732:     }
 4733: 
 4734:     # Main switch on form.action and form.state, as appropriate
 4735:     if (! exists($env{'form.action'})) {
 4736:         $args = {bread_crumbs => $brcrum,
 4737:                  bread_crumbs_component => $bread_crumbs_component}; 
 4738:         $r->print(&header(undef,$args));
 4739:         $r->print(&print_main_menu($permission,$context,$crstype));
 4740:     } elsif ($env{'form.action'} eq 'upload' && $permission->{'cusr'}) {
 4741:         push(@{$brcrum},
 4742:               { href => '/adm/createuser?action=upload&state=',
 4743:                 text => 'Upload Users List',
 4744:                 help => 'Course_Create_Class_List',
 4745:               });
 4746:         $bread_crumbs_component = 'Upload Users List';
 4747:         $args = {bread_crumbs           => $brcrum,
 4748:                  bread_crumbs_component => $bread_crumbs_component};
 4749:         $r->print(&header(undef,$args));
 4750:         $r->print('<form name="studentform" method="post" '.
 4751:                   'enctype="multipart/form-data" '.
 4752:                   ' action="/adm/createuser">'."\n");
 4753:         if (! exists($env{'form.state'})) {
 4754:             &Apache::lonuserutils::print_first_users_upload_form($r,$context);
 4755:         } elsif ($env{'form.state'} eq 'got_file') {
 4756:             &Apache::lonuserutils::print_upload_manager_form($r,$context,$permission,
 4757:                                                              $crstype,$showcredits);
 4758:         } elsif ($env{'form.state'} eq 'enrolling') {
 4759:             if ($env{'form.datatoken'}) {
 4760:                 &Apache::lonuserutils::upfile_drop_add($r,$context,$permission,
 4761:                                                        $showcredits);
 4762:             }
 4763:         } else {
 4764:             &Apache::lonuserutils::print_first_users_upload_form($r,$context);
 4765:         }
 4766:     } elsif (((($env{'form.action'} eq 'singleuser') || ($env{'form.action'}
 4767:               eq 'singlestudent')) && ($permission->{'cusr'})) ||
 4768:              (($env{'form.action'} eq 'singleuser') && ($permission->{'view'})) ||
 4769:              (($env{'form.action'} eq 'accesslogs') && ($permission->{'activity'}))) {
 4770:         my $phase = $env{'form.phase'};
 4771:         my @search = ('srchterm','srchby','srchin','srchtype','srchdomain');
 4772: 	&Apache::loncreateuser::restore_prev_selections();
 4773: 	my $srch;
 4774: 	foreach my $item (@search) {
 4775: 	    $srch->{$item} = $env{'form.'.$item};
 4776: 	}
 4777:         if (($phase eq 'get_user_info') || ($phase eq 'userpicked') ||
 4778:             ($phase eq 'createnewuser') || ($phase eq 'activity')) {
 4779:             if ($env{'form.phase'} eq 'createnewuser') {
 4780:                 my $response;
 4781:                 if ($env{'form.srchterm'} !~ /^$match_username$/) {
 4782:                     my $response =
 4783:                         '<span class="LC_warning">'
 4784:                        .&mt('You must specify a valid username. Only the following are allowed:'
 4785:                            .' letters numbers - . @')
 4786:                        .'</span>';
 4787:                     $env{'form.phase'} = '';
 4788:                     &print_username_entry_form($r,$context,$response,$srch,undef,
 4789:                                                $crstype,$brcrum,$showcredits);
 4790:                 } else {
 4791:                     my $ccuname =&LONCAPA::clean_username($srch->{'srchterm'});
 4792:                     my $ccdomain=&LONCAPA::clean_domain($srch->{'srchdomain'});
 4793:                     &print_user_modification_page($r,$ccuname,$ccdomain,
 4794:                                                   $srch,$response,$context,
 4795:                                                   $permission,$crstype,$brcrum,
 4796:                                                   $showcredits);
 4797:                 }
 4798:             } elsif ($env{'form.phase'} eq 'get_user_info') {
 4799:                 my ($currstate,$response,$forcenewuser,$results) = 
 4800:                     &user_search_result($context,$srch);
 4801:                 if ($env{'form.currstate'} eq 'modify') {
 4802:                     $currstate = $env{'form.currstate'};
 4803:                 }
 4804:                 if ($currstate eq 'select') {
 4805:                     &print_user_selection_page($r,$response,$srch,$results,
 4806:                                                \@search,$context,undef,$crstype,
 4807:                                                $brcrum);
 4808:                 } elsif (($currstate eq 'modify') || ($env{'form.action'} eq 'accesslogs')) {
 4809:                     my ($ccuname,$ccdomain,$uhome);
 4810:                     if (($srch->{'srchby'} eq 'uname') && 
 4811:                         ($srch->{'srchtype'} eq 'exact')) {
 4812:                         $ccuname = $srch->{'srchterm'};
 4813:                         $ccdomain= $srch->{'srchdomain'};
 4814:                     } else {
 4815:                         my @matchedunames = keys(%{$results});
 4816:                         ($ccuname,$ccdomain) = split(/:/,$matchedunames[0]);
 4817:                     }
 4818:                     $ccuname =&LONCAPA::clean_username($ccuname);
 4819:                     $ccdomain=&LONCAPA::clean_domain($ccdomain);
 4820:                     if ($env{'form.action'} eq 'accesslogs') {
 4821:                         my $uhome;
 4822:                         if (($ccuname ne '') && ($ccdomain ne '')) {
 4823:                            $uhome = &Apache::lonnet::homeserver($ccuname,$ccdomain);
 4824:                         }
 4825:                         if (($uhome eq '') || ($uhome eq 'no_host')) {
 4826:                             $env{'form.phase'} = '';
 4827:                             undef($forcenewuser);
 4828:                             #if ($response) {
 4829:                             #    unless ($response =~ m{\Q<br /><br />\E$}) {
 4830:                             #        $response .= '<br /><br />';
 4831:                             #    }
 4832:                             #}
 4833:                             &print_username_entry_form($r,$context,$response,$srch,
 4834:                                                        $forcenewuser,$crstype,$brcrum);
 4835:                         } else {
 4836:                             &print_useraccesslogs_display($r,$ccuname,$ccdomain,$permission,$brcrum);
 4837:                         }
 4838:                     } else {
 4839:                         if ($env{'form.forcenewuser'}) {
 4840:                             $response = '';
 4841:                         }
 4842:                         &print_user_modification_page($r,$ccuname,$ccdomain,
 4843:                                                       $srch,$response,$context,
 4844:                                                       $permission,$crstype,$brcrum);
 4845:                     }
 4846:                 } elsif ($currstate eq 'query') {
 4847:                     &print_user_query_page($r,'createuser',$brcrum);
 4848:                 } else {
 4849:                     $env{'form.phase'} = '';
 4850:                     &print_username_entry_form($r,$context,$response,$srch,
 4851:                                                $forcenewuser,$crstype,$brcrum);
 4852:                 }
 4853:             } elsif ($env{'form.phase'} eq 'userpicked') {
 4854:                 my $ccuname = &LONCAPA::clean_username($env{'form.seluname'});
 4855:                 my $ccdomain = &LONCAPA::clean_domain($env{'form.seludom'});
 4856:                 if ($env{'form.action'} eq 'accesslogs') {
 4857:                     &print_useraccesslogs_display($r,$ccuname,$ccdomain,$permission,$brcrum);
 4858:                 } else {
 4859:                     &print_user_modification_page($r,$ccuname,$ccdomain,$srch,'',
 4860:                                                   $context,$permission,$crstype,
 4861:                                                   $brcrum);
 4862:                 }
 4863:             } elsif ($env{'form.action'} eq 'accesslogs') {
 4864:                 my $ccuname = &LONCAPA::clean_username($env{'form.accessuname'});
 4865:                 my $ccdomain = &LONCAPA::clean_domain($env{'form.accessudom'});
 4866:                 &print_useraccesslogs_display($r,$ccuname,$ccdomain,$permission,$brcrum);
 4867:             }
 4868:         } elsif ($env{'form.phase'} eq 'update_user_data') {
 4869:             &update_user_data($r,$context,$crstype,$brcrum,$showcredits);
 4870:         } else {
 4871:             &print_username_entry_form($r,$context,undef,$srch,undef,$crstype,
 4872:                                        $brcrum);
 4873:         }
 4874:     } elsif ($env{'form.action'} eq 'custom' && $permission->{'custom'}) {
 4875:         my $prefix;
 4876:         if ($env{'form.phase'} eq 'set_custom_roles') {
 4877:             &set_custom_role($r,$context,$brcrum,$prefix);
 4878:         } else {
 4879:             &custom_role_editor($r,$brcrum,$prefix);
 4880:         }
 4881:     } elsif (($env{'form.action'} eq 'processauthorreq') &&
 4882:              ($permission->{'cusr'}) && 
 4883:              (&Apache::lonnet::allowed('cau',$env{'request.role.domain'}))) {
 4884:         push(@{$brcrum},
 4885:                  {href => '/adm/createuser?action=processauthorreq',
 4886:                   text => 'Authoring Space requests',
 4887:                   help => 'Domain_Role_Approvals'});
 4888:         $bread_crumbs_component = 'Authoring requests';
 4889:         if ($env{'form.state'} eq 'done') {
 4890:             push(@{$brcrum},
 4891:                      {href => '/adm/createuser?action=authorreqqueue',
 4892:                       text => 'Result',
 4893:                       help => 'Domain_Role_Approvals'});
 4894:             $bread_crumbs_component = 'Authoring request result';
 4895:         }
 4896:         $args = { bread_crumbs           => $brcrum,
 4897:                   bread_crumbs_component => $bread_crumbs_component};
 4898:         my $js = &usernamerequest_javascript();
 4899:         $r->print(&header(&add_script($js),$args));
 4900:         if (!exists($env{'form.state'})) {
 4901:             $r->print(&Apache::loncoursequeueadmin::display_queued_requests('requestauthor',
 4902:                                                                             $env{'request.role.domain'}));
 4903:         } elsif ($env{'form.state'} eq 'done') {
 4904:             $r->print('<h3>'.&mt('Authoring request processing').'</h3>'."\n");
 4905:             $r->print(&Apache::loncoursequeueadmin::update_request_queue('requestauthor',
 4906:                                                                          $env{'request.role.domain'}));
 4907:         }
 4908:     } elsif (($env{'form.action'} eq 'processusernamereq') &&
 4909:              ($permission->{'cusr'}) &&
 4910:              (&Apache::lonnet::allowed('cau',$env{'request.role.domain'}))) {
 4911:         push(@{$brcrum},
 4912:                  {href => '/adm/createuser?action=processusernamereq',
 4913:                   text => 'LON-CAPA account requests',
 4914:                   help => 'Domain_Username_Approvals'});
 4915:         $bread_crumbs_component = 'Account requests';
 4916:         if ($env{'form.state'} eq 'done') {
 4917:             push(@{$brcrum},
 4918:                      {href => '/adm/createuser?action=usernamereqqueue',
 4919:                       text => 'Result',
 4920:                       help => 'Domain_Username_Approvals'});
 4921:             $bread_crumbs_component = 'LON-CAPA account request result';
 4922:         }
 4923:         $args = { bread_crumbs           => $brcrum,
 4924:                   bread_crumbs_component => $bread_crumbs_component};
 4925:         my $js = &usernamerequest_javascript();
 4926:         $r->print(&header(&add_script($js),$args));
 4927:         if (!exists($env{'form.state'})) {
 4928:             $r->print(&Apache::loncoursequeueadmin::display_queued_requests('requestusername',
 4929:                                                                             $env{'request.role.domain'}));
 4930:         } elsif ($env{'form.state'} eq 'done') {
 4931:             $r->print('<h3>'.&mt('LON-CAPA account request processing').'</h3>'."\n");
 4932:             $r->print(&Apache::loncoursequeueadmin::update_request_queue('requestusername',
 4933:                                                                          $env{'request.role.domain'}));
 4934:         }
 4935:     } elsif (($env{'form.action'} eq 'displayuserreq') &&
 4936:              ($permission->{'cusr'})) {
 4937:         my $dom = $env{'form.domain'};
 4938:         my $uname = $env{'form.username'};
 4939:         my $warning;
 4940:         if (($dom =~ /^$match_domain$/) && (&Apache::lonnet::domain($dom) ne '')) {
 4941:             if (($dom eq $env{'request.role.domain'}) && (&Apache::lonnet::allowed('ccc',$dom))) {
 4942:                 if (($uname =~ /^$match_username$/) && ($env{'form.queue'} eq 'approval')) {
 4943:                     my $uhome = &Apache::lonnet::homeserver($uname,$dom);
 4944:                     if ($uhome eq 'no_host') {
 4945:                         my $queue = $env{'form.queue'};
 4946:                         my $reqkey = &escape($uname).'_'.$queue; 
 4947:                         my $namespace = 'usernamequeue';
 4948:                         my $domconfig = &Apache::lonnet::get_domainconfiguser($dom);
 4949:                         my %queued =
 4950:                             &Apache::lonnet::get($namespace,[$reqkey],$dom,$domconfig);
 4951:                         unless ($queued{$reqkey}) {
 4952:                             $warning = &mt('No information was found for this LON-CAPA account request.');
 4953:                         }
 4954:                     } else {
 4955:                         $warning = &mt('A LON-CAPA account already exists for the requested username and domain.');
 4956:                     }
 4957:                 } else {
 4958:                     $warning = &mt('LON-CAPA account request status check is for an invalid username.');
 4959:                 }
 4960:             } else {
 4961:                 $warning = &mt('You do not have rights to view LON-CAPA account requests in the domain specified.');
 4962:             }
 4963:         } else {
 4964:             $warning = &mt('LON-CAPA account request status check is for an invalid domain.');
 4965:         }
 4966:         my $args = { only_body => 1 };
 4967:         $r->print(&header(undef,$args).
 4968:                   '<h3>'.&mt('LON-CAPA Account Request Details').'</h3>');
 4969:         if ($warning ne '') {
 4970:             $r->print('<div class="LC_warning">'.$warning.'</div>');
 4971:         } else {
 4972:             my ($infofields,$infotitles) = &Apache::loncommon::emailusername_info();
 4973:             my $domconfiguser = &Apache::lonnet::get_domainconfiguser($dom);
 4974:             my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 4975:             if (ref($domconfig{'usercreation'}) eq 'HASH') {
 4976:                 if (ref($domconfig{'usercreation'}{'cancreate'}) eq 'HASH') {
 4977:                     if (ref($domconfig{'usercreation'}{'cancreate'}{'emailusername'}) eq 'HASH') {
 4978:                         my %info =
 4979:                             &Apache::lonnet::get('nohist_requestedusernames',[$uname],$dom,$domconfiguser);
 4980:                         if (ref($info{$uname}) eq 'HASH') {
 4981:                             my $usertype = $info{$uname}{'inststatus'};
 4982:                             unless ($usertype) {
 4983:                                 $usertype = 'default';
 4984:                             }
 4985:                             if (ref($domconfig{'usercreation'}{'cancreate'}{'emailusername'}{$usertype}) eq 'HASH') {
 4986:                                 if ((ref($infofields) eq 'ARRAY') && (ref($infotitles) eq 'HASH')) {
 4987:                                     $r->print('<div>'.&Apache::lonhtmlcommon::start_pick_box());
 4988:                                     my ($num,$count,$showstatus);
 4989:                                     $count = scalar(keys(%{$domconfig{'usercreation'}{'cancreate'}{'emailusername'}{$usertype}}));
 4990:                                     unless ($usertype eq 'default') {
 4991:                                         my ($othertitle,$usertypes,$types) = 
 4992:                                             &Apache::loncommon::sorted_inst_types($dom);
 4993:                                         if (ref($usertypes) eq 'HASH') {
 4994:                                             if ($usertypes->{$usertype}) {
 4995:                                                 $showstatus = $usertypes->{$usertype};
 4996:                                                 $count ++;
 4997:                                             }
 4998:                                         }
 4999:                                     }
 5000:                                     foreach my $field (@{$infofields}) {
 5001:                                         next unless ($domconfig{'usercreation'}{'cancreate'}{'emailusername'}{$usertype}{$field});
 5002:                                         next unless ($infotitles->{$field});
 5003:                                         $r->print(&Apache::lonhtmlcommon::row_title($infotitles->{$field}).
 5004:                                                   $info{$uname}{$field});
 5005:                                         $num ++;
 5006:                                         if ($count == $num) {
 5007:                                             $r->print(&Apache::lonhtmlcommon::row_closure(1));
 5008:                                         } else {
 5009:                                             $r->print(&Apache::lonhtmlcommon::row_closure());
 5010:                                         }
 5011:                                     }
 5012:                                     if ($showstatus) {
 5013:                                         $r->print(&Apache::lonhtmlcommon::row_title(&mt('Status type (self-reported)')).
 5014:                                                   $showstatus.
 5015:                                                   &Apache::lonhtmlcommon::row_closure(1));
 5016:                                     }
 5017:                                     $r->print(&Apache::lonhtmlcommon::end_pick_box().'</div>');
 5018:                                 }
 5019:                             }
 5020:                         }
 5021:                     }
 5022:                 }
 5023:             }
 5024:             $r->print(&close_popup_form());
 5025:         }
 5026:     } elsif (($env{'form.action'} eq 'listusers') && 
 5027:              ($permission->{'view'} || $permission->{'cusr'})) {
 5028:         if ($env{'form.phase'} eq 'bulkchange') {
 5029:             push(@{$brcrum},
 5030:                     {href => '/adm/createuser?action=listusers',
 5031:                      text => "List Users"},
 5032:                     {href => "/adm/createuser",
 5033:                      text => "Result",
 5034:                      help => 'Course_View_Class_List'});
 5035:             $bread_crumbs_component = 'Update Users';
 5036:             $args = {bread_crumbs           => $brcrum,
 5037:                      bread_crumbs_component => $bread_crumbs_component};
 5038:             $r->print(&header(undef,$args));
 5039:             my $setting = $env{'form.roletype'};
 5040:             my $choice = $env{'form.bulkaction'};
 5041:             if ($permission->{'cusr'}) {
 5042:                 &Apache::lonuserutils::update_user_list($r,$context,$setting,$choice,$crstype);
 5043:             } else {
 5044:                 $r->print(&mt('You are not authorized to make bulk changes to user roles'));
 5045:                 $r->print('<p><a href="/adm/createuser?action=listusers">'.&mt('Display User Lists').'</a>');
 5046:             }
 5047:         } else {
 5048:             push(@{$brcrum},
 5049:                     {href => '/adm/createuser?action=listusers',
 5050:                      text => "List Users",
 5051:                      help => 'Course_View_Class_List'});
 5052:             $bread_crumbs_component = 'List Users';
 5053:             $args = {bread_crumbs           => $brcrum,
 5054:                      bread_crumbs_component => $bread_crumbs_component};
 5055:             my ($cb_jscript,$jscript,$totcodes,$codetitles,$idlist,$idlist_titles);
 5056:             my $formname = 'studentform';
 5057:             my $hidecall = "hide_searching();";
 5058:             if (($context eq 'domain') && (($env{'form.roletype'} eq 'course') ||
 5059:                 ($env{'form.roletype'} eq 'community'))) {
 5060:                 if ($env{'form.roletype'} eq 'course') {
 5061:                     ($cb_jscript,$jscript,$totcodes,$codetitles,$idlist,$idlist_titles) = 
 5062:                         &Apache::lonuserutils::courses_selector($env{'request.role.domain'},
 5063:                                                                 $formname);
 5064:                 } elsif ($env{'form.roletype'} eq 'community') {
 5065:                     $cb_jscript = 
 5066:                         &Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'});
 5067:                     my %elements = (
 5068:                                       coursepick => 'radio',
 5069:                                       coursetotal => 'text',
 5070:                                       courselist => 'text',
 5071:                                    );
 5072:                     $jscript = &Apache::lonhtmlcommon::set_form_elements(\%elements);
 5073:                 }
 5074:                 $jscript .= &verify_user_display($context)."\n".
 5075:                             &Apache::loncommon::check_uncheck_jscript();
 5076:                 my $js = &add_script($jscript).$cb_jscript;
 5077:                 my $loadcode = 
 5078:                     &Apache::lonuserutils::course_selector_loadcode($formname);
 5079:                 if ($loadcode ne '') {
 5080:                     $args->{add_entries} = {onload => "$loadcode;$hidecall"};
 5081:                 } else {
 5082:                     $args->{add_entries} = {onload => $hidecall};
 5083:                 }
 5084:                 $r->print(&header($js,$args));
 5085:             } else {
 5086:                 $args->{add_entries} = {onload => $hidecall};
 5087:                 $jscript = &verify_user_display($context).
 5088:                            &Apache::loncommon::check_uncheck_jscript(); 
 5089:                 $r->print(&header(&add_script($jscript),$args));
 5090:             }
 5091:             &Apache::lonuserutils::print_userlist($r,undef,$permission,$context,
 5092:                          $formname,$totcodes,$codetitles,$idlist,$idlist_titles,
 5093:                          $showcredits);
 5094:         }
 5095:     } elsif ($env{'form.action'} eq 'drop' && $permission->{'cusr'}) {
 5096:         my $brtext;
 5097:         if ($crstype eq 'Community') {
 5098:             $brtext = 'Drop Members';
 5099:         } else {
 5100:             $brtext = 'Drop Students';
 5101:         }
 5102:         push(@{$brcrum},
 5103:                 {href => '/adm/createuser?action=drop',
 5104:                  text => $brtext,
 5105:                  help => 'Course_Drop_Student'});
 5106:         if ($env{'form.state'} eq 'done') {
 5107:             push(@{$brcrum},
 5108:                      {href=>'/adm/createuser?action=drop',
 5109:                       text=>"Result"});
 5110:         }
 5111:         $bread_crumbs_component = $brtext;
 5112:         $args = {bread_crumbs           => $brcrum,
 5113:                  bread_crumbs_component => $bread_crumbs_component}; 
 5114:         $r->print(&header(undef,$args));
 5115:         if (!exists($env{'form.state'})) {
 5116:             &Apache::lonuserutils::print_drop_menu($r,$context,$permission,$crstype);
 5117:         } elsif ($env{'form.state'} eq 'done') {
 5118:             &Apache::lonuserutils::update_user_list($r,$context,undef,
 5119:                                                     $env{'form.action'});
 5120:         }
 5121:     } elsif ($env{'form.action'} eq 'dateselect') {
 5122:         if ($permission->{'cusr'}) {
 5123:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 5124:                       &Apache::lonuserutils::date_section_selector($context,$permission,
 5125:                                                                    $crstype,$showcredits));
 5126:         } else {
 5127:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 5128:                      '<span class="LC_error">'.&mt('You do not have permission to modify dates or sections for users').'</span>'); 
 5129:         }
 5130:     } elsif ($env{'form.action'} eq 'selfenroll') {
 5131:         if ($permission->{selfenrolladmin}) {
 5132:             my $cid = $env{'request.course.id'};
 5133:             my $cdom = $env{'course.'.$cid.'.domain'};
 5134:             my $cnum = $env{'course.'.$cid.'.num'};
 5135:             my %currsettings = (
 5136:                 selfenroll_types              => $env{'course.'.$cid.'.internal.selfenroll_types'},
 5137:                 selfenroll_registered         => $env{'course.'.$cid.'.internal.selfenroll_registered'},
 5138:                 selfenroll_section            => $env{'course.'.$cid.'.internal.selfenroll_section'},
 5139:                 selfenroll_notifylist         => $env{'course.'.$cid.'.internal.selfenroll_notifylist'},
 5140:                 selfenroll_approval           => $env{'course.'.$cid.'.internal.selfenroll_approval'},
 5141:                 selfenroll_limit              => $env{'course.'.$cid.'.internal.selfenroll_limit'},
 5142:                 selfenroll_cap                => $env{'course.'.$cid.'.internal.selfenroll_cap'},
 5143:                 selfenroll_start_date         => $env{'course.'.$cid.'.internal.selfenroll_start_date'},
 5144:                 selfenroll_end_date           => $env{'course.'.$cid.'.internal.selfenroll_end_date'},
 5145:                 selfenroll_start_access       => $env{'course.'.$cid.'.internal.selfenroll_start_access'},
 5146:                 selfenroll_end_access         => $env{'course.'.$cid.'.internal.selfenroll_end_access'},
 5147:                 default_enrollment_start_date => $env{'course.'.$cid.'.default_enrollment_start_date'},
 5148:                 default_enrollment_end_date   => $env{'course.'.$cid.'.default_enrollment_end_date'},
 5149:                 uniquecode                    => $env{'course.'.$cid.'.internal.uniquecode'},
 5150:             );
 5151:             push(@{$brcrum},
 5152:                     {href => '/adm/createuser?action=selfenroll',
 5153:                      text => "Configure Self-enrollment",
 5154:                      help => 'Course_Self_Enrollment'});
 5155:             if (!exists($env{'form.state'})) {
 5156:                 $args = { bread_crumbs           => $brcrum,
 5157:                           bread_crumbs_component => 'Configure Self-enrollment'};
 5158:                 $r->print(&header(undef,$args));
 5159:                 $r->print('<h3>'.&mt('Self-enrollment with a student role').'</h3>'."\n");
 5160:                 &print_selfenroll_menu($r,'course',$cid,$cdom,$cnum,\%currsettings);
 5161:             } elsif ($env{'form.state'} eq 'done') {
 5162:                 push (@{$brcrum},
 5163:                           {href=>'/adm/createuser?action=selfenroll',
 5164:                            text=>"Result"});
 5165:                 $args = { bread_crumbs           => $brcrum,
 5166:                           bread_crumbs_component => 'Self-enrollment result'};
 5167:                 $r->print(&header(undef,$args));
 5168:                 $r->print('<h3>'.&mt('Self-enrollment with a student role').'</h3>'."\n");
 5169:                 &update_selfenroll_config($r,$cid,$cdom,$cnum,$context,$crstype,\%currsettings);
 5170:             }
 5171:         } else {
 5172:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 5173:                      '<span class="LC_error">'.&mt('You do not have permission to configure self-enrollment').'</span>');
 5174:         }
 5175:     } elsif ($env{'form.action'} eq 'selfenrollqueue') {
 5176:         if ($permission->{selfenrolladmin}) {
 5177:             push(@{$brcrum},
 5178:                      {href => '/adm/createuser?action=selfenrollqueue',
 5179:                       text => 'Enrollment requests',
 5180:                       help => 'Course_Self_Enrollment'});
 5181:             $bread_crumbs_component = 'Enrollment requests';
 5182:             if ($env{'form.state'} eq 'done') {
 5183:                 push(@{$brcrum},
 5184:                          {href => '/adm/createuser?action=selfenrollqueue',
 5185:                           text => 'Result',
 5186:                           help => 'Course_Self_Enrollment'});
 5187:                 $bread_crumbs_component = 'Enrollment result';
 5188:             }
 5189:             $args = { bread_crumbs           => $brcrum,
 5190:                       bread_crumbs_component => $bread_crumbs_component};
 5191:             $r->print(&header(undef,$args));
 5192:             my $cid = $env{'request.course.id'};
 5193:             my $cdom = $env{'course.'.$cid.'.domain'};
 5194:             my $cnum = $env{'course.'.$cid.'.num'};
 5195:             my $coursedesc = $env{'course.'.$cid.'.description'};
 5196:             if (!exists($env{'form.state'})) {
 5197:                 $r->print('<h3>'.&mt('Pending enrollment requests').'</h3>'."\n");
 5198:                 $r->print(&Apache::loncoursequeueadmin::display_queued_requests($context,
 5199:                                                                                 $cdom,$cnum));
 5200:             } elsif ($env{'form.state'} eq 'done') {
 5201:                 $r->print('<h3>'.&mt('Enrollment request processing').'</h3>'."\n");
 5202:                 $r->print(&Apache::loncoursequeueadmin::update_request_queue($context,
 5203:                                $cdom,$cnum,$coursedesc));
 5204:             }
 5205:         } else {
 5206:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 5207:                      '<span class="LC_error">'.&mt('You do not have permission to manage self-enrollment').'</span>');
 5208:         }
 5209:     } elsif ($env{'form.action'} eq 'changelogs') {
 5210:         if ($permission->{cusr} || $permission->{view}) {
 5211:             &print_userchangelogs_display($r,$context,$permission,$brcrum);
 5212:         } else {
 5213:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 5214:                      '<span class="LC_error">'.&mt('You do not have permission to view change logs').'</span>');
 5215:         }
 5216:     } else {
 5217:         $bread_crumbs_component = 'User Management';
 5218:         $args = { bread_crumbs           => $brcrum,
 5219:                   bread_crumbs_component => $bread_crumbs_component};
 5220:         $r->print(&header(undef,$args));
 5221:         $r->print(&print_main_menu($permission,$context,$crstype));
 5222:     }
 5223:     $r->print(&Apache::loncommon::end_page());
 5224:     return OK;
 5225: }
 5226: 
 5227: sub header {
 5228:     my ($jscript,$args) = @_;
 5229:     my $start_page;
 5230:     if (ref($args) eq 'HASH') {
 5231:         $start_page=&Apache::loncommon::start_page('User Management',$jscript,$args);
 5232:     } else {
 5233:         $start_page=&Apache::loncommon::start_page('User Management',$jscript);
 5234:     }
 5235:     return $start_page;
 5236: }
 5237: 
 5238: sub add_script {
 5239:     my ($js) = @_;
 5240:     return '<script type="text/javascript">'."\n"
 5241:           .'// <![CDATA['."\n"
 5242:           .$js."\n"
 5243:           .'// ]]>'."\n"
 5244:           .'</script>'."\n";
 5245: }
 5246: 
 5247: sub usernamerequest_javascript {
 5248:     my $js = <<ENDJS;
 5249: 
 5250: function openusernamereqdisplay(dom,uname,queue) {
 5251:     var url = '/adm/createuser?action=displayuserreq';
 5252:     url += '&domain='+dom+'&username='+uname+'&queue='+queue;
 5253:     var title = 'Account_Request_Browser';
 5254:     var options = 'scrollbars=1,resizable=1,menubar=0';
 5255:     options += ',width=700,height=600';
 5256:     var stdeditbrowser = open(url,title,options,'1');
 5257:     stdeditbrowser.focus();
 5258:     return;
 5259: }
 5260:  
 5261: ENDJS
 5262: }
 5263: 
 5264: sub close_popup_form {
 5265:     my $close= &mt('Close Window');
 5266:     return << "END";
 5267: <p><form name="displayreq" action="" method="post">
 5268: <input type="button" name="closeme" value="$close" onclick="javascript:self.close();" />
 5269: </form></p>
 5270: END
 5271: }
 5272: 
 5273: sub verify_user_display {
 5274:     my ($context) = @_;
 5275:     my %lt = &Apache::lonlocal::texthash (
 5276:         course    => 'course(s): description, section(s), status',
 5277:         community => 'community(s): description, section(s), status',
 5278:         author    => 'author',
 5279:     );
 5280:     my $photos;
 5281:     if (($context eq 'course') && $env{'request.course.id'}) {
 5282:         $photos = $env{'course.'.$env{'request.course.id'}.'.internal.showphoto'};
 5283:     }
 5284:     my $output = <<"END";
 5285: 
 5286: function hide_searching() {
 5287:     if (document.getElementById('searching')) {
 5288:         document.getElementById('searching').style.display = 'none';
 5289:     }
 5290:     return;
 5291: }
 5292: 
 5293: function display_update() {
 5294:     document.studentform.action.value = 'listusers';
 5295:     document.studentform.phase.value = 'display';
 5296:     document.studentform.submit();
 5297: }
 5298: 
 5299: function updateCols(caller) {
 5300:     var context = '$context';
 5301:     var photos = '$photos';
 5302:     if (caller == 'Status') {
 5303:         if ((context == 'domain') && 
 5304:             ((document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'course') ||
 5305:              (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'community'))) {
 5306:             document.getElementById('showcolstatus').checked = false;
 5307:             document.getElementById('showcolstatus').disabled = 'disabled';
 5308:             document.getElementById('showcolstart').checked = false;
 5309:             document.getElementById('showcolend').checked = false;
 5310:         } else {
 5311:             if (document.studentform.Status.options[document.studentform.Status.selectedIndex].value == 'Any') {
 5312:                 document.getElementById('showcolstatus').checked = true;
 5313:                 document.getElementById('showcolstatus').disabled = '';
 5314:                 document.getElementById('showcolstart').checked = true;
 5315:                 document.getElementById('showcolend').checked = true;
 5316:             } else {
 5317:                 document.getElementById('showcolstatus').checked = false;
 5318:                 document.getElementById('showcolstatus').disabled = 'disabled';
 5319:                 document.getElementById('showcolstart').checked = false;
 5320:                 document.getElementById('showcolend').checked = false;
 5321:             }
 5322:         }
 5323:     }
 5324:     if (caller == 'output') {
 5325:         if (photos == 1) {
 5326:             if (document.getElementById('showcolphoto')) {
 5327:                 var photoitem = document.getElementById('showcolphoto');
 5328:                 if (document.studentform.output.options[document.studentform.output.selectedIndex].value == 'html') {
 5329:                     photoitem.checked = true;
 5330:                     photoitem.disabled = '';
 5331:                 } else {
 5332:                     photoitem.checked = false;
 5333:                     photoitem.disabled = 'disabled';
 5334:                 }
 5335:             }
 5336:         }
 5337:     }
 5338:     if (caller == 'showrole') {
 5339:         if ((document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'Any') ||
 5340:             (document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'cr')) {
 5341:             document.getElementById('showcolrole').checked = true;
 5342:             document.getElementById('showcolrole').disabled = '';
 5343:         } else {
 5344:             document.getElementById('showcolrole').checked = false;
 5345:             document.getElementById('showcolrole').disabled = 'disabled';
 5346:         }
 5347:         if (context == 'domain') {
 5348:             var quotausageshow = 0;
 5349:             if ((document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'course') ||
 5350:                 (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'community')) {
 5351:                 document.getElementById('showcolstatus').checked = false;
 5352:                 document.getElementById('showcolstatus').disabled = 'disabled';
 5353:                 document.getElementById('showcolstart').checked = false;
 5354:                 document.getElementById('showcolend').checked = false;
 5355:             } else {
 5356:                 if (document.studentform.Status.options[document.studentform.Status.selectedIndex].value == 'Any') {
 5357:                     document.getElementById('showcolstatus').checked = true;
 5358:                     document.getElementById('showcolstatus').disabled = '';
 5359:                     document.getElementById('showcolstart').checked = true;
 5360:                     document.getElementById('showcolend').checked = true;
 5361:                 }
 5362:             }
 5363:             if (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'domain') {
 5364:                 document.getElementById('showcolextent').disabled = 'disabled';
 5365:                 document.getElementById('showcolextent').checked = 'false';
 5366:                 document.getElementById('showextent').style.display='none';
 5367:                 document.getElementById('showcoltextextent').innerHTML = '';
 5368:                 if ((document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'au') ||
 5369:                     (document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'Any')) {
 5370:                     if (document.getElementById('showcolauthorusage')) {
 5371:                         document.getElementById('showcolauthorusage').disabled = '';
 5372:                     }
 5373:                     if (document.getElementById('showcolauthorquota')) {
 5374:                         document.getElementById('showcolauthorquota').disabled = '';
 5375:                     }
 5376:                     quotausageshow = 1;
 5377:                 }
 5378:             } else {
 5379:                 document.getElementById('showextent').style.display='block';
 5380:                 document.getElementById('showextent').style.textAlign='left';
 5381:                 document.getElementById('showextent').style.textFace='normal';
 5382:                 if (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'author') {
 5383:                     document.getElementById('showcolextent').disabled = '';
 5384:                     document.getElementById('showcolextent').checked = 'true';
 5385:                     document.getElementById('showcoltextextent').innerHTML="$lt{'author'}";
 5386:                 } else {
 5387:                     document.getElementById('showcolextent').disabled = '';
 5388:                     document.getElementById('showcolextent').checked = 'true';
 5389:                     if (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'community') {
 5390:                         document.getElementById('showcoltextextent').innerHTML="$lt{'community'}";
 5391:                     } else {
 5392:                         document.getElementById('showcoltextextent').innerHTML="$lt{'course'}";
 5393:                     }
 5394:                 }
 5395:             }
 5396:             if (quotausageshow == 0)  {
 5397:                 if (document.getElementById('showcolauthorusage')) {
 5398:                     document.getElementById('showcolauthorusage').checked = false;
 5399:                     document.getElementById('showcolauthorusage').disabled = 'disabled';
 5400:                 }
 5401:                 if (document.getElementById('showcolauthorquota')) {
 5402:                     document.getElementById('showcolauthorquota').checked = false;
 5403:                     document.getElementById('showcolauthorquota').disabled = 'disabled';
 5404:                 }
 5405:             }
 5406:         }
 5407:     }
 5408:     return;
 5409: }
 5410: 
 5411: END
 5412:     return $output;
 5413: 
 5414: }
 5415: 
 5416: ###############################################################
 5417: ###############################################################
 5418: #  Menu Phase One
 5419: sub print_main_menu {
 5420:     my ($permission,$context,$crstype) = @_;
 5421:     my $linkcontext = $context;
 5422:     my $stuterm = lc(&Apache::lonnet::plaintext('st',$crstype));
 5423:     if (($context eq 'course') && ($crstype eq 'Community')) {
 5424:         $linkcontext = lc($crstype);
 5425:         $stuterm = 'Members';
 5426:     }
 5427:     my %links = (
 5428:                 domain => {
 5429:                             upload     => 'Upload a File of Users',
 5430:                             singleuser => 'Add/Modify a User',
 5431:                             listusers  => 'Manage Users',
 5432:                             },
 5433:                 author => {
 5434:                             upload     => 'Upload a File of Co-authors',
 5435:                             singleuser => 'Add/Modify a Co-author',
 5436:                             listusers  => 'Manage Co-authors',
 5437:                             },
 5438:                 course => {
 5439:                             upload     => 'Upload a File of Course Users',
 5440:                             singleuser => 'Add/Modify a Course User',
 5441:                             listusers  => 'List and Modify Multiple Course Users',
 5442:                             },
 5443:                 community => {
 5444:                             upload     => 'Upload a File of Community Users',
 5445:                             singleuser => 'Add/Modify a Community User',
 5446:                             listusers  => 'List and Modify Multiple Community Users',
 5447:                            },
 5448:                 );
 5449:      my %linktitles = (
 5450:                 domain => {
 5451:                             singleuser => 'Add a user to the domain, and/or a course or community in the domain.',
 5452:                             listusers  => 'Show and manage users in this domain.',
 5453:                             },
 5454:                 author => {
 5455:                             singleuser => 'Add a user with a co- or assistant author role.',
 5456:                             listusers  => 'Show and manage co- or assistant authors.',
 5457:                             },
 5458:                 course => {
 5459:                             singleuser => 'Add a user with a certain role to this course.',
 5460:                             listusers  => 'Show and manage users in this course.',
 5461:                             },
 5462:                 community => {
 5463:                             singleuser => 'Add a user with a certain role to this community.',
 5464:                             listusers  => 'Show and manage users in this community.',
 5465:                            },
 5466:                 );
 5467:   if ($linkcontext eq 'domain') {
 5468:       unless ($permission->{'cusr'}) {
 5469:           $links{'domain'}{'singleuser'} = 'View a User'; 
 5470:           $linktitles{'domain'}{'singleuser'} = 'View information about a user in the domain';
 5471:           
 5472:       }
 5473:   } elsif ($linkcontext eq 'course') {
 5474:       unless ($permission->{'cusr'}) {
 5475:           $links{'course'}{'singleuser'} = 'View a Course User';
 5476:           $linktitles{'course'}{'singleuser'} = 'View information about a user in this course';
 5477:           $links{'course'}{'listusers'} = 'List Course Users';
 5478:           $linktitles{'course'}{'listusers'} = 'Show information about users in this course';
 5479:       }
 5480:   } elsif ($linkcontext eq 'community') {
 5481:       unless ($permission->{'cusr'}) {
 5482:           $links{'community'}{'singleuser'} = 'View a Community User';
 5483:           $linktitles{'community'}{'singleuser'} = 'View information about a user in this community';
 5484:           $links{'community'}{'listusers'} = 'List Community Users';
 5485:           $linktitles{'community'}{'listusers'} = 'Show information about users in this community';
 5486:       }
 5487:   }
 5488:   my @menu = ( {categorytitle => 'Single Users', 
 5489:          items =>
 5490:          [
 5491:             {
 5492:              linktext => $links{$linkcontext}{'singleuser'},
 5493:              icon => 'edit-redo.png',
 5494:              #help => 'Course_Change_Privileges',
 5495:              url => '/adm/createuser?action=singleuser',
 5496:              permission => ($permission->{'view'} || $permission->{'cusr'}),
 5497:              linktitle => $linktitles{$linkcontext}{'singleuser'},
 5498:             },
 5499:          ]},
 5500: 
 5501:          {categorytitle => 'Multiple Users',
 5502:          items => 
 5503:          [
 5504:             {
 5505:              linktext => $links{$linkcontext}{'upload'},
 5506:              icon => 'uplusr.png',
 5507:              #help => 'Course_Create_Class_List',
 5508:              url => '/adm/createuser?action=upload',
 5509:              permission => $permission->{'cusr'},
 5510:              linktitle => 'Upload a CSV or a text file containing users.',
 5511:             },
 5512:             {
 5513:              linktext => $links{$linkcontext}{'listusers'},
 5514:              icon => 'mngcu.png',
 5515:              #help => 'Course_View_Class_List',
 5516:              url => '/adm/createuser?action=listusers',
 5517:              permission => ($permission->{'view'} || $permission->{'cusr'}),
 5518:              linktitle => $linktitles{$linkcontext}{'listusers'}, 
 5519:             },
 5520: 
 5521:          ]},
 5522: 
 5523:          {categorytitle => 'Administration',
 5524:          items => [ ]},
 5525:        );
 5526: 
 5527:     if ($context eq 'domain'){
 5528:         push(@{  $menu[0]->{items} }, # Single Users
 5529:             {
 5530:              linktext => 'User Access Log',
 5531:              icon => 'document-properties.png',
 5532:              #help => 'User_Access_Logs',
 5533:              url => '/adm/createuser?action=accesslogs',
 5534:              permission => $permission->{'activity'},
 5535:              linktitle => 'View user access log.',
 5536:             }
 5537:         );
 5538:         
 5539:         push(@{ $menu[2]->{items} }, #Category: Administration
 5540:             {
 5541:              linktext => 'Custom Roles',
 5542:              icon => 'emblem-photos.png',
 5543:              #help => 'Course_Editing_Custom_Roles',
 5544:              url => '/adm/createuser?action=custom',
 5545:              permission => $permission->{'custom'},
 5546:              linktitle => 'Configure a custom role.',
 5547:             },
 5548:             {
 5549:              linktext => 'Authoring Space Requests',
 5550:              icon => 'selfenrl-queue.png',
 5551:              #help => 'Domain_Role_Approvals',
 5552:              url => '/adm/createuser?action=processauthorreq',
 5553:              permission => $permission->{'cusr'},
 5554:              linktitle => 'Approve or reject author role requests',
 5555:             },
 5556:             {
 5557:              linktext => 'LON-CAPA Account Requests',
 5558:              icon => 'list-add.png',
 5559:              #help => 'Domain_Username_Approvals',
 5560:              url => '/adm/createuser?action=processusernamereq',
 5561:              permission => $permission->{'cusr'},
 5562:              linktitle => 'Approve or reject LON-CAPA account requests',
 5563:             },
 5564:             {
 5565:              linktext => 'Change Log',
 5566:              icon => 'document-properties.png',
 5567:              #help => 'Course_User_Logs',
 5568:              url => '/adm/createuser?action=changelogs',
 5569:              permission => ($permission->{'cusr'} || $permission->{'view'}),
 5570:              linktitle => 'View change log.',
 5571:             },
 5572:         );
 5573:         
 5574:     }elsif ($context eq 'course'){
 5575:         my ($cnum,$cdom) = &Apache::lonuserutils::get_course_identity();
 5576: 
 5577:         my %linktext = (
 5578:                          'Course'    => {
 5579:                                           single => 'Add/Modify a Student', 
 5580:                                           drop   => 'Drop Students',
 5581:                                           groups => 'Course Groups',
 5582:                                         },
 5583:                          'Community' => {
 5584:                                           single => 'Add/Modify a Member', 
 5585:                                           drop   => 'Drop Members',
 5586:                                           groups => 'Community Groups',
 5587:                                         },
 5588:                        );
 5589:         $linktext{'Placement'} = $linktext{'Course'};
 5590: 
 5591:         my %linktitle = (
 5592:             'Course' => {
 5593:                   single => 'Add a user with the role of student to this course',
 5594:                   drop   => 'Remove a student from this course.',
 5595:                   groups => 'Manage course groups',
 5596:                         },
 5597:             'Community' => {
 5598:                   single => 'Add a user with the role of member to this community',
 5599:                   drop   => 'Remove a member from this community.',
 5600:                   groups => 'Manage community groups',
 5601:                            },
 5602:         );
 5603: 
 5604:         $linktitle{'Placement'} = $linktitle{'Course'};
 5605: 
 5606:         push(@{ $menu[0]->{items} }, #Category: Single Users
 5607:             {   
 5608:              linktext => $linktext{$crstype}{'single'},
 5609:              #help => 'Course_Add_Student',
 5610:              icon => 'list-add.png',
 5611:              url => '/adm/createuser?action=singlestudent',
 5612:              permission => $permission->{'cusr'},
 5613:              linktitle => $linktitle{$crstype}{'single'},
 5614:             },
 5615:         );
 5616:         
 5617:         push(@{ $menu[1]->{items} }, #Category: Multiple Users 
 5618:             {
 5619:              linktext => $linktext{$crstype}{'drop'},
 5620:              icon => 'edit-undo.png',
 5621:              #help => 'Course_Drop_Student',
 5622:              url => '/adm/createuser?action=drop',
 5623:              permission => $permission->{'cusr'},
 5624:              linktitle => $linktitle{$crstype}{'drop'},
 5625:             },
 5626:         );
 5627:         push(@{ $menu[2]->{items} }, #Category: Administration
 5628:             {    
 5629:              linktext => 'Custom Roles',
 5630:              icon => 'emblem-photos.png',
 5631:              #help => 'Course_Editing_Custom_Roles',
 5632:              url => '/adm/createuser?action=custom',
 5633:              permission => $permission->{'custom'},
 5634:              linktitle => 'Configure a custom role.',
 5635:             },
 5636:             {
 5637:              linktext => $linktext{$crstype}{'groups'},
 5638:              icon => 'grps.png',
 5639:              #help => 'Course_Manage_Group',
 5640:              url => '/adm/coursegroups?refpage=cusr',
 5641:              permission => $permission->{'grp_manage'},
 5642:              linktitle => $linktitle{$crstype}{'groups'},
 5643:             },
 5644:             {
 5645:              linktext => 'Change Log',
 5646:              icon => 'document-properties.png',
 5647:              #help => 'Course_User_Logs',
 5648:              url => '/adm/createuser?action=changelogs',
 5649:              permission => ($permission->{'view'} || $permission->{'cusr'}),
 5650:              linktitle => 'View change log.',
 5651:             },
 5652:         );
 5653:         if ($env{'course.'.$env{'request.course.id'}.'.internal.selfenroll_approval'}) {
 5654:             push(@{ $menu[2]->{items} },
 5655:                     {
 5656:                      linktext => 'Enrollment Requests',
 5657:                      icon => 'selfenrl-queue.png',
 5658:                      #help => 'Course_Approve_Selfenroll',
 5659:                      url => '/adm/createuser?action=selfenrollqueue',
 5660:                      permission => $permission->{'selfenrolladmin'},
 5661:                      linktitle =>'Approve or reject enrollment requests.',
 5662:                     },
 5663:             );
 5664:         }
 5665:         
 5666:         if (!exists($permission->{'cusr_section'})){
 5667:             if ($crstype ne 'Community') {
 5668:                 push(@{ $menu[2]->{items} },
 5669:                     {
 5670:                      linktext => 'Automated Enrollment',
 5671:                      icon => 'roles.png',
 5672:                      #help => 'Course_Automated_Enrollment',
 5673:                      permission => (&Apache::lonnet::auto_run($cnum,$cdom)
 5674:                                          && (($permission->{'cusr'}) ||
 5675:                                              ($permission->{'view'}))),
 5676:                      url  => '/adm/populate',
 5677:                      linktitle => 'Automated enrollment manager.',
 5678:                     }
 5679:                 );
 5680:             }
 5681:             push(@{ $menu[2]->{items} }, 
 5682:                 {
 5683:                  linktext => 'User Self-Enrollment',
 5684:                  icon => 'self_enroll.png',
 5685:                  #help => 'Course_Self_Enrollment',
 5686:                  url => '/adm/createuser?action=selfenroll',
 5687:                  permission => $permission->{'selfenrolladmin'},
 5688:                  linktitle => 'Configure user self-enrollment.',
 5689:                 },
 5690:             );
 5691:         }
 5692:     } elsif ($context eq 'author') {
 5693:         push(@{ $menu[2]->{items} }, #Category: Administration
 5694:             {
 5695:              linktext => 'Change Log',
 5696:              icon => 'document-properties.png',
 5697:              #help => 'Course_User_Logs',
 5698:              url => '/adm/createuser?action=changelogs',
 5699:              permission => $permission->{'cusr'},
 5700:              linktitle => 'View change log.',
 5701:             },
 5702:         );
 5703:     }
 5704:     return Apache::lonhtmlcommon::generate_menu(@menu);
 5705: #               { text => 'View Log-in History',
 5706: #                 help => 'Course_User_Logins',
 5707: #                 action => 'logins',
 5708: #                 permission => $permission->{'cusr'},
 5709: #               });
 5710: }
 5711: 
 5712: sub restore_prev_selections {
 5713:     my %saveable_parameters = ('srchby'   => 'scalar',
 5714: 			       'srchin'   => 'scalar',
 5715: 			       'srchtype' => 'scalar',
 5716: 			       );
 5717:     &Apache::loncommon::store_settings('user','user_picker',
 5718: 				       \%saveable_parameters);
 5719:     &Apache::loncommon::restore_settings('user','user_picker',
 5720: 					 \%saveable_parameters);
 5721: }
 5722: 
 5723: sub print_selfenroll_menu {
 5724:     my ($r,$context,$cid,$cdom,$cnum,$currsettings,$additional,$readonly) = @_;
 5725:     my $crstype = &Apache::loncommon::course_type();
 5726:     my $formname = 'selfenroll';
 5727:     my $nolink = 1;
 5728:     my ($row,$lt) = &Apache::lonuserutils::get_selfenroll_titles();
 5729:     my $groupslist = &Apache::lonuserutils::get_groupslist();
 5730:     my $setsec_js = 
 5731:         &Apache::lonuserutils::setsections_javascript($formname,$groupslist);
 5732:     my %alerts = &Apache::lonlocal::texthash(
 5733:         acto => 'Activation of self-enrollment was selected for the following domain(s)',
 5734:         butn => 'but no user types have been checked.',
 5735:         wilf => "Please uncheck 'activate' or check at least one type.",
 5736:     );
 5737:     my $disabled;
 5738:     if ($readonly) {
 5739:        $disabled = ' disabled="disabled"';
 5740:     }
 5741:     &js_escape(\%alerts);
 5742:     my $selfenroll_js = <<"ENDSCRIPT";
 5743: function update_types(caller,num) {
 5744:     var delidx = getIndexByName('selfenroll_delete');
 5745:     var actidx = getIndexByName('selfenroll_activate');
 5746:     if (caller == 'selfenroll_all') {
 5747:         var selall;
 5748:         for (var i=0; i<document.$formname.selfenroll_all.length; i++) {
 5749:             if (document.$formname.selfenroll_all[i].checked) {
 5750:                 selall = document.$formname.selfenroll_all[i].value;
 5751:             }
 5752:         }
 5753:         if (selall == 1) {
 5754:             if (delidx != -1) {
 5755:                 if (document.$formname.selfenroll_delete.length) {
 5756:                     for (var j=0; j<document.$formname.selfenroll_delete.length; j++) {
 5757:                         document.$formname.selfenroll_delete[j].checked = true;
 5758:                     }
 5759:                 } else {
 5760:                     document.$formname.elements[delidx].checked = true;
 5761:                 }
 5762:             }
 5763:             if (actidx != -1) {
 5764:                 if (document.$formname.selfenroll_activate.length) {
 5765:                     for (var j=0; j<document.$formname.selfenroll_activate.length; j++) {
 5766:                         document.$formname.selfenroll_activate[j].checked = false;
 5767:                     }
 5768:                 } else {
 5769:                     document.$formname.elements[actidx].checked = false;
 5770:                 }
 5771:             }
 5772:             document.$formname.selfenroll_newdom.selectedIndex = 0; 
 5773:         }
 5774:     }
 5775:     if (caller == 'selfenroll_activate') {
 5776:         if (document.$formname.selfenroll_activate.length) {
 5777:             for (var j=0; j<document.$formname.selfenroll_activate.length; j++) {
 5778:                 if (document.$formname.selfenroll_activate[j].value == num) {
 5779:                     if (document.$formname.selfenroll_activate[j].checked) {
 5780:                         for (var i=0; i<document.$formname.selfenroll_all.length; i++) {
 5781:                             if (document.$formname.selfenroll_all[i].value == '1') {
 5782:                                 document.$formname.selfenroll_all[i].checked = false;
 5783:                             }
 5784:                             if (document.$formname.selfenroll_all[i].value == '0') {
 5785:                                 document.$formname.selfenroll_all[i].checked = true;
 5786:                             }
 5787:                         }
 5788:                     }
 5789:                 }
 5790:             }
 5791:         } else {
 5792:             for (var i=0; i<document.$formname.selfenroll_all.length; i++) {
 5793:                 if (document.$formname.selfenroll_all[i].value == '1') {
 5794:                     document.$formname.selfenroll_all[i].checked = false;
 5795:                 }
 5796:                 if (document.$formname.selfenroll_all[i].value == '0') {
 5797:                     document.$formname.selfenroll_all[i].checked = true;
 5798:                 }
 5799:             }
 5800:         }
 5801:     }
 5802:     if (caller == 'selfenroll_delete') {
 5803:         if (document.$formname.selfenroll_delete.length) {
 5804:             for (var j=0; j<document.$formname.selfenroll_delete.length; j++) {
 5805:                 if (document.$formname.selfenroll_delete[j].value == num) {
 5806:                     if (document.$formname.selfenroll_delete[j].checked) {
 5807:                         var delindex = getIndexByName('selfenroll_types_'+num);
 5808:                         if (delindex != -1) { 
 5809:                             if (document.$formname.elements[delindex].length) {
 5810:                                 for (var k=0; k<document.$formname.elements[delindex].length; k++) {
 5811:                                     document.$formname.elements[delindex][k].checked = false;
 5812:                                 }
 5813:                             } else {
 5814:                                 document.$formname.elements[delindex].checked = false;
 5815:                             }
 5816:                         }
 5817:                     }
 5818:                 }
 5819:             }
 5820:         } else {
 5821:             if (document.$formname.selfenroll_delete.checked) {
 5822:                 var delindex = getIndexByName('selfenroll_types_'+num);
 5823:                 if (delindex != -1) {
 5824:                     if (document.$formname.elements[delindex].length) {
 5825:                         for (var k=0; k<document.$formname.elements[delindex].length; k++) {
 5826:                             document.$formname.elements[delindex][k].checked = false;
 5827:                         }
 5828:                     } else {
 5829:                         document.$formname.elements[delindex].checked = false;
 5830:                     }
 5831:                 }
 5832:             }
 5833:         }
 5834:     }
 5835:     return;
 5836: }
 5837: 
 5838: function validate_types(form) {
 5839:     var needaction = new Array();
 5840:     var countfail = 0;
 5841:     var actidx = getIndexByName('selfenroll_activate');
 5842:     if (actidx != -1) {
 5843:         if (document.$formname.selfenroll_activate.length) {
 5844:             for (var j=0; j<document.$formname.selfenroll_activate.length; j++) {
 5845:                 var num = document.$formname.selfenroll_activate[j].value;
 5846:                 if (document.$formname.selfenroll_activate[j].checked) {
 5847:                     countfail = check_types(num,countfail,needaction)
 5848:                 }
 5849:             }
 5850:         } else {
 5851:             if (document.$formname.selfenroll_activate.checked) {
 5852:                 var num = document.$formname.selfenroll_activate.value;
 5853:                 countfail = check_types(num,countfail,needaction)
 5854:             }
 5855:         }
 5856:     }
 5857:     if (countfail > 0) {
 5858:         var msg = "$alerts{'acto'}\\n";
 5859:         var loopend = needaction.length -1;
 5860:         if (loopend > 0) {
 5861:             for (var m=0; m<loopend; m++) {
 5862:                 msg += needaction[m]+", ";
 5863:             }
 5864:         }
 5865:         msg += needaction[loopend]+"\\n$alerts{'butn'}\\n$alerts{'wilf'}";
 5866:         alert(msg);
 5867:         return; 
 5868:     }
 5869:     setSections(form);
 5870: }
 5871: 
 5872: function check_types(num,countfail,needaction) {
 5873:     var typeidx = getIndexByName('selfenroll_types_'+num);
 5874:     var count = 0;
 5875:     if (typeidx != -1) {
 5876:         if (document.$formname.elements[typeidx].length) {
 5877:             for (var k=0; k<document.$formname.elements[typeidx].length; k++) {
 5878:                 if (document.$formname.elements[typeidx][k].checked) {
 5879:                     count ++;
 5880:                 }
 5881:             }
 5882:         } else {
 5883:             if (document.$formname.elements[typeidx].checked) {
 5884:                 count ++;
 5885:             }
 5886:         }
 5887:         if (count == 0) {
 5888:             var domidx = getIndexByName('selfenroll_dom_'+num);
 5889:             if (domidx != -1) {
 5890:                 var domname = document.$formname.elements[domidx].value;
 5891:                 needaction[countfail] = domname;
 5892:                 countfail ++;
 5893:             }
 5894:         }
 5895:     }
 5896:     return countfail;
 5897: }
 5898: 
 5899: function toggleNotify() {
 5900:     var selfenrollApproval = 0;
 5901:     if (document.$formname.selfenroll_approval.length) {
 5902:         for (var i=0; i<document.$formname.selfenroll_approval.length; i++) {
 5903:             if (document.$formname.selfenroll_approval[i].checked) {
 5904:                 selfenrollApproval = document.$formname.selfenroll_approval[i].value;
 5905:                 break;        
 5906:             }
 5907:         }
 5908:     }
 5909:     if (document.getElementById('notified')) {
 5910:         if (selfenrollApproval == 0) {
 5911:             document.getElementById('notified').style.display='none';
 5912:         } else {
 5913:             document.getElementById('notified').style.display='block';
 5914:         }
 5915:     }
 5916:     return;
 5917: }
 5918: 
 5919: function getIndexByName(item) {
 5920:     for (var i=0;i<document.$formname.elements.length;i++) {
 5921:         if (document.$formname.elements[i].name == item) {
 5922:             return i;
 5923:         }
 5924:     }
 5925:     return -1;
 5926: }
 5927: ENDSCRIPT
 5928: 
 5929:     my $output = '<script type="text/javascript">'."\n".
 5930:                  '// <![CDATA['."\n".
 5931:                  $setsec_js."\n".$selfenroll_js."\n".
 5932:                  '// ]]>'."\n".
 5933:                  '</script>'."\n".
 5934:                  '<h3>'.$lt->{'selfenroll'}.'</h3>'."\n";
 5935:  
 5936:     my $visactions = &cat_visibility();
 5937:     my ($cathash,%cattype);
 5938:     my %domconfig = &Apache::lonnet::get_dom('configuration',['coursecategories'],$cdom);
 5939:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 5940:         $cathash = $domconfig{'coursecategories'}{'cats'};
 5941:         $cattype{'auth'} = $domconfig{'coursecategories'}{'auth'};
 5942:         $cattype{'unauth'} = $domconfig{'coursecategories'}{'unauth'};
 5943:         if ($cattype{'auth'} eq '') {
 5944:             $cattype{'auth'} = 'std';
 5945:         }
 5946:         if ($cattype{'unauth'} eq '') {
 5947:             $cattype{'unauth'} = 'std';
 5948:         }
 5949:     } else {
 5950:         $cathash = {};
 5951:         $cattype{'auth'} = 'std';
 5952:         $cattype{'unauth'} = 'std';
 5953:     }
 5954:     if (($cattype{'auth'} eq 'none') && ($cattype{'unauth'} eq 'none')) {
 5955:         $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
 5956:                   '<br />'.
 5957:                   '<br />'.$visactions->{'take'}.'<ul>'.
 5958:                   '<li>'.$visactions->{'dc_chgconf'}.'</li>'.
 5959:                   '</ul>');
 5960:     } elsif (($cattype{'auth'} !~ /^(std|domonly)$/) && ($cattype{'unauth'} !~ /^(std|domonly)$/)) {
 5961:         if ($currsettings->{'uniquecode'}) {
 5962:             $r->print('<span class="LC_info">'.$visactions->{'vis'}.'</span>');
 5963:         } else {
 5964:             $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
 5965:                   '<br />'.
 5966:                   '<br />'.$visactions->{'take'}.'<ul>'.
 5967:                   '<li>'.$visactions->{'dc_setcode'}.'</li>'.
 5968:                   '</ul><br />');
 5969:         }
 5970:     } else {
 5971:         my ($visible,$cansetvis,$vismsgs) = &visible_in_stdcat($cdom,$cnum,\%domconfig);
 5972:         if (ref($visactions) eq 'HASH') {
 5973:             if ($visible) {
 5974:                 $output .= '<p class="LC_info">'.$visactions->{'vis'}.'</p>';
 5975:            } else {
 5976:                 $output .= '<p class="LC_warning">'.$visactions->{'miss'}.'</p>'
 5977:                           .$visactions->{'yous'}.
 5978:                            '<p>'.$visactions->{'gen'}.'<br />'.$visactions->{'coca'};
 5979:                 if (ref($vismsgs) eq 'ARRAY') {
 5980:                     $output .= '<br />'.$visactions->{'make'}.'<ul>';
 5981:                     foreach my $item (@{$vismsgs}) {
 5982:                         $output .= '<li>'.$visactions->{$item}.'</li>';
 5983:                     }
 5984:                     $output .= '</ul>';
 5985:                 }
 5986:                 $output .= '</p>';
 5987:             }
 5988:         }
 5989:     }
 5990:     my $actionhref = '/adm/createuser';
 5991:     if ($context eq 'domain') {
 5992:         $actionhref = '/adm/modifycourse';
 5993:     }
 5994: 
 5995:     my %noedit;
 5996:     unless ($context eq 'domain') {
 5997:         %noedit = &get_noedit_fields($cdom,$cnum,$crstype,$row);
 5998:     }
 5999:     $output .= '<form name="'.$formname.'" method="post" action="'.$actionhref.'">'."\n".
 6000:                &Apache::lonhtmlcommon::start_pick_box();
 6001:     if (ref($row) eq 'ARRAY') {
 6002:         foreach my $item (@{$row}) {
 6003:             my $title = $item; 
 6004:             if (ref($lt) eq 'HASH') {
 6005:                 $title = $lt->{$item};
 6006:             }
 6007:             $output .= &Apache::lonhtmlcommon::row_title($title);
 6008:             if ($item eq 'types') {
 6009:                 my $curr_types;
 6010:                 if (ref($currsettings) eq 'HASH') {
 6011:                     $curr_types = $currsettings->{'selfenroll_types'};
 6012:                 }
 6013:                 if ($noedit{$item}) {
 6014:                     if ($curr_types eq '*') {
 6015:                         $output .= &mt('Any user in any domain');   
 6016:                     } else {
 6017:                         my @entries = split(/;/,$curr_types);
 6018:                         if (@entries > 0) {
 6019:                             $output .= '<ul>'; 
 6020:                             foreach my $entry (@entries) {
 6021:                                 my ($currdom,$typestr) = split(/:/,$entry);
 6022:                                 next if ($typestr eq '');
 6023:                                 my $domdesc = &Apache::lonnet::domain($currdom);
 6024:                                 my @currinsttypes = split(',',$typestr);
 6025:                                 my ($othertitle,$usertypes,$types) = 
 6026:                                     &Apache::loncommon::sorted_inst_types($currdom);
 6027:                                 if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 6028:                                     $usertypes->{'any'} = &mt('any user'); 
 6029:                                     if (keys(%{$usertypes}) > 0) {
 6030:                                         $usertypes->{'other'} = &mt('other users');
 6031:                                     }
 6032:                                     my @longinsttypes = map { $usertypes->{$_}; } @currinsttypes;
 6033:                                     $output .= '<li>'.$domdesc.':'.join(', ',@longinsttypes).'</li>';
 6034:                                  }
 6035:                             }
 6036:                             $output .= '</ul>';
 6037:                         } else {
 6038:                             $output .= &mt('None');
 6039:                         }
 6040:                     }
 6041:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 6042:                     next;
 6043:                 }
 6044:                 my $showdomdesc = 1;
 6045:                 my $includeempty = 1;
 6046:                 my $num = 0;
 6047:                 $output .= &Apache::loncommon::start_data_table().
 6048:                            &Apache::loncommon::start_data_table_row()
 6049:                            .'<td colspan="2"><span class="LC_nobreak"><label>'
 6050:                            .&mt('Any user in any domain:')
 6051:                            .'&nbsp;<input type="radio" name="selfenroll_all" value="1" ';
 6052:                 if ($curr_types eq '*') {
 6053:                     $output .= ' checked="checked" '; 
 6054:                 }
 6055:                 $output .= 'onchange="javascript:update_types('.
 6056:                            "'selfenroll_all'".');"'.$disabled.' />'.&mt('Yes').'</label>'.
 6057:                            '&nbsp;&nbsp;<input type="radio" name="selfenroll_all" value="0" ';
 6058:                 if ($curr_types ne '*') {
 6059:                     $output .= ' checked="checked" ';
 6060:                 }
 6061:                 $output .= ' onchange="javascript:update_types('.
 6062:                            "'selfenroll_all'".');"'.$disabled.' />'.&mt('No').'</label></td>'.
 6063:                            &Apache::loncommon::end_data_table_row().
 6064:                            &Apache::loncommon::end_data_table().
 6065:                            &mt('Or').'<br />'.
 6066:                            &Apache::loncommon::start_data_table();
 6067:                 my %currdoms;
 6068:                 if ($curr_types eq '') {
 6069:                     $output .= &new_selfenroll_dom_row($cdom,'0');
 6070:                 } elsif ($curr_types ne '*') {
 6071:                     my @entries = split(/;/,$curr_types);
 6072:                     if (@entries > 0) {
 6073:                         foreach my $entry (@entries) {
 6074:                             my ($currdom,$typestr) = split(/:/,$entry);
 6075:                             $currdoms{$currdom} = 1;
 6076:                             my $domdesc = &Apache::lonnet::domain($currdom);
 6077:                             my @currinsttypes = split(',',$typestr);
 6078:                             $output .= &Apache::loncommon::start_data_table_row()
 6079:                                        .'<td valign="top"><span class="LC_nobreak">'.&mt('Domain:').'<b>'
 6080:                                        .'&nbsp;'.$domdesc.' ('.$currdom.')'
 6081:                                        .'</b><input type="hidden" name="selfenroll_dom_'.$num
 6082:                                        .'" value="'.$currdom.'" /></span><br />'
 6083:                                        .'<span class="LC_nobreak"><label><input type="checkbox" '
 6084:                                        .'name="selfenroll_delete" value="'.$num.'" onchange="javascript:update_types('."'selfenroll_delete','$num'".');"'.$disabled.' />'
 6085:                                        .&mt('Delete').'</label></span></td>';
 6086:                             $output .= '<td valign="top">&nbsp;&nbsp;'.&mt('User types:').'<br />'
 6087:                                        .&selfenroll_inst_types($num,$currdom,\@currinsttypes,$readonly).'</td>'
 6088:                                        .&Apache::loncommon::end_data_table_row();
 6089:                             $num ++;
 6090:                         }
 6091:                     }
 6092:                 }
 6093:                 my $add_domtitle = &mt('Users in additional domain:');
 6094:                 if ($curr_types eq '*') { 
 6095:                     $add_domtitle = &mt('Users in specific domain:');
 6096:                 } elsif ($curr_types eq '') {
 6097:                     $add_domtitle = &mt('Users in other domain:');
 6098:                 }
 6099:                 $output .= &Apache::loncommon::start_data_table_row()
 6100:                            .'<td colspan="2"><span class="LC_nobreak">'.$add_domtitle.'</span><br />'
 6101:                            .&Apache::loncommon::select_dom_form('','selfenroll_newdom',
 6102:                                                                 $includeempty,$showdomdesc,'','','',$readonly)
 6103:                            .'<input type="hidden" name="selfenroll_types_total" value="'.$num.'" />'
 6104:                            .'</td>'.&Apache::loncommon::end_data_table_row()
 6105:                            .&Apache::loncommon::end_data_table();
 6106:             } elsif ($item eq 'registered') {
 6107:                 my ($regon,$regoff);
 6108:                 my $registered;
 6109:                 if (ref($currsettings) eq 'HASH') {
 6110:                     $registered = $currsettings->{'selfenroll_registered'};
 6111:                 }
 6112:                 if ($noedit{$item}) {
 6113:                     if ($registered) {
 6114:                         $output .= &mt('Must be registered in course');
 6115:                     } else {
 6116:                         $output .= &mt('No requirement');
 6117:                     }
 6118:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 6119:                     next;
 6120:                 }
 6121:                 if ($registered) {
 6122:                     $regon = ' checked="checked" ';
 6123:                     $regoff = '';
 6124:                 } else {
 6125:                     $regon = '';
 6126:                     $regoff = ' checked="checked" ';
 6127:                 }
 6128:                 $output .= '<label>'.
 6129:                            '<input type="radio" name="selfenroll_registered" value="1"'.$regon.$disabled.' />'.
 6130:                            &mt('Yes').'</label>&nbsp;&nbsp;<label>'.
 6131:                            '<input type="radio" name="selfenroll_registered" value="0"'.$regoff.$disabled.' />'.
 6132:                            &mt('No').'</label>';
 6133:             } elsif ($item eq 'enroll_dates') {
 6134:                 my ($starttime,$endtime);
 6135:                 if (ref($currsettings) eq 'HASH') {
 6136:                     $starttime = $currsettings->{'selfenroll_start_date'};
 6137:                     $endtime = $currsettings->{'selfenroll_end_date'};
 6138:                     if ($starttime eq '') {
 6139:                         $starttime = $currsettings->{'default_enrollment_start_date'};
 6140:                     }
 6141:                     if ($endtime eq '') {
 6142:                         $endtime = $currsettings->{'default_enrollment_end_date'};
 6143:                     }
 6144:                 }
 6145:                 if ($noedit{$item}) {
 6146:                     $output .= &mt('From: [_1], to: [_2]',&Apache::lonlocal::locallocaltime($starttime),
 6147:                                                           &Apache::lonlocal::locallocaltime($endtime));
 6148:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 6149:                     next;
 6150:                 }
 6151:                 my $startform =
 6152:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_start_date',$starttime,
 6153:                                       $disabled,undef,undef,undef,undef,undef,undef,$nolink);
 6154:                 my $endform =
 6155:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_end_date',$endtime,
 6156:                                       $disabled,undef,undef,undef,undef,undef,undef,$nolink);
 6157:                 $output .= &selfenroll_date_forms($startform,$endform);
 6158:             } elsif ($item eq 'access_dates') {
 6159:                 my ($starttime,$endtime);
 6160:                 if (ref($currsettings) eq 'HASH') {
 6161:                     $starttime = $currsettings->{'selfenroll_start_access'};
 6162:                     $endtime = $currsettings->{'selfenroll_end_access'};
 6163:                     if ($starttime eq '') {
 6164:                         $starttime = $currsettings->{'default_enrollment_start_date'};
 6165:                     }
 6166:                     if ($endtime eq '') {
 6167:                         $endtime = $currsettings->{'default_enrollment_end_date'};
 6168:                     }
 6169:                 }
 6170:                 if ($noedit{$item}) {
 6171:                     $output .= &mt('From: [_1], to: [_2]',&Apache::lonlocal::locallocaltime($starttime),
 6172:                                                           &Apache::lonlocal::locallocaltime($endtime));
 6173:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 6174:                     next;
 6175:                 }
 6176:                 my $startform =
 6177:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_start_access',$starttime,
 6178:                                       $disabled,undef,undef,undef,undef,undef,undef,$nolink);
 6179:                 my $endform =
 6180:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_end_access',$endtime,
 6181:                                       $disabled,undef,undef,undef,undef,undef,undef,$nolink);
 6182:                 $output .= &selfenroll_date_forms($startform,$endform);
 6183:             } elsif ($item eq 'section') {
 6184:                 my $currsec;
 6185:                 if (ref($currsettings) eq 'HASH') {
 6186:                     $currsec = $currsettings->{'selfenroll_section'};
 6187:                 }
 6188:                 my %sections_count = &Apache::loncommon::get_sections($cdom,$cnum);
 6189:                 my $newsecval;
 6190:                 if ($currsec ne 'none' && $currsec ne '') {
 6191:                     if (!defined($sections_count{$currsec})) {
 6192:                         $newsecval = $currsec;
 6193:                     }
 6194:                 }
 6195:                 if ($noedit{$item}) {
 6196:                     if ($currsec ne '') {
 6197:                         $output .= $currsec;
 6198:                     } else {
 6199:                         $output .= &mt('No specific section');
 6200:                     }
 6201:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 6202:                     next;
 6203:                 }
 6204:                 my $sections_select = 
 6205:                     &Apache::lonuserutils::course_sections(\%sections_count,'st',$currsec,$disabled);
 6206:                 $output .= '<table class="LC_createuser">'."\n".
 6207:                            '<tr class="LC_section_row">'."\n".
 6208:                            '<td align="center">'.&mt('Existing sections')."\n".
 6209:                            '<br />'.$sections_select.'</td><td align="center">'.
 6210:                            &mt('New section').'<br />'."\n".
 6211:                            '<input type="text" name="newsec" size="15" value="'.$newsecval.'"'.$disabled.' />'."\n".
 6212:                            '<input type="hidden" name="sections" value="" />'."\n".
 6213:                            '</td></tr></table>'."\n";
 6214:             } elsif ($item eq 'approval') {
 6215:                 my ($currnotified,$currapproval,%appchecked);
 6216:                 my %selfdescs = &Apache::lonuserutils::selfenroll_default_descs();
 6217:                 if (ref($currsettings) eq 'HASH') { 
 6218:                     $currnotified = $currsettings->{'selfenroll_notifylist'};
 6219:                     $currapproval = $currsettings->{'selfenroll_approval'};
 6220:                 }
 6221:                 if ($currapproval !~ /^[012]$/) {
 6222:                     $currapproval = 0;
 6223:                 }
 6224:                 if ($noedit{$item}) {
 6225:                     $output .=  $selfdescs{'approval'}{$currapproval}.
 6226:                                 '<br />'.&mt('(Set by Domain Coordinator)');
 6227:                     next;
 6228:                 }
 6229:                 $appchecked{$currapproval} = ' checked="checked"';
 6230:                 for my $i (0..2) {
 6231:                     $output .= '<label>'.
 6232:                                '<input type="radio" name="selfenroll_approval" value="'.$i.'"'.
 6233:                                $appchecked{$i}.' onclick="toggleNotify();"'.$disabled.' />'.
 6234:                                $selfdescs{'approval'}{$i}.'</label>'.('&nbsp;'x2);
 6235:                 }
 6236:                 my %advhash = &Apache::lonnet::get_course_adv_roles($cid,1);
 6237:                 my (@ccs,%notified);
 6238:                 my $ccrole = 'cc';
 6239:                 if ($crstype eq 'Community') {
 6240:                     $ccrole = 'co';
 6241:                 }
 6242:                 if ($advhash{$ccrole}) {
 6243:                     @ccs = split(/,/,$advhash{$ccrole});
 6244:                 }
 6245:                 if ($currnotified) {
 6246:                     foreach my $current (split(/,/,$currnotified)) {
 6247:                         $notified{$current} = 1;
 6248:                         if (!grep(/^\Q$current\E$/,@ccs)) {
 6249:                             push(@ccs,$current);
 6250:                         }
 6251:                     }
 6252:                 }
 6253:                 if (@ccs) {
 6254:                     my $style;
 6255:                     unless ($currapproval) {
 6256:                         $style = ' style="display: none;"'; 
 6257:                     }
 6258:                     $output .= '<br /><div id="notified"'.$style.'>'.
 6259:                                &mt('Personnel to be notified when an enrollment request needs approval, or has been approved:').'&nbsp;'.
 6260:                                &Apache::loncommon::start_data_table().
 6261:                                &Apache::loncommon::start_data_table_row();
 6262:                     my $count = 0;
 6263:                     my $numcols = 4;
 6264:                     foreach my $cc (sort(@ccs)) {
 6265:                         my $notifyon;
 6266:                         my ($ccuname,$ccudom) = split(/:/,$cc);
 6267:                         if ($notified{$cc}) {
 6268:                             $notifyon = ' checked="checked" ';
 6269:                         }
 6270:                         if ($count && !$count%$numcols) {
 6271:                             $output .= &Apache::loncommon::end_data_table_row().
 6272:                                        &Apache::loncommon::start_data_table_row()
 6273:                         }
 6274:                         $output .= '<td><span class="LC_nobreak"><label>'.
 6275:                                    '<input type="checkbox" name="selfenroll_notify"'.$notifyon.' value="'.$cc.'"'.$disabled.' />'.
 6276:                                    &Apache::loncommon::plainname($ccuname,$ccudom).
 6277:                                    '</label></span></td>';
 6278:                         $count ++;
 6279:                     }
 6280:                     my $rem = $count%$numcols;
 6281:                     if ($rem) {
 6282:                         my $emptycols = $numcols - $rem;
 6283:                         for (my $i=0; $i<$emptycols; $i++) { 
 6284:                             $output .= '<td>&nbsp;</td>';
 6285:                         }
 6286:                     }
 6287:                     $output .= &Apache::loncommon::end_data_table_row().
 6288:                                &Apache::loncommon::end_data_table().
 6289:                                '</div>';
 6290:                 }
 6291:             } elsif ($item eq 'limit') {
 6292:                 my ($crslimit,$selflimit,$nolimit,$currlim,$currcap);
 6293:                 if (ref($currsettings) eq 'HASH') {
 6294:                     $currlim = $currsettings->{'selfenroll_limit'};
 6295:                     $currcap = $currsettings->{'selfenroll_cap'};
 6296:                 }
 6297:                 if ($noedit{$item}) {
 6298:                     if (($currlim eq 'allstudents') || ($currlim eq 'selfenrolled')) {
 6299:                         if ($currlim eq 'allstudents') {
 6300:                             $output .= &mt('Limit by total students');
 6301:                         } elsif ($currlim eq 'selfenrolled') {
 6302:                             $output .= &mt('Limit by total self-enrolled students');
 6303:                         }
 6304:                         $output .= ' '.&mt('Maximum: [_1]',$currcap).
 6305:                                    '<br />'.&mt('(Set by Domain Coordinator)');
 6306:                     } else {
 6307:                         $output .= &mt('No limit').'<br />'.&mt('(Set by Domain Coordinator)');
 6308:                     }
 6309:                     next;
 6310:                 }
 6311:                 if ($currlim eq 'allstudents') {
 6312:                     $crslimit = ' checked="checked" ';
 6313:                     $selflimit = ' ';
 6314:                     $nolimit = ' ';
 6315:                 } elsif ($currlim eq 'selfenrolled') {
 6316:                     $crslimit = ' ';
 6317:                     $selflimit = ' checked="checked" ';
 6318:                     $nolimit = ' '; 
 6319:                 } else {
 6320:                     $crslimit = ' ';
 6321:                     $selflimit = ' ';
 6322:                     $nolimit = ' checked="checked" ';
 6323:                 }
 6324:                 $output .= '<table><tr><td><label>'.
 6325:                            '<input type="radio" name="selfenroll_limit" value="none"'.$nolimit.$disabled.'/>'.
 6326:                            &mt('No limit').'</label></td><td><label>'.
 6327:                            '<input type="radio" name="selfenroll_limit" value="allstudents"'.$crslimit.$disabled.'/>'.
 6328:                            &mt('Limit by total students').'</label></td><td><label>'.
 6329:                            '<input type="radio" name="selfenroll_limit" value="selfenrolled"'.$selflimit.$disabled.'/>'.
 6330:                            &mt('Limit by total self-enrolled students').
 6331:                            '</td></tr><tr>'.
 6332:                            '<td>&nbsp;</td><td colspan="2"><span class="LC_nobreak">'.
 6333:                            ('&nbsp;'x3).&mt('Maximum number allowed: ').
 6334:                            '<input type="text" name="selfenroll_cap" size = "5" value="'.$currcap.'"'.$disabled.' /></td></tr></table>';
 6335:             }
 6336:             $output .= &Apache::lonhtmlcommon::row_closure(1);
 6337:         }
 6338:     }
 6339:     $output .= &Apache::lonhtmlcommon::end_pick_box().'<br />';
 6340:     unless ($readonly) {
 6341:         $output .= '<input type="button" name="selfenrollconf" value="'
 6342:                    .&mt('Save').'" onclick="validate_types(this.form);" />';
 6343:     }
 6344:     $output .= '<input type="hidden" name="action" value="selfenroll" />'
 6345:               .'<input type="hidden" name="state" value="done" />'."\n"
 6346:               .$additional.'</form>';
 6347:     $r->print($output);
 6348:     return;
 6349: }
 6350: 
 6351: sub get_noedit_fields {
 6352:     my ($cdom,$cnum,$crstype,$row) = @_;
 6353:     my %noedit;
 6354:     if (ref($row) eq 'ARRAY') {
 6355:         my %settings = &Apache::lonnet::get('environment',['internal.coursecode','internal.textbook',
 6356:                                                            'internal.selfenrollmgrdc',
 6357:                                                            'internal.selfenrollmgrcc'],$cdom,$cnum);
 6358:         my $type = &Apache::lonuserutils::get_extended_type($cdom,$cnum,$crstype,\%settings);
 6359:         my (%specific_managebydc,%specific_managebycc,%default_managebydc);
 6360:         map { $specific_managebydc{$_} = 1; } (split(/,/,$settings{'internal.selfenrollmgrdc'}));
 6361:         map { $specific_managebycc{$_} = 1; } (split(/,/,$settings{'internal.selfenrollmgrcc'}));
 6362:         my %domdefaults = &Apache::lonnet::get_domain_defaults($cdom);
 6363:         map { $default_managebydc{$_} = 1; } (split(/,/,$domdefaults{$type.'selfenrolladmdc'}));
 6364: 
 6365:         foreach my $item (@{$row}) {
 6366:             next if ($specific_managebycc{$item});
 6367:             if (($specific_managebydc{$item}) || ($default_managebydc{$item})) {
 6368:                 $noedit{$item} = 1;
 6369:             }
 6370:         }
 6371:     }
 6372:     return %noedit;
 6373: } 
 6374: 
 6375: sub visible_in_stdcat {
 6376:     my ($cdom,$cnum,$domconf) = @_;
 6377:     my ($cathash,%settable,@vismsgs,$cansetvis,$visible);
 6378:     unless (ref($domconf) eq 'HASH') {
 6379:         return ($visible,$cansetvis,\@vismsgs);
 6380:     }
 6381:     if (ref($domconf->{'coursecategories'}) eq 'HASH') {
 6382:         if ($domconf->{'coursecategories'}{'togglecats'} eq 'crs') {
 6383:             $settable{'togglecats'} = 1;
 6384:         }
 6385:         if ($domconf->{'coursecategories'}{'categorize'} eq 'crs') {
 6386:             $settable{'categorize'} = 1;
 6387:         }
 6388:         $cathash = $domconf->{'coursecategories'}{'cats'};
 6389:     }
 6390:     if ($settable{'togglecats'} && $settable{'categorize'}) {
 6391:         $cansetvis = &mt('You are able to both assign a course category and choose to exclude this course from the catalog.');   
 6392:     } elsif ($settable{'togglecats'}) {
 6393:         $cansetvis = &mt('You are able to choose to exclude this course from the catalog, but only a Domain Coordinator may assign a course category.'); 
 6394:     } elsif ($settable{'categorize'}) {
 6395:         $cansetvis = &mt('You may assign a course category, but only a Domain Coordinator may choose to exclude this course from the catalog.');  
 6396:     } else {
 6397:         $cansetvis = &mt('Only a Domain Coordinator may assign a course category or choose to exclude this course from the catalog.'); 
 6398:     }
 6399:      
 6400:     my %currsettings =
 6401:         &Apache::lonnet::get('environment',['hidefromcat','categories','internal.coursecode'],
 6402:                              $cdom,$cnum);
 6403:     $visible = 0;
 6404:     if ($currsettings{'internal.coursecode'} ne '') {
 6405:         if (ref($domconf->{'coursecategories'}) eq 'HASH') {
 6406:             $cathash = $domconf->{'coursecategories'}{'cats'};
 6407:             if (ref($cathash) eq 'HASH') {
 6408:                 if ($cathash->{'instcode::0'} eq '') {
 6409:                     push(@vismsgs,'dc_addinst'); 
 6410:                 } else {
 6411:                     $visible = 1;
 6412:                 }
 6413:             } else {
 6414:                 $visible = 1;
 6415:             }
 6416:         } else {
 6417:             $visible = 1;
 6418:         }
 6419:     } else {
 6420:         if (ref($cathash) eq 'HASH') {
 6421:             if ($cathash->{'instcode::0'} ne '') {
 6422:                 push(@vismsgs,'dc_instcode');
 6423:             }
 6424:         } else {
 6425:             push(@vismsgs,'dc_instcode');
 6426:         }
 6427:     }
 6428:     if ($currsettings{'categories'} ne '') {
 6429:         my $cathash;
 6430:         if (ref($domconf->{'coursecategories'}) eq 'HASH') {
 6431:             $cathash = $domconf->{'coursecategories'}{'cats'};
 6432:             if (ref($cathash) eq 'HASH') {
 6433:                 if (keys(%{$cathash}) == 0) {
 6434:                     push(@vismsgs,'dc_catalog');
 6435:                 } elsif ((keys(%{$cathash}) == 1) && ($cathash->{'instcode::0'} ne '')) {
 6436:                     push(@vismsgs,'dc_categories');
 6437:                 } else {
 6438:                     my @currcategories = split('&',$currsettings{'categories'});
 6439:                     my $matched = 0;
 6440:                     foreach my $cat (@currcategories) {
 6441:                         if ($cathash->{$cat} ne '') {
 6442:                             $visible = 1;
 6443:                             $matched = 1;
 6444:                             last;
 6445:                         }
 6446:                     }
 6447:                     if (!$matched) {
 6448:                         if ($settable{'categorize'}) { 
 6449:                             push(@vismsgs,'chgcat');
 6450:                         } else {
 6451:                             push(@vismsgs,'dc_chgcat');
 6452:                         }
 6453:                     }
 6454:                 }
 6455:             }
 6456:         }
 6457:     } else {
 6458:         if (ref($cathash) eq 'HASH') {
 6459:             if ((keys(%{$cathash}) > 1) || 
 6460:                 (keys(%{$cathash}) == 1) && ($cathash->{'instcode::0'} eq '')) {
 6461:                 if ($settable{'categorize'}) {
 6462:                     push(@vismsgs,'addcat');
 6463:                 } else {
 6464:                     push(@vismsgs,'dc_addcat');
 6465:                 }
 6466:             }
 6467:         }
 6468:     }
 6469:     if ($currsettings{'hidefromcat'} eq 'yes') {
 6470:         $visible = 0;
 6471:         if ($settable{'togglecats'}) {
 6472:             unshift(@vismsgs,'unhide');
 6473:         } else {
 6474:             unshift(@vismsgs,'dc_unhide')
 6475:         }
 6476:     }
 6477:     return ($visible,$cansetvis,\@vismsgs);
 6478: }
 6479: 
 6480: sub cat_visibility {
 6481:     my %visactions = &Apache::lonlocal::texthash(
 6482:                    vis => 'This course/community currently appears in the Course/Community Catalog for this domain.',
 6483:                    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.',
 6484:                    miss => 'This course/community does not currently appear in the Course/Community Catalog for this domain.',
 6485:                    none => 'Display of a course catalog is disabled for this domain.',
 6486:                    yous => 'You should remedy this if you plan to allow self-enrollment, otherwise students will have difficulty finding this course.',
 6487:                    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.',
 6488:                    make => 'Make any changes to self-enrollment settings below, click "Save", then take action to include the course in the Catalog:',
 6489:                    take => 'Take the following action to ensure the course appears in the Catalog:',
 6490:                    dc_chgconf => 'Ask a domain coordinator to change the Catalog type for this domain.',
 6491:                    dc_setcode => 'Ask a domain coordinator to assign a six character code to the course',
 6492:                    dc_unhide  => 'Ask a domain coordinator to change the "Exclude from course catalog" setting.',
 6493:                    dc_addinst => 'Ask a domain coordinator to enable display the catalog of "Official courses (with institutional codes)".',
 6494:                    dc_instcode => 'Ask a domain coordinator to assign an institutional code (if this is an official course).',
 6495:                    dc_catalog  => 'Ask a domain coordinator to enable or create at least one course category in the domain.',
 6496:                    dc_categories => 'Ask a domain coordinator to create a hierarchy of categories and sub categories for courses in the domain.',
 6497:                    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',
 6498:                    dc_addcat => 'Ask a domain coordinator to assign a category to the course.',
 6499:     );
 6500:     $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>"');
 6501:     $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>"');
 6502:     $visactions{'addcat'} = &mt('Use [_1]Categorize course[_2] to assign a category to the course.','"<a href="/adm/courseprefs?phase=display&actions=courseinfo">','</a>"');
 6503:     return \%visactions;
 6504: }
 6505: 
 6506: sub new_selfenroll_dom_row {
 6507:     my ($newdom,$num) = @_;
 6508:     my $domdesc = &Apache::lonnet::domain($newdom);
 6509:     my $output;
 6510:     if ($domdesc ne '') {
 6511:         $output .= &Apache::loncommon::start_data_table_row()
 6512:                    .'<td valign="top"><span class="LC_nobreak">'.&mt('Domain:').'&nbsp;<b>'.$domdesc
 6513:                    .' ('.$newdom.')</b><input type="hidden" name="selfenroll_dom_'.$num
 6514:                    .'" value="'.$newdom.'" /></span><br />'
 6515:                    .'<span class="LC_nobreak"><label><input type="checkbox" '
 6516:                    .'name="selfenroll_activate" value="'.$num.'" '
 6517:                    .'onchange="javascript:update_types('
 6518:                    ."'selfenroll_activate','$num'".');" />'
 6519:                    .&mt('Activate').'</label></span></td>';
 6520:         my @currinsttypes;
 6521:         $output .= '<td>'.&mt('User types:').'<br />'
 6522:                    .&selfenroll_inst_types($num,$newdom,\@currinsttypes).'</td>'
 6523:                    .&Apache::loncommon::end_data_table_row();
 6524:     }
 6525:     return $output;
 6526: }
 6527: 
 6528: sub selfenroll_inst_types {
 6529:     my ($num,$currdom,$currinsttypes,$readonly) = @_;
 6530:     my $output;
 6531:     my $numinrow = 4;
 6532:     my $count = 0;
 6533:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($currdom);
 6534:     my $othervalue = 'any';
 6535:     my $disabled;
 6536:     if ($readonly) {
 6537:         $disabled = ' disabled="disabled"';
 6538:     }
 6539:     if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 6540:         if (keys(%{$usertypes}) > 0) {
 6541:             $othervalue = 'other';
 6542:         }
 6543:         $output .= '<table><tr>';
 6544:         foreach my $type (@{$types}) {
 6545:             if (($count > 0) && ($count%$numinrow == 0)) {
 6546:                 $output .= '</tr><tr>';
 6547:             }
 6548:             if (defined($usertypes->{$type})) {
 6549:                 my $esc_type = &escape($type);
 6550:                 $output .= '<td><span class="LC_nobreak"><label><input type = "checkbox" value="'.
 6551:                            $esc_type.'" ';
 6552:                 if (ref($currinsttypes) eq 'ARRAY') {
 6553:                     if (@{$currinsttypes} > 0) {
 6554:                         if (grep(/^any$/,@{$currinsttypes})) {
 6555:                             $output .= 'checked="checked"';
 6556:                         } elsif (grep(/^\Q$esc_type\E$/,@{$currinsttypes})) {
 6557:                             $output .= 'checked="checked"';
 6558:                         }
 6559:                     } else {
 6560:                         $output .= 'checked="checked"';
 6561:                     }
 6562:                 }
 6563:                 $output .= ' name="selfenroll_types_'.$num.'"'.$disabled.' />'.$usertypes->{$type}.'</label></span></td>';
 6564:             }
 6565:             $count ++;
 6566:         }
 6567:         if (($count > 0) && ($count%$numinrow == 0)) {
 6568:             $output .= '</tr><tr>';
 6569:         }
 6570:         $output .= '<td><span class="LC_nobreak"><label><input type = "checkbox" value="'.$othervalue.'"';
 6571:         if (ref($currinsttypes) eq 'ARRAY') {
 6572:             if (@{$currinsttypes} > 0) {
 6573:                 if (grep(/^any$/,@{$currinsttypes})) { 
 6574:                     $output .= ' checked="checked"';
 6575:                 } elsif ($othervalue eq 'other') {
 6576:                     if (grep(/^\Q$othervalue\E$/,@{$currinsttypes})) {
 6577:                         $output .= ' checked="checked"';
 6578:                     }
 6579:                 }
 6580:             } else {
 6581:                 $output .= ' checked="checked"';
 6582:             }
 6583:         } else {
 6584:             $output .= ' checked="checked"';
 6585:         }
 6586:         $output .= ' name="selfenroll_types_'.$num.'"'.$disabled.' />'.$othertitle.'</label></span></td></tr></table>';
 6587:     }
 6588:     return $output;
 6589: }
 6590: 
 6591: sub selfenroll_date_forms {
 6592:     my ($startform,$endform) = @_;
 6593:     my $output .= &Apache::lonhtmlcommon::start_pick_box()."\n".
 6594:                   &Apache::lonhtmlcommon::row_title(&mt('Start date'),
 6595:                                                     'LC_oddrow_value')."\n".
 6596:                   $startform."\n".
 6597:                   &Apache::lonhtmlcommon::row_closure(1).
 6598:                   &Apache::lonhtmlcommon::row_title(&mt('End date'),
 6599:                                                    'LC_oddrow_value')."\n".
 6600:                   $endform."\n".
 6601:                   &Apache::lonhtmlcommon::row_closure(1).
 6602:                   &Apache::lonhtmlcommon::end_pick_box();
 6603:     return $output;
 6604: }
 6605: 
 6606: sub print_userchangelogs_display {
 6607:     my ($r,$context,$permission,$brcrum) = @_;
 6608:     my $formname = 'rolelog';
 6609:     my ($username,$domain,$crstype,$viewablesec,%roleslog);
 6610:     if ($context eq 'domain') {
 6611:         $domain = $env{'request.role.domain'};
 6612:         %roleslog=&Apache::lonnet::dump_dom('nohist_rolelog',$domain);
 6613:     } else {
 6614:         if ($context eq 'course') { 
 6615:             $domain = $env{'course.'.$env{'request.course.id'}.'.domain'};
 6616:             $username = $env{'course.'.$env{'request.course.id'}.'.num'};
 6617:             $crstype = &Apache::loncommon::course_type();
 6618:             $viewablesec = &Apache::lonuserutils::viewable_section($permission);
 6619:             my %saveable_parameters = ('show' => 'scalar',);
 6620:             &Apache::loncommon::store_course_settings('roles_log',
 6621:                                                       \%saveable_parameters);
 6622:             &Apache::loncommon::restore_course_settings('roles_log',
 6623:                                                         \%saveable_parameters);
 6624:         } elsif ($context eq 'author') {
 6625:             $domain = $env{'user.domain'}; 
 6626:             if ($env{'request.role'} =~ m{^au\./\Q$domain\E/$}) {
 6627:                 $username = $env{'user.name'};
 6628:             } else {
 6629:                 undef($domain);
 6630:             }
 6631:         }
 6632:         if ($domain ne '' && $username ne '') { 
 6633:             %roleslog=&Apache::lonnet::dump('nohist_rolelog',$domain,$username);
 6634:         }
 6635:     }
 6636:     if ((keys(%roleslog))[0]=~/^error\:/) { undef(%roleslog); }
 6637: 
 6638:     my $helpitem;
 6639:     if ($context eq 'course') {
 6640:         $helpitem = 'Course_User_Logs';
 6641:     }
 6642:     push (@{$brcrum},
 6643:              {href => '/adm/createuser?action=changelogs',
 6644:               text => 'User Management Logs',
 6645:               help => $helpitem});
 6646:     my $bread_crumbs_component = 'User Changes';
 6647:     my $args = { bread_crumbs           => $brcrum,
 6648:                  bread_crumbs_component => $bread_crumbs_component};
 6649: 
 6650:     # Create navigation javascript
 6651:     my $jsnav = &userlogdisplay_js($formname);
 6652: 
 6653:     my $jscript = (<<ENDSCRIPT);
 6654: <script type="text/javascript">
 6655: // <![CDATA[
 6656: $jsnav
 6657: // ]]>
 6658: </script>
 6659: ENDSCRIPT
 6660: 
 6661:     # print page header
 6662:     $r->print(&header($jscript,$args));
 6663: 
 6664:     # set defaults
 6665:     my $now = time();
 6666:     my $defstart = $now - (7*24*3600); #7 days ago 
 6667:     my %defaults = (
 6668:                      page               => '1',
 6669:                      show               => '10',
 6670:                      role               => 'any',
 6671:                      chgcontext         => 'any',
 6672:                      rolelog_start_date => $defstart,
 6673:                      rolelog_end_date   => $now,
 6674:                    );
 6675:     my $more_records = 0;
 6676: 
 6677:     # set current
 6678:     my %curr;
 6679:     foreach my $item ('show','page','role','chgcontext') {
 6680:         $curr{$item} = $env{'form.'.$item};
 6681:     }
 6682:     my ($startdate,$enddate) = 
 6683:         &Apache::lonuserutils::get_dates_from_form('rolelog_start_date','rolelog_end_date');
 6684:     $curr{'rolelog_start_date'} = $startdate;
 6685:     $curr{'rolelog_end_date'} = $enddate;
 6686:     foreach my $key (keys(%defaults)) {
 6687:         if ($curr{$key} eq '') {
 6688:             $curr{$key} = $defaults{$key};
 6689:         }
 6690:     }
 6691:     my (%whodunit,%changed,$version);
 6692:     ($version) = ($r->dir_config('lonVersion') =~ /^([\d\.]+)\-/);
 6693:     my ($minshown,$maxshown);
 6694:     $minshown = 1;
 6695:     my $count = 0;
 6696:     if ($curr{'show'} =~ /\D/) {
 6697:         $curr{'page'} = 1;
 6698:     } else {
 6699:         $maxshown = $curr{'page'} * $curr{'show'};
 6700:         if ($curr{'page'} > 1) {
 6701:             $minshown = 1 + ($curr{'page'} - 1) * $curr{'show'};
 6702:         }
 6703:     }
 6704: 
 6705:     # Form Header
 6706:     $r->print('<form action="/adm/createuser" method="post" name="'.$formname.'">'.
 6707:               &role_display_filter($context,$formname,$domain,$username,\%curr,
 6708:                                    $version,$crstype));
 6709: 
 6710:     my $showntableheader = 0;
 6711: 
 6712:     # Table Header
 6713:     my $tableheader = 
 6714:         &Apache::loncommon::start_data_table_header_row()
 6715:        .'<th>&nbsp;</th>'
 6716:        .'<th>'.&mt('When').'</th>'
 6717:        .'<th>'.&mt('Who made the change').'</th>'
 6718:        .'<th>'.&mt('Changed User').'</th>'
 6719:        .'<th>'.&mt('Role').'</th>';
 6720: 
 6721:     if ($context eq 'course') {
 6722:         $tableheader .= '<th>'.&mt('Section').'</th>';
 6723:     }
 6724:     $tableheader .=
 6725:         '<th>'.&mt('Context').'</th>'
 6726:        .'<th>'.&mt('Start').'</th>'
 6727:        .'<th>'.&mt('End').'</th>'
 6728:        .&Apache::loncommon::end_data_table_header_row();
 6729: 
 6730:     # Display user change log data
 6731:     foreach my $id (sort { $roleslog{$b}{'exe_time'}<=>$roleslog{$a}{'exe_time'} } (keys(%roleslog))) {
 6732:         next if (($roleslog{$id}{'exe_time'} < $curr{'rolelog_start_date'}) ||
 6733:                  ($roleslog{$id}{'exe_time'} > $curr{'rolelog_end_date'}));
 6734:         if ($curr{'show'} !~ /\D/) {
 6735:             if ($count >= $curr{'page'} * $curr{'show'}) {
 6736:                 $more_records = 1;
 6737:                 last;
 6738:             }
 6739:         }
 6740:         if ($curr{'role'} ne 'any') {
 6741:             next if ($roleslog{$id}{'logentry'}{'role'} ne $curr{'role'}); 
 6742:         }
 6743:         if ($curr{'chgcontext'} ne 'any') {
 6744:             if ($curr{'chgcontext'} eq 'selfenroll') {
 6745:                 next if (!$roleslog{$id}{'logentry'}{'selfenroll'});
 6746:             } else {
 6747:                 next if ($roleslog{$id}{'logentry'}{'context'} ne $curr{'chgcontext'});
 6748:             }
 6749:         }
 6750:         if (($context eq 'course') && ($viewablesec ne '')) {
 6751:             next if ($roleslog{$id}{'logentry'}{'section'} ne $viewablesec); 
 6752:         }
 6753:         $count ++;
 6754:         next if ($count < $minshown);
 6755:         unless ($showntableheader) {
 6756:             $r->print(&Apache::loncommon::start_data_table()
 6757:                      .$tableheader);
 6758:             $r->rflush();
 6759:             $showntableheader = 1;
 6760:         }
 6761:         if ($whodunit{$roleslog{$id}{'exe_uname'}.':'.$roleslog{$id}{'exe_udom'}} eq '') {
 6762:             $whodunit{$roleslog{$id}{'exe_uname'}.':'.$roleslog{$id}{'exe_udom'}} =
 6763:                 &Apache::loncommon::plainname($roleslog{$id}{'exe_uname'},$roleslog{$id}{'exe_udom'});
 6764:         }
 6765:         if ($changed{$roleslog{$id}{'uname'}.':'.$roleslog{$id}{'udom'}} eq '') {
 6766:             $changed{$roleslog{$id}{'uname'}.':'.$roleslog{$id}{'udom'}} =
 6767:                 &Apache::loncommon::plainname($roleslog{$id}{'uname'},$roleslog{$id}{'udom'});
 6768:         }
 6769:         my $sec = $roleslog{$id}{'logentry'}{'section'};
 6770:         if ($sec eq '') {
 6771:             $sec = &mt('None');
 6772:         }
 6773:         my ($rolestart,$roleend);
 6774:         if ($roleslog{$id}{'delflag'}) {
 6775:             $rolestart = &mt('deleted');
 6776:             $roleend = &mt('deleted');
 6777:         } else {
 6778:             $rolestart = $roleslog{$id}{'logentry'}{'start'};
 6779:             $roleend = $roleslog{$id}{'logentry'}{'end'};
 6780:             if ($rolestart eq '' || $rolestart == 0) {
 6781:                 $rolestart = &mt('No start date'); 
 6782:             } else {
 6783:                 $rolestart = &Apache::lonlocal::locallocaltime($rolestart);
 6784:             }
 6785:             if ($roleend eq '' || $roleend == 0) { 
 6786:                 $roleend = &mt('No end date');
 6787:             } else {
 6788:                 $roleend = &Apache::lonlocal::locallocaltime($roleend);
 6789:             }
 6790:         }
 6791:         my $chgcontext = $roleslog{$id}{'logentry'}{'context'};
 6792:         if ($roleslog{$id}{'logentry'}{'selfenroll'}) {
 6793:             $chgcontext = 'selfenroll';
 6794:         }
 6795:         my %lt = &rolechg_contexts($context,$crstype);
 6796:         if ($chgcontext ne '' && $lt{$chgcontext} ne '') {
 6797:             $chgcontext = $lt{$chgcontext};
 6798:         }
 6799:         $r->print(
 6800:             &Apache::loncommon::start_data_table_row()
 6801:            .'<td>'.$count.'</td>'
 6802:            .'<td>'.&Apache::lonlocal::locallocaltime($roleslog{$id}{'exe_time'}).'</td>'
 6803:            .'<td>'.$whodunit{$roleslog{$id}{'exe_uname'}.':'.$roleslog{$id}{'exe_udom'}}.'</td>'
 6804:            .'<td>'.$changed{$roleslog{$id}{'uname'}.':'.$roleslog{$id}{'udom'}}.'</td>'
 6805:            .'<td>'.&Apache::lonnet::plaintext($roleslog{$id}{'logentry'}{'role'},$crstype).'</td>');
 6806:         if ($context eq 'course') { 
 6807:             $r->print('<td>'.$sec.'</td>');
 6808:         }
 6809:         $r->print(
 6810:             '<td>'.$chgcontext.'</td>'
 6811:            .'<td>'.$rolestart.'</td>'
 6812:            .'<td>'.$roleend.'</td>'
 6813:            .&Apache::loncommon::end_data_table_row()."\n");
 6814:     }
 6815: 
 6816:     if ($showntableheader) { # Table footer, if content displayed above
 6817:         $r->print(&Apache::loncommon::end_data_table().
 6818:                   &userlogdisplay_navlinks(\%curr,$more_records));
 6819:     } else { # No content displayed above
 6820:         $r->print('<p class="LC_info">'
 6821:                  .&mt('There are no records to display.')
 6822:                  .'</p>'
 6823:         );
 6824:     }
 6825: 
 6826:     # Form Footer
 6827:     $r->print( 
 6828:         '<input type="hidden" name="page" value="'.$curr{'page'}.'" />'
 6829:        .'<input type="hidden" name="action" value="changelogs" />'
 6830:        .'</form>');
 6831:     return;
 6832: }
 6833: 
 6834: sub print_useraccesslogs_display {
 6835:     my ($r,$uname,$udom,$permission,$brcrum) = @_;
 6836:     my $formname = 'accesslog';
 6837:     my $form = 'document.accesslog';
 6838: 
 6839: # set breadcrumbs
 6840:     my %breadcrumb_text = &singleuser_breadcrumb('','domain',$udom);
 6841:     push (@{$brcrum},
 6842:         {href => "javascript:backPage($form)",
 6843:          text => $breadcrumb_text{'search'}});
 6844:     my (@prevphases,$prevphasestr);
 6845:     if ($env{'form.prevphases'}) {
 6846:         @prevphases = split(/,/,$env{'form.prevphases'});
 6847:         $prevphasestr = $env{'form.prevphases'};
 6848:     }
 6849:     if (($env{'form.phase'} eq 'userpicked') || (grep(/^userpicked$/,@prevphases))) {
 6850:         push(@{$brcrum},
 6851:               {href => "javascript:backPage($form,'get_user_info','select')",
 6852:                text => $breadcrumb_text{'userpicked'}});
 6853:         if ($env{'form.phase'} eq 'userpicked') {
 6854:             $prevphasestr = 'userpicked';
 6855:         }
 6856:     }
 6857:     push(@{$brcrum},
 6858:              {href => '/adm/createuser?action=accesslogs',
 6859:               text => 'User access logs',
 6860:               help => 'User_Access_Logs'});
 6861:     my $bread_crumbs_component = 'User Access Logs';
 6862:     my $args = { bread_crumbs           => $brcrum,
 6863:                  bread_crumbs_component => 'User Management'};
 6864: 
 6865: # set javascript
 6866:     my ($jsback,$elements) = &crumb_utilities();
 6867:     my $jsnav = &userlogdisplay_js($formname);
 6868: 
 6869:     my $jscript = (<<ENDSCRIPT);
 6870: <script type="text/javascript">
 6871: // <![CDATA[
 6872: 
 6873: $jsback
 6874: $jsnav
 6875: 
 6876: // ]]>
 6877: </script>
 6878: 
 6879: ENDSCRIPT
 6880: 
 6881: # print page header
 6882:     $r->print(&header($jscript,$args));
 6883: 
 6884: # early out unless log data can be displayed.
 6885:     unless ($permission->{'activity'}) {
 6886:         $r->print('<p class="LC_warning">'
 6887:                  .&mt('You do not have rights to display user access logs.')
 6888:                  .'</p>'
 6889:                  .&earlyout_accesslog_form($formname,$prevphasestr,$udom));
 6890:         return;
 6891:     }
 6892: 
 6893:     unless ($udom eq $env{'request.role.domain'}) {
 6894:         $r->print('<p class="LC_warning">'
 6895:                  .&mt("User's domain must match role's domain")
 6896:                  .'</p>'
 6897:                  .&earlyout_accesslog_form($formname,$prevphasestr,$udom));
 6898:         return;
 6899:     }
 6900: 
 6901:     if (($uname eq '') || ($udom eq '')) {
 6902:         $r->print('<p class="LC_warning">'
 6903:                  .&mt('Invalid username or domain')
 6904:                  .'</p>'
 6905:                  .&earlyout_accesslog_form($formname,$prevphasestr,$udom));
 6906:         return;
 6907:     }
 6908: 
 6909: # set defaults
 6910:     my $now = time();
 6911:     my $defstart = $now - (7*24*3600);
 6912:     my %defaults = (
 6913:                      page                 => '1',
 6914:                      show                 => '10',
 6915:                      activity             => 'any',
 6916:                      accesslog_start_date => $defstart,
 6917:                      accesslog_end_date   => $now,
 6918:                    );
 6919:     my $more_records = 0;
 6920: 
 6921: # set current
 6922:     my %curr;
 6923:     foreach my $item ('show','page','activity') {
 6924:         $curr{$item} = $env{'form.'.$item};
 6925:     }
 6926:     my ($startdate,$enddate) =
 6927:         &Apache::lonuserutils::get_dates_from_form('accesslog_start_date','accesslog_end_date');
 6928:     $curr{'accesslog_start_date'} = $startdate;
 6929:     $curr{'accesslog_end_date'} = $enddate;
 6930:     foreach my $key (keys(%defaults)) {
 6931:         if ($curr{$key} eq '') {
 6932:             $curr{$key} = $defaults{$key};
 6933:         }
 6934:     }
 6935:     my ($minshown,$maxshown);
 6936:     $minshown = 1;
 6937:     my $count = 0;
 6938:     if ($curr{'show'} =~ /\D/) {
 6939:         $curr{'page'} = 1;
 6940:     } else {
 6941:         $maxshown = $curr{'page'} * $curr{'show'};
 6942:         if ($curr{'page'} > 1) {
 6943:             $minshown = 1 + ($curr{'page'} - 1) * $curr{'show'};
 6944:         }
 6945:     }
 6946: 
 6947: # form header
 6948:     $r->print('<form action="/adm/createuser" method="post" name="'.$formname.'">'.
 6949:               &activity_display_filter($formname,\%curr));
 6950: 
 6951:     my $showntableheader = 0;
 6952:     my ($nav_script,$nav_links);
 6953: 
 6954: # table header
 6955:     my $tableheader =
 6956:         &Apache::loncommon::start_data_table_header_row()
 6957:        .'<th>&nbsp;</th>'
 6958:        .'<th>'.&mt('When').'</th>'
 6959:        .'<th>'.&mt('HostID').'</th>'
 6960:        .'<th>'.&mt('Event').'</th>'
 6961:        .'<th>'.&mt('Other data').'</th>'
 6962:        .&Apache::loncommon::end_data_table_header_row();
 6963: 
 6964:     my %filters=(
 6965:         start  => $curr{'accesslog_start_date'},
 6966:         end    => $curr{'accesslog_end_date'},
 6967:         action => $curr{'activity'},
 6968:     );
 6969: 
 6970:     my $reply = &Apache::lonnet::userlog_query($uname,$udom,%filters);
 6971:     unless ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 6972:         my (%courses,%missing);
 6973:         my @results = split(/\&/,$reply);
 6974:         foreach my $item (reverse(@results)) {
 6975:             my ($timestamp,$host,$event) = split(/:/,$item);
 6976:             next unless ($event =~ /^(Log|Role)/);
 6977:             if ($curr{'show'} !~ /\D/) {
 6978:                 if ($count >= $curr{'page'} * $curr{'show'}) {
 6979:                     $more_records = 1;
 6980:                     last;
 6981:                 }
 6982:             }
 6983:             $count ++;
 6984:             next if ($count < $minshown);
 6985:             unless ($showntableheader) {
 6986:                 $r->print($nav_script
 6987:                          .&Apache::loncommon::start_data_table()
 6988:                          .$tableheader);
 6989:                 $r->rflush();
 6990:                 $showntableheader = 1;
 6991:             }
 6992:             my ($shown,$extra);
 6993:             my ($event,$data) = split(/\s+/,&unescape($event));
 6994:             if ($event eq 'Role') {
 6995:                 my ($rolecode,$extent) = split(/\./,$data,2);
 6996:                 next if ($extent eq '');
 6997:                 my ($crstype,$desc,$info);
 6998:                 if ($extent =~ m{^/($match_domain)/($match_courseid)(?:/(\w+)|)$}) {
 6999:                     my ($cdom,$cnum,$sec) = ($1,$2,$3);
 7000:                     my $cid = $cdom.'_'.$cnum;
 7001:                     if (exists($courses{$cid})) {
 7002:                         $crstype = $courses{$cid}{'type'};
 7003:                         $desc = $courses{$cid}{'description'};
 7004:                     } elsif ($missing{$cid}) {
 7005:                         $crstype = 'Course';
 7006:                         $desc = 'Course/Community';
 7007:                     } else {
 7008:                         my %crsinfo = &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 7009:                         if (ref($crsinfo{$cdom.'_'.$cnum}) eq 'HASH') {
 7010:                             $courses{$cid} = $crsinfo{$cid};
 7011:                             $crstype = $crsinfo{$cid}{'type'};
 7012:                             $desc = $crsinfo{$cid}{'description'};
 7013:                         } else {
 7014:                             $missing{$cid} = 1;
 7015:                         }
 7016:                     }
 7017:                     $extra = &mt($crstype).': <a href="/public/'.$cdom.'/'.$cnum.'/syllabus">'.$desc.'</a>';
 7018:                     if ($sec ne '') {
 7019:                        $extra .= ' ('.&mt('Section: [_1]',$sec).')';
 7020:                     }
 7021:                 } elsif ($extent =~ m{^/($match_domain)/($match_username|$)}) {
 7022:                     my ($dom,$name) = ($1,$2);
 7023:                     if ($rolecode eq 'au') {
 7024:                         $extra = '';
 7025:                     } elsif ($rolecode =~ /^(ca|aa)$/) {
 7026:                         $extra = &mt('Authoring Space: [_1]',$name.':'.$dom);
 7027:                     } elsif ($rolecode =~ /^(li|dg|dh|dc|sc)$/) {
 7028:                         $extra = &mt('Domain: [_1]',$dom);
 7029:                     }
 7030:                 }
 7031:                 my $rolename;
 7032:                 if ($rolecode =~ m{^cr/($match_domain)/($match_username)/(\w+)}) {
 7033:                     my $role = $3;
 7034:                     my $owner = "($2:$1)";
 7035:                     if ($2 eq $1.'-domainconfig') {
 7036:                         $owner = '(ad hoc)';
 7037:                     }
 7038:                     $rolename = &mt('Custom role: [_1]',$role.' '.$owner);
 7039:                 } else {
 7040:                     $rolename = &Apache::lonnet::plaintext($rolecode,$crstype);
 7041:                 }
 7042:                 $shown = &mt('Role selection: [_1]',$rolename);
 7043:             } else {
 7044:                 $shown = &mt($event);
 7045:                 if ($data ne '') {
 7046:                    $extra = &mt('Client IP address: [_1]',$data);
 7047:                 }
 7048:             }
 7049:             $r->print(
 7050:             &Apache::loncommon::start_data_table_row()
 7051:            .'<td>'.$count.'</td>'
 7052:            .'<td>'.&Apache::lonlocal::locallocaltime($timestamp).'</td>'
 7053:            .'<td>'.$host.'</td>'
 7054:            .'<td>'.$shown.'</td>'
 7055:            .'<td>'.$extra.'</td>'
 7056:            .&Apache::loncommon::end_data_table_row()."\n");
 7057:         }
 7058:     }
 7059: 
 7060:     if ($showntableheader) { # Table footer, if content displayed above
 7061:         $r->print(&Apache::loncommon::end_data_table().
 7062:                   &userlogdisplay_navlinks(\%curr,$more_records));
 7063:     } else { # No content displayed above
 7064:         $r->print('<p class="LC_info">'
 7065:                  .&mt('There are no records to display.')
 7066:                  .'</p>');
 7067:     }
 7068: 
 7069:     # Form Footer
 7070:     $r->print(
 7071:         '<input type="hidden" name="currstate" value="" />'
 7072:        .'<input type="hidden" name="accessuname" value="'.$uname.'" />'
 7073:        .'<input type="hidden" name="accessudom" value="'.$udom.'" />'
 7074:        .'<input type="hidden" name="page" value="'.$curr{'page'}.'" />'
 7075:        .'<input type="hidden" name="prevphases" value="'.$prevphasestr.'" />'
 7076:        .'<input type="hidden" name="phase" value="activity" />'
 7077:        .'<input type="hidden" name="action" value="accesslogs" />'
 7078:        .'<input type="hidden" name="srchdomain" value="'.$udom.'" />'
 7079:        .'<input type="hidden" name="srchby" value="'.$env{'form.srchby'}.'" />'
 7080:        .'<input type="hidden" name="srchtype" value="'.$env{'form.srchtype'}.'" />'
 7081:        .'<input type="hidden" name="srchterm" value="'.&HTML::Entities::encode($env{'form.srchterm'},'<>"&').'" />'
 7082:        .'<input type="hidden" name="srchin" value="'.$env{'form.srchin'}.'" />'
 7083:        .'</form>');
 7084:     return;
 7085: }
 7086: 
 7087: sub earlyout_accesslog_form {
 7088:     my ($formname,$prevphasestr,$udom) = @_;
 7089:     my $srchterm = &HTML::Entities::encode($env{'form.srchterm'},'<>"&');
 7090:    return <<"END";
 7091: <form action="/adm/createuser" method="post" name="$formname">
 7092: <input type="hidden" name="currstate" value="" />
 7093: <input type="hidden" name="prevphases" value="$prevphasestr" />
 7094: <input type="hidden" name="phase" value="activity" />
 7095: <input type="hidden" name="action" value="accesslogs" />
 7096: <input type="hidden" name="srchdomain" value="$udom" />
 7097: <input type="hidden" name="srchby" value="$env{'form.srchby'}" />
 7098: <input type="hidden" name="srchtype" value="$env{'form.srchtype'}" />
 7099: <input type="hidden" name="srchterm" value="$srchterm" />
 7100: <input type="hidden" name="srchin" value="$env{'form.srchin'}" />
 7101: </form>
 7102: END
 7103: }
 7104: 
 7105: sub activity_display_filter {
 7106:     my ($formname,$curr) = @_;
 7107:     my $nolink = 1;
 7108:     my $output = '<table><tr><td valign="top">'.
 7109:                  '<span class="LC_nobreak"><b>'.&mt('Actions/page:').'</b></span><br />'.
 7110:                  &Apache::lonmeta::selectbox('show',$curr->{'show'},undef,
 7111:                                               (&mt('all'),5,10,20,50,100,1000,10000)).
 7112:                  '</td><td>&nbsp;&nbsp;</td>';
 7113:     my $startform =
 7114:         &Apache::lonhtmlcommon::date_setter($formname,'accesslog_start_date',
 7115:                                             $curr->{'accesslog_start_date'},undef,
 7116:                                             undef,undef,undef,undef,undef,undef,$nolink);
 7117:     my $endform =
 7118:         &Apache::lonhtmlcommon::date_setter($formname,'accesslog_end_date',
 7119:                                             $curr->{'accesslog_end_date'},undef,
 7120:                                             undef,undef,undef,undef,undef,undef,$nolink);
 7121:     my %lt = &Apache::lonlocal::texthash (
 7122:                                           activity => 'Activity',
 7123:                                           Role     => 'Role selection',
 7124:                                           log      => 'Log-in or Logout',
 7125:     );
 7126:     $output .= '<td valign="top"><b>'.&mt('Window during which actions occurred:').'</b><br />'.
 7127:                '<table><tr><td>'.&mt('After:').
 7128:                '</td><td>'.$startform.'</td></tr>'.
 7129:                '<tr><td>'.&mt('Before:').'</td>'.
 7130:                '<td>'.$endform.'</td></tr></table>'.
 7131:                '</td>'.
 7132:                '<td>&nbsp;&nbsp;</td>'.
 7133:                '<td valign="top"><b>'.&mt('Activities').'</b><br />'.
 7134:                '<select name="activity"><option value="any"';
 7135:     if ($curr->{'activity'} eq 'any') {
 7136:         $output .= ' selected="selected"';
 7137:     }
 7138:     $output .= '>'.&mt('Any').'</option>'."\n";
 7139:     foreach my $activity ('Role','log') {
 7140:         my $selstr = '';
 7141:         if ($activity eq $curr->{'activity'}) {
 7142:             $selstr = ' selected="selected"';
 7143:         }
 7144:         $output .= '<option value="'.$activity.'"'.$selstr.'>'.$lt{$activity}.'</option>';
 7145:     }
 7146:     $output .= '</select></td>'.
 7147:                '</tr></table>';
 7148:     # Update Display button
 7149:     $output .= '<p>'
 7150:               .'<input type="submit" value="'.&mt('Update Display').'" />'
 7151:               .'</p>';
 7152:     return $output;
 7153: }
 7154: 
 7155: sub userlogdisplay_js {
 7156:     my ($formname) = @_;
 7157:     return <<"ENDSCRIPT";
 7158: 
 7159: function chgPage(caller) {
 7160:     if (caller == 'previous') {
 7161:         document.$formname.page.value --;
 7162:     }
 7163:     if (caller == 'next') {
 7164:         document.$formname.page.value ++;
 7165:     }
 7166:     document.$formname.submit();
 7167:     return;
 7168: }
 7169: ENDSCRIPT
 7170: }
 7171: 
 7172: sub userlogdisplay_navlinks {
 7173:     my ($curr,$more_records) = @_;
 7174:     return unless(ref($curr) eq 'HASH');
 7175:     # Navigation Buttons
 7176:     my $nav_links = '<p>';
 7177:     if (($curr->{'page'} > 1) || ($more_records)) {
 7178:         if (($curr->{'page'} > 1) && ($curr->{'show'} !~ /\D/)) {
 7179:             $nav_links .= '<input type="button"'
 7180:                          .' onclick="javascript:chgPage('."'previous'".');"'
 7181:                          .' value="'.&mt('Previous [_1] changes',$curr->{'show'})
 7182:                          .'" /> ';
 7183:         }
 7184:         if ($more_records) {
 7185:             $nav_links .= '<input type="button"'
 7186:                          .' onclick="javascript:chgPage('."'next'".');"'
 7187:                          .' value="'.&mt('Next [_1] changes',$curr->{'show'})
 7188:                          .'" />';
 7189:         }
 7190:     }
 7191:     $nav_links .= '</p>';
 7192:     return $nav_links;
 7193: }
 7194: 
 7195: sub role_display_filter {
 7196:     my ($context,$formname,$cdom,$cnum,$curr,$version,$crstype) = @_;
 7197:     my $lctype;
 7198:     if ($context eq 'course') {
 7199:         $lctype = lc($crstype);
 7200:     }
 7201:     my $nolink = 1;
 7202:     my $output = '<table><tr><td valign="top">'.
 7203:                  '<span class="LC_nobreak"><b>'.&mt('Changes/page:').'</b></span><br />'.
 7204:                  &Apache::lonmeta::selectbox('show',$curr->{'show'},undef,
 7205:                                               (&mt('all'),5,10,20,50,100,1000,10000)).
 7206:                  '</td><td>&nbsp;&nbsp;</td>';
 7207:     my $startform =
 7208:         &Apache::lonhtmlcommon::date_setter($formname,'rolelog_start_date',
 7209:                                             $curr->{'rolelog_start_date'},undef,
 7210:                                             undef,undef,undef,undef,undef,undef,$nolink);
 7211:     my $endform =
 7212:         &Apache::lonhtmlcommon::date_setter($formname,'rolelog_end_date',
 7213:                                             $curr->{'rolelog_end_date'},undef,
 7214:                                             undef,undef,undef,undef,undef,undef,$nolink);
 7215:     my %lt = &rolechg_contexts($context,$crstype);
 7216:     $output .= '<td valign="top"><b>'.&mt('Window during which changes occurred:').'</b><br />'.
 7217:                '<table><tr><td>'.&mt('After:').
 7218:                '</td><td>'.$startform.'</td></tr>'.
 7219:                '<tr><td>'.&mt('Before:').'</td>'.
 7220:                '<td>'.$endform.'</td></tr></table>'.
 7221:                '</td>'.
 7222:                '<td>&nbsp;&nbsp;</td>'.
 7223:                '<td valign="top"><b>'.&mt('Role:').'</b><br />'.
 7224:                '<select name="role"><option value="any"';
 7225:     if ($curr->{'role'} eq 'any') {
 7226:         $output .= ' selected="selected"';
 7227:     }
 7228:     $output .=  '>'.&mt('Any').'</option>'."\n";
 7229:     my @roles = &Apache::lonuserutils::roles_by_context($context,1,$crstype);
 7230:     foreach my $role (@roles) {
 7231:         my $plrole;
 7232:         if ($role eq 'cr') {
 7233:             $plrole = &mt('Custom Role');
 7234:         } else {
 7235:             $plrole=&Apache::lonnet::plaintext($role,$crstype);
 7236:         }
 7237:         my $selstr = '';
 7238:         if ($role eq $curr->{'role'}) {
 7239:             $selstr = ' selected="selected"';
 7240:         }
 7241:         $output .= '  <option value="'.$role.'"'.$selstr.'>'.$plrole.'</option>';
 7242:     }
 7243:     $output .= '</select></td>'.
 7244:                '<td>&nbsp;&nbsp;</td>'.
 7245:                '<td valign="top"><b>'.
 7246:                &mt('Context:').'</b><br /><select name="chgcontext">';
 7247:     my @posscontexts;
 7248:     if ($context eq 'course') {
 7249:         @posscontexts = ('any','automated','updatenow','createcourse','course','domain','selfenroll','requestcourses');
 7250:     } elsif ($context eq 'domain') {
 7251:         @posscontexts = ('any','domain','requestauthor','domconfig','server');
 7252:     } else {
 7253:         @posscontexts = ('any','author','domain');
 7254:     } 
 7255:     foreach my $chgtype (@posscontexts) {
 7256:         my $selstr = '';
 7257:         if ($curr->{'chgcontext'} eq $chgtype) {
 7258:             $selstr = ' selected="selected"';
 7259:         }
 7260:         if ($context eq 'course') {
 7261:             if (($chgtype eq 'automated') || ($chgtype eq 'updatenow')) {
 7262:                 next if (!&Apache::lonnet::auto_run($cnum,$cdom));
 7263:             }
 7264:         }
 7265:         $output .= '<option value="'.$chgtype.'"'.$selstr.'>'.$lt{$chgtype}.'</option>'."\n";
 7266:     }
 7267:     $output .= '</select></td>'
 7268:               .'</tr></table>';
 7269: 
 7270:     # Update Display button
 7271:     $output .= '<p>'
 7272:               .'<input type="submit" value="'.&mt('Update Display').'" />'
 7273:               .'</p>';
 7274: 
 7275:     # Server version info
 7276:     my $needsrev = '2.11.0';
 7277:     if ($context eq 'course') {
 7278:         $needsrev = '2.7.0';
 7279:     }
 7280:     
 7281:     $output .= '<p class="LC_info">'
 7282:               .&mt('Only changes made from servers running LON-CAPA [_1] or later are displayed.'
 7283:                   ,$needsrev);
 7284:     if ($version) {
 7285:         $output .= ' '.&mt('This LON-CAPA server is version [_1]',$version);
 7286:     }
 7287:     $output .= '</p><hr />';
 7288:     return $output;
 7289: }
 7290: 
 7291: sub rolechg_contexts {
 7292:     my ($context,$crstype) = @_;
 7293:     my %lt;
 7294:     if ($context eq 'course') {
 7295:         %lt = &Apache::lonlocal::texthash (
 7296:                                              any          => 'Any',
 7297:                                              automated    => 'Automated Enrollment',
 7298:                                              updatenow    => 'Roster Update',
 7299:                                              createcourse => 'Course Creation',
 7300:                                              course       => 'User Management in course',
 7301:                                              domain       => 'User Management in domain',
 7302:                                              selfenroll   => 'Self-enrolled',
 7303:                                              requestcourses => 'Course Request',
 7304:                                          );
 7305:         if ($crstype eq 'Community') {
 7306:             $lt{'createcourse'} = &mt('Community Creation');
 7307:             $lt{'course'} = &mt('User Management in community');
 7308:             $lt{'requestcourses'} = &mt('Community Request');
 7309:         }
 7310:     } elsif ($context eq 'domain') {
 7311:         %lt = &Apache::lonlocal::texthash (
 7312:                                              any           => 'Any',
 7313:                                              domain        => 'User Management in domain',
 7314:                                              requestauthor => 'Authoring Request',
 7315:                                              server        => 'Command line script (DC role)',
 7316:                                              domconfig     => 'Self-enrolled',
 7317:                                          );
 7318:     } else {
 7319:         %lt = &Apache::lonlocal::texthash (
 7320:                                              any    => 'Any',
 7321:                                              domain => 'User Management in domain',
 7322:                                              author => 'User Management by author',
 7323:                                          );
 7324:     } 
 7325:     return %lt;
 7326: }
 7327: 
 7328: #-------------------------------------------------- functions for &phase_two
 7329: sub user_search_result {
 7330:     my ($context,$srch) = @_;
 7331:     my %allhomes;
 7332:     my %inst_matches;
 7333:     my %srch_results;
 7334:     my ($response,$currstate,$forcenewuser,$dirsrchres);
 7335:     $srch->{'srchterm'} =~ s/\s+/ /g;
 7336:     if ($srch->{'srchby'} !~ /^(uname|lastname|lastfirst)$/) {
 7337:         $response = &mt('Invalid search.');
 7338:     }
 7339:     if ($srch->{'srchin'} !~ /^(crs|dom|alc|instd)$/) {
 7340:         $response = &mt('Invalid search.');
 7341:     }
 7342:     if ($srch->{'srchtype'} !~ /^(exact|contains|begins)$/) {
 7343:         $response = &mt('Invalid search.');
 7344:     }
 7345:     if ($srch->{'srchterm'} eq '') {
 7346:         $response = &mt('You must enter a search term.');
 7347:     }
 7348:     if ($srch->{'srchterm'} =~ /^\s+$/) {
 7349:         $response = &mt('Your search term must contain more than just spaces.');
 7350:     }
 7351:     if (($srch->{'srchin'} eq 'dom') || ($srch->{'srchin'} eq 'instd')) {
 7352:         if (($srch->{'srchdomain'} eq '') || 
 7353: 	    ! (&Apache::lonnet::domain($srch->{'srchdomain'}))) {
 7354:             $response = &mt('You must specify a valid domain when searching in a domain or institutional directory.')
 7355:         }
 7356:     }
 7357:     if (($srch->{'srchin'} eq 'dom') || ($srch->{'srchin'} eq 'crs') ||
 7358:         ($srch->{'srchin'} eq 'alc')) {
 7359:         if ($srch->{'srchby'} eq 'uname') {
 7360:             my $unamecheck = $srch->{'srchterm'};
 7361:             if ($srch->{'srchtype'} eq 'contains') {
 7362:                 if ($unamecheck !~ /^\w/) {
 7363:                     $unamecheck = 'a'.$unamecheck; 
 7364:                 }
 7365:             }
 7366:             if ($unamecheck !~ /^$match_username$/) {
 7367:                 $response = &mt('You must specify a valid username. Only the following are allowed: letters numbers - . @');
 7368:             }
 7369:         }
 7370:     }
 7371:     if ($response ne '') {
 7372:         $response = '<span class="LC_warning">'.$response.'</span><br />';
 7373:     }
 7374:     if ($srch->{'srchin'} eq 'instd') {
 7375:         my $instd_chk = &instdirectorysrch_check($srch);
 7376:         if ($instd_chk ne 'ok') {
 7377:             my $domd_chk = &domdirectorysrch_check($srch);
 7378:             $response .= '<span class="LC_warning">'.$instd_chk.'</span><br />';
 7379:             if ($domd_chk eq 'ok') {
 7380:                 $response .= &mt('You may want to search in the LON-CAPA domain instead of the institutional directory.');
 7381:             }
 7382:             $response .= '<br />';
 7383:         }
 7384:     } else {
 7385:         unless (($context eq 'requestcrs') && ($srch->{'srchtype'} eq 'exact')) {
 7386:             my $domd_chk = &domdirectorysrch_check($srch);
 7387:             if ($domd_chk ne 'ok') {
 7388:                 my $instd_chk = &instdirectorysrch_check($srch);
 7389:                 $response .= '<span class="LC_warning">'.$domd_chk.'</span><br />';
 7390:                 if ($instd_chk eq 'ok') {
 7391:                     $response .= &mt('You may want to search in the institutional directory instead of the LON-CAPA domain.');
 7392:                 }
 7393:                 $response .= '<br />';
 7394:             }
 7395:         }
 7396:     }
 7397:     if ($response ne '') {
 7398:         return ($currstate,$response);
 7399:     }
 7400:     if ($srch->{'srchby'} eq 'uname') {
 7401:         if (($srch->{'srchin'} eq 'dom') || ($srch->{'srchin'} eq 'crs')) {
 7402:             if ($env{'form.forcenew'}) {
 7403:                 if ($srch->{'srchdomain'} ne $env{'request.role.domain'}) {
 7404:                     my $uhome=&Apache::lonnet::homeserver($srch->{'srchterm'},$srch->{'srchdomain'});
 7405:                     if ($uhome eq 'no_host') {
 7406:                         my $domdesc = &Apache::lonnet::domain($env{'request.role.domain'},'description');
 7407:                         my $showdom = &display_domain_info($env{'request.role.domain'});
 7408:                         $response = &mt('New users can only be created in the domain to which your current role belongs - [_1].',$showdom);
 7409:                     } else {
 7410:                         $currstate = 'modify';
 7411:                     }
 7412:                 } else {
 7413:                     $currstate = 'modify';
 7414:                 }
 7415:             } else {
 7416:                 if ($srch->{'srchin'} eq 'dom') {
 7417:                     if ($srch->{'srchtype'} eq 'exact') {
 7418:                         my $uhome=&Apache::lonnet::homeserver($srch->{'srchterm'},$srch->{'srchdomain'});
 7419:                         if ($uhome eq 'no_host') {
 7420:                             ($currstate,$response,$forcenewuser) =
 7421:                                 &build_search_response($context,$srch,%srch_results);
 7422:                         } else {
 7423:                             $currstate = 'modify';
 7424:                             if ($env{'form.action'} eq 'accesslogs') {
 7425:                                 $currstate = 'activity';
 7426:                             }
 7427:                             my $uname = $srch->{'srchterm'};
 7428:                             my $udom = $srch->{'srchdomain'};
 7429:                             $srch_results{$uname.':'.$udom} =
 7430:                                 { &Apache::lonnet::get('environment',
 7431:                                                        ['firstname',
 7432:                                                         'lastname',
 7433:                                                         'permanentemail'],
 7434:                                                          $udom,$uname)
 7435:                                 };
 7436:                         }
 7437:                     } else {
 7438:                         %srch_results = &Apache::lonnet::usersearch($srch);
 7439:                         ($currstate,$response,$forcenewuser) =
 7440:                             &build_search_response($context,$srch,%srch_results);
 7441:                     }
 7442:                 } else {
 7443:                     my $courseusers = &get_courseusers();
 7444:                     if ($srch->{'srchtype'} eq 'exact') {
 7445:                         if (exists($courseusers->{$srch->{'srchterm'}.':'.$srch->{'srchdomain'}})) {
 7446:                             $currstate = 'modify';
 7447:                         } else {
 7448:                             ($currstate,$response,$forcenewuser) =
 7449:                                 &build_search_response($context,$srch,%srch_results);
 7450:                         }
 7451:                     } else {
 7452:                         foreach my $user (keys(%$courseusers)) {
 7453:                             my ($cuname,$cudomain) = split(/:/,$user);
 7454:                             if ($cudomain eq $srch->{'srchdomain'}) {
 7455:                                 my $matched = 0;
 7456:                                 if ($srch->{'srchtype'} eq 'begins') {
 7457:                                     if ($cuname =~ /^\Q$srch->{'srchterm'}\E/i) {
 7458:                                         $matched = 1;
 7459:                                     }
 7460:                                 } else {
 7461:                                     if ($cuname =~ /\Q$srch->{'srchterm'}\E/i) {
 7462:                                         $matched = 1;
 7463:                                     }
 7464:                                 }
 7465:                                 if ($matched) {
 7466:                                     $srch_results{$user} = 
 7467: 					{&Apache::lonnet::get('environment',
 7468: 							     ['firstname',
 7469: 							      'lastname',
 7470: 							      'permanentemail'],
 7471: 							      $cudomain,$cuname)};
 7472:                                 }
 7473:                             }
 7474:                         }
 7475:                         ($currstate,$response,$forcenewuser) =
 7476:                             &build_search_response($context,$srch,%srch_results);
 7477:                     }
 7478:                 }
 7479:             }
 7480:         } elsif ($srch->{'srchin'} eq 'alc') {
 7481:             $currstate = 'query';
 7482:         } elsif ($srch->{'srchin'} eq 'instd') {
 7483:             ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query($srch);
 7484:             if ($dirsrchres eq 'ok') {
 7485:                 ($currstate,$response,$forcenewuser) = 
 7486:                     &build_search_response($context,$srch,%srch_results);
 7487:             } else {
 7488:                 my $showdom = &display_domain_info($srch->{'srchdomain'});
 7489:                 $response = '<span class="LC_warning">'.
 7490:                     &mt('Institutional directory search is not available in domain: [_1]',$showdom).
 7491:                     '</span><br />'.
 7492:                     &mt('You may want to search in the LON-CAPA domain instead of the institutional directory.').
 7493:                     '<br />'; 
 7494:             }
 7495:         }
 7496:     } else {
 7497:         if ($srch->{'srchin'} eq 'dom') {
 7498:             %srch_results = &Apache::lonnet::usersearch($srch);
 7499:             ($currstate,$response,$forcenewuser) = 
 7500:                 &build_search_response($context,$srch,%srch_results); 
 7501:         } elsif ($srch->{'srchin'} eq 'crs') {
 7502:             my $courseusers = &get_courseusers(); 
 7503:             foreach my $user (keys(%$courseusers)) {
 7504:                 my ($uname,$udom) = split(/:/,$user);
 7505:                 my %names = &Apache::loncommon::getnames($uname,$udom);
 7506:                 my %emails = &Apache::loncommon::getemails($uname,$udom);
 7507:                 if ($srch->{'srchby'} eq 'lastname') {
 7508:                     if ((($srch->{'srchtype'} eq 'exact') && 
 7509:                          ($names{'lastname'} eq $srch->{'srchterm'})) || 
 7510:                         (($srch->{'srchtype'} eq 'begins') &&
 7511:                          ($names{'lastname'} =~ /^\Q$srch->{'srchterm'}\E/i)) ||
 7512:                         (($srch->{'srchtype'} eq 'contains') &&
 7513:                          ($names{'lastname'} =~ /\Q$srch->{'srchterm'}\E/i))) {
 7514:                         $srch_results{$user} = {firstname => $names{'firstname'},
 7515:                                             lastname => $names{'lastname'},
 7516:                                             permanentemail => $emails{'permanentemail'},
 7517:                                            };
 7518:                     }
 7519:                 } elsif ($srch->{'srchby'} eq 'lastfirst') {
 7520:                     my ($srchlast,$srchfirst) = split(/,/,$srch->{'srchterm'});
 7521:                     $srchlast =~ s/\s+$//;
 7522:                     $srchfirst =~ s/^\s+//;
 7523:                     if ($srch->{'srchtype'} eq 'exact') {
 7524:                         if (($names{'lastname'} eq $srchlast) &&
 7525:                             ($names{'firstname'} eq $srchfirst)) {
 7526:                             $srch_results{$user} = {firstname => $names{'firstname'},
 7527:                                                 lastname => $names{'lastname'},
 7528:                                                 permanentemail => $emails{'permanentemail'},
 7529: 
 7530:                                            };
 7531:                         }
 7532:                     } elsif ($srch->{'srchtype'} eq 'begins') {
 7533:                         if (($names{'lastname'} =~ /^\Q$srchlast\E/i) &&
 7534:                             ($names{'firstname'} =~ /^\Q$srchfirst\E/i)) {
 7535:                             $srch_results{$user} = {firstname => $names{'firstname'},
 7536:                                                 lastname => $names{'lastname'},
 7537:                                                 permanentemail => $emails{'permanentemail'},
 7538:                                                };
 7539:                         }
 7540:                     } else {
 7541:                         if (($names{'lastname'} =~ /\Q$srchlast\E/i) && 
 7542:                             ($names{'firstname'} =~ /\Q$srchfirst\E/i)) {
 7543:                             $srch_results{$user} = {firstname => $names{'firstname'},
 7544:                                                 lastname => $names{'lastname'},
 7545:                                                 permanentemail => $emails{'permanentemail'},
 7546:                                                };
 7547:                         }
 7548:                     }
 7549:                 }
 7550:             }
 7551:             ($currstate,$response,$forcenewuser) = 
 7552:                 &build_search_response($context,$srch,%srch_results); 
 7553:         } elsif ($srch->{'srchin'} eq 'alc') {
 7554:             $currstate = 'query';
 7555:         } elsif ($srch->{'srchin'} eq 'instd') {
 7556:             ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query($srch); 
 7557:             if ($dirsrchres eq 'ok') {
 7558:                 ($currstate,$response,$forcenewuser) = 
 7559:                     &build_search_response($context,$srch,%srch_results);
 7560:             } else {
 7561:                 my $showdom = &display_domain_info($srch->{'srchdomain'});
 7562:                 $response = '<span class="LC_warning">'.
 7563:                     &mt('Institutional directory search is not available in domain: [_1]',$showdom).
 7564:                     '</span><br />'.
 7565:                     &mt('You may want to search in the LON-CAPA domain instead of the institutional directory.').
 7566:                     '<br />';
 7567:             }
 7568:         }
 7569:     }
 7570:     return ($currstate,$response,$forcenewuser,\%srch_results);
 7571: }
 7572: 
 7573: sub domdirectorysrch_check {
 7574:     my ($srch) = @_;
 7575:     my $response;
 7576:     my %dom_inst_srch = &Apache::lonnet::get_dom('configuration',
 7577:                                              ['directorysrch'],$srch->{'srchdomain'});
 7578:     my $showdom = &display_domain_info($srch->{'srchdomain'});
 7579:     if (ref($dom_inst_srch{'directorysrch'}) eq 'HASH') {
 7580:         if ($dom_inst_srch{'directorysrch'}{'lcavailable'} eq '0') {
 7581:             return &mt('LON-CAPA directory search is not available in domain: [_1]',$showdom);
 7582:         }
 7583:         if ($dom_inst_srch{'directorysrch'}{'lclocalonly'}) {
 7584:             if ($env{'request.role.domain'} ne $srch->{'srchdomain'}) {
 7585:                 return &mt('LON-CAPA directory search in domain: [_1] is only allowed for users with a current role in the domain.',$showdom);
 7586:             }
 7587:         }
 7588:     }
 7589:     return 'ok';
 7590: }
 7591: 
 7592: sub instdirectorysrch_check {
 7593:     my ($srch) = @_;
 7594:     my $can_search = 0;
 7595:     my $response;
 7596:     my %dom_inst_srch = &Apache::lonnet::get_dom('configuration',
 7597:                                              ['directorysrch'],$srch->{'srchdomain'});
 7598:     my $showdom = &display_domain_info($srch->{'srchdomain'});
 7599:     if (ref($dom_inst_srch{'directorysrch'}) eq 'HASH') {
 7600:         if (!$dom_inst_srch{'directorysrch'}{'available'}) {
 7601:             return &mt('Institutional directory search is not available in domain: [_1]',$showdom); 
 7602:         }
 7603:         if ($dom_inst_srch{'directorysrch'}{'localonly'}) {
 7604:             if ($env{'request.role.domain'} ne $srch->{'srchdomain'}) {
 7605:                 return &mt('Institutional directory search in domain: [_1] is only allowed for users with a current role in the domain.',$showdom); 
 7606:             }
 7607:             my @usertypes = split(/:/,$env{'environment.inststatus'});
 7608:             if (!@usertypes) {
 7609:                 push(@usertypes,'default');
 7610:             }
 7611:             if (ref($dom_inst_srch{'directorysrch'}{'cansearch'}) eq 'ARRAY') {
 7612:                 foreach my $type (@usertypes) {
 7613:                     if (grep(/^\Q$type\E$/,@{$dom_inst_srch{'directorysrch'}{'cansearch'}})) {
 7614:                         $can_search = 1;
 7615:                         last;
 7616:                     }
 7617:                 }
 7618:             }
 7619:             if (!$can_search) {
 7620:                 my ($insttypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($srch->{'srchdomain'});
 7621:                 my @longtypes; 
 7622:                 foreach my $item (@usertypes) {
 7623:                     if (defined($insttypes->{$item})) { 
 7624:                         push (@longtypes,$insttypes->{$item});
 7625:                     } elsif ($item eq 'default') {
 7626:                         push (@longtypes,&mt('other')); 
 7627:                     }
 7628:                 }
 7629:                 my $insttype_str = join(', ',@longtypes); 
 7630:                 return &mt('Institutional directory search in domain: [_1] is not available to your user type: ',$showdom).$insttype_str;
 7631:             }
 7632:         } else {
 7633:             $can_search = 1;
 7634:         }
 7635:     } else {
 7636:         return &mt('Institutional directory search has not been configured for domain: [_1]',$showdom);
 7637:     }
 7638:     my %longtext = &Apache::lonlocal::texthash (
 7639:                        uname     => 'username',
 7640:                        lastfirst => 'last name, first name',
 7641:                        lastname  => 'last name',
 7642:                        contains  => 'contains',
 7643:                        exact     => 'as exact match to',
 7644:                        begins    => 'begins with',
 7645:                    );
 7646:     if ($can_search) {
 7647:         if (ref($dom_inst_srch{'directorysrch'}{'searchby'}) eq 'ARRAY') {
 7648:             if (!grep(/^\Q$srch->{'srchby'}\E$/,@{$dom_inst_srch{'directorysrch'}{'searchby'}})) {
 7649:                 return &mt('Institutional directory search in domain: [_1] is not available for searching by "[_2]"',$showdom,$longtext{$srch->{'srchby'}});
 7650:             }
 7651:         } else {
 7652:             return &mt('Institutional directory search in domain: [_1] is not available.', $showdom);
 7653:         }
 7654:     }
 7655:     if ($can_search) {
 7656:         if (ref($dom_inst_srch{'directorysrch'}{'searchtypes'}) eq 'ARRAY') {
 7657:             if (grep(/^\Q$srch->{'srchtype'}\E/,@{$dom_inst_srch{'directorysrch'}{'searchtypes'}})) {
 7658:                 return 'ok';
 7659:             } else {
 7660:                 return &mt('Institutional directory search in domain [_1] is not available for the requested search type: "[_2]"',$showdom,$longtext{$srch->{'srchtype'}});
 7661:             }
 7662:         } else {
 7663:             if ((($dom_inst_srch{'directorysrch'}{'searchtypes'} eq 'specify') &&
 7664:                  ($srch->{'srchtype'} eq 'exact' || $srch->{'srchtype'} eq 'contains')) ||
 7665:                 ($dom_inst_srch{'directorysrch'}{'searchtypes'} eq $srch->{'srchtype'})) {
 7666:                 return 'ok';
 7667:             } else {
 7668:                 return &mt('Institutional directory search in domain [_1] is not available for the requested search type: "[_2]"',$showdom,$longtext{$srch->{'srchtype'}});
 7669:             }
 7670:         }
 7671:     }
 7672: }
 7673: 
 7674: sub get_courseusers {
 7675:     my %advhash;
 7676:     my $classlist = &Apache::loncoursedata::get_classlist();
 7677:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles();
 7678:     foreach my $role (sort(keys(%coursepersonnel))) {
 7679:         foreach my $user (split(/\,/,$coursepersonnel{$role})) {
 7680: 	    if (!exists($classlist->{$user})) {
 7681: 		$classlist->{$user} = [];
 7682: 	    }
 7683:         }
 7684:     }
 7685:     return $classlist;
 7686: }
 7687: 
 7688: sub build_search_response {
 7689:     my ($context,$srch,%srch_results) = @_;
 7690:     my ($currstate,$response,$forcenewuser);
 7691:     my %names = (
 7692:           'uname'     => 'username',
 7693:           'lastname'  => 'last name',
 7694:           'lastfirst' => 'last name, first name',
 7695:           'crs'       => 'this course',
 7696:           'dom'       => 'LON-CAPA domain',
 7697:           'instd'     => 'the institutional directory for domain',
 7698:     );
 7699: 
 7700:     my %single = (
 7701:                    begins   => 'A match',
 7702:                    contains => 'A match',
 7703:                    exact    => 'An exact match',
 7704:                  );
 7705:     my %nomatch = (
 7706:                    begins   => 'No match',
 7707:                    contains => 'No match',
 7708:                    exact    => 'No exact match',
 7709:                   );
 7710:     if (keys(%srch_results) > 1) {
 7711:         $currstate = 'select';
 7712:     } else {
 7713:         if (keys(%srch_results) == 1) {
 7714:             if ($env{'form.action'} eq 'accesslogs') {
 7715:                 $currstate = 'activity';
 7716:             } else {
 7717:                 $currstate = 'modify';
 7718:             }
 7719:             $response = &mt("$single{$srch->{'srchtype'}} was found for the $names{$srch->{'srchby'}} ([_1]) in $names{$srch->{'srchin'}}.",$srch->{'srchterm'});
 7720:             if ($srch->{'srchin'} eq 'dom' || $srch->{'srchin'} eq 'instd') {
 7721:                 $response .= ': '.&display_domain_info($srch->{'srchdomain'});
 7722:             }
 7723:         } else { # Search has nothing found. Prepare message to user.
 7724:             $response = '<span class="LC_warning">';
 7725:             if ($srch->{'srchin'} eq 'dom' || $srch->{'srchin'} eq 'instd') {
 7726:                 $response .= &mt("$nomatch{$srch->{'srchtype'}} found for the $names{$srch->{'srchby'}} [_1] in $names{$srch->{'srchin'}}: [_2]",
 7727:                                  '<b>'.$srch->{'srchterm'}.'</b>',
 7728:                                  &display_domain_info($srch->{'srchdomain'}));
 7729:             } else {
 7730:                 $response .= &mt("$nomatch{$srch->{'srchtype'}} found for the $names{$srch->{'srchby'}} [_1] in $names{$srch->{'srchin'}}.",
 7731:                                  '<b>'.$srch->{'srchterm'}.'</b>');
 7732:             }
 7733:             $response .= '</span>';
 7734: 
 7735:             if ($srch->{'srchin'} ne 'alc') {
 7736:                 $forcenewuser = 1;
 7737:                 my $cansrchinst = 0; 
 7738:                 if ($srch->{'srchdomain'}) {
 7739:                     my %domconfig = &Apache::lonnet::get_dom('configuration',['directorysrch'],$srch->{'srchdomain'});
 7740:                     if (ref($domconfig{'directorysrch'}) eq 'HASH') {
 7741:                         if ($domconfig{'directorysrch'}{'available'}) {
 7742:                             $cansrchinst = 1;
 7743:                         } 
 7744:                     }
 7745:                 }
 7746:                 if ((($srch->{'srchby'} eq 'lastfirst') || 
 7747:                      ($srch->{'srchby'} eq 'lastname')) &&
 7748:                     ($srch->{'srchin'} eq 'dom')) {
 7749:                     if ($cansrchinst) {
 7750:                         $response .= '<br />'.&mt('You may want to broaden your search to a search of the institutional directory for the domain.');
 7751:                     }
 7752:                 }
 7753:                 if ($srch->{'srchin'} eq 'crs') {
 7754:                     $response .= '<br />'.&mt('You may want to broaden your search to the selected LON-CAPA domain.');
 7755:                 }
 7756:             }
 7757:             my $createdom = $env{'request.role.domain'};
 7758:             if ($context eq 'requestcrs') {
 7759:                 if ($env{'form.coursedom'} ne '') {
 7760:                     $createdom = $env{'form.coursedom'};
 7761:                 }
 7762:             }
 7763:             unless (($env{'form.action'} eq 'accesslogs') || (($srch->{'srchby'} eq 'uname') && ($srch->{'srchin'} eq 'dom') &&
 7764:                     ($srch->{'srchtype'} eq 'exact') && ($srch->{'srchdomain'} eq $createdom))) {
 7765:                 my $cancreate =
 7766:                     &Apache::lonuserutils::can_create_user($createdom,$context);
 7767:                 my $targetdom = '<span class="LC_cusr_emph">'.$createdom.'</span>';
 7768:                 if ($cancreate) {
 7769:                     my $showdom = &display_domain_info($createdom); 
 7770:                     $response .= '<br /><br />'
 7771:                                 .'<b>'.&mt('To add a new user:').'</b>'
 7772:                                 .'<br />';
 7773:                     if ($context eq 'requestcrs') {
 7774:                         $response .= &mt("(You can only define new users in the new course's domain - [_1])",$targetdom);
 7775:                     } else {
 7776:                         $response .= &mt("(You can only create new users in your current role's domain - [_1])",$targetdom);
 7777:                     }
 7778:                     $response .='<ul><li>'
 7779:                                 .&mt("Set 'Domain/institution to search' to: [_1]",'<span class="LC_cusr_emph">'.$showdom.'</span>')
 7780:                                 .'</li><li>'
 7781:                                 .&mt("Set 'Search criteria' to: [_1]username is ..... in selected LON-CAPA domain[_2]",'<span class="LC_cusr_emph">','</span>')
 7782:                                 .'</li><li>'
 7783:                                 .&mt('Provide the proposed username')
 7784:                                 .'</li><li>'
 7785:                                 .&mt("Click 'Search'")
 7786:                                 .'</li></ul><br />';
 7787:                 } else {
 7788:                     unless (($context eq 'domain') && ($env{'form.action'} eq 'singleuser')) {
 7789:                         my $helplink = ' href="javascript:helpMenu('."'display'".')"';
 7790:                         $response .= '<br /><br />';
 7791:                         if ($context eq 'requestcrs') {
 7792:                             $response .= &mt("You are not authorized to define new users in the new course's domain - [_1].",$targetdom);
 7793:                         } else {
 7794:                             $response .= &mt("You are not authorized to create new users in your current role's domain - [_1].",$targetdom);
 7795:                         }
 7796:                         $response .= '<br />'
 7797:                                      .&mt('Please contact the [_1]helpdesk[_2] if you need to create a new user.'
 7798:                                         ,' <a'.$helplink.'>'
 7799:                                         ,'</a>')
 7800:                                      .'<br />';
 7801:                     
 7802:                     }
 7803:                 }
 7804:             }
 7805:         }
 7806:     }
 7807:     return ($currstate,$response,$forcenewuser);
 7808: }
 7809: 
 7810: sub display_domain_info {
 7811:     my ($dom) = @_;
 7812:     my $output = $dom;
 7813:     if ($dom ne '') { 
 7814:         my $domdesc = &Apache::lonnet::domain($dom,'description');
 7815:         if ($domdesc ne '') {
 7816:             $output .= ' <span class="LC_cusr_emph">('.$domdesc.')</span>';
 7817:         }
 7818:     }
 7819:     return $output;
 7820: }
 7821: 
 7822: sub crumb_utilities {
 7823:     my %elements = (
 7824:        crtuser => {
 7825:            srchterm => 'text',
 7826:            srchin => 'selectbox',
 7827:            srchby => 'selectbox',
 7828:            srchtype => 'selectbox',
 7829:            srchdomain => 'selectbox',
 7830:        },
 7831:        crtusername => {
 7832:            srchterm => 'text',
 7833:            srchdomain => 'selectbox',
 7834:        },
 7835:        docustom => {
 7836:            rolename => 'selectbox',
 7837:            newrolename => 'textbox',
 7838:        },
 7839:        studentform => {
 7840:            srchterm => 'text',
 7841:            srchin => 'selectbox',
 7842:            srchby => 'selectbox',
 7843:            srchtype => 'selectbox',
 7844:            srchdomain => 'selectbox',
 7845:        },
 7846:     );
 7847: 
 7848:     my $jsback .= qq|
 7849: function backPage(formname,prevphase,prevstate) {
 7850:     if (typeof prevphase == 'undefined') {
 7851:         formname.phase.value = '';
 7852:     }
 7853:     else {  
 7854:         formname.phase.value = prevphase;
 7855:     }
 7856:     if (typeof prevstate == 'undefined') {
 7857:         formname.currstate.value = '';
 7858:     }
 7859:     else {
 7860:         formname.currstate.value = prevstate;
 7861:     }
 7862:     formname.submit();
 7863: }
 7864: |;
 7865:     return ($jsback,\%elements);
 7866: }
 7867: 
 7868: sub course_level_table {
 7869:     my ($inccourses,$showcredits,$defaultcredits) = @_;
 7870:     return unless (ref($inccourses) eq 'HASH');
 7871:     my $table = '';
 7872: # Custom Roles?
 7873: 
 7874:     my %customroles=&Apache::lonuserutils::my_custom_roles();
 7875:     my %lt=&Apache::lonlocal::texthash(
 7876:             'exs'  => "Existing sections",
 7877:             'new'  => "Define new section",
 7878:             'ssd'  => "Set Start Date",
 7879:             'sed'  => "Set End Date",
 7880:             'crl'  => "Course Level",
 7881:             'act'  => "Activate",
 7882:             'rol'  => "Role",
 7883:             'ext'  => "Extent",
 7884:             'grs'  => "Section",
 7885:             'crd'  => "Credits",
 7886:             'sta'  => "Start",
 7887:             'end'  => "End"
 7888:     );
 7889: 
 7890:     foreach my $protectedcourse (sort(keys(%{$inccourses}))) {
 7891: 	my $thiscourse=$protectedcourse;
 7892: 	$thiscourse=~s:_:/:g;
 7893: 	my %coursedata=&Apache::lonnet::coursedescription($thiscourse);
 7894:         my $isowner = &Apache::lonuserutils::is_courseowner($protectedcourse,$coursedata{'internal.courseowner'});
 7895: 	my $area=$coursedata{'description'};
 7896:         my $crstype=$coursedata{'type'};
 7897: 	if (!defined($area)) { $area=&mt('Unavailable course').': '.$protectedcourse; }
 7898: 	my ($domain,$cnum)=split(/\//,$thiscourse);
 7899:         my %sections_count;
 7900:         if (defined($env{'request.course.id'})) {
 7901:             if ($env{'request.course.id'} eq $domain.'_'.$cnum) {
 7902:                 %sections_count = 
 7903: 		    &Apache::loncommon::get_sections($domain,$cnum);
 7904:             }
 7905:         }
 7906:         my @roles = &Apache::lonuserutils::roles_by_context('course','',$crstype);
 7907: 	foreach my $role (@roles) {
 7908:             my $plrole=&Apache::lonnet::plaintext($role,$crstype);
 7909: 	    if ((&Apache::lonnet::allowed('c'.$role,$thiscourse)) ||
 7910:                 ((($role eq 'cc') || ($role eq 'co')) && ($isowner))) {
 7911:                 $table .= &course_level_row($protectedcourse,$role,$area,$domain,
 7912:                                             $plrole,\%sections_count,\%lt,
 7913:                                             $showcredits,$defaultcredits,$crstype);
 7914:             } elsif ($env{'request.course.sec'} ne '') {
 7915:                 if (&Apache::lonnet::allowed('c'.$role,$thiscourse.'/'.
 7916:                                              $env{'request.course.sec'})) {
 7917:                     $table .= &course_level_row($protectedcourse,$role,$area,$domain,
 7918:                                                 $plrole,\%sections_count,\%lt,
 7919:                                                 $showcredits,$defaultcredits,$crstype);
 7920:                 }
 7921:             }
 7922:         }
 7923:         if (&Apache::lonnet::allowed('ccr',$thiscourse)) {
 7924:             foreach my $cust (sort(keys(%customroles))) {
 7925:                 next if ($crstype eq 'Community' && $customroles{$cust} =~ /bre\&S/);
 7926:                 my $role = 'cr_cr_'.$env{'user.domain'}.'_'.$env{'user.name'}.'_'.$cust;
 7927:                 $table .= &course_level_row($protectedcourse,$role,$area,$domain,
 7928:                                             $cust,\%sections_count,\%lt,
 7929:                                             $showcredits,$defaultcredits,$crstype);
 7930:             }
 7931: 	}
 7932:     }
 7933:     return '' if ($table eq ''); # return nothing if there is nothing 
 7934:                                  # in the table
 7935:     my $result;
 7936:     if (!$env{'request.course.id'}) {
 7937:         $result = '<h4>'.$lt{'crl'}.'</h4>'."\n";
 7938:     }
 7939:     $result .= 
 7940: &Apache::loncommon::start_data_table().
 7941: &Apache::loncommon::start_data_table_header_row().
 7942: '<th>'.$lt{'act'}.'</th><th>'.$lt{'rol'}.'</th>'."\n".
 7943: '<th>'.$lt{'ext'}.'</th><th>'."\n";
 7944:     if ($showcredits) {
 7945:         $result .= $lt{'crd'}.'</th>';
 7946:     }
 7947:     $result .=
 7948: '<th>'.$lt{'grs'}.'</th><th>'.$lt{'sta'}.'</th>'."\n".
 7949: '<th>'.$lt{'end'}.'</th>'.
 7950: &Apache::loncommon::end_data_table_header_row().
 7951: $table.
 7952: &Apache::loncommon::end_data_table();
 7953:     return $result;
 7954: }
 7955: 
 7956: sub course_level_row {
 7957:     my ($protectedcourse,$role,$area,$domain,$plrole,$sections_count,
 7958:         $lt,$showcredits,$defaultcredits,$crstype) = @_;
 7959:     my $creditem;
 7960:     my $row = &Apache::loncommon::start_data_table_row().
 7961:               ' <td><input type="checkbox" name="act_'.
 7962:               $protectedcourse.'_'.$role.'" /></td>'."\n".
 7963:               ' <td>'.$plrole.'</td>'."\n".
 7964:               ' <td>'.$area.'<br />Domain: '.$domain.'</td>'."\n";
 7965:     if (($showcredits) && ($role eq 'st') && ($crstype eq 'Course')) {
 7966:         $row .= 
 7967:             '<td><input type="text" name="credits_'.$protectedcourse.'_'.
 7968:             $role.'" size="3" value="'.$defaultcredits.'" /></td>';
 7969:     } else {
 7970:         $row .= '<td>&nbsp;</td>';
 7971:     }
 7972:     if (($role eq 'cc') || ($role eq 'co')) {
 7973:         $row .= '<td>&nbsp;</td>';
 7974:     } elsif ($env{'request.course.sec'} ne '') {
 7975:         $row .= ' <td><input type="hidden" value="'.
 7976:                 $env{'request.course.sec'}.'" '.
 7977:                 'name="sec_'.$protectedcourse.'_'.$role.'" />'.
 7978:                 $env{'request.course.sec'}.'</td>';
 7979:     } else {
 7980:         if (ref($sections_count) eq 'HASH') {
 7981:             my $currsec = 
 7982:                 &Apache::lonuserutils::course_sections($sections_count,
 7983:                                                        $protectedcourse.'_'.$role);
 7984:             $row .= '<td><table class="LC_createuser">'."\n".
 7985:                     '<tr class="LC_section_row">'."\n".
 7986:                     ' <td valign="top">'.$lt->{'exs'}.'<br />'.
 7987:                        $currsec.'</td>'."\n".
 7988:                      ' <td>&nbsp;&nbsp;</td>'."\n".
 7989:                      ' <td valign="top">&nbsp;'.$lt->{'new'}.'<br />'.
 7990:                      '<input type="text" name="newsec_'.$protectedcourse.'_'.$role.
 7991:                      '" value="" />'.
 7992:                      '<input type="hidden" '.
 7993:                      'name="sec_'.$protectedcourse.'_'.$role.'" /></td>'."\n".
 7994:                      '</tr></table></td>'."\n";
 7995:         } else {
 7996:             $row .= '<td><input type="text" size="10" '.
 7997:                     'name="sec_'.$protectedcourse.'_'.$role.'" /></td>'."\n";
 7998:         }
 7999:     }
 8000:     $row .= <<ENDTIMEENTRY;
 8001: <td><input type="hidden" name="start_$protectedcourse\_$role" value="" />
 8002: <a href=
 8003: "javascript:pjump('date_start','Start Date $plrole',document.cu.start_$protectedcourse\_$role.value,'start_$protectedcourse\_$role','cu.pres','dateset')">$lt->{'ssd'}</a></td>
 8004: <td><input type="hidden" name="end_$protectedcourse\_$role" value="" />
 8005: <a href=
 8006: "javascript:pjump('date_end','End Date $plrole',document.cu.end_$protectedcourse\_$role.value,'end_$protectedcourse\_$role','cu.pres','dateset')">$lt->{'sed'}</a></td>
 8007: ENDTIMEENTRY
 8008:     $row .= &Apache::loncommon::end_data_table_row();
 8009:     return $row;
 8010: }
 8011: 
 8012: sub course_level_dc {
 8013:     my ($dcdom,$showcredits) = @_;
 8014:     my %customroles=&Apache::lonuserutils::my_custom_roles();
 8015:     my @roles = &Apache::lonuserutils::roles_by_context('course');
 8016:     my $hiddenitems = '<input type="hidden" name="dcdomain" value="'.$dcdom.'" />'.
 8017:                       '<input type="hidden" name="origdom" value="'.$dcdom.'" />'.
 8018:                       '<input type="hidden" name="dccourse" value="" />';
 8019:     my $courseform=&Apache::loncommon::selectcourse_link
 8020:             ('cu','dccourse','dcdomain','coursedesc',undef,undef,'Select','crstype');
 8021:     my $credit_elem;
 8022:     if ($showcredits) {
 8023:         $credit_elem = 'credits';
 8024:     }
 8025:     my $cb_jscript = &Apache::loncommon::coursebrowser_javascript($dcdom,'currsec','cu','role','Course/Community Browser',$credit_elem);
 8026:     my %lt=&Apache::lonlocal::texthash(
 8027:                     'rol'  => "Role",
 8028:                     'grs'  => "Section",
 8029:                     'exs'  => "Existing sections",
 8030:                     'new'  => "Define new section", 
 8031:                     'sta'  => "Start",
 8032:                     'end'  => "End",
 8033:                     'ssd'  => "Set Start Date",
 8034:                     'sed'  => "Set End Date",
 8035:                     'scc'  => "Course/Community",
 8036:                     'crd'  => "Credits",
 8037:                   );
 8038:     my $header = '<h4>'.&mt('Course/Community Level').'</h4>'.
 8039:                  &Apache::loncommon::start_data_table().
 8040:                  &Apache::loncommon::start_data_table_header_row().
 8041:                  '<th>'.$lt{'scc'}.'</th><th>'.$lt{'rol'}.'</th>'."\n".
 8042:                  '<th>'.$lt{'grs'}.'</th>'."\n";
 8043:     $header .=   '<th>'.$lt{'crd'}.'</th>'."\n" if ($showcredits);
 8044:     $header .=   '<th>'.$lt{'sta'}.'</th><th>'.$lt{'end'}.'</th>'."\n".
 8045:                  &Apache::loncommon::end_data_table_header_row();
 8046:     my $otheritems = &Apache::loncommon::start_data_table_row()."\n".
 8047:                      '<td><br /><span class="LC_nobreak"><input type="text" name="coursedesc" value="" onfocus="this.blur();opencrsbrowser('."'cu','dccourse','dcdomain','coursedesc','','','','crstype'".')" />'.
 8048:                      $courseform.('&nbsp;' x4).'</span></td>'."\n".
 8049:                      '<td valign="top"><br /><select name="role">'."\n";
 8050:     foreach my $role (@roles) {
 8051:         my $plrole=&Apache::lonnet::plaintext($role);
 8052:         $otheritems .= '  <option value="'.$role.'">'.$plrole.'</option>';
 8053:     }
 8054:     if ( keys(%customroles) > 0) {
 8055:         foreach my $cust (sort(keys(%customroles))) {
 8056:             my $custrole='cr_cr_'.$env{'user.domain'}.
 8057:                     '_'.$env{'user.name'}.'_'.$cust;
 8058:             $otheritems .= '  <option value="'.$custrole.'">'.$cust.'</option>';
 8059:         }
 8060:     }
 8061:     $otheritems .= '</select></td><td>'.
 8062:                      '<table border="0" cellspacing="0" cellpadding="0">'.
 8063:                      '<tr><td valign="top"><b>'.$lt{'exs'}.'</b><br /><select name="currsec">'.
 8064:                      ' <option value="">&lt;--'.&mt('Pick course first').'</option></select></td>'.
 8065:                      '<td>&nbsp;&nbsp;</td>'.
 8066:                      '<td valign="top">&nbsp;<b>'.$lt{'new'}.'</b><br />'.
 8067:                      '<input type="text" name="newsec" value="" />'.
 8068:                      '<input type="hidden" name="section" value="" />'.
 8069:                      '<input type="hidden" name="groups" value="" />'.
 8070:                      '<input type="hidden" name="crstype" value="" /></td>'.
 8071:                      '</tr></table></td>'."\n";
 8072:     if ($showcredits) {
 8073:         $otheritems .= '<td><br />'."\n".
 8074:                        '<input type="text" size="3" name="credits" value="" /></td>'."\n";
 8075:     }
 8076:     $otheritems .= <<ENDTIMEENTRY;
 8077: <td><br /><input type="hidden" name="start" value='' />
 8078: <a href=
 8079: "javascript:pjump('date_start','Start Date',document.cu.start.value,'start','cu.pres','dateset')">$lt{'ssd'}</a></td>
 8080: <td><br /><input type="hidden" name="end" value='' />
 8081: <a href=
 8082: "javascript:pjump('date_end','End Date',document.cu.end.value,'end','cu.pres','dateset')">$lt{'sed'}</a></td>
 8083: ENDTIMEENTRY
 8084:     $otheritems .= &Apache::loncommon::end_data_table_row().
 8085:                    &Apache::loncommon::end_data_table()."\n";
 8086:     return $cb_jscript.$header.$hiddenitems.$otheritems;
 8087: }
 8088: 
 8089: sub update_selfenroll_config {
 8090:     my ($r,$cid,$cdom,$cnum,$context,$crstype,$currsettings) = @_;
 8091:     return unless (ref($currsettings) eq 'HASH');
 8092:     my ($row,$lt) = &Apache::lonuserutils::get_selfenroll_titles();
 8093:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
 8094:     my (%changes,%warning);
 8095:     my $curr_types;
 8096:     my %noedit;
 8097:     unless ($context eq 'domain') {
 8098:         %noedit = &get_noedit_fields($cdom,$cnum,$crstype,$row);
 8099:     }
 8100:     if (ref($row) eq 'ARRAY') {
 8101:         foreach my $item (@{$row}) {
 8102:             next if ($noedit{$item});
 8103:             if ($item eq 'enroll_dates') {
 8104:                 my (%currenrolldate,%newenrolldate);
 8105:                 foreach my $type ('start','end') {
 8106:                     $currenrolldate{$type} = $currsettings->{'selfenroll_'.$type.'_date'};
 8107:                     $newenrolldate{$type} = &Apache::lonhtmlcommon::get_date_from_form('selfenroll_'.$type.'_date');
 8108:                     if ($newenrolldate{$type} ne $currenrolldate{$type}) {
 8109:                         $changes{'internal.selfenroll_'.$type.'_date'} = $newenrolldate{$type};
 8110:                     }
 8111:                 }
 8112:             } elsif ($item eq 'access_dates') {
 8113:                 my (%currdate,%newdate);
 8114:                 foreach my $type ('start','end') {
 8115:                     $currdate{$type} = $currsettings->{'selfenroll_'.$type.'_access'};
 8116:                     $newdate{$type} = &Apache::lonhtmlcommon::get_date_from_form('selfenroll_'.$type.'_access');
 8117:                     if ($newdate{$type} ne $currdate{$type}) {
 8118:                         $changes{'internal.selfenroll_'.$type.'_access'} = $newdate{$type};
 8119:                     }
 8120:                 }
 8121:             } elsif ($item eq 'types') {
 8122:                 $curr_types = $currsettings->{'selfenroll_'.$item};
 8123:                 if ($env{'form.selfenroll_all'}) {
 8124:                     if ($curr_types ne '*') {
 8125:                         $changes{'internal.selfenroll_types'} = '*';
 8126:                     } else {
 8127:                         next;
 8128:                     }
 8129:                 } else {
 8130:                     my %currdoms;
 8131:                     my @entries = split(/;/,$curr_types);
 8132:                     my @deletedoms = &Apache::loncommon::get_env_multiple('form.selfenroll_delete');
 8133:                     my @activations = &Apache::loncommon::get_env_multiple('form.selfenroll_activate');
 8134:                     my $newnum = 0;
 8135:                     my @latesttypes;
 8136:                     foreach my $num (@activations) {
 8137:                         my @types = &Apache::loncommon::get_env_multiple('form.selfenroll_types_'.$num);
 8138:                         if (@types > 0) {
 8139:                             @types = sort(@types);
 8140:                             my $typestr = join(',',@types);
 8141:                             my $typedom = $env{'form.selfenroll_dom_'.$num};
 8142:                             $latesttypes[$newnum] = $typedom.':'.$typestr;
 8143:                             $currdoms{$typedom} = 1;
 8144:                             $newnum ++;
 8145:                         }
 8146:                     }
 8147:                     for (my $j=0; $j<$env{'form.selfenroll_types_total'}; $j++) {
 8148:                         if ((!grep(/^$j$/,@deletedoms)) && (!grep(/^$j$/,@activations))) {
 8149:                             my @types = &Apache::loncommon::get_env_multiple('form.selfenroll_types_'.$j);
 8150:                             if (@types > 0) {
 8151:                                 @types = sort(@types);
 8152:                                 my $typestr = join(',',@types);
 8153:                                 my $typedom = $env{'form.selfenroll_dom_'.$j};
 8154:                                 $latesttypes[$newnum] = $typedom.':'.$typestr;
 8155:                                 $currdoms{$typedom} = 1;
 8156:                                 $newnum ++;
 8157:                             }
 8158:                         }
 8159:                     }
 8160:                     if ($env{'form.selfenroll_newdom'} ne '') {
 8161:                         my $typedom = $env{'form.selfenroll_newdom'};
 8162:                         if ((!defined($currdoms{$typedom})) && 
 8163:                             (&Apache::lonnet::domain($typedom) ne '')) {
 8164:                             my $typestr;
 8165:                             my ($othertitle,$usertypes,$types) = 
 8166:                                 &Apache::loncommon::sorted_inst_types($typedom);
 8167:                             my $othervalue = 'any';
 8168:                             if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 8169:                                 if (@{$types} > 0) {
 8170:                                     my @esc_types = map { &escape($_); } @{$types};
 8171:                                     $othervalue = 'other';
 8172:                                     $typestr = join(',',(@esc_types,$othervalue));
 8173:                                 }
 8174:                                 $typestr = $othervalue;
 8175:                             } else {
 8176:                                 $typestr = $othervalue;
 8177:                             } 
 8178:                             $latesttypes[$newnum] = $typedom.':'.$typestr;
 8179:                             $newnum ++ ;
 8180:                         }
 8181:                     }
 8182:                     my $selfenroll_types = join(';',@latesttypes);
 8183:                     if ($selfenroll_types ne $curr_types) {
 8184:                         $changes{'internal.selfenroll_types'} = $selfenroll_types;
 8185:                     }
 8186:                 }
 8187:             } elsif ($item eq 'limit') {
 8188:                 my $newlimit = $env{'form.selfenroll_limit'};
 8189:                 my $newcap = $env{'form.selfenroll_cap'};
 8190:                 $newcap =~s/\s+//g;
 8191:                 my $currlimit =  $currsettings->{'selfenroll_limit'};
 8192:                 $currlimit = 'none' if ($currlimit eq '');
 8193:                 my $currcap = $currsettings->{'selfenroll_cap'};
 8194:                 if ($newlimit ne $currlimit) {
 8195:                     if ($newlimit ne 'none') {
 8196:                         if ($newcap =~ /^\d+$/) {
 8197:                             if ($newcap ne $currcap) {
 8198:                                 $changes{'internal.selfenroll_cap'} = $newcap;
 8199:                             }
 8200:                             $changes{'internal.selfenroll_limit'} = $newlimit;
 8201:                         } else {
 8202:                             $warning{$item} = &mt('Maximum enrollment setting unchanged.').'<br />'.
 8203:                                 &mt('The value provided was invalid - it must be a positive integer if enrollment is being limited.'); 
 8204:                         }
 8205:                     } elsif ($currcap ne '') {
 8206:                         $changes{'internal.selfenroll_cap'} = '';
 8207:                         $changes{'internal.selfenroll_limit'} = $newlimit; 
 8208:                     }
 8209:                 } elsif ($currlimit ne 'none') {
 8210:                     if ($newcap =~ /^\d+$/) {
 8211:                         if ($newcap ne $currcap) {
 8212:                             $changes{'internal.selfenroll_cap'} = $newcap;
 8213:                         }
 8214:                     } else {
 8215:                         $warning{$item} = &mt('Maximum enrollment setting unchanged.').'<br />'.
 8216:                             &mt('The value provided was invalid - it must be a positive integer if enrollment is being limited.');
 8217:                     }
 8218:                 }
 8219:             } elsif ($item eq 'approval') {
 8220:                 my (@currnotified,@newnotified);
 8221:                 my $currapproval = $currsettings->{'selfenroll_approval'};
 8222:                 my $currnotifylist = $currsettings->{'selfenroll_notifylist'};
 8223:                 if ($currnotifylist ne '') {
 8224:                     @currnotified = split(/,/,$currnotifylist);
 8225:                     @currnotified = sort(@currnotified);
 8226:                 }
 8227:                 my $newapproval = $env{'form.selfenroll_approval'};
 8228:                 @newnotified = &Apache::loncommon::get_env_multiple('form.selfenroll_notify');
 8229:                 @newnotified = sort(@newnotified);
 8230:                 if ($newapproval ne $currapproval) {
 8231:                     $changes{'internal.selfenroll_approval'} = $newapproval;
 8232:                     if (!$newapproval) {
 8233:                         if ($currnotifylist ne '') {
 8234:                             $changes{'internal.selfenroll_notifylist'} = '';
 8235:                         }
 8236:                     } else {
 8237:                         my @differences =  
 8238:                             &Apache::loncommon::compare_arrays(\@currnotified,\@newnotified);
 8239:                         if (@differences > 0) {
 8240:                             if (@newnotified > 0) {
 8241:                                 $changes{'internal.selfenroll_notifylist'} = join(',',@newnotified);
 8242:                             } else {
 8243:                                 $changes{'internal.selfenroll_notifylist'} = join(',',@newnotified);
 8244:                             }
 8245:                         }
 8246:                     }
 8247:                 } else {
 8248:                     my @differences = &Apache::loncommon::compare_arrays(\@currnotified,\@newnotified);
 8249:                     if (@differences > 0) {
 8250:                         if (@newnotified > 0) {
 8251:                             $changes{'internal.selfenroll_notifylist'} = join(',',@newnotified);
 8252:                         } else {
 8253:                             $changes{'internal.selfenroll_notifylist'} = '';
 8254:                         }
 8255:                     }
 8256:                 }
 8257:             } else {
 8258:                 my $curr_val = $currsettings->{'selfenroll_'.$item};
 8259:                 my $newval = $env{'form.selfenroll_'.$item};
 8260:                 if ($item eq 'section') {
 8261:                     $newval = $env{'form.sections'};
 8262:                     if (defined($curr_groups{$newval})) {
 8263:                         $newval = $curr_val;
 8264:                         $warning{$item} = &mt('Section for self-enrolled users unchanged as the proposed section is a group').'<br />'.
 8265:                                           &mt('Group names and section names must be distinct');
 8266:                     } elsif ($newval eq 'all') {
 8267:                         $newval = $curr_val;
 8268:                         $warning{$item} = &mt('Section for self-enrolled users unchanged, as "all" is a reserved section name.');
 8269:                     }
 8270:                     if ($newval eq '') {
 8271:                         $newval = 'none';
 8272:                     }
 8273:                 }
 8274:                 if ($newval ne $curr_val) {
 8275:                     $changes{'internal.selfenroll_'.$item} = $newval;
 8276:                 }
 8277:             }
 8278:         }
 8279:         if (keys(%warning) > 0) {
 8280:             foreach my $item (@{$row}) {
 8281:                 if (exists($warning{$item})) {
 8282:                     $r->print($warning{$item}.'<br />');
 8283:                 }
 8284:             } 
 8285:         }
 8286:         if (keys(%changes) > 0) {
 8287:             my $putresult = &Apache::lonnet::put('environment',\%changes,$cdom,$cnum);
 8288:             if ($putresult eq 'ok') {
 8289:                 if ((exists($changes{'internal.selfenroll_types'})) ||
 8290:                     (exists($changes{'internal.selfenroll_start_date'}))  ||
 8291:                     (exists($changes{'internal.selfenroll_end_date'}))) {
 8292:                     my %crsinfo = &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',
 8293:                                                                 $cnum,undef,undef,'Course');
 8294:                     my $chome = &Apache::lonnet::homeserver($cnum,$cdom);
 8295:                     if (ref($crsinfo{$cid}) eq 'HASH') {
 8296:                         foreach my $item ('selfenroll_types','selfenroll_start_date','selfenroll_end_date') {
 8297:                             if (exists($changes{'internal.'.$item})) {
 8298:                                 $crsinfo{$cid}{$item} = $changes{'internal.'.$item};
 8299:                             }
 8300:                         }
 8301:                         my $crsputresult =
 8302:                             &Apache::lonnet::courseidput($cdom,\%crsinfo,
 8303:                                                          $chome,'notime');
 8304:                     }
 8305:                 }
 8306:                 $r->print(&mt('The following changes were made to self-enrollment settings:').'<ul>');
 8307:                 foreach my $item (@{$row}) {
 8308:                     my $title = $item;
 8309:                     if (ref($lt) eq 'HASH') {
 8310:                         $title = $lt->{$item};
 8311:                     }
 8312:                     if ($item eq 'enroll_dates') {
 8313:                         foreach my $type ('start','end') {
 8314:                             if (exists($changes{'internal.selfenroll_'.$type.'_date'})) {
 8315:                                 my $newdate = &Apache::lonlocal::locallocaltime($changes{'internal.selfenroll_'.$type.'_date'});
 8316:                                 $r->print('<li>'.&mt('[_1]: "[_2]" set to "[_3]".',
 8317:                                           $title,$type,$newdate).'</li>');
 8318:                             }
 8319:                         }
 8320:                     } elsif ($item eq 'access_dates') {
 8321:                         foreach my $type ('start','end') {
 8322:                             if (exists($changes{'internal.selfenroll_'.$type.'_access'})) {
 8323:                                 my $newdate = &Apache::lonlocal::locallocaltime($changes{'internal.selfenroll_'.$type.'_access'});
 8324:                                 $r->print('<li>'.&mt('[_1]: "[_2]" set to "[_3]".',
 8325:                                           $title,$type,$newdate).'</li>');
 8326:                             }
 8327:                         }
 8328:                     } elsif ($item eq 'limit') {
 8329:                         if ((exists($changes{'internal.selfenroll_limit'})) ||
 8330:                             (exists($changes{'internal.selfenroll_cap'}))) {
 8331:                             my ($newval,$newcap);
 8332:                             if ($changes{'internal.selfenroll_cap'} ne '') {
 8333:                                 $newcap = $changes{'internal.selfenroll_cap'}
 8334:                             } else {
 8335:                                 $newcap = $currsettings->{'selfenroll_cap'};
 8336:                             }
 8337:                             if ($changes{'internal.selfenroll_limit'} eq 'none') {
 8338:                                 $newval = &mt('No limit');
 8339:                             } elsif ($changes{'internal.selfenroll_limit'} eq 
 8340:                                      'allstudents') {
 8341:                                 $newval = &mt('New self-enrollment no longer allowed when total (all students) reaches [_1].',$newcap);
 8342:                             } elsif ($changes{'internal.selfenroll_limit'} eq 'selfenrolled') {
 8343:                                 $newval = &mt('New self-enrollment no longer allowed when total number of self-enrolled students reaches [_1].',$newcap);
 8344:                             } else {
 8345:                                 my $currlimit =  $currsettings->{'selfenroll_limit'};
 8346:                                 if ($currlimit eq 'allstudents') {
 8347:                                     $newval = &mt('New self-enrollment no longer allowed when total (all students) reaches [_1].',$newcap);
 8348:                                 } elsif ($changes{'internal.selfenroll_limit'} eq 'selfenrolled') {
 8349:                                     $newval =  &mt('New self-enrollment no longer allowed when total number of self-enrolled students reaches [_1].',$newcap);
 8350:                                 }
 8351:                             }
 8352:                             $r->print('<li>'.&mt('"[_1]" set to "[_2]".',$title,$newval).'</li>'."\n");
 8353:                         }
 8354:                     } elsif ($item eq 'approval') {
 8355:                         if ((exists($changes{'internal.selfenroll_approval'})) ||
 8356:                             (exists($changes{'internal.selfenroll_notifylist'}))) {
 8357:                             my %selfdescs = &Apache::lonuserutils::selfenroll_default_descs();
 8358:                             my ($newval,$newnotify);
 8359:                             if (exists($changes{'internal.selfenroll_notifylist'})) {
 8360:                                 $newnotify = $changes{'internal.selfenroll_notifylist'};
 8361:                             } else {   
 8362:                                 $newnotify = $currsettings->{'selfenroll_notifylist'};
 8363:                             }
 8364:                             if (exists($changes{'internal.selfenroll_approval'})) {
 8365:                                 if ($changes{'internal.selfenroll_approval'} !~ /^[012]$/) {
 8366:                                     $changes{'internal.selfenroll_approval'} = '0';
 8367:                                 }
 8368:                                 $newval = $selfdescs{'approval'}{$changes{'internal.selfenroll_approval'}};
 8369:                             } else {
 8370:                                 my $currapproval = $currsettings->{'selfenroll_approval'}; 
 8371:                                 if ($currapproval !~ /^[012]$/) {
 8372:                                     $currapproval = 0;
 8373:                                 }
 8374:                                 $newval = $selfdescs{'approval'}{$currapproval};
 8375:                             }
 8376:                             $r->print('<li>'.&mt('"[_1]" set to "[_2]".',$title,$newval));
 8377:                             if ($newnotify) {
 8378:                                 $r->print('<br />'.&mt('The following will be notified when an enrollment request needs approval, or has been approved: [_1].',$newnotify));
 8379:                             } else {
 8380:                                 $r->print('<br />'.&mt('No notifications sent when an enrollment request needs approval, or has been approved.'));
 8381:                             }
 8382:                             $r->print('</li>'."\n");
 8383:                         }
 8384:                     } else {
 8385:                         if (exists($changes{'internal.selfenroll_'.$item})) {
 8386:                             my $newval = $changes{'internal.selfenroll_'.$item};
 8387:                             if ($item eq 'types') {
 8388:                                 if ($newval eq '') {
 8389:                                     $newval = &mt('None');
 8390:                                 } elsif ($newval eq '*') {
 8391:                                     $newval = &mt('Any user in any domain');
 8392:                                 }
 8393:                             } elsif ($item eq 'registered') {
 8394:                                 if ($newval eq '1') {
 8395:                                     $newval = &mt('Yes');
 8396:                                 } elsif ($newval eq '0') {
 8397:                                     $newval = &mt('No');
 8398:                                 }
 8399:                             }
 8400:                             $r->print('<li>'.&mt('"[_1]" set to "[_2]".',$title,$newval).'</li>'."\n");
 8401:                         }
 8402:                     }
 8403:                 }
 8404:                 $r->print('</ul>');
 8405:                 if ($env{'course.'.$cid.'.description'} ne '') {
 8406:                     my %newenvhash;
 8407:                     foreach my $key (keys(%changes)) {
 8408:                         $newenvhash{'course.'.$cid.'.'.$key} = $changes{$key};
 8409:                     }
 8410:                     &Apache::lonnet::appenv(\%newenvhash);
 8411:                 }
 8412:             } else {
 8413:                 $r->print(&mt('An error occurred when saving changes to self-enrollment settings in this course.').'<br />'.
 8414:                           &mt('The error was: [_1].',$putresult));
 8415:             }
 8416:         } else {
 8417:             $r->print(&mt('No changes were made to the existing self-enrollment settings in this course.'));
 8418:         }
 8419:     } else {
 8420:         $r->print(&mt('No changes were made to the existing self-enrollment settings in this course.'));
 8421:     }
 8422:     my $visactions = &cat_visibility();
 8423:     my ($cathash,%cattype);
 8424:     my %domconfig = &Apache::lonnet::get_dom('configuration',['coursecategories'],$cdom);
 8425:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 8426:         $cathash = $domconfig{'coursecategories'}{'cats'};
 8427:         $cattype{'auth'} = $domconfig{'coursecategories'}{'auth'};
 8428:         $cattype{'unauth'} = $domconfig{'coursecategories'}{'unauth'};
 8429:     } else {
 8430:         $cathash = {};
 8431:         $cattype{'auth'} = 'std';
 8432:         $cattype{'unauth'} = 'std';
 8433:     }
 8434:     if (($cattype{'auth'} eq 'none') && ($cattype{'unauth'} eq 'none')) {
 8435:         $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
 8436:                   '<br />'.
 8437:                   '<br />'.$visactions->{'take'}.'<ul>'.
 8438:                   '<li>'.$visactions->{'dc_chgconf'}.'</li>'.
 8439:                   '</ul>');
 8440:     } elsif (($cattype{'auth'} !~ /^(std|domonly)$/) && ($cattype{'unauth'} !~ /^(std|domonly)$/)) {
 8441:         if ($currsettings->{'uniquecode'}) {
 8442:             $r->print('<span class="LC_info">'.$visactions->{'vis'}.'</span>');
 8443:         } else {
 8444:             $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
 8445:                   '<br />'.
 8446:                   '<br />'.$visactions->{'take'}.'<ul>'.
 8447:                   '<li>'.$visactions->{'dc_setcode'}.'</li>'.
 8448:                   '</ul><br />');
 8449:         }
 8450:     } else {
 8451:         my ($visible,$cansetvis,$vismsgs) = &visible_in_stdcat($cdom,$cnum,\%domconfig);
 8452:         if (ref($visactions) eq 'HASH') {
 8453:             if (!$visible) {
 8454:                 $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
 8455:                           '<br />');
 8456:                 if (ref($vismsgs) eq 'ARRAY') {
 8457:                     $r->print('<br />'.$visactions->{'take'}.'<ul>');
 8458:                     foreach my $item (@{$vismsgs}) {
 8459:                         $r->print('<li>'.$visactions->{$item}.'</li>');
 8460:                     }
 8461:                     $r->print('</ul>');
 8462:                 }
 8463:                 $r->print($cansetvis);
 8464:             }
 8465:         }
 8466:     } 
 8467:     return;
 8468: }
 8469: 
 8470: #---------------------------------------------- end functions for &phase_two
 8471: 
 8472: #--------------------------------- functions for &phase_two and &phase_three
 8473: 
 8474: #--------------------------end of functions for &phase_two and &phase_three
 8475: 
 8476: 1;
 8477: __END__
 8478: 
 8479: 

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