File:  [LON-CAPA] / loncom / interface / loncreateuser.pm
Revision 1.406.2.7: download - view: text, annotated - select for diffs
Sun Nov 13 15:47:04 2016 UTC (7 years, 6 months ago) by raeburn
Branches: version_2_11_X
- For 2.11
  - Backport 1.420, 1.421, 1.422

    1: # The LearningOnline Network with CAPA
    2: # Create a user
    3: #
    4: # $Id: loncreateuser.pm,v 1.406.2.7 2016/11/13 15:47:04 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,$context,$defdom);
  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:                     'srvu' => 'Search for a user and view user information and roles',
  783:                     'srva' => 'Search for a user and view access log information',
  784: 		    'usr'  => "Username",
  785:                     'dom'  => "Domain",
  786:                     'ecrp' => "Define or Edit Custom Role",
  787:                     'nr'   => "role name",
  788:                     'cre'  => "Next",
  789: 				       );
  790: 
  791:     if ($env{'form.action'} eq 'custom') {
  792:         if (&Apache::lonnet::allowed('mcr','/')) {
  793:             my $newroletext = &mt('Define new custom role:');
  794:             $r->print('<form action="/adm/createuser" method="post" name="docustom">'.
  795:                       '<input type="hidden" name="action" value="'.$env{'form.action'}.'" />'.
  796:                       '<input type="hidden" name="phase" value="selected_custom_edit" />'.
  797:                       '<h3>'.$lt{'ecrp'}.'</h3>'.
  798:                       &Apache::loncommon::start_data_table().
  799:                       &Apache::loncommon::start_data_table_row().
  800:                       '<td>');
  801:             if (keys(%existingroles) > 0) {
  802:                 $r->print('<br /><label><input type="radio" name="customroleaction" value="new" checked="checked" onclick="setCustomFields();" /><b>'.$newroletext.'</b></label>');
  803:             } else {
  804:                 $r->print('<br /><input type="hidden" name="customroleaction" value="new" /><b>'.$newroletext.'</b>');
  805:             }
  806:             $r->print('</td><td align="center">'.$lt{'nr'}.'<br /><input type="text" size="15" name="newrolename" onfocus="setCustomAction('."'new'".');" /></td>'.
  807:                       &Apache::loncommon::end_data_table_row());
  808:             if (keys(%existingroles) > 0) {
  809:                 $r->print(&Apache::loncommon::start_data_table_row().'<td><br />'.
  810:                           '<label><input type="radio" name="customroleaction" value="edit" onclick="setCustomFields();"/><b>'.
  811:                           &mt('View/Modify existing role:').'</b></label></td>'.
  812:                           '<td align="center"><br />'.
  813:                           '<select name="rolename" onchange="setCustomAction('."'edit'".');">'.
  814:                           '<option value="" selected="selected">'.
  815:                           &mt('Select'));
  816:                 foreach my $role (sort(keys(%existingroles))) {
  817:                     $r->print('<option value="'.$role.'">'.$role.'</option>');
  818:                 }
  819:                 $r->print('</select>'.
  820:                           '</td>'.
  821:                           &Apache::loncommon::end_data_table_row());
  822:             }
  823:             $r->print(&Apache::loncommon::end_data_table().'<p>'.
  824:                       '<input name="customeditor" type="submit" value="'.
  825:                       $lt{'cre'}.'" /></p>'.
  826:                       '</form>');
  827:         }
  828:     } else {
  829:         my $actiontext = $lt{'srad'};
  830:         if ($env{'form.action'} eq 'singlestudent') {
  831:             if ($crstype eq 'Community') {
  832:                 $actiontext = $lt{'srme'};
  833:             } else {
  834:                 $actiontext = $lt{'srst'};
  835:             }
  836:         } elsif ($env{'form.action'} eq 'accesslogs') {
  837:             $actiontext = $lt{'srva'};
  838:         } elsif (($env{'form.action'} eq 'singleuser') &&
  839:                  ($context eq 'domain') && (!&Apache::lonnet::allowed('mau',$defdom))) {
  840:             $actiontext = $lt{'srvu'};
  841:         }
  842:         $r->print("<h3>$actiontext</h3>");
  843:         if ($env{'form.origform'} ne 'crtusername') {
  844:             if ($response) {
  845:                $r->print("\n<div>$response</div>".
  846:                          '<br clear="all" />');
  847:             }
  848:         }
  849:         $r->print(&entry_form($defdom,$srch,$forcenewuser,$context,$response,$crstype,1));
  850:     }
  851: }
  852: 
  853: sub customrole_javascript {
  854:     my $js = <<"END";
  855: <script type="text/javascript">
  856: // <![CDATA[
  857: 
  858: function setCustomFields() {
  859:     if (document.docustom.customroleaction.length > 0) {
  860:         for (var i=0; i<document.docustom.customroleaction.length; i++) {
  861:             if (document.docustom.customroleaction[i].checked) {
  862:                 if (document.docustom.customroleaction[i].value == 'new') {
  863:                     document.docustom.rolename.selectedIndex = 0;
  864:                 } else {
  865:                     document.docustom.newrolename.value = '';
  866:                 }
  867:             }
  868:         }
  869:     }
  870:     return;
  871: }
  872: 
  873: function setCustomAction(caller) {
  874:     if (document.docustom.customroleaction.length > 0) {
  875:         for (var i=0; i<document.docustom.customroleaction.length; i++) {
  876:             if (document.docustom.customroleaction[i].value == caller) {
  877:                 document.docustom.customroleaction[i].checked = true;
  878:             }
  879:         }
  880:     }
  881:     setCustomFields();
  882:     return;
  883: }
  884: 
  885: // ]]>
  886: </script>
  887: END
  888:     return $js;
  889: }
  890: 
  891: sub entry_form {
  892:     my ($dom,$srch,$forcenewuser,$context,$responsemsg,$crstype,$fixeddom) = @_;
  893:     my ($usertype,$inexact);
  894:     if (ref($srch) eq 'HASH') {
  895:         if (($srch->{'srchin'} eq 'dom') &&
  896:             ($srch->{'srchby'} eq 'uname') &&
  897:             ($srch->{'srchtype'} eq 'exact') &&
  898:             ($srch->{'srchdomain'} ne '') &&
  899:             ($srch->{'srchterm'} ne '')) {
  900:             my (%curr_rules,%got_rules);
  901:             my ($rules,$ruleorder) =
  902:                 &Apache::lonnet::inst_userrules($srch->{'srchdomain'},'username');
  903:             $usertype = &Apache::lonuserutils::check_usertype($srch->{'srchdomain'},$srch->{'srchterm'},$rules,\%curr_rules,\%got_rules);
  904:         } else {
  905:             $inexact = 1;
  906:         }
  907:     }
  908:     my $cancreate =
  909:         &Apache::lonuserutils::can_create_user($dom,$context,$usertype);
  910:     my ($userpicker,$cansearch) = 
  911:        &Apache::loncommon::user_picker($dom,$srch,$forcenewuser,
  912:                                        'document.crtuser',$cancreate,$usertype,$context,$fixeddom);
  913:     my $srchbutton = &mt('Search');
  914:     if ($env{'form.action'} eq 'singlestudent') {
  915:         $srchbutton = &mt('Search and Enroll');
  916:     } elsif ($env{'form.action'} eq 'accesslogs') {
  917:         $srchbutton = &mt('Search');
  918:     } elsif ($cancreate && $responsemsg ne '' && $inexact) {
  919:         $srchbutton = &mt('Search or Add New User');
  920:     }
  921:     my $output;
  922:     if ($cansearch) {
  923:         $output = <<"ENDBLOCK";
  924: <form action="/adm/createuser" method="post" name="crtuser">
  925: <input type="hidden" name="action" value="$env{'form.action'}" />
  926: <input type="hidden" name="phase" value="get_user_info" />
  927: $userpicker
  928: <input name="userrole" type="button" value="$srchbutton" onclick="javascript:validateEntry(document.crtuser)" />
  929: </form>
  930: ENDBLOCK
  931:     } else {
  932:         $output = '<p>'.$userpicker.'</p>';
  933:     }
  934:     if (($env{'form.phase'} eq '') && ($env{'form.action'} ne 'accesslogs') &&
  935:         (!(($env{'form.action'} eq 'singleuser') && ($context eq 'domain') &&
  936:         (!&Apache::lonnet::allowed('mau',$env{'request.role.domain'}))))) {
  937:         my $defdom=$env{'request.role.domain'};
  938:         my $domform = &Apache::loncommon::select_dom_form($defdom,'srchdomain');
  939:         my %lt=&Apache::lonlocal::texthash(
  940:                   'enro' => 'Enroll one student',
  941:                   'enrm' => 'Enroll one member',
  942:                   'admo' => 'Add/modify a single user',
  943:                   'crea' => 'create new user if required',
  944:                   'uskn' => "username is known",
  945:                   'crnu' => 'Create a new user',
  946:                   'usr'  => 'Username',
  947:                   'dom'  => 'in domain',
  948:                   'enrl' => 'Enroll',
  949:                   'cram'  => 'Create/Modify user',
  950:         );
  951:         my $sellink=&Apache::loncommon::selectstudent_link('crtusername','srchterm','srchdomain');
  952:         my ($title,$buttontext,$showresponse);
  953:         if ($env{'form.action'} eq 'singlestudent') {
  954:             if ($crstype eq 'Community') {
  955:                 $title = $lt{'enrm'};
  956:             } else {
  957:                 $title = $lt{'enro'};
  958:             }
  959:             $buttontext = $lt{'enrl'};
  960:         } else {
  961:             $title = $lt{'admo'};
  962:             $buttontext = $lt{'cram'};
  963:         }
  964:         if ($cancreate) {
  965:             $title .= ' <span class="LC_cusr_subheading">('.$lt{'crea'}.')</span>';
  966:         } else {
  967:             $title .= ' <span class="LC_cusr_subheading">('.$lt{'uskn'}.')</span>';
  968:         }
  969:         if ($env{'form.origform'} eq 'crtusername') {
  970:             $showresponse = $responsemsg;
  971:         }
  972:         $output .= <<"ENDDOCUMENT";
  973: <br />
  974: <form action="/adm/createuser" method="post" name="crtusername">
  975: <input type="hidden" name="action" value="$env{'form.action'}" />
  976: <input type="hidden" name="phase" value="createnewuser" />
  977: <input type="hidden" name="srchtype" value="exact" />
  978: <input type="hidden" name="srchby" value="uname" />
  979: <input type="hidden" name="srchin" value="dom" />
  980: <input type="hidden" name="forcenewuser" value="1" />
  981: <input type="hidden" name="origform" value="crtusername" />
  982: <h3>$title</h3>
  983: $showresponse
  984: <table>
  985:  <tr>
  986:   <td>$lt{'usr'}:</td>
  987:   <td><input type="text" size="15" name="srchterm" /></td>
  988:   <td>&nbsp;$lt{'dom'}:</td><td>$domform</td>
  989:   <td>&nbsp;$sellink&nbsp;</td>
  990:   <td>&nbsp;<input name="userrole" type="submit" value="$buttontext" /></td>
  991:  </tr>
  992: </table>
  993: </form>
  994: ENDDOCUMENT
  995:     }
  996:     return $output;
  997: }
  998: 
  999: sub user_modification_js {
 1000:     my ($pjump_def,$dc_setcourse_code,$nondc_setsection_code,$groupslist)=@_;
 1001:     
 1002:     return <<END;
 1003: <script type="text/javascript" language="Javascript">
 1004: // <![CDATA[
 1005: 
 1006:     $pjump_def
 1007:     $dc_setcourse_code
 1008: 
 1009:     function dateset() {
 1010:         eval("document.cu."+document.cu.pres_marker.value+
 1011:             ".value=document.cu.pres_value.value");
 1012:         modalWindow.close();
 1013:     }
 1014: 
 1015:     $nondc_setsection_code
 1016: // ]]>
 1017: </script>
 1018: END
 1019: }
 1020: 
 1021: # =================================================================== Phase two
 1022: sub print_user_selection_page {
 1023:     my ($r,$response,$srch,$srch_results,$srcharray,$context,$opener_elements,$crstype,$brcrum) = @_;
 1024:     my @fields = ('username','domain','lastname','firstname','permanentemail');
 1025:     my $sortby = $env{'form.sortby'};
 1026: 
 1027:     if (!grep(/^\Q$sortby\E$/,@fields)) {
 1028:         $sortby = 'lastname';
 1029:     }
 1030: 
 1031:     my ($jsback,$elements) = &crumb_utilities();
 1032: 
 1033:     my $jscript = (<<ENDSCRIPT);
 1034: <script type="text/javascript">
 1035: // <![CDATA[
 1036: function pickuser(uname,udom) {
 1037:     document.usersrchform.seluname.value=uname;
 1038:     document.usersrchform.seludom.value=udom;
 1039:     document.usersrchform.phase.value="userpicked";
 1040:     document.usersrchform.submit();
 1041: }
 1042: 
 1043: $jsback
 1044: // ]]>
 1045: </script>
 1046: ENDSCRIPT
 1047: 
 1048:     my %lt=&Apache::lonlocal::texthash(
 1049:                                        'usrch'          => "User Search to add/modify roles",
 1050:                                        'stusrch'        => "User Search to enroll student",
 1051:                                        'memsrch'        => "User Search to enroll member",
 1052:                                        'srcva'          => "Search for a user and view access log information",
 1053:                                        'usrvu'          => "User Search to view user roles",
 1054:                                        'usel'           => "Select a user to add/modify roles",
 1055:                                        'suvr'           => "Select a user to view roles",
 1056:                                        'stusel'         => "Select a user to enroll as a student",
 1057:                                        'memsel'         => "Select a user to enroll as a member",
 1058:                                        'vacsel'         => "Select a user to view access log",
 1059:                                        'username'       => "username",
 1060:                                        'domain'         => "domain",
 1061:                                        'lastname'       => "last name",
 1062:                                        'firstname'      => "first name",
 1063:                                        'permanentemail' => "permanent e-mail",
 1064:                                       );
 1065:     if ($context eq 'requestcrs') {
 1066:         $r->print('<div>');
 1067:     } else {
 1068:         my %breadcrumb_text = &singleuser_breadcrumb($crstype,$context,$srch->{'srchdomain'});
 1069:         my $helpitem;
 1070:         if ($env{'form.action'} eq 'singleuser') {
 1071:             $helpitem = 'Course_Change_Privileges';
 1072:         } elsif ($env{'form.action'} eq 'singlestudent') {
 1073:             $helpitem = 'Course_Add_Student';
 1074:         }
 1075:         push (@{$brcrum},
 1076:                   {href => "javascript:backPage(document.usersrchform,'','')",
 1077:                    text => $breadcrumb_text{'search'},
 1078:                    faq  => 282,
 1079:                    bug  => 'Instructor Interface',},
 1080:                   {href => "javascript:backPage(document.usersrchform,'get_user_info','select')",
 1081:                    text => $breadcrumb_text{'userpicked'},
 1082:                    faq  => 282,
 1083:                    bug  => 'Instructor Interface',
 1084:                    help => $helpitem}
 1085:                   );
 1086:         $r->print(&Apache::loncommon::start_page('User Management',$jscript,{bread_crumbs => $brcrum}));
 1087:         if ($env{'form.action'} eq 'singleuser') {
 1088:             my $readonly;
 1089:             if (($context eq 'domain') && (!&Apache::lonnet::allowed('mau',$srch->{'srchdomain'}))) {
 1090:                 $readonly = 1;
 1091:                 $r->print("<b>$lt{'usrvu'}</b><br />");
 1092:             } else {
 1093:                 $r->print("<b>$lt{'usrch'}</b><br />");
 1094:             }
 1095:             $r->print(&entry_form($srch->{'srchdomain'},$srch,undef,$context,undef,$crstype));
 1096:             if ($readonly) {
 1097:                 $r->print('<h3>'.$lt{'suvr'}.'</h3>');
 1098:             } else {
 1099:                 $r->print('<h3>'.$lt{'usel'}.'</h3>');
 1100:             }
 1101:         } elsif ($env{'form.action'} eq 'singlestudent') {
 1102:             $r->print($jscript."<b>");
 1103:             if ($crstype eq 'Community') {
 1104:                 $r->print($lt{'memsrch'});
 1105:             } else {
 1106:                 $r->print($lt{'stusrch'});
 1107:             }
 1108:             $r->print("</b><br />");
 1109:             $r->print(&entry_form($srch->{'srchdomain'},$srch,undef,$context,undef,$crstype));
 1110:             $r->print('</form><h3>');
 1111:             if ($crstype eq 'Community') {
 1112:                 $r->print($lt{'memsel'});
 1113:             } else {
 1114:                 $r->print($lt{'stusel'});
 1115:             }
 1116:             $r->print('</h3>');
 1117:         } elsif ($env{'form.action'} eq 'accesslogs') {
 1118:             $r->print("<b>$lt{'srcva'}</b><br />");
 1119:             $r->print(&entry_form($srch->{'srchdomain'},$srch,undef,'accesslogs',undef,undef,1));
 1120:             $r->print('<h3>'.$lt{'vacsel'}.'</h3>');
 1121:         }
 1122:     }
 1123:     $r->print('<form name="usersrchform" method="post" action="">'.
 1124:               &Apache::loncommon::start_data_table()."\n".
 1125:               &Apache::loncommon::start_data_table_header_row()."\n".
 1126:               ' <th> </th>'."\n");
 1127:     foreach my $field (@fields) {
 1128:         $r->print(' <th><a href="javascript:document.usersrchform.sortby.value='.
 1129:                   "'".$field."'".';document.usersrchform.submit();">'.
 1130:                   $lt{$field}.'</a></th>'."\n");
 1131:     }
 1132:     $r->print(&Apache::loncommon::end_data_table_header_row());
 1133: 
 1134:     my @sorted_users = sort {
 1135:         lc($srch_results->{$a}->{$sortby})   cmp lc($srch_results->{$b}->{$sortby})
 1136:             ||
 1137:         lc($srch_results->{$a}->{lastname})  cmp lc($srch_results->{$b}->{lastname})
 1138:             ||
 1139:         lc($srch_results->{$a}->{firstname}) cmp lc($srch_results->{$b}->{firstname})
 1140: 	    ||
 1141: 	lc($a) cmp lc($b)
 1142:         } (keys(%$srch_results));
 1143: 
 1144:     foreach my $user (@sorted_users) {
 1145:         my ($uname,$udom) = split(/:/,$user);
 1146:         my $onclick;
 1147:         if ($context eq 'requestcrs') {
 1148:             $onclick =
 1149:                 'onclick="javascript:gochoose('."'$uname','$udom',".
 1150:                                                "'$srch_results->{$user}->{firstname}',".
 1151:                                                "'$srch_results->{$user}->{lastname}',".
 1152:                                                "'$srch_results->{$user}->{permanentemail}'".');"';
 1153:         } else {
 1154:             $onclick =
 1155:                 ' onclick="javascript:pickuser('."'".$uname."'".','."'".$udom."'".');"';
 1156:         }
 1157:         $r->print(&Apache::loncommon::start_data_table_row().
 1158:                   '<td><input type="button" name="seluser" value="'.&mt('Select').'" '.
 1159:                   $onclick.' /></td>'.
 1160:                   '<td><tt>'.$uname.'</tt></td>'.
 1161:                   '<td><tt>'.$udom.'</tt></td>');
 1162:         foreach my $field ('lastname','firstname','permanentemail') {
 1163:             $r->print('<td>'.$srch_results->{$user}->{$field}.'</td>');
 1164:         }
 1165:         $r->print(&Apache::loncommon::end_data_table_row());
 1166:     }
 1167:     $r->print(&Apache::loncommon::end_data_table().'<br /><br />');
 1168:     if (ref($srcharray) eq 'ARRAY') {
 1169:         foreach my $item (@{$srcharray}) {
 1170:             $r->print('<input type="hidden" name="'.$item.'" value="'.$env{'form.'.$item}.'" />'."\n");
 1171:         }
 1172:     }
 1173:     $r->print(' <input type="hidden" name="sortby" value="'.$sortby.'" />'."\n".
 1174:               ' <input type="hidden" name="seluname" value="" />'."\n".
 1175:               ' <input type="hidden" name="seludom" value="" />'."\n".
 1176:               ' <input type="hidden" name="currstate" value="select" />'."\n".
 1177:               ' <input type="hidden" name="phase" value="get_user_info" />'."\n".
 1178:               ' <input type="hidden" name="action" value="'.$env{'form.action'}.'" />'."\n");
 1179:     if ($context eq 'requestcrs') {
 1180:         $r->print($opener_elements.'</form></div>');
 1181:     } else {
 1182:         $r->print($response.'</form>');
 1183:     }
 1184: }
 1185: 
 1186: sub print_user_query_page {
 1187:     my ($r,$caller,$brcrum) = @_;
 1188: # FIXME - this is for a network-wide name search (similar to catalog search)
 1189: # To use frames with similar behavior to catalog/portfolio search.
 1190: # To be implemented. 
 1191:     return;
 1192: }
 1193: 
 1194: sub print_user_modification_page {
 1195:     my ($r,$ccuname,$ccdomain,$srch,$response,$context,$permission,$crstype,
 1196:         $brcrum,$showcredits) = @_;
 1197:     if (($ccuname eq '') || ($ccdomain eq '')) {
 1198:         my $usermsg = &mt('No username and/or domain provided.');
 1199:         $env{'form.phase'} = '';
 1200: 	&print_username_entry_form($r,$context,$usermsg,'','',$crstype,$brcrum);
 1201:         return;
 1202:     }
 1203:     my ($form,$formname);
 1204:     if ($env{'form.action'} eq 'singlestudent') {
 1205:         $form = 'document.enrollstudent';
 1206:         $formname = 'enrollstudent';
 1207:     } else {
 1208:         $form = 'document.cu';
 1209:         $formname = 'cu';
 1210:     }
 1211:     my %abv_auth = &auth_abbrev();
 1212:     my (%rulematch,%inst_results,$newuser,%alerts,%curr_rules,%got_rules);
 1213:     my $uhome=&Apache::lonnet::homeserver($ccuname,$ccdomain);
 1214:     if ($uhome eq 'no_host') {
 1215:         my $usertype;
 1216:         my ($rules,$ruleorder) =
 1217:             &Apache::lonnet::inst_userrules($ccdomain,'username');
 1218:             $usertype =
 1219:                 &Apache::lonuserutils::check_usertype($ccdomain,$ccuname,$rules,
 1220:                                                       \%curr_rules,\%got_rules);
 1221:         my $cancreate =
 1222:             &Apache::lonuserutils::can_create_user($ccdomain,$context,
 1223:                                                    $usertype);
 1224:         if (!$cancreate) {
 1225:             my $helplink = 'javascript:helpMenu('."'display'".')';
 1226:             my %usertypetext = (
 1227:                 official   => 'institutional',
 1228:                 unofficial => 'non-institutional',
 1229:             );
 1230:             my $response;
 1231:             if ($env{'form.origform'} eq 'crtusername') {
 1232:                 $response = '<span class="LC_warning">'.
 1233:                             &mt('No match found for the username [_1] in LON-CAPA domain: [_2]',
 1234:                                 '<b>'.$ccuname.'</b>',$ccdomain).
 1235:                             '</span><br />';
 1236:             }
 1237:             $response .= '<p class="LC_warning">'
 1238:                         .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
 1239:                         .' ';
 1240:             if ($context eq 'domain') {
 1241:                 $response .= &mt('Please contact a [_1] for assistance.',
 1242:                                  &Apache::lonnet::plaintext('dc'));
 1243:             } else {
 1244:                 $response .= &mt('Please contact the [_1]helpdesk[_2] for assistance.'
 1245:                                 ,'<a href="'.$helplink.'">','</a>');
 1246:             }
 1247:             $response .= '</p><br />';
 1248:             $env{'form.phase'} = '';
 1249:             &print_username_entry_form($r,$context,$response,undef,undef,$crstype,$brcrum);
 1250:             return;
 1251:         }
 1252:         $newuser = 1;
 1253:         my $checkhash;
 1254:         my $checks = { 'username' => 1 };
 1255:         $checkhash->{$ccuname.':'.$ccdomain} = { 'newuser' => $newuser };
 1256:         &Apache::loncommon::user_rule_check($checkhash,$checks,
 1257:             \%alerts,\%rulematch,\%inst_results,\%curr_rules,\%got_rules);
 1258:         if (ref($alerts{'username'}) eq 'HASH') {
 1259:             if (ref($alerts{'username'}{$ccdomain}) eq 'HASH') {
 1260:                 my $domdesc =
 1261:                     &Apache::lonnet::domain($ccdomain,'description');
 1262:                 if ($alerts{'username'}{$ccdomain}{$ccuname}) {
 1263:                     my $userchkmsg;
 1264:                     if (ref($curr_rules{$ccdomain}) eq 'HASH') {  
 1265:                         $userchkmsg = 
 1266:                             &Apache::loncommon::instrule_disallow_msg('username',
 1267:                                                                  $domdesc,1).
 1268:                         &Apache::loncommon::user_rule_formats($ccdomain,
 1269:                             $domdesc,$curr_rules{$ccdomain}{'username'},
 1270:                             'username');
 1271:                     }
 1272:                     $env{'form.phase'} = '';
 1273:                     &print_username_entry_form($r,$context,$userchkmsg,undef,undef,$crstype,$brcrum);
 1274:                     return;
 1275:                 }
 1276:             }
 1277:         }
 1278:     } else {
 1279:         $newuser = 0;
 1280:     }
 1281:     if ($response) {
 1282:         $response = '<br />'.$response;
 1283:     }
 1284: 
 1285:     my $pjump_def = &Apache::lonhtmlcommon::pjump_javascript_definition();
 1286:     my $dc_setcourse_code = '';
 1287:     my $nondc_setsection_code = '';                                        
 1288:     my %loaditem;
 1289: 
 1290:     my $groupslist = &Apache::lonuserutils::get_groupslist();
 1291: 
 1292:     my $js = &validation_javascript($context,$ccdomain,$pjump_def,$crstype,
 1293:                                $groupslist,$newuser,$formname,\%loaditem);
 1294:     my %breadcrumb_text = &singleuser_breadcrumb($crstype,$context,$ccdomain);
 1295:     my $helpitem = 'Course_Change_Privileges';
 1296:     if ($env{'form.action'} eq 'singlestudent') {
 1297:         $helpitem = 'Course_Add_Student';
 1298:     }
 1299:     push (@{$brcrum},
 1300:         {href => "javascript:backPage($form)",
 1301:          text => $breadcrumb_text{'search'},
 1302:          faq  => 282,
 1303:          bug  => 'Instructor Interface',});
 1304:     if ($env{'form.phase'} eq 'userpicked') {
 1305:        push(@{$brcrum},
 1306:               {href => "javascript:backPage($form,'get_user_info','select')",
 1307:                text => $breadcrumb_text{'userpicked'},
 1308:                faq  => 282,
 1309:                bug  => 'Instructor Interface',});
 1310:     }
 1311:     push(@{$brcrum},
 1312:             {href => "javascript:backPage($form,'$env{'form.phase'}','modify')",
 1313:              text => $breadcrumb_text{'modify'},
 1314:              faq  => 282,
 1315:              bug  => 'Instructor Interface',
 1316:              help => $helpitem});
 1317:     my $args = {'add_entries'           => \%loaditem,
 1318:                 'bread_crumbs'          => $brcrum,
 1319:                 'bread_crumbs_component' => 'User Management'};
 1320:     if ($env{'form.popup'}) {
 1321:         $args->{'no_nav_bar'} = 1;
 1322:     }
 1323:     my $start_page =
 1324:         &Apache::loncommon::start_page('User Management',$js,$args);
 1325: 
 1326:     my $forminfo =<<"ENDFORMINFO";
 1327: <form action="/adm/createuser" method="post" name="$formname">
 1328: <input type="hidden" name="phase" value="update_user_data" />
 1329: <input type="hidden" name="ccuname" value="$ccuname" />
 1330: <input type="hidden" name="ccdomain" value="$ccdomain" />
 1331: <input type="hidden" name="pres_value"  value="" />
 1332: <input type="hidden" name="pres_type"   value="" />
 1333: <input type="hidden" name="pres_marker" value="" />
 1334: ENDFORMINFO
 1335:     my (%inccourses,$roledom,$defaultcredits);
 1336:     if ($context eq 'course') {
 1337:         $inccourses{$env{'request.course.id'}}=1;
 1338:         $roledom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 1339:         if ($showcredits) {
 1340:             $defaultcredits = &Apache::lonuserutils::get_defaultcredits();
 1341:         }
 1342:     } elsif ($context eq 'author') {
 1343:         $roledom = $env{'request.role.domain'};
 1344:     } elsif ($context eq 'domain') {
 1345:         foreach my $key (keys(%env)) {
 1346:             $roledom = $env{'request.role.domain'};
 1347:             if ($key=~/^user\.priv\.cm\.\/($roledom)\/($match_username)/) {
 1348:                 $inccourses{$1.'_'.$2}=1;
 1349:             }
 1350:         }
 1351:     } else {
 1352:         foreach my $key (keys(%env)) {
 1353: 	    if ($key=~/^user\.priv\.cm\.\/($match_domain)\/($match_username)/) {
 1354: 	        $inccourses{$1.'_'.$2}=1;
 1355:             }
 1356:         }
 1357:     }
 1358:     my $title = '';
 1359:     if ($newuser) {
 1360:         my ($portfolioform,$domroleform,$adhocroleform);
 1361:         if ((&Apache::lonnet::allowed('mpq',$env{'request.role.domain'})) ||
 1362:             (&Apache::lonnet::allowed('mut',$env{'request.role.domain'}))) {
 1363:             # Current user has quota or user tools modification privileges
 1364:             $portfolioform = '<br />'.&user_quotas($ccuname,$ccdomain);
 1365:         }
 1366:         if ((&Apache::lonnet::allowed('cau',$env{'request.role.domain'})) &&
 1367:             ($ccdomain eq $env{'request.role.domain'})) {
 1368:             $domroleform = '<br />'.&domainrole_req($ccuname,$ccdomain);
 1369:         }
 1370:         if (&Apache::lonnet::allowed('cdh',$env{'request.role.domain'})) {
 1371:             $adhocroleform = &domadhocroles($ccuname,$ccdomain);
 1372:             if ($adhocroleform) {
 1373:                 $adhocroleform = '<br />'.$adhocroleform;
 1374:             }
 1375:         }
 1376:         &initialize_authen_forms($ccdomain,$formname);
 1377:         my %lt=&Apache::lonlocal::texthash(
 1378:                 'lg'             => 'Login Data',
 1379:                 'hs'             => "Home Server",
 1380:         );
 1381: 	$r->print(<<ENDTITLE);
 1382: $start_page
 1383: $response
 1384: $forminfo
 1385: <script type="text/javascript" language="Javascript">
 1386: // <![CDATA[
 1387: $loginscript
 1388: // ]]>
 1389: </script>
 1390: <input type='hidden' name='makeuser' value='1' />
 1391: ENDTITLE
 1392:         if ($env{'form.action'} eq 'singlestudent') {
 1393:             if ($crstype eq 'Community') {
 1394:                 $title = &mt('Create New User [_1] in domain [_2] as a member',
 1395:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1396:             } else {
 1397:                 $title = &mt('Create New User [_1] in domain [_2] as a student',
 1398:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1399:             }
 1400:         } else {
 1401:                 $title = &mt('Create New User [_1] in domain [_2]',
 1402:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1403:         }
 1404:         $r->print('<h2>'.$title.'</h2>'."\n");
 1405:         $r->print('<div class="LC_left_float">');
 1406:         $r->print(&personal_data_display($ccuname,$ccdomain,$newuser,$context,
 1407:                                          $inst_results{$ccuname.':'.$ccdomain}));
 1408:         # Option to disable student/employee ID conflict checking not offerred for new users.
 1409:         my ($home_server_pick,$numlib) = 
 1410:             &Apache::loncommon::home_server_form_item($ccdomain,'hserver',
 1411:                                                       'default','hide');
 1412:         if ($numlib > 1) {
 1413:             $r->print("
 1414: <br />
 1415: $lt{'hs'}: $home_server_pick
 1416: <br />");
 1417:         } else {
 1418:             $r->print($home_server_pick);
 1419:         }
 1420:         if (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) {
 1421:             $r->print('<br /><h3>'.
 1422:                       &mt('User Can Request Creation of Courses/Communities in this Domain?').'</h3>'.
 1423:                       &Apache::loncommon::start_data_table().
 1424:                       &build_tools_display($ccuname,$ccdomain,
 1425:                                            'requestcourses').
 1426:                       &Apache::loncommon::end_data_table());
 1427:         }
 1428:         $r->print('</div>'."\n".'<div class="LC_left_float"><h3>'.
 1429:                   $lt{'lg'}.'</h3>');
 1430:         my ($fixedauth,$varauth,$authmsg); 
 1431:         if (ref($rulematch{$ccuname.':'.$ccdomain}) eq 'HASH') {
 1432:             my $matchedrule = $rulematch{$ccuname.':'.$ccdomain}{'username'};
 1433:             my ($rules,$ruleorder) = 
 1434:                 &Apache::lonnet::inst_userrules($ccdomain,'username');
 1435:             if (ref($rules) eq 'HASH') {
 1436:                 if (ref($rules->{$matchedrule}) eq 'HASH') {
 1437:                     my $authtype = $rules->{$matchedrule}{'authtype'};
 1438:                     if ($authtype !~ /^(krb4|krb5|int|fsys|loc)$/) {
 1439:                         $r->print(&Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc));
 1440:                     } else { 
 1441:                         my $authparm = $rules->{$matchedrule}{'authparm'};
 1442:                         $authmsg = $rules->{$matchedrule}{'authmsg'};
 1443:                         if ($authtype =~ /^krb(4|5)$/) {
 1444:                             my $ver = $1;
 1445:                             if ($authparm ne '') {
 1446:                                 $fixedauth = <<"KERB"; 
 1447: <input type="hidden" name="login" value="krb" />
 1448: <input type="hidden" name="krbver" value="$ver" />
 1449: <input type="hidden" name="krbarg" value="$authparm" />
 1450: KERB
 1451:                             }
 1452:                         } else {
 1453:                             $fixedauth = 
 1454: '<input type="hidden" name="login" value="'.$authtype.'" />'."\n";
 1455:                             if ($rules->{$matchedrule}{'authparmfixed'}) {
 1456:                                 $fixedauth .=    
 1457: '<input type="hidden" name="'.$authtype.'arg" value="'.$authparm.'" />'."\n";
 1458:                             } else {
 1459:                                 if ($authtype eq 'int') {
 1460:                                     $varauth = '<br />'.
 1461: &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>';
 1462:                                 } elsif ($authtype eq 'loc') {
 1463:                                     $varauth = '<br />'.
 1464: &mt('[_1] Local Authentication with argument [_2]','','<input type="text" name="'.$authtype.'arg" value="" />')."\n";
 1465:                                 } else {
 1466:                                     $varauth =
 1467: '<input type="text" name="'.$authtype.'arg" value="" />'."\n";
 1468:                                 }
 1469:                             }
 1470:                         }
 1471:                     }
 1472:                 } else {
 1473:                     $r->print(&Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc));
 1474:                 }
 1475:             }
 1476:             if ($authmsg) {
 1477:                 $r->print(<<ENDAUTH);
 1478: $fixedauth
 1479: $authmsg
 1480: $varauth
 1481: ENDAUTH
 1482:             }
 1483:         } else {
 1484:             $r->print(&Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc)); 
 1485:         }
 1486:         $r->print($portfolioform.$domroleform.$adhocroleform);
 1487:         if ($env{'form.action'} eq 'singlestudent') {
 1488:             $r->print(&date_sections_select($context,$newuser,$formname,
 1489:                                             $permission,$crstype,$ccuname,
 1490:                                             $ccdomain,$showcredits));
 1491:         }
 1492:         $r->print('</div><div class="LC_clear_float_footer"></div>');
 1493:     } else { # user already exists
 1494: 	$r->print($start_page.$forminfo);
 1495:         if ($env{'form.action'} eq 'singlestudent') {
 1496:             if ($crstype eq 'Community') {
 1497:                 $title = &mt('Enroll one member: [_1] in domain [_2]',
 1498:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1499:             } else {
 1500:                 $title = &mt('Enroll one student: [_1] in domain [_2]',
 1501:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1502:             }
 1503:         } else {
 1504:             if ($permission->{'cusr'}) {
 1505:                 $title = &mt('Modify existing user: [_1] in domain [_2]',
 1506:                              '"'.$ccuname.'"','"'.$ccdomain.'"');
 1507:             } else {
 1508:                 $title = &mt('Existing user: [_1] in domain [_2]',
 1509:                              '"'.$ccuname.'"','"'.$ccdomain.'"');
 1510:             }
 1511:         }
 1512:         $r->print('<h2>'.$title.'</h2>'."\n");
 1513:         $r->print('<div class="LC_left_float">');
 1514:         $r->print(&personal_data_display($ccuname,$ccdomain,$newuser,$context,
 1515:                                          $inst_results{$ccuname.':'.$ccdomain}));
 1516:         if ((&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) ||
 1517:             (&Apache::lonnet::allowed('udp',$env{'request.role.domain'}))) {
 1518:             $r->print('<br /><h3>'.&mt('User Can Request Creation of Courses/Communities in this Domain?').'</h3>'.
 1519:                       &Apache::loncommon::start_data_table());
 1520:             if ($env{'request.role.domain'} eq $ccdomain) {
 1521:                 $r->print(&build_tools_display($ccuname,$ccdomain,'requestcourses'));
 1522:             } else {
 1523:                 $r->print(&coursereq_externaluser($ccuname,$ccdomain,
 1524:                                                   $env{'request.role.domain'}));
 1525:             }
 1526:             $r->print(&Apache::loncommon::end_data_table());
 1527:         }
 1528:         $r->print('</div>');
 1529:         my @order = ('auth','quota','tools','requestauthor','adhocroles');
 1530:         my %user_text;
 1531:         my ($isadv,$isauthor) = 
 1532:             &Apache::lonnet::is_advanced_user($ccdomain,$ccuname);
 1533:         if ((!$isauthor) && 
 1534:             ((&Apache::lonnet::allowed('cau',$env{'request.role.domain'})) ||
 1535:              (&Apache::lonnet::allowed('udp',$env{'request.role.domain'}))) &&
 1536:              ($env{'request.role.domain'} eq $ccdomain)) {
 1537:             $user_text{'requestauthor'} = &domainrole_req($ccuname,$ccdomain);
 1538:         }
 1539:         if ((&Apache::lonnet::allowed('cdh',$env{'request.role.domain'})) ||
 1540:             (&Apache::lonnet::allowed('udp',$env{'request.role.domain'}))) {
 1541:             $user_text{'adhocroles'} = &domadhocroles($ccuname,$ccdomain);
 1542:         }
 1543:         $user_text{'auth'} =  &user_authentication($ccuname,$ccdomain,$formname);
 1544:         if ((&Apache::lonnet::allowed('mpq',$ccdomain)) ||
 1545:             (&Apache::lonnet::allowed('mut',$ccdomain)) ||
 1546:             (&Apache::lonnet::allowed('udp',$ccdomain))) {
 1547:             # Current user has quota modification privileges
 1548:             $user_text{'quota'} = &user_quotas($ccuname,$ccdomain);
 1549:         }
 1550:         if (!&Apache::lonnet::allowed('mpq',$ccdomain)) {
 1551:             if (&Apache::lonnet::allowed('mpq',$env{'request.role.domain'})) {
 1552:                 my %lt=&Apache::lonlocal::texthash(
 1553:                     'dska'  => "Disk quotas for user's portfolio and Authoring Space",
 1554:                     'youd'  => "You do not have privileges to modify the portfolio and/or Authoring Space quotas for this user.",
 1555:                     'ichr'  => "If a change is required, contact a domain coordinator for the domain",
 1556:                 );
 1557:                 $user_text{'quota'} = <<ENDNOPORTPRIV;
 1558: <h3>$lt{'dska'}</h3>
 1559: $lt{'youd'} $lt{'ichr'}: $ccdomain
 1560: ENDNOPORTPRIV
 1561:             }
 1562:         }
 1563:         if (!&Apache::lonnet::allowed('mut',$ccdomain)) {
 1564:             if (&Apache::lonnet::allowed('mut',$env{'request.role.domain'})) {
 1565:                 my %lt=&Apache::lonlocal::texthash(
 1566:                     'utav'  => "User Tools Availability",
 1567:                     'yodo'  => "You do not have privileges to modify Portfolio, Blog, WebDAV, or Personal Information Page settings for this user.",
 1568:                     'ifch'  => "If a change is required, contact a domain coordinator for the domain",
 1569:                 );
 1570:                 $user_text{'tools'} = <<ENDNOTOOLSPRIV;
 1571: <h3>$lt{'utav'}</h3>
 1572: $lt{'yodo'} $lt{'ifch'}: $ccdomain
 1573: ENDNOTOOLSPRIV
 1574:             }
 1575:         }
 1576:         my $gotdiv = 0; 
 1577:         foreach my $item (@order) {
 1578:             if ($user_text{$item} ne '') {
 1579:                 unless ($gotdiv) {
 1580:                     $r->print('<div class="LC_left_float">');
 1581:                     $gotdiv = 1;
 1582:                 }
 1583:                 $r->print('<br />'.$user_text{$item});
 1584:             }
 1585:         }
 1586:         if ($env{'form.action'} eq 'singlestudent') {
 1587:             unless ($gotdiv) {
 1588:                 $r->print('<div class="LC_left_float">');
 1589:             }
 1590:             my $credits;
 1591:             if ($showcredits) {
 1592:                 $credits = &get_user_credits($ccuname,$ccdomain,$defaultcredits);
 1593:                 if ($credits eq '') {
 1594:                     $credits = $defaultcredits;
 1595:                 }
 1596:             }
 1597:             $r->print(&date_sections_select($context,$newuser,$formname,
 1598:                                             $permission,$crstype,$ccuname,
 1599:                                             $ccdomain,$showcredits));
 1600:         }
 1601:         if ($gotdiv) {
 1602:             $r->print('</div><div class="LC_clear_float_footer"></div>');
 1603:         }
 1604:         my $statuses;
 1605:         if (($context eq 'domain') && (&Apache::lonnet::allowed('udp',$ccdomain)) &&
 1606:             (!&Apache::lonnet::allowed('mau',$ccdomain))) {
 1607:             $statuses = ['active'];
 1608:         } elsif (($context eq 'course') && ((&Apache::lonnet::allowed('vcl',$env{'request.course.id'})) ||
 1609:                  ($env{'request.course.sec'} &&
 1610:                   &Apache::lonnet::allowed('vcl',$env{'request.course.id'}.'/'.$env{'request.course.sec'})))) {
 1611:             $statuses = ['active'];
 1612:         }
 1613:         if ($env{'form.action'} ne 'singlestudent') {
 1614:             &display_existing_roles($r,$ccuname,$ccdomain,\%inccourses,$context,
 1615:                                     $roledom,$crstype,$showcredits,$statuses);
 1616:         }
 1617:     } ## End of new user/old user logic
 1618:     if ($env{'form.action'} eq 'singlestudent') {
 1619:         my $btntxt;
 1620:         if ($crstype eq 'Community') {
 1621:             $btntxt = &mt('Enroll Member');
 1622:         } else {
 1623:             $btntxt = &mt('Enroll Student');
 1624:         }
 1625:         $r->print('<br /><input type="button" value="'.$btntxt.'" onclick="setSections(this.form)" />'."\n");
 1626:     } elsif ($permission->{'cusr'}) {
 1627:         $r->print('<div class="LC_left_float">'.
 1628:                   '<fieldset><legend>'.&mt('Add Roles').'</legend>');
 1629:         my $addrolesdisplay = 0;
 1630:         if ($context eq 'domain' || $context eq 'author') {
 1631:             $addrolesdisplay = &new_coauthor_roles($r,$ccuname,$ccdomain);
 1632:         }
 1633:         if ($context eq 'domain') {
 1634:             my $add_domainroles = &new_domain_roles($r,$ccdomain);
 1635:             if (!$addrolesdisplay) {
 1636:                 $addrolesdisplay = $add_domainroles;
 1637:             }
 1638:             $r->print(&course_level_dc($env{'request.role.domain'},$showcredits));
 1639:             $r->print('</fieldset></div><div class="LC_clear_float_footer"></div>'.
 1640:                       '<br /><input type="button" value="'.&mt('Save').'" onclick="setCourse()" />'."\n");
 1641:         } elsif ($context eq 'author') {
 1642:             if ($addrolesdisplay) {
 1643:                 $r->print('</fieldset></div><div class="LC_clear_float_footer"></div>'.
 1644:                           '<br /><input type="button" value="'.&mt('Save').'"');
 1645:                 if ($newuser) {
 1646:                     $r->print(' onclick="auth_check()" \>'."\n");
 1647:                 } else {
 1648:                     $r->print('onclick="this.form.submit()" \>'."\n");
 1649:                 }
 1650:             } else {
 1651:                 $r->print('</fieldset></div>'.
 1652:                           '<div class="LC_clear_float_footer"></div>'.
 1653:                           '<br /><a href="javascript:backPage(document.cu)">'.
 1654:                           &mt('Back to previous page').'</a>');
 1655:             }
 1656:         } else {
 1657:             $r->print(&course_level_table(\%inccourses,$showcredits,$defaultcredits));
 1658:             $r->print('</fieldset></div><div class="LC_clear_float_footer"></div>'.
 1659:                       '<br /><input type="button" value="'.&mt('Save').'" onclick="setSections(this.form)" />'."\n");
 1660:         }
 1661:     }
 1662:     $r->print(&Apache::lonhtmlcommon::echo_form_input(['phase','userrole','ccdomain','prevphase','currstate','ccuname','ccdomain']));
 1663:     $r->print('<input type="hidden" name="currstate" value="" />');
 1664:     $r->print('<input type="hidden" name="prevphase" value="'.$env{'form.phase'}.'" /></form><br /><br />');
 1665:     return;
 1666: }
 1667: 
 1668: sub singleuser_breadcrumb {
 1669:     my ($crstype,$context,$domain) = @_;
 1670:     my %breadcrumb_text;
 1671:     if ($env{'form.action'} eq 'singlestudent') {
 1672:         if ($crstype eq 'Community') {
 1673:             $breadcrumb_text{'search'} = 'Enroll a member';
 1674:         } else {
 1675:             $breadcrumb_text{'search'} = 'Enroll a student';
 1676:         }
 1677:         $breadcrumb_text{'userpicked'} = 'Select a user';
 1678:         $breadcrumb_text{'modify'} = 'Set section/dates';
 1679:     } elsif ($env{'form.action'} eq 'accesslogs') {
 1680:         $breadcrumb_text{'search'} = 'View access logs for a user';
 1681:         $breadcrumb_text{'userpicked'} = 'Select a user';
 1682:         $breadcrumb_text{'activity'} = 'Activity';
 1683:     } elsif (($env{'form.action'} eq 'singleuser') && ($context eq 'domain') &&
 1684:              (!&Apache::lonnet::allowed('mau',$domain))) {
 1685:         $breadcrumb_text{'search'} = "View user's roles";
 1686:         $breadcrumb_text{'userpicked'} = 'Select a user';
 1687:         $breadcrumb_text{'modify'} = 'User roles';
 1688:     } else {
 1689:         $breadcrumb_text{'search'} = 'Create/modify a user';
 1690:         $breadcrumb_text{'userpicked'} = 'Select a user';
 1691:         $breadcrumb_text{'modify'} = 'Set user role';
 1692:     }
 1693:     return %breadcrumb_text;
 1694: }
 1695: 
 1696: sub date_sections_select {
 1697:     my ($context,$newuser,$formname,$permission,$crstype,$ccuname,$ccdomain,
 1698:         $showcredits) = @_;
 1699:     my $credits;
 1700:     if ($showcredits) {
 1701:         my $defaultcredits = &Apache::lonuserutils::get_defaultcredits();
 1702:         $credits = &get_user_credits($ccuname,$ccdomain,$defaultcredits);
 1703:         if ($credits eq '') {
 1704:             $credits = $defaultcredits;
 1705:         }
 1706:     }
 1707:     my $cid = $env{'request.course.id'};
 1708:     my ($cnum,$cdom) = &Apache::lonuserutils::get_course_identity($cid);
 1709:     my $date_table = '<h3>'.&mt('Starting and Ending Dates').'</h3>'."\n".
 1710:         &Apache::lonuserutils::date_setting_table(undef,undef,$context,
 1711:                                                   undef,$formname,$permission);
 1712:     my $rowtitle = 'Section';
 1713:     my $secbox = '<h3>'.&mt('Section and Credits').'</h3>'."\n".
 1714:         &Apache::lonuserutils::section_picker($cdom,$cnum,'st',$rowtitle,
 1715:                                               $permission,$context,'',$crstype,
 1716:                                               $showcredits,$credits);
 1717:     my $output = $date_table.$secbox;
 1718:     return $output;
 1719: }
 1720: 
 1721: sub validation_javascript {
 1722:     my ($context,$ccdomain,$pjump_def,$crstype,$groupslist,$newuser,$formname,
 1723:         $loaditem) = @_;
 1724:     my $dc_setcourse_code = '';
 1725:     my $nondc_setsection_code = '';
 1726:     if ($context eq 'domain') {
 1727:         my $dcdom = $env{'request.role.domain'};
 1728:         $loaditem->{'onload'} = "document.cu.coursedesc.value='';";
 1729:         $dc_setcourse_code = 
 1730:             &Apache::lonuserutils::dc_setcourse_js('cu','singleuser',$context);
 1731:     } else {
 1732:         my $checkauth; 
 1733:         if (($newuser) || (&Apache::lonnet::allowed('mau',$ccdomain))) {
 1734:             $checkauth = 1;
 1735:         }
 1736:         if ($context eq 'course') {
 1737:             $nondc_setsection_code =
 1738:                 &Apache::lonuserutils::setsections_javascript($formname,$groupslist,
 1739:                                                               undef,$checkauth,
 1740:                                                               $crstype);
 1741:         }
 1742:         if ($checkauth) {
 1743:             $nondc_setsection_code .= 
 1744:                 &Apache::lonuserutils::verify_authen($formname,$context);
 1745:         }
 1746:     }
 1747:     my $js = &user_modification_js($pjump_def,$dc_setcourse_code,
 1748:                                    $nondc_setsection_code,$groupslist);
 1749:     my ($jsback,$elements) = &crumb_utilities();
 1750:     $js .= "\n".
 1751:            '<script type="text/javascript">'."\n".
 1752:            '// <![CDATA['."\n".
 1753:            $jsback."\n".
 1754:            '// ]]>'."\n".
 1755:            '</script>'."\n";
 1756:     return $js;
 1757: }
 1758: 
 1759: sub display_existing_roles {
 1760:     my ($r,$ccuname,$ccdomain,$inccourses,$context,$roledom,$crstype,
 1761:         $showcredits,$statuses) = @_;
 1762:     my $now=time;
 1763:     my $showall = 1;
 1764:     my ($showexpired,$showactive);
 1765:     if ((ref($statuses) eq 'ARRAY') && (@{$statuses} > 0)) {
 1766:         $showall = 0;
 1767:         if (grep(/^expired$/,@{$statuses})) {
 1768:             $showexpired = 1;
 1769:         }
 1770:         if (grep(/^active$/,@{$statuses})) {
 1771:             $showactive = 1;
 1772:         }
 1773:         if ($showexpired && $showactive) {
 1774:             $showall = 1;
 1775:         }
 1776:     }
 1777:     my %lt=&Apache::lonlocal::texthash(
 1778:                     'rer'  => "Existing Roles",
 1779:                     'rev'  => "Revoke",
 1780:                     'del'  => "Delete",
 1781:                     'ren'  => "Re-Enable",
 1782:                     'rol'  => "Role",
 1783:                     'ext'  => "Extent",
 1784:                     'crd'  => "Credits",
 1785:                     'sta'  => "Start",
 1786:                     'end'  => "End",
 1787:                                        );
 1788:     my (%rolesdump,%roletext,%sortrole,%roleclass,%rolepriv);
 1789:     if ($context eq 'course' || $context eq 'author') {
 1790:         my @roles = &Apache::lonuserutils::roles_by_context($context,1,$crstype);
 1791:         my %roleshash = 
 1792:             &Apache::lonnet::get_my_roles($ccuname,$ccdomain,'userroles',
 1793:                               ['active','previous','future'],\@roles,$roledom,1);
 1794:         foreach my $key (keys(%roleshash)) {
 1795:             my ($start,$end) = split(':',$roleshash{$key});
 1796:             next if ($start eq '-1' || $end eq '-1');
 1797:             my ($rnum,$rdom,$role,$sec) = split(':',$key);
 1798:             if ($context eq 'course') {
 1799:                 next unless (($rnum eq $env{'course.'.$env{'request.course.id'}.'.num'})
 1800:                              && ($rdom eq $env{'course.'.$env{'request.course.id'}.'.domain'}));
 1801:             } elsif ($context eq 'author') {
 1802:                 next unless (($rnum eq $env{'user.name'}) && ($rdom eq $env{'request.role.domain'}));
 1803:             }
 1804:             my ($newkey,$newvalue,$newrole);
 1805:             $newkey = '/'.$rdom.'/'.$rnum;
 1806:             if ($sec ne '') {
 1807:                 $newkey .= '/'.$sec;
 1808:             }
 1809:             $newvalue = $role;
 1810:             if ($role =~ /^cr/) {
 1811:                 $newrole = 'cr';
 1812:             } else {
 1813:                 $newrole = $role;
 1814:             }
 1815:             $newkey .= '_'.$newrole;
 1816:             if ($start ne '' && $end ne '') {
 1817:                 $newvalue .= '_'.$end.'_'.$start;
 1818:             } elsif ($end ne '') {
 1819:                 $newvalue .= '_'.$end;
 1820:             }
 1821:             $rolesdump{$newkey} = $newvalue;
 1822:         }
 1823:     } else {
 1824:         %rolesdump=&Apache::lonnet::dump('roles',$ccdomain,$ccuname);
 1825:     }
 1826:     # Build up table of user roles to allow revocation and re-enabling of roles.
 1827:     my ($tmp) = keys(%rolesdump);
 1828:     return if ($tmp =~ /^(con_lost|error)/i);
 1829:     foreach my $area (sort { my $a1=join('_',(split('_',$a))[1,0]);
 1830:                                 my $b1=join('_',(split('_',$b))[1,0]);
 1831:                                 return $a1 cmp $b1;
 1832:                             } keys(%rolesdump)) {
 1833:         next if ($area =~ /^rolesdef/);
 1834:         my $envkey=$area;
 1835:         my $role = $rolesdump{$area};
 1836:         my $thisrole=$area;
 1837:         $area =~ s/\_\w\w$//;
 1838:         my ($role_code,$role_end_time,$role_start_time) =
 1839:             split(/_/,$role);
 1840:         my $active=1;
 1841:         $active=0 if (($role_end_time) && ($now>$role_end_time));
 1842:         if ($active) {
 1843:             next unless($showall || $showactive);
 1844:         } else {
 1845:             next unless($showall || $showexpired);
 1846:         }
 1847: # Is this a custom role? Get role owner and title.
 1848:         my ($croleudom,$croleuname,$croletitle)=
 1849:             ($role_code=~m{^cr/($match_domain)/($match_username)/(\w+)$});
 1850:         my $allowed=0;
 1851:         my $delallowed=0;
 1852:         my $sortkey=$role_code;
 1853:         my $class='Unknown';
 1854:         my $credits='';
 1855:         my $csec;
 1856:         if ($area =~ m{^/($match_domain)/($match_courseid)}) {
 1857:             $class='Course';
 1858:             my ($coursedom,$coursedir) = ($1,$2);
 1859:             my $cid = $1.'_'.$2;
 1860:             # $1.'_'.$2 is the course id (eg. 103_12345abcef103l3).
 1861:             next if ($envkey =~ m{^/$match_domain/$match_courseid/[A-Za-z0-9]+_gr$});
 1862:             my %coursedata=
 1863:                 &Apache::lonnet::coursedescription($cid);
 1864:             if ($coursedir =~ /^$match_community$/) {
 1865:                 $class='Community';
 1866:             }
 1867:             $sortkey.="\0$coursedom";
 1868:             my $carea;
 1869:             if (defined($coursedata{'description'})) {
 1870:                 $carea=$coursedata{'description'}.
 1871:                     '<br />'.&mt('Domain').': '.$coursedom.('&nbsp;'x8).
 1872:     &Apache::loncommon::syllabuswrapper(&mt('Syllabus'),$coursedir,$coursedom);
 1873:                 $sortkey.="\0".$coursedata{'description'};
 1874:             } else {
 1875:                 if ($class eq 'Community') {
 1876:                     $carea=&mt('Unavailable community').': '.$area;
 1877:                     $sortkey.="\0".&mt('Unavailable community').': '.$area;
 1878:                 } else {
 1879:                     $carea=&mt('Unavailable course').': '.$area;
 1880:                     $sortkey.="\0".&mt('Unavailable course').': '.$area;
 1881:                 }
 1882:             }
 1883:             $sortkey.="\0$coursedir";
 1884:             $inccourses->{$cid}=1;
 1885:             if (($showcredits) && ($class eq 'Course') && ($role_code eq 'st')) {
 1886:                 my $defaultcredits = $coursedata{'internal.defaultcredits'};
 1887:                 $credits =
 1888:                     &get_user_credits($ccuname,$ccdomain,$defaultcredits,
 1889:                                       $coursedom,$coursedir);
 1890:                 if ($credits eq '') {
 1891:                     $credits = $defaultcredits;
 1892:                 }
 1893:             }
 1894:             if ((&Apache::lonnet::allowed('c'.$role_code,$coursedom.'/'.$coursedir)) ||
 1895:                 (&Apache::lonnet::allowed('c'.$role_code,$ccdomain))) {
 1896:                 $allowed=1;
 1897:             }
 1898:             unless ($allowed) {
 1899:                 my $isowner = &Apache::lonuserutils::is_courseowner($cid,$coursedata{'internal.courseowner'});
 1900:                 if ($isowner) {
 1901:                     if (($role_code eq 'co') && ($class eq 'Community')) {
 1902:                         $allowed = 1;
 1903:                     } elsif (($role_code eq 'cc') && ($class eq 'Course')) {
 1904:                         $allowed = 1;
 1905:                     }
 1906:                 }
 1907:             } 
 1908:             if ((&Apache::lonnet::allowed('dro',$coursedom)) ||
 1909:                 (&Apache::lonnet::allowed('dro',$ccdomain))) {
 1910:                 $delallowed=1;
 1911:             }
 1912: # - custom role. Needs more info, too
 1913:             if ($croletitle) {
 1914:                 if (&Apache::lonnet::allowed('ccr',$coursedom.'/'.$coursedir)) {
 1915:                     $allowed=1;
 1916:                     $thisrole.='.'.$role_code;
 1917:                 }
 1918:             }
 1919:             if ($area=~m{^/($match_domain/$match_courseid/(\w+))}) {
 1920:                 $csec = $2;
 1921:                 $carea.='<br />'.&mt('Section: [_1]',$csec);
 1922:                 $sortkey.="\0$csec";
 1923:                 if (!$allowed) {
 1924:                     if ($env{'request.course.sec'} eq $csec) {
 1925:                         if (&Apache::lonnet::allowed('c'.$role_code,$1)) {
 1926:                             $allowed = 1;
 1927:                         }
 1928:                     }
 1929:                 }
 1930:             }
 1931:             $area=$carea;
 1932:         } else {
 1933:             $sortkey.="\0".$area;
 1934:             # Determine if current user is able to revoke privileges
 1935:             if ($area=~m{^/($match_domain)/}) {
 1936:                 if ((&Apache::lonnet::allowed('c'.$role_code,$1)) ||
 1937:                    (&Apache::lonnet::allowed('c'.$role_code,$ccdomain))) {
 1938:                    $allowed=1;
 1939:                 }
 1940:                 if (((&Apache::lonnet::allowed('dro',$1))  ||
 1941:                     (&Apache::lonnet::allowed('dro',$ccdomain))) &&
 1942:                     ($role_code ne 'dc')) {
 1943:                     $delallowed=1;
 1944:                 }
 1945:             } else {
 1946:                 if (&Apache::lonnet::allowed('c'.$role_code,'/')) {
 1947:                     $allowed=1;
 1948:                 }
 1949:             }
 1950:             if ($role_code eq 'ca' || $role_code eq 'au' || $role_code eq 'aa') {
 1951:                 $class='Authoring Space';
 1952:             } elsif ($role_code eq 'su') {
 1953:                 $class='System';
 1954:             } else {
 1955:                 $class='Domain';
 1956:             }
 1957:         }
 1958:         if (($role_code eq 'ca') || ($role_code eq 'aa')) {
 1959:             $area=~m{/($match_domain)/($match_username)};
 1960:             if (&Apache::lonuserutils::authorpriv($2,$1)) {
 1961:                 $allowed=1;
 1962:             } else {
 1963:                 $allowed=0;
 1964:             }
 1965:         }
 1966:         my $row = '';
 1967:         if ($showall) {
 1968:             $row.= '<td>';
 1969:             if (($active) && ($allowed)) {
 1970:                 $row.= '<input type="checkbox" name="rev:'.$thisrole.'" />';
 1971:             } else {
 1972:                 if ($active) {
 1973:                     $row.='&nbsp;';
 1974:                 } else {
 1975:                     $row.=&mt('expired or revoked');
 1976:                 }
 1977:             }
 1978:             $row.='</td><td>';
 1979:             if ($allowed && !$active) {
 1980:                 $row.= '<input type="checkbox" name="ren:'.$thisrole.'" />';
 1981:             } else {
 1982:                 $row.='&nbsp;';
 1983:             }
 1984:             $row.='</td><td>';
 1985:             if ($delallowed) {
 1986:                 $row.= '<input type="checkbox" name="del:'.$thisrole.'" />';
 1987:             } else {
 1988:                 $row.='&nbsp;';
 1989:             }
 1990:             $row.= '</td>';
 1991:         }
 1992:         my $plaintext='';
 1993:         if (!$croletitle) {
 1994:             $plaintext=&Apache::lonnet::plaintext($role_code,$class);
 1995:             if (($showcredits) && ($credits ne '')) {
 1996:                 $plaintext .= '<br/ ><span class="LC_nobreak">'.
 1997:                               '<span class="LC_fontsize_small">'.
 1998:                               &mt('Credits: [_1]',$credits).
 1999:                               '</span></span>';
 2000:             }
 2001:         } else {
 2002:             $plaintext=
 2003:                 &mt('Custom role [_1][_2]defined by [_3]',
 2004:                         '"'.$croletitle.'"',
 2005:                         '<br />',
 2006:                         $croleuname.':'.$croleudom);
 2007:         }
 2008:         $row.= '<td>'.$plaintext.'</td>'.
 2009:                '<td>'.$area.'</td>'.
 2010:                '<td>'.($role_start_time?&Apache::lonlocal::locallocaltime($role_start_time)
 2011:                                             : '&nbsp;' ).'</td>'.
 2012:                '<td>'.($role_end_time  ?&Apache::lonlocal::locallocaltime($role_end_time)
 2013:                                             : '&nbsp;' ).'</td>';
 2014:         $sortrole{$sortkey}=$envkey;
 2015:         $roletext{$envkey}=$row;
 2016:         $roleclass{$envkey}=$class;
 2017:         if ($allowed) {
 2018:             $rolepriv{$envkey}='edit';
 2019:         } else {
 2020:             if ($context eq 'domain') {
 2021:                 if ((&Apache::lonnet::allowed('vur',$ccdomain)) &&
 2022:                     ($envkey=~m{^/$ccdomain/})) {
 2023:                     $rolepriv{$envkey}='view';
 2024:                 }
 2025:             } elsif ($context eq 'course') {
 2026:                 if ((&Apache::lonnet::allowed('vcl',$env{'request.course.id'})) ||
 2027:                     ($env{'request.course.sec'} && ($env{'request.course.sec'} eq $csec) &&
 2028:                      &Apache::lonnet::allowed('vcl',$env{'request.course.id'}.'/'.$env{'request.course.sec'}))) {
 2029:                     $rolepriv{$envkey}='view';
 2030:                 }
 2031:             }
 2032:         }
 2033:     } # end of foreach        (table building loop)
 2034: 
 2035:     my $rolesdisplay = 0;
 2036:     my %output = ();
 2037:     foreach my $type ('Authoring Space','Course','Community','Domain','System','Unknown') {
 2038:         $output{$type} = '';
 2039:         foreach my $which (sort {uc($a) cmp uc($b)} (keys(%sortrole))) {
 2040:             if ( ($roleclass{$sortrole{$which}} =~ /^\Q$type\E/ ) && ($rolepriv{$sortrole{$which}}) ) {
 2041:                  $output{$type}.=
 2042:                       &Apache::loncommon::start_data_table_row().
 2043:                       $roletext{$sortrole{$which}}.
 2044:                       &Apache::loncommon::end_data_table_row();
 2045:             }
 2046:         }
 2047:         unless($output{$type} eq '') {
 2048:             $output{$type} = '<tr class="LC_info_row">'.
 2049:                       "<td align='center' colspan='7'>".&mt($type)."</td></tr>".
 2050:                       $output{$type};
 2051:             $rolesdisplay = 1;
 2052:         }
 2053:     }
 2054:     if ($rolesdisplay == 1) {
 2055:         my $contextrole='';
 2056:         if ($env{'request.course.id'}) {
 2057:             if (&Apache::loncommon::course_type() eq 'Community') {
 2058:                 $contextrole = &mt('Existing Roles in this Community');
 2059:             } else {
 2060:                 $contextrole = &mt('Existing Roles in this Course');
 2061:             }
 2062:         } elsif ($env{'request.role'} =~ /^au\./) {
 2063:             $contextrole = &mt('Existing Co-Author Roles in your Authoring Space');
 2064:         } else {
 2065:             if ($showall) {
 2066:                 $contextrole = &mt('Existing Roles in this Domain');
 2067:             } elsif ($showactive) {
 2068:                 $contextrole = &mt('Unexpired Roles in this Domain');
 2069:             } elsif ($showexpired) {
 2070:                 $contextrole = &mt('Expired or Revoked Roles in this Domain');
 2071:             }
 2072:         }
 2073:         $r->print('<div class="LC_left_float">'.
 2074: '<fieldset><legend>'.$contextrole.'</legend>'.
 2075: &Apache::loncommon::start_data_table("LC_createuser").
 2076: &Apache::loncommon::start_data_table_header_row());
 2077:         if ($showall) {
 2078:             $r->print(
 2079: '<th>'.$lt{'rev'}.'</th><th>'.$lt{'ren'}.'</th><th>'.$lt{'del'}.'</th>'
 2080:             );
 2081:         } elsif ($showexpired) {
 2082:             $r->print('<th>'.$lt{'rev'}.'</th>');
 2083:         }
 2084:         $r->print(
 2085: '<th>'.$lt{'rol'}.'</th><th>'.$lt{'ext'}.'</th>'.
 2086: '<th>'.$lt{'sta'}.'</th><th>'.$lt{'end'}.'</th>'.
 2087: &Apache::loncommon::end_data_table_header_row());
 2088:         foreach my $type ('Authoring Space','Course','Community','Domain','System','Unknown') {
 2089:             if ($output{$type}) {
 2090:                 $r->print($output{$type}."\n");
 2091:             }
 2092:         }
 2093:         $r->print(&Apache::loncommon::end_data_table().
 2094:                   '</fieldset></div>');
 2095:     }
 2096:     return;
 2097: }
 2098: 
 2099: sub new_coauthor_roles {
 2100:     my ($r,$ccuname,$ccdomain) = @_;
 2101:     my $addrolesdisplay = 0;
 2102:     #
 2103:     # Co-Author
 2104:     #
 2105:     if (&Apache::lonuserutils::authorpriv($env{'user.name'},
 2106:                                           $env{'request.role.domain'}) &&
 2107:         ($env{'user.name'} ne $ccuname || $env{'user.domain'} ne $ccdomain)) {
 2108:         # No sense in assigning co-author role to yourself
 2109:         $addrolesdisplay = 1;
 2110:         my $cuname=$env{'user.name'};
 2111:         my $cudom=$env{'request.role.domain'};
 2112:         my %lt=&Apache::lonlocal::texthash(
 2113:                     'cs'   => "Authoring Space",
 2114:                     'act'  => "Activate",
 2115:                     'rol'  => "Role",
 2116:                     'ext'  => "Extent",
 2117:                     'sta'  => "Start",
 2118:                     'end'  => "End",
 2119:                     'cau'  => "Co-Author",
 2120:                     'caa'  => "Assistant Co-Author",
 2121:                     'ssd'  => "Set Start Date",
 2122:                     'sed'  => "Set End Date"
 2123:                                        );
 2124:         $r->print('<h4>'.$lt{'cs'}.'</h4>'."\n".
 2125:                   &Apache::loncommon::start_data_table()."\n".
 2126:                   &Apache::loncommon::start_data_table_header_row()."\n".
 2127:                   '<th>'.$lt{'act'}.'</th><th>'.$lt{'rol'}.'</th>'.
 2128:                   '<th>'.$lt{'ext'}.'</th><th>'.$lt{'sta'}.'</th>'.
 2129:                   '<th>'.$lt{'end'}.'</th>'."\n".
 2130:                   &Apache::loncommon::end_data_table_header_row()."\n".
 2131:                   &Apache::loncommon::start_data_table_row().'
 2132:            <td>
 2133:             <input type="checkbox" name="act_'.$cudom.'_'.$cuname.'_ca" />
 2134:            </td>
 2135:            <td>'.$lt{'cau'}.'</td>
 2136:            <td>'.$cudom.'_'.$cuname.'</td>
 2137:            <td><input type="hidden" name="start_'.$cudom.'_'.$cuname.'_ca" value="" />
 2138:              <a href=
 2139: "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>
 2140: <td><input type="hidden" name="end_'.$cudom.'_'.$cuname.'_ca" value="" />
 2141: <a href=
 2142: "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".
 2143:               &Apache::loncommon::end_data_table_row()."\n".
 2144:               &Apache::loncommon::start_data_table_row()."\n".
 2145: '<td><input type="checkbox" name="act_'.$cudom.'_'.$cuname.'_aa" /></td>
 2146: <td>'.$lt{'caa'}.'</td>
 2147: <td>'.$cudom.'_'.$cuname.'</td>
 2148: <td><input type="hidden" name="start_'.$cudom.'_'.$cuname.'_aa" value="" />
 2149: <a href=
 2150: "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>
 2151: <td><input type="hidden" name="end_'.$cudom.'_'.$cuname.'_aa" value="" />
 2152: <a href=
 2153: "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".
 2154:              &Apache::loncommon::end_data_table_row()."\n".
 2155:              &Apache::loncommon::end_data_table());
 2156:     } elsif ($env{'request.role'} =~ /^au\./) {
 2157:         if (!(&Apache::lonuserutils::authorpriv($env{'user.name'},
 2158:                                                 $env{'request.role.domain'}))) {
 2159:             $r->print('<span class="LC_error">'.
 2160:                       &mt('You do not have privileges to assign co-author roles.').
 2161:                       '</span>');
 2162:         } elsif (($env{'user.name'} eq $ccuname) &&
 2163:              ($env{'user.domain'} eq $ccdomain)) {
 2164:             $r->print(&mt('Assigning yourself a co-author or assistant co-author role in your own author area in Authoring Space is not permitted'));
 2165:         }
 2166:     }
 2167:     return $addrolesdisplay;;
 2168: }
 2169: 
 2170: sub new_domain_roles {
 2171:     my ($r,$ccdomain) = @_;
 2172:     my $addrolesdisplay = 0;
 2173:     #
 2174:     # Domain level
 2175:     #
 2176:     my $num_domain_level = 0;
 2177:     my $domaintext =
 2178:     '<h4>'.&mt('Domain Level').'</h4>'.
 2179:     &Apache::loncommon::start_data_table().
 2180:     &Apache::loncommon::start_data_table_header_row().
 2181:     '<th>'.&mt('Activate').'</th><th>'.&mt('Role').'</th><th>'.
 2182:     &mt('Extent').'</th>'.
 2183:     '<th>'.&mt('Start').'</th><th>'.&mt('End').'</th>'.
 2184:     &Apache::loncommon::end_data_table_header_row();
 2185:     my @allroles = &Apache::lonuserutils::roles_by_context('domain');
 2186:     foreach my $thisdomain (sort(&Apache::lonnet::all_domains())) {
 2187:         foreach my $role (@allroles) {
 2188:             next if ($role eq 'ad');
 2189:             next if (($role eq 'au') && ($ccdomain ne $thisdomain));
 2190:             if (&Apache::lonnet::allowed('c'.$role,$thisdomain)) {
 2191:                my $plrole=&Apache::lonnet::plaintext($role);
 2192:                my %lt=&Apache::lonlocal::texthash(
 2193:                     'ssd'  => "Set Start Date",
 2194:                     'sed'  => "Set End Date"
 2195:                                        );
 2196:                $num_domain_level ++;
 2197:                $domaintext .=
 2198: &Apache::loncommon::start_data_table_row().
 2199: '<td><input type="checkbox" name="act_'.$thisdomain.'_'.$role.'" /></td>
 2200: <td>'.$plrole.'</td>
 2201: <td>'.$thisdomain.'</td>
 2202: <td><input type="hidden" name="start_'.$thisdomain.'_'.$role.'" value="" />
 2203: <a href=
 2204: "javascript:pjump('."'date_start','Start Date $plrole',document.cu.start_$thisdomain\_$role.value,'start_$thisdomain\_$role','cu.pres','dateset'".')">'.$lt{'ssd'}.'</a></td>
 2205: <td><input type="hidden" name="end_'.$thisdomain.'_'.$role.'" value="" />
 2206: <a href=
 2207: "javascript:pjump('."'date_end','End Date $plrole',document.cu.end_$thisdomain\_$role.value,'end_$thisdomain\_$role','cu.pres','dateset'".')">'.$lt{'sed'}.'</a></td>'.
 2208: &Apache::loncommon::end_data_table_row();
 2209:             }
 2210:         }
 2211:     }
 2212:     $domaintext.= &Apache::loncommon::end_data_table();
 2213:     if ($num_domain_level > 0) {
 2214:         $r->print($domaintext);
 2215:         $addrolesdisplay = 1;
 2216:     }
 2217:     return $addrolesdisplay;
 2218: }
 2219: 
 2220: sub user_authentication {
 2221:     my ($ccuname,$ccdomain,$formname) = @_;
 2222:     my $currentauth=&Apache::lonnet::queryauthenticate($ccuname,$ccdomain);
 2223:     my $outcome;
 2224:     my %lt=&Apache::lonlocal::texthash(
 2225:                    'err'   => "ERROR",
 2226:                    'uuas'  => "This user has an unrecognized authentication scheme",
 2227:                    'adcs'  => "Please alert a domain coordinator of this situation",
 2228:                    'sldb'  => "Please specify login data below",
 2229:                    'ld'    => "Login Data"
 2230:     );
 2231:     # Check for a bad authentication type
 2232:     if ($currentauth !~ /^(krb4|krb5|unix|internal|localauth):/) {
 2233:         # bad authentication scheme
 2234:         if (&Apache::lonnet::allowed('mau',$ccdomain)) {
 2235:             &initialize_authen_forms($ccdomain,$formname);
 2236: 
 2237:             my $choices = &Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc);
 2238:             $outcome = <<ENDBADAUTH;
 2239: <script type="text/javascript" language="Javascript">
 2240: // <![CDATA[
 2241: $loginscript
 2242: // ]]>
 2243: </script>
 2244: <span class="LC_error">$lt{'err'}:
 2245: $lt{'uuas'} ($currentauth). $lt{'sldb'}.</span>
 2246: <h3>$lt{'ld'}</h3>
 2247: $choices
 2248: ENDBADAUTH
 2249:         } else {
 2250:             # This user is not allowed to modify the user's
 2251:             # authentication scheme, so just notify them of the problem
 2252:             $outcome = <<ENDBADAUTH;
 2253: <span class="LC_error"> $lt{'err'}: 
 2254: $lt{'uuas'} ($currentauth). $lt{'adcs'}.
 2255: </span>
 2256: ENDBADAUTH
 2257:         }
 2258:     } else { # Authentication type is valid
 2259:         &initialize_authen_forms($ccdomain,$formname,$currentauth,'modifyuser');
 2260:         my ($authformcurrent,$can_modify,@authform_others) =
 2261:             &modify_login_block($ccdomain,$currentauth);
 2262:         if (&Apache::lonnet::allowed('mau',$ccdomain)) {
 2263:             # Current user has login modification privileges
 2264:             $outcome =
 2265:                        '<script type="text/javascript" language="Javascript">'."\n".
 2266:                        '// <![CDATA['."\n".
 2267:                        $loginscript."\n".
 2268:                        '// ]]>'."\n".
 2269:                        '</script>'."\n".
 2270:                        '<h3>'.$lt{'ld'}.'</h3>'.
 2271:                        &Apache::loncommon::start_data_table().
 2272:                        &Apache::loncommon::start_data_table_row().
 2273:                        '<td>'.$authformnop;
 2274:             if (($can_modify) && (&Apache::lonnet::allowed('mau',$ccdomain))) {
 2275:                 $outcome .= '</td>'."\n".
 2276:                             &Apache::loncommon::end_data_table_row().
 2277:                             &Apache::loncommon::start_data_table_row().
 2278:                             '<td>'.$authformcurrent.'</td>'.
 2279:                             &Apache::loncommon::end_data_table_row()."\n";
 2280:             } else {
 2281:                 $outcome .= '&nbsp;('.$authformcurrent.')</td>'.
 2282:                             &Apache::loncommon::end_data_table_row()."\n";
 2283:             }
 2284:             if (&Apache::lonnet::allowed('mau',$ccdomain)) {
 2285:                 foreach my $item (@authform_others) { 
 2286:                     $outcome .= &Apache::loncommon::start_data_table_row().
 2287:                                 '<td>'.$item.'</td>'.
 2288:                                 &Apache::loncommon::end_data_table_row()."\n";
 2289:                 }
 2290:             }
 2291:             $outcome .= &Apache::loncommon::end_data_table();
 2292:         } else {
 2293:             if (&Apache::lonnet::allowed('udp',$ccdomain)) {
 2294:                 # Current user has rights to view domain preferences for user's domain
 2295:                 my $result;
 2296:                 if ($currentauth =~ /^krb(4|5):([^:]*)$/) {
 2297:                     my ($krbver,$krbrealm) = ($1,$2);
 2298:                     if ($krbrealm eq '') {
 2299:                         $result = &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
 2300:                     } else {
 2301:                         $result = &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
 2302:                                       $krbver,$krbrealm);
 2303:                     }
 2304:                 } elsif ($currentauth =~ /^internal:/) {
 2305:                     $result = &mt('Currently internally authenticated.');
 2306:                 } elsif ($currentauth =~ /^localauth:/) {
 2307:                     $result = &mt('Currently using local (institutional) authentication.');
 2308:                 } elsif ($currentauth =~ /^unix:/) {
 2309:                     $result = &mt('Currently Filesystem Authenticated.');
 2310:                 }
 2311:                 $outcome = '<h3>'.$lt{'ld'}.'</h3>'.
 2312:                            &Apache::loncommon::start_data_table().
 2313:                            &Apache::loncommon::start_data_table_row().
 2314:                            '<td>'.$result.'</td>'.
 2315:                            &Apache::loncommon::end_data_table_row()."\n".
 2316:                            &Apache::loncommon::end_data_table();
 2317:             } elsif (&Apache::lonnet::allowed('mau',$env{'request.role.domain'})) {
 2318:                 my %lt=&Apache::lonlocal::texthash(
 2319:                            'ccld'  => "Change Current Login Data",
 2320:                            'yodo'  => "You do not have privileges to modify the authentication configuration for this user.",
 2321:                            'ifch'  => "If a change is required, contact a domain coordinator for the domain",
 2322:                 );
 2323:                 $outcome .= <<ENDNOPRIV;
 2324: <h3>$lt{'ccld'}</h3>
 2325: $lt{'yodo'} $lt{'ifch'}: $ccdomain
 2326: <input type="hidden" name="login" value="nochange" />
 2327: ENDNOPRIV
 2328:             }
 2329:         }
 2330:     }  ## End of "check for bad authentication type" logic
 2331:     return $outcome;
 2332: }
 2333: 
 2334: sub modify_login_block {
 2335:     my ($dom,$currentauth) = @_;
 2336:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 2337:     my ($authnum,%can_assign) =
 2338:         &Apache::loncommon::get_assignable_auth($dom);
 2339:     my ($authformcurrent,@authform_others,$show_override_msg);
 2340:     if ($currentauth=~/^krb(4|5):/) {
 2341:         $authformcurrent=$authformkrb;
 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{'krb4'}) || ($can_assign{'krb5'})) {
 2349:             $show_override_msg = 1;
 2350:         }
 2351:     } elsif ($currentauth=~/^internal:/) {
 2352:         $authformcurrent=$authformint;
 2353:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2354:             push(@authform_others,$authformkrb);
 2355:         }
 2356:         if ($can_assign{'loc'}) {
 2357:             push(@authform_others,$authformloc);
 2358:         }
 2359:         if ($can_assign{'int'}) {
 2360:             $show_override_msg = 1;
 2361:         }
 2362:     } elsif ($currentauth=~/^unix:/) {
 2363:         $authformcurrent=$authformfsys;
 2364:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2365:             push(@authform_others,$authformkrb);
 2366:         }
 2367:         if ($can_assign{'int'}) {
 2368:             push(@authform_others,$authformint);
 2369:         }
 2370:         if ($can_assign{'loc'}) {
 2371:             push(@authform_others,$authformloc);
 2372:         }
 2373:         if ($can_assign{'fsys'}) {
 2374:             $show_override_msg = 1;
 2375:         }
 2376:     } elsif ($currentauth=~/^localauth:/) {
 2377:         $authformcurrent=$authformloc;
 2378:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2379:             push(@authform_others,$authformkrb);
 2380:         }
 2381:         if ($can_assign{'int'}) {
 2382:             push(@authform_others,$authformint);
 2383:         }
 2384:         if ($can_assign{'loc'}) {
 2385:             $show_override_msg = 1;
 2386:         }
 2387:     }
 2388:     if ($show_override_msg) {
 2389:         $authformcurrent = '<table><tr><td colspan="3">'.$authformcurrent.
 2390:                            '</td></tr>'."\n".
 2391:                            '<tr><td>&nbsp;&nbsp;&nbsp;</td>'.
 2392:                            '<td><b>'.&mt('Currently in use').'</b></td>'.
 2393:                            '<td align="right"><span class="LC_cusr_emph">'.
 2394:                             &mt('will override current values').
 2395:                             '</span></td></tr></table>';
 2396:     }
 2397:     return ($authformcurrent,$show_override_msg,@authform_others); 
 2398: }
 2399: 
 2400: sub personal_data_display {
 2401:     my ($ccuname,$ccdomain,$newuser,$context,$inst_results,$rolesarray,
 2402:         $now,$captchaform,$emailusername,$usertype) = @_;
 2403:     my ($output,%userenv,%canmodify,%canmodify_status);
 2404:     my @userinfo = ('firstname','middlename','lastname','generation',
 2405:                     'permanentemail','id');
 2406:     my $rowcount = 0;
 2407:     my $editable = 0;
 2408:     my %textboxsize = (
 2409:                        firstname      => '15',
 2410:                        middlename     => '15',
 2411:                        lastname       => '15',
 2412:                        generation     => '5',
 2413:                        permanentemail => '25',
 2414:                        id             => '15',
 2415:                       );
 2416: 
 2417:     my %lt=&Apache::lonlocal::texthash(
 2418:                 'pd'             => "Personal Data",
 2419:                 'firstname'      => "First Name",
 2420:                 'middlename'     => "Middle Name",
 2421:                 'lastname'       => "Last Name",
 2422:                 'generation'     => "Generation",
 2423:                 'permanentemail' => "Permanent e-mail address",
 2424:                 'id'             => "Student/Employee ID",
 2425:                 'lg'             => "Login Data",
 2426:                 'inststatus'     => "Affiliation",
 2427:                 'email'          => 'E-mail address',
 2428:                 'valid'          => 'Validation',
 2429:     );
 2430: 
 2431:     %canmodify_status =
 2432:         &Apache::lonuserutils::can_modify_userinfo($context,$ccdomain,
 2433:                                                    ['inststatus'],$rolesarray);
 2434:     if (!$newuser) {
 2435:         # Get the users information
 2436:         %userenv = &Apache::lonnet::get('environment',
 2437:                    ['firstname','middlename','lastname','generation',
 2438:                     'permanentemail','id','inststatus'],$ccdomain,$ccuname);
 2439:         %canmodify =
 2440:             &Apache::lonuserutils::can_modify_userinfo($context,$ccdomain,
 2441:                                                        \@userinfo,$rolesarray);
 2442:     } elsif ($context eq 'selfcreate') {
 2443:         if ($newuser eq 'email') {
 2444:             if (ref($emailusername) eq 'HASH') {
 2445:                 if (ref($emailusername->{$usertype}) eq 'HASH') {
 2446:                     my ($infofields,$infotitles) = &Apache::loncommon::emailusername_info();
 2447:                     @userinfo = ();          
 2448:                     if ((ref($infofields) eq 'ARRAY') && (ref($infotitles) eq 'HASH')) {
 2449:                         foreach my $field (@{$infofields}) { 
 2450:                             if ($emailusername->{$usertype}->{$field}) {
 2451:                                 push(@userinfo,$field);
 2452:                                 $canmodify{$field} = 1;
 2453:                                 unless ($textboxsize{$field}) {
 2454:                                     $textboxsize{$field} = 25;
 2455:                                 }
 2456:                                 unless ($lt{$field}) {
 2457:                                     $lt{$field} = $infotitles->{$field};
 2458:                                 }
 2459:                                 if ($emailusername->{$usertype}->{$field} eq 'required') {
 2460:                                     $lt{$field} .= '<b>*</b>';
 2461:                                 }
 2462:                             }
 2463:                         }
 2464:                     }
 2465:                 }
 2466:             }
 2467:         } else {
 2468:             %canmodify = &selfcreate_canmodify($context,$ccdomain,\@userinfo,
 2469:                                                $inst_results,$rolesarray);
 2470:         }
 2471:     }
 2472: 
 2473:     my $genhelp=&Apache::loncommon::help_open_topic('Generation');
 2474:     $output = '<h3>'.$lt{'pd'}.'</h3>'.
 2475:               &Apache::lonhtmlcommon::start_pick_box();
 2476:     if (($context eq 'selfcreate') && ($newuser eq 'email')) {
 2477:         $output .= &Apache::lonhtmlcommon::row_title($lt{'email'}.'<b>*</b>',undef,
 2478:                                                      'LC_oddrow_value')."\n".
 2479:                    '<input type="text" name="uname" size="25" value="" autocomplete="off" />';
 2480:         $rowcount ++;
 2481:         $output .= &Apache::lonhtmlcommon::row_closure(1);
 2482:         my $upassone = '<input type="password" name="upass'.$now.'" size="20" autocomplete="off" />';
 2483:         my $upasstwo = '<input type="password" name="upasscheck'.$now.'" size="20" autocomplete="off" />';
 2484:         $output .= &Apache::lonhtmlcommon::row_title(&mt('Password').'<b>*</b>',
 2485:                                                     'LC_pick_box_title',
 2486:                                                     'LC_oddrow_value')."\n".
 2487:                    $upassone."\n".
 2488:                    &Apache::lonhtmlcommon::row_closure(1)."\n".
 2489:                    &Apache::lonhtmlcommon::row_title(&mt('Confirm password').'<b>*</b>',
 2490:                                                      'LC_pick_box_title',
 2491:                                                      'LC_oddrow_value')."\n".
 2492:                    $upasstwo.
 2493:                    &Apache::lonhtmlcommon::row_closure()."\n";
 2494:     }
 2495:     foreach my $item (@userinfo) {
 2496:         my $rowtitle = $lt{$item};
 2497:         my $hiderow = 0;
 2498:         if ($item eq 'generation') {
 2499:             $rowtitle = $genhelp.$rowtitle;
 2500:         }
 2501:         my $row = &Apache::lonhtmlcommon::row_title($rowtitle,undef,'LC_oddrow_value')."\n";
 2502:         if ($newuser) {
 2503:             if (ref($inst_results) eq 'HASH') {
 2504:                 if ($inst_results->{$item} ne '') {
 2505:                     $row .= '<input type="hidden" name="c'.$item.'" value="'.$inst_results->{$item}.'" />'.$inst_results->{$item};
 2506:                 } else {
 2507:                     if ($context eq 'selfcreate') {
 2508:                         if ($canmodify{$item}) {
 2509:                             $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="" autocomplete="off" />';
 2510:                             $editable ++;
 2511:                         } else {
 2512:                             $hiderow = 1;
 2513:                         }
 2514:                     } else {
 2515:                         $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="" />';
 2516:                     }
 2517:                 }
 2518:             } else {
 2519:                 if ($context eq 'selfcreate') {
 2520:                     if ($canmodify{$item}) {
 2521:                         if ($newuser eq 'email') {
 2522:                             $row .= '<input type="text" name="'.$item.'" size="'.$textboxsize{$item}.'" value="" autocomplete="off" />';
 2523:                         } else {
 2524:                             $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="" autocomplete="off" />';
 2525:                         }
 2526:                         $editable ++;
 2527:                     } else {
 2528:                         $hiderow = 1;
 2529:                     }
 2530:                 } else {
 2531:                     $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="" />';
 2532:                 }
 2533:             }
 2534:         } else {
 2535:             if ($canmodify{$item}) {
 2536:                 $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="'.$userenv{$item}.'" />';
 2537:                 if (($item eq 'id') && (!$newuser)) {
 2538:                     $row .= '<br />'.&Apache::lonuserutils::forceid_change($context);
 2539:                 }
 2540:             } else {
 2541:                 $row .= $userenv{$item};
 2542:             }
 2543:         }
 2544:         $row .= &Apache::lonhtmlcommon::row_closure(1);
 2545:         if (!$hiderow) {
 2546:             $output .= $row;
 2547:             $rowcount ++;
 2548:         }
 2549:     }
 2550:     if (($canmodify_status{'inststatus'}) || ($context ne 'selfcreate')) {
 2551:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($ccdomain);
 2552:         if (ref($types) eq 'ARRAY') {
 2553:             if (@{$types} > 0) {
 2554:                 my ($hiderow,$shown);
 2555:                 if ($canmodify_status{'inststatus'}) {
 2556:                     $shown = &pick_inst_statuses($userenv{'inststatus'},$usertypes,$types);
 2557:                 } else {
 2558:                     if ($userenv{'inststatus'} eq '') {
 2559:                         $hiderow = 1;
 2560:                     } else {
 2561:                         my @showitems;
 2562:                         foreach my $item ( map { &unescape($_); } split(':',$userenv{'inststatus'})) {
 2563:                             if (exists($usertypes->{$item})) {
 2564:                                 push(@showitems,$usertypes->{$item});
 2565:                             } else {
 2566:                                 push(@showitems,$item);
 2567:                             }
 2568:                         }
 2569:                         if (@showitems) {
 2570:                             $shown = join(', ',@showitems);
 2571:                         } else {
 2572:                             $hiderow = 1;
 2573:                         }
 2574:                     }
 2575:                 }
 2576:                 if (!$hiderow) {
 2577:                     my $row = &Apache::lonhtmlcommon::row_title(&mt('Affiliations'),undef,'LC_oddrow_value')."\n".
 2578:                               $shown.&Apache::lonhtmlcommon::row_closure(1); 
 2579:                     if ($context eq 'selfcreate') {
 2580:                         $rowcount ++;
 2581:                     }
 2582:                     $output .= $row;
 2583:                 }
 2584:             }
 2585:         }
 2586:     }
 2587:     if (($context eq 'selfcreate') && ($newuser eq 'email')) {
 2588:         if ($captchaform) {
 2589:             $output .= &Apache::lonhtmlcommon::row_title($lt{'valid'}.'*',
 2590:                                                          'LC_pick_box_title')."\n".
 2591:                        $captchaform."\n".'<br /><br />'.
 2592:                        &Apache::lonhtmlcommon::row_closure(1); 
 2593:             $rowcount ++;
 2594:         }
 2595:         my $submit_text = &mt('Create account');
 2596:         $output .= &Apache::lonhtmlcommon::row_title()."\n".
 2597:                    '<br /><input type="submit" name="createaccount" value="'.
 2598:                    $submit_text.'" />'.
 2599:                    '<input type="hidden" name="type" value="'.$usertype.'" />'.
 2600:                    &Apache::lonhtmlcommon::row_closure(1);
 2601:     }
 2602:     $output .= &Apache::lonhtmlcommon::end_pick_box();
 2603:     if (wantarray) {
 2604:         if ($context eq 'selfcreate') {
 2605:             return($output,$rowcount,$editable);
 2606:         } else {
 2607:             return $output;
 2608:         }
 2609:     } else {
 2610:         return $output;
 2611:     }
 2612: }
 2613: 
 2614: sub pick_inst_statuses {
 2615:     my ($curr,$usertypes,$types) = @_;
 2616:     my ($output,$rem,@currtypes);
 2617:     if ($curr ne '') {
 2618:         @currtypes = map { &unescape($_); } split(/:/,$curr);
 2619:     }
 2620:     my $numinrow = 2;
 2621:     if (ref($types) eq 'ARRAY') {
 2622:         $output = '<table>';
 2623:         my $lastcolspan; 
 2624:         for (my $i=0; $i<@{$types}; $i++) {
 2625:             if (defined($usertypes->{$types->[$i]})) {
 2626:                 my $rem = $i%($numinrow);
 2627:                 if ($rem == 0) {
 2628:                     if ($i<@{$types}-1) {
 2629:                         if ($i > 0) { 
 2630:                             $output .= '</tr>';
 2631:                         }
 2632:                         $output .= '<tr>';
 2633:                     }
 2634:                 } elsif ($i==@{$types}-1) {
 2635:                     my $colsleft = $numinrow - $rem;
 2636:                     if ($colsleft > 1) {
 2637:                         $lastcolspan = ' colspan="'.$colsleft.'"';
 2638:                     }
 2639:                 }
 2640:                 my $check = ' ';
 2641:                 if (grep(/^\Q$types->[$i]\E$/,@currtypes)) {
 2642:                     $check = ' checked="checked" ';
 2643:                 }
 2644:                 $output .= '<td class="LC_left_item"'.$lastcolspan.'>'.
 2645:                            '<span class="LC_nobreak"><label>'.
 2646:                            '<input type="checkbox" name="inststatus" '.
 2647:                            'value="'.$types->[$i].'"'.$check.'/>'.
 2648:                            $usertypes->{$types->[$i]}.'</label></span></td>';
 2649:             }
 2650:         }
 2651:         $output .= '</tr></table>';
 2652:     }
 2653:     return $output;
 2654: }
 2655: 
 2656: sub selfcreate_canmodify {
 2657:     my ($context,$dom,$userinfo,$inst_results,$rolesarray) = @_;
 2658:     if (ref($inst_results) eq 'HASH') {
 2659:         my @inststatuses = &get_inststatuses($inst_results);
 2660:         if (@inststatuses == 0) {
 2661:             @inststatuses = ('default');
 2662:         }
 2663:         $rolesarray = \@inststatuses;
 2664:     }
 2665:     my %canmodify =
 2666:         &Apache::lonuserutils::can_modify_userinfo($context,$dom,$userinfo,
 2667:                                                    $rolesarray);
 2668:     return %canmodify;
 2669: }
 2670: 
 2671: sub get_inststatuses {
 2672:     my ($insthashref) = @_;
 2673:     my @inststatuses = ();
 2674:     if (ref($insthashref) eq 'HASH') {
 2675:         if (ref($insthashref->{'inststatus'}) eq 'ARRAY') {
 2676:             @inststatuses = @{$insthashref->{'inststatus'}};
 2677:         }
 2678:     }
 2679:     return @inststatuses;
 2680: }
 2681: 
 2682: # ================================================================= Phase Three
 2683: sub update_user_data {
 2684:     my ($r,$context,$crstype,$brcrum,$showcredits) = @_; 
 2685:     my $uhome=&Apache::lonnet::homeserver($env{'form.ccuname'},
 2686:                                           $env{'form.ccdomain'});
 2687:     # Error messages
 2688:     my $error     = '<span class="LC_error">'.&mt('Error').': ';
 2689:     my $end       = '</span><br /><br />';
 2690:     my $rtnlink   = '<a href="javascript:backPage(document.userupdate,'.
 2691:                     "'$env{'form.prevphase'}','modify')".'" />'.
 2692:                     &mt('Return to previous page').'</a>'.
 2693:                     &Apache::loncommon::end_page();
 2694:     my $now = time;
 2695:     my $title;
 2696:     if (exists($env{'form.makeuser'})) {
 2697: 	$title='Set Privileges for New User';
 2698:     } else {
 2699:         $title='Modify User Privileges';
 2700:     }
 2701:     my $newuser = 0;
 2702:     my ($jsback,$elements) = &crumb_utilities();
 2703:     my $jscript = '<script type="text/javascript">'."\n".
 2704:                   '// <![CDATA['."\n".
 2705:                   $jsback."\n".
 2706:                   '// ]]>'."\n".
 2707:                   '</script>'."\n";
 2708:     my %breadcrumb_text = &singleuser_breadcrumb($crstype,$context,$env{'form.ccdomain'});
 2709:     push (@{$brcrum},
 2710:              {href => "javascript:backPage(document.userupdate)",
 2711:               text => $breadcrumb_text{'search'},
 2712:               faq  => 282,
 2713:               bug  => 'Instructor Interface',}
 2714:              );
 2715:     if ($env{'form.prevphase'} eq 'userpicked') {
 2716:         push(@{$brcrum},
 2717:                {href => "javascript:backPage(document.userupdate,'get_user_info','select')",
 2718:                 text => $breadcrumb_text{'userpicked'},
 2719:                 faq  => 282,
 2720:                 bug  => 'Instructor Interface',});
 2721:     }
 2722:     my $helpitem = 'Course_Change_Privileges';
 2723:     if ($env{'form.action'} eq 'singlestudent') {
 2724:         $helpitem = 'Course_Add_Student';
 2725:     }
 2726:     push(@{$brcrum}, 
 2727:             {href => "javascript:backPage(document.userupdate,'$env{'form.prevphase'}','modify')",
 2728:              text => $breadcrumb_text{'modify'},
 2729:              faq  => 282,
 2730:              bug  => 'Instructor Interface',},
 2731:             {href => "/adm/createuser",
 2732:              text => "Result",
 2733:              faq  => 282,
 2734:              bug  => 'Instructor Interface',
 2735:              help => $helpitem});
 2736:     my $args = {bread_crumbs          => $brcrum,
 2737:                 bread_crumbs_component => 'User Management'};
 2738:     if ($env{'form.popup'}) {
 2739:         $args->{'no_nav_bar'} = 1;
 2740:     }
 2741:     $r->print(&Apache::loncommon::start_page($title,$jscript,$args));
 2742:     $r->print(&update_result_form($uhome));
 2743:     # Check Inputs
 2744:     if (! $env{'form.ccuname'} ) {
 2745: 	$r->print($error.&mt('No login name specified').'.'.$end.$rtnlink);
 2746: 	return;
 2747:     }
 2748:     if (  $env{'form.ccuname'} ne 
 2749: 	  &LONCAPA::clean_username($env{'form.ccuname'}) ) {
 2750: 	$r->print($error.&mt('Invalid login name.').'  '.
 2751: 		  &mt('Only letters, numbers, periods, dashes, @, and underscores are valid.').
 2752: 		  $end.$rtnlink);
 2753: 	return;
 2754:     }
 2755:     if (! $env{'form.ccdomain'}       ) {
 2756: 	$r->print($error.&mt('No domain specified').'.'.$end.$rtnlink);
 2757: 	return;
 2758:     }
 2759:     if (  $env{'form.ccdomain'} ne
 2760: 	  &LONCAPA::clean_domain($env{'form.ccdomain'}) ) {
 2761: 	$r->print($error.&mt('Invalid domain name.').'  '.
 2762: 		  &mt('Only letters, numbers, periods, dashes, and underscores are valid.').
 2763: 		  $end.$rtnlink);
 2764: 	return;
 2765:     }
 2766:     if ($uhome eq 'no_host') {
 2767:         $newuser = 1;
 2768:     }
 2769:     if (! exists($env{'form.makeuser'})) {
 2770:         # Modifying an existing user, so check the validity of the name
 2771:         if ($uhome eq 'no_host') {
 2772:             $r->print(
 2773:                 $error
 2774:                .'<p class="LC_error">'
 2775:                .&mt('Unable to determine home server for [_1] in domain [_2].',
 2776:                         '"'.$env{'form.ccuname'}.'"','"'.$env{'form.ccdomain'}.'"')
 2777:                .'</p>');
 2778:             return;
 2779:         }
 2780:     }
 2781:     # Determine authentication method and password for the user being modified
 2782:     my $amode='';
 2783:     my $genpwd='';
 2784:     if ($env{'form.login'} eq 'krb') {
 2785: 	$amode='krb';
 2786: 	$amode.=$env{'form.krbver'};
 2787: 	$genpwd=$env{'form.krbarg'};
 2788:     } elsif ($env{'form.login'} eq 'int') {
 2789: 	$amode='internal';
 2790: 	$genpwd=$env{'form.intarg'};
 2791:     } elsif ($env{'form.login'} eq 'fsys') {
 2792: 	$amode='unix';
 2793: 	$genpwd=$env{'form.fsysarg'};
 2794:     } elsif ($env{'form.login'} eq 'loc') {
 2795: 	$amode='localauth';
 2796: 	$genpwd=$env{'form.locarg'};
 2797: 	$genpwd=" " if (!$genpwd);
 2798:     } elsif (($env{'form.login'} eq 'nochange') ||
 2799:              ($env{'form.login'} eq ''        )) { 
 2800:         # There is no need to tell the user we did not change what they
 2801:         # did not ask us to change.
 2802:         # If they are creating a new user but have not specified login
 2803:         # information this will be caught below.
 2804:     } else {
 2805:             $r->print($error.&mt('Invalid login mode or password').$end.$rtnlink);
 2806:             return;
 2807:     }
 2808: 
 2809:     $r->print('<h3>'.&mt('User [_1] in domain [_2]',
 2810:                         $env{'form.ccuname'}.' ('.&Apache::loncommon::plainname($env{'form.ccuname'},
 2811:                         $env{'form.ccdomain'}).')', $env{'form.ccdomain'}).'</h3>');
 2812:     my %prog_state = &Apache::lonhtmlcommon::Create_PrgWin($r,2);
 2813: 
 2814:     my (%alerts,%rulematch,%inst_results,%curr_rules);
 2815:     my @userinfo = ('firstname','middlename','lastname','generation','permanentemail','id');
 2816:     my @usertools = ('aboutme','blog','webdav','portfolio');
 2817:     my @requestcourses = ('official','unofficial','community','textbook');
 2818:     my @requestauthor = ('requestauthor');
 2819:     my ($othertitle,$usertypes,$types) = 
 2820:         &Apache::loncommon::sorted_inst_types($env{'form.ccdomain'});
 2821:     my %canmodify_status =
 2822:         &Apache::lonuserutils::can_modify_userinfo($context,$env{'form.ccdomain'},
 2823:                                                    ['inststatus']);
 2824:     if ($env{'form.makeuser'}) {
 2825: 	$r->print('<h3>'.&mt('Creating new account.').'</h3>');
 2826:         # Check for the authentication mode and password
 2827:         if (! $amode || ! $genpwd) {
 2828: 	    $r->print($error.&mt('Invalid login mode or password').$end.$rtnlink);    
 2829: 	    return;
 2830: 	}
 2831:         # Determine desired host
 2832:         my $desiredhost = $env{'form.hserver'};
 2833:         if (lc($desiredhost) eq 'default') {
 2834:             $desiredhost = undef;
 2835:         } else {
 2836:             my %home_servers = 
 2837: 		&Apache::lonnet::get_servers($env{'form.ccdomain'},'library');
 2838:             if (! exists($home_servers{$desiredhost})) {
 2839:                 $r->print($error.&mt('Invalid home server specified').$end.$rtnlink);
 2840:                 return;
 2841:             }
 2842:         }
 2843:         # Check ID format
 2844:         my %checkhash;
 2845:         my %checks = ('id' => 1);
 2846:         %{$checkhash{$env{'form.ccuname'}.':'.$env{'form.ccdomain'}}} = (
 2847:             'newuser' => $newuser, 
 2848:             'id' => $env{'form.cid'},
 2849:         );
 2850:         if ($env{'form.cid'} ne '') {
 2851:             &Apache::loncommon::user_rule_check(\%checkhash,\%checks,\%alerts,
 2852:                                           \%rulematch,\%inst_results,\%curr_rules);
 2853:             if (ref($alerts{'id'}) eq 'HASH') {
 2854:                 if (ref($alerts{'id'}{$env{'form.ccdomain'}}) eq 'HASH') {
 2855:                     my $domdesc =
 2856:                         &Apache::lonnet::domain($env{'form.ccdomain'},'description');
 2857:                     if ($alerts{'id'}{$env{'form.ccdomain'}}{$env{'form.cid'}}) {
 2858:                         my $userchkmsg;
 2859:                         if (ref($curr_rules{$env{'form.ccdomain'}}) eq 'HASH') {
 2860:                             $userchkmsg  = 
 2861:                                 &Apache::loncommon::instrule_disallow_msg('id',
 2862:                                                                     $domdesc,1).
 2863:                                 &Apache::loncommon::user_rule_formats($env{'form.ccdomain'},
 2864:                                     $domdesc,$curr_rules{$env{'form.ccdomain'}}{'id'},'id');
 2865:                         }
 2866:                         $r->print($error.&mt('Invalid ID format').$end.
 2867:                                   $userchkmsg.$rtnlink);
 2868:                         return;
 2869:                     }
 2870:                 }
 2871:             }
 2872:         }
 2873:         &Apache::lonhtmlcommon::Increment_PrgWin($r, \%prog_state);
 2874: 	# Call modifyuser
 2875: 	my $result = &Apache::lonnet::modifyuser
 2876: 	    ($env{'form.ccdomain'},$env{'form.ccuname'},$env{'form.cid'},
 2877:              $amode,$genpwd,$env{'form.cfirstname'},
 2878:              $env{'form.cmiddlename'},$env{'form.clastname'},
 2879:              $env{'form.cgeneration'},undef,$desiredhost,
 2880:              $env{'form.cpermanentemail'});
 2881: 	$r->print(&mt('Generating user').': '.$result);
 2882:         $uhome = &Apache::lonnet::homeserver($env{'form.ccuname'},
 2883:                                                $env{'form.ccdomain'});
 2884:         my (%changeHash,%newcustom,%changed,%changedinfo);
 2885:         if ($uhome ne 'no_host') {
 2886:             if ($context eq 'domain') {
 2887:                 foreach my $name ('portfolio','author') {
 2888:                     if ($env{'form.custom_'.$name.'quota'} == 1) {
 2889:                         if ($env{'form.'.$name.'quota'} eq '') {
 2890:                             $newcustom{$name.'quota'} = 0;
 2891:                         } else {
 2892:                             $newcustom{$name.'quota'} = $env{'form.'.$name.'quota'};
 2893:                             $newcustom{$name.'quota'} =~ s/[^\d\.]//g;
 2894:                         }
 2895:                         if (&quota_admin($newcustom{$name.'quota'},\%changeHash,$name)) {
 2896:                             $changed{$name.'quota'} = 1;
 2897:                         }
 2898:                     }
 2899:                 }
 2900:                 foreach my $item (@usertools) {
 2901:                     if ($env{'form.custom'.$item} == 1) {
 2902:                         $newcustom{$item} = $env{'form.tools_'.$item};
 2903:                         $changed{$item} = &tool_admin($item,$newcustom{$item},
 2904:                                                      \%changeHash,'tools');
 2905:                     }
 2906:                 }
 2907:                 foreach my $item (@requestcourses) {
 2908:                     if ($env{'form.custom'.$item} == 1) {
 2909:                         $newcustom{$item} = $env{'form.crsreq_'.$item};
 2910:                         if ($env{'form.crsreq_'.$item} eq 'autolimit') {
 2911:                             $newcustom{$item} .= '=';
 2912:                             $env{'form.crsreq_'.$item.'_limit'} =~ s/\D+//g;
 2913:                             if ($env{'form.crsreq_'.$item.'_limit'}) {
 2914:                                 $newcustom{$item} .= $env{'form.crsreq_'.$item.'_limit'};
 2915:                             }
 2916:                         }
 2917:                         $changed{$item} = &tool_admin($item,$newcustom{$item},
 2918:                                                       \%changeHash,'requestcourses');
 2919:                     }
 2920:                 }
 2921:                 if ($env{'form.customrequestauthor'} == 1) {
 2922:                     $newcustom{'requestauthor'} = $env{'form.requestauthor'};
 2923:                     $changed{'requestauthor'} = &tool_admin('requestauthor',
 2924:                                                     $newcustom{'requestauthor'},
 2925:                                                     \%changeHash,'requestauthor');
 2926:                 }
 2927:                 if (&Apache::lonnet::allowed('cdh',$env{'request.role.domain'})) {
 2928:                     my @adds = &Apache::loncommon::get_env_multiple('form.adhocroleadd');
 2929:                     if (&adhocrole_changes(\%changeHash)) {
 2930:                         $changed{'adhocroles.'.$env{'request.role.domain'}} = $changeHash{'adhocroles.'.$env{'request.role.domain'}};
 2931:                     }
 2932:                 }
 2933:             }
 2934:             if ($canmodify_status{'inststatus'}) {
 2935:                 if (exists($env{'form.inststatus'})) {
 2936:                     my @inststatuses = &Apache::loncommon::get_env_multiple('form.inststatus');
 2937:                     if (@inststatuses > 0) {
 2938:                         $changeHash{'inststatus'} = join(',',@inststatuses);
 2939:                         $changed{'inststatus'} = $changeHash{'inststatus'};
 2940:                     }
 2941:                 }
 2942:             }
 2943:             if (keys(%changed)) {
 2944:                 foreach my $item (@userinfo) {
 2945:                     $changeHash{$item}  = $env{'form.c'.$item};
 2946:                 }
 2947:                 my $chgresult =
 2948:                      &Apache::lonnet::put('environment',\%changeHash,
 2949:                                           $env{'form.ccdomain'},$env{'form.ccuname'});
 2950:             } 
 2951:         }
 2952:         $r->print('<br />'.&mt('Home server').': '.$uhome.' '.
 2953:                   &Apache::lonnet::hostname($uhome));
 2954:     } elsif (($env{'form.login'} ne 'nochange') &&
 2955:              ($env{'form.login'} ne ''        )) {
 2956: 	# Modify user privileges
 2957:         if (! $amode || ! $genpwd) {
 2958: 	    $r->print($error.'Invalid login mode or password'.$end.$rtnlink);    
 2959: 	    return;
 2960: 	}
 2961: 	# Only allow authentication modification if the person has authority
 2962: 	if (&Apache::lonnet::allowed('mau',$env{'form.ccdomain'})) {
 2963: 	    $r->print('Modifying authentication: '.
 2964:                       &Apache::lonnet::modifyuserauth(
 2965: 		       $env{'form.ccdomain'},$env{'form.ccuname'},
 2966:                        $amode,$genpwd));
 2967:             $r->print('<br />'.&mt('Home server').': '.&Apache::lonnet::homeserver
 2968: 		  ($env{'form.ccuname'},$env{'form.ccdomain'}));
 2969: 	} else {
 2970: 	    # Okay, this is a non-fatal error.
 2971: 	    $r->print($error.&mt('You do not have the authority to modify this users authentication information.').$end);    
 2972: 	}
 2973:     }
 2974:     $r->rflush(); # Finish display of header before time consuming actions start
 2975:     &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state);
 2976:     ##
 2977:     my (@userroles,%userupdate,$cnum,$cdom,$defaultcredits,%namechanged);
 2978:     if ($context eq 'course') {
 2979:         ($cnum,$cdom) =
 2980:             &Apache::lonuserutils::get_course_identity();
 2981:         $crstype = &Apache::loncommon::course_type($cdom.'_'.$cnum);
 2982:         if ($showcredits) {
 2983:            $defaultcredits = &Apache::lonuserutils::get_defaultcredits($cdom,$cnum);
 2984:         }
 2985:     }
 2986:     if (! $env{'form.makeuser'} ) {
 2987:         # Check for need to change
 2988:         my %userenv = &Apache::lonnet::get
 2989:             ('environment',['firstname','middlename','lastname','generation',
 2990:              'id','permanentemail','portfolioquota','authorquota','inststatus',
 2991:              'tools.aboutme','tools.blog','tools.webdav','tools.portfolio',
 2992:              'requestcourses.official','requestcourses.unofficial',
 2993:              'requestcourses.community','requestcourses.textbook',
 2994:              'reqcrsotherdom.official','reqcrsotherdom.unofficial',
 2995:              'reqcrsotherdom.community','reqcrsotherdom.textbook',
 2996:              'requestauthor','adhocroles.'.$env{'request.role.domain'}],
 2997:               $env{'form.ccdomain'},$env{'form.ccuname'});
 2998:         my ($tmp) = keys(%userenv);
 2999:         if ($tmp =~ /^(con_lost|error)/i) { 
 3000:             %userenv = ();
 3001:         }
 3002:         my $no_forceid_alert;
 3003:         # Check to see if user information can be changed
 3004:         my %domconfig =
 3005:             &Apache::lonnet::get_dom('configuration',['usermodification'],
 3006:                                      $env{'form.ccdomain'});
 3007:         my @statuses = ('active','future');
 3008:         my %roles = &Apache::lonnet::get_my_roles($env{'form.ccuname'},$env{'form.ccdomain'},'userroles',\@statuses,undef,$env{'request.role.domain'});
 3009:         my ($auname,$audom);
 3010:         if ($context eq 'author') {
 3011:             $auname = $env{'user.name'};
 3012:             $audom = $env{'user.domain'};     
 3013:         }
 3014:         foreach my $item (keys(%roles)) {
 3015:             my ($rolenum,$roledom,$role) = split(/:/,$item,-1);
 3016:             if ($context eq 'course') {
 3017:                 if ($cnum ne '' && $cdom ne '') {
 3018:                     if ($rolenum eq $cnum && $roledom eq $cdom) {
 3019:                         if (!grep(/^\Q$role\E$/,@userroles)) {
 3020:                             push(@userroles,$role);
 3021:                         }
 3022:                     }
 3023:                 }
 3024:             } elsif ($context eq 'author') {
 3025:                 if ($rolenum eq $auname && $roledom eq $audom) {
 3026:                     if (!grep(/^\Q$role\E$/,@userroles)) { 
 3027:                         push(@userroles,$role);
 3028:                     }
 3029:                 }
 3030:             }
 3031:         }
 3032:         if ($env{'form.action'} eq 'singlestudent') {
 3033:             if (!grep(/^st$/,@userroles)) {
 3034:                 push(@userroles,'st');
 3035:             }
 3036:         } else {
 3037:             # Check for course or co-author roles being activated or re-enabled
 3038:             if ($context eq 'author' || $context eq 'course') {
 3039:                 foreach my $key (keys(%env)) {
 3040:                     if ($context eq 'author') {
 3041:                         if ($key=~/^form\.act_\Q$audom\E_\Q$auname\E_([^_]+)/) {
 3042:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 3043:                                 push(@userroles,$1);
 3044:                             }
 3045:                         } elsif ($key =~/^form\.ren\:\Q$audom\E\/\Q$auname\E_([^_]+)/) {
 3046:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 3047:                                 push(@userroles,$1);
 3048:                             }
 3049:                         }
 3050:                     } elsif ($context eq 'course') {
 3051:                         if ($key=~/^form\.act_\Q$cdom\E_\Q$cnum\E_([^_]+)/) {
 3052:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 3053:                                 push(@userroles,$1);
 3054:                             }
 3055:                         } elsif ($key =~/^form\.ren\:\Q$cdom\E\/\Q$cnum\E(\/?\w*)_([^_]+)/) {
 3056:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 3057:                                 push(@userroles,$1);
 3058:                             }
 3059:                         }
 3060:                     }
 3061:                 }
 3062:             }
 3063:         }
 3064:         #Check to see if we can change personal data for the user 
 3065:         my (@mod_disallowed,@longroles);
 3066:         foreach my $role (@userroles) {
 3067:             if ($role eq 'cr') {
 3068:                 push(@longroles,'Custom');
 3069:             } else {
 3070:                 push(@longroles,&Apache::lonnet::plaintext($role,$crstype)); 
 3071:             }
 3072:         }
 3073:         my %canmodify = &Apache::lonuserutils::can_modify_userinfo($context,$env{'form.ccdomain'},\@userinfo,\@userroles);
 3074:         foreach my $item (@userinfo) {
 3075:             # Strip leading and trailing whitespace
 3076:             $env{'form.c'.$item} =~ s/(\s+$|^\s+)//g;
 3077:             if (!$canmodify{$item}) {
 3078:                 if (defined($env{'form.c'.$item})) {
 3079:                     if ($env{'form.c'.$item} ne $userenv{$item}) {
 3080:                         push(@mod_disallowed,$item);
 3081:                     }
 3082:                 }
 3083:                 $env{'form.c'.$item} = $userenv{$item};
 3084:             }
 3085:         }
 3086:         # Check to see if we can change the Student/Employee ID
 3087:         my $forceid = $env{'form.forceid'};
 3088:         my $recurseid = $env{'form.recurseid'};
 3089:         my (%alerts,%rulematch,%idinst_results,%curr_rules,%got_rules);
 3090:         my %uidhash = &Apache::lonnet::idrget($env{'form.ccdomain'},
 3091:                                             $env{'form.ccuname'});
 3092:         if (($uidhash{$env{'form.ccuname'}}) && 
 3093:             ($uidhash{$env{'form.ccuname'}}!~/error\:/) && 
 3094:             (!$forceid)) {
 3095:             if ($env{'form.cid'} ne $uidhash{$env{'form.ccuname'}}) {
 3096:                 $env{'form.cid'} = $userenv{'id'};
 3097:                 $no_forceid_alert = &mt('New student/employee ID does not match existing ID for this user.')
 3098:                                    .'<br />'
 3099:                                    .&mt("Change is not permitted without checking the 'Force ID change' checkbox on the previous page.")
 3100:                                    .'<br />'."\n";
 3101:             }
 3102:         }
 3103:         if ($env{'form.cid'} ne $userenv{'id'}) {
 3104:             my $checkhash;
 3105:             my $checks = { 'id' => 1 };
 3106:             $checkhash->{$env{'form.ccuname'}.':'.$env{'form.ccdomain'}} = 
 3107:                    { 'newuser' => $newuser,
 3108:                      'id'  => $env{'form.cid'}, 
 3109:                    };
 3110:             &Apache::loncommon::user_rule_check($checkhash,$checks,
 3111:                 \%alerts,\%rulematch,\%idinst_results,\%curr_rules,\%got_rules);
 3112:             if (ref($alerts{'id'}) eq 'HASH') {
 3113:                 if (ref($alerts{'id'}{$env{'form.ccdomain'}}) eq 'HASH') {
 3114:                    $env{'form.cid'} = $userenv{'id'};
 3115:                 }
 3116:             }
 3117:         }
 3118:         my (%quotachanged,%oldquota,%newquota,%olddefquota,%newdefquota, 
 3119:             $oldinststatus,$newinststatus,%oldisdefault,%newisdefault,%oldsettings,
 3120:             %oldsettingstext,%newsettings,%newsettingstext,@disporder,
 3121:             %oldsettingstatus,%newsettingstatus);
 3122:         @disporder = ('inststatus');
 3123:         if ($env{'request.role.domain'} eq $env{'form.ccdomain'}) {
 3124:             push(@disporder,'requestcourses','requestauthor');
 3125:         } else {
 3126:             push(@disporder,'reqcrsotherdom');
 3127:         }
 3128:         push(@disporder,('quota','tools'));
 3129:         $oldinststatus = $userenv{'inststatus'};
 3130:         foreach my $name ('portfolio','author') {
 3131:             ($olddefquota{$name},$oldsettingstatus{$name}) = 
 3132:                 &Apache::loncommon::default_quota($env{'form.ccdomain'},$oldinststatus,$name);
 3133:             ($newdefquota{$name},$newsettingstatus{$name}) = ($olddefquota{$name},$oldsettingstatus{$name});
 3134:         }
 3135:         push(@disporder,'adhocroles');
 3136:         my %canshow;
 3137:         if (&Apache::lonnet::allowed('mpq',$env{'form.ccdomain'})) {
 3138:             $canshow{'quota'} = 1;
 3139:         }
 3140:         if (&Apache::lonnet::allowed('mut',$env{'form.ccdomain'})) {
 3141:             $canshow{'tools'} = 1;
 3142:         }
 3143:         if (&Apache::lonnet::allowed('ccc',$env{'form.ccdomain'})) {
 3144:             $canshow{'requestcourses'} = 1;
 3145:         } elsif (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) {
 3146:             $canshow{'reqcrsotherdom'} = 1;
 3147:         }
 3148:         if (&Apache::lonnet::allowed('mau',$env{'form.ccdomain'})) {
 3149:             $canshow{'inststatus'} = 1;
 3150:         }
 3151:         if (&Apache::lonnet::allowed('cau',$env{'form.ccdomain'})) {
 3152:             $canshow{'requestauthor'} = 1;
 3153:         }
 3154:         if (&Apache::lonnet::allowed('cdh',$env{'request.role.domain'})) {
 3155:             $canshow{'adhocroles'} = 1;
 3156:         }
 3157:         my (%changeHash,%changed);
 3158:         if ($oldinststatus eq '') {
 3159:             $oldsettings{'inststatus'} = $othertitle; 
 3160:         } else {
 3161:             if (ref($usertypes) eq 'HASH') {
 3162:                 $oldsettings{'inststatus'} = join(', ',map{ $usertypes->{ &unescape($_) }; } (split(/:/,$userenv{'inststatus'})));
 3163:             } else {
 3164:                 $oldsettings{'inststatus'} = join(', ',map{ &unescape($_); } (split(/:/,$userenv{'inststatus'})));
 3165:             }
 3166:         }
 3167:         $changeHash{'inststatus'} = $userenv{'inststatus'};
 3168:         if ($canmodify_status{'inststatus'}) {
 3169:             $canshow{'inststatus'} = 1;
 3170:             if (exists($env{'form.inststatus'})) {
 3171:                 my @inststatuses = &Apache::loncommon::get_env_multiple('form.inststatus');
 3172:                 if (@inststatuses > 0) {
 3173:                     $newinststatus = join(':',map { &escape($_); } @inststatuses);
 3174:                     $changeHash{'inststatus'} = $newinststatus;
 3175:                     if ($newinststatus ne $oldinststatus) {
 3176:                         $changed{'inststatus'} = $newinststatus;
 3177:                         foreach my $name ('portfolio','author') {
 3178:                             ($newdefquota{$name},$newsettingstatus{$name}) =
 3179:                                 &Apache::loncommon::default_quota($env{'form.ccdomain'},$newinststatus,$name);
 3180:                         }
 3181:                     }
 3182:                     if (ref($usertypes) eq 'HASH') {
 3183:                         $newsettings{'inststatus'} = join(', ',map{ $usertypes->{$_}; } (@inststatuses)); 
 3184:                     } else {
 3185:                         $newsettings{'inststatus'} = join(', ',@inststatuses);
 3186:                     }
 3187:                 }
 3188:             } else {
 3189:                 $newinststatus = '';
 3190:                 $changeHash{'inststatus'} = $newinststatus;
 3191:                 $newsettings{'inststatus'} = $othertitle;
 3192:                 if ($newinststatus ne $oldinststatus) {
 3193:                     $changed{'inststatus'} = $changeHash{'inststatus'};
 3194:                     foreach my $name ('portfolio','author') {
 3195:                         ($newdefquota{$name},$newsettingstatus{$name}) =
 3196:                             &Apache::loncommon::default_quota($env{'form.ccdomain'},$newinststatus,$name);
 3197:                     }
 3198:                 }
 3199:             }
 3200:         } elsif ($context ne 'selfcreate') {
 3201:             $canshow{'inststatus'} = 1;
 3202:             $newsettings{'inststatus'} = $oldsettings{'inststatus'};
 3203:         }
 3204:         foreach my $name ('portfolio','author') {
 3205:             $changeHash{$name.'quota'} = $userenv{$name.'quota'};
 3206:         }
 3207:         if ($context eq 'domain') {
 3208:             foreach my $name ('portfolio','author') {
 3209:                 if ($userenv{$name.'quota'} ne '') {
 3210:                     $oldquota{$name} = $userenv{$name.'quota'};
 3211:                     if ($env{'form.custom_'.$name.'quota'} == 1) {
 3212:                         if ($env{'form.'.$name.'quota'} eq '') {
 3213:                             $newquota{$name} = 0;
 3214:                         } else {
 3215:                             $newquota{$name} = $env{'form.'.$name.'quota'};
 3216:                             $newquota{$name} =~ s/[^\d\.]//g;
 3217:                         }
 3218:                         if ($newquota{$name} != $oldquota{$name}) {
 3219:                             if (&quota_admin($newquota{$name},\%changeHash,$name)) {
 3220:                                 $changed{$name.'quota'} = 1;
 3221:                             }
 3222:                         }
 3223:                     } else {
 3224:                         if (&quota_admin('',\%changeHash,$name)) {
 3225:                             $changed{$name.'quota'} = 1;
 3226:                             $newquota{$name} = $newdefquota{$name};
 3227:                             $newisdefault{$name} = 1;
 3228:                         }
 3229:                     }
 3230:                 } else {
 3231:                     $oldisdefault{$name} = 1;
 3232:                     $oldquota{$name} = $olddefquota{$name};
 3233:                     if ($env{'form.custom_'.$name.'quota'} == 1) {
 3234:                         if ($env{'form.'.$name.'quota'} eq '') {
 3235:                             $newquota{$name} = 0;
 3236:                         } else {
 3237:                             $newquota{$name} = $env{'form.'.$name.'quota'};
 3238:                             $newquota{$name} =~ s/[^\d\.]//g;
 3239:                         }
 3240:                         if (&quota_admin($newquota{$name},\%changeHash,$name)) {
 3241:                             $changed{$name.'quota'} = 1;
 3242:                         }
 3243:                     } else {
 3244:                         $newquota{$name} = $newdefquota{$name};
 3245:                         $newisdefault{$name} = 1;
 3246:                     }
 3247:                 }
 3248:                 if ($oldisdefault{$name}) {
 3249:                     $oldsettingstext{'quota'}{$name} = &get_defaultquota_text($oldsettingstatus{$name});
 3250:                 }  else {
 3251:                     $oldsettingstext{'quota'}{$name} = &mt('custom quota: [_1] MB',$oldquota{$name});
 3252:                 }
 3253:                 if ($newisdefault{$name}) {
 3254:                     $newsettingstext{'quota'}{$name} = &get_defaultquota_text($newsettingstatus{$name});
 3255:                 } else {
 3256:                     $newsettingstext{'quota'}{$name} = &mt('custom quota: [_1] MB',$newquota{$name});
 3257:                 }
 3258:             }
 3259:             &tool_changes('tools',\@usertools,\%oldsettings,\%oldsettingstext,\%userenv,
 3260:                           \%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3261:             if ($env{'form.ccdomain'} eq $env{'request.role.domain'}) {
 3262:                 &tool_changes('requestcourses',\@requestcourses,\%oldsettings,\%oldsettingstext,
 3263:                               \%userenv,\%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3264:                 &tool_changes('requestauthor',\@requestauthor,\%oldsettings,\%oldsettingstext,
 3265:                               \%userenv,\%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3266:             } else {
 3267:                 &tool_changes('reqcrsotherdom',\@requestcourses,\%oldsettings,\%oldsettingstext,
 3268:                               \%userenv,\%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3269:             }
 3270:             if ($userenv{'adhocroles.'.$env{'request.role.domain'}}) {
 3271:                 $changeHash{'adhocroles.'.$env{'request.role.domain'}} = $userenv{'adhocroles.'.$env{'request.role.domain'}};
 3272:             }
 3273:             if (&adhocrole_changes(\%changeHash,\%userenv)) {
 3274:                 $changed{'adhocroles'} = 1;
 3275:                 $oldsettings{'adhocroles'} = $userenv{'adhocroles.'.$env{'request.role.domain'}};
 3276:                 $newsettings{'adhocroles'} = $changeHash{'adhocroles.'.$env{'request.role.domain'}};
 3277:             }
 3278:         }
 3279:         foreach my $item (@userinfo) {
 3280:             if ($env{'form.c'.$item} ne $userenv{$item}) {
 3281:                 $namechanged{$item} = 1;
 3282:             }
 3283:         }
 3284:         foreach my $name ('portfolio','author') {
 3285:             $oldsettings{'quota'}{$name} = &mt('[_1] MB',$oldquota{$name});
 3286:             $newsettings{'quota'}{$name} = &mt('[_1] MB',$newquota{$name});
 3287:         }
 3288:         if ((keys(%namechanged) > 0) || (keys(%changed) > 0)) {
 3289:             my ($chgresult,$namechgresult);
 3290:             if (keys(%changed) > 0) {
 3291:                 $chgresult = 
 3292:                     &Apache::lonnet::put('environment',\%changeHash,
 3293:                                   $env{'form.ccdomain'},$env{'form.ccuname'});
 3294:                 if ($chgresult eq 'ok') {
 3295:                     if (($env{'user.name'} eq $env{'form.ccuname'}) &&
 3296:                         ($env{'user.domain'} eq $env{'form.ccdomain'})) {
 3297:                         my %newenvhash;
 3298:                         foreach my $key (keys(%changed)) {
 3299:                             if (($key eq 'official') || ($key eq 'unofficial')
 3300:                                 || ($key eq 'community') || ($key eq 'textbook')) {
 3301:                                 $newenvhash{'environment.requestcourses.'.$key} =
 3302:                                     $changeHash{'requestcourses.'.$key};
 3303:                                 if ($changeHash{'requestcourses.'.$key}) {
 3304:                                     $newenvhash{'environment.canrequest.'.$key} = 1;
 3305:                                 } else {
 3306:                                     $newenvhash{'environment.canrequest.'.$key} =
 3307:           &Apache::lonnet::usertools_access($env{'user.name'},$env{'user.domain'},
 3308:                                             $key,'reload','requestcourses');
 3309:                                 }
 3310:                             } elsif ($key eq 'requestauthor') {
 3311:                                 $newenvhash{'environment.'.$key} = $changeHash{$key};
 3312:                                 if ($changeHash{$key}) {
 3313:                                     $newenvhash{'environment.canrequest.author'} = 1;
 3314:                                 } else {
 3315:                                     $newenvhash{'environment.canrequest.author'} =
 3316:           &Apache::lonnet::usertools_access($env{'user.name'},$env{'user.domain'},
 3317:                                             $key,'reload','requestauthor');
 3318:                                 }
 3319:                             } elsif ($key eq 'adhocroles') {
 3320:                                 $newenvhash{'adhocroles.'.$env{'request.role.domain'}} =
 3321:                                     $changeHash{'adhocroles.'.$env{'request.role.domain'}};
 3322:                             } elsif ($key ne 'quota') {
 3323:                                 $newenvhash{'environment.tools.'.$key} = 
 3324:                                     $changeHash{'tools.'.$key};
 3325:                                 if ($changeHash{'tools.'.$key} ne '') {
 3326:                                     $newenvhash{'environment.availabletools.'.$key} =
 3327:                                         $changeHash{'tools.'.$key};
 3328:                                 } else {
 3329:                                     $newenvhash{'environment.availabletools.'.$key} =
 3330:           &Apache::lonnet::usertools_access($env{'user.name'},$env{'user.domain'},
 3331:           $key,'reload','tools');
 3332:                                 }
 3333:                             }
 3334:                         }
 3335:                         if (keys(%newenvhash)) {
 3336:                             &Apache::lonnet::appenv(\%newenvhash);
 3337:                         }
 3338:                     }
 3339:                 }
 3340:             }
 3341:             if (keys(%namechanged) > 0) {
 3342:                 foreach my $field (@userinfo) {
 3343:                     $changeHash{$field}  = $env{'form.c'.$field};
 3344:                 }
 3345: # Make the change
 3346:                 $namechgresult =
 3347:                     &Apache::lonnet::modifyuser($env{'form.ccdomain'},
 3348:                         $env{'form.ccuname'},$changeHash{'id'},undef,undef,
 3349:                         $changeHash{'firstname'},$changeHash{'middlename'},
 3350:                         $changeHash{'lastname'},$changeHash{'generation'},
 3351:                         $changeHash{'id'},undef,$changeHash{'permanentemail'},undef,\@userinfo);
 3352:                 %userupdate = (
 3353:                                lastname   => $env{'form.clastname'},
 3354:                                middlename => $env{'form.cmiddlename'},
 3355:                                firstname  => $env{'form.cfirstname'},
 3356:                                generation => $env{'form.cgeneration'},
 3357:                                id         => $env{'form.cid'},
 3358:                              );
 3359:             }
 3360:             if (((keys(%namechanged) > 0) && $namechgresult eq 'ok') || 
 3361:                 ((keys(%changed) > 0) && $chgresult eq 'ok')) {
 3362:             # Tell the user we changed the name
 3363:                 &display_userinfo($r,1,\@disporder,\%canshow,\@requestcourses,
 3364:                                   \@usertools,\@requestauthor,\%userenv,\%changed,\%namechanged,
 3365:                                   \%oldsettings, \%oldsettingstext,\%newsettings,
 3366:                                   \%newsettingstext);
 3367:                 if ($env{'form.cid'} ne $userenv{'id'}) {
 3368:                     &Apache::lonnet::idput($env{'form.ccdomain'},
 3369:                          {$env{'form.ccuname'} => $env{'form.cid'}});
 3370:                     if (($recurseid) &&
 3371:                         (&Apache::lonnet::allowed('mau',$env{'form.ccdomain'}))) {
 3372:                         my $idresult = 
 3373:                             &Apache::lonuserutils::propagate_id_change(
 3374:                                 $env{'form.ccuname'},$env{'form.ccdomain'},
 3375:                                 \%userupdate);
 3376:                         $r->print('<br />'.$idresult.'<br />');
 3377:                     }
 3378:                 }
 3379:                 if (($env{'form.ccdomain'} eq $env{'user.domain'}) && 
 3380:                     ($env{'form.ccuname'} eq $env{'user.name'})) {
 3381:                     my %newenvhash;
 3382:                     foreach my $key (keys(%changeHash)) {
 3383:                         $newenvhash{'environment.'.$key} = $changeHash{$key};
 3384:                     }
 3385:                     &Apache::lonnet::appenv(\%newenvhash);
 3386:                 }
 3387:             } else { # error occurred
 3388:                 $r->print(
 3389:                     '<p class="LC_error">'
 3390:                    .&mt('Unable to successfully change environment for [_1] in domain [_2].',
 3391:                             '"'.$env{'form.ccuname'}.'"',
 3392:                             '"'.$env{'form.ccdomain'}.'"')
 3393:                    .'</p>');
 3394:             }
 3395:         } else { # End of if ($env ... ) logic
 3396:             # They did not want to change the users name, quota, tool availability,
 3397:             # or ability to request creation of courses, 
 3398:             # but we can still tell them what the name and quota and availabilities are  
 3399:             &display_userinfo($r,undef,\@disporder,\%canshow,\@requestcourses,
 3400:                               \@usertools,\@requestauthor,\%userenv,\%changed,\%namechanged,\%oldsettings,
 3401:                               \%oldsettingstext,\%newsettings,\%newsettingstext);
 3402:         }
 3403:         if (@mod_disallowed) {
 3404:             my ($rolestr,$contextname);
 3405:             if (@longroles > 0) {
 3406:                 $rolestr = join(', ',@longroles);
 3407:             } else {
 3408:                 $rolestr = &mt('No roles');
 3409:             }
 3410:             if ($context eq 'course') {
 3411:                 $contextname = 'course';
 3412:             } elsif ($context eq 'author') {
 3413:                 $contextname = 'co-author';
 3414:             }
 3415:             $r->print(&mt('The following fields were not updated: ').'<ul>');
 3416:             my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
 3417:             foreach my $field (@mod_disallowed) {
 3418:                 $r->print('<li>'.$fieldtitles{$field}.'</li>'."\n"); 
 3419:             }
 3420:             $r->print('</ul>');
 3421:             if (@mod_disallowed == 1) {
 3422:                 $r->print(&mt("You do not have the authority to change this field given the user's current set of active/future $contextname roles:"));
 3423:             } else {
 3424:                 $r->print(&mt("You do not have the authority to change these fields given the user's current set of active/future $contextname roles:"));
 3425:             }
 3426:             my $helplink = 'javascript:helpMenu('."'display'".')';
 3427:             $r->print('<span class="LC_cusr_emph">'.$rolestr.'</span><br />'
 3428:                      .&mt('Please contact your [_1]helpdesk[_2] for more information.'
 3429:                          ,'<a href="'.$helplink.'">','</a>')
 3430:                       .'<br />');
 3431:         }
 3432:         $r->print('<span class="LC_warning">'
 3433:                   .$no_forceid_alert
 3434:                   .&Apache::lonuserutils::print_namespacing_alerts($env{'form.ccdomain'},\%alerts,\%curr_rules)
 3435:                   .'</span>');
 3436:     }
 3437:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 3438:     if ($env{'form.action'} eq 'singlestudent') {
 3439:         &enroll_single_student($r,$uhome,$amode,$genpwd,$now,$newuser,$context,
 3440:                                $crstype,$showcredits,$defaultcredits);
 3441:         my $linktext = ($crstype eq 'Community' ?
 3442:             &mt('Enroll Another Member') : &mt('Enroll Another Student'));
 3443:         $r->print(
 3444:             &Apache::lonhtmlcommon::actionbox([
 3445:                 '<a href="javascript:backPage(document.userupdate)">'
 3446:                .($crstype eq 'Community' ? 
 3447:                     &mt('Enroll Another Member') : &mt('Enroll Another Student'))
 3448:                .'</a>']));
 3449:     } else {
 3450:         my @rolechanges = &update_roles($r,$context,$showcredits);
 3451:         if (keys(%namechanged) > 0) {
 3452:             if ($context eq 'course') {
 3453:                 if (@userroles > 0) {
 3454:                     if ((@rolechanges == 0) || 
 3455:                         (!(grep(/^st$/,@rolechanges)))) {
 3456:                         if (grep(/^st$/,@userroles)) {
 3457:                             my $classlistupdated =
 3458:                                 &Apache::lonuserutils::update_classlist($cdom,
 3459:                                               $cnum,$env{'form.ccdomain'},
 3460:                                        $env{'form.ccuname'},\%userupdate);
 3461:                         }
 3462:                     }
 3463:                 }
 3464:             }
 3465:         }
 3466:         my $userinfo = &Apache::loncommon::plainname($env{'form.ccuname'},
 3467:                                                      $env{'form.ccdomain'});
 3468:         if ($env{'form.popup'}) {
 3469:             $r->print('<p><a href="javascript:window.close()">'.&mt('Close window').'</a></p>');
 3470:         } else {
 3471:             $r->print('<br />'.&Apache::lonhtmlcommon::actionbox(['<a href="javascript:backPage(document.userupdate,'."'$env{'form.prevphase'}','modify'".')">'
 3472:                      .&mt('Modify this user: [_1]','<span class="LC_cusr_emph">'.$env{'form.ccuname'}.':'.$env{'form.ccdomain'}.' ('.$userinfo.')</span>').'</a>',
 3473:                      '<a href="javascript:backPage(document.userupdate)">'.&mt('Create/Modify Another User').'</a>']));
 3474:         }
 3475:     }
 3476: }
 3477: 
 3478: sub display_userinfo {
 3479:     my ($r,$changed,$order,$canshow,$requestcourses,$usertools,$requestauthor,
 3480:         $userenv,$changedhash,$namechangedhash,$oldsetting,$oldsettingtext,
 3481:         $newsetting,$newsettingtext) = @_;
 3482:     return unless (ref($order) eq 'ARRAY' &&
 3483:                    ref($canshow) eq 'HASH' && 
 3484:                    ref($requestcourses) eq 'ARRAY' && 
 3485:                    ref($requestauthor) eq 'ARRAY' &&
 3486:                    ref($usertools) eq 'ARRAY' && 
 3487:                    ref($userenv) eq 'HASH' &&
 3488:                    ref($changedhash) eq 'HASH' &&
 3489:                    ref($oldsetting) eq 'HASH' &&
 3490:                    ref($oldsettingtext) eq 'HASH' &&
 3491:                    ref($newsetting) eq 'HASH' &&
 3492:                    ref($newsettingtext) eq 'HASH');
 3493:     my %lt=&Apache::lonlocal::texthash(
 3494:          'ui'             => 'User Information',
 3495:          'uic'            => 'User Information Changed',
 3496:          'firstname'      => 'First Name',
 3497:          'middlename'     => 'Middle Name',
 3498:          'lastname'       => 'Last Name',
 3499:          'generation'     => 'Generation',
 3500:          'id'             => 'Student/Employee ID',
 3501:          'permanentemail' => 'Permanent e-mail address',
 3502:          'portfolioquota' => 'Disk space allocated to portfolio files',
 3503:          'authorquota'    => 'Disk space allocated to Authoring Space',
 3504:          'blog'           => 'Blog Availability',
 3505:          'webdav'         => 'WebDAV Availability',
 3506:          'aboutme'        => 'Personal Information Page Availability',
 3507:          'portfolio'      => 'Portfolio Availability',
 3508:          'official'       => 'Can Request Official Courses',
 3509:          'unofficial'     => 'Can Request Unofficial Courses',
 3510:          'community'      => 'Can Request Communities',
 3511:          'textbook'       => 'Can Request Textbook Courses',
 3512:          'requestauthor'  => 'Can Request Author Role',
 3513:          'adhocroles'     => 'Ad Hoc Roles Selectable via Helpdesk Role',
 3514:          'inststatus'     => "Affiliation",
 3515:          'prvs'           => 'Previous Value:',
 3516:          'chto'           => 'Changed To:'
 3517:     );
 3518:     if ($changed) {
 3519:         $r->print('<h3>'.$lt{'uic'}.'</h3>'.
 3520:                 &Apache::loncommon::start_data_table().
 3521:                 &Apache::loncommon::start_data_table_header_row());
 3522:         $r->print("<th>&nbsp;</th>\n");
 3523:         $r->print('<th><b>'.$lt{'prvs'}.'</b></th>');
 3524:         $r->print('<th><span class="LC_nobreak"><b>'.$lt{'chto'}.'</b></span></th>');
 3525:         $r->print(&Apache::loncommon::end_data_table_header_row());
 3526:         my @userinfo = ('firstname','middlename','lastname','generation','permanentemail','id');
 3527: 
 3528:         foreach my $item (@userinfo) {
 3529:             my $value = $env{'form.c'.$item};
 3530:             #show changes only:
 3531:             unless ($value eq $userenv->{$item}){
 3532:                 $r->print(&Apache::loncommon::start_data_table_row());
 3533:                 $r->print("<td>$lt{$item}</td>\n");
 3534:                 $r->print("<td>".$userenv->{$item}."</td>\n");
 3535:                 $r->print("<td>$value </td>\n");
 3536:                 $r->print(&Apache::loncommon::end_data_table_row());
 3537:             }
 3538:         }
 3539:         foreach my $entry (@{$order}) {
 3540:             if ($canshow->{$entry}) {
 3541:                 if (($entry eq 'requestcourses') || ($entry eq 'reqcrsotherdom') || ($entry eq 'requestauthor')) {
 3542:                     my @items;
 3543:                     if ($entry eq 'requestauthor') {
 3544:                         @items = ($entry);
 3545:                     } else {
 3546:                         @items = @{$requestcourses};
 3547:                     }
 3548:                     foreach my $item (@items) {
 3549:                         if (($newsetting->{$item} ne $oldsetting->{$item}) || 
 3550:                             ($newsettingtext->{$item} ne $oldsettingtext->{$item})) {
 3551:                             $r->print(&Apache::loncommon::start_data_table_row()."\n");  
 3552:                             $r->print("<td>$lt{$item}</td>\n");
 3553:                             $r->print("<td>".$oldsetting->{$item});
 3554:                             if ($oldsettingtext->{$item}) {
 3555:                                 if ($oldsetting->{$item}) {
 3556:                                     $r->print(' -- ');
 3557:                                 }
 3558:                                 $r->print($oldsettingtext->{$item});
 3559:                             }
 3560:                             $r->print("</td>\n");
 3561:                             $r->print("<td>".$newsetting->{$item});
 3562:                             if ($newsettingtext->{$item}) {
 3563:                                 if ($newsetting->{$item}) {
 3564:                                     $r->print(' -- ');
 3565:                                 }
 3566:                                 $r->print($newsettingtext->{$item});
 3567:                             }
 3568:                             $r->print("</td>\n");
 3569:                             $r->print(&Apache::loncommon::end_data_table_row()."\n");
 3570:                         }
 3571:                     }
 3572:                 } elsif ($entry eq 'tools') {
 3573:                     foreach my $item (@{$usertools}) {
 3574:                         if ($newsetting->{$item} ne $oldsetting->{$item}) {
 3575:                             $r->print(&Apache::loncommon::start_data_table_row()."\n");
 3576:                             $r->print("<td>$lt{$item}</td>\n");
 3577:                             $r->print("<td>".$oldsetting->{$item}.' '.$oldsettingtext->{$item}."</td>\n");
 3578:                             $r->print("<td>".$newsetting->{$item}.' '.$newsettingtext->{$item}."</td>\n");
 3579:                             $r->print(&Apache::loncommon::end_data_table_row()."\n");
 3580:                         }
 3581:                     }
 3582:                 } elsif ($entry eq 'quota') {
 3583:                     if ((ref($oldsetting->{$entry}) eq 'HASH') && (ref($oldsettingtext->{$entry}) eq 'HASH') &&
 3584:                         (ref($newsetting->{$entry}) eq 'HASH') && (ref($newsettingtext->{$entry}) eq 'HASH')) {
 3585:                         foreach my $name ('portfolio','author') {
 3586:                             if ($newsetting->{$entry}->{$name} ne $oldsetting->{$entry}->{$name}) {
 3587:                                 $r->print(&Apache::loncommon::start_data_table_row()."\n");
 3588:                                 $r->print("<td>$lt{$name.$entry}</td>\n");
 3589:                                 $r->print("<td>".$oldsettingtext->{$entry}->{$name}."</td>\n");
 3590:                                 $r->print("<td>".$newsettingtext->{$entry}->{$name}."</td>\n");
 3591:                                 $r->print(&Apache::loncommon::end_data_table_row()."\n");
 3592:                             }
 3593:                         }
 3594:                     }
 3595:                 } else {
 3596:                     if ($newsetting->{$entry} ne $oldsetting->{$entry}) {
 3597:                         $r->print(&Apache::loncommon::start_data_table_row()."\n");
 3598:                         $r->print("<td>$lt{$entry}</td>\n");
 3599:                         $r->print("<td>".$oldsetting->{$entry}.' '.$oldsettingtext->{$entry}."</td>\n");
 3600:                         $r->print("<td>".$newsetting->{$entry}.' '.$newsettingtext->{$entry}."</td>\n");
 3601:                         $r->print(&Apache::loncommon::end_data_table_row()."\n");
 3602:                     }
 3603:                 }
 3604:             }
 3605:         }
 3606:         $r->print(&Apache::loncommon::end_data_table().'<br />');
 3607:     } else {
 3608:         $r->print('<h3>'.$lt{'ui'}.'</h3>'.
 3609:                   '<p>'.&mt('No changes made to user information').'</p>');
 3610:     }
 3611:     return;
 3612: }
 3613: 
 3614: sub tool_changes {
 3615:     my ($context,$usertools,$oldaccess,$oldaccesstext,$userenv,$changeHash,
 3616:         $changed,$newaccess,$newaccesstext) = @_;
 3617:     if (!((ref($usertools) eq 'ARRAY') && (ref($oldaccess) eq 'HASH') &&
 3618:           (ref($oldaccesstext) eq 'HASH') && (ref($userenv) eq 'HASH') &&
 3619:           (ref($changeHash) eq 'HASH') && (ref($changed) eq 'HASH') &&
 3620:           (ref($newaccess) eq 'HASH') && (ref($newaccesstext) eq 'HASH'))) {
 3621:         return;
 3622:     }
 3623:     my %reqdisplay = &requestchange_display();
 3624:     if ($context eq 'reqcrsotherdom') {
 3625:         my @options = ('approval','validate','autolimit');
 3626:         my $optregex = join('|',@options);
 3627:         my $cdom = $env{'request.role.domain'};
 3628:         foreach my $tool (@{$usertools}) {
 3629:             $oldaccesstext->{$tool} = &mt("availability set to 'off'");
 3630:             $newaccesstext->{$tool} = $oldaccesstext->{$tool};
 3631:             $changeHash->{$context.'.'.$tool} = $userenv->{$context.'.'.$tool};
 3632:             my ($newop,$limit);
 3633:             if ($env{'form.'.$context.'_'.$tool}) {
 3634:                 $newop = $env{'form.'.$context.'_'.$tool};
 3635:                 if ($newop eq 'autolimit') {
 3636:                     $limit = $env{'form.'.$context.'_'.$tool.'_limit'};
 3637:                     $limit =~ s/\D+//g;
 3638:                     $newop .= '='.$limit;
 3639:                 }
 3640:             }
 3641:             if ($userenv->{$context.'.'.$tool} eq '') {
 3642:                 if ($newop) {
 3643:                     $changed->{$tool}=&tool_admin($tool,$cdom.':'.$newop,
 3644:                                                   $changeHash,$context);
 3645:                     if ($changed->{$tool}) {
 3646:                         if ($newop =~ /^autolimit/) {
 3647:                             if ($limit) {
 3648:                                 $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3649:                             } else {
 3650:                                 $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3651:                             }
 3652:                         } else {
 3653:                             $newaccesstext->{$tool} = $reqdisplay{$newop};
 3654:                         }
 3655:                     } else {
 3656:                         $newaccesstext->{$tool} = $oldaccesstext->{$tool};
 3657:                     }
 3658:                 }
 3659:             } else {
 3660:                 my @curr = split(',',$userenv->{$context.'.'.$tool});
 3661:                 my @new;
 3662:                 my $changedoms;
 3663:                 foreach my $req (@curr) {
 3664:                     if ($req =~ /^\Q$cdom\E\:($optregex\=?\d*)$/) {
 3665:                         my $oldop = $1;
 3666:                         if ($oldop =~ /^autolimit=(\d*)/) {
 3667:                             my $limit = $1;
 3668:                             if ($limit) {
 3669:                                 $oldaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3670:                             } else {
 3671:                                 $oldaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3672:                             }
 3673:                         } else {
 3674:                             $oldaccesstext->{$tool} = $reqdisplay{$oldop};
 3675:                         }
 3676:                         if ($oldop ne $newop) {
 3677:                             $changedoms = 1;
 3678:                             foreach my $item (@curr) {
 3679:                                 my ($reqdom,$option) = split(':',$item);
 3680:                                 unless ($reqdom eq $cdom) {
 3681:                                     push(@new,$item);
 3682:                                 }
 3683:                             }
 3684:                             if ($newop) {
 3685:                                 push(@new,$cdom.':'.$newop);
 3686:                             }
 3687:                             @new = sort(@new);
 3688:                         }
 3689:                         last;
 3690:                     }
 3691:                 }
 3692:                 if ((!$changedoms) && ($newop)) {
 3693:                     $changedoms = 1;
 3694:                     @new = sort(@curr,$cdom.':'.$newop);
 3695:                 }
 3696:                 if ($changedoms) {
 3697:                     my $newdomstr;
 3698:                     if (@new) {
 3699:                         $newdomstr = join(',',@new);
 3700:                     }
 3701:                     $changed->{$tool}=&tool_admin($tool,$newdomstr,$changeHash,
 3702:                                                   $context);
 3703:                     if ($changed->{$tool}) {
 3704:                         if ($env{'form.'.$context.'_'.$tool}) {
 3705:                             if ($env{'form.'.$context.'_'.$tool} eq 'autolimit') {
 3706:                                 my $limit = $env{'form.'.$context.'_'.$tool.'_limit'};
 3707:                                 $limit =~ s/\D+//g;
 3708:                                 if ($limit) {
 3709:                                     $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3710:                                 } else {
 3711:                                     $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3712:                                 }
 3713:                             } else {
 3714:                                 $newaccesstext->{$tool} = $reqdisplay{$env{'form.'.$context.'_'.$tool}};
 3715:                             }
 3716:                         } else {
 3717:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3718:                         }
 3719:                     }
 3720:                 }
 3721:             }
 3722:         }
 3723:         return;
 3724:     }
 3725:     foreach my $tool (@{$usertools}) {
 3726:         my ($newval,$limit,$envkey);
 3727:         $envkey = $context.'.'.$tool;
 3728:         if ($context eq 'requestcourses') {
 3729:             $newval = $env{'form.crsreq_'.$tool};
 3730:             if ($newval eq 'autolimit') {
 3731:                 $limit = $env{'form.crsreq_'.$tool.'_limit'};
 3732:                 $limit =~ s/\D+//g;
 3733:                 $newval .= '='.$limit;
 3734:             }
 3735:         } elsif ($context eq 'requestauthor') {
 3736:             $newval = $env{'form.'.$context};
 3737:             $envkey = $context;
 3738:         } else {
 3739:             $newval = $env{'form.'.$context.'_'.$tool};
 3740:         }
 3741:         if ($userenv->{$envkey} ne '') {
 3742:             $oldaccess->{$tool} = &mt('custom');
 3743:             if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 3744:                 if ($userenv->{$envkey} =~ /^autolimit=(\d*)$/) {
 3745:                     my $currlimit = $1;
 3746:                     if ($currlimit eq '') {
 3747:                         $oldaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3748:                     } else {
 3749:                         $oldaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$currlimit);
 3750:                     }
 3751:                 } elsif ($userenv->{$envkey}) {
 3752:                     $oldaccesstext->{$tool} = $reqdisplay{$userenv->{$envkey}};
 3753:                 } else {
 3754:                     $oldaccesstext->{$tool} = &mt("availability set to 'off'");
 3755:                 }
 3756:             } else {
 3757:                 if ($userenv->{$envkey}) {
 3758:                     $oldaccesstext->{$tool} = &mt("availability set to 'on'");
 3759:                 } else {
 3760:                     $oldaccesstext->{$tool} = &mt("availability set to 'off'");
 3761:                 }
 3762:             }
 3763:             $changeHash->{$envkey} = $userenv->{$envkey};
 3764:             if ($env{'form.custom'.$tool} == 1) {
 3765:                 if ($newval ne $userenv->{$envkey}) {
 3766:                     $changed->{$tool} = &tool_admin($tool,$newval,$changeHash,
 3767:                                                     $context);
 3768:                     if ($changed->{$tool}) {
 3769:                         $newaccess->{$tool} = &mt('custom');
 3770:                         if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 3771:                             if ($newval =~ /^autolimit/) {
 3772:                                 if ($limit) {
 3773:                                     $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3774:                                 } else {
 3775:                                     $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3776:                                 }
 3777:                             } elsif ($newval) {
 3778:                                 $newaccesstext->{$tool} = $reqdisplay{$newval};
 3779:                             } else {
 3780:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3781:                             }
 3782:                         } else {
 3783:                             if ($newval) {
 3784:                                 $newaccesstext->{$tool} = &mt("availability set to 'on'");
 3785:                             } else {
 3786:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3787:                             }
 3788:                         }
 3789:                     } else {
 3790:                         $newaccess->{$tool} = $oldaccess->{$tool};
 3791:                         if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 3792:                             if ($newval =~ /^autolimit/) {
 3793:                                 if ($limit) {
 3794:                                     $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3795:                                 } else {
 3796:                                     $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3797:                                 }
 3798:                             } elsif ($newval) {
 3799:                                 $newaccesstext->{$tool} = $reqdisplay{$newval};
 3800:                             } else {
 3801:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3802:                             }
 3803:                         } else {
 3804:                             if ($userenv->{$context.'.'.$tool}) {
 3805:                                 $newaccesstext->{$tool} = &mt("availability set to 'on'");
 3806:                             } else {
 3807:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3808:                             }
 3809:                         }
 3810:                     }
 3811:                 } else {
 3812:                     $newaccess->{$tool} = $oldaccess->{$tool};
 3813:                     $newaccesstext->{$tool} = $oldaccesstext->{$tool};
 3814:                 }
 3815:             } else {
 3816:                 $changed->{$tool} = &tool_admin($tool,'',$changeHash,$context);
 3817:                 if ($changed->{$tool}) {
 3818:                     $newaccess->{$tool} = &mt('default');
 3819:                 } else {
 3820:                     $newaccess->{$tool} = $oldaccess->{$tool};
 3821:                     if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 3822:                         if ($newval =~ /^autolimit/) {
 3823:                             if ($limit) {
 3824:                                 $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3825:                             } else {
 3826:                                 $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3827:                             }
 3828:                         } elsif ($newval) {
 3829:                             $newaccesstext->{$tool} = $reqdisplay{$newval};
 3830:                         } else {
 3831:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3832:                         }
 3833:                     } else {
 3834:                         if ($userenv->{$context.'.'.$tool}) {
 3835:                             $newaccesstext->{$tool} = &mt("availability set to 'on'");
 3836:                         } else {
 3837:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3838:                         }
 3839:                     }
 3840:                 }
 3841:             }
 3842:         } else {
 3843:             $oldaccess->{$tool} = &mt('default');
 3844:             if ($env{'form.custom'.$tool} == 1) {
 3845:                 $changed->{$tool} = &tool_admin($tool,$newval,$changeHash,
 3846:                                                 $context);
 3847:                 if ($changed->{$tool}) {
 3848:                     $newaccess->{$tool} = &mt('custom');
 3849:                     if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 3850:                         if ($newval =~ /^autolimit/) {
 3851:                             if ($limit) {
 3852:                                 $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3853:                             } else {
 3854:                                 $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3855:                             }
 3856:                         } elsif ($newval) {
 3857:                             $newaccesstext->{$tool} = $reqdisplay{$newval};
 3858:                         } else {
 3859:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3860:                         }
 3861:                     } else {
 3862:                         if ($newval) {
 3863:                             $newaccesstext->{$tool} = &mt("availability set to 'on'");
 3864:                         } else {
 3865:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3866:                         }
 3867:                     }
 3868:                 } else {
 3869:                     $newaccess->{$tool} = $oldaccess->{$tool};
 3870:                 }
 3871:             } else {
 3872:                 $newaccess->{$tool} = $oldaccess->{$tool};
 3873:             }
 3874:         }
 3875:     }
 3876:     return;
 3877: }
 3878: 
 3879: sub adhocrole_changes {
 3880:     my ($changehashref,$userenv) = @_;
 3881:     my @adds = &Apache::loncommon::get_env_multiple('form.adhocroleadd');
 3882:     my @dels = &Apache::loncommon::get_env_multiple('form.adhocroledel');
 3883:     my (@saved,@added,@alladhoc,$changed);
 3884:     my $adhoc_key = 'adhocroles.'.$env{'request.role.domain'};
 3885:     if (!$env{'form.makeuser'}) {
 3886:         if (ref($userenv) eq 'HASH') {
 3887:             my @current;
 3888:             if ($userenv->{$adhoc_key}) {
 3889:                 @current = split(/,/,$userenv->{$adhoc_key});
 3890:                 if (@dels) {
 3891:                     foreach my $curr (@current) {
 3892:                         next if ($curr eq '');
 3893:                         unless (grep(/\Q$curr\E$/,@dels)) {
 3894:                             push(@saved,$curr);
 3895:                         }
 3896:                     }
 3897:                     $changed = 1;
 3898:                 } else {
 3899:                     @saved = @current;
 3900:                 }
 3901:             }
 3902:         }
 3903:     }
 3904:     if (@adds) {
 3905:         my $confname = &Apache::lonnet::get_domainconfiguser($env{'request.role.domain'});
 3906:         my %existing=&Apache::lonnet::dump('roles',$env{'request.role.domain'},
 3907:                                            $confname,'rolesdef_');
 3908:         foreach my $poss (@adds) {
 3909:             if (exists($existing{'rolesdef_'.$poss})) {
 3910:                 push(@added,$poss);
 3911:                 $changed = 1;
 3912:             }
 3913:         }
 3914:     }
 3915:     if (@added) {
 3916:         if (@saved) {
 3917:             foreach my $add (@added) {
 3918:                 unless (grep(/^\Q$add\E$/,@saved)) {
 3919:                     push(@alladhoc,$add);
 3920:                 }
 3921:             }
 3922:         } else {
 3923:             push(@alladhoc,@added);
 3924:         }
 3925:     }
 3926:     if (@saved) {
 3927:         push(@alladhoc,@saved);
 3928:     }
 3929:     if (@alladhoc) {
 3930:         my $adhocstr = join(',',sort(@alladhoc));
 3931:         $changehashref->{$adhoc_key} = $adhocstr;
 3932:     } elsif (@dels) {
 3933:         &Apache::lonnet::del('environment',[$adhoc_key],$env{'form.ccdomain'},$env{'form.ccuname'});
 3934:         delete($changehashref->{$adhoc_key});
 3935:         if (($env{'form.ccdomain'} eq $env{'user.domain'}) &&
 3936:             ($env{'form.ccuname'} eq $env{'user.name'})) {
 3937:             &Apache::lonnet::delenv($adhoc_key);
 3938:         }
 3939:     }
 3940:     return $changed;
 3941: }
 3942: 
 3943: sub update_roles {
 3944:     my ($r,$context,$showcredits) = @_;
 3945:     my $now=time;
 3946:     my @rolechanges;
 3947:     my %disallowed;
 3948:     $r->print('<h3>'.&mt('Modifying Roles').'</h3>');
 3949:     foreach my $key (keys(%env)) {
 3950: 	next if (! $env{$key});
 3951:         next if ($key eq 'form.action');
 3952: 	# Revoke roles
 3953: 	if ($key=~/^form\.rev/) {
 3954: 	    if ($key=~/^form\.rev\:([^\_]+)\_([^\_\.]+)$/) {
 3955: # Revoke standard role
 3956: 		my ($scope,$role) = ($1,$2);
 3957: 		my $result =
 3958: 		    &Apache::lonnet::revokerole($env{'form.ccdomain'},
 3959: 						$env{'form.ccuname'},
 3960: 						$scope,$role,'','',$context);
 3961:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
 3962:                             &mt('Revoking [_1] in [_2]',
 3963:                                 &Apache::lonnet::plaintext($role),
 3964:                                 &Apache::loncommon::show_role_extent($scope,$context,$role)),
 3965:                                 $result ne "ok").'<br />');
 3966:                 if ($result ne "ok") {
 3967:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 3968:                 }
 3969: 		if ($role eq 'st') {
 3970: 		    my $result = 
 3971:                         &Apache::lonuserutils::classlist_drop($scope,
 3972:                             $env{'form.ccuname'},$env{'form.ccdomain'},
 3973: 			    $now);
 3974:                     $r->print(&Apache::lonhtmlcommon::confirm_success($result));
 3975: 		}
 3976:                 if (!grep(/^\Q$role\E$/,@rolechanges)) {
 3977:                     push(@rolechanges,$role);
 3978:                 }
 3979: 	    }
 3980: 	    if ($key=~m{^form\.rev\:([^_]+)_cr\.cr/($match_domain)/($match_username)/(\w+)$}s) {
 3981: # Revoke custom role
 3982:                 my $result = &Apache::lonnet::revokecustomrole(
 3983:                     $env{'form.ccdomain'},$env{'form.ccuname'},$1,$2,$3,$4,'','',$context);
 3984:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
 3985:                             &mt('Revoking custom role [_1] by [_2] in [_3]',
 3986:                                 $4,$3.':'.$2,&Apache::loncommon::show_role_extent($1,$context,'cr')),
 3987:                             $result ne 'ok').'<br />');
 3988:                 if ($result ne "ok") {
 3989:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 3990:                 }
 3991:                 if (!grep(/^cr$/,@rolechanges)) {
 3992:                     push(@rolechanges,'cr');
 3993:                 }
 3994: 	    }
 3995: 	} elsif ($key=~/^form\.del/) {
 3996: 	    if ($key=~/^form\.del\:([^\_]+)\_([^\_\.]+)$/) {
 3997: # Delete standard role
 3998: 		my ($scope,$role) = ($1,$2);
 3999: 		my $result =
 4000: 		    &Apache::lonnet::assignrole($env{'form.ccdomain'},
 4001: 						$env{'form.ccuname'},
 4002: 						$scope,$role,$now,0,1,'',
 4003:                                                 $context);
 4004:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
 4005:                             &mt('Deleting [_1] in [_2]',
 4006:                                 &Apache::lonnet::plaintext($role),
 4007:                                 &Apache::loncommon::show_role_extent($scope,$context,$role)),
 4008:                             $result ne 'ok').'<br />');
 4009:                 if ($result ne "ok") {
 4010:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 4011:                 }
 4012: 
 4013: 		if ($role eq 'st') {
 4014: 		    my $result = 
 4015:                         &Apache::lonuserutils::classlist_drop($scope,
 4016:                             $env{'form.ccuname'},$env{'form.ccdomain'},
 4017: 			    $now);
 4018: 		    $r->print(&Apache::lonhtmlcommon::confirm_success($result));
 4019: 		}
 4020:                 if (!grep(/^\Q$role\E$/,@rolechanges)) {
 4021:                     push(@rolechanges,$role);
 4022:                 }
 4023:             }
 4024: 	    if ($key=~m{^form\.del\:([^_]+)_cr\.cr/($match_domain)/($match_username)/(\w+)$}) {
 4025:                 my ($url,$rdom,$rnam,$rolename) = ($1,$2,$3,$4);
 4026: # Delete custom role
 4027:                 my $result =
 4028:                     &Apache::lonnet::assigncustomrole($env{'form.ccdomain'},
 4029:                         $env{'form.ccuname'},$url,$rdom,$rnam,$rolename,$now,
 4030:                         0,1,$context);
 4031:                 $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('Deleting custom role [_1] by [_2] in [_3]',
 4032:                       $rolename,$rnam.':'.$rdom,&Apache::loncommon::show_role_extent($1,$context,'cr')),
 4033:                       $result ne "ok").'<br />');
 4034:                 if ($result ne "ok") {
 4035:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 4036:                 }
 4037: 
 4038:                 if (!grep(/^cr$/,@rolechanges)) {
 4039:                     push(@rolechanges,'cr');
 4040:                 }
 4041:             }
 4042: 	} elsif ($key=~/^form\.ren/) {
 4043:             my $udom = $env{'form.ccdomain'};
 4044:             my $uname = $env{'form.ccuname'};
 4045: # Re-enable standard role
 4046: 	    if ($key=~/^form\.ren\:([^\_]+)\_([^\_\.]+)$/) {
 4047:                 my $url = $1;
 4048:                 my $role = $2;
 4049:                 my $logmsg;
 4050:                 my $output;
 4051:                 if ($role eq 'st') {
 4052:                     if ($url =~ m-^/($match_domain)/($match_courseid)/?(\w*)$-) {
 4053:                         my ($cdom,$cnum,$csec) = ($1,$2,$3);
 4054:                         my $credits;
 4055:                         if ($showcredits) {
 4056:                             my $defaultcredits = 
 4057:                                 &Apache::lonuserutils::get_defaultcredits($cdom,$cnum);
 4058:                             $credits = &get_user_credits($defaultcredits,$cdom,$cnum);
 4059:                         }
 4060:                         my $result = &Apache::loncommon::commit_studentrole(\$logmsg,$udom,$uname,$url,$role,$now,0,$cdom,$cnum,$csec,$context,$credits);
 4061:                         if (($result =~ /^error/) || ($result eq 'not_in_class') || ($result eq 'unknown_course') || ($result eq 'refused')) {
 4062:                             if ($result eq 'refused' && $logmsg) {
 4063:                                 $output = $logmsg;
 4064:                             } else { 
 4065:                                 $output = &mt('Error: [_1]',$result)."\n";
 4066:                             }
 4067:                         } else {
 4068:                             $output = &Apache::lonhtmlcommon::confirm_success(&mt('Assigning [_1] in [_2] starting [_3]',
 4069:                                         &Apache::lonnet::plaintext($role),
 4070:                                         &Apache::loncommon::show_role_extent($url,$context,'st'),
 4071:                                         &Apache::lonlocal::locallocaltime($now))).'<br />'.$logmsg.'<br />';
 4072:                         }
 4073:                     }
 4074:                 } else {
 4075: 		    my $result=&Apache::lonnet::assignrole($env{'form.ccdomain'},
 4076:                                $env{'form.ccuname'},$url,$role,0,$now,'','',
 4077:                                $context);
 4078:                         $output = &Apache::lonhtmlcommon::confirm_success(&mt('Re-enabling [_1] in [_2]',
 4079:                                         &Apache::lonnet::plaintext($role),
 4080:                                         &Apache::loncommon::show_role_extent($url,$context,$role)),$result ne "ok").'<br />';
 4081:                     if ($result ne "ok") {
 4082:                         $output .= &mt('Error: [_1]',$result).'<br />';
 4083:                     }
 4084:                 }
 4085:                 $r->print($output);
 4086:                 if (!grep(/^\Q$role\E$/,@rolechanges)) {
 4087:                     push(@rolechanges,$role);
 4088:                 }
 4089: 	    }
 4090: # Re-enable custom role
 4091: 	    if ($key=~m{^form\.ren\:([^_]+)_cr\.cr/($match_domain)/($match_username)/(\w+)$}) {
 4092:                 my ($url,$rdom,$rnam,$rolename) = ($1,$2,$3,$4);
 4093:                 my $result = &Apache::lonnet::assigncustomrole(
 4094:                                $env{'form.ccdomain'}, $env{'form.ccuname'},
 4095:                                $url,$rdom,$rnam,$rolename,0,$now,undef,$context);
 4096:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
 4097:                     &mt('Re-enabling custom role [_1] by [_2] in [_3]',
 4098:                         $rolename,$rnam.':'.$rdom,&Apache::loncommon::show_role_extent($1,$context,'cr')),
 4099:                     $result ne "ok").'<br />');
 4100:                 if ($result ne "ok") {
 4101:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 4102:                 }
 4103:                 if (!grep(/^cr$/,@rolechanges)) {
 4104:                     push(@rolechanges,'cr');
 4105:                 }
 4106:             }
 4107: 	} elsif ($key=~/^form\.act/) {
 4108:             my $udom = $env{'form.ccdomain'};
 4109:             my $uname = $env{'form.ccuname'};
 4110: 	    if ($key=~/^form\.act\_($match_domain)\_($match_courseid)\_cr_cr_($match_domain)_($match_username)_([^\_]+)$/) {
 4111:                 # Activate a custom role
 4112: 		my ($one,$two,$three,$four,$five)=($1,$2,$3,$4,$5);
 4113: 		my $url='/'.$one.'/'.$two;
 4114: 		my $full=$one.'_'.$two.'_cr_cr_'.$three.'_'.$four.'_'.$five;
 4115: 
 4116:                 my $start = ( $env{'form.start_'.$full} ?
 4117:                               $env{'form.start_'.$full} :
 4118:                               $now );
 4119:                 my $end   = ( $env{'form.end_'.$full} ?
 4120:                               $env{'form.end_'.$full} :
 4121:                               0 );
 4122:                                                                                      
 4123:                 # split multiple sections
 4124:                 my %sections = ();
 4125:                 my $num_sections = &build_roles($env{'form.sec_'.$full},\%sections,$5);
 4126:                 if ($num_sections == 0) {
 4127:                     $r->print(&Apache::loncommon::commit_customrole($udom,$uname,$url,$three,$four,$five,$start,$end,$context));
 4128:                 } else {
 4129: 		    my %curr_groups =
 4130: 			&Apache::longroup::coursegroups($one,$two);
 4131:                     foreach my $sec (sort {$a cmp $b} keys(%sections)) {
 4132:                         if (($sec eq 'none') || ($sec eq 'all') || 
 4133:                             exists($curr_groups{$sec})) {
 4134:                             $disallowed{$sec} = $url;
 4135:                             next;
 4136:                         }
 4137:                         my $securl = $url.'/'.$sec;
 4138: 		        $r->print(&Apache::loncommon::commit_customrole($udom,$uname,$securl,$three,$four,$five,$start,$end,$context));
 4139:                     }
 4140:                 }
 4141:                 if (!grep(/^cr$/,@rolechanges)) {
 4142:                     push(@rolechanges,'cr');
 4143:                 }
 4144: 	    } elsif ($key=~/^form\.act\_($match_domain)\_($match_name)\_([^\_]+)$/) {
 4145: 		# Activate roles for sections with 3 id numbers
 4146: 		# set start, end times, and the url for the class
 4147: 		my ($one,$two,$three)=($1,$2,$3);
 4148: 		my $start = ( $env{'form.start_'.$one.'_'.$two.'_'.$three} ? 
 4149: 			      $env{'form.start_'.$one.'_'.$two.'_'.$three} : 
 4150: 			      $now );
 4151: 		my $end   = ( $env{'form.end_'.$one.'_'.$two.'_'.$three} ? 
 4152: 			      $env{'form.end_'.$one.'_'.$two.'_'.$three} :
 4153: 			      0 );
 4154: 		my $url='/'.$one.'/'.$two;
 4155:                 my $type = 'three';
 4156:                 # split multiple sections
 4157:                 my %sections = ();
 4158:                 my $num_sections = &build_roles($env{'form.sec_'.$one.'_'.$two.'_'.$three},\%sections,$three);
 4159:                 my $credits;
 4160:                 if ($three eq 'st') {
 4161:                     if ($showcredits) { 
 4162:                         my $defaultcredits = 
 4163:                             &Apache::lonuserutils::get_defaultcredits($one,$two);
 4164:                         $credits = $env{'form.credits_'.$one.'_'.$two.'_'.$three};
 4165:                         $credits =~ s/[^\d\.]//g;
 4166:                         if ($credits eq $defaultcredits) {
 4167:                             undef($credits);
 4168:                         }
 4169:                     }
 4170:                 }
 4171:                 if ($num_sections == 0) {
 4172:                     $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$three,$start,$end,$one,$two,'',$context,$credits));
 4173:                 } else {
 4174:                     my %curr_groups = 
 4175: 			&Apache::longroup::coursegroups($one,$two);
 4176:                     my $emptysec = 0;
 4177:                     foreach my $sec (sort {$a cmp $b} keys(%sections)) {
 4178:                         $sec =~ s/\W//g;
 4179:                         if ($sec ne '') {
 4180:                             if (($sec eq 'none') || ($sec eq 'all') || 
 4181:                                 exists($curr_groups{$sec})) {
 4182:                                 $disallowed{$sec} = $url;
 4183:                                 next;
 4184:                             }
 4185:                             my $securl = $url.'/'.$sec;
 4186:                             $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$securl,$three,$start,$end,$one,$two,$sec,$context,$credits));
 4187:                         } else {
 4188:                             $emptysec = 1;
 4189:                         }
 4190:                     }
 4191:                     if ($emptysec) {
 4192:                         $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$three,$start,$end,$one,$two,'',$context,$credits));
 4193:                     }
 4194:                 }
 4195:                 if (!grep(/^\Q$three\E$/,@rolechanges)) {
 4196:                     push(@rolechanges,$three);
 4197:                 }
 4198: 	    } elsif ($key=~/^form\.act\_([^\_]+)\_([^\_]+)$/) {
 4199: 		# Activate roles for sections with two id numbers
 4200: 		# set start, end times, and the url for the class
 4201: 		my $start = ( $env{'form.start_'.$1.'_'.$2} ? 
 4202: 			      $env{'form.start_'.$1.'_'.$2} : 
 4203: 			      $now );
 4204: 		my $end   = ( $env{'form.end_'.$1.'_'.$2} ? 
 4205: 			      $env{'form.end_'.$1.'_'.$2} :
 4206: 			      0 );
 4207:                 my $one = $1;
 4208:                 my $two = $2;
 4209: 		my $url='/'.$one.'/';
 4210:                 # split multiple sections
 4211:                 my %sections = ();
 4212:                 my $num_sections = &build_roles($env{'form.sec_'.$one.'_'.$two},\%sections,$two);
 4213:                 if ($num_sections == 0) {
 4214:                     $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$two,$start,$end,$one,undef,'',$context));
 4215:                 } else {
 4216:                     my $emptysec = 0;
 4217:                     foreach my $sec (sort {$a cmp $b} keys(%sections)) {
 4218:                         if ($sec ne '') {
 4219:                             my $securl = $url.'/'.$sec;
 4220:                             $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$securl,$two,$start,$end,$one,undef,$sec,$context));
 4221:                         } else {
 4222:                             $emptysec = 1;
 4223:                         }
 4224:                     }
 4225:                     if ($emptysec) {
 4226:                         $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$two,$start,$end,$one,undef,'',$context));
 4227:                     }
 4228:                 }
 4229:                 if (!grep(/^\Q$two\E$/,@rolechanges)) {
 4230:                     push(@rolechanges,$two);
 4231:                 }
 4232: 	    } else {
 4233: 		$r->print('<p><span class="LC_error">'.&mt('ERROR').': '.&mt('Unknown command').' <tt>'.$key.'</tt></span></p><br />');
 4234:             }
 4235:             foreach my $key (sort(keys(%disallowed))) {
 4236:                 $r->print('<p class="LC_warning">');
 4237:                 if (($key eq 'none') || ($key eq 'all')) {  
 4238:                     $r->print(&mt('[_1] may not be used as the name for a section, as it is a reserved word.','<tt>'.$key.'</tt>'));
 4239:                 } else {
 4240:                     $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>'));
 4241:                 }
 4242:                 $r->print('</p><p>'
 4243:                          .&mt('Please [_1]go back[_2] and choose a different section name.'
 4244:                              ,'<a href="javascript:history.go(-1)'
 4245:                              ,'</a>')
 4246:                          .'</p><br />'
 4247:                 );
 4248:             }
 4249: 	}
 4250:     } # End of foreach (keys(%env))
 4251: # Flush the course logs so reverse user roles immediately updated
 4252:     $r->register_cleanup(\&Apache::lonnet::flushcourselogs);
 4253:     if (@rolechanges == 0) {
 4254:         $r->print('<p>'.&mt('No roles to modify').'</p>');
 4255:     }
 4256:     return @rolechanges;
 4257: }
 4258: 
 4259: sub get_user_credits {
 4260:     my ($uname,$udom,$defaultcredits,$cdom,$cnum) = @_;
 4261:     if ($cdom eq '' || $cnum eq '') {
 4262:         return unless ($env{'request.course.id'});
 4263:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4264:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4265:     }
 4266:     my $credits;
 4267:     my %currhash =
 4268:         &Apache::lonnet::get('classlist',[$uname.':'.$udom],$cdom,$cnum);
 4269:     if (keys(%currhash) > 0) {
 4270:         my @items = split(/:/,$currhash{$uname.':'.$udom});
 4271:         my $crdidx = &Apache::loncoursedata::CL_CREDITS() - 3;
 4272:         $credits = $items[$crdidx];
 4273:         $credits =~ s/[^\d\.]//g;
 4274:     }
 4275:     if ($credits eq $defaultcredits) {
 4276:         undef($credits);
 4277:     }
 4278:     return $credits;
 4279: }
 4280: 
 4281: sub enroll_single_student {
 4282:     my ($r,$uhome,$amode,$genpwd,$now,$newuser,$context,$crstype,
 4283:         $showcredits,$defaultcredits) = @_;
 4284:     $r->print('<h3>');
 4285:     if ($crstype eq 'Community') {
 4286:         $r->print(&mt('Enrolling Member'));
 4287:     } else {
 4288:         $r->print(&mt('Enrolling Student'));
 4289:     }
 4290:     $r->print('</h3>');
 4291: 
 4292:     # Remove non alphanumeric values from section
 4293:     $env{'form.sections'}=~s/\W//g;
 4294: 
 4295:     my $credits;
 4296:     if (($showcredits) && ($env{'form.credits'} ne '')) {
 4297:         $credits = $env{'form.credits'};
 4298:         $credits =~ s/[^\d\.]//g;
 4299:         if ($credits ne '') {
 4300:             if ($credits eq $defaultcredits) {
 4301:                 undef($credits);
 4302:             }
 4303:         }
 4304:     }
 4305: 
 4306:     # Clean out any old student roles the user has in this class.
 4307:     &Apache::lonuserutils::modifystudent($env{'form.ccdomain'},
 4308:          $env{'form.ccuname'},$env{'request.course.id'},undef,$uhome);
 4309:     my ($startdate,$enddate) = &Apache::lonuserutils::get_dates_from_form();
 4310:     my $enroll_result =
 4311:         &Apache::lonnet::modify_student_enrollment($env{'form.ccdomain'},
 4312:             $env{'form.ccuname'},$env{'form.cid'},$env{'form.cfirstname'},
 4313:             $env{'form.cmiddlename'},$env{'form.clastname'},
 4314:             $env{'form.generation'},$env{'form.sections'},$enddate,
 4315:             $startdate,'manual',undef,$env{'request.course.id'},'',$context,
 4316:             $credits);
 4317:     if ($enroll_result =~ /^ok/) {
 4318:         $r->print(&mt('[_1] enrolled','<b>'.$env{'form.ccuname'}.':'.$env{'form.ccdomain'}.'</b>'));
 4319:         if ($env{'form.sections'} ne '') {
 4320:             $r->print(' '.&mt('in section [_1]',$env{'form.sections'}));
 4321:         }
 4322:         my ($showstart,$showend);
 4323:         if ($startdate <= $now) {
 4324:             $showstart = &mt('Access starts immediately');
 4325:         } else {
 4326:             $showstart = &mt('Access starts: ').&Apache::lonlocal::locallocaltime($startdate);
 4327:         }
 4328:         if ($enddate == 0) {
 4329:             $showend = &mt('ends: no ending date');
 4330:         } else {
 4331:             $showend = &mt('ends: ').&Apache::lonlocal::locallocaltime($enddate);
 4332:         }
 4333:         $r->print('.<br />'.$showstart.'; '.$showend);
 4334:         if ($startdate <= $now && !$newuser) {
 4335:             $r->print('<p class="LC_info">');
 4336:             if ($crstype eq 'Community') {
 4337:                 $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.'));
 4338:             } else {
 4339:                 $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.'));
 4340:            }
 4341:            $r->print('</p>');
 4342:         }
 4343:     } else {
 4344:         $r->print(&mt('unable to enroll').": ".$enroll_result);
 4345:     }
 4346:     return;
 4347: }
 4348: 
 4349: sub get_defaultquota_text {
 4350:     my ($settingstatus) = @_;
 4351:     my $defquotatext; 
 4352:     if ($settingstatus eq '') {
 4353:         $defquotatext = &mt('default');
 4354:     } else {
 4355:         my ($usertypes,$order) =
 4356:             &Apache::lonnet::retrieve_inst_usertypes($env{'form.ccdomain'});
 4357:         if ($usertypes->{$settingstatus} eq '') {
 4358:             $defquotatext = &mt('default');
 4359:         } else {
 4360:             $defquotatext = &mt('default for [_1]',$usertypes->{$settingstatus});
 4361:         }
 4362:     }
 4363:     return $defquotatext;
 4364: }
 4365: 
 4366: sub update_result_form {
 4367:     my ($uhome) = @_;
 4368:     my $outcome = 
 4369:     '<form name="userupdate" method="post" action="">'."\n";
 4370:     foreach my $item ('srchby','srchin','srchtype','srchterm','srchdomain','ccuname','ccdomain') {
 4371:         $outcome .= '<input type="hidden" name="'.$item.'" value="'.$env{'form.'.$item}.'" />'."\n";
 4372:     }
 4373:     if ($env{'form.origname'} ne '') {
 4374:         $outcome .= '<input type="hidden" name="origname" value="'.$env{'form.origname'}.'" />'."\n";
 4375:     }
 4376:     foreach my $item ('sortby','seluname','seludom') {
 4377:         if (exists($env{'form.'.$item})) {
 4378:             $outcome .= '<input type="hidden" name="'.$item.'" value="'.$env{'form.'.$item}.'" />'."\n";
 4379:         }
 4380:     }
 4381:     if ($uhome eq 'no_host') {
 4382:         $outcome .= '<input type="hidden" name="forcenewuser" value="1" />'."\n";
 4383:     }
 4384:     $outcome .= '<input type="hidden" name="phase" value="" />'."\n".
 4385:                 '<input type="hidden" name="currstate" value="" />'."\n".
 4386:                 '<input type="hidden" name="action" value="'.$env{'form.action'}.'" />'."\n".
 4387:                 '</form>';
 4388:     return $outcome;
 4389: }
 4390: 
 4391: sub quota_admin {
 4392:     my ($setquota,$changeHash,$name) = @_;
 4393:     my $quotachanged;
 4394:     if (&Apache::lonnet::allowed('mpq',$env{'form.ccdomain'})) {
 4395:         # Current user has quota modification privileges
 4396:         if (ref($changeHash) eq 'HASH') {
 4397:             $quotachanged = 1;
 4398:             $changeHash->{$name.'quota'} = $setquota;
 4399:         }
 4400:     }
 4401:     return $quotachanged;
 4402: }
 4403: 
 4404: sub tool_admin {
 4405:     my ($tool,$settool,$changeHash,$context) = @_;
 4406:     my $canchange = 0; 
 4407:     if ($context eq 'requestcourses') {
 4408:         if (&Apache::lonnet::allowed('ccc',$env{'form.ccdomain'})) {
 4409:             $canchange = 1;
 4410:         }
 4411:     } elsif ($context eq 'reqcrsotherdom') {
 4412:         if (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) {
 4413:             $canchange = 1;
 4414:         }
 4415:     } elsif ($context eq 'requestauthor') {
 4416:         if (&Apache::lonnet::allowed('cau',$env{'request.role.domain'})) {
 4417:             $canchange = 1;
 4418:         }
 4419:     } elsif (&Apache::lonnet::allowed('mut',$env{'form.ccdomain'})) {
 4420:         # Current user has quota modification privileges
 4421:         $canchange = 1;
 4422:     }
 4423:     my $toolchanged;
 4424:     if ($canchange) {
 4425:         if (ref($changeHash) eq 'HASH') {
 4426:             $toolchanged = 1;
 4427:             if ($tool eq 'requestauthor') {
 4428:                 $changeHash->{$context} = $settool;
 4429:             } else {
 4430:                 $changeHash->{$context.'.'.$tool} = $settool;
 4431:             }
 4432:         }
 4433:     }
 4434:     return $toolchanged;
 4435: }
 4436: 
 4437: sub build_roles {
 4438:     my ($sectionstr,$sections,$role) = @_;
 4439:     my $num_sections = 0;
 4440:     if ($sectionstr=~ /,/) {
 4441:         my @secnums = split/,/,$sectionstr;
 4442:         if ($role eq 'st') {
 4443:             $secnums[0] =~ s/\W//g;
 4444:             $$sections{$secnums[0]} = 1;
 4445:             $num_sections = 1;
 4446:         } else {
 4447:             foreach my $sec (@secnums) {
 4448:                 $sec =~ ~s/\W//g;
 4449:                 if (!($sec eq "")) {
 4450:                     if (exists($$sections{$sec})) {
 4451:                         $$sections{$sec} ++;
 4452:                     } else {
 4453:                         $$sections{$sec} = 1;
 4454:                         $num_sections ++;
 4455:                     }
 4456:                 }
 4457:             }
 4458:         }
 4459:     } else {
 4460:         $sectionstr=~s/\W//g;
 4461:         unless ($sectionstr eq '') {
 4462:             $$sections{$sectionstr} = 1;
 4463:             $num_sections ++;
 4464:         }
 4465:     }
 4466: 
 4467:     return $num_sections;
 4468: }
 4469: 
 4470: # ========================================================== Custom Role Editor
 4471: 
 4472: sub custom_role_editor {
 4473:     my ($r,$brcrum,$prefix) = @_;
 4474:     my $action = $env{'form.customroleaction'};
 4475:     my $rolename; 
 4476:     if ($action eq 'new') {
 4477:         $rolename=$env{'form.newrolename'};
 4478:     } else {
 4479:         $rolename=$env{'form.rolename'};
 4480:     }
 4481: 
 4482:     my ($crstype,$context);
 4483:     if ($env{'request.course.id'}) {
 4484:         $crstype = &Apache::loncommon::course_type();
 4485:         $context = 'course';
 4486:     } else {
 4487:         $context = 'domain';
 4488:         $crstype = 'course';
 4489:     }
 4490: 
 4491:     $rolename=~s/[^A-Za-z0-9]//gs;
 4492:     if (!$rolename || $env{'form.phase'} eq 'pickrole') {
 4493: 	&print_username_entry_form($r,undef,undef,undef,undef,$crstype,$brcrum);
 4494:         return;
 4495:     }
 4496: 
 4497:     my $formname = 'form1';
 4498:     my %privs=();
 4499:     my $body_top = '<h2>';
 4500: # ------------------------------------------------------- Does this role exist?
 4501:     my ($rdummy,$roledef)=
 4502: 			 &Apache::lonnet::get('roles',["rolesdef_$rolename"]);
 4503:     if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 4504:         $body_top .= &mt('Existing Role').' "';
 4505: # ------------------------------------------------- Get current role privileges
 4506:         ($privs{'system'},$privs{'domain'},$privs{'course'})=split(/\_/,$roledef);
 4507:         if ($privs{'system'} =~ /bre\&S/) {
 4508:             if ($context eq 'domain') {
 4509:                 $crstype = 'Course';
 4510:             } elsif ($crstype eq 'Community') {
 4511:                 $privs{'system'} =~ s/bre\&S//;
 4512:             }
 4513:         } elsif ($context eq 'domain') {
 4514:             $crstype = 'Course';
 4515:         }
 4516:     } else {
 4517:         $body_top .= &mt('New Role').' "';
 4518:         $roledef='';
 4519:     }
 4520:     $body_top .= $rolename.'"</h2>';
 4521: 
 4522: # ------------------------------------------------------- What can be assigned?
 4523:     my %full=();
 4524:     my %levels=(
 4525:                  course => {},
 4526:                  domain => {},
 4527:                  system => {},
 4528:                );
 4529:     my %levelscurrent=(
 4530:                         course => {},
 4531:                         domain => {},
 4532:                         system => {},
 4533:                       );
 4534:     &Apache::lonuserutils::custom_role_privs(\%privs,\%full,\%levels,\%levelscurrent);
 4535:     my ($jsback,$elements) = &crumb_utilities();
 4536:     my @templateroles = &Apache::lonuserutils::custom_template_roles($context,$crstype);
 4537:     my $head_script =
 4538:         &Apache::lonuserutils::custom_roledefs_js($context,$crstype,$formname,
 4539:                                                   \%full,\@templateroles,$jsback);
 4540:     push (@{$brcrum},
 4541:               {href => "javascript:backPage(document.$formname,'pickrole','')",
 4542:                text => "Pick custom role",
 4543:                faq  => 282,bug=>'Instructor Interface',},
 4544:               {href => "javascript:backPage(document.$formname,'','')",
 4545:                text => "Edit custom role",
 4546:                faq  => 282,
 4547:                bug  => 'Instructor Interface',
 4548:                help => 'Course_Editing_Custom_Roles'}
 4549:               );
 4550:     my $args = { bread_crumbs          => $brcrum,
 4551:                  bread_crumbs_component => 'User Management'};
 4552: 
 4553:     $r->print(&Apache::loncommon::start_page('Custom Role Editor',
 4554:                                              $head_script,$args).
 4555:               $body_top);
 4556:     $r->print('<form name="'.$formname.'" method="post" action="">'."\n".
 4557:               &Apache::lonuserutils::custom_role_header($context,$crstype,
 4558:                                                         \@templateroles,$prefix));
 4559: 
 4560:     $r->print(<<ENDCCF);
 4561: <input type="hidden" name="phase" value="set_custom_roles" />
 4562: <input type="hidden" name="rolename" value="$rolename" />
 4563: ENDCCF
 4564:     $r->print(&Apache::lonuserutils::custom_role_table($crstype,\%full,\%levels,
 4565:                                                        \%levelscurrent,$prefix));
 4566:     $r->print(&Apache::loncommon::end_data_table().
 4567:    '<input type="hidden" name="action" value="'.$env{'form.action'}.'" />'.
 4568:    '<input type="hidden" name="startrolename" value="'.$env{'form.rolename'}.
 4569:    '" />'."\n".'<input type="hidden" name="currstate" value="" />'."\n".
 4570:    '<input type="reset" value="'.&mt("Reset").'" />'."\n".
 4571:    '<input type="submit" value="'.&mt('Save').'" /></form>');
 4572: }
 4573: 
 4574: # ---------------------------------------------------------- Call to definerole
 4575: sub set_custom_role {
 4576:     my ($r,$context,$brcrum,$prefix) = @_;
 4577:     my $rolename=$env{'form.rolename'};
 4578:     $rolename=~s/[^A-Za-z0-9]//gs;
 4579:     if (!$rolename) {
 4580: 	&custom_role_editor($r,$brcrum,$prefix);
 4581:         return;
 4582:     }
 4583:     my ($jsback,$elements) = &crumb_utilities();
 4584:     my $jscript = '<script type="text/javascript">'
 4585:                  .'// <![CDATA['."\n"
 4586:                  .$jsback."\n"
 4587:                  .'// ]]>'."\n"
 4588:                  .'</script>'."\n";
 4589:     push(@{$brcrum},
 4590:         {href => "javascript:backPage(document.customresult,'pickrole','')",
 4591:          text => "Pick custom role",
 4592:          faq  => 282,
 4593:          bug  => 'Instructor Interface',},
 4594:         {href => "javascript:backPage(document.customresult,'selected_custom_edit','')",
 4595:          text => "Edit custom role",
 4596:          faq  => 282,
 4597:          bug  => 'Instructor Interface',},
 4598:         {href => "javascript:backPage(document.customresult,'set_custom_roles','')",
 4599:          text => "Result",
 4600:          faq  => 282,
 4601:          bug  => 'Instructor Interface',
 4602:          help => 'Course_Editing_Custom_Roles'},
 4603:         );
 4604:     my $args = { bread_crumbs           => $brcrum,
 4605:                  bread_crumbs_component => 'User Management'};
 4606:     $r->print(&Apache::loncommon::start_page('Save Custom Role',$jscript,$args));
 4607: 
 4608:     my $newrole;
 4609:     my ($rdummy,$roledef)=
 4610: 	&Apache::lonnet::get('roles',["rolesdef_$rolename"]);
 4611: 
 4612: # ------------------------------------------------------- Does this role exist?
 4613:     $r->print('<h3>');
 4614:     if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 4615: 	$r->print(&mt('Existing Role').' "');
 4616:     } else {
 4617: 	$r->print(&mt('New Role').' "');
 4618: 	$roledef='';
 4619:         $newrole = 1;
 4620:     }
 4621:     $r->print($rolename.'"</h3>');
 4622: # ------------------------------------------------- Assign role and show result
 4623: 
 4624:     my $errmsg;
 4625:     my %newprivs = &Apache::lonuserutils::custom_role_update($rolename,$prefix);
 4626:     # Assign role and return result
 4627:     my $result = &Apache::lonnet::definerole($rolename,$newprivs{'s'},$newprivs{'d'},
 4628:                                              $newprivs{'c'});
 4629:     if ($result ne 'ok') {
 4630:         $errmsg = ': '.$result;
 4631:     }
 4632:     my $message =
 4633:         &Apache::lonhtmlcommon::confirm_success(
 4634:             &mt('Defining Role').$errmsg, ($result eq 'ok' ? 0 : 1));
 4635:     if ($env{'request.course.id'}) {
 4636:         my $url='/'.$env{'request.course.id'};
 4637:         $url=~s/\_/\//g;
 4638:         $result =
 4639:             &Apache::lonnet::assigncustomrole(
 4640:                 $env{'user.domain'},$env{'user.name'},
 4641:                 $url,
 4642:                 $env{'user.domain'},$env{'user.name'},
 4643:                 $rolename,undef,undef,undef,$context);
 4644:         if ($result ne 'ok') {
 4645:             $errmsg = ': '.$result;
 4646:         }
 4647:         $message .=
 4648:             '<br />'
 4649:            .&Apache::lonhtmlcommon::confirm_success(
 4650:                 &mt('Assigning Role to Self').$errmsg, ($result eq 'ok' ? 0 : 1));
 4651:     }
 4652:     $r->print(
 4653:         &Apache::loncommon::confirmwrapper($message)
 4654:        .'<br />'
 4655:        .&Apache::lonhtmlcommon::actionbox([
 4656:             '<a href="javascript:backPage(document.customresult,'."'pickrole'".')">'
 4657:            .&mt('Create or edit another custom role')
 4658:            .'</a>'])
 4659:        .'<form name="customresult" method="post" action="">'
 4660:        .&Apache::lonhtmlcommon::echo_form_input([])
 4661:        .'</form>'
 4662:     );
 4663: }
 4664: 
 4665: # ================================================================ Main Handler
 4666: sub handler {
 4667:     my $r = shift;
 4668:     if ($r->header_only) {
 4669:        &Apache::loncommon::content_type($r,'text/html');
 4670:        $r->send_http_header;
 4671:        return OK;
 4672:     }
 4673:     my ($context,$crstype);
 4674:     if ($env{'request.course.id'}) {
 4675:         $context = 'course';
 4676:         $crstype = &Apache::loncommon::course_type();
 4677:     } elsif ($env{'request.role'} =~ /^au\./) {
 4678:         $context = 'author';
 4679:     } else {
 4680:         $context = 'domain';
 4681:     }
 4682: 
 4683:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 4684:         ['action','state','callingform','roletype','showrole','bulkaction','popup','phase',
 4685:          'username','domain','srchterm','srchdomain','srchin','srchby','srchtype','queue']);
 4686:     &Apache::lonhtmlcommon::clear_breadcrumbs();
 4687:     my $args;
 4688:     my $brcrum = [];
 4689:     my $bread_crumbs_component = 'User Management';
 4690:     if (($env{'form.action'} ne 'dateselect') && ($env{'form.action'} ne 'displayuserreq')) {
 4691:         $brcrum = [{href=>"/adm/createuser",
 4692:                     text=>"User Management",
 4693:                     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'}
 4694:                   ];
 4695:     }
 4696:     #SD Following files not added to help, because the corresponding .tex-files seem to
 4697:     #be missing: Course_Approve_Selfenroll,Course_User_Logs,
 4698:     my ($permission,$allowed) = 
 4699:         &Apache::lonuserutils::get_permission($context,$crstype);
 4700:     if (!$allowed) {
 4701:         if ($context eq 'course') {
 4702:             $r->internal_redirect('/adm/viewclasslist');
 4703:             return OK;
 4704:         }
 4705:         $env{'user.error.msg'}=
 4706:             "/adm/createuser:cst:0:0:Cannot create/modify user data ".
 4707:                                  "or view user status.";
 4708:         return HTTP_NOT_ACCEPTABLE;
 4709:     }
 4710: 
 4711:     &Apache::loncommon::content_type($r,'text/html');
 4712:     $r->send_http_header;
 4713: 
 4714:     my $showcredits;
 4715:     if ((($context eq 'course') && ($crstype eq 'Course')) || 
 4716:          ($context eq 'domain')) {
 4717:         my %domdefaults = 
 4718:             &Apache::lonnet::get_domain_defaults($env{'request.role.domain'});
 4719:         if ($domdefaults{'officialcredits'} || $domdefaults{'unofficialcredits'}) {
 4720:             $showcredits = 1;
 4721:         }
 4722:     }
 4723: 
 4724:     # Main switch on form.action and form.state, as appropriate
 4725:     if (! exists($env{'form.action'})) {
 4726:         $args = {bread_crumbs => $brcrum,
 4727:                  bread_crumbs_component => $bread_crumbs_component}; 
 4728:         $r->print(&header(undef,$args));
 4729:         $r->print(&print_main_menu($permission,$context,$crstype));
 4730:     } elsif ($env{'form.action'} eq 'upload' && $permission->{'cusr'}) {
 4731:         push(@{$brcrum},
 4732:               { href => '/adm/createuser?action=upload&state=',
 4733:                 text => 'Upload Users List',
 4734:                 help => 'Course_Create_Class_List',
 4735:               });
 4736:         $bread_crumbs_component = 'Upload Users List';
 4737:         $args = {bread_crumbs           => $brcrum,
 4738:                  bread_crumbs_component => $bread_crumbs_component};
 4739:         $r->print(&header(undef,$args));
 4740:         $r->print('<form name="studentform" method="post" '.
 4741:                   'enctype="multipart/form-data" '.
 4742:                   ' action="/adm/createuser">'."\n");
 4743:         if (! exists($env{'form.state'})) {
 4744:             &Apache::lonuserutils::print_first_users_upload_form($r,$context);
 4745:         } elsif ($env{'form.state'} eq 'got_file') {
 4746:             &Apache::lonuserutils::print_upload_manager_form($r,$context,$permission,
 4747:                                                              $crstype,$showcredits);
 4748:         } elsif ($env{'form.state'} eq 'enrolling') {
 4749:             if ($env{'form.datatoken'}) {
 4750:                 &Apache::lonuserutils::upfile_drop_add($r,$context,$permission,
 4751:                                                        $showcredits);
 4752:             }
 4753:         } else {
 4754:             &Apache::lonuserutils::print_first_users_upload_form($r,$context);
 4755:         }
 4756:     } elsif (((($env{'form.action'} eq 'singleuser') || ($env{'form.action'}
 4757:               eq 'singlestudent')) && ($permission->{'cusr'})) ||
 4758:              (($env{'form.action'} eq 'singleuser') && ($permission->{'view'})) ||
 4759:              (($env{'form.action'} eq 'accesslogs') && ($permission->{'activity'}))) {
 4760:         my $phase = $env{'form.phase'};
 4761:         my @search = ('srchterm','srchby','srchin','srchtype','srchdomain');
 4762: 	&Apache::loncreateuser::restore_prev_selections();
 4763: 	my $srch;
 4764: 	foreach my $item (@search) {
 4765: 	    $srch->{$item} = $env{'form.'.$item};
 4766: 	}
 4767:         if (($phase eq 'get_user_info') || ($phase eq 'userpicked') ||
 4768:             ($phase eq 'createnewuser') || ($phase eq 'activity')) {
 4769:             if ($env{'form.phase'} eq 'createnewuser') {
 4770:                 my $response;
 4771:                 if ($env{'form.srchterm'} !~ /^$match_username$/) {
 4772:                     my $response =
 4773:                         '<span class="LC_warning">'
 4774:                        .&mt('You must specify a valid username. Only the following are allowed:'
 4775:                            .' letters numbers - . @')
 4776:                        .'</span>';
 4777:                     $env{'form.phase'} = '';
 4778:                     &print_username_entry_form($r,$context,$response,$srch,undef,
 4779:                                                $crstype,$brcrum,$showcredits);
 4780:                 } else {
 4781:                     my $ccuname =&LONCAPA::clean_username($srch->{'srchterm'});
 4782:                     my $ccdomain=&LONCAPA::clean_domain($srch->{'srchdomain'});
 4783:                     &print_user_modification_page($r,$ccuname,$ccdomain,
 4784:                                                   $srch,$response,$context,
 4785:                                                   $permission,$crstype,$brcrum,
 4786:                                                   $showcredits);
 4787:                 }
 4788:             } elsif ($env{'form.phase'} eq 'get_user_info') {
 4789:                 my ($currstate,$response,$forcenewuser,$results) = 
 4790:                     &user_search_result($context,$srch);
 4791:                 if ($env{'form.currstate'} eq 'modify') {
 4792:                     $currstate = $env{'form.currstate'};
 4793:                 }
 4794:                 if ($currstate eq 'select') {
 4795:                     &print_user_selection_page($r,$response,$srch,$results,
 4796:                                                \@search,$context,undef,$crstype,
 4797:                                                $brcrum);
 4798:                 } elsif (($currstate eq 'modify') || ($env{'form.action'} eq 'accesslogs')) {
 4799:                     my ($ccuname,$ccdomain,$uhome);
 4800:                     if (($srch->{'srchby'} eq 'uname') && 
 4801:                         ($srch->{'srchtype'} eq 'exact')) {
 4802:                         $ccuname = $srch->{'srchterm'};
 4803:                         $ccdomain= $srch->{'srchdomain'};
 4804:                     } else {
 4805:                         my @matchedunames = keys(%{$results});
 4806:                         ($ccuname,$ccdomain) = split(/:/,$matchedunames[0]);
 4807:                     }
 4808:                     $ccuname =&LONCAPA::clean_username($ccuname);
 4809:                     $ccdomain=&LONCAPA::clean_domain($ccdomain);
 4810:                     if ($env{'form.action'} eq 'accesslogs') {
 4811:                         my $uhome;
 4812:                         if (($ccuname ne '') && ($ccdomain ne '')) {
 4813:                            $uhome = &Apache::lonnet::homeserver($ccuname,$ccdomain);
 4814:                         }
 4815:                         if (($uhome eq '') || ($uhome eq 'no_host')) {
 4816:                             $env{'form.phase'} = '';
 4817:                             undef($forcenewuser);
 4818:                             #if ($response) {
 4819:                             #    unless ($response =~ m{\Q<br /><br />\E$}) {
 4820:                             #        $response .= '<br /><br />';
 4821:                             #    }
 4822:                             #}
 4823:                             &print_username_entry_form($r,$context,$response,$srch,
 4824:                                                        $forcenewuser,$crstype,$brcrum);
 4825:                         } else {
 4826:                             &print_useraccesslogs_display($r,$ccuname,$ccdomain,$permission,$brcrum);
 4827:                         }
 4828:                     } else {
 4829:                         if ($env{'form.forcenewuser'}) {
 4830:                             $response = '';
 4831:                         }
 4832:                         &print_user_modification_page($r,$ccuname,$ccdomain,
 4833:                                                       $srch,$response,$context,
 4834:                                                       $permission,$crstype,$brcrum);
 4835:                     }
 4836:                 } elsif ($currstate eq 'query') {
 4837:                     &print_user_query_page($r,'createuser',$brcrum);
 4838:                 } else {
 4839:                     $env{'form.phase'} = '';
 4840:                     &print_username_entry_form($r,$context,$response,$srch,
 4841:                                                $forcenewuser,$crstype,$brcrum);
 4842:                 }
 4843:             } elsif ($env{'form.phase'} eq 'userpicked') {
 4844:                 my $ccuname = &LONCAPA::clean_username($env{'form.seluname'});
 4845:                 my $ccdomain = &LONCAPA::clean_domain($env{'form.seludom'});
 4846:                 if ($env{'form.action'} eq 'accesslogs') {
 4847:                     &print_useraccesslogs_display($r,$ccuname,$ccdomain,$permission,$brcrum);
 4848:                 } else {
 4849:                     &print_user_modification_page($r,$ccuname,$ccdomain,$srch,'',
 4850:                                                   $context,$permission,$crstype,
 4851:                                                   $brcrum);
 4852:                 }
 4853:             } elsif ($env{'form.action'} eq 'accesslogs') {
 4854:                 my $ccuname = &LONCAPA::clean_username($env{'form.accessuname'});
 4855:                 my $ccdomain = &LONCAPA::clean_domain($env{'form.accessudom'});
 4856:                 &print_useraccesslogs_display($r,$ccuname,$ccdomain,$permission,$brcrum);
 4857:             }
 4858:         } elsif ($env{'form.phase'} eq 'update_user_data') {
 4859:             &update_user_data($r,$context,$crstype,$brcrum,$showcredits);
 4860:         } else {
 4861:             &print_username_entry_form($r,$context,undef,$srch,undef,$crstype,
 4862:                                        $brcrum);
 4863:         }
 4864:     } elsif ($env{'form.action'} eq 'custom' && $permission->{'custom'}) {
 4865:         my $prefix;
 4866:         if ($env{'form.phase'} eq 'set_custom_roles') {
 4867:             &set_custom_role($r,$context,$brcrum,$prefix);
 4868:         } else {
 4869:             &custom_role_editor($r,$brcrum,$prefix);
 4870:         }
 4871:     } elsif (($env{'form.action'} eq 'processauthorreq') &&
 4872:              ($permission->{'cusr'}) && 
 4873:              (&Apache::lonnet::allowed('cau',$env{'request.role.domain'}))) {
 4874:         push(@{$brcrum},
 4875:                  {href => '/adm/createuser?action=processauthorreq',
 4876:                   text => 'Authoring Space requests',
 4877:                   help => 'Domain_Role_Approvals'});
 4878:         $bread_crumbs_component = 'Authoring requests';
 4879:         if ($env{'form.state'} eq 'done') {
 4880:             push(@{$brcrum},
 4881:                      {href => '/adm/createuser?action=authorreqqueue',
 4882:                       text => 'Result',
 4883:                       help => 'Domain_Role_Approvals'});
 4884:             $bread_crumbs_component = 'Authoring request result';
 4885:         }
 4886:         $args = { bread_crumbs           => $brcrum,
 4887:                   bread_crumbs_component => $bread_crumbs_component};
 4888:         my $js = &usernamerequest_javascript();
 4889:         $r->print(&header(&add_script($js),$args));
 4890:         if (!exists($env{'form.state'})) {
 4891:             $r->print(&Apache::loncoursequeueadmin::display_queued_requests('requestauthor',
 4892:                                                                             $env{'request.role.domain'}));
 4893:         } elsif ($env{'form.state'} eq 'done') {
 4894:             $r->print('<h3>'.&mt('Authoring request processing').'</h3>'."\n");
 4895:             $r->print(&Apache::loncoursequeueadmin::update_request_queue('requestauthor',
 4896:                                                                          $env{'request.role.domain'}));
 4897:         }
 4898:     } elsif (($env{'form.action'} eq 'processusernamereq') &&
 4899:              ($permission->{'cusr'}) &&
 4900:              (&Apache::lonnet::allowed('cau',$env{'request.role.domain'}))) {
 4901:         push(@{$brcrum},
 4902:                  {href => '/adm/createuser?action=processusernamereq',
 4903:                   text => 'LON-CAPA account requests',
 4904:                   help => 'Domain_Username_Approvals'});
 4905:         $bread_crumbs_component = 'Account requests';
 4906:         if ($env{'form.state'} eq 'done') {
 4907:             push(@{$brcrum},
 4908:                      {href => '/adm/createuser?action=usernamereqqueue',
 4909:                       text => 'Result',
 4910:                       help => 'Domain_Username_Approvals'});
 4911:             $bread_crumbs_component = 'LON-CAPA account request result';
 4912:         }
 4913:         $args = { bread_crumbs           => $brcrum,
 4914:                   bread_crumbs_component => $bread_crumbs_component};
 4915:         my $js = &usernamerequest_javascript();
 4916:         $r->print(&header(&add_script($js),$args));
 4917:         if (!exists($env{'form.state'})) {
 4918:             $r->print(&Apache::loncoursequeueadmin::display_queued_requests('requestusername',
 4919:                                                                             $env{'request.role.domain'}));
 4920:         } elsif ($env{'form.state'} eq 'done') {
 4921:             $r->print('<h3>'.&mt('LON-CAPA account request processing').'</h3>'."\n");
 4922:             $r->print(&Apache::loncoursequeueadmin::update_request_queue('requestusername',
 4923:                                                                          $env{'request.role.domain'}));
 4924:         }
 4925:     } elsif (($env{'form.action'} eq 'displayuserreq') &&
 4926:              ($permission->{'cusr'})) {
 4927:         my $dom = $env{'form.domain'};
 4928:         my $uname = $env{'form.username'};
 4929:         my $warning;
 4930:         if (($dom =~ /^$match_domain$/) && (&Apache::lonnet::domain($dom) ne '')) {
 4931:             if (($dom eq $env{'request.role.domain'}) && (&Apache::lonnet::allowed('ccc',$dom))) {
 4932:                 if (($uname =~ /^$match_username$/) && ($env{'form.queue'} eq 'approval')) {
 4933:                     my $uhome = &Apache::lonnet::homeserver($uname,$dom);
 4934:                     if ($uhome eq 'no_host') {
 4935:                         my $queue = $env{'form.queue'};
 4936:                         my $reqkey = &escape($uname).'_'.$queue; 
 4937:                         my $namespace = 'usernamequeue';
 4938:                         my $domconfig = &Apache::lonnet::get_domainconfiguser($dom);
 4939:                         my %queued =
 4940:                             &Apache::lonnet::get($namespace,[$reqkey],$dom,$domconfig);
 4941:                         unless ($queued{$reqkey}) {
 4942:                             $warning = &mt('No information was found for this LON-CAPA account request.');
 4943:                         }
 4944:                     } else {
 4945:                         $warning = &mt('A LON-CAPA account already exists for the requested username and domain.');
 4946:                     }
 4947:                 } else {
 4948:                     $warning = &mt('LON-CAPA account request status check is for an invalid username.');
 4949:                 }
 4950:             } else {
 4951:                 $warning = &mt('You do not have rights to view LON-CAPA account requests in the domain specified.');
 4952:             }
 4953:         } else {
 4954:             $warning = &mt('LON-CAPA account request status check is for an invalid domain.');
 4955:         }
 4956:         my $args = { only_body => 1 };
 4957:         $r->print(&header(undef,$args).
 4958:                   '<h3>'.&mt('LON-CAPA Account Request Details').'</h3>');
 4959:         if ($warning ne '') {
 4960:             $r->print('<div class="LC_warning">'.$warning.'</div>');
 4961:         } else {
 4962:             my ($infofields,$infotitles) = &Apache::loncommon::emailusername_info();
 4963:             my $domconfiguser = &Apache::lonnet::get_domainconfiguser($dom);
 4964:             my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 4965:             if (ref($domconfig{'usercreation'}) eq 'HASH') {
 4966:                 if (ref($domconfig{'usercreation'}{'cancreate'}) eq 'HASH') {
 4967:                     if (ref($domconfig{'usercreation'}{'cancreate'}{'emailusername'}) eq 'HASH') {
 4968:                         my %info =
 4969:                             &Apache::lonnet::get('nohist_requestedusernames',[$uname],$dom,$domconfiguser);
 4970:                         if (ref($info{$uname}) eq 'HASH') {
 4971:                             my $usertype = $info{$uname}{'inststatus'};
 4972:                             unless ($usertype) {
 4973:                                 $usertype = 'default';
 4974:                             }
 4975:                             if (ref($domconfig{'usercreation'}{'cancreate'}{'emailusername'}{$usertype}) eq 'HASH') {
 4976:                                 if ((ref($infofields) eq 'ARRAY') && (ref($infotitles) eq 'HASH')) {
 4977:                                     $r->print('<div>'.&Apache::lonhtmlcommon::start_pick_box());
 4978:                                     my ($num,$count,$showstatus);
 4979:                                     $count = scalar(keys(%{$domconfig{'usercreation'}{'cancreate'}{'emailusername'}{$usertype}}));
 4980:                                     unless ($usertype eq 'default') {
 4981:                                         my ($othertitle,$usertypes,$types) = 
 4982:                                             &Apache::loncommon::sorted_inst_types($dom);
 4983:                                         if (ref($usertypes) eq 'HASH') {
 4984:                                             if ($usertypes->{$usertype}) {
 4985:                                                 $showstatus = $usertypes->{$usertype};
 4986:                                                 $count ++;
 4987:                                             }
 4988:                                         }
 4989:                                     }
 4990:                                     foreach my $field (@{$infofields}) {
 4991:                                         next unless ($domconfig{'usercreation'}{'cancreate'}{'emailusername'}{$usertype}{$field});
 4992:                                         next unless ($infotitles->{$field});
 4993:                                         $r->print(&Apache::lonhtmlcommon::row_title($infotitles->{$field}).
 4994:                                                   $info{$uname}{$field});
 4995:                                         $num ++;
 4996:                                         if ($count == $num) {
 4997:                                             $r->print(&Apache::lonhtmlcommon::row_closure(1));
 4998:                                         } else {
 4999:                                             $r->print(&Apache::lonhtmlcommon::row_closure());
 5000:                                         }
 5001:                                     }
 5002:                                     if ($showstatus) {
 5003:                                         $r->print(&Apache::lonhtmlcommon::row_title(&mt('Status type (self-reported)')).
 5004:                                                   $showstatus.
 5005:                                                   &Apache::lonhtmlcommon::row_closure(1));
 5006:                                     }
 5007:                                     $r->print(&Apache::lonhtmlcommon::end_pick_box().'</div>');
 5008:                                 }
 5009:                             }
 5010:                         }
 5011:                     }
 5012:                 }
 5013:             }
 5014:             $r->print(&close_popup_form());
 5015:         }
 5016:     } elsif (($env{'form.action'} eq 'listusers') && 
 5017:              ($permission->{'view'} || $permission->{'cusr'})) {
 5018:         if ($env{'form.phase'} eq 'bulkchange') {
 5019:             push(@{$brcrum},
 5020:                     {href => '/adm/createuser?action=listusers',
 5021:                      text => "List Users"},
 5022:                     {href => "/adm/createuser",
 5023:                      text => "Result",
 5024:                      help => 'Course_View_Class_List'});
 5025:             $bread_crumbs_component = 'Update Users';
 5026:             $args = {bread_crumbs           => $brcrum,
 5027:                      bread_crumbs_component => $bread_crumbs_component};
 5028:             $r->print(&header(undef,$args));
 5029:             my $setting = $env{'form.roletype'};
 5030:             my $choice = $env{'form.bulkaction'};
 5031:             if ($permission->{'cusr'}) {
 5032:                 &Apache::lonuserutils::update_user_list($r,$context,$setting,$choice,$crstype);
 5033:             } else {
 5034:                 $r->print(&mt('You are not authorized to make bulk changes to user roles'));
 5035:                 $r->print('<p><a href="/adm/createuser?action=listusers">'.&mt('Display User Lists').'</a>');
 5036:             }
 5037:         } else {
 5038:             push(@{$brcrum},
 5039:                     {href => '/adm/createuser?action=listusers',
 5040:                      text => "List Users",
 5041:                      help => 'Course_View_Class_List'});
 5042:             $bread_crumbs_component = 'List Users';
 5043:             $args = {bread_crumbs           => $brcrum,
 5044:                      bread_crumbs_component => $bread_crumbs_component};
 5045:             my ($cb_jscript,$jscript,$totcodes,$codetitles,$idlist,$idlist_titles);
 5046:             my $formname = 'studentform';
 5047:             my $hidecall = "hide_searching();";
 5048:             if (($context eq 'domain') && (($env{'form.roletype'} eq 'course') ||
 5049:                 ($env{'form.roletype'} eq 'community'))) {
 5050:                 if ($env{'form.roletype'} eq 'course') {
 5051:                     ($cb_jscript,$jscript,$totcodes,$codetitles,$idlist,$idlist_titles) = 
 5052:                         &Apache::lonuserutils::courses_selector($env{'request.role.domain'},
 5053:                                                                 $formname);
 5054:                 } elsif ($env{'form.roletype'} eq 'community') {
 5055:                     $cb_jscript = 
 5056:                         &Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'});
 5057:                     my %elements = (
 5058:                                       coursepick => 'radio',
 5059:                                       coursetotal => 'text',
 5060:                                       courselist => 'text',
 5061:                                    );
 5062:                     $jscript = &Apache::lonhtmlcommon::set_form_elements(\%elements);
 5063:                 }
 5064:                 $jscript .= &verify_user_display($context)."\n".
 5065:                             &Apache::loncommon::check_uncheck_jscript();
 5066:                 my $js = &add_script($jscript).$cb_jscript;
 5067:                 my $loadcode = 
 5068:                     &Apache::lonuserutils::course_selector_loadcode($formname);
 5069:                 if ($loadcode ne '') {
 5070:                     $args->{add_entries} = {onload => "$loadcode;$hidecall"};
 5071:                 } else {
 5072:                     $args->{add_entries} = {onload => $hidecall};
 5073:                 }
 5074:                 $r->print(&header($js,$args));
 5075:             } else {
 5076:                 $args->{add_entries} = {onload => $hidecall};
 5077:                 $jscript = &verify_user_display($context).
 5078:                            &Apache::loncommon::check_uncheck_jscript(); 
 5079:                 $r->print(&header(&add_script($jscript),$args));
 5080:             }
 5081:             &Apache::lonuserutils::print_userlist($r,undef,$permission,$context,
 5082:                          $formname,$totcodes,$codetitles,$idlist,$idlist_titles,
 5083:                          $showcredits);
 5084:         }
 5085:     } elsif ($env{'form.action'} eq 'drop' && $permission->{'cusr'}) {
 5086:         my $brtext;
 5087:         if ($crstype eq 'Community') {
 5088:             $brtext = 'Drop Members';
 5089:         } else {
 5090:             $brtext = 'Drop Students';
 5091:         }
 5092:         push(@{$brcrum},
 5093:                 {href => '/adm/createuser?action=drop',
 5094:                  text => $brtext,
 5095:                  help => 'Course_Drop_Student'});
 5096:         if ($env{'form.state'} eq 'done') {
 5097:             push(@{$brcrum},
 5098:                      {href=>'/adm/createuser?action=drop',
 5099:                       text=>"Result"});
 5100:         }
 5101:         $bread_crumbs_component = $brtext;
 5102:         $args = {bread_crumbs           => $brcrum,
 5103:                  bread_crumbs_component => $bread_crumbs_component}; 
 5104:         $r->print(&header(undef,$args));
 5105:         if (!exists($env{'form.state'})) {
 5106:             &Apache::lonuserutils::print_drop_menu($r,$context,$permission,$crstype);
 5107:         } elsif ($env{'form.state'} eq 'done') {
 5108:             &Apache::lonuserutils::update_user_list($r,$context,undef,
 5109:                                                     $env{'form.action'});
 5110:         }
 5111:     } elsif ($env{'form.action'} eq 'dateselect') {
 5112:         if ($permission->{'cusr'}) {
 5113:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 5114:                       &Apache::lonuserutils::date_section_selector($context,$permission,
 5115:                                                                    $crstype,$showcredits));
 5116:         } else {
 5117:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 5118:                      '<span class="LC_error">'.&mt('You do not have permission to modify dates or sections for users').'</span>'); 
 5119:         }
 5120:     } elsif ($env{'form.action'} eq 'selfenroll') {
 5121:         if ($permission->{selfenrolladmin}) {
 5122:             my $cid = $env{'request.course.id'};
 5123:             my $cdom = $env{'course.'.$cid.'.domain'};
 5124:             my $cnum = $env{'course.'.$cid.'.num'};
 5125:             my %currsettings = (
 5126:                 selfenroll_types              => $env{'course.'.$cid.'.internal.selfenroll_types'},
 5127:                 selfenroll_registered         => $env{'course.'.$cid.'.internal.selfenroll_registered'},
 5128:                 selfenroll_section            => $env{'course.'.$cid.'.internal.selfenroll_section'},
 5129:                 selfenroll_notifylist         => $env{'course.'.$cid.'.internal.selfenroll_notifylist'},
 5130:                 selfenroll_approval           => $env{'course.'.$cid.'.internal.selfenroll_approval'},
 5131:                 selfenroll_limit              => $env{'course.'.$cid.'.internal.selfenroll_limit'},
 5132:                 selfenroll_cap                => $env{'course.'.$cid.'.internal.selfenroll_cap'},
 5133:                 selfenroll_start_date         => $env{'course.'.$cid.'.internal.selfenroll_start_date'},
 5134:                 selfenroll_end_date           => $env{'course.'.$cid.'.internal.selfenroll_end_date'},
 5135:                 selfenroll_start_access       => $env{'course.'.$cid.'.internal.selfenroll_start_access'},
 5136:                 selfenroll_end_access         => $env{'course.'.$cid.'.internal.selfenroll_end_access'},
 5137:                 default_enrollment_start_date => $env{'course.'.$cid.'.default_enrollment_start_date'},
 5138:                 default_enrollment_end_date   => $env{'course.'.$cid.'.default_enrollment_end_date'},
 5139:                 uniquecode                    => $env{'course.'.$cid.'.internal.uniquecode'},
 5140:             );
 5141:             push(@{$brcrum},
 5142:                     {href => '/adm/createuser?action=selfenroll',
 5143:                      text => "Configure Self-enrollment",
 5144:                      help => 'Course_Self_Enrollment'});
 5145:             if (!exists($env{'form.state'})) {
 5146:                 $args = { bread_crumbs           => $brcrum,
 5147:                           bread_crumbs_component => 'Configure Self-enrollment'};
 5148:                 $r->print(&header(undef,$args));
 5149:                 $r->print('<h3>'.&mt('Self-enrollment with a student role').'</h3>'."\n");
 5150:                 &print_selfenroll_menu($r,'course',$cid,$cdom,$cnum,\%currsettings);
 5151:             } elsif ($env{'form.state'} eq 'done') {
 5152:                 push (@{$brcrum},
 5153:                           {href=>'/adm/createuser?action=selfenroll',
 5154:                            text=>"Result"});
 5155:                 $args = { bread_crumbs           => $brcrum,
 5156:                           bread_crumbs_component => 'Self-enrollment result'};
 5157:                 $r->print(&header(undef,$args));
 5158:                 $r->print('<h3>'.&mt('Self-enrollment with a student role').'</h3>'."\n");
 5159:                 &update_selfenroll_config($r,$cid,$cdom,$cnum,$context,$crstype,\%currsettings);
 5160:             }
 5161:         } else {
 5162:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 5163:                      '<span class="LC_error">'.&mt('You do not have permission to configure self-enrollment').'</span>');
 5164:         }
 5165:     } elsif ($env{'form.action'} eq 'selfenrollqueue') {
 5166:         if ($permission->{selfenrolladmin}) {
 5167:             push(@{$brcrum},
 5168:                      {href => '/adm/createuser?action=selfenrollqueue',
 5169:                       text => 'Enrollment requests',
 5170:                       help => 'Course_Self_Enrollment'});
 5171:             $bread_crumbs_component = 'Enrollment requests';
 5172:             if ($env{'form.state'} eq 'done') {
 5173:                 push(@{$brcrum},
 5174:                          {href => '/adm/createuser?action=selfenrollqueue',
 5175:                           text => 'Result',
 5176:                           help => 'Course_Self_Enrollment'});
 5177:                 $bread_crumbs_component = 'Enrollment result';
 5178:             }
 5179:             $args = { bread_crumbs           => $brcrum,
 5180:                       bread_crumbs_component => $bread_crumbs_component};
 5181:             $r->print(&header(undef,$args));
 5182:             my $cid = $env{'request.course.id'};
 5183:             my $cdom = $env{'course.'.$cid.'.domain'};
 5184:             my $cnum = $env{'course.'.$cid.'.num'};
 5185:             my $coursedesc = $env{'course.'.$cid.'.description'};
 5186:             if (!exists($env{'form.state'})) {
 5187:                 $r->print('<h3>'.&mt('Pending enrollment requests').'</h3>'."\n");
 5188:                 $r->print(&Apache::loncoursequeueadmin::display_queued_requests($context,
 5189:                                                                                 $cdom,$cnum));
 5190:             } elsif ($env{'form.state'} eq 'done') {
 5191:                 $r->print('<h3>'.&mt('Enrollment request processing').'</h3>'."\n");
 5192:                 $r->print(&Apache::loncoursequeueadmin::update_request_queue($context,
 5193:                               $cdom,$cnum,$coursedesc));
 5194:             }
 5195:         } else {
 5196:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 5197:                      '<span class="LC_error">'.&mt('You do not have permission to manage self-enrollment').'</span>');
 5198:         }
 5199: 
 5200:     } elsif ($env{'form.action'} eq 'changelogs') {
 5201:         if ($permission->{cusr} || $permission->{view}) {
 5202:             &print_userchangelogs_display($r,$context,$permission,$brcrum);
 5203:         } else {
 5204:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 5205:                      '<span class="LC_error">'.&mt('You do not have permission to view change logs').'</span>');
 5206:         }
 5207:     } else {
 5208:         $bread_crumbs_component = 'User Management';
 5209:         $args = { bread_crumbs           => $brcrum,
 5210:                   bread_crumbs_component => $bread_crumbs_component};
 5211:         $r->print(&header(undef,$args));
 5212:         $r->print(&print_main_menu($permission,$context,$crstype));
 5213:     }
 5214:     $r->print(&Apache::loncommon::end_page());
 5215:     return OK;
 5216: }
 5217: 
 5218: sub header {
 5219:     my ($jscript,$args) = @_;
 5220:     my $start_page;
 5221:     if (ref($args) eq 'HASH') {
 5222:         $start_page=&Apache::loncommon::start_page('User Management',$jscript,$args);
 5223:     } else {
 5224:         $start_page=&Apache::loncommon::start_page('User Management',$jscript);
 5225:     }
 5226:     return $start_page;
 5227: }
 5228: 
 5229: sub add_script {
 5230:     my ($js) = @_;
 5231:     return '<script type="text/javascript">'."\n"
 5232:           .'// <![CDATA['."\n"
 5233:           .$js."\n"
 5234:           .'// ]]>'."\n"
 5235:           .'</script>'."\n";
 5236: }
 5237: 
 5238: sub usernamerequest_javascript {
 5239:     my $js = <<ENDJS;
 5240: 
 5241: function openusernamereqdisplay(dom,uname,queue) {
 5242:     var url = '/adm/createuser?action=displayuserreq';
 5243:     url += '&domain='+dom+'&username='+uname+'&queue='+queue;
 5244:     var title = 'Account_Request_Browser';
 5245:     var options = 'scrollbars=1,resizable=1,menubar=0';
 5246:     options += ',width=700,height=600';
 5247:     var stdeditbrowser = open(url,title,options,'1');
 5248:     stdeditbrowser.focus();
 5249:     return;
 5250: }
 5251:  
 5252: ENDJS
 5253: }
 5254: 
 5255: sub close_popup_form {
 5256:     my $close= &mt('Close Window');
 5257:     return << "END";
 5258: <p><form name="displayreq" action="" method="post">
 5259: <input type="button" name="closeme" value="$close" onclick="javascript:self.close();" />
 5260: </form></p>
 5261: END
 5262: }
 5263: 
 5264: sub verify_user_display {
 5265:     my ($context) = @_;
 5266:     my %lt = &Apache::lonlocal::texthash (
 5267:         course    => 'course(s): description, section(s), status',
 5268:         community => 'community(s): description, section(s), status',
 5269:         author    => 'author',
 5270:     );
 5271:     my $photos;
 5272:     if (($context eq 'course') && $env{'request.course.id'}) {
 5273:         $photos = $env{'course.'.$env{'request.course.id'}.'.internal.showphoto'};
 5274:     }
 5275:     my $output = <<"END";
 5276: 
 5277: function hide_searching() {
 5278:     if (document.getElementById('searching')) {
 5279:         document.getElementById('searching').style.display = 'none';
 5280:     }
 5281:     return;
 5282: }
 5283: 
 5284: function display_update() {
 5285:     document.studentform.action.value = 'listusers';
 5286:     document.studentform.phase.value = 'display';
 5287:     document.studentform.submit();
 5288: }
 5289: 
 5290: function updateCols(caller) {
 5291:     var context = '$context';
 5292:     var photos = '$photos';
 5293:     if (caller == 'Status') {
 5294:         if ((context == 'domain') && 
 5295:             ((document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'course') ||
 5296:              (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'community'))) {
 5297:             document.getElementById('showcolstatus').checked = false;
 5298:             document.getElementById('showcolstatus').disabled = 'disabled';
 5299:             document.getElementById('showcolstart').checked = false;
 5300:             document.getElementById('showcolend').checked = false;
 5301:         } else {
 5302:             if (document.studentform.Status.options[document.studentform.Status.selectedIndex].value == 'Any') {
 5303:                 document.getElementById('showcolstatus').checked = true;
 5304:                 document.getElementById('showcolstatus').disabled = '';
 5305:                 document.getElementById('showcolstart').checked = true;
 5306:                 document.getElementById('showcolend').checked = true;
 5307:             } else {
 5308:                 document.getElementById('showcolstatus').checked = false;
 5309:                 document.getElementById('showcolstatus').disabled = 'disabled';
 5310:                 document.getElementById('showcolstart').checked = false;
 5311:                 document.getElementById('showcolend').checked = false;
 5312:             }
 5313:         }
 5314:     }
 5315:     if (caller == 'output') {
 5316:         if (photos == 1) {
 5317:             if (document.getElementById('showcolphoto')) {
 5318:                 var photoitem = document.getElementById('showcolphoto');
 5319:                 if (document.studentform.output.options[document.studentform.output.selectedIndex].value == 'html') {
 5320:                     photoitem.checked = true;
 5321:                     photoitem.disabled = '';
 5322:                 } else {
 5323:                     photoitem.checked = false;
 5324:                     photoitem.disabled = 'disabled';
 5325:                 }
 5326:             }
 5327:         }
 5328:     }
 5329:     if (caller == 'showrole') {
 5330:         if ((document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'Any') ||
 5331:             (document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'cr')) {
 5332:             document.getElementById('showcolrole').checked = true;
 5333:             document.getElementById('showcolrole').disabled = '';
 5334:         } else {
 5335:             document.getElementById('showcolrole').checked = false;
 5336:             document.getElementById('showcolrole').disabled = 'disabled';
 5337:         }
 5338:         if (context == 'domain') {
 5339:             var quotausageshow = 0;
 5340:             if ((document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'course') ||
 5341:                 (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'community')) {
 5342:                 document.getElementById('showcolstatus').checked = false;
 5343:                 document.getElementById('showcolstatus').disabled = 'disabled';
 5344:                 document.getElementById('showcolstart').checked = false;
 5345:                 document.getElementById('showcolend').checked = false;
 5346:             } else {
 5347:                 if (document.studentform.Status.options[document.studentform.Status.selectedIndex].value == 'Any') {
 5348:                     document.getElementById('showcolstatus').checked = true;
 5349:                     document.getElementById('showcolstatus').disabled = '';
 5350:                     document.getElementById('showcolstart').checked = true;
 5351:                     document.getElementById('showcolend').checked = true;
 5352:                 }
 5353:             }
 5354:             if (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'domain') {
 5355:                 document.getElementById('showcolextent').disabled = 'disabled';
 5356:                 document.getElementById('showcolextent').checked = 'false';
 5357:                 document.getElementById('showextent').style.display='none';
 5358:                 document.getElementById('showcoltextextent').innerHTML = '';
 5359:                 if ((document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'au') ||
 5360:                     (document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'Any')) {
 5361:                     if (document.getElementById('showcolauthorusage')) {
 5362:                         document.getElementById('showcolauthorusage').disabled = '';
 5363:                     }
 5364:                     if (document.getElementById('showcolauthorquota')) {
 5365:                         document.getElementById('showcolauthorquota').disabled = '';
 5366:                     }
 5367:                     quotausageshow = 1;
 5368:                 }
 5369:             } else {
 5370:                 document.getElementById('showextent').style.display='block';
 5371:                 document.getElementById('showextent').style.textAlign='left';
 5372:                 document.getElementById('showextent').style.textFace='normal';
 5373:                 if (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'author') {
 5374:                     document.getElementById('showcolextent').disabled = '';
 5375:                     document.getElementById('showcolextent').checked = 'true';
 5376:                     document.getElementById('showcoltextextent').innerHTML="$lt{'author'}";
 5377:                 } else {
 5378:                     document.getElementById('showcolextent').disabled = '';
 5379:                     document.getElementById('showcolextent').checked = 'true';
 5380:                     if (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'community') {
 5381:                         document.getElementById('showcoltextextent').innerHTML="$lt{'community'}";
 5382:                     } else {
 5383:                         document.getElementById('showcoltextextent').innerHTML="$lt{'course'}";
 5384:                     }
 5385:                 }
 5386:             }
 5387:             if (quotausageshow == 0)  {
 5388:                 if (document.getElementById('showcolauthorusage')) {
 5389:                     document.getElementById('showcolauthorusage').checked = false;
 5390:                     document.getElementById('showcolauthorusage').disabled = 'disabled';
 5391:                 }
 5392:                 if (document.getElementById('showcolauthorquota')) {
 5393:                     document.getElementById('showcolauthorquota').checked = false;
 5394:                     document.getElementById('showcolauthorquota').disabled = 'disabled';
 5395:                 }
 5396:             }
 5397:         }
 5398:     }
 5399:     return;
 5400: }
 5401: 
 5402: END
 5403:     return $output;
 5404: 
 5405: }
 5406: 
 5407: ###############################################################
 5408: ###############################################################
 5409: #  Menu Phase One
 5410: sub print_main_menu {
 5411:     my ($permission,$context,$crstype) = @_;
 5412:     my $linkcontext = $context;
 5413:     my $stuterm = lc(&Apache::lonnet::plaintext('st',$crstype));
 5414:     if (($context eq 'course') && ($crstype eq 'Community')) {
 5415:         $linkcontext = lc($crstype);
 5416:         $stuterm = 'Members';
 5417:     }
 5418:     my %links = (
 5419:                 domain => {
 5420:                             upload     => 'Upload a File of Users',
 5421:                             singleuser => 'Add/Modify a User',
 5422:                             listusers  => 'Manage Users',
 5423:                             },
 5424:                 author => {
 5425:                             upload     => 'Upload a File of Co-authors',
 5426:                             singleuser => 'Add/Modify a Co-author',
 5427:                             listusers  => 'Manage Co-authors',
 5428:                             },
 5429:                 course => {
 5430:                             upload     => 'Upload a File of Course Users',
 5431:                             singleuser => 'Add/Modify a Course User',
 5432:                             listusers  => 'List and Modify Multiple Course Users',
 5433:                             },
 5434:                 community => {
 5435:                             upload     => 'Upload a File of Community Users',
 5436:                             singleuser => 'Add/Modify a Community User',
 5437:                             listusers  => 'List and Modify Multiple Community Users',
 5438:                            },
 5439:                 );
 5440:      my %linktitles = (
 5441:                 domain => {
 5442:                             singleuser => 'Add a user to the domain, and/or a course or community in the domain.',
 5443:                             listusers  => 'Show and manage users in this domain.',
 5444:                             },
 5445:                 author => {
 5446:                             singleuser => 'Add a user with a co- or assistant author role.',
 5447:                             listusers  => 'Show and manage co- or assistant authors.',
 5448:                             },
 5449:                 course => {
 5450:                             singleuser => 'Add a user with a certain role to this course.',
 5451:                             listusers  => 'Show and manage users in this course.',
 5452:                             },
 5453:                 community => {
 5454:                             singleuser => 'Add a user with a certain role to this community.',
 5455:                             listusers  => 'Show and manage users in this community.',
 5456:                            },
 5457:                 );
 5458:   if ($linkcontext eq 'domain') {
 5459:       unless ($permission->{'cusr'}) {
 5460:           $links{'domain'}{'singleuser'} = 'View a User';
 5461:           $linktitles{'domain'}{'singleuser'} = 'View information about a user in the domain';
 5462: 
 5463:       }
 5464:   } elsif ($linkcontext eq 'course') {
 5465:       unless ($permission->{'cusr'}) {
 5466:           $links{'course'}{'singleuser'} = 'View a Course User';
 5467:           $linktitles{'course'}{'singleuser'} = 'View information about a user in this course';
 5468:           $links{'course'}{'listusers'} = 'List Course Users';
 5469:           $linktitles{'course'}{'listusers'} = 'Show information about users in this course';
 5470:       }
 5471:   } elsif ($linkcontext eq 'community') {
 5472:       unless ($permission->{'cusr'}) {
 5473:           $links{'community'}{'singleuser'} = 'View a Community User';
 5474:           $linktitles{'community'}{'singleuser'} = 'View information about a user in this community';
 5475:           $links{'community'}{'listusers'} = 'List Community Users';
 5476:           $linktitles{'community'}{'listusers'} = 'Show information about users in this community';
 5477:       }
 5478:   }
 5479:   my @menu = ( {categorytitle => 'Single Users', 
 5480:          items =>
 5481:          [
 5482:             {
 5483:              linktext => $links{$linkcontext}{'singleuser'},
 5484:              icon => 'edit-redo.png',
 5485:              #help => 'Course_Change_Privileges',
 5486:              url => '/adm/createuser?action=singleuser',
 5487:              permission => ($permission->{'view'} || $permission->{'cusr'}),
 5488:              linktitle => $linktitles{$linkcontext}{'singleuser'},
 5489:             },
 5490:          ]},
 5491: 
 5492:          {categorytitle => 'Multiple Users',
 5493:          items => 
 5494:          [
 5495:             {
 5496:              linktext => $links{$linkcontext}{'upload'},
 5497:              icon => 'uplusr.png',
 5498:              #help => 'Course_Create_Class_List',
 5499:              url => '/adm/createuser?action=upload',
 5500:              permission => $permission->{'cusr'},
 5501:              linktitle => 'Upload a CSV or a text file containing users.',
 5502:             },
 5503:             {
 5504:              linktext => $links{$linkcontext}{'listusers'},
 5505:              icon => 'mngcu.png',
 5506:              #help => 'Course_View_Class_List',
 5507:              url => '/adm/createuser?action=listusers',
 5508:              permission => ($permission->{'view'} || $permission->{'cusr'}),
 5509:              linktitle => $linktitles{$linkcontext}{'listusers'}, 
 5510:             },
 5511: 
 5512:          ]},
 5513: 
 5514:          {categorytitle => 'Administration',
 5515:          items => [ ]},
 5516:        );
 5517: 
 5518:     if ($context eq 'domain'){
 5519:         push(@{  $menu[0]->{items} }, # Single Users
 5520:             {
 5521:              linktext => 'User Access Log',
 5522:              icon => 'document-properties.png',
 5523:              #help => 'User_Access_Logs',
 5524:              url => '/adm/createuser?action=accesslogs',
 5525:              permission => $permission->{'activity'},
 5526:              linktitle => 'View user access log.',
 5527:             }
 5528:         );
 5529:         
 5530:         push(@{ $menu[2]->{items} }, #Category: Administration
 5531:             {
 5532:              linktext => 'Custom Roles',
 5533:              icon => 'emblem-photos.png',
 5534:              #help => 'Course_Editing_Custom_Roles',
 5535:              url => '/adm/createuser?action=custom',
 5536:              permission => $permission->{'custom'},
 5537:              linktitle => 'Configure a custom role.',
 5538:             },
 5539:             {
 5540:              linktext => 'Authoring Space Requests',
 5541:              icon => 'selfenrl-queue.png',
 5542:              #help => 'Domain_Role_Approvals',
 5543:              url => '/adm/createuser?action=processauthorreq',
 5544:              permission => $permission->{'cusr'},
 5545:              linktitle => 'Approve or reject author role requests',
 5546:             },
 5547:             {
 5548:              linktext => 'LON-CAPA Account Requests',
 5549:              icon => 'list-add.png',
 5550:              #help => 'Domain_Username_Approvals',
 5551:              url => '/adm/createuser?action=processusernamereq',
 5552:              permission => $permission->{'cusr'},
 5553:              linktitle => 'Approve or reject LON-CAPA account requests',
 5554:             },
 5555:             {
 5556:              linktext => 'Change Log',
 5557:              icon => 'document-properties.png',
 5558:              #help => 'Course_User_Logs',
 5559:              url => '/adm/createuser?action=changelogs',
 5560:              permission => ($permission->{'cusr'} || $permission->{'view'}),
 5561:              linktitle => 'View change log.',
 5562:             },
 5563:         );
 5564:         
 5565:     }elsif ($context eq 'course'){
 5566:         my ($cnum,$cdom) = &Apache::lonuserutils::get_course_identity();
 5567: 
 5568:         my %linktext = (
 5569:                          'Course'    => {
 5570:                                           single => 'Add/Modify a Student', 
 5571:                                           drop   => 'Drop Students',
 5572:                                           groups => 'Course Groups',
 5573:                                         },
 5574:                          'Community' => {
 5575:                                           single => 'Add/Modify a Member', 
 5576:                                           drop   => 'Drop Members',
 5577:                                           groups => 'Community Groups',
 5578:                                         },
 5579:                        );
 5580: 
 5581:         my %linktitle = (
 5582:             'Course' => {
 5583:                   single => 'Add a user with the role of student to this course',
 5584:                   drop   => 'Remove a student from this course.',
 5585:                   groups => 'Manage course groups',
 5586:                         },
 5587:             'Community' => {
 5588:                   single => 'Add a user with the role of member to this community',
 5589:                   drop   => 'Remove a member from this community.',
 5590:                   groups => 'Manage community groups',
 5591:                            },
 5592:         );
 5593: 
 5594:         push(@{ $menu[0]->{items} }, #Category: Single Users
 5595:             {   
 5596:              linktext => $linktext{$crstype}{'single'},
 5597:              #help => 'Course_Add_Student',
 5598:              icon => 'list-add.png',
 5599:              url => '/adm/createuser?action=singlestudent',
 5600:              permission => $permission->{'cusr'},
 5601:              linktitle => $linktitle{$crstype}{'single'},
 5602:             },
 5603:         );
 5604:         
 5605:         push(@{ $menu[1]->{items} }, #Category: Multiple Users 
 5606:             {
 5607:              linktext => $linktext{$crstype}{'drop'},
 5608:              icon => 'edit-undo.png',
 5609:              #help => 'Course_Drop_Student',
 5610:              url => '/adm/createuser?action=drop',
 5611:              permission => $permission->{'cusr'},
 5612:              linktitle => $linktitle{$crstype}{'drop'},
 5613:             },
 5614:         );
 5615:         push(@{ $menu[2]->{items} }, #Category: Administration
 5616:             {    
 5617:              linktext => 'Custom Roles',
 5618:              icon => 'emblem-photos.png',
 5619:              #help => 'Course_Editing_Custom_Roles',
 5620:              url => '/adm/createuser?action=custom',
 5621:              permission => $permission->{'custom'},
 5622:              linktitle => 'Configure a custom role.',
 5623:             },
 5624:             {
 5625:              linktext => $linktext{$crstype}{'groups'},
 5626:              icon => 'grps.png',
 5627:              #help => 'Course_Manage_Group',
 5628:              url => '/adm/coursegroups?refpage=cusr',
 5629:              permission => $permission->{'grp_manage'},
 5630:              linktitle => $linktitle{$crstype}{'groups'},
 5631:             },
 5632:             {
 5633:              linktext => 'Change Log',
 5634:              icon => 'document-properties.png',
 5635:              #help => 'Course_User_Logs',
 5636:              url => '/adm/createuser?action=changelogs',
 5637:              permission => ($permission->{'view'} || $permission->{'cusr'}),
 5638:              linktitle => 'View change log.',
 5639:             },
 5640:         );
 5641:         if ($env{'course.'.$env{'request.course.id'}.'.internal.selfenroll_approval'}) {
 5642:             push(@{ $menu[2]->{items} },
 5643:                     {
 5644:                      linktext => 'Enrollment Requests',
 5645:                      icon => 'selfenrl-queue.png',
 5646:                      #help => 'Course_Approve_Selfenroll',
 5647:                      url => '/adm/createuser?action=selfenrollqueue',
 5648:                      permission => $permission->{'selfenrolladmin'},
 5649:                      linktitle =>'Approve or reject enrollment requests.',
 5650:                     },
 5651:             );
 5652:         }
 5653:         
 5654:         if (!exists($permission->{'cusr_section'})){
 5655:             if ($crstype ne 'Community') {
 5656:                 push(@{ $menu[2]->{items} },
 5657:                     {
 5658:                      linktext => 'Automated Enrollment',
 5659:                      icon => 'roles.png',
 5660:                      #help => 'Course_Automated_Enrollment',
 5661:                      permission => (&Apache::lonnet::auto_run($cnum,$cdom)
 5662:                                          && (($permission->{'cusr'}) ||
 5663:                                              ($permission->{'view'}))),
 5664:                      url  => '/adm/populate',
 5665:                      linktitle => 'Automated enrollment manager.',
 5666:                     }
 5667:                 );
 5668:             }
 5669:             push(@{ $menu[2]->{items} }, 
 5670:                 {
 5671:                  linktext => 'User Self-Enrollment',
 5672:                  icon => 'self_enroll.png',
 5673:                  #help => 'Course_Self_Enrollment',
 5674:                  url => '/adm/createuser?action=selfenroll',
 5675:                  permission => $permission->{'selfenrolladmin'},
 5676:                  linktitle => 'Configure user self-enrollment.',
 5677:                 },
 5678:             );
 5679:         }
 5680:     } elsif ($context eq 'author') {
 5681:         push(@{ $menu[2]->{items} }, #Category: Administration
 5682:             {
 5683:              linktext => 'Change Log',
 5684:              icon => 'document-properties.png',
 5685:              #help => 'Course_User_Logs',
 5686:              url => '/adm/createuser?action=changelogs',
 5687:              permission => $permission->{'cusr'},
 5688:              linktitle => 'View change log.',
 5689:             },
 5690:         );
 5691:     }
 5692:     return Apache::lonhtmlcommon::generate_menu(@menu);
 5693: #               { text => 'View Log-in History',
 5694: #                 help => 'Course_User_Logins',
 5695: #                 action => 'logins',
 5696: #                 permission => $permission->{'cusr'},
 5697: #               });
 5698: }
 5699: 
 5700: sub restore_prev_selections {
 5701:     my %saveable_parameters = ('srchby'   => 'scalar',
 5702: 			       'srchin'   => 'scalar',
 5703: 			       'srchtype' => 'scalar',
 5704: 			       );
 5705:     &Apache::loncommon::store_settings('user','user_picker',
 5706: 				       \%saveable_parameters);
 5707:     &Apache::loncommon::restore_settings('user','user_picker',
 5708: 					 \%saveable_parameters);
 5709: }
 5710: 
 5711: sub print_selfenroll_menu {
 5712:     my ($r,$context,$cid,$cdom,$cnum,$currsettings,$additional,$readonly) = @_;
 5713:     my $crstype = &Apache::loncommon::course_type();
 5714:     my $formname = 'selfenroll';
 5715:     my $nolink = 1;
 5716:     my ($row,$lt) = &Apache::lonuserutils::get_selfenroll_titles();
 5717:     my $groupslist = &Apache::lonuserutils::get_groupslist();
 5718:     my $setsec_js = 
 5719:         &Apache::lonuserutils::setsections_javascript($formname,$groupslist);
 5720:     my %alerts = &Apache::lonlocal::texthash(
 5721:         acto => 'Activation of self-enrollment was selected for the following domain(s)',
 5722:         butn => 'but no user types have been checked.',
 5723:         wilf => "Please uncheck 'activate' or check at least one type.",
 5724:     );
 5725:     my $disabled;
 5726:     if ($readonly) {
 5727:        $disabled = ' disabled="disabled"';
 5728:     }
 5729:     &js_escape(\%alerts);
 5730:     my $selfenroll_js = <<"ENDSCRIPT";
 5731: function update_types(caller,num) {
 5732:     var delidx = getIndexByName('selfenroll_delete');
 5733:     var actidx = getIndexByName('selfenroll_activate');
 5734:     if (caller == 'selfenroll_all') {
 5735:         var selall;
 5736:         for (var i=0; i<document.$formname.selfenroll_all.length; i++) {
 5737:             if (document.$formname.selfenroll_all[i].checked) {
 5738:                 selall = document.$formname.selfenroll_all[i].value;
 5739:             }
 5740:         }
 5741:         if (selall == 1) {
 5742:             if (delidx != -1) {
 5743:                 if (document.$formname.selfenroll_delete.length) {
 5744:                     for (var j=0; j<document.$formname.selfenroll_delete.length; j++) {
 5745:                         document.$formname.selfenroll_delete[j].checked = true;
 5746:                     }
 5747:                 } else {
 5748:                     document.$formname.elements[delidx].checked = true;
 5749:                 }
 5750:             }
 5751:             if (actidx != -1) {
 5752:                 if (document.$formname.selfenroll_activate.length) {
 5753:                     for (var j=0; j<document.$formname.selfenroll_activate.length; j++) {
 5754:                         document.$formname.selfenroll_activate[j].checked = false;
 5755:                     }
 5756:                 } else {
 5757:                     document.$formname.elements[actidx].checked = false;
 5758:                 }
 5759:             }
 5760:             document.$formname.selfenroll_newdom.selectedIndex = 0; 
 5761:         }
 5762:     }
 5763:     if (caller == 'selfenroll_activate') {
 5764:         if (document.$formname.selfenroll_activate.length) {
 5765:             for (var j=0; j<document.$formname.selfenroll_activate.length; j++) {
 5766:                 if (document.$formname.selfenroll_activate[j].value == num) {
 5767:                     if (document.$formname.selfenroll_activate[j].checked) {
 5768:                         for (var i=0; i<document.$formname.selfenroll_all.length; i++) {
 5769:                             if (document.$formname.selfenroll_all[i].value == '1') {
 5770:                                 document.$formname.selfenroll_all[i].checked = false;
 5771:                             }
 5772:                             if (document.$formname.selfenroll_all[i].value == '0') {
 5773:                                 document.$formname.selfenroll_all[i].checked = true;
 5774:                             }
 5775:                         }
 5776:                     }
 5777:                 }
 5778:             }
 5779:         } else {
 5780:             for (var i=0; i<document.$formname.selfenroll_all.length; i++) {
 5781:                 if (document.$formname.selfenroll_all[i].value == '1') {
 5782:                     document.$formname.selfenroll_all[i].checked = false;
 5783:                 }
 5784:                 if (document.$formname.selfenroll_all[i].value == '0') {
 5785:                     document.$formname.selfenroll_all[i].checked = true;
 5786:                 }
 5787:             }
 5788:         }
 5789:     }
 5790:     if (caller == 'selfenroll_delete') {
 5791:         if (document.$formname.selfenroll_delete.length) {
 5792:             for (var j=0; j<document.$formname.selfenroll_delete.length; j++) {
 5793:                 if (document.$formname.selfenroll_delete[j].value == num) {
 5794:                     if (document.$formname.selfenroll_delete[j].checked) {
 5795:                         var delindex = getIndexByName('selfenroll_types_'+num);
 5796:                         if (delindex != -1) { 
 5797:                             if (document.$formname.elements[delindex].length) {
 5798:                                 for (var k=0; k<document.$formname.elements[delindex].length; k++) {
 5799:                                     document.$formname.elements[delindex][k].checked = false;
 5800:                                 }
 5801:                             } else {
 5802:                                 document.$formname.elements[delindex].checked = false;
 5803:                             }
 5804:                         }
 5805:                     }
 5806:                 }
 5807:             }
 5808:         } else {
 5809:             if (document.$formname.selfenroll_delete.checked) {
 5810:                 var delindex = getIndexByName('selfenroll_types_'+num);
 5811:                 if (delindex != -1) {
 5812:                     if (document.$formname.elements[delindex].length) {
 5813:                         for (var k=0; k<document.$formname.elements[delindex].length; k++) {
 5814:                             document.$formname.elements[delindex][k].checked = false;
 5815:                         }
 5816:                     } else {
 5817:                         document.$formname.elements[delindex].checked = false;
 5818:                     }
 5819:                 }
 5820:             }
 5821:         }
 5822:     }
 5823:     return;
 5824: }
 5825: 
 5826: function validate_types(form) {
 5827:     var needaction = new Array();
 5828:     var countfail = 0;
 5829:     var actidx = getIndexByName('selfenroll_activate');
 5830:     if (actidx != -1) {
 5831:         if (document.$formname.selfenroll_activate.length) {
 5832:             for (var j=0; j<document.$formname.selfenroll_activate.length; j++) {
 5833:                 var num = document.$formname.selfenroll_activate[j].value;
 5834:                 if (document.$formname.selfenroll_activate[j].checked) {
 5835:                     countfail = check_types(num,countfail,needaction)
 5836:                 }
 5837:             }
 5838:         } else {
 5839:             if (document.$formname.selfenroll_activate.checked) {
 5840:                 var num = document.$formname.selfenroll_activate.value;
 5841:                 countfail = check_types(num,countfail,needaction)
 5842:             }
 5843:         }
 5844:     }
 5845:     if (countfail > 0) {
 5846:         var msg = "$alerts{'acto'}\\n";
 5847:         var loopend = needaction.length -1;
 5848:         if (loopend > 0) {
 5849:             for (var m=0; m<loopend; m++) {
 5850:                 msg += needaction[m]+", ";
 5851:             }
 5852:         }
 5853:         msg += needaction[loopend]+"\\n$alerts{'butn'}\\n$alerts{'wilf'}";
 5854:         alert(msg);
 5855:         return; 
 5856:     }
 5857:     setSections(form);
 5858: }
 5859: 
 5860: function check_types(num,countfail,needaction) {
 5861:     var typeidx = getIndexByName('selfenroll_types_'+num);
 5862:     var count = 0;
 5863:     if (typeidx != -1) {
 5864:         if (document.$formname.elements[typeidx].length) {
 5865:             for (var k=0; k<document.$formname.elements[typeidx].length; k++) {
 5866:                 if (document.$formname.elements[typeidx][k].checked) {
 5867:                     count ++;
 5868:                 }
 5869:             }
 5870:         } else {
 5871:             if (document.$formname.elements[typeidx].checked) {
 5872:                 count ++;
 5873:             }
 5874:         }
 5875:         if (count == 0) {
 5876:             var domidx = getIndexByName('selfenroll_dom_'+num);
 5877:             if (domidx != -1) {
 5878:                 var domname = document.$formname.elements[domidx].value;
 5879:                 needaction[countfail] = domname;
 5880:                 countfail ++;
 5881:             }
 5882:         }
 5883:     }
 5884:     return countfail;
 5885: }
 5886: 
 5887: function toggleNotify() {
 5888:     var selfenrollApproval = 0;
 5889:     if (document.$formname.selfenroll_approval.length) {
 5890:         for (var i=0; i<document.$formname.selfenroll_approval.length; i++) {
 5891:             if (document.$formname.selfenroll_approval[i].checked) {
 5892:                 selfenrollApproval = document.$formname.selfenroll_approval[i].value;
 5893:                 break;        
 5894:             }
 5895:         }
 5896:     }
 5897:     if (document.getElementById('notified')) {
 5898:         if (selfenrollApproval == 0) {
 5899:             document.getElementById('notified').style.display='none';
 5900:         } else {
 5901:             document.getElementById('notified').style.display='block';
 5902:         }
 5903:     }
 5904:     return;
 5905: }
 5906: 
 5907: function getIndexByName(item) {
 5908:     for (var i=0;i<document.$formname.elements.length;i++) {
 5909:         if (document.$formname.elements[i].name == item) {
 5910:             return i;
 5911:         }
 5912:     }
 5913:     return -1;
 5914: }
 5915: ENDSCRIPT
 5916: 
 5917:     my $output = '<script type="text/javascript">'."\n".
 5918:                  '// <![CDATA['."\n".
 5919:                  $setsec_js."\n".$selfenroll_js."\n".
 5920:                  '// ]]>'."\n".
 5921:                  '</script>'."\n".
 5922:                  '<h3>'.$lt->{'selfenroll'}.'</h3>'."\n";
 5923:  
 5924:     my $visactions = &cat_visibility();
 5925:     my ($cathash,%cattype);
 5926:     my %domconfig = &Apache::lonnet::get_dom('configuration',['coursecategories'],$cdom);
 5927:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 5928:         $cathash = $domconfig{'coursecategories'}{'cats'};
 5929:         $cattype{'auth'} = $domconfig{'coursecategories'}{'auth'};
 5930:         $cattype{'unauth'} = $domconfig{'coursecategories'}{'unauth'};
 5931:         if ($cattype{'auth'} eq '') {
 5932:             $cattype{'auth'} = 'std';
 5933:         }
 5934:         if ($cattype{'unauth'} eq '') {
 5935:             $cattype{'unauth'} = 'std';
 5936:         }
 5937:     } else {
 5938:         $cathash = {};
 5939:         $cattype{'auth'} = 'std';
 5940:         $cattype{'unauth'} = 'std';
 5941:     }
 5942:     if (($cattype{'auth'} eq 'none') && ($cattype{'unauth'} eq 'none')) {
 5943:         $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
 5944:                   '<br />'.
 5945:                   '<br />'.$visactions->{'take'}.'<ul>'.
 5946:                   '<li>'.$visactions->{'dc_chgconf'}.'</li>'.
 5947:                   '</ul>');
 5948:     } elsif (($cattype{'auth'} !~ /^(std|domonly)$/) && ($cattype{'unauth'} !~ /^(std|domonly)$/)) {
 5949:         if ($currsettings->{'uniquecode'}) {
 5950:             $r->print('<span class="LC_info">'.$visactions->{'vis'}.'</span>');
 5951:         } else {
 5952:             $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
 5953:                   '<br />'.
 5954:                   '<br />'.$visactions->{'take'}.'<ul>'.
 5955:                   '<li>'.$visactions->{'dc_setcode'}.'</li>'.
 5956:                   '</ul><br />');
 5957:         }
 5958:     } else {
 5959:         my ($visible,$cansetvis,$vismsgs) = &visible_in_stdcat($cdom,$cnum,\%domconfig);
 5960:         if (ref($visactions) eq 'HASH') {
 5961:             if ($visible) {
 5962:                 $output .= '<p class="LC_info">'.$visactions->{'vis'}.'</p>';
 5963:            } else {
 5964:                 $output .= '<p class="LC_warning">'.$visactions->{'miss'}.'</p>'
 5965:                           .$visactions->{'yous'}.
 5966:                            '<p>'.$visactions->{'gen'}.'<br />'.$visactions->{'coca'};
 5967:                 if (ref($vismsgs) eq 'ARRAY') {
 5968:                     $output .= '<br />'.$visactions->{'make'}.'<ul>';
 5969:                     foreach my $item (@{$vismsgs}) {
 5970:                         $output .= '<li>'.$visactions->{$item}.'</li>';
 5971:                     }
 5972:                     $output .= '</ul>';
 5973:                 }
 5974:                 $output .= '</p>';
 5975:             }
 5976:         }
 5977:     }
 5978:     my $actionhref = '/adm/createuser';
 5979:     if ($context eq 'domain') {
 5980:         $actionhref = '/adm/modifycourse';
 5981:     }
 5982: 
 5983:     my %noedit;
 5984:     unless ($context eq 'domain') {
 5985:         %noedit = &get_noedit_fields($cdom,$cnum,$crstype,$row);
 5986:     }
 5987:     $output .= '<form name="'.$formname.'" method="post" action="'.$actionhref.'">'."\n".
 5988:                &Apache::lonhtmlcommon::start_pick_box();
 5989:     if (ref($row) eq 'ARRAY') {
 5990:         foreach my $item (@{$row}) {
 5991:             my $title = $item; 
 5992:             if (ref($lt) eq 'HASH') {
 5993:                 $title = $lt->{$item};
 5994:             }
 5995:             $output .= &Apache::lonhtmlcommon::row_title($title);
 5996:             if ($item eq 'types') {
 5997:                 my $curr_types;
 5998:                 if (ref($currsettings) eq 'HASH') {
 5999:                     $curr_types = $currsettings->{'selfenroll_types'};
 6000:                 }
 6001:                 if ($noedit{$item}) {
 6002:                     if ($curr_types eq '*') {
 6003:                         $output .= &mt('Any user in any domain');   
 6004:                     } else {
 6005:                         my @entries = split(/;/,$curr_types);
 6006:                         if (@entries > 0) {
 6007:                             $output .= '<ul>'; 
 6008:                             foreach my $entry (@entries) {
 6009:                                 my ($currdom,$typestr) = split(/:/,$entry);
 6010:                                 next if ($typestr eq '');
 6011:                                 my $domdesc = &Apache::lonnet::domain($currdom);
 6012:                                 my @currinsttypes = split(',',$typestr);
 6013:                                 my ($othertitle,$usertypes,$types) = 
 6014:                                     &Apache::loncommon::sorted_inst_types($currdom);
 6015:                                 if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 6016:                                     $usertypes->{'any'} = &mt('any user'); 
 6017:                                     if (keys(%{$usertypes}) > 0) {
 6018:                                         $usertypes->{'other'} = &mt('other users');
 6019:                                     }
 6020:                                     my @longinsttypes = map { $usertypes->{$_}; } @currinsttypes;
 6021:                                     $output .= '<li>'.$domdesc.':'.join(', ',@longinsttypes).'</li>';
 6022:                                  }
 6023:                             }
 6024:                             $output .= '</ul>';
 6025:                         } else {
 6026:                             $output .= &mt('None');
 6027:                         }
 6028:                     }
 6029:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 6030:                     next;
 6031:                 }
 6032:                 my $showdomdesc = 1;
 6033:                 my $includeempty = 1;
 6034:                 my $num = 0;
 6035:                 $output .= &Apache::loncommon::start_data_table().
 6036:                            &Apache::loncommon::start_data_table_row()
 6037:                            .'<td colspan="2"><span class="LC_nobreak"><label>'
 6038:                            .&mt('Any user in any domain:')
 6039:                            .'&nbsp;<input type="radio" name="selfenroll_all" value="1" ';
 6040:                 if ($curr_types eq '*') {
 6041:                     $output .= ' checked="checked" '; 
 6042:                 }
 6043:                 $output .= 'onchange="javascript:update_types('.
 6044:                            "'selfenroll_all'".');"'.$disabled.' />'.&mt('Yes').'</label>'.
 6045:                            '&nbsp;&nbsp;<input type="radio" name="selfenroll_all" value="0" ';
 6046:                 if ($curr_types ne '*') {
 6047:                     $output .= ' checked="checked" ';
 6048:                 }
 6049:                 $output .= ' onchange="javascript:update_types('.
 6050:                            "'selfenroll_all'".');"'.$disabled.' />'.&mt('No').'</label></td>'.
 6051:                            &Apache::loncommon::end_data_table_row().
 6052:                            &Apache::loncommon::end_data_table().
 6053:                            &mt('Or').'<br />'.
 6054:                            &Apache::loncommon::start_data_table();
 6055:                 my %currdoms;
 6056:                 if ($curr_types eq '') {
 6057:                     $output .= &new_selfenroll_dom_row($cdom,'0');
 6058:                 } elsif ($curr_types ne '*') {
 6059:                     my @entries = split(/;/,$curr_types);
 6060:                     if (@entries > 0) {
 6061:                         foreach my $entry (@entries) {
 6062:                             my ($currdom,$typestr) = split(/:/,$entry);
 6063:                             $currdoms{$currdom} = 1;
 6064:                             my $domdesc = &Apache::lonnet::domain($currdom);
 6065:                             my @currinsttypes = split(',',$typestr);
 6066:                             $output .= &Apache::loncommon::start_data_table_row()
 6067:                                        .'<td valign="top"><span class="LC_nobreak">'.&mt('Domain:').'<b>'
 6068:                                        .'&nbsp;'.$domdesc.' ('.$currdom.')'
 6069:                                        .'</b><input type="hidden" name="selfenroll_dom_'.$num
 6070:                                        .'" value="'.$currdom.'" /></span><br />'
 6071:                                        .'<span class="LC_nobreak"><label><input type="checkbox" '
 6072:                                        .'name="selfenroll_delete" value="'.$num.'" onchange="javascript:update_types('."'selfenroll_delete','$num'".');"'.$disabled.' />'
 6073:                                        .&mt('Delete').'</label></span></td>';
 6074:                             $output .= '<td valign="top">&nbsp;&nbsp;'.&mt('User types:').'<br />'
 6075:                                        .&selfenroll_inst_types($num,$currdom,\@currinsttypes,$readonly).'</td>'
 6076:                                        .&Apache::loncommon::end_data_table_row();
 6077:                             $num ++;
 6078:                         }
 6079:                     }
 6080:                 }
 6081:                 my $add_domtitle = &mt('Users in additional domain:');
 6082:                 if ($curr_types eq '*') { 
 6083:                     $add_domtitle = &mt('Users in specific domain:');
 6084:                 } elsif ($curr_types eq '') {
 6085:                     $add_domtitle = &mt('Users in other domain:');
 6086:                 }
 6087:                 $output .= &Apache::loncommon::start_data_table_row()
 6088:                            .'<td colspan="2"><span class="LC_nobreak">'.$add_domtitle.'</span><br />'
 6089:                            .&Apache::loncommon::select_dom_form('','selfenroll_newdom',
 6090:                                                                 $includeempty,$showdomdesc,'','','',$readonly)
 6091:                            .'<input type="hidden" name="selfenroll_types_total" value="'.$num.'" />'
 6092:                            .'</td>'.&Apache::loncommon::end_data_table_row()
 6093:                            .&Apache::loncommon::end_data_table();
 6094:             } elsif ($item eq 'registered') {
 6095:                 my ($regon,$regoff);
 6096:                 my $registered;
 6097:                 if (ref($currsettings) eq 'HASH') {
 6098:                     $registered = $currsettings->{'selfenroll_registered'};
 6099:                 }
 6100:                 if ($noedit{$item}) {
 6101:                     if ($registered) {
 6102:                         $output .= &mt('Must be registered in course');
 6103:                     } else {
 6104:                         $output .= &mt('No requirement');
 6105:                     }
 6106:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 6107:                     next;
 6108:                 }
 6109:                 if ($registered) {
 6110:                     $regon = ' checked="checked" ';
 6111:                     $regoff = '';
 6112:                 } else {
 6113:                     $regon = '';
 6114:                     $regoff = ' checked="checked" ';
 6115:                 }
 6116:                 $output .= '<label>'.
 6117:                            '<input type="radio" name="selfenroll_registered" value="1"'.$regon.$disabled.' />'.
 6118:                            &mt('Yes').'</label>&nbsp;&nbsp;<label>'.
 6119:                            '<input type="radio" name="selfenroll_registered" value="0"'.$regoff.$disabled.' />'.
 6120:                            &mt('No').'</label>';
 6121:             } elsif ($item eq 'enroll_dates') {
 6122:                 my ($starttime,$endtime);
 6123:                 if (ref($currsettings) eq 'HASH') {
 6124:                     $starttime = $currsettings->{'selfenroll_start_date'};
 6125:                     $endtime = $currsettings->{'selfenroll_end_date'};
 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_date',$starttime,
 6141:                                       $disabled,undef,undef,undef,undef,undef,undef,$nolink);
 6142:                 my $endform =
 6143:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_end_date',$endtime,
 6144:                                       $disabled,undef,undef,undef,undef,undef,undef,$nolink);
 6145:                 $output .= &selfenroll_date_forms($startform,$endform);
 6146:             } elsif ($item eq 'access_dates') {
 6147:                 my ($starttime,$endtime);
 6148:                 if (ref($currsettings) eq 'HASH') {
 6149:                     $starttime = $currsettings->{'selfenroll_start_access'};
 6150:                     $endtime = $currsettings->{'selfenroll_end_access'};
 6151:                     if ($starttime eq '') {
 6152:                         $starttime = $currsettings->{'default_enrollment_start_date'};
 6153:                     }
 6154:                     if ($endtime eq '') {
 6155:                         $endtime = $currsettings->{'default_enrollment_end_date'};
 6156:                     }
 6157:                 }
 6158:                 if ($noedit{$item}) {
 6159:                     $output .= &mt('From: [_1], to: [_2]',&Apache::lonlocal::locallocaltime($starttime),
 6160:                                                           &Apache::lonlocal::locallocaltime($endtime));
 6161:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 6162:                     next;
 6163:                 }
 6164:                 my $startform =
 6165:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_start_access',$starttime,
 6166:                                       $disabled,undef,undef,undef,undef,undef,undef,$nolink);
 6167:                 my $endform =
 6168:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_end_access',$endtime,
 6169:                                       $disabled,undef,undef,undef,undef,undef,undef,$nolink);
 6170:                 $output .= &selfenroll_date_forms($startform,$endform);
 6171:             } elsif ($item eq 'section') {
 6172:                 my $currsec;
 6173:                 if (ref($currsettings) eq 'HASH') {
 6174:                     $currsec = $currsettings->{'selfenroll_section'};
 6175:                 }
 6176:                 my %sections_count = &Apache::loncommon::get_sections($cdom,$cnum);
 6177:                 my $newsecval;
 6178:                 if ($currsec ne 'none' && $currsec ne '') {
 6179:                     if (!defined($sections_count{$currsec})) {
 6180:                         $newsecval = $currsec;
 6181:                     }
 6182:                 }
 6183:                 if ($noedit{$item}) {
 6184:                     if ($currsec ne '') {
 6185:                         $output .= $currsec;
 6186:                     } else {
 6187:                         $output .= &mt('No specific section');
 6188:                     }
 6189:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 6190:                     next;
 6191:                 }
 6192:                 my $sections_select = 
 6193:                     &Apache::lonuserutils::course_sections(\%sections_count,'st',$currsec,$disabled);
 6194:                 $output .= '<table class="LC_createuser">'."\n".
 6195:                            '<tr class="LC_section_row">'."\n".
 6196:                            '<td align="center">'.&mt('Existing sections')."\n".
 6197:                            '<br />'.$sections_select.'</td><td align="center">'.
 6198:                            &mt('New section').'<br />'."\n".
 6199:                            '<input type="text" name="newsec" size="15" value="'.$newsecval.'"'.$disabled.' />'."\n".
 6200:                            '<input type="hidden" name="sections" value="" />'."\n".
 6201:                            '</td></tr></table>'."\n";
 6202:             } elsif ($item eq 'approval') {
 6203:                 my ($currnotified,$currapproval,%appchecked);
 6204:                 my %selfdescs = &Apache::lonuserutils::selfenroll_default_descs();
 6205:                 if (ref($currsettings) eq 'HASH') {
 6206:                     $currnotified = $currsettings->{'selfenroll_notifylist'};
 6207:                     $currapproval = $currsettings->{'selfenroll_approval'};
 6208:                 }
 6209:                 if ($currapproval !~ /^[012]$/) {
 6210:                     $currapproval = 0;
 6211:                 }
 6212:                 if ($noedit{$item}) {
 6213:                     $output .=  $selfdescs{'approval'}{$currapproval}.
 6214:                                 '<br />'.&mt('(Set by Domain Coordinator)');
 6215:                     next;
 6216:                 }
 6217:                 $appchecked{$currapproval} = ' checked="checked"';
 6218:                 for my $i (0..2) {
 6219:                     $output .= '<label>'.
 6220:                                '<input type="radio" name="selfenroll_approval" value="'.$i.'"'.
 6221:                                $appchecked{$i}.' onclick="toggleNotify();"'.$disabled.' />'.
 6222:                                $selfdescs{'approval'}{$i}.'</label>'.('&nbsp;'x2);
 6223:                 }
 6224:                 my %advhash = &Apache::lonnet::get_course_adv_roles($cid,1);
 6225:                 my (@ccs,%notified);
 6226:                 my $ccrole = 'cc';
 6227:                 if ($crstype eq 'Community') {
 6228:                     $ccrole = 'co';
 6229:                 }
 6230:                 if ($advhash{$ccrole}) {
 6231:                     @ccs = split(/,/,$advhash{$ccrole});
 6232:                 }
 6233:                 if ($currnotified) {
 6234:                     foreach my $current (split(/,/,$currnotified)) {
 6235:                         $notified{$current} = 1;
 6236:                         if (!grep(/^\Q$current\E$/,@ccs)) {
 6237:                             push(@ccs,$current);
 6238:                         }
 6239:                     }
 6240:                 }
 6241:                 if (@ccs) {
 6242:                     my $style;
 6243:                     unless ($currapproval) {
 6244:                         $style = ' style="display: none;"'; 
 6245:                     }
 6246:                     $output .= '<br /><div id="notified"'.$style.'>'.
 6247:                                &mt('Personnel to be notified when an enrollment request needs approval, or has been approved:').'&nbsp;'.
 6248:                                &Apache::loncommon::start_data_table().
 6249:                                &Apache::loncommon::start_data_table_row();
 6250:                     my $count = 0;
 6251:                     my $numcols = 4;
 6252:                     foreach my $cc (sort(@ccs)) {
 6253:                         my $notifyon;
 6254:                         my ($ccuname,$ccudom) = split(/:/,$cc);
 6255:                         if ($notified{$cc}) {
 6256:                             $notifyon = ' checked="checked" ';
 6257:                         }
 6258:                         if ($count && !$count%$numcols) {
 6259:                             $output .= &Apache::loncommon::end_data_table_row().
 6260:                                        &Apache::loncommon::start_data_table_row()
 6261:                         }
 6262:                         $output .= '<td><span class="LC_nobreak"><label>'.
 6263:                                    '<input type="checkbox" name="selfenroll_notify"'.$notifyon.' value="'.$cc.'"'.$disabled.' />'.
 6264:                                    &Apache::loncommon::plainname($ccuname,$ccudom).
 6265:                                    '</label></span></td>';
 6266:                         $count ++;
 6267:                     }
 6268:                     my $rem = $count%$numcols;
 6269:                     if ($rem) {
 6270:                         my $emptycols = $numcols - $rem;
 6271:                         for (my $i=0; $i<$emptycols; $i++) { 
 6272:                             $output .= '<td>&nbsp;</td>';
 6273:                         }
 6274:                     }
 6275:                     $output .= &Apache::loncommon::end_data_table_row().
 6276:                                &Apache::loncommon::end_data_table().
 6277:                                '</div>';
 6278:                 }
 6279:             } elsif ($item eq 'limit') {
 6280:                 my ($crslimit,$selflimit,$nolimit,$currlim,$currcap);
 6281:                 if (ref($currsettings) eq 'HASH') {
 6282:                     $currlim = $currsettings->{'selfenroll_limit'};
 6283:                     $currcap = $currsettings->{'selfenroll_cap'};
 6284:                 }
 6285:                 if ($noedit{$item}) {
 6286:                     if (($currlim eq 'allstudents') || ($currlim eq 'selfenrolled')) {
 6287:                         if ($currlim eq 'allstudents') {
 6288:                             $output .= &mt('Limit by total students');
 6289:                         } elsif ($currlim eq 'selfenrolled') {
 6290:                             $output .= &mt('Limit by total self-enrolled students');
 6291:                         }
 6292:                         $output .= ' '.&mt('Maximum: [_1]',$currcap).
 6293:                                    '<br />'.&mt('(Set by Domain Coordinator)');
 6294:                     } else {
 6295:                         $output .= &mt('No limit').'<br />'.&mt('(Set by Domain Coordinator)');
 6296:                     }
 6297:                     next;
 6298:                 }
 6299:                 if ($currlim eq 'allstudents') {
 6300:                     $crslimit = ' checked="checked" ';
 6301:                     $selflimit = ' ';
 6302:                     $nolimit = ' ';
 6303:                 } elsif ($currlim eq 'selfenrolled') {
 6304:                     $crslimit = ' ';
 6305:                     $selflimit = ' checked="checked" ';
 6306:                     $nolimit = ' '; 
 6307:                 } else {
 6308:                     $crslimit = ' ';
 6309:                     $selflimit = ' ';
 6310:                     $nolimit = ' checked="checked" ';
 6311:                 }
 6312:                 $output .= '<table><tr><td><label>'.
 6313:                            '<input type="radio" name="selfenroll_limit" value="none"'.$nolimit.$disabled.'/>'.
 6314:                            &mt('No limit').'</label></td><td><label>'.
 6315:                            '<input type="radio" name="selfenroll_limit" value="allstudents"'.$crslimit.$disabled.'/>'.
 6316:                            &mt('Limit by total students').'</label></td><td><label>'.
 6317:                            '<input type="radio" name="selfenroll_limit" value="selfenrolled"'.$selflimit.$disabled.'/>'.
 6318:                            &mt('Limit by total self-enrolled students').
 6319:                            '</td></tr><tr>'.
 6320:                            '<td>&nbsp;</td><td colspan="2"><span class="LC_nobreak">'.
 6321:                            ('&nbsp;'x3).&mt('Maximum number allowed: ').
 6322:                            '<input type="text" name="selfenroll_cap" size = "5" value="'.$currcap.'"'.$disabled.' /></td></tr></table>';
 6323:             }
 6324:             $output .= &Apache::lonhtmlcommon::row_closure(1);
 6325:         }
 6326:     }
 6327:     $output .= &Apache::lonhtmlcommon::end_pick_box().'<br />';
 6328:     unless ($readonly) {
 6329:         $output .= '<input type="button" name="selfenrollconf" value="'
 6330:                    .&mt('Save').'" onclick="validate_types(this.form);" />';
 6331:     }
 6332:     $output .= '<input type="hidden" name="action" value="selfenroll" />'
 6333:                .'<input type="hidden" name="state" value="done" />'."\n"
 6334:                .$additional.'</form>';
 6335:     $r->print($output);
 6336:     return;
 6337: }
 6338: 
 6339: sub get_noedit_fields {
 6340:     my ($cdom,$cnum,$crstype,$row) = @_;
 6341:     my %noedit;
 6342:     if (ref($row) eq 'ARRAY') {
 6343:         my %settings = &Apache::lonnet::get('environment',['internal.coursecode','internal.textbook',
 6344:                                                            'internal.selfenrollmgrdc',
 6345:                                                            'internal.selfenrollmgrcc'],$cdom,$cnum);
 6346:         my $type = &Apache::lonuserutils::get_extended_type($cdom,$cnum,$crstype,\%settings);
 6347:         my (%specific_managebydc,%specific_managebycc,%default_managebydc);
 6348:         map { $specific_managebydc{$_} = 1; } (split(/,/,$settings{'internal.selfenrollmgrdc'}));
 6349:         map { $specific_managebycc{$_} = 1; } (split(/,/,$settings{'internal.selfenrollmgrcc'}));
 6350:         my %domdefaults = &Apache::lonnet::get_domain_defaults($cdom);
 6351:         map { $default_managebydc{$_} = 1; } (split(/,/,$domdefaults{$type.'selfenrolladmdc'}));
 6352: 
 6353:         foreach my $item (@{$row}) {
 6354:             next if ($specific_managebycc{$item});
 6355:             if (($specific_managebydc{$item}) || ($default_managebydc{$item})) {
 6356:                 $noedit{$item} = 1;
 6357:             }
 6358:         }
 6359:     }
 6360:     return %noedit;
 6361: } 
 6362: 
 6363: sub visible_in_stdcat {
 6364:     my ($cdom,$cnum,$domconf) = @_;
 6365:     my ($cathash,%settable,@vismsgs,$cansetvis,$visible);
 6366:     unless (ref($domconf) eq 'HASH') {
 6367:         return ($visible,$cansetvis,\@vismsgs);
 6368:     }
 6369:     if (ref($domconf->{'coursecategories'}) eq 'HASH') {
 6370:         if ($domconf->{'coursecategories'}{'togglecats'} eq 'crs') {
 6371:             $settable{'togglecats'} = 1;
 6372:         }
 6373:         if ($domconf->{'coursecategories'}{'categorize'} eq 'crs') {
 6374:             $settable{'categorize'} = 1;
 6375:         }
 6376:         $cathash = $domconf->{'coursecategories'}{'cats'};
 6377:     }
 6378:     if ($settable{'togglecats'} && $settable{'categorize'}) {
 6379:         $cansetvis = &mt('You are able to both assign a course category and choose to exclude this course from the catalog.');   
 6380:     } elsif ($settable{'togglecats'}) {
 6381:         $cansetvis = &mt('You are able to choose to exclude this course from the catalog, but only a Domain Coordinator may assign a course category.'); 
 6382:     } elsif ($settable{'categorize'}) {
 6383:         $cansetvis = &mt('You may assign a course category, but only a Domain Coordinator may choose to exclude this course from the catalog.');  
 6384:     } else {
 6385:         $cansetvis = &mt('Only a Domain Coordinator may assign a course category or choose to exclude this course from the catalog.'); 
 6386:     }
 6387:      
 6388:     my %currsettings =
 6389:         &Apache::lonnet::get('environment',['hidefromcat','categories','internal.coursecode'],
 6390:                              $cdom,$cnum);
 6391:     $visible = 0;
 6392:     if ($currsettings{'internal.coursecode'} ne '') {
 6393:         if (ref($domconf->{'coursecategories'}) eq 'HASH') {
 6394:             $cathash = $domconf->{'coursecategories'}{'cats'};
 6395:             if (ref($cathash) eq 'HASH') {
 6396:                 if ($cathash->{'instcode::0'} eq '') {
 6397:                     push(@vismsgs,'dc_addinst'); 
 6398:                 } else {
 6399:                     $visible = 1;
 6400:                 }
 6401:             } else {
 6402:                 $visible = 1;
 6403:             }
 6404:         } else {
 6405:             $visible = 1;
 6406:         }
 6407:     } else {
 6408:         if (ref($cathash) eq 'HASH') {
 6409:             if ($cathash->{'instcode::0'} ne '') {
 6410:                 push(@vismsgs,'dc_instcode');
 6411:             }
 6412:         } else {
 6413:             push(@vismsgs,'dc_instcode');
 6414:         }
 6415:     }
 6416:     if ($currsettings{'categories'} ne '') {
 6417:         my $cathash;
 6418:         if (ref($domconf->{'coursecategories'}) eq 'HASH') {
 6419:             $cathash = $domconf->{'coursecategories'}{'cats'};
 6420:             if (ref($cathash) eq 'HASH') {
 6421:                 if (keys(%{$cathash}) == 0) {
 6422:                     push(@vismsgs,'dc_catalog');
 6423:                 } elsif ((keys(%{$cathash}) == 1) && ($cathash->{'instcode::0'} ne '')) {
 6424:                     push(@vismsgs,'dc_categories');
 6425:                 } else {
 6426:                     my @currcategories = split('&',$currsettings{'categories'});
 6427:                     my $matched = 0;
 6428:                     foreach my $cat (@currcategories) {
 6429:                         if ($cathash->{$cat} ne '') {
 6430:                             $visible = 1;
 6431:                             $matched = 1;
 6432:                             last;
 6433:                         }
 6434:                     }
 6435:                     if (!$matched) {
 6436:                         if ($settable{'categorize'}) { 
 6437:                             push(@vismsgs,'chgcat');
 6438:                         } else {
 6439:                             push(@vismsgs,'dc_chgcat');
 6440:                         }
 6441:                     }
 6442:                 }
 6443:             }
 6444:         }
 6445:     } else {
 6446:         if (ref($cathash) eq 'HASH') {
 6447:             if ((keys(%{$cathash}) > 1) || 
 6448:                 (keys(%{$cathash}) == 1) && ($cathash->{'instcode::0'} eq '')) {
 6449:                 if ($settable{'categorize'}) {
 6450:                     push(@vismsgs,'addcat');
 6451:                 } else {
 6452:                     push(@vismsgs,'dc_addcat');
 6453:                 }
 6454:             }
 6455:         }
 6456:     }
 6457:     if ($currsettings{'hidefromcat'} eq 'yes') {
 6458:         $visible = 0;
 6459:         if ($settable{'togglecats'}) {
 6460:             unshift(@vismsgs,'unhide');
 6461:         } else {
 6462:             unshift(@vismsgs,'dc_unhide')
 6463:         }
 6464:     }
 6465:     return ($visible,$cansetvis,\@vismsgs);
 6466: }
 6467: 
 6468: sub cat_visibility {
 6469:     my %visactions = &Apache::lonlocal::texthash(
 6470:                    vis => 'This course/community currently appears in the Course/Community Catalog for this domain.',
 6471:                    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.',
 6472:                    miss => 'This course/community does not currently appear in the Course/Community Catalog for this domain.',
 6473:                    none => 'Display of a course catalog is disabled for this domain.',
 6474:                    yous => 'You should remedy this if you plan to allow self-enrollment, otherwise students will have difficulty finding this course.',
 6475:                    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.',
 6476:                    make => 'Make any changes to self-enrollment settings below, click "Save", then take action to include the course in the Catalog:',
 6477:                    take => 'Take the following action to ensure the course appears in the Catalog:',
 6478:                    dc_chgconf => 'Ask a domain coordinator to change the Catalog type for this domain.',
 6479:                    dc_setcode => 'Ask a domain coordinator to assign a six character code to the course',
 6480:                    dc_unhide  => 'Ask a domain coordinator to change the "Exclude from course catalog" setting.',
 6481:                    dc_addinst => 'Ask a domain coordinator to enable display the catalog of "Official courses (with institutional codes)".',
 6482:                    dc_instcode => 'Ask a domain coordinator to assign an institutional code (if this is an official course).',
 6483:                    dc_catalog  => 'Ask a domain coordinator to enable or create at least one course category in the domain.',
 6484:                    dc_categories => 'Ask a domain coordinator to create a hierarchy of categories and sub categories for courses in the domain.',
 6485:                    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',
 6486:                    dc_addcat => 'Ask a domain coordinator to assign a category to the course.',
 6487:     );
 6488:     $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>"');
 6489:     $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>"');
 6490:     $visactions{'addcat'} = &mt('Use [_1]Categorize course[_2] to assign a category to the course.','"<a href="/adm/courseprefs?phase=display&actions=courseinfo">','</a>"');
 6491:     return \%visactions;
 6492: }
 6493: 
 6494: sub new_selfenroll_dom_row {
 6495:     my ($newdom,$num) = @_;
 6496:     my $domdesc = &Apache::lonnet::domain($newdom);
 6497:     my $output;
 6498:     if ($domdesc ne '') {
 6499:         $output .= &Apache::loncommon::start_data_table_row()
 6500:                    .'<td valign="top"><span class="LC_nobreak">'.&mt('Domain:').'&nbsp;<b>'.$domdesc
 6501:                    .' ('.$newdom.')</b><input type="hidden" name="selfenroll_dom_'.$num
 6502:                    .'" value="'.$newdom.'" /></span><br />'
 6503:                    .'<span class="LC_nobreak"><label><input type="checkbox" '
 6504:                    .'name="selfenroll_activate" value="'.$num.'" '
 6505:                    .'onchange="javascript:update_types('
 6506:                    ."'selfenroll_activate','$num'".');" />'
 6507:                    .&mt('Activate').'</label></span></td>';
 6508:         my @currinsttypes;
 6509:         $output .= '<td>'.&mt('User types:').'<br />'
 6510:                    .&selfenroll_inst_types($num,$newdom,\@currinsttypes).'</td>'
 6511:                    .&Apache::loncommon::end_data_table_row();
 6512:     }
 6513:     return $output;
 6514: }
 6515: 
 6516: sub selfenroll_inst_types {
 6517:     my ($num,$currdom,$currinsttypes,$readonly) = @_;
 6518:     my $output;
 6519:     my $numinrow = 4;
 6520:     my $count = 0;
 6521:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($currdom);
 6522:     my $othervalue = 'any';
 6523:     my $disabled;
 6524:     if ($readonly) {
 6525:         $disabled = ' disabled="disabled"';
 6526:     }
 6527:     if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 6528:         if (keys(%{$usertypes}) > 0) {
 6529:             $othervalue = 'other';
 6530:         }
 6531:         $output .= '<table><tr>';
 6532:         foreach my $type (@{$types}) {
 6533:             if (($count > 0) && ($count%$numinrow == 0)) {
 6534:                 $output .= '</tr><tr>';
 6535:             }
 6536:             if (defined($usertypes->{$type})) {
 6537:                 my $esc_type = &escape($type);
 6538:                 $output .= '<td><span class="LC_nobreak"><label><input type = "checkbox" value="'.
 6539:                            $esc_type.'" ';
 6540:                 if (ref($currinsttypes) eq 'ARRAY') {
 6541:                     if (@{$currinsttypes} > 0) {
 6542:                         if (grep(/^any$/,@{$currinsttypes})) {
 6543:                             $output .= 'checked="checked"';
 6544:                         } elsif (grep(/^\Q$esc_type\E$/,@{$currinsttypes})) {
 6545:                             $output .= 'checked="checked"';
 6546:                         }
 6547:                     } else {
 6548:                         $output .= 'checked="checked"';
 6549:                     }
 6550:                 }
 6551:                 $output .= ' name="selfenroll_types_'.$num.'"'.$disabled.' />'.$usertypes->{$type}.'</label></span></td>';
 6552:             }
 6553:             $count ++;
 6554:         }
 6555:         if (($count > 0) && ($count%$numinrow == 0)) {
 6556:             $output .= '</tr><tr>';
 6557:         }
 6558:         $output .= '<td><span class="LC_nobreak"><label><input type = "checkbox" value="'.$othervalue.'"';
 6559:         if (ref($currinsttypes) eq 'ARRAY') {
 6560:             if (@{$currinsttypes} > 0) {
 6561:                 if (grep(/^any$/,@{$currinsttypes})) { 
 6562:                     $output .= ' checked="checked"';
 6563:                 } elsif ($othervalue eq 'other') {
 6564:                     if (grep(/^\Q$othervalue\E$/,@{$currinsttypes})) {
 6565:                         $output .= ' checked="checked"';
 6566:                     }
 6567:                 }
 6568:             } else {
 6569:                 $output .= ' checked="checked"';
 6570:             }
 6571:         } else {
 6572:             $output .= ' checked="checked"';
 6573:         }
 6574:         $output .= ' name="selfenroll_types_'.$num.'"'.$disabled.' />'.$othertitle.'</label></span></td></tr></table>';
 6575:     }
 6576:     return $output;
 6577: }
 6578: 
 6579: sub selfenroll_date_forms {
 6580:     my ($startform,$endform) = @_;
 6581:     my $output .= &Apache::lonhtmlcommon::start_pick_box()."\n".
 6582:                   &Apache::lonhtmlcommon::row_title(&mt('Start date'),
 6583:                                                     'LC_oddrow_value')."\n".
 6584:                   $startform."\n".
 6585:                   &Apache::lonhtmlcommon::row_closure(1).
 6586:                   &Apache::lonhtmlcommon::row_title(&mt('End date'),
 6587:                                                    'LC_oddrow_value')."\n".
 6588:                   $endform."\n".
 6589:                   &Apache::lonhtmlcommon::row_closure(1).
 6590:                   &Apache::lonhtmlcommon::end_pick_box();
 6591:     return $output;
 6592: }
 6593: 
 6594: sub print_userchangelogs_display {
 6595:     my ($r,$context,$permission,$brcrum) = @_;
 6596:     my $formname = 'rolelog';
 6597:     my ($username,$domain,$crstype,$viewablesec,%roleslog);
 6598:     if ($context eq 'domain') {
 6599:         $domain = $env{'request.role.domain'};
 6600:         %roleslog=&Apache::lonnet::dump_dom('nohist_rolelog',$domain);
 6601:     } else {
 6602:         if ($context eq 'course') { 
 6603:             $domain = $env{'course.'.$env{'request.course.id'}.'.domain'};
 6604:             $username = $env{'course.'.$env{'request.course.id'}.'.num'};
 6605:             $crstype = &Apache::loncommon::course_type();
 6606:             $viewablesec = &Apache::lonuserutils::viewable_section($permission);
 6607:             my %saveable_parameters = ('show' => 'scalar',);
 6608:             &Apache::loncommon::store_course_settings('roles_log',
 6609:                                                       \%saveable_parameters);
 6610:             &Apache::loncommon::restore_course_settings('roles_log',
 6611:                                                         \%saveable_parameters);
 6612:         } elsif ($context eq 'author') {
 6613:             $domain = $env{'user.domain'}; 
 6614:             if ($env{'request.role'} =~ m{^au\./\Q$domain\E/$}) {
 6615:                 $username = $env{'user.name'};
 6616:             } else {
 6617:                 undef($domain);
 6618:             }
 6619:         }
 6620:         if ($domain ne '' && $username ne '') { 
 6621:             %roleslog=&Apache::lonnet::dump('nohist_rolelog',$domain,$username);
 6622:         }
 6623:     }
 6624:     if ((keys(%roleslog))[0]=~/^error\:/) { undef(%roleslog); }
 6625: 
 6626:     my $helpitem;
 6627:     if ($context eq 'course') {
 6628:         $helpitem = 'Course_User_Logs';
 6629:     }
 6630:     push (@{$brcrum},
 6631:              {href => '/adm/createuser?action=changelogs',
 6632:               text => 'User Management Logs',
 6633:               help => $helpitem});
 6634:     my $bread_crumbs_component = 'User Changes';
 6635:     my $args = { bread_crumbs           => $brcrum,
 6636:                  bread_crumbs_component => $bread_crumbs_component};
 6637: 
 6638:     # Create navigation javascript
 6639:     my $jsnav = &userlogdisplay_js($formname);
 6640: 
 6641:     my $jscript = (<<ENDSCRIPT);
 6642: <script type="text/javascript">
 6643: // <![CDATA[
 6644: $jsnav
 6645: // ]]>
 6646: </script>
 6647: ENDSCRIPT
 6648: 
 6649:     # print page header
 6650:     $r->print(&header($jscript,$args));
 6651: 
 6652:     # set defaults
 6653:     my $now = time();
 6654:     my $defstart = $now - (7*24*3600); #7 days ago 
 6655:     my %defaults = (
 6656:                      page               => '1',
 6657:                      show               => '10',
 6658:                      role               => 'any',
 6659:                      chgcontext         => 'any',
 6660:                      rolelog_start_date => $defstart,
 6661:                      rolelog_end_date   => $now,
 6662:                    );
 6663:     my $more_records = 0;
 6664: 
 6665:     # set current
 6666:     my %curr;
 6667:     foreach my $item ('show','page','role','chgcontext') {
 6668:         $curr{$item} = $env{'form.'.$item};
 6669:     }
 6670:     my ($startdate,$enddate) = 
 6671:         &Apache::lonuserutils::get_dates_from_form('rolelog_start_date','rolelog_end_date');
 6672:     $curr{'rolelog_start_date'} = $startdate;
 6673:     $curr{'rolelog_end_date'} = $enddate;
 6674:     foreach my $key (keys(%defaults)) {
 6675:         if ($curr{$key} eq '') {
 6676:             $curr{$key} = $defaults{$key};
 6677:         }
 6678:     }
 6679:     my (%whodunit,%changed,$version);
 6680:     ($version) = ($r->dir_config('lonVersion') =~ /^([\d\.]+)\-/);
 6681:     my ($minshown,$maxshown);
 6682:     $minshown = 1;
 6683:     my $count = 0;
 6684:     if ($curr{'show'} =~ /\D/) {
 6685:         $curr{'page'} = 1;
 6686:     } else {
 6687:         $maxshown = $curr{'page'} * $curr{'show'};
 6688:         if ($curr{'page'} > 1) {
 6689:             $minshown = 1 + ($curr{'page'} - 1) * $curr{'show'};
 6690:         }
 6691:     }
 6692: 
 6693:     # Form Header
 6694:     $r->print('<form action="/adm/createuser" method="post" name="'.$formname.'">'.
 6695:               &role_display_filter($context,$formname,$domain,$username,\%curr,
 6696:                                    $version,$crstype));
 6697: 
 6698:     my $showntableheader = 0;
 6699: 
 6700:     # Table Header
 6701:     my $tableheader = 
 6702:         &Apache::loncommon::start_data_table_header_row()
 6703:        .'<th>&nbsp;</th>'
 6704:        .'<th>'.&mt('When').'</th>'
 6705:        .'<th>'.&mt('Who made the change').'</th>'
 6706:        .'<th>'.&mt('Changed User').'</th>'
 6707:        .'<th>'.&mt('Role').'</th>';
 6708: 
 6709:     if ($context eq 'course') {
 6710:         $tableheader .= '<th>'.&mt('Section').'</th>';
 6711:     }
 6712:     $tableheader .=
 6713:         '<th>'.&mt('Context').'</th>'
 6714:        .'<th>'.&mt('Start').'</th>'
 6715:        .'<th>'.&mt('End').'</th>'
 6716:        .&Apache::loncommon::end_data_table_header_row();
 6717: 
 6718:     # Display user change log data
 6719:     foreach my $id (sort { $roleslog{$b}{'exe_time'}<=>$roleslog{$a}{'exe_time'} } (keys(%roleslog))) {
 6720:         next if (($roleslog{$id}{'exe_time'} < $curr{'rolelog_start_date'}) ||
 6721:                  ($roleslog{$id}{'exe_time'} > $curr{'rolelog_end_date'}));
 6722:         if ($curr{'show'} !~ /\D/) {
 6723:             if ($count >= $curr{'page'} * $curr{'show'}) {
 6724:                 $more_records = 1;
 6725:                 last;
 6726:             }
 6727:         }
 6728:         if ($curr{'role'} ne 'any') {
 6729:             next if ($roleslog{$id}{'logentry'}{'role'} ne $curr{'role'}); 
 6730:         }
 6731:         if ($curr{'chgcontext'} ne 'any') {
 6732:             if ($curr{'chgcontext'} eq 'selfenroll') {
 6733:                 next if (!$roleslog{$id}{'logentry'}{'selfenroll'});
 6734:             } else {
 6735:                 next if ($roleslog{$id}{'logentry'}{'context'} ne $curr{'chgcontext'});
 6736:             }
 6737:         }
 6738:         if (($context eq 'course') && ($viewablesec ne '')) {
 6739:             next if ($roleslog{$id}{'logentry'}{'section'} ne $viewablesec);
 6740:         }
 6741:         $count ++;
 6742:         next if ($count < $minshown);
 6743:         unless ($showntableheader) {
 6744:             $r->print(&Apache::loncommon::start_data_table()
 6745:                      .$tableheader);
 6746:             $r->rflush();
 6747:             $showntableheader = 1;
 6748:         }
 6749:         if ($whodunit{$roleslog{$id}{'exe_uname'}.':'.$roleslog{$id}{'exe_udom'}} eq '') {
 6750:             $whodunit{$roleslog{$id}{'exe_uname'}.':'.$roleslog{$id}{'exe_udom'}} =
 6751:                 &Apache::loncommon::plainname($roleslog{$id}{'exe_uname'},$roleslog{$id}{'exe_udom'});
 6752:         }
 6753:         if ($changed{$roleslog{$id}{'uname'}.':'.$roleslog{$id}{'udom'}} eq '') {
 6754:             $changed{$roleslog{$id}{'uname'}.':'.$roleslog{$id}{'udom'}} =
 6755:                 &Apache::loncommon::plainname($roleslog{$id}{'uname'},$roleslog{$id}{'udom'});
 6756:         }
 6757:         my $sec = $roleslog{$id}{'logentry'}{'section'};
 6758:         if ($sec eq '') {
 6759:             $sec = &mt('None');
 6760:         }
 6761:         my ($rolestart,$roleend);
 6762:         if ($roleslog{$id}{'delflag'}) {
 6763:             $rolestart = &mt('deleted');
 6764:             $roleend = &mt('deleted');
 6765:         } else {
 6766:             $rolestart = $roleslog{$id}{'logentry'}{'start'};
 6767:             $roleend = $roleslog{$id}{'logentry'}{'end'};
 6768:             if ($rolestart eq '' || $rolestart == 0) {
 6769:                 $rolestart = &mt('No start date'); 
 6770:             } else {
 6771:                 $rolestart = &Apache::lonlocal::locallocaltime($rolestart);
 6772:             }
 6773:             if ($roleend eq '' || $roleend == 0) { 
 6774:                 $roleend = &mt('No end date');
 6775:             } else {
 6776:                 $roleend = &Apache::lonlocal::locallocaltime($roleend);
 6777:             }
 6778:         }
 6779:         my $chgcontext = $roleslog{$id}{'logentry'}{'context'};
 6780:         if ($roleslog{$id}{'logentry'}{'selfenroll'}) {
 6781:             $chgcontext = 'selfenroll';
 6782:         }
 6783:         my %lt = &rolechg_contexts($context,$crstype);
 6784:         if ($chgcontext ne '' && $lt{$chgcontext} ne '') {
 6785:             $chgcontext = $lt{$chgcontext};
 6786:         }
 6787:         $r->print(
 6788:             &Apache::loncommon::start_data_table_row()
 6789:            .'<td>'.$count.'</td>'
 6790:            .'<td>'.&Apache::lonlocal::locallocaltime($roleslog{$id}{'exe_time'}).'</td>'
 6791:            .'<td>'.$whodunit{$roleslog{$id}{'exe_uname'}.':'.$roleslog{$id}{'exe_udom'}}.'</td>'
 6792:            .'<td>'.$changed{$roleslog{$id}{'uname'}.':'.$roleslog{$id}{'udom'}}.'</td>'
 6793:            .'<td>'.&Apache::lonnet::plaintext($roleslog{$id}{'logentry'}{'role'},$crstype).'</td>');
 6794:         if ($context eq 'course') { 
 6795:             $r->print('<td>'.$sec.'</td>');
 6796:         }
 6797:         $r->print(
 6798:             '<td>'.$chgcontext.'</td>'
 6799:            .'<td>'.$rolestart.'</td>'
 6800:            .'<td>'.$roleend.'</td>'
 6801:            .&Apache::loncommon::end_data_table_row()."\n");
 6802:     }
 6803: 
 6804:     if ($showntableheader) { # Table footer, if content displayed above
 6805:         $r->print(&Apache::loncommon::end_data_table().
 6806:                   &userlogdisplay_navlinks(\%curr,$more_records));
 6807:     } else { # No content displayed above
 6808:         $r->print('<p class="LC_info">'
 6809:                  .&mt('There are no records to display.')
 6810:                  .'</p>'
 6811:         );
 6812:     }
 6813: 
 6814:     # Form Footer
 6815:     $r->print( 
 6816:         '<input type="hidden" name="page" value="'.$curr{'page'}.'" />'
 6817:        .'<input type="hidden" name="action" value="changelogs" />'
 6818:        .'</form>');
 6819:     return;
 6820: }
 6821: 
 6822: sub print_useraccesslogs_display {
 6823:     my ($r,$uname,$udom,$permission,$brcrum) = @_;
 6824:     my $formname = 'accesslog';
 6825:     my $form = 'document.accesslog';
 6826: 
 6827: # set breadcrumbs
 6828:     my %breadcrumb_text = &singleuser_breadcrumb('','domain',$udom);
 6829:     push (@{$brcrum},
 6830:         {href => "javascript:backPage($form)",
 6831:          text => $breadcrumb_text{'search'}});
 6832:     my (@prevphases,$prevphasestr);
 6833:     if ($env{'form.prevphases'}) {
 6834:         @prevphases = split(/,/,$env{'form.prevphases'});
 6835:         $prevphasestr = $env{'form.prevphases'};
 6836:     }
 6837:     if (($env{'form.phase'} eq 'userpicked') || (grep(/^userpicked$/,@prevphases))) {
 6838:         push(@{$brcrum},
 6839:               {href => "javascript:backPage($form,'get_user_info','select')",
 6840:                text => $breadcrumb_text{'userpicked'}});
 6841:         if ($env{'form.phase'} eq 'userpicked') {
 6842:             $prevphasestr = 'userpicked';
 6843:         }
 6844:     }
 6845:     push(@{$brcrum},
 6846:              {href => '/adm/createuser?action=accesslogs',
 6847:               text => 'User access logs',
 6848:               help => 'User_Access_Logs'});
 6849:     my $bread_crumbs_component = 'User Access Logs';
 6850:     my $args = { bread_crumbs           => $brcrum,
 6851:                  bread_crumbs_component => 'User Management'};
 6852: 
 6853: # set javascript
 6854:     my ($jsback,$elements) = &crumb_utilities();
 6855:     my $jsnav = &userlogdisplay_js($formname);
 6856: 
 6857:     my $jscript = (<<ENDSCRIPT);
 6858: <script type="text/javascript">
 6859: // <![CDATA[
 6860: 
 6861: $jsback
 6862: $jsnav
 6863: 
 6864: // ]]>
 6865: </script>
 6866: 
 6867: ENDSCRIPT
 6868: 
 6869: # print page header
 6870:     $r->print(&header($jscript,$args));
 6871: 
 6872: # early out unless log data can be displayed.
 6873:     unless ($permission->{'activity'}) {
 6874:         $r->print('<p class="LC_warning">'
 6875:                  .&mt('You do not have rights to display user access logs.')
 6876:                  .'</p>'
 6877:                  .&earlyout_accesslog_form($formname,$prevphasestr,$udom));
 6878:         return;
 6879:     }
 6880: 
 6881:     unless ($udom eq $env{'request.role.domain'}) {
 6882:         $r->print('<p class="LC_warning">'
 6883:                  .&mt("User's domain must match role's domain")
 6884:                  .'</p>'
 6885:                  .&earlyout_accesslog_form($formname,$prevphasestr,$udom));
 6886:         return;
 6887:     }
 6888: 
 6889:     if (($uname eq '') || ($udom eq '')) {
 6890:         $r->print('<p class="LC_warning">'
 6891:                  .&mt('Invalid username or domain')
 6892:                  .'</p>'
 6893:                  .&earlyout_accesslog_form($formname,$prevphasestr,$udom));
 6894:         return;
 6895:     }
 6896: 
 6897: # set defaults
 6898:     my $now = time();
 6899:     my $defstart = $now - (7*24*3600);
 6900:     my %defaults = (
 6901:                      page                 => '1',
 6902:                      show                 => '10',
 6903:                      activity             => 'any',
 6904:                      accesslog_start_date => $defstart,
 6905:                      accesslog_end_date   => $now,
 6906:                    );
 6907:     my $more_records = 0;
 6908: 
 6909: # set current
 6910:     my %curr;
 6911:     foreach my $item ('show','page','activity') {
 6912:         $curr{$item} = $env{'form.'.$item};
 6913:     }
 6914:     my ($startdate,$enddate) =
 6915:         &Apache::lonuserutils::get_dates_from_form('accesslog_start_date','accesslog_end_date');
 6916:     $curr{'accesslog_start_date'} = $startdate;
 6917:     $curr{'accesslog_end_date'} = $enddate;
 6918:     foreach my $key (keys(%defaults)) {
 6919:         if ($curr{$key} eq '') {
 6920:             $curr{$key} = $defaults{$key};
 6921:         }
 6922:     }
 6923:     my ($minshown,$maxshown);
 6924:     $minshown = 1;
 6925:     my $count = 0;
 6926:     if ($curr{'show'} =~ /\D/) {
 6927:         $curr{'page'} = 1;
 6928:     } else {
 6929:         $maxshown = $curr{'page'} * $curr{'show'};
 6930:         if ($curr{'page'} > 1) {
 6931:             $minshown = 1 + ($curr{'page'} - 1) * $curr{'show'};
 6932:         }
 6933:     }
 6934: 
 6935: # form header
 6936:     $r->print('<form action="/adm/createuser" method="post" name="'.$formname.'">'.
 6937:               &activity_display_filter($formname,\%curr));
 6938: 
 6939:     my $showntableheader = 0;
 6940:     my ($nav_script,$nav_links);
 6941: 
 6942: # table header
 6943:     my $tableheader =
 6944:         &Apache::loncommon::start_data_table_header_row()
 6945:        .'<th>&nbsp;</th>'
 6946:        .'<th>'.&mt('When').'</th>'
 6947:        .'<th>'.&mt('HostID').'</th>'
 6948:        .'<th>'.&mt('Event').'</th>'
 6949:        .'<th>'.&mt('Other data').'</th>'
 6950:        .&Apache::loncommon::end_data_table_header_row();
 6951: 
 6952:     my %filters=(
 6953:         start  => $curr{'accesslog_start_date'},
 6954:         end    => $curr{'accesslog_end_date'},
 6955:         action => $curr{'activity'},
 6956:     );
 6957: 
 6958:     my $reply = &Apache::lonnet::userlog_query($uname,$udom,%filters);
 6959:     unless ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 6960:         my (%courses,%missing);
 6961:         my @results = split(/\&/,$reply);
 6962:         foreach my $item (reverse(@results)) {
 6963:             my ($timestamp,$host,$event) = split(/:/,$item);
 6964:             next unless ($event =~ /^(Log|Role)/);
 6965:             if ($curr{'show'} !~ /\D/) {
 6966:                 if ($count >= $curr{'page'} * $curr{'show'}) {
 6967:                     $more_records = 1;
 6968:                     last;
 6969:                 }
 6970:             }
 6971:             $count ++;
 6972:             next if ($count < $minshown);
 6973:             unless ($showntableheader) {
 6974:                 $r->print($nav_script
 6975:                          .&Apache::loncommon::start_data_table()
 6976:                          .$tableheader);
 6977:                 $r->rflush();
 6978:                 $showntableheader = 1;
 6979:             }
 6980:             my ($shown,$extra);
 6981:             my ($event,$data) = split(/\s+/,&unescape($event));
 6982:             if ($event eq 'Role') {
 6983:                 my ($rolecode,$extent) = split(/\./,$data,2);
 6984:                 next if ($extent eq '');
 6985:                 my ($crstype,$desc,$info);
 6986:                 if ($extent =~ m{^/($match_domain)/($match_courseid)(?:/(\w+)|)$}) {
 6987:                     my ($cdom,$cnum,$sec) = ($1,$2,$3);
 6988:                     my $cid = $cdom.'_'.$cnum;
 6989:                     if (exists($courses{$cid})) {
 6990:                         $crstype = $courses{$cid}{'type'};
 6991:                         $desc = $courses{$cid}{'description'};
 6992:                     } elsif ($missing{$cid}) {
 6993:                         $crstype = 'Course';
 6994:                         $desc = 'Course/Community';
 6995:                     } else {
 6996:                         my %crsinfo = &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 6997:                         if (ref($crsinfo{$cdom.'_'.$cnum}) eq 'HASH') {
 6998:                             $courses{$cid} = $crsinfo{$cid};
 6999:                             $crstype = $crsinfo{$cid}{'type'};
 7000:                             $desc = $crsinfo{$cid}{'description'};
 7001:                         } else {
 7002:                             $missing{$cid} = 1;
 7003:                         }
 7004:                     }
 7005:                     $extra = &mt($crstype).': <a href="/public/'.$cdom.'/'.$cnum.'/syllabus">'.$desc.'</a>';
 7006:                     if ($sec ne '') {
 7007:                        $extra .= ' ('.&mt('Section: [_1]',$sec).')';
 7008:                     }
 7009:                 } elsif ($extent =~ m{^/($match_domain)/($match_username|$)}) {
 7010:                     my ($dom,$name) = ($1,$2);
 7011:                     if ($rolecode eq 'au') {
 7012:                         $extra = '';
 7013:                     } elsif ($rolecode =~ /^(ca|aa)$/) {
 7014:                         $extra = &mt('Authoring Space: [_1]',$name.':'.$dom);
 7015:                     } elsif ($rolecode =~ /^(li|dg|dh|dc|sc)$/) {
 7016:                         $extra = &mt('Domain: [_1]',$dom);
 7017:                     }
 7018:                 }
 7019:                 my $rolename;
 7020:                 if ($rolecode =~ m{^cr/($match_domain)/($match_username)/(\w+)}) {
 7021:                     my $role = $3;
 7022:                     my $owner = "($2:$1)";
 7023:                     if ($2 eq $1.'-domainconfig') {
 7024:                         $owner = '(ad hoc)';
 7025:                     }
 7026:                     $rolename = &mt('Custom role: [_1]',$role.' '.$owner);
 7027:                 } else {
 7028:                     $rolename = &Apache::lonnet::plaintext($rolecode,$crstype);
 7029:                 }
 7030:                 $shown = &mt('Role selection: [_1]',$rolename);
 7031:             } else {
 7032:                 $shown = &mt($event);
 7033:                 if ($data ne '') {
 7034:                    $extra = &mt('Client IP address: [_1]',$data);
 7035:                 }
 7036:             }
 7037:             $r->print(
 7038:             &Apache::loncommon::start_data_table_row()
 7039:            .'<td>'.$count.'</td>'
 7040:            .'<td>'.&Apache::lonlocal::locallocaltime($timestamp).'</td>'
 7041:            .'<td>'.$host.'</td>'
 7042:            .'<td>'.$shown.'</td>'
 7043:            .'<td>'.$extra.'</td>'
 7044:            .&Apache::loncommon::end_data_table_row()."\n");
 7045:         }
 7046:     }
 7047: 
 7048:     if ($showntableheader) { # Table footer, if content displayed above
 7049:         $r->print(&Apache::loncommon::end_data_table().
 7050:                   &userlogdisplay_navlinks(\%curr,$more_records));
 7051:     } else { # No content displayed above
 7052:         $r->print('<p class="LC_info">'
 7053:                  .&mt('There are no records to display.')
 7054:                  .'</p>');
 7055:     }
 7056: 
 7057:     # Form Footer
 7058:     $r->print(
 7059:         '<input type="hidden" name="currstate" value="" />'
 7060:        .'<input type="hidden" name="accessuname" value="'.$uname.'" />'
 7061:        .'<input type="hidden" name="accessudom" value="'.$udom.'" />'
 7062:        .'<input type="hidden" name="page" value="'.$curr{'page'}.'" />'
 7063:        .'<input type="hidden" name="prevphases" value="'.$prevphasestr.'" />'
 7064:        .'<input type="hidden" name="phase" value="activity" />'
 7065:        .'<input type="hidden" name="action" value="accesslogs" />'
 7066:        .'<input type="hidden" name="srchdomain" value="'.$udom.'" />'
 7067:        .'<input type="hidden" name="srchby" value="'.$env{'form.srchby'}.'" />'
 7068:        .'<input type="hidden" name="srchtype" value="'.$env{'form.srchtype'}.'" />'
 7069:        .'<input type="hidden" name="srchterm" value="'.&HTML::Entities::encode($env{'form.srchterm'},'<>"&').'" />'
 7070:        .'<input type="hidden" name="srchin" value="'.$env{'form.srchin'}.'" />'
 7071:        .'</form>');
 7072:     return;
 7073: }
 7074: 
 7075: sub earlyout_accesslog_form {
 7076:     my ($formname,$prevphasestr,$udom) = @_;
 7077:     my $srchterm = &HTML::Entities::encode($env{'form.srchterm'},'<>"&');
 7078:    return <<"END";
 7079: <form action="/adm/createuser" method="post" name="$formname">
 7080: <input type="hidden" name="currstate" value="" />
 7081: <input type="hidden" name="prevphases" value="$prevphasestr" />
 7082: <input type="hidden" name="phase" value="activity" />
 7083: <input type="hidden" name="action" value="accesslogs" />
 7084: <input type="hidden" name="srchdomain" value="$udom" />
 7085: <input type="hidden" name="srchby" value="$env{'form.srchby'}" />
 7086: <input type="hidden" name="srchtype" value="$env{'form.srchtype'}" />
 7087: <input type="hidden" name="srchterm" value="$srchterm" />
 7088: <input type="hidden" name="srchin" value="$env{'form.srchin'}" />
 7089: </form>
 7090: END
 7091: }
 7092: 
 7093: sub activity_display_filter {
 7094:     my ($formname,$curr) = @_;
 7095:     my $nolink = 1;
 7096:     my $output = '<table><tr><td valign="top">'.
 7097:                  '<span class="LC_nobreak"><b>'.&mt('Actions/page:').'</b></span><br />'.
 7098:                  &Apache::lonmeta::selectbox('show',$curr->{'show'},undef,
 7099:                                               (&mt('all'),5,10,20,50,100,1000,10000)).
 7100:                  '</td><td>&nbsp;&nbsp;</td>';
 7101:     my $startform =
 7102:         &Apache::lonhtmlcommon::date_setter($formname,'accesslog_start_date',
 7103:                                             $curr->{'accesslog_start_date'},undef,
 7104:                                             undef,undef,undef,undef,undef,undef,$nolink);
 7105:     my $endform =
 7106:         &Apache::lonhtmlcommon::date_setter($formname,'accesslog_end_date',
 7107:                                             $curr->{'accesslog_end_date'},undef,
 7108:                                             undef,undef,undef,undef,undef,undef,$nolink);
 7109:     my %lt = &Apache::lonlocal::texthash (
 7110:                                           activity => 'Activity',
 7111:                                           Role     => 'Role selection',
 7112:                                           log      => 'Log-in or Logout',
 7113:     );
 7114:     $output .= '<td valign="top"><b>'.&mt('Window during which actions occurred:').'</b><br />'.
 7115:                '<table><tr><td>'.&mt('After:').
 7116:                '</td><td>'.$startform.'</td></tr>'.
 7117:                '<tr><td>'.&mt('Before:').'</td>'.
 7118:                '<td>'.$endform.'</td></tr></table>'.
 7119:                '</td>'.
 7120:                '<td>&nbsp;&nbsp;</td>'.
 7121:                '<td valign="top"><b>'.&mt('Activities').'</b><br />'.
 7122:                '<select name="activity"><option value="any"';
 7123:     if ($curr->{'activity'} eq 'any') {
 7124:         $output .= ' selected="selected"';
 7125:     }
 7126:     $output .= '>'.&mt('Any').'</option>'."\n";
 7127:     foreach my $activity ('Role','log') {
 7128:         my $selstr = '';
 7129:         if ($activity eq $curr->{'activity'}) {
 7130:             $selstr = ' selected="selected"';
 7131:         }
 7132:         $output .= '<option value="'.$activity.'"'.$selstr.'>'.$lt{$activity}.'</option>';
 7133:     }
 7134:     $output .= '</select></td>'.
 7135:                '</tr></table>';
 7136:     # Update Display button
 7137:     $output .= '<p>'
 7138:               .'<input type="submit" value="'.&mt('Update Display').'" />'
 7139:               .'</p>';
 7140:     return $output;
 7141: }
 7142: 
 7143: sub userlogdisplay_js {
 7144:     my ($formname) = @_;
 7145:     return <<"ENDSCRIPT";
 7146: 
 7147: function chgPage(caller) {
 7148:     if (caller == 'previous') {
 7149:         document.$formname.page.value --;
 7150:     }
 7151:     if (caller == 'next') {
 7152:         document.$formname.page.value ++;
 7153:     }
 7154:     document.$formname.submit();
 7155:     return;
 7156: }
 7157: ENDSCRIPT
 7158: }
 7159: 
 7160: sub userlogdisplay_navlinks {
 7161:     my ($curr,$more_records) = @_;
 7162:     return unless(ref($curr) eq 'HASH');
 7163:     # Navigation Buttons
 7164:     my $nav_links = '<p>';
 7165:     if (($curr->{'page'} > 1) || ($more_records)) {
 7166:         if (($curr->{'page'} > 1) && ($curr->{'show'} !~ /\D/)) {
 7167:             $nav_links .= '<input type="button"'
 7168:                          .' onclick="javascript:chgPage('."'previous'".');"'
 7169:                          .' value="'.&mt('Previous [_1] changes',$curr->{'show'})
 7170:                          .'" /> ';
 7171:         }
 7172:         if ($more_records) {
 7173:             $nav_links .= '<input type="button"'
 7174:                          .' onclick="javascript:chgPage('."'next'".');"'
 7175:                          .' value="'.&mt('Next [_1] changes',$curr->{'show'})
 7176:                          .'" />';
 7177:         }
 7178:     }
 7179:     $nav_links .= '</p>';
 7180:     return $nav_links;
 7181: }
 7182: 
 7183: sub role_display_filter {
 7184:     my ($context,$formname,$cdom,$cnum,$curr,$version,$crstype) = @_;
 7185:     my $lctype;
 7186:     if ($context eq 'course') {
 7187:         $lctype = lc($crstype);
 7188:     }
 7189:     my $nolink = 1;
 7190:     my $output = '<table><tr><td valign="top">'.
 7191:                  '<span class="LC_nobreak"><b>'.&mt('Changes/page:').'</b></span><br />'.
 7192:                  &Apache::lonmeta::selectbox('show',$curr->{'show'},undef,
 7193:                                               (&mt('all'),5,10,20,50,100,1000,10000)).
 7194:                  '</td><td>&nbsp;&nbsp;</td>';
 7195:     my $startform =
 7196:         &Apache::lonhtmlcommon::date_setter($formname,'rolelog_start_date',
 7197:                                             $curr->{'rolelog_start_date'},undef,
 7198:                                             undef,undef,undef,undef,undef,undef,$nolink);
 7199:     my $endform =
 7200:         &Apache::lonhtmlcommon::date_setter($formname,'rolelog_end_date',
 7201:                                             $curr->{'rolelog_end_date'},undef,
 7202:                                             undef,undef,undef,undef,undef,undef,$nolink);
 7203:     my %lt = &rolechg_contexts($context,$crstype);
 7204:     $output .= '<td valign="top"><b>'.&mt('Window during which changes occurred:').'</b><br />'.
 7205:                '<table><tr><td>'.&mt('After:').
 7206:                '</td><td>'.$startform.'</td></tr>'.
 7207:                '<tr><td>'.&mt('Before:').'</td>'.
 7208:                '<td>'.$endform.'</td></tr></table>'.
 7209:                '</td>'.
 7210:                '<td>&nbsp;&nbsp;</td>'.
 7211:                '<td valign="top"><b>'.&mt('Role:').'</b><br />'.
 7212:                '<select name="role"><option value="any"';
 7213:     if ($curr->{'role'} eq 'any') {
 7214:         $output .= ' selected="selected"';
 7215:     }
 7216:     $output .=  '>'.&mt('Any').'</option>'."\n";
 7217:     my @roles = &Apache::lonuserutils::roles_by_context($context,1,$crstype);
 7218:     foreach my $role (@roles) {
 7219:         my $plrole;
 7220:         if ($role eq 'cr') {
 7221:             $plrole = &mt('Custom Role');
 7222:         } else {
 7223:             $plrole=&Apache::lonnet::plaintext($role,$crstype);
 7224:         }
 7225:         my $selstr = '';
 7226:         if ($role eq $curr->{'role'}) {
 7227:             $selstr = ' selected="selected"';
 7228:         }
 7229:         $output .= '  <option value="'.$role.'"'.$selstr.'>'.$plrole.'</option>';
 7230:     }
 7231:     $output .= '</select></td>'.
 7232:                '<td>&nbsp;&nbsp;</td>'.
 7233:                '<td valign="top"><b>'.
 7234:                &mt('Context:').'</b><br /><select name="chgcontext">';
 7235:     my @posscontexts;
 7236:     if ($context eq 'course') {
 7237:         @posscontexts = ('any','automated','updatenow','createcourse','course','domain','selfenroll','requestcourses');
 7238:     } elsif ($context eq 'domain') {
 7239:         @posscontexts = ('any','domain','requestauthor','domconfig','server');
 7240:     } else {
 7241:         @posscontexts = ('any','author','domain');
 7242:     } 
 7243:     foreach my $chgtype (@posscontexts) {
 7244:         my $selstr = '';
 7245:         if ($curr->{'chgcontext'} eq $chgtype) {
 7246:             $selstr = ' selected="selected"';
 7247:         }
 7248:         if ($context eq 'course') {
 7249:             if (($chgtype eq 'automated') || ($chgtype eq 'updatenow')) {
 7250:                 next if (!&Apache::lonnet::auto_run($cnum,$cdom));
 7251:             }
 7252:         }
 7253:         $output .= '<option value="'.$chgtype.'"'.$selstr.'>'.$lt{$chgtype}.'</option>'."\n";
 7254:     }
 7255:     $output .= '</select></td>'
 7256:               .'</tr></table>';
 7257: 
 7258:     # Update Display button
 7259:     $output .= '<p>'
 7260:               .'<input type="submit" value="'.&mt('Update Display').'" />'
 7261:               .'</p>';
 7262: 
 7263:     # Server version info
 7264:     my $needsrev = '2.11.0';
 7265:     if ($context eq 'course') {
 7266:         $needsrev = '2.7.0';
 7267:     }
 7268:     
 7269:     $output .= '<p class="LC_info">'
 7270:               .&mt('Only changes made from servers running LON-CAPA [_1] or later are displayed.'
 7271:                   ,$needsrev);
 7272:     if ($version) {
 7273:         $output .= ' '.&mt('This LON-CAPA server is version [_1]',$version);
 7274:     }
 7275:     $output .= '</p><hr />';
 7276:     return $output;
 7277: }
 7278: 
 7279: sub rolechg_contexts {
 7280:     my ($context,$crstype) = @_;
 7281:     my %lt;
 7282:     if ($context eq 'course') {
 7283:         %lt = &Apache::lonlocal::texthash (
 7284:                                              any          => 'Any',
 7285:                                              automated    => 'Automated Enrollment',
 7286:                                              updatenow    => 'Roster Update',
 7287:                                              createcourse => 'Course Creation',
 7288:                                              course       => 'User Management in course',
 7289:                                              domain       => 'User Management in domain',
 7290:                                              selfenroll   => 'Self-enrolled',
 7291:                                              requestcourses => 'Course Request',
 7292:                                          );
 7293:         if ($crstype eq 'Community') {
 7294:             $lt{'createcourse'} = &mt('Community Creation');
 7295:             $lt{'course'} = &mt('User Management in community');
 7296:             $lt{'requestcourses'} = &mt('Community Request');
 7297:         }
 7298:     } elsif ($context eq 'domain') {
 7299:         %lt = &Apache::lonlocal::texthash (
 7300:                                              any           => 'Any',
 7301:                                              domain        => 'User Management in domain',
 7302:                                              requestauthor => 'Authoring Request',
 7303:                                              server        => 'Command line script (DC role)',
 7304:                                              domconfig     => 'Self-enrolled',
 7305:                                          );
 7306:     } else {
 7307:         %lt = &Apache::lonlocal::texthash (
 7308:                                              any    => 'Any',
 7309:                                              domain => 'User Management in domain',
 7310:                                              author => 'User Management by author',
 7311:                                          );
 7312:     } 
 7313:     return %lt;
 7314: }
 7315: 
 7316: #-------------------------------------------------- functions for &phase_two
 7317: sub user_search_result {
 7318:     my ($context,$srch) = @_;
 7319:     my %allhomes;
 7320:     my %inst_matches;
 7321:     my %srch_results;
 7322:     my ($response,$currstate,$forcenewuser,$dirsrchres);
 7323:     $srch->{'srchterm'} =~ s/\s+/ /g;
 7324:     if ($srch->{'srchby'} !~ /^(uname|lastname|lastfirst)$/) {
 7325:         $response = &mt('Invalid search.');
 7326:     }
 7327:     if ($srch->{'srchin'} !~ /^(crs|dom|alc|instd)$/) {
 7328:         $response = &mt('Invalid search.');
 7329:     }
 7330:     if ($srch->{'srchtype'} !~ /^(exact|contains|begins)$/) {
 7331:         $response = &mt('Invalid search.');
 7332:     }
 7333:     if ($srch->{'srchterm'} eq '') {
 7334:         $response = &mt('You must enter a search term.');
 7335:     }
 7336:     if ($srch->{'srchterm'} =~ /^\s+$/) {
 7337:         $response = &mt('Your search term must contain more than just spaces.');
 7338:     }
 7339:     if (($srch->{'srchin'} eq 'dom') || ($srch->{'srchin'} eq 'instd')) {
 7340:         if (($srch->{'srchdomain'} eq '') || 
 7341: 	    ! (&Apache::lonnet::domain($srch->{'srchdomain'}))) {
 7342:             $response = &mt('You must specify a valid domain when searching in a domain or institutional directory.')
 7343:         }
 7344:     }
 7345:     if (($srch->{'srchin'} eq 'dom') || ($srch->{'srchin'} eq 'crs') ||
 7346:         ($srch->{'srchin'} eq 'alc')) {
 7347:         if ($srch->{'srchby'} eq 'uname') {
 7348:             my $unamecheck = $srch->{'srchterm'};
 7349:             if ($srch->{'srchtype'} eq 'contains') {
 7350:                 if ($unamecheck !~ /^\w/) {
 7351:                     $unamecheck = 'a'.$unamecheck; 
 7352:                 }
 7353:             }
 7354:             if ($unamecheck !~ /^$match_username$/) {
 7355:                 $response = &mt('You must specify a valid username. Only the following are allowed: letters numbers - . @');
 7356:             }
 7357:         }
 7358:     }
 7359:     if ($response ne '') {
 7360:         $response = '<span class="LC_warning">'.$response.'</span><br />';
 7361:     }
 7362:     if ($srch->{'srchin'} eq 'instd') {
 7363:         my $instd_chk = &instdirectorysrch_check($srch);
 7364:         if ($instd_chk ne 'ok') {
 7365:             my $domd_chk = &domdirectorysrch_check($srch);
 7366:             $response .= '<span class="LC_warning">'.$instd_chk.'</span><br />';
 7367:             if ($domd_chk eq 'ok') {
 7368:                 $response .= &mt('You may want to search in the LON-CAPA domain instead of the institutional directory.');
 7369:             }
 7370:             $response .= '<br />';
 7371:         }
 7372:     } else {
 7373:         unless (($context eq 'requestcrs') && ($srch->{'srchtype'} eq 'exact')) {
 7374:             my $domd_chk = &domdirectorysrch_check($srch);
 7375:             if ($domd_chk ne 'ok') {
 7376:                 my $instd_chk = &instdirectorysrch_check($srch);
 7377:                 $response .= '<span class="LC_warning">'.$domd_chk.'</span><br />';
 7378:                 if ($instd_chk eq 'ok') {
 7379:                     $response .= &mt('You may want to search in the institutional directory instead of the LON-CAPA domain.');
 7380:                 }
 7381:                 $response .= '<br />';
 7382:             }
 7383:         }
 7384:     }
 7385:     if ($response ne '') {
 7386:         return ($currstate,$response);
 7387:     }
 7388:     if ($srch->{'srchby'} eq 'uname') {
 7389:         if (($srch->{'srchin'} eq 'dom') || ($srch->{'srchin'} eq 'crs')) {
 7390:             if ($env{'form.forcenew'}) {
 7391:                 if ($srch->{'srchdomain'} ne $env{'request.role.domain'}) {
 7392:                     my $uhome=&Apache::lonnet::homeserver($srch->{'srchterm'},$srch->{'srchdomain'});
 7393:                     if ($uhome eq 'no_host') {
 7394:                         my $domdesc = &Apache::lonnet::domain($env{'request.role.domain'},'description');
 7395:                         my $showdom = &display_domain_info($env{'request.role.domain'});
 7396:                         $response = &mt('New users can only be created in the domain to which your current role belongs - [_1].',$showdom);
 7397:                     } else {
 7398:                         $currstate = 'modify';
 7399:                     }
 7400:                 } else {
 7401:                     $currstate = 'modify';
 7402:                 }
 7403:             } else {
 7404:                 if ($srch->{'srchin'} eq 'dom') {
 7405:                     if ($srch->{'srchtype'} eq 'exact') {
 7406:                         my $uhome=&Apache::lonnet::homeserver($srch->{'srchterm'},$srch->{'srchdomain'});
 7407:                         if ($uhome eq 'no_host') {
 7408:                             ($currstate,$response,$forcenewuser) =
 7409:                                 &build_search_response($context,$srch,%srch_results);
 7410:                         } else {
 7411:                             $currstate = 'modify';
 7412:                             if ($env{'form.action'} eq 'accesslogs') {
 7413:                                 $currstate = 'activity';
 7414:                             }
 7415:                             my $uname = $srch->{'srchterm'};
 7416:                             my $udom = $srch->{'srchdomain'};
 7417:                             $srch_results{$uname.':'.$udom} =
 7418:                                 { &Apache::lonnet::get('environment',
 7419:                                                        ['firstname',
 7420:                                                         'lastname',
 7421:                                                         'permanentemail'],
 7422:                                                          $udom,$uname)
 7423:                                 };
 7424:                         }
 7425:                     } else {
 7426:                         %srch_results = &Apache::lonnet::usersearch($srch);
 7427:                         ($currstate,$response,$forcenewuser) =
 7428:                             &build_search_response($context,$srch,%srch_results);
 7429:                     }
 7430:                 } else {
 7431:                     my $courseusers = &get_courseusers();
 7432:                     if ($srch->{'srchtype'} eq 'exact') {
 7433:                         if (exists($courseusers->{$srch->{'srchterm'}.':'.$srch->{'srchdomain'}})) {
 7434:                             $currstate = 'modify';
 7435:                         } else {
 7436:                             ($currstate,$response,$forcenewuser) =
 7437:                                 &build_search_response($context,$srch,%srch_results);
 7438:                         }
 7439:                     } else {
 7440:                         foreach my $user (keys(%$courseusers)) {
 7441:                             my ($cuname,$cudomain) = split(/:/,$user);
 7442:                             if ($cudomain eq $srch->{'srchdomain'}) {
 7443:                                 my $matched = 0;
 7444:                                 if ($srch->{'srchtype'} eq 'begins') {
 7445:                                     if ($cuname =~ /^\Q$srch->{'srchterm'}\E/i) {
 7446:                                         $matched = 1;
 7447:                                     }
 7448:                                 } else {
 7449:                                     if ($cuname =~ /\Q$srch->{'srchterm'}\E/i) {
 7450:                                         $matched = 1;
 7451:                                     }
 7452:                                 }
 7453:                                 if ($matched) {
 7454:                                     $srch_results{$user} = 
 7455: 					{&Apache::lonnet::get('environment',
 7456: 							     ['firstname',
 7457: 							      'lastname',
 7458: 							      'permanentemail'],
 7459: 							      $cudomain,$cuname)};
 7460:                                 }
 7461:                             }
 7462:                         }
 7463:                         ($currstate,$response,$forcenewuser) =
 7464:                             &build_search_response($context,$srch,%srch_results);
 7465:                     }
 7466:                 }
 7467:             }
 7468:         } elsif ($srch->{'srchin'} eq 'alc') {
 7469:             $currstate = 'query';
 7470:         } elsif ($srch->{'srchin'} eq 'instd') {
 7471:             ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query($srch);
 7472:             if ($dirsrchres eq 'ok') {
 7473:                 ($currstate,$response,$forcenewuser) = 
 7474:                     &build_search_response($context,$srch,%srch_results);
 7475:             } else {
 7476:                 my $showdom = &display_domain_info($srch->{'srchdomain'});
 7477:                 $response = '<span class="LC_warning">'.
 7478:                     &mt('Institutional directory search is not available in domain: [_1]',$showdom).
 7479:                     '</span><br />'.
 7480:                     &mt('You may want to search in the LON-CAPA domain instead of the institutional directory.').
 7481:                     '<br />'; 
 7482:             }
 7483:         }
 7484:     } else {
 7485:         if ($srch->{'srchin'} eq 'dom') {
 7486:             %srch_results = &Apache::lonnet::usersearch($srch);
 7487:             ($currstate,$response,$forcenewuser) = 
 7488:                 &build_search_response($context,$srch,%srch_results); 
 7489:         } elsif ($srch->{'srchin'} eq 'crs') {
 7490:             my $courseusers = &get_courseusers(); 
 7491:             foreach my $user (keys(%$courseusers)) {
 7492:                 my ($uname,$udom) = split(/:/,$user);
 7493:                 my %names = &Apache::loncommon::getnames($uname,$udom);
 7494:                 my %emails = &Apache::loncommon::getemails($uname,$udom);
 7495:                 if ($srch->{'srchby'} eq 'lastname') {
 7496:                     if ((($srch->{'srchtype'} eq 'exact') && 
 7497:                          ($names{'lastname'} eq $srch->{'srchterm'})) || 
 7498:                         (($srch->{'srchtype'} eq 'begins') &&
 7499:                          ($names{'lastname'} =~ /^\Q$srch->{'srchterm'}\E/i)) ||
 7500:                         (($srch->{'srchtype'} eq 'contains') &&
 7501:                          ($names{'lastname'} =~ /\Q$srch->{'srchterm'}\E/i))) {
 7502:                         $srch_results{$user} = {firstname => $names{'firstname'},
 7503:                                             lastname => $names{'lastname'},
 7504:                                             permanentemail => $emails{'permanentemail'},
 7505:                                            };
 7506:                     }
 7507:                 } elsif ($srch->{'srchby'} eq 'lastfirst') {
 7508:                     my ($srchlast,$srchfirst) = split(/,/,$srch->{'srchterm'});
 7509:                     $srchlast =~ s/\s+$//;
 7510:                     $srchfirst =~ s/^\s+//;
 7511:                     if ($srch->{'srchtype'} eq 'exact') {
 7512:                         if (($names{'lastname'} eq $srchlast) &&
 7513:                             ($names{'firstname'} eq $srchfirst)) {
 7514:                             $srch_results{$user} = {firstname => $names{'firstname'},
 7515:                                                 lastname => $names{'lastname'},
 7516:                                                 permanentemail => $emails{'permanentemail'},
 7517: 
 7518:                                            };
 7519:                         }
 7520:                     } elsif ($srch->{'srchtype'} eq 'begins') {
 7521:                         if (($names{'lastname'} =~ /^\Q$srchlast\E/i) &&
 7522:                             ($names{'firstname'} =~ /^\Q$srchfirst\E/i)) {
 7523:                             $srch_results{$user} = {firstname => $names{'firstname'},
 7524:                                                 lastname => $names{'lastname'},
 7525:                                                 permanentemail => $emails{'permanentemail'},
 7526:                                                };
 7527:                         }
 7528:                     } else {
 7529:                         if (($names{'lastname'} =~ /\Q$srchlast\E/i) && 
 7530:                             ($names{'firstname'} =~ /\Q$srchfirst\E/i)) {
 7531:                             $srch_results{$user} = {firstname => $names{'firstname'},
 7532:                                                 lastname => $names{'lastname'},
 7533:                                                 permanentemail => $emails{'permanentemail'},
 7534:                                                };
 7535:                         }
 7536:                     }
 7537:                 }
 7538:             }
 7539:             ($currstate,$response,$forcenewuser) = 
 7540:                 &build_search_response($context,$srch,%srch_results); 
 7541:         } elsif ($srch->{'srchin'} eq 'alc') {
 7542:             $currstate = 'query';
 7543:         } elsif ($srch->{'srchin'} eq 'instd') {
 7544:             ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query($srch); 
 7545:             if ($dirsrchres eq 'ok') {
 7546:                 ($currstate,$response,$forcenewuser) = 
 7547:                     &build_search_response($context,$srch,%srch_results);
 7548:             } else {
 7549:                 my $showdom = &display_domain_info($srch->{'srchdomain'});
 7550:                 $response = '<span class="LC_warning">'.
 7551:                     &mt('Institutional directory search is not available in domain: [_1]',$showdom).
 7552:                     '</span><br />'.
 7553:                     &mt('You may want to search in the LON-CAPA domain instead of the institutional directory.').
 7554:                     '<br />';
 7555:             }
 7556:         }
 7557:     }
 7558:     return ($currstate,$response,$forcenewuser,\%srch_results);
 7559: }
 7560: 
 7561: sub domdirectorysrch_check {
 7562:     my ($srch) = @_;
 7563:     my $response;
 7564:     my %dom_inst_srch = &Apache::lonnet::get_dom('configuration',
 7565:                                              ['directorysrch'],$srch->{'srchdomain'});
 7566:     my $showdom = &display_domain_info($srch->{'srchdomain'});
 7567:     if (ref($dom_inst_srch{'directorysrch'}) eq 'HASH') {
 7568:         if ($dom_inst_srch{'directorysrch'}{'lcavailable'} eq '0') {
 7569:             return &mt('LON-CAPA directory search is not available in domain: [_1]',$showdom);
 7570:         }
 7571:         if ($dom_inst_srch{'directorysrch'}{'lclocalonly'}) {
 7572:             if ($env{'request.role.domain'} ne $srch->{'srchdomain'}) {
 7573:                 return &mt('LON-CAPA directory search in domain: [_1] is only allowed for users with a current role in the domain.',$showdom);
 7574:             }
 7575:         }
 7576:     }
 7577:     return 'ok';
 7578: }
 7579: 
 7580: sub instdirectorysrch_check {
 7581:     my ($srch) = @_;
 7582:     my $can_search = 0;
 7583:     my $response;
 7584:     my %dom_inst_srch = &Apache::lonnet::get_dom('configuration',
 7585:                                              ['directorysrch'],$srch->{'srchdomain'});
 7586:     my $showdom = &display_domain_info($srch->{'srchdomain'});
 7587:     if (ref($dom_inst_srch{'directorysrch'}) eq 'HASH') {
 7588:         if (!$dom_inst_srch{'directorysrch'}{'available'}) {
 7589:             return &mt('Institutional directory search is not available in domain: [_1]',$showdom); 
 7590:         }
 7591:         if ($dom_inst_srch{'directorysrch'}{'localonly'}) {
 7592:             if ($env{'request.role.domain'} ne $srch->{'srchdomain'}) {
 7593:                 return &mt('Institutional directory search in domain: [_1] is only allowed for users with a current role in the domain.',$showdom); 
 7594:             }
 7595:             my @usertypes = split(/:/,$env{'environment.inststatus'});
 7596:             if (!@usertypes) {
 7597:                 push(@usertypes,'default');
 7598:             }
 7599:             if (ref($dom_inst_srch{'directorysrch'}{'cansearch'}) eq 'ARRAY') {
 7600:                 foreach my $type (@usertypes) {
 7601:                     if (grep(/^\Q$type\E$/,@{$dom_inst_srch{'directorysrch'}{'cansearch'}})) {
 7602:                         $can_search = 1;
 7603:                         last;
 7604:                     }
 7605:                 }
 7606:             }
 7607:             if (!$can_search) {
 7608:                 my ($insttypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($srch->{'srchdomain'});
 7609:                 my @longtypes; 
 7610:                 foreach my $item (@usertypes) {
 7611:                     if (defined($insttypes->{$item})) { 
 7612:                         push (@longtypes,$insttypes->{$item});
 7613:                     } elsif ($item eq 'default') {
 7614:                         push (@longtypes,&mt('other')); 
 7615:                     }
 7616:                 }
 7617:                 my $insttype_str = join(', ',@longtypes); 
 7618:                 return &mt('Institutional directory search in domain: [_1] is not available to your user type: ',$showdom).$insttype_str;
 7619:             }
 7620:         } else {
 7621:             $can_search = 1;
 7622:         }
 7623:     } else {
 7624:         return &mt('Institutional directory search has not been configured for domain: [_1]',$showdom);
 7625:     }
 7626:     my %longtext = &Apache::lonlocal::texthash (
 7627:                        uname     => 'username',
 7628:                        lastfirst => 'last name, first name',
 7629:                        lastname  => 'last name',
 7630:                        contains  => 'contains',
 7631:                        exact     => 'as exact match to',
 7632:                        begins    => 'begins with',
 7633:                    );
 7634:     if ($can_search) {
 7635:         if (ref($dom_inst_srch{'directorysrch'}{'searchby'}) eq 'ARRAY') {
 7636:             if (!grep(/^\Q$srch->{'srchby'}\E$/,@{$dom_inst_srch{'directorysrch'}{'searchby'}})) {
 7637:                 return &mt('Institutional directory search in domain: [_1] is not available for searching by "[_2]"',$showdom,$longtext{$srch->{'srchby'}});
 7638:             }
 7639:         } else {
 7640:             return &mt('Institutional directory search in domain: [_1] is not available.', $showdom);
 7641:         }
 7642:     }
 7643:     if ($can_search) {
 7644:         if (ref($dom_inst_srch{'directorysrch'}{'searchtypes'}) eq 'ARRAY') {
 7645:             if (grep(/^\Q$srch->{'srchtype'}\E/,@{$dom_inst_srch{'directorysrch'}{'searchtypes'}})) {
 7646:                 return 'ok';
 7647:             } else {
 7648:                 return &mt('Institutional directory search in domain [_1] is not available for the requested search type: "[_2]"',$showdom,$longtext{$srch->{'srchtype'}});
 7649:             }
 7650:         } else {
 7651:             if ((($dom_inst_srch{'directorysrch'}{'searchtypes'} eq 'specify') &&
 7652:                  ($srch->{'srchtype'} eq 'exact' || $srch->{'srchtype'} eq 'contains')) ||
 7653:                 ($dom_inst_srch{'directorysrch'}{'searchtypes'} eq $srch->{'srchtype'})) {
 7654:                 return 'ok';
 7655:             } else {
 7656:                 return &mt('Institutional directory search in domain [_1] is not available for the requested search type: "[_2]"',$showdom,$longtext{$srch->{'srchtype'}});
 7657:             }
 7658:         }
 7659:     }
 7660: }
 7661: 
 7662: sub get_courseusers {
 7663:     my %advhash;
 7664:     my $classlist = &Apache::loncoursedata::get_classlist();
 7665:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles();
 7666:     foreach my $role (sort(keys(%coursepersonnel))) {
 7667:         foreach my $user (split(/\,/,$coursepersonnel{$role})) {
 7668: 	    if (!exists($classlist->{$user})) {
 7669: 		$classlist->{$user} = [];
 7670: 	    }
 7671:         }
 7672:     }
 7673:     return $classlist;
 7674: }
 7675: 
 7676: sub build_search_response {
 7677:     my ($context,$srch,%srch_results) = @_;
 7678:     my ($currstate,$response,$forcenewuser);
 7679:     my %names = (
 7680:           'uname'     => 'username',
 7681:           'lastname'  => 'last name',
 7682:           'lastfirst' => 'last name, first name',
 7683:           'crs'       => 'this course',
 7684:           'dom'       => 'LON-CAPA domain',
 7685:           'instd'     => 'the institutional directory for domain',
 7686:     );
 7687: 
 7688:     my %single = (
 7689:                    begins   => 'A match',
 7690:                    contains => 'A match',
 7691:                    exact    => 'An exact match',
 7692:                  );
 7693:     my %nomatch = (
 7694:                    begins   => 'No match',
 7695:                    contains => 'No match',
 7696:                    exact    => 'No exact match',
 7697:                   );
 7698:     if (keys(%srch_results) > 1) {
 7699:         $currstate = 'select';
 7700:     } else {
 7701:         if (keys(%srch_results) == 1) {
 7702:             if ($env{'form.action'} eq 'accesslogs') {
 7703:                 $currstate = 'activity';
 7704:             } else {
 7705:                 $currstate = 'modify';
 7706:             }
 7707:             $response = &mt("$single{$srch->{'srchtype'}} was found for the $names{$srch->{'srchby'}} ([_1]) in $names{$srch->{'srchin'}}.",$srch->{'srchterm'});
 7708:             if ($srch->{'srchin'} eq 'dom' || $srch->{'srchin'} eq 'instd') {
 7709:                 $response .= ': '.&display_domain_info($srch->{'srchdomain'});
 7710:             }
 7711:         } else { # Search has nothing found. Prepare message to user.
 7712:             $response = '<span class="LC_warning">';
 7713:             if ($srch->{'srchin'} eq 'dom' || $srch->{'srchin'} eq 'instd') {
 7714:                 $response .= &mt("$nomatch{$srch->{'srchtype'}} found for the $names{$srch->{'srchby'}} [_1] in $names{$srch->{'srchin'}}: [_2]",
 7715:                                  '<b>'.$srch->{'srchterm'}.'</b>',
 7716:                                  &display_domain_info($srch->{'srchdomain'}));
 7717:             } else {
 7718:                 $response .= &mt("$nomatch{$srch->{'srchtype'}} found for the $names{$srch->{'srchby'}} [_1] in $names{$srch->{'srchin'}}.",
 7719:                                  '<b>'.$srch->{'srchterm'}.'</b>');
 7720:             }
 7721:             $response .= '</span>';
 7722: 
 7723:             if ($srch->{'srchin'} ne 'alc') {
 7724:                 $forcenewuser = 1;
 7725:                 my $cansrchinst = 0; 
 7726:                 if ($srch->{'srchdomain'}) {
 7727:                     my %domconfig = &Apache::lonnet::get_dom('configuration',['directorysrch'],$srch->{'srchdomain'});
 7728:                     if (ref($domconfig{'directorysrch'}) eq 'HASH') {
 7729:                         if ($domconfig{'directorysrch'}{'available'}) {
 7730:                             $cansrchinst = 1;
 7731:                         } 
 7732:                     }
 7733:                 }
 7734:                 if ((($srch->{'srchby'} eq 'lastfirst') || 
 7735:                      ($srch->{'srchby'} eq 'lastname')) &&
 7736:                     ($srch->{'srchin'} eq 'dom')) {
 7737:                     if ($cansrchinst) {
 7738:                         $response .= '<br />'.&mt('You may want to broaden your search to a search of the institutional directory for the domain.');
 7739:                     }
 7740:                 }
 7741:                 if ($srch->{'srchin'} eq 'crs') {
 7742:                     $response .= '<br />'.&mt('You may want to broaden your search to the selected LON-CAPA domain.');
 7743:                 }
 7744:             }
 7745:             my $createdom = $env{'request.role.domain'};
 7746:             if ($context eq 'requestcrs') {
 7747:                 if ($env{'form.coursedom'} ne '') {
 7748:                     $createdom = $env{'form.coursedom'};
 7749:                 }
 7750:             }
 7751:             unless (($env{'form.action'} eq 'accesslogs') || (($srch->{'srchby'} eq 'uname') && ($srch->{'srchin'} eq 'dom') &&
 7752:                     ($srch->{'srchtype'} eq 'exact') && ($srch->{'srchdomain'} eq $createdom))) {
 7753:                 my $cancreate =
 7754:                     &Apache::lonuserutils::can_create_user($createdom,$context);
 7755:                 my $targetdom = '<span class="LC_cusr_emph">'.$createdom.'</span>';
 7756:                 if ($cancreate) {
 7757:                     my $showdom = &display_domain_info($createdom); 
 7758:                     $response .= '<br /><br />'
 7759:                                 .'<b>'.&mt('To add a new user:').'</b>'
 7760:                                 .'<br />';
 7761:                     if ($context eq 'requestcrs') {
 7762:                         $response .= &mt("(You can only define new users in the new course's domain - [_1])",$targetdom);
 7763:                     } else {
 7764:                         $response .= &mt("(You can only create new users in your current role's domain - [_1])",$targetdom);
 7765:                     }
 7766:                     $response .='<ul><li>'
 7767:                                 .&mt("Set 'Domain/institution to search' to: [_1]",'<span class="LC_cusr_emph">'.$showdom.'</span>')
 7768:                                 .'</li><li>'
 7769:                                 .&mt("Set 'Search criteria' to: [_1]username is ..... in selected LON-CAPA domain[_2]",'<span class="LC_cusr_emph">','</span>')
 7770:                                 .'</li><li>'
 7771:                                 .&mt('Provide the proposed username')
 7772:                                 .'</li><li>'
 7773:                                 .&mt("Click 'Search'")
 7774:                                 .'</li></ul><br />';
 7775:                 } else {
 7776:                     unless (($context eq 'domain') && ($env{'form.action'} eq 'singleuser')) {
 7777:                         my $helplink = ' href="javascript:helpMenu('."'display'".')"';
 7778:                         $response .= '<br /><br />';
 7779:                         if ($context eq 'requestcrs') {
 7780:                             $response .= &mt("You are not authorized to define new users in the new course's domain - [_1].",$targetdom);
 7781:                         } else {
 7782:                             $response .= &mt("You are not authorized to create new users in your current role's domain - [_1].",$targetdom);
 7783:                         }
 7784:                         $response .= '<br />'
 7785:                                      .&mt('Please contact the [_1]helpdesk[_2] if you need to create a new user.'
 7786:                                         ,' <a'.$helplink.'>'
 7787:                                         ,'</a>')
 7788:                                      .'<br />';
 7789:                     }
 7790:                 }
 7791:             }
 7792:         }
 7793:     }
 7794:     return ($currstate,$response,$forcenewuser);
 7795: }
 7796: 
 7797: sub display_domain_info {
 7798:     my ($dom) = @_;
 7799:     my $output = $dom;
 7800:     if ($dom ne '') { 
 7801:         my $domdesc = &Apache::lonnet::domain($dom,'description');
 7802:         if ($domdesc ne '') {
 7803:             $output .= ' <span class="LC_cusr_emph">('.$domdesc.')</span>';
 7804:         }
 7805:     }
 7806:     return $output;
 7807: }
 7808: 
 7809: sub crumb_utilities {
 7810:     my %elements = (
 7811:        crtuser => {
 7812:            srchterm => 'text',
 7813:            srchin => 'selectbox',
 7814:            srchby => 'selectbox',
 7815:            srchtype => 'selectbox',
 7816:            srchdomain => 'selectbox',
 7817:        },
 7818:        crtusername => {
 7819:            srchterm => 'text',
 7820:            srchdomain => 'selectbox',
 7821:        },
 7822:        docustom => {
 7823:            rolename => 'selectbox',
 7824:            newrolename => 'textbox',
 7825:        },
 7826:        studentform => {
 7827:            srchterm => 'text',
 7828:            srchin => 'selectbox',
 7829:            srchby => 'selectbox',
 7830:            srchtype => 'selectbox',
 7831:            srchdomain => 'selectbox',
 7832:        },
 7833:     );
 7834: 
 7835:     my $jsback .= qq|
 7836: function backPage(formname,prevphase,prevstate) {
 7837:     if (typeof prevphase == 'undefined') {
 7838:         formname.phase.value = '';
 7839:     }
 7840:     else {  
 7841:         formname.phase.value = prevphase;
 7842:     }
 7843:     if (typeof prevstate == 'undefined') {
 7844:         formname.currstate.value = '';
 7845:     }
 7846:     else {
 7847:         formname.currstate.value = prevstate;
 7848:     }
 7849:     formname.submit();
 7850: }
 7851: |;
 7852:     return ($jsback,\%elements);
 7853: }
 7854: 
 7855: sub course_level_table {
 7856:     my ($inccourses,$showcredits,$defaultcredits) = @_;
 7857:     return unless (ref($inccourses) eq 'HASH');
 7858:     my $table = '';
 7859: # Custom Roles?
 7860: 
 7861:     my %customroles=&Apache::lonuserutils::my_custom_roles();
 7862:     my %lt=&Apache::lonlocal::texthash(
 7863:             'exs'  => "Existing sections",
 7864:             'new'  => "Define new section",
 7865:             'ssd'  => "Set Start Date",
 7866:             'sed'  => "Set End Date",
 7867:             'crl'  => "Course Level",
 7868:             'act'  => "Activate",
 7869:             'rol'  => "Role",
 7870:             'ext'  => "Extent",
 7871:             'grs'  => "Section",
 7872:             'crd'  => "Credits",
 7873:             'sta'  => "Start",
 7874:             'end'  => "End"
 7875:     );
 7876: 
 7877:     foreach my $protectedcourse (sort(keys(%{$inccourses}))) {
 7878: 	my $thiscourse=$protectedcourse;
 7879: 	$thiscourse=~s:_:/:g;
 7880: 	my %coursedata=&Apache::lonnet::coursedescription($thiscourse);
 7881:         my $isowner = &Apache::lonuserutils::is_courseowner($protectedcourse,$coursedata{'internal.courseowner'});
 7882: 	my $area=$coursedata{'description'};
 7883:         my $crstype=$coursedata{'type'};
 7884: 	if (!defined($area)) { $area=&mt('Unavailable course').': '.$protectedcourse; }
 7885: 	my ($domain,$cnum)=split(/\//,$thiscourse);
 7886:         my %sections_count;
 7887:         if (defined($env{'request.course.id'})) {
 7888:             if ($env{'request.course.id'} eq $domain.'_'.$cnum) {
 7889:                 %sections_count = 
 7890: 		    &Apache::loncommon::get_sections($domain,$cnum);
 7891:             }
 7892:         }
 7893:         my @roles = &Apache::lonuserutils::roles_by_context('course','',$crstype);
 7894: 	foreach my $role (@roles) {
 7895:             my $plrole=&Apache::lonnet::plaintext($role,$crstype);
 7896: 	    if ((&Apache::lonnet::allowed('c'.$role,$thiscourse)) ||
 7897:                 ((($role eq 'cc') || ($role eq 'co')) && ($isowner))) {
 7898:                 $table .= &course_level_row($protectedcourse,$role,$area,$domain,
 7899:                                             $plrole,\%sections_count,\%lt,
 7900:                                             $showcredits,$defaultcredits,$crstype);
 7901:             } elsif ($env{'request.course.sec'} ne '') {
 7902:                 if (&Apache::lonnet::allowed('c'.$role,$thiscourse.'/'.
 7903:                                              $env{'request.course.sec'})) {
 7904:                     $table .= &course_level_row($protectedcourse,$role,$area,$domain,
 7905:                                                 $plrole,\%sections_count,\%lt,
 7906:                                                 $showcredits,$defaultcredits,$crstype);
 7907:                 }
 7908:             }
 7909:         }
 7910:         if (&Apache::lonnet::allowed('ccr',$thiscourse)) {
 7911:             foreach my $cust (sort(keys(%customroles))) {
 7912:                 next if ($crstype eq 'Community' && $customroles{$cust} =~ /bre\&S/);
 7913:                 my $role = 'cr_cr_'.$env{'user.domain'}.'_'.$env{'user.name'}.'_'.$cust;
 7914:                 $table .= &course_level_row($protectedcourse,$role,$area,$domain,
 7915:                                             $cust,\%sections_count,\%lt,
 7916:                                             $showcredits,$defaultcredits,$crstype);
 7917:             }
 7918: 	}
 7919:     }
 7920:     return '' if ($table eq ''); # return nothing if there is nothing 
 7921:                                  # in the table
 7922:     my $result;
 7923:     if (!$env{'request.course.id'}) {
 7924:         $result = '<h4>'.$lt{'crl'}.'</h4>'."\n";
 7925:     }
 7926:     $result .= 
 7927: &Apache::loncommon::start_data_table().
 7928: &Apache::loncommon::start_data_table_header_row().
 7929: '<th>'.$lt{'act'}.'</th><th>'.$lt{'rol'}.'</th>'."\n".
 7930: '<th>'.$lt{'ext'}.'</th><th>'."\n";
 7931:     if ($showcredits) {
 7932:         $result .= $lt{'crd'}.'</th>';
 7933:     }
 7934:     $result .=
 7935: '<th>'.$lt{'grs'}.'</th><th>'.$lt{'sta'}.'</th>'."\n".
 7936: '<th>'.$lt{'end'}.'</th>'.
 7937: &Apache::loncommon::end_data_table_header_row().
 7938: $table.
 7939: &Apache::loncommon::end_data_table();
 7940:     return $result;
 7941: }
 7942: 
 7943: sub course_level_row {
 7944:     my ($protectedcourse,$role,$area,$domain,$plrole,$sections_count,
 7945:         $lt,$showcredits,$defaultcredits,$crstype) = @_;
 7946:     my $creditem;
 7947:     my $row = &Apache::loncommon::start_data_table_row().
 7948:               ' <td><input type="checkbox" name="act_'.
 7949:               $protectedcourse.'_'.$role.'" /></td>'."\n".
 7950:               ' <td>'.$plrole.'</td>'."\n".
 7951:               ' <td>'.$area.'<br />Domain: '.$domain.'</td>'."\n";
 7952:     if (($showcredits) && ($role eq 'st') && ($crstype eq 'Course')) {
 7953:         $row .= 
 7954:             '<td><input type="text" name="credits_'.$protectedcourse.'_'.
 7955:             $role.'" size="3" value="'.$defaultcredits.'" /></td>';
 7956:     } else {
 7957:         $row .= '<td>&nbsp;</td>';
 7958:     }
 7959:     if (($role eq 'cc') || ($role eq 'co')) {
 7960:         $row .= '<td>&nbsp;</td>';
 7961:     } elsif ($env{'request.course.sec'} ne '') {
 7962:         $row .= ' <td><input type="hidden" value="'.
 7963:                 $env{'request.course.sec'}.'" '.
 7964:                 'name="sec_'.$protectedcourse.'_'.$role.'" />'.
 7965:                 $env{'request.course.sec'}.'</td>';
 7966:     } else {
 7967:         if (ref($sections_count) eq 'HASH') {
 7968:             my $currsec = 
 7969:                 &Apache::lonuserutils::course_sections($sections_count,
 7970:                                                        $protectedcourse.'_'.$role);
 7971:             $row .= '<td><table class="LC_createuser">'."\n".
 7972:                     '<tr class="LC_section_row">'."\n".
 7973:                     ' <td valign="top">'.$lt->{'exs'}.'<br />'.
 7974:                        $currsec.'</td>'."\n".
 7975:                      ' <td>&nbsp;&nbsp;</td>'."\n".
 7976:                      ' <td valign="top">&nbsp;'.$lt->{'new'}.'<br />'.
 7977:                      '<input type="text" name="newsec_'.$protectedcourse.'_'.$role.
 7978:                      '" value="" />'.
 7979:                      '<input type="hidden" '.
 7980:                      'name="sec_'.$protectedcourse.'_'.$role.'" /></td>'."\n".
 7981:                      '</tr></table></td>'."\n";
 7982:         } else {
 7983:             $row .= '<td><input type="text" size="10" '.
 7984:                     'name="sec_'.$protectedcourse.'_'.$role.'" /></td>'."\n";
 7985:         }
 7986:     }
 7987:     $row .= <<ENDTIMEENTRY;
 7988: <td><input type="hidden" name="start_$protectedcourse\_$role" value="" />
 7989: <a href=
 7990: "javascript:pjump('date_start','Start Date $plrole',document.cu.start_$protectedcourse\_$role.value,'start_$protectedcourse\_$role','cu.pres','dateset')">$lt->{'ssd'}</a></td>
 7991: <td><input type="hidden" name="end_$protectedcourse\_$role" value="" />
 7992: <a href=
 7993: "javascript:pjump('date_end','End Date $plrole',document.cu.end_$protectedcourse\_$role.value,'end_$protectedcourse\_$role','cu.pres','dateset')">$lt->{'sed'}</a></td>
 7994: ENDTIMEENTRY
 7995:     $row .= &Apache::loncommon::end_data_table_row();
 7996:     return $row;
 7997: }
 7998: 
 7999: sub course_level_dc {
 8000:     my ($dcdom,$showcredits) = @_;
 8001:     my %customroles=&Apache::lonuserutils::my_custom_roles();
 8002:     my @roles = &Apache::lonuserutils::roles_by_context('course');
 8003:     my $hiddenitems = '<input type="hidden" name="dcdomain" value="'.$dcdom.'" />'.
 8004:                       '<input type="hidden" name="origdom" value="'.$dcdom.'" />'.
 8005:                       '<input type="hidden" name="dccourse" value="" />';
 8006:     my $courseform=&Apache::loncommon::selectcourse_link
 8007:             ('cu','dccourse','dcdomain','coursedesc',undef,undef,'Select','crstype');
 8008:     my $credit_elem;
 8009:     if ($showcredits) {
 8010:         $credit_elem = 'credits';
 8011:     }
 8012:     my $cb_jscript = &Apache::loncommon::coursebrowser_javascript($dcdom,'currsec','cu','role','Course/Community Browser',$credit_elem);
 8013:     my %lt=&Apache::lonlocal::texthash(
 8014:                     'rol'  => "Role",
 8015:                     'grs'  => "Section",
 8016:                     'exs'  => "Existing sections",
 8017:                     'new'  => "Define new section", 
 8018:                     'sta'  => "Start",
 8019:                     'end'  => "End",
 8020:                     'ssd'  => "Set Start Date",
 8021:                     'sed'  => "Set End Date",
 8022:                     'scc'  => "Course/Community",
 8023:                     'crd'  => "Credits",
 8024:                   );
 8025:     my $header = '<h4>'.&mt('Course/Community Level').'</h4>'.
 8026:                  &Apache::loncommon::start_data_table().
 8027:                  &Apache::loncommon::start_data_table_header_row().
 8028:                  '<th>'.$lt{'scc'}.'</th><th>'.$lt{'rol'}.'</th>'."\n".
 8029:                  '<th>'.$lt{'grs'}.'</th>'."\n";
 8030:     $header .=   '<th>'.$lt{'crd'}.'</th>'."\n" if ($showcredits);
 8031:     $header .=   '<th>'.$lt{'sta'}.'</th><th>'.$lt{'end'}.'</th>'."\n".
 8032:                  &Apache::loncommon::end_data_table_header_row();
 8033:     my $otheritems = &Apache::loncommon::start_data_table_row()."\n".
 8034:                      '<td><br /><span class="LC_nobreak"><input type="text" name="coursedesc" value="" onfocus="this.blur();opencrsbrowser('."'cu','dccourse','dcdomain','coursedesc','','','','crstype'".')" />'.
 8035:                      $courseform.('&nbsp;' x4).'</span></td>'."\n".
 8036:                      '<td valign="top"><br /><select name="role">'."\n";
 8037:     foreach my $role (@roles) {
 8038:         my $plrole=&Apache::lonnet::plaintext($role);
 8039:         $otheritems .= '  <option value="'.$role.'">'.$plrole.'</option>';
 8040:     }
 8041:     if ( keys(%customroles) > 0) {
 8042:         foreach my $cust (sort(keys(%customroles))) {
 8043:             my $custrole='cr_cr_'.$env{'user.domain'}.
 8044:                     '_'.$env{'user.name'}.'_'.$cust;
 8045:             $otheritems .= '  <option value="'.$custrole.'">'.$cust.'</option>';
 8046:         }
 8047:     }
 8048:     $otheritems .= '</select></td><td>'.
 8049:                      '<table border="0" cellspacing="0" cellpadding="0">'.
 8050:                      '<tr><td valign="top"><b>'.$lt{'exs'}.'</b><br /><select name="currsec">'.
 8051:                      ' <option value="">&lt;--'.&mt('Pick course first').'</option></select></td>'.
 8052:                      '<td>&nbsp;&nbsp;</td>'.
 8053:                      '<td valign="top">&nbsp;<b>'.$lt{'new'}.'</b><br />'.
 8054:                      '<input type="text" name="newsec" value="" />'.
 8055:                      '<input type="hidden" name="section" value="" />'.
 8056:                      '<input type="hidden" name="groups" value="" />'.
 8057:                      '<input type="hidden" name="crstype" value="" /></td>'.
 8058:                      '</tr></table></td>'."\n";
 8059:     if ($showcredits) {
 8060:         $otheritems .= '<td><br />'."\n".
 8061:                        '<input type="text" size="3" name="credits" value="" /></td>'."\n";
 8062:     }
 8063:     $otheritems .= <<ENDTIMEENTRY;
 8064: <td><br /><input type="hidden" name="start" value='' />
 8065: <a href=
 8066: "javascript:pjump('date_start','Start Date',document.cu.start.value,'start','cu.pres','dateset')">$lt{'ssd'}</a></td>
 8067: <td><br /><input type="hidden" name="end" value='' />
 8068: <a href=
 8069: "javascript:pjump('date_end','End Date',document.cu.end.value,'end','cu.pres','dateset')">$lt{'sed'}</a></td>
 8070: ENDTIMEENTRY
 8071:     $otheritems .= &Apache::loncommon::end_data_table_row().
 8072:                    &Apache::loncommon::end_data_table()."\n";
 8073:     return $cb_jscript.$header.$hiddenitems.$otheritems;
 8074: }
 8075: 
 8076: sub update_selfenroll_config {
 8077:     my ($r,$cid,$cdom,$cnum,$context,$crstype,$currsettings) = @_;
 8078:     return unless (ref($currsettings) eq 'HASH');
 8079:     my ($row,$lt) = &Apache::lonuserutils::get_selfenroll_titles();
 8080:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
 8081:     my (%changes,%warning);
 8082:     my $curr_types;
 8083:     my %noedit;
 8084:     unless ($context eq 'domain') {
 8085:         %noedit = &get_noedit_fields($cdom,$cnum,$crstype,$row);
 8086:     }
 8087:     if (ref($row) eq 'ARRAY') {
 8088:         foreach my $item (@{$row}) {
 8089:             next if ($noedit{$item});
 8090:             if ($item eq 'enroll_dates') {
 8091:                 my (%currenrolldate,%newenrolldate);
 8092:                 foreach my $type ('start','end') {
 8093:                     $currenrolldate{$type} = $currsettings->{'selfenroll_'.$type.'_date'};
 8094:                     $newenrolldate{$type} = &Apache::lonhtmlcommon::get_date_from_form('selfenroll_'.$type.'_date');
 8095:                     if ($newenrolldate{$type} ne $currenrolldate{$type}) {
 8096:                         $changes{'internal.selfenroll_'.$type.'_date'} = $newenrolldate{$type};
 8097:                     }
 8098:                 }
 8099:             } elsif ($item eq 'access_dates') {
 8100:                 my (%currdate,%newdate);
 8101:                 foreach my $type ('start','end') {
 8102:                     $currdate{$type} = $currsettings->{'selfenroll_'.$type.'_access'};
 8103:                     $newdate{$type} = &Apache::lonhtmlcommon::get_date_from_form('selfenroll_'.$type.'_access');
 8104:                     if ($newdate{$type} ne $currdate{$type}) {
 8105:                         $changes{'internal.selfenroll_'.$type.'_access'} = $newdate{$type};
 8106:                     }
 8107:                 }
 8108:             } elsif ($item eq 'types') {
 8109:                 $curr_types = $currsettings->{'selfenroll_'.$item};
 8110:                 if ($env{'form.selfenroll_all'}) {
 8111:                     if ($curr_types ne '*') {
 8112:                         $changes{'internal.selfenroll_types'} = '*';
 8113:                     } else {
 8114:                         next;
 8115:                     }
 8116:                 } else {
 8117:                     my %currdoms;
 8118:                     my @entries = split(/;/,$curr_types);
 8119:                     my @deletedoms = &Apache::loncommon::get_env_multiple('form.selfenroll_delete');
 8120:                     my @activations = &Apache::loncommon::get_env_multiple('form.selfenroll_activate');
 8121:                     my $newnum = 0;
 8122:                     my @latesttypes;
 8123:                     foreach my $num (@activations) {
 8124:                         my @types = &Apache::loncommon::get_env_multiple('form.selfenroll_types_'.$num);
 8125:                         if (@types > 0) {
 8126:                             @types = sort(@types);
 8127:                             my $typestr = join(',',@types);
 8128:                             my $typedom = $env{'form.selfenroll_dom_'.$num};
 8129:                             $latesttypes[$newnum] = $typedom.':'.$typestr;
 8130:                             $currdoms{$typedom} = 1;
 8131:                             $newnum ++;
 8132:                         }
 8133:                     }
 8134:                     for (my $j=0; $j<$env{'form.selfenroll_types_total'}; $j++) {
 8135:                         if ((!grep(/^$j$/,@deletedoms)) && (!grep(/^$j$/,@activations))) {
 8136:                             my @types = &Apache::loncommon::get_env_multiple('form.selfenroll_types_'.$j);
 8137:                             if (@types > 0) {
 8138:                                 @types = sort(@types);
 8139:                                 my $typestr = join(',',@types);
 8140:                                 my $typedom = $env{'form.selfenroll_dom_'.$j};
 8141:                                 $latesttypes[$newnum] = $typedom.':'.$typestr;
 8142:                                 $currdoms{$typedom} = 1;
 8143:                                 $newnum ++;
 8144:                             }
 8145:                         }
 8146:                     }
 8147:                     if ($env{'form.selfenroll_newdom'} ne '') {
 8148:                         my $typedom = $env{'form.selfenroll_newdom'};
 8149:                         if ((!defined($currdoms{$typedom})) && 
 8150:                             (&Apache::lonnet::domain($typedom) ne '')) {
 8151:                             my $typestr;
 8152:                             my ($othertitle,$usertypes,$types) = 
 8153:                                 &Apache::loncommon::sorted_inst_types($typedom);
 8154:                             my $othervalue = 'any';
 8155:                             if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 8156:                                 if (@{$types} > 0) {
 8157:                                     my @esc_types = map { &escape($_); } @{$types};
 8158:                                     $othervalue = 'other';
 8159:                                     $typestr = join(',',(@esc_types,$othervalue));
 8160:                                 }
 8161:                                 $typestr = $othervalue;
 8162:                             } else {
 8163:                                 $typestr = $othervalue;
 8164:                             } 
 8165:                             $latesttypes[$newnum] = $typedom.':'.$typestr;
 8166:                             $newnum ++ ;
 8167:                         }
 8168:                     }
 8169:                     my $selfenroll_types = join(';',@latesttypes);
 8170:                     if ($selfenroll_types ne $curr_types) {
 8171:                         $changes{'internal.selfenroll_types'} = $selfenroll_types;
 8172:                     }
 8173:                 }
 8174:             } elsif ($item eq 'limit') {
 8175:                 my $newlimit = $env{'form.selfenroll_limit'};
 8176:                 my $newcap = $env{'form.selfenroll_cap'};
 8177:                 $newcap =~s/\s+//g;
 8178:                 my $currlimit =  $currsettings->{'selfenroll_limit'};
 8179:                 $currlimit = 'none' if ($currlimit eq '');
 8180:                 my $currcap = $currsettings->{'selfenroll_cap'};
 8181:                 if ($newlimit ne $currlimit) {
 8182:                     if ($newlimit ne 'none') {
 8183:                         if ($newcap =~ /^\d+$/) {
 8184:                             if ($newcap ne $currcap) {
 8185:                                 $changes{'internal.selfenroll_cap'} = $newcap;
 8186:                             }
 8187:                             $changes{'internal.selfenroll_limit'} = $newlimit;
 8188:                         } else {
 8189:                             $warning{$item} = &mt('Maximum enrollment setting unchanged.').'<br />'.
 8190:                                 &mt('The value provided was invalid - it must be a positive integer if enrollment is being limited.'); 
 8191:                         }
 8192:                     } elsif ($currcap ne '') {
 8193:                         $changes{'internal.selfenroll_cap'} = '';
 8194:                         $changes{'internal.selfenroll_limit'} = $newlimit; 
 8195:                     }
 8196:                 } elsif ($currlimit ne 'none') {
 8197:                     if ($newcap =~ /^\d+$/) {
 8198:                         if ($newcap ne $currcap) {
 8199:                             $changes{'internal.selfenroll_cap'} = $newcap;
 8200:                         }
 8201:                     } else {
 8202:                         $warning{$item} = &mt('Maximum enrollment setting unchanged.').'<br />'.
 8203:                             &mt('The value provided was invalid - it must be a positive integer if enrollment is being limited.');
 8204:                     }
 8205:                 }
 8206:             } elsif ($item eq 'approval') {
 8207:                 my (@currnotified,@newnotified);
 8208:                 my $currapproval = $currsettings->{'selfenroll_approval'};
 8209:                 my $currnotifylist = $currsettings->{'selfenroll_notifylist'};
 8210:                 if ($currnotifylist ne '') {
 8211:                     @currnotified = split(/,/,$currnotifylist);
 8212:                     @currnotified = sort(@currnotified);
 8213:                 }
 8214:                 my $newapproval = $env{'form.selfenroll_approval'};
 8215:                 @newnotified = &Apache::loncommon::get_env_multiple('form.selfenroll_notify');
 8216:                 @newnotified = sort(@newnotified);
 8217:                 if ($newapproval ne $currapproval) {
 8218:                     $changes{'internal.selfenroll_approval'} = $newapproval;
 8219:                     if (!$newapproval) {
 8220:                         if ($currnotifylist ne '') {
 8221:                             $changes{'internal.selfenroll_notifylist'} = '';
 8222:                         }
 8223:                     } else {
 8224:                         my @differences =  
 8225:                             &Apache::loncommon::compare_arrays(\@currnotified,\@newnotified);
 8226:                         if (@differences > 0) {
 8227:                             if (@newnotified > 0) {
 8228:                                 $changes{'internal.selfenroll_notifylist'} = join(',',@newnotified);
 8229:                             } else {
 8230:                                 $changes{'internal.selfenroll_notifylist'} = join(',',@newnotified);
 8231:                             }
 8232:                         }
 8233:                     }
 8234:                 } else {
 8235:                     my @differences = &Apache::loncommon::compare_arrays(\@currnotified,\@newnotified);
 8236:                     if (@differences > 0) {
 8237:                         if (@newnotified > 0) {
 8238:                             $changes{'internal.selfenroll_notifylist'} = join(',',@newnotified);
 8239:                         } else {
 8240:                             $changes{'internal.selfenroll_notifylist'} = '';
 8241:                         }
 8242:                     }
 8243:                 }
 8244:             } else {
 8245:                 my $curr_val = $currsettings->{'selfenroll_'.$item};
 8246:                 my $newval = $env{'form.selfenroll_'.$item};
 8247:                 if ($item eq 'section') {
 8248:                     $newval = $env{'form.sections'};
 8249:                     if (defined($curr_groups{$newval})) {
 8250:                         $newval = $curr_val;
 8251:                         $warning{$item} = &mt('Section for self-enrolled users unchanged as the proposed section is a group').'<br />'.
 8252:                                           &mt('Group names and section names must be distinct');
 8253:                     } elsif ($newval eq 'all') {
 8254:                         $newval = $curr_val;
 8255:                         $warning{$item} = &mt('Section for self-enrolled users unchanged, as "all" is a reserved section name.');
 8256:                     }
 8257:                     if ($newval eq '') {
 8258:                         $newval = 'none';
 8259:                     }
 8260:                 }
 8261:                 if ($newval ne $curr_val) {
 8262:                     $changes{'internal.selfenroll_'.$item} = $newval;
 8263:                 }
 8264:             }
 8265:         }
 8266:         if (keys(%warning) > 0) {
 8267:             foreach my $item (@{$row}) {
 8268:                 if (exists($warning{$item})) {
 8269:                     $r->print($warning{$item}.'<br />');
 8270:                 }
 8271:             } 
 8272:         }
 8273:         if (keys(%changes) > 0) {
 8274:             my $putresult = &Apache::lonnet::put('environment',\%changes,$cdom,$cnum);
 8275:             if ($putresult eq 'ok') {
 8276:                 if ((exists($changes{'internal.selfenroll_types'})) ||
 8277:                     (exists($changes{'internal.selfenroll_start_date'}))  ||
 8278:                     (exists($changes{'internal.selfenroll_end_date'}))) {
 8279:                     my %crsinfo = &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',
 8280:                                                                 $cnum,undef,undef,'Course');
 8281:                     my $chome = &Apache::lonnet::homeserver($cnum,$cdom);
 8282:                     if (ref($crsinfo{$cid}) eq 'HASH') {
 8283:                         foreach my $item ('selfenroll_types','selfenroll_start_date','selfenroll_end_date') {
 8284:                             if (exists($changes{'internal.'.$item})) {
 8285:                                 $crsinfo{$cid}{$item} = $changes{'internal.'.$item};
 8286:                             }
 8287:                         }
 8288:                         my $crsputresult =
 8289:                             &Apache::lonnet::courseidput($cdom,\%crsinfo,
 8290:                                                          $chome,'notime');
 8291:                     }
 8292:                 }
 8293:                 $r->print(&mt('The following changes were made to self-enrollment settings:').'<ul>');
 8294:                 foreach my $item (@{$row}) {
 8295:                     my $title = $item;
 8296:                     if (ref($lt) eq 'HASH') {
 8297:                         $title = $lt->{$item};
 8298:                     }
 8299:                     if ($item eq 'enroll_dates') {
 8300:                         foreach my $type ('start','end') {
 8301:                             if (exists($changes{'internal.selfenroll_'.$type.'_date'})) {
 8302:                                 my $newdate = &Apache::lonlocal::locallocaltime($changes{'internal.selfenroll_'.$type.'_date'});
 8303:                                 $r->print('<li>'.&mt('[_1]: "[_2]" set to "[_3]".',
 8304:                                           $title,$type,$newdate).'</li>');
 8305:                             }
 8306:                         }
 8307:                     } elsif ($item eq 'access_dates') {
 8308:                         foreach my $type ('start','end') {
 8309:                             if (exists($changes{'internal.selfenroll_'.$type.'_access'})) {
 8310:                                 my $newdate = &Apache::lonlocal::locallocaltime($changes{'internal.selfenroll_'.$type.'_access'});
 8311:                                 $r->print('<li>'.&mt('[_1]: "[_2]" set to "[_3]".',
 8312:                                           $title,$type,$newdate).'</li>');
 8313:                             }
 8314:                         }
 8315:                     } elsif ($item eq 'limit') {
 8316:                         if ((exists($changes{'internal.selfenroll_limit'})) ||
 8317:                             (exists($changes{'internal.selfenroll_cap'}))) {
 8318:                             my ($newval,$newcap);
 8319:                             if ($changes{'internal.selfenroll_cap'} ne '') {
 8320:                                 $newcap = $changes{'internal.selfenroll_cap'}
 8321:                             } else {
 8322:                                 $newcap = $currsettings->{'selfenroll_cap'};
 8323:                             }
 8324:                             if ($changes{'internal.selfenroll_limit'} eq 'none') {
 8325:                                 $newval = &mt('No limit');
 8326:                             } elsif ($changes{'internal.selfenroll_limit'} eq 
 8327:                                      'allstudents') {
 8328:                                 $newval = &mt('New self-enrollment no longer allowed when total (all students) reaches [_1].',$newcap);
 8329:                             } elsif ($changes{'internal.selfenroll_limit'} eq 'selfenrolled') {
 8330:                                 $newval = &mt('New self-enrollment no longer allowed when total number of self-enrolled students reaches [_1].',$newcap);
 8331:                             } else {
 8332:                                 my $currlimit =  $currsettings->{'selfenroll_limit'};
 8333:                                 if ($currlimit eq 'allstudents') {
 8334:                                     $newval = &mt('New self-enrollment no longer allowed when total (all students) reaches [_1].',$newcap);
 8335:                                 } elsif ($changes{'internal.selfenroll_limit'} eq 'selfenrolled') {
 8336:                                     $newval =  &mt('New self-enrollment no longer allowed when total number of self-enrolled students reaches [_1].',$newcap);
 8337:                                 }
 8338:                             }
 8339:                             $r->print('<li>'.&mt('"[_1]" set to "[_2]".',$title,$newval).'</li>'."\n");
 8340:                         }
 8341:                     } elsif ($item eq 'approval') {
 8342:                         if ((exists($changes{'internal.selfenroll_approval'})) ||
 8343:                             (exists($changes{'internal.selfenroll_notifylist'}))) {
 8344:                             my %selfdescs = &Apache::lonuserutils::selfenroll_default_descs();
 8345:                             my ($newval,$newnotify);
 8346:                             if (exists($changes{'internal.selfenroll_notifylist'})) {
 8347:                                 $newnotify = $changes{'internal.selfenroll_notifylist'};
 8348:                             } else {   
 8349:                                 $newnotify = $currsettings->{'selfenroll_notifylist'};
 8350:                             }
 8351:                             if (exists($changes{'internal.selfenroll_approval'})) {
 8352:                                 if ($changes{'internal.selfenroll_approval'} !~ /^[012]$/) {
 8353:                                     $changes{'internal.selfenroll_approval'} = '0';
 8354:                                 }
 8355:                                 $newval = $selfdescs{'approval'}{$changes{'internal.selfenroll_approval'}};
 8356:                             } else {
 8357:                                 my $currapproval = $currsettings->{'selfenroll_approval'}; 
 8358:                                 if ($currapproval !~ /^[012]$/) {
 8359:                                     $currapproval = 0;
 8360:                                 }
 8361:                                 $newval = $selfdescs{'approval'}{$currapproval};
 8362:                             }
 8363:                             $r->print('<li>'.&mt('"[_1]" set to "[_2]".',$title,$newval));
 8364:                             if ($newnotify) {
 8365:                                 $r->print('<br />'.&mt('The following will be notified when an enrollment request needs approval, or has been approved: [_1].',$newnotify));
 8366:                             } else {
 8367:                                 $r->print('<br />'.&mt('No notifications sent when an enrollment request needs approval, or has been approved.'));
 8368:                             }
 8369:                             $r->print('</li>'."\n");
 8370:                         }
 8371:                     } else {
 8372:                         if (exists($changes{'internal.selfenroll_'.$item})) {
 8373:                             my $newval = $changes{'internal.selfenroll_'.$item};
 8374:                             if ($item eq 'types') {
 8375:                                 if ($newval eq '') {
 8376:                                     $newval = &mt('None');
 8377:                                 } elsif ($newval eq '*') {
 8378:                                     $newval = &mt('Any user in any domain');
 8379:                                 }
 8380:                             } elsif ($item eq 'registered') {
 8381:                                 if ($newval eq '1') {
 8382:                                     $newval = &mt('Yes');
 8383:                                 } elsif ($newval eq '0') {
 8384:                                     $newval = &mt('No');
 8385:                                 }
 8386:                             }
 8387:                             $r->print('<li>'.&mt('"[_1]" set to "[_2]".',$title,$newval).'</li>'."\n");
 8388:                         }
 8389:                     }
 8390:                 }
 8391:                 $r->print('</ul>');
 8392:                 if ($env{'course.'.$cid.'.description'} ne '') {
 8393:                     my %newenvhash;
 8394:                     foreach my $key (keys(%changes)) {
 8395:                         $newenvhash{'course.'.$cid.'.'.$key} = $changes{$key};
 8396:                     }
 8397:                     &Apache::lonnet::appenv(\%newenvhash);
 8398:                 }
 8399:             } else {
 8400:                 $r->print(&mt('An error occurred when saving changes to self-enrollment settings in this course.').'<br />'.
 8401:                           &mt('The error was: [_1].',$putresult));
 8402:             }
 8403:         } else {
 8404:             $r->print(&mt('No changes were made to the existing self-enrollment settings in this course.'));
 8405:         }
 8406:     } else {
 8407:         $r->print(&mt('No changes were made to the existing self-enrollment settings in this course.'));
 8408:     }
 8409:     my $visactions = &cat_visibility();
 8410:     my ($cathash,%cattype);
 8411:     my %domconfig = &Apache::lonnet::get_dom('configuration',['coursecategories'],$cdom);
 8412:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 8413:         $cathash = $domconfig{'coursecategories'}{'cats'};
 8414:         $cattype{'auth'} = $domconfig{'coursecategories'}{'auth'};
 8415:         $cattype{'unauth'} = $domconfig{'coursecategories'}{'unauth'};
 8416:     } else {
 8417:         $cathash = {};
 8418:         $cattype{'auth'} = 'std';
 8419:         $cattype{'unauth'} = 'std';
 8420:     }
 8421:     if (($cattype{'auth'} eq 'none') && ($cattype{'unauth'} eq 'none')) {
 8422:         $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
 8423:                   '<br />'.
 8424:                   '<br />'.$visactions->{'take'}.'<ul>'.
 8425:                   '<li>'.$visactions->{'dc_chgconf'}.'</li>'.
 8426:                   '</ul>');
 8427:     } elsif (($cattype{'auth'} !~ /^(std|domonly)$/) && ($cattype{'unauth'} !~ /^(std|domonly)$/)) {
 8428:         if ($currsettings->{'uniquecode'}) {
 8429:             $r->print('<span class="LC_info">'.$visactions->{'vis'}.'</span>');
 8430:         } else {
 8431:             $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
 8432:                   '<br />'.
 8433:                   '<br />'.$visactions->{'take'}.'<ul>'.
 8434:                   '<li>'.$visactions->{'dc_setcode'}.'</li>'.
 8435:                   '</ul><br />');
 8436:         }
 8437:     } else {
 8438:         my ($visible,$cansetvis,$vismsgs) = &visible_in_stdcat($cdom,$cnum,\%domconfig);
 8439:         if (ref($visactions) eq 'HASH') {
 8440:             if (!$visible) {
 8441:                 $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
 8442:                           '<br />');
 8443:                 if (ref($vismsgs) eq 'ARRAY') {
 8444:                     $r->print('<br />'.$visactions->{'take'}.'<ul>');
 8445:                     foreach my $item (@{$vismsgs}) {
 8446:                         $r->print('<li>'.$visactions->{$item}.'</li>');
 8447:                     }
 8448:                     $r->print('</ul>');
 8449:                 }
 8450:                 $r->print($cansetvis);
 8451:             }
 8452:         }
 8453:     } 
 8454:     return;
 8455: }
 8456: 
 8457: #---------------------------------------------- end functions for &phase_two
 8458: 
 8459: #--------------------------------- functions for &phase_two and &phase_three
 8460: 
 8461: #--------------------------end of functions for &phase_two and &phase_three
 8462: 
 8463: 1;
 8464: __END__
 8465: 
 8466: 

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