File:  [LON-CAPA] / loncom / interface / loncreateuser.pm
Revision 1.406.2.6: download - view: text, annotated - select for diffs
Fri Nov 11 02:13:51 2016 UTC (7 years, 10 months ago) by raeburn
Branches: version_2_11_X
- For 2.11
  - Backport 1.418, 1.419

    1: # The LearningOnline Network with CAPA
    2: # Create a user
    3: #
    4: # $Id: loncreateuser.pm,v 1.406.2.6 2016/11/11 02:13:51 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:                    'requestauthor'  => 'Can request author space',
  256:     );
  257:     if ($context eq 'requestcourses') {
  258:         %userenv = &Apache::lonnet::userenvironment($ccdomain,$ccuname,
  259:                       'requestcourses.official','requestcourses.unofficial',
  260:                       'requestcourses.community','requestcourses.textbook');
  261:         @usertools = ('official','unofficial','community','textbook');
  262:         @options =('norequest','approval','autolimit','validate');
  263:         %validations = &Apache::lonnet::auto_courserequest_checks($ccdomain);
  264:         %reqtitles = &courserequest_titles();
  265:         %reqdisplay = &courserequest_display();
  266:         $colspan = ' colspan="2"';
  267:         %domconfig =
  268:             &Apache::lonnet::get_dom('configuration',['requestcourses'],$ccdomain);
  269:         $isadv = &Apache::lonnet::is_advanced_user($ccdomain,$ccuname);
  270:     } elsif ($context eq 'requestauthor') {
  271:         %userenv = &Apache::lonnet::userenvironment($ccdomain,$ccuname,
  272:                                                     'requestauthor');
  273:         @usertools = ('requestauthor');
  274:         @options =('norequest','approval','automatic');
  275:         %reqtitles = &requestauthor_titles();
  276:         %reqdisplay = &requestauthor_display();
  277:         $colspan = ' colspan="2"';
  278:         %domconfig =
  279:             &Apache::lonnet::get_dom('configuration',['requestauthor'],$ccdomain);
  280:     } else {
  281:         %userenv = &Apache::lonnet::userenvironment($ccdomain,$ccuname,
  282:                           'tools.aboutme','tools.portfolio','tools.blog',
  283:                           'tools.webdav');
  284:         @usertools = ('aboutme','blog','webdav','portfolio');
  285:     }
  286:     foreach my $item (@usertools) {
  287:         my ($custom_access,$curr_access,$cust_on,$cust_off,$tool_on,$tool_off,
  288:             $currdisp,$custdisp,$custradio);
  289:         $cust_off = 'checked="checked" ';
  290:         $tool_on = 'checked="checked" ';
  291:         $curr_access =  
  292:             &Apache::lonnet::usertools_access($ccuname,$ccdomain,$item,undef,
  293:                                               $context);
  294:         if ($context eq 'requestauthor') {
  295:             if ($userenv{$context} ne '') {
  296:                 $cust_on = ' checked="checked" ';
  297:                 $cust_off = '';
  298:             }  
  299:         } elsif ($userenv{$context.'.'.$item} ne '') {
  300:             $cust_on = ' checked="checked" ';
  301:             $cust_off = '';
  302:         }
  303:         if ($context eq 'requestcourses') {
  304:             if ($userenv{$context.'.'.$item} eq '') {
  305:                 $custom_access = &mt('Currently from default setting.');
  306:             } else {
  307:                 $custom_access = &mt('Currently from custom setting.');
  308:             }
  309:         } elsif ($context eq 'requestauthor') {
  310:             if ($userenv{$context} eq '') {
  311:                 $custom_access = &mt('Currently from default setting.');
  312:             } else {
  313:                 $custom_access = &mt('Currently from custom setting.');
  314:             }
  315:         } else {
  316:             if ($userenv{$context.'.'.$item} eq '') {
  317:                 $custom_access =
  318:                     &mt('Availability determined currently from default setting.');
  319:                 if (!$curr_access) {
  320:                     $tool_off = 'checked="checked" ';
  321:                     $tool_on = '';
  322:                 }
  323:             } else {
  324:                 $custom_access =
  325:                     &mt('Availability determined currently from custom setting.');
  326:                 if ($userenv{$context.'.'.$item} == 0) {
  327:                     $tool_off = 'checked="checked" ';
  328:                     $tool_on = '';
  329:                 }
  330:             }
  331:         }
  332:         $output .= '  <tr class="LC_info_row">'."\n".
  333:                    '   <td'.$colspan.'>'.$lt{$item}.'</td>'."\n".
  334:                    '  </tr>'."\n".
  335:                    &Apache::loncommon::start_data_table_row()."\n";
  336:         if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
  337:             my ($curroption,$currlimit);
  338:             my $envkey = $context.'.'.$item;
  339:             if ($context eq 'requestauthor') {
  340:                 $envkey = $context;
  341:             }
  342:             if ($userenv{$envkey} ne '') {
  343:                 $curroption = $userenv{$envkey};
  344:             } else {
  345:                 my (@inststatuses);
  346:                 if ($context eq 'requestcourses') {
  347:                     $curroption =
  348:                         &Apache::loncoursequeueadmin::get_processtype('course',$ccuname,$ccdomain,
  349:                                                                       $isadv,$ccdomain,$item,
  350:                                                                       \@inststatuses,\%domconfig);
  351:                 } else {
  352:                      $curroption = 
  353:                          &Apache::loncoursequeueadmin::get_processtype('requestauthor',$ccuname,$ccdomain,
  354:                                                                        $isadv,$ccdomain,undef,
  355:                                                                        \@inststatuses,\%domconfig);
  356:                 }
  357:             }
  358:             if (!$curroption) {
  359:                 $curroption = 'norequest';
  360:             }
  361:             if ($curroption =~ /^autolimit=(\d*)$/) {
  362:                 $currlimit = $1;
  363:                 if ($currlimit eq '') {
  364:                     $currdisp = &mt('Yes, automatic creation');
  365:                 } else {
  366:                     $currdisp = &mt('Yes, up to [quant,_1,request]/user',$currlimit);
  367:                 }
  368:             } else {
  369:                 $currdisp = $reqdisplay{$curroption};
  370:             }
  371:             $custdisp = '<table>';
  372:             foreach my $option (@options) {
  373:                 my $val = $option;
  374:                 if ($option eq 'norequest') {
  375:                     $val = 0;
  376:                 }
  377:                 if ($option eq 'validate') {
  378:                     my $canvalidate = 0;
  379:                     if (ref($validations{$item}) eq 'HASH') {
  380:                         if ($validations{$item}{'_custom_'}) {
  381:                             $canvalidate = 1;
  382:                         }
  383:                     }
  384:                     next if (!$canvalidate);
  385:                 }
  386:                 my $checked = '';
  387:                 if ($option eq $curroption) {
  388:                     $checked = ' checked="checked"';
  389:                 } elsif ($option eq 'autolimit') {
  390:                     if ($curroption =~ /^autolimit/) {
  391:                         $checked = ' checked="checked"';
  392:                     }
  393:                 }
  394:                 my $name = 'crsreq_'.$item;
  395:                 if ($context eq 'requestauthor') {
  396:                     $name = $item;
  397:                 }
  398:                 $custdisp .= '<tr><td><span class="LC_nobreak"><label>'.
  399:                              '<input type="radio" name="'.$name.'" '.
  400:                              'value="'.$val.'"'.$checked.' />'.
  401:                              $reqtitles{$option}.'</label>&nbsp;';
  402:                 if ($option eq 'autolimit') {
  403:                     $custdisp .= '<input type="text" name="'.$name.
  404:                                  '_limit" size="1" '.
  405:                                  'value="'.$currlimit.'" /></span><br />'.
  406:                                  $reqtitles{'unlimited'};
  407:                 } else {
  408:                     $custdisp .= '</span>';
  409:                 }
  410:                 $custdisp .= '</td></tr>';
  411:             }
  412:             $custdisp .= '</table>';
  413:             $custradio = '</span></td><td>'.&mt('Custom setting').'<br />'.$custdisp;
  414:         } else {
  415:             $currdisp = ($curr_access?&mt('Yes'):&mt('No'));
  416:             my $name = $context.'_'.$item;
  417:             if ($context eq 'requestauthor') {
  418:                 $name = $context;
  419:             }
  420:             $custdisp = '<span class="LC_nobreak"><label>'.
  421:                         '<input type="radio" name="'.$name.'"'.
  422:                         ' value="1" '.$tool_on.'/>'.&mt('On').'</label>&nbsp;<label>'.
  423:                         '<input type="radio" name="'.$name.'" value="0" '.
  424:                         $tool_off.'/>'.&mt('Off').'</label></span>';
  425:             $custradio = ('&nbsp;'x2).'--'.$lt{'cusa'}.':&nbsp;'.$custdisp.
  426:                           '</span>';
  427:         }
  428:         $output .= '  <td'.$colspan.'>'.$custom_access.('&nbsp;'x4).
  429:                    $lt{'avai'}.': '.$currdisp.'</td>'."\n".
  430:                    &Apache::loncommon::end_data_table_row()."\n";
  431:         unless (&Apache::lonnet::allowed('udp',$ccdomain)) {
  432:             $output .=
  433:                    &Apache::loncommon::start_data_table_row()."\n".
  434:                    '  <td style="vertical-align:top;"><span class="LC_nobreak">'.
  435:                    $lt{'chse'}.': <label>'.
  436:                    '<input type="radio" name="custom'.$item.'" value="0" '.
  437:                    $cust_off.'/>'.$lt{'usde'}.'</label>'.('&nbsp;' x3).
  438:                    '<label><input type="radio" name="custom'.$item.'" value="1" '.
  439:                    $cust_on.'/>'.$lt{'uscu'}.'</label>'.$custradio.'</td>'.
  440:                    &Apache::loncommon::end_data_table_row()."\n";
  441:         }
  442:     }
  443:     return $output;
  444: }
  445: 
  446: sub coursereq_externaluser {
  447:     my ($ccuname,$ccdomain,$cdom) = @_;
  448:     my (@usertools,@options,%validations,%userenv,$output);
  449:     my %lt = &Apache::lonlocal::texthash (
  450:                    'official'   => 'Can request creation of official courses',
  451:                    'unofficial' => 'Can request creation of unofficial courses',
  452:                    'community'  => 'Can request creation of communities',
  453:                    'textbook'   => 'Can request creation of textbook courses',
  454:     );
  455: 
  456:     %userenv = &Apache::lonnet::userenvironment($ccdomain,$ccuname,
  457:                       'reqcrsotherdom.official','reqcrsotherdom.unofficial',
  458:                       'reqcrsotherdom.community','reqcrsotherdom.textbook');
  459:     @usertools = ('official','unofficial','community','textbook');
  460:     @options = ('approval','validate','autolimit');
  461:     %validations = &Apache::lonnet::auto_courserequest_checks($cdom);
  462:     my $optregex = join('|',@options);
  463:     my %reqtitles = &courserequest_titles();
  464:     foreach my $item (@usertools) {
  465:         my ($curroption,$currlimit,$tooloff);
  466:         if ($userenv{'reqcrsotherdom.'.$item} ne '') {
  467:             my @curr = split(',',$userenv{'reqcrsotherdom.'.$item});
  468:             foreach my $req (@curr) {
  469:                 if ($req =~ /^\Q$cdom\E\:($optregex)=?(\d*)$/) {
  470:                     $curroption = $1;
  471:                     $currlimit = $2;
  472:                     last;
  473:                 }
  474:             }
  475:             if (!$curroption) {
  476:                 $curroption = 'norequest';
  477:                 $tooloff = ' checked="checked"';
  478:             }
  479:         } else {
  480:             $curroption = 'norequest';
  481:             $tooloff = ' checked="checked"';
  482:         }
  483:         $output.= &Apache::loncommon::start_data_table_row()."\n".
  484:                   '  <td><span class="LC_nobreak">'.$lt{$item}.': </span></td><td>'.
  485:                   '<table><tr><td valign="top">'."\n".
  486:                   '<label><input type="radio" name="reqcrsotherdom_'.$item.
  487:                   '" value=""'.$tooloff.' />'.$reqtitles{'norequest'}.
  488:                   '</label></td>';
  489:         foreach my $option (@options) {
  490:             if ($option eq 'validate') {
  491:                 my $canvalidate = 0;
  492:                 if (ref($validations{$item}) eq 'HASH') {
  493:                     if ($validations{$item}{'_external_'}) {
  494:                         $canvalidate = 1;
  495:                     }
  496:                 }
  497:                 next if (!$canvalidate);
  498:             }
  499:             my $checked = '';
  500:             if ($option eq $curroption) {
  501:                 $checked = ' checked="checked"';
  502:             }
  503:             $output .= '<td valign="top"><span class="LC_nobreak"><label>'.
  504:                        '<input type="radio" name="reqcrsotherdom_'.$item.
  505:                        '" value="'.$option.'"'.$checked.' />'.
  506:                        $reqtitles{$option}.'</label>';
  507:             if ($option eq 'autolimit') {
  508:                 $output .= '&nbsp;<input type="text" name="reqcrsotherdom_'.
  509:                            $item.'_limit" size="1" '.
  510:                            'value="'.$currlimit.'" /></span>'.
  511:                            '<br />'.$reqtitles{'unlimited'};
  512:             } else {
  513:                 $output .= '</span>';
  514:             }
  515:             $output .= '</td>';
  516:         }
  517:         $output .= '</td></tr></table></td>'."\n".
  518:                    &Apache::loncommon::end_data_table_row()."\n";
  519:     }
  520:     return $output;
  521: }
  522: 
  523: sub domainrole_req {
  524:     my ($ccuname,$ccdomain) = @_;
  525:     return '<br /><h3>'.
  526:            &mt('User Can Request Assignment of Domain Roles?').
  527:            '</h3>'."\n".
  528:            &Apache::loncommon::start_data_table().
  529:            &build_tools_display($ccuname,$ccdomain,
  530:                                 'requestauthor').
  531:            &Apache::loncommon::end_data_table();
  532: }
  533: 
  534: sub domadhocroles {
  535:     my ($ccuname,$ccdomain) = @_;
  536:     my $confname = &Apache::lonnet::get_domainconfiguser($env{'request.role.domain'});
  537:     my %existing=&Apache::lonnet::dump('roles',$env{'request.role.domain'},
  538:                                        $confname,'rolesdef_');
  539:     my ($output,$canmodify);
  540:     if (&Apache::lonnet::allowed('cdh',$env{'request.role.domain'})) {
  541:         $canmodify = 1;
  542:     }
  543:     if (keys(%existing) > 0) {
  544:         my @current;
  545:         my $curradhoc = 'adhocroles.'.$env{'request.role.domain'};
  546:         my %userenv = &Apache::lonnet::userenvironment($ccdomain,$ccuname,$curradhoc);
  547:         if ($userenv{$curradhoc}) {
  548:             @current = split(/,/,$userenv{$curradhoc});
  549:         }
  550:         if (!$canmodify && !@current) {
  551:             return;
  552:         }
  553:         my %customroles;
  554:         foreach my $key (keys(%existing)) {
  555:             if ($key=~/^rolesdef\_(\w+)$/) {
  556:                 my $rolename = $1;
  557:                 my %privs;
  558:                 ($privs{'system'},$privs{'domain'},$privs{'course'}) = split(/\_/,$existing{$key});
  559:                 $customroles{$rolename} = \%privs;
  560:             }
  561:         }
  562:         $output = '<br /><h3>'.
  563:                   &mt('Ad Hoc Course Roles Selectable via Helpdesk Role').
  564:                   '</h3>'."\n".
  565:                   &Apache::loncommon::start_data_table().
  566:                   &Apache::loncommon::start_data_table_header_row();
  567:         if ($canmodify) {
  568:             $output .= '<th>'.&mt('Action').'</th>';
  569:         }
  570:         $output .= '<th>'.&mt('Role').'</th>'.
  571:                    '<th>'.&mt('Privileges in Course').'<th>'.
  572:                    &Apache::loncommon::end_data_table_header_row();
  573:         foreach my $key (sort(keys(%customroles))) {
  574:             next if ((!$canmodify) && (!grep(/^\Q$key\E$/,@current)));
  575:             $output .= &Apache::loncommon::start_data_table_row();
  576:             if ($canmodify) {
  577:                 if (grep(/^\Q$key\E$/,@current)) {
  578:                     $output .= '<td><label>'.
  579:                                '<input type="checkbox" name="adhocroledel" value="'.$key.'" />'.
  580:                                &mt('Delete').'</label>'.
  581:                                '</td>';
  582:                 } else {
  583:                     $output .= '<td><label>'.
  584:                                '<input type="checkbox" name="adhocroleadd" value="'.$key.'" />'.
  585:                                &mt('Add').'</label>'.
  586:                                '</td>';
  587:                 }
  588:             }
  589:             $output .= '<td>'.$key.'</td><td>';
  590:             foreach my $level ('course','domain','system') {
  591:                 if ($customroles{$key}{$level}) {
  592:                     my $suffix;
  593:                     if (($level eq 'domain') || ($level eq 'system')) {
  594:                         $suffix = '&nbsp;('.&mt($level).')';
  595:                     }
  596:                     my @privs = split(/:/,$customroles{$key}{$level});
  597:                     foreach my $item (@privs) {
  598:                         next if ($item eq '');
  599:                         my ($priv,$cond) = split(/\&/,$item);
  600:                         $output .= &Apache::lonnet::plaintext($priv,'Course').$suffix.'<br />';
  601:                     }
  602:                 }
  603:             }
  604:             $output .= '</td>'.
  605:                        &Apache::loncommon::end_data_table_row();
  606:         }
  607:         $output .= &Apache::loncommon::end_data_table();
  608:     }
  609:     return $output;
  610: }
  611: 
  612: sub courserequest_titles {
  613:     my %titles = &Apache::lonlocal::texthash (
  614:                                    official   => 'Official',
  615:                                    unofficial => 'Unofficial',
  616:                                    community  => 'Communities',
  617:                                    textbook   => 'Textbook',
  618:                                    norequest  => 'Not allowed',
  619:                                    approval   => 'Approval by Dom. Coord.',
  620:                                    validate   => 'With validation',
  621:                                    autolimit  => 'Numerical limit',
  622:                                    unlimited  => '(blank for unlimited)',
  623:                  );
  624:     return %titles;
  625: }
  626: 
  627: sub courserequest_display {
  628:     my %titles = &Apache::lonlocal::texthash (
  629:                                    approval   => 'Yes, need approval',
  630:                                    validate   => 'Yes, with validation',
  631:                                    norequest  => 'No',
  632:    );
  633:    return %titles;
  634: }
  635: 
  636: sub requestauthor_titles {
  637:     my %titles = &Apache::lonlocal::texthash (
  638:                                    norequest  => 'Not allowed',
  639:                                    approval   => 'Approval by Dom. Coord.',
  640:                                    automatic  => 'Automatic approval',
  641:                  );
  642:     return %titles;
  643: 
  644: }
  645: 
  646: sub requestauthor_display {
  647:     my %titles = &Apache::lonlocal::texthash (
  648:                                    approval   => 'Yes, need approval',
  649:                                    automatic  => 'Yes, automatic approval',
  650:                                    norequest  => 'No',
  651:    );
  652:    return %titles;
  653: }
  654: 
  655: sub requestchange_display {
  656:     my %titles = &Apache::lonlocal::texthash (
  657:                                    approval   => "availability set to 'on' (approval required)", 
  658:                                    automatic  => "availability set to 'on' (automatic approval)",
  659:                                    norequest  => "availability set to 'off'",
  660:    );
  661:    return %titles;
  662: }
  663: 
  664: sub curr_requestauthor {
  665:     my ($uname,$udom,$isadv,$inststatuses,$domconfig) = @_;
  666:     return unless ((ref($inststatuses) eq 'ARRAY') && (ref($domconfig) eq 'HASH'));
  667:     if ($uname eq '' || $udom eq '') {
  668:         $uname = $env{'user.name'};
  669:         $udom = $env{'user.domain'};
  670:         $isadv = $env{'user.adv'};
  671:     }
  672:     my (%userenv,%settings,$val);
  673:     my @options = ('automatic','approval');
  674:     %userenv =
  675:         &Apache::lonnet::userenvironment($udom,$uname,'requestauthor','inststatus');
  676:     if ($userenv{'requestauthor'}) {
  677:         $val = $userenv{'requestauthor'};
  678:         @{$inststatuses} = ('_custom_');
  679:     } else {
  680:         my %alltasks;
  681:         if (ref($domconfig->{'requestauthor'}) eq 'HASH') {
  682:             %settings = %{$domconfig->{'requestauthor'}};
  683:             if (($isadv) && ($settings{'_LC_adv'} ne '')) {
  684:                 $val = $settings{'_LC_adv'};
  685:                 @{$inststatuses} = ('_LC_adv_');
  686:             } else {
  687:                 if ($userenv{'inststatus'} ne '') {
  688:                     @{$inststatuses} = split(',',$userenv{'inststatus'});
  689:                 } else {
  690:                     @{$inststatuses} = ('default');
  691:                 }
  692:                 foreach my $status (@{$inststatuses}) {
  693:                     if (exists($settings{$status})) {
  694:                         my $value = $settings{$status};
  695:                         next unless ($value);
  696:                         unless (exists($alltasks{$value})) {
  697:                             if (ref($alltasks{$value}) eq 'ARRAY') {
  698:                                 unless(grep(/^\Q$status\E$/,@{$alltasks{$value}})) {
  699:                                     push(@{$alltasks{$value}},$status);
  700:                                 }
  701:                             } else {
  702:                                 @{$alltasks{$value}} = ($status);
  703:                             }
  704:                         }
  705:                     }
  706:                 }
  707:                 foreach my $option (@options) {
  708:                     if ($alltasks{$option}) {
  709:                         $val = $option;
  710:                         last;
  711:                     }
  712:                 }
  713:             }
  714:         }
  715:     }
  716:     return $val;
  717: }
  718: 
  719: # =================================================================== Phase one
  720: 
  721: sub print_username_entry_form {
  722:     my ($r,$context,$response,$srch,$forcenewuser,$crstype,$brcrum) = @_;
  723:     my $defdom=$env{'request.role.domain'};
  724:     my $formtoset = 'crtuser';
  725:     if (exists($env{'form.startrolename'})) {
  726:         $formtoset = 'docustom';
  727:         $env{'form.rolename'} = $env{'form.startrolename'};
  728:     } elsif ($env{'form.origform'} eq 'crtusername') {
  729:         $formtoset =  $env{'form.origform'};
  730:     }
  731: 
  732:     my ($jsback,$elements) = &crumb_utilities();
  733: 
  734:     my $jscript = &Apache::loncommon::studentbrowser_javascript()."\n".
  735:         '<script type="text/javascript">'."\n".
  736:         '// <![CDATA['."\n".
  737:         &Apache::lonhtmlcommon::set_form_elements($elements->{$formtoset})."\n".
  738:         '// ]]>'."\n".
  739:         '</script>'."\n";
  740: 
  741:     my %existingroles=&Apache::lonuserutils::my_custom_roles($crstype);
  742:     if (($env{'form.action'} eq 'custom') && (keys(%existingroles) > 0)
  743:         && (&Apache::lonnet::allowed('mcr','/'))) {
  744:         $jscript .= &customrole_javascript();
  745:     }
  746:     my $helpitem = 'Course_Change_Privileges';
  747:     if ($env{'form.action'} eq 'custom') {
  748:         $helpitem = 'Course_Editing_Custom_Roles';
  749:     } elsif ($env{'form.action'} eq 'singlestudent') {
  750:         $helpitem = 'Course_Add_Student';
  751:     } elsif ($env{'form.action'} eq 'accesslogs') {
  752:         $helpitem = 'Domain_User_Access_Logs';
  753:     }
  754:     my %breadcrumb_text = &singleuser_breadcrumb($crstype);
  755:     if ($env{'form.action'} eq 'custom') {
  756:         push(@{$brcrum},
  757:                  {href=>"javascript:backPage(document.crtuser)",       
  758:                   text=>"Pick custom role",
  759:                   help => $helpitem,}
  760:                  );
  761:     } else {
  762:         push (@{$brcrum},
  763:                   {href => "javascript:backPage(document.crtuser)",
  764:                    text => $breadcrumb_text{'search'},
  765:                    help => $helpitem,
  766:                    faq  => 282,
  767:                    bug  => 'Instructor Interface',}
  768:                   );
  769:     }
  770:     my %loaditems = (
  771:                 'onload' => "javascript:setFormElements(document.$formtoset)",
  772:                     );
  773:     my $args = {bread_crumbs           => $brcrum,
  774:                 bread_crumbs_component => 'User Management',
  775:                 add_entries            => \%loaditems,};
  776:     $r->print(&Apache::loncommon::start_page('User Management',$jscript,$args));
  777: 
  778:     my %lt=&Apache::lonlocal::texthash(
  779:                     'srst' => 'Search for a user and enroll as a student',
  780:                     'srme' => 'Search for a user and enroll as a member',
  781:                     'srad' => 'Search for a user and modify/add user information or roles',
  782:                     'srva' => 'Search for a user and view access log information',
  783: 		    'usr'  => "Username",
  784:                     'dom'  => "Domain",
  785:                     'ecrp' => "Define or Edit Custom Role",
  786:                     'nr'   => "role name",
  787:                     'cre'  => "Next",
  788: 				       );
  789: 
  790:     if ($env{'form.action'} eq 'custom') {
  791:         if (&Apache::lonnet::allowed('mcr','/')) {
  792:             my $newroletext = &mt('Define new custom role:');
  793:             $r->print('<form action="/adm/createuser" method="post" name="docustom">'.
  794:                       '<input type="hidden" name="action" value="'.$env{'form.action'}.'" />'.
  795:                       '<input type="hidden" name="phase" value="selected_custom_edit" />'.
  796:                       '<h3>'.$lt{'ecrp'}.'</h3>'.
  797:                       &Apache::loncommon::start_data_table().
  798:                       &Apache::loncommon::start_data_table_row().
  799:                       '<td>');
  800:             if (keys(%existingroles) > 0) {
  801:                 $r->print('<br /><label><input type="radio" name="customroleaction" value="new" checked="checked" onclick="setCustomFields();" /><b>'.$newroletext.'</b></label>');
  802:             } else {
  803:                 $r->print('<br /><input type="hidden" name="customroleaction" value="new" /><b>'.$newroletext.'</b>');
  804:             }
  805:             $r->print('</td><td align="center">'.$lt{'nr'}.'<br /><input type="text" size="15" name="newrolename" onfocus="setCustomAction('."'new'".');" /></td>'.
  806:                       &Apache::loncommon::end_data_table_row());
  807:             if (keys(%existingroles) > 0) {
  808:                 $r->print(&Apache::loncommon::start_data_table_row().'<td><br />'.
  809:                           '<label><input type="radio" name="customroleaction" value="edit" onclick="setCustomFields();"/><b>'.
  810:                           &mt('View/Modify existing role:').'</b></label></td>'.
  811:                           '<td align="center"><br />'.
  812:                           '<select name="rolename" onchange="setCustomAction('."'edit'".');">'.
  813:                           '<option value="" selected="selected">'.
  814:                           &mt('Select'));
  815:                 foreach my $role (sort(keys(%existingroles))) {
  816:                     $r->print('<option value="'.$role.'">'.$role.'</option>');
  817:                 }
  818:                 $r->print('</select>'.
  819:                           '</td>'.
  820:                           &Apache::loncommon::end_data_table_row());
  821:             }
  822:             $r->print(&Apache::loncommon::end_data_table().'<p>'.
  823:                       '<input name="customeditor" type="submit" value="'.
  824:                       $lt{'cre'}.'" /></p>'.
  825:                       '</form>');
  826:         }
  827:     } else {
  828:         my $actiontext = $lt{'srad'};
  829:         if ($env{'form.action'} eq 'singlestudent') {
  830:             if ($crstype eq 'Community') {
  831:                 $actiontext = $lt{'srme'};
  832:             } else {
  833:                 $actiontext = $lt{'srst'};
  834:             }
  835:         } elsif ($env{'form.action'} eq 'accesslogs') {
  836:             $actiontext = $lt{'srva'};
  837:         }
  838:         $r->print("<h3>$actiontext</h3>");
  839:         if ($env{'form.origform'} ne 'crtusername') {
  840:             if ($response) {
  841:                $r->print("\n<div>$response</div>".
  842:                          '<br clear="all" />');
  843:             }
  844:         }
  845:         $r->print(&entry_form($defdom,$srch,$forcenewuser,$context,$response,$crstype,1));
  846:     }
  847: }
  848: 
  849: sub customrole_javascript {
  850:     my $js = <<"END";
  851: <script type="text/javascript">
  852: // <![CDATA[
  853: 
  854: function setCustomFields() {
  855:     if (document.docustom.customroleaction.length > 0) {
  856:         for (var i=0; i<document.docustom.customroleaction.length; i++) {
  857:             if (document.docustom.customroleaction[i].checked) {
  858:                 if (document.docustom.customroleaction[i].value == 'new') {
  859:                     document.docustom.rolename.selectedIndex = 0;
  860:                 } else {
  861:                     document.docustom.newrolename.value = '';
  862:                 }
  863:             }
  864:         }
  865:     }
  866:     return;
  867: }
  868: 
  869: function setCustomAction(caller) {
  870:     if (document.docustom.customroleaction.length > 0) {
  871:         for (var i=0; i<document.docustom.customroleaction.length; i++) {
  872:             if (document.docustom.customroleaction[i].value == caller) {
  873:                 document.docustom.customroleaction[i].checked = true;
  874:             }
  875:         }
  876:     }
  877:     setCustomFields();
  878:     return;
  879: }
  880: 
  881: // ]]>
  882: </script>
  883: END
  884:     return $js;
  885: }
  886: 
  887: sub entry_form {
  888:     my ($dom,$srch,$forcenewuser,$context,$responsemsg,$crstype,$fixeddom) = @_;
  889:     my ($usertype,$inexact);
  890:     if (ref($srch) eq 'HASH') {
  891:         if (($srch->{'srchin'} eq 'dom') &&
  892:             ($srch->{'srchby'} eq 'uname') &&
  893:             ($srch->{'srchtype'} eq 'exact') &&
  894:             ($srch->{'srchdomain'} ne '') &&
  895:             ($srch->{'srchterm'} ne '')) {
  896:             my (%curr_rules,%got_rules);
  897:             my ($rules,$ruleorder) =
  898:                 &Apache::lonnet::inst_userrules($srch->{'srchdomain'},'username');
  899:             $usertype = &Apache::lonuserutils::check_usertype($srch->{'srchdomain'},$srch->{'srchterm'},$rules,\%curr_rules,\%got_rules);
  900:         } else {
  901:             $inexact = 1;
  902:         }
  903:     }
  904:     my $cancreate =
  905:         &Apache::lonuserutils::can_create_user($dom,$context,$usertype);
  906:     my ($userpicker,$cansearch) = 
  907:        &Apache::loncommon::user_picker($dom,$srch,$forcenewuser,
  908:                                        'document.crtuser',$cancreate,$usertype,$context,$fixeddom);
  909:     my $srchbutton = &mt('Search');
  910:     if ($env{'form.action'} eq 'singlestudent') {
  911:         $srchbutton = &mt('Search and Enroll');
  912:     } elsif ($env{'form.action'} eq 'accesslogs') {
  913:         $srchbutton = &mt('Search');
  914:     } elsif ($cancreate && $responsemsg ne '' && $inexact) {
  915:         $srchbutton = &mt('Search or Add New User');
  916:     }
  917:     my $output;
  918:     if ($cansearch) {
  919:         $output = <<"ENDBLOCK";
  920: <form action="/adm/createuser" method="post" name="crtuser">
  921: <input type="hidden" name="action" value="$env{'form.action'}" />
  922: <input type="hidden" name="phase" value="get_user_info" />
  923: $userpicker
  924: <input name="userrole" type="button" value="$srchbutton" onclick="javascript:validateEntry(document.crtuser)" />
  925: </form>
  926: ENDBLOCK
  927:     } else {
  928:         $output = '<p>'.$userpicker.'</p>';
  929:     }
  930:     if (($env{'form.phase'} eq '') && ($env{'form.action'} ne 'accesslogs')) {
  931:         my $defdom=$env{'request.role.domain'};
  932:         my $domform = &Apache::loncommon::select_dom_form($defdom,'srchdomain');
  933:         my %lt=&Apache::lonlocal::texthash(
  934:                   'enro' => 'Enroll one student',
  935:                   'enrm' => 'Enroll one member',
  936:                   'admo' => 'Add/modify a single user',
  937:                   'crea' => 'create new user if required',
  938:                   'uskn' => "username is known",
  939:                   'crnu' => 'Create a new user',
  940:                   'usr'  => 'Username',
  941:                   'dom'  => 'in domain',
  942:                   'enrl' => 'Enroll',
  943:                   'cram'  => 'Create/Modify user',
  944:         );
  945:         my $sellink=&Apache::loncommon::selectstudent_link('crtusername','srchterm','srchdomain');
  946:         my ($title,$buttontext,$showresponse);
  947:         if ($env{'form.action'} eq 'singlestudent') {
  948:             if ($crstype eq 'Community') {
  949:                 $title = $lt{'enrm'};
  950:             } else {
  951:                 $title = $lt{'enro'};
  952:             }
  953:             $buttontext = $lt{'enrl'};
  954:         } else {
  955:             $title = $lt{'admo'};
  956:             $buttontext = $lt{'cram'};
  957:         }
  958:         if ($cancreate) {
  959:             $title .= ' <span class="LC_cusr_subheading">('.$lt{'crea'}.')</span>';
  960:         } else {
  961:             $title .= ' <span class="LC_cusr_subheading">('.$lt{'uskn'}.')</span>';
  962:         }
  963:         if ($env{'form.origform'} eq 'crtusername') {
  964:             $showresponse = $responsemsg;
  965:         }
  966:         $output .= <<"ENDDOCUMENT";
  967: <br />
  968: <form action="/adm/createuser" method="post" name="crtusername">
  969: <input type="hidden" name="action" value="$env{'form.action'}" />
  970: <input type="hidden" name="phase" value="createnewuser" />
  971: <input type="hidden" name="srchtype" value="exact" />
  972: <input type="hidden" name="srchby" value="uname" />
  973: <input type="hidden" name="srchin" value="dom" />
  974: <input type="hidden" name="forcenewuser" value="1" />
  975: <input type="hidden" name="origform" value="crtusername" />
  976: <h3>$title</h3>
  977: $showresponse
  978: <table>
  979:  <tr>
  980:   <td>$lt{'usr'}:</td>
  981:   <td><input type="text" size="15" name="srchterm" /></td>
  982:   <td>&nbsp;$lt{'dom'}:</td><td>$domform</td>
  983:   <td>&nbsp;$sellink&nbsp;</td>
  984:   <td>&nbsp;<input name="userrole" type="submit" value="$buttontext" /></td>
  985:  </tr>
  986: </table>
  987: </form>
  988: ENDDOCUMENT
  989:     }
  990:     return $output;
  991: }
  992: 
  993: sub user_modification_js {
  994:     my ($pjump_def,$dc_setcourse_code,$nondc_setsection_code,$groupslist)=@_;
  995:     
  996:     return <<END;
  997: <script type="text/javascript" language="Javascript">
  998: // <![CDATA[
  999: 
 1000:     $pjump_def
 1001:     $dc_setcourse_code
 1002: 
 1003:     function dateset() {
 1004:         eval("document.cu."+document.cu.pres_marker.value+
 1005:             ".value=document.cu.pres_value.value");
 1006:         modalWindow.close();
 1007:     }
 1008: 
 1009:     $nondc_setsection_code
 1010: // ]]>
 1011: </script>
 1012: END
 1013: }
 1014: 
 1015: # =================================================================== Phase two
 1016: sub print_user_selection_page {
 1017:     my ($r,$response,$srch,$srch_results,$srcharray,$context,$opener_elements,$crstype,$brcrum) = @_;
 1018:     my @fields = ('username','domain','lastname','firstname','permanentemail');
 1019:     my $sortby = $env{'form.sortby'};
 1020: 
 1021:     if (!grep(/^\Q$sortby\E$/,@fields)) {
 1022:         $sortby = 'lastname';
 1023:     }
 1024: 
 1025:     my ($jsback,$elements) = &crumb_utilities();
 1026: 
 1027:     my $jscript = (<<ENDSCRIPT);
 1028: <script type="text/javascript">
 1029: // <![CDATA[
 1030: function pickuser(uname,udom) {
 1031:     document.usersrchform.seluname.value=uname;
 1032:     document.usersrchform.seludom.value=udom;
 1033:     document.usersrchform.phase.value="userpicked";
 1034:     document.usersrchform.submit();
 1035: }
 1036: 
 1037: $jsback
 1038: // ]]>
 1039: </script>
 1040: ENDSCRIPT
 1041: 
 1042:     my %lt=&Apache::lonlocal::texthash(
 1043:                                        'usrch'          => "User Search to add/modify roles",
 1044:                                        'stusrch'        => "User Search to enroll student",
 1045:                                        'memsrch'        => "User Search to enroll member",
 1046:                                        'srcva'          => "Search for a user and view access log information",
 1047:                                        'usel'           => "Select a user to add/modify roles",
 1048:                                        'stusel'         => "Select a user to enroll as a student",
 1049:                                        'memsel'         => "Select a user to enroll as a member",
 1050:                                        'vacsel'         => "Select a user to view access log",
 1051:                                        'username'       => "username",
 1052:                                        'domain'         => "domain",
 1053:                                        'lastname'       => "last name",
 1054:                                        'firstname'      => "first name",
 1055:                                        'permanentemail' => "permanent e-mail",
 1056:                                       );
 1057:     if ($context eq 'requestcrs') {
 1058:         $r->print('<div>');
 1059:     } else {
 1060:         my %breadcrumb_text = &singleuser_breadcrumb($crstype);
 1061:         my $helpitem;
 1062:         if ($env{'form.action'} eq 'singleuser') {
 1063:             $helpitem = 'Course_Change_Privileges';
 1064:         } elsif ($env{'form.action'} eq 'singlestudent') {
 1065:             $helpitem = 'Course_Add_Student';
 1066:         }
 1067:         push (@{$brcrum},
 1068:                   {href => "javascript:backPage(document.usersrchform,'','')",
 1069:                    text => $breadcrumb_text{'search'},
 1070:                    faq  => 282,
 1071:                    bug  => 'Instructor Interface',},
 1072:                   {href => "javascript:backPage(document.usersrchform,'get_user_info','select')",
 1073:                    text => $breadcrumb_text{'userpicked'},
 1074:                    faq  => 282,
 1075:                    bug  => 'Instructor Interface',
 1076:                    help => $helpitem}
 1077:                   );
 1078:         $r->print(&Apache::loncommon::start_page('User Management',$jscript,{bread_crumbs => $brcrum}));
 1079:         if ($env{'form.action'} eq 'singleuser') {
 1080:             $r->print("<b>$lt{'usrch'}</b><br />");
 1081:             $r->print(&entry_form($srch->{'srchdomain'},$srch,undef,$context,undef,$crstype));
 1082:             $r->print('<h3>'.$lt{'usel'}.'</h3>');
 1083:         } elsif ($env{'form.action'} eq 'singlestudent') {
 1084:             $r->print($jscript."<b>");
 1085:             if ($crstype eq 'Community') {
 1086:                 $r->print($lt{'memsrch'});
 1087:             } else {
 1088:                 $r->print($lt{'stusrch'});
 1089:             }
 1090:             $r->print("</b><br />");
 1091:             $r->print(&entry_form($srch->{'srchdomain'},$srch,undef,$context,undef,$crstype));
 1092:             $r->print('</form><h3>');
 1093:             if ($crstype eq 'Community') {
 1094:                 $r->print($lt{'memsel'});
 1095:             } else {
 1096:                 $r->print($lt{'stusel'});
 1097:             }
 1098:             $r->print('</h3>');
 1099:         } elsif ($env{'form.action'} eq 'accesslogs') {
 1100:             $r->print("<b>$lt{'srcva'}</b><br />");
 1101:             $r->print(&entry_form($srch->{'srchdomain'},$srch,undef,'accesslogs',undef,undef,1));
 1102:             $r->print('<h3>'.$lt{'vacsel'}.'</h3>');
 1103:         }
 1104:     }
 1105:     $r->print('<form name="usersrchform" method="post" action="">'.
 1106:               &Apache::loncommon::start_data_table()."\n".
 1107:               &Apache::loncommon::start_data_table_header_row()."\n".
 1108:               ' <th> </th>'."\n");
 1109:     foreach my $field (@fields) {
 1110:         $r->print(' <th><a href="javascript:document.usersrchform.sortby.value='.
 1111:                   "'".$field."'".';document.usersrchform.submit();">'.
 1112:                   $lt{$field}.'</a></th>'."\n");
 1113:     }
 1114:     $r->print(&Apache::loncommon::end_data_table_header_row());
 1115: 
 1116:     my @sorted_users = sort {
 1117:         lc($srch_results->{$a}->{$sortby})   cmp lc($srch_results->{$b}->{$sortby})
 1118:             ||
 1119:         lc($srch_results->{$a}->{lastname})  cmp lc($srch_results->{$b}->{lastname})
 1120:             ||
 1121:         lc($srch_results->{$a}->{firstname}) cmp lc($srch_results->{$b}->{firstname})
 1122: 	    ||
 1123: 	lc($a) cmp lc($b)
 1124:         } (keys(%$srch_results));
 1125: 
 1126:     foreach my $user (@sorted_users) {
 1127:         my ($uname,$udom) = split(/:/,$user);
 1128:         my $onclick;
 1129:         if ($context eq 'requestcrs') {
 1130:             $onclick =
 1131:                 'onclick="javascript:gochoose('."'$uname','$udom',".
 1132:                                                "'$srch_results->{$user}->{firstname}',".
 1133:                                                "'$srch_results->{$user}->{lastname}',".
 1134:                                                "'$srch_results->{$user}->{permanentemail}'".');"';
 1135:         } else {
 1136:             $onclick =
 1137:                 ' onclick="javascript:pickuser('."'".$uname."'".','."'".$udom."'".');"';
 1138:         }
 1139:         $r->print(&Apache::loncommon::start_data_table_row().
 1140:                   '<td><input type="button" name="seluser" value="'.&mt('Select').'" '.
 1141:                   $onclick.' /></td>'.
 1142:                   '<td><tt>'.$uname.'</tt></td>'.
 1143:                   '<td><tt>'.$udom.'</tt></td>');
 1144:         foreach my $field ('lastname','firstname','permanentemail') {
 1145:             $r->print('<td>'.$srch_results->{$user}->{$field}.'</td>');
 1146:         }
 1147:         $r->print(&Apache::loncommon::end_data_table_row());
 1148:     }
 1149:     $r->print(&Apache::loncommon::end_data_table().'<br /><br />');
 1150:     if (ref($srcharray) eq 'ARRAY') {
 1151:         foreach my $item (@{$srcharray}) {
 1152:             $r->print('<input type="hidden" name="'.$item.'" value="'.$env{'form.'.$item}.'" />'."\n");
 1153:         }
 1154:     }
 1155:     $r->print(' <input type="hidden" name="sortby" value="'.$sortby.'" />'."\n".
 1156:               ' <input type="hidden" name="seluname" value="" />'."\n".
 1157:               ' <input type="hidden" name="seludom" value="" />'."\n".
 1158:               ' <input type="hidden" name="currstate" value="select" />'."\n".
 1159:               ' <input type="hidden" name="phase" value="get_user_info" />'."\n".
 1160:               ' <input type="hidden" name="action" value="'.$env{'form.action'}.'" />'."\n");
 1161:     if ($context eq 'requestcrs') {
 1162:         $r->print($opener_elements.'</form></div>');
 1163:     } else {
 1164:         $r->print($response.'</form>');
 1165:     }
 1166: }
 1167: 
 1168: sub print_user_query_page {
 1169:     my ($r,$caller,$brcrum) = @_;
 1170: # FIXME - this is for a network-wide name search (similar to catalog search)
 1171: # To use frames with similar behavior to catalog/portfolio search.
 1172: # To be implemented. 
 1173:     return;
 1174: }
 1175: 
 1176: sub print_user_modification_page {
 1177:     my ($r,$ccuname,$ccdomain,$srch,$response,$context,$permission,$crstype,
 1178:         $brcrum,$showcredits) = @_;
 1179:     if (($ccuname eq '') || ($ccdomain eq '')) {
 1180:         my $usermsg = &mt('No username and/or domain provided.');
 1181:         $env{'form.phase'} = '';
 1182: 	&print_username_entry_form($r,$context,$usermsg,'','',$crstype,$brcrum);
 1183:         return;
 1184:     }
 1185:     my ($form,$formname);
 1186:     if ($env{'form.action'} eq 'singlestudent') {
 1187:         $form = 'document.enrollstudent';
 1188:         $formname = 'enrollstudent';
 1189:     } else {
 1190:         $form = 'document.cu';
 1191:         $formname = 'cu';
 1192:     }
 1193:     my %abv_auth = &auth_abbrev();
 1194:     my (%rulematch,%inst_results,$newuser,%alerts,%curr_rules,%got_rules);
 1195:     my $uhome=&Apache::lonnet::homeserver($ccuname,$ccdomain);
 1196:     if ($uhome eq 'no_host') {
 1197:         my $usertype;
 1198:         my ($rules,$ruleorder) =
 1199:             &Apache::lonnet::inst_userrules($ccdomain,'username');
 1200:             $usertype =
 1201:                 &Apache::lonuserutils::check_usertype($ccdomain,$ccuname,$rules,
 1202:                                                       \%curr_rules,\%got_rules);
 1203:         my $cancreate =
 1204:             &Apache::lonuserutils::can_create_user($ccdomain,$context,
 1205:                                                    $usertype);
 1206:         if (!$cancreate) {
 1207:             my $helplink = 'javascript:helpMenu('."'display'".')';
 1208:             my %usertypetext = (
 1209:                 official   => 'institutional',
 1210:                 unofficial => 'non-institutional',
 1211:             );
 1212:             my $response;
 1213:             if ($env{'form.origform'} eq 'crtusername') {
 1214:                 $response = '<span class="LC_warning">'.
 1215:                             &mt('No match found for the username [_1] in LON-CAPA domain: [_2]',
 1216:                                 '<b>'.$ccuname.'</b>',$ccdomain).
 1217:                             '</span><br />';
 1218:             }
 1219:             $response .= '<p class="LC_warning">'
 1220:                         .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
 1221:                         .' ';
 1222:             if ($context eq 'domain') {
 1223:                 $response .= &mt('Please contact a [_1] for assistance.',
 1224:                                  &Apache::lonnet::plaintext('dc'));
 1225:             } else {
 1226:                 $response .= &mt('Please contact the [_1]helpdesk[_2] for assistance.'
 1227:                                 ,'<a href="'.$helplink.'">','</a>');
 1228:             }
 1229:             $response .= '</p><br />';
 1230:             $env{'form.phase'} = '';
 1231:             &print_username_entry_form($r,$context,$response,undef,undef,$crstype,$brcrum);
 1232:             return;
 1233:         }
 1234:         $newuser = 1;
 1235:         my $checkhash;
 1236:         my $checks = { 'username' => 1 };
 1237:         $checkhash->{$ccuname.':'.$ccdomain} = { 'newuser' => $newuser };
 1238:         &Apache::loncommon::user_rule_check($checkhash,$checks,
 1239:             \%alerts,\%rulematch,\%inst_results,\%curr_rules,\%got_rules);
 1240:         if (ref($alerts{'username'}) eq 'HASH') {
 1241:             if (ref($alerts{'username'}{$ccdomain}) eq 'HASH') {
 1242:                 my $domdesc =
 1243:                     &Apache::lonnet::domain($ccdomain,'description');
 1244:                 if ($alerts{'username'}{$ccdomain}{$ccuname}) {
 1245:                     my $userchkmsg;
 1246:                     if (ref($curr_rules{$ccdomain}) eq 'HASH') {  
 1247:                         $userchkmsg = 
 1248:                             &Apache::loncommon::instrule_disallow_msg('username',
 1249:                                                                  $domdesc,1).
 1250:                         &Apache::loncommon::user_rule_formats($ccdomain,
 1251:                             $domdesc,$curr_rules{$ccdomain}{'username'},
 1252:                             'username');
 1253:                     }
 1254:                     $env{'form.phase'} = '';
 1255:                     &print_username_entry_form($r,$context,$userchkmsg,undef,undef,$crstype,$brcrum);
 1256:                     return;
 1257:                 }
 1258:             }
 1259:         }
 1260:     } else {
 1261:         $newuser = 0;
 1262:     }
 1263:     if ($response) {
 1264:         $response = '<br />'.$response;
 1265:     }
 1266: 
 1267:     my $pjump_def = &Apache::lonhtmlcommon::pjump_javascript_definition();
 1268:     my $dc_setcourse_code = '';
 1269:     my $nondc_setsection_code = '';                                        
 1270:     my %loaditem;
 1271: 
 1272:     my $groupslist = &Apache::lonuserutils::get_groupslist();
 1273: 
 1274:     my $js = &validation_javascript($context,$ccdomain,$pjump_def,$crstype,
 1275:                                $groupslist,$newuser,$formname,\%loaditem);
 1276:     my %breadcrumb_text = &singleuser_breadcrumb($crstype);
 1277:     my $helpitem = 'Course_Change_Privileges';
 1278:     if ($env{'form.action'} eq 'singlestudent') {
 1279:         $helpitem = 'Course_Add_Student';
 1280:     }
 1281:     push (@{$brcrum},
 1282:         {href => "javascript:backPage($form)",
 1283:          text => $breadcrumb_text{'search'},
 1284:          faq  => 282,
 1285:          bug  => 'Instructor Interface',});
 1286:     if ($env{'form.phase'} eq 'userpicked') {
 1287:        push(@{$brcrum},
 1288:               {href => "javascript:backPage($form,'get_user_info','select')",
 1289:                text => $breadcrumb_text{'userpicked'},
 1290:                faq  => 282,
 1291:                bug  => 'Instructor Interface',});
 1292:     }
 1293:     push(@{$brcrum},
 1294:             {href => "javascript:backPage($form,'$env{'form.phase'}','modify')",
 1295:              text => $breadcrumb_text{'modify'},
 1296:              faq  => 282,
 1297:              bug  => 'Instructor Interface',
 1298:              help => $helpitem});
 1299:     my $args = {'add_entries'           => \%loaditem,
 1300:                 'bread_crumbs'          => $brcrum,
 1301:                 'bread_crumbs_component' => 'User Management'};
 1302:     if ($env{'form.popup'}) {
 1303:         $args->{'no_nav_bar'} = 1;
 1304:     }
 1305:     my $start_page =
 1306:         &Apache::loncommon::start_page('User Management',$js,$args);
 1307: 
 1308:     my $forminfo =<<"ENDFORMINFO";
 1309: <form action="/adm/createuser" method="post" name="$formname">
 1310: <input type="hidden" name="phase" value="update_user_data" />
 1311: <input type="hidden" name="ccuname" value="$ccuname" />
 1312: <input type="hidden" name="ccdomain" value="$ccdomain" />
 1313: <input type="hidden" name="pres_value"  value="" />
 1314: <input type="hidden" name="pres_type"   value="" />
 1315: <input type="hidden" name="pres_marker" value="" />
 1316: ENDFORMINFO
 1317:     my (%inccourses,$roledom,$defaultcredits);
 1318:     if ($context eq 'course') {
 1319:         $inccourses{$env{'request.course.id'}}=1;
 1320:         $roledom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 1321:         if ($showcredits) {
 1322:             $defaultcredits = &Apache::lonuserutils::get_defaultcredits();
 1323:         }
 1324:     } elsif ($context eq 'author') {
 1325:         $roledom = $env{'request.role.domain'};
 1326:     } elsif ($context eq 'domain') {
 1327:         foreach my $key (keys(%env)) {
 1328:             $roledom = $env{'request.role.domain'};
 1329:             if ($key=~/^user\.priv\.cm\.\/($roledom)\/($match_username)/) {
 1330:                 $inccourses{$1.'_'.$2}=1;
 1331:             }
 1332:         }
 1333:     } else {
 1334:         foreach my $key (keys(%env)) {
 1335: 	    if ($key=~/^user\.priv\.cm\.\/($match_domain)\/($match_username)/) {
 1336: 	        $inccourses{$1.'_'.$2}=1;
 1337:             }
 1338:         }
 1339:     }
 1340:     my $title = '';
 1341:     if ($newuser) {
 1342:         my ($portfolioform,$domroleform,$adhocroleform);
 1343:         if ((&Apache::lonnet::allowed('mpq',$env{'request.role.domain'})) ||
 1344:             (&Apache::lonnet::allowed('mut',$env{'request.role.domain'}))) {
 1345:             # Current user has quota or user tools modification privileges
 1346:             $portfolioform = '<br />'.&user_quotas($ccuname,$ccdomain);
 1347:         }
 1348:         if ((&Apache::lonnet::allowed('cau',$env{'request.role.domain'})) &&
 1349:             ($ccdomain eq $env{'request.role.domain'})) {
 1350:             $domroleform = '<br />'.&domainrole_req($ccuname,$ccdomain);
 1351:         }
 1352:         if (&Apache::lonnet::allowed('cdh',$env{'request.role.domain'})) {
 1353:             $adhocroleform = &domadhocroles($ccuname,$ccdomain);
 1354:             if ($adhocroleform) {
 1355:                 $adhocroleform = '<br />'.$adhocroleform;
 1356:             }
 1357:         }
 1358:         &initialize_authen_forms($ccdomain,$formname);
 1359:         my %lt=&Apache::lonlocal::texthash(
 1360:                 'lg'             => 'Login Data',
 1361:                 'hs'             => "Home Server",
 1362:         );
 1363: 	$r->print(<<ENDTITLE);
 1364: $start_page
 1365: $response
 1366: $forminfo
 1367: <script type="text/javascript" language="Javascript">
 1368: // <![CDATA[
 1369: $loginscript
 1370: // ]]>
 1371: </script>
 1372: <input type='hidden' name='makeuser' value='1' />
 1373: ENDTITLE
 1374:         if ($env{'form.action'} eq 'singlestudent') {
 1375:             if ($crstype eq 'Community') {
 1376:                 $title = &mt('Create New User [_1] in domain [_2] as a member',
 1377:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1378:             } else {
 1379:                 $title = &mt('Create New User [_1] in domain [_2] as a student',
 1380:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1381:             }
 1382:         } else {
 1383:                 $title = &mt('Create New User [_1] in domain [_2]',
 1384:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1385:         }
 1386:         $r->print('<h2>'.$title.'</h2>'."\n");
 1387:         $r->print('<div class="LC_left_float">');
 1388:         $r->print(&personal_data_display($ccuname,$ccdomain,$newuser,$context,
 1389:                                          $inst_results{$ccuname.':'.$ccdomain}));
 1390:         # Option to disable student/employee ID conflict checking not offerred for new users.
 1391:         my ($home_server_pick,$numlib) = 
 1392:             &Apache::loncommon::home_server_form_item($ccdomain,'hserver',
 1393:                                                       'default','hide');
 1394:         if ($numlib > 1) {
 1395:             $r->print("
 1396: <br />
 1397: $lt{'hs'}: $home_server_pick
 1398: <br />");
 1399:         } else {
 1400:             $r->print($home_server_pick);
 1401:         }
 1402:         if (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) {
 1403:             $r->print('<br /><h3>'.
 1404:                       &mt('User Can Request Creation of Courses/Communities in this Domain?').'</h3>'.
 1405:                       &Apache::loncommon::start_data_table().
 1406:                       &build_tools_display($ccuname,$ccdomain,
 1407:                                            'requestcourses').
 1408:                       &Apache::loncommon::end_data_table());
 1409:         }
 1410:         $r->print('</div>'."\n".'<div class="LC_left_float"><h3>'.
 1411:                   $lt{'lg'}.'</h3>');
 1412:         my ($fixedauth,$varauth,$authmsg); 
 1413:         if (ref($rulematch{$ccuname.':'.$ccdomain}) eq 'HASH') {
 1414:             my $matchedrule = $rulematch{$ccuname.':'.$ccdomain}{'username'};
 1415:             my ($rules,$ruleorder) = 
 1416:                 &Apache::lonnet::inst_userrules($ccdomain,'username');
 1417:             if (ref($rules) eq 'HASH') {
 1418:                 if (ref($rules->{$matchedrule}) eq 'HASH') {
 1419:                     my $authtype = $rules->{$matchedrule}{'authtype'};
 1420:                     if ($authtype !~ /^(krb4|krb5|int|fsys|loc)$/) {
 1421:                         $r->print(&Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc));
 1422:                     } else { 
 1423:                         my $authparm = $rules->{$matchedrule}{'authparm'};
 1424:                         $authmsg = $rules->{$matchedrule}{'authmsg'};
 1425:                         if ($authtype =~ /^krb(4|5)$/) {
 1426:                             my $ver = $1;
 1427:                             if ($authparm ne '') {
 1428:                                 $fixedauth = <<"KERB"; 
 1429: <input type="hidden" name="login" value="krb" />
 1430: <input type="hidden" name="krbver" value="$ver" />
 1431: <input type="hidden" name="krbarg" value="$authparm" />
 1432: KERB
 1433:                             }
 1434:                         } else {
 1435:                             $fixedauth = 
 1436: '<input type="hidden" name="login" value="'.$authtype.'" />'."\n";
 1437:                             if ($rules->{$matchedrule}{'authparmfixed'}) {
 1438:                                 $fixedauth .=    
 1439: '<input type="hidden" name="'.$authtype.'arg" value="'.$authparm.'" />'."\n";
 1440:                             } else {
 1441:                                 if ($authtype eq 'int') {
 1442:                                     $varauth = '<br />'.
 1443: &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>';
 1444:                                 } elsif ($authtype eq 'loc') {
 1445:                                     $varauth = '<br />'.
 1446: &mt('[_1] Local Authentication with argument [_2]','','<input type="text" name="'.$authtype.'arg" value="" />')."\n";
 1447:                                 } else {
 1448:                                     $varauth =
 1449: '<input type="text" name="'.$authtype.'arg" value="" />'."\n";
 1450:                                 }
 1451:                             }
 1452:                         }
 1453:                     }
 1454:                 } else {
 1455:                     $r->print(&Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc));
 1456:                 }
 1457:             }
 1458:             if ($authmsg) {
 1459:                 $r->print(<<ENDAUTH);
 1460: $fixedauth
 1461: $authmsg
 1462: $varauth
 1463: ENDAUTH
 1464:             }
 1465:         } else {
 1466:             $r->print(&Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc)); 
 1467:         }
 1468:         $r->print($portfolioform.$domroleform.$adhocroleform);
 1469:         if ($env{'form.action'} eq 'singlestudent') {
 1470:             $r->print(&date_sections_select($context,$newuser,$formname,
 1471:                                             $permission,$crstype,$ccuname,
 1472:                                             $ccdomain,$showcredits));
 1473:         }
 1474:         $r->print('</div><div class="LC_clear_float_footer"></div>');
 1475:     } else { # user already exists
 1476: 	$r->print($start_page.$forminfo);
 1477:         if ($env{'form.action'} eq 'singlestudent') {
 1478:             if ($crstype eq 'Community') {
 1479:                 $title = &mt('Enroll one member: [_1] in domain [_2]',
 1480:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1481:             } else {
 1482:                 $title = &mt('Enroll one student: [_1] in domain [_2]',
 1483:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1484:             }
 1485:         } else {
 1486:             if ($permission->{'cusr'}) {
 1487:                 $title = &mt('Modify existing user: [_1] in domain [_2]',
 1488:                              '"'.$ccuname.'"','"'.$ccdomain.'"');
 1489:             } else {
 1490:                 $title = &mt('Existing user: [_1] in domain [_2]',
 1491:                              '"'.$ccuname.'"','"'.$ccdomain.'"');
 1492:             }
 1493:         }
 1494:         $r->print('<h2>'.$title.'</h2>'."\n");
 1495:         $r->print('<div class="LC_left_float">');
 1496:         $r->print(&personal_data_display($ccuname,$ccdomain,$newuser,$context,
 1497:                                          $inst_results{$ccuname.':'.$ccdomain}));
 1498:         if ((&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) ||
 1499:             (&Apache::lonnet::allowed('udp',$env{'request.role.domain'}))) {
 1500:             $r->print('<br /><h3>'.&mt('User Can Request Creation of Courses/Communities in this Domain?').'</h3>'.
 1501:                       &Apache::loncommon::start_data_table());
 1502:             if ($env{'request.role.domain'} eq $ccdomain) {
 1503:                 $r->print(&build_tools_display($ccuname,$ccdomain,'requestcourses'));
 1504:             } else {
 1505:                 $r->print(&coursereq_externaluser($ccuname,$ccdomain,
 1506:                                                   $env{'request.role.domain'}));
 1507:             }
 1508:             $r->print(&Apache::loncommon::end_data_table());
 1509:         }
 1510:         $r->print('</div>');
 1511:         my @order = ('auth','quota','tools','requestauthor','adhocroles');
 1512:         my %user_text;
 1513:         my ($isadv,$isauthor) = 
 1514:             &Apache::lonnet::is_advanced_user($ccdomain,$ccuname);
 1515:         if ((!$isauthor) && 
 1516:             ((&Apache::lonnet::allowed('cau',$env{'request.role.domain'})) ||
 1517:              (&Apache::lonnet::allowed('udp',$env{'request.role.domain'}))) &&
 1518:              ($env{'request.role.domain'} eq $ccdomain)) {
 1519:             $user_text{'requestauthor'} = &domainrole_req($ccuname,$ccdomain);
 1520:         }
 1521:         if ((&Apache::lonnet::allowed('cdh',$env{'request.role.domain'})) ||
 1522:             (&Apache::lonnet::allowed('udp',$env{'request.role.domain'}))) {
 1523:             $user_text{'adhocroles'} = &domadhocroles($ccuname,$ccdomain);
 1524:         }
 1525:         $user_text{'auth'} =  &user_authentication($ccuname,$ccdomain,$formname);
 1526:         if ((&Apache::lonnet::allowed('mpq',$ccdomain)) ||
 1527:             (&Apache::lonnet::allowed('mut',$ccdomain)) ||
 1528:             (&Apache::lonnet::allowed('udp',$ccdomain))) {
 1529:             # Current user has quota modification privileges
 1530:             $user_text{'quota'} = &user_quotas($ccuname,$ccdomain);
 1531:         }
 1532:         if (!&Apache::lonnet::allowed('mpq',$ccdomain)) {
 1533:             if (&Apache::lonnet::allowed('mpq',$env{'request.role.domain'})) {
 1534:                 my %lt=&Apache::lonlocal::texthash(
 1535:                     'dska'  => "Disk quotas for user's portfolio and Authoring Space",
 1536:                     'youd'  => "You do not have privileges to modify the portfolio and/or Authoring Space quotas for this user.",
 1537:                     'ichr'  => "If a change is required, contact a domain coordinator for the domain",
 1538:                 );
 1539:                 $user_text{'quota'} = <<ENDNOPORTPRIV;
 1540: <h3>$lt{'dska'}</h3>
 1541: $lt{'youd'} $lt{'ichr'}: $ccdomain
 1542: ENDNOPORTPRIV
 1543:             }
 1544:         }
 1545:         if (!&Apache::lonnet::allowed('mut',$ccdomain)) {
 1546:             if (&Apache::lonnet::allowed('mut',$env{'request.role.domain'})) {
 1547:                 my %lt=&Apache::lonlocal::texthash(
 1548:                     'utav'  => "User Tools Availability",
 1549:                     'yodo'  => "You do not have privileges to modify Portfolio, Blog, WebDAV, or Personal Information Page settings for this user.",
 1550:                     'ifch'  => "If a change is required, contact a domain coordinator for the domain",
 1551:                 );
 1552:                 $user_text{'tools'} = <<ENDNOTOOLSPRIV;
 1553: <h3>$lt{'utav'}</h3>
 1554: $lt{'yodo'} $lt{'ifch'}: $ccdomain
 1555: ENDNOTOOLSPRIV
 1556:             }
 1557:         }
 1558:         my $gotdiv = 0; 
 1559:         foreach my $item (@order) {
 1560:             if ($user_text{$item} ne '') {
 1561:                 unless ($gotdiv) {
 1562:                     $r->print('<div class="LC_left_float">');
 1563:                     $gotdiv = 1;
 1564:                 }
 1565:                 $r->print('<br />'.$user_text{$item});
 1566:             }
 1567:         }
 1568:         if ($env{'form.action'} eq 'singlestudent') {
 1569:             unless ($gotdiv) {
 1570:                 $r->print('<div class="LC_left_float">');
 1571:             }
 1572:             my $credits;
 1573:             if ($showcredits) {
 1574:                 $credits = &get_user_credits($ccuname,$ccdomain,$defaultcredits);
 1575:                 if ($credits eq '') {
 1576:                     $credits = $defaultcredits;
 1577:                 }
 1578:             }
 1579:             $r->print(&date_sections_select($context,$newuser,$formname,
 1580:                                             $permission,$crstype,$ccuname,
 1581:                                             $ccdomain,$showcredits));
 1582:         }
 1583:         if ($gotdiv) {
 1584:             $r->print('</div><div class="LC_clear_float_footer"></div>');
 1585:         }
 1586:         my $statuses;
 1587:         if (($context eq 'domain') && (&Apache::lonnet::allowed('udp',$ccdomain)) &&
 1588:             (!&Apache::lonnet::allowed('mau',$ccdomain))) {
 1589:             $statuses = ['active'];
 1590:         } elsif (($context eq 'course') && ((&Apache::lonnet::allowed('vcl',$env{'request.course.id'})) ||
 1591:                  ($env{'request.course.sec'} &&
 1592:                   &Apache::lonnet::allowed('vcl',$env{'request.course.id'}.'/'.$env{'request.course.sec'})))) {
 1593:             $statuses = ['active'];
 1594:         }
 1595:         if ($env{'form.action'} ne 'singlestudent') {
 1596:             &display_existing_roles($r,$ccuname,$ccdomain,\%inccourses,$context,
 1597:                                     $roledom,$crstype,$showcredits,$statuses);
 1598:         }
 1599:     } ## End of new user/old user logic
 1600:     if ($env{'form.action'} eq 'singlestudent') {
 1601:         my $btntxt;
 1602:         if ($crstype eq 'Community') {
 1603:             $btntxt = &mt('Enroll Member');
 1604:         } else {
 1605:             $btntxt = &mt('Enroll Student');
 1606:         }
 1607:         $r->print('<br /><input type="button" value="'.$btntxt.'" onclick="setSections(this.form)" />'."\n");
 1608:     } elsif ($permission->{'cusr'}) {
 1609:         $r->print('<div class="LC_left_float">'.
 1610:                   '<fieldset><legend>'.&mt('Add Roles').'</legend>');
 1611:         my $addrolesdisplay = 0;
 1612:         if ($context eq 'domain' || $context eq 'author') {
 1613:             $addrolesdisplay = &new_coauthor_roles($r,$ccuname,$ccdomain);
 1614:         }
 1615:         if ($context eq 'domain') {
 1616:             my $add_domainroles = &new_domain_roles($r,$ccdomain);
 1617:             if (!$addrolesdisplay) {
 1618:                 $addrolesdisplay = $add_domainroles;
 1619:             }
 1620:             $r->print(&course_level_dc($env{'request.role.domain'},$showcredits));
 1621:             $r->print('</fieldset></div><div class="LC_clear_float_footer"></div>'.
 1622:                       '<br /><input type="button" value="'.&mt('Save').'" onclick="setCourse()" />'."\n");
 1623:         } elsif ($context eq 'author') {
 1624:             if ($addrolesdisplay) {
 1625:                 $r->print('</fieldset></div><div class="LC_clear_float_footer"></div>'.
 1626:                           '<br /><input type="button" value="'.&mt('Save').'"');
 1627:                 if ($newuser) {
 1628:                     $r->print(' onclick="auth_check()" \>'."\n");
 1629:                 } else {
 1630:                     $r->print('onclick="this.form.submit()" \>'."\n");
 1631:                 }
 1632:             } else {
 1633:                 $r->print('</fieldset></div>'.
 1634:                           '<div class="LC_clear_float_footer"></div>'.
 1635:                           '<br /><a href="javascript:backPage(document.cu)">'.
 1636:                           &mt('Back to previous page').'</a>');
 1637:             }
 1638:         } else {
 1639:             $r->print(&course_level_table(\%inccourses,$showcredits,$defaultcredits));
 1640:             $r->print('</fieldset></div><div class="LC_clear_float_footer"></div>'.
 1641:                       '<br /><input type="button" value="'.&mt('Save').'" onclick="setSections(this.form)" />'."\n");
 1642:         }
 1643:     }
 1644:     $r->print(&Apache::lonhtmlcommon::echo_form_input(['phase','userrole','ccdomain','prevphase','currstate','ccuname','ccdomain']));
 1645:     $r->print('<input type="hidden" name="currstate" value="" />');
 1646:     $r->print('<input type="hidden" name="prevphase" value="'.$env{'form.phase'}.'" /></form><br /><br />');
 1647:     return;
 1648: }
 1649: 
 1650: sub singleuser_breadcrumb {
 1651:     my ($crstype) = @_;
 1652:     my %breadcrumb_text;
 1653:     if ($env{'form.action'} eq 'singlestudent') {
 1654:         if ($crstype eq 'Community') {
 1655:             $breadcrumb_text{'search'} = 'Enroll a member';
 1656:         } else {
 1657:             $breadcrumb_text{'search'} = 'Enroll a student';
 1658:         }
 1659:         $breadcrumb_text{'userpicked'} = 'Select a user',
 1660:         $breadcrumb_text{'modify'} = 'Set section/dates',
 1661:     } elsif ($env{'form.action'} eq 'accesslogs') {
 1662:         $breadcrumb_text{'search'} = 'View access logs for a user';
 1663:         $breadcrumb_text{'userpicked'} = 'Select a user',
 1664:         $breadcrumb_text{'activity'} = 'Activity',
 1665:     } else {
 1666:         $breadcrumb_text{'search'} = 'Create/modify a user';
 1667:         $breadcrumb_text{'userpicked'} = 'Select a user',
 1668:         $breadcrumb_text{'modify'} = 'Set user role',
 1669:     }
 1670:     return %breadcrumb_text;
 1671: }
 1672: 
 1673: sub date_sections_select {
 1674:     my ($context,$newuser,$formname,$permission,$crstype,$ccuname,$ccdomain,
 1675:         $showcredits) = @_;
 1676:     my $credits;
 1677:     if ($showcredits) {
 1678:         my $defaultcredits = &Apache::lonuserutils::get_defaultcredits();
 1679:         $credits = &get_user_credits($ccuname,$ccdomain,$defaultcredits);
 1680:         if ($credits eq '') {
 1681:             $credits = $defaultcredits;
 1682:         }
 1683:     }
 1684:     my $cid = $env{'request.course.id'};
 1685:     my ($cnum,$cdom) = &Apache::lonuserutils::get_course_identity($cid);
 1686:     my $date_table = '<h3>'.&mt('Starting and Ending Dates').'</h3>'."\n".
 1687:         &Apache::lonuserutils::date_setting_table(undef,undef,$context,
 1688:                                                   undef,$formname,$permission);
 1689:     my $rowtitle = 'Section';
 1690:     my $secbox = '<h3>'.&mt('Section and Credits').'</h3>'."\n".
 1691:         &Apache::lonuserutils::section_picker($cdom,$cnum,'st',$rowtitle,
 1692:                                               $permission,$context,'',$crstype,
 1693:                                               $showcredits,$credits);
 1694:     my $output = $date_table.$secbox;
 1695:     return $output;
 1696: }
 1697: 
 1698: sub validation_javascript {
 1699:     my ($context,$ccdomain,$pjump_def,$crstype,$groupslist,$newuser,$formname,
 1700:         $loaditem) = @_;
 1701:     my $dc_setcourse_code = '';
 1702:     my $nondc_setsection_code = '';
 1703:     if ($context eq 'domain') {
 1704:         my $dcdom = $env{'request.role.domain'};
 1705:         $loaditem->{'onload'} = "document.cu.coursedesc.value='';";
 1706:         $dc_setcourse_code = 
 1707:             &Apache::lonuserutils::dc_setcourse_js('cu','singleuser',$context);
 1708:     } else {
 1709:         my $checkauth; 
 1710:         if (($newuser) || (&Apache::lonnet::allowed('mau',$ccdomain))) {
 1711:             $checkauth = 1;
 1712:         }
 1713:         if ($context eq 'course') {
 1714:             $nondc_setsection_code =
 1715:                 &Apache::lonuserutils::setsections_javascript($formname,$groupslist,
 1716:                                                               undef,$checkauth,
 1717:                                                               $crstype);
 1718:         }
 1719:         if ($checkauth) {
 1720:             $nondc_setsection_code .= 
 1721:                 &Apache::lonuserutils::verify_authen($formname,$context);
 1722:         }
 1723:     }
 1724:     my $js = &user_modification_js($pjump_def,$dc_setcourse_code,
 1725:                                    $nondc_setsection_code,$groupslist);
 1726:     my ($jsback,$elements) = &crumb_utilities();
 1727:     $js .= "\n".
 1728:            '<script type="text/javascript">'."\n".
 1729:            '// <![CDATA['."\n".
 1730:            $jsback."\n".
 1731:            '// ]]>'."\n".
 1732:            '</script>'."\n";
 1733:     return $js;
 1734: }
 1735: 
 1736: sub display_existing_roles {
 1737:     my ($r,$ccuname,$ccdomain,$inccourses,$context,$roledom,$crstype,
 1738:         $showcredits,$statuses) = @_;
 1739:     my $now=time;
 1740:     my $showall = 1;
 1741:     my ($showexpired,$showactive);
 1742:     if ((ref($statuses) eq 'ARRAY') && (@{$statuses} > 0)) {
 1743:         $showall = 0;
 1744:         if (grep(/^expired$/,@{$statuses})) {
 1745:             $showexpired = 1;
 1746:         }
 1747:         if (grep(/^active$/,@{$statuses})) {
 1748:             $showactive = 1;
 1749:         }
 1750:         if ($showexpired && $showactive) {
 1751:             $showall = 1;
 1752:         }
 1753:     }
 1754:     my %lt=&Apache::lonlocal::texthash(
 1755:                     'rer'  => "Existing Roles",
 1756:                     'rev'  => "Revoke",
 1757:                     'del'  => "Delete",
 1758:                     'ren'  => "Re-Enable",
 1759:                     'rol'  => "Role",
 1760:                     'ext'  => "Extent",
 1761:                     'crd'  => "Credits",
 1762:                     'sta'  => "Start",
 1763:                     'end'  => "End",
 1764:                                        );
 1765:     my (%rolesdump,%roletext,%sortrole,%roleclass,%rolepriv);
 1766:     if ($context eq 'course' || $context eq 'author') {
 1767:         my @roles = &Apache::lonuserutils::roles_by_context($context,1,$crstype);
 1768:         my %roleshash = 
 1769:             &Apache::lonnet::get_my_roles($ccuname,$ccdomain,'userroles',
 1770:                               ['active','previous','future'],\@roles,$roledom,1);
 1771:         foreach my $key (keys(%roleshash)) {
 1772:             my ($start,$end) = split(':',$roleshash{$key});
 1773:             next if ($start eq '-1' || $end eq '-1');
 1774:             my ($rnum,$rdom,$role,$sec) = split(':',$key);
 1775:             if ($context eq 'course') {
 1776:                 next unless (($rnum eq $env{'course.'.$env{'request.course.id'}.'.num'})
 1777:                              && ($rdom eq $env{'course.'.$env{'request.course.id'}.'.domain'}));
 1778:             } elsif ($context eq 'author') {
 1779:                 next unless (($rnum eq $env{'user.name'}) && ($rdom eq $env{'request.role.domain'}));
 1780:             }
 1781:             my ($newkey,$newvalue,$newrole);
 1782:             $newkey = '/'.$rdom.'/'.$rnum;
 1783:             if ($sec ne '') {
 1784:                 $newkey .= '/'.$sec;
 1785:             }
 1786:             $newvalue = $role;
 1787:             if ($role =~ /^cr/) {
 1788:                 $newrole = 'cr';
 1789:             } else {
 1790:                 $newrole = $role;
 1791:             }
 1792:             $newkey .= '_'.$newrole;
 1793:             if ($start ne '' && $end ne '') {
 1794:                 $newvalue .= '_'.$end.'_'.$start;
 1795:             } elsif ($end ne '') {
 1796:                 $newvalue .= '_'.$end;
 1797:             }
 1798:             $rolesdump{$newkey} = $newvalue;
 1799:         }
 1800:     } else {
 1801:         %rolesdump=&Apache::lonnet::dump('roles',$ccdomain,$ccuname);
 1802:     }
 1803:     # Build up table of user roles to allow revocation and re-enabling of roles.
 1804:     my ($tmp) = keys(%rolesdump);
 1805:     return if ($tmp =~ /^(con_lost|error)/i);
 1806:     foreach my $area (sort { my $a1=join('_',(split('_',$a))[1,0]);
 1807:                                 my $b1=join('_',(split('_',$b))[1,0]);
 1808:                                 return $a1 cmp $b1;
 1809:                             } keys(%rolesdump)) {
 1810:         next if ($area =~ /^rolesdef/);
 1811:         my $envkey=$area;
 1812:         my $role = $rolesdump{$area};
 1813:         my $thisrole=$area;
 1814:         $area =~ s/\_\w\w$//;
 1815:         my ($role_code,$role_end_time,$role_start_time) =
 1816:             split(/_/,$role);
 1817:         my $active=1;
 1818:         $active=0 if (($role_end_time) && ($now>$role_end_time));
 1819:         if ($active) {
 1820:             next unless($showall || $showactive);
 1821:         } else {
 1822:             next unless($showall || $showexpired);
 1823:         }
 1824: # Is this a custom role? Get role owner and title.
 1825:         my ($croleudom,$croleuname,$croletitle)=
 1826:             ($role_code=~m{^cr/($match_domain)/($match_username)/(\w+)$});
 1827:         my $allowed=0;
 1828:         my $delallowed=0;
 1829:         my $sortkey=$role_code;
 1830:         my $class='Unknown';
 1831:         my $credits='';
 1832:         my $csec;
 1833:         if ($area =~ m{^/($match_domain)/($match_courseid)} ) {
 1834:             $class='Course';
 1835:             my ($coursedom,$coursedir) = ($1,$2);
 1836:             my $cid = $1.'_'.$2;
 1837:             # $1.'_'.$2 is the course id (eg. 103_12345abcef103l3).
 1838:             my %coursedata=
 1839:                 &Apache::lonnet::coursedescription($cid);
 1840:             if ($coursedir =~ /^$match_community$/) {
 1841:                 $class='Community';
 1842:             }
 1843:             $sortkey.="\0$coursedom";
 1844:             my $carea;
 1845:             if (defined($coursedata{'description'})) {
 1846:                 $carea=$coursedata{'description'}.
 1847:                     '<br />'.&mt('Domain').': '.$coursedom.('&nbsp;'x8).
 1848:     &Apache::loncommon::syllabuswrapper(&mt('Syllabus'),$coursedir,$coursedom);
 1849:                 $sortkey.="\0".$coursedata{'description'};
 1850:             } else {
 1851:                 if ($class eq 'Community') {
 1852:                     $carea=&mt('Unavailable community').': '.$area;
 1853:                     $sortkey.="\0".&mt('Unavailable community').': '.$area;
 1854:                 } else {
 1855:                     $carea=&mt('Unavailable course').': '.$area;
 1856:                     $sortkey.="\0".&mt('Unavailable course').': '.$area;
 1857:                 }
 1858:             }
 1859:             $sortkey.="\0$coursedir";
 1860:             $inccourses->{$cid}=1;
 1861:             if (($showcredits) && ($class eq 'Course') && ($role_code eq 'st')) {
 1862:                 my $defaultcredits = $coursedata{'internal.defaultcredits'};
 1863:                 $credits =
 1864:                     &get_user_credits($ccuname,$ccdomain,$defaultcredits,
 1865:                                       $coursedom,$coursedir);
 1866:                 if ($credits eq '') {
 1867:                     $credits = $defaultcredits;
 1868:                 }
 1869:             }
 1870:             if ((&Apache::lonnet::allowed('c'.$role_code,$coursedom.'/'.$coursedir)) ||
 1871:                 (&Apache::lonnet::allowed('c'.$role_code,$ccdomain))) {
 1872:                 $allowed=1;
 1873:             }
 1874:             unless ($allowed) {
 1875:                 my $isowner = &Apache::lonuserutils::is_courseowner($cid,$coursedata{'internal.courseowner'});
 1876:                 if ($isowner) {
 1877:                     if (($role_code eq 'co') && ($class eq 'Community')) {
 1878:                         $allowed = 1;
 1879:                     } elsif (($role_code eq 'cc') && ($class eq 'Course')) {
 1880:                         $allowed = 1;
 1881:                     }
 1882:                 }
 1883:             } 
 1884:             if ((&Apache::lonnet::allowed('dro',$coursedom)) ||
 1885:                 (&Apache::lonnet::allowed('dro',$ccdomain))) {
 1886:                 $delallowed=1;
 1887:             }
 1888: # - custom role. Needs more info, too
 1889:             if ($croletitle) {
 1890:                 if (&Apache::lonnet::allowed('ccr',$coursedom.'/'.$coursedir)) {
 1891:                     $allowed=1;
 1892:                     $thisrole.='.'.$role_code;
 1893:                 }
 1894:             }
 1895:             if ($area=~m{^/($match_domain/$match_courseid/(\w+))}) {
 1896:                 $csec = $2;
 1897:                 $carea.='<br />'.&mt('Section: [_1]',$csec);
 1898:                 $sortkey.="\0$csec";
 1899:                 if (!$allowed) {
 1900:                     if ($env{'request.course.sec'} eq $csec) {
 1901:                         if (&Apache::lonnet::allowed('c'.$role_code,$1)) {
 1902:                             $allowed = 1;
 1903:                         }
 1904:                     }
 1905:                 }
 1906:             }
 1907:             $area=$carea;
 1908:         } else {
 1909:             $sortkey.="\0".$area;
 1910:             # Determine if current user is able to revoke privileges
 1911:             if ($area=~m{^/($match_domain)/}) {
 1912:                 if ((&Apache::lonnet::allowed('c'.$role_code,$1)) ||
 1913:                    (&Apache::lonnet::allowed('c'.$role_code,$ccdomain))) {
 1914:                    $allowed=1;
 1915:                 }
 1916:                 if (((&Apache::lonnet::allowed('dro',$1))  ||
 1917:                     (&Apache::lonnet::allowed('dro',$ccdomain))) &&
 1918:                     ($role_code ne 'dc')) {
 1919:                     $delallowed=1;
 1920:                 }
 1921:             } else {
 1922:                 if (&Apache::lonnet::allowed('c'.$role_code,'/')) {
 1923:                     $allowed=1;
 1924:                 }
 1925:             }
 1926:             if ($role_code eq 'ca' || $role_code eq 'au' || $role_code eq 'aa') {
 1927:                 $class='Authoring Space';
 1928:             } elsif ($role_code eq 'su') {
 1929:                 $class='System';
 1930:             } else {
 1931:                 $class='Domain';
 1932:             }
 1933:         }
 1934:         if (($role_code eq 'ca') || ($role_code eq 'aa')) {
 1935:             $area=~m{/($match_domain)/($match_username)};
 1936:             if (&Apache::lonuserutils::authorpriv($2,$1)) {
 1937:                 $allowed=1;
 1938:             } else {
 1939:                 $allowed=0;
 1940:             }
 1941:         }
 1942:         my $row = '';
 1943:         if ($showall) {
 1944:             $row.= '<td>';
 1945:             if (($active) && ($allowed)) {
 1946:                 $row.= '<input type="checkbox" name="rev:'.$thisrole.'" />';
 1947:             } else {
 1948:                 if ($active) {
 1949:                     $row.='&nbsp;';
 1950:                 } else {
 1951:                     $row.=&mt('expired or revoked');
 1952:                 }
 1953:             }
 1954:             $row.='</td><td>';
 1955:             if ($allowed && !$active) {
 1956:                 $row.= '<input type="checkbox" name="ren:'.$thisrole.'" />';
 1957:             } else {
 1958:                 $row.='&nbsp;';
 1959:             }
 1960:             $row.='</td><td>';
 1961:             if ($delallowed) {
 1962:                 $row.= '<input type="checkbox" name="del:'.$thisrole.'" />';
 1963:             } else {
 1964:                 $row.='&nbsp;';
 1965:             }
 1966:             $row.= '</td>';
 1967:         }
 1968:         my $plaintext='';
 1969:         if (!$croletitle) {
 1970:             $plaintext=&Apache::lonnet::plaintext($role_code,$class);
 1971:             if (($showcredits) && ($credits ne '')) {
 1972:                 $plaintext .= '<br/ ><span class="LC_nobreak">'.
 1973:                               '<span class="LC_fontsize_small">'.
 1974:                               &mt('Credits: [_1]',$credits).
 1975:                               '</span></span>';
 1976:             }
 1977:         } else {
 1978:             $plaintext=
 1979:                 &mt('Custom role [_1][_2]defined by [_3]',
 1980:                         '"'.$croletitle.'"',
 1981:                         '<br />',
 1982:                         $croleuname.':'.$croleudom);
 1983:         }
 1984:         $row.= '<td>'.$plaintext.'</td>'.
 1985:                '<td>'.$area.'</td>'.
 1986:                '<td>'.($role_start_time?&Apache::lonlocal::locallocaltime($role_start_time)
 1987:                                             : '&nbsp;' ).'</td>'.
 1988:                '<td>'.($role_end_time  ?&Apache::lonlocal::locallocaltime($role_end_time)
 1989:                                             : '&nbsp;' ).'</td>';
 1990:         $sortrole{$sortkey}=$envkey;
 1991:         $roletext{$envkey}=$row;
 1992:         $roleclass{$envkey}=$class;
 1993:         if ($allowed) {
 1994:             $rolepriv{$envkey}='edit';
 1995:         } else {
 1996:             if ($context eq 'domain') {
 1997:                 if (&Apache::lonnet::allowed('vur',$ccdomain)) {
 1998:                     $rolepriv{$envkey}='view';
 1999:                 }
 2000:             } elsif ($context eq 'course') {
 2001:                 if ((&Apache::lonnet::allowed('vcl',$env{'request.course.id'})) ||
 2002:                     ($env{'request.course.sec'} && ($env{'request.course.sec'} eq $csec) &&
 2003:                      &Apache::lonnet::allowed('vcl',$env{'request.course.id'}.'/'.$env{'request.course.sec'}))) {
 2004:                     $rolepriv{$envkey}='view';
 2005:                 }
 2006:             }
 2007:         }
 2008:     } # end of foreach        (table building loop)
 2009: 
 2010:     my $rolesdisplay = 0;
 2011:     my %output = ();
 2012:     foreach my $type ('Authoring Space','Course','Community','Domain','System','Unknown') {
 2013:         $output{$type} = '';
 2014:         foreach my $which (sort {uc($a) cmp uc($b)} (keys(%sortrole))) {
 2015:             if ( ($roleclass{$sortrole{$which}} =~ /^\Q$type\E/ ) && ($rolepriv{$sortrole{$which}}) ) {
 2016:                  $output{$type}.=
 2017:                       &Apache::loncommon::start_data_table_row().
 2018:                       $roletext{$sortrole{$which}}.
 2019:                       &Apache::loncommon::end_data_table_row();
 2020:             }
 2021:         }
 2022:         unless($output{$type} eq '') {
 2023:             $output{$type} = '<tr class="LC_info_row">'.
 2024:                       "<td align='center' colspan='7'>".&mt($type)."</td></tr>".
 2025:                       $output{$type};
 2026:             $rolesdisplay = 1;
 2027:         }
 2028:     }
 2029:     if ($rolesdisplay == 1) {
 2030:         my $contextrole='';
 2031:         if ($env{'request.course.id'}) {
 2032:             if (&Apache::loncommon::course_type() eq 'Community') {
 2033:                 $contextrole = &mt('Existing Roles in this Community');
 2034:             } else {
 2035:                 $contextrole = &mt('Existing Roles in this Course');
 2036:             }
 2037:         } elsif ($env{'request.role'} =~ /^au\./) {
 2038:             $contextrole = &mt('Existing Co-Author Roles in your Authoring Space');
 2039:         } else {
 2040:             if ($showall) {
 2041:                 $contextrole = &mt('Existing Roles in this Domain');
 2042:             } elsif ($showactive) {
 2043:                 $contextrole = &mt('Unexpired Roles in this Domain');
 2044:             } elsif ($showexpired) {
 2045:                 $contextrole = &mt('Expired or Revoked Roles in this Domain');
 2046:             }
 2047:         }
 2048:         $r->print('<div class="LC_left_float">'.
 2049: '<fieldset><legend>'.$contextrole.'</legend>'.
 2050: &Apache::loncommon::start_data_table("LC_createuser").
 2051: &Apache::loncommon::start_data_table_header_row());
 2052:         if ($showall) {
 2053:             $r->print(
 2054: '<th>'.$lt{'rev'}.'</th><th>'.$lt{'ren'}.'</th><th>'.$lt{'del'}.'</th>'
 2055:             );
 2056:         } elsif ($showexpired) {
 2057:             $r->print('<th>'.$lt{'rev'}.'</th>');
 2058:         }
 2059:         $r->print(
 2060: '<th>'.$lt{'rol'}.'</th><th>'.$lt{'ext'}.'</th>'.
 2061: '<th>'.$lt{'sta'}.'</th><th>'.$lt{'end'}.'</th>'.
 2062: &Apache::loncommon::end_data_table_header_row());
 2063:         foreach my $type ('Authoring Space','Course','Community','Domain','System','Unknown') {
 2064:             if ($output{$type}) {
 2065:                 $r->print($output{$type}."\n");
 2066:             }
 2067:         }
 2068:         $r->print(&Apache::loncommon::end_data_table().
 2069:                   '</fieldset></div>');
 2070:     }
 2071:     return;
 2072: }
 2073: 
 2074: sub new_coauthor_roles {
 2075:     my ($r,$ccuname,$ccdomain) = @_;
 2076:     my $addrolesdisplay = 0;
 2077:     #
 2078:     # Co-Author
 2079:     #
 2080:     if (&Apache::lonuserutils::authorpriv($env{'user.name'},
 2081:                                           $env{'request.role.domain'}) &&
 2082:         ($env{'user.name'} ne $ccuname || $env{'user.domain'} ne $ccdomain)) {
 2083:         # No sense in assigning co-author role to yourself
 2084:         $addrolesdisplay = 1;
 2085:         my $cuname=$env{'user.name'};
 2086:         my $cudom=$env{'request.role.domain'};
 2087:         my %lt=&Apache::lonlocal::texthash(
 2088:                     'cs'   => "Authoring Space",
 2089:                     'act'  => "Activate",
 2090:                     'rol'  => "Role",
 2091:                     'ext'  => "Extent",
 2092:                     'sta'  => "Start",
 2093:                     'end'  => "End",
 2094:                     'cau'  => "Co-Author",
 2095:                     'caa'  => "Assistant Co-Author",
 2096:                     'ssd'  => "Set Start Date",
 2097:                     'sed'  => "Set End Date"
 2098:                                        );
 2099:         $r->print('<h4>'.$lt{'cs'}.'</h4>'."\n".
 2100:                   &Apache::loncommon::start_data_table()."\n".
 2101:                   &Apache::loncommon::start_data_table_header_row()."\n".
 2102:                   '<th>'.$lt{'act'}.'</th><th>'.$lt{'rol'}.'</th>'.
 2103:                   '<th>'.$lt{'ext'}.'</th><th>'.$lt{'sta'}.'</th>'.
 2104:                   '<th>'.$lt{'end'}.'</th>'."\n".
 2105:                   &Apache::loncommon::end_data_table_header_row()."\n".
 2106:                   &Apache::loncommon::start_data_table_row().'
 2107:            <td>
 2108:             <input type="checkbox" name="act_'.$cudom.'_'.$cuname.'_ca" />
 2109:            </td>
 2110:            <td>'.$lt{'cau'}.'</td>
 2111:            <td>'.$cudom.'_'.$cuname.'</td>
 2112:            <td><input type="hidden" name="start_'.$cudom.'_'.$cuname.'_ca" value="" />
 2113:              <a href=
 2114: "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>
 2115: <td><input type="hidden" name="end_'.$cudom.'_'.$cuname.'_ca" value="" />
 2116: <a href=
 2117: "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".
 2118:               &Apache::loncommon::end_data_table_row()."\n".
 2119:               &Apache::loncommon::start_data_table_row()."\n".
 2120: '<td><input type="checkbox" name="act_'.$cudom.'_'.$cuname.'_aa" /></td>
 2121: <td>'.$lt{'caa'}.'</td>
 2122: <td>'.$cudom.'_'.$cuname.'</td>
 2123: <td><input type="hidden" name="start_'.$cudom.'_'.$cuname.'_aa" value="" />
 2124: <a href=
 2125: "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>
 2126: <td><input type="hidden" name="end_'.$cudom.'_'.$cuname.'_aa" value="" />
 2127: <a href=
 2128: "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".
 2129:              &Apache::loncommon::end_data_table_row()."\n".
 2130:              &Apache::loncommon::end_data_table());
 2131:     } elsif ($env{'request.role'} =~ /^au\./) {
 2132:         if (!(&Apache::lonuserutils::authorpriv($env{'user.name'},
 2133:                                                 $env{'request.role.domain'}))) {
 2134:             $r->print('<span class="LC_error">'.
 2135:                       &mt('You do not have privileges to assign co-author roles.').
 2136:                       '</span>');
 2137:         } elsif (($env{'user.name'} eq $ccuname) &&
 2138:              ($env{'user.domain'} eq $ccdomain)) {
 2139:             $r->print(&mt('Assigning yourself a co-author or assistant co-author role in your own author area in Authoring Space is not permitted'));
 2140:         }
 2141:     }
 2142:     return $addrolesdisplay;;
 2143: }
 2144: 
 2145: sub new_domain_roles {
 2146:     my ($r,$ccdomain) = @_;
 2147:     my $addrolesdisplay = 0;
 2148:     #
 2149:     # Domain level
 2150:     #
 2151:     my $num_domain_level = 0;
 2152:     my $domaintext =
 2153:     '<h4>'.&mt('Domain Level').'</h4>'.
 2154:     &Apache::loncommon::start_data_table().
 2155:     &Apache::loncommon::start_data_table_header_row().
 2156:     '<th>'.&mt('Activate').'</th><th>'.&mt('Role').'</th><th>'.
 2157:     &mt('Extent').'</th>'.
 2158:     '<th>'.&mt('Start').'</th><th>'.&mt('End').'</th>'.
 2159:     &Apache::loncommon::end_data_table_header_row();
 2160:     my @allroles = &Apache::lonuserutils::roles_by_context('domain');
 2161:     foreach my $thisdomain (sort(&Apache::lonnet::all_domains())) {
 2162:         foreach my $role (@allroles) {
 2163:             next if ($role eq 'ad');
 2164:             next if (($role eq 'au') && ($ccdomain ne $thisdomain));
 2165:             if (&Apache::lonnet::allowed('c'.$role,$thisdomain)) {
 2166:                my $plrole=&Apache::lonnet::plaintext($role);
 2167:                my %lt=&Apache::lonlocal::texthash(
 2168:                     'ssd'  => "Set Start Date",
 2169:                     'sed'  => "Set End Date"
 2170:                                        );
 2171:                $num_domain_level ++;
 2172:                $domaintext .=
 2173: &Apache::loncommon::start_data_table_row().
 2174: '<td><input type="checkbox" name="act_'.$thisdomain.'_'.$role.'" /></td>
 2175: <td>'.$plrole.'</td>
 2176: <td>'.$thisdomain.'</td>
 2177: <td><input type="hidden" name="start_'.$thisdomain.'_'.$role.'" value="" />
 2178: <a href=
 2179: "javascript:pjump('."'date_start','Start Date $plrole',document.cu.start_$thisdomain\_$role.value,'start_$thisdomain\_$role','cu.pres','dateset'".')">'.$lt{'ssd'}.'</a></td>
 2180: <td><input type="hidden" name="end_'.$thisdomain.'_'.$role.'" value="" />
 2181: <a href=
 2182: "javascript:pjump('."'date_end','End Date $plrole',document.cu.end_$thisdomain\_$role.value,'end_$thisdomain\_$role','cu.pres','dateset'".')">'.$lt{'sed'}.'</a></td>'.
 2183: &Apache::loncommon::end_data_table_row();
 2184:             }
 2185:         }
 2186:     }
 2187:     $domaintext.= &Apache::loncommon::end_data_table();
 2188:     if ($num_domain_level > 0) {
 2189:         $r->print($domaintext);
 2190:         $addrolesdisplay = 1;
 2191:     }
 2192:     return $addrolesdisplay;
 2193: }
 2194: 
 2195: sub user_authentication {
 2196:     my ($ccuname,$ccdomain,$formname) = @_;
 2197:     my $currentauth=&Apache::lonnet::queryauthenticate($ccuname,$ccdomain);
 2198:     my $outcome;
 2199:     my %lt=&Apache::lonlocal::texthash(
 2200:                    'err'   => "ERROR",
 2201:                    'uuas'  => "This user has an unrecognized authentication scheme",
 2202:                    'adcs'  => "Please alert a domain coordinator of this situation",
 2203:                    'sldb'  => "Please specify login data below",
 2204:                    'ld'    => "Login Data"
 2205:     );
 2206:     # Check for a bad authentication type
 2207:     if ($currentauth !~ /^(krb4|krb5|unix|internal|localauth):/) {
 2208:         # bad authentication scheme
 2209:         if (&Apache::lonnet::allowed('mau',$ccdomain)) {
 2210:             &initialize_authen_forms($ccdomain,$formname);
 2211: 
 2212:             my $choices = &Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc);
 2213:             $outcome = <<ENDBADAUTH;
 2214: <script type="text/javascript" language="Javascript">
 2215: // <![CDATA[
 2216: $loginscript
 2217: // ]]>
 2218: </script>
 2219: <span class="LC_error">$lt{'err'}:
 2220: $lt{'uuas'} ($currentauth). $lt{'sldb'}.</span>
 2221: <h3>$lt{'ld'}</h3>
 2222: $choices
 2223: ENDBADAUTH
 2224:         } else {
 2225:             # This user is not allowed to modify the user's
 2226:             # authentication scheme, so just notify them of the problem
 2227:             $outcome = <<ENDBADAUTH;
 2228: <span class="LC_error"> $lt{'err'}: 
 2229: $lt{'uuas'} ($currentauth). $lt{'adcs'}.
 2230: </span>
 2231: ENDBADAUTH
 2232:         }
 2233:     } else { # Authentication type is valid
 2234:         &initialize_authen_forms($ccdomain,$formname,$currentauth,'modifyuser');
 2235:         my ($authformcurrent,$can_modify,@authform_others) =
 2236:             &modify_login_block($ccdomain,$currentauth);
 2237:         if (&Apache::lonnet::allowed('mau',$ccdomain)) {
 2238:             # Current user has login modification privileges
 2239:             $outcome =
 2240:                        '<script type="text/javascript" language="Javascript">'."\n".
 2241:                        '// <![CDATA['."\n".
 2242:                        $loginscript."\n".
 2243:                        '// ]]>'."\n".
 2244:                        '</script>'."\n".
 2245:                        '<h3>'.$lt{'ld'}.'</h3>'.
 2246:                        &Apache::loncommon::start_data_table().
 2247:                        &Apache::loncommon::start_data_table_row().
 2248:                        '<td>'.$authformnop;
 2249:             if (($can_modify) && (&Apache::lonnet::allowed('mau',$ccdomain))) {
 2250:                 $outcome .= '</td>'."\n".
 2251:                             &Apache::loncommon::end_data_table_row().
 2252:                             &Apache::loncommon::start_data_table_row().
 2253:                             '<td>'.$authformcurrent.'</td>'.
 2254:                             &Apache::loncommon::end_data_table_row()."\n";
 2255:             } else {
 2256:                 $outcome .= '&nbsp;('.$authformcurrent.')</td>'.
 2257:                             &Apache::loncommon::end_data_table_row()."\n";
 2258:             }
 2259:             if (&Apache::lonnet::allowed('mau',$ccdomain)) {
 2260:                 foreach my $item (@authform_others) { 
 2261:                     $outcome .= &Apache::loncommon::start_data_table_row().
 2262:                                 '<td>'.$item.'</td>'.
 2263:                                 &Apache::loncommon::end_data_table_row()."\n";
 2264:                 }
 2265:             }
 2266:             $outcome .= &Apache::loncommon::end_data_table();
 2267:         } else {
 2268:             if (&Apache::lonnet::allowed('udp',$ccdomain)) {
 2269:                 # Current user has rights to view domain preferences for user's domain
 2270:                 my $result;
 2271:                 if ($currentauth =~ /^krb(4|5):([^:]*)$/) {
 2272:                     my ($krbver,$krbrealm) = ($1,$2);
 2273:                     if ($krbrealm eq '') {
 2274:                         $result = &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
 2275:                     } else {
 2276:                         $result = &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
 2277:                                       $krbver,$krbrealm);
 2278:                     }
 2279:                 } elsif ($currentauth =~ /^internal:/) {
 2280:                     $result = &mt('Currently internally authenticated.');
 2281:                 } elsif ($currentauth =~ /^localauth:/) {
 2282:                     $result = &mt('Currently using local (institutional) authentication.');
 2283:                 } elsif ($currentauth =~ /^unix:/) {
 2284:                     $result = &mt('Currently Filesystem Authenticated.');
 2285:                 }
 2286:                 $outcome = '<h3>'.$lt{'ld'}.'</h3>'.
 2287:                            &Apache::loncommon::start_data_table().
 2288:                            &Apache::loncommon::start_data_table_row().
 2289:                            '<td>'.$result.'</td>'.
 2290:                            &Apache::loncommon::end_data_table_row()."\n".
 2291:                            &Apache::loncommon::end_data_table();
 2292:             } elsif (&Apache::lonnet::allowed('mau',$env{'request.role.domain'})) {
 2293:                 my %lt=&Apache::lonlocal::texthash(
 2294:                            'ccld'  => "Change Current Login Data",
 2295:                            'yodo'  => "You do not have privileges to modify the authentication configuration for this user.",
 2296:                            'ifch'  => "If a change is required, contact a domain coordinator for the domain",
 2297:                 );
 2298:                 $outcome .= <<ENDNOPRIV;
 2299: <h3>$lt{'ccld'}</h3>
 2300: $lt{'yodo'} $lt{'ifch'}: $ccdomain
 2301: <input type="hidden" name="login" value="nochange" />
 2302: ENDNOPRIV
 2303:             }
 2304:         }
 2305:     }  ## End of "check for bad authentication type" logic
 2306:     return $outcome;
 2307: }
 2308: 
 2309: sub modify_login_block {
 2310:     my ($dom,$currentauth) = @_;
 2311:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 2312:     my ($authnum,%can_assign) =
 2313:         &Apache::loncommon::get_assignable_auth($dom);
 2314:     my ($authformcurrent,@authform_others,$show_override_msg);
 2315:     if ($currentauth=~/^krb(4|5):/) {
 2316:         $authformcurrent=$authformkrb;
 2317:         if ($can_assign{'int'}) {
 2318:             push(@authform_others,$authformint);
 2319:         }
 2320:         if ($can_assign{'loc'}) {
 2321:             push(@authform_others,$authformloc);
 2322:         }
 2323:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2324:             $show_override_msg = 1;
 2325:         }
 2326:     } elsif ($currentauth=~/^internal:/) {
 2327:         $authformcurrent=$authformint;
 2328:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2329:             push(@authform_others,$authformkrb);
 2330:         }
 2331:         if ($can_assign{'loc'}) {
 2332:             push(@authform_others,$authformloc);
 2333:         }
 2334:         if ($can_assign{'int'}) {
 2335:             $show_override_msg = 1;
 2336:         }
 2337:     } elsif ($currentauth=~/^unix:/) {
 2338:         $authformcurrent=$authformfsys;
 2339:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2340:             push(@authform_others,$authformkrb);
 2341:         }
 2342:         if ($can_assign{'int'}) {
 2343:             push(@authform_others,$authformint);
 2344:         }
 2345:         if ($can_assign{'loc'}) {
 2346:             push(@authform_others,$authformloc);
 2347:         }
 2348:         if ($can_assign{'fsys'}) {
 2349:             $show_override_msg = 1;
 2350:         }
 2351:     } elsif ($currentauth=~/^localauth:/) {
 2352:         $authformcurrent=$authformloc;
 2353:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2354:             push(@authform_others,$authformkrb);
 2355:         }
 2356:         if ($can_assign{'int'}) {
 2357:             push(@authform_others,$authformint);
 2358:         }
 2359:         if ($can_assign{'loc'}) {
 2360:             $show_override_msg = 1;
 2361:         }
 2362:     }
 2363:     if ($show_override_msg) {
 2364:         $authformcurrent = '<table><tr><td colspan="3">'.$authformcurrent.
 2365:                            '</td></tr>'."\n".
 2366:                            '<tr><td>&nbsp;&nbsp;&nbsp;</td>'.
 2367:                            '<td><b>'.&mt('Currently in use').'</b></td>'.
 2368:                            '<td align="right"><span class="LC_cusr_emph">'.
 2369:                             &mt('will override current values').
 2370:                             '</span></td></tr></table>';
 2371:     }
 2372:     return ($authformcurrent,$show_override_msg,@authform_others); 
 2373: }
 2374: 
 2375: sub personal_data_display {
 2376:     my ($ccuname,$ccdomain,$newuser,$context,$inst_results,$rolesarray,
 2377:         $now,$captchaform,$emailusername,$usertype) = @_;
 2378:     my ($output,%userenv,%canmodify,%canmodify_status);
 2379:     my @userinfo = ('firstname','middlename','lastname','generation',
 2380:                     'permanentemail','id');
 2381:     my $rowcount = 0;
 2382:     my $editable = 0;
 2383:     my %textboxsize = (
 2384:                        firstname      => '15',
 2385:                        middlename     => '15',
 2386:                        lastname       => '15',
 2387:                        generation     => '5',
 2388:                        permanentemail => '25',
 2389:                        id             => '15',
 2390:                       );
 2391: 
 2392:     my %lt=&Apache::lonlocal::texthash(
 2393:                 'pd'             => "Personal Data",
 2394:                 'firstname'      => "First Name",
 2395:                 'middlename'     => "Middle Name",
 2396:                 'lastname'       => "Last Name",
 2397:                 'generation'     => "Generation",
 2398:                 'permanentemail' => "Permanent e-mail address",
 2399:                 'id'             => "Student/Employee ID",
 2400:                 'lg'             => "Login Data",
 2401:                 'inststatus'     => "Affiliation",
 2402:                 'email'          => 'E-mail address',
 2403:                 'valid'          => 'Validation',
 2404:     );
 2405: 
 2406:     %canmodify_status =
 2407:         &Apache::lonuserutils::can_modify_userinfo($context,$ccdomain,
 2408:                                                    ['inststatus'],$rolesarray);
 2409:     if (!$newuser) {
 2410:         # Get the users information
 2411:         %userenv = &Apache::lonnet::get('environment',
 2412:                    ['firstname','middlename','lastname','generation',
 2413:                     'permanentemail','id','inststatus'],$ccdomain,$ccuname);
 2414:         %canmodify =
 2415:             &Apache::lonuserutils::can_modify_userinfo($context,$ccdomain,
 2416:                                                        \@userinfo,$rolesarray);
 2417:     } elsif ($context eq 'selfcreate') {
 2418:         if ($newuser eq 'email') {
 2419:             if (ref($emailusername) eq 'HASH') {
 2420:                 if (ref($emailusername->{$usertype}) eq 'HASH') {
 2421:                     my ($infofields,$infotitles) = &Apache::loncommon::emailusername_info();
 2422:                     @userinfo = ();          
 2423:                     if ((ref($infofields) eq 'ARRAY') && (ref($infotitles) eq 'HASH')) {
 2424:                         foreach my $field (@{$infofields}) { 
 2425:                             if ($emailusername->{$usertype}->{$field}) {
 2426:                                 push(@userinfo,$field);
 2427:                                 $canmodify{$field} = 1;
 2428:                                 unless ($textboxsize{$field}) {
 2429:                                     $textboxsize{$field} = 25;
 2430:                                 }
 2431:                                 unless ($lt{$field}) {
 2432:                                     $lt{$field} = $infotitles->{$field};
 2433:                                 }
 2434:                                 if ($emailusername->{$usertype}->{$field} eq 'required') {
 2435:                                     $lt{$field} .= '<b>*</b>';
 2436:                                 }
 2437:                             }
 2438:                         }
 2439:                     }
 2440:                 }
 2441:             }
 2442:         } else {
 2443:             %canmodify = &selfcreate_canmodify($context,$ccdomain,\@userinfo,
 2444:                                                $inst_results,$rolesarray);
 2445:         }
 2446:     }
 2447: 
 2448:     my $genhelp=&Apache::loncommon::help_open_topic('Generation');
 2449:     $output = '<h3>'.$lt{'pd'}.'</h3>'.
 2450:               &Apache::lonhtmlcommon::start_pick_box();
 2451:     if (($context eq 'selfcreate') && ($newuser eq 'email')) {
 2452:         $output .= &Apache::lonhtmlcommon::row_title($lt{'email'}.'<b>*</b>',undef,
 2453:                                                      'LC_oddrow_value')."\n".
 2454:                    '<input type="text" name="uname" size="25" value="" autocomplete="off" />';
 2455:         $rowcount ++;
 2456:         $output .= &Apache::lonhtmlcommon::row_closure(1);
 2457:         my $upassone = '<input type="password" name="upass'.$now.'" size="20" autocomplete="off" />';
 2458:         my $upasstwo = '<input type="password" name="upasscheck'.$now.'" size="20" autocomplete="off" />';
 2459:         $output .= &Apache::lonhtmlcommon::row_title(&mt('Password').'<b>*</b>',
 2460:                                                     'LC_pick_box_title',
 2461:                                                     'LC_oddrow_value')."\n".
 2462:                    $upassone."\n".
 2463:                    &Apache::lonhtmlcommon::row_closure(1)."\n".
 2464:                    &Apache::lonhtmlcommon::row_title(&mt('Confirm password').'<b>*</b>',
 2465:                                                      'LC_pick_box_title',
 2466:                                                      'LC_oddrow_value')."\n".
 2467:                    $upasstwo.
 2468:                    &Apache::lonhtmlcommon::row_closure()."\n";
 2469:     }
 2470:     foreach my $item (@userinfo) {
 2471:         my $rowtitle = $lt{$item};
 2472:         my $hiderow = 0;
 2473:         if ($item eq 'generation') {
 2474:             $rowtitle = $genhelp.$rowtitle;
 2475:         }
 2476:         my $row = &Apache::lonhtmlcommon::row_title($rowtitle,undef,'LC_oddrow_value')."\n";
 2477:         if ($newuser) {
 2478:             if (ref($inst_results) eq 'HASH') {
 2479:                 if ($inst_results->{$item} ne '') {
 2480:                     $row .= '<input type="hidden" name="c'.$item.'" value="'.$inst_results->{$item}.'" />'.$inst_results->{$item};
 2481:                 } else {
 2482:                     if ($context eq 'selfcreate') {
 2483:                         if ($canmodify{$item}) {
 2484:                             $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="" autocomplete="off" />';
 2485:                             $editable ++;
 2486:                         } else {
 2487:                             $hiderow = 1;
 2488:                         }
 2489:                     } else {
 2490:                         $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="" />';
 2491:                     }
 2492:                 }
 2493:             } else {
 2494:                 if ($context eq 'selfcreate') {
 2495:                     if ($canmodify{$item}) {
 2496:                         if ($newuser eq 'email') {
 2497:                             $row .= '<input type="text" name="'.$item.'" size="'.$textboxsize{$item}.'" value="" autocomplete="off" />';
 2498:                         } else {
 2499:                             $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="" autocomplete="off" />';
 2500:                         }
 2501:                         $editable ++;
 2502:                     } else {
 2503:                         $hiderow = 1;
 2504:                     }
 2505:                 } else {
 2506:                     $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="" />';
 2507:                 }
 2508:             }
 2509:         } else {
 2510:             if ($canmodify{$item}) {
 2511:                 $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="'.$userenv{$item}.'" />';
 2512:                 if (($item eq 'id') && (!$newuser)) {
 2513:                     $row .= '<br />'.&Apache::lonuserutils::forceid_change($context);
 2514:                 }
 2515:             } else {
 2516:                 $row .= $userenv{$item};
 2517:             }
 2518:         }
 2519:         $row .= &Apache::lonhtmlcommon::row_closure(1);
 2520:         if (!$hiderow) {
 2521:             $output .= $row;
 2522:             $rowcount ++;
 2523:         }
 2524:     }
 2525:     if (($canmodify_status{'inststatus'}) || ($context ne 'selfcreate')) {
 2526:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($ccdomain);
 2527:         if (ref($types) eq 'ARRAY') {
 2528:             if (@{$types} > 0) {
 2529:                 my ($hiderow,$shown);
 2530:                 if ($canmodify_status{'inststatus'}) {
 2531:                     $shown = &pick_inst_statuses($userenv{'inststatus'},$usertypes,$types);
 2532:                 } else {
 2533:                     if ($userenv{'inststatus'} eq '') {
 2534:                         $hiderow = 1;
 2535:                     } else {
 2536:                         my @showitems;
 2537:                         foreach my $item ( map { &unescape($_); } split(':',$userenv{'inststatus'})) {
 2538:                             if (exists($usertypes->{$item})) {
 2539:                                 push(@showitems,$usertypes->{$item});
 2540:                             } else {
 2541:                                 push(@showitems,$item);
 2542:                             }
 2543:                         }
 2544:                         if (@showitems) {
 2545:                             $shown = join(', ',@showitems);
 2546:                         } else {
 2547:                             $hiderow = 1;
 2548:                         }
 2549:                     }
 2550:                 }
 2551:                 if (!$hiderow) {
 2552:                     my $row = &Apache::lonhtmlcommon::row_title(&mt('Affiliations'),undef,'LC_oddrow_value')."\n".
 2553:                               $shown.&Apache::lonhtmlcommon::row_closure(1); 
 2554:                     if ($context eq 'selfcreate') {
 2555:                         $rowcount ++;
 2556:                     }
 2557:                     $output .= $row;
 2558:                 }
 2559:             }
 2560:         }
 2561:     }
 2562:     if (($context eq 'selfcreate') && ($newuser eq 'email')) {
 2563:         if ($captchaform) {
 2564:             $output .= &Apache::lonhtmlcommon::row_title($lt{'valid'}.'*',
 2565:                                                          'LC_pick_box_title')."\n".
 2566:                        $captchaform."\n".'<br /><br />'.
 2567:                        &Apache::lonhtmlcommon::row_closure(1); 
 2568:             $rowcount ++;
 2569:         }
 2570:         my $submit_text = &mt('Create account');
 2571:         $output .= &Apache::lonhtmlcommon::row_title()."\n".
 2572:                    '<br /><input type="submit" name="createaccount" value="'.
 2573:                    $submit_text.'" />'.
 2574:                    '<input type="hidden" name="type" value="'.$usertype.'" />'.
 2575:                    &Apache::lonhtmlcommon::row_closure(1);
 2576:     }
 2577:     $output .= &Apache::lonhtmlcommon::end_pick_box();
 2578:     if (wantarray) {
 2579:         if ($context eq 'selfcreate') {
 2580:             return($output,$rowcount,$editable);
 2581:         } else {
 2582:             return $output;
 2583:         }
 2584:     } else {
 2585:         return $output;
 2586:     }
 2587: }
 2588: 
 2589: sub pick_inst_statuses {
 2590:     my ($curr,$usertypes,$types) = @_;
 2591:     my ($output,$rem,@currtypes);
 2592:     if ($curr ne '') {
 2593:         @currtypes = map { &unescape($_); } split(/:/,$curr);
 2594:     }
 2595:     my $numinrow = 2;
 2596:     if (ref($types) eq 'ARRAY') {
 2597:         $output = '<table>';
 2598:         my $lastcolspan; 
 2599:         for (my $i=0; $i<@{$types}; $i++) {
 2600:             if (defined($usertypes->{$types->[$i]})) {
 2601:                 my $rem = $i%($numinrow);
 2602:                 if ($rem == 0) {
 2603:                     if ($i<@{$types}-1) {
 2604:                         if ($i > 0) { 
 2605:                             $output .= '</tr>';
 2606:                         }
 2607:                         $output .= '<tr>';
 2608:                     }
 2609:                 } elsif ($i==@{$types}-1) {
 2610:                     my $colsleft = $numinrow - $rem;
 2611:                     if ($colsleft > 1) {
 2612:                         $lastcolspan = ' colspan="'.$colsleft.'"';
 2613:                     }
 2614:                 }
 2615:                 my $check = ' ';
 2616:                 if (grep(/^\Q$types->[$i]\E$/,@currtypes)) {
 2617:                     $check = ' checked="checked" ';
 2618:                 }
 2619:                 $output .= '<td class="LC_left_item"'.$lastcolspan.'>'.
 2620:                            '<span class="LC_nobreak"><label>'.
 2621:                            '<input type="checkbox" name="inststatus" '.
 2622:                            'value="'.$types->[$i].'"'.$check.'/>'.
 2623:                            $usertypes->{$types->[$i]}.'</label></span></td>';
 2624:             }
 2625:         }
 2626:         $output .= '</tr></table>';
 2627:     }
 2628:     return $output;
 2629: }
 2630: 
 2631: sub selfcreate_canmodify {
 2632:     my ($context,$dom,$userinfo,$inst_results,$rolesarray) = @_;
 2633:     if (ref($inst_results) eq 'HASH') {
 2634:         my @inststatuses = &get_inststatuses($inst_results);
 2635:         if (@inststatuses == 0) {
 2636:             @inststatuses = ('default');
 2637:         }
 2638:         $rolesarray = \@inststatuses;
 2639:     }
 2640:     my %canmodify =
 2641:         &Apache::lonuserutils::can_modify_userinfo($context,$dom,$userinfo,
 2642:                                                    $rolesarray);
 2643:     return %canmodify;
 2644: }
 2645: 
 2646: sub get_inststatuses {
 2647:     my ($insthashref) = @_;
 2648:     my @inststatuses = ();
 2649:     if (ref($insthashref) eq 'HASH') {
 2650:         if (ref($insthashref->{'inststatus'}) eq 'ARRAY') {
 2651:             @inststatuses = @{$insthashref->{'inststatus'}};
 2652:         }
 2653:     }
 2654:     return @inststatuses;
 2655: }
 2656: 
 2657: # ================================================================= Phase Three
 2658: sub update_user_data {
 2659:     my ($r,$context,$crstype,$brcrum,$showcredits) = @_; 
 2660:     my $uhome=&Apache::lonnet::homeserver($env{'form.ccuname'},
 2661:                                           $env{'form.ccdomain'});
 2662:     # Error messages
 2663:     my $error     = '<span class="LC_error">'.&mt('Error').': ';
 2664:     my $end       = '</span><br /><br />';
 2665:     my $rtnlink   = '<a href="javascript:backPage(document.userupdate,'.
 2666:                     "'$env{'form.prevphase'}','modify')".'" />'.
 2667:                     &mt('Return to previous page').'</a>'.
 2668:                     &Apache::loncommon::end_page();
 2669:     my $now = time;
 2670:     my $title;
 2671:     if (exists($env{'form.makeuser'})) {
 2672: 	$title='Set Privileges for New User';
 2673:     } else {
 2674:         $title='Modify User Privileges';
 2675:     }
 2676:     my $newuser = 0;
 2677:     my ($jsback,$elements) = &crumb_utilities();
 2678:     my $jscript = '<script type="text/javascript">'."\n".
 2679:                   '// <![CDATA['."\n".
 2680:                   $jsback."\n".
 2681:                   '// ]]>'."\n".
 2682:                   '</script>'."\n";
 2683:     my %breadcrumb_text = &singleuser_breadcrumb($crstype);
 2684:     push (@{$brcrum},
 2685:              {href => "javascript:backPage(document.userupdate)",
 2686:               text => $breadcrumb_text{'search'},
 2687:               faq  => 282,
 2688:               bug  => 'Instructor Interface',}
 2689:              );
 2690:     if ($env{'form.prevphase'} eq 'userpicked') {
 2691:         push(@{$brcrum},
 2692:                {href => "javascript:backPage(document.userupdate,'get_user_info','select')",
 2693:                 text => $breadcrumb_text{'userpicked'},
 2694:                 faq  => 282,
 2695:                 bug  => 'Instructor Interface',});
 2696:     }
 2697:     my $helpitem = 'Course_Change_Privileges';
 2698:     if ($env{'form.action'} eq 'singlestudent') {
 2699:         $helpitem = 'Course_Add_Student';
 2700:     }
 2701:     push(@{$brcrum}, 
 2702:             {href => "javascript:backPage(document.userupdate,'$env{'form.prevphase'}','modify')",
 2703:              text => $breadcrumb_text{'modify'},
 2704:              faq  => 282,
 2705:              bug  => 'Instructor Interface',},
 2706:             {href => "/adm/createuser",
 2707:              text => "Result",
 2708:              faq  => 282,
 2709:              bug  => 'Instructor Interface',
 2710:              help => $helpitem});
 2711:     my $args = {bread_crumbs          => $brcrum,
 2712:                 bread_crumbs_component => 'User Management'};
 2713:     if ($env{'form.popup'}) {
 2714:         $args->{'no_nav_bar'} = 1;
 2715:     }
 2716:     $r->print(&Apache::loncommon::start_page($title,$jscript,$args));
 2717:     $r->print(&update_result_form($uhome));
 2718:     # Check Inputs
 2719:     if (! $env{'form.ccuname'} ) {
 2720: 	$r->print($error.&mt('No login name specified').'.'.$end.$rtnlink);
 2721: 	return;
 2722:     }
 2723:     if (  $env{'form.ccuname'} ne 
 2724: 	  &LONCAPA::clean_username($env{'form.ccuname'}) ) {
 2725: 	$r->print($error.&mt('Invalid login name.').'  '.
 2726: 		  &mt('Only letters, numbers, periods, dashes, @, and underscores are valid.').
 2727: 		  $end.$rtnlink);
 2728: 	return;
 2729:     }
 2730:     if (! $env{'form.ccdomain'}       ) {
 2731: 	$r->print($error.&mt('No domain specified').'.'.$end.$rtnlink);
 2732: 	return;
 2733:     }
 2734:     if (  $env{'form.ccdomain'} ne
 2735: 	  &LONCAPA::clean_domain($env{'form.ccdomain'}) ) {
 2736: 	$r->print($error.&mt('Invalid domain name.').'  '.
 2737: 		  &mt('Only letters, numbers, periods, dashes, and underscores are valid.').
 2738: 		  $end.$rtnlink);
 2739: 	return;
 2740:     }
 2741:     if ($uhome eq 'no_host') {
 2742:         $newuser = 1;
 2743:     }
 2744:     if (! exists($env{'form.makeuser'})) {
 2745:         # Modifying an existing user, so check the validity of the name
 2746:         if ($uhome eq 'no_host') {
 2747:             $r->print(
 2748:                 $error
 2749:                .'<p class="LC_error">'
 2750:                .&mt('Unable to determine home server for [_1] in domain [_2].',
 2751:                         '"'.$env{'form.ccuname'}.'"','"'.$env{'form.ccdomain'}.'"')
 2752:                .'</p>');
 2753:             return;
 2754:         }
 2755:     }
 2756:     # Determine authentication method and password for the user being modified
 2757:     my $amode='';
 2758:     my $genpwd='';
 2759:     if ($env{'form.login'} eq 'krb') {
 2760: 	$amode='krb';
 2761: 	$amode.=$env{'form.krbver'};
 2762: 	$genpwd=$env{'form.krbarg'};
 2763:     } elsif ($env{'form.login'} eq 'int') {
 2764: 	$amode='internal';
 2765: 	$genpwd=$env{'form.intarg'};
 2766:     } elsif ($env{'form.login'} eq 'fsys') {
 2767: 	$amode='unix';
 2768: 	$genpwd=$env{'form.fsysarg'};
 2769:     } elsif ($env{'form.login'} eq 'loc') {
 2770: 	$amode='localauth';
 2771: 	$genpwd=$env{'form.locarg'};
 2772: 	$genpwd=" " if (!$genpwd);
 2773:     } elsif (($env{'form.login'} eq 'nochange') ||
 2774:              ($env{'form.login'} eq ''        )) { 
 2775:         # There is no need to tell the user we did not change what they
 2776:         # did not ask us to change.
 2777:         # If they are creating a new user but have not specified login
 2778:         # information this will be caught below.
 2779:     } else {
 2780:             $r->print($error.&mt('Invalid login mode or password').$end.$rtnlink);
 2781:             return;
 2782:     }
 2783: 
 2784:     $r->print('<h3>'.&mt('User [_1] in domain [_2]',
 2785:                         $env{'form.ccuname'}.' ('.&Apache::loncommon::plainname($env{'form.ccuname'},
 2786:                         $env{'form.ccdomain'}).')', $env{'form.ccdomain'}).'</h3>');
 2787:     my %prog_state = &Apache::lonhtmlcommon::Create_PrgWin($r,2);
 2788: 
 2789:     my (%alerts,%rulematch,%inst_results,%curr_rules);
 2790:     my @userinfo = ('firstname','middlename','lastname','generation','permanentemail','id');
 2791:     my @usertools = ('aboutme','blog','webdav','portfolio');
 2792:     my @requestcourses = ('official','unofficial','community','textbook');
 2793:     my @requestauthor = ('requestauthor');
 2794:     my ($othertitle,$usertypes,$types) = 
 2795:         &Apache::loncommon::sorted_inst_types($env{'form.ccdomain'});
 2796:     my %canmodify_status =
 2797:         &Apache::lonuserutils::can_modify_userinfo($context,$env{'form.ccdomain'},
 2798:                                                    ['inststatus']);
 2799:     if ($env{'form.makeuser'}) {
 2800: 	$r->print('<h3>'.&mt('Creating new account.').'</h3>');
 2801:         # Check for the authentication mode and password
 2802:         if (! $amode || ! $genpwd) {
 2803: 	    $r->print($error.&mt('Invalid login mode or password').$end.$rtnlink);    
 2804: 	    return;
 2805: 	}
 2806:         # Determine desired host
 2807:         my $desiredhost = $env{'form.hserver'};
 2808:         if (lc($desiredhost) eq 'default') {
 2809:             $desiredhost = undef;
 2810:         } else {
 2811:             my %home_servers = 
 2812: 		&Apache::lonnet::get_servers($env{'form.ccdomain'},'library');
 2813:             if (! exists($home_servers{$desiredhost})) {
 2814:                 $r->print($error.&mt('Invalid home server specified').$end.$rtnlink);
 2815:                 return;
 2816:             }
 2817:         }
 2818:         # Check ID format
 2819:         my %checkhash;
 2820:         my %checks = ('id' => 1);
 2821:         %{$checkhash{$env{'form.ccuname'}.':'.$env{'form.ccdomain'}}} = (
 2822:             'newuser' => $newuser, 
 2823:             'id' => $env{'form.cid'},
 2824:         );
 2825:         if ($env{'form.cid'} ne '') {
 2826:             &Apache::loncommon::user_rule_check(\%checkhash,\%checks,\%alerts,
 2827:                                           \%rulematch,\%inst_results,\%curr_rules);
 2828:             if (ref($alerts{'id'}) eq 'HASH') {
 2829:                 if (ref($alerts{'id'}{$env{'form.ccdomain'}}) eq 'HASH') {
 2830:                     my $domdesc =
 2831:                         &Apache::lonnet::domain($env{'form.ccdomain'},'description');
 2832:                     if ($alerts{'id'}{$env{'form.ccdomain'}}{$env{'form.cid'}}) {
 2833:                         my $userchkmsg;
 2834:                         if (ref($curr_rules{$env{'form.ccdomain'}}) eq 'HASH') {
 2835:                             $userchkmsg  = 
 2836:                                 &Apache::loncommon::instrule_disallow_msg('id',
 2837:                                                                     $domdesc,1).
 2838:                                 &Apache::loncommon::user_rule_formats($env{'form.ccdomain'},
 2839:                                     $domdesc,$curr_rules{$env{'form.ccdomain'}}{'id'},'id');
 2840:                         }
 2841:                         $r->print($error.&mt('Invalid ID format').$end.
 2842:                                   $userchkmsg.$rtnlink);
 2843:                         return;
 2844:                     }
 2845:                 }
 2846:             }
 2847:         }
 2848:         &Apache::lonhtmlcommon::Increment_PrgWin($r, \%prog_state);
 2849: 	# Call modifyuser
 2850: 	my $result = &Apache::lonnet::modifyuser
 2851: 	    ($env{'form.ccdomain'},$env{'form.ccuname'},$env{'form.cid'},
 2852:              $amode,$genpwd,$env{'form.cfirstname'},
 2853:              $env{'form.cmiddlename'},$env{'form.clastname'},
 2854:              $env{'form.cgeneration'},undef,$desiredhost,
 2855:              $env{'form.cpermanentemail'});
 2856: 	$r->print(&mt('Generating user').': '.$result);
 2857:         $uhome = &Apache::lonnet::homeserver($env{'form.ccuname'},
 2858:                                                $env{'form.ccdomain'});
 2859:         my (%changeHash,%newcustom,%changed,%changedinfo);
 2860:         if ($uhome ne 'no_host') {
 2861:             if ($context eq 'domain') {
 2862:                 foreach my $name ('portfolio','author') {
 2863:                     if ($env{'form.custom_'.$name.'quota'} == 1) {
 2864:                         if ($env{'form.'.$name.'quota'} eq '') {
 2865:                             $newcustom{$name.'quota'} = 0;
 2866:                         } else {
 2867:                             $newcustom{$name.'quota'} = $env{'form.'.$name.'quota'};
 2868:                             $newcustom{$name.'quota'} =~ s/[^\d\.]//g;
 2869:                         }
 2870:                         if (&quota_admin($newcustom{$name.'quota'},\%changeHash,$name)) {
 2871:                             $changed{$name.'quota'} = 1;
 2872:                         }
 2873:                     }
 2874:                 }
 2875:                 foreach my $item (@usertools) {
 2876:                     if ($env{'form.custom'.$item} == 1) {
 2877:                         $newcustom{$item} = $env{'form.tools_'.$item};
 2878:                         $changed{$item} = &tool_admin($item,$newcustom{$item},
 2879:                                                      \%changeHash,'tools');
 2880:                     }
 2881:                 }
 2882:                 foreach my $item (@requestcourses) {
 2883:                     if ($env{'form.custom'.$item} == 1) {
 2884:                         $newcustom{$item} = $env{'form.crsreq_'.$item};
 2885:                         if ($env{'form.crsreq_'.$item} eq 'autolimit') {
 2886:                             $newcustom{$item} .= '=';
 2887:                             $env{'form.crsreq_'.$item.'_limit'} =~ s/\D+//g;
 2888:                             if ($env{'form.crsreq_'.$item.'_limit'}) {
 2889:                                 $newcustom{$item} .= $env{'form.crsreq_'.$item.'_limit'};
 2890:                             }
 2891:                         }
 2892:                         $changed{$item} = &tool_admin($item,$newcustom{$item},
 2893:                                                       \%changeHash,'requestcourses');
 2894:                     }
 2895:                 }
 2896:                 if ($env{'form.customrequestauthor'} == 1) {
 2897:                     $newcustom{'requestauthor'} = $env{'form.requestauthor'};
 2898:                     $changed{'requestauthor'} = &tool_admin('requestauthor',
 2899:                                                     $newcustom{'requestauthor'},
 2900:                                                     \%changeHash,'requestauthor');
 2901:                 }
 2902:                 if (&Apache::lonnet::allowed('cdh',$env{'request.role.domain'})) {
 2903:                     my @adds = &Apache::loncommon::get_env_multiple('form.adhocroleadd');
 2904:                     if (&adhocrole_changes(\%changeHash)) {
 2905:                         $changed{'adhocroles.'.$env{'request.role.domain'}} = $changeHash{'adhocroles.'.$env{'request.role.domain'}};
 2906:                     }
 2907:                 }
 2908:             }
 2909:             if ($canmodify_status{'inststatus'}) {
 2910:                 if (exists($env{'form.inststatus'})) {
 2911:                     my @inststatuses = &Apache::loncommon::get_env_multiple('form.inststatus');
 2912:                     if (@inststatuses > 0) {
 2913:                         $changeHash{'inststatus'} = join(',',@inststatuses);
 2914:                         $changed{'inststatus'} = $changeHash{'inststatus'};
 2915:                     }
 2916:                 }
 2917:             }
 2918:             if (keys(%changed)) {
 2919:                 foreach my $item (@userinfo) {
 2920:                     $changeHash{$item}  = $env{'form.c'.$item};
 2921:                 }
 2922:                 my $chgresult =
 2923:                      &Apache::lonnet::put('environment',\%changeHash,
 2924:                                           $env{'form.ccdomain'},$env{'form.ccuname'});
 2925:             } 
 2926:         }
 2927:         $r->print('<br />'.&mt('Home server').': '.$uhome.' '.
 2928:                   &Apache::lonnet::hostname($uhome));
 2929:     } elsif (($env{'form.login'} ne 'nochange') &&
 2930:              ($env{'form.login'} ne ''        )) {
 2931: 	# Modify user privileges
 2932:         if (! $amode || ! $genpwd) {
 2933: 	    $r->print($error.'Invalid login mode or password'.$end.$rtnlink);    
 2934: 	    return;
 2935: 	}
 2936: 	# Only allow authentication modification if the person has authority
 2937: 	if (&Apache::lonnet::allowed('mau',$env{'form.ccdomain'})) {
 2938: 	    $r->print('Modifying authentication: '.
 2939:                       &Apache::lonnet::modifyuserauth(
 2940: 		       $env{'form.ccdomain'},$env{'form.ccuname'},
 2941:                        $amode,$genpwd));
 2942:             $r->print('<br />'.&mt('Home server').': '.&Apache::lonnet::homeserver
 2943: 		  ($env{'form.ccuname'},$env{'form.ccdomain'}));
 2944: 	} else {
 2945: 	    # Okay, this is a non-fatal error.
 2946: 	    $r->print($error.&mt('You do not have the authority to modify this users authentication information.').$end);    
 2947: 	}
 2948:     }
 2949:     $r->rflush(); # Finish display of header before time consuming actions start
 2950:     &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state);
 2951:     ##
 2952:     my (@userroles,%userupdate,$cnum,$cdom,$defaultcredits,%namechanged);
 2953:     if ($context eq 'course') {
 2954:         ($cnum,$cdom) =
 2955:             &Apache::lonuserutils::get_course_identity();
 2956:         $crstype = &Apache::loncommon::course_type($cdom.'_'.$cnum);
 2957:         if ($showcredits) {
 2958:            $defaultcredits = &Apache::lonuserutils::get_defaultcredits($cdom,$cnum);
 2959:         }
 2960:     }
 2961:     if (! $env{'form.makeuser'} ) {
 2962:         # Check for need to change
 2963:         my %userenv = &Apache::lonnet::get
 2964:             ('environment',['firstname','middlename','lastname','generation',
 2965:              'id','permanentemail','portfolioquota','authorquota','inststatus',
 2966:              'tools.aboutme','tools.blog','tools.webdav','tools.portfolio',
 2967:              'requestcourses.official','requestcourses.unofficial',
 2968:              'requestcourses.community','requestcourses.textbook',
 2969:              'reqcrsotherdom.official','reqcrsotherdom.unofficial',
 2970:              'reqcrsotherdom.community','reqcrsotherdom.textbook',
 2971:              'requestauthor','adhocroles.'.$env{'request.role.domain'}],
 2972:               $env{'form.ccdomain'},$env{'form.ccuname'});
 2973:         my ($tmp) = keys(%userenv);
 2974:         if ($tmp =~ /^(con_lost|error)/i) { 
 2975:             %userenv = ();
 2976:         }
 2977:         my $no_forceid_alert;
 2978:         # Check to see if user information can be changed
 2979:         my %domconfig =
 2980:             &Apache::lonnet::get_dom('configuration',['usermodification'],
 2981:                                      $env{'form.ccdomain'});
 2982:         my @statuses = ('active','future');
 2983:         my %roles = &Apache::lonnet::get_my_roles($env{'form.ccuname'},$env{'form.ccdomain'},'userroles',\@statuses,undef,$env{'request.role.domain'});
 2984:         my ($auname,$audom);
 2985:         if ($context eq 'author') {
 2986:             $auname = $env{'user.name'};
 2987:             $audom = $env{'user.domain'};     
 2988:         }
 2989:         foreach my $item (keys(%roles)) {
 2990:             my ($rolenum,$roledom,$role) = split(/:/,$item,-1);
 2991:             if ($context eq 'course') {
 2992:                 if ($cnum ne '' && $cdom ne '') {
 2993:                     if ($rolenum eq $cnum && $roledom eq $cdom) {
 2994:                         if (!grep(/^\Q$role\E$/,@userroles)) {
 2995:                             push(@userroles,$role);
 2996:                         }
 2997:                     }
 2998:                 }
 2999:             } elsif ($context eq 'author') {
 3000:                 if ($rolenum eq $auname && $roledom eq $audom) {
 3001:                     if (!grep(/^\Q$role\E$/,@userroles)) { 
 3002:                         push(@userroles,$role);
 3003:                     }
 3004:                 }
 3005:             }
 3006:         }
 3007:         if ($env{'form.action'} eq 'singlestudent') {
 3008:             if (!grep(/^st$/,@userroles)) {
 3009:                 push(@userroles,'st');
 3010:             }
 3011:         } else {
 3012:             # Check for course or co-author roles being activated or re-enabled
 3013:             if ($context eq 'author' || $context eq 'course') {
 3014:                 foreach my $key (keys(%env)) {
 3015:                     if ($context eq 'author') {
 3016:                         if ($key=~/^form\.act_\Q$audom\E_\Q$auname\E_([^_]+)/) {
 3017:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 3018:                                 push(@userroles,$1);
 3019:                             }
 3020:                         } elsif ($key =~/^form\.ren\:\Q$audom\E\/\Q$auname\E_([^_]+)/) {
 3021:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 3022:                                 push(@userroles,$1);
 3023:                             }
 3024:                         }
 3025:                     } elsif ($context eq 'course') {
 3026:                         if ($key=~/^form\.act_\Q$cdom\E_\Q$cnum\E_([^_]+)/) {
 3027:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 3028:                                 push(@userroles,$1);
 3029:                             }
 3030:                         } elsif ($key =~/^form\.ren\:\Q$cdom\E\/\Q$cnum\E(\/?\w*)_([^_]+)/) {
 3031:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 3032:                                 push(@userroles,$1);
 3033:                             }
 3034:                         }
 3035:                     }
 3036:                 }
 3037:             }
 3038:         }
 3039:         #Check to see if we can change personal data for the user 
 3040:         my (@mod_disallowed,@longroles);
 3041:         foreach my $role (@userroles) {
 3042:             if ($role eq 'cr') {
 3043:                 push(@longroles,'Custom');
 3044:             } else {
 3045:                 push(@longroles,&Apache::lonnet::plaintext($role,$crstype)); 
 3046:             }
 3047:         }
 3048:         my %canmodify = &Apache::lonuserutils::can_modify_userinfo($context,$env{'form.ccdomain'},\@userinfo,\@userroles);
 3049:         foreach my $item (@userinfo) {
 3050:             # Strip leading and trailing whitespace
 3051:             $env{'form.c'.$item} =~ s/(\s+$|^\s+)//g;
 3052:             if (!$canmodify{$item}) {
 3053:                 if (defined($env{'form.c'.$item})) {
 3054:                     if ($env{'form.c'.$item} ne $userenv{$item}) {
 3055:                         push(@mod_disallowed,$item);
 3056:                     }
 3057:                 }
 3058:                 $env{'form.c'.$item} = $userenv{$item};
 3059:             }
 3060:         }
 3061:         # Check to see if we can change the Student/Employee ID
 3062:         my $forceid = $env{'form.forceid'};
 3063:         my $recurseid = $env{'form.recurseid'};
 3064:         my (%alerts,%rulematch,%idinst_results,%curr_rules,%got_rules);
 3065:         my %uidhash = &Apache::lonnet::idrget($env{'form.ccdomain'},
 3066:                                             $env{'form.ccuname'});
 3067:         if (($uidhash{$env{'form.ccuname'}}) && 
 3068:             ($uidhash{$env{'form.ccuname'}}!~/error\:/) && 
 3069:             (!$forceid)) {
 3070:             if ($env{'form.cid'} ne $uidhash{$env{'form.ccuname'}}) {
 3071:                 $env{'form.cid'} = $userenv{'id'};
 3072:                 $no_forceid_alert = &mt('New student/employee ID does not match existing ID for this user.')
 3073:                                    .'<br />'
 3074:                                    .&mt("Change is not permitted without checking the 'Force ID change' checkbox on the previous page.")
 3075:                                    .'<br />'."\n";
 3076:             }
 3077:         }
 3078:         if ($env{'form.cid'} ne $userenv{'id'}) {
 3079:             my $checkhash;
 3080:             my $checks = { 'id' => 1 };
 3081:             $checkhash->{$env{'form.ccuname'}.':'.$env{'form.ccdomain'}} = 
 3082:                    { 'newuser' => $newuser,
 3083:                      'id'  => $env{'form.cid'}, 
 3084:                    };
 3085:             &Apache::loncommon::user_rule_check($checkhash,$checks,
 3086:                 \%alerts,\%rulematch,\%idinst_results,\%curr_rules,\%got_rules);
 3087:             if (ref($alerts{'id'}) eq 'HASH') {
 3088:                 if (ref($alerts{'id'}{$env{'form.ccdomain'}}) eq 'HASH') {
 3089:                    $env{'form.cid'} = $userenv{'id'};
 3090:                 }
 3091:             }
 3092:         }
 3093:         my (%quotachanged,%oldquota,%newquota,%olddefquota,%newdefquota, 
 3094:             $oldinststatus,$newinststatus,%oldisdefault,%newisdefault,%oldsettings,
 3095:             %oldsettingstext,%newsettings,%newsettingstext,@disporder,
 3096:             %oldsettingstatus,%newsettingstatus);
 3097:         @disporder = ('inststatus');
 3098:         if ($env{'request.role.domain'} eq $env{'form.ccdomain'}) {
 3099:             push(@disporder,'requestcourses','requestauthor');
 3100:         } else {
 3101:             push(@disporder,'reqcrsotherdom');
 3102:         }
 3103:         push(@disporder,('quota','tools'));
 3104:         $oldinststatus = $userenv{'inststatus'};
 3105:         foreach my $name ('portfolio','author') {
 3106:             ($olddefquota{$name},$oldsettingstatus{$name}) = 
 3107:                 &Apache::loncommon::default_quota($env{'form.ccdomain'},$oldinststatus,$name);
 3108:             ($newdefquota{$name},$newsettingstatus{$name}) = ($olddefquota{$name},$oldsettingstatus{$name});
 3109:         }
 3110:         push(@disporder,'adhocroles');
 3111:         my %canshow;
 3112:         if (&Apache::lonnet::allowed('mpq',$env{'form.ccdomain'})) {
 3113:             $canshow{'quota'} = 1;
 3114:         }
 3115:         if (&Apache::lonnet::allowed('mut',$env{'form.ccdomain'})) {
 3116:             $canshow{'tools'} = 1;
 3117:         }
 3118:         if (&Apache::lonnet::allowed('ccc',$env{'form.ccdomain'})) {
 3119:             $canshow{'requestcourses'} = 1;
 3120:         } elsif (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) {
 3121:             $canshow{'reqcrsotherdom'} = 1;
 3122:         }
 3123:         if (&Apache::lonnet::allowed('mau',$env{'form.ccdomain'})) {
 3124:             $canshow{'inststatus'} = 1;
 3125:         }
 3126:         if (&Apache::lonnet::allowed('cau',$env{'form.ccdomain'})) {
 3127:             $canshow{'requestauthor'} = 1;
 3128:         }
 3129:         if (&Apache::lonnet::allowed('cdh',$env{'request.role.domain'})) {
 3130:             $canshow{'adhocroles'} = 1;
 3131:         }
 3132:         my (%changeHash,%changed);
 3133:         if ($oldinststatus eq '') {
 3134:             $oldsettings{'inststatus'} = $othertitle; 
 3135:         } else {
 3136:             if (ref($usertypes) eq 'HASH') {
 3137:                 $oldsettings{'inststatus'} = join(', ',map{ $usertypes->{ &unescape($_) }; } (split(/:/,$userenv{'inststatus'})));
 3138:             } else {
 3139:                 $oldsettings{'inststatus'} = join(', ',map{ &unescape($_); } (split(/:/,$userenv{'inststatus'})));
 3140:             }
 3141:         }
 3142:         $changeHash{'inststatus'} = $userenv{'inststatus'};
 3143:         if ($canmodify_status{'inststatus'}) {
 3144:             $canshow{'inststatus'} = 1;
 3145:             if (exists($env{'form.inststatus'})) {
 3146:                 my @inststatuses = &Apache::loncommon::get_env_multiple('form.inststatus');
 3147:                 if (@inststatuses > 0) {
 3148:                     $newinststatus = join(':',map { &escape($_); } @inststatuses);
 3149:                     $changeHash{'inststatus'} = $newinststatus;
 3150:                     if ($newinststatus ne $oldinststatus) {
 3151:                         $changed{'inststatus'} = $newinststatus;
 3152:                         foreach my $name ('portfolio','author') {
 3153:                             ($newdefquota{$name},$newsettingstatus{$name}) =
 3154:                                 &Apache::loncommon::default_quota($env{'form.ccdomain'},$newinststatus,$name);
 3155:                         }
 3156:                     }
 3157:                     if (ref($usertypes) eq 'HASH') {
 3158:                         $newsettings{'inststatus'} = join(', ',map{ $usertypes->{$_}; } (@inststatuses)); 
 3159:                     } else {
 3160:                         $newsettings{'inststatus'} = join(', ',@inststatuses);
 3161:                     }
 3162:                 }
 3163:             } else {
 3164:                 $newinststatus = '';
 3165:                 $changeHash{'inststatus'} = $newinststatus;
 3166:                 $newsettings{'inststatus'} = $othertitle;
 3167:                 if ($newinststatus ne $oldinststatus) {
 3168:                     $changed{'inststatus'} = $changeHash{'inststatus'};
 3169:                     foreach my $name ('portfolio','author') {
 3170:                         ($newdefquota{$name},$newsettingstatus{$name}) =
 3171:                             &Apache::loncommon::default_quota($env{'form.ccdomain'},$newinststatus,$name);
 3172:                     }
 3173:                 }
 3174:             }
 3175:         } elsif ($context ne 'selfcreate') {
 3176:             $canshow{'inststatus'} = 1;
 3177:             $newsettings{'inststatus'} = $oldsettings{'inststatus'};
 3178:         }
 3179:         foreach my $name ('portfolio','author') {
 3180:             $changeHash{$name.'quota'} = $userenv{$name.'quota'};
 3181:         }
 3182:         if ($context eq 'domain') {
 3183:             foreach my $name ('portfolio','author') {
 3184:                 if ($userenv{$name.'quota'} ne '') {
 3185:                     $oldquota{$name} = $userenv{$name.'quota'};
 3186:                     if ($env{'form.custom_'.$name.'quota'} == 1) {
 3187:                         if ($env{'form.'.$name.'quota'} eq '') {
 3188:                             $newquota{$name} = 0;
 3189:                         } else {
 3190:                             $newquota{$name} = $env{'form.'.$name.'quota'};
 3191:                             $newquota{$name} =~ s/[^\d\.]//g;
 3192:                         }
 3193:                         if ($newquota{$name} != $oldquota{$name}) {
 3194:                             if (&quota_admin($newquota{$name},\%changeHash,$name)) {
 3195:                                 $changed{$name.'quota'} = 1;
 3196:                             }
 3197:                         }
 3198:                     } else {
 3199:                         if (&quota_admin('',\%changeHash,$name)) {
 3200:                             $changed{$name.'quota'} = 1;
 3201:                             $newquota{$name} = $newdefquota{$name};
 3202:                             $newisdefault{$name} = 1;
 3203:                         }
 3204:                     }
 3205:                 } else {
 3206:                     $oldisdefault{$name} = 1;
 3207:                     $oldquota{$name} = $olddefquota{$name};
 3208:                     if ($env{'form.custom_'.$name.'quota'} == 1) {
 3209:                         if ($env{'form.'.$name.'quota'} eq '') {
 3210:                             $newquota{$name} = 0;
 3211:                         } else {
 3212:                             $newquota{$name} = $env{'form.'.$name.'quota'};
 3213:                             $newquota{$name} =~ s/[^\d\.]//g;
 3214:                         }
 3215:                         if (&quota_admin($newquota{$name},\%changeHash,$name)) {
 3216:                             $changed{$name.'quota'} = 1;
 3217:                         }
 3218:                     } else {
 3219:                         $newquota{$name} = $newdefquota{$name};
 3220:                         $newisdefault{$name} = 1;
 3221:                     }
 3222:                 }
 3223:                 if ($oldisdefault{$name}) {
 3224:                     $oldsettingstext{'quota'}{$name} = &get_defaultquota_text($oldsettingstatus{$name});
 3225:                 }  else {
 3226:                     $oldsettingstext{'quota'}{$name} = &mt('custom quota: [_1] MB',$oldquota{$name});
 3227:                 }
 3228:                 if ($newisdefault{$name}) {
 3229:                     $newsettingstext{'quota'}{$name} = &get_defaultquota_text($newsettingstatus{$name});
 3230:                 } else {
 3231:                     $newsettingstext{'quota'}{$name} = &mt('custom quota: [_1] MB',$newquota{$name});
 3232:                 }
 3233:             }
 3234:             &tool_changes('tools',\@usertools,\%oldsettings,\%oldsettingstext,\%userenv,
 3235:                           \%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3236:             if ($env{'form.ccdomain'} eq $env{'request.role.domain'}) {
 3237:                 &tool_changes('requestcourses',\@requestcourses,\%oldsettings,\%oldsettingstext,
 3238:                               \%userenv,\%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3239:                 &tool_changes('requestauthor',\@requestauthor,\%oldsettings,\%oldsettingstext,
 3240:                               \%userenv,\%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3241:             } else {
 3242:                 &tool_changes('reqcrsotherdom',\@requestcourses,\%oldsettings,\%oldsettingstext,
 3243:                               \%userenv,\%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3244:             }
 3245:             if ($userenv{'adhocroles.'.$env{'request.role.domain'}}) {
 3246:                 $changeHash{'adhocroles.'.$env{'request.role.domain'}} = $userenv{'adhocroles.'.$env{'request.role.domain'}};
 3247:             }
 3248:             if (&adhocrole_changes(\%changeHash,\%userenv)) {
 3249:                 $changed{'adhocroles'} = 1;
 3250:                 $oldsettings{'adhocroles'} = $userenv{'adhocroles.'.$env{'request.role.domain'}};
 3251:                 $newsettings{'adhocroles'} = $changeHash{'adhocroles.'.$env{'request.role.domain'}};
 3252:             }
 3253:         }
 3254:         foreach my $item (@userinfo) {
 3255:             if ($env{'form.c'.$item} ne $userenv{$item}) {
 3256:                 $namechanged{$item} = 1;
 3257:             }
 3258:         }
 3259:         foreach my $name ('portfolio','author') {
 3260:             $oldsettings{'quota'}{$name} = &mt('[_1] MB',$oldquota{$name});
 3261:             $newsettings{'quota'}{$name} = &mt('[_1] MB',$newquota{$name});
 3262:         }
 3263:         if ((keys(%namechanged) > 0) || (keys(%changed) > 0)) {
 3264:             my ($chgresult,$namechgresult);
 3265:             if (keys(%changed) > 0) {
 3266:                 $chgresult = 
 3267:                     &Apache::lonnet::put('environment',\%changeHash,
 3268:                                   $env{'form.ccdomain'},$env{'form.ccuname'});
 3269:                 if ($chgresult eq 'ok') {
 3270:                     if (($env{'user.name'} eq $env{'form.ccuname'}) &&
 3271:                         ($env{'user.domain'} eq $env{'form.ccdomain'})) {
 3272:                         my %newenvhash;
 3273:                         foreach my $key (keys(%changed)) {
 3274:                             if (($key eq 'official') || ($key eq 'unofficial')
 3275:                                 || ($key eq 'community') || ($key eq 'textbook')) {
 3276:                                 $newenvhash{'environment.requestcourses.'.$key} =
 3277:                                     $changeHash{'requestcourses.'.$key};
 3278:                                 if ($changeHash{'requestcourses.'.$key}) {
 3279:                                     $newenvhash{'environment.canrequest.'.$key} = 1;
 3280:                                 } else {
 3281:                                     $newenvhash{'environment.canrequest.'.$key} =
 3282:           &Apache::lonnet::usertools_access($env{'user.name'},$env{'user.domain'},
 3283:                                             $key,'reload','requestcourses');
 3284:                                 }
 3285:                             } elsif ($key eq 'requestauthor') {
 3286:                                 $newenvhash{'environment.'.$key} = $changeHash{$key};
 3287:                                 if ($changeHash{$key}) {
 3288:                                     $newenvhash{'environment.canrequest.author'} = 1;
 3289:                                 } else {
 3290:                                     $newenvhash{'environment.canrequest.author'} =
 3291:           &Apache::lonnet::usertools_access($env{'user.name'},$env{'user.domain'},
 3292:                                             $key,'reload','requestauthor');
 3293:                                 }
 3294:                             } elsif ($key eq 'adhocroles') {
 3295:                                 $newenvhash{'adhocroles.'.$env{'request.role.domain'}} =
 3296:                                     $changeHash{'adhocroles.'.$env{'request.role.domain'}};
 3297:                             } elsif ($key ne 'quota') {
 3298:                                 $newenvhash{'environment.tools.'.$key} = 
 3299:                                     $changeHash{'tools.'.$key};
 3300:                                 if ($changeHash{'tools.'.$key} ne '') {
 3301:                                     $newenvhash{'environment.availabletools.'.$key} =
 3302:                                         $changeHash{'tools.'.$key};
 3303:                                 } else {
 3304:                                     $newenvhash{'environment.availabletools.'.$key} =
 3305:           &Apache::lonnet::usertools_access($env{'user.name'},$env{'user.domain'},
 3306:           $key,'reload','tools');
 3307:                                 }
 3308:                             }
 3309:                         }
 3310:                         if (keys(%newenvhash)) {
 3311:                             &Apache::lonnet::appenv(\%newenvhash);
 3312:                         }
 3313:                     }
 3314:                 }
 3315:             }
 3316:             if (keys(%namechanged) > 0) {
 3317:                 foreach my $field (@userinfo) {
 3318:                     $changeHash{$field}  = $env{'form.c'.$field};
 3319:                 }
 3320: # Make the change
 3321:                 $namechgresult =
 3322:                     &Apache::lonnet::modifyuser($env{'form.ccdomain'},
 3323:                         $env{'form.ccuname'},$changeHash{'id'},undef,undef,
 3324:                         $changeHash{'firstname'},$changeHash{'middlename'},
 3325:                         $changeHash{'lastname'},$changeHash{'generation'},
 3326:                         $changeHash{'id'},undef,$changeHash{'permanentemail'},undef,\@userinfo);
 3327:                 %userupdate = (
 3328:                                lastname   => $env{'form.clastname'},
 3329:                                middlename => $env{'form.cmiddlename'},
 3330:                                firstname  => $env{'form.cfirstname'},
 3331:                                generation => $env{'form.cgeneration'},
 3332:                                id         => $env{'form.cid'},
 3333:                              );
 3334:             }
 3335:             if (((keys(%namechanged) > 0) && $namechgresult eq 'ok') || 
 3336:                 ((keys(%changed) > 0) && $chgresult eq 'ok')) {
 3337:             # Tell the user we changed the name
 3338:                 &display_userinfo($r,1,\@disporder,\%canshow,\@requestcourses,
 3339:                                   \@usertools,\@requestauthor,\%userenv,\%changed,\%namechanged,
 3340:                                   \%oldsettings, \%oldsettingstext,\%newsettings,
 3341:                                   \%newsettingstext);
 3342:                 if ($env{'form.cid'} ne $userenv{'id'}) {
 3343:                     &Apache::lonnet::idput($env{'form.ccdomain'},
 3344:                          {$env{'form.ccuname'} => $env{'form.cid'}});
 3345:                     if (($recurseid) &&
 3346:                         (&Apache::lonnet::allowed('mau',$env{'form.ccdomain'}))) {
 3347:                         my $idresult = 
 3348:                             &Apache::lonuserutils::propagate_id_change(
 3349:                                 $env{'form.ccuname'},$env{'form.ccdomain'},
 3350:                                 \%userupdate);
 3351:                         $r->print('<br />'.$idresult.'<br />');
 3352:                     }
 3353:                 }
 3354:                 if (($env{'form.ccdomain'} eq $env{'user.domain'}) && 
 3355:                     ($env{'form.ccuname'} eq $env{'user.name'})) {
 3356:                     my %newenvhash;
 3357:                     foreach my $key (keys(%changeHash)) {
 3358:                         $newenvhash{'environment.'.$key} = $changeHash{$key};
 3359:                     }
 3360:                     &Apache::lonnet::appenv(\%newenvhash);
 3361:                 }
 3362:             } else { # error occurred
 3363:                 $r->print(
 3364:                     '<p class="LC_error">'
 3365:                    .&mt('Unable to successfully change environment for [_1] in domain [_2].',
 3366:                             '"'.$env{'form.ccuname'}.'"',
 3367:                             '"'.$env{'form.ccdomain'}.'"')
 3368:                    .'</p>');
 3369:             }
 3370:         } else { # End of if ($env ... ) logic
 3371:             # They did not want to change the users name, quota, tool availability,
 3372:             # or ability to request creation of courses, 
 3373:             # but we can still tell them what the name and quota and availabilities are  
 3374:             &display_userinfo($r,undef,\@disporder,\%canshow,\@requestcourses,
 3375:                               \@usertools,\@requestauthor,\%userenv,\%changed,\%namechanged,\%oldsettings,
 3376:                               \%oldsettingstext,\%newsettings,\%newsettingstext);
 3377:         }
 3378:         if (@mod_disallowed) {
 3379:             my ($rolestr,$contextname);
 3380:             if (@longroles > 0) {
 3381:                 $rolestr = join(', ',@longroles);
 3382:             } else {
 3383:                 $rolestr = &mt('No roles');
 3384:             }
 3385:             if ($context eq 'course') {
 3386:                 $contextname = 'course';
 3387:             } elsif ($context eq 'author') {
 3388:                 $contextname = 'co-author';
 3389:             }
 3390:             $r->print(&mt('The following fields were not updated: ').'<ul>');
 3391:             my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
 3392:             foreach my $field (@mod_disallowed) {
 3393:                 $r->print('<li>'.$fieldtitles{$field}.'</li>'."\n"); 
 3394:             }
 3395:             $r->print('</ul>');
 3396:             if (@mod_disallowed == 1) {
 3397:                 $r->print(&mt("You do not have the authority to change this field given the user's current set of active/future $contextname roles:"));
 3398:             } else {
 3399:                 $r->print(&mt("You do not have the authority to change these fields given the user's current set of active/future $contextname roles:"));
 3400:             }
 3401:             my $helplink = 'javascript:helpMenu('."'display'".')';
 3402:             $r->print('<span class="LC_cusr_emph">'.$rolestr.'</span><br />'
 3403:                      .&mt('Please contact your [_1]helpdesk[_2] for more information.'
 3404:                          ,'<a href="'.$helplink.'">','</a>')
 3405:                       .'<br />');
 3406:         }
 3407:         $r->print('<span class="LC_warning">'
 3408:                   .$no_forceid_alert
 3409:                   .&Apache::lonuserutils::print_namespacing_alerts($env{'form.ccdomain'},\%alerts,\%curr_rules)
 3410:                   .'</span>');
 3411:     }
 3412:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 3413:     if ($env{'form.action'} eq 'singlestudent') {
 3414:         &enroll_single_student($r,$uhome,$amode,$genpwd,$now,$newuser,$context,
 3415:                                $crstype,$showcredits,$defaultcredits);
 3416:         my $linktext = ($crstype eq 'Community' ?
 3417:             &mt('Enroll Another Member') : &mt('Enroll Another Student'));
 3418:         $r->print(
 3419:             &Apache::lonhtmlcommon::actionbox([
 3420:                 '<a href="javascript:backPage(document.userupdate)">'
 3421:                .($crstype eq 'Community' ? 
 3422:                     &mt('Enroll Another Member') : &mt('Enroll Another Student'))
 3423:                .'</a>']));
 3424:     } else {
 3425:         my @rolechanges = &update_roles($r,$context,$showcredits);
 3426:         if (keys(%namechanged) > 0) {
 3427:             if ($context eq 'course') {
 3428:                 if (@userroles > 0) {
 3429:                     if ((@rolechanges == 0) || 
 3430:                         (!(grep(/^st$/,@rolechanges)))) {
 3431:                         if (grep(/^st$/,@userroles)) {
 3432:                             my $classlistupdated =
 3433:                                 &Apache::lonuserutils::update_classlist($cdom,
 3434:                                               $cnum,$env{'form.ccdomain'},
 3435:                                        $env{'form.ccuname'},\%userupdate);
 3436:                         }
 3437:                     }
 3438:                 }
 3439:             }
 3440:         }
 3441:         my $userinfo = &Apache::loncommon::plainname($env{'form.ccuname'},
 3442:                                                      $env{'form.ccdomain'});
 3443:         if ($env{'form.popup'}) {
 3444:             $r->print('<p><a href="javascript:window.close()">'.&mt('Close window').'</a></p>');
 3445:         } else {
 3446:             $r->print('<br />'.&Apache::lonhtmlcommon::actionbox(['<a href="javascript:backPage(document.userupdate,'."'$env{'form.prevphase'}','modify'".')">'
 3447:                      .&mt('Modify this user: [_1]','<span class="LC_cusr_emph">'.$env{'form.ccuname'}.':'.$env{'form.ccdomain'}.' ('.$userinfo.')</span>').'</a>',
 3448:                      '<a href="javascript:backPage(document.userupdate)">'.&mt('Create/Modify Another User').'</a>']));
 3449:         }
 3450:     }
 3451: }
 3452: 
 3453: sub display_userinfo {
 3454:     my ($r,$changed,$order,$canshow,$requestcourses,$usertools,$requestauthor,
 3455:         $userenv,$changedhash,$namechangedhash,$oldsetting,$oldsettingtext,
 3456:         $newsetting,$newsettingtext) = @_;
 3457:     return unless (ref($order) eq 'ARRAY' &&
 3458:                    ref($canshow) eq 'HASH' && 
 3459:                    ref($requestcourses) eq 'ARRAY' && 
 3460:                    ref($requestauthor) eq 'ARRAY' &&
 3461:                    ref($usertools) eq 'ARRAY' && 
 3462:                    ref($userenv) eq 'HASH' &&
 3463:                    ref($changedhash) eq 'HASH' &&
 3464:                    ref($oldsetting) eq 'HASH' &&
 3465:                    ref($oldsettingtext) eq 'HASH' &&
 3466:                    ref($newsetting) eq 'HASH' &&
 3467:                    ref($newsettingtext) eq 'HASH');
 3468:     my %lt=&Apache::lonlocal::texthash(
 3469:          'ui'             => 'User Information',
 3470:          'uic'            => 'User Information Changed',
 3471:          'firstname'      => 'First Name',
 3472:          'middlename'     => 'Middle Name',
 3473:          'lastname'       => 'Last Name',
 3474:          'generation'     => 'Generation',
 3475:          'id'             => 'Student/Employee ID',
 3476:          'permanentemail' => 'Permanent e-mail address',
 3477:          'portfolioquota' => 'Disk space allocated to portfolio files',
 3478:          'authorquota'    => 'Disk space allocated to Authoring Space',
 3479:          'blog'           => 'Blog Availability',
 3480:          'webdav'         => 'WebDAV Availability',
 3481:          'aboutme'        => 'Personal Information Page Availability',
 3482:          'portfolio'      => 'Portfolio Availability',
 3483:          'official'       => 'Can Request Official Courses',
 3484:          'unofficial'     => 'Can Request Unofficial Courses',
 3485:          'community'      => 'Can Request Communities',
 3486:          'textbook'       => 'Can Request Textbook Courses',
 3487:          'requestauthor'  => 'Can Request Author Role',
 3488:          'adhocroles'     => 'Ad Hoc Roles Selectable via Helpdesk Role',
 3489:          'inststatus'     => "Affiliation",
 3490:          'prvs'           => 'Previous Value:',
 3491:          'chto'           => 'Changed To:'
 3492:     );
 3493:     if ($changed) {
 3494:         $r->print('<h3>'.$lt{'uic'}.'</h3>'.
 3495:                 &Apache::loncommon::start_data_table().
 3496:                 &Apache::loncommon::start_data_table_header_row());
 3497:         $r->print("<th>&nbsp;</th>\n");
 3498:         $r->print('<th><b>'.$lt{'prvs'}.'</b></th>');
 3499:         $r->print('<th><span class="LC_nobreak"><b>'.$lt{'chto'}.'</b></span></th>');
 3500:         $r->print(&Apache::loncommon::end_data_table_header_row());
 3501:         my @userinfo = ('firstname','middlename','lastname','generation','permanentemail','id');
 3502: 
 3503:         foreach my $item (@userinfo) {
 3504:             my $value = $env{'form.c'.$item};
 3505:             #show changes only:
 3506:             unless ($value eq $userenv->{$item}){
 3507:                 $r->print(&Apache::loncommon::start_data_table_row());
 3508:                 $r->print("<td>$lt{$item}</td>\n");
 3509:                 $r->print("<td>".$userenv->{$item}."</td>\n");
 3510:                 $r->print("<td>$value </td>\n");
 3511:                 $r->print(&Apache::loncommon::end_data_table_row());
 3512:             }
 3513:         }
 3514:         foreach my $entry (@{$order}) {
 3515:             if ($canshow->{$entry}) {
 3516:                 if (($entry eq 'requestcourses') || ($entry eq 'reqcrsotherdom') || ($entry eq 'requestauthor')) {
 3517:                     my @items;
 3518:                     if ($entry eq 'requestauthor') {
 3519:                         @items = ($entry);
 3520:                     } else {
 3521:                         @items = @{$requestcourses};
 3522:                     }
 3523:                     foreach my $item (@items) {
 3524:                         if (($newsetting->{$item} ne $oldsetting->{$item}) || 
 3525:                             ($newsettingtext->{$item} ne $oldsettingtext->{$item})) {
 3526:                             $r->print(&Apache::loncommon::start_data_table_row()."\n");  
 3527:                             $r->print("<td>$lt{$item}</td>\n");
 3528:                             $r->print("<td>".$oldsetting->{$item});
 3529:                             if ($oldsettingtext->{$item}) {
 3530:                                 if ($oldsetting->{$item}) {
 3531:                                     $r->print(' -- ');
 3532:                                 }
 3533:                                 $r->print($oldsettingtext->{$item});
 3534:                             }
 3535:                             $r->print("</td>\n");
 3536:                             $r->print("<td>".$newsetting->{$item});
 3537:                             if ($newsettingtext->{$item}) {
 3538:                                 if ($newsetting->{$item}) {
 3539:                                     $r->print(' -- ');
 3540:                                 }
 3541:                                 $r->print($newsettingtext->{$item});
 3542:                             }
 3543:                             $r->print("</td>\n");
 3544:                             $r->print(&Apache::loncommon::end_data_table_row()."\n");
 3545:                         }
 3546:                     }
 3547:                 } elsif ($entry eq 'tools') {
 3548:                     foreach my $item (@{$usertools}) {
 3549:                         if ($newsetting->{$item} ne $oldsetting->{$item}) {
 3550:                             $r->print(&Apache::loncommon::start_data_table_row()."\n");
 3551:                             $r->print("<td>$lt{$item}</td>\n");
 3552:                             $r->print("<td>".$oldsetting->{$item}.' '.$oldsettingtext->{$item}."</td>\n");
 3553:                             $r->print("<td>".$newsetting->{$item}.' '.$newsettingtext->{$item}."</td>\n");
 3554:                             $r->print(&Apache::loncommon::end_data_table_row()."\n");
 3555:                         }
 3556:                     }
 3557:                 } elsif ($entry eq 'quota') {
 3558:                     if ((ref($oldsetting->{$entry}) eq 'HASH') && (ref($oldsettingtext->{$entry}) eq 'HASH') &&
 3559:                         (ref($newsetting->{$entry}) eq 'HASH') && (ref($newsettingtext->{$entry}) eq 'HASH')) {
 3560:                         foreach my $name ('portfolio','author') {
 3561:                             if ($newsetting->{$entry}->{$name} ne $oldsetting->{$entry}->{$name}) {
 3562:                                 $r->print(&Apache::loncommon::start_data_table_row()."\n");
 3563:                                 $r->print("<td>$lt{$name.$entry}</td>\n");
 3564:                                 $r->print("<td>".$oldsettingtext->{$entry}->{$name}."</td>\n");
 3565:                                 $r->print("<td>".$newsettingtext->{$entry}->{$name}."</td>\n");
 3566:                                 $r->print(&Apache::loncommon::end_data_table_row()."\n");
 3567:                             }
 3568:                         }
 3569:                     }
 3570:                 } else {
 3571:                     if ($newsetting->{$entry} ne $oldsetting->{$entry}) {
 3572:                         $r->print(&Apache::loncommon::start_data_table_row()."\n");
 3573:                         $r->print("<td>$lt{$entry}</td>\n");
 3574:                         $r->print("<td>".$oldsetting->{$entry}.' '.$oldsettingtext->{$entry}."</td>\n");
 3575:                         $r->print("<td>".$newsetting->{$entry}.' '.$newsettingtext->{$entry}."</td>\n");
 3576:                         $r->print(&Apache::loncommon::end_data_table_row()."\n");
 3577:                     }
 3578:                 }
 3579:             }
 3580:         }
 3581:         $r->print(&Apache::loncommon::end_data_table().'<br />');
 3582:     } else {
 3583:         $r->print('<h3>'.$lt{'ui'}.'</h3>'.
 3584:                   '<p>'.&mt('No changes made to user information').'</p>');
 3585:     }
 3586:     return;
 3587: }
 3588: 
 3589: sub tool_changes {
 3590:     my ($context,$usertools,$oldaccess,$oldaccesstext,$userenv,$changeHash,
 3591:         $changed,$newaccess,$newaccesstext) = @_;
 3592:     if (!((ref($usertools) eq 'ARRAY') && (ref($oldaccess) eq 'HASH') &&
 3593:           (ref($oldaccesstext) eq 'HASH') && (ref($userenv) eq 'HASH') &&
 3594:           (ref($changeHash) eq 'HASH') && (ref($changed) eq 'HASH') &&
 3595:           (ref($newaccess) eq 'HASH') && (ref($newaccesstext) eq 'HASH'))) {
 3596:         return;
 3597:     }
 3598:     my %reqdisplay = &requestchange_display();
 3599:     if ($context eq 'reqcrsotherdom') {
 3600:         my @options = ('approval','validate','autolimit');
 3601:         my $optregex = join('|',@options);
 3602:         my $cdom = $env{'request.role.domain'};
 3603:         foreach my $tool (@{$usertools}) {
 3604:             $oldaccesstext->{$tool} = &mt("availability set to 'off'");
 3605:             $newaccesstext->{$tool} = $oldaccesstext->{$tool};
 3606:             $changeHash->{$context.'.'.$tool} = $userenv->{$context.'.'.$tool};
 3607:             my ($newop,$limit);
 3608:             if ($env{'form.'.$context.'_'.$tool}) {
 3609:                 $newop = $env{'form.'.$context.'_'.$tool};
 3610:                 if ($newop eq 'autolimit') {
 3611:                     $limit = $env{'form.'.$context.'_'.$tool.'_limit'};
 3612:                     $limit =~ s/\D+//g;
 3613:                     $newop .= '='.$limit;
 3614:                 }
 3615:             }
 3616:             if ($userenv->{$context.'.'.$tool} eq '') {
 3617:                 if ($newop) {
 3618:                     $changed->{$tool}=&tool_admin($tool,$cdom.':'.$newop,
 3619:                                                   $changeHash,$context);
 3620:                     if ($changed->{$tool}) {
 3621:                         if ($newop =~ /^autolimit/) {
 3622:                             if ($limit) {
 3623:                                 $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3624:                             } else {
 3625:                                 $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3626:                             }
 3627:                         } else {
 3628:                             $newaccesstext->{$tool} = $reqdisplay{$newop};
 3629:                         }
 3630:                     } else {
 3631:                         $newaccesstext->{$tool} = $oldaccesstext->{$tool};
 3632:                     }
 3633:                 }
 3634:             } else {
 3635:                 my @curr = split(',',$userenv->{$context.'.'.$tool});
 3636:                 my @new;
 3637:                 my $changedoms;
 3638:                 foreach my $req (@curr) {
 3639:                     if ($req =~ /^\Q$cdom\E\:($optregex\=?\d*)$/) {
 3640:                         my $oldop = $1;
 3641:                         if ($oldop =~ /^autolimit=(\d*)/) {
 3642:                             my $limit = $1;
 3643:                             if ($limit) {
 3644:                                 $oldaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3645:                             } else {
 3646:                                 $oldaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3647:                             }
 3648:                         } else {
 3649:                             $oldaccesstext->{$tool} = $reqdisplay{$oldop};
 3650:                         }
 3651:                         if ($oldop ne $newop) {
 3652:                             $changedoms = 1;
 3653:                             foreach my $item (@curr) {
 3654:                                 my ($reqdom,$option) = split(':',$item);
 3655:                                 unless ($reqdom eq $cdom) {
 3656:                                     push(@new,$item);
 3657:                                 }
 3658:                             }
 3659:                             if ($newop) {
 3660:                                 push(@new,$cdom.':'.$newop);
 3661:                             }
 3662:                             @new = sort(@new);
 3663:                         }
 3664:                         last;
 3665:                     }
 3666:                 }
 3667:                 if ((!$changedoms) && ($newop)) {
 3668:                     $changedoms = 1;
 3669:                     @new = sort(@curr,$cdom.':'.$newop);
 3670:                 }
 3671:                 if ($changedoms) {
 3672:                     my $newdomstr;
 3673:                     if (@new) {
 3674:                         $newdomstr = join(',',@new);
 3675:                     }
 3676:                     $changed->{$tool}=&tool_admin($tool,$newdomstr,$changeHash,
 3677:                                                   $context);
 3678:                     if ($changed->{$tool}) {
 3679:                         if ($env{'form.'.$context.'_'.$tool}) {
 3680:                             if ($env{'form.'.$context.'_'.$tool} eq 'autolimit') {
 3681:                                 my $limit = $env{'form.'.$context.'_'.$tool.'_limit'};
 3682:                                 $limit =~ s/\D+//g;
 3683:                                 if ($limit) {
 3684:                                     $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3685:                                 } else {
 3686:                                     $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3687:                                 }
 3688:                             } else {
 3689:                                 $newaccesstext->{$tool} = $reqdisplay{$env{'form.'.$context.'_'.$tool}};
 3690:                             }
 3691:                         } else {
 3692:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3693:                         }
 3694:                     }
 3695:                 }
 3696:             }
 3697:         }
 3698:         return;
 3699:     }
 3700:     foreach my $tool (@{$usertools}) {
 3701:         my ($newval,$limit,$envkey);
 3702:         $envkey = $context.'.'.$tool;
 3703:         if ($context eq 'requestcourses') {
 3704:             $newval = $env{'form.crsreq_'.$tool};
 3705:             if ($newval eq 'autolimit') {
 3706:                 $limit = $env{'form.crsreq_'.$tool.'_limit'};
 3707:                 $limit =~ s/\D+//g;
 3708:                 $newval .= '='.$limit;
 3709:             }
 3710:         } elsif ($context eq 'requestauthor') {
 3711:             $newval = $env{'form.'.$context};
 3712:             $envkey = $context;
 3713:         } else {
 3714:             $newval = $env{'form.'.$context.'_'.$tool};
 3715:         }
 3716:         if ($userenv->{$envkey} ne '') {
 3717:             $oldaccess->{$tool} = &mt('custom');
 3718:             if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 3719:                 if ($userenv->{$envkey} =~ /^autolimit=(\d*)$/) {
 3720:                     my $currlimit = $1;
 3721:                     if ($currlimit eq '') {
 3722:                         $oldaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3723:                     } else {
 3724:                         $oldaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$currlimit);
 3725:                     }
 3726:                 } elsif ($userenv->{$envkey}) {
 3727:                     $oldaccesstext->{$tool} = $reqdisplay{$userenv->{$envkey}};
 3728:                 } else {
 3729:                     $oldaccesstext->{$tool} = &mt("availability set to 'off'");
 3730:                 }
 3731:             } else {
 3732:                 if ($userenv->{$envkey}) {
 3733:                     $oldaccesstext->{$tool} = &mt("availability set to 'on'");
 3734:                 } else {
 3735:                     $oldaccesstext->{$tool} = &mt("availability set to 'off'");
 3736:                 }
 3737:             }
 3738:             $changeHash->{$envkey} = $userenv->{$envkey};
 3739:             if ($env{'form.custom'.$tool} == 1) {
 3740:                 if ($newval ne $userenv->{$envkey}) {
 3741:                     $changed->{$tool} = &tool_admin($tool,$newval,$changeHash,
 3742:                                                     $context);
 3743:                     if ($changed->{$tool}) {
 3744:                         $newaccess->{$tool} = &mt('custom');
 3745:                         if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 3746:                             if ($newval =~ /^autolimit/) {
 3747:                                 if ($limit) {
 3748:                                     $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3749:                                 } else {
 3750:                                     $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3751:                                 }
 3752:                             } elsif ($newval) {
 3753:                                 $newaccesstext->{$tool} = $reqdisplay{$newval};
 3754:                             } else {
 3755:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3756:                             }
 3757:                         } else {
 3758:                             if ($newval) {
 3759:                                 $newaccesstext->{$tool} = &mt("availability set to 'on'");
 3760:                             } else {
 3761:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3762:                             }
 3763:                         }
 3764:                     } else {
 3765:                         $newaccess->{$tool} = $oldaccess->{$tool};
 3766:                         if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 3767:                             if ($newval =~ /^autolimit/) {
 3768:                                 if ($limit) {
 3769:                                     $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3770:                                 } else {
 3771:                                     $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3772:                                 }
 3773:                             } elsif ($newval) {
 3774:                                 $newaccesstext->{$tool} = $reqdisplay{$newval};
 3775:                             } else {
 3776:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3777:                             }
 3778:                         } else {
 3779:                             if ($userenv->{$context.'.'.$tool}) {
 3780:                                 $newaccesstext->{$tool} = &mt("availability set to 'on'");
 3781:                             } else {
 3782:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3783:                             }
 3784:                         }
 3785:                     }
 3786:                 } else {
 3787:                     $newaccess->{$tool} = $oldaccess->{$tool};
 3788:                     $newaccesstext->{$tool} = $oldaccesstext->{$tool};
 3789:                 }
 3790:             } else {
 3791:                 $changed->{$tool} = &tool_admin($tool,'',$changeHash,$context);
 3792:                 if ($changed->{$tool}) {
 3793:                     $newaccess->{$tool} = &mt('default');
 3794:                 } else {
 3795:                     $newaccess->{$tool} = $oldaccess->{$tool};
 3796:                     if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 3797:                         if ($newval =~ /^autolimit/) {
 3798:                             if ($limit) {
 3799:                                 $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3800:                             } else {
 3801:                                 $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3802:                             }
 3803:                         } elsif ($newval) {
 3804:                             $newaccesstext->{$tool} = $reqdisplay{$newval};
 3805:                         } else {
 3806:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3807:                         }
 3808:                     } else {
 3809:                         if ($userenv->{$context.'.'.$tool}) {
 3810:                             $newaccesstext->{$tool} = &mt("availability set to 'on'");
 3811:                         } else {
 3812:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3813:                         }
 3814:                     }
 3815:                 }
 3816:             }
 3817:         } else {
 3818:             $oldaccess->{$tool} = &mt('default');
 3819:             if ($env{'form.custom'.$tool} == 1) {
 3820:                 $changed->{$tool} = &tool_admin($tool,$newval,$changeHash,
 3821:                                                 $context);
 3822:                 if ($changed->{$tool}) {
 3823:                     $newaccess->{$tool} = &mt('custom');
 3824:                     if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 3825:                         if ($newval =~ /^autolimit/) {
 3826:                             if ($limit) {
 3827:                                 $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3828:                             } else {
 3829:                                 $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3830:                             }
 3831:                         } elsif ($newval) {
 3832:                             $newaccesstext->{$tool} = $reqdisplay{$newval};
 3833:                         } else {
 3834:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3835:                         }
 3836:                     } else {
 3837:                         if ($newval) {
 3838:                             $newaccesstext->{$tool} = &mt("availability set to 'on'");
 3839:                         } else {
 3840:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3841:                         }
 3842:                     }
 3843:                 } else {
 3844:                     $newaccess->{$tool} = $oldaccess->{$tool};
 3845:                 }
 3846:             } else {
 3847:                 $newaccess->{$tool} = $oldaccess->{$tool};
 3848:             }
 3849:         }
 3850:     }
 3851:     return;
 3852: }
 3853: 
 3854: sub adhocrole_changes {
 3855:     my ($changehashref,$userenv) = @_;
 3856:     my @adds = &Apache::loncommon::get_env_multiple('form.adhocroleadd');
 3857:     my @dels = &Apache::loncommon::get_env_multiple('form.adhocroledel');
 3858:     my (@saved,@added,@alladhoc,$changed);
 3859:     my $adhoc_key = 'adhocroles.'.$env{'request.role.domain'};
 3860:     if (!$env{'form.makeuser'}) {
 3861:         if (ref($userenv) eq 'HASH') {
 3862:             my @current;
 3863:             if ($userenv->{$adhoc_key}) {
 3864:                 @current = split(/,/,$userenv->{$adhoc_key});
 3865:                 if (@dels) {
 3866:                     foreach my $curr (@current) {
 3867:                         next if ($curr eq '');
 3868:                         unless (grep(/\Q$curr\E$/,@dels)) {
 3869:                             push(@saved,$curr);
 3870:                         }
 3871:                     }
 3872:                     $changed = 1;
 3873:                 } else {
 3874:                     @saved = @current;
 3875:                 }
 3876:             }
 3877:         }
 3878:     }
 3879:     if (@adds) {
 3880:         my $confname = &Apache::lonnet::get_domainconfiguser($env{'request.role.domain'});
 3881:         my %existing=&Apache::lonnet::dump('roles',$env{'request.role.domain'},
 3882:                                            $confname,'rolesdef_');
 3883:         foreach my $poss (@adds) {
 3884:             if (exists($existing{'rolesdef_'.$poss})) {
 3885:                 push(@added,$poss);
 3886:                 $changed = 1;
 3887:             }
 3888:         }
 3889:     }
 3890:     if (@added) {
 3891:         if (@saved) {
 3892:             foreach my $add (@added) {
 3893:                 unless (grep(/^\Q$add\E$/,@saved)) {
 3894:                     push(@alladhoc,$add);
 3895:                 }
 3896:             }
 3897:         } else {
 3898:             push(@alladhoc,@added);
 3899:         }
 3900:     }
 3901:     if (@saved) {
 3902:         push(@alladhoc,@saved);
 3903:     }
 3904:     if (@alladhoc) {
 3905:         my $adhocstr = join(',',sort(@alladhoc));
 3906:         $changehashref->{$adhoc_key} = $adhocstr;
 3907:     } elsif (@dels) {
 3908:         &Apache::lonnet::del('environment',[$adhoc_key],$env{'form.ccdomain'},$env{'form.ccuname'});
 3909:         delete($changehashref->{$adhoc_key});
 3910:         if (($env{'form.ccdomain'} eq $env{'user.domain'}) &&
 3911:             ($env{'form.ccuname'} eq $env{'user.name'})) {
 3912:             &Apache::lonnet::delenv($adhoc_key);
 3913:         }
 3914:     }
 3915:     return $changed;
 3916: }
 3917: 
 3918: sub update_roles {
 3919:     my ($r,$context,$showcredits) = @_;
 3920:     my $now=time;
 3921:     my @rolechanges;
 3922:     my %disallowed;
 3923:     $r->print('<h3>'.&mt('Modifying Roles').'</h3>');
 3924:     foreach my $key (keys(%env)) {
 3925: 	next if (! $env{$key});
 3926:         next if ($key eq 'form.action');
 3927: 	# Revoke roles
 3928: 	if ($key=~/^form\.rev/) {
 3929: 	    if ($key=~/^form\.rev\:([^\_]+)\_([^\_\.]+)$/) {
 3930: # Revoke standard role
 3931: 		my ($scope,$role) = ($1,$2);
 3932: 		my $result =
 3933: 		    &Apache::lonnet::revokerole($env{'form.ccdomain'},
 3934: 						$env{'form.ccuname'},
 3935: 						$scope,$role,'','',$context);
 3936:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
 3937:                             &mt('Revoking [_1] in [_2]',
 3938:                                 &Apache::lonnet::plaintext($role),
 3939:                                 &Apache::loncommon::show_role_extent($scope,$context,$role)),
 3940:                                 $result ne "ok").'<br />');
 3941:                 if ($result ne "ok") {
 3942:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 3943:                 }
 3944: 		if ($role eq 'st') {
 3945: 		    my $result = 
 3946:                         &Apache::lonuserutils::classlist_drop($scope,
 3947:                             $env{'form.ccuname'},$env{'form.ccdomain'},
 3948: 			    $now);
 3949:                     $r->print(&Apache::lonhtmlcommon::confirm_success($result));
 3950: 		}
 3951:                 if (!grep(/^\Q$role\E$/,@rolechanges)) {
 3952:                     push(@rolechanges,$role);
 3953:                 }
 3954: 	    }
 3955: 	    if ($key=~m{^form\.rev\:([^_]+)_cr\.cr/($match_domain)/($match_username)/(\w+)$}s) {
 3956: # Revoke custom role
 3957:                 my $result = &Apache::lonnet::revokecustomrole(
 3958:                     $env{'form.ccdomain'},$env{'form.ccuname'},$1,$2,$3,$4,'','',$context);
 3959:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
 3960:                             &mt('Revoking custom role [_1] by [_2] in [_3]',
 3961:                                 $4,$3.':'.$2,&Apache::loncommon::show_role_extent($1,$context,'cr')),
 3962:                             $result ne 'ok').'<br />');
 3963:                 if ($result ne "ok") {
 3964:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 3965:                 }
 3966:                 if (!grep(/^cr$/,@rolechanges)) {
 3967:                     push(@rolechanges,'cr');
 3968:                 }
 3969: 	    }
 3970: 	} elsif ($key=~/^form\.del/) {
 3971: 	    if ($key=~/^form\.del\:([^\_]+)\_([^\_\.]+)$/) {
 3972: # Delete standard role
 3973: 		my ($scope,$role) = ($1,$2);
 3974: 		my $result =
 3975: 		    &Apache::lonnet::assignrole($env{'form.ccdomain'},
 3976: 						$env{'form.ccuname'},
 3977: 						$scope,$role,$now,0,1,'',
 3978:                                                 $context);
 3979:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
 3980:                             &mt('Deleting [_1] in [_2]',
 3981:                                 &Apache::lonnet::plaintext($role),
 3982:                                 &Apache::loncommon::show_role_extent($scope,$context,$role)),
 3983:                             $result ne 'ok').'<br />');
 3984:                 if ($result ne "ok") {
 3985:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 3986:                 }
 3987: 
 3988: 		if ($role eq 'st') {
 3989: 		    my $result = 
 3990:                         &Apache::lonuserutils::classlist_drop($scope,
 3991:                             $env{'form.ccuname'},$env{'form.ccdomain'},
 3992: 			    $now);
 3993: 		    $r->print(&Apache::lonhtmlcommon::confirm_success($result));
 3994: 		}
 3995:                 if (!grep(/^\Q$role\E$/,@rolechanges)) {
 3996:                     push(@rolechanges,$role);
 3997:                 }
 3998:             }
 3999: 	    if ($key=~m{^form\.del\:([^_]+)_cr\.cr/($match_domain)/($match_username)/(\w+)$}) {
 4000:                 my ($url,$rdom,$rnam,$rolename) = ($1,$2,$3,$4);
 4001: # Delete custom role
 4002:                 my $result =
 4003:                     &Apache::lonnet::assigncustomrole($env{'form.ccdomain'},
 4004:                         $env{'form.ccuname'},$url,$rdom,$rnam,$rolename,$now,
 4005:                         0,1,$context);
 4006:                 $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('Deleting custom role [_1] by [_2] in [_3]',
 4007:                       $rolename,$rnam.':'.$rdom,&Apache::loncommon::show_role_extent($1,$context,'cr')),
 4008:                       $result ne "ok").'<br />');
 4009:                 if ($result ne "ok") {
 4010:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 4011:                 }
 4012: 
 4013:                 if (!grep(/^cr$/,@rolechanges)) {
 4014:                     push(@rolechanges,'cr');
 4015:                 }
 4016:             }
 4017: 	} elsif ($key=~/^form\.ren/) {
 4018:             my $udom = $env{'form.ccdomain'};
 4019:             my $uname = $env{'form.ccuname'};
 4020: # Re-enable standard role
 4021: 	    if ($key=~/^form\.ren\:([^\_]+)\_([^\_\.]+)$/) {
 4022:                 my $url = $1;
 4023:                 my $role = $2;
 4024:                 my $logmsg;
 4025:                 my $output;
 4026:                 if ($role eq 'st') {
 4027:                     if ($url =~ m-^/($match_domain)/($match_courseid)/?(\w*)$-) {
 4028:                         my ($cdom,$cnum,$csec) = ($1,$2,$3);
 4029:                         my $credits;
 4030:                         if ($showcredits) {
 4031:                             my $defaultcredits = 
 4032:                                 &Apache::lonuserutils::get_defaultcredits($cdom,$cnum);
 4033:                             $credits = &get_user_credits($defaultcredits,$cdom,$cnum);
 4034:                         }
 4035:                         my $result = &Apache::loncommon::commit_studentrole(\$logmsg,$udom,$uname,$url,$role,$now,0,$cdom,$cnum,$csec,$context,$credits);
 4036:                         if (($result =~ /^error/) || ($result eq 'not_in_class') || ($result eq 'unknown_course') || ($result eq 'refused')) {
 4037:                             if ($result eq 'refused' && $logmsg) {
 4038:                                 $output = $logmsg;
 4039:                             } else { 
 4040:                                 $output = &mt('Error: [_1]',$result)."\n";
 4041:                             }
 4042:                         } else {
 4043:                             $output = &Apache::lonhtmlcommon::confirm_success(&mt('Assigning [_1] in [_2] starting [_3]',
 4044:                                         &Apache::lonnet::plaintext($role),
 4045:                                         &Apache::loncommon::show_role_extent($url,$context,'st'),
 4046:                                         &Apache::lonlocal::locallocaltime($now))).'<br />'.$logmsg.'<br />';
 4047:                         }
 4048:                     }
 4049:                 } else {
 4050: 		    my $result=&Apache::lonnet::assignrole($env{'form.ccdomain'},
 4051:                                $env{'form.ccuname'},$url,$role,0,$now,'','',
 4052:                                $context);
 4053:                         $output = &Apache::lonhtmlcommon::confirm_success(&mt('Re-enabling [_1] in [_2]',
 4054:                                         &Apache::lonnet::plaintext($role),
 4055:                                         &Apache::loncommon::show_role_extent($url,$context,$role)),$result ne "ok").'<br />';
 4056:                     if ($result ne "ok") {
 4057:                         $output .= &mt('Error: [_1]',$result).'<br />';
 4058:                     }
 4059:                 }
 4060:                 $r->print($output);
 4061:                 if (!grep(/^\Q$role\E$/,@rolechanges)) {
 4062:                     push(@rolechanges,$role);
 4063:                 }
 4064: 	    }
 4065: # Re-enable custom role
 4066: 	    if ($key=~m{^form\.ren\:([^_]+)_cr\.cr/($match_domain)/($match_username)/(\w+)$}) {
 4067:                 my ($url,$rdom,$rnam,$rolename) = ($1,$2,$3,$4);
 4068:                 my $result = &Apache::lonnet::assigncustomrole(
 4069:                                $env{'form.ccdomain'}, $env{'form.ccuname'},
 4070:                                $url,$rdom,$rnam,$rolename,0,$now,undef,$context);
 4071:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
 4072:                     &mt('Re-enabling custom role [_1] by [_2] in [_3]',
 4073:                         $rolename,$rnam.':'.$rdom,&Apache::loncommon::show_role_extent($1,$context,'cr')),
 4074:                     $result ne "ok").'<br />');
 4075:                 if ($result ne "ok") {
 4076:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 4077:                 }
 4078:                 if (!grep(/^cr$/,@rolechanges)) {
 4079:                     push(@rolechanges,'cr');
 4080:                 }
 4081:             }
 4082: 	} elsif ($key=~/^form\.act/) {
 4083:             my $udom = $env{'form.ccdomain'};
 4084:             my $uname = $env{'form.ccuname'};
 4085: 	    if ($key=~/^form\.act\_($match_domain)\_($match_courseid)\_cr_cr_($match_domain)_($match_username)_([^\_]+)$/) {
 4086:                 # Activate a custom role
 4087: 		my ($one,$two,$three,$four,$five)=($1,$2,$3,$4,$5);
 4088: 		my $url='/'.$one.'/'.$two;
 4089: 		my $full=$one.'_'.$two.'_cr_cr_'.$three.'_'.$four.'_'.$five;
 4090: 
 4091:                 my $start = ( $env{'form.start_'.$full} ?
 4092:                               $env{'form.start_'.$full} :
 4093:                               $now );
 4094:                 my $end   = ( $env{'form.end_'.$full} ?
 4095:                               $env{'form.end_'.$full} :
 4096:                               0 );
 4097:                                                                                      
 4098:                 # split multiple sections
 4099:                 my %sections = ();
 4100:                 my $num_sections = &build_roles($env{'form.sec_'.$full},\%sections,$5);
 4101:                 if ($num_sections == 0) {
 4102:                     $r->print(&Apache::loncommon::commit_customrole($udom,$uname,$url,$three,$four,$five,$start,$end,$context));
 4103:                 } else {
 4104: 		    my %curr_groups =
 4105: 			&Apache::longroup::coursegroups($one,$two);
 4106:                     foreach my $sec (sort {$a cmp $b} keys(%sections)) {
 4107:                         if (($sec eq 'none') || ($sec eq 'all') || 
 4108:                             exists($curr_groups{$sec})) {
 4109:                             $disallowed{$sec} = $url;
 4110:                             next;
 4111:                         }
 4112:                         my $securl = $url.'/'.$sec;
 4113: 		        $r->print(&Apache::loncommon::commit_customrole($udom,$uname,$securl,$three,$four,$five,$start,$end,$context));
 4114:                     }
 4115:                 }
 4116:                 if (!grep(/^cr$/,@rolechanges)) {
 4117:                     push(@rolechanges,'cr');
 4118:                 }
 4119: 	    } elsif ($key=~/^form\.act\_($match_domain)\_($match_name)\_([^\_]+)$/) {
 4120: 		# Activate roles for sections with 3 id numbers
 4121: 		# set start, end times, and the url for the class
 4122: 		my ($one,$two,$three)=($1,$2,$3);
 4123: 		my $start = ( $env{'form.start_'.$one.'_'.$two.'_'.$three} ? 
 4124: 			      $env{'form.start_'.$one.'_'.$two.'_'.$three} : 
 4125: 			      $now );
 4126: 		my $end   = ( $env{'form.end_'.$one.'_'.$two.'_'.$three} ? 
 4127: 			      $env{'form.end_'.$one.'_'.$two.'_'.$three} :
 4128: 			      0 );
 4129: 		my $url='/'.$one.'/'.$two;
 4130:                 my $type = 'three';
 4131:                 # split multiple sections
 4132:                 my %sections = ();
 4133:                 my $num_sections = &build_roles($env{'form.sec_'.$one.'_'.$two.'_'.$three},\%sections,$three);
 4134:                 my $credits;
 4135:                 if ($three eq 'st') {
 4136:                     if ($showcredits) { 
 4137:                         my $defaultcredits = 
 4138:                             &Apache::lonuserutils::get_defaultcredits($one,$two);
 4139:                         $credits = $env{'form.credits_'.$one.'_'.$two.'_'.$three};
 4140:                         $credits =~ s/[^\d\.]//g;
 4141:                         if ($credits eq $defaultcredits) {
 4142:                             undef($credits);
 4143:                         }
 4144:                     }
 4145:                 }
 4146:                 if ($num_sections == 0) {
 4147:                     $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$three,$start,$end,$one,$two,'',$context,$credits));
 4148:                 } else {
 4149:                     my %curr_groups = 
 4150: 			&Apache::longroup::coursegroups($one,$two);
 4151:                     my $emptysec = 0;
 4152:                     foreach my $sec (sort {$a cmp $b} keys(%sections)) {
 4153:                         $sec =~ s/\W//g;
 4154:                         if ($sec ne '') {
 4155:                             if (($sec eq 'none') || ($sec eq 'all') || 
 4156:                                 exists($curr_groups{$sec})) {
 4157:                                 $disallowed{$sec} = $url;
 4158:                                 next;
 4159:                             }
 4160:                             my $securl = $url.'/'.$sec;
 4161:                             $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$securl,$three,$start,$end,$one,$two,$sec,$context,$credits));
 4162:                         } else {
 4163:                             $emptysec = 1;
 4164:                         }
 4165:                     }
 4166:                     if ($emptysec) {
 4167:                         $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$three,$start,$end,$one,$two,'',$context,$credits));
 4168:                     }
 4169:                 }
 4170:                 if (!grep(/^\Q$three\E$/,@rolechanges)) {
 4171:                     push(@rolechanges,$three);
 4172:                 }
 4173: 	    } elsif ($key=~/^form\.act\_([^\_]+)\_([^\_]+)$/) {
 4174: 		# Activate roles for sections with two id numbers
 4175: 		# set start, end times, and the url for the class
 4176: 		my $start = ( $env{'form.start_'.$1.'_'.$2} ? 
 4177: 			      $env{'form.start_'.$1.'_'.$2} : 
 4178: 			      $now );
 4179: 		my $end   = ( $env{'form.end_'.$1.'_'.$2} ? 
 4180: 			      $env{'form.end_'.$1.'_'.$2} :
 4181: 			      0 );
 4182:                 my $one = $1;
 4183:                 my $two = $2;
 4184: 		my $url='/'.$one.'/';
 4185:                 # split multiple sections
 4186:                 my %sections = ();
 4187:                 my $num_sections = &build_roles($env{'form.sec_'.$one.'_'.$two},\%sections,$two);
 4188:                 if ($num_sections == 0) {
 4189:                     $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$two,$start,$end,$one,undef,'',$context));
 4190:                 } else {
 4191:                     my $emptysec = 0;
 4192:                     foreach my $sec (sort {$a cmp $b} keys(%sections)) {
 4193:                         if ($sec ne '') {
 4194:                             my $securl = $url.'/'.$sec;
 4195:                             $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$securl,$two,$start,$end,$one,undef,$sec,$context));
 4196:                         } else {
 4197:                             $emptysec = 1;
 4198:                         }
 4199:                     }
 4200:                     if ($emptysec) {
 4201:                         $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$two,$start,$end,$one,undef,'',$context));
 4202:                     }
 4203:                 }
 4204:                 if (!grep(/^\Q$two\E$/,@rolechanges)) {
 4205:                     push(@rolechanges,$two);
 4206:                 }
 4207: 	    } else {
 4208: 		$r->print('<p><span class="LC_error">'.&mt('ERROR').': '.&mt('Unknown command').' <tt>'.$key.'</tt></span></p><br />');
 4209:             }
 4210:             foreach my $key (sort(keys(%disallowed))) {
 4211:                 $r->print('<p class="LC_warning">');
 4212:                 if (($key eq 'none') || ($key eq 'all')) {  
 4213:                     $r->print(&mt('[_1] may not be used as the name for a section, as it is a reserved word.','<tt>'.$key.'</tt>'));
 4214:                 } else {
 4215:                     $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>'));
 4216:                 }
 4217:                 $r->print('</p><p>'
 4218:                          .&mt('Please [_1]go back[_2] and choose a different section name.'
 4219:                              ,'<a href="javascript:history.go(-1)'
 4220:                              ,'</a>')
 4221:                          .'</p><br />'
 4222:                 );
 4223:             }
 4224: 	}
 4225:     } # End of foreach (keys(%env))
 4226: # Flush the course logs so reverse user roles immediately updated
 4227:     $r->register_cleanup(\&Apache::lonnet::flushcourselogs);
 4228:     if (@rolechanges == 0) {
 4229:         $r->print('<p>'.&mt('No roles to modify').'</p>');
 4230:     }
 4231:     return @rolechanges;
 4232: }
 4233: 
 4234: sub get_user_credits {
 4235:     my ($uname,$udom,$defaultcredits,$cdom,$cnum) = @_;
 4236:     if ($cdom eq '' || $cnum eq '') {
 4237:         return unless ($env{'request.course.id'});
 4238:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4239:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4240:     }
 4241:     my $credits;
 4242:     my %currhash =
 4243:         &Apache::lonnet::get('classlist',[$uname.':'.$udom],$cdom,$cnum);
 4244:     if (keys(%currhash) > 0) {
 4245:         my @items = split(/:/,$currhash{$uname.':'.$udom});
 4246:         my $crdidx = &Apache::loncoursedata::CL_CREDITS() - 3;
 4247:         $credits = $items[$crdidx];
 4248:         $credits =~ s/[^\d\.]//g;
 4249:     }
 4250:     if ($credits eq $defaultcredits) {
 4251:         undef($credits);
 4252:     }
 4253:     return $credits;
 4254: }
 4255: 
 4256: sub enroll_single_student {
 4257:     my ($r,$uhome,$amode,$genpwd,$now,$newuser,$context,$crstype,
 4258:         $showcredits,$defaultcredits) = @_;
 4259:     $r->print('<h3>');
 4260:     if ($crstype eq 'Community') {
 4261:         $r->print(&mt('Enrolling Member'));
 4262:     } else {
 4263:         $r->print(&mt('Enrolling Student'));
 4264:     }
 4265:     $r->print('</h3>');
 4266: 
 4267:     # Remove non alphanumeric values from section
 4268:     $env{'form.sections'}=~s/\W//g;
 4269: 
 4270:     my $credits;
 4271:     if (($showcredits) && ($env{'form.credits'} ne '')) {
 4272:         $credits = $env{'form.credits'};
 4273:         $credits =~ s/[^\d\.]//g;
 4274:         if ($credits ne '') {
 4275:             if ($credits eq $defaultcredits) {
 4276:                 undef($credits);
 4277:             }
 4278:         }
 4279:     }
 4280: 
 4281:     # Clean out any old student roles the user has in this class.
 4282:     &Apache::lonuserutils::modifystudent($env{'form.ccdomain'},
 4283:          $env{'form.ccuname'},$env{'request.course.id'},undef,$uhome);
 4284:     my ($startdate,$enddate) = &Apache::lonuserutils::get_dates_from_form();
 4285:     my $enroll_result =
 4286:         &Apache::lonnet::modify_student_enrollment($env{'form.ccdomain'},
 4287:             $env{'form.ccuname'},$env{'form.cid'},$env{'form.cfirstname'},
 4288:             $env{'form.cmiddlename'},$env{'form.clastname'},
 4289:             $env{'form.generation'},$env{'form.sections'},$enddate,
 4290:             $startdate,'manual',undef,$env{'request.course.id'},'',$context,
 4291:             $credits);
 4292:     if ($enroll_result =~ /^ok/) {
 4293:         $r->print(&mt('[_1] enrolled','<b>'.$env{'form.ccuname'}.':'.$env{'form.ccdomain'}.'</b>'));
 4294:         if ($env{'form.sections'} ne '') {
 4295:             $r->print(' '.&mt('in section [_1]',$env{'form.sections'}));
 4296:         }
 4297:         my ($showstart,$showend);
 4298:         if ($startdate <= $now) {
 4299:             $showstart = &mt('Access starts immediately');
 4300:         } else {
 4301:             $showstart = &mt('Access starts: ').&Apache::lonlocal::locallocaltime($startdate);
 4302:         }
 4303:         if ($enddate == 0) {
 4304:             $showend = &mt('ends: no ending date');
 4305:         } else {
 4306:             $showend = &mt('ends: ').&Apache::lonlocal::locallocaltime($enddate);
 4307:         }
 4308:         $r->print('.<br />'.$showstart.'; '.$showend);
 4309:         if ($startdate <= $now && !$newuser) {
 4310:             $r->print('<p class="LC_info">');
 4311:             if ($crstype eq 'Community') {
 4312:                 $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.'));
 4313:             } else {
 4314:                 $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.'));
 4315:            }
 4316:            $r->print('</p>');
 4317:         }
 4318:     } else {
 4319:         $r->print(&mt('unable to enroll').": ".$enroll_result);
 4320:     }
 4321:     return;
 4322: }
 4323: 
 4324: sub get_defaultquota_text {
 4325:     my ($settingstatus) = @_;
 4326:     my $defquotatext; 
 4327:     if ($settingstatus eq '') {
 4328:         $defquotatext = &mt('default');
 4329:     } else {
 4330:         my ($usertypes,$order) =
 4331:             &Apache::lonnet::retrieve_inst_usertypes($env{'form.ccdomain'});
 4332:         if ($usertypes->{$settingstatus} eq '') {
 4333:             $defquotatext = &mt('default');
 4334:         } else {
 4335:             $defquotatext = &mt('default for [_1]',$usertypes->{$settingstatus});
 4336:         }
 4337:     }
 4338:     return $defquotatext;
 4339: }
 4340: 
 4341: sub update_result_form {
 4342:     my ($uhome) = @_;
 4343:     my $outcome = 
 4344:     '<form name="userupdate" method="post" action="">'."\n";
 4345:     foreach my $item ('srchby','srchin','srchtype','srchterm','srchdomain','ccuname','ccdomain') {
 4346:         $outcome .= '<input type="hidden" name="'.$item.'" value="'.$env{'form.'.$item}.'" />'."\n";
 4347:     }
 4348:     if ($env{'form.origname'} ne '') {
 4349:         $outcome .= '<input type="hidden" name="origname" value="'.$env{'form.origname'}.'" />'."\n";
 4350:     }
 4351:     foreach my $item ('sortby','seluname','seludom') {
 4352:         if (exists($env{'form.'.$item})) {
 4353:             $outcome .= '<input type="hidden" name="'.$item.'" value="'.$env{'form.'.$item}.'" />'."\n";
 4354:         }
 4355:     }
 4356:     if ($uhome eq 'no_host') {
 4357:         $outcome .= '<input type="hidden" name="forcenewuser" value="1" />'."\n";
 4358:     }
 4359:     $outcome .= '<input type="hidden" name="phase" value="" />'."\n".
 4360:                 '<input type="hidden" name="currstate" value="" />'."\n".
 4361:                 '<input type="hidden" name="action" value="'.$env{'form.action'}.'" />'."\n".
 4362:                 '</form>';
 4363:     return $outcome;
 4364: }
 4365: 
 4366: sub quota_admin {
 4367:     my ($setquota,$changeHash,$name) = @_;
 4368:     my $quotachanged;
 4369:     if (&Apache::lonnet::allowed('mpq',$env{'form.ccdomain'})) {
 4370:         # Current user has quota modification privileges
 4371:         if (ref($changeHash) eq 'HASH') {
 4372:             $quotachanged = 1;
 4373:             $changeHash->{$name.'quota'} = $setquota;
 4374:         }
 4375:     }
 4376:     return $quotachanged;
 4377: }
 4378: 
 4379: sub tool_admin {
 4380:     my ($tool,$settool,$changeHash,$context) = @_;
 4381:     my $canchange = 0; 
 4382:     if ($context eq 'requestcourses') {
 4383:         if (&Apache::lonnet::allowed('ccc',$env{'form.ccdomain'})) {
 4384:             $canchange = 1;
 4385:         }
 4386:     } elsif ($context eq 'reqcrsotherdom') {
 4387:         if (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) {
 4388:             $canchange = 1;
 4389:         }
 4390:     } elsif ($context eq 'requestauthor') {
 4391:         if (&Apache::lonnet::allowed('cau',$env{'request.role.domain'})) {
 4392:             $canchange = 1;
 4393:         }
 4394:     } elsif (&Apache::lonnet::allowed('mut',$env{'form.ccdomain'})) {
 4395:         # Current user has quota modification privileges
 4396:         $canchange = 1;
 4397:     }
 4398:     my $toolchanged;
 4399:     if ($canchange) {
 4400:         if (ref($changeHash) eq 'HASH') {
 4401:             $toolchanged = 1;
 4402:             if ($tool eq 'requestauthor') {
 4403:                 $changeHash->{$context} = $settool;
 4404:             } else {
 4405:                 $changeHash->{$context.'.'.$tool} = $settool;
 4406:             }
 4407:         }
 4408:     }
 4409:     return $toolchanged;
 4410: }
 4411: 
 4412: sub build_roles {
 4413:     my ($sectionstr,$sections,$role) = @_;
 4414:     my $num_sections = 0;
 4415:     if ($sectionstr=~ /,/) {
 4416:         my @secnums = split/,/,$sectionstr;
 4417:         if ($role eq 'st') {
 4418:             $secnums[0] =~ s/\W//g;
 4419:             $$sections{$secnums[0]} = 1;
 4420:             $num_sections = 1;
 4421:         } else {
 4422:             foreach my $sec (@secnums) {
 4423:                 $sec =~ ~s/\W//g;
 4424:                 if (!($sec eq "")) {
 4425:                     if (exists($$sections{$sec})) {
 4426:                         $$sections{$sec} ++;
 4427:                     } else {
 4428:                         $$sections{$sec} = 1;
 4429:                         $num_sections ++;
 4430:                     }
 4431:                 }
 4432:             }
 4433:         }
 4434:     } else {
 4435:         $sectionstr=~s/\W//g;
 4436:         unless ($sectionstr eq '') {
 4437:             $$sections{$sectionstr} = 1;
 4438:             $num_sections ++;
 4439:         }
 4440:     }
 4441: 
 4442:     return $num_sections;
 4443: }
 4444: 
 4445: # ========================================================== Custom Role Editor
 4446: 
 4447: sub custom_role_editor {
 4448:     my ($r,$brcrum,$prefix) = @_;
 4449:     my $action = $env{'form.customroleaction'};
 4450:     my $rolename; 
 4451:     if ($action eq 'new') {
 4452:         $rolename=$env{'form.newrolename'};
 4453:     } else {
 4454:         $rolename=$env{'form.rolename'};
 4455:     }
 4456: 
 4457:     my ($crstype,$context);
 4458:     if ($env{'request.course.id'}) {
 4459:         $crstype = &Apache::loncommon::course_type();
 4460:         $context = 'course';
 4461:     } else {
 4462:         $context = 'domain';
 4463:         $crstype = 'course';
 4464:     }
 4465: 
 4466:     $rolename=~s/[^A-Za-z0-9]//gs;
 4467:     if (!$rolename || $env{'form.phase'} eq 'pickrole') {
 4468: 	&print_username_entry_form($r,undef,undef,undef,undef,$crstype,$brcrum);
 4469:         return;
 4470:     }
 4471: 
 4472:     my $formname = 'form1';
 4473:     my %privs=();
 4474:     my $body_top = '<h2>';
 4475: # ------------------------------------------------------- Does this role exist?
 4476:     my ($rdummy,$roledef)=
 4477: 			 &Apache::lonnet::get('roles',["rolesdef_$rolename"]);
 4478:     if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 4479:         $body_top .= &mt('Existing Role').' "';
 4480: # ------------------------------------------------- Get current role privileges
 4481:         ($privs{'system'},$privs{'domain'},$privs{'course'})=split(/\_/,$roledef);
 4482:         if ($privs{'system'} =~ /bre\&S/) {
 4483:             if ($context eq 'domain') {
 4484:                 $crstype = 'Course';
 4485:             } elsif ($crstype eq 'Community') {
 4486:                 $privs{'system'} =~ s/bre\&S//;
 4487:             }
 4488:         } elsif ($context eq 'domain') {
 4489:             $crstype = 'Course';
 4490:         }
 4491:     } else {
 4492:         $body_top .= &mt('New Role').' "';
 4493:         $roledef='';
 4494:     }
 4495:     $body_top .= $rolename.'"</h2>';
 4496: 
 4497: # ------------------------------------------------------- What can be assigned?
 4498:     my %full=();
 4499:     my %levels=(
 4500:                  course => {},
 4501:                  domain => {},
 4502:                  system => {},
 4503:                );
 4504:     my %levelscurrent=(
 4505:                         course => {},
 4506:                         domain => {},
 4507:                         system => {},
 4508:                       );
 4509:     &Apache::lonuserutils::custom_role_privs(\%privs,\%full,\%levels,\%levelscurrent);
 4510:     my ($jsback,$elements) = &crumb_utilities();
 4511:     my @templateroles = &Apache::lonuserutils::custom_template_roles($context,$crstype);
 4512:     my $head_script =
 4513:         &Apache::lonuserutils::custom_roledefs_js($context,$crstype,$formname,
 4514:                                                   \%full,\@templateroles,$jsback);
 4515:     push (@{$brcrum},
 4516:               {href => "javascript:backPage(document.$formname,'pickrole','')",
 4517:                text => "Pick custom role",
 4518:                faq  => 282,bug=>'Instructor Interface',},
 4519:               {href => "javascript:backPage(document.$formname,'','')",
 4520:                text => "Edit custom role",
 4521:                faq  => 282,
 4522:                bug  => 'Instructor Interface',
 4523:                help => 'Course_Editing_Custom_Roles'}
 4524:               );
 4525:     my $args = { bread_crumbs          => $brcrum,
 4526:                  bread_crumbs_component => 'User Management'};
 4527: 
 4528:     $r->print(&Apache::loncommon::start_page('Custom Role Editor',
 4529:                                              $head_script,$args).
 4530:               $body_top);
 4531:     $r->print('<form name="'.$formname.'" method="post" action="">'."\n".
 4532:               &Apache::lonuserutils::custom_role_header($context,$crstype,
 4533:                                                         \@templateroles,$prefix));
 4534: 
 4535:     $r->print(<<ENDCCF);
 4536: <input type="hidden" name="phase" value="set_custom_roles" />
 4537: <input type="hidden" name="rolename" value="$rolename" />
 4538: ENDCCF
 4539:     $r->print(&Apache::lonuserutils::custom_role_table($crstype,\%full,\%levels,
 4540:                                                        \%levelscurrent,$prefix));
 4541:     $r->print(&Apache::loncommon::end_data_table().
 4542:    '<input type="hidden" name="action" value="'.$env{'form.action'}.'" />'.
 4543:    '<input type="hidden" name="startrolename" value="'.$env{'form.rolename'}.
 4544:    '" />'."\n".'<input type="hidden" name="currstate" value="" />'."\n".
 4545:    '<input type="reset" value="'.&mt("Reset").'" />'."\n".
 4546:    '<input type="submit" value="'.&mt('Save').'" /></form>');
 4547: }
 4548: 
 4549: # ---------------------------------------------------------- Call to definerole
 4550: sub set_custom_role {
 4551:     my ($r,$context,$brcrum,$prefix) = @_;
 4552:     my $rolename=$env{'form.rolename'};
 4553:     $rolename=~s/[^A-Za-z0-9]//gs;
 4554:     if (!$rolename) {
 4555: 	&custom_role_editor($r,$brcrum,$prefix);
 4556:         return;
 4557:     }
 4558:     my ($jsback,$elements) = &crumb_utilities();
 4559:     my $jscript = '<script type="text/javascript">'
 4560:                  .'// <![CDATA['."\n"
 4561:                  .$jsback."\n"
 4562:                  .'// ]]>'."\n"
 4563:                  .'</script>'."\n";
 4564:     push(@{$brcrum},
 4565:         {href => "javascript:backPage(document.customresult,'pickrole','')",
 4566:          text => "Pick custom role",
 4567:          faq  => 282,
 4568:          bug  => 'Instructor Interface',},
 4569:         {href => "javascript:backPage(document.customresult,'selected_custom_edit','')",
 4570:          text => "Edit custom role",
 4571:          faq  => 282,
 4572:          bug  => 'Instructor Interface',},
 4573:         {href => "javascript:backPage(document.customresult,'set_custom_roles','')",
 4574:          text => "Result",
 4575:          faq  => 282,
 4576:          bug  => 'Instructor Interface',
 4577:          help => 'Course_Editing_Custom_Roles'},
 4578:         );
 4579:     my $args = { bread_crumbs           => $brcrum,
 4580:                  bread_crumbs_component => 'User Management'};
 4581:     $r->print(&Apache::loncommon::start_page('Save Custom Role',$jscript,$args));
 4582: 
 4583:     my $newrole;
 4584:     my ($rdummy,$roledef)=
 4585: 	&Apache::lonnet::get('roles',["rolesdef_$rolename"]);
 4586: 
 4587: # ------------------------------------------------------- Does this role exist?
 4588:     $r->print('<h3>');
 4589:     if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 4590: 	$r->print(&mt('Existing Role').' "');
 4591:     } else {
 4592: 	$r->print(&mt('New Role').' "');
 4593: 	$roledef='';
 4594:         $newrole = 1;
 4595:     }
 4596:     $r->print($rolename.'"</h3>');
 4597: # ------------------------------------------------- Assign role and show result
 4598: 
 4599:     my $errmsg;
 4600:     my %newprivs = &Apache::lonuserutils::custom_role_update($rolename,$prefix);
 4601:     # Assign role and return result
 4602:     my $result = &Apache::lonnet::definerole($rolename,$newprivs{'s'},$newprivs{'d'},
 4603:                                              $newprivs{'c'});
 4604:     if ($result ne 'ok') {
 4605:         $errmsg = ': '.$result;
 4606:     }
 4607:     my $message =
 4608:         &Apache::lonhtmlcommon::confirm_success(
 4609:             &mt('Defining Role').$errmsg, ($result eq 'ok' ? 0 : 1));
 4610:     if ($env{'request.course.id'}) {
 4611:         my $url='/'.$env{'request.course.id'};
 4612:         $url=~s/\_/\//g;
 4613:         $result =
 4614:             &Apache::lonnet::assigncustomrole(
 4615:                 $env{'user.domain'},$env{'user.name'},
 4616:                 $url,
 4617:                 $env{'user.domain'},$env{'user.name'},
 4618:                 $rolename,undef,undef,undef,$context);
 4619:         if ($result ne 'ok') {
 4620:             $errmsg = ': '.$result;
 4621:         }
 4622:         $message .=
 4623:             '<br />'
 4624:            .&Apache::lonhtmlcommon::confirm_success(
 4625:                 &mt('Assigning Role to Self').$errmsg, ($result eq 'ok' ? 0 : 1));
 4626:     }
 4627:     $r->print(
 4628:         &Apache::loncommon::confirmwrapper($message)
 4629:        .'<br />'
 4630:        .&Apache::lonhtmlcommon::actionbox([
 4631:             '<a href="javascript:backPage(document.customresult,'."'pickrole'".')">'
 4632:            .&mt('Create or edit another custom role')
 4633:            .'</a>'])
 4634:        .'<form name="customresult" method="post" action="">'
 4635:        .&Apache::lonhtmlcommon::echo_form_input([])
 4636:        .'</form>'
 4637:     );
 4638: }
 4639: 
 4640: # ================================================================ Main Handler
 4641: sub handler {
 4642:     my $r = shift;
 4643:     if ($r->header_only) {
 4644:        &Apache::loncommon::content_type($r,'text/html');
 4645:        $r->send_http_header;
 4646:        return OK;
 4647:     }
 4648:     my ($context,$crstype);
 4649:     if ($env{'request.course.id'}) {
 4650:         $context = 'course';
 4651:         $crstype = &Apache::loncommon::course_type();
 4652:     } elsif ($env{'request.role'} =~ /^au\./) {
 4653:         $context = 'author';
 4654:     } else {
 4655:         $context = 'domain';
 4656:     }
 4657: 
 4658:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 4659:         ['action','state','callingform','roletype','showrole','bulkaction','popup','phase',
 4660:          'username','domain','srchterm','srchdomain','srchin','srchby','srchtype','queue']);
 4661:     &Apache::lonhtmlcommon::clear_breadcrumbs();
 4662:     my $args;
 4663:     my $brcrum = [];
 4664:     my $bread_crumbs_component = 'User Management';
 4665:     if (($env{'form.action'} ne 'dateselect') && ($env{'form.action'} ne 'displayuserreq')) {
 4666:         $brcrum = [{href=>"/adm/createuser",
 4667:                     text=>"User Management",
 4668:                     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'}
 4669:                   ];
 4670:     }
 4671:     #SD Following files not added to help, because the corresponding .tex-files seem to
 4672:     #be missing: Course_Approve_Selfenroll,Course_User_Logs,
 4673:     my ($permission,$allowed) = 
 4674:         &Apache::lonuserutils::get_permission($context,$crstype);
 4675:     if (!$allowed) {
 4676:         if ($context eq 'course') {
 4677:             $r->internal_redirect('/adm/viewclasslist');
 4678:             return OK;
 4679:         }
 4680:         $env{'user.error.msg'}=
 4681:             "/adm/createuser:cst:0:0:Cannot create/modify user data ".
 4682:                                  "or view user status.";
 4683:         return HTTP_NOT_ACCEPTABLE;
 4684:     }
 4685: 
 4686:     &Apache::loncommon::content_type($r,'text/html');
 4687:     $r->send_http_header;
 4688: 
 4689:     my $showcredits;
 4690:     if ((($context eq 'course') && ($crstype eq 'Course')) || 
 4691:          ($context eq 'domain')) {
 4692:         my %domdefaults = 
 4693:             &Apache::lonnet::get_domain_defaults($env{'request.role.domain'});
 4694:         if ($domdefaults{'officialcredits'} || $domdefaults{'unofficialcredits'}) {
 4695:             $showcredits = 1;
 4696:         }
 4697:     }
 4698: 
 4699:     # Main switch on form.action and form.state, as appropriate
 4700:     if (! exists($env{'form.action'})) {
 4701:         $args = {bread_crumbs => $brcrum,
 4702:                  bread_crumbs_component => $bread_crumbs_component}; 
 4703:         $r->print(&header(undef,$args));
 4704:         $r->print(&print_main_menu($permission,$context,$crstype));
 4705:     } elsif ($env{'form.action'} eq 'upload' && $permission->{'cusr'}) {
 4706:         push(@{$brcrum},
 4707:               { href => '/adm/createuser?action=upload&state=',
 4708:                 text => 'Upload Users List',
 4709:                 help => 'Course_Create_Class_List',
 4710:               });
 4711:         $bread_crumbs_component = 'Upload Users List';
 4712:         $args = {bread_crumbs           => $brcrum,
 4713:                  bread_crumbs_component => $bread_crumbs_component};
 4714:         $r->print(&header(undef,$args));
 4715:         $r->print('<form name="studentform" method="post" '.
 4716:                   'enctype="multipart/form-data" '.
 4717:                   ' action="/adm/createuser">'."\n");
 4718:         if (! exists($env{'form.state'})) {
 4719:             &Apache::lonuserutils::print_first_users_upload_form($r,$context);
 4720:         } elsif ($env{'form.state'} eq 'got_file') {
 4721:             &Apache::lonuserutils::print_upload_manager_form($r,$context,$permission,
 4722:                                                              $crstype,$showcredits);
 4723:         } elsif ($env{'form.state'} eq 'enrolling') {
 4724:             if ($env{'form.datatoken'}) {
 4725:                 &Apache::lonuserutils::upfile_drop_add($r,$context,$permission,
 4726:                                                        $showcredits);
 4727:             }
 4728:         } else {
 4729:             &Apache::lonuserutils::print_first_users_upload_form($r,$context);
 4730:         }
 4731:     } elsif (((($env{'form.action'} eq 'singleuser') || ($env{'form.action'}
 4732:               eq 'singlestudent')) && ($permission->{'cusr'})) ||
 4733:              (($env{'form.action'} eq 'singleuser') && ($permission->{'view'})) ||
 4734:              (($env{'form.action'} eq 'accesslogs') && ($permission->{'activity'}))) {
 4735:         my $phase = $env{'form.phase'};
 4736:         my @search = ('srchterm','srchby','srchin','srchtype','srchdomain');
 4737: 	&Apache::loncreateuser::restore_prev_selections();
 4738: 	my $srch;
 4739: 	foreach my $item (@search) {
 4740: 	    $srch->{$item} = $env{'form.'.$item};
 4741: 	}
 4742:         if (($phase eq 'get_user_info') || ($phase eq 'userpicked') ||
 4743:             ($phase eq 'createnewuser') || ($phase eq 'activity')) {
 4744:             if ($env{'form.phase'} eq 'createnewuser') {
 4745:                 my $response;
 4746:                 if ($env{'form.srchterm'} !~ /^$match_username$/) {
 4747:                     my $response =
 4748:                         '<span class="LC_warning">'
 4749:                        .&mt('You must specify a valid username. Only the following are allowed:'
 4750:                            .' letters numbers - . @')
 4751:                        .'</span>';
 4752:                     $env{'form.phase'} = '';
 4753:                     &print_username_entry_form($r,$context,$response,$srch,undef,
 4754:                                                $crstype,$brcrum,$showcredits);
 4755:                 } else {
 4756:                     my $ccuname =&LONCAPA::clean_username($srch->{'srchterm'});
 4757:                     my $ccdomain=&LONCAPA::clean_domain($srch->{'srchdomain'});
 4758:                     &print_user_modification_page($r,$ccuname,$ccdomain,
 4759:                                                   $srch,$response,$context,
 4760:                                                   $permission,$crstype,$brcrum,
 4761:                                                   $showcredits);
 4762:                 }
 4763:             } elsif ($env{'form.phase'} eq 'get_user_info') {
 4764:                 my ($currstate,$response,$forcenewuser,$results) = 
 4765:                     &user_search_result($context,$srch);
 4766:                 if ($env{'form.currstate'} eq 'modify') {
 4767:                     $currstate = $env{'form.currstate'};
 4768:                 }
 4769:                 if ($currstate eq 'select') {
 4770:                     &print_user_selection_page($r,$response,$srch,$results,
 4771:                                                \@search,$context,undef,$crstype,
 4772:                                                $brcrum);
 4773:                 } elsif (($currstate eq 'modify') || ($env{'form.action'} eq 'accesslogs')) {
 4774:                     my ($ccuname,$ccdomain,$uhome);
 4775:                     if (($srch->{'srchby'} eq 'uname') && 
 4776:                         ($srch->{'srchtype'} eq 'exact')) {
 4777:                         $ccuname = $srch->{'srchterm'};
 4778:                         $ccdomain= $srch->{'srchdomain'};
 4779:                     } else {
 4780:                         my @matchedunames = keys(%{$results});
 4781:                         ($ccuname,$ccdomain) = split(/:/,$matchedunames[0]);
 4782:                     }
 4783:                     $ccuname =&LONCAPA::clean_username($ccuname);
 4784:                     $ccdomain=&LONCAPA::clean_domain($ccdomain);
 4785:                     if ($env{'form.action'} eq 'accesslogs') {
 4786:                         my $uhome;
 4787:                         if (($ccuname ne '') && ($ccdomain ne '')) {
 4788:                            $uhome = &Apache::lonnet::homeserver($ccuname,$ccdomain);
 4789:                         }
 4790:                         if (($uhome eq '') || ($uhome eq 'no_host')) {
 4791:                             $env{'form.phase'} = '';
 4792:                             undef($forcenewuser);
 4793:                             #if ($response) {
 4794:                             #    unless ($response =~ m{\Q<br /><br />\E$}) {
 4795:                             #        $response .= '<br /><br />';
 4796:                             #    }
 4797:                             #}
 4798:                             &print_username_entry_form($r,$context,$response,$srch,
 4799:                                                        $forcenewuser,$crstype,$brcrum);
 4800:                         } else {
 4801:                             &print_useraccesslogs_display($r,$ccuname,$ccdomain,$permission,$brcrum);
 4802:                         }
 4803:                     } else {
 4804:                         if ($env{'form.forcenewuser'}) {
 4805:                             $response = '';
 4806:                         }
 4807:                         &print_user_modification_page($r,$ccuname,$ccdomain,
 4808:                                                       $srch,$response,$context,
 4809:                                                       $permission,$crstype,$brcrum);
 4810:                     }
 4811:                 } elsif ($currstate eq 'query') {
 4812:                     &print_user_query_page($r,'createuser',$brcrum);
 4813:                 } else {
 4814:                     $env{'form.phase'} = '';
 4815:                     &print_username_entry_form($r,$context,$response,$srch,
 4816:                                                $forcenewuser,$crstype,$brcrum);
 4817:                 }
 4818:             } elsif ($env{'form.phase'} eq 'userpicked') {
 4819:                 my $ccuname = &LONCAPA::clean_username($env{'form.seluname'});
 4820:                 my $ccdomain = &LONCAPA::clean_domain($env{'form.seludom'});
 4821:                 if ($env{'form.action'} eq 'accesslogs') {
 4822:                     &print_useraccesslogs_display($r,$ccuname,$ccdomain,$permission,$brcrum);
 4823:                 } else {
 4824:                     &print_user_modification_page($r,$ccuname,$ccdomain,$srch,'',
 4825:                                                   $context,$permission,$crstype,
 4826:                                                   $brcrum);
 4827:                 }
 4828:             } elsif ($env{'form.action'} eq 'accesslogs') {
 4829:                 my $ccuname = &LONCAPA::clean_username($env{'form.accessuname'});
 4830:                 my $ccdomain = &LONCAPA::clean_domain($env{'form.accessudom'});
 4831:                 &print_useraccesslogs_display($r,$ccuname,$ccdomain,$permission,$brcrum);
 4832:             }
 4833:         } elsif ($env{'form.phase'} eq 'update_user_data') {
 4834:             &update_user_data($r,$context,$crstype,$brcrum,$showcredits);
 4835:         } else {
 4836:             &print_username_entry_form($r,$context,undef,$srch,undef,$crstype,
 4837:                                        $brcrum);
 4838:         }
 4839:     } elsif ($env{'form.action'} eq 'custom' && $permission->{'custom'}) {
 4840:         my $prefix;
 4841:         if ($env{'form.phase'} eq 'set_custom_roles') {
 4842:             &set_custom_role($r,$context,$brcrum,$prefix);
 4843:         } else {
 4844:             &custom_role_editor($r,$brcrum,$prefix);
 4845:         }
 4846:     } elsif (($env{'form.action'} eq 'processauthorreq') &&
 4847:              ($permission->{'cusr'}) && 
 4848:              (&Apache::lonnet::allowed('cau',$env{'request.role.domain'}))) {
 4849:         push(@{$brcrum},
 4850:                  {href => '/adm/createuser?action=processauthorreq',
 4851:                   text => 'Authoring Space requests',
 4852:                   help => 'Domain_Role_Approvals'});
 4853:         $bread_crumbs_component = 'Authoring requests';
 4854:         if ($env{'form.state'} eq 'done') {
 4855:             push(@{$brcrum},
 4856:                      {href => '/adm/createuser?action=authorreqqueue',
 4857:                       text => 'Result',
 4858:                       help => 'Domain_Role_Approvals'});
 4859:             $bread_crumbs_component = 'Authoring request result';
 4860:         }
 4861:         $args = { bread_crumbs           => $brcrum,
 4862:                   bread_crumbs_component => $bread_crumbs_component};
 4863:         my $js = &usernamerequest_javascript();
 4864:         $r->print(&header(&add_script($js),$args));
 4865:         if (!exists($env{'form.state'})) {
 4866:             $r->print(&Apache::loncoursequeueadmin::display_queued_requests('requestauthor',
 4867:                                                                             $env{'request.role.domain'}));
 4868:         } elsif ($env{'form.state'} eq 'done') {
 4869:             $r->print('<h3>'.&mt('Authoring request processing').'</h3>'."\n");
 4870:             $r->print(&Apache::loncoursequeueadmin::update_request_queue('requestauthor',
 4871:                                                                          $env{'request.role.domain'}));
 4872:         }
 4873:     } elsif (($env{'form.action'} eq 'processusernamereq') &&
 4874:              ($permission->{'cusr'}) &&
 4875:              (&Apache::lonnet::allowed('cau',$env{'request.role.domain'}))) {
 4876:         push(@{$brcrum},
 4877:                  {href => '/adm/createuser?action=processusernamereq',
 4878:                   text => 'LON-CAPA account requests',
 4879:                   help => 'Domain_Username_Approvals'});
 4880:         $bread_crumbs_component = 'Account requests';
 4881:         if ($env{'form.state'} eq 'done') {
 4882:             push(@{$brcrum},
 4883:                      {href => '/adm/createuser?action=usernamereqqueue',
 4884:                       text => 'Result',
 4885:                       help => 'Domain_Username_Approvals'});
 4886:             $bread_crumbs_component = 'LON-CAPA account request result';
 4887:         }
 4888:         $args = { bread_crumbs           => $brcrum,
 4889:                   bread_crumbs_component => $bread_crumbs_component};
 4890:         my $js = &usernamerequest_javascript();
 4891:         $r->print(&header(&add_script($js),$args));
 4892:         if (!exists($env{'form.state'})) {
 4893:             $r->print(&Apache::loncoursequeueadmin::display_queued_requests('requestusername',
 4894:                                                                             $env{'request.role.domain'}));
 4895:         } elsif ($env{'form.state'} eq 'done') {
 4896:             $r->print('<h3>'.&mt('LON-CAPA account request processing').'</h3>'."\n");
 4897:             $r->print(&Apache::loncoursequeueadmin::update_request_queue('requestusername',
 4898:                                                                          $env{'request.role.domain'}));
 4899:         }
 4900:     } elsif (($env{'form.action'} eq 'displayuserreq') &&
 4901:              ($permission->{'cusr'})) {
 4902:         my $dom = $env{'form.domain'};
 4903:         my $uname = $env{'form.username'};
 4904:         my $warning;
 4905:         if (($dom =~ /^$match_domain$/) && (&Apache::lonnet::domain($dom) ne '')) {
 4906:             if (($dom eq $env{'request.role.domain'}) && (&Apache::lonnet::allowed('ccc',$dom))) {
 4907:                 if (($uname =~ /^$match_username$/) && ($env{'form.queue'} eq 'approval')) {
 4908:                     my $uhome = &Apache::lonnet::homeserver($uname,$dom);
 4909:                     if ($uhome eq 'no_host') {
 4910:                         my $queue = $env{'form.queue'};
 4911:                         my $reqkey = &escape($uname).'_'.$queue; 
 4912:                         my $namespace = 'usernamequeue';
 4913:                         my $domconfig = &Apache::lonnet::get_domainconfiguser($dom);
 4914:                         my %queued =
 4915:                             &Apache::lonnet::get($namespace,[$reqkey],$dom,$domconfig);
 4916:                         unless ($queued{$reqkey}) {
 4917:                             $warning = &mt('No information was found for this LON-CAPA account request.');
 4918:                         }
 4919:                     } else {
 4920:                         $warning = &mt('A LON-CAPA account already exists for the requested username and domain.');
 4921:                     }
 4922:                 } else {
 4923:                     $warning = &mt('LON-CAPA account request status check is for an invalid username.');
 4924:                 }
 4925:             } else {
 4926:                 $warning = &mt('You do not have rights to view LON-CAPA account requests in the domain specified.');
 4927:             }
 4928:         } else {
 4929:             $warning = &mt('LON-CAPA account request status check is for an invalid domain.');
 4930:         }
 4931:         my $args = { only_body => 1 };
 4932:         $r->print(&header(undef,$args).
 4933:                   '<h3>'.&mt('LON-CAPA Account Request Details').'</h3>');
 4934:         if ($warning ne '') {
 4935:             $r->print('<div class="LC_warning">'.$warning.'</div>');
 4936:         } else {
 4937:             my ($infofields,$infotitles) = &Apache::loncommon::emailusername_info();
 4938:             my $domconfiguser = &Apache::lonnet::get_domainconfiguser($dom);
 4939:             my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 4940:             if (ref($domconfig{'usercreation'}) eq 'HASH') {
 4941:                 if (ref($domconfig{'usercreation'}{'cancreate'}) eq 'HASH') {
 4942:                     if (ref($domconfig{'usercreation'}{'cancreate'}{'emailusername'}) eq 'HASH') {
 4943:                         my %info =
 4944:                             &Apache::lonnet::get('nohist_requestedusernames',[$uname],$dom,$domconfiguser);
 4945:                         if (ref($info{$uname}) eq 'HASH') {
 4946:                             my $usertype = $info{$uname}{'inststatus'};
 4947:                             unless ($usertype) {
 4948:                                 $usertype = 'default';
 4949:                             }
 4950:                             if (ref($domconfig{'usercreation'}{'cancreate'}{'emailusername'}{$usertype}) eq 'HASH') {
 4951:                                 if ((ref($infofields) eq 'ARRAY') && (ref($infotitles) eq 'HASH')) {
 4952:                                     $r->print('<div>'.&Apache::lonhtmlcommon::start_pick_box());
 4953:                                     my ($num,$count,$showstatus);
 4954:                                     $count = scalar(keys(%{$domconfig{'usercreation'}{'cancreate'}{'emailusername'}{$usertype}}));
 4955:                                     unless ($usertype eq 'default') {
 4956:                                         my ($othertitle,$usertypes,$types) = 
 4957:                                             &Apache::loncommon::sorted_inst_types($dom);
 4958:                                         if (ref($usertypes) eq 'HASH') {
 4959:                                             if ($usertypes->{$usertype}) {
 4960:                                                 $showstatus = $usertypes->{$usertype};
 4961:                                                 $count ++;
 4962:                                             }
 4963:                                         }
 4964:                                     }
 4965:                                     foreach my $field (@{$infofields}) {
 4966:                                         next unless ($domconfig{'usercreation'}{'cancreate'}{'emailusername'}{$usertype}{$field});
 4967:                                         next unless ($infotitles->{$field});
 4968:                                         $r->print(&Apache::lonhtmlcommon::row_title($infotitles->{$field}).
 4969:                                                   $info{$uname}{$field});
 4970:                                         $num ++;
 4971:                                         if ($count == $num) {
 4972:                                             $r->print(&Apache::lonhtmlcommon::row_closure(1));
 4973:                                         } else {
 4974:                                             $r->print(&Apache::lonhtmlcommon::row_closure());
 4975:                                         }
 4976:                                     }
 4977:                                     if ($showstatus) {
 4978:                                         $r->print(&Apache::lonhtmlcommon::row_title(&mt('Status type (self-reported)')).
 4979:                                                   $showstatus.
 4980:                                                   &Apache::lonhtmlcommon::row_closure(1));
 4981:                                     }
 4982:                                     $r->print(&Apache::lonhtmlcommon::end_pick_box().'</div>');
 4983:                                 }
 4984:                             }
 4985:                         }
 4986:                     }
 4987:                 }
 4988:             }
 4989:             $r->print(&close_popup_form());
 4990:         }
 4991:     } elsif (($env{'form.action'} eq 'listusers') && 
 4992:              ($permission->{'view'} || $permission->{'cusr'})) {
 4993:         if ($env{'form.phase'} eq 'bulkchange') {
 4994:             push(@{$brcrum},
 4995:                     {href => '/adm/createuser?action=listusers',
 4996:                      text => "List Users"},
 4997:                     {href => "/adm/createuser",
 4998:                      text => "Result",
 4999:                      help => 'Course_View_Class_List'});
 5000:             $bread_crumbs_component = 'Update Users';
 5001:             $args = {bread_crumbs           => $brcrum,
 5002:                      bread_crumbs_component => $bread_crumbs_component};
 5003:             $r->print(&header(undef,$args));
 5004:             my $setting = $env{'form.roletype'};
 5005:             my $choice = $env{'form.bulkaction'};
 5006:             if ($permission->{'cusr'}) {
 5007:                 &Apache::lonuserutils::update_user_list($r,$context,$setting,$choice,$crstype);
 5008:             } else {
 5009:                 $r->print(&mt('You are not authorized to make bulk changes to user roles'));
 5010:                 $r->print('<p><a href="/adm/createuser?action=listusers">'.&mt('Display User Lists').'</a>');
 5011:             }
 5012:         } else {
 5013:             push(@{$brcrum},
 5014:                     {href => '/adm/createuser?action=listusers',
 5015:                      text => "List Users",
 5016:                      help => 'Course_View_Class_List'});
 5017:             $bread_crumbs_component = 'List Users';
 5018:             $args = {bread_crumbs           => $brcrum,
 5019:                      bread_crumbs_component => $bread_crumbs_component};
 5020:             my ($cb_jscript,$jscript,$totcodes,$codetitles,$idlist,$idlist_titles);
 5021:             my $formname = 'studentform';
 5022:             my $hidecall = "hide_searching();";
 5023:             if (($context eq 'domain') && (($env{'form.roletype'} eq 'course') ||
 5024:                 ($env{'form.roletype'} eq 'community'))) {
 5025:                 if ($env{'form.roletype'} eq 'course') {
 5026:                     ($cb_jscript,$jscript,$totcodes,$codetitles,$idlist,$idlist_titles) = 
 5027:                         &Apache::lonuserutils::courses_selector($env{'request.role.domain'},
 5028:                                                                 $formname);
 5029:                 } elsif ($env{'form.roletype'} eq 'community') {
 5030:                     $cb_jscript = 
 5031:                         &Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'});
 5032:                     my %elements = (
 5033:                                       coursepick => 'radio',
 5034:                                       coursetotal => 'text',
 5035:                                       courselist => 'text',
 5036:                                    );
 5037:                     $jscript = &Apache::lonhtmlcommon::set_form_elements(\%elements);
 5038:                 }
 5039:                 $jscript .= &verify_user_display($context)."\n".
 5040:                             &Apache::loncommon::check_uncheck_jscript();
 5041:                 my $js = &add_script($jscript).$cb_jscript;
 5042:                 my $loadcode = 
 5043:                     &Apache::lonuserutils::course_selector_loadcode($formname);
 5044:                 if ($loadcode ne '') {
 5045:                     $args->{add_entries} = {onload => "$loadcode;$hidecall"};
 5046:                 } else {
 5047:                     $args->{add_entries} = {onload => $hidecall};
 5048:                 }
 5049:                 $r->print(&header($js,$args));
 5050:             } else {
 5051:                 $args->{add_entries} = {onload => $hidecall};
 5052:                 $jscript = &verify_user_display($context).
 5053:                            &Apache::loncommon::check_uncheck_jscript(); 
 5054:                 $r->print(&header(&add_script($jscript),$args));
 5055:             }
 5056:             &Apache::lonuserutils::print_userlist($r,undef,$permission,$context,
 5057:                          $formname,$totcodes,$codetitles,$idlist,$idlist_titles,
 5058:                          $showcredits);
 5059:         }
 5060:     } elsif ($env{'form.action'} eq 'drop' && $permission->{'cusr'}) {
 5061:         my $brtext;
 5062:         if ($crstype eq 'Community') {
 5063:             $brtext = 'Drop Members';
 5064:         } else {
 5065:             $brtext = 'Drop Students';
 5066:         }
 5067:         push(@{$brcrum},
 5068:                 {href => '/adm/createuser?action=drop',
 5069:                  text => $brtext,
 5070:                  help => 'Course_Drop_Student'});
 5071:         if ($env{'form.state'} eq 'done') {
 5072:             push(@{$brcrum},
 5073:                      {href=>'/adm/createuser?action=drop',
 5074:                       text=>"Result"});
 5075:         }
 5076:         $bread_crumbs_component = $brtext;
 5077:         $args = {bread_crumbs           => $brcrum,
 5078:                  bread_crumbs_component => $bread_crumbs_component}; 
 5079:         $r->print(&header(undef,$args));
 5080:         if (!exists($env{'form.state'})) {
 5081:             &Apache::lonuserutils::print_drop_menu($r,$context,$permission,$crstype);
 5082:         } elsif ($env{'form.state'} eq 'done') {
 5083:             &Apache::lonuserutils::update_user_list($r,$context,undef,
 5084:                                                     $env{'form.action'});
 5085:         }
 5086:     } elsif ($env{'form.action'} eq 'dateselect') {
 5087:         if ($permission->{'cusr'}) {
 5088:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 5089:                       &Apache::lonuserutils::date_section_selector($context,$permission,
 5090:                                                                    $crstype,$showcredits));
 5091:         } else {
 5092:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 5093:                      '<span class="LC_error">'.&mt('You do not have permission to modify dates or sections for users').'</span>'); 
 5094:         }
 5095:     } elsif ($env{'form.action'} eq 'selfenroll') {
 5096:         if ($permission->{selfenrolladmin}) {
 5097:             my $cid = $env{'request.course.id'};
 5098:             my $cdom = $env{'course.'.$cid.'.domain'};
 5099:             my $cnum = $env{'course.'.$cid.'.num'};
 5100:             my %currsettings = (
 5101:                 selfenroll_types              => $env{'course.'.$cid.'.internal.selfenroll_types'},
 5102:                 selfenroll_registered         => $env{'course.'.$cid.'.internal.selfenroll_registered'},
 5103:                 selfenroll_section            => $env{'course.'.$cid.'.internal.selfenroll_section'},
 5104:                 selfenroll_notifylist         => $env{'course.'.$cid.'.internal.selfenroll_notifylist'},
 5105:                 selfenroll_approval           => $env{'course.'.$cid.'.internal.selfenroll_approval'},
 5106:                 selfenroll_limit              => $env{'course.'.$cid.'.internal.selfenroll_limit'},
 5107:                 selfenroll_cap                => $env{'course.'.$cid.'.internal.selfenroll_cap'},
 5108:                 selfenroll_start_date         => $env{'course.'.$cid.'.internal.selfenroll_start_date'},
 5109:                 selfenroll_end_date           => $env{'course.'.$cid.'.internal.selfenroll_end_date'},
 5110:                 selfenroll_start_access       => $env{'course.'.$cid.'.internal.selfenroll_start_access'},
 5111:                 selfenroll_end_access         => $env{'course.'.$cid.'.internal.selfenroll_end_access'},
 5112:                 default_enrollment_start_date => $env{'course.'.$cid.'.default_enrollment_start_date'},
 5113:                 default_enrollment_end_date   => $env{'course.'.$cid.'.default_enrollment_end_date'},
 5114:                 uniquecode                    => $env{'course.'.$cid.'.internal.uniquecode'},
 5115:             );
 5116:             push(@{$brcrum},
 5117:                     {href => '/adm/createuser?action=selfenroll',
 5118:                      text => "Configure Self-enrollment",
 5119:                      help => 'Course_Self_Enrollment'});
 5120:             if (!exists($env{'form.state'})) {
 5121:                 $args = { bread_crumbs           => $brcrum,
 5122:                           bread_crumbs_component => 'Configure Self-enrollment'};
 5123:                 $r->print(&header(undef,$args));
 5124:                 $r->print('<h3>'.&mt('Self-enrollment with a student role').'</h3>'."\n");
 5125:                 &print_selfenroll_menu($r,'course',$cid,$cdom,$cnum,\%currsettings);
 5126:             } elsif ($env{'form.state'} eq 'done') {
 5127:                 push (@{$brcrum},
 5128:                           {href=>'/adm/createuser?action=selfenroll',
 5129:                            text=>"Result"});
 5130:                 $args = { bread_crumbs           => $brcrum,
 5131:                           bread_crumbs_component => 'Self-enrollment result'};
 5132:                 $r->print(&header(undef,$args));
 5133:                 $r->print('<h3>'.&mt('Self-enrollment with a student role').'</h3>'."\n");
 5134:                 &update_selfenroll_config($r,$cid,$cdom,$cnum,$context,$crstype,\%currsettings);
 5135:             }
 5136:         } else {
 5137:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 5138:                      '<span class="LC_error">'.&mt('You do not have permission to configure self-enrollment').'</span>');
 5139:         }
 5140:     } elsif ($env{'form.action'} eq 'selfenrollqueue') {
 5141:         if ($permission->{selfenrolladmin}) {
 5142:             push(@{$brcrum},
 5143:                      {href => '/adm/createuser?action=selfenrollqueue',
 5144:                       text => 'Enrollment requests',
 5145:                       help => 'Course_Self_Enrollment'});
 5146:             $bread_crumbs_component = 'Enrollment requests';
 5147:             if ($env{'form.state'} eq 'done') {
 5148:                 push(@{$brcrum},
 5149:                          {href => '/adm/createuser?action=selfenrollqueue',
 5150:                           text => 'Result',
 5151:                           help => 'Course_Self_Enrollment'});
 5152:                 $bread_crumbs_component = 'Enrollment result';
 5153:             }
 5154:             $args = { bread_crumbs           => $brcrum,
 5155:                       bread_crumbs_component => $bread_crumbs_component};
 5156:             $r->print(&header(undef,$args));
 5157:             my $cid = $env{'request.course.id'};
 5158:             my $cdom = $env{'course.'.$cid.'.domain'};
 5159:             my $cnum = $env{'course.'.$cid.'.num'};
 5160:             my $coursedesc = $env{'course.'.$cid.'.description'};
 5161:             if (!exists($env{'form.state'})) {
 5162:                 $r->print('<h3>'.&mt('Pending enrollment requests').'</h3>'."\n");
 5163:                 $r->print(&Apache::loncoursequeueadmin::display_queued_requests($context,
 5164:                                                                                 $cdom,$cnum));
 5165:             } elsif ($env{'form.state'} eq 'done') {
 5166:                 $r->print('<h3>'.&mt('Enrollment request processing').'</h3>'."\n");
 5167:                 $r->print(&Apache::loncoursequeueadmin::update_request_queue($context,
 5168:                               $cdom,$cnum,$coursedesc));
 5169:             }
 5170:         } else {
 5171:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 5172:                      '<span class="LC_error">'.&mt('You do not have permission to manage self-enrollment').'</span>');
 5173:         }
 5174: 
 5175:     } elsif ($env{'form.action'} eq 'changelogs') {
 5176:         if ($permission->{cusr} || $permission->{view}) {
 5177:             &print_userchangelogs_display($r,$context,$permission,$brcrum);
 5178:         } else {
 5179:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 5180:                      '<span class="LC_error">'.&mt('You do not have permission to view change logs').'</span>');
 5181:         }
 5182:     } else {
 5183:         $bread_crumbs_component = 'User Management';
 5184:         $args = { bread_crumbs           => $brcrum,
 5185:                   bread_crumbs_component => $bread_crumbs_component};
 5186:         $r->print(&header(undef,$args));
 5187:         $r->print(&print_main_menu($permission,$context,$crstype));
 5188:     }
 5189:     $r->print(&Apache::loncommon::end_page());
 5190:     return OK;
 5191: }
 5192: 
 5193: sub header {
 5194:     my ($jscript,$args) = @_;
 5195:     my $start_page;
 5196:     if (ref($args) eq 'HASH') {
 5197:         $start_page=&Apache::loncommon::start_page('User Management',$jscript,$args);
 5198:     } else {
 5199:         $start_page=&Apache::loncommon::start_page('User Management',$jscript);
 5200:     }
 5201:     return $start_page;
 5202: }
 5203: 
 5204: sub add_script {
 5205:     my ($js) = @_;
 5206:     return '<script type="text/javascript">'."\n"
 5207:           .'// <![CDATA['."\n"
 5208:           .$js."\n"
 5209:           .'// ]]>'."\n"
 5210:           .'</script>'."\n";
 5211: }
 5212: 
 5213: sub usernamerequest_javascript {
 5214:     my $js = <<ENDJS;
 5215: 
 5216: function openusernamereqdisplay(dom,uname,queue) {
 5217:     var url = '/adm/createuser?action=displayuserreq';
 5218:     url += '&domain='+dom+'&username='+uname+'&queue='+queue;
 5219:     var title = 'Account_Request_Browser';
 5220:     var options = 'scrollbars=1,resizable=1,menubar=0';
 5221:     options += ',width=700,height=600';
 5222:     var stdeditbrowser = open(url,title,options,'1');
 5223:     stdeditbrowser.focus();
 5224:     return;
 5225: }
 5226:  
 5227: ENDJS
 5228: }
 5229: 
 5230: sub close_popup_form {
 5231:     my $close= &mt('Close Window');
 5232:     return << "END";
 5233: <p><form name="displayreq" action="" method="post">
 5234: <input type="button" name="closeme" value="$close" onclick="javascript:self.close();" />
 5235: </form></p>
 5236: END
 5237: }
 5238: 
 5239: sub verify_user_display {
 5240:     my ($context) = @_;
 5241:     my %lt = &Apache::lonlocal::texthash (
 5242:         course    => 'course(s): description, section(s), status',
 5243:         community => 'community(s): description, section(s), status',
 5244:         author    => 'author',
 5245:     );
 5246:     my $photos;
 5247:     if (($context eq 'course') && $env{'request.course.id'}) {
 5248:         $photos = $env{'course.'.$env{'request.course.id'}.'.internal.showphoto'};
 5249:     }
 5250:     my $output = <<"END";
 5251: 
 5252: function hide_searching() {
 5253:     if (document.getElementById('searching')) {
 5254:         document.getElementById('searching').style.display = 'none';
 5255:     }
 5256:     return;
 5257: }
 5258: 
 5259: function display_update() {
 5260:     document.studentform.action.value = 'listusers';
 5261:     document.studentform.phase.value = 'display';
 5262:     document.studentform.submit();
 5263: }
 5264: 
 5265: function updateCols(caller) {
 5266:     var context = '$context';
 5267:     var photos = '$photos';
 5268:     if (caller == 'Status') {
 5269:         if ((context == 'domain') && 
 5270:             ((document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'course') ||
 5271:              (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'community'))) {
 5272:             document.getElementById('showcolstatus').checked = false;
 5273:             document.getElementById('showcolstatus').disabled = 'disabled';
 5274:             document.getElementById('showcolstart').checked = false;
 5275:             document.getElementById('showcolend').checked = false;
 5276:         } else {
 5277:             if (document.studentform.Status.options[document.studentform.Status.selectedIndex].value == 'Any') {
 5278:                 document.getElementById('showcolstatus').checked = true;
 5279:                 document.getElementById('showcolstatus').disabled = '';
 5280:                 document.getElementById('showcolstart').checked = true;
 5281:                 document.getElementById('showcolend').checked = true;
 5282:             } else {
 5283:                 document.getElementById('showcolstatus').checked = false;
 5284:                 document.getElementById('showcolstatus').disabled = 'disabled';
 5285:                 document.getElementById('showcolstart').checked = false;
 5286:                 document.getElementById('showcolend').checked = false;
 5287:             }
 5288:         }
 5289:     }
 5290:     if (caller == 'output') {
 5291:         if (photos == 1) {
 5292:             if (document.getElementById('showcolphoto')) {
 5293:                 var photoitem = document.getElementById('showcolphoto');
 5294:                 if (document.studentform.output.options[document.studentform.output.selectedIndex].value == 'html') {
 5295:                     photoitem.checked = true;
 5296:                     photoitem.disabled = '';
 5297:                 } else {
 5298:                     photoitem.checked = false;
 5299:                     photoitem.disabled = 'disabled';
 5300:                 }
 5301:             }
 5302:         }
 5303:     }
 5304:     if (caller == 'showrole') {
 5305:         if ((document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'Any') ||
 5306:             (document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'cr')) {
 5307:             document.getElementById('showcolrole').checked = true;
 5308:             document.getElementById('showcolrole').disabled = '';
 5309:         } else {
 5310:             document.getElementById('showcolrole').checked = false;
 5311:             document.getElementById('showcolrole').disabled = 'disabled';
 5312:         }
 5313:         if (context == 'domain') {
 5314:             var quotausageshow = 0;
 5315:             if ((document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'course') ||
 5316:                 (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'community')) {
 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:             } else {
 5322:                 if (document.studentform.Status.options[document.studentform.Status.selectedIndex].value == 'Any') {
 5323:                     document.getElementById('showcolstatus').checked = true;
 5324:                     document.getElementById('showcolstatus').disabled = '';
 5325:                     document.getElementById('showcolstart').checked = true;
 5326:                     document.getElementById('showcolend').checked = true;
 5327:                 }
 5328:             }
 5329:             if (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'domain') {
 5330:                 document.getElementById('showcolextent').disabled = 'disabled';
 5331:                 document.getElementById('showcolextent').checked = 'false';
 5332:                 document.getElementById('showextent').style.display='none';
 5333:                 document.getElementById('showcoltextextent').innerHTML = '';
 5334:                 if ((document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'au') ||
 5335:                     (document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'Any')) {
 5336:                     if (document.getElementById('showcolauthorusage')) {
 5337:                         document.getElementById('showcolauthorusage').disabled = '';
 5338:                     }
 5339:                     if (document.getElementById('showcolauthorquota')) {
 5340:                         document.getElementById('showcolauthorquota').disabled = '';
 5341:                     }
 5342:                     quotausageshow = 1;
 5343:                 }
 5344:             } else {
 5345:                 document.getElementById('showextent').style.display='block';
 5346:                 document.getElementById('showextent').style.textAlign='left';
 5347:                 document.getElementById('showextent').style.textFace='normal';
 5348:                 if (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'author') {
 5349:                     document.getElementById('showcolextent').disabled = '';
 5350:                     document.getElementById('showcolextent').checked = 'true';
 5351:                     document.getElementById('showcoltextextent').innerHTML="$lt{'author'}";
 5352:                 } else {
 5353:                     document.getElementById('showcolextent').disabled = '';
 5354:                     document.getElementById('showcolextent').checked = 'true';
 5355:                     if (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'community') {
 5356:                         document.getElementById('showcoltextextent').innerHTML="$lt{'community'}";
 5357:                     } else {
 5358:                         document.getElementById('showcoltextextent').innerHTML="$lt{'course'}";
 5359:                     }
 5360:                 }
 5361:             }
 5362:             if (quotausageshow == 0)  {
 5363:                 if (document.getElementById('showcolauthorusage')) {
 5364:                     document.getElementById('showcolauthorusage').checked = false;
 5365:                     document.getElementById('showcolauthorusage').disabled = 'disabled';
 5366:                 }
 5367:                 if (document.getElementById('showcolauthorquota')) {
 5368:                     document.getElementById('showcolauthorquota').checked = false;
 5369:                     document.getElementById('showcolauthorquota').disabled = 'disabled';
 5370:                 }
 5371:             }
 5372:         }
 5373:     }
 5374:     return;
 5375: }
 5376: 
 5377: END
 5378:     return $output;
 5379: 
 5380: }
 5381: 
 5382: ###############################################################
 5383: ###############################################################
 5384: #  Menu Phase One
 5385: sub print_main_menu {
 5386:     my ($permission,$context,$crstype) = @_;
 5387:     my $linkcontext = $context;
 5388:     my $stuterm = lc(&Apache::lonnet::plaintext('st',$crstype));
 5389:     if (($context eq 'course') && ($crstype eq 'Community')) {
 5390:         $linkcontext = lc($crstype);
 5391:         $stuterm = 'Members';
 5392:     }
 5393:     my %links = (
 5394:                 domain => {
 5395:                             upload     => 'Upload a File of Users',
 5396:                             singleuser => 'Add/Modify a User',
 5397:                             listusers  => 'Manage Users',
 5398:                             },
 5399:                 author => {
 5400:                             upload     => 'Upload a File of Co-authors',
 5401:                             singleuser => 'Add/Modify a Co-author',
 5402:                             listusers  => 'Manage Co-authors',
 5403:                             },
 5404:                 course => {
 5405:                             upload     => 'Upload a File of Course Users',
 5406:                             singleuser => 'Add/Modify a Course User',
 5407:                             listusers  => 'List and Modify Multiple Course Users',
 5408:                             },
 5409:                 community => {
 5410:                             upload     => 'Upload a File of Community Users',
 5411:                             singleuser => 'Add/Modify a Community User',
 5412:                             listusers  => 'List and Modify Multiple Community Users',
 5413:                            },
 5414:                 );
 5415:      my %linktitles = (
 5416:                 domain => {
 5417:                             singleuser => 'Add a user to the domain, and/or a course or community in the domain.',
 5418:                             listusers  => 'Show and manage users in this domain.',
 5419:                             },
 5420:                 author => {
 5421:                             singleuser => 'Add a user with a co- or assistant author role.',
 5422:                             listusers  => 'Show and manage co- or assistant authors.',
 5423:                             },
 5424:                 course => {
 5425:                             singleuser => 'Add a user with a certain role to this course.',
 5426:                             listusers  => 'Show and manage users in this course.',
 5427:                             },
 5428:                 community => {
 5429:                             singleuser => 'Add a user with a certain role to this community.',
 5430:                             listusers  => 'Show and manage users in this community.',
 5431:                            },
 5432:                 );
 5433:   if ($linkcontext eq 'domain') {
 5434:       unless ($permission->{'cusr'}) {
 5435:           $links{'domain'}{'singleuser'} = 'View a User';
 5436:           $linktitles{'domain'}{'singleuser'} = 'View information about a user in the domain';
 5437: 
 5438:       }
 5439:   } elsif ($linkcontext eq 'course') {
 5440:       unless ($permission->{'cusr'}) {
 5441:           $links{'course'}{'singleuser'} = 'View a Course User';
 5442:           $linktitles{'course'}{'singleuser'} = 'View information about a user in this course';
 5443:           $links{'course'}{'listusers'} = 'List Course Users';
 5444:           $linktitles{'course'}{'listusers'} = 'Show information about users in this course';
 5445:       }
 5446:   } elsif ($linkcontext eq 'community') {
 5447:       unless ($permission->{'cusr'}) {
 5448:           $links{'community'}{'singleuser'} = 'View a Community User';
 5449:           $linktitles{'community'}{'singleuser'} = 'View information about a user in this community';
 5450:           $links{'community'}{'listusers'} = 'List Community Users';
 5451:           $linktitles{'community'}{'listusers'} = 'Show information about users in this community';
 5452:       }
 5453:   }
 5454:   my @menu = ( {categorytitle => 'Single Users', 
 5455:          items =>
 5456:          [
 5457:             {
 5458:              linktext => $links{$linkcontext}{'singleuser'},
 5459:              icon => 'edit-redo.png',
 5460:              #help => 'Course_Change_Privileges',
 5461:              url => '/adm/createuser?action=singleuser',
 5462:              permission => ($permission->{'view'} || $permission->{'cusr'}),
 5463:              linktitle => $linktitles{$linkcontext}{'singleuser'},
 5464:             },
 5465:          ]},
 5466: 
 5467:          {categorytitle => 'Multiple Users',
 5468:          items => 
 5469:          [
 5470:             {
 5471:              linktext => $links{$linkcontext}{'upload'},
 5472:              icon => 'uplusr.png',
 5473:              #help => 'Course_Create_Class_List',
 5474:              url => '/adm/createuser?action=upload',
 5475:              permission => $permission->{'cusr'},
 5476:              linktitle => 'Upload a CSV or a text file containing users.',
 5477:             },
 5478:             {
 5479:              linktext => $links{$linkcontext}{'listusers'},
 5480:              icon => 'mngcu.png',
 5481:              #help => 'Course_View_Class_List',
 5482:              url => '/adm/createuser?action=listusers',
 5483:              permission => ($permission->{'view'} || $permission->{'cusr'}),
 5484:              linktitle => $linktitles{$linkcontext}{'listusers'}, 
 5485:             },
 5486: 
 5487:          ]},
 5488: 
 5489:          {categorytitle => 'Administration',
 5490:          items => [ ]},
 5491:        );
 5492: 
 5493:     if ($context eq 'domain'){
 5494:         push(@{  $menu[0]->{items} }, # Single Users
 5495:             {
 5496:              linktext => 'User Access Log',
 5497:              icon => 'document-properties.png',
 5498:              #help => 'User_Access_Logs',
 5499:              url => '/adm/createuser?action=accesslogs',
 5500:              permission => $permission->{'activity'},
 5501:              linktitle => 'View user access log.',
 5502:             }
 5503:         );
 5504:         
 5505:         push(@{ $menu[2]->{items} }, #Category: Administration
 5506:             {
 5507:              linktext => 'Custom Roles',
 5508:              icon => 'emblem-photos.png',
 5509:              #help => 'Course_Editing_Custom_Roles',
 5510:              url => '/adm/createuser?action=custom',
 5511:              permission => $permission->{'custom'},
 5512:              linktitle => 'Configure a custom role.',
 5513:             },
 5514:             {
 5515:              linktext => 'Authoring Space Requests',
 5516:              icon => 'selfenrl-queue.png',
 5517:              #help => 'Domain_Role_Approvals',
 5518:              url => '/adm/createuser?action=processauthorreq',
 5519:              permission => $permission->{'cusr'},
 5520:              linktitle => 'Approve or reject author role requests',
 5521:             },
 5522:             {
 5523:              linktext => 'LON-CAPA Account Requests',
 5524:              icon => 'list-add.png',
 5525:              #help => 'Domain_Username_Approvals',
 5526:              url => '/adm/createuser?action=processusernamereq',
 5527:              permission => $permission->{'cusr'},
 5528:              linktitle => 'Approve or reject LON-CAPA account requests',
 5529:             },
 5530:             {
 5531:              linktext => 'Change Log',
 5532:              icon => 'document-properties.png',
 5533:              #help => 'Course_User_Logs',
 5534:              url => '/adm/createuser?action=changelogs',
 5535:              permission => ($permission->{'cusr'} || $permission->{'view'}),
 5536:              linktitle => 'View change log.',
 5537:             },
 5538:         );
 5539:         
 5540:     }elsif ($context eq 'course'){
 5541:         my ($cnum,$cdom) = &Apache::lonuserutils::get_course_identity();
 5542: 
 5543:         my %linktext = (
 5544:                          'Course'    => {
 5545:                                           single => 'Add/Modify a Student', 
 5546:                                           drop   => 'Drop Students',
 5547:                                           groups => 'Course Groups',
 5548:                                         },
 5549:                          'Community' => {
 5550:                                           single => 'Add/Modify a Member', 
 5551:                                           drop   => 'Drop Members',
 5552:                                           groups => 'Community Groups',
 5553:                                         },
 5554:                        );
 5555: 
 5556:         my %linktitle = (
 5557:             'Course' => {
 5558:                   single => 'Add a user with the role of student to this course',
 5559:                   drop   => 'Remove a student from this course.',
 5560:                   groups => 'Manage course groups',
 5561:                         },
 5562:             'Community' => {
 5563:                   single => 'Add a user with the role of member to this community',
 5564:                   drop   => 'Remove a member from this community.',
 5565:                   groups => 'Manage community groups',
 5566:                            },
 5567:         );
 5568: 
 5569:         push(@{ $menu[0]->{items} }, #Category: Single Users
 5570:             {   
 5571:              linktext => $linktext{$crstype}{'single'},
 5572:              #help => 'Course_Add_Student',
 5573:              icon => 'list-add.png',
 5574:              url => '/adm/createuser?action=singlestudent',
 5575:              permission => $permission->{'cusr'},
 5576:              linktitle => $linktitle{$crstype}{'single'},
 5577:             },
 5578:         );
 5579:         
 5580:         push(@{ $menu[1]->{items} }, #Category: Multiple Users 
 5581:             {
 5582:              linktext => $linktext{$crstype}{'drop'},
 5583:              icon => 'edit-undo.png',
 5584:              #help => 'Course_Drop_Student',
 5585:              url => '/adm/createuser?action=drop',
 5586:              permission => $permission->{'cusr'},
 5587:              linktitle => $linktitle{$crstype}{'drop'},
 5588:             },
 5589:         );
 5590:         push(@{ $menu[2]->{items} }, #Category: Administration
 5591:             {    
 5592:              linktext => 'Custom Roles',
 5593:              icon => 'emblem-photos.png',
 5594:              #help => 'Course_Editing_Custom_Roles',
 5595:              url => '/adm/createuser?action=custom',
 5596:              permission => $permission->{'custom'},
 5597:              linktitle => 'Configure a custom role.',
 5598:             },
 5599:             {
 5600:              linktext => $linktext{$crstype}{'groups'},
 5601:              icon => 'grps.png',
 5602:              #help => 'Course_Manage_Group',
 5603:              url => '/adm/coursegroups?refpage=cusr',
 5604:              permission => $permission->{'grp_manage'},
 5605:              linktitle => $linktitle{$crstype}{'groups'},
 5606:             },
 5607:             {
 5608:              linktext => 'Change Log',
 5609:              icon => 'document-properties.png',
 5610:              #help => 'Course_User_Logs',
 5611:              url => '/adm/createuser?action=changelogs',
 5612:              permission => ($permission->{'view'} || $permission->{'cusr'}),
 5613:              linktitle => 'View change log.',
 5614:             },
 5615:         );
 5616:         if ($env{'course.'.$env{'request.course.id'}.'.internal.selfenroll_approval'}) {
 5617:             push(@{ $menu[2]->{items} },
 5618:                     {
 5619:                      linktext => 'Enrollment Requests',
 5620:                      icon => 'selfenrl-queue.png',
 5621:                      #help => 'Course_Approve_Selfenroll',
 5622:                      url => '/adm/createuser?action=selfenrollqueue',
 5623:                      permission => $permission->{'selfenrolladmin'},
 5624:                      linktitle =>'Approve or reject enrollment requests.',
 5625:                     },
 5626:             );
 5627:         }
 5628:         
 5629:         if (!exists($permission->{'cusr_section'})){
 5630:             if ($crstype ne 'Community') {
 5631:                 push(@{ $menu[2]->{items} },
 5632:                     {
 5633:                      linktext => 'Automated Enrollment',
 5634:                      icon => 'roles.png',
 5635:                      #help => 'Course_Automated_Enrollment',
 5636:                      permission => (&Apache::lonnet::auto_run($cnum,$cdom)
 5637:                                          && (($permission->{'cusr'}) ||
 5638:                                              ($permission->{'view'}))),
 5639:                      url  => '/adm/populate',
 5640:                      linktitle => 'Automated enrollment manager.',
 5641:                     }
 5642:                 );
 5643:             }
 5644:             push(@{ $menu[2]->{items} }, 
 5645:                 {
 5646:                  linktext => 'User Self-Enrollment',
 5647:                  icon => 'self_enroll.png',
 5648:                  #help => 'Course_Self_Enrollment',
 5649:                  url => '/adm/createuser?action=selfenroll',
 5650:                  permission => $permission->{'selfenrolladmin'},
 5651:                  linktitle => 'Configure user self-enrollment.',
 5652:                 },
 5653:             );
 5654:         }
 5655:     } elsif ($context eq 'author') {
 5656:         push(@{ $menu[2]->{items} }, #Category: Administration
 5657:             {
 5658:              linktext => 'Change Log',
 5659:              icon => 'document-properties.png',
 5660:              #help => 'Course_User_Logs',
 5661:              url => '/adm/createuser?action=changelogs',
 5662:              permission => $permission->{'cusr'},
 5663:              linktitle => 'View change log.',
 5664:             },
 5665:         );
 5666:     }
 5667:     return Apache::lonhtmlcommon::generate_menu(@menu);
 5668: #               { text => 'View Log-in History',
 5669: #                 help => 'Course_User_Logins',
 5670: #                 action => 'logins',
 5671: #                 permission => $permission->{'cusr'},
 5672: #               });
 5673: }
 5674: 
 5675: sub restore_prev_selections {
 5676:     my %saveable_parameters = ('srchby'   => 'scalar',
 5677: 			       'srchin'   => 'scalar',
 5678: 			       'srchtype' => 'scalar',
 5679: 			       );
 5680:     &Apache::loncommon::store_settings('user','user_picker',
 5681: 				       \%saveable_parameters);
 5682:     &Apache::loncommon::restore_settings('user','user_picker',
 5683: 					 \%saveable_parameters);
 5684: }
 5685: 
 5686: sub print_selfenroll_menu {
 5687:     my ($r,$context,$cid,$cdom,$cnum,$currsettings,$additional,$readonly) = @_;
 5688:     my $crstype = &Apache::loncommon::course_type();
 5689:     my $formname = 'selfenroll';
 5690:     my $nolink = 1;
 5691:     my ($row,$lt) = &Apache::lonuserutils::get_selfenroll_titles();
 5692:     my $groupslist = &Apache::lonuserutils::get_groupslist();
 5693:     my $setsec_js = 
 5694:         &Apache::lonuserutils::setsections_javascript($formname,$groupslist);
 5695:     my %alerts = &Apache::lonlocal::texthash(
 5696:         acto => 'Activation of self-enrollment was selected for the following domain(s)',
 5697:         butn => 'but no user types have been checked.',
 5698:         wilf => "Please uncheck 'activate' or check at least one type.",
 5699:     );
 5700:     my $disabled;
 5701:     if ($readonly) {
 5702:        $disabled = ' disabled="disabled"';
 5703:     }
 5704:     &js_escape(\%alerts);
 5705:     my $selfenroll_js = <<"ENDSCRIPT";
 5706: function update_types(caller,num) {
 5707:     var delidx = getIndexByName('selfenroll_delete');
 5708:     var actidx = getIndexByName('selfenroll_activate');
 5709:     if (caller == 'selfenroll_all') {
 5710:         var selall;
 5711:         for (var i=0; i<document.$formname.selfenroll_all.length; i++) {
 5712:             if (document.$formname.selfenroll_all[i].checked) {
 5713:                 selall = document.$formname.selfenroll_all[i].value;
 5714:             }
 5715:         }
 5716:         if (selall == 1) {
 5717:             if (delidx != -1) {
 5718:                 if (document.$formname.selfenroll_delete.length) {
 5719:                     for (var j=0; j<document.$formname.selfenroll_delete.length; j++) {
 5720:                         document.$formname.selfenroll_delete[j].checked = true;
 5721:                     }
 5722:                 } else {
 5723:                     document.$formname.elements[delidx].checked = true;
 5724:                 }
 5725:             }
 5726:             if (actidx != -1) {
 5727:                 if (document.$formname.selfenroll_activate.length) {
 5728:                     for (var j=0; j<document.$formname.selfenroll_activate.length; j++) {
 5729:                         document.$formname.selfenroll_activate[j].checked = false;
 5730:                     }
 5731:                 } else {
 5732:                     document.$formname.elements[actidx].checked = false;
 5733:                 }
 5734:             }
 5735:             document.$formname.selfenroll_newdom.selectedIndex = 0; 
 5736:         }
 5737:     }
 5738:     if (caller == 'selfenroll_activate') {
 5739:         if (document.$formname.selfenroll_activate.length) {
 5740:             for (var j=0; j<document.$formname.selfenroll_activate.length; j++) {
 5741:                 if (document.$formname.selfenroll_activate[j].value == num) {
 5742:                     if (document.$formname.selfenroll_activate[j].checked) {
 5743:                         for (var i=0; i<document.$formname.selfenroll_all.length; i++) {
 5744:                             if (document.$formname.selfenroll_all[i].value == '1') {
 5745:                                 document.$formname.selfenroll_all[i].checked = false;
 5746:                             }
 5747:                             if (document.$formname.selfenroll_all[i].value == '0') {
 5748:                                 document.$formname.selfenroll_all[i].checked = true;
 5749:                             }
 5750:                         }
 5751:                     }
 5752:                 }
 5753:             }
 5754:         } else {
 5755:             for (var i=0; i<document.$formname.selfenroll_all.length; i++) {
 5756:                 if (document.$formname.selfenroll_all[i].value == '1') {
 5757:                     document.$formname.selfenroll_all[i].checked = false;
 5758:                 }
 5759:                 if (document.$formname.selfenroll_all[i].value == '0') {
 5760:                     document.$formname.selfenroll_all[i].checked = true;
 5761:                 }
 5762:             }
 5763:         }
 5764:     }
 5765:     if (caller == 'selfenroll_delete') {
 5766:         if (document.$formname.selfenroll_delete.length) {
 5767:             for (var j=0; j<document.$formname.selfenroll_delete.length; j++) {
 5768:                 if (document.$formname.selfenroll_delete[j].value == num) {
 5769:                     if (document.$formname.selfenroll_delete[j].checked) {
 5770:                         var delindex = getIndexByName('selfenroll_types_'+num);
 5771:                         if (delindex != -1) { 
 5772:                             if (document.$formname.elements[delindex].length) {
 5773:                                 for (var k=0; k<document.$formname.elements[delindex].length; k++) {
 5774:                                     document.$formname.elements[delindex][k].checked = false;
 5775:                                 }
 5776:                             } else {
 5777:                                 document.$formname.elements[delindex].checked = false;
 5778:                             }
 5779:                         }
 5780:                     }
 5781:                 }
 5782:             }
 5783:         } else {
 5784:             if (document.$formname.selfenroll_delete.checked) {
 5785:                 var delindex = getIndexByName('selfenroll_types_'+num);
 5786:                 if (delindex != -1) {
 5787:                     if (document.$formname.elements[delindex].length) {
 5788:                         for (var k=0; k<document.$formname.elements[delindex].length; k++) {
 5789:                             document.$formname.elements[delindex][k].checked = false;
 5790:                         }
 5791:                     } else {
 5792:                         document.$formname.elements[delindex].checked = false;
 5793:                     }
 5794:                 }
 5795:             }
 5796:         }
 5797:     }
 5798:     return;
 5799: }
 5800: 
 5801: function validate_types(form) {
 5802:     var needaction = new Array();
 5803:     var countfail = 0;
 5804:     var actidx = getIndexByName('selfenroll_activate');
 5805:     if (actidx != -1) {
 5806:         if (document.$formname.selfenroll_activate.length) {
 5807:             for (var j=0; j<document.$formname.selfenroll_activate.length; j++) {
 5808:                 var num = document.$formname.selfenroll_activate[j].value;
 5809:                 if (document.$formname.selfenroll_activate[j].checked) {
 5810:                     countfail = check_types(num,countfail,needaction)
 5811:                 }
 5812:             }
 5813:         } else {
 5814:             if (document.$formname.selfenroll_activate.checked) {
 5815:                 var num = document.$formname.selfenroll_activate.value;
 5816:                 countfail = check_types(num,countfail,needaction)
 5817:             }
 5818:         }
 5819:     }
 5820:     if (countfail > 0) {
 5821:         var msg = "$alerts{'acto'}\\n";
 5822:         var loopend = needaction.length -1;
 5823:         if (loopend > 0) {
 5824:             for (var m=0; m<loopend; m++) {
 5825:                 msg += needaction[m]+", ";
 5826:             }
 5827:         }
 5828:         msg += needaction[loopend]+"\\n$alerts{'butn'}\\n$alerts{'wilf'}";
 5829:         alert(msg);
 5830:         return; 
 5831:     }
 5832:     setSections(form);
 5833: }
 5834: 
 5835: function check_types(num,countfail,needaction) {
 5836:     var typeidx = getIndexByName('selfenroll_types_'+num);
 5837:     var count = 0;
 5838:     if (typeidx != -1) {
 5839:         if (document.$formname.elements[typeidx].length) {
 5840:             for (var k=0; k<document.$formname.elements[typeidx].length; k++) {
 5841:                 if (document.$formname.elements[typeidx][k].checked) {
 5842:                     count ++;
 5843:                 }
 5844:             }
 5845:         } else {
 5846:             if (document.$formname.elements[typeidx].checked) {
 5847:                 count ++;
 5848:             }
 5849:         }
 5850:         if (count == 0) {
 5851:             var domidx = getIndexByName('selfenroll_dom_'+num);
 5852:             if (domidx != -1) {
 5853:                 var domname = document.$formname.elements[domidx].value;
 5854:                 needaction[countfail] = domname;
 5855:                 countfail ++;
 5856:             }
 5857:         }
 5858:     }
 5859:     return countfail;
 5860: }
 5861: 
 5862: function toggleNotify() {
 5863:     var selfenrollApproval = 0;
 5864:     if (document.$formname.selfenroll_approval.length) {
 5865:         for (var i=0; i<document.$formname.selfenroll_approval.length; i++) {
 5866:             if (document.$formname.selfenroll_approval[i].checked) {
 5867:                 selfenrollApproval = document.$formname.selfenroll_approval[i].value;
 5868:                 break;        
 5869:             }
 5870:         }
 5871:     }
 5872:     if (document.getElementById('notified')) {
 5873:         if (selfenrollApproval == 0) {
 5874:             document.getElementById('notified').style.display='none';
 5875:         } else {
 5876:             document.getElementById('notified').style.display='block';
 5877:         }
 5878:     }
 5879:     return;
 5880: }
 5881: 
 5882: function getIndexByName(item) {
 5883:     for (var i=0;i<document.$formname.elements.length;i++) {
 5884:         if (document.$formname.elements[i].name == item) {
 5885:             return i;
 5886:         }
 5887:     }
 5888:     return -1;
 5889: }
 5890: ENDSCRIPT
 5891: 
 5892:     my $output = '<script type="text/javascript">'."\n".
 5893:                  '// <![CDATA['."\n".
 5894:                  $setsec_js."\n".$selfenroll_js."\n".
 5895:                  '// ]]>'."\n".
 5896:                  '</script>'."\n".
 5897:                  '<h3>'.$lt->{'selfenroll'}.'</h3>'."\n";
 5898:  
 5899:     my $visactions = &cat_visibility();
 5900:     my ($cathash,%cattype);
 5901:     my %domconfig = &Apache::lonnet::get_dom('configuration',['coursecategories'],$cdom);
 5902:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 5903:         $cathash = $domconfig{'coursecategories'}{'cats'};
 5904:         $cattype{'auth'} = $domconfig{'coursecategories'}{'auth'};
 5905:         $cattype{'unauth'} = $domconfig{'coursecategories'}{'unauth'};
 5906:         if ($cattype{'auth'} eq '') {
 5907:             $cattype{'auth'} = 'std';
 5908:         }
 5909:         if ($cattype{'unauth'} eq '') {
 5910:             $cattype{'unauth'} = 'std';
 5911:         }
 5912:     } else {
 5913:         $cathash = {};
 5914:         $cattype{'auth'} = 'std';
 5915:         $cattype{'unauth'} = 'std';
 5916:     }
 5917:     if (($cattype{'auth'} eq 'none') && ($cattype{'unauth'} eq 'none')) {
 5918:         $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
 5919:                   '<br />'.
 5920:                   '<br />'.$visactions->{'take'}.'<ul>'.
 5921:                   '<li>'.$visactions->{'dc_chgconf'}.'</li>'.
 5922:                   '</ul>');
 5923:     } elsif (($cattype{'auth'} !~ /^(std|domonly)$/) && ($cattype{'unauth'} !~ /^(std|domonly)$/)) {
 5924:         if ($currsettings->{'uniquecode'}) {
 5925:             $r->print('<span class="LC_info">'.$visactions->{'vis'}.'</span>');
 5926:         } else {
 5927:             $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
 5928:                   '<br />'.
 5929:                   '<br />'.$visactions->{'take'}.'<ul>'.
 5930:                   '<li>'.$visactions->{'dc_setcode'}.'</li>'.
 5931:                   '</ul><br />');
 5932:         }
 5933:     } else {
 5934:         my ($visible,$cansetvis,$vismsgs) = &visible_in_stdcat($cdom,$cnum,\%domconfig);
 5935:         if (ref($visactions) eq 'HASH') {
 5936:             if ($visible) {
 5937:                 $output .= '<p class="LC_info">'.$visactions->{'vis'}.'</p>';
 5938:            } else {
 5939:                 $output .= '<p class="LC_warning">'.$visactions->{'miss'}.'</p>'
 5940:                           .$visactions->{'yous'}.
 5941:                            '<p>'.$visactions->{'gen'}.'<br />'.$visactions->{'coca'};
 5942:                 if (ref($vismsgs) eq 'ARRAY') {
 5943:                     $output .= '<br />'.$visactions->{'make'}.'<ul>';
 5944:                     foreach my $item (@{$vismsgs}) {
 5945:                         $output .= '<li>'.$visactions->{$item}.'</li>';
 5946:                     }
 5947:                     $output .= '</ul>';
 5948:                 }
 5949:                 $output .= '</p>';
 5950:             }
 5951:         }
 5952:     }
 5953:     my $actionhref = '/adm/createuser';
 5954:     if ($context eq 'domain') {
 5955:         $actionhref = '/adm/modifycourse';
 5956:     }
 5957: 
 5958:     my %noedit;
 5959:     unless ($context eq 'domain') {
 5960:         %noedit = &get_noedit_fields($cdom,$cnum,$crstype,$row);
 5961:     }
 5962:     $output .= '<form name="'.$formname.'" method="post" action="'.$actionhref.'">'."\n".
 5963:                &Apache::lonhtmlcommon::start_pick_box();
 5964:     if (ref($row) eq 'ARRAY') {
 5965:         foreach my $item (@{$row}) {
 5966:             my $title = $item; 
 5967:             if (ref($lt) eq 'HASH') {
 5968:                 $title = $lt->{$item};
 5969:             }
 5970:             $output .= &Apache::lonhtmlcommon::row_title($title);
 5971:             if ($item eq 'types') {
 5972:                 my $curr_types;
 5973:                 if (ref($currsettings) eq 'HASH') {
 5974:                     $curr_types = $currsettings->{'selfenroll_types'};
 5975:                 }
 5976:                 if ($noedit{$item}) {
 5977:                     if ($curr_types eq '*') {
 5978:                         $output .= &mt('Any user in any domain');   
 5979:                     } else {
 5980:                         my @entries = split(/;/,$curr_types);
 5981:                         if (@entries > 0) {
 5982:                             $output .= '<ul>'; 
 5983:                             foreach my $entry (@entries) {
 5984:                                 my ($currdom,$typestr) = split(/:/,$entry);
 5985:                                 next if ($typestr eq '');
 5986:                                 my $domdesc = &Apache::lonnet::domain($currdom);
 5987:                                 my @currinsttypes = split(',',$typestr);
 5988:                                 my ($othertitle,$usertypes,$types) = 
 5989:                                     &Apache::loncommon::sorted_inst_types($currdom);
 5990:                                 if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 5991:                                     $usertypes->{'any'} = &mt('any user'); 
 5992:                                     if (keys(%{$usertypes}) > 0) {
 5993:                                         $usertypes->{'other'} = &mt('other users');
 5994:                                     }
 5995:                                     my @longinsttypes = map { $usertypes->{$_}; } @currinsttypes;
 5996:                                     $output .= '<li>'.$domdesc.':'.join(', ',@longinsttypes).'</li>';
 5997:                                  }
 5998:                             }
 5999:                             $output .= '</ul>';
 6000:                         } else {
 6001:                             $output .= &mt('None');
 6002:                         }
 6003:                     }
 6004:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 6005:                     next;
 6006:                 }
 6007:                 my $showdomdesc = 1;
 6008:                 my $includeempty = 1;
 6009:                 my $num = 0;
 6010:                 $output .= &Apache::loncommon::start_data_table().
 6011:                            &Apache::loncommon::start_data_table_row()
 6012:                            .'<td colspan="2"><span class="LC_nobreak"><label>'
 6013:                            .&mt('Any user in any domain:')
 6014:                            .'&nbsp;<input type="radio" name="selfenroll_all" value="1" ';
 6015:                 if ($curr_types eq '*') {
 6016:                     $output .= ' checked="checked" '; 
 6017:                 }
 6018:                 $output .= 'onchange="javascript:update_types('.
 6019:                            "'selfenroll_all'".');"'.$disabled.' />'.&mt('Yes').'</label>'.
 6020:                            '&nbsp;&nbsp;<input type="radio" name="selfenroll_all" value="0" ';
 6021:                 if ($curr_types ne '*') {
 6022:                     $output .= ' checked="checked" ';
 6023:                 }
 6024:                 $output .= ' onchange="javascript:update_types('.
 6025:                            "'selfenroll_all'".');"'.$disabled.' />'.&mt('No').'</label></td>'.
 6026:                            &Apache::loncommon::end_data_table_row().
 6027:                            &Apache::loncommon::end_data_table().
 6028:                            &mt('Or').'<br />'.
 6029:                            &Apache::loncommon::start_data_table();
 6030:                 my %currdoms;
 6031:                 if ($curr_types eq '') {
 6032:                     $output .= &new_selfenroll_dom_row($cdom,'0');
 6033:                 } elsif ($curr_types ne '*') {
 6034:                     my @entries = split(/;/,$curr_types);
 6035:                     if (@entries > 0) {
 6036:                         foreach my $entry (@entries) {
 6037:                             my ($currdom,$typestr) = split(/:/,$entry);
 6038:                             $currdoms{$currdom} = 1;
 6039:                             my $domdesc = &Apache::lonnet::domain($currdom);
 6040:                             my @currinsttypes = split(',',$typestr);
 6041:                             $output .= &Apache::loncommon::start_data_table_row()
 6042:                                        .'<td valign="top"><span class="LC_nobreak">'.&mt('Domain:').'<b>'
 6043:                                        .'&nbsp;'.$domdesc.' ('.$currdom.')'
 6044:                                        .'</b><input type="hidden" name="selfenroll_dom_'.$num
 6045:                                        .'" value="'.$currdom.'" /></span><br />'
 6046:                                        .'<span class="LC_nobreak"><label><input type="checkbox" '
 6047:                                        .'name="selfenroll_delete" value="'.$num.'" onchange="javascript:update_types('."'selfenroll_delete','$num'".');"'.$disabled.' />'
 6048:                                        .&mt('Delete').'</label></span></td>';
 6049:                             $output .= '<td valign="top">&nbsp;&nbsp;'.&mt('User types:').'<br />'
 6050:                                        .&selfenroll_inst_types($num,$currdom,\@currinsttypes,$readonly).'</td>'
 6051:                                        .&Apache::loncommon::end_data_table_row();
 6052:                             $num ++;
 6053:                         }
 6054:                     }
 6055:                 }
 6056:                 my $add_domtitle = &mt('Users in additional domain:');
 6057:                 if ($curr_types eq '*') { 
 6058:                     $add_domtitle = &mt('Users in specific domain:');
 6059:                 } elsif ($curr_types eq '') {
 6060:                     $add_domtitle = &mt('Users in other domain:');
 6061:                 }
 6062:                 $output .= &Apache::loncommon::start_data_table_row()
 6063:                            .'<td colspan="2"><span class="LC_nobreak">'.$add_domtitle.'</span><br />'
 6064:                            .&Apache::loncommon::select_dom_form('','selfenroll_newdom',
 6065:                                                                 $includeempty,$showdomdesc,'','','',$readonly)
 6066:                            .'<input type="hidden" name="selfenroll_types_total" value="'.$num.'" />'
 6067:                            .'</td>'.&Apache::loncommon::end_data_table_row()
 6068:                            .&Apache::loncommon::end_data_table();
 6069:             } elsif ($item eq 'registered') {
 6070:                 my ($regon,$regoff);
 6071:                 my $registered;
 6072:                 if (ref($currsettings) eq 'HASH') {
 6073:                     $registered = $currsettings->{'selfenroll_registered'};
 6074:                 }
 6075:                 if ($noedit{$item}) {
 6076:                     if ($registered) {
 6077:                         $output .= &mt('Must be registered in course');
 6078:                     } else {
 6079:                         $output .= &mt('No requirement');
 6080:                     }
 6081:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 6082:                     next;
 6083:                 }
 6084:                 if ($registered) {
 6085:                     $regon = ' checked="checked" ';
 6086:                     $regoff = '';
 6087:                 } else {
 6088:                     $regon = '';
 6089:                     $regoff = ' checked="checked" ';
 6090:                 }
 6091:                 $output .= '<label>'.
 6092:                            '<input type="radio" name="selfenroll_registered" value="1"'.$regon.$disabled.' />'.
 6093:                            &mt('Yes').'</label>&nbsp;&nbsp;<label>'.
 6094:                            '<input type="radio" name="selfenroll_registered" value="0"'.$regoff.$disabled.' />'.
 6095:                            &mt('No').'</label>';
 6096:             } elsif ($item eq 'enroll_dates') {
 6097:                 my ($starttime,$endtime);
 6098:                 if (ref($currsettings) eq 'HASH') {
 6099:                     $starttime = $currsettings->{'selfenroll_start_date'};
 6100:                     $endtime = $currsettings->{'selfenroll_end_date'};
 6101:                     if ($starttime eq '') {
 6102:                         $starttime = $currsettings->{'default_enrollment_start_date'};
 6103:                     }
 6104:                     if ($endtime eq '') {
 6105:                         $endtime = $currsettings->{'default_enrollment_end_date'};
 6106:                     }
 6107:                 }
 6108:                 if ($noedit{$item}) {
 6109:                     $output .= &mt('From: [_1], to: [_2]',&Apache::lonlocal::locallocaltime($starttime),
 6110:                                                           &Apache::lonlocal::locallocaltime($endtime));
 6111:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 6112:                     next;
 6113:                 }
 6114:                 my $startform =
 6115:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_start_date',$starttime,
 6116:                                       $disabled,undef,undef,undef,undef,undef,undef,$nolink);
 6117:                 my $endform =
 6118:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_end_date',$endtime,
 6119:                                       $disabled,undef,undef,undef,undef,undef,undef,$nolink);
 6120:                 $output .= &selfenroll_date_forms($startform,$endform);
 6121:             } elsif ($item eq 'access_dates') {
 6122:                 my ($starttime,$endtime);
 6123:                 if (ref($currsettings) eq 'HASH') {
 6124:                     $starttime = $currsettings->{'selfenroll_start_access'};
 6125:                     $endtime = $currsettings->{'selfenroll_end_access'};
 6126:                     if ($starttime eq '') {
 6127:                         $starttime = $currsettings->{'default_enrollment_start_date'};
 6128:                     }
 6129:                     if ($endtime eq '') {
 6130:                         $endtime = $currsettings->{'default_enrollment_end_date'};
 6131:                     }
 6132:                 }
 6133:                 if ($noedit{$item}) {
 6134:                     $output .= &mt('From: [_1], to: [_2]',&Apache::lonlocal::locallocaltime($starttime),
 6135:                                                           &Apache::lonlocal::locallocaltime($endtime));
 6136:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 6137:                     next;
 6138:                 }
 6139:                 my $startform =
 6140:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_start_access',$starttime,
 6141:                                       $disabled,undef,undef,undef,undef,undef,undef,$nolink);
 6142:                 my $endform =
 6143:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_end_access',$endtime,
 6144:                                       $disabled,undef,undef,undef,undef,undef,undef,$nolink);
 6145:                 $output .= &selfenroll_date_forms($startform,$endform);
 6146:             } elsif ($item eq 'section') {
 6147:                 my $currsec;
 6148:                 if (ref($currsettings) eq 'HASH') {
 6149:                     $currsec = $currsettings->{'selfenroll_section'};
 6150:                 }
 6151:                 my %sections_count = &Apache::loncommon::get_sections($cdom,$cnum);
 6152:                 my $newsecval;
 6153:                 if ($currsec ne 'none' && $currsec ne '') {
 6154:                     if (!defined($sections_count{$currsec})) {
 6155:                         $newsecval = $currsec;
 6156:                     }
 6157:                 }
 6158:                 if ($noedit{$item}) {
 6159:                     if ($currsec ne '') {
 6160:                         $output .= $currsec;
 6161:                     } else {
 6162:                         $output .= &mt('No specific section');
 6163:                     }
 6164:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 6165:                     next;
 6166:                 }
 6167:                 my $sections_select = 
 6168:                     &Apache::lonuserutils::course_sections(\%sections_count,'st',$currsec,$disabled);
 6169:                 $output .= '<table class="LC_createuser">'."\n".
 6170:                            '<tr class="LC_section_row">'."\n".
 6171:                            '<td align="center">'.&mt('Existing sections')."\n".
 6172:                            '<br />'.$sections_select.'</td><td align="center">'.
 6173:                            &mt('New section').'<br />'."\n".
 6174:                            '<input type="text" name="newsec" size="15" value="'.$newsecval.'"'.$disabled.' />'."\n".
 6175:                            '<input type="hidden" name="sections" value="" />'."\n".
 6176:                            '</td></tr></table>'."\n";
 6177:             } elsif ($item eq 'approval') {
 6178:                 my ($currnotified,$currapproval,%appchecked);
 6179:                 my %selfdescs = &Apache::lonuserutils::selfenroll_default_descs();
 6180:                 if (ref($currsettings) eq 'HASH') {
 6181:                     $currnotified = $currsettings->{'selfenroll_notifylist'};
 6182:                     $currapproval = $currsettings->{'selfenroll_approval'};
 6183:                 }
 6184:                 if ($currapproval !~ /^[012]$/) {
 6185:                     $currapproval = 0;
 6186:                 }
 6187:                 if ($noedit{$item}) {
 6188:                     $output .=  $selfdescs{'approval'}{$currapproval}.
 6189:                                 '<br />'.&mt('(Set by Domain Coordinator)');
 6190:                     next;
 6191:                 }
 6192:                 $appchecked{$currapproval} = ' checked="checked"';
 6193:                 for my $i (0..2) {
 6194:                     $output .= '<label>'.
 6195:                                '<input type="radio" name="selfenroll_approval" value="'.$i.'"'.
 6196:                                $appchecked{$i}.' onclick="toggleNotify();"'.$disabled.' />'.
 6197:                                $selfdescs{'approval'}{$i}.'</label>'.('&nbsp;'x2);
 6198:                 }
 6199:                 my %advhash = &Apache::lonnet::get_course_adv_roles($cid,1);
 6200:                 my (@ccs,%notified);
 6201:                 my $ccrole = 'cc';
 6202:                 if ($crstype eq 'Community') {
 6203:                     $ccrole = 'co';
 6204:                 }
 6205:                 if ($advhash{$ccrole}) {
 6206:                     @ccs = split(/,/,$advhash{$ccrole});
 6207:                 }
 6208:                 if ($currnotified) {
 6209:                     foreach my $current (split(/,/,$currnotified)) {
 6210:                         $notified{$current} = 1;
 6211:                         if (!grep(/^\Q$current\E$/,@ccs)) {
 6212:                             push(@ccs,$current);
 6213:                         }
 6214:                     }
 6215:                 }
 6216:                 if (@ccs) {
 6217:                     my $style;
 6218:                     unless ($currapproval) {
 6219:                         $style = ' style="display: none;"'; 
 6220:                     }
 6221:                     $output .= '<br /><div id="notified"'.$style.'>'.
 6222:                                &mt('Personnel to be notified when an enrollment request needs approval, or has been approved:').'&nbsp;'.
 6223:                                &Apache::loncommon::start_data_table().
 6224:                                &Apache::loncommon::start_data_table_row();
 6225:                     my $count = 0;
 6226:                     my $numcols = 4;
 6227:                     foreach my $cc (sort(@ccs)) {
 6228:                         my $notifyon;
 6229:                         my ($ccuname,$ccudom) = split(/:/,$cc);
 6230:                         if ($notified{$cc}) {
 6231:                             $notifyon = ' checked="checked" ';
 6232:                         }
 6233:                         if ($count && !$count%$numcols) {
 6234:                             $output .= &Apache::loncommon::end_data_table_row().
 6235:                                        &Apache::loncommon::start_data_table_row()
 6236:                         }
 6237:                         $output .= '<td><span class="LC_nobreak"><label>'.
 6238:                                    '<input type="checkbox" name="selfenroll_notify"'.$notifyon.' value="'.$cc.'"'.$disabled.' />'.
 6239:                                    &Apache::loncommon::plainname($ccuname,$ccudom).
 6240:                                    '</label></span></td>';
 6241:                         $count ++;
 6242:                     }
 6243:                     my $rem = $count%$numcols;
 6244:                     if ($rem) {
 6245:                         my $emptycols = $numcols - $rem;
 6246:                         for (my $i=0; $i<$emptycols; $i++) { 
 6247:                             $output .= '<td>&nbsp;</td>';
 6248:                         }
 6249:                     }
 6250:                     $output .= &Apache::loncommon::end_data_table_row().
 6251:                                &Apache::loncommon::end_data_table().
 6252:                                '</div>';
 6253:                 }
 6254:             } elsif ($item eq 'limit') {
 6255:                 my ($crslimit,$selflimit,$nolimit,$currlim,$currcap);
 6256:                 if (ref($currsettings) eq 'HASH') {
 6257:                     $currlim = $currsettings->{'selfenroll_limit'};
 6258:                     $currcap = $currsettings->{'selfenroll_cap'};
 6259:                 }
 6260:                 if ($noedit{$item}) {
 6261:                     if (($currlim eq 'allstudents') || ($currlim eq 'selfenrolled')) {
 6262:                         if ($currlim eq 'allstudents') {
 6263:                             $output .= &mt('Limit by total students');
 6264:                         } elsif ($currlim eq 'selfenrolled') {
 6265:                             $output .= &mt('Limit by total self-enrolled students');
 6266:                         }
 6267:                         $output .= ' '.&mt('Maximum: [_1]',$currcap).
 6268:                                    '<br />'.&mt('(Set by Domain Coordinator)');
 6269:                     } else {
 6270:                         $output .= &mt('No limit').'<br />'.&mt('(Set by Domain Coordinator)');
 6271:                     }
 6272:                     next;
 6273:                 }
 6274:                 if ($currlim eq 'allstudents') {
 6275:                     $crslimit = ' checked="checked" ';
 6276:                     $selflimit = ' ';
 6277:                     $nolimit = ' ';
 6278:                 } elsif ($currlim eq 'selfenrolled') {
 6279:                     $crslimit = ' ';
 6280:                     $selflimit = ' checked="checked" ';
 6281:                     $nolimit = ' '; 
 6282:                 } else {
 6283:                     $crslimit = ' ';
 6284:                     $selflimit = ' ';
 6285:                     $nolimit = ' checked="checked" ';
 6286:                 }
 6287:                 $output .= '<table><tr><td><label>'.
 6288:                            '<input type="radio" name="selfenroll_limit" value="none"'.$nolimit.$disabled.'/>'.
 6289:                            &mt('No limit').'</label></td><td><label>'.
 6290:                            '<input type="radio" name="selfenroll_limit" value="allstudents"'.$crslimit.$disabled.'/>'.
 6291:                            &mt('Limit by total students').'</label></td><td><label>'.
 6292:                            '<input type="radio" name="selfenroll_limit" value="selfenrolled"'.$selflimit.$disabled.'/>'.
 6293:                            &mt('Limit by total self-enrolled students').
 6294:                            '</td></tr><tr>'.
 6295:                            '<td>&nbsp;</td><td colspan="2"><span class="LC_nobreak">'.
 6296:                            ('&nbsp;'x3).&mt('Maximum number allowed: ').
 6297:                            '<input type="text" name="selfenroll_cap" size = "5" value="'.$currcap.'"'.$disabled.' /></td></tr></table>';
 6298:             }
 6299:             $output .= &Apache::lonhtmlcommon::row_closure(1);
 6300:         }
 6301:     }
 6302:     $output .= &Apache::lonhtmlcommon::end_pick_box().'<br />';
 6303:     unless ($readonly) {
 6304:         $output .= '<input type="button" name="selfenrollconf" value="'
 6305:                    .&mt('Save').'" onclick="validate_types(this.form);" />';
 6306:     }
 6307:     $output .= '<input type="hidden" name="action" value="selfenroll" />'
 6308:                .'<input type="hidden" name="state" value="done" />'."\n"
 6309:                .$additional.'</form>';
 6310:     $r->print($output);
 6311:     return;
 6312: }
 6313: 
 6314: sub get_noedit_fields {
 6315:     my ($cdom,$cnum,$crstype,$row) = @_;
 6316:     my %noedit;
 6317:     if (ref($row) eq 'ARRAY') {
 6318:         my %settings = &Apache::lonnet::get('environment',['internal.coursecode','internal.textbook',
 6319:                                                            'internal.selfenrollmgrdc',
 6320:                                                            'internal.selfenrollmgrcc'],$cdom,$cnum);
 6321:         my $type = &Apache::lonuserutils::get_extended_type($cdom,$cnum,$crstype,\%settings);
 6322:         my (%specific_managebydc,%specific_managebycc,%default_managebydc);
 6323:         map { $specific_managebydc{$_} = 1; } (split(/,/,$settings{'internal.selfenrollmgrdc'}));
 6324:         map { $specific_managebycc{$_} = 1; } (split(/,/,$settings{'internal.selfenrollmgrcc'}));
 6325:         my %domdefaults = &Apache::lonnet::get_domain_defaults($cdom);
 6326:         map { $default_managebydc{$_} = 1; } (split(/,/,$domdefaults{$type.'selfenrolladmdc'}));
 6327: 
 6328:         foreach my $item (@{$row}) {
 6329:             next if ($specific_managebycc{$item});
 6330:             if (($specific_managebydc{$item}) || ($default_managebydc{$item})) {
 6331:                 $noedit{$item} = 1;
 6332:             }
 6333:         }
 6334:     }
 6335:     return %noedit;
 6336: } 
 6337: 
 6338: sub visible_in_stdcat {
 6339:     my ($cdom,$cnum,$domconf) = @_;
 6340:     my ($cathash,%settable,@vismsgs,$cansetvis,$visible);
 6341:     unless (ref($domconf) eq 'HASH') {
 6342:         return ($visible,$cansetvis,\@vismsgs);
 6343:     }
 6344:     if (ref($domconf->{'coursecategories'}) eq 'HASH') {
 6345:         if ($domconf->{'coursecategories'}{'togglecats'} eq 'crs') {
 6346:             $settable{'togglecats'} = 1;
 6347:         }
 6348:         if ($domconf->{'coursecategories'}{'categorize'} eq 'crs') {
 6349:             $settable{'categorize'} = 1;
 6350:         }
 6351:         $cathash = $domconf->{'coursecategories'}{'cats'};
 6352:     }
 6353:     if ($settable{'togglecats'} && $settable{'categorize'}) {
 6354:         $cansetvis = &mt('You are able to both assign a course category and choose to exclude this course from the catalog.');   
 6355:     } elsif ($settable{'togglecats'}) {
 6356:         $cansetvis = &mt('You are able to choose to exclude this course from the catalog, but only a Domain Coordinator may assign a course category.'); 
 6357:     } elsif ($settable{'categorize'}) {
 6358:         $cansetvis = &mt('You may assign a course category, but only a Domain Coordinator may choose to exclude this course from the catalog.');  
 6359:     } else {
 6360:         $cansetvis = &mt('Only a Domain Coordinator may assign a course category or choose to exclude this course from the catalog.'); 
 6361:     }
 6362:      
 6363:     my %currsettings =
 6364:         &Apache::lonnet::get('environment',['hidefromcat','categories','internal.coursecode'],
 6365:                              $cdom,$cnum);
 6366:     $visible = 0;
 6367:     if ($currsettings{'internal.coursecode'} ne '') {
 6368:         if (ref($domconf->{'coursecategories'}) eq 'HASH') {
 6369:             $cathash = $domconf->{'coursecategories'}{'cats'};
 6370:             if (ref($cathash) eq 'HASH') {
 6371:                 if ($cathash->{'instcode::0'} eq '') {
 6372:                     push(@vismsgs,'dc_addinst'); 
 6373:                 } else {
 6374:                     $visible = 1;
 6375:                 }
 6376:             } else {
 6377:                 $visible = 1;
 6378:             }
 6379:         } else {
 6380:             $visible = 1;
 6381:         }
 6382:     } else {
 6383:         if (ref($cathash) eq 'HASH') {
 6384:             if ($cathash->{'instcode::0'} ne '') {
 6385:                 push(@vismsgs,'dc_instcode');
 6386:             }
 6387:         } else {
 6388:             push(@vismsgs,'dc_instcode');
 6389:         }
 6390:     }
 6391:     if ($currsettings{'categories'} ne '') {
 6392:         my $cathash;
 6393:         if (ref($domconf->{'coursecategories'}) eq 'HASH') {
 6394:             $cathash = $domconf->{'coursecategories'}{'cats'};
 6395:             if (ref($cathash) eq 'HASH') {
 6396:                 if (keys(%{$cathash}) == 0) {
 6397:                     push(@vismsgs,'dc_catalog');
 6398:                 } elsif ((keys(%{$cathash}) == 1) && ($cathash->{'instcode::0'} ne '')) {
 6399:                     push(@vismsgs,'dc_categories');
 6400:                 } else {
 6401:                     my @currcategories = split('&',$currsettings{'categories'});
 6402:                     my $matched = 0;
 6403:                     foreach my $cat (@currcategories) {
 6404:                         if ($cathash->{$cat} ne '') {
 6405:                             $visible = 1;
 6406:                             $matched = 1;
 6407:                             last;
 6408:                         }
 6409:                     }
 6410:                     if (!$matched) {
 6411:                         if ($settable{'categorize'}) { 
 6412:                             push(@vismsgs,'chgcat');
 6413:                         } else {
 6414:                             push(@vismsgs,'dc_chgcat');
 6415:                         }
 6416:                     }
 6417:                 }
 6418:             }
 6419:         }
 6420:     } else {
 6421:         if (ref($cathash) eq 'HASH') {
 6422:             if ((keys(%{$cathash}) > 1) || 
 6423:                 (keys(%{$cathash}) == 1) && ($cathash->{'instcode::0'} eq '')) {
 6424:                 if ($settable{'categorize'}) {
 6425:                     push(@vismsgs,'addcat');
 6426:                 } else {
 6427:                     push(@vismsgs,'dc_addcat');
 6428:                 }
 6429:             }
 6430:         }
 6431:     }
 6432:     if ($currsettings{'hidefromcat'} eq 'yes') {
 6433:         $visible = 0;
 6434:         if ($settable{'togglecats'}) {
 6435:             unshift(@vismsgs,'unhide');
 6436:         } else {
 6437:             unshift(@vismsgs,'dc_unhide')
 6438:         }
 6439:     }
 6440:     return ($visible,$cansetvis,\@vismsgs);
 6441: }
 6442: 
 6443: sub cat_visibility {
 6444:     my %visactions = &Apache::lonlocal::texthash(
 6445:                    vis => 'This course/community currently appears in the Course/Community Catalog for this domain.',
 6446:                    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.',
 6447:                    miss => 'This course/community does not currently appear in the Course/Community Catalog for this domain.',
 6448:                    none => 'Display of a course catalog is disabled for this domain.',
 6449:                    yous => 'You should remedy this if you plan to allow self-enrollment, otherwise students will have difficulty finding this course.',
 6450:                    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.',
 6451:                    make => 'Make any changes to self-enrollment settings below, click "Save", then take action to include the course in the Catalog:',
 6452:                    take => 'Take the following action to ensure the course appears in the Catalog:',
 6453:                    dc_chgconf => 'Ask a domain coordinator to change the Catalog type for this domain.',
 6454:                    dc_setcode => 'Ask a domain coordinator to assign a six character code to the course',
 6455:                    dc_unhide  => 'Ask a domain coordinator to change the "Exclude from course catalog" setting.',
 6456:                    dc_addinst => 'Ask a domain coordinator to enable display the catalog of "Official courses (with institutional codes)".',
 6457:                    dc_instcode => 'Ask a domain coordinator to assign an institutional code (if this is an official course).',
 6458:                    dc_catalog  => 'Ask a domain coordinator to enable or create at least one course category in the domain.',
 6459:                    dc_categories => 'Ask a domain coordinator to create a hierarchy of categories and sub categories for courses in the domain.',
 6460:                    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',
 6461:                    dc_addcat => 'Ask a domain coordinator to assign a category to the course.',
 6462:     );
 6463:     $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>"');
 6464:     $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>"');
 6465:     $visactions{'addcat'} = &mt('Use [_1]Categorize course[_2] to assign a category to the course.','"<a href="/adm/courseprefs?phase=display&actions=courseinfo">','</a>"');
 6466:     return \%visactions;
 6467: }
 6468: 
 6469: sub new_selfenroll_dom_row {
 6470:     my ($newdom,$num) = @_;
 6471:     my $domdesc = &Apache::lonnet::domain($newdom);
 6472:     my $output;
 6473:     if ($domdesc ne '') {
 6474:         $output .= &Apache::loncommon::start_data_table_row()
 6475:                    .'<td valign="top"><span class="LC_nobreak">'.&mt('Domain:').'&nbsp;<b>'.$domdesc
 6476:                    .' ('.$newdom.')</b><input type="hidden" name="selfenroll_dom_'.$num
 6477:                    .'" value="'.$newdom.'" /></span><br />'
 6478:                    .'<span class="LC_nobreak"><label><input type="checkbox" '
 6479:                    .'name="selfenroll_activate" value="'.$num.'" '
 6480:                    .'onchange="javascript:update_types('
 6481:                    ."'selfenroll_activate','$num'".');" />'
 6482:                    .&mt('Activate').'</label></span></td>';
 6483:         my @currinsttypes;
 6484:         $output .= '<td>'.&mt('User types:').'<br />'
 6485:                    .&selfenroll_inst_types($num,$newdom,\@currinsttypes).'</td>'
 6486:                    .&Apache::loncommon::end_data_table_row();
 6487:     }
 6488:     return $output;
 6489: }
 6490: 
 6491: sub selfenroll_inst_types {
 6492:     my ($num,$currdom,$currinsttypes,$readonly) = @_;
 6493:     my $output;
 6494:     my $numinrow = 4;
 6495:     my $count = 0;
 6496:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($currdom);
 6497:     my $othervalue = 'any';
 6498:     my $disabled;
 6499:     if ($readonly) {
 6500:         $disabled = ' disabled="disabled"';
 6501:     }
 6502:     if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 6503:         if (keys(%{$usertypes}) > 0) {
 6504:             $othervalue = 'other';
 6505:         }
 6506:         $output .= '<table><tr>';
 6507:         foreach my $type (@{$types}) {
 6508:             if (($count > 0) && ($count%$numinrow == 0)) {
 6509:                 $output .= '</tr><tr>';
 6510:             }
 6511:             if (defined($usertypes->{$type})) {
 6512:                 my $esc_type = &escape($type);
 6513:                 $output .= '<td><span class="LC_nobreak"><label><input type = "checkbox" value="'.
 6514:                            $esc_type.'" ';
 6515:                 if (ref($currinsttypes) eq 'ARRAY') {
 6516:                     if (@{$currinsttypes} > 0) {
 6517:                         if (grep(/^any$/,@{$currinsttypes})) {
 6518:                             $output .= 'checked="checked"';
 6519:                         } elsif (grep(/^\Q$esc_type\E$/,@{$currinsttypes})) {
 6520:                             $output .= 'checked="checked"';
 6521:                         }
 6522:                     } else {
 6523:                         $output .= 'checked="checked"';
 6524:                     }
 6525:                 }
 6526:                 $output .= ' name="selfenroll_types_'.$num.'"'.$disabled.' />'.$usertypes->{$type}.'</label></span></td>';
 6527:             }
 6528:             $count ++;
 6529:         }
 6530:         if (($count > 0) && ($count%$numinrow == 0)) {
 6531:             $output .= '</tr><tr>';
 6532:         }
 6533:         $output .= '<td><span class="LC_nobreak"><label><input type = "checkbox" value="'.$othervalue.'"';
 6534:         if (ref($currinsttypes) eq 'ARRAY') {
 6535:             if (@{$currinsttypes} > 0) {
 6536:                 if (grep(/^any$/,@{$currinsttypes})) { 
 6537:                     $output .= ' checked="checked"';
 6538:                 } elsif ($othervalue eq 'other') {
 6539:                     if (grep(/^\Q$othervalue\E$/,@{$currinsttypes})) {
 6540:                         $output .= ' checked="checked"';
 6541:                     }
 6542:                 }
 6543:             } else {
 6544:                 $output .= ' checked="checked"';
 6545:             }
 6546:         } else {
 6547:             $output .= ' checked="checked"';
 6548:         }
 6549:         $output .= ' name="selfenroll_types_'.$num.'"'.$disabled.' />'.$othertitle.'</label></span></td></tr></table>';
 6550:     }
 6551:     return $output;
 6552: }
 6553: 
 6554: sub selfenroll_date_forms {
 6555:     my ($startform,$endform) = @_;
 6556:     my $output .= &Apache::lonhtmlcommon::start_pick_box()."\n".
 6557:                   &Apache::lonhtmlcommon::row_title(&mt('Start date'),
 6558:                                                     'LC_oddrow_value')."\n".
 6559:                   $startform."\n".
 6560:                   &Apache::lonhtmlcommon::row_closure(1).
 6561:                   &Apache::lonhtmlcommon::row_title(&mt('End date'),
 6562:                                                    'LC_oddrow_value')."\n".
 6563:                   $endform."\n".
 6564:                   &Apache::lonhtmlcommon::row_closure(1).
 6565:                   &Apache::lonhtmlcommon::end_pick_box();
 6566:     return $output;
 6567: }
 6568: 
 6569: sub print_userchangelogs_display {
 6570:     my ($r,$context,$permission,$brcrum) = @_;
 6571:     my $formname = 'rolelog';
 6572:     my ($username,$domain,$crstype,$viewablesec,%roleslog);
 6573:     if ($context eq 'domain') {
 6574:         $domain = $env{'request.role.domain'};
 6575:         %roleslog=&Apache::lonnet::dump_dom('nohist_rolelog',$domain);
 6576:     } else {
 6577:         if ($context eq 'course') { 
 6578:             $domain = $env{'course.'.$env{'request.course.id'}.'.domain'};
 6579:             $username = $env{'course.'.$env{'request.course.id'}.'.num'};
 6580:             $crstype = &Apache::loncommon::course_type();
 6581:             $viewablesec = &Apache::lonuserutils::viewable_section($permission);
 6582:             my %saveable_parameters = ('show' => 'scalar',);
 6583:             &Apache::loncommon::store_course_settings('roles_log',
 6584:                                                       \%saveable_parameters);
 6585:             &Apache::loncommon::restore_course_settings('roles_log',
 6586:                                                         \%saveable_parameters);
 6587:         } elsif ($context eq 'author') {
 6588:             $domain = $env{'user.domain'}; 
 6589:             if ($env{'request.role'} =~ m{^au\./\Q$domain\E/$}) {
 6590:                 $username = $env{'user.name'};
 6591:             } else {
 6592:                 undef($domain);
 6593:             }
 6594:         }
 6595:         if ($domain ne '' && $username ne '') { 
 6596:             %roleslog=&Apache::lonnet::dump('nohist_rolelog',$domain,$username);
 6597:         }
 6598:     }
 6599:     if ((keys(%roleslog))[0]=~/^error\:/) { undef(%roleslog); }
 6600: 
 6601:     my $helpitem;
 6602:     if ($context eq 'course') {
 6603:         $helpitem = 'Course_User_Logs';
 6604:     }
 6605:     push (@{$brcrum},
 6606:              {href => '/adm/createuser?action=changelogs',
 6607:               text => 'User Management Logs',
 6608:               help => $helpitem});
 6609:     my $bread_crumbs_component = 'User Changes';
 6610:     my $args = { bread_crumbs           => $brcrum,
 6611:                  bread_crumbs_component => $bread_crumbs_component};
 6612: 
 6613:     # Create navigation javascript
 6614:     my $jsnav = &userlogdisplay_js($formname);
 6615: 
 6616:     my $jscript = (<<ENDSCRIPT);
 6617: <script type="text/javascript">
 6618: // <![CDATA[
 6619: $jsnav
 6620: // ]]>
 6621: </script>
 6622: ENDSCRIPT
 6623: 
 6624:     # print page header
 6625:     $r->print(&header($jscript,$args));
 6626: 
 6627:     # set defaults
 6628:     my $now = time();
 6629:     my $defstart = $now - (7*24*3600); #7 days ago 
 6630:     my %defaults = (
 6631:                      page               => '1',
 6632:                      show               => '10',
 6633:                      role               => 'any',
 6634:                      chgcontext         => 'any',
 6635:                      rolelog_start_date => $defstart,
 6636:                      rolelog_end_date   => $now,
 6637:                    );
 6638:     my $more_records = 0;
 6639: 
 6640:     # set current
 6641:     my %curr;
 6642:     foreach my $item ('show','page','role','chgcontext') {
 6643:         $curr{$item} = $env{'form.'.$item};
 6644:     }
 6645:     my ($startdate,$enddate) = 
 6646:         &Apache::lonuserutils::get_dates_from_form('rolelog_start_date','rolelog_end_date');
 6647:     $curr{'rolelog_start_date'} = $startdate;
 6648:     $curr{'rolelog_end_date'} = $enddate;
 6649:     foreach my $key (keys(%defaults)) {
 6650:         if ($curr{$key} eq '') {
 6651:             $curr{$key} = $defaults{$key};
 6652:         }
 6653:     }
 6654:     my (%whodunit,%changed,$version);
 6655:     ($version) = ($r->dir_config('lonVersion') =~ /^([\d\.]+)\-/);
 6656:     my ($minshown,$maxshown);
 6657:     $minshown = 1;
 6658:     my $count = 0;
 6659:     if ($curr{'show'} =~ /\D/) {
 6660:         $curr{'page'} = 1;
 6661:     } else {
 6662:         $maxshown = $curr{'page'} * $curr{'show'};
 6663:         if ($curr{'page'} > 1) {
 6664:             $minshown = 1 + ($curr{'page'} - 1) * $curr{'show'};
 6665:         }
 6666:     }
 6667: 
 6668:     # Form Header
 6669:     $r->print('<form action="/adm/createuser" method="post" name="'.$formname.'">'.
 6670:               &role_display_filter($context,$formname,$domain,$username,\%curr,
 6671:                                    $version,$crstype));
 6672: 
 6673:     my $showntableheader = 0;
 6674: 
 6675:     # Table Header
 6676:     my $tableheader = 
 6677:         &Apache::loncommon::start_data_table_header_row()
 6678:        .'<th>&nbsp;</th>'
 6679:        .'<th>'.&mt('When').'</th>'
 6680:        .'<th>'.&mt('Who made the change').'</th>'
 6681:        .'<th>'.&mt('Changed User').'</th>'
 6682:        .'<th>'.&mt('Role').'</th>';
 6683: 
 6684:     if ($context eq 'course') {
 6685:         $tableheader .= '<th>'.&mt('Section').'</th>';
 6686:     }
 6687:     $tableheader .=
 6688:         '<th>'.&mt('Context').'</th>'
 6689:        .'<th>'.&mt('Start').'</th>'
 6690:        .'<th>'.&mt('End').'</th>'
 6691:        .&Apache::loncommon::end_data_table_header_row();
 6692: 
 6693:     # Display user change log data
 6694:     foreach my $id (sort { $roleslog{$b}{'exe_time'}<=>$roleslog{$a}{'exe_time'} } (keys(%roleslog))) {
 6695:         next if (($roleslog{$id}{'exe_time'} < $curr{'rolelog_start_date'}) ||
 6696:                  ($roleslog{$id}{'exe_time'} > $curr{'rolelog_end_date'}));
 6697:         if ($curr{'show'} !~ /\D/) {
 6698:             if ($count >= $curr{'page'} * $curr{'show'}) {
 6699:                 $more_records = 1;
 6700:                 last;
 6701:             }
 6702:         }
 6703:         if ($curr{'role'} ne 'any') {
 6704:             next if ($roleslog{$id}{'logentry'}{'role'} ne $curr{'role'}); 
 6705:         }
 6706:         if ($curr{'chgcontext'} ne 'any') {
 6707:             if ($curr{'chgcontext'} eq 'selfenroll') {
 6708:                 next if (!$roleslog{$id}{'logentry'}{'selfenroll'});
 6709:             } else {
 6710:                 next if ($roleslog{$id}{'logentry'}{'context'} ne $curr{'chgcontext'});
 6711:             }
 6712:         }
 6713:         if (($context eq 'course') && ($viewablesec ne '')) {
 6714:             next if ($roleslog{$id}{'logentry'}{'section'} ne $viewablesec);
 6715:         }
 6716:         $count ++;
 6717:         next if ($count < $minshown);
 6718:         unless ($showntableheader) {
 6719:             $r->print(&Apache::loncommon::start_data_table()
 6720:                      .$tableheader);
 6721:             $r->rflush();
 6722:             $showntableheader = 1;
 6723:         }
 6724:         if ($whodunit{$roleslog{$id}{'exe_uname'}.':'.$roleslog{$id}{'exe_udom'}} eq '') {
 6725:             $whodunit{$roleslog{$id}{'exe_uname'}.':'.$roleslog{$id}{'exe_udom'}} =
 6726:                 &Apache::loncommon::plainname($roleslog{$id}{'exe_uname'},$roleslog{$id}{'exe_udom'});
 6727:         }
 6728:         if ($changed{$roleslog{$id}{'uname'}.':'.$roleslog{$id}{'udom'}} eq '') {
 6729:             $changed{$roleslog{$id}{'uname'}.':'.$roleslog{$id}{'udom'}} =
 6730:                 &Apache::loncommon::plainname($roleslog{$id}{'uname'},$roleslog{$id}{'udom'});
 6731:         }
 6732:         my $sec = $roleslog{$id}{'logentry'}{'section'};
 6733:         if ($sec eq '') {
 6734:             $sec = &mt('None');
 6735:         }
 6736:         my ($rolestart,$roleend);
 6737:         if ($roleslog{$id}{'delflag'}) {
 6738:             $rolestart = &mt('deleted');
 6739:             $roleend = &mt('deleted');
 6740:         } else {
 6741:             $rolestart = $roleslog{$id}{'logentry'}{'start'};
 6742:             $roleend = $roleslog{$id}{'logentry'}{'end'};
 6743:             if ($rolestart eq '' || $rolestart == 0) {
 6744:                 $rolestart = &mt('No start date'); 
 6745:             } else {
 6746:                 $rolestart = &Apache::lonlocal::locallocaltime($rolestart);
 6747:             }
 6748:             if ($roleend eq '' || $roleend == 0) { 
 6749:                 $roleend = &mt('No end date');
 6750:             } else {
 6751:                 $roleend = &Apache::lonlocal::locallocaltime($roleend);
 6752:             }
 6753:         }
 6754:         my $chgcontext = $roleslog{$id}{'logentry'}{'context'};
 6755:         if ($roleslog{$id}{'logentry'}{'selfenroll'}) {
 6756:             $chgcontext = 'selfenroll';
 6757:         }
 6758:         my %lt = &rolechg_contexts($context,$crstype);
 6759:         if ($chgcontext ne '' && $lt{$chgcontext} ne '') {
 6760:             $chgcontext = $lt{$chgcontext};
 6761:         }
 6762:         $r->print(
 6763:             &Apache::loncommon::start_data_table_row()
 6764:            .'<td>'.$count.'</td>'
 6765:            .'<td>'.&Apache::lonlocal::locallocaltime($roleslog{$id}{'exe_time'}).'</td>'
 6766:            .'<td>'.$whodunit{$roleslog{$id}{'exe_uname'}.':'.$roleslog{$id}{'exe_udom'}}.'</td>'
 6767:            .'<td>'.$changed{$roleslog{$id}{'uname'}.':'.$roleslog{$id}{'udom'}}.'</td>'
 6768:            .'<td>'.&Apache::lonnet::plaintext($roleslog{$id}{'logentry'}{'role'},$crstype).'</td>');
 6769:         if ($context eq 'course') { 
 6770:             $r->print('<td>'.$sec.'</td>');
 6771:         }
 6772:         $r->print(
 6773:             '<td>'.$chgcontext.'</td>'
 6774:            .'<td>'.$rolestart.'</td>'
 6775:            .'<td>'.$roleend.'</td>'
 6776:            .&Apache::loncommon::end_data_table_row()."\n");
 6777:     }
 6778: 
 6779:     if ($showntableheader) { # Table footer, if content displayed above
 6780:         $r->print(&Apache::loncommon::end_data_table().
 6781:                   &userlogdisplay_navlinks(\%curr,$more_records));
 6782:     } else { # No content displayed above
 6783:         $r->print('<p class="LC_info">'
 6784:                  .&mt('There are no records to display.')
 6785:                  .'</p>'
 6786:         );
 6787:     }
 6788: 
 6789:     # Form Footer
 6790:     $r->print( 
 6791:         '<input type="hidden" name="page" value="'.$curr{'page'}.'" />'
 6792:        .'<input type="hidden" name="action" value="changelogs" />'
 6793:        .'</form>');
 6794:     return;
 6795: }
 6796: 
 6797: sub print_useraccesslogs_display {
 6798:     my ($r,$uname,$udom,$permission,$brcrum) = @_;
 6799:     my $formname = 'accesslog';
 6800:     my $form = 'document.accesslog';
 6801: 
 6802: # set breadcrumbs
 6803:     my %breadcrumb_text = &singleuser_breadcrumb();
 6804:     push (@{$brcrum},
 6805:         {href => "javascript:backPage($form)",
 6806:          text => $breadcrumb_text{'search'}});
 6807:     my (@prevphases,$prevphasestr);
 6808:     if ($env{'form.prevphases'}) {
 6809:         @prevphases = split(/,/,$env{'form.prevphases'});
 6810:         $prevphasestr = $env{'form.prevphases'};
 6811:     }
 6812:     if (($env{'form.phase'} eq 'userpicked') || (grep(/^userpicked$/,@prevphases))) {
 6813:         push(@{$brcrum},
 6814:               {href => "javascript:backPage($form,'get_user_info','select')",
 6815:                text => $breadcrumb_text{'userpicked'}});
 6816:         if ($env{'form.phase'} eq 'userpicked') {
 6817:             $prevphasestr = 'userpicked';
 6818:         }
 6819:     }
 6820:     push(@{$brcrum},
 6821:              {href => '/adm/createuser?action=accesslogs',
 6822:               text => 'User access logs',
 6823:               help => 'User_Access_Logs'});
 6824:     my $bread_crumbs_component = 'User Access Logs';
 6825:     my $args = { bread_crumbs           => $brcrum,
 6826:                  bread_crumbs_component => 'User Management'};
 6827: 
 6828: # set javascript
 6829:     my ($jsback,$elements) = &crumb_utilities();
 6830:     my $jsnav = &userlogdisplay_js($formname);
 6831: 
 6832:     my $jscript = (<<ENDSCRIPT);
 6833: <script type="text/javascript">
 6834: // <![CDATA[
 6835: 
 6836: $jsback
 6837: $jsnav
 6838: 
 6839: // ]]>
 6840: </script>
 6841: 
 6842: ENDSCRIPT
 6843: 
 6844: # print page header
 6845:     $r->print(&header($jscript,$args));
 6846: 
 6847: # early out unless log data can be displayed.
 6848:     unless ($permission->{'activity'}) {
 6849:         $r->print('<p class="LC_warning">'
 6850:                  .&mt('You do not have rights to display user access logs.')
 6851:                  .'</p>'
 6852:                  .&earlyout_accesslog_form($formname,$prevphasestr,$udom));
 6853:         return;
 6854:     }
 6855: 
 6856:     unless ($udom eq $env{'request.role.domain'}) {
 6857:         $r->print('<p class="LC_warning">'
 6858:                  .&mt("User's domain must match role's domain")
 6859:                  .'</p>'
 6860:                  .&earlyout_accesslog_form($formname,$prevphasestr,$udom));
 6861:         return;
 6862:     }
 6863: 
 6864:     if (($uname eq '') || ($udom eq '')) {
 6865:         $r->print('<p class="LC_warning">'
 6866:                  .&mt('Invalid username or domain')
 6867:                  .'</p>'
 6868:                  .&earlyout_accesslog_form($formname,$prevphasestr,$udom));
 6869:         return;
 6870:     }
 6871: 
 6872: # set defaults
 6873:     my $now = time();
 6874:     my $defstart = $now - (7*24*3600);
 6875:     my %defaults = (
 6876:                      page                 => '1',
 6877:                      show                 => '10',
 6878:                      activity             => 'any',
 6879:                      accesslog_start_date => $defstart,
 6880:                      accesslog_end_date   => $now,
 6881:                    );
 6882:     my $more_records = 0;
 6883: 
 6884: # set current
 6885:     my %curr;
 6886:     foreach my $item ('show','page','activity') {
 6887:         $curr{$item} = $env{'form.'.$item};
 6888:     }
 6889:     my ($startdate,$enddate) =
 6890:         &Apache::lonuserutils::get_dates_from_form('accesslog_start_date','accesslog_end_date');
 6891:     $curr{'accesslog_start_date'} = $startdate;
 6892:     $curr{'accesslog_end_date'} = $enddate;
 6893:     foreach my $key (keys(%defaults)) {
 6894:         if ($curr{$key} eq '') {
 6895:             $curr{$key} = $defaults{$key};
 6896:         }
 6897:     }
 6898:     my ($minshown,$maxshown);
 6899:     $minshown = 1;
 6900:     my $count = 0;
 6901:     if ($curr{'show'} =~ /\D/) {
 6902:         $curr{'page'} = 1;
 6903:     } else {
 6904:         $maxshown = $curr{'page'} * $curr{'show'};
 6905:         if ($curr{'page'} > 1) {
 6906:             $minshown = 1 + ($curr{'page'} - 1) * $curr{'show'};
 6907:         }
 6908:     }
 6909: 
 6910: # form header
 6911:     $r->print('<form action="/adm/createuser" method="post" name="'.$formname.'">'.
 6912:               &activity_display_filter($formname,\%curr));
 6913: 
 6914:     my $showntableheader = 0;
 6915:     my ($nav_script,$nav_links);
 6916: 
 6917: # table header
 6918:     my $tableheader =
 6919:         &Apache::loncommon::start_data_table_header_row()
 6920:        .'<th>&nbsp;</th>'
 6921:        .'<th>'.&mt('When').'</th>'
 6922:        .'<th>'.&mt('HostID').'</th>'
 6923:        .'<th>'.&mt('Event').'</th>'
 6924:        .'<th>'.&mt('Other data').'</th>'
 6925:        .&Apache::loncommon::end_data_table_header_row();
 6926: 
 6927:     my %filters=(
 6928:         start  => $curr{'accesslog_start_date'},
 6929:         end    => $curr{'accesslog_end_date'},
 6930:         action => $curr{'activity'},
 6931:     );
 6932: 
 6933:     my $reply = &Apache::lonnet::userlog_query($uname,$udom,%filters);
 6934:     unless ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 6935:         my (%courses,%missing);
 6936:         my @results = split(/\&/,$reply);
 6937:         foreach my $item (reverse(@results)) {
 6938:             my ($timestamp,$host,$event) = split(/:/,$item);
 6939:             next unless ($event =~ /^(Log|Role)/);
 6940:             if ($curr{'show'} !~ /\D/) {
 6941:                 if ($count >= $curr{'page'} * $curr{'show'}) {
 6942:                     $more_records = 1;
 6943:                     last;
 6944:                 }
 6945:             }
 6946:             $count ++;
 6947:             next if ($count < $minshown);
 6948:             unless ($showntableheader) {
 6949:                 $r->print($nav_script
 6950:                          .&Apache::loncommon::start_data_table()
 6951:                          .$tableheader);
 6952:                 $r->rflush();
 6953:                 $showntableheader = 1;
 6954:             }
 6955:             my ($shown,$extra);
 6956:             my ($event,$data) = split(/\s+/,&unescape($event));
 6957:             if ($event eq 'Role') {
 6958:                 my ($rolecode,$extent) = split(/\./,$data,2);
 6959:                 next if ($extent eq '');
 6960:                 my ($crstype,$desc,$info);
 6961:                 if ($extent =~ m{^/($match_domain)/($match_courseid)(?:/(\w+)|)$}) {
 6962:                     my ($cdom,$cnum,$sec) = ($1,$2,$3);
 6963:                     my $cid = $cdom.'_'.$cnum;
 6964:                     if (exists($courses{$cid})) {
 6965:                         $crstype = $courses{$cid}{'type'};
 6966:                         $desc = $courses{$cid}{'description'};
 6967:                     } elsif ($missing{$cid}) {
 6968:                         $crstype = 'Course';
 6969:                         $desc = 'Course/Community';
 6970:                     } else {
 6971:                         my %crsinfo = &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 6972:                         if (ref($crsinfo{$cdom.'_'.$cnum}) eq 'HASH') {
 6973:                             $courses{$cid} = $crsinfo{$cid};
 6974:                             $crstype = $crsinfo{$cid}{'type'};
 6975:                             $desc = $crsinfo{$cid}{'description'};
 6976:                         } else {
 6977:                             $missing{$cid} = 1;
 6978:                         }
 6979:                     }
 6980:                     $extra = &mt($crstype).': <a href="/public/'.$cdom.'/'.$cnum.'/syllabus">'.$desc.'</a>';
 6981:                     if ($sec ne '') {
 6982:                        $extra .= ' ('.&mt('Section: [_1]',$sec).')';
 6983:                     }
 6984:                 } elsif ($extent =~ m{^/($match_domain)/($match_username|$)}) {
 6985:                     my ($dom,$name) = ($1,$2);
 6986:                     if ($rolecode eq 'au') {
 6987:                         $extra = '';
 6988:                     } elsif ($rolecode =~ /^(ca|aa)$/) {
 6989:                         $extra = &mt('Authoring Space: [_1]',$name.':'.$dom);
 6990:                     } elsif ($rolecode =~ /^(li|dg|dh|dc|sc)$/) {
 6991:                         $extra = &mt('Domain: [_1]',$dom);
 6992:                     }
 6993:                 }
 6994:                 my $rolename;
 6995:                 if ($rolecode =~ m{^cr/($match_domain)/($match_username)/(\w+)}) {
 6996:                     my $role = $3;
 6997:                     my $owner = "($2:$1)";
 6998:                     if ($2 eq $1.'-domainconfig') {
 6999:                         $owner = '(ad hoc)';
 7000:                     }
 7001:                     $rolename = &mt('Custom role: [_1]',$role.' '.$owner);
 7002:                 } else {
 7003:                     $rolename = &Apache::lonnet::plaintext($rolecode,$crstype);
 7004:                 }
 7005:                 $shown = &mt('Role selection: [_1]',$rolename);
 7006:             } else {
 7007:                 $shown = &mt($event);
 7008:                 if ($data ne '') {
 7009:                    $extra = &mt('Client IP address: [_1]',$data);
 7010:                 }
 7011:             }
 7012:             $r->print(
 7013:             &Apache::loncommon::start_data_table_row()
 7014:            .'<td>'.$count.'</td>'
 7015:            .'<td>'.&Apache::lonlocal::locallocaltime($timestamp).'</td>'
 7016:            .'<td>'.$host.'</td>'
 7017:            .'<td>'.$shown.'</td>'
 7018:            .'<td>'.$extra.'</td>'
 7019:            .&Apache::loncommon::end_data_table_row()."\n");
 7020:         }
 7021:     }
 7022: 
 7023:     if ($showntableheader) { # Table footer, if content displayed above
 7024:         $r->print(&Apache::loncommon::end_data_table().
 7025:                   &userlogdisplay_navlinks(\%curr,$more_records));
 7026:     } else { # No content displayed above
 7027:         $r->print('<p class="LC_info">'
 7028:                  .&mt('There are no records to display.')
 7029:                  .'</p>');
 7030:     }
 7031: 
 7032:     # Form Footer
 7033:     $r->print(
 7034:         '<input type="hidden" name="currstate" value="" />'
 7035:        .'<input type="hidden" name="accessuname" value="'.$uname.'" />'
 7036:        .'<input type="hidden" name="accessudom" value="'.$udom.'" />'
 7037:        .'<input type="hidden" name="page" value="'.$curr{'page'}.'" />'
 7038:        .'<input type="hidden" name="prevphases" value="'.$prevphasestr.'" />'
 7039:        .'<input type="hidden" name="phase" value="activity" />'
 7040:        .'<input type="hidden" name="action" value="accesslogs" />'
 7041:        .'<input type="hidden" name="srchdomain" value="'.$udom.'" />'
 7042:        .'<input type="hidden" name="srchby" value="'.$env{'form.srchby'}.'" />'
 7043:        .'<input type="hidden" name="srchtype" value="'.$env{'form.srchtype'}.'" />'
 7044:        .'<input type="hidden" name="srchterm" value="'.&HTML::Entities::encode($env{'form.srchterm'},'<>"&').'" />'
 7045:        .'<input type="hidden" name="srchin" value="'.$env{'form.srchin'}.'" />'
 7046:        .'</form>');
 7047:     return;
 7048: }
 7049: 
 7050: sub earlyout_accesslog_form {
 7051:     my ($formname,$prevphasestr,$udom) = @_;
 7052:     my $srchterm = &HTML::Entities::encode($env{'form.srchterm'},'<>"&');
 7053:    return <<"END";
 7054: <form action="/adm/createuser" method="post" name="$formname">
 7055: <input type="hidden" name="currstate" value="" />
 7056: <input type="hidden" name="prevphases" value="$prevphasestr" />
 7057: <input type="hidden" name="phase" value="activity" />
 7058: <input type="hidden" name="action" value="accesslogs" />
 7059: <input type="hidden" name="srchdomain" value="$udom" />
 7060: <input type="hidden" name="srchby" value="$env{'form.srchby'}" />
 7061: <input type="hidden" name="srchtype" value="$env{'form.srchtype'}" />
 7062: <input type="hidden" name="srchterm" value="$srchterm" />
 7063: <input type="hidden" name="srchin" value="$env{'form.srchin'}" />
 7064: </form>
 7065: END
 7066: }
 7067: 
 7068: sub activity_display_filter {
 7069:     my ($formname,$curr) = @_;
 7070:     my $nolink = 1;
 7071:     my $output = '<table><tr><td valign="top">'.
 7072:                  '<span class="LC_nobreak"><b>'.&mt('Actions/page:').'</b></span><br />'.
 7073:                  &Apache::lonmeta::selectbox('show',$curr->{'show'},undef,
 7074:                                               (&mt('all'),5,10,20,50,100,1000,10000)).
 7075:                  '</td><td>&nbsp;&nbsp;</td>';
 7076:     my $startform =
 7077:         &Apache::lonhtmlcommon::date_setter($formname,'accesslog_start_date',
 7078:                                             $curr->{'accesslog_start_date'},undef,
 7079:                                             undef,undef,undef,undef,undef,undef,$nolink);
 7080:     my $endform =
 7081:         &Apache::lonhtmlcommon::date_setter($formname,'accesslog_end_date',
 7082:                                             $curr->{'accesslog_end_date'},undef,
 7083:                                             undef,undef,undef,undef,undef,undef,$nolink);
 7084:     my %lt = &Apache::lonlocal::texthash (
 7085:                                           activity => 'Activity',
 7086:                                           Role     => 'Role selection',
 7087:                                           log      => 'Log-in or Logout',
 7088:     );
 7089:     $output .= '<td valign="top"><b>'.&mt('Window during which actions occurred:').'</b><br />'.
 7090:                '<table><tr><td>'.&mt('After:').
 7091:                '</td><td>'.$startform.'</td></tr>'.
 7092:                '<tr><td>'.&mt('Before:').'</td>'.
 7093:                '<td>'.$endform.'</td></tr></table>'.
 7094:                '</td>'.
 7095:                '<td>&nbsp;&nbsp;</td>'.
 7096:                '<td valign="top"><b>'.&mt('Activities').'</b><br />'.
 7097:                '<select name="activity"><option value="any"';
 7098:     if ($curr->{'activity'} eq 'any') {
 7099:         $output .= ' selected="selected"';
 7100:     }
 7101:     $output .= '>'.&mt('Any').'</option>'."\n";
 7102:     foreach my $activity ('Role','log') {
 7103:         my $selstr = '';
 7104:         if ($activity eq $curr->{'activity'}) {
 7105:             $selstr = ' selected="selected"';
 7106:         }
 7107:         $output .= '<option value="'.$activity.'"'.$selstr.'>'.$lt{$activity}.'</option>';
 7108:     }
 7109:     $output .= '</select></td>'.
 7110:                '</tr></table>';
 7111:     # Update Display button
 7112:     $output .= '<p>'
 7113:               .'<input type="submit" value="'.&mt('Update Display').'" />'
 7114:               .'</p>';
 7115:     return $output;
 7116: }
 7117: 
 7118: sub userlogdisplay_js {
 7119:     my ($formname) = @_;
 7120:     return <<"ENDSCRIPT";
 7121: 
 7122: function chgPage(caller) {
 7123:     if (caller == 'previous') {
 7124:         document.$formname.page.value --;
 7125:     }
 7126:     if (caller == 'next') {
 7127:         document.$formname.page.value ++;
 7128:     }
 7129:     document.$formname.submit();
 7130:     return;
 7131: }
 7132: ENDSCRIPT
 7133: }
 7134: 
 7135: sub userlogdisplay_navlinks {
 7136:     my ($curr,$more_records) = @_;
 7137:     return unless(ref($curr) eq 'HASH');
 7138:     # Navigation Buttons
 7139:     my $nav_links = '<p>';
 7140:     if (($curr->{'page'} > 1) || ($more_records)) {
 7141:         if (($curr->{'page'} > 1) && ($curr->{'show'} !~ /\D/)) {
 7142:             $nav_links .= '<input type="button"'
 7143:                          .' onclick="javascript:chgPage('."'previous'".');"'
 7144:                          .' value="'.&mt('Previous [_1] changes',$curr->{'show'})
 7145:                          .'" /> ';
 7146:         }
 7147:         if ($more_records) {
 7148:             $nav_links .= '<input type="button"'
 7149:                          .' onclick="javascript:chgPage('."'next'".');"'
 7150:                          .' value="'.&mt('Next [_1] changes',$curr->{'show'})
 7151:                          .'" />';
 7152:         }
 7153:     }
 7154:     $nav_links .= '</p>';
 7155:     return $nav_links;
 7156: }
 7157: 
 7158: sub role_display_filter {
 7159:     my ($context,$formname,$cdom,$cnum,$curr,$version,$crstype) = @_;
 7160:     my $lctype;
 7161:     if ($context eq 'course') {
 7162:         $lctype = lc($crstype);
 7163:     }
 7164:     my $nolink = 1;
 7165:     my $output = '<table><tr><td valign="top">'.
 7166:                  '<span class="LC_nobreak"><b>'.&mt('Changes/page:').'</b></span><br />'.
 7167:                  &Apache::lonmeta::selectbox('show',$curr->{'show'},undef,
 7168:                                               (&mt('all'),5,10,20,50,100,1000,10000)).
 7169:                  '</td><td>&nbsp;&nbsp;</td>';
 7170:     my $startform =
 7171:         &Apache::lonhtmlcommon::date_setter($formname,'rolelog_start_date',
 7172:                                             $curr->{'rolelog_start_date'},undef,
 7173:                                             undef,undef,undef,undef,undef,undef,$nolink);
 7174:     my $endform =
 7175:         &Apache::lonhtmlcommon::date_setter($formname,'rolelog_end_date',
 7176:                                             $curr->{'rolelog_end_date'},undef,
 7177:                                             undef,undef,undef,undef,undef,undef,$nolink);
 7178:     my %lt = &rolechg_contexts($context,$crstype);
 7179:     $output .= '<td valign="top"><b>'.&mt('Window during which changes occurred:').'</b><br />'.
 7180:                '<table><tr><td>'.&mt('After:').
 7181:                '</td><td>'.$startform.'</td></tr>'.
 7182:                '<tr><td>'.&mt('Before:').'</td>'.
 7183:                '<td>'.$endform.'</td></tr></table>'.
 7184:                '</td>'.
 7185:                '<td>&nbsp;&nbsp;</td>'.
 7186:                '<td valign="top"><b>'.&mt('Role:').'</b><br />'.
 7187:                '<select name="role"><option value="any"';
 7188:     if ($curr->{'role'} eq 'any') {
 7189:         $output .= ' selected="selected"';
 7190:     }
 7191:     $output .=  '>'.&mt('Any').'</option>'."\n";
 7192:     my @roles = &Apache::lonuserutils::roles_by_context($context,1,$crstype);
 7193:     foreach my $role (@roles) {
 7194:         my $plrole;
 7195:         if ($role eq 'cr') {
 7196:             $plrole = &mt('Custom Role');
 7197:         } else {
 7198:             $plrole=&Apache::lonnet::plaintext($role,$crstype);
 7199:         }
 7200:         my $selstr = '';
 7201:         if ($role eq $curr->{'role'}) {
 7202:             $selstr = ' selected="selected"';
 7203:         }
 7204:         $output .= '  <option value="'.$role.'"'.$selstr.'>'.$plrole.'</option>';
 7205:     }
 7206:     $output .= '</select></td>'.
 7207:                '<td>&nbsp;&nbsp;</td>'.
 7208:                '<td valign="top"><b>'.
 7209:                &mt('Context:').'</b><br /><select name="chgcontext">';
 7210:     my @posscontexts;
 7211:     if ($context eq 'course') {
 7212:         @posscontexts = ('any','automated','updatenow','createcourse','course','domain','selfenroll','requestcourses');
 7213:     } elsif ($context eq 'domain') {
 7214:         @posscontexts = ('any','domain','requestauthor','domconfig','server');
 7215:     } else {
 7216:         @posscontexts = ('any','author','domain');
 7217:     } 
 7218:     foreach my $chgtype (@posscontexts) {
 7219:         my $selstr = '';
 7220:         if ($curr->{'chgcontext'} eq $chgtype) {
 7221:             $selstr = ' selected="selected"';
 7222:         }
 7223:         if ($context eq 'course') {
 7224:             if (($chgtype eq 'automated') || ($chgtype eq 'updatenow')) {
 7225:                 next if (!&Apache::lonnet::auto_run($cnum,$cdom));
 7226:             }
 7227:         }
 7228:         $output .= '<option value="'.$chgtype.'"'.$selstr.'>'.$lt{$chgtype}.'</option>'."\n";
 7229:     }
 7230:     $output .= '</select></td>'
 7231:               .'</tr></table>';
 7232: 
 7233:     # Update Display button
 7234:     $output .= '<p>'
 7235:               .'<input type="submit" value="'.&mt('Update Display').'" />'
 7236:               .'</p>';
 7237: 
 7238:     # Server version info
 7239:     my $needsrev = '2.11.0';
 7240:     if ($context eq 'course') {
 7241:         $needsrev = '2.7.0';
 7242:     }
 7243:     
 7244:     $output .= '<p class="LC_info">'
 7245:               .&mt('Only changes made from servers running LON-CAPA [_1] or later are displayed.'
 7246:                   ,$needsrev);
 7247:     if ($version) {
 7248:         $output .= ' '.&mt('This LON-CAPA server is version [_1]',$version);
 7249:     }
 7250:     $output .= '</p><hr />';
 7251:     return $output;
 7252: }
 7253: 
 7254: sub rolechg_contexts {
 7255:     my ($context,$crstype) = @_;
 7256:     my %lt;
 7257:     if ($context eq 'course') {
 7258:         %lt = &Apache::lonlocal::texthash (
 7259:                                              any          => 'Any',
 7260:                                              automated    => 'Automated Enrollment',
 7261:                                              updatenow    => 'Roster Update',
 7262:                                              createcourse => 'Course Creation',
 7263:                                              course       => 'User Management in course',
 7264:                                              domain       => 'User Management in domain',
 7265:                                              selfenroll   => 'Self-enrolled',
 7266:                                              requestcourses => 'Course Request',
 7267:                                          );
 7268:         if ($crstype eq 'Community') {
 7269:             $lt{'createcourse'} = &mt('Community Creation');
 7270:             $lt{'course'} = &mt('User Management in community');
 7271:             $lt{'requestcourses'} = &mt('Community Request');
 7272:         }
 7273:     } elsif ($context eq 'domain') {
 7274:         %lt = &Apache::lonlocal::texthash (
 7275:                                              any           => 'Any',
 7276:                                              domain        => 'User Management in domain',
 7277:                                              requestauthor => 'Authoring Request',
 7278:                                              server        => 'Command line script (DC role)',
 7279:                                              domconfig     => 'Self-enrolled',
 7280:                                          );
 7281:     } else {
 7282:         %lt = &Apache::lonlocal::texthash (
 7283:                                              any    => 'Any',
 7284:                                              domain => 'User Management in domain',
 7285:                                              author => 'User Management by author',
 7286:                                          );
 7287:     } 
 7288:     return %lt;
 7289: }
 7290: 
 7291: #-------------------------------------------------- functions for &phase_two
 7292: sub user_search_result {
 7293:     my ($context,$srch) = @_;
 7294:     my %allhomes;
 7295:     my %inst_matches;
 7296:     my %srch_results;
 7297:     my ($response,$currstate,$forcenewuser,$dirsrchres);
 7298:     $srch->{'srchterm'} =~ s/\s+/ /g;
 7299:     if ($srch->{'srchby'} !~ /^(uname|lastname|lastfirst)$/) {
 7300:         $response = &mt('Invalid search.');
 7301:     }
 7302:     if ($srch->{'srchin'} !~ /^(crs|dom|alc|instd)$/) {
 7303:         $response = &mt('Invalid search.');
 7304:     }
 7305:     if ($srch->{'srchtype'} !~ /^(exact|contains|begins)$/) {
 7306:         $response = &mt('Invalid search.');
 7307:     }
 7308:     if ($srch->{'srchterm'} eq '') {
 7309:         $response = &mt('You must enter a search term.');
 7310:     }
 7311:     if ($srch->{'srchterm'} =~ /^\s+$/) {
 7312:         $response = &mt('Your search term must contain more than just spaces.');
 7313:     }
 7314:     if (($srch->{'srchin'} eq 'dom') || ($srch->{'srchin'} eq 'instd')) {
 7315:         if (($srch->{'srchdomain'} eq '') || 
 7316: 	    ! (&Apache::lonnet::domain($srch->{'srchdomain'}))) {
 7317:             $response = &mt('You must specify a valid domain when searching in a domain or institutional directory.')
 7318:         }
 7319:     }
 7320:     if (($srch->{'srchin'} eq 'dom') || ($srch->{'srchin'} eq 'crs') ||
 7321:         ($srch->{'srchin'} eq 'alc')) {
 7322:         if ($srch->{'srchby'} eq 'uname') {
 7323:             my $unamecheck = $srch->{'srchterm'};
 7324:             if ($srch->{'srchtype'} eq 'contains') {
 7325:                 if ($unamecheck !~ /^\w/) {
 7326:                     $unamecheck = 'a'.$unamecheck; 
 7327:                 }
 7328:             }
 7329:             if ($unamecheck !~ /^$match_username$/) {
 7330:                 $response = &mt('You must specify a valid username. Only the following are allowed: letters numbers - . @');
 7331:             }
 7332:         }
 7333:     }
 7334:     if ($response ne '') {
 7335:         $response = '<span class="LC_warning">'.$response.'</span><br />';
 7336:     }
 7337:     if ($srch->{'srchin'} eq 'instd') {
 7338:         my $instd_chk = &instdirectorysrch_check($srch);
 7339:         if ($instd_chk ne 'ok') {
 7340:             my $domd_chk = &domdirectorysrch_check($srch);
 7341:             $response .= '<span class="LC_warning">'.$instd_chk.'</span><br />';
 7342:             if ($domd_chk eq 'ok') {
 7343:                 $response .= &mt('You may want to search in the LON-CAPA domain instead of the institutional directory.');
 7344:             }
 7345:             $response .= '<br />';
 7346:         }
 7347:     } else {
 7348:         unless (($context eq 'requestcrs') && ($srch->{'srchtype'} eq 'exact')) {
 7349:             my $domd_chk = &domdirectorysrch_check($srch);
 7350:             if ($domd_chk ne 'ok') {
 7351:                 my $instd_chk = &instdirectorysrch_check($srch);
 7352:                 $response .= '<span class="LC_warning">'.$domd_chk.'</span><br />';
 7353:                 if ($instd_chk eq 'ok') {
 7354:                     $response .= &mt('You may want to search in the institutional directory instead of the LON-CAPA domain.');
 7355:                 }
 7356:                 $response .= '<br />';
 7357:             }
 7358:         }
 7359:     }
 7360:     if ($response ne '') {
 7361:         return ($currstate,$response);
 7362:     }
 7363:     if ($srch->{'srchby'} eq 'uname') {
 7364:         if (($srch->{'srchin'} eq 'dom') || ($srch->{'srchin'} eq 'crs')) {
 7365:             if ($env{'form.forcenew'}) {
 7366:                 if ($srch->{'srchdomain'} ne $env{'request.role.domain'}) {
 7367:                     my $uhome=&Apache::lonnet::homeserver($srch->{'srchterm'},$srch->{'srchdomain'});
 7368:                     if ($uhome eq 'no_host') {
 7369:                         my $domdesc = &Apache::lonnet::domain($env{'request.role.domain'},'description');
 7370:                         my $showdom = &display_domain_info($env{'request.role.domain'});
 7371:                         $response = &mt('New users can only be created in the domain to which your current role belongs - [_1].',$showdom);
 7372:                     } else {
 7373:                         $currstate = 'modify';
 7374:                     }
 7375:                 } else {
 7376:                     $currstate = 'modify';
 7377:                 }
 7378:             } else {
 7379:                 if ($srch->{'srchin'} eq 'dom') {
 7380:                     if ($srch->{'srchtype'} eq 'exact') {
 7381:                         my $uhome=&Apache::lonnet::homeserver($srch->{'srchterm'},$srch->{'srchdomain'});
 7382:                         if ($uhome eq 'no_host') {
 7383:                             ($currstate,$response,$forcenewuser) =
 7384:                                 &build_search_response($context,$srch,%srch_results);
 7385:                         } else {
 7386:                             $currstate = 'modify';
 7387:                             if ($env{'form.action'} eq 'accesslogs') {
 7388:                                 $currstate = 'activity';
 7389:                             }
 7390:                             my $uname = $srch->{'srchterm'};
 7391:                             my $udom = $srch->{'srchdomain'};
 7392:                             $srch_results{$uname.':'.$udom} =
 7393:                                 { &Apache::lonnet::get('environment',
 7394:                                                        ['firstname',
 7395:                                                         'lastname',
 7396:                                                         'permanentemail'],
 7397:                                                          $udom,$uname)
 7398:                                 };
 7399:                         }
 7400:                     } else {
 7401:                         %srch_results = &Apache::lonnet::usersearch($srch);
 7402:                         ($currstate,$response,$forcenewuser) =
 7403:                             &build_search_response($context,$srch,%srch_results);
 7404:                     }
 7405:                 } else {
 7406:                     my $courseusers = &get_courseusers();
 7407:                     if ($srch->{'srchtype'} eq 'exact') {
 7408:                         if (exists($courseusers->{$srch->{'srchterm'}.':'.$srch->{'srchdomain'}})) {
 7409:                             $currstate = 'modify';
 7410:                         } else {
 7411:                             ($currstate,$response,$forcenewuser) =
 7412:                                 &build_search_response($context,$srch,%srch_results);
 7413:                         }
 7414:                     } else {
 7415:                         foreach my $user (keys(%$courseusers)) {
 7416:                             my ($cuname,$cudomain) = split(/:/,$user);
 7417:                             if ($cudomain eq $srch->{'srchdomain'}) {
 7418:                                 my $matched = 0;
 7419:                                 if ($srch->{'srchtype'} eq 'begins') {
 7420:                                     if ($cuname =~ /^\Q$srch->{'srchterm'}\E/i) {
 7421:                                         $matched = 1;
 7422:                                     }
 7423:                                 } else {
 7424:                                     if ($cuname =~ /\Q$srch->{'srchterm'}\E/i) {
 7425:                                         $matched = 1;
 7426:                                     }
 7427:                                 }
 7428:                                 if ($matched) {
 7429:                                     $srch_results{$user} = 
 7430: 					{&Apache::lonnet::get('environment',
 7431: 							     ['firstname',
 7432: 							      'lastname',
 7433: 							      'permanentemail'],
 7434: 							      $cudomain,$cuname)};
 7435:                                 }
 7436:                             }
 7437:                         }
 7438:                         ($currstate,$response,$forcenewuser) =
 7439:                             &build_search_response($context,$srch,%srch_results);
 7440:                     }
 7441:                 }
 7442:             }
 7443:         } elsif ($srch->{'srchin'} eq 'alc') {
 7444:             $currstate = 'query';
 7445:         } elsif ($srch->{'srchin'} eq 'instd') {
 7446:             ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query($srch);
 7447:             if ($dirsrchres eq 'ok') {
 7448:                 ($currstate,$response,$forcenewuser) = 
 7449:                     &build_search_response($context,$srch,%srch_results);
 7450:             } else {
 7451:                 my $showdom = &display_domain_info($srch->{'srchdomain'});
 7452:                 $response = '<span class="LC_warning">'.
 7453:                     &mt('Institutional directory search is not available in domain: [_1]',$showdom).
 7454:                     '</span><br />'.
 7455:                     &mt('You may want to search in the LON-CAPA domain instead of the institutional directory.').
 7456:                     '<br />'; 
 7457:             }
 7458:         }
 7459:     } else {
 7460:         if ($srch->{'srchin'} eq 'dom') {
 7461:             %srch_results = &Apache::lonnet::usersearch($srch);
 7462:             ($currstate,$response,$forcenewuser) = 
 7463:                 &build_search_response($context,$srch,%srch_results); 
 7464:         } elsif ($srch->{'srchin'} eq 'crs') {
 7465:             my $courseusers = &get_courseusers(); 
 7466:             foreach my $user (keys(%$courseusers)) {
 7467:                 my ($uname,$udom) = split(/:/,$user);
 7468:                 my %names = &Apache::loncommon::getnames($uname,$udom);
 7469:                 my %emails = &Apache::loncommon::getemails($uname,$udom);
 7470:                 if ($srch->{'srchby'} eq 'lastname') {
 7471:                     if ((($srch->{'srchtype'} eq 'exact') && 
 7472:                          ($names{'lastname'} eq $srch->{'srchterm'})) || 
 7473:                         (($srch->{'srchtype'} eq 'begins') &&
 7474:                          ($names{'lastname'} =~ /^\Q$srch->{'srchterm'}\E/i)) ||
 7475:                         (($srch->{'srchtype'} eq 'contains') &&
 7476:                          ($names{'lastname'} =~ /\Q$srch->{'srchterm'}\E/i))) {
 7477:                         $srch_results{$user} = {firstname => $names{'firstname'},
 7478:                                             lastname => $names{'lastname'},
 7479:                                             permanentemail => $emails{'permanentemail'},
 7480:                                            };
 7481:                     }
 7482:                 } elsif ($srch->{'srchby'} eq 'lastfirst') {
 7483:                     my ($srchlast,$srchfirst) = split(/,/,$srch->{'srchterm'});
 7484:                     $srchlast =~ s/\s+$//;
 7485:                     $srchfirst =~ s/^\s+//;
 7486:                     if ($srch->{'srchtype'} eq 'exact') {
 7487:                         if (($names{'lastname'} eq $srchlast) &&
 7488:                             ($names{'firstname'} eq $srchfirst)) {
 7489:                             $srch_results{$user} = {firstname => $names{'firstname'},
 7490:                                                 lastname => $names{'lastname'},
 7491:                                                 permanentemail => $emails{'permanentemail'},
 7492: 
 7493:                                            };
 7494:                         }
 7495:                     } elsif ($srch->{'srchtype'} eq 'begins') {
 7496:                         if (($names{'lastname'} =~ /^\Q$srchlast\E/i) &&
 7497:                             ($names{'firstname'} =~ /^\Q$srchfirst\E/i)) {
 7498:                             $srch_results{$user} = {firstname => $names{'firstname'},
 7499:                                                 lastname => $names{'lastname'},
 7500:                                                 permanentemail => $emails{'permanentemail'},
 7501:                                                };
 7502:                         }
 7503:                     } else {
 7504:                         if (($names{'lastname'} =~ /\Q$srchlast\E/i) && 
 7505:                             ($names{'firstname'} =~ /\Q$srchfirst\E/i)) {
 7506:                             $srch_results{$user} = {firstname => $names{'firstname'},
 7507:                                                 lastname => $names{'lastname'},
 7508:                                                 permanentemail => $emails{'permanentemail'},
 7509:                                                };
 7510:                         }
 7511:                     }
 7512:                 }
 7513:             }
 7514:             ($currstate,$response,$forcenewuser) = 
 7515:                 &build_search_response($context,$srch,%srch_results); 
 7516:         } elsif ($srch->{'srchin'} eq 'alc') {
 7517:             $currstate = 'query';
 7518:         } elsif ($srch->{'srchin'} eq 'instd') {
 7519:             ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query($srch); 
 7520:             if ($dirsrchres eq 'ok') {
 7521:                 ($currstate,$response,$forcenewuser) = 
 7522:                     &build_search_response($context,$srch,%srch_results);
 7523:             } else {
 7524:                 my $showdom = &display_domain_info($srch->{'srchdomain'});
 7525:                 $response = '<span class="LC_warning">'.
 7526:                     &mt('Institutional directory search is not available in domain: [_1]',$showdom).
 7527:                     '</span><br />'.
 7528:                     &mt('You may want to search in the LON-CAPA domain instead of the institutional directory.').
 7529:                     '<br />';
 7530:             }
 7531:         }
 7532:     }
 7533:     return ($currstate,$response,$forcenewuser,\%srch_results);
 7534: }
 7535: 
 7536: sub domdirectorysrch_check {
 7537:     my ($srch) = @_;
 7538:     my $response;
 7539:     my %dom_inst_srch = &Apache::lonnet::get_dom('configuration',
 7540:                                              ['directorysrch'],$srch->{'srchdomain'});
 7541:     my $showdom = &display_domain_info($srch->{'srchdomain'});
 7542:     if (ref($dom_inst_srch{'directorysrch'}) eq 'HASH') {
 7543:         if ($dom_inst_srch{'directorysrch'}{'lcavailable'} eq '0') {
 7544:             return &mt('LON-CAPA directory search is not available in domain: [_1]',$showdom);
 7545:         }
 7546:         if ($dom_inst_srch{'directorysrch'}{'lclocalonly'}) {
 7547:             if ($env{'request.role.domain'} ne $srch->{'srchdomain'}) {
 7548:                 return &mt('LON-CAPA directory search in domain: [_1] is only allowed for users with a current role in the domain.',$showdom);
 7549:             }
 7550:         }
 7551:     }
 7552:     return 'ok';
 7553: }
 7554: 
 7555: sub instdirectorysrch_check {
 7556:     my ($srch) = @_;
 7557:     my $can_search = 0;
 7558:     my $response;
 7559:     my %dom_inst_srch = &Apache::lonnet::get_dom('configuration',
 7560:                                              ['directorysrch'],$srch->{'srchdomain'});
 7561:     my $showdom = &display_domain_info($srch->{'srchdomain'});
 7562:     if (ref($dom_inst_srch{'directorysrch'}) eq 'HASH') {
 7563:         if (!$dom_inst_srch{'directorysrch'}{'available'}) {
 7564:             return &mt('Institutional directory search is not available in domain: [_1]',$showdom); 
 7565:         }
 7566:         if ($dom_inst_srch{'directorysrch'}{'localonly'}) {
 7567:             if ($env{'request.role.domain'} ne $srch->{'srchdomain'}) {
 7568:                 return &mt('Institutional directory search in domain: [_1] is only allowed for users with a current role in the domain.',$showdom); 
 7569:             }
 7570:             my @usertypes = split(/:/,$env{'environment.inststatus'});
 7571:             if (!@usertypes) {
 7572:                 push(@usertypes,'default');
 7573:             }
 7574:             if (ref($dom_inst_srch{'directorysrch'}{'cansearch'}) eq 'ARRAY') {
 7575:                 foreach my $type (@usertypes) {
 7576:                     if (grep(/^\Q$type\E$/,@{$dom_inst_srch{'directorysrch'}{'cansearch'}})) {
 7577:                         $can_search = 1;
 7578:                         last;
 7579:                     }
 7580:                 }
 7581:             }
 7582:             if (!$can_search) {
 7583:                 my ($insttypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($srch->{'srchdomain'});
 7584:                 my @longtypes; 
 7585:                 foreach my $item (@usertypes) {
 7586:                     if (defined($insttypes->{$item})) { 
 7587:                         push (@longtypes,$insttypes->{$item});
 7588:                     } elsif ($item eq 'default') {
 7589:                         push (@longtypes,&mt('other')); 
 7590:                     }
 7591:                 }
 7592:                 my $insttype_str = join(', ',@longtypes); 
 7593:                 return &mt('Institutional directory search in domain: [_1] is not available to your user type: ',$showdom).$insttype_str;
 7594:             }
 7595:         } else {
 7596:             $can_search = 1;
 7597:         }
 7598:     } else {
 7599:         return &mt('Institutional directory search has not been configured for domain: [_1]',$showdom);
 7600:     }
 7601:     my %longtext = &Apache::lonlocal::texthash (
 7602:                        uname     => 'username',
 7603:                        lastfirst => 'last name, first name',
 7604:                        lastname  => 'last name',
 7605:                        contains  => 'contains',
 7606:                        exact     => 'as exact match to',
 7607:                        begins    => 'begins with',
 7608:                    );
 7609:     if ($can_search) {
 7610:         if (ref($dom_inst_srch{'directorysrch'}{'searchby'}) eq 'ARRAY') {
 7611:             if (!grep(/^\Q$srch->{'srchby'}\E$/,@{$dom_inst_srch{'directorysrch'}{'searchby'}})) {
 7612:                 return &mt('Institutional directory search in domain: [_1] is not available for searching by "[_2]"',$showdom,$longtext{$srch->{'srchby'}});
 7613:             }
 7614:         } else {
 7615:             return &mt('Institutional directory search in domain: [_1] is not available.', $showdom);
 7616:         }
 7617:     }
 7618:     if ($can_search) {
 7619:         if (ref($dom_inst_srch{'directorysrch'}{'searchtypes'}) eq 'ARRAY') {
 7620:             if (grep(/^\Q$srch->{'srchtype'}\E/,@{$dom_inst_srch{'directorysrch'}{'searchtypes'}})) {
 7621:                 return 'ok';
 7622:             } else {
 7623:                 return &mt('Institutional directory search in domain [_1] is not available for the requested search type: "[_2]"',$showdom,$longtext{$srch->{'srchtype'}});
 7624:             }
 7625:         } else {
 7626:             if ((($dom_inst_srch{'directorysrch'}{'searchtypes'} eq 'specify') &&
 7627:                  ($srch->{'srchtype'} eq 'exact' || $srch->{'srchtype'} eq 'contains')) ||
 7628:                 ($dom_inst_srch{'directorysrch'}{'searchtypes'} eq $srch->{'srchtype'})) {
 7629:                 return 'ok';
 7630:             } else {
 7631:                 return &mt('Institutional directory search in domain [_1] is not available for the requested search type: "[_2]"',$showdom,$longtext{$srch->{'srchtype'}});
 7632:             }
 7633:         }
 7634:     }
 7635: }
 7636: 
 7637: sub get_courseusers {
 7638:     my %advhash;
 7639:     my $classlist = &Apache::loncoursedata::get_classlist();
 7640:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles();
 7641:     foreach my $role (sort(keys(%coursepersonnel))) {
 7642:         foreach my $user (split(/\,/,$coursepersonnel{$role})) {
 7643: 	    if (!exists($classlist->{$user})) {
 7644: 		$classlist->{$user} = [];
 7645: 	    }
 7646:         }
 7647:     }
 7648:     return $classlist;
 7649: }
 7650: 
 7651: sub build_search_response {
 7652:     my ($context,$srch,%srch_results) = @_;
 7653:     my ($currstate,$response,$forcenewuser);
 7654:     my %names = (
 7655:           'uname'     => 'username',
 7656:           'lastname'  => 'last name',
 7657:           'lastfirst' => 'last name, first name',
 7658:           'crs'       => 'this course',
 7659:           'dom'       => 'LON-CAPA domain',
 7660:           'instd'     => 'the institutional directory for domain',
 7661:     );
 7662: 
 7663:     my %single = (
 7664:                    begins   => 'A match',
 7665:                    contains => 'A match',
 7666:                    exact    => 'An exact match',
 7667:                  );
 7668:     my %nomatch = (
 7669:                    begins   => 'No match',
 7670:                    contains => 'No match',
 7671:                    exact    => 'No exact match',
 7672:                   );
 7673:     if (keys(%srch_results) > 1) {
 7674:         $currstate = 'select';
 7675:     } else {
 7676:         if (keys(%srch_results) == 1) {
 7677:             if ($env{'form.action'} eq 'accesslogs') {
 7678:                 $currstate = 'activity';
 7679:             } else {
 7680:                 $currstate = 'modify';
 7681:             }
 7682:             $response = &mt("$single{$srch->{'srchtype'}} was found for the $names{$srch->{'srchby'}} ([_1]) in $names{$srch->{'srchin'}}.",$srch->{'srchterm'});
 7683:             if ($srch->{'srchin'} eq 'dom' || $srch->{'srchin'} eq 'instd') {
 7684:                 $response .= ': '.&display_domain_info($srch->{'srchdomain'});
 7685:             }
 7686:         } else { # Search has nothing found. Prepare message to user.
 7687:             $response = '<span class="LC_warning">';
 7688:             if ($srch->{'srchin'} eq 'dom' || $srch->{'srchin'} eq 'instd') {
 7689:                 $response .= &mt("$nomatch{$srch->{'srchtype'}} found for the $names{$srch->{'srchby'}} [_1] in $names{$srch->{'srchin'}}: [_2]",
 7690:                                  '<b>'.$srch->{'srchterm'}.'</b>',
 7691:                                  &display_domain_info($srch->{'srchdomain'}));
 7692:             } else {
 7693:                 $response .= &mt("$nomatch{$srch->{'srchtype'}} found for the $names{$srch->{'srchby'}} [_1] in $names{$srch->{'srchin'}}.",
 7694:                                  '<b>'.$srch->{'srchterm'}.'</b>');
 7695:             }
 7696:             $response .= '</span>';
 7697: 
 7698:             if ($srch->{'srchin'} ne 'alc') {
 7699:                 $forcenewuser = 1;
 7700:                 my $cansrchinst = 0; 
 7701:                 if ($srch->{'srchdomain'}) {
 7702:                     my %domconfig = &Apache::lonnet::get_dom('configuration',['directorysrch'],$srch->{'srchdomain'});
 7703:                     if (ref($domconfig{'directorysrch'}) eq 'HASH') {
 7704:                         if ($domconfig{'directorysrch'}{'available'}) {
 7705:                             $cansrchinst = 1;
 7706:                         } 
 7707:                     }
 7708:                 }
 7709:                 if ((($srch->{'srchby'} eq 'lastfirst') || 
 7710:                      ($srch->{'srchby'} eq 'lastname')) &&
 7711:                     ($srch->{'srchin'} eq 'dom')) {
 7712:                     if ($cansrchinst) {
 7713:                         $response .= '<br />'.&mt('You may want to broaden your search to a search of the institutional directory for the domain.');
 7714:                     }
 7715:                 }
 7716:                 if ($srch->{'srchin'} eq 'crs') {
 7717:                     $response .= '<br />'.&mt('You may want to broaden your search to the selected LON-CAPA domain.');
 7718:                 }
 7719:             }
 7720:             my $createdom = $env{'request.role.domain'};
 7721:             if ($context eq 'requestcrs') {
 7722:                 if ($env{'form.coursedom'} ne '') {
 7723:                     $createdom = $env{'form.coursedom'};
 7724:                 }
 7725:             }
 7726:             unless (($env{'form.action'} eq 'accesslogs') || (($srch->{'srchby'} eq 'uname') && ($srch->{'srchin'} eq 'dom') &&
 7727:                     ($srch->{'srchtype'} eq 'exact') && ($srch->{'srchdomain'} eq $createdom))) {
 7728:                 my $cancreate =
 7729:                     &Apache::lonuserutils::can_create_user($createdom,$context);
 7730:                 my $targetdom = '<span class="LC_cusr_emph">'.$createdom.'</span>';
 7731:                 if ($cancreate) {
 7732:                     my $showdom = &display_domain_info($createdom); 
 7733:                     $response .= '<br /><br />'
 7734:                                 .'<b>'.&mt('To add a new user:').'</b>'
 7735:                                 .'<br />';
 7736:                     if ($context eq 'requestcrs') {
 7737:                         $response .= &mt("(You can only define new users in the new course's domain - [_1])",$targetdom);
 7738:                     } else {
 7739:                         $response .= &mt("(You can only create new users in your current role's domain - [_1])",$targetdom);
 7740:                     }
 7741:                     $response .='<ul><li>'
 7742:                                 .&mt("Set 'Domain/institution to search' to: [_1]",'<span class="LC_cusr_emph">'.$showdom.'</span>')
 7743:                                 .'</li><li>'
 7744:                                 .&mt("Set 'Search criteria' to: [_1]username is ..... in selected LON-CAPA domain[_2]",'<span class="LC_cusr_emph">','</span>')
 7745:                                 .'</li><li>'
 7746:                                 .&mt('Provide the proposed username')
 7747:                                 .'</li><li>'
 7748:                                 .&mt("Click 'Search'")
 7749:                                 .'</li></ul><br />';
 7750:                 } else {
 7751:                     my $helplink = ' href="javascript:helpMenu('."'display'".')"';
 7752:                     $response .= '<br /><br />';
 7753:                     if ($context eq 'requestcrs') {
 7754:                         $response .= &mt("You are not authorized to define new users in the new course's domain - [_1].",$targetdom);
 7755:                     } else {
 7756:                         $response .= &mt("You are not authorized to create new users in your current role's domain - [_1].",$targetdom);
 7757:                     }
 7758:                     $response .= '<br />'
 7759:                                  .&mt('Please contact the [_1]helpdesk[_2] if you need to create a new user.'
 7760:                                     ,' <a'.$helplink.'>'
 7761:                                     ,'</a>')
 7762:                                  .'<br />';
 7763:                 }
 7764:             }
 7765:         }
 7766:     }
 7767:     return ($currstate,$response,$forcenewuser);
 7768: }
 7769: 
 7770: sub display_domain_info {
 7771:     my ($dom) = @_;
 7772:     my $output = $dom;
 7773:     if ($dom ne '') { 
 7774:         my $domdesc = &Apache::lonnet::domain($dom,'description');
 7775:         if ($domdesc ne '') {
 7776:             $output .= ' <span class="LC_cusr_emph">('.$domdesc.')</span>';
 7777:         }
 7778:     }
 7779:     return $output;
 7780: }
 7781: 
 7782: sub crumb_utilities {
 7783:     my %elements = (
 7784:        crtuser => {
 7785:            srchterm => 'text',
 7786:            srchin => 'selectbox',
 7787:            srchby => 'selectbox',
 7788:            srchtype => 'selectbox',
 7789:            srchdomain => 'selectbox',
 7790:        },
 7791:        crtusername => {
 7792:            srchterm => 'text',
 7793:            srchdomain => 'selectbox',
 7794:        },
 7795:        docustom => {
 7796:            rolename => 'selectbox',
 7797:            newrolename => 'textbox',
 7798:        },
 7799:        studentform => {
 7800:            srchterm => 'text',
 7801:            srchin => 'selectbox',
 7802:            srchby => 'selectbox',
 7803:            srchtype => 'selectbox',
 7804:            srchdomain => 'selectbox',
 7805:        },
 7806:     );
 7807: 
 7808:     my $jsback .= qq|
 7809: function backPage(formname,prevphase,prevstate) {
 7810:     if (typeof prevphase == 'undefined') {
 7811:         formname.phase.value = '';
 7812:     }
 7813:     else {  
 7814:         formname.phase.value = prevphase;
 7815:     }
 7816:     if (typeof prevstate == 'undefined') {
 7817:         formname.currstate.value = '';
 7818:     }
 7819:     else {
 7820:         formname.currstate.value = prevstate;
 7821:     }
 7822:     formname.submit();
 7823: }
 7824: |;
 7825:     return ($jsback,\%elements);
 7826: }
 7827: 
 7828: sub course_level_table {
 7829:     my ($inccourses,$showcredits,$defaultcredits) = @_;
 7830:     return unless (ref($inccourses) eq 'HASH');
 7831:     my $table = '';
 7832: # Custom Roles?
 7833: 
 7834:     my %customroles=&Apache::lonuserutils::my_custom_roles();
 7835:     my %lt=&Apache::lonlocal::texthash(
 7836:             'exs'  => "Existing sections",
 7837:             'new'  => "Define new section",
 7838:             'ssd'  => "Set Start Date",
 7839:             'sed'  => "Set End Date",
 7840:             'crl'  => "Course Level",
 7841:             'act'  => "Activate",
 7842:             'rol'  => "Role",
 7843:             'ext'  => "Extent",
 7844:             'grs'  => "Section",
 7845:             'crd'  => "Credits",
 7846:             'sta'  => "Start",
 7847:             'end'  => "End"
 7848:     );
 7849: 
 7850:     foreach my $protectedcourse (sort(keys(%{$inccourses}))) {
 7851: 	my $thiscourse=$protectedcourse;
 7852: 	$thiscourse=~s:_:/:g;
 7853: 	my %coursedata=&Apache::lonnet::coursedescription($thiscourse);
 7854:         my $isowner = &Apache::lonuserutils::is_courseowner($protectedcourse,$coursedata{'internal.courseowner'});
 7855: 	my $area=$coursedata{'description'};
 7856:         my $crstype=$coursedata{'type'};
 7857: 	if (!defined($area)) { $area=&mt('Unavailable course').': '.$protectedcourse; }
 7858: 	my ($domain,$cnum)=split(/\//,$thiscourse);
 7859:         my %sections_count;
 7860:         if (defined($env{'request.course.id'})) {
 7861:             if ($env{'request.course.id'} eq $domain.'_'.$cnum) {
 7862:                 %sections_count = 
 7863: 		    &Apache::loncommon::get_sections($domain,$cnum);
 7864:             }
 7865:         }
 7866:         my @roles = &Apache::lonuserutils::roles_by_context('course','',$crstype);
 7867: 	foreach my $role (@roles) {
 7868:             my $plrole=&Apache::lonnet::plaintext($role,$crstype);
 7869: 	    if ((&Apache::lonnet::allowed('c'.$role,$thiscourse)) ||
 7870:                 ((($role eq 'cc') || ($role eq 'co')) && ($isowner))) {
 7871:                 $table .= &course_level_row($protectedcourse,$role,$area,$domain,
 7872:                                             $plrole,\%sections_count,\%lt,
 7873:                                             $showcredits,$defaultcredits,$crstype);
 7874:             } elsif ($env{'request.course.sec'} ne '') {
 7875:                 if (&Apache::lonnet::allowed('c'.$role,$thiscourse.'/'.
 7876:                                              $env{'request.course.sec'})) {
 7877:                     $table .= &course_level_row($protectedcourse,$role,$area,$domain,
 7878:                                                 $plrole,\%sections_count,\%lt,
 7879:                                                 $showcredits,$defaultcredits,$crstype);
 7880:                 }
 7881:             }
 7882:         }
 7883:         if (&Apache::lonnet::allowed('ccr',$thiscourse)) {
 7884:             foreach my $cust (sort(keys(%customroles))) {
 7885:                 next if ($crstype eq 'Community' && $customroles{$cust} =~ /bre\&S/);
 7886:                 my $role = 'cr_cr_'.$env{'user.domain'}.'_'.$env{'user.name'}.'_'.$cust;
 7887:                 $table .= &course_level_row($protectedcourse,$role,$area,$domain,
 7888:                                             $cust,\%sections_count,\%lt,
 7889:                                             $showcredits,$defaultcredits,$crstype);
 7890:             }
 7891: 	}
 7892:     }
 7893:     return '' if ($table eq ''); # return nothing if there is nothing 
 7894:                                  # in the table
 7895:     my $result;
 7896:     if (!$env{'request.course.id'}) {
 7897:         $result = '<h4>'.$lt{'crl'}.'</h4>'."\n";
 7898:     }
 7899:     $result .= 
 7900: &Apache::loncommon::start_data_table().
 7901: &Apache::loncommon::start_data_table_header_row().
 7902: '<th>'.$lt{'act'}.'</th><th>'.$lt{'rol'}.'</th>'."\n".
 7903: '<th>'.$lt{'ext'}.'</th><th>'."\n";
 7904:     if ($showcredits) {
 7905:         $result .= $lt{'crd'}.'</th>';
 7906:     }
 7907:     $result .=
 7908: '<th>'.$lt{'grs'}.'</th><th>'.$lt{'sta'}.'</th>'."\n".
 7909: '<th>'.$lt{'end'}.'</th>'.
 7910: &Apache::loncommon::end_data_table_header_row().
 7911: $table.
 7912: &Apache::loncommon::end_data_table();
 7913:     return $result;
 7914: }
 7915: 
 7916: sub course_level_row {
 7917:     my ($protectedcourse,$role,$area,$domain,$plrole,$sections_count,
 7918:         $lt,$showcredits,$defaultcredits,$crstype) = @_;
 7919:     my $creditem;
 7920:     my $row = &Apache::loncommon::start_data_table_row().
 7921:               ' <td><input type="checkbox" name="act_'.
 7922:               $protectedcourse.'_'.$role.'" /></td>'."\n".
 7923:               ' <td>'.$plrole.'</td>'."\n".
 7924:               ' <td>'.$area.'<br />Domain: '.$domain.'</td>'."\n";
 7925:     if (($showcredits) && ($role eq 'st') && ($crstype eq 'Course')) {
 7926:         $row .= 
 7927:             '<td><input type="text" name="credits_'.$protectedcourse.'_'.
 7928:             $role.'" size="3" value="'.$defaultcredits.'" /></td>';
 7929:     } else {
 7930:         $row .= '<td>&nbsp;</td>';
 7931:     }
 7932:     if (($role eq 'cc') || ($role eq 'co')) {
 7933:         $row .= '<td>&nbsp;</td>';
 7934:     } elsif ($env{'request.course.sec'} ne '') {
 7935:         $row .= ' <td><input type="hidden" value="'.
 7936:                 $env{'request.course.sec'}.'" '.
 7937:                 'name="sec_'.$protectedcourse.'_'.$role.'" />'.
 7938:                 $env{'request.course.sec'}.'</td>';
 7939:     } else {
 7940:         if (ref($sections_count) eq 'HASH') {
 7941:             my $currsec = 
 7942:                 &Apache::lonuserutils::course_sections($sections_count,
 7943:                                                        $protectedcourse.'_'.$role);
 7944:             $row .= '<td><table class="LC_createuser">'."\n".
 7945:                     '<tr class="LC_section_row">'."\n".
 7946:                     ' <td valign="top">'.$lt->{'exs'}.'<br />'.
 7947:                        $currsec.'</td>'."\n".
 7948:                      ' <td>&nbsp;&nbsp;</td>'."\n".
 7949:                      ' <td valign="top">&nbsp;'.$lt->{'new'}.'<br />'.
 7950:                      '<input type="text" name="newsec_'.$protectedcourse.'_'.$role.
 7951:                      '" value="" />'.
 7952:                      '<input type="hidden" '.
 7953:                      'name="sec_'.$protectedcourse.'_'.$role.'" /></td>'."\n".
 7954:                      '</tr></table></td>'."\n";
 7955:         } else {
 7956:             $row .= '<td><input type="text" size="10" '.
 7957:                     'name="sec_'.$protectedcourse.'_'.$role.'" /></td>'."\n";
 7958:         }
 7959:     }
 7960:     $row .= <<ENDTIMEENTRY;
 7961: <td><input type="hidden" name="start_$protectedcourse\_$role" value="" />
 7962: <a href=
 7963: "javascript:pjump('date_start','Start Date $plrole',document.cu.start_$protectedcourse\_$role.value,'start_$protectedcourse\_$role','cu.pres','dateset')">$lt->{'ssd'}</a></td>
 7964: <td><input type="hidden" name="end_$protectedcourse\_$role" value="" />
 7965: <a href=
 7966: "javascript:pjump('date_end','End Date $plrole',document.cu.end_$protectedcourse\_$role.value,'end_$protectedcourse\_$role','cu.pres','dateset')">$lt->{'sed'}</a></td>
 7967: ENDTIMEENTRY
 7968:     $row .= &Apache::loncommon::end_data_table_row();
 7969:     return $row;
 7970: }
 7971: 
 7972: sub course_level_dc {
 7973:     my ($dcdom,$showcredits) = @_;
 7974:     my %customroles=&Apache::lonuserutils::my_custom_roles();
 7975:     my @roles = &Apache::lonuserutils::roles_by_context('course');
 7976:     my $hiddenitems = '<input type="hidden" name="dcdomain" value="'.$dcdom.'" />'.
 7977:                       '<input type="hidden" name="origdom" value="'.$dcdom.'" />'.
 7978:                       '<input type="hidden" name="dccourse" value="" />';
 7979:     my $courseform=&Apache::loncommon::selectcourse_link
 7980:             ('cu','dccourse','dcdomain','coursedesc',undef,undef,'Select','crstype');
 7981:     my $credit_elem;
 7982:     if ($showcredits) {
 7983:         $credit_elem = 'credits';
 7984:     }
 7985:     my $cb_jscript = &Apache::loncommon::coursebrowser_javascript($dcdom,'currsec','cu','role','Course/Community Browser',$credit_elem);
 7986:     my %lt=&Apache::lonlocal::texthash(
 7987:                     'rol'  => "Role",
 7988:                     'grs'  => "Section",
 7989:                     'exs'  => "Existing sections",
 7990:                     'new'  => "Define new section", 
 7991:                     'sta'  => "Start",
 7992:                     'end'  => "End",
 7993:                     'ssd'  => "Set Start Date",
 7994:                     'sed'  => "Set End Date",
 7995:                     'scc'  => "Course/Community",
 7996:                     'crd'  => "Credits",
 7997:                   );
 7998:     my $header = '<h4>'.&mt('Course/Community Level').'</h4>'.
 7999:                  &Apache::loncommon::start_data_table().
 8000:                  &Apache::loncommon::start_data_table_header_row().
 8001:                  '<th>'.$lt{'scc'}.'</th><th>'.$lt{'rol'}.'</th>'."\n".
 8002:                  '<th>'.$lt{'grs'}.'</th>'."\n";
 8003:     $header .=   '<th>'.$lt{'crd'}.'</th>'."\n" if ($showcredits);
 8004:     $header .=   '<th>'.$lt{'sta'}.'</th><th>'.$lt{'end'}.'</th>'."\n".
 8005:                  &Apache::loncommon::end_data_table_header_row();
 8006:     my $otheritems = &Apache::loncommon::start_data_table_row()."\n".
 8007:                      '<td><br /><span class="LC_nobreak"><input type="text" name="coursedesc" value="" onfocus="this.blur();opencrsbrowser('."'cu','dccourse','dcdomain','coursedesc','','','','crstype'".')" />'.
 8008:                      $courseform.('&nbsp;' x4).'</span></td>'."\n".
 8009:                      '<td valign="top"><br /><select name="role">'."\n";
 8010:     foreach my $role (@roles) {
 8011:         my $plrole=&Apache::lonnet::plaintext($role);
 8012:         $otheritems .= '  <option value="'.$role.'">'.$plrole.'</option>';
 8013:     }
 8014:     if ( keys(%customroles) > 0) {
 8015:         foreach my $cust (sort(keys(%customroles))) {
 8016:             my $custrole='cr_cr_'.$env{'user.domain'}.
 8017:                     '_'.$env{'user.name'}.'_'.$cust;
 8018:             $otheritems .= '  <option value="'.$custrole.'">'.$cust.'</option>';
 8019:         }
 8020:     }
 8021:     $otheritems .= '</select></td><td>'.
 8022:                      '<table border="0" cellspacing="0" cellpadding="0">'.
 8023:                      '<tr><td valign="top"><b>'.$lt{'exs'}.'</b><br /><select name="currsec">'.
 8024:                      ' <option value="">&lt;--'.&mt('Pick course first').'</option></select></td>'.
 8025:                      '<td>&nbsp;&nbsp;</td>'.
 8026:                      '<td valign="top">&nbsp;<b>'.$lt{'new'}.'</b><br />'.
 8027:                      '<input type="text" name="newsec" value="" />'.
 8028:                      '<input type="hidden" name="section" value="" />'.
 8029:                      '<input type="hidden" name="groups" value="" />'.
 8030:                      '<input type="hidden" name="crstype" value="" /></td>'.
 8031:                      '</tr></table></td>'."\n";
 8032:     if ($showcredits) {
 8033:         $otheritems .= '<td><br />'."\n".
 8034:                        '<input type="text" size="3" name="credits" value="" /></td>'."\n";
 8035:     }
 8036:     $otheritems .= <<ENDTIMEENTRY;
 8037: <td><br /><input type="hidden" name="start" value='' />
 8038: <a href=
 8039: "javascript:pjump('date_start','Start Date',document.cu.start.value,'start','cu.pres','dateset')">$lt{'ssd'}</a></td>
 8040: <td><br /><input type="hidden" name="end" value='' />
 8041: <a href=
 8042: "javascript:pjump('date_end','End Date',document.cu.end.value,'end','cu.pres','dateset')">$lt{'sed'}</a></td>
 8043: ENDTIMEENTRY
 8044:     $otheritems .= &Apache::loncommon::end_data_table_row().
 8045:                    &Apache::loncommon::end_data_table()."\n";
 8046:     return $cb_jscript.$header.$hiddenitems.$otheritems;
 8047: }
 8048: 
 8049: sub update_selfenroll_config {
 8050:     my ($r,$cid,$cdom,$cnum,$context,$crstype,$currsettings) = @_;
 8051:     return unless (ref($currsettings) eq 'HASH');
 8052:     my ($row,$lt) = &Apache::lonuserutils::get_selfenroll_titles();
 8053:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
 8054:     my (%changes,%warning);
 8055:     my $curr_types;
 8056:     my %noedit;
 8057:     unless ($context eq 'domain') {
 8058:         %noedit = &get_noedit_fields($cdom,$cnum,$crstype,$row);
 8059:     }
 8060:     if (ref($row) eq 'ARRAY') {
 8061:         foreach my $item (@{$row}) {
 8062:             next if ($noedit{$item});
 8063:             if ($item eq 'enroll_dates') {
 8064:                 my (%currenrolldate,%newenrolldate);
 8065:                 foreach my $type ('start','end') {
 8066:                     $currenrolldate{$type} = $currsettings->{'selfenroll_'.$type.'_date'};
 8067:                     $newenrolldate{$type} = &Apache::lonhtmlcommon::get_date_from_form('selfenroll_'.$type.'_date');
 8068:                     if ($newenrolldate{$type} ne $currenrolldate{$type}) {
 8069:                         $changes{'internal.selfenroll_'.$type.'_date'} = $newenrolldate{$type};
 8070:                     }
 8071:                 }
 8072:             } elsif ($item eq 'access_dates') {
 8073:                 my (%currdate,%newdate);
 8074:                 foreach my $type ('start','end') {
 8075:                     $currdate{$type} = $currsettings->{'selfenroll_'.$type.'_access'};
 8076:                     $newdate{$type} = &Apache::lonhtmlcommon::get_date_from_form('selfenroll_'.$type.'_access');
 8077:                     if ($newdate{$type} ne $currdate{$type}) {
 8078:                         $changes{'internal.selfenroll_'.$type.'_access'} = $newdate{$type};
 8079:                     }
 8080:                 }
 8081:             } elsif ($item eq 'types') {
 8082:                 $curr_types = $currsettings->{'selfenroll_'.$item};
 8083:                 if ($env{'form.selfenroll_all'}) {
 8084:                     if ($curr_types ne '*') {
 8085:                         $changes{'internal.selfenroll_types'} = '*';
 8086:                     } else {
 8087:                         next;
 8088:                     }
 8089:                 } else {
 8090:                     my %currdoms;
 8091:                     my @entries = split(/;/,$curr_types);
 8092:                     my @deletedoms = &Apache::loncommon::get_env_multiple('form.selfenroll_delete');
 8093:                     my @activations = &Apache::loncommon::get_env_multiple('form.selfenroll_activate');
 8094:                     my $newnum = 0;
 8095:                     my @latesttypes;
 8096:                     foreach my $num (@activations) {
 8097:                         my @types = &Apache::loncommon::get_env_multiple('form.selfenroll_types_'.$num);
 8098:                         if (@types > 0) {
 8099:                             @types = sort(@types);
 8100:                             my $typestr = join(',',@types);
 8101:                             my $typedom = $env{'form.selfenroll_dom_'.$num};
 8102:                             $latesttypes[$newnum] = $typedom.':'.$typestr;
 8103:                             $currdoms{$typedom} = 1;
 8104:                             $newnum ++;
 8105:                         }
 8106:                     }
 8107:                     for (my $j=0; $j<$env{'form.selfenroll_types_total'}; $j++) {
 8108:                         if ((!grep(/^$j$/,@deletedoms)) && (!grep(/^$j$/,@activations))) {
 8109:                             my @types = &Apache::loncommon::get_env_multiple('form.selfenroll_types_'.$j);
 8110:                             if (@types > 0) {
 8111:                                 @types = sort(@types);
 8112:                                 my $typestr = join(',',@types);
 8113:                                 my $typedom = $env{'form.selfenroll_dom_'.$j};
 8114:                                 $latesttypes[$newnum] = $typedom.':'.$typestr;
 8115:                                 $currdoms{$typedom} = 1;
 8116:                                 $newnum ++;
 8117:                             }
 8118:                         }
 8119:                     }
 8120:                     if ($env{'form.selfenroll_newdom'} ne '') {
 8121:                         my $typedom = $env{'form.selfenroll_newdom'};
 8122:                         if ((!defined($currdoms{$typedom})) && 
 8123:                             (&Apache::lonnet::domain($typedom) ne '')) {
 8124:                             my $typestr;
 8125:                             my ($othertitle,$usertypes,$types) = 
 8126:                                 &Apache::loncommon::sorted_inst_types($typedom);
 8127:                             my $othervalue = 'any';
 8128:                             if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 8129:                                 if (@{$types} > 0) {
 8130:                                     my @esc_types = map { &escape($_); } @{$types};
 8131:                                     $othervalue = 'other';
 8132:                                     $typestr = join(',',(@esc_types,$othervalue));
 8133:                                 }
 8134:                                 $typestr = $othervalue;
 8135:                             } else {
 8136:                                 $typestr = $othervalue;
 8137:                             } 
 8138:                             $latesttypes[$newnum] = $typedom.':'.$typestr;
 8139:                             $newnum ++ ;
 8140:                         }
 8141:                     }
 8142:                     my $selfenroll_types = join(';',@latesttypes);
 8143:                     if ($selfenroll_types ne $curr_types) {
 8144:                         $changes{'internal.selfenroll_types'} = $selfenroll_types;
 8145:                     }
 8146:                 }
 8147:             } elsif ($item eq 'limit') {
 8148:                 my $newlimit = $env{'form.selfenroll_limit'};
 8149:                 my $newcap = $env{'form.selfenroll_cap'};
 8150:                 $newcap =~s/\s+//g;
 8151:                 my $currlimit =  $currsettings->{'selfenroll_limit'};
 8152:                 $currlimit = 'none' if ($currlimit eq '');
 8153:                 my $currcap = $currsettings->{'selfenroll_cap'};
 8154:                 if ($newlimit ne $currlimit) {
 8155:                     if ($newlimit ne 'none') {
 8156:                         if ($newcap =~ /^\d+$/) {
 8157:                             if ($newcap ne $currcap) {
 8158:                                 $changes{'internal.selfenroll_cap'} = $newcap;
 8159:                             }
 8160:                             $changes{'internal.selfenroll_limit'} = $newlimit;
 8161:                         } else {
 8162:                             $warning{$item} = &mt('Maximum enrollment setting unchanged.').'<br />'.
 8163:                                 &mt('The value provided was invalid - it must be a positive integer if enrollment is being limited.'); 
 8164:                         }
 8165:                     } elsif ($currcap ne '') {
 8166:                         $changes{'internal.selfenroll_cap'} = '';
 8167:                         $changes{'internal.selfenroll_limit'} = $newlimit; 
 8168:                     }
 8169:                 } elsif ($currlimit ne 'none') {
 8170:                     if ($newcap =~ /^\d+$/) {
 8171:                         if ($newcap ne $currcap) {
 8172:                             $changes{'internal.selfenroll_cap'} = $newcap;
 8173:                         }
 8174:                     } else {
 8175:                         $warning{$item} = &mt('Maximum enrollment setting unchanged.').'<br />'.
 8176:                             &mt('The value provided was invalid - it must be a positive integer if enrollment is being limited.');
 8177:                     }
 8178:                 }
 8179:             } elsif ($item eq 'approval') {
 8180:                 my (@currnotified,@newnotified);
 8181:                 my $currapproval = $currsettings->{'selfenroll_approval'};
 8182:                 my $currnotifylist = $currsettings->{'selfenroll_notifylist'};
 8183:                 if ($currnotifylist ne '') {
 8184:                     @currnotified = split(/,/,$currnotifylist);
 8185:                     @currnotified = sort(@currnotified);
 8186:                 }
 8187:                 my $newapproval = $env{'form.selfenroll_approval'};
 8188:                 @newnotified = &Apache::loncommon::get_env_multiple('form.selfenroll_notify');
 8189:                 @newnotified = sort(@newnotified);
 8190:                 if ($newapproval ne $currapproval) {
 8191:                     $changes{'internal.selfenroll_approval'} = $newapproval;
 8192:                     if (!$newapproval) {
 8193:                         if ($currnotifylist ne '') {
 8194:                             $changes{'internal.selfenroll_notifylist'} = '';
 8195:                         }
 8196:                     } else {
 8197:                         my @differences =  
 8198:                             &Apache::loncommon::compare_arrays(\@currnotified,\@newnotified);
 8199:                         if (@differences > 0) {
 8200:                             if (@newnotified > 0) {
 8201:                                 $changes{'internal.selfenroll_notifylist'} = join(',',@newnotified);
 8202:                             } else {
 8203:                                 $changes{'internal.selfenroll_notifylist'} = join(',',@newnotified);
 8204:                             }
 8205:                         }
 8206:                     }
 8207:                 } else {
 8208:                     my @differences = &Apache::loncommon::compare_arrays(\@currnotified,\@newnotified);
 8209:                     if (@differences > 0) {
 8210:                         if (@newnotified > 0) {
 8211:                             $changes{'internal.selfenroll_notifylist'} = join(',',@newnotified);
 8212:                         } else {
 8213:                             $changes{'internal.selfenroll_notifylist'} = '';
 8214:                         }
 8215:                     }
 8216:                 }
 8217:             } else {
 8218:                 my $curr_val = $currsettings->{'selfenroll_'.$item};
 8219:                 my $newval = $env{'form.selfenroll_'.$item};
 8220:                 if ($item eq 'section') {
 8221:                     $newval = $env{'form.sections'};
 8222:                     if (defined($curr_groups{$newval})) {
 8223:                         $newval = $curr_val;
 8224:                         $warning{$item} = &mt('Section for self-enrolled users unchanged as the proposed section is a group').'<br />'.
 8225:                                           &mt('Group names and section names must be distinct');
 8226:                     } elsif ($newval eq 'all') {
 8227:                         $newval = $curr_val;
 8228:                         $warning{$item} = &mt('Section for self-enrolled users unchanged, as "all" is a reserved section name.');
 8229:                     }
 8230:                     if ($newval eq '') {
 8231:                         $newval = 'none';
 8232:                     }
 8233:                 }
 8234:                 if ($newval ne $curr_val) {
 8235:                     $changes{'internal.selfenroll_'.$item} = $newval;
 8236:                 }
 8237:             }
 8238:         }
 8239:         if (keys(%warning) > 0) {
 8240:             foreach my $item (@{$row}) {
 8241:                 if (exists($warning{$item})) {
 8242:                     $r->print($warning{$item}.'<br />');
 8243:                 }
 8244:             } 
 8245:         }
 8246:         if (keys(%changes) > 0) {
 8247:             my $putresult = &Apache::lonnet::put('environment',\%changes,$cdom,$cnum);
 8248:             if ($putresult eq 'ok') {
 8249:                 if ((exists($changes{'internal.selfenroll_types'})) ||
 8250:                     (exists($changes{'internal.selfenroll_start_date'}))  ||
 8251:                     (exists($changes{'internal.selfenroll_end_date'}))) {
 8252:                     my %crsinfo = &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',
 8253:                                                                 $cnum,undef,undef,'Course');
 8254:                     my $chome = &Apache::lonnet::homeserver($cnum,$cdom);
 8255:                     if (ref($crsinfo{$cid}) eq 'HASH') {
 8256:                         foreach my $item ('selfenroll_types','selfenroll_start_date','selfenroll_end_date') {
 8257:                             if (exists($changes{'internal.'.$item})) {
 8258:                                 $crsinfo{$cid}{$item} = $changes{'internal.'.$item};
 8259:                             }
 8260:                         }
 8261:                         my $crsputresult =
 8262:                             &Apache::lonnet::courseidput($cdom,\%crsinfo,
 8263:                                                          $chome,'notime');
 8264:                     }
 8265:                 }
 8266:                 $r->print(&mt('The following changes were made to self-enrollment settings:').'<ul>');
 8267:                 foreach my $item (@{$row}) {
 8268:                     my $title = $item;
 8269:                     if (ref($lt) eq 'HASH') {
 8270:                         $title = $lt->{$item};
 8271:                     }
 8272:                     if ($item eq 'enroll_dates') {
 8273:                         foreach my $type ('start','end') {
 8274:                             if (exists($changes{'internal.selfenroll_'.$type.'_date'})) {
 8275:                                 my $newdate = &Apache::lonlocal::locallocaltime($changes{'internal.selfenroll_'.$type.'_date'});
 8276:                                 $r->print('<li>'.&mt('[_1]: "[_2]" set to "[_3]".',
 8277:                                           $title,$type,$newdate).'</li>');
 8278:                             }
 8279:                         }
 8280:                     } elsif ($item eq 'access_dates') {
 8281:                         foreach my $type ('start','end') {
 8282:                             if (exists($changes{'internal.selfenroll_'.$type.'_access'})) {
 8283:                                 my $newdate = &Apache::lonlocal::locallocaltime($changes{'internal.selfenroll_'.$type.'_access'});
 8284:                                 $r->print('<li>'.&mt('[_1]: "[_2]" set to "[_3]".',
 8285:                                           $title,$type,$newdate).'</li>');
 8286:                             }
 8287:                         }
 8288:                     } elsif ($item eq 'limit') {
 8289:                         if ((exists($changes{'internal.selfenroll_limit'})) ||
 8290:                             (exists($changes{'internal.selfenroll_cap'}))) {
 8291:                             my ($newval,$newcap);
 8292:                             if ($changes{'internal.selfenroll_cap'} ne '') {
 8293:                                 $newcap = $changes{'internal.selfenroll_cap'}
 8294:                             } else {
 8295:                                 $newcap = $currsettings->{'selfenroll_cap'};
 8296:                             }
 8297:                             if ($changes{'internal.selfenroll_limit'} eq 'none') {
 8298:                                 $newval = &mt('No limit');
 8299:                             } elsif ($changes{'internal.selfenroll_limit'} eq 
 8300:                                      'allstudents') {
 8301:                                 $newval = &mt('New self-enrollment no longer allowed when total (all students) reaches [_1].',$newcap);
 8302:                             } elsif ($changes{'internal.selfenroll_limit'} eq 'selfenrolled') {
 8303:                                 $newval = &mt('New self-enrollment no longer allowed when total number of self-enrolled students reaches [_1].',$newcap);
 8304:                             } else {
 8305:                                 my $currlimit =  $currsettings->{'selfenroll_limit'};
 8306:                                 if ($currlimit eq 'allstudents') {
 8307:                                     $newval = &mt('New self-enrollment no longer allowed when total (all students) reaches [_1].',$newcap);
 8308:                                 } elsif ($changes{'internal.selfenroll_limit'} eq 'selfenrolled') {
 8309:                                     $newval =  &mt('New self-enrollment no longer allowed when total number of self-enrolled students reaches [_1].',$newcap);
 8310:                                 }
 8311:                             }
 8312:                             $r->print('<li>'.&mt('"[_1]" set to "[_2]".',$title,$newval).'</li>'."\n");
 8313:                         }
 8314:                     } elsif ($item eq 'approval') {
 8315:                         if ((exists($changes{'internal.selfenroll_approval'})) ||
 8316:                             (exists($changes{'internal.selfenroll_notifylist'}))) {
 8317:                             my %selfdescs = &Apache::lonuserutils::selfenroll_default_descs();
 8318:                             my ($newval,$newnotify);
 8319:                             if (exists($changes{'internal.selfenroll_notifylist'})) {
 8320:                                 $newnotify = $changes{'internal.selfenroll_notifylist'};
 8321:                             } else {   
 8322:                                 $newnotify = $currsettings->{'selfenroll_notifylist'};
 8323:                             }
 8324:                             if (exists($changes{'internal.selfenroll_approval'})) {
 8325:                                 if ($changes{'internal.selfenroll_approval'} !~ /^[012]$/) {
 8326:                                     $changes{'internal.selfenroll_approval'} = '0';
 8327:                                 }
 8328:                                 $newval = $selfdescs{'approval'}{$changes{'internal.selfenroll_approval'}};
 8329:                             } else {
 8330:                                 my $currapproval = $currsettings->{'selfenroll_approval'}; 
 8331:                                 if ($currapproval !~ /^[012]$/) {
 8332:                                     $currapproval = 0;
 8333:                                 }
 8334:                                 $newval = $selfdescs{'approval'}{$currapproval};
 8335:                             }
 8336:                             $r->print('<li>'.&mt('"[_1]" set to "[_2]".',$title,$newval));
 8337:                             if ($newnotify) {
 8338:                                 $r->print('<br />'.&mt('The following will be notified when an enrollment request needs approval, or has been approved: [_1].',$newnotify));
 8339:                             } else {
 8340:                                 $r->print('<br />'.&mt('No notifications sent when an enrollment request needs approval, or has been approved.'));
 8341:                             }
 8342:                             $r->print('</li>'."\n");
 8343:                         }
 8344:                     } else {
 8345:                         if (exists($changes{'internal.selfenroll_'.$item})) {
 8346:                             my $newval = $changes{'internal.selfenroll_'.$item};
 8347:                             if ($item eq 'types') {
 8348:                                 if ($newval eq '') {
 8349:                                     $newval = &mt('None');
 8350:                                 } elsif ($newval eq '*') {
 8351:                                     $newval = &mt('Any user in any domain');
 8352:                                 }
 8353:                             } elsif ($item eq 'registered') {
 8354:                                 if ($newval eq '1') {
 8355:                                     $newval = &mt('Yes');
 8356:                                 } elsif ($newval eq '0') {
 8357:                                     $newval = &mt('No');
 8358:                                 }
 8359:                             }
 8360:                             $r->print('<li>'.&mt('"[_1]" set to "[_2]".',$title,$newval).'</li>'."\n");
 8361:                         }
 8362:                     }
 8363:                 }
 8364:                 $r->print('</ul>');
 8365:                 if ($env{'course.'.$cid.'.description'} ne '') {
 8366:                     my %newenvhash;
 8367:                     foreach my $key (keys(%changes)) {
 8368:                         $newenvhash{'course.'.$cid.'.'.$key} = $changes{$key};
 8369:                     }
 8370:                     &Apache::lonnet::appenv(\%newenvhash);
 8371:                 }
 8372:             } else {
 8373:                 $r->print(&mt('An error occurred when saving changes to self-enrollment settings in this course.').'<br />'.
 8374:                           &mt('The error was: [_1].',$putresult));
 8375:             }
 8376:         } else {
 8377:             $r->print(&mt('No changes were made to the existing self-enrollment settings in this course.'));
 8378:         }
 8379:     } else {
 8380:         $r->print(&mt('No changes were made to the existing self-enrollment settings in this course.'));
 8381:     }
 8382:     my $visactions = &cat_visibility();
 8383:     my ($cathash,%cattype);
 8384:     my %domconfig = &Apache::lonnet::get_dom('configuration',['coursecategories'],$cdom);
 8385:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 8386:         $cathash = $domconfig{'coursecategories'}{'cats'};
 8387:         $cattype{'auth'} = $domconfig{'coursecategories'}{'auth'};
 8388:         $cattype{'unauth'} = $domconfig{'coursecategories'}{'unauth'};
 8389:     } else {
 8390:         $cathash = {};
 8391:         $cattype{'auth'} = 'std';
 8392:         $cattype{'unauth'} = 'std';
 8393:     }
 8394:     if (($cattype{'auth'} eq 'none') && ($cattype{'unauth'} eq 'none')) {
 8395:         $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
 8396:                   '<br />'.
 8397:                   '<br />'.$visactions->{'take'}.'<ul>'.
 8398:                   '<li>'.$visactions->{'dc_chgconf'}.'</li>'.
 8399:                   '</ul>');
 8400:     } elsif (($cattype{'auth'} !~ /^(std|domonly)$/) && ($cattype{'unauth'} !~ /^(std|domonly)$/)) {
 8401:         if ($currsettings->{'uniquecode'}) {
 8402:             $r->print('<span class="LC_info">'.$visactions->{'vis'}.'</span>');
 8403:         } else {
 8404:             $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
 8405:                   '<br />'.
 8406:                   '<br />'.$visactions->{'take'}.'<ul>'.
 8407:                   '<li>'.$visactions->{'dc_setcode'}.'</li>'.
 8408:                   '</ul><br />');
 8409:         }
 8410:     } else {
 8411:         my ($visible,$cansetvis,$vismsgs) = &visible_in_stdcat($cdom,$cnum,\%domconfig);
 8412:         if (ref($visactions) eq 'HASH') {
 8413:             if (!$visible) {
 8414:                 $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
 8415:                           '<br />');
 8416:                 if (ref($vismsgs) eq 'ARRAY') {
 8417:                     $r->print('<br />'.$visactions->{'take'}.'<ul>');
 8418:                     foreach my $item (@{$vismsgs}) {
 8419:                         $r->print('<li>'.$visactions->{$item}.'</li>');
 8420:                     }
 8421:                     $r->print('</ul>');
 8422:                 }
 8423:                 $r->print($cansetvis);
 8424:             }
 8425:         }
 8426:     } 
 8427:     return;
 8428: }
 8429: 
 8430: #---------------------------------------------- end functions for &phase_two
 8431: 
 8432: #--------------------------------- functions for &phase_two and &phase_three
 8433: 
 8434: #--------------------------end of functions for &phase_two and &phase_three
 8435: 
 8436: 1;
 8437: __END__
 8438: 
 8439: 

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