File:  [LON-CAPA] / loncom / interface / loncreateuser.pm
Revision 1.391: download - view: text, annotated - select for diffs
Wed Feb 12 21:29:03 2014 UTC (10 years, 3 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Bug 6646
  - Self-creation of user accounts with e-mail address as username can
    be queued for approval.
  - Link in Domain Coordinator's User Management menu to approve/reject
    requests.
  - Support for pop-up window to display details of new account request.
  - User information and password requested from prospective user in a single
    web form.

    1: # The LearningOnline Network with CAPA
    2: # Create a user
    3: #
    4: # $Id: loncreateuser.pm,v 1.391 2014/02/12 21:29:03 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: ###
   29: 
   30: package Apache::loncreateuser;
   31: 
   32: =pod
   33: 
   34: =head1 NAME
   35: 
   36: Apache::loncreateuser.pm
   37: 
   38: =head1 SYNOPSIS
   39: 
   40:     Handler to create users and custom roles
   41: 
   42:     Provides an Apache handler for creating users,
   43:     editing their login parameters, roles, and removing roles, and
   44:     also creating and assigning custom roles.
   45: 
   46: =head1 OVERVIEW
   47: 
   48: =head2 Custom Roles
   49: 
   50: In LON-CAPA, roles are actually collections of privileges. "Teaching
   51: Assistant", "Course Coordinator", and other such roles are really just
   52: collection of privileges that are useful in many circumstances.
   53: 
   54: Custom roles can be defined by a Domain Coordinator, Course Coordinator
   55: or Community Coordinator via the Manage User functionality.
   56: The custom role editor screen will show all privileges which can be
   57: assigned to users. For a complete list of privileges, please see 
   58: C</home/httpd/lonTabs/rolesplain.tab>.
   59: 
   60: Custom role definitions are stored in the C<roles.db> file of the creator
   61: of the role.
   62: 
   63: =cut
   64: 
   65: use strict;
   66: use Apache::Constants qw(:common :http);
   67: use Apache::lonnet;
   68: use Apache::loncommon;
   69: use Apache::lonlocal;
   70: use Apache::longroup;
   71: use Apache::lonuserutils;
   72: use Apache::loncoursequeueadmin;
   73: use LONCAPA qw(:DEFAULT :match);
   74: 
   75: my $loginscript; # piece of javascript used in two separate instances
   76: my $authformnop;
   77: my $authformkrb;
   78: my $authformint;
   79: my $authformfsys;
   80: my $authformloc;
   81: 
   82: sub initialize_authen_forms {
   83:     my ($dom,$formname,$curr_authtype,$mode) = @_;
   84:     my ($krbdef,$krbdefdom) = &Apache::loncommon::get_kerberos_defaults($dom);
   85:     my %param = ( formname => $formname,
   86:                   kerb_def_dom => $krbdefdom,
   87:                   kerb_def_auth => $krbdef,
   88:                   domain => $dom,
   89:                 );
   90:     my %abv_auth = &auth_abbrev();
   91:     if ($curr_authtype =~ /^(krb4|krb5|internal|localauth|unix):(.*)$/) {
   92:         my $long_auth = $1;
   93:         my $curr_autharg = $2;
   94:         my %abv_auth = &auth_abbrev();
   95:         $param{'curr_authtype'} = $abv_auth{$long_auth};
   96:         if ($long_auth =~ /^krb(4|5)$/) {
   97:             $param{'curr_kerb_ver'} = $1;
   98:             $param{'curr_autharg'} = $curr_autharg;
   99:         }
  100:         if ($mode eq 'modifyuser') {
  101:             $param{'mode'} = $mode;
  102:         }
  103:     }
  104:     $loginscript  = &Apache::loncommon::authform_header(%param);
  105:     $authformkrb  = &Apache::loncommon::authform_kerberos(%param);
  106:     $authformnop  = &Apache::loncommon::authform_nochange(%param);
  107:     $authformint  = &Apache::loncommon::authform_internal(%param);
  108:     $authformfsys = &Apache::loncommon::authform_filesystem(%param);
  109:     $authformloc  = &Apache::loncommon::authform_local(%param);
  110: }
  111: 
  112: sub auth_abbrev {
  113:     my %abv_auth = (
  114:                      krb5      => 'krb',
  115:                      krb4      => 'krb',
  116:                      internal  => 'int',
  117:                      localauth => 'loc',
  118:                      unix      => 'fsys',
  119:                    );
  120:     return %abv_auth;
  121: }
  122: 
  123: # ====================================================
  124: 
  125: sub user_quotas {
  126:     my ($ccuname,$ccdomain) = @_;
  127:     my %lt = &Apache::lonlocal::texthash(
  128:                    'usrt'      => "User Tools",
  129:                    'cust'      => "Custom quota",
  130:                    'chqu'      => "Change quota",
  131:     );
  132:    
  133:     my $quota_javascript = <<"END_SCRIPT";
  134: <script type="text/javascript">
  135: // <![CDATA[
  136: function quota_changes(caller,context) {
  137:     var customoff = document.getElementById('custom_'+context+'quota_off');
  138:     var customon = document.getElementById('custom_'+context+'quota_on');
  139:     var number = document.getElementById(context+'quota');
  140:     if (caller == "custom") {
  141:         if (customoff) {
  142:             if (customoff.checked) {
  143:                 number.value = "";
  144:             }
  145:         }
  146:     }
  147:     if (caller == "quota") {
  148:         if (customon) {
  149:             customon.checked = true;
  150:         }
  151:     }
  152:     return;
  153: }
  154: // ]]>
  155: </script>
  156: END_SCRIPT
  157:     my $longinsttype;
  158:     my ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($ccdomain);
  159:     my $output = $quota_javascript."\n".
  160:                  '<h3>'.$lt{'usrt'}.'</h3>'."\n".
  161:                  &Apache::loncommon::start_data_table();
  162: 
  163:     if (&Apache::lonnet::allowed('mut',$ccdomain)) {
  164:         $output .= &build_tools_display($ccuname,$ccdomain,'tools');
  165:     }
  166: 
  167:     my %titles = &Apache::lonlocal::texthash (
  168:                     portfolio => "Disk space allocated to user's portfolio files",
  169:                     author    => "Disk space allocated to user's Authoring Space (if role assigned)",
  170:                  );
  171:     foreach my $name ('portfolio','author') {
  172:         my ($currquota,$quotatype,$inststatus,$defquota) =
  173:             &Apache::loncommon::get_user_quota($ccuname,$ccdomain,$name);
  174:         if ($longinsttype eq '') { 
  175:             if ($inststatus ne '') {
  176:                 if ($usertypes->{$inststatus} ne '') {
  177:                     $longinsttype = $usertypes->{$inststatus};
  178:                 }
  179:             }
  180:         }
  181:         my ($showquota,$custom_on,$custom_off,$defaultinfo);
  182:         $custom_on = ' ';
  183:         $custom_off = ' checked="checked" ';
  184:         if ($quotatype eq 'custom') {
  185:             $custom_on = $custom_off;
  186:             $custom_off = ' ';
  187:             $showquota = $currquota;
  188:             if ($longinsttype eq '') {
  189:                 $defaultinfo = &mt('For this user, the default quota would be [_1]'
  190:                               .' MB.',$defquota);
  191:             } else {
  192:                 $defaultinfo = &mt("For this user, the default quota would be [_1]".
  193:                                    " MB, as determined by the user's institutional".
  194:                                    " affiliation ([_2]).",$defquota,$longinsttype);
  195:             }
  196:         } else {
  197:             if ($longinsttype eq '') {
  198:                 $defaultinfo = &mt('For this user, the default quota is [_1]'
  199:                               .' MB.',$defquota);
  200:             } else {
  201:                 $defaultinfo = &mt("For this user, the default quota of [_1]".
  202:                                    " MB, is determined by the user's institutional".
  203:                                    " affiliation ([_2]).",$defquota,$longinsttype);
  204:             }
  205:         }
  206: 
  207:         if (&Apache::lonnet::allowed('mpq',$ccdomain)) {
  208:             $output .= '<tr class="LC_info_row">'."\n".
  209:                        '    <td>'.$titles{$name}.'</td>'."\n".
  210:                        '  </tr>'."\n".
  211:                        &Apache::loncommon::start_data_table_row()."\n".
  212:                        '  <td><span class="LC_nobreak">'.
  213:                        &mt('Current quota: [_1] MB',$currquota).'</span>&nbsp;&nbsp;'.
  214:                        $defaultinfo.'</td>'."\n".
  215:                        &Apache::loncommon::end_data_table_row()."\n".
  216:                        &Apache::loncommon::start_data_table_row()."\n".
  217:                        '  <td><span class="LC_nobreak">'.$lt{'chqu'}.
  218:                        ': <label>'.
  219:                        '<input type="radio" name="custom_'.$name.'quota" id="custom_'.$name.'quota_off" '.
  220:                        'value="0" '.$custom_off.' onchange="javascript:quota_changes('."'custom','$name'".');"'.
  221:                        ' /><span class="LC_nobreak">'.
  222:                        &mt('Default ([_1] MB)',$defquota).'</span></label>&nbsp;'.
  223:                        '&nbsp;<label><input type="radio" name="custom_'.$name.'quota" id="custom_'.$name.'quota_on" '.
  224:                        'value="1" '.$custom_on.'  onchange="javascript:quota_changes('."'custom','$name'".');"'.
  225:                        ' />'.$lt{'cust'}.':</label>&nbsp;'.
  226:                        '<input type="text" name="'.$name.'quota" id="'.$name.'quota" size ="5" '.
  227:                        'value="'.$showquota.'" onfocus="javascript:quota_changes('."'quota','$name'".');"'.
  228:                        ' />&nbsp;'.&mt('MB').'</span></td>'."\n".
  229:                        &Apache::loncommon::end_data_table_row()."\n";
  230:         }
  231:     }
  232:     $output .= &Apache::loncommon::end_data_table();
  233:     return $output;
  234: }
  235: 
  236: sub build_tools_display {
  237:     my ($ccuname,$ccdomain,$context) = @_;
  238:     my (@usertools,%userenv,$output,@options,%validations,%reqtitles,%reqdisplay,
  239:         $colspan,$isadv,%domconfig);
  240:     my %lt = &Apache::lonlocal::texthash (
  241:                    'blog'       => "Personal User Blog",
  242:                    'aboutme'    => "Personal Information Page",
  243:                    'webdav'     => "WebDAV access to Authoring Spaces (if SSL and author/co-author)",
  244:                    'portfolio'  => "Personal User Portfolio",
  245:                    'avai'       => "Available",
  246:                    'cusa'       => "availability",
  247:                    'chse'       => "Change setting",
  248:                    'usde'       => "Use default",
  249:                    'uscu'       => "Use custom",
  250:                    'official'   => 'Can request creation of official courses',
  251:                    'unofficial' => 'Can request creation of unofficial courses',
  252:                    'community'  => 'Can request creation of communities',
  253:                    'textbook'   => 'Can request creation of textbook courses',
  254:                    'requestauthor'  => 'Can request author space',
  255:     );
  256:     if ($context eq 'requestcourses') {
  257:         %userenv = &Apache::lonnet::userenvironment($ccdomain,$ccuname,
  258:                       'requestcourses.official','requestcourses.unofficial',
  259:                       'requestcourses.community','requestcourses.textbook');
  260:         @usertools = ('official','unofficial','community','textbook');
  261:         @options =('norequest','approval','autolimit','validate');
  262:         %validations = &Apache::lonnet::auto_courserequest_checks($ccdomain);
  263:         %reqtitles = &courserequest_titles();
  264:         %reqdisplay = &courserequest_display();
  265:         $colspan = ' colspan="2"';
  266:         %domconfig =
  267:             &Apache::lonnet::get_dom('configuration',['requestcourses'],$ccdomain);
  268:         $isadv = &Apache::lonnet::is_advanced_user($ccuname,$ccdomain);
  269:     } elsif ($context eq 'requestauthor') {
  270:         %userenv = &Apache::lonnet::userenvironment($ccdomain,$ccuname,
  271:                                                     'requestauthor');
  272:         @usertools = ('requestauthor');
  273:         @options =('norequest','approval','automatic');
  274:         %reqtitles = &requestauthor_titles();
  275:         %reqdisplay = &requestauthor_display();
  276:         $colspan = ' colspan="2"';
  277:         %domconfig =
  278:             &Apache::lonnet::get_dom('configuration',['requestauthor'],$ccdomain);
  279:     } else {
  280:         %userenv = &Apache::lonnet::userenvironment($ccdomain,$ccuname,
  281:                           'tools.aboutme','tools.portfolio','tools.blog',
  282:                           'tools.webdav');
  283:         @usertools = ('aboutme','blog','webdav','portfolio');
  284:     }
  285:     foreach my $item (@usertools) {
  286:         my ($custom_access,$curr_access,$cust_on,$cust_off,$tool_on,$tool_off,
  287:             $currdisp,$custdisp,$custradio);
  288:         $cust_off = 'checked="checked" ';
  289:         $tool_on = 'checked="checked" ';
  290:         $curr_access =  
  291:             &Apache::lonnet::usertools_access($ccuname,$ccdomain,$item,undef,
  292:                                               $context);
  293:         if ($context eq 'requestauthor') {
  294:             if ($userenv{$context} ne '') {
  295:                 $cust_on = ' checked="checked" ';
  296:                 $cust_off = '';
  297:             }  
  298:         } elsif ($userenv{$context.'.'.$item} ne '') {
  299:             $cust_on = ' checked="checked" ';
  300:             $cust_off = '';
  301:         }
  302:         if ($context eq 'requestcourses') {
  303:             if ($userenv{$context.'.'.$item} eq '') {
  304:                 $custom_access = &mt('Currently from default setting.');
  305:             } else {
  306:                 $custom_access = &mt('Currently from custom setting.');
  307:             }
  308:         } elsif ($context eq 'requestauthor') {
  309:             if ($userenv{$context} eq '') {
  310:                 $custom_access = &mt('Currently from default setting.');
  311:             } else {
  312:                 $custom_access = &mt('Currently from custom setting.');
  313:             }
  314:         } else {
  315:             if ($userenv{$context.'.'.$item} eq '') {
  316:                 $custom_access =
  317:                     &mt('Availability determined currently from default setting.');
  318:                 if (!$curr_access) {
  319:                     $tool_off = 'checked="checked" ';
  320:                     $tool_on = '';
  321:                 }
  322:             } else {
  323:                 $custom_access =
  324:                     &mt('Availability determined currently from custom setting.');
  325:                 if ($userenv{$context.'.'.$item} == 0) {
  326:                     $tool_off = 'checked="checked" ';
  327:                     $tool_on = '';
  328:                 }
  329:             }
  330:         }
  331:         $output .= '  <tr class="LC_info_row">'."\n".
  332:                    '   <td'.$colspan.'>'.$lt{$item}.'</td>'."\n".
  333:                    '  </tr>'."\n".
  334:                    &Apache::loncommon::start_data_table_row()."\n";
  335:         if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
  336:             my ($curroption,$currlimit);
  337:             my $envkey = $context.'.'.$item;
  338:             if ($context eq 'requestauthor') {
  339:                 $envkey = $context;
  340:             }
  341:             if ($userenv{$envkey} ne '') {
  342:                 $curroption = $userenv{$envkey};
  343:             } else {
  344:                 my (@inststatuses);
  345:                 if ($context eq 'requestcourses') {
  346:                     $curroption =
  347:                         &Apache::loncoursequeueadmin::get_processtype('course',$ccuname,$ccdomain,
  348:                                                                       $isadv,$ccdomain,$item,
  349:                                                                       \@inststatuses,\%domconfig);
  350:                 } else {
  351:                      $curroption = 
  352:                          &Apache::loncoursequeueadmin::get_processtype('requestauthor',$ccuname,$ccdomain,
  353:                                                                        $isadv,$ccdomain,undef,
  354:                                                                        \@inststatuses,\%domconfig);
  355:                 }
  356:             }
  357:             if (!$curroption) {
  358:                 $curroption = 'norequest';
  359:             }
  360:             if ($curroption =~ /^autolimit=(\d*)$/) {
  361:                 $currlimit = $1;
  362:                 if ($currlimit eq '') {
  363:                     $currdisp = &mt('Yes, automatic creation');
  364:                 } else {
  365:                     $currdisp = &mt('Yes, up to [quant,_1,request]/user',$currlimit);
  366:                 }
  367:             } else {
  368:                 $currdisp = $reqdisplay{$curroption};
  369:             }
  370:             $custdisp = '<table>';
  371:             foreach my $option (@options) {
  372:                 my $val = $option;
  373:                 if ($option eq 'norequest') {
  374:                     $val = 0;
  375:                 }
  376:                 if ($option eq 'validate') {
  377:                     my $canvalidate = 0;
  378:                     if (ref($validations{$item}) eq 'HASH') {
  379:                         if ($validations{$item}{'_custom_'}) {
  380:                             $canvalidate = 1;
  381:                         }
  382:                     }
  383:                     next if (!$canvalidate);
  384:                 }
  385:                 my $checked = '';
  386:                 if ($option eq $curroption) {
  387:                     $checked = ' checked="checked"';
  388:                 } elsif ($option eq 'autolimit') {
  389:                     if ($curroption =~ /^autolimit/) {
  390:                         $checked = ' checked="checked"';
  391:                     }
  392:                 }
  393:                 my $name = 'crsreq_'.$item;
  394:                 if ($context eq 'requestauthor') {
  395:                     $name = $item;
  396:                 }
  397:                 $custdisp .= '<tr><td><span class="LC_nobreak"><label>'.
  398:                              '<input type="radio" name="'.$name.'" '.
  399:                              'value="'.$val.'"'.$checked.' />'.
  400:                              $reqtitles{$option}.'</label>&nbsp;';
  401:                 if ($option eq 'autolimit') {
  402:                     $custdisp .= '<input type="text" name="'.$name.
  403:                                  '_limit" size="1" '.
  404:                                  'value="'.$currlimit.'" /></span><br />'.
  405:                                  $reqtitles{'unlimited'};
  406:                 } else {
  407:                     $custdisp .= '</span>';
  408:                 }
  409:                 $custdisp .= '</td></tr>';
  410:             }
  411:             $custdisp .= '</table>';
  412:             $custradio = '</span></td><td>'.&mt('Custom setting').'<br />'.$custdisp;
  413:         } else {
  414:             $currdisp = ($curr_access?&mt('Yes'):&mt('No'));
  415:             my $name = $context.'_'.$item;
  416:             if ($context eq 'requestauthor') {
  417:                 $name = $context;
  418:             }
  419:             $custdisp = '<span class="LC_nobreak"><label>'.
  420:                         '<input type="radio" name="'.$name.'"'.
  421:                         ' value="1" '.$tool_on.'/>'.&mt('On').'</label>&nbsp;<label>'.
  422:                         '<input type="radio" name="'.$name.'" value="0" '.
  423:                         $tool_off.'/>'.&mt('Off').'</label></span>';
  424:             $custradio = ('&nbsp;'x2).'--'.$lt{'cusa'}.':&nbsp;'.$custdisp.
  425:                           '</span>';
  426:         }
  427:         $output .= '  <td'.$colspan.'>'.$custom_access.('&nbsp;'x4).
  428:                    $lt{'avai'}.': '.$currdisp.'</td>'."\n".
  429:                    &Apache::loncommon::end_data_table_row()."\n".
  430:                    &Apache::loncommon::start_data_table_row()."\n".
  431:                    '  <td style="vertical-align:top;"><span class="LC_nobreak">'.
  432:                    $lt{'chse'}.': <label>'.
  433:                    '<input type="radio" name="custom'.$item.'" value="0" '.
  434:                    $cust_off.'/>'.$lt{'usde'}.'</label>'.('&nbsp;' x3).
  435:                    '<label><input type="radio" name="custom'.$item.'" value="1" '.
  436:                    $cust_on.'/>'.$lt{'uscu'}.'</label>'.$custradio.'</td>'.
  437:                    &Apache::loncommon::end_data_table_row()."\n";
  438:     }
  439:     return $output;
  440: }
  441: 
  442: sub coursereq_externaluser {
  443:     my ($ccuname,$ccdomain,$cdom) = @_;
  444:     my (@usertools,@options,%validations,%userenv,$output);
  445:     my %lt = &Apache::lonlocal::texthash (
  446:                    'official'   => 'Can request creation of official courses',
  447:                    'unofficial' => 'Can request creation of unofficial courses',
  448:                    'community'  => 'Can request creation of communities',
  449:                    'textbook'   => 'Can request creation of textbook courses',
  450:     );
  451: 
  452:     %userenv = &Apache::lonnet::userenvironment($ccdomain,$ccuname,
  453:                       'reqcrsotherdom.official','reqcrsotherdom.unofficial',
  454:                       'reqcrsotherdom.community','reqcrsotherdom.textbook');
  455:     @usertools = ('official','unofficial','community','textbook');
  456:     @options = ('approval','validate','autolimit');
  457:     %validations = &Apache::lonnet::auto_courserequest_checks($cdom);
  458:     my $optregex = join('|',@options);
  459:     my %reqtitles = &courserequest_titles();
  460:     foreach my $item (@usertools) {
  461:         my ($curroption,$currlimit,$tooloff);
  462:         if ($userenv{'reqcrsotherdom.'.$item} ne '') {
  463:             my @curr = split(',',$userenv{'reqcrsotherdom.'.$item});
  464:             foreach my $req (@curr) {
  465:                 if ($req =~ /^\Q$cdom\E\:($optregex)=?(\d*)$/) {
  466:                     $curroption = $1;
  467:                     $currlimit = $2;
  468:                     last;
  469:                 }
  470:             }
  471:             if (!$curroption) {
  472:                 $curroption = 'norequest';
  473:                 $tooloff = ' checked="checked"';
  474:             }
  475:         } else {
  476:             $curroption = 'norequest';
  477:             $tooloff = ' checked="checked"';
  478:         }
  479:         $output.= &Apache::loncommon::start_data_table_row()."\n".
  480:                   '  <td><span class="LC_nobreak">'.$lt{$item}.': </span></td><td>'.
  481:                   '<table><tr><td valign="top">'."\n".
  482:                   '<label><input type="radio" name="reqcrsotherdom_'.$item.
  483:                   '" value=""'.$tooloff.' />'.$reqtitles{'norequest'}.
  484:                   '</label></td>';
  485:         foreach my $option (@options) {
  486:             if ($option eq 'validate') {
  487:                 my $canvalidate = 0;
  488:                 if (ref($validations{$item}) eq 'HASH') {
  489:                     if ($validations{$item}{'_external_'}) {
  490:                         $canvalidate = 1;
  491:                     }
  492:                 }
  493:                 next if (!$canvalidate);
  494:             }
  495:             my $checked = '';
  496:             if ($option eq $curroption) {
  497:                 $checked = ' checked="checked"';
  498:             }
  499:             $output .= '<td valign="top"><span class="LC_nobreak"><label>'.
  500:                        '<input type="radio" name="reqcrsotherdom_'.$item.
  501:                        '" value="'.$option.'"'.$checked.' />'.
  502:                        $reqtitles{$option}.'</label>';
  503:             if ($option eq 'autolimit') {
  504:                 $output .= '&nbsp;<input type="text" name="reqcrsotherdom_'.
  505:                            $item.'_limit" size="1" '.
  506:                            'value="'.$currlimit.'" /></span>'.
  507:                            '<br />'.$reqtitles{'unlimited'};
  508:             } else {
  509:                 $output .= '</span>';
  510:             }
  511:             $output .= '</td>';
  512:         }
  513:         $output .= '</td></tr></table></td>'."\n".
  514:                    &Apache::loncommon::end_data_table_row()."\n";
  515:     }
  516:     return $output;
  517: }
  518: 
  519: sub domainrole_req {
  520:     my ($ccuname,$ccdomain) = @_;
  521:     return '<br /><h3>'.
  522:            &mt('User Can Request Assignment of Domain Roles?').
  523:            '</h3>'."\n".
  524:            &Apache::loncommon::start_data_table().
  525:            &build_tools_display($ccuname,$ccdomain,
  526:                                 'requestauthor').
  527:            &Apache::loncommon::end_data_table();
  528: }
  529: 
  530: sub courserequest_titles {
  531:     my %titles = &Apache::lonlocal::texthash (
  532:                                    official   => 'Official',
  533:                                    unofficial => 'Unofficial',
  534:                                    community  => 'Communities',
  535:                                    textbook   => 'Textbook',
  536:                                    norequest  => 'Not allowed',
  537:                                    approval   => 'Approval by Dom. Coord.',
  538:                                    validate   => 'With validation',
  539:                                    autolimit  => 'Numerical limit',
  540:                                    unlimited  => '(blank for unlimited)',
  541:                  );
  542:     return %titles;
  543: }
  544: 
  545: sub courserequest_display {
  546:     my %titles = &Apache::lonlocal::texthash (
  547:                                    approval   => 'Yes, need approval',
  548:                                    validate   => 'Yes, with validation',
  549:                                    norequest  => 'No',
  550:    );
  551:    return %titles;
  552: }
  553: 
  554: sub requestauthor_titles {
  555:     my %titles = &Apache::lonlocal::texthash (
  556:                                    norequest  => 'Not allowed',
  557:                                    approval   => 'Approval by Dom. Coord.',
  558:                                    automatic  => 'Automatic approval',
  559:                  );
  560:     return %titles;
  561: 
  562: }
  563: 
  564: sub requestauthor_display {
  565:     my %titles = &Apache::lonlocal::texthash (
  566:                                    approval   => 'Yes, need approval',
  567:                                    automatic  => 'Yes, automatic approval',
  568:                                    norequest  => 'No',
  569:    );
  570:    return %titles;
  571: }
  572: 
  573: sub requestchange_display {
  574:     my %titles = &Apache::lonlocal::texthash (
  575:                                    approval   => "availability set to 'on' (approval required)", 
  576:                                    automatic  => "availability set to 'on' (automatic approval)",
  577:                                    norequest  => "availability set to 'off'",
  578:    );
  579:    return %titles;
  580: }
  581: 
  582: sub curr_requestauthor {
  583:     my ($uname,$udom,$isadv,$inststatuses,$domconfig) = @_;
  584:     return unless ((ref($inststatuses) eq 'ARRAY') && (ref($domconfig) eq 'HASH'));
  585:     if ($uname eq '' || $udom eq '') {
  586:         $uname = $env{'user.name'};
  587:         $udom = $env{'user.domain'};
  588:         $isadv = $env{'user.adv'};
  589:     }
  590:     my (%userenv,%settings,$val);
  591:     my @options = ('automatic','approval');
  592:     %userenv =
  593:         &Apache::lonnet::userenvironment($udom,$uname,'requestauthor','inststatus');
  594:     if ($userenv{'requestauthor'}) {
  595:         $val = $userenv{'requestauthor'};
  596:         @{$inststatuses} = ('_custom_');
  597:     } else {
  598:         my %alltasks;
  599:         if (ref($domconfig->{'requestauthor'}) eq 'HASH') {
  600:             %settings = %{$domconfig->{'requestauthor'}};
  601:             if (($isadv) && ($settings{'_LC_adv'} ne '')) {
  602:                 $val = $settings{'_LC_adv'};
  603:                 @{$inststatuses} = ('_LC_adv_');
  604:             } else {
  605:                 if ($userenv{'inststatus'} ne '') {
  606:                     @{$inststatuses} = split(',',$userenv{'inststatus'});
  607:                 } else {
  608:                     @{$inststatuses} = ('default');
  609:                 }
  610:                 foreach my $status (@{$inststatuses}) {
  611:                     if (exists($settings{$status})) {
  612:                         my $value = $settings{$status};
  613:                         next unless ($value);
  614:                         unless (exists($alltasks{$value})) {
  615:                             if (ref($alltasks{$value}) eq 'ARRAY') {
  616:                                 unless(grep(/^\Q$status\E$/,@{$alltasks{$value}})) {
  617:                                     push(@{$alltasks{$value}},$status);
  618:                                 }
  619:                             } else {
  620:                                 @{$alltasks{$value}} = ($status);
  621:                             }
  622:                         }
  623:                     }
  624:                 }
  625:                 foreach my $option (@options) {
  626:                     if ($alltasks{$option}) {
  627:                         $val = $option;
  628:                         last;
  629:                     }
  630:                 }
  631:             }
  632:         }
  633:     }
  634:     return $val;
  635: }
  636: 
  637: # =================================================================== Phase one
  638: 
  639: sub print_username_entry_form {
  640:     my ($r,$context,$response,$srch,$forcenewuser,$crstype,$brcrum) = @_;
  641:     my $defdom=$env{'request.role.domain'};
  642:     my $formtoset = 'crtuser';
  643:     if (exists($env{'form.startrolename'})) {
  644:         $formtoset = 'docustom';
  645:         $env{'form.rolename'} = $env{'form.startrolename'};
  646:     } elsif ($env{'form.origform'} eq 'crtusername') {
  647:         $formtoset =  $env{'form.origform'};
  648:     }
  649: 
  650:     my ($jsback,$elements) = &crumb_utilities();
  651: 
  652:     my $jscript = &Apache::loncommon::studentbrowser_javascript()."\n".
  653:         '<script type="text/javascript">'."\n".
  654:         '// <![CDATA['."\n".
  655:         &Apache::lonhtmlcommon::set_form_elements($elements->{$formtoset})."\n".
  656:         '// ]]>'."\n".
  657:         '</script>'."\n";
  658: 
  659:     my %existingroles=&Apache::lonuserutils::my_custom_roles($crstype);
  660:     if (($env{'form.action'} eq 'custom') && (keys(%existingroles) > 0)
  661:         && (&Apache::lonnet::allowed('mcr','/'))) {
  662:         $jscript .= &customrole_javascript();
  663:     }
  664:     my $helpitem = 'Course_Change_Privileges';
  665:     if ($env{'form.action'} eq 'custom') {
  666:         $helpitem = 'Course_Editing_Custom_Roles';
  667:     } elsif ($env{'form.action'} eq 'singlestudent') {
  668:         $helpitem = 'Course_Add_Student';
  669:     }
  670:     my %breadcrumb_text = &singleuser_breadcrumb($crstype);
  671:     if ($env{'form.action'} eq 'custom') {
  672:         push(@{$brcrum},
  673:                  {href=>"javascript:backPage(document.crtuser)",       
  674:                   text=>"Pick custom role",
  675:                   help => $helpitem,}
  676:                  );
  677:     } else {
  678:         push (@{$brcrum},
  679:                   {href => "javascript:backPage(document.crtuser)",
  680:                    text => $breadcrumb_text{'search'},
  681:                    help => $helpitem,
  682:                    faq  => 282,
  683:                    bug  => 'Instructor Interface',}
  684:                   );
  685:     }
  686:     my %loaditems = (
  687:                 'onload' => "javascript:setFormElements(document.$formtoset)",
  688:                     );
  689:     my $args = {bread_crumbs           => $brcrum,
  690:                 bread_crumbs_component => 'User Management',
  691:                 add_entries            => \%loaditems,};
  692:     $r->print(&Apache::loncommon::start_page('User Management',$jscript,$args));
  693: 
  694:     my %lt=&Apache::lonlocal::texthash(
  695:                     'srst' => 'Search for a user and enroll as a student',
  696:                     'srme' => 'Search for a user and enroll as a member',
  697:                     'srad' => 'Search for a user and modify/add user information or roles',
  698: 		    'usr'  => "Username",
  699:                     'dom'  => "Domain",
  700:                     'ecrp' => "Define or Edit Custom Role",
  701:                     'nr'   => "role name",
  702:                     'cre'  => "Next",
  703: 				       );
  704: 
  705:     if ($env{'form.action'} eq 'custom') {
  706:         if (&Apache::lonnet::allowed('mcr','/')) {
  707:             my $newroletext = &mt('Define new custom role:');
  708:             $r->print('<form action="/adm/createuser" method="post" name="docustom">'.
  709:                       '<input type="hidden" name="action" value="'.$env{'form.action'}.'" />'.
  710:                       '<input type="hidden" name="phase" value="selected_custom_edit" />'.
  711:                       '<h3>'.$lt{'ecrp'}.'</h3>'.
  712:                       &Apache::loncommon::start_data_table().
  713:                       &Apache::loncommon::start_data_table_row().
  714:                       '<td>');
  715:             if (keys(%existingroles) > 0) {
  716:                 $r->print('<br /><label><input type="radio" name="customroleaction" value="new" checked="checked" onclick="setCustomFields();" /><b>'.$newroletext.'</b></label>');
  717:             } else {
  718:                 $r->print('<br /><input type="hidden" name="customroleaction" value="new" /><b>'.$newroletext.'</b>');
  719:             }
  720:             $r->print('</td><td align="center">'.$lt{'nr'}.'<br /><input type="text" size="15" name="newrolename" onfocus="setCustomAction('."'new'".');" /></td>'.
  721:                       &Apache::loncommon::end_data_table_row());
  722:             if (keys(%existingroles) > 0) {
  723:                 $r->print(&Apache::loncommon::start_data_table_row().'<td><br />'.
  724:                           '<label><input type="radio" name="customroleaction" value="edit" onclick="setCustomFields();"/><b>'.
  725:                           &mt('View/Modify existing role:').'</b></label></td>'.
  726:                           '<td align="center"><br />'.
  727:                           '<select name="rolename" onchange="setCustomAction('."'edit'".');">'.
  728:                           '<option value="" selected="selected">'.
  729:                           &mt('Select'));
  730:                 foreach my $role (sort(keys(%existingroles))) {
  731:                     $r->print('<option value="'.$role.'">'.$role.'</option>');
  732:                 }
  733:                 $r->print('</select>'.
  734:                           '</td>'.
  735:                           &Apache::loncommon::end_data_table_row());
  736:             }
  737:             $r->print(&Apache::loncommon::end_data_table().'<p>'.
  738:                       '<input name="customeditor" type="submit" value="'.
  739:                       $lt{'cre'}.'" /></p>'.
  740:                       '</form>');
  741:         }
  742:     } else {
  743:         my $actiontext = $lt{'srad'};
  744:         if ($env{'form.action'} eq 'singlestudent') {
  745:             if ($crstype eq 'Community') {
  746:                 $actiontext = $lt{'srme'};
  747:             } else {
  748:                 $actiontext = $lt{'srst'};
  749:             }
  750:         }
  751:         $r->print("<h3>$actiontext</h3>");
  752:         if ($env{'form.origform'} ne 'crtusername') {
  753:             $r->print("\n".$response);
  754:         }
  755:         $r->print(&entry_form($defdom,$srch,$forcenewuser,$context,$response,$crstype));
  756:     }
  757: }
  758: 
  759: sub customrole_javascript {
  760:     my $js = <<"END";
  761: <script type="text/javascript">
  762: // <![CDATA[
  763: 
  764: function setCustomFields() {
  765:     if (document.docustom.customroleaction.length > 0) {
  766:         for (var i=0; i<document.docustom.customroleaction.length; i++) {
  767:             if (document.docustom.customroleaction[i].checked) {
  768:                 if (document.docustom.customroleaction[i].value == 'new') {
  769:                     document.docustom.rolename.selectedIndex = 0;
  770:                 } else {
  771:                     document.docustom.newrolename.value = '';
  772:                 }
  773:             }
  774:         }
  775:     }
  776:     return;
  777: }
  778: 
  779: function setCustomAction(caller) {
  780:     if (document.docustom.customroleaction.length > 0) {
  781:         for (var i=0; i<document.docustom.customroleaction.length; i++) {
  782:             if (document.docustom.customroleaction[i].value == caller) {
  783:                 document.docustom.customroleaction[i].checked = true;
  784:             }
  785:         }
  786:     }
  787:     setCustomFields();
  788:     return;
  789: }
  790: 
  791: // ]]>
  792: </script>
  793: END
  794:     return $js;
  795: }
  796: 
  797: sub entry_form {
  798:     my ($dom,$srch,$forcenewuser,$context,$responsemsg,$crstype) = @_;
  799:     my ($usertype,$inexact);
  800:     if (ref($srch) eq 'HASH') {
  801:         if (($srch->{'srchin'} eq 'dom') &&
  802:             ($srch->{'srchby'} eq 'uname') &&
  803:             ($srch->{'srchtype'} eq 'exact') &&
  804:             ($srch->{'srchdomain'} ne '') &&
  805:             ($srch->{'srchterm'} ne '')) {
  806:             my (%curr_rules,%got_rules);
  807:             my ($rules,$ruleorder) =
  808:                 &Apache::lonnet::inst_userrules($srch->{'srchdomain'},'username');
  809:             $usertype = &Apache::lonuserutils::check_usertype($srch->{'srchdomain'},$srch->{'srchterm'},$rules,\%curr_rules,\%got_rules);
  810:         } else {
  811:             $inexact = 1;
  812:         }
  813:     }
  814:     my $cancreate =
  815:         &Apache::lonuserutils::can_create_user($dom,$context,$usertype);
  816:     my $userpicker = 
  817:        &Apache::loncommon::user_picker($dom,$srch,$forcenewuser,
  818:                                        'document.crtuser',$cancreate,$usertype);
  819:     my $srchbutton = &mt('Search');
  820:     if ($env{'form.action'} eq 'singlestudent') {
  821:         $srchbutton = &mt('Search and Enroll');
  822:     } elsif ($cancreate && $responsemsg ne '' && $inexact) {
  823:         $srchbutton = &mt('Search or Add New User');
  824:     }
  825:     my $output = <<"ENDBLOCK";
  826: <form action="/adm/createuser" method="post" name="crtuser">
  827: <input type="hidden" name="action" value="$env{'form.action'}" />
  828: <input type="hidden" name="phase" value="get_user_info" />
  829: $userpicker
  830: <input name="userrole" type="button" value="$srchbutton" onclick="javascript:validateEntry(document.crtuser)" />
  831: </form>
  832: ENDBLOCK
  833:     if ($env{'form.phase'} eq '') {
  834:         my $defdom=$env{'request.role.domain'};
  835:         my $domform = &Apache::loncommon::select_dom_form($defdom,'srchdomain');
  836:         my %lt=&Apache::lonlocal::texthash(
  837:                   'enro' => 'Enroll one student',
  838:                   'enrm' => 'Enroll one member',
  839:                   'admo' => 'Add/modify a single user',
  840:                   'crea' => 'create new user if required',
  841:                   'uskn' => "username is known",
  842:                   'crnu' => 'Create a new user',
  843:                   'usr'  => 'Username',
  844:                   'dom'  => 'in domain',
  845:                   'enrl' => 'Enroll',
  846:                   'cram'  => 'Create/Modify user',
  847:         );
  848:         my $sellink=&Apache::loncommon::selectstudent_link('crtusername','srchterm','srchdomain');
  849:         my ($title,$buttontext,$showresponse);
  850:         if ($env{'form.action'} eq 'singlestudent') {
  851:             if ($crstype eq 'Community') {
  852:                 $title = $lt{'enrm'};
  853:             } else {
  854:                 $title = $lt{'enro'};
  855:             }
  856:             $buttontext = $lt{'enrl'};
  857:         } else {
  858:             $title = $lt{'admo'};
  859:             $buttontext = $lt{'cram'};
  860:         }
  861:         if ($cancreate) {
  862:             $title .= ' <span class="LC_cusr_subheading">('.$lt{'crea'}.')</span>';
  863:         } else {
  864:             $title .= ' <span class="LC_cusr_subheading">('.$lt{'uskn'}.')</span>';
  865:         }
  866:         if ($env{'form.origform'} eq 'crtusername') {
  867:             $showresponse = $responsemsg;
  868:         }
  869:         $output .= <<"ENDDOCUMENT";
  870: <br />
  871: <form action="/adm/createuser" method="post" name="crtusername">
  872: <input type="hidden" name="action" value="$env{'form.action'}" />
  873: <input type="hidden" name="phase" value="createnewuser" />
  874: <input type="hidden" name="srchtype" value="exact" />
  875: <input type="hidden" name="srchby" value="uname" />
  876: <input type="hidden" name="srchin" value="dom" />
  877: <input type="hidden" name="forcenewuser" value="1" />
  878: <input type="hidden" name="origform" value="crtusername" />
  879: <h3>$title</h3>
  880: $showresponse
  881: <table>
  882:  <tr>
  883:   <td>$lt{'usr'}:</td>
  884:   <td><input type="text" size="15" name="srchterm" /></td>
  885:   <td>&nbsp;$lt{'dom'}:</td><td>$domform</td>
  886:   <td>&nbsp;$sellink&nbsp;</td>
  887:   <td>&nbsp;<input name="userrole" type="submit" value="$buttontext" /></td>
  888:  </tr>
  889: </table>
  890: </form>
  891: ENDDOCUMENT
  892:     }
  893:     return $output;
  894: }
  895: 
  896: sub user_modification_js {
  897:     my ($pjump_def,$dc_setcourse_code,$nondc_setsection_code,$groupslist)=@_;
  898:     
  899:     return <<END;
  900: <script type="text/javascript" language="Javascript">
  901: // <![CDATA[
  902: 
  903:     $pjump_def
  904:     $dc_setcourse_code
  905: 
  906:     function dateset() {
  907:         eval("document.cu."+document.cu.pres_marker.value+
  908:             ".value=document.cu.pres_value.value");
  909:         modalWindow.close();
  910:     }
  911: 
  912:     $nondc_setsection_code
  913: // ]]>
  914: </script>
  915: END
  916: }
  917: 
  918: # =================================================================== Phase two
  919: sub print_user_selection_page {
  920:     my ($r,$response,$srch,$srch_results,$srcharray,$context,$opener_elements,$crstype,$brcrum) = @_;
  921:     my @fields = ('username','domain','lastname','firstname','permanentemail');
  922:     my $sortby = $env{'form.sortby'};
  923: 
  924:     if (!grep(/^\Q$sortby\E$/,@fields)) {
  925:         $sortby = 'lastname';
  926:     }
  927: 
  928:     my ($jsback,$elements) = &crumb_utilities();
  929: 
  930:     my $jscript = (<<ENDSCRIPT);
  931: <script type="text/javascript">
  932: // <![CDATA[
  933: function pickuser(uname,udom) {
  934:     document.usersrchform.seluname.value=uname;
  935:     document.usersrchform.seludom.value=udom;
  936:     document.usersrchform.phase.value="userpicked";
  937:     document.usersrchform.submit();
  938: }
  939: 
  940: $jsback
  941: // ]]>
  942: </script>
  943: ENDSCRIPT
  944: 
  945:     my %lt=&Apache::lonlocal::texthash(
  946:                                        'usrch'          => "User Search to add/modify roles",
  947:                                        'stusrch'        => "User Search to enroll student",
  948:                                        'memsrch'        => "User Search to enroll member",
  949:                                        'usel'           => "Select a user to add/modify roles",
  950:                                        'stusel'         => "Select a user to enroll as a student",
  951:                                        'memsel'         => "Select a user to enroll as a member",
  952:                                        'username'       => "username",
  953:                                        'domain'         => "domain",
  954:                                        'lastname'       => "last name",
  955:                                        'firstname'      => "first name",
  956:                                        'permanentemail' => "permanent e-mail",
  957:                                       );
  958:     if ($context eq 'requestcrs') {
  959:         $r->print('<div>');
  960:     } else {
  961:         my %breadcrumb_text = &singleuser_breadcrumb($crstype);
  962:         my $helpitem;
  963:         if ($env{'form.action'} eq 'singleuser') {
  964:             $helpitem = 'Course_Change_Privileges';
  965:         } elsif ($env{'form.action'} eq 'singlestudent') {
  966:             $helpitem = 'Course_Add_Student';
  967:         }
  968:         push (@{$brcrum},
  969:                   {href => "javascript:backPage(document.usersrchform,'','')",
  970:                    text => $breadcrumb_text{'search'},
  971:                    faq  => 282,
  972:                    bug  => 'Instructor Interface',},
  973:                   {href => "javascript:backPage(document.usersrchform,'get_user_info','select')",
  974:                    text => $breadcrumb_text{'userpicked'},
  975:                    faq  => 282,
  976:                    bug  => 'Instructor Interface',
  977:                    help => $helpitem}
  978:                   );
  979:         $r->print(&Apache::loncommon::start_page('User Management',$jscript,{bread_crumbs => $brcrum}));
  980:         if ($env{'form.action'} eq 'singleuser') {
  981:             $r->print("<b>$lt{'usrch'}</b><br />");
  982:             $r->print(&entry_form($srch->{'srchdomain'},$srch,undef,$context,undef,$crstype));
  983:             $r->print('<h3>'.$lt{'usel'}.'</h3>');
  984:         } elsif ($env{'form.action'} eq 'singlestudent') {
  985:             $r->print($jscript."<b>");
  986:             if ($crstype eq 'Community') {
  987:                 $r->print($lt{'memsrch'});
  988:             } else {
  989:                 $r->print($lt{'stusrch'});
  990:             }
  991:             $r->print("</b><br />");
  992:             $r->print(&entry_form($srch->{'srchdomain'},$srch,undef,$context,undef,$crstype));
  993:             $r->print('</form><h3>');
  994:             if ($crstype eq 'Community') {
  995:                 $r->print($lt{'memsel'});
  996:             } else {
  997:                 $r->print($lt{'stusel'});
  998:             }
  999:             $r->print('</h3>');
 1000:         }
 1001:     }
 1002:     $r->print('<form name="usersrchform" method="post" action="">'.
 1003:               &Apache::loncommon::start_data_table()."\n".
 1004:               &Apache::loncommon::start_data_table_header_row()."\n".
 1005:               ' <th> </th>'."\n");
 1006:     foreach my $field (@fields) {
 1007:         $r->print(' <th><a href="javascript:document.usersrchform.sortby.value='.
 1008:                   "'".$field."'".';document.usersrchform.submit();">'.
 1009:                   $lt{$field}.'</a></th>'."\n");
 1010:     }
 1011:     $r->print(&Apache::loncommon::end_data_table_header_row());
 1012: 
 1013:     my @sorted_users = sort {
 1014:         lc($srch_results->{$a}->{$sortby})   cmp lc($srch_results->{$b}->{$sortby})
 1015:             ||
 1016:         lc($srch_results->{$a}->{lastname})  cmp lc($srch_results->{$b}->{lastname})
 1017:             ||
 1018:         lc($srch_results->{$a}->{firstname}) cmp lc($srch_results->{$b}->{firstname})
 1019: 	    ||
 1020: 	lc($a) cmp lc($b)
 1021:         } (keys(%$srch_results));
 1022: 
 1023:     foreach my $user (@sorted_users) {
 1024:         my ($uname,$udom) = split(/:/,$user);
 1025:         my $onclick;
 1026:         if ($context eq 'requestcrs') {
 1027:             $onclick =
 1028:                 'onclick="javascript:gochoose('."'$uname','$udom',".
 1029:                                                "'$srch_results->{$user}->{firstname}',".
 1030:                                                "'$srch_results->{$user}->{lastname}',".
 1031:                                                "'$srch_results->{$user}->{permanentemail}'".');"';
 1032:         } else {
 1033:             $onclick =
 1034:                 ' onclick="javascript:pickuser('."'".$uname."'".','."'".$udom."'".');"';
 1035:         }
 1036:         $r->print(&Apache::loncommon::start_data_table_row().
 1037:                   '<td><input type="button" name="seluser" value="'.&mt('Select').'" '.
 1038:                   $onclick.' /></td>'.
 1039:                   '<td><tt>'.$uname.'</tt></td>'.
 1040:                   '<td><tt>'.$udom.'</tt></td>');
 1041:         foreach my $field ('lastname','firstname','permanentemail') {
 1042:             $r->print('<td>'.$srch_results->{$user}->{$field}.'</td>');
 1043:         }
 1044:         $r->print(&Apache::loncommon::end_data_table_row());
 1045:     }
 1046:     $r->print(&Apache::loncommon::end_data_table().'<br /><br />');
 1047:     if (ref($srcharray) eq 'ARRAY') {
 1048:         foreach my $item (@{$srcharray}) {
 1049:             $r->print('<input type="hidden" name="'.$item.'" value="'.$env{'form.'.$item}.'" />'."\n");
 1050:         }
 1051:     }
 1052:     $r->print(' <input type="hidden" name="sortby" value="'.$sortby.'" />'."\n".
 1053:               ' <input type="hidden" name="seluname" value="" />'."\n".
 1054:               ' <input type="hidden" name="seludom" value="" />'."\n".
 1055:               ' <input type="hidden" name="currstate" value="select" />'."\n".
 1056:               ' <input type="hidden" name="phase" value="get_user_info" />'."\n".
 1057:               ' <input type="hidden" name="action" value="'.$env{'form.action'}.'" />'."\n");
 1058:     if ($context eq 'requestcrs') {
 1059:         $r->print($opener_elements.'</form></div>');
 1060:     } else {
 1061:         $r->print($response.'</form>');
 1062:     }
 1063: }
 1064: 
 1065: sub print_user_query_page {
 1066:     my ($r,$caller,$brcrum) = @_;
 1067: # FIXME - this is for a network-wide name search (similar to catalog search)
 1068: # To use frames with similar behavior to catalog/portfolio search.
 1069: # To be implemented. 
 1070:     return;
 1071: }
 1072: 
 1073: sub print_user_modification_page {
 1074:     my ($r,$ccuname,$ccdomain,$srch,$response,$context,$permission,$crstype,
 1075:         $brcrum,$showcredits) = @_;
 1076:     if (($ccuname eq '') || ($ccdomain eq '')) {
 1077:         my $usermsg = &mt('No username and/or domain provided.');
 1078:         $env{'form.phase'} = '';
 1079: 	&print_username_entry_form($r,$context,$usermsg,'','',$crstype,$brcrum);
 1080:         return;
 1081:     }
 1082:     my ($form,$formname);
 1083:     if ($env{'form.action'} eq 'singlestudent') {
 1084:         $form = 'document.enrollstudent';
 1085:         $formname = 'enrollstudent';
 1086:     } else {
 1087:         $form = 'document.cu';
 1088:         $formname = 'cu';
 1089:     }
 1090:     my %abv_auth = &auth_abbrev();
 1091:     my (%rulematch,%inst_results,$newuser,%alerts,%curr_rules,%got_rules);
 1092:     my $uhome=&Apache::lonnet::homeserver($ccuname,$ccdomain);
 1093:     if ($uhome eq 'no_host') {
 1094:         my $usertype;
 1095:         my ($rules,$ruleorder) =
 1096:             &Apache::lonnet::inst_userrules($ccdomain,'username');
 1097:             $usertype =
 1098:                 &Apache::lonuserutils::check_usertype($ccdomain,$ccuname,$rules,
 1099:                                                       \%curr_rules,\%got_rules);
 1100:         my $cancreate =
 1101:             &Apache::lonuserutils::can_create_user($ccdomain,$context,
 1102:                                                    $usertype);
 1103:         if (!$cancreate) {
 1104:             my $helplink = 'javascript:helpMenu('."'display'".')';
 1105:             my %usertypetext = (
 1106:                 official   => 'institutional',
 1107:                 unofficial => 'non-institutional',
 1108:             );
 1109:             my $response;
 1110:             if ($env{'form.origform'} eq 'crtusername') {
 1111:                 $response = '<span class="LC_warning">'.
 1112:                             &mt('No match found for the username [_1] in LON-CAPA domain: [_2]',
 1113:                                 '<b>'.$ccuname.'</b>',$ccdomain).
 1114:                             '</span><br />';
 1115:             }
 1116:             $response .= '<p class="LC_warning">'
 1117:                         .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
 1118:                         .' '
 1119:                         .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
 1120:                             ,'<a href="'.$helplink.'">','</a>')
 1121:                         .'</p><br />';
 1122:             $env{'form.phase'} = '';
 1123:             &print_username_entry_form($r,$context,$response,undef,undef,$crstype,$brcrum);
 1124:             return;
 1125:         }
 1126:         $newuser = 1;
 1127:         my $checkhash;
 1128:         my $checks = { 'username' => 1 };
 1129:         $checkhash->{$ccuname.':'.$ccdomain} = { 'newuser' => $newuser };
 1130:         &Apache::loncommon::user_rule_check($checkhash,$checks,
 1131:             \%alerts,\%rulematch,\%inst_results,\%curr_rules,\%got_rules);
 1132:         if (ref($alerts{'username'}) eq 'HASH') {
 1133:             if (ref($alerts{'username'}{$ccdomain}) eq 'HASH') {
 1134:                 my $domdesc =
 1135:                     &Apache::lonnet::domain($ccdomain,'description');
 1136:                 if ($alerts{'username'}{$ccdomain}{$ccuname}) {
 1137:                     my $userchkmsg;
 1138:                     if (ref($curr_rules{$ccdomain}) eq 'HASH') {  
 1139:                         $userchkmsg = 
 1140:                             &Apache::loncommon::instrule_disallow_msg('username',
 1141:                                                                  $domdesc,1).
 1142:                         &Apache::loncommon::user_rule_formats($ccdomain,
 1143:                             $domdesc,$curr_rules{$ccdomain}{'username'},
 1144:                             'username');
 1145:                     }
 1146:                     $env{'form.phase'} = '';
 1147:                     &print_username_entry_form($r,$context,$userchkmsg,undef,undef,$crstype,$brcrum);
 1148:                     return;
 1149:                 }
 1150:             }
 1151:         }
 1152:     } else {
 1153:         $newuser = 0;
 1154:     }
 1155:     if ($response) {
 1156:         $response = '<br />'.$response;
 1157:     }
 1158: 
 1159:     my $pjump_def = &Apache::lonhtmlcommon::pjump_javascript_definition();
 1160:     my $dc_setcourse_code = '';
 1161:     my $nondc_setsection_code = '';                                        
 1162:     my %loaditem;
 1163: 
 1164:     my $groupslist = &Apache::lonuserutils::get_groupslist();
 1165: 
 1166:     my $js = &validation_javascript($context,$ccdomain,$pjump_def,$crstype,
 1167:                                $groupslist,$newuser,$formname,\%loaditem);
 1168:     my %breadcrumb_text = &singleuser_breadcrumb($crstype);
 1169:     my $helpitem = 'Course_Change_Privileges';
 1170:     if ($env{'form.action'} eq 'singlestudent') {
 1171:         $helpitem = 'Course_Add_Student';
 1172:     }
 1173:     push (@{$brcrum},
 1174:         {href => "javascript:backPage($form)",
 1175:          text => $breadcrumb_text{'search'},
 1176:          faq  => 282,
 1177:          bug  => 'Instructor Interface',});
 1178:     if ($env{'form.phase'} eq 'userpicked') {
 1179:        push(@{$brcrum},
 1180:               {href => "javascript:backPage($form,'get_user_info','select')",
 1181:                text => $breadcrumb_text{'userpicked'},
 1182:                faq  => 282,
 1183:                bug  => 'Instructor Interface',});
 1184:     }
 1185:     push(@{$brcrum},
 1186:             {href => "javascript:backPage($form,'$env{'form.phase'}','modify')",
 1187:              text => $breadcrumb_text{'modify'},
 1188:              faq  => 282,
 1189:              bug  => 'Instructor Interface',
 1190:              help => $helpitem});
 1191:     my $args = {'add_entries'           => \%loaditem,
 1192:                 'bread_crumbs'          => $brcrum,
 1193:                 'bread_crumbs_component' => 'User Management'};
 1194:     if ($env{'form.popup'}) {
 1195:         $args->{'no_nav_bar'} = 1;
 1196:     }
 1197:     my $start_page =
 1198:         &Apache::loncommon::start_page('User Management',$js,$args);
 1199: 
 1200:     my $forminfo =<<"ENDFORMINFO";
 1201: <form action="/adm/createuser" method="post" name="$formname">
 1202: <input type="hidden" name="phase" value="update_user_data" />
 1203: <input type="hidden" name="ccuname" value="$ccuname" />
 1204: <input type="hidden" name="ccdomain" value="$ccdomain" />
 1205: <input type="hidden" name="pres_value"  value="" />
 1206: <input type="hidden" name="pres_type"   value="" />
 1207: <input type="hidden" name="pres_marker" value="" />
 1208: ENDFORMINFO
 1209:     my (%inccourses,$roledom,$defaultcredits);
 1210:     if ($context eq 'course') {
 1211:         $inccourses{$env{'request.course.id'}}=1;
 1212:         $roledom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 1213:         if ($showcredits) {
 1214:             $defaultcredits = &Apache::lonuserutils::get_defaultcredits();
 1215:         }
 1216:     } elsif ($context eq 'author') {
 1217:         $roledom = $env{'request.role.domain'};
 1218:     } elsif ($context eq 'domain') {
 1219:         foreach my $key (keys(%env)) {
 1220:             $roledom = $env{'request.role.domain'};
 1221:             if ($key=~/^user\.priv\.cm\.\/($roledom)\/($match_username)/) {
 1222:                 $inccourses{$1.'_'.$2}=1;
 1223:             }
 1224:         }
 1225:     } else {
 1226:         foreach my $key (keys(%env)) {
 1227: 	    if ($key=~/^user\.priv\.cm\.\/($match_domain)\/($match_username)/) {
 1228: 	        $inccourses{$1.'_'.$2}=1;
 1229:             }
 1230:         }
 1231:     }
 1232:     my $title = '';
 1233:     if ($newuser) {
 1234:         my ($portfolioform,$domroleform);
 1235:         if ((&Apache::lonnet::allowed('mpq',$env{'request.role.domain'})) ||
 1236:             (&Apache::lonnet::allowed('mut',$env{'request.role.domain'}))) {
 1237:             # Current user has quota or user tools modification privileges
 1238:             $portfolioform = '<br />'.&user_quotas($ccuname,$ccdomain);
 1239:         }
 1240:         if ((&Apache::lonnet::allowed('cau',$env{'request.role.domain'})) &&
 1241:             ($ccdomain eq $env{'request.role.domain'})) {
 1242:             $domroleform = '<br />'.&domainrole_req($ccuname,$ccdomain);
 1243:         }
 1244:         &initialize_authen_forms($ccdomain,$formname);
 1245:         my %lt=&Apache::lonlocal::texthash(
 1246:                 'lg'             => 'Login Data',
 1247:                 'hs'             => "Home Server",
 1248:         );
 1249: 	$r->print(<<ENDTITLE);
 1250: $start_page
 1251: $response
 1252: $forminfo
 1253: <script type="text/javascript" language="Javascript">
 1254: // <![CDATA[
 1255: $loginscript
 1256: // ]]>
 1257: </script>
 1258: <input type='hidden' name='makeuser' value='1' />
 1259: ENDTITLE
 1260:         if ($env{'form.action'} eq 'singlestudent') {
 1261:             if ($crstype eq 'Community') {
 1262:                 $title = &mt('Create New User [_1] in domain [_2] as a member',
 1263:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1264:             } else {
 1265:                 $title = &mt('Create New User [_1] in domain [_2] as a student',
 1266:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1267:             }
 1268:         } else {
 1269:                 $title = &mt('Create New User [_1] in domain [_2]',
 1270:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1271:         }
 1272:         $r->print('<h2>'.$title.'</h2>'."\n");
 1273:         $r->print('<div class="LC_left_float">');
 1274:         my $personal_table = 
 1275:             &personal_data_display($ccuname,$ccdomain,$newuser,$context,
 1276:                                    $inst_results{$ccuname.':'.$ccdomain});
 1277:         # (Do not offer Disable Safeguard here)
 1278:         $r->print($personal_table);
 1279:         my ($home_server_pick,$numlib) = 
 1280:             &Apache::loncommon::home_server_form_item($ccdomain,'hserver',
 1281:                                                       'default','hide');
 1282:         if ($numlib > 1) {
 1283:             $r->print("
 1284: <br />
 1285: $lt{'hs'}: $home_server_pick
 1286: <br />");
 1287:         } else {
 1288:             $r->print($home_server_pick);
 1289:         }
 1290:         if (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) {
 1291:             $r->print('<br /><h3>'.
 1292:                       &mt('User Can Request Creation of Courses/Communities in this Domain?').'</h3>'.
 1293:                       &Apache::loncommon::start_data_table().
 1294:                       &build_tools_display($ccuname,$ccdomain,
 1295:                                            'requestcourses').
 1296:                       &Apache::loncommon::end_data_table());
 1297:         }
 1298:         $r->print('</div>'."\n".'<div class="LC_left_float"><h3>'.
 1299:                   $lt{'lg'}.'</h3>');
 1300:         my ($fixedauth,$varauth,$authmsg); 
 1301:         if (ref($rulematch{$ccuname.':'.$ccdomain}) eq 'HASH') {
 1302:             my $matchedrule = $rulematch{$ccuname.':'.$ccdomain}{'username'};
 1303:             my ($rules,$ruleorder) = 
 1304:                 &Apache::lonnet::inst_userrules($ccdomain,'username');
 1305:             if (ref($rules) eq 'HASH') {
 1306:                 if (ref($rules->{$matchedrule}) eq 'HASH') {
 1307:                     my $authtype = $rules->{$matchedrule}{'authtype'};
 1308:                     if ($authtype !~ /^(krb4|krb5|int|fsys|loc)$/) {
 1309:                         $r->print(&Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc));
 1310:                     } else { 
 1311:                         my $authparm = $rules->{$matchedrule}{'authparm'};
 1312:                         $authmsg = $rules->{$matchedrule}{'authmsg'};
 1313:                         if ($authtype =~ /^krb(4|5)$/) {
 1314:                             my $ver = $1;
 1315:                             if ($authparm ne '') {
 1316:                                 $fixedauth = <<"KERB"; 
 1317: <input type="hidden" name="login" value="krb" />
 1318: <input type="hidden" name="krbver" value="$ver" />
 1319: <input type="hidden" name="krbarg" value="$authparm" />
 1320: KERB
 1321:                             }
 1322:                         } else {
 1323:                             $fixedauth = 
 1324: '<input type="hidden" name="login" value="'.$authtype.'" />'."\n";
 1325:                             if ($rules->{$matchedrule}{'authparmfixed'}) {
 1326:                                 $fixedauth .=    
 1327: '<input type="hidden" name="'.$authtype.'arg" value="'.$authparm.'" />'."\n";
 1328:                             } else {
 1329:                                 if ($authtype eq 'int') {
 1330:                                     $varauth = '<br />'.
 1331: &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>';
 1332:                                 } elsif ($authtype eq 'loc') {
 1333:                                     $varauth = '<br />'.
 1334: &mt('[_1] Local Authentication with argument [_2]','','<input type="text" name="'.$authtype.'arg" value="" />')."\n";
 1335:                                 } else {
 1336:                                     $varauth =
 1337: '<input type="text" name="'.$authtype.'arg" value="" />'."\n";
 1338:                                 }
 1339:                             }
 1340:                         }
 1341:                     }
 1342:                 } else {
 1343:                     $r->print(&Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc));
 1344:                 }
 1345:             }
 1346:             if ($authmsg) {
 1347:                 $r->print(<<ENDAUTH);
 1348: $fixedauth
 1349: $authmsg
 1350: $varauth
 1351: ENDAUTH
 1352:             }
 1353:         } else {
 1354:             $r->print(&Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc)); 
 1355:         }
 1356:         $r->print($portfolioform.$domroleform);
 1357:         if ($env{'form.action'} eq 'singlestudent') {
 1358:             $r->print(&date_sections_select($context,$newuser,$formname,
 1359:                                             $permission,$crstype,$ccuname,
 1360:                                             $ccdomain,$showcredits));
 1361:         }
 1362:         $r->print('</div><div class="LC_clear_float_footer"></div>');
 1363:     } else { # user already exists
 1364: 	$r->print($start_page.$forminfo);
 1365:         if ($env{'form.action'} eq 'singlestudent') {
 1366:             if ($crstype eq 'Community') {
 1367:                 $title = &mt('Enroll one member: [_1] in domain [_2]',
 1368:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1369:             } else {
 1370:                 $title = &mt('Enroll one student: [_1] in domain [_2]',
 1371:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1372:             }
 1373:         } else {
 1374:             $title = &mt('Modify existing user: [_1] in domain [_2]',
 1375:                              '"'.$ccuname.'"','"'.$ccdomain.'"');
 1376:         }
 1377:         $r->print('<h2>'.$title.'</h2>'."\n");
 1378:         $r->print('<div class="LC_left_float">');
 1379:         my $personal_table = 
 1380:             &personal_data_display($ccuname,$ccdomain,$newuser,$context,
 1381:                                    $inst_results{$ccuname.':'.$ccdomain});
 1382:         $r->print($personal_table);
 1383:         if (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) {
 1384:             $r->print('<br /><h3>'.&mt('User Can Request Creation of Courses/Communities in this Domain?').'</h3>'.
 1385:                       &Apache::loncommon::start_data_table());
 1386:             if ($env{'request.role.domain'} eq $ccdomain) {
 1387:                 $r->print(&build_tools_display($ccuname,$ccdomain,'requestcourses'));
 1388:             } else {
 1389:                 $r->print(&coursereq_externaluser($ccuname,$ccdomain,
 1390:                                                   $env{'request.role.domain'}));
 1391:             }
 1392:             $r->print(&Apache::loncommon::end_data_table());
 1393:         }
 1394:         $r->print('</div>');
 1395:         my @order = ('auth','quota','tools','requestauthor');
 1396:         my %user_text;
 1397:         my ($isadv,$isauthor) = 
 1398:             &Apache::lonnet::is_advanced_user($ccuname,$ccdomain);
 1399:         if ((!$isauthor) && 
 1400:             (&Apache::lonnet::allowed('cau',$env{'request.role.domain'}))
 1401:             && ($env{'request.role.domain'} eq $ccdomain)) {
 1402:             $user_text{'requestauthor'} = &domainrole_req($ccuname,$ccdomain);
 1403:         }
 1404:         $user_text{'auth'} =  &user_authentication($ccuname,$ccdomain,$formname);
 1405:         if ((&Apache::lonnet::allowed('mpq',$ccdomain)) ||
 1406:             (&Apache::lonnet::allowed('mut',$ccdomain))) {
 1407:             # Current user has quota modification privileges
 1408:             $user_text{'quota'} = &user_quotas($ccuname,$ccdomain);
 1409:         }
 1410:         if (!&Apache::lonnet::allowed('mpq',$ccdomain)) {
 1411:             if (&Apache::lonnet::allowed('mpq',$env{'request.role.domain'})) {
 1412:                 my %lt=&Apache::lonlocal::texthash(
 1413:                     'dska'  => "Disk quotas for user's portfolio and Authoring Space",
 1414:                     'youd'  => "You do not have privileges to modify the portfolio and/or Authoring Space quotas for this user.",
 1415:                     'ichr'  => "If a change is required, contact a domain coordinator for the domain",
 1416:                 );
 1417:                 $user_text{'quota'} = <<ENDNOPORTPRIV;
 1418: <h3>$lt{'dska'}</h3>
 1419: $lt{'youd'} $lt{'ichr'}: $ccdomain
 1420: ENDNOPORTPRIV
 1421:             }
 1422:         }
 1423:         if (!&Apache::lonnet::allowed('mut',$ccdomain)) {
 1424:             if (&Apache::lonnet::allowed('mut',$env{'request.role.domain'})) {
 1425:                 my %lt=&Apache::lonlocal::texthash(
 1426:                     'utav'  => "User Tools Availability",
 1427:                     'yodo'  => "You do not have privileges to modify Portfolio, Blog, WebDAV, or Personal Information Page settings for this user.",
 1428:                     'ifch'  => "If a change is required, contact a domain coordinator for the domain",
 1429:                 );
 1430:                 $user_text{'tools'} = <<ENDNOTOOLSPRIV;
 1431: <h3>$lt{'utav'}</h3>
 1432: $lt{'yodo'} $lt{'ifch'}: $ccdomain
 1433: ENDNOTOOLSPRIV
 1434:             }
 1435:         }
 1436:         my $gotdiv = 0; 
 1437:         foreach my $item (@order) {
 1438:             if ($user_text{$item} ne '') {
 1439:                 unless ($gotdiv) {
 1440:                     $r->print('<div class="LC_left_float">');
 1441:                     $gotdiv = 1;
 1442:                 }
 1443:                 $r->print('<br />'.$user_text{$item});
 1444:             }
 1445:         }
 1446:         if ($env{'form.action'} eq 'singlestudent') {
 1447:             unless ($gotdiv) {
 1448:                 $r->print('<div class="LC_left_float">');
 1449:             }
 1450:             my $credits;
 1451:             if ($showcredits) {
 1452:                 $credits = &get_user_credits($ccuname,$ccdomain,$defaultcredits);
 1453:                 if ($credits eq '') {
 1454:                     $credits = $defaultcredits;
 1455:                 }
 1456:             }
 1457:             $r->print(&date_sections_select($context,$newuser,$formname,
 1458:                                             $permission,$crstype,$ccuname,
 1459:                                             $ccdomain,$showcredits));
 1460:         }
 1461:         if ($gotdiv) {
 1462:             $r->print('</div><div class="LC_clear_float_footer"></div>');
 1463:         }
 1464:         if ($env{'form.action'} ne 'singlestudent') {
 1465:             &display_existing_roles($r,$ccuname,$ccdomain,\%inccourses,$context,
 1466:                                     $roledom,$crstype);
 1467:         }
 1468:     } ## End of new user/old user logic
 1469:     if ($env{'form.action'} eq 'singlestudent') {
 1470:         my $btntxt;
 1471:         if ($crstype eq 'Community') {
 1472:             $btntxt = &mt('Enroll Member');
 1473:         } else {
 1474:             $btntxt = &mt('Enroll Student');
 1475:         }
 1476:         $r->print('<br /><input type="button" value="'.$btntxt.'" onclick="setSections(this.form)" />'."\n");
 1477:     } else {
 1478:         $r->print('<fieldset><legend>'.&mt('Add Roles').'</legend>');
 1479:         my $addrolesdisplay = 0;
 1480:         if ($context eq 'domain' || $context eq 'author') {
 1481:             $addrolesdisplay = &new_coauthor_roles($r,$ccuname,$ccdomain);
 1482:         }
 1483:         if ($context eq 'domain') {
 1484:             my $add_domainroles = &new_domain_roles($r,$ccdomain);
 1485:             if (!$addrolesdisplay) {
 1486:                 $addrolesdisplay = $add_domainroles;
 1487:             }
 1488:             $r->print(&course_level_dc($env{'request.role.domain'},$showcredits));
 1489:             $r->print('</fieldset><br /><input type="button" value="'.&mt('Save').'" onclick="setCourse()" />'."\n");
 1490:         } elsif ($context eq 'author') {
 1491:             if ($addrolesdisplay) {
 1492:                 $r->print('</fieldset><br /><input type="button" value="'.&mt('Save').'"');
 1493:                 if ($newuser) {
 1494:                     $r->print(' onclick="auth_check()" \>'."\n");
 1495:                 } else {
 1496:                     $r->print('onclick="this.form.submit()" \>'."\n");
 1497:                 }
 1498:             } else {
 1499:                 $r->print('</fieldset><br /><a href="javascript:backPage(document.cu)">'.
 1500:                           &mt('Back to previous page').'</a>');
 1501:             }
 1502:         } else {
 1503:             $r->print(&course_level_table(\%inccourses,$showcredits,$defaultcredits));
 1504:             $r->print('</fieldset><br /><input type="button" value="'.&mt('Save').'" onclick="setSections(this.form)" />'."\n");
 1505:         }
 1506:     }
 1507:     $r->print(&Apache::lonhtmlcommon::echo_form_input(['phase','userrole','ccdomain','prevphase','currstate','ccuname','ccdomain']));
 1508:     $r->print('<input type="hidden" name="currstate" value="" />');
 1509:     $r->print('<input type="hidden" name="prevphase" value="'.$env{'form.phase'}.'" /></form>');
 1510:     return;
 1511: }
 1512: 
 1513: sub singleuser_breadcrumb {
 1514:     my ($crstype) = @_;
 1515:     my %breadcrumb_text;
 1516:     if ($env{'form.action'} eq 'singlestudent') {
 1517:         if ($crstype eq 'Community') {
 1518:             $breadcrumb_text{'search'} = 'Enroll a member';
 1519:         } else {
 1520:             $breadcrumb_text{'search'} = 'Enroll a student';
 1521:         }
 1522:         $breadcrumb_text{'userpicked'} = 'Select a user',
 1523:         $breadcrumb_text{'modify'} = 'Set section/dates',
 1524:     } else {
 1525:         $breadcrumb_text{'search'} = 'Create/modify a user';
 1526:         $breadcrumb_text{'userpicked'} = 'Select a user',
 1527:         $breadcrumb_text{'modify'} = 'Set user role',
 1528:     }
 1529:     return %breadcrumb_text;
 1530: }
 1531: 
 1532: sub date_sections_select {
 1533:     my ($context,$newuser,$formname,$permission,$crstype,$ccuname,$ccdomain,
 1534:         $showcredits) = @_;
 1535:     my $credits;
 1536:     if ($showcredits) {
 1537:         my $defaultcredits = &Apache::lonuserutils::get_defaultcredits();
 1538:         $credits = &get_user_credits($ccuname,$ccdomain,$defaultcredits);
 1539:         if ($credits eq '') {
 1540:             $credits = $defaultcredits;
 1541:         }
 1542:     }
 1543:     my $cid = $env{'request.course.id'};
 1544:     my ($cnum,$cdom) = &Apache::lonuserutils::get_course_identity($cid);
 1545:     my $date_table = '<h3>'.&mt('Starting and Ending Dates').'</h3>'."\n".
 1546:         &Apache::lonuserutils::date_setting_table(undef,undef,$context,
 1547:                                                   undef,$formname,$permission);
 1548:     my $rowtitle = 'Section';
 1549:     my $secbox = '<h3>'.&mt('Section and Credits').'</h3>'."\n".
 1550:         &Apache::lonuserutils::section_picker($cdom,$cnum,'st',$rowtitle,
 1551:                                               $permission,$context,'',$crstype,
 1552:                                               $showcredits,$credits);
 1553:     my $output = $date_table.$secbox;
 1554:     return $output;
 1555: }
 1556: 
 1557: sub validation_javascript {
 1558:     my ($context,$ccdomain,$pjump_def,$crstype,$groupslist,$newuser,$formname,
 1559:         $loaditem) = @_;
 1560:     my $dc_setcourse_code = '';
 1561:     my $nondc_setsection_code = '';
 1562:     if ($context eq 'domain') {
 1563:         my $dcdom = $env{'request.role.domain'};
 1564:         $loaditem->{'onload'} = "document.cu.coursedesc.value='';";
 1565:         $dc_setcourse_code = 
 1566:             &Apache::lonuserutils::dc_setcourse_js('cu','singleuser',$context);
 1567:     } else {
 1568:         my $checkauth; 
 1569:         if (($newuser) || (&Apache::lonnet::allowed('mau',$ccdomain))) {
 1570:             $checkauth = 1;
 1571:         }
 1572:         if ($context eq 'course') {
 1573:             $nondc_setsection_code =
 1574:                 &Apache::lonuserutils::setsections_javascript($formname,$groupslist,
 1575:                                                               undef,$checkauth,
 1576:                                                               $crstype);
 1577:         }
 1578:         if ($checkauth) {
 1579:             $nondc_setsection_code .= 
 1580:                 &Apache::lonuserutils::verify_authen($formname,$context);
 1581:         }
 1582:     }
 1583:     my $js = &user_modification_js($pjump_def,$dc_setcourse_code,
 1584:                                    $nondc_setsection_code,$groupslist);
 1585:     my ($jsback,$elements) = &crumb_utilities();
 1586:     $js .= "\n".
 1587:            '<script type="text/javascript">'."\n".
 1588:            '// <![CDATA['."\n".
 1589:            $jsback."\n".
 1590:            '// ]]>'."\n".
 1591:            '</script>'."\n";
 1592:     return $js;
 1593: }
 1594: 
 1595: sub display_existing_roles {
 1596:     my ($r,$ccuname,$ccdomain,$inccourses,$context,$roledom,$crstype,
 1597:         $showcredits) = @_;
 1598:     my $now=time;
 1599:     my %lt=&Apache::lonlocal::texthash(
 1600:                     'rer'  => "Existing Roles",
 1601:                     'rev'  => "Revoke",
 1602:                     'del'  => "Delete",
 1603:                     'ren'  => "Re-Enable",
 1604:                     'rol'  => "Role",
 1605:                     'ext'  => "Extent",
 1606:                     'crd'  => "Credits",
 1607:                     'sta'  => "Start",
 1608:                     'end'  => "End",
 1609:                                        );
 1610:     my (%rolesdump,%roletext,%sortrole,%roleclass,%rolepriv);
 1611:     if ($context eq 'course' || $context eq 'author') {
 1612:         my @roles = &Apache::lonuserutils::roles_by_context($context,1,$crstype);
 1613:         my %roleshash = 
 1614:             &Apache::lonnet::get_my_roles($ccuname,$ccdomain,'userroles',
 1615:                               ['active','previous','future'],\@roles,$roledom,1);
 1616:         foreach my $key (keys(%roleshash)) {
 1617:             my ($start,$end) = split(':',$roleshash{$key});
 1618:             next if ($start eq '-1' || $end eq '-1');
 1619:             my ($rnum,$rdom,$role,$sec) = split(':',$key);
 1620:             if ($context eq 'course') {
 1621:                 next unless (($rnum eq $env{'course.'.$env{'request.course.id'}.'.num'})
 1622:                              && ($rdom eq $env{'course.'.$env{'request.course.id'}.'.domain'}));
 1623:             } elsif ($context eq 'author') {
 1624:                 next unless (($rnum eq $env{'user.name'}) && ($rdom eq $env{'request.role.domain'}));
 1625:             }
 1626:             my ($newkey,$newvalue,$newrole);
 1627:             $newkey = '/'.$rdom.'/'.$rnum;
 1628:             if ($sec ne '') {
 1629:                 $newkey .= '/'.$sec;
 1630:             }
 1631:             $newvalue = $role;
 1632:             if ($role =~ /^cr/) {
 1633:                 $newrole = 'cr';
 1634:             } else {
 1635:                 $newrole = $role;
 1636:             }
 1637:             $newkey .= '_'.$newrole;
 1638:             if ($start ne '' && $end ne '') {
 1639:                 $newvalue .= '_'.$end.'_'.$start;
 1640:             } elsif ($end ne '') {
 1641:                 $newvalue .= '_'.$end;
 1642:             }
 1643:             $rolesdump{$newkey} = $newvalue;
 1644:         }
 1645:     } else {
 1646:         %rolesdump=&Apache::lonnet::dump('roles',$ccdomain,$ccuname);
 1647:     }
 1648:     # Build up table of user roles to allow revocation and re-enabling of roles.
 1649:     my ($tmp) = keys(%rolesdump);
 1650:     return if ($tmp =~ /^(con_lost|error)/i);
 1651:     foreach my $area (sort { my $a1=join('_',(split('_',$a))[1,0]);
 1652:                                 my $b1=join('_',(split('_',$b))[1,0]);
 1653:                                 return $a1 cmp $b1;
 1654:                             } keys(%rolesdump)) {
 1655:         next if ($area =~ /^rolesdef/);
 1656:         my $envkey=$area;
 1657:         my $role = $rolesdump{$area};
 1658:         my $thisrole=$area;
 1659:         $area =~ s/\_\w\w$//;
 1660:         my ($role_code,$role_end_time,$role_start_time) =
 1661:             split(/_/,$role);
 1662: # Is this a custom role? Get role owner and title.
 1663:         my ($croleudom,$croleuname,$croletitle)=
 1664:             ($role_code=~m{^cr/($match_domain)/($match_username)/(\w+)$});
 1665:         my $allowed=0;
 1666:         my $delallowed=0;
 1667:         my $sortkey=$role_code;
 1668:         my $class='Unknown';
 1669:         my $credits='';
 1670:         if ($area =~ m{^/($match_domain)/($match_courseid)} ) {
 1671:             $class='Course';
 1672:             my ($coursedom,$coursedir) = ($1,$2);
 1673:             my $cid = $1.'_'.$2;
 1674:             # $1.'_'.$2 is the course id (eg. 103_12345abcef103l3).
 1675:             my %coursedata=
 1676:                 &Apache::lonnet::coursedescription($cid);
 1677:             if ($coursedir =~ /^$match_community$/) {
 1678:                 $class='Community';
 1679:             }
 1680:             $sortkey.="\0$coursedom";
 1681:             my $carea;
 1682:             if (defined($coursedata{'description'})) {
 1683:                 $carea=$coursedata{'description'}.
 1684:                     '<br />'.&mt('Domain').': '.$coursedom.('&nbsp;'x8).
 1685:     &Apache::loncommon::syllabuswrapper(&mt('Syllabus'),$coursedir,$coursedom);
 1686:                 $sortkey.="\0".$coursedata{'description'};
 1687:             } else {
 1688:                 if ($class eq 'Community') {
 1689:                     $carea=&mt('Unavailable community').': '.$area;
 1690:                     $sortkey.="\0".&mt('Unavailable community').': '.$area;
 1691:                 } else {
 1692:                     $carea=&mt('Unavailable course').': '.$area;
 1693:                     $sortkey.="\0".&mt('Unavailable course').': '.$area;
 1694:                 }
 1695:             }
 1696:             $sortkey.="\0$coursedir";
 1697:             $inccourses->{$cid}=1;
 1698:             if (($showcredits) && ($class eq 'Course') && ($role_code eq 'st')) {
 1699:                 my $defaultcredits = $coursedata{'internal.defaultcredits'};
 1700:                 $credits =
 1701:                     &get_user_credits($ccuname,$ccdomain,$defaultcredits,
 1702:                                       $coursedom,$coursedir);
 1703:                 if ($credits eq '') {
 1704:                     $credits = $defaultcredits;
 1705:                 }
 1706:             }
 1707:             if ((&Apache::lonnet::allowed('c'.$role_code,$coursedom.'/'.$coursedir)) ||
 1708:                 (&Apache::lonnet::allowed('c'.$role_code,$ccdomain))) {
 1709:                 $allowed=1;
 1710:             }
 1711:             unless ($allowed) {
 1712:                 my $isowner = &Apache::lonuserutils::is_courseowner($cid,$coursedata{'internal.courseowner'});
 1713:                 if ($isowner) {
 1714:                     if (($role_code eq 'co') && ($class eq 'Community')) {
 1715:                         $allowed = 1;
 1716:                     } elsif (($role_code eq 'cc') && ($class eq 'Course')) {
 1717:                         $allowed = 1;
 1718:                     }
 1719:                 }
 1720:             } 
 1721:             if ((&Apache::lonnet::allowed('dro',$coursedom)) ||
 1722:                 (&Apache::lonnet::allowed('dro',$ccdomain))) {
 1723:                 $delallowed=1;
 1724:             }
 1725: # - custom role. Needs more info, too
 1726:             if ($croletitle) {
 1727:                 if (&Apache::lonnet::allowed('ccr',$coursedom.'/'.$coursedir)) {
 1728:                     $allowed=1;
 1729:                     $thisrole.='.'.$role_code;
 1730:                 }
 1731:             }
 1732:             if ($area=~m{^/($match_domain)/($match_courseid)/(\w+)}) {
 1733:                 $carea.='<br />'.&mt('Section: [_1]',$3);
 1734:                 $sortkey.="\0$3";
 1735:                 if (!$allowed) {
 1736:                     if ($env{'request.course.sec'} eq $3) {
 1737:                         if (&Apache::lonnet::allowed('c'.$role_code,$1.'/'.$2.'/'.$3)) {
 1738:                             $allowed = 1;
 1739:                         }
 1740:                     }
 1741:                 }
 1742:             }
 1743:             $area=$carea;
 1744:         } else {
 1745:             $sortkey.="\0".$area;
 1746:             # Determine if current user is able to revoke privileges
 1747:             if ($area=~m{^/($match_domain)/}) {
 1748:                 if ((&Apache::lonnet::allowed('c'.$role_code,$1)) ||
 1749:                    (&Apache::lonnet::allowed('c'.$role_code,$ccdomain))) {
 1750:                    $allowed=1;
 1751:                 }
 1752:                 if (((&Apache::lonnet::allowed('dro',$1))  ||
 1753:                     (&Apache::lonnet::allowed('dro',$ccdomain))) &&
 1754:                     ($role_code ne 'dc')) {
 1755:                     $delallowed=1;
 1756:                 }
 1757:             } else {
 1758:                 if (&Apache::lonnet::allowed('c'.$role_code,'/')) {
 1759:                     $allowed=1;
 1760:                 }
 1761:             }
 1762:             if ($role_code eq 'ca' || $role_code eq 'au' || $role_code eq 'aa') {
 1763:                 $class='Authoring Space';
 1764:             } elsif ($role_code eq 'su') {
 1765:                 $class='System';
 1766:             } else {
 1767:                 $class='Domain';
 1768:             }
 1769:         }
 1770:         if (($role_code eq 'ca') || ($role_code eq 'aa')) {
 1771:             $area=~m{/($match_domain)/($match_username)};
 1772:             if (&Apache::lonuserutils::authorpriv($2,$1)) {
 1773:                 $allowed=1;
 1774:             } else {
 1775:                 $allowed=0;
 1776:             }
 1777:         }
 1778:         my $row = '';
 1779:         $row.= '<td>';
 1780:         my $active=1;
 1781:         $active=0 if (($role_end_time) && ($now>$role_end_time));
 1782:         if (($active) && ($allowed)) {
 1783:             $row.= '<input type="checkbox" name="rev:'.$thisrole.'" />';
 1784:         } else {
 1785:             if ($active) {
 1786:                $row.='&nbsp;';
 1787:             } else {
 1788:                $row.=&mt('expired or revoked');
 1789:             }
 1790:         }
 1791:         $row.='</td><td>';
 1792:         if ($allowed && !$active) {
 1793:             $row.= '<input type="checkbox" name="ren:'.$thisrole.'" />';
 1794:         } else {
 1795:             $row.='&nbsp;';
 1796:         }
 1797:         $row.='</td><td>';
 1798:         if ($delallowed) {
 1799:             $row.= '<input type="checkbox" name="del:'.$thisrole.'" />';
 1800:         } else {
 1801:             $row.='&nbsp;';
 1802:         }
 1803:         my $plaintext='';
 1804:         if (!$croletitle) {
 1805:             $plaintext=&Apache::lonnet::plaintext($role_code,$class);
 1806:             if (($showcredits) && ($credits ne '')) {
 1807:                 $plaintext .= '<br/ ><span class="LC_nobreak">'.
 1808:                               '<span class="LC_fontsize_small">'.
 1809:                               &mt('Credits: [_1]',$credits).
 1810:                               '</span></span>';
 1811:             }
 1812:         } else {
 1813:             $plaintext=
 1814:                 &mt('Customrole [_1][_2]defined by [_3]',
 1815:                         '"'.$croletitle.'"',
 1816:                         '<br />',
 1817:                         $croleuname.':'.$croleudom);
 1818:         }
 1819:         $row.= '</td><td>'.$plaintext.
 1820:                '</td><td>'.$area.
 1821:                '</td><td>'.($role_start_time?&Apache::lonlocal::locallocaltime($role_start_time)
 1822:                                             : '&nbsp;' ).
 1823:                '</td><td>'.($role_end_time  ?&Apache::lonlocal::locallocaltime($role_end_time)
 1824:                                             : '&nbsp;' )
 1825:                ."</td>";
 1826:         $sortrole{$sortkey}=$envkey;
 1827:         $roletext{$envkey}=$row;
 1828:         $roleclass{$envkey}=$class;
 1829:         $rolepriv{$envkey}=$allowed;
 1830:     } # end of foreach        (table building loop)
 1831: 
 1832:     my $rolesdisplay = 0;
 1833:     my %output = ();
 1834:     foreach my $type ('Authoring Space','Course','Community','Domain','System','Unknown') {
 1835:         $output{$type} = '';
 1836:         foreach my $which (sort {uc($a) cmp uc($b)} (keys(%sortrole))) {
 1837:             if ( ($roleclass{$sortrole{$which}} =~ /^\Q$type\E/ ) && ($rolepriv{$sortrole{$which}}) ) {
 1838:                  $output{$type}.=
 1839:                       &Apache::loncommon::start_data_table_row().
 1840:                       $roletext{$sortrole{$which}}.
 1841:                       &Apache::loncommon::end_data_table_row();
 1842:             }
 1843:         }
 1844:         unless($output{$type} eq '') {
 1845:             $output{$type} = '<tr class="LC_info_row">'.
 1846:                       "<td align='center' colspan='7'>".&mt($type)."</td></tr>".
 1847:                       $output{$type};
 1848:             $rolesdisplay = 1;
 1849:         }
 1850:     }
 1851:     if ($rolesdisplay == 1) {
 1852:         my $contextrole='';
 1853:         if ($env{'request.course.id'}) {
 1854:             if (&Apache::loncommon::course_type() eq 'Community') {
 1855:                 $contextrole = &mt('Existing Roles in this Community');
 1856:             } else {
 1857:                 $contextrole = &mt('Existing Roles in this Course');
 1858:             }
 1859:         } elsif ($env{'request.role'} =~ /^au\./) {
 1860:             $contextrole = &mt('Existing Co-Author Roles in your Authoring Space');
 1861:         } else {
 1862:             $contextrole = &mt('Existing Roles in this Domain');
 1863:         }
 1864:         $r->print('<div>'.
 1865: '<fieldset><legend>'.$contextrole.'</legend>'.
 1866: &Apache::loncommon::start_data_table("LC_createuser").
 1867: &Apache::loncommon::start_data_table_header_row().
 1868: '<th>'.$lt{'rev'}.'</th><th>'.$lt{'ren'}.'</th><th>'.$lt{'del'}.
 1869: '</th><th>'.$lt{'rol'}.'</th><th>'.$lt{'ext'}.
 1870: '</th><th>'.$lt{'sta'}.'</th><th>'.$lt{'end'}.'</th>'.
 1871: &Apache::loncommon::end_data_table_header_row());
 1872:         foreach my $type ('Authoring Space','Course','Community','Domain','System','Unknown') {
 1873:             if ($output{$type}) {
 1874:                 $r->print($output{$type}."\n");
 1875:             }
 1876:         }
 1877:         $r->print(&Apache::loncommon::end_data_table().
 1878:                   '</fieldset></div>');
 1879:     }
 1880:     return;
 1881: }
 1882: 
 1883: sub new_coauthor_roles {
 1884:     my ($r,$ccuname,$ccdomain) = @_;
 1885:     my $addrolesdisplay = 0;
 1886:     #
 1887:     # Co-Author
 1888:     #
 1889:     if (&Apache::lonuserutils::authorpriv($env{'user.name'},
 1890:                                           $env{'request.role.domain'}) &&
 1891:         ($env{'user.name'} ne $ccuname || $env{'user.domain'} ne $ccdomain)) {
 1892:         # No sense in assigning co-author role to yourself
 1893:         $addrolesdisplay = 1;
 1894:         my $cuname=$env{'user.name'};
 1895:         my $cudom=$env{'request.role.domain'};
 1896:         my %lt=&Apache::lonlocal::texthash(
 1897:                     'cs'   => "Authoring Space",
 1898:                     'act'  => "Activate",
 1899:                     'rol'  => "Role",
 1900:                     'ext'  => "Extent",
 1901:                     'sta'  => "Start",
 1902:                     'end'  => "End",
 1903:                     'cau'  => "Co-Author",
 1904:                     'caa'  => "Assistant Co-Author",
 1905:                     'ssd'  => "Set Start Date",
 1906:                     'sed'  => "Set End Date"
 1907:                                        );
 1908:         $r->print('<h4>'.$lt{'cs'}.'</h4>'."\n".
 1909:                   &Apache::loncommon::start_data_table()."\n".
 1910:                   &Apache::loncommon::start_data_table_header_row()."\n".
 1911:                   '<th>'.$lt{'act'}.'</th><th>'.$lt{'rol'}.'</th>'.
 1912:                   '<th>'.$lt{'ext'}.'</th><th>'.$lt{'sta'}.'</th>'.
 1913:                   '<th>'.$lt{'end'}.'</th>'."\n".
 1914:                   &Apache::loncommon::end_data_table_header_row()."\n".
 1915:                   &Apache::loncommon::start_data_table_row().'
 1916:            <td>
 1917:             <input type="checkbox" name="act_'.$cudom.'_'.$cuname.'_ca" />
 1918:            </td>
 1919:            <td>'.$lt{'cau'}.'</td>
 1920:            <td>'.$cudom.'_'.$cuname.'</td>
 1921:            <td><input type="hidden" name="start_'.$cudom.'_'.$cuname.'_ca" value="" />
 1922:              <a href=
 1923: "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>
 1924: <td><input type="hidden" name="end_'.$cudom.'_'.$cuname.'_ca" value="" />
 1925: <a href=
 1926: "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".
 1927:               &Apache::loncommon::end_data_table_row()."\n".
 1928:               &Apache::loncommon::start_data_table_row()."\n".
 1929: '<td><input type="checkbox" name="act_'.$cudom.'_'.$cuname.'_aa" /></td>
 1930: <td>'.$lt{'caa'}.'</td>
 1931: <td>'.$cudom.'_'.$cuname.'</td>
 1932: <td><input type="hidden" name="start_'.$cudom.'_'.$cuname.'_aa" value="" />
 1933: <a href=
 1934: "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>
 1935: <td><input type="hidden" name="end_'.$cudom.'_'.$cuname.'_aa" value="" />
 1936: <a href=
 1937: "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".
 1938:              &Apache::loncommon::end_data_table_row()."\n".
 1939:              &Apache::loncommon::end_data_table());
 1940:     } elsif ($env{'request.role'} =~ /^au\./) {
 1941:         if (!(&Apache::lonuserutils::authorpriv($env{'user.name'},
 1942:                                                 $env{'request.role.domain'}))) {
 1943:             $r->print('<span class="LC_error">'.
 1944:                       &mt('You do not have privileges to assign co-author roles.').
 1945:                       '</span>');
 1946:         } elsif (($env{'user.name'} eq $ccuname) &&
 1947:              ($env{'user.domain'} eq $ccdomain)) {
 1948:             $r->print(&mt('Assigning yourself a co-author or assistant co-author role in your own author area in Authoring Space is not permitted'));
 1949:         }
 1950:     }
 1951:     return $addrolesdisplay;;
 1952: }
 1953: 
 1954: sub new_domain_roles {
 1955:     my ($r,$ccdomain) = @_;
 1956:     my $addrolesdisplay = 0;
 1957:     #
 1958:     # Domain level
 1959:     #
 1960:     my $num_domain_level = 0;
 1961:     my $domaintext =
 1962:     '<h4>'.&mt('Domain Level').'</h4>'.
 1963:     &Apache::loncommon::start_data_table().
 1964:     &Apache::loncommon::start_data_table_header_row().
 1965:     '<th>'.&mt('Activate').'</th><th>'.&mt('Role').'</th><th>'.
 1966:     &mt('Extent').'</th>'.
 1967:     '<th>'.&mt('Start').'</th><th>'.&mt('End').'</th>'.
 1968:     &Apache::loncommon::end_data_table_header_row();
 1969:     my @allroles = &Apache::lonuserutils::roles_by_context('domain');
 1970:     foreach my $thisdomain (sort(&Apache::lonnet::all_domains())) {
 1971:         foreach my $role (@allroles) {
 1972:             next if ($role eq 'ad');
 1973:             next if (($role eq 'au') && ($ccdomain ne $thisdomain));
 1974:             if (&Apache::lonnet::allowed('c'.$role,$thisdomain)) {
 1975:                my $plrole=&Apache::lonnet::plaintext($role);
 1976:                my %lt=&Apache::lonlocal::texthash(
 1977:                     'ssd'  => "Set Start Date",
 1978:                     'sed'  => "Set End Date"
 1979:                                        );
 1980:                $num_domain_level ++;
 1981:                $domaintext .=
 1982: &Apache::loncommon::start_data_table_row().
 1983: '<td><input type="checkbox" name="act_'.$thisdomain.'_'.$role.'" /></td>
 1984: <td>'.$plrole.'</td>
 1985: <td>'.$thisdomain.'</td>
 1986: <td><input type="hidden" name="start_'.$thisdomain.'_'.$role.'" value="" />
 1987: <a href=
 1988: "javascript:pjump('."'date_start','Start Date $plrole',document.cu.start_$thisdomain\_$role.value,'start_$thisdomain\_$role','cu.pres','dateset'".')">'.$lt{'ssd'}.'</a></td>
 1989: <td><input type="hidden" name="end_'.$thisdomain.'_'.$role.'" value="" />
 1990: <a href=
 1991: "javascript:pjump('."'date_end','End Date $plrole',document.cu.end_$thisdomain\_$role.value,'end_$thisdomain\_$role','cu.pres','dateset'".')">'.$lt{'sed'}.'</a></td>'.
 1992: &Apache::loncommon::end_data_table_row();
 1993:             }
 1994:         }
 1995:     }
 1996:     $domaintext.= &Apache::loncommon::end_data_table();
 1997:     if ($num_domain_level > 0) {
 1998:         $r->print($domaintext);
 1999:         $addrolesdisplay = 1;
 2000:     }
 2001:     return $addrolesdisplay;
 2002: }
 2003: 
 2004: sub user_authentication {
 2005:     my ($ccuname,$ccdomain,$formname) = @_;
 2006:     my $currentauth=&Apache::lonnet::queryauthenticate($ccuname,$ccdomain);
 2007:     my $outcome;
 2008:     # Check for a bad authentication type
 2009:     if ($currentauth !~ /^(krb4|krb5|unix|internal|localauth):/) {
 2010:         # bad authentication scheme
 2011:         my %lt=&Apache::lonlocal::texthash(
 2012:                        'err'   => "ERROR",
 2013:                        'uuas'  => "This user has an unrecognized authentication scheme",
 2014:                        'adcs'  => "Please alert a domain coordinator of this situation",
 2015:                        'sldb'  => "Please specify login data below",
 2016:                        'ld'    => "Login Data"
 2017:         );
 2018:         if (&Apache::lonnet::allowed('mau',$ccdomain)) {
 2019:             &initialize_authen_forms($ccdomain,$formname);
 2020: 
 2021:             my $choices = &Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc);
 2022:             $outcome = <<ENDBADAUTH;
 2023: <script type="text/javascript" language="Javascript">
 2024: // <![CDATA[
 2025: $loginscript
 2026: // ]]>
 2027: </script>
 2028: <span class="LC_error">$lt{'err'}:
 2029: $lt{'uuas'} ($currentauth). $lt{'sldb'}.</span>
 2030: <h3>$lt{'ld'}</h3>
 2031: $choices
 2032: ENDBADAUTH
 2033:         } else {
 2034:             # This user is not allowed to modify the user's
 2035:             # authentication scheme, so just notify them of the problem
 2036:             $outcome = <<ENDBADAUTH;
 2037: <span class="LC_error"> $lt{'err'}: 
 2038: $lt{'uuas'} ($currentauth). $lt{'adcs'}.
 2039: </span>
 2040: ENDBADAUTH
 2041:         }
 2042:     } else { # Authentication type is valid
 2043:         &initialize_authen_forms($ccdomain,$formname,$currentauth,'modifyuser');
 2044:         my ($authformcurrent,$can_modify,@authform_others) =
 2045:             &modify_login_block($ccdomain,$currentauth);
 2046:         if (&Apache::lonnet::allowed('mau',$ccdomain)) {
 2047:             # Current user has login modification privileges
 2048:             my %lt=&Apache::lonlocal::texthash (
 2049:                            'ld'    => "Login Data",
 2050:                            'ccld'  => "Change Current Login Data",
 2051:                            'enld'  => "Enter New Login Data"
 2052:                                                );
 2053:             $outcome =
 2054:                        '<script type="text/javascript" language="Javascript">'."\n".
 2055:                        '// <![CDATA['."\n".
 2056:                        $loginscript."\n".
 2057:                        '// ]]>'."\n".
 2058:                        '</script>'."\n".
 2059:                        '<h3>'.$lt{'ld'}.'</h3>'.
 2060:                        &Apache::loncommon::start_data_table().
 2061:                        &Apache::loncommon::start_data_table_row().
 2062:                        '<td>'.$authformnop;
 2063:             if ($can_modify) {
 2064:                 $outcome .= '</td>'."\n".
 2065:                             &Apache::loncommon::end_data_table_row().
 2066:                             &Apache::loncommon::start_data_table_row().
 2067:                             '<td>'.$authformcurrent.'</td>'.
 2068:                             &Apache::loncommon::end_data_table_row()."\n";
 2069:             } else {
 2070:                 $outcome .= '&nbsp;('.$authformcurrent.')</td>'.
 2071:                             &Apache::loncommon::end_data_table_row()."\n";
 2072:             }
 2073:             foreach my $item (@authform_others) { 
 2074:                 $outcome .= &Apache::loncommon::start_data_table_row().
 2075:                             '<td>'.$item.'</td>'.
 2076:                             &Apache::loncommon::end_data_table_row()."\n";
 2077:             }
 2078:             $outcome .= &Apache::loncommon::end_data_table();
 2079:         } else {
 2080:             if (&Apache::lonnet::allowed('mau',$env{'request.role.domain'})) {
 2081:                 my %lt=&Apache::lonlocal::texthash(
 2082:                            'ccld'  => "Change Current Login Data",
 2083:                            'yodo'  => "You do not have privileges to modify the authentication configuration for this user.",
 2084:                            'ifch'  => "If a change is required, contact a domain coordinator for the domain",
 2085:                 );
 2086:                 $outcome .= <<ENDNOPRIV;
 2087: <h3>$lt{'ccld'}</h3>
 2088: $lt{'yodo'} $lt{'ifch'}: $ccdomain
 2089: <input type="hidden" name="login" value="nochange" />
 2090: ENDNOPRIV
 2091:             }
 2092:         }
 2093:     }  ## End of "check for bad authentication type" logic
 2094:     return $outcome;
 2095: }
 2096: 
 2097: sub modify_login_block {
 2098:     my ($dom,$currentauth) = @_;
 2099:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 2100:     my ($authnum,%can_assign) =
 2101:         &Apache::loncommon::get_assignable_auth($dom);
 2102:     my ($authformcurrent,@authform_others,$show_override_msg);
 2103:     if ($currentauth=~/^krb(4|5):/) {
 2104:         $authformcurrent=$authformkrb;
 2105:         if ($can_assign{'int'}) {
 2106:             push(@authform_others,$authformint);
 2107:         }
 2108:         if ($can_assign{'loc'}) {
 2109:             push(@authform_others,$authformloc);
 2110:         }
 2111:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2112:             $show_override_msg = 1;
 2113:         }
 2114:     } elsif ($currentauth=~/^internal:/) {
 2115:         $authformcurrent=$authformint;
 2116:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2117:             push(@authform_others,$authformkrb);
 2118:         }
 2119:         if ($can_assign{'loc'}) {
 2120:             push(@authform_others,$authformloc);
 2121:         }
 2122:         if ($can_assign{'int'}) {
 2123:             $show_override_msg = 1;
 2124:         }
 2125:     } elsif ($currentauth=~/^unix:/) {
 2126:         $authformcurrent=$authformfsys;
 2127:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2128:             push(@authform_others,$authformkrb);
 2129:         }
 2130:         if ($can_assign{'int'}) {
 2131:             push(@authform_others,$authformint);
 2132:         }
 2133:         if ($can_assign{'loc'}) {
 2134:             push(@authform_others,$authformloc);
 2135:         }
 2136:         if ($can_assign{'fsys'}) {
 2137:             $show_override_msg = 1;
 2138:         }
 2139:     } elsif ($currentauth=~/^localauth:/) {
 2140:         $authformcurrent=$authformloc;
 2141:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2142:             push(@authform_others,$authformkrb);
 2143:         }
 2144:         if ($can_assign{'int'}) {
 2145:             push(@authform_others,$authformint);
 2146:         }
 2147:         if ($can_assign{'loc'}) {
 2148:             $show_override_msg = 1;
 2149:         }
 2150:     }
 2151:     if ($show_override_msg) {
 2152:         $authformcurrent = '<table><tr><td colspan="3">'.$authformcurrent.
 2153:                            '</td></tr>'."\n".
 2154:                            '<tr><td>&nbsp;&nbsp;&nbsp;</td>'.
 2155:                            '<td><b>'.&mt('Currently in use').'</b></td>'.
 2156:                            '<td align="right"><span class="LC_cusr_emph">'.
 2157:                             &mt('will override current values').
 2158:                             '</span></td></tr></table>';
 2159:     }
 2160:     return ($authformcurrent,$show_override_msg,@authform_others); 
 2161: }
 2162: 
 2163: sub personal_data_display {
 2164:     my ($ccuname,$ccdomain,$newuser,$context,$inst_results,$rolesarray,
 2165:         $now,$captchaform,$emailusername) = @_;
 2166:     my ($output,%userenv,%canmodify,%canmodify_status);
 2167:     my @userinfo = ('firstname','middlename','lastname','generation',
 2168:                     'permanentemail','id');
 2169:     my $rowcount = 0;
 2170:     my $editable = 0;
 2171:     my %textboxsize = (
 2172:                        firstname      => '15',
 2173:                        middlename     => '15',
 2174:                        lastname       => '15',
 2175:                        generation     => '5',
 2176:                        permanentemail => '25',
 2177:                        id             => '15',
 2178:                       );
 2179: 
 2180:     my %lt=&Apache::lonlocal::texthash(
 2181:                 'pd'             => "Personal Data",
 2182:                 'firstname'      => "First Name",
 2183:                 'middlename'     => "Middle Name",
 2184:                 'lastname'       => "Last Name",
 2185:                 'generation'     => "Generation",
 2186:                 'permanentemail' => "Permanent e-mail address",
 2187:                 'id'             => "Student/Employee ID",
 2188:                 'lg'             => "Login Data",
 2189:                 'inststatus'     => "Affiliation",
 2190:                 'email'          => 'E-mail address',
 2191:                 'valid'          => 'Validation',
 2192:     );
 2193: 
 2194:     %canmodify_status =
 2195:         &Apache::lonuserutils::can_modify_userinfo($context,$ccdomain,
 2196:                                                    ['inststatus'],$rolesarray);
 2197:     if (!$newuser) {
 2198:         # Get the users information
 2199:         %userenv = &Apache::lonnet::get('environment',
 2200:                    ['firstname','middlename','lastname','generation',
 2201:                     'permanentemail','id','inststatus'],$ccdomain,$ccuname);
 2202:         %canmodify =
 2203:             &Apache::lonuserutils::can_modify_userinfo($context,$ccdomain,
 2204:                                                        \@userinfo,$rolesarray);
 2205:     } elsif ($context eq 'selfcreate') {
 2206:         if ($newuser eq 'email') {
 2207:             if (ref($emailusername) eq 'HASH') { 
 2208:                 my ($infofields,$infotitles) = &Apache::loncommon::emailusername_info();
 2209:                 @userinfo = ();          
 2210:                 if ((ref($infofields) eq 'ARRAY') && (ref($infotitles) eq 'HASH')) {
 2211:                     foreach my $field (@{$infofields}) { 
 2212:                         if ($emailusername->{$field}) {
 2213:                             push(@userinfo,$field);
 2214:                             $canmodify{$field} = 1;
 2215:                             unless ($textboxsize{$field}) {
 2216:                                 $textboxsize{$field} = 25;
 2217:                             }
 2218:                             unless ($lt{$field}) {
 2219:                                 $lt{$field} = $infotitles->{$field};
 2220:                             }
 2221:                         }
 2222:                     }
 2223:                 }
 2224:             }
 2225:         } else {
 2226:             %canmodify = &selfcreate_canmodify($context,$ccdomain,\@userinfo,
 2227:                                                $inst_results,$rolesarray);
 2228:         }
 2229:     }
 2230: 
 2231:     my $genhelp=&Apache::loncommon::help_open_topic('Generation');
 2232:     $output = '<h3>'.$lt{'pd'}.'</h3>'.
 2233:               &Apache::lonhtmlcommon::start_pick_box();
 2234:     if (($context eq 'selfcreate') && ($newuser eq 'email')) {
 2235:         $output .= &Apache::lonhtmlcommon::row_title($lt{'email'},undef,
 2236:                                                      'LC_oddrow_value')."\n".
 2237:                    '<input type="text" name="uname" size="25" value="" />';
 2238:         $rowcount ++;
 2239:         $output .= &Apache::lonhtmlcommon::row_closure(1);
 2240:         my $upassone = '<input type="password" name="upass'.$now.'" size="10" />';
 2241:         my $upasstwo = '<input type="password" name="upasscheck'.$now.'" size="10" />';
 2242:         $output .= &Apache::lonhtmlcommon::row_title(&mt('Password'),
 2243:                                                     'LC_pick_box_title',
 2244:                                                     'LC_oddrow_value')."\n".
 2245:                    $upassone."\n".
 2246:                    &Apache::lonhtmlcommon::row_closure(1)."\n".
 2247:                    &Apache::lonhtmlcommon::row_title(&mt('Confirm password'),
 2248:                                                      'LC_pick_box_title',
 2249:                                                      'LC_oddrow_value')."\n".
 2250:                    $upasstwo.
 2251:                    &Apache::lonhtmlcommon::row_closure()."\n";
 2252:     }
 2253:     foreach my $item (@userinfo) {
 2254:         my $rowtitle = $lt{$item};
 2255:         my $hiderow = 0;
 2256:         if ($item eq 'generation') {
 2257:             $rowtitle = $genhelp.$rowtitle;
 2258:         }
 2259:         my $row = &Apache::lonhtmlcommon::row_title($rowtitle,undef,'LC_oddrow_value')."\n";
 2260:         if ($newuser) {
 2261:             if (ref($inst_results) eq 'HASH') {
 2262:                 if ($inst_results->{$item} ne '') {
 2263:                     $row .= '<input type="hidden" name="c'.$item.'" value="'.$inst_results->{$item}.'" />'.$inst_results->{$item};
 2264:                 } else {
 2265:                     if ($context eq 'selfcreate') {
 2266:                         if ($canmodify{$item}) {
 2267:                             $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="" />';
 2268:                             $editable ++;
 2269:                         } else {
 2270:                             $hiderow = 1;
 2271:                         }
 2272:                     } else {
 2273:                         $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="" />';
 2274:                     }
 2275:                 }
 2276:             } else {
 2277:                 if ($context eq 'selfcreate') {
 2278:                     if (($item eq 'permanentemail') && ($newuser eq 'email')) {
 2279:                         $row .= $ccuname;
 2280:                     } else {
 2281:                         if ($canmodify{$item}) {
 2282:                             if ($newuser eq 'email') {
 2283:                                 $row .= '<input type="text" name="'.$item.'" size="'.$textboxsize{$item}.'" value="" />';
 2284:                             } else {
 2285:                                 $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="" />';
 2286:                             }
 2287:                             $editable ++;
 2288:                         } else {
 2289:                             $hiderow = 1;
 2290:                         }
 2291:                     }
 2292:                 } else {
 2293:                     $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="" />';
 2294:                 }
 2295:             }
 2296:         } else {
 2297:             if ($canmodify{$item}) {
 2298:                 $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="'.$userenv{$item}.'" />';
 2299:             } else {
 2300:                 $row .= $userenv{$item};
 2301:             }
 2302:             if (($item eq 'id') && ($canmodify{$item})) {
 2303:                  $row .= '<br />'.&Apache::lonuserutils::forceid_change($context);
 2304:             }
 2305:         }
 2306:         $row .= &Apache::lonhtmlcommon::row_closure(1);
 2307:         if (!$hiderow) {
 2308:             $output .= $row;
 2309:             $rowcount ++;
 2310:         }
 2311:     }
 2312:     if (($canmodify_status{'inststatus'}) || ($context ne 'selfcreate')) {
 2313:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($ccdomain);
 2314:         if (ref($types) eq 'ARRAY') {
 2315:             if (@{$types} > 0) {
 2316:                 my ($hiderow,$shown);
 2317:                 if ($canmodify_status{'inststatus'}) {
 2318:                     $shown = &pick_inst_statuses($userenv{'inststatus'},$usertypes,$types);
 2319:                 } else {
 2320:                     if ($userenv{'inststatus'} eq '') {
 2321:                         $hiderow = 1;
 2322:                     } else {
 2323:                         my @showitems;
 2324:                         foreach my $item ( map { &unescape($_); } split(':',$userenv{'inststatus'})) {
 2325:                             if (exists($usertypes->{$item})) {
 2326:                                 push(@showitems,$usertypes->{$item});
 2327:                             } else {
 2328:                                 push(@showitems,$item);
 2329:                             }
 2330:                         }
 2331:                         if (@showitems) {
 2332:                             $shown = join(', ',@showitems);
 2333:                         } else {
 2334:                             $hiderow = 1;
 2335:                         }
 2336:                     }
 2337:                 }
 2338:                 if (!$hiderow) {
 2339:                     my $row = &Apache::lonhtmlcommon::row_title(&mt('Affiliations'),undef,'LC_oddrow_value')."\n".
 2340:                               $shown.&Apache::lonhtmlcommon::row_closure(1); 
 2341:                     if ($context eq 'selfcreate') {
 2342:                         $rowcount ++;
 2343:                     }
 2344:                     $output .= $row;
 2345:                 }
 2346:             }
 2347:         }
 2348:     }
 2349:     if (($context eq 'selfcreate') && ($newuser eq 'email')) {
 2350:         if ($captchaform) {
 2351:             $output .= &Apache::lonhtmlcommon::row_title($lt{'valid'},
 2352:                                                          'LC_pick_box_title')."\n".
 2353:                        $captchaform."\n".'<br /><br />'.
 2354:                        &Apache::lonhtmlcommon::row_closure(1); 
 2355:             $rowcount ++;
 2356:         }
 2357:         my $submit_text = &mt('Create account');
 2358:         $output .= &Apache::lonhtmlcommon::row_title()."\n".
 2359:                    '<br /><input type="submit" name="createaccount" value="'.
 2360:                    $submit_text.'" />'.
 2361:                    &Apache::lonhtmlcommon::row_closure(1);
 2362:     }
 2363:     $output .= &Apache::lonhtmlcommon::end_pick_box();
 2364:     if (wantarray) {
 2365:         if ($context eq 'selfcreate') {
 2366:             return($output,$rowcount,$editable);
 2367:         } else {
 2368:             return $output;
 2369:         }
 2370:     } else {
 2371:         return $output;
 2372:     }
 2373: }
 2374: 
 2375: sub pick_inst_statuses {
 2376:     my ($curr,$usertypes,$types) = @_;
 2377:     my ($output,$rem,@currtypes);
 2378:     if ($curr ne '') {
 2379:         @currtypes = map { &unescape($_); } split(/:/,$curr);
 2380:     }
 2381:     my $numinrow = 2;
 2382:     if (ref($types) eq 'ARRAY') {
 2383:         $output = '<table>';
 2384:         my $lastcolspan; 
 2385:         for (my $i=0; $i<@{$types}; $i++) {
 2386:             if (defined($usertypes->{$types->[$i]})) {
 2387:                 my $rem = $i%($numinrow);
 2388:                 if ($rem == 0) {
 2389:                     if ($i<@{$types}-1) {
 2390:                         if ($i > 0) { 
 2391:                             $output .= '</tr>';
 2392:                         }
 2393:                         $output .= '<tr>';
 2394:                     }
 2395:                 } elsif ($i==@{$types}-1) {
 2396:                     my $colsleft = $numinrow - $rem;
 2397:                     if ($colsleft > 1) {
 2398:                         $lastcolspan = ' colspan="'.$colsleft.'"';
 2399:                     }
 2400:                 }
 2401:                 my $check = ' ';
 2402:                 if (grep(/^\Q$types->[$i]\E$/,@currtypes)) {
 2403:                     $check = ' checked="checked" ';
 2404:                 }
 2405:                 $output .= '<td class="LC_left_item"'.$lastcolspan.'>'.
 2406:                            '<span class="LC_nobreak"><label>'.
 2407:                            '<input type="checkbox" name="inststatus" '.
 2408:                            'value="'.$types->[$i].'"'.$check.'/>'.
 2409:                            $usertypes->{$types->[$i]}.'</label></span></td>';
 2410:             }
 2411:         }
 2412:         $output .= '</tr></table>';
 2413:     }
 2414:     return $output;
 2415: }
 2416: 
 2417: sub selfcreate_canmodify {
 2418:     my ($context,$dom,$userinfo,$inst_results,$rolesarray) = @_;
 2419:     if (ref($inst_results) eq 'HASH') {
 2420:         my @inststatuses = &get_inststatuses($inst_results);
 2421:         if (@inststatuses == 0) {
 2422:             @inststatuses = ('default');
 2423:         }
 2424:         $rolesarray = \@inststatuses;
 2425:     }
 2426:     my %canmodify =
 2427:         &Apache::lonuserutils::can_modify_userinfo($context,$dom,$userinfo,
 2428:                                                    $rolesarray);
 2429:     return %canmodify;
 2430: }
 2431: 
 2432: sub get_inststatuses {
 2433:     my ($insthashref) = @_;
 2434:     my @inststatuses = ();
 2435:     if (ref($insthashref) eq 'HASH') {
 2436:         if (ref($insthashref->{'inststatus'}) eq 'ARRAY') {
 2437:             @inststatuses = @{$insthashref->{'inststatus'}};
 2438:         }
 2439:     }
 2440:     return @inststatuses;
 2441: }
 2442: 
 2443: # ================================================================= Phase Three
 2444: sub update_user_data {
 2445:     my ($r,$context,$crstype,$brcrum,$showcredits) = @_; 
 2446:     my $uhome=&Apache::lonnet::homeserver($env{'form.ccuname'},
 2447:                                           $env{'form.ccdomain'});
 2448:     # Error messages
 2449:     my $error     = '<span class="LC_error">'.&mt('Error').': ';
 2450:     my $end       = '</span><br /><br />';
 2451:     my $rtnlink   = '<a href="javascript:backPage(document.userupdate,'.
 2452:                     "'$env{'form.prevphase'}','modify')".'" />'.
 2453:                     &mt('Return to previous page').'</a>'.
 2454:                     &Apache::loncommon::end_page();
 2455:     my $now = time;
 2456:     my $title;
 2457:     if (exists($env{'form.makeuser'})) {
 2458: 	$title='Set Privileges for New User';
 2459:     } else {
 2460:         $title='Modify User Privileges';
 2461:     }
 2462:     my $newuser = 0;
 2463:     my ($jsback,$elements) = &crumb_utilities();
 2464:     my $jscript = '<script type="text/javascript">'."\n".
 2465:                   '// <![CDATA['."\n".
 2466:                   $jsback."\n".
 2467:                   '// ]]>'."\n".
 2468:                   '</script>'."\n";
 2469:     my %breadcrumb_text = &singleuser_breadcrumb($crstype);
 2470:     push (@{$brcrum},
 2471:              {href => "javascript:backPage(document.userupdate)",
 2472:               text => $breadcrumb_text{'search'},
 2473:               faq  => 282,
 2474:               bug  => 'Instructor Interface',}
 2475:              );
 2476:     if ($env{'form.prevphase'} eq 'userpicked') {
 2477:         push(@{$brcrum},
 2478:                {href => "javascript:backPage(document.userupdate,'get_user_info','select')",
 2479:                 text => $breadcrumb_text{'userpicked'},
 2480:                 faq  => 282,
 2481:                 bug  => 'Instructor Interface',});
 2482:     }
 2483:     my $helpitem = 'Course_Change_Privileges';
 2484:     if ($env{'form.action'} eq 'singlestudent') {
 2485:         $helpitem = 'Course_Add_Student';
 2486:     }
 2487:     push(@{$brcrum}, 
 2488:             {href => "javascript:backPage(document.userupdate,'$env{'form.prevphase'}','modify')",
 2489:              text => $breadcrumb_text{'modify'},
 2490:              faq  => 282,
 2491:              bug  => 'Instructor Interface',},
 2492:             {href => "/adm/createuser",
 2493:              text => "Result",
 2494:              faq  => 282,
 2495:              bug  => 'Instructor Interface',
 2496:              help => $helpitem});
 2497:     my $args = {bread_crumbs          => $brcrum,
 2498:                 bread_crumbs_component => 'User Management'};
 2499:     if ($env{'form.popup'}) {
 2500:         $args->{'no_nav_bar'} = 1;
 2501:     }
 2502:     $r->print(&Apache::loncommon::start_page($title,$jscript,$args));
 2503:     $r->print(&update_result_form($uhome));
 2504:     # Check Inputs
 2505:     if (! $env{'form.ccuname'} ) {
 2506: 	$r->print($error.&mt('No login name specified').'.'.$end.$rtnlink);
 2507: 	return;
 2508:     }
 2509:     if (  $env{'form.ccuname'} ne 
 2510: 	  &LONCAPA::clean_username($env{'form.ccuname'}) ) {
 2511: 	$r->print($error.&mt('Invalid login name.').'  '.
 2512: 		  &mt('Only letters, numbers, periods, dashes, @, and underscores are valid.').
 2513: 		  $end.$rtnlink);
 2514: 	return;
 2515:     }
 2516:     if (! $env{'form.ccdomain'}       ) {
 2517: 	$r->print($error.&mt('No domain specified').'.'.$end.$rtnlink);
 2518: 	return;
 2519:     }
 2520:     if (  $env{'form.ccdomain'} ne
 2521: 	  &LONCAPA::clean_domain($env{'form.ccdomain'}) ) {
 2522: 	$r->print($error.&mt('Invalid domain name.').'  '.
 2523: 		  &mt('Only letters, numbers, periods, dashes, and underscores are valid.').
 2524: 		  $end.$rtnlink);
 2525: 	return;
 2526:     }
 2527:     if ($uhome eq 'no_host') {
 2528:         $newuser = 1;
 2529:     }
 2530:     if (! exists($env{'form.makeuser'})) {
 2531:         # Modifying an existing user, so check the validity of the name
 2532:         if ($uhome eq 'no_host') {
 2533:             $r->print(
 2534:                 $error
 2535:                .'<p class="LC_error">'
 2536:                .&mt('Unable to determine home server for [_1] in domain [_2].',
 2537:                         '"'.$env{'form.ccuname'}.'"','"'.$env{'form.ccdomain'}.'"')
 2538:                .'</p>');
 2539:             return;
 2540:         }
 2541:     }
 2542:     # Determine authentication method and password for the user being modified
 2543:     my $amode='';
 2544:     my $genpwd='';
 2545:     if ($env{'form.login'} eq 'krb') {
 2546: 	$amode='krb';
 2547: 	$amode.=$env{'form.krbver'};
 2548: 	$genpwd=$env{'form.krbarg'};
 2549:     } elsif ($env{'form.login'} eq 'int') {
 2550: 	$amode='internal';
 2551: 	$genpwd=$env{'form.intarg'};
 2552:     } elsif ($env{'form.login'} eq 'fsys') {
 2553: 	$amode='unix';
 2554: 	$genpwd=$env{'form.fsysarg'};
 2555:     } elsif ($env{'form.login'} eq 'loc') {
 2556: 	$amode='localauth';
 2557: 	$genpwd=$env{'form.locarg'};
 2558: 	$genpwd=" " if (!$genpwd);
 2559:     } elsif (($env{'form.login'} eq 'nochange') ||
 2560:              ($env{'form.login'} eq ''        )) { 
 2561:         # There is no need to tell the user we did not change what they
 2562:         # did not ask us to change.
 2563:         # If they are creating a new user but have not specified login
 2564:         # information this will be caught below.
 2565:     } else {
 2566:             $r->print($error.&mt('Invalid login mode or password').$end.$rtnlink);
 2567:             return;
 2568:     }
 2569: 
 2570:     $r->print('<h3>'.&mt('User [_1] in domain [_2]',
 2571:                         $env{'form.ccuname'}.' ('.&Apache::loncommon::plainname($env{'form.ccuname'},
 2572:                         $env{'form.ccdomain'}).')', $env{'form.ccdomain'}).'</h3>');
 2573:     my %prog_state = &Apache::lonhtmlcommon::Create_PrgWin($r,2);
 2574: 
 2575:     my (%alerts,%rulematch,%inst_results,%curr_rules);
 2576:     my @userinfo = ('firstname','middlename','lastname','generation','permanentemail','id');
 2577:     my @usertools = ('aboutme','blog','webdav','portfolio');
 2578:     my @requestcourses = ('official','unofficial','community','textbook');
 2579:     my @requestauthor = ('requestauthor');
 2580:     my ($othertitle,$usertypes,$types) = 
 2581:         &Apache::loncommon::sorted_inst_types($env{'form.ccdomain'});
 2582:     my %canmodify_status =
 2583:         &Apache::lonuserutils::can_modify_userinfo($context,$env{'form.ccdomain'},
 2584:                                                    ['inststatus']);
 2585:     if ($env{'form.makeuser'}) {
 2586: 	$r->print('<h3>'.&mt('Creating new account.').'</h3>');
 2587:         # Check for the authentication mode and password
 2588:         if (! $amode || ! $genpwd) {
 2589: 	    $r->print($error.&mt('Invalid login mode or password').$end.$rtnlink);    
 2590: 	    return;
 2591: 	}
 2592:         # Determine desired host
 2593:         my $desiredhost = $env{'form.hserver'};
 2594:         if (lc($desiredhost) eq 'default') {
 2595:             $desiredhost = undef;
 2596:         } else {
 2597:             my %home_servers = 
 2598: 		&Apache::lonnet::get_servers($env{'form.ccdomain'},'library');
 2599:             if (! exists($home_servers{$desiredhost})) {
 2600:                 $r->print($error.&mt('Invalid home server specified').$end.$rtnlink);
 2601:                 return;
 2602:             }
 2603:         }
 2604:         # Check ID format
 2605:         my %checkhash;
 2606:         my %checks = ('id' => 1);
 2607:         %{$checkhash{$env{'form.ccuname'}.':'.$env{'form.ccdomain'}}} = (
 2608:             'newuser' => $newuser, 
 2609:             'id' => $env{'form.cid'},
 2610:         );
 2611:         if ($env{'form.cid'} ne '') {
 2612:             &Apache::loncommon::user_rule_check(\%checkhash,\%checks,\%alerts,
 2613:                                           \%rulematch,\%inst_results,\%curr_rules);
 2614:             if (ref($alerts{'id'}) eq 'HASH') {
 2615:                 if (ref($alerts{'id'}{$env{'form.ccdomain'}}) eq 'HASH') {
 2616:                     my $domdesc =
 2617:                         &Apache::lonnet::domain($env{'form.ccdomain'},'description');
 2618:                     if ($alerts{'id'}{$env{'form.ccdomain'}}{$env{'form.cid'}}) {
 2619:                         my $userchkmsg;
 2620:                         if (ref($curr_rules{$env{'form.ccdomain'}}) eq 'HASH') {
 2621:                             $userchkmsg  = 
 2622:                                 &Apache::loncommon::instrule_disallow_msg('id',
 2623:                                                                     $domdesc,1).
 2624:                                 &Apache::loncommon::user_rule_formats($env{'form.ccdomain'},
 2625:                                     $domdesc,$curr_rules{$env{'form.ccdomain'}}{'id'},'id');
 2626:                         }
 2627:                         $r->print($error.&mt('Invalid ID format').$end.
 2628:                                   $userchkmsg.$rtnlink);
 2629:                         return;
 2630:                     }
 2631:                 }
 2632:             }
 2633:         }
 2634:         &Apache::lonhtmlcommon::Increment_PrgWin($r, \%prog_state);
 2635: 	# Call modifyuser
 2636: 	my $result = &Apache::lonnet::modifyuser
 2637: 	    ($env{'form.ccdomain'},$env{'form.ccuname'},$env{'form.cid'},
 2638:              $amode,$genpwd,$env{'form.cfirstname'},
 2639:              $env{'form.cmiddlename'},$env{'form.clastname'},
 2640:              $env{'form.cgeneration'},undef,$desiredhost,
 2641:              $env{'form.cpermanentemail'});
 2642: 	$r->print(&mt('Generating user').': '.$result);
 2643:         $uhome = &Apache::lonnet::homeserver($env{'form.ccuname'},
 2644:                                                $env{'form.ccdomain'});
 2645:         my (%changeHash,%newcustom,%changed,%changedinfo);
 2646:         if ($uhome ne 'no_host') {
 2647:             if ($context eq 'domain') {
 2648:                 foreach my $name ('portfolio','author') {
 2649:                     if ($env{'form.custom_'.$name.'quota'} == 1) {
 2650:                         if ($env{'form.'.$name.'quota'} eq '') {
 2651:                             $newcustom{$name.'quota'} = 0;
 2652:                         } else {
 2653:                             $newcustom{$name.'quota'} = $env{'form.'.$name.'quota'};
 2654:                             $newcustom{$name.'quota'} =~ s/[^\d\.]//g;
 2655:                         }
 2656:                         if (&quota_admin($newcustom{$name.'quota'},\%changeHash,$name)) {
 2657:                             $changed{$name.'quota'} = 1;
 2658:                         }
 2659:                     }
 2660:                 }
 2661:                 foreach my $item (@usertools) {
 2662:                     if ($env{'form.custom'.$item} == 1) {
 2663:                         $newcustom{$item} = $env{'form.tools_'.$item};
 2664:                         $changed{$item} = &tool_admin($item,$newcustom{$item},
 2665:                                                      \%changeHash,'tools');
 2666:                     }
 2667:                 }
 2668:                 foreach my $item (@requestcourses) {
 2669:                     if ($env{'form.custom'.$item} == 1) {
 2670:                         $newcustom{$item} = $env{'form.crsreq_'.$item};
 2671:                         if ($env{'form.crsreq_'.$item} eq 'autolimit') {
 2672:                             $newcustom{$item} .= '=';
 2673:                             $env{'form.crsreq_'.$item.'_limit'} =~ s/\D+//g;
 2674:                             if ($env{'form.crsreq_'.$item.'_limit'}) {
 2675:                                 $newcustom{$item} .= $env{'form.crsreq_'.$item.'_limit'};
 2676:                             }
 2677:                         }
 2678:                         $changed{$item} = &tool_admin($item,$newcustom{$item},
 2679:                                                       \%changeHash,'requestcourses');
 2680:                     }
 2681:                 }
 2682:                 if ($env{'form.customrequestauthor'} == 1) {
 2683:                     $newcustom{'requestauthor'} = $env{'form.requestauthor'};
 2684:                     $changed{'requestauthor'} = &tool_admin('requestauthor',
 2685:                                                     $newcustom{'requestauthor'},
 2686:                                                     \%changeHash,'requestauthor');
 2687:                 }
 2688:             }
 2689:             if ($canmodify_status{'inststatus'}) {
 2690:                 if (exists($env{'form.inststatus'})) {
 2691:                     my @inststatuses = &Apache::loncommon::get_env_multiple('form.inststatus');
 2692:                     if (@inststatuses > 0) {
 2693:                         $changeHash{'inststatus'} = join(',',@inststatuses);
 2694:                         $changed{'inststatus'} = $changeHash{'inststatus'};
 2695:                     }
 2696:                 }
 2697:             }
 2698:             if (keys(%changed)) {
 2699:                 foreach my $item (@userinfo) {
 2700:                     $changeHash{$item}  = $env{'form.c'.$item};
 2701:                 }
 2702:                 my $chgresult =
 2703:                      &Apache::lonnet::put('environment',\%changeHash,
 2704:                                           $env{'form.ccdomain'},$env{'form.ccuname'});
 2705:             } 
 2706:         }
 2707:         $r->print('<br />'.&mt('Home server').': '.$uhome.' '.
 2708:                   &Apache::lonnet::hostname($uhome));
 2709:     } elsif (($env{'form.login'} ne 'nochange') &&
 2710:              ($env{'form.login'} ne ''        )) {
 2711: 	# Modify user privileges
 2712:         if (! $amode || ! $genpwd) {
 2713: 	    $r->print($error.'Invalid login mode or password'.$end.$rtnlink);    
 2714: 	    return;
 2715: 	}
 2716: 	# Only allow authentification modification if the person has authority
 2717: 	if (&Apache::lonnet::allowed('mau',$env{'form.ccdomain'})) {
 2718: 	    $r->print('Modifying authentication: '.
 2719:                       &Apache::lonnet::modifyuserauth(
 2720: 		       $env{'form.ccdomain'},$env{'form.ccuname'},
 2721:                        $amode,$genpwd));
 2722:             $r->print('<br />'.&mt('Home server').': '.&Apache::lonnet::homeserver
 2723: 		  ($env{'form.ccuname'},$env{'form.ccdomain'}));
 2724: 	} else {
 2725: 	    # Okay, this is a non-fatal error.
 2726: 	    $r->print($error.&mt('You do not have the authority to modify this users authentification information').'.'.$end);    
 2727: 	}
 2728:     }
 2729:     $r->rflush(); # Finish display of header before time consuming actions start
 2730:     &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state);
 2731:     ##
 2732:     my (@userroles,%userupdate,$cnum,$cdom,$defaultcredits,%namechanged);
 2733:     if ($context eq 'course') {
 2734:         ($cnum,$cdom) =
 2735:             &Apache::lonuserutils::get_course_identity();
 2736:         $crstype = &Apache::loncommon::course_type($cdom.'_'.$cnum);
 2737:         if ($showcredits) {
 2738:            $defaultcredits = &Apache::lonuserutils::get_defaultcredits($cdom,$cnum);
 2739:         }
 2740:     }
 2741:     if (! $env{'form.makeuser'} ) {
 2742:         # Check for need to change
 2743:         my %userenv = &Apache::lonnet::get
 2744:             ('environment',['firstname','middlename','lastname','generation',
 2745:              'id','permanentemail','portfolioquota','authorquota','inststatus',
 2746:              'tools.aboutme','tools.blog','tools.webdav','tools.portfolio',
 2747:              'requestcourses.official','requestcourses.unofficial',
 2748:              'requestcourses.community','requestcourses.textbook',
 2749:              'reqcrsotherdom.official','reqcrsotherdom.unofficial',
 2750:              'reqcrsotherdom.community','reqcrsotherdom.textbook',
 2751:              'requestauthor'],
 2752:               $env{'form.ccdomain'},$env{'form.ccuname'});
 2753:         my ($tmp) = keys(%userenv);
 2754:         if ($tmp =~ /^(con_lost|error)/i) { 
 2755:             %userenv = ();
 2756:         }
 2757:         my $no_forceid_alert;
 2758:         # Check to see if user information can be changed
 2759:         my %domconfig =
 2760:             &Apache::lonnet::get_dom('configuration',['usermodification'],
 2761:                                      $env{'form.ccdomain'});
 2762:         my @statuses = ('active','future');
 2763:         my %roles = &Apache::lonnet::get_my_roles($env{'form.ccuname'},$env{'form.ccdomain'},'userroles',\@statuses,undef,$env{'request.role.domain'});
 2764:         my ($auname,$audom);
 2765:         if ($context eq 'author') {
 2766:             $auname = $env{'user.name'};
 2767:             $audom = $env{'user.domain'};     
 2768:         }
 2769:         foreach my $item (keys(%roles)) {
 2770:             my ($rolenum,$roledom,$role) = split(/:/,$item,-1);
 2771:             if ($context eq 'course') {
 2772:                 if ($cnum ne '' && $cdom ne '') {
 2773:                     if ($rolenum eq $cnum && $roledom eq $cdom) {
 2774:                         if (!grep(/^\Q$role\E$/,@userroles)) {
 2775:                             push(@userroles,$role);
 2776:                         }
 2777:                     }
 2778:                 }
 2779:             } elsif ($context eq 'author') {
 2780:                 if ($rolenum eq $auname && $roledom eq $audom) {
 2781:                     if (!grep(/^\Q$role\E$/,@userroles)) { 
 2782:                         push(@userroles,$role);
 2783:                     }
 2784:                 }
 2785:             }
 2786:         }
 2787:         if ($env{'form.action'} eq 'singlestudent') {
 2788:             if (!grep(/^st$/,@userroles)) {
 2789:                 push(@userroles,'st');
 2790:             }
 2791:         } else {
 2792:             # Check for course or co-author roles being activated or re-enabled
 2793:             if ($context eq 'author' || $context eq 'course') {
 2794:                 foreach my $key (keys(%env)) {
 2795:                     if ($context eq 'author') {
 2796:                         if ($key=~/^form\.act_\Q$audom\E_\Q$auname\E_([^_]+)/) {
 2797:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 2798:                                 push(@userroles,$1);
 2799:                             }
 2800:                         } elsif ($key =~/^form\.ren\:\Q$audom\E\/\Q$auname\E_([^_]+)/) {
 2801:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 2802:                                 push(@userroles,$1);
 2803:                             }
 2804:                         }
 2805:                     } elsif ($context eq 'course') {
 2806:                         if ($key=~/^form\.act_\Q$cdom\E_\Q$cnum\E_([^_]+)/) {
 2807:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 2808:                                 push(@userroles,$1);
 2809:                             }
 2810:                         } elsif ($key =~/^form\.ren\:\Q$cdom\E\/\Q$cnum\E(\/?\w*)_([^_]+)/) {
 2811:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 2812:                                 push(@userroles,$1);
 2813:                             }
 2814:                         }
 2815:                     }
 2816:                 }
 2817:             }
 2818:         }
 2819:         #Check to see if we can change personal data for the user 
 2820:         my (@mod_disallowed,@longroles);
 2821:         foreach my $role (@userroles) {
 2822:             if ($role eq 'cr') {
 2823:                 push(@longroles,'Custom');
 2824:             } else {
 2825:                 push(@longroles,&Apache::lonnet::plaintext($role,$crstype)); 
 2826:             }
 2827:         }
 2828:         my %canmodify = &Apache::lonuserutils::can_modify_userinfo($context,$env{'form.ccdomain'},\@userinfo,\@userroles);
 2829:         foreach my $item (@userinfo) {
 2830:             # Strip leading and trailing whitespace
 2831:             $env{'form.c'.$item} =~ s/(\s+$|^\s+)//g;
 2832:             if (!$canmodify{$item}) {
 2833:                 if (defined($env{'form.c'.$item})) {
 2834:                     if ($env{'form.c'.$item} ne $userenv{$item}) {
 2835:                         push(@mod_disallowed,$item);
 2836:                     }
 2837:                 }
 2838:                 $env{'form.c'.$item} = $userenv{$item};
 2839:             }
 2840:         }
 2841:         # Check to see if we can change the Student/Employee ID
 2842:         my $forceid = $env{'form.forceid'};
 2843:         my $recurseid = $env{'form.recurseid'};
 2844:         my (%alerts,%rulematch,%idinst_results,%curr_rules,%got_rules);
 2845:         my %uidhash = &Apache::lonnet::idrget($env{'form.ccdomain'},
 2846:                                             $env{'form.ccuname'});
 2847:         if (($uidhash{$env{'form.ccuname'}}) && 
 2848:             ($uidhash{$env{'form.ccuname'}}!~/error\:/) && 
 2849:             (!$forceid)) {
 2850:             if ($env{'form.cid'} ne $uidhash{$env{'form.ccuname'}}) {
 2851:                 $env{'form.cid'} = $userenv{'id'};
 2852:                 $no_forceid_alert = &mt('New student/employee ID does not match existing ID for this user.')
 2853:                                    .'<br />'
 2854:                                    .&mt("Change is not permitted without checking the 'Force ID change' checkbox on the previous page.")
 2855:                                    .'<br />'."\n";
 2856:             }
 2857:         }
 2858:         if ($env{'form.cid'} ne $userenv{'id'}) {
 2859:             my $checkhash;
 2860:             my $checks = { 'id' => 1 };
 2861:             $checkhash->{$env{'form.ccuname'}.':'.$env{'form.ccdomain'}} = 
 2862:                    { 'newuser' => $newuser,
 2863:                      'id'  => $env{'form.cid'}, 
 2864:                    };
 2865:             &Apache::loncommon::user_rule_check($checkhash,$checks,
 2866:                 \%alerts,\%rulematch,\%idinst_results,\%curr_rules,\%got_rules);
 2867:             if (ref($alerts{'id'}) eq 'HASH') {
 2868:                 if (ref($alerts{'id'}{$env{'form.ccdomain'}}) eq 'HASH') {
 2869:                    $env{'form.cid'} = $userenv{'id'};
 2870:                 }
 2871:             }
 2872:         }
 2873:         my (%quotachanged,%oldquota,%newquota,%olddefquota,%newdefquota, 
 2874:             $oldinststatus,$newinststatus,%oldisdefault,%newisdefault,%oldsettings,
 2875:             %oldsettingstext,%newsettings,%newsettingstext,@disporder,
 2876:             %oldsettingstatus,%newsettingstatus);
 2877:         @disporder = ('inststatus');
 2878:         if ($env{'request.role.domain'} eq $env{'form.ccdomain'}) {
 2879:             push(@disporder,'requestcourses','requestauthor');
 2880:         } else {
 2881:             push(@disporder,'reqcrsotherdom');
 2882:         }
 2883:         push(@disporder,('quota','tools'));
 2884:         $oldinststatus = $userenv{'inststatus'};
 2885:         foreach my $name ('portfolio','author') {
 2886:             ($olddefquota{$name},$oldsettingstatus{$name}) = 
 2887:                 &Apache::loncommon::default_quota($env{'form.ccdomain'},$oldinststatus,$name);
 2888:             ($newdefquota{$name},$newsettingstatus{$name}) = ($olddefquota{$name},$oldsettingstatus{$name});
 2889:         }
 2890:         my %canshow;
 2891:         if (&Apache::lonnet::allowed('mpq',$env{'form.ccdomain'})) {
 2892:             $canshow{'quota'} = 1;
 2893:         }
 2894:         if (&Apache::lonnet::allowed('mut',$env{'form.ccdomain'})) {
 2895:             $canshow{'tools'} = 1;
 2896:         }
 2897:         if (&Apache::lonnet::allowed('ccc',$env{'form.ccdomain'})) {
 2898:             $canshow{'requestcourses'} = 1;
 2899:         } elsif (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) {
 2900:             $canshow{'reqcrsotherdom'} = 1;
 2901:         }
 2902:         if (&Apache::lonnet::allowed('mau',$env{'form.ccdomain'})) {
 2903:             $canshow{'inststatus'} = 1;
 2904:         }
 2905:         if (&Apache::lonnet::allowed('cau',$env{'form.ccdomain'})) {
 2906:             $canshow{'requestauthor'} = 1;
 2907:         }
 2908:         my (%changeHash,%changed);
 2909:         if ($oldinststatus eq '') {
 2910:             $oldsettings{'inststatus'} = $othertitle; 
 2911:         } else {
 2912:             if (ref($usertypes) eq 'HASH') {
 2913:                 $oldsettings{'inststatus'} = join(', ',map{ $usertypes->{ &unescape($_) }; } (split(/:/,$userenv{'inststatus'})));
 2914:             } else {
 2915:                 $oldsettings{'inststatus'} = join(', ',map{ &unescape($_); } (split(/:/,$userenv{'inststatus'})));
 2916:             }
 2917:         }
 2918:         $changeHash{'inststatus'} = $userenv{'inststatus'};
 2919:         if ($canmodify_status{'inststatus'}) {
 2920:             $canshow{'inststatus'} = 1;
 2921:             if (exists($env{'form.inststatus'})) {
 2922:                 my @inststatuses = &Apache::loncommon::get_env_multiple('form.inststatus');
 2923:                 if (@inststatuses > 0) {
 2924:                     $newinststatus = join(':',map { &escape($_); } @inststatuses);
 2925:                     $changeHash{'inststatus'} = $newinststatus;
 2926:                     if ($newinststatus ne $oldinststatus) {
 2927:                         $changed{'inststatus'} = $newinststatus;
 2928:                         foreach my $name ('portfolio','author') {
 2929:                             ($newdefquota{$name},$newsettingstatus{$name}) =
 2930:                                 &Apache::loncommon::default_quota($env{'form.ccdomain'},$newinststatus,$name);
 2931:                         }
 2932:                     }
 2933:                     if (ref($usertypes) eq 'HASH') {
 2934:                         $newsettings{'inststatus'} = join(', ',map{ $usertypes->{$_}; } (@inststatuses)); 
 2935:                     } else {
 2936:                         $newsettings{'inststatus'} = join(', ',@inststatuses);
 2937:                     }
 2938:                 }
 2939:             } else {
 2940:                 $newinststatus = '';
 2941:                 $changeHash{'inststatus'} = $newinststatus;
 2942:                 $newsettings{'inststatus'} = $othertitle;
 2943:                 if ($newinststatus ne $oldinststatus) {
 2944:                     $changed{'inststatus'} = $changeHash{'inststatus'};
 2945:                     foreach my $name ('portfolio','author') {
 2946:                         ($newdefquota{$name},$newsettingstatus{$name}) =
 2947:                             &Apache::loncommon::default_quota($env{'form.ccdomain'},$newinststatus,$name);
 2948:                     }
 2949:                 }
 2950:             }
 2951:         } elsif ($context ne 'selfcreate') {
 2952:             $canshow{'inststatus'} = 1;
 2953:             $newsettings{'inststatus'} = $oldsettings{'inststatus'};
 2954:         }
 2955:         foreach my $name ('portfolio','author') {
 2956:             $changeHash{$name.'quota'} = $userenv{$name.'quota'};
 2957:         }
 2958:         if ($context eq 'domain') {
 2959:             foreach my $name ('portfolio','author') {
 2960:                 if ($userenv{$name.'quota'} ne '') {
 2961:                     $oldquota{$name} = $userenv{$name.'quota'};
 2962:                     if ($env{'form.custom_'.$name.'quota'} == 1) {
 2963:                         if ($env{'form.'.$name.'quota'} eq '') {
 2964:                             $newquota{$name} = 0;
 2965:                         } else {
 2966:                             $newquota{$name} = $env{'form.'.$name.'quota'};
 2967:                             $newquota{$name} =~ s/[^\d\.]//g;
 2968:                         }
 2969:                         if ($newquota{$name} != $oldquota{$name}) {
 2970:                             if (&quota_admin($newquota{$name},\%changeHash,$name)) {
 2971:                                 $changed{$name.'quota'} = 1;
 2972:                             }
 2973:                         }
 2974:                     } else {
 2975:                         if (&quota_admin('',\%changeHash,$name)) {
 2976:                             $changed{$name.'quota'} = 1;
 2977:                             $newquota{$name} = $newdefquota{$name};
 2978:                             $newisdefault{$name} = 1;
 2979:                         }
 2980:                     }
 2981:                 } else {
 2982:                     $oldisdefault{$name} = 1;
 2983:                     $oldquota{$name} = $olddefquota{$name};
 2984:                     if ($env{'form.custom_'.$name.'quota'} == 1) {
 2985:                         if ($env{'form.'.$name.'quota'} eq '') {
 2986:                             $newquota{$name} = 0;
 2987:                         } else {
 2988:                             $newquota{$name} = $env{'form.'.$name.'quota'};
 2989:                             $newquota{$name} =~ s/[^\d\.]//g;
 2990:                         }
 2991:                         if (&quota_admin($newquota{$name},\%changeHash,$name)) {
 2992:                             $changed{$name.'quota'} = 1;
 2993:                         }
 2994:                     } else {
 2995:                         $newquota{$name} = $newdefquota{$name};
 2996:                         $newisdefault{$name} = 1;
 2997:                     }
 2998:                 }
 2999:                 if ($oldisdefault{$name}) {
 3000:                     $oldsettingstext{'quota'}{$name} = &get_defaultquota_text($oldsettingstatus{$name});
 3001:                 }  else {
 3002:                     $oldsettingstext{'quota'}{$name} = &mt('custom quota: [_1] MB',$oldquota{$name});
 3003:                 }
 3004:                 if ($newisdefault{$name}) {
 3005:                     $newsettingstext{'quota'}{$name} = &get_defaultquota_text($newsettingstatus{$name});
 3006:                 } else {
 3007:                     $newsettingstext{'quota'}{$name} = &mt('custom quota: [_1] MB',$newquota{$name});
 3008:                 }
 3009:             }
 3010:             &tool_changes('tools',\@usertools,\%oldsettings,\%oldsettingstext,\%userenv,
 3011:                           \%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3012:             if ($env{'form.ccdomain'} eq $env{'request.role.domain'}) {
 3013:                 &tool_changes('requestcourses',\@requestcourses,\%oldsettings,\%oldsettingstext,
 3014:                               \%userenv,\%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3015:                 &tool_changes('requestauthor',\@requestauthor,\%oldsettings,\%oldsettingstext,
 3016:                               \%userenv,\%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3017:             } else {
 3018:                 &tool_changes('reqcrsotherdom',\@requestcourses,\%oldsettings,\%oldsettingstext,
 3019:                               \%userenv,\%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3020:             }
 3021:         }
 3022:         foreach my $item (@userinfo) {
 3023:             if ($env{'form.c'.$item} ne $userenv{$item}) {
 3024:                 $namechanged{$item} = 1;
 3025:             }
 3026:         }
 3027:         foreach my $name ('portfolio','author') {
 3028:             $oldsettings{'quota'}{$name} = &mt('[_1] MB',$oldquota{$name});
 3029:             $newsettings{'quota'}{$name} = &mt('[_1] MB',$newquota{$name});
 3030:         }
 3031:         if ((keys(%namechanged) > 0) || (keys(%changed) > 0)) {
 3032:             my ($chgresult,$namechgresult);
 3033:             if (keys(%changed) > 0) {
 3034:                 $chgresult = 
 3035:                     &Apache::lonnet::put('environment',\%changeHash,
 3036:                                   $env{'form.ccdomain'},$env{'form.ccuname'});
 3037:                 if ($chgresult eq 'ok') {
 3038:                     if (($env{'user.name'} eq $env{'form.ccuname'}) &&
 3039:                         ($env{'user.domain'} eq $env{'form.ccdomain'})) {
 3040:                         my %newenvhash;
 3041:                         foreach my $key (keys(%changed)) {
 3042:                             if (($key eq 'official') || ($key eq 'unofficial')
 3043:                                 || ($key eq 'community')) {
 3044:                                 $newenvhash{'environment.requestcourses.'.$key} =
 3045:                                     $changeHash{'requestcourses.'.$key};
 3046:                                 if ($changeHash{'requestcourses.'.$key}) {
 3047:                                     $newenvhash{'environment.canrequest.'.$key} = 1;
 3048:                                 } else {
 3049:                                     $newenvhash{'environment.canrequest.'.$key} =
 3050:           &Apache::lonnet::usertools_access($env{'user.name'},$env{'user.domain'},
 3051:                                             $key,'reload','requestcourses');
 3052:                                 }
 3053:                             } elsif ($key eq 'requestauthor') {
 3054:                                 $newenvhash{'environment.'.$key} = $changeHash{$key};
 3055:                                 if ($changeHash{$key}) {
 3056:                                     $newenvhash{'environment.canrequest.author'} = 1;
 3057:                                 } else {
 3058:                                     $newenvhash{'environment.canrequest.author'} =
 3059:           &Apache::lonnet::usertools_access($env{'user.name'},$env{'user.domain'},
 3060:                                             $key,'reload','requestauthor');
 3061:                                 }
 3062:                             } elsif ($key ne 'quota') {
 3063:                                 $newenvhash{'environment.tools.'.$key} = 
 3064:                                     $changeHash{'tools.'.$key};
 3065:                                 if ($changeHash{'tools.'.$key} ne '') {
 3066:                                     $newenvhash{'environment.availabletools.'.$key} =
 3067:                                         $changeHash{'tools.'.$key};
 3068:                                 } else {
 3069:                                     $newenvhash{'environment.availabletools.'.$key} =
 3070:           &Apache::lonnet::usertools_access($env{'user.name'},$env{'user.domain'},
 3071:           $key,'reload','tools');
 3072:                                 }
 3073:                             }
 3074:                         }
 3075:                         if (keys(%newenvhash)) {
 3076:                             &Apache::lonnet::appenv(\%newenvhash);
 3077:                         }
 3078:                     }
 3079:                 }
 3080:             }
 3081:             if (keys(%namechanged) > 0) {
 3082:                 foreach my $field (@userinfo) {
 3083:                     $changeHash{$field}  = $env{'form.c'.$field};
 3084:                 }
 3085: # Make the change
 3086:                 $namechgresult =
 3087:                     &Apache::lonnet::modifyuser($env{'form.ccdomain'},
 3088:                         $env{'form.ccuname'},$changeHash{'id'},undef,undef,
 3089:                         $changeHash{'firstname'},$changeHash{'middlename'},
 3090:                         $changeHash{'lastname'},$changeHash{'generation'},
 3091:                         $changeHash{'id'},undef,$changeHash{'permanentemail'},undef,\@userinfo);
 3092:                 %userupdate = (
 3093:                                lastname   => $env{'form.clastname'},
 3094:                                middlename => $env{'form.cmiddlename'},
 3095:                                firstname  => $env{'form.cfirstname'},
 3096:                                generation => $env{'form.cgeneration'},
 3097:                                id         => $env{'form.cid'},
 3098:                              );
 3099:             }
 3100:             if (((keys(%namechanged) > 0) && $namechgresult eq 'ok') || 
 3101:                 ((keys(%changed) > 0) && $chgresult eq 'ok')) {
 3102:             # Tell the user we changed the name
 3103:                 &display_userinfo($r,1,\@disporder,\%canshow,\@requestcourses,
 3104:                                   \@usertools,\@requestauthor,\%userenv,\%changed,\%namechanged,
 3105:                                   \%oldsettings, \%oldsettingstext,\%newsettings,
 3106:                                   \%newsettingstext);
 3107:                 if ($env{'form.cid'} ne $userenv{'id'}) {
 3108:                     &Apache::lonnet::idput($env{'form.ccdomain'},
 3109:                          ($env{'form.ccuname'} => $env{'form.cid'}));
 3110:                     if (($recurseid) &&
 3111:                         (&Apache::lonnet::allowed('mau',$env{'form.ccdomain'}))) {
 3112:                         my $idresult = 
 3113:                             &Apache::lonuserutils::propagate_id_change(
 3114:                                 $env{'form.ccuname'},$env{'form.ccdomain'},
 3115:                                 \%userupdate);
 3116:                         $r->print('<br />'.$idresult.'<br />');
 3117:                     }
 3118:                 }
 3119:                 if (($env{'form.ccdomain'} eq $env{'user.domain'}) && 
 3120:                     ($env{'form.ccuname'} eq $env{'user.name'})) {
 3121:                     my %newenvhash;
 3122:                     foreach my $key (keys(%changeHash)) {
 3123:                         $newenvhash{'environment.'.$key} = $changeHash{$key};
 3124:                     }
 3125:                     &Apache::lonnet::appenv(\%newenvhash);
 3126:                 }
 3127:             } else { # error occurred
 3128:                 $r->print(
 3129:                     '<p class="LC_error">'
 3130:                    .&mt('Unable to successfully change environment for [_1] in domain [_2].',
 3131:                             '"'.$env{'form.ccuname'}.'"',
 3132:                             '"'.$env{'form.ccdomain'}.'"')
 3133:                    .'</p>');
 3134:             }
 3135:         } else { # End of if ($env ... ) logic
 3136:             # They did not want to change the users name, quota, tool availability,
 3137:             # or ability to request creation of courses, 
 3138:             # but we can still tell them what the name and quota and availabilities are  
 3139:             &display_userinfo($r,undef,\@disporder,\%canshow,\@requestcourses,
 3140:                               \@usertools,\@requestauthor,\%userenv,\%changed,\%namechanged,\%oldsettings,
 3141:                               \%oldsettingstext,\%newsettings,\%newsettingstext);
 3142:         }
 3143:         if (@mod_disallowed) {
 3144:             my ($rolestr,$contextname);
 3145:             if (@longroles > 0) {
 3146:                 $rolestr = join(', ',@longroles);
 3147:             } else {
 3148:                 $rolestr = &mt('No roles');
 3149:             }
 3150:             if ($context eq 'course') {
 3151:                 $contextname = &mt('course');
 3152:             } elsif ($context eq 'author') {
 3153:                 $contextname = &mt('co-author');
 3154:             }
 3155:             $r->print(&mt('The following fields were not updated: ').'<ul>');
 3156:             my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
 3157:             foreach my $field (@mod_disallowed) {
 3158:                 $r->print('<li>'.$fieldtitles{$field}.'</li>'."\n"); 
 3159:             }
 3160:             $r->print('</ul>');
 3161:             if (@mod_disallowed == 1) {
 3162:                 $r->print(&mt("You do not have the authority to change this field given the user's current set of active/future [_1] roles:",$contextname));
 3163:             } else {
 3164:                 $r->print(&mt("You do not have the authority to change these fields given the user's current set of active/future [_1] roles:",$contextname));
 3165:             }
 3166:             my $helplink = 'javascript:helpMenu('."'display'".')';
 3167:             $r->print('<span class="LC_cusr_emph">'.$rolestr.'</span><br />'
 3168:                      .&mt('Please contact your [_1]helpdesk[_2] for more information.'
 3169:                          ,'<a href="'.$helplink.'">','</a>')
 3170:                       .'<br />');
 3171:         }
 3172:         $r->print('<span class="LC_warning">'
 3173:                   .$no_forceid_alert
 3174:                   .&Apache::lonuserutils::print_namespacing_alerts($env{'form.ccdomain'},\%alerts,\%curr_rules)
 3175:                   .'</span>');
 3176:     }
 3177:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 3178:     if ($env{'form.action'} eq 'singlestudent') {
 3179:         &enroll_single_student($r,$uhome,$amode,$genpwd,$now,$newuser,$context,
 3180:                                $crstype,$showcredits,$defaultcredits);
 3181:         my $linktext = ($crstype eq 'Community' ?
 3182:             &mt('Enroll Another Member') : &mt('Enroll Another Student'));
 3183:         $r->print(
 3184:             &Apache::lonhtmlcommon::actionbox([
 3185:                 '<a href="javascript:backPage(document.userupdate)">'
 3186:                .($crstype eq 'Community' ? 
 3187:                     &mt('Enroll Another Member') : &mt('Enroll Another Student'))
 3188:                .'</a>']));
 3189:     } else {
 3190:         my @rolechanges = &update_roles($r,$context,$showcredits);
 3191:         if (keys(%namechanged) > 0) {
 3192:             if ($context eq 'course') {
 3193:                 if (@userroles > 0) {
 3194:                     if ((@rolechanges == 0) || 
 3195:                         (!(grep(/^st$/,@rolechanges)))) {
 3196:                         if (grep(/^st$/,@userroles)) {
 3197:                             my $classlistupdated =
 3198:                                 &Apache::lonuserutils::update_classlist($cdom,
 3199:                                               $cnum,$env{'form.ccdomain'},
 3200:                                        $env{'form.ccuname'},\%userupdate);
 3201:                         }
 3202:                     }
 3203:                 }
 3204:             }
 3205:         }
 3206:         my $userinfo = &Apache::loncommon::plainname($env{'form.ccuname'},
 3207:                                                      $env{'form.ccdomain'});
 3208:         if ($env{'form.popup'}) {
 3209:             $r->print('<p><a href="javascript:window.close()">'.&mt('Close window').'</a></p>');
 3210:         } else {
 3211:             $r->print('<br />'.&Apache::lonhtmlcommon::actionbox(['<a href="javascript:backPage(document.userupdate,'."'$env{'form.prevphase'}','modify'".')">'
 3212:                      .&mt('Modify this user: [_1]','<span class="LC_cusr_emph">'.$env{'form.ccuname'}.':'.$env{'form.ccdomain'}.' ('.$userinfo.')</span>').'</a>',
 3213:                      '<a href="javascript:backPage(document.userupdate)">'.&mt('Create/Modify Another User').'</a>']));
 3214:         }
 3215:     }
 3216: }
 3217: 
 3218: sub display_userinfo {
 3219:     my ($r,$changed,$order,$canshow,$requestcourses,$usertools,$requestauthor,
 3220:         $userenv,$changedhash,$namechangedhash,$oldsetting,$oldsettingtext,
 3221:         $newsetting,$newsettingtext) = @_;
 3222:     return unless (ref($order) eq 'ARRAY' &&
 3223:                    ref($canshow) eq 'HASH' && 
 3224:                    ref($requestcourses) eq 'ARRAY' && 
 3225:                    ref($requestauthor) eq 'ARRAY' &&
 3226:                    ref($usertools) eq 'ARRAY' && 
 3227:                    ref($userenv) eq 'HASH' &&
 3228:                    ref($changedhash) eq 'HASH' &&
 3229:                    ref($oldsetting) eq 'HASH' &&
 3230:                    ref($oldsettingtext) eq 'HASH' &&
 3231:                    ref($newsetting) eq 'HASH' &&
 3232:                    ref($newsettingtext) eq 'HASH');
 3233:     my %lt=&Apache::lonlocal::texthash(
 3234:          'ui'             => 'User Information',
 3235:          'uic'            => 'User Information Changed',
 3236:          'firstname'      => 'First Name',
 3237:          'middlename'     => 'Middle Name',
 3238:          'lastname'       => 'Last Name',
 3239:          'generation'     => 'Generation',
 3240:          'id'             => 'Student/Employee ID',
 3241:          'permanentemail' => 'Permanent e-mail address',
 3242:          'portfolioquota' => 'Disk space allocated to portfolio files',
 3243:          'authorquota'    => 'Disk space allocated to Authoring Space',
 3244:          'blog'           => 'Blog Availability',
 3245:          'webdav'         => 'WebDAV Availability',
 3246:          'aboutme'        => 'Personal Information Page Availability',
 3247:          'portfolio'      => 'Portfolio Availability',
 3248:          'official'       => 'Can Request Official Courses',
 3249:          'unofficial'     => 'Can Request Unofficial Courses',
 3250:          'community'      => 'Can Request Communities',
 3251:          'textbook'       => 'Can Request Textbook Courses',
 3252:          'requestauthor'  => 'Can Request Author Role',
 3253:          'inststatus'     => "Affiliation",
 3254:          'prvs'           => 'Previous Value:',
 3255:          'chto'           => 'Changed To:'
 3256:     );
 3257:     if ($changed) {
 3258:         $r->print('<h3>'.$lt{'uic'}.'</h3>'.
 3259:                 &Apache::loncommon::start_data_table().
 3260:                 &Apache::loncommon::start_data_table_header_row());
 3261:         $r->print("<th>&nbsp;</th>\n");
 3262:         $r->print('<th><b>'.$lt{'prvs'}.'</b></th>');
 3263:         $r->print('<th><span class="LC_nobreak"><b>'.$lt{'chto'}.'</b></span></th>');
 3264:         $r->print(&Apache::loncommon::end_data_table_header_row());
 3265:         my @userinfo = ('firstname','middlename','lastname','generation','permanentemail','id');
 3266: 
 3267:         foreach my $item (@userinfo) {
 3268:             my $value = $env{'form.c'.$item};
 3269:             #show changes only:
 3270:             unless ($value eq $userenv->{$item}){
 3271:                 $r->print(&Apache::loncommon::start_data_table_row());
 3272:                 $r->print("<td>$lt{$item}</td>\n");
 3273:                 $r->print("<td>".$userenv->{$item}."</td>\n");
 3274:                 $r->print("<td>$value </td>\n");
 3275:                 $r->print(&Apache::loncommon::end_data_table_row());
 3276:             }
 3277:         }
 3278:         foreach my $entry (@{$order}) {
 3279:             if ($canshow->{$entry}) {
 3280:                 if (($entry eq 'requestcourses') || ($entry eq 'reqcrsotherdom') || ($entry eq 'requestauthor')) {
 3281:                     my @items;
 3282:                     if ($entry eq 'requestauthor') {
 3283:                         @items = ($entry);
 3284:                     } else {
 3285:                         @items = @{$requestcourses};
 3286:                     }
 3287:                     foreach my $item (@items) {
 3288:                         if (($newsetting->{$item} ne $oldsetting->{$item}) || 
 3289:                             ($newsettingtext->{$item} ne $oldsettingtext->{$item})) {
 3290:                             $r->print(&Apache::loncommon::start_data_table_row()."\n");  
 3291:                             $r->print("<td>$lt{$item}</td>\n");
 3292:                             $r->print("<td>".$oldsetting->{$item});
 3293:                             if ($oldsettingtext->{$item}) {
 3294:                                 if ($oldsetting->{$item}) {
 3295:                                     $r->print(' -- ');
 3296:                                 }
 3297:                                 $r->print($oldsettingtext->{$item});
 3298:                             }
 3299:                             $r->print("</td>\n");
 3300:                             $r->print("<td>".$newsetting->{$item});
 3301:                             if ($newsettingtext->{$item}) {
 3302:                                 if ($newsetting->{$item}) {
 3303:                                     $r->print(' -- ');
 3304:                                 }
 3305:                                 $r->print($newsettingtext->{$item});
 3306:                             }
 3307:                             $r->print("</td>\n");
 3308:                             $r->print(&Apache::loncommon::end_data_table_row()."\n");
 3309:                         }
 3310:                     }
 3311:                 } elsif ($entry eq 'tools') {
 3312:                     foreach my $item (@{$usertools}) {
 3313:                         if ($newsetting->{$item} ne $oldsetting->{$item}) {
 3314:                             $r->print(&Apache::loncommon::start_data_table_row()."\n");
 3315:                             $r->print("<td>$lt{$item}</td>\n");
 3316:                             $r->print("<td>".$oldsetting->{$item}.' '.$oldsettingtext->{$item}."</td>\n");
 3317:                             $r->print("<td>".$newsetting->{$item}.' '.$newsettingtext->{$item}."</td>\n");
 3318:                             $r->print(&Apache::loncommon::end_data_table_row()."\n");
 3319:                         }
 3320:                     }
 3321:                 } elsif ($entry eq 'quota') {
 3322:                     if ((ref($oldsetting->{$entry}) eq 'HASH') && (ref($oldsettingtext->{$entry}) eq 'HASH') &&
 3323:                         (ref($newsetting->{$entry}) eq 'HASH') && (ref($newsettingtext->{$entry}) eq 'HASH')) {
 3324:                         foreach my $name ('portfolio','author') {
 3325:                             if ($newsetting->{$entry}->{$name} ne $oldsetting->{$entry}->{$name}) {
 3326:                                 $r->print(&Apache::loncommon::start_data_table_row()."\n");
 3327:                                 $r->print("<td>$lt{$name.$entry}</td>\n");
 3328:                                 $r->print("<td>".$oldsettingtext->{$entry}->{$name}."</td>\n");
 3329:                                 $r->print("<td>".$newsettingtext->{$entry}->{$name}."</td>\n");
 3330:                                 $r->print(&Apache::loncommon::end_data_table_row()."\n");
 3331:                             }
 3332:                         }
 3333:                     }
 3334:                 } else {
 3335:                     if ($newsetting->{$entry} ne $oldsetting->{$entry}) {
 3336:                         $r->print(&Apache::loncommon::start_data_table_row()."\n");
 3337:                         $r->print("<td>$lt{$entry}</td>\n");
 3338:                         $r->print("<td>".$oldsetting->{$entry}.' '.$oldsettingtext->{$entry}."</td>\n");
 3339:                         $r->print("<td>".$newsetting->{$entry}.' '.$newsettingtext->{$entry}."</td>\n");
 3340:                         $r->print(&Apache::loncommon::end_data_table_row()."\n");
 3341:                     }
 3342:                 }
 3343:             }
 3344:         }
 3345:         $r->print(&Apache::loncommon::end_data_table().'<br />');
 3346:     } else {
 3347:         $r->print('<h3>'.$lt{'ui'}.'</h3>'.
 3348:                   '<p>'.&mt('No changes made to user information').'</p>');
 3349:     }
 3350:     return;
 3351: }
 3352: 
 3353: sub tool_changes {
 3354:     my ($context,$usertools,$oldaccess,$oldaccesstext,$userenv,$changeHash,
 3355:         $changed,$newaccess,$newaccesstext) = @_;
 3356:     if (!((ref($usertools) eq 'ARRAY') && (ref($oldaccess) eq 'HASH') &&
 3357:           (ref($oldaccesstext) eq 'HASH') && (ref($userenv) eq 'HASH') &&
 3358:           (ref($changeHash) eq 'HASH') && (ref($changed) eq 'HASH') &&
 3359:           (ref($newaccess) eq 'HASH') && (ref($newaccesstext) eq 'HASH'))) {
 3360:         return;
 3361:     }
 3362:     my %reqdisplay = &requestchange_display();
 3363:     if ($context eq 'reqcrsotherdom') {
 3364:         my @options = ('approval','validate','autolimit');
 3365:         my $optregex = join('|',@options);
 3366:         my $cdom = $env{'request.role.domain'};
 3367:         foreach my $tool (@{$usertools}) {
 3368:             $oldaccesstext->{$tool} = &mt("availability set to 'off'");
 3369:             $newaccesstext->{$tool} = $oldaccesstext->{$tool};
 3370:             $changeHash->{$context.'.'.$tool} = $userenv->{$context.'.'.$tool};
 3371:             my ($newop,$limit);
 3372:             if ($env{'form.'.$context.'_'.$tool}) {
 3373:                 $newop = $env{'form.'.$context.'_'.$tool};
 3374:                 if ($newop eq 'autolimit') {
 3375:                     $limit = $env{'form.'.$context.'_'.$tool.'_limit'};
 3376:                     $limit =~ s/\D+//g;
 3377:                     $newop .= '='.$limit;
 3378:                 }
 3379:             }
 3380:             if ($userenv->{$context.'.'.$tool} eq '') {
 3381:                 if ($newop) {
 3382:                     $changed->{$tool}=&tool_admin($tool,$cdom.':'.$newop,
 3383:                                                   $changeHash,$context);
 3384:                     if ($changed->{$tool}) {
 3385:                         if ($newop =~ /^autolimit/) {
 3386:                             if ($limit) {
 3387:                                 $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3388:                             } else {
 3389:                                 $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3390:                             }
 3391:                         } else {
 3392:                             $newaccesstext->{$tool} = $reqdisplay{$newop};
 3393:                         }
 3394:                     } else {
 3395:                         $newaccesstext->{$tool} = $oldaccesstext->{$tool};
 3396:                     }
 3397:                 }
 3398:             } else {
 3399:                 my @curr = split(',',$userenv->{$context.'.'.$tool});
 3400:                 my @new;
 3401:                 my $changedoms;
 3402:                 foreach my $req (@curr) {
 3403:                     if ($req =~ /^\Q$cdom\E\:($optregex\=?\d*)$/) {
 3404:                         my $oldop = $1;
 3405:                         if ($oldop =~ /^autolimit=(\d*)/) {
 3406:                             my $limit = $1;
 3407:                             if ($limit) {
 3408:                                 $oldaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3409:                             } else {
 3410:                                 $oldaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3411:                             }
 3412:                         } else {
 3413:                             $oldaccesstext->{$tool} = $reqdisplay{$oldop};
 3414:                         }
 3415:                         if ($oldop ne $newop) {
 3416:                             $changedoms = 1;
 3417:                             foreach my $item (@curr) {
 3418:                                 my ($reqdom,$option) = split(':',$item);
 3419:                                 unless ($reqdom eq $cdom) {
 3420:                                     push(@new,$item);
 3421:                                 }
 3422:                             }
 3423:                             if ($newop) {
 3424:                                 push(@new,$cdom.':'.$newop);
 3425:                             }
 3426:                             @new = sort(@new);
 3427:                         }
 3428:                         last;
 3429:                     }
 3430:                 }
 3431:                 if ((!$changedoms) && ($newop)) {
 3432:                     $changedoms = 1;
 3433:                     @new = sort(@curr,$cdom.':'.$newop);
 3434:                 }
 3435:                 if ($changedoms) {
 3436:                     my $newdomstr;
 3437:                     if (@new) {
 3438:                         $newdomstr = join(',',@new);
 3439:                     }
 3440:                     $changed->{$tool}=&tool_admin($tool,$newdomstr,$changeHash,
 3441:                                                   $context);
 3442:                     if ($changed->{$tool}) {
 3443:                         if ($env{'form.'.$context.'_'.$tool}) {
 3444:                             if ($env{'form.'.$context.'_'.$tool} eq 'autolimit') {
 3445:                                 my $limit = $env{'form.'.$context.'_'.$tool.'_limit'};
 3446:                                 $limit =~ s/\D+//g;
 3447:                                 if ($limit) {
 3448:                                     $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3449:                                 } else {
 3450:                                     $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3451:                                 }
 3452:                             } else {
 3453:                                 $newaccesstext->{$tool} = $reqdisplay{$env{'form.'.$context.'_'.$tool}};
 3454:                             }
 3455:                         } else {
 3456:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3457:                         }
 3458:                     }
 3459:                 }
 3460:             }
 3461:         }
 3462:         return;
 3463:     }
 3464:     foreach my $tool (@{$usertools}) {
 3465:         my ($newval,$limit,$envkey);
 3466:         $envkey = $context.'.'.$tool;
 3467:         if ($context eq 'requestcourses') {
 3468:             $newval = $env{'form.crsreq_'.$tool};
 3469:             if ($newval eq 'autolimit') {
 3470:                 $limit = $env{'form.crsreq_'.$tool.'_limit'};
 3471:                 $limit =~ s/\D+//g;
 3472:                 $newval .= '='.$limit;
 3473:             }
 3474:         } elsif ($context eq 'requestauthor') {
 3475:             $newval = $env{'form.'.$context};
 3476:             $envkey = $context;
 3477:         } else {
 3478:             $newval = $env{'form.'.$context.'_'.$tool};
 3479:         }
 3480:         if ($userenv->{$envkey} ne '') {
 3481:             $oldaccess->{$tool} = &mt('custom');
 3482:             if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 3483:                 if ($userenv->{$envkey} =~ /^autolimit=(\d*)$/) {
 3484:                     my $currlimit = $1;
 3485:                     if ($currlimit eq '') {
 3486:                         $oldaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3487:                     } else {
 3488:                         $oldaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$currlimit);
 3489:                     }
 3490:                 } elsif ($userenv->{$envkey}) {
 3491:                     $oldaccesstext->{$tool} = $reqdisplay{$userenv->{$envkey}};
 3492:                 } else {
 3493:                     $oldaccesstext->{$tool} = &mt("availability set to 'off'");
 3494:                 }
 3495:             } else {
 3496:                 if ($userenv->{$envkey}) {
 3497:                     $oldaccesstext->{$tool} = &mt("availability set to 'on'");
 3498:                 } else {
 3499:                     $oldaccesstext->{$tool} = &mt("availability set to 'off'");
 3500:                 }
 3501:             }
 3502:             $changeHash->{$envkey} = $userenv->{$envkey};
 3503:             if ($env{'form.custom'.$tool} == 1) {
 3504:                 if ($newval ne $userenv->{$envkey}) {
 3505:                     $changed->{$tool} = &tool_admin($tool,$newval,$changeHash,
 3506:                                                     $context);
 3507:                     if ($changed->{$tool}) {
 3508:                         $newaccess->{$tool} = &mt('custom');
 3509:                         if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 3510:                             if ($newval =~ /^autolimit/) {
 3511:                                 if ($limit) {
 3512:                                     $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3513:                                 } else {
 3514:                                     $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3515:                                 }
 3516:                             } elsif ($newval) {
 3517:                                 $newaccesstext->{$tool} = $reqdisplay{$newval};
 3518:                             } else {
 3519:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3520:                             }
 3521:                         } else {
 3522:                             if ($newval) {
 3523:                                 $newaccesstext->{$tool} = &mt("availability set to 'on'");
 3524:                             } else {
 3525:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3526:                             }
 3527:                         }
 3528:                     } else {
 3529:                         $newaccess->{$tool} = $oldaccess->{$tool};
 3530:                         if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 3531:                             if ($newval =~ /^autolimit/) {
 3532:                                 if ($limit) {
 3533:                                     $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3534:                                 } else {
 3535:                                     $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3536:                                 }
 3537:                             } elsif ($newval) {
 3538:                                 $newaccesstext->{$tool} = $reqdisplay{$newval};
 3539:                             } else {
 3540:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3541:                             }
 3542:                         } else {
 3543:                             if ($userenv->{$context.'.'.$tool}) {
 3544:                                 $newaccesstext->{$tool} = &mt("availability set to 'on'");
 3545:                             } else {
 3546:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3547:                             }
 3548:                         }
 3549:                     }
 3550:                 } else {
 3551:                     $newaccess->{$tool} = $oldaccess->{$tool};
 3552:                     $newaccesstext->{$tool} = $oldaccesstext->{$tool};
 3553:                 }
 3554:             } else {
 3555:                 $changed->{$tool} = &tool_admin($tool,'',$changeHash,$context);
 3556:                 if ($changed->{$tool}) {
 3557:                     $newaccess->{$tool} = &mt('default');
 3558:                 } else {
 3559:                     $newaccess->{$tool} = $oldaccess->{$tool};
 3560:                     if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 3561:                         if ($newval =~ /^autolimit/) {
 3562:                             if ($limit) {
 3563:                                 $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3564:                             } else {
 3565:                                 $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3566:                             }
 3567:                         } elsif ($newval) {
 3568:                             $newaccesstext->{$tool} = $reqdisplay{$newval};
 3569:                         } else {
 3570:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3571:                         }
 3572:                     } else {
 3573:                         if ($userenv->{$context.'.'.$tool}) {
 3574:                             $newaccesstext->{$tool} = &mt("availability set to 'on'");
 3575:                         } else {
 3576:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3577:                         }
 3578:                     }
 3579:                 }
 3580:             }
 3581:         } else {
 3582:             $oldaccess->{$tool} = &mt('default');
 3583:             if ($env{'form.custom'.$tool} == 1) {
 3584:                 $changed->{$tool} = &tool_admin($tool,$newval,$changeHash,
 3585:                                                 $context);
 3586:                 if ($changed->{$tool}) {
 3587:                     $newaccess->{$tool} = &mt('custom');
 3588:                     if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 3589:                         if ($newval =~ /^autolimit/) {
 3590:                             if ($limit) {
 3591:                                 $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3592:                             } else {
 3593:                                 $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3594:                             }
 3595:                         } elsif ($newval) {
 3596:                             $newaccesstext->{$tool} = $reqdisplay{$newval};
 3597:                         } else {
 3598:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3599:                         }
 3600:                     } else {
 3601:                         if ($newval) {
 3602:                             $newaccesstext->{$tool} = &mt("availability set to 'on'");
 3603:                         } else {
 3604:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3605:                         }
 3606:                     }
 3607:                 } else {
 3608:                     $newaccess->{$tool} = $oldaccess->{$tool};
 3609:                 }
 3610:             } else {
 3611:                 $newaccess->{$tool} = $oldaccess->{$tool};
 3612:             }
 3613:         }
 3614:     }
 3615:     return;
 3616: }
 3617: 
 3618: sub update_roles {
 3619:     my ($r,$context,$showcredits) = @_;
 3620:     my $now=time;
 3621:     my @rolechanges;
 3622:     my %disallowed;
 3623:     $r->print('<h3>'.&mt('Modifying Roles').'</h3>');
 3624:     foreach my $key (keys (%env)) {
 3625: 	next if (! $env{$key});
 3626:         next if ($key eq 'form.action');
 3627: 	# Revoke roles
 3628: 	if ($key=~/^form\.rev/) {
 3629: 	    if ($key=~/^form\.rev\:([^\_]+)\_([^\_\.]+)$/) {
 3630: # Revoke standard role
 3631: 		my ($scope,$role) = ($1,$2);
 3632: 		my $result =
 3633: 		    &Apache::lonnet::revokerole($env{'form.ccdomain'},
 3634: 						$env{'form.ccuname'},
 3635: 						$scope,$role,'','',$context);
 3636:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
 3637:                             &mt('Revoking [_1] in [_2]',
 3638:                                 &Apache::lonnet::plaintext($role),
 3639:                                 &Apache::loncommon::show_role_extent($scope,$context,$role)),
 3640:                                 $result ne "ok").'<br />');
 3641:                 if ($result ne "ok") {
 3642:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 3643:                 }
 3644: 		if ($role eq 'st') {
 3645: 		    my $result = 
 3646:                         &Apache::lonuserutils::classlist_drop($scope,
 3647:                             $env{'form.ccuname'},$env{'form.ccdomain'},
 3648: 			    $now);
 3649:                     $r->print(&Apache::lonhtmlcommon::confirm_success($result));
 3650: 		}
 3651:                 if (!grep(/^\Q$role\E$/,@rolechanges)) {
 3652:                     push(@rolechanges,$role);
 3653:                 }
 3654: 	    }
 3655: 	    if ($key=~m{^form\.rev\:([^_]+)_cr\.cr/($match_domain)/($match_username)/(\w+)$}s) {
 3656: # Revoke custom role
 3657:                 my $result = &Apache::lonnet::revokecustomrole(
 3658:                     $env{'form.ccdomain'},$env{'form.ccuname'},$1,$2,$3,$4,'','',$context);
 3659:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
 3660:                             &mt('Revoking custom role [_1] by [_2] in [_3]',
 3661:                                 $4,$3.':'.$2,&Apache::loncommon::show_role_extent($1,$context,'cr')),
 3662:                             $result ne 'ok').'<br />');
 3663:                 if ($result ne "ok") {
 3664:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 3665:                 }
 3666:                 if (!grep(/^cr$/,@rolechanges)) {
 3667:                     push(@rolechanges,'cr');
 3668:                 }
 3669: 	    }
 3670: 	} elsif ($key=~/^form\.del/) {
 3671: 	    if ($key=~/^form\.del\:([^\_]+)\_([^\_\.]+)$/) {
 3672: # Delete standard role
 3673: 		my ($scope,$role) = ($1,$2);
 3674: 		my $result =
 3675: 		    &Apache::lonnet::assignrole($env{'form.ccdomain'},
 3676: 						$env{'form.ccuname'},
 3677: 						$scope,$role,$now,0,1,'',
 3678:                                                 $context);
 3679:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
 3680:                             &mt('Deleting [_1] in [_2]',
 3681:                                 &Apache::lonnet::plaintext($role),
 3682:                                 &Apache::loncommon::show_role_extent($scope,$context,$role)),
 3683:                             $result ne 'ok').'<br />');
 3684:                 if ($result ne "ok") {
 3685:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 3686:                 }
 3687: 
 3688: 		if ($role eq 'st') {
 3689: 		    my $result = 
 3690:                         &Apache::lonuserutils::classlist_drop($scope,
 3691:                             $env{'form.ccuname'},$env{'form.ccdomain'},
 3692: 			    $now);
 3693: 		    $r->print(&Apache::lonhtmlcommon::confirm_success($result));
 3694: 		}
 3695:                 if (!grep(/^\Q$role\E$/,@rolechanges)) {
 3696:                     push(@rolechanges,$role);
 3697:                 }
 3698:             }
 3699: 	    if ($key=~m{^form\.del\:([^_]+)_cr\.cr/($match_domain)/($match_username)/(\w+)$}) {
 3700:                 my ($url,$rdom,$rnam,$rolename) = ($1,$2,$3,$4);
 3701: # Delete custom role
 3702:                 my $result =
 3703:                     &Apache::lonnet::assigncustomrole($env{'form.ccdomain'},
 3704:                         $env{'form.ccuname'},$url,$rdom,$rnam,$rolename,$now,
 3705:                         0,1,$context);
 3706:                 $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('Deleting custom role [_1] by [_2] in [_3]',
 3707:                       $rolename,$rnam.':'.$rdom,&Apache::loncommon::show_role_extent($1,$context,'cr')),
 3708:                       $result ne "ok").'<br />');
 3709:                 if ($result ne "ok") {
 3710:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 3711:                 }
 3712: 
 3713:                 if (!grep(/^cr$/,@rolechanges)) {
 3714:                     push(@rolechanges,'cr');
 3715:                 }
 3716:             }
 3717: 	} elsif ($key=~/^form\.ren/) {
 3718:             my $udom = $env{'form.ccdomain'};
 3719:             my $uname = $env{'form.ccuname'};
 3720: # Re-enable standard role
 3721: 	    if ($key=~/^form\.ren\:([^\_]+)\_([^\_\.]+)$/) {
 3722:                 my $url = $1;
 3723:                 my $role = $2;
 3724:                 my $logmsg;
 3725:                 my $output;
 3726:                 if ($role eq 'st') {
 3727:                     if ($url =~ m-^/($match_domain)/($match_courseid)/?(\w*)$-) {
 3728:                         my ($cdom,$cnum,$csec) = ($1,$2,$3);
 3729:                         my $credits;
 3730:                         if ($showcredits) {
 3731:                             my $defaultcredits = 
 3732:                                 &Apache::lonuserutils::get_defaultcredits($cdom,$cnum);
 3733:                             $credits = &get_user_credits($defaultcredits,$cdom,$cnum);
 3734:                         }
 3735:                         my $result = &Apache::loncommon::commit_studentrole(\$logmsg,$udom,$uname,$url,$role,$now,0,$cdom,$cnum,$csec,$context,$credits);
 3736:                         if (($result =~ /^error/) || ($result eq 'not_in_class') || ($result eq 'unknown_course') || ($result eq 'refused')) {
 3737:                             if ($result eq 'refused' && $logmsg) {
 3738:                                 $output = $logmsg;
 3739:                             } else { 
 3740:                                 $output = &mt('Error: [_1]',$result)."\n";
 3741:                             }
 3742:                         } else {
 3743:                             $output = &Apache::lonhtmlcommon::confirm_success(&mt('Assigning [_1] in [_2] starting [_3]',
 3744:                                         &Apache::lonnet::plaintext($role),
 3745:                                         &Apache::loncommon::show_role_extent($url,$context,'st'),
 3746:                                         &Apache::lonlocal::locallocaltime($now))).'<br />'.$logmsg.'<br />';
 3747:                         }
 3748:                     }
 3749:                 } else {
 3750: 		    my $result=&Apache::lonnet::assignrole($env{'form.ccdomain'},
 3751:                                $env{'form.ccuname'},$url,$role,0,$now,'','',
 3752:                                $context);
 3753:                         $output = &Apache::lonhtmlcommon::confirm_success(&mt('Re-enabling [_1] in [_2]',
 3754:                                         &Apache::lonnet::plaintext($role),
 3755:                                         &Apache::loncommon::show_role_extent($url,$context,$role)),$result ne "ok").'<br />';
 3756:                     if ($result ne "ok") {
 3757:                         $output .= &mt('Error: [_1]',$result).'<br />';
 3758:                     }
 3759:                 }
 3760:                 $r->print($output);
 3761:                 if (!grep(/^\Q$role\E$/,@rolechanges)) {
 3762:                     push(@rolechanges,$role);
 3763:                 }
 3764: 	    }
 3765: # Re-enable custom role
 3766: 	    if ($key=~m{^form\.ren\:([^_]+)_cr\.cr/($match_domain)/($match_username)/(\w+)$}) {
 3767:                 my ($url,$rdom,$rnam,$rolename) = ($1,$2,$3,$4);
 3768:                 my $result = &Apache::lonnet::assigncustomrole(
 3769:                                $env{'form.ccdomain'}, $env{'form.ccuname'},
 3770:                                $url,$rdom,$rnam,$rolename,0,$now,undef,$context);
 3771:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
 3772:                     &mt('Re-enabling custom role [_1] by [_2] in [_3]',
 3773:                         $rolename,$rnam.':'.$rdom,&Apache::loncommon::show_role_extent($1,$context,'cr')),
 3774:                     $result ne "ok").'<br />');
 3775:                 if ($result ne "ok") {
 3776:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 3777:                 }
 3778:                 if (!grep(/^cr$/,@rolechanges)) {
 3779:                     push(@rolechanges,'cr');
 3780:                 }
 3781:             }
 3782: 	} elsif ($key=~/^form\.act/) {
 3783:             my $udom = $env{'form.ccdomain'};
 3784:             my $uname = $env{'form.ccuname'};
 3785: 	    if ($key=~/^form\.act\_($match_domain)\_($match_courseid)\_cr_cr_($match_domain)_($match_username)_([^\_]+)$/) {
 3786:                 # Activate a custom role
 3787: 		my ($one,$two,$three,$four,$five)=($1,$2,$3,$4,$5);
 3788: 		my $url='/'.$one.'/'.$two;
 3789: 		my $full=$one.'_'.$two.'_cr_cr_'.$three.'_'.$four.'_'.$five;
 3790: 
 3791:                 my $start = ( $env{'form.start_'.$full} ?
 3792:                               $env{'form.start_'.$full} :
 3793:                               $now );
 3794:                 my $end   = ( $env{'form.end_'.$full} ?
 3795:                               $env{'form.end_'.$full} :
 3796:                               0 );
 3797:                                                                                      
 3798:                 # split multiple sections
 3799:                 my %sections = ();
 3800:                 my $num_sections = &build_roles($env{'form.sec_'.$full},\%sections,$5);
 3801:                 if ($num_sections == 0) {
 3802:                     $r->print(&Apache::loncommon::commit_customrole($udom,$uname,$url,$three,$four,$five,$start,$end,$context));
 3803:                 } else {
 3804: 		    my %curr_groups =
 3805: 			&Apache::longroup::coursegroups($one,$two);
 3806:                     foreach my $sec (sort {$a cmp $b} keys %sections) {
 3807:                         if (($sec eq 'none') || ($sec eq 'all') || 
 3808:                             exists($curr_groups{$sec})) {
 3809:                             $disallowed{$sec} = $url;
 3810:                             next;
 3811:                         }
 3812:                         my $securl = $url.'/'.$sec;
 3813: 		        $r->print(&Apache::loncommon::commit_customrole($udom,$uname,$securl,$three,$four,$five,$start,$end,$context));
 3814:                     }
 3815:                 }
 3816:                 if (!grep(/^cr$/,@rolechanges)) {
 3817:                     push(@rolechanges,'cr');
 3818:                 }
 3819: 	    } elsif ($key=~/^form\.act\_($match_domain)\_($match_name)\_([^\_]+)$/) {
 3820: 		# Activate roles for sections with 3 id numbers
 3821: 		# set start, end times, and the url for the class
 3822: 		my ($one,$two,$three)=($1,$2,$3);
 3823: 		my $start = ( $env{'form.start_'.$one.'_'.$two.'_'.$three} ? 
 3824: 			      $env{'form.start_'.$one.'_'.$two.'_'.$three} : 
 3825: 			      $now );
 3826: 		my $end   = ( $env{'form.end_'.$one.'_'.$two.'_'.$three} ? 
 3827: 			      $env{'form.end_'.$one.'_'.$two.'_'.$three} :
 3828: 			      0 );
 3829: 		my $url='/'.$one.'/'.$two;
 3830:                 my $type = 'three';
 3831:                 # split multiple sections
 3832:                 my %sections = ();
 3833:                 my $num_sections = &build_roles($env{'form.sec_'.$one.'_'.$two.'_'.$three},\%sections,$three);
 3834:                 my $credits;
 3835:                 if ($three eq 'st') {
 3836:                     if ($showcredits) { 
 3837:                         my $defaultcredits = 
 3838:                             &Apache::lonuserutils::get_defaultcredits($one,$two);
 3839:                         $credits = $env{'form.credits_'.$one.'_'.$two.'_'.$three};
 3840:                         $credits =~ s/[^\d\.]//g;
 3841:                         if ($credits eq $defaultcredits) {
 3842:                             undef($credits);
 3843:                         }
 3844:                     }
 3845:                 }
 3846:                 if ($num_sections == 0) {
 3847:                     $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$three,$start,$end,$one,$two,'',$context,$credits));
 3848:                 } else {
 3849:                     my %curr_groups = 
 3850: 			&Apache::longroup::coursegroups($one,$two);
 3851:                     my $emptysec = 0;
 3852:                     foreach my $sec (sort {$a cmp $b} keys %sections) {
 3853:                         $sec =~ s/\W//g;
 3854:                         if ($sec ne '') {
 3855:                             if (($sec eq 'none') || ($sec eq 'all') || 
 3856:                                 exists($curr_groups{$sec})) {
 3857:                                 $disallowed{$sec} = $url;
 3858:                                 next;
 3859:                             }
 3860:                             my $securl = $url.'/'.$sec;
 3861:                             $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$securl,$three,$start,$end,$one,$two,$sec,$context,$credits));
 3862:                         } else {
 3863:                             $emptysec = 1;
 3864:                         }
 3865:                     }
 3866:                     if ($emptysec) {
 3867:                         $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$three,$start,$end,$one,$two,'',$context,$credits));
 3868:                     }
 3869:                 }
 3870:                 if (!grep(/^\Q$three\E$/,@rolechanges)) {
 3871:                     push(@rolechanges,$three);
 3872:                 }
 3873: 	    } elsif ($key=~/^form\.act\_([^\_]+)\_([^\_]+)$/) {
 3874: 		# Activate roles for sections with two id numbers
 3875: 		# set start, end times, and the url for the class
 3876: 		my $start = ( $env{'form.start_'.$1.'_'.$2} ? 
 3877: 			      $env{'form.start_'.$1.'_'.$2} : 
 3878: 			      $now );
 3879: 		my $end   = ( $env{'form.end_'.$1.'_'.$2} ? 
 3880: 			      $env{'form.end_'.$1.'_'.$2} :
 3881: 			      0 );
 3882:                 my $one = $1;
 3883:                 my $two = $2;
 3884: 		my $url='/'.$one.'/';
 3885:                 # split multiple sections
 3886:                 my %sections = ();
 3887:                 my $num_sections = &build_roles($env{'form.sec_'.$one.'_'.$two},\%sections,$two);
 3888:                 if ($num_sections == 0) {
 3889:                     $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$two,$start,$end,$one,undef,'',$context));
 3890:                 } else {
 3891:                     my $emptysec = 0;
 3892:                     foreach my $sec (sort {$a cmp $b} keys %sections) {
 3893:                         if ($sec ne '') {
 3894:                             my $securl = $url.'/'.$sec;
 3895:                             $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$securl,$two,$start,$end,$one,undef,$sec,$context));
 3896:                         } else {
 3897:                             $emptysec = 1;
 3898:                         }
 3899:                     }
 3900:                     if ($emptysec) {
 3901:                         $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$two,$start,$end,$one,undef,'',$context));
 3902:                     }
 3903:                 }
 3904:                 if (!grep(/^\Q$two\E$/,@rolechanges)) {
 3905:                     push(@rolechanges,$two);
 3906:                 }
 3907: 	    } else {
 3908: 		$r->print('<p><span class="LC_error">'.&mt('ERROR').': '.&mt('Unknown command').' <tt>'.$key.'</tt></span></p><br />');
 3909:             }
 3910:             foreach my $key (sort(keys(%disallowed))) {
 3911:                 $r->print('<p class="LC_warning">');
 3912:                 if (($key eq 'none') || ($key eq 'all')) {  
 3913:                     $r->print(&mt('[_1] may not be used as the name for a section, as it is a reserved word.','<tt>'.$key.'</tt>'));
 3914:                 } else {
 3915:                     $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>'));
 3916:                 }
 3917:                 $r->print('</p><p>'
 3918:                          .&mt('Please [_1]go back[_2] and choose a different section name.'
 3919:                              ,'<a href="javascript:history.go(-1)'
 3920:                              ,'</a>')
 3921:                          .'</p><br />'
 3922:                 );
 3923:             }
 3924: 	}
 3925:     } # End of foreach (keys(%env))
 3926: # Flush the course logs so reverse user roles immediately updated
 3927:     $r->register_cleanup(\&Apache::lonnet::flushcourselogs);
 3928:     if (@rolechanges == 0) {
 3929:         $r->print('<p>'.&mt('No roles to modify').'</p>');
 3930:     }
 3931:     return @rolechanges;
 3932: }
 3933: 
 3934: sub get_user_credits {
 3935:     my ($uname,$udom,$defaultcredits,$cdom,$cnum) = @_;
 3936:     if ($cdom eq '' || $cnum eq '') {
 3937:         return unless ($env{'request.course.id'});
 3938:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3939:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3940:     }
 3941:     my $credits;
 3942:     my %currhash =
 3943:         &Apache::lonnet::get('classlist',[$uname.':'.$udom],$cdom,$cnum);
 3944:     if (keys(%currhash) > 0) {
 3945:         my @items = split(/:/,$currhash{$uname.':'.$udom});
 3946:         my $crdidx = &Apache::loncoursedata::CL_CREDITS() - 3;
 3947:         $credits = $items[$crdidx];
 3948:         $credits =~ s/[^\d\.]//g;
 3949:     }
 3950:     if ($credits eq $defaultcredits) {
 3951:         undef($credits);
 3952:     }
 3953:     return $credits;
 3954: }
 3955: 
 3956: sub enroll_single_student {
 3957:     my ($r,$uhome,$amode,$genpwd,$now,$newuser,$context,$crstype,
 3958:         $showcredits,$defaultcredits) = @_;
 3959:     $r->print('<h3>');
 3960:     if ($crstype eq 'Community') {
 3961:         $r->print(&mt('Enrolling Member'));
 3962:     } else {
 3963:         $r->print(&mt('Enrolling Student'));
 3964:     }
 3965:     $r->print('</h3>');
 3966: 
 3967:     # Remove non alphanumeric values from section
 3968:     $env{'form.sections'}=~s/\W//g;
 3969: 
 3970:     my $credits;
 3971:     if (($showcredits) && ($env{'form.credits'} ne '')) {
 3972:         $credits = $env{'form.credits'};
 3973:         $credits =~ s/[^\d\.]//g;
 3974:         if ($credits ne '') {
 3975:             if ($credits eq $defaultcredits) {
 3976:                 undef($credits);
 3977:             }
 3978:         }
 3979:     }
 3980: 
 3981:     # Clean out any old student roles the user has in this class.
 3982:     &Apache::lonuserutils::modifystudent($env{'form.ccdomain'},
 3983:          $env{'form.ccuname'},$env{'request.course.id'},undef,$uhome);
 3984:     my ($startdate,$enddate) = &Apache::lonuserutils::get_dates_from_form();
 3985:     my $enroll_result =
 3986:         &Apache::lonnet::modify_student_enrollment($env{'form.ccdomain'},
 3987:             $env{'form.ccuname'},$env{'form.cid'},$env{'form.cfirstname'},
 3988:             $env{'form.cmiddlename'},$env{'form.clastname'},
 3989:             $env{'form.generation'},$env{'form.sections'},$enddate,
 3990:             $startdate,'manual',undef,$env{'request.course.id'},'',$context,
 3991:             $credits);
 3992:     if ($enroll_result =~ /^ok/) {
 3993:         $r->print(&mt('[_1] enrolled','<b>'.$env{'form.ccuname'}.':'.$env{'form.ccdomain'}.'</b>'));
 3994:         if ($env{'form.sections'} ne '') {
 3995:             $r->print(' '.&mt('in section [_1]',$env{'form.sections'}));
 3996:         }
 3997:         my ($showstart,$showend);
 3998:         if ($startdate <= $now) {
 3999:             $showstart = &mt('Access starts immediately');
 4000:         } else {
 4001:             $showstart = &mt('Access starts: ').&Apache::lonlocal::locallocaltime($startdate);
 4002:         }
 4003:         if ($enddate == 0) {
 4004:             $showend = &mt('ends: no ending date');
 4005:         } else {
 4006:             $showend = &mt('ends: ').&Apache::lonlocal::locallocaltime($enddate);
 4007:         }
 4008:         $r->print('.<br />'.$showstart.'; '.$showend);
 4009:         if ($startdate <= $now && !$newuser) {
 4010:             $r->print('<p class="LC_info">');
 4011:             if ($crstype eq 'Community') {
 4012:                 $r->print(&mt('If the member is currently logged-in to LON-CAPA, the new role will be available when the member next logs in.'));
 4013:             } else {
 4014:                 $r->print(&mt('If the student is currently logged-in to LON-CAPA, the new role will be available when the student next logs in.'));
 4015:            }
 4016:            $r->print('</p>');
 4017:         }
 4018:     } else {
 4019:         $r->print(&mt('unable to enroll').": ".$enroll_result);
 4020:     }
 4021:     return;
 4022: }
 4023: 
 4024: sub get_defaultquota_text {
 4025:     my ($settingstatus) = @_;
 4026:     my $defquotatext; 
 4027:     if ($settingstatus eq '') {
 4028:         $defquotatext = &mt('default');
 4029:     } else {
 4030:         my ($usertypes,$order) =
 4031:             &Apache::lonnet::retrieve_inst_usertypes($env{'form.ccdomain'});
 4032:         if ($usertypes->{$settingstatus} eq '') {
 4033:             $defquotatext = &mt('default');
 4034:         } else {
 4035:             $defquotatext = &mt('default for [_1]',$usertypes->{$settingstatus});
 4036:         }
 4037:     }
 4038:     return $defquotatext;
 4039: }
 4040: 
 4041: sub update_result_form {
 4042:     my ($uhome) = @_;
 4043:     my $outcome = 
 4044:     '<form name="userupdate" method="post" action="">'."\n";
 4045:     foreach my $item ('srchby','srchin','srchtype','srchterm','srchdomain','ccuname','ccdomain') {
 4046:         $outcome .= '<input type="hidden" name="'.$item.'" value="'.$env{'form.'.$item}.'" />'."\n";
 4047:     }
 4048:     if ($env{'form.origname'} ne '') {
 4049:         $outcome .= '<input type="hidden" name="origname" value="'.$env{'form.origname'}.'" />'."\n";
 4050:     }
 4051:     foreach my $item ('sortby','seluname','seludom') {
 4052:         if (exists($env{'form.'.$item})) {
 4053:             $outcome .= '<input type="hidden" name="'.$item.'" value="'.$env{'form.'.$item}.'" />'."\n";
 4054:         }
 4055:     }
 4056:     if ($uhome eq 'no_host') {
 4057:         $outcome .= '<input type="hidden" name="forcenewuser" value="1" />'."\n";
 4058:     }
 4059:     $outcome .= '<input type="hidden" name="phase" value="" />'."\n".
 4060:                 '<input type="hidden" name="currstate" value="" />'."\n".
 4061:                 '<input type="hidden" name="action" value="'.$env{'form.action'}.'" />'."\n".
 4062:                 '</form>';
 4063:     return $outcome;
 4064: }
 4065: 
 4066: sub quota_admin {
 4067:     my ($setquota,$changeHash,$name) = @_;
 4068:     my $quotachanged;
 4069:     if (&Apache::lonnet::allowed('mpq',$env{'form.ccdomain'})) {
 4070:         # Current user has quota modification privileges
 4071:         if (ref($changeHash) eq 'HASH') {
 4072:             $quotachanged = 1;
 4073:             $changeHash->{$name.'quota'} = $setquota;
 4074:         }
 4075:     }
 4076:     return $quotachanged;
 4077: }
 4078: 
 4079: sub tool_admin {
 4080:     my ($tool,$settool,$changeHash,$context) = @_;
 4081:     my $canchange = 0; 
 4082:     if ($context eq 'requestcourses') {
 4083:         if (&Apache::lonnet::allowed('ccc',$env{'form.ccdomain'})) {
 4084:             $canchange = 1;
 4085:         }
 4086:     } elsif ($context eq 'reqcrsotherdom') {
 4087:         if (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) {
 4088:             $canchange = 1;
 4089:         }
 4090:     } elsif ($context eq 'requestauthor') {
 4091:         if (&Apache::lonnet::allowed('cau',$env{'request.role.domain'})) {
 4092:             $canchange = 1;
 4093:         }
 4094:     } elsif (&Apache::lonnet::allowed('mut',$env{'form.ccdomain'})) {
 4095:         # Current user has quota modification privileges
 4096:         $canchange = 1;
 4097:     }
 4098:     my $toolchanged;
 4099:     if ($canchange) {
 4100:         if (ref($changeHash) eq 'HASH') {
 4101:             $toolchanged = 1;
 4102:             if ($tool eq 'requestauthor') {
 4103:                 $changeHash->{$context} = $settool;
 4104:             } else {
 4105:                 $changeHash->{$context.'.'.$tool} = $settool;
 4106:             }
 4107:         }
 4108:     }
 4109:     return $toolchanged;
 4110: }
 4111: 
 4112: sub build_roles {
 4113:     my ($sectionstr,$sections,$role) = @_;
 4114:     my $num_sections = 0;
 4115:     if ($sectionstr=~ /,/) {
 4116:         my @secnums = split/,/,$sectionstr;
 4117:         if ($role eq 'st') {
 4118:             $secnums[0] =~ s/\W//g;
 4119:             $$sections{$secnums[0]} = 1;
 4120:             $num_sections = 1;
 4121:         } else {
 4122:             foreach my $sec (@secnums) {
 4123:                 $sec =~ ~s/\W//g;
 4124:                 if (!($sec eq "")) {
 4125:                     if (exists($$sections{$sec})) {
 4126:                         $$sections{$sec} ++;
 4127:                     } else {
 4128:                         $$sections{$sec} = 1;
 4129:                         $num_sections ++;
 4130:                     }
 4131:                 }
 4132:             }
 4133:         }
 4134:     } else {
 4135:         $sectionstr=~s/\W//g;
 4136:         unless ($sectionstr eq '') {
 4137:             $$sections{$sectionstr} = 1;
 4138:             $num_sections ++;
 4139:         }
 4140:     }
 4141: 
 4142:     return $num_sections;
 4143: }
 4144: 
 4145: # ========================================================== Custom Role Editor
 4146: 
 4147: sub custom_role_editor {
 4148:     my ($r,$brcrum) = @_;
 4149:     my $action = $env{'form.customroleaction'};
 4150:     my $rolename; 
 4151:     if ($action eq 'new') {
 4152:         $rolename=$env{'form.newrolename'};
 4153:     } else {
 4154:         $rolename=$env{'form.rolename'};
 4155:     }
 4156: 
 4157:     my ($crstype,$context);
 4158:     if ($env{'request.course.id'}) {
 4159:         $crstype = &Apache::loncommon::course_type();
 4160:         $context = 'course';
 4161:     } else {
 4162:         $context = 'domain';
 4163:         $crstype = $env{'form.templatecrstype'};
 4164:     }
 4165: 
 4166:     $rolename=~s/[^A-Za-z0-9]//gs;
 4167:     if (!$rolename || $env{'form.phase'} eq 'pickrole') {
 4168: 	&print_username_entry_form($r,undef,undef,undef,undef,$crstype,$brcrum);
 4169:         return;
 4170:     }
 4171: 
 4172: # ------------------------------------------------------- What can be assigned?
 4173:     my %full=();
 4174:     my %courselevel=();
 4175:     my %courselevelcurrent=();
 4176:     my $syspriv='';
 4177:     my $dompriv='';
 4178:     my $coursepriv='';
 4179:     my $body_top;
 4180:     my ($rdummy,$roledef)=
 4181: 			 &Apache::lonnet::get('roles',["rolesdef_$rolename"]);
 4182: # ------------------------------------------------------- Does this role exist?
 4183:     $body_top .= '<h2>';
 4184:     if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 4185: 	$body_top .= &mt('Existing Role').' "';
 4186: # ------------------------------------------------- Get current role privileges
 4187: 	($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 4188:         if ($crstype eq 'Community') {
 4189:             $syspriv =~ s/bre\&S//;   
 4190:         }
 4191:     } else {
 4192: 	$body_top .= &mt('New Role').' "';
 4193: 	$roledef='';
 4194:     }
 4195:     $body_top .= $rolename.'"</h2>';
 4196:     foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
 4197: 	my ($priv,$restrict)=split(/\&/,$item);
 4198:         if (!$restrict) { $restrict='F'; }
 4199:         $courselevel{$priv}=$restrict;
 4200:         if ($coursepriv=~/\:$priv/) {
 4201: 	    $courselevelcurrent{$priv}=1;
 4202: 	}
 4203: 	$full{$priv}=1;
 4204:     }
 4205:     my %domainlevel=();
 4206:     my %domainlevelcurrent=();
 4207:     foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:d'})) {
 4208: 	my ($priv,$restrict)=split(/\&/,$item);
 4209:         if (!$restrict) { $restrict='F'; }
 4210:         $domainlevel{$priv}=$restrict;
 4211:         if ($dompriv=~/\:$priv/) {
 4212: 	    $domainlevelcurrent{$priv}=1;
 4213: 	}
 4214: 	$full{$priv}=1;
 4215:     }
 4216:     my %systemlevel=();
 4217:     my %systemlevelcurrent=();
 4218:     foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:s'})) {
 4219: 	my ($priv,$restrict)=split(/\&/,$item);
 4220:         if (!$restrict) { $restrict='F'; }
 4221:         $systemlevel{$priv}=$restrict;
 4222:         if ($syspriv=~/\:$priv/) {
 4223: 	    $systemlevelcurrent{$priv}=1;
 4224: 	}
 4225: 	$full{$priv}=1;
 4226:     }
 4227:     my ($jsback,$elements) = &crumb_utilities();
 4228:     my $button_code = "\n";
 4229:     my $head_script = "\n";
 4230:     $head_script .= '<script type="text/javascript">'."\n"
 4231:                    .'// <![CDATA['."\n";
 4232:     my @template_roles = ("in","ta","ep");
 4233:     if ($context eq 'domain') {
 4234:         push(@template_roles,"ad");
 4235:     }
 4236:     push(@template_roles,"st");
 4237:     if ($crstype eq 'Community') {
 4238:         unshift(@template_roles,'co');
 4239:     } else {
 4240:         unshift(@template_roles,'cc');
 4241:     }
 4242:     foreach my $role (@template_roles) {
 4243:         $head_script .= &make_script_template($role,$crstype);
 4244:         $button_code .= &make_button_code($role,$crstype).' ';
 4245:     }
 4246:     my $context_code;
 4247:     if ($context eq 'domain') {
 4248:         my $checkedCommunity = '';
 4249:         my $checkedCourse = ' checked="checked"';
 4250:         if ($env{'form.templatecrstype'} eq 'Community') {
 4251:             $checkedCommunity = $checkedCourse;
 4252:             $checkedCourse = '';
 4253:         }
 4254:         $context_code = '<label>'.
 4255:                         '<input type="radio" name="templatecrstype" value="Course"'.$checkedCourse.' onclick="this.form.submit();">'.
 4256:                         &mt('Course').
 4257:                         '</label>'.('&nbsp;' x2).
 4258:                         '<label>'.
 4259:                         '<input type="radio" name="templatecrstype" value="Community"'.$checkedCommunity.' onclick="this.form.submit();">'.
 4260:                         &mt('Community').
 4261:                         '</label>'.
 4262:                         '</fieldset>'.
 4263:                         '<input type="hidden" name="customroleaction" value="'.
 4264:                         $action.'" />';
 4265:         if ($env{'form.customroleaction'} eq 'new') {
 4266:             $context_code .= '<input type="hidden" name="newrolename" value="'.
 4267:                              $rolename.'" />';
 4268:         } else {
 4269:             $context_code .= '<input type="hidden" name="rolename" value="'.
 4270:                              $rolename.'" />';
 4271:         }
 4272:         $context_code .= '<input type="hidden" name="action" value="custom" />'.
 4273:                          '<input type="hidden" name="phase" value="selected_custom_edit" />';
 4274:     }
 4275: 
 4276:     $head_script .= "\n".$jsback."\n"
 4277:                    .'// ]]>'."\n"
 4278:                    .'</script>'."\n";
 4279:     push (@{$brcrum},
 4280:               {href => "javascript:backPage(document.form1,'pickrole','')",
 4281:                text => "Pick custom role",
 4282:                faq  => 282,bug=>'Instructor Interface',},
 4283:               {href => "javascript:backPage(document.form1,'','')",
 4284:                text => "Edit custom role",
 4285:                faq  => 282,
 4286:                bug  => 'Instructor Interface',
 4287:                help => 'Course_Editing_Custom_Roles'}
 4288:               );
 4289:     my $args = { bread_crumbs          => $brcrum,
 4290:                  bread_crumbs_component => 'User Management'};
 4291:  
 4292:     $r->print(&Apache::loncommon::start_page('Custom Role Editor',
 4293:                                              $head_script,$args).
 4294:               $body_top);
 4295:     my %lt=&Apache::lonlocal::texthash(
 4296: 		    'prv'  => "Privilege",
 4297: 		    'crl'  => "Course Level",
 4298:                     'dml'  => "Domain Level",
 4299:                     'ssl'  => "System Level");
 4300: 
 4301:     $r->print('<div class="LC_left_float">'
 4302:              .'<form action=""><fieldset>'
 4303:              .'<legend>'.&mt('Select a Template').'</legend>'
 4304:              .$button_code
 4305:              .'</fieldset></form></div>');
 4306:     if ($context_code) {
 4307:         $r->print('<div class="LC_left_float">'
 4308:                  .'<form action="/adm/createuser" method="post"><fieldset>'
 4309:                  .'<legend>'.&mt('Context').'</legend>'
 4310:                  .$context_code
 4311:                  .'</form>'
 4312:                  .'</div>'
 4313:         );
 4314:     }
 4315:     $r->print('<br clear="all" />');
 4316: 
 4317:     $r->print(<<ENDCCF);
 4318: <form name="form1" method="post" action="">
 4319: <input type="hidden" name="phase" value="set_custom_roles" />
 4320: <input type="hidden" name="rolename" value="$rolename" />
 4321: ENDCCF
 4322:     $r->print(&Apache::loncommon::start_data_table().
 4323:               &Apache::loncommon::start_data_table_header_row(). 
 4324: '<th>'.$lt{'prv'}.'</th><th>'.$lt{'crl'}.'</th><th>'.$lt{'dml'}.
 4325: '</th><th>'.$lt{'ssl'}.'</th>'.
 4326:               &Apache::loncommon::end_data_table_header_row());
 4327:     foreach my $priv (sort(keys(%full))) {
 4328:         my $privtext = &Apache::lonnet::plaintext($priv,$crstype);
 4329:         $r->print(&Apache::loncommon::start_data_table_row().
 4330: 	          '<td>'.$privtext.'</td><td>'.
 4331:     ($courselevel{$priv}?'<input type="checkbox" name="'.$priv.'_c"'.
 4332:     ($courselevelcurrent{$priv}?' checked="checked"':'').' />':'&nbsp;').
 4333:     '</td><td>'.
 4334:     ($domainlevel{$priv}?'<input type="checkbox" name="'.$priv.'_d"'.
 4335:     ($domainlevelcurrent{$priv}?' checked="checked"':'').' />':'&nbsp;').
 4336:     '</td><td>');
 4337:         if ($priv eq 'bre' && $crstype eq 'Community') {
 4338:             $r->print('&nbsp;');  
 4339:         } else {
 4340:             $r->print($systemlevel{$priv}?'<input type="checkbox" name="'.$priv.'_s"'.
 4341:                       ($systemlevelcurrent{$priv}?' checked="checked"':'').' />':'&nbsp;');
 4342:         }
 4343:         $r->print('</td>'.
 4344:                   &Apache::loncommon::end_data_table_row());
 4345:     }
 4346:     $r->print(&Apache::loncommon::end_data_table().
 4347:    '<input type="hidden" name="action" value="'.$env{'form.action'}.'" />'.
 4348:    '<input type="hidden" name="startrolename" value="'.$env{'form.rolename'}.
 4349:    '" />'."\n".'<input type="hidden" name="currstate" value="" />'."\n".   
 4350:    '<input type="reset" value="'.&mt("Reset").'" />'."\n".
 4351:    '<input type="submit" value="'.&mt('Save').'" /></form>');
 4352: }
 4353: # --------------------------------------------------------
 4354: sub make_script_template {
 4355:     my ($role,$crstype) = @_;
 4356:     my %full_c=();
 4357:     my %full_d=();
 4358:     my %full_s=();
 4359:     my $return_script;
 4360:     foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
 4361:         my ($priv,$restrict)=split(/\&/,$item);
 4362:         $full_c{$priv}=1;
 4363:     }
 4364:     foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:d'})) {
 4365:         my ($priv,$restrict)=split(/\&/,$item);
 4366:         $full_d{$priv}=1;
 4367:     }
 4368:     foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:s'})) {
 4369:         next if (($crstype eq 'Community') && ($item eq 'bre&S'));
 4370:         my ($priv,$restrict)=split(/\&/,$item);
 4371:         $full_s{$priv}=1;
 4372:     }
 4373:     $return_script .= 'function set_'.$role.'() {'."\n";
 4374:     my @temp = split(/:/,$Apache::lonnet::pr{$role.':c'});
 4375:     my %role_c;
 4376:     foreach my $priv (@temp) {
 4377:         my ($priv_item, $dummy) = split(/\&/,$priv);
 4378:         $role_c{$priv_item} = 1;
 4379:     }
 4380:     my %role_d;
 4381:     @temp = split(/:/,$Apache::lonnet::pr{$role.':d'});
 4382:     foreach my $priv(@temp) {
 4383:         my ($priv_item, $dummy) = split(/\&/,$priv);
 4384:         $role_d{$priv_item} = 1;
 4385:     }
 4386:     my %role_s;
 4387:     @temp = split(/:/,$Apache::lonnet::pr{$role.':s'});
 4388:     foreach my $priv(@temp) {
 4389:         my ($priv_item, $dummy) = split(/\&/,$priv);
 4390:         $role_s{$priv_item} = 1;
 4391:     }
 4392:     foreach my $priv_item (keys(%full_c)) {
 4393:         my ($priv, $dummy) = split(/\&/,$priv_item);
 4394:         if ((exists($role_c{$priv})) || (exists($role_d{$priv})) || 
 4395:             (exists($role_s{$priv}))) {
 4396:             $return_script .= "document.form1.$priv"."_c.checked = true;\n";
 4397:         } else {
 4398:             $return_script .= "document.form1.$priv"."_c.checked = false;\n";
 4399:         }
 4400:     }
 4401:     foreach my $priv_item (keys(%full_d)) {
 4402:         my ($priv, $dummy) = split(/\&/,$priv_item);
 4403:         if ((exists($role_d{$priv})) || (exists($role_s{$priv}))) {
 4404:             $return_script .= "document.form1.$priv"."_d.checked = true;\n";
 4405:         } else {
 4406:             $return_script .= "document.form1.$priv"."_d.checked = false;\n";
 4407:         }
 4408:     }
 4409:     foreach my $priv_item (keys(%full_s)) {
 4410:         my ($priv, $dummy) = split(/\&/,$priv_item);
 4411:         if (exists($role_s{$priv})) {
 4412:             $return_script .= "document.form1.$priv"."_s.checked = true;\n";
 4413:         } else {
 4414:             $return_script .= "document.form1.$priv"."_s.checked = false;\n";
 4415:         }
 4416:     }
 4417:     $return_script .= '}'."\n";
 4418:     return ($return_script);
 4419: }
 4420: # ----------------------------------------------------------
 4421: sub make_button_code {
 4422:     my ($role,$crstype) = @_;
 4423:     my $label = &Apache::lonnet::plaintext($role,$crstype);
 4424:     my $button_code = '<input type="button" onclick="set_'.$role.'()" value="'.$label.'" />';
 4425:     return ($button_code);
 4426: }
 4427: # ---------------------------------------------------------- Call to definerole
 4428: sub set_custom_role {
 4429:     my ($r,$context,$brcrum) = @_;
 4430:     my $rolename=$env{'form.rolename'};
 4431:     $rolename=~s/[^A-Za-z0-9]//gs;
 4432:     if (!$rolename) {
 4433: 	&custom_role_editor($r,$brcrum);
 4434:         return;
 4435:     }
 4436:     my ($jsback,$elements) = &crumb_utilities();
 4437:     my $jscript = '<script type="text/javascript">'
 4438:                  .'// <![CDATA['."\n"
 4439:                  .$jsback."\n"
 4440:                  .'// ]]>'."\n"
 4441:                  .'</script>'."\n";
 4442:     push(@{$brcrum},
 4443:         {href => "javascript:backPage(document.customresult,'pickrole','')",
 4444:          text => "Pick custom role",
 4445:          faq  => 282,
 4446:          bug  => 'Instructor Interface',},
 4447:         {href => "javascript:backPage(document.customresult,'selected_custom_edit','')",
 4448:          text => "Edit custom role",
 4449:          faq  => 282,
 4450:          bug  => 'Instructor Interface',},
 4451:         {href => "javascript:backPage(document.customresult,'set_custom_roles','')",
 4452:          text => "Result",
 4453:          faq  => 282,
 4454:          bug  => 'Instructor Interface',
 4455:          help => 'Course_Editing_Custom_Roles'},
 4456:         );
 4457:     my $args = { bread_crumbs           => $brcrum,
 4458:                  bread_crumbs_component => 'User Management'}; 
 4459:     $r->print(&Apache::loncommon::start_page('Save Custom Role',$jscript,$args));
 4460: 
 4461:     my ($rdummy,$roledef)=
 4462: 	&Apache::lonnet::get('roles',["rolesdef_$rolename"]);
 4463: 
 4464: # ------------------------------------------------------- Does this role exist?
 4465:     $r->print('<h3>');
 4466:     if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 4467: 	$r->print(&mt('Existing Role').' "');
 4468:     } else {
 4469: 	$r->print(&mt('New Role').' "');
 4470: 	$roledef='';
 4471:     }
 4472:     $r->print($rolename.'"</h3>');
 4473: # ------------------------------------------------------- What can be assigned?
 4474:     my $sysrole='';
 4475:     my $domrole='';
 4476:     my $courole='';
 4477: 
 4478:     foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
 4479: 	my ($priv,$restrict)=split(/\&/,$item);
 4480:         if (!$restrict) { $restrict=''; }
 4481:         if ($env{'form.'.$priv.'_c'}) {
 4482: 	    $courole.=':'.$item;
 4483: 	}
 4484:     }
 4485: 
 4486:     foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:d'})) {
 4487: 	my ($priv,$restrict)=split(/\&/,$item);
 4488:         if (!$restrict) { $restrict=''; }
 4489:         if ($env{'form.'.$priv.'_d'}) {
 4490: 	    $domrole.=':'.$item;
 4491: 	}
 4492:     }
 4493: 
 4494:     foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:s'})) {
 4495: 	my ($priv,$restrict)=split(/\&/,$item);
 4496:         if (!$restrict) { $restrict=''; }
 4497:         if ($env{'form.'.$priv.'_s'}) {
 4498: 	    $sysrole.=':'.$item;
 4499: 	}
 4500:     }
 4501:     # Assign role; Compile and show result
 4502:     my $errmsg;
 4503:     my $result =
 4504:         &Apache::lonnet::definerole($rolename,$sysrole,$domrole,$courole);
 4505:     if ($result ne 'ok') {
 4506:         $errmsg = ': '.$result;
 4507:     }
 4508:     my $message =
 4509:         &Apache::lonhtmlcommon::confirm_success(
 4510:             &mt('Defining Role').$errmsg, ($result eq 'ok' ? 0 : 1));
 4511:     if ($env{'request.course.id'}) {
 4512:         my $url='/'.$env{'request.course.id'};
 4513:         $url=~s/\_/\//g;
 4514:         $result =
 4515:             &Apache::lonnet::assigncustomrole(
 4516:                 $env{'user.domain'},$env{'user.name'},
 4517:                 $url,
 4518:                 $env{'user.domain'},$env{'user.name'},
 4519:                 $rolename,undef,undef,undef,$context);
 4520:         if ($result ne 'ok') {
 4521:             $errmsg = ': '.$result;
 4522:         }
 4523:         $message .=
 4524:             '<br />'
 4525:            .&Apache::lonhtmlcommon::confirm_success(
 4526:                 &mt('Assigning Role to Self').$errmsg, ($result eq 'ok' ? 0 : 1));
 4527:     }
 4528:     $r->print(
 4529:         &Apache::loncommon::confirmwrapper($message)
 4530:        .'<br />'
 4531:        .&Apache::lonhtmlcommon::actionbox([
 4532:             '<a href="javascript:backPage(document.customresult,'."'pickrole'".')">'
 4533:            .&mt('Create or edit another custom role')
 4534:            .'</a>'])
 4535:        .'<form name="customresult" method="post" action="">'
 4536:        .&Apache::lonhtmlcommon::echo_form_input([])
 4537:        .'</form>'
 4538:     );
 4539: }
 4540: 
 4541: # ================================================================ Main Handler
 4542: sub handler {
 4543:     my $r = shift;
 4544:     if ($r->header_only) {
 4545:        &Apache::loncommon::content_type($r,'text/html');
 4546:        $r->send_http_header;
 4547:        return OK;
 4548:     }
 4549:     my ($context,$crstype);
 4550:     if ($env{'request.course.id'}) {
 4551:         $context = 'course';
 4552:         $crstype = &Apache::loncommon::course_type();
 4553:     } elsif ($env{'request.role'} =~ /^au\./) {
 4554:         $context = 'author';
 4555:     } else {
 4556:         $context = 'domain';
 4557:     }
 4558: 
 4559:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 4560:         ['action','state','callingform','roletype','showrole','bulkaction','popup','phase',
 4561:          'username','domain','srchterm','srchdomain','srchin','srchby','srchtype','queue']);
 4562:     &Apache::lonhtmlcommon::clear_breadcrumbs();
 4563:     my $args;
 4564:     my $brcrum = [];
 4565:     my $bread_crumbs_component = 'User Management';
 4566:     if (($env{'form.action'} ne 'dateselect') && ($env{'form.action'} ne 'displayuserreq')) {
 4567:         $brcrum = [{href=>"/adm/createuser",
 4568:                     text=>"User Management",
 4569:                     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'}
 4570:                   ];
 4571:     }
 4572:     #SD Following files not added to help, because the corresponding .tex-files seem to
 4573:     #be missing: Course_Approve_Selfenroll,Course_User_Logs,
 4574:     my ($permission,$allowed) = 
 4575:         &Apache::lonuserutils::get_permission($context,$crstype);
 4576:     if (!$allowed) {
 4577:         if ($context eq 'course') {
 4578:             $r->internal_redirect('/adm/viewclasslist');
 4579:             return OK;
 4580:         }
 4581:         $env{'user.error.msg'}=
 4582:             "/adm/createuser:cst:0:0:Cannot create/modify user data ".
 4583:                                  "or view user status.";
 4584:         return HTTP_NOT_ACCEPTABLE;
 4585:     }
 4586: 
 4587:     &Apache::loncommon::content_type($r,'text/html');
 4588:     $r->send_http_header;
 4589: 
 4590:     my $showcredits;
 4591:     if ((($context eq 'course') && ($crstype eq 'Course')) || 
 4592:          ($context eq 'domain')) {
 4593:         my %domdefaults = 
 4594:             &Apache::lonnet::get_domain_defaults($env{'request.role.domain'});
 4595:         if ($domdefaults{'officialcredits'} || $domdefaults{'unofficialcredits'}) {
 4596:             $showcredits = 1;
 4597:         }
 4598:     }
 4599: 
 4600:     # Main switch on form.action and form.state, as appropriate
 4601:     if (! exists($env{'form.action'})) {
 4602:         $args = {bread_crumbs => $brcrum,
 4603:                  bread_crumbs_component => $bread_crumbs_component}; 
 4604:         $r->print(&header(undef,$args));
 4605:         $r->print(&print_main_menu($permission,$context,$crstype));
 4606:     } elsif ($env{'form.action'} eq 'upload' && $permission->{'cusr'}) {
 4607:         push(@{$brcrum},
 4608:               { href => '/adm/createuser?action=upload&state=',
 4609:                 text => 'Upload Users List',
 4610:                 help => 'Course_Create_Class_List',
 4611:               });
 4612:         $bread_crumbs_component = 'Upload Users List';
 4613:         $args = {bread_crumbs           => $brcrum,
 4614:                  bread_crumbs_component => $bread_crumbs_component};
 4615:         $r->print(&header(undef,$args));
 4616:         $r->print('<form name="studentform" method="post" '.
 4617:                   'enctype="multipart/form-data" '.
 4618:                   ' action="/adm/createuser">'."\n");
 4619:         if (! exists($env{'form.state'})) {
 4620:             &Apache::lonuserutils::print_first_users_upload_form($r,$context);
 4621:         } elsif ($env{'form.state'} eq 'got_file') {
 4622:             &Apache::lonuserutils::print_upload_manager_form($r,$context,$permission,
 4623:                                                              $crstype,$showcredits);
 4624:         } elsif ($env{'form.state'} eq 'enrolling') {
 4625:             if ($env{'form.datatoken'}) {
 4626:                 &Apache::lonuserutils::upfile_drop_add($r,$context,$permission,
 4627:                                                        $showcredits);
 4628:             }
 4629:         } else {
 4630:             &Apache::lonuserutils::print_first_users_upload_form($r,$context);
 4631:         }
 4632:     } elsif ((($env{'form.action'} eq 'singleuser') || ($env{'form.action'}
 4633:              eq 'singlestudent')) && ($permission->{'cusr'})) {
 4634:         my $phase = $env{'form.phase'};
 4635:         my @search = ('srchterm','srchby','srchin','srchtype','srchdomain');
 4636: 	&Apache::loncreateuser::restore_prev_selections();
 4637: 	my $srch;
 4638: 	foreach my $item (@search) {
 4639: 	    $srch->{$item} = $env{'form.'.$item};
 4640: 	}
 4641:         if (($phase eq 'get_user_info') || ($phase eq 'userpicked') ||
 4642:             ($phase eq 'createnewuser')) {
 4643:             if ($env{'form.phase'} eq 'createnewuser') {
 4644:                 my $response;
 4645:                 if ($env{'form.srchterm'} !~ /^$match_username$/) {
 4646:                     my $response =
 4647:                         '<span class="LC_warning">'
 4648:                        .&mt('You must specify a valid username. Only the following are allowed:'
 4649:                            .' letters numbers - . @')
 4650:                        .'</span>';
 4651:                     $env{'form.phase'} = '';
 4652:                     &print_username_entry_form($r,$context,$response,$srch,undef,
 4653:                                                $crstype,$brcrum,$showcredits);
 4654:                 } else {
 4655:                     my $ccuname =&LONCAPA::clean_username($srch->{'srchterm'});
 4656:                     my $ccdomain=&LONCAPA::clean_domain($srch->{'srchdomain'});
 4657:                     &print_user_modification_page($r,$ccuname,$ccdomain,
 4658:                                                   $srch,$response,$context,
 4659:                                                   $permission,$crstype,$brcrum,
 4660:                                                   $showcredits);
 4661:                 }
 4662:             } elsif ($env{'form.phase'} eq 'get_user_info') {
 4663:                 my ($currstate,$response,$forcenewuser,$results) = 
 4664:                     &user_search_result($context,$srch);
 4665:                 if ($env{'form.currstate'} eq 'modify') {
 4666:                     $currstate = $env{'form.currstate'};
 4667:                 }
 4668:                 if ($currstate eq 'select') {
 4669:                     &print_user_selection_page($r,$response,$srch,$results,
 4670:                                                \@search,$context,undef,$crstype,
 4671:                                                $brcrum);
 4672:                 } elsif ($currstate eq 'modify') {
 4673:                     my ($ccuname,$ccdomain);
 4674:                     if (($srch->{'srchby'} eq 'uname') && 
 4675:                         ($srch->{'srchtype'} eq 'exact')) {
 4676:                         $ccuname = $srch->{'srchterm'};
 4677:                         $ccdomain= $srch->{'srchdomain'};
 4678:                     } else {
 4679:                         my @matchedunames = keys(%{$results});
 4680:                         ($ccuname,$ccdomain) = split(/:/,$matchedunames[0]);
 4681:                     }
 4682:                     $ccuname =&LONCAPA::clean_username($ccuname);
 4683:                     $ccdomain=&LONCAPA::clean_domain($ccdomain);
 4684:                     if ($env{'form.forcenewuser'}) {
 4685:                         $response = '';
 4686:                     }
 4687:                     &print_user_modification_page($r,$ccuname,$ccdomain,
 4688:                                                   $srch,$response,$context,
 4689:                                                   $permission,$crstype,$brcrum);
 4690:                 } elsif ($currstate eq 'query') {
 4691:                     &print_user_query_page($r,'createuser',$brcrum);
 4692:                 } else {
 4693:                     $env{'form.phase'} = '';
 4694:                     &print_username_entry_form($r,$context,$response,$srch,
 4695:                                                $forcenewuser,$crstype,$brcrum);
 4696:                 }
 4697:             } elsif ($env{'form.phase'} eq 'userpicked') {
 4698:                 my $ccuname = &LONCAPA::clean_username($env{'form.seluname'});
 4699:                 my $ccdomain = &LONCAPA::clean_domain($env{'form.seludom'});
 4700:                 &print_user_modification_page($r,$ccuname,$ccdomain,$srch,'',
 4701:                                               $context,$permission,$crstype,
 4702:                                               $brcrum);
 4703:             }
 4704:         } elsif ($env{'form.phase'} eq 'update_user_data') {
 4705:             &update_user_data($r,$context,$crstype,$brcrum,$showcredits);
 4706:         } else {
 4707:             &print_username_entry_form($r,$context,undef,$srch,undef,$crstype,
 4708:                                        $brcrum);
 4709:         }
 4710:     } elsif ($env{'form.action'} eq 'custom' && $permission->{'custom'}) {
 4711:         if ($env{'form.phase'} eq 'set_custom_roles') {
 4712:             &set_custom_role($r,$context,$brcrum);
 4713:         } else {
 4714:             &custom_role_editor($r,$brcrum);
 4715:         }
 4716:     } elsif (($env{'form.action'} eq 'processauthorreq') &&
 4717:              ($permission->{'cusr'}) && 
 4718:              (&Apache::lonnet::allowed('cau',$env{'request.role.domain'}))) {
 4719:         push(@{$brcrum},
 4720:                  {href => '/adm/createuser?action=processauthorreq',
 4721:                   text => 'Authoring Space requests',
 4722:                   help => 'Domain_Role_Approvals'});
 4723:         $bread_crumbs_component = 'Authoring requests';
 4724:         if ($env{'form.state'} eq 'done') {
 4725:             push(@{$brcrum},
 4726:                      {href => '/adm/createuser?action=authorreqqueue',
 4727:                       text => 'Result',
 4728:                       help => 'Domain_Role_Approvals'});
 4729:             $bread_crumbs_component = 'Authoring request result';
 4730:         }
 4731:         $args = { bread_crumbs           => $brcrum,
 4732:                   bread_crumbs_component => $bread_crumbs_component};
 4733:         my $js = &usernamerequest_javascript();
 4734:         $r->print(&header(&add_script($js),$args));
 4735:         if (!exists($env{'form.state'})) {
 4736:             $r->print(&Apache::loncoursequeueadmin::display_queued_requests('requestauthor',
 4737:                                                                             $env{'request.role.domain'}));
 4738:         } elsif ($env{'form.state'} eq 'done') {
 4739:             $r->print('<h3>'.&mt('Authoring request processing').'</h3>'."\n");
 4740:             $r->print(&Apache::loncoursequeueadmin::update_request_queue('requestauthor',
 4741:                                                                          $env{'request.role.domain'}));
 4742:         }
 4743:     } elsif (($env{'form.action'} eq 'processusernamereq') &&
 4744:              ($permission->{'cusr'}) &&
 4745:              (&Apache::lonnet::allowed('cau',$env{'request.role.domain'}))) {
 4746:         push(@{$brcrum},
 4747:                  {href => '/adm/createuser?action=processusernamereq',
 4748:                   text => 'LON-CAPA account requests',
 4749:                   help => 'Domain_Username_Approvals'});
 4750:         $bread_crumbs_component = 'Account requests';
 4751:         if ($env{'form.state'} eq 'done') {
 4752:             push(@{$brcrum},
 4753:                      {href => '/adm/createuser?action=usernamereqqueue',
 4754:                       text => 'Result',
 4755:                       help => 'Domain_Username_Approvals'});
 4756:             $bread_crumbs_component = 'LON-CAPA account request result';
 4757:         }
 4758:         $args = { bread_crumbs           => $brcrum,
 4759:                   bread_crumbs_component => $bread_crumbs_component};
 4760:         my $js = &usernamerequest_javascript();
 4761:         $r->print(&header(&add_script($js),$args));
 4762:         if (!exists($env{'form.state'})) {
 4763:             $r->print(&Apache::loncoursequeueadmin::display_queued_requests('requestusername',
 4764:                                                                             $env{'request.role.domain'}));
 4765:         } elsif ($env{'form.state'} eq 'done') {
 4766:             $r->print('<h3>'.&mt('LON-CAPA account request processing').'</h3>'."\n");
 4767:             $r->print(&Apache::loncoursequeueadmin::update_request_queue('requestusername',
 4768:                                                                          $env{'request.role.domain'}));
 4769:         }
 4770:     } elsif (($env{'form.action'} eq 'displayuserreq') &&
 4771:              ($permission->{'cusr'})) {
 4772:         my $dom = $env{'form.domain'};
 4773:         my $uname = $env{'form.username'};
 4774:         my $warning;
 4775:         if (($dom =~ /^$match_domain$/) && (&Apache::lonnet::domain($dom) ne '')) {
 4776:             if (($dom eq $env{'request.role.domain'}) && (&Apache::lonnet::allowed('ccc',$dom))) {
 4777:                 if (($uname =~ /^$match_username$/) && ($env{'form.queue'} eq 'approval')) {
 4778:                     my $uhome = &Apache::lonnet::homeserver($uname,$dom);
 4779:                     if ($uhome eq 'no_host') {
 4780:                         my $queue = $env{'form.queue'};
 4781:                         my $reqkey = &escape($uname).'_'.$queue; 
 4782:                         my $namespace = 'usernamequeue';
 4783:                         my $domconfig = &Apache::lonnet::get_domainconfiguser($dom);
 4784:                         my %queued =
 4785:                             &Apache::lonnet::get($namespace,[$reqkey],$dom,$domconfig);
 4786:                         unless ($queued{$reqkey}) {
 4787:                             $warning = &mt('No information was found for this LON-CAPA account request.');
 4788:                         }
 4789:                     } else {
 4790:                         $warning = &mt('A LON-CAPA account already exists for the requested username and domain.');
 4791:                     }
 4792:                 } else {
 4793:                     $warning = &mt('LON-CAPA account request status check is for an invalid username.');
 4794:                 }
 4795:             } else {
 4796:                 $warning = &mt('You do not have rights to view LON-CAPA account requests in the domain specified.');
 4797:             }
 4798:         } else {
 4799:             $warning = &mt('LON-CAPA account request status check is for an invalid domain.');
 4800:         }
 4801:         my $args = { only_body => 1 };
 4802:         $r->print(&header(undef,$args).
 4803:                   '<h3>'.&mt('LON-CAPA Account Request Details').'</h3>');
 4804:         if ($warning ne '') {
 4805:             $r->print('<div class="LC_warning">'.$warning.'</div>');
 4806:         } else {
 4807:             my ($infofields,$infotitles) = &Apache::loncommon::emailusername_info();
 4808:             my $domconfiguser = &Apache::lonnet::get_domainconfiguser($dom);
 4809:             my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 4810:             if (ref($domconfig{'usercreation'}) eq 'HASH') {
 4811:                 if (ref($domconfig{'usercreation'}{'cancreate'}) eq 'HASH') {
 4812:                     if (ref($domconfig{'usercreation'}{'cancreate'}{'emailusername'}) eq 'HASH') {
 4813:                         my $count = scalar(keys(%{$domconfig{'usercreation'}{'cancreate'}{'emailusername'}}));
 4814:                         my %info =
 4815:                             &Apache::lonnet::get('nohist_requestedusernames',[$uname],$dom,$domconfiguser);
 4816:                         if (ref($info{$uname}) eq 'HASH') {
 4817:                             if ((ref($infofields) eq 'ARRAY') && (ref($infotitles) eq 'HASH')) {
 4818:                                 $r->print('<div>'.&Apache::lonhtmlcommon::start_pick_box());
 4819:                                 my $num;
 4820:                                 foreach my $field (@{$infofields}) {
 4821:                                     next unless ($domconfig{'usercreation'}{'cancreate'}{'emailusername'}{$field});
 4822:                                     next unless ($infotitles->{$field});
 4823:                                     $r->print(&Apache::lonhtmlcommon::row_title($infotitles->{$field}).
 4824:                                               $info{$uname}{$field});
 4825:                                     $num ++;
 4826:                                     if ($count == $num) {
 4827:                                         $r->print(&Apache::lonhtmlcommon::row_closure(1));
 4828:                                     } else {
 4829:                                         $r->print(&Apache::lonhtmlcommon::row_closure());
 4830:                                     }
 4831:                                 }
 4832:                                 $r->print(&Apache::lonhtmlcommon::end_pick_box().'</div>');
 4833:                             }
 4834:                         }
 4835:                     }
 4836:                 }
 4837:             }
 4838:             $r->print(&close_popup_form());
 4839:         }
 4840:     } elsif (($env{'form.action'} eq 'listusers') && 
 4841:              ($permission->{'view'} || $permission->{'cusr'})) {
 4842:         if ($env{'form.phase'} eq 'bulkchange') {
 4843:             push(@{$brcrum},
 4844:                     {href => '/adm/createuser?action=listusers',
 4845:                      text => "List Users"},
 4846:                     {href => "/adm/createuser",
 4847:                      text => "Result",
 4848:                      help => 'Course_View_Class_List'});
 4849:             $bread_crumbs_component = 'Update Users';
 4850:             $args = {bread_crumbs           => $brcrum,
 4851:                      bread_crumbs_component => $bread_crumbs_component};
 4852:             $r->print(&header(undef,$args));
 4853:             my $setting = $env{'form.roletype'};
 4854:             my $choice = $env{'form.bulkaction'};
 4855:             if ($permission->{'cusr'}) {
 4856:                 &Apache::lonuserutils::update_user_list($r,$context,$setting,$choice,$crstype);
 4857:             } else {
 4858:                 $r->print(&mt('You are not authorized to make bulk changes to user roles'));
 4859:                 $r->print('<p><a href="/adm/createuser?action=listusers">'.&mt('Display User Lists').'</a>');
 4860:             }
 4861:         } else {
 4862:             push(@{$brcrum},
 4863:                     {href => '/adm/createuser?action=listusers',
 4864:                      text => "List Users",
 4865:                      help => 'Course_View_Class_List'});
 4866:             $bread_crumbs_component = 'List Users';
 4867:             $args = {bread_crumbs           => $brcrum,
 4868:                      bread_crumbs_component => $bread_crumbs_component};
 4869:             my ($cb_jscript,$jscript,$totcodes,$codetitles,$idlist,$idlist_titles);
 4870:             my $formname = 'studentform';
 4871:             my $hidecall = "hide_searching();";
 4872:             if (($context eq 'domain') && (($env{'form.roletype'} eq 'course') ||
 4873:                 ($env{'form.roletype'} eq 'community'))) {
 4874:                 if ($env{'form.roletype'} eq 'course') {
 4875:                     ($cb_jscript,$jscript,$totcodes,$codetitles,$idlist,$idlist_titles) = 
 4876:                         &Apache::lonuserutils::courses_selector($env{'request.role.domain'},
 4877:                                                                 $formname);
 4878:                 } elsif ($env{'form.roletype'} eq 'community') {
 4879:                     $cb_jscript = 
 4880:                         &Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'});
 4881:                     my %elements = (
 4882:                                       coursepick => 'radio',
 4883:                                       coursetotal => 'text',
 4884:                                       courselist => 'text',
 4885:                                    );
 4886:                     $jscript = &Apache::lonhtmlcommon::set_form_elements(\%elements);
 4887:                 }
 4888:                 $jscript .= &verify_user_display($context)."\n".
 4889:                             &Apache::loncommon::check_uncheck_jscript();
 4890:                 my $js = &add_script($jscript).$cb_jscript;
 4891:                 my $loadcode = 
 4892:                     &Apache::lonuserutils::course_selector_loadcode($formname);
 4893:                 if ($loadcode ne '') {
 4894:                     $args->{add_entries} = {onload => "$loadcode;$hidecall"};
 4895:                 } else {
 4896:                     $args->{add_entries} = {onload => $hidecall};
 4897:                 }
 4898:                 $r->print(&header($js,$args));
 4899:             } else {
 4900:                 $args->{add_entries} = {onload => $hidecall};
 4901:                 $jscript = &verify_user_display($context).
 4902:                            &Apache::loncommon::check_uncheck_jscript(); 
 4903:                 $r->print(&header(&add_script($jscript),$args));
 4904:             }
 4905:             &Apache::lonuserutils::print_userlist($r,undef,$permission,$context,
 4906:                          $formname,$totcodes,$codetitles,$idlist,$idlist_titles,
 4907:                          $showcredits);
 4908:         }
 4909:     } elsif ($env{'form.action'} eq 'drop' && $permission->{'cusr'}) {
 4910:         my $brtext;
 4911:         if ($crstype eq 'Community') {
 4912:             $brtext = 'Drop Members';
 4913:         } else {
 4914:             $brtext = 'Drop Students';
 4915:         }
 4916:         push(@{$brcrum},
 4917:                 {href => '/adm/createuser?action=drop',
 4918:                  text => $brtext,
 4919:                  help => 'Course_Drop_Student'});
 4920:         if ($env{'form.state'} eq 'done') {
 4921:             push(@{$brcrum},
 4922:                      {href=>'/adm/createuser?action=drop',
 4923:                       text=>"Result"});
 4924:         }
 4925:         $bread_crumbs_component = $brtext;
 4926:         $args = {bread_crumbs           => $brcrum,
 4927:                  bread_crumbs_component => $bread_crumbs_component}; 
 4928:         $r->print(&header(undef,$args));
 4929:         if (!exists($env{'form.state'})) {
 4930:             &Apache::lonuserutils::print_drop_menu($r,$context,$permission,$crstype);
 4931:         } elsif ($env{'form.state'} eq 'done') {
 4932:             &Apache::lonuserutils::update_user_list($r,$context,undef,
 4933:                                                     $env{'form.action'});
 4934:         }
 4935:     } elsif ($env{'form.action'} eq 'dateselect') {
 4936:         if ($permission->{'cusr'}) {
 4937:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 4938:                       &Apache::lonuserutils::date_section_selector($context,$permission,
 4939:                                                                    $crstype,$showcredits));
 4940:         } else {
 4941:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 4942:                      '<span class="LC_error">'.&mt('You do not have permission to modify dates or sections for users').'</span>'); 
 4943:         }
 4944:     } elsif ($env{'form.action'} eq 'selfenroll') {
 4945:         push(@{$brcrum},
 4946:                 {href => '/adm/createuser?action=selfenroll',
 4947:                  text => "Configure Self-enrollment",
 4948:                  help => 'Course_Self_Enrollment'});
 4949:         if (!exists($env{'form.state'})) {
 4950:             $args = { bread_crumbs           => $brcrum,
 4951:                       bread_crumbs_component => 'Configure Self-enrollment'};
 4952:             $r->print(&header(undef,$args));
 4953:             $r->print('<h3>'.&mt('Self-enrollment with a student role').'</h3>'."\n");
 4954:             &print_selfenroll_menu($r,$context,$permission);
 4955:         } elsif ($env{'form.state'} eq 'done') {
 4956:             push (@{$brcrum},
 4957:                       {href=>'/adm/createuser?action=selfenroll',
 4958:                        text=>"Result"});
 4959:             $args = { bread_crumbs           => $brcrum,
 4960:                       bread_crumbs_component => 'Self-enrollment result'};
 4961:             $r->print(&header(undef,$args));
 4962:             $r->print('<h3>'.&mt('Self-enrollment with a student role').'</h3>'."\n");
 4963:             &update_selfenroll_config($r,$context,$permission);
 4964:         }
 4965:     } elsif ($env{'form.action'} eq 'selfenrollqueue') {
 4966:         push(@{$brcrum},
 4967:                  {href => '/adm/createuser?action=selfenrollqueue',
 4968:                   text => 'Enrollment requests',
 4969:                   help => 'Course_Self_Enrollment'});
 4970:         $bread_crumbs_component = 'Enrollment requests';
 4971:         if ($env{'form.state'} eq 'done') {
 4972:             push(@{$brcrum},
 4973:                      {href => '/adm/createuser?action=selfenrollqueue',
 4974:                       text => 'Result',
 4975:                       help => 'Course_Self_Enrollment'});
 4976:             $bread_crumbs_component = 'Enrollment result';
 4977:         }
 4978:         $args = { bread_crumbs           => $brcrum,
 4979:                   bread_crumbs_component => $bread_crumbs_component};
 4980:         $r->print(&header(undef,$args));
 4981:         my $cid = $env{'request.course.id'};
 4982:         my $cdom = $env{'course.'.$cid.'.domain'};
 4983:         my $cnum = $env{'course.'.$cid.'.num'};
 4984:         my $coursedesc = $env{'course.'.$cid.'.description'};
 4985:         if (!exists($env{'form.state'})) {
 4986:             $r->print('<h3>'.&mt('Pending enrollment requests').'</h3>'."\n");
 4987:             $r->print(&Apache::loncoursequeueadmin::display_queued_requests($context,
 4988:                                                                        $cdom,$cnum));
 4989:         } elsif ($env{'form.state'} eq 'done') {
 4990:             $r->print('<h3>'.&mt('Enrollment request processing').'</h3>'."\n");
 4991:             $r->print(&Apache::loncoursequeueadmin::update_request_queue($context,
 4992:                           $cdom,$cnum,$coursedesc));
 4993:         }
 4994:     } elsif ($env{'form.action'} eq 'changelogs') {
 4995:         my $helpitem;
 4996:         if ($context eq 'course') {
 4997:             $helpitem = 'Course_User_Logs';
 4998:         }
 4999:         push (@{$brcrum},
 5000:                  {href => '/adm/createuser?action=changelogs',
 5001:                   text => 'User Management Logs',
 5002:                   help => $helpitem});
 5003:         $bread_crumbs_component = 'User Changes';
 5004:         $args = { bread_crumbs           => $brcrum,
 5005:                   bread_crumbs_component => $bread_crumbs_component};
 5006:         $r->print(&header(undef,$args));
 5007:         &print_userchangelogs_display($r,$context,$permission);
 5008:     } else {
 5009:         $bread_crumbs_component = 'User Management';
 5010:         $args = { bread_crumbs           => $brcrum,
 5011:                   bread_crumbs_component => $bread_crumbs_component};
 5012:         $r->print(&header(undef,$args));
 5013:         $r->print(&print_main_menu($permission,$context,$crstype));
 5014:     }
 5015:     $r->print(&Apache::loncommon::end_page());
 5016:     return OK;
 5017: }
 5018: 
 5019: sub header {
 5020:     my ($jscript,$args) = @_;
 5021:     my $start_page;
 5022:     if (ref($args) eq 'HASH') {
 5023:         $start_page=&Apache::loncommon::start_page('User Management',$jscript,$args);
 5024:     } else {
 5025:         $start_page=&Apache::loncommon::start_page('User Management',$jscript);
 5026:     }
 5027:     return $start_page;
 5028: }
 5029: 
 5030: sub add_script {
 5031:     my ($js) = @_;
 5032:     return '<script type="text/javascript">'."\n"
 5033:           .'// <![CDATA['."\n"
 5034:           .$js."\n"
 5035:           .'// ]]>'."\n"
 5036:           .'</script>'."\n";
 5037: }
 5038: 
 5039: sub usernamerequest_javascript {
 5040:     my $js = <<ENDJS;
 5041: 
 5042: function openusernamereqdisplay(dom,uname,queue) {
 5043:     var url = '/adm/createuser?action=displayuserreq';
 5044:     url += '&domain='+dom+'&username='+uname+'&queue='+queue;
 5045:     var title = 'Account_Request_Browser';
 5046:     var options = 'scrollbars=1,resizable=1,menubar=0';
 5047:     options += ',width=700,height=600';
 5048:     var stdeditbrowser = open(url,title,options,'1');
 5049:     stdeditbrowser.focus();
 5050:     return;
 5051: }
 5052:  
 5053: ENDJS
 5054: }
 5055: 
 5056: sub close_popup_form {
 5057:     my $close= &mt('Close Window');
 5058:     return << "END";
 5059: <p><form name="displayreq" action="" method="post">
 5060: <input type="button" name="closeme" value="$close" onclick="javascript:self.close();" />
 5061: </form></p>
 5062: END
 5063: }
 5064: 
 5065: sub verify_user_display {
 5066:     my ($context) = @_;
 5067:     my %lt = &Apache::lonlocal::texthash (
 5068:         course    => 'course(s): description, section(s), status',
 5069:         community => 'community(s): description, section(s), status',
 5070:         author    => 'author',
 5071:     );
 5072:     my $photos;
 5073:     if (($context eq 'course') && $env{'request.course.id'}) {
 5074:         $photos = $env{'course.'.$env{'request.course.id'}.'.internal.showphoto'};
 5075:     }
 5076:     my $output = <<"END";
 5077: 
 5078: function hide_searching() {
 5079:     if (document.getElementById('searching')) {
 5080:         document.getElementById('searching').style.display = 'none';
 5081:     }
 5082:     return;
 5083: }
 5084: 
 5085: function display_update() {
 5086:     document.studentform.action.value = 'listusers';
 5087:     document.studentform.phase.value = 'display';
 5088:     document.studentform.submit();
 5089: }
 5090: 
 5091: function updateCols(caller) {
 5092:     var context = '$context';
 5093:     var photos = '$photos';
 5094:     if (caller == 'Status') {
 5095:         if ((context == 'domain') && 
 5096:             ((document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'course') ||
 5097:              (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'community'))) {
 5098:             document.getElementById('showcolstatus').checked = false;
 5099:             document.getElementById('showcolstatus').disabled = 'disabled';
 5100:             document.getElementById('showcolstart').checked = false;
 5101:             document.getElementById('showcolend').checked = false;
 5102:         } else {
 5103:             if (document.studentform.Status.options[document.studentform.Status.selectedIndex].value == 'Any') {
 5104:                 document.getElementById('showcolstatus').checked = true;
 5105:                 document.getElementById('showcolstatus').disabled = '';
 5106:                 document.getElementById('showcolstart').checked = true;
 5107:                 document.getElementById('showcolend').checked = true;
 5108:             } else {
 5109:                 document.getElementById('showcolstatus').checked = false;
 5110:                 document.getElementById('showcolstatus').disabled = 'disabled';
 5111:                 document.getElementById('showcolstart').checked = false;
 5112:                 document.getElementById('showcolend').checked = false;
 5113:             }
 5114:         }
 5115:     }
 5116:     if (caller == 'output') {
 5117:         if (photos == 1) {
 5118:             if (document.getElementById('showcolphoto')) {
 5119:                 var photoitem = document.getElementById('showcolphoto');
 5120:                 if (document.studentform.output.options[document.studentform.output.selectedIndex].value == 'html') {
 5121:                     photoitem.checked = true;
 5122:                     photoitem.disabled = '';
 5123:                 } else {
 5124:                     photoitem.checked = false;
 5125:                     photoitem.disabled = 'disabled';
 5126:                 }
 5127:             }
 5128:         }
 5129:     }
 5130:     if (caller == 'showrole') {
 5131:         if ((document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'Any') ||
 5132:             (document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'cr')) {
 5133:             document.getElementById('showcolrole').checked = true;
 5134:             document.getElementById('showcolrole').disabled = '';
 5135:         } else {
 5136:             document.getElementById('showcolrole').checked = false;
 5137:             document.getElementById('showcolrole').disabled = 'disabled';
 5138:         }
 5139:         if (context == 'domain') {
 5140:             var quotausageshow = 0;
 5141:             if ((document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'course') ||
 5142:                 (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'community')) {
 5143:                 document.getElementById('showcolstatus').checked = false;
 5144:                 document.getElementById('showcolstatus').disabled = 'disabled';
 5145:                 document.getElementById('showcolstart').checked = false;
 5146:                 document.getElementById('showcolend').checked = false;
 5147:             } else {
 5148:                 if (document.studentform.Status.options[document.studentform.Status.selectedIndex].value == 'Any') {
 5149:                     document.getElementById('showcolstatus').checked = true;
 5150:                     document.getElementById('showcolstatus').disabled = '';
 5151:                     document.getElementById('showcolstart').checked = true;
 5152:                     document.getElementById('showcolend').checked = true;
 5153:                 }
 5154:             }
 5155:             if (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'domain') {
 5156:                 document.getElementById('showcolextent').disabled = 'disabled';
 5157:                 document.getElementById('showcolextent').checked = 'false';
 5158:                 document.getElementById('showextent').style.display='none';
 5159:                 document.getElementById('showcoltextextent').innerHTML = '';
 5160:                 if ((document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'au') ||
 5161:                     (document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'Any')) {
 5162:                     if (document.getElementById('showcolauthorusage')) {
 5163:                         document.getElementById('showcolauthorusage').disabled = '';
 5164:                     }
 5165:                     if (document.getElementById('showcolauthorquota')) {
 5166:                         document.getElementById('showcolauthorquota').disabled = '';
 5167:                     }
 5168:                     quotausageshow = 1;
 5169:                 }
 5170:             } else {
 5171:                 document.getElementById('showextent').style.display='block';
 5172:                 document.getElementById('showextent').style.textAlign='left';
 5173:                 document.getElementById('showextent').style.textFace='normal';
 5174:                 if (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'author') {
 5175:                     document.getElementById('showcolextent').disabled = '';
 5176:                     document.getElementById('showcolextent').checked = 'true';
 5177:                     document.getElementById('showcoltextextent').innerHTML="$lt{'author'}";
 5178:                 } else {
 5179:                     document.getElementById('showcolextent').disabled = '';
 5180:                     document.getElementById('showcolextent').checked = 'true';
 5181:                     if (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'community') {
 5182:                         document.getElementById('showcoltextextent').innerHTML="$lt{'community'}";
 5183:                     } else {
 5184:                         document.getElementById('showcoltextextent').innerHTML="$lt{'course'}";
 5185:                     }
 5186:                 }
 5187:             }
 5188:             if (quotausageshow == 0)  {
 5189:                 if (document.getElementById('showcolauthorusage')) {
 5190:                     document.getElementById('showcolauthorusage').checked = false;
 5191:                     document.getElementById('showcolauthorusage').disabled = 'disabled';
 5192:                 }
 5193:                 if (document.getElementById('showcolauthorquota')) {
 5194:                     document.getElementById('showcolauthorquota').checked = false;
 5195:                     document.getElementById('showcolauthorquota').disabled = 'disabled';
 5196:                 }
 5197:             }
 5198:         }
 5199:     }
 5200:     return;
 5201: }
 5202: 
 5203: END
 5204:     return $output;
 5205: 
 5206: }
 5207: 
 5208: ###############################################################
 5209: ###############################################################
 5210: #  Menu Phase One
 5211: sub print_main_menu {
 5212:     my ($permission,$context,$crstype) = @_;
 5213:     my $linkcontext = $context;
 5214:     my $stuterm = lc(&Apache::lonnet::plaintext('st',$crstype));
 5215:     if (($context eq 'course') && ($crstype eq 'Community')) {
 5216:         $linkcontext = lc($crstype);
 5217:         $stuterm = 'Members';
 5218:     }
 5219:     my %links = (
 5220:                 domain => {
 5221:                             upload     => 'Upload a File of Users',
 5222:                             singleuser => 'Add/Modify a User',
 5223:                             listusers  => 'Manage Users',
 5224:                             },
 5225:                 author => {
 5226:                             upload     => 'Upload a File of Co-authors',
 5227:                             singleuser => 'Add/Modify a Co-author',
 5228:                             listusers  => 'Manage Co-authors',
 5229:                             },
 5230:                 course => {
 5231:                             upload     => 'Upload a File of Course Users',
 5232:                             singleuser => 'Add/Modify a Course User',
 5233:                             listusers  => 'List and Modify Multiple Course Users',
 5234:                             },
 5235:                 community => {
 5236:                             upload     => 'Upload a File of Community Users',
 5237:                             singleuser => 'Add/Modify a Community User',
 5238:                             listusers  => 'List and Modify Multiple Community Users',
 5239:                            },
 5240:                 );
 5241:      my %linktitles = (
 5242:                 domain => {
 5243:                             singleuser => 'Add a user to the domain, and/or a course or community in the domain.',
 5244:                             listusers  => 'Show and manage users in this domain.',
 5245:                             },
 5246:                 author => {
 5247:                             singleuser => 'Add a user with a co- or assistant author role.',
 5248:                             listusers  => 'Show and manage co- or assistant authors.',
 5249:                             },
 5250:                 course => {
 5251:                             singleuser => 'Add a user with a certain role to this course.',
 5252:                             listusers  => 'Show and manage users in this course.',
 5253:                             },
 5254:                 community => {
 5255:                             singleuser => 'Add a user with a certain role to this community.',
 5256:                             listusers  => 'Show and manage users in this community.',
 5257:                            },
 5258:                 );
 5259:   my @menu = ( {categorytitle => 'Single Users', 
 5260:          items =>
 5261:          [
 5262:             {
 5263:              linktext => $links{$linkcontext}{'singleuser'},
 5264:              icon => 'edit-redo.png',
 5265:              #help => 'Course_Change_Privileges',
 5266:              url => '/adm/createuser?action=singleuser',
 5267:              permission => $permission->{'cusr'},
 5268:              linktitle => $linktitles{$linkcontext}{'singleuser'},
 5269:             },
 5270:          ]},
 5271: 
 5272:          {categorytitle => 'Multiple Users',
 5273:          items => 
 5274:          [
 5275:             {
 5276:              linktext => $links{$linkcontext}{'upload'},
 5277:              icon => 'uplusr.png',
 5278:              #help => 'Course_Create_Class_List',
 5279:              url => '/adm/createuser?action=upload',
 5280:              permission => $permission->{'cusr'},
 5281:              linktitle => 'Upload a CSV or a text file containing users.',
 5282:             },
 5283:             {
 5284:              linktext => $links{$linkcontext}{'listusers'},
 5285:              icon => 'mngcu.png',
 5286:              #help => 'Course_View_Class_List',
 5287:              url => '/adm/createuser?action=listusers',
 5288:              permission => ($permission->{'view'} || $permission->{'cusr'}),
 5289:              linktitle => $linktitles{$linkcontext}{'listusers'}, 
 5290:             },
 5291: 
 5292:          ]},
 5293: 
 5294:          {categorytitle => 'Administration',
 5295:          items => [ ]},
 5296:        );
 5297:             
 5298:     if ($context eq 'domain'){
 5299:         
 5300:         push(@{ $menu[2]->{items} }, #Category: Administration
 5301:             {
 5302:              linktext => 'Custom Roles',
 5303:              icon => 'emblem-photos.png',
 5304:              #help => 'Course_Editing_Custom_Roles',
 5305:              url => '/adm/createuser?action=custom',
 5306:              permission => $permission->{'custom'},
 5307:              linktitle => 'Configure a custom role.',
 5308:             },
 5309:             {
 5310:              linktext => 'Authoring Space Requests',
 5311:              icon => 'selfenrl-queue.png',
 5312:              #help => 'Domain_Role_Approvals',
 5313:              url => '/adm/createuser?action=processauthorreq',
 5314:              permission => $permission->{'cusr'},
 5315:              linktitle => 'Approve or reject author role requests',
 5316:             },
 5317:             {
 5318:              linktext => 'LON-CAPA Account Requests',
 5319:              icon => 'list-add.png',
 5320:              #help => 'Domain_Username_Approvals',
 5321:              url => '/adm/createuser?action=processusernamereq',
 5322:              permission => $permission->{'cusr'},
 5323:              linktitle => 'Approve or reject LON-CAPA account requests',
 5324:             },
 5325:             {
 5326:              linktext => 'Change Log',
 5327:              icon => 'document-properties.png',
 5328:              #help => 'Course_User_Logs',
 5329:              url => '/adm/createuser?action=changelogs',
 5330:              permission => $permission->{'cusr'},
 5331:              linktitle => 'View change log.',
 5332:             },
 5333:         );
 5334:         
 5335:     }elsif ($context eq 'course'){
 5336:         my ($cnum,$cdom) = &Apache::lonuserutils::get_course_identity();
 5337: 
 5338:         my %linktext = (
 5339:                          'Course'    => {
 5340:                                           single => 'Add/Modify a Student', 
 5341:                                           drop   => 'Drop Students',
 5342:                                           groups => 'Course Groups',
 5343:                                         },
 5344:                          'Community' => {
 5345:                                           single => 'Add/Modify a Member', 
 5346:                                           drop   => 'Drop Members',
 5347:                                           groups => 'Community Groups',
 5348:                                         },
 5349:                        );
 5350: 
 5351:         my %linktitle = (
 5352:             'Course' => {
 5353:                   single => 'Add a user with the role of student to this course',
 5354:                   drop   => 'Remove a student from this course.',
 5355:                   groups => 'Manage course groups',
 5356:                         },
 5357:             'Community' => {
 5358:                   single => 'Add a user with the role of member to this community',
 5359:                   drop   => 'Remove a member from this community.',
 5360:                   groups => 'Manage community groups',
 5361:                            },
 5362:         );
 5363: 
 5364:         push(@{ $menu[0]->{items} }, #Category: Single Users
 5365:             {   
 5366:              linktext => $linktext{$crstype}{'single'},
 5367:              #help => 'Course_Add_Student',
 5368:              icon => 'list-add.png',
 5369:              url => '/adm/createuser?action=singlestudent',
 5370:              permission => $permission->{'cusr'},
 5371:              linktitle => $linktitle{$crstype}{'single'},
 5372:             },
 5373:         );
 5374:         
 5375:         push(@{ $menu[1]->{items} }, #Category: Multiple Users 
 5376:             {
 5377:              linktext => $linktext{$crstype}{'drop'},
 5378:              icon => 'edit-undo.png',
 5379:              #help => 'Course_Drop_Student',
 5380:              url => '/adm/createuser?action=drop',
 5381:              permission => $permission->{'cusr'},
 5382:              linktitle => $linktitle{$crstype}{'drop'},
 5383:             },
 5384:         );
 5385:         push(@{ $menu[2]->{items} }, #Category: Administration
 5386:             {    
 5387:              linktext => 'Custom Roles',
 5388:              icon => 'emblem-photos.png',
 5389:              #help => 'Course_Editing_Custom_Roles',
 5390:              url => '/adm/createuser?action=custom',
 5391:              permission => $permission->{'custom'},
 5392:              linktitle => 'Configure a custom role.',
 5393:             },
 5394:             {
 5395:              linktext => $linktext{$crstype}{'groups'},
 5396:              icon => 'grps.png',
 5397:              #help => 'Course_Manage_Group',
 5398:              url => '/adm/coursegroups?refpage=cusr',
 5399:              permission => $permission->{'grp_manage'},
 5400:              linktitle => $linktitle{$crstype}{'groups'},
 5401:             },
 5402:             {
 5403:              linktext => 'Change Log',
 5404:              icon => 'document-properties.png',
 5405:              #help => 'Course_User_Logs',
 5406:              url => '/adm/createuser?action=changelogs',
 5407:              permission => $permission->{'cusr'},
 5408:              linktitle => 'View change log.',
 5409:             },
 5410:         );
 5411:         if ($env{'course.'.$env{'request.course.id'}.'.internal.selfenroll_approval'}) {
 5412:             push(@{ $menu[2]->{items} },
 5413:                     {   
 5414:                      linktext => 'Enrollment Requests',
 5415:                      icon => 'selfenrl-queue.png',
 5416:                      #help => 'Course_Approve_Selfenroll',
 5417:                      url => '/adm/createuser?action=selfenrollqueue',
 5418:                      permission => $permission->{'cusr'},
 5419:                      linktitle =>'Approve or reject enrollment requests.',
 5420:                     },
 5421:             );
 5422:         }
 5423:         
 5424:         if (!exists($permission->{'cusr_section'})){
 5425:             if ($crstype ne 'Community') {
 5426:                 push(@{ $menu[2]->{items} },
 5427:                     {
 5428:                      linktext => 'Automated Enrollment',
 5429:                      icon => 'roles.png',
 5430:                      #help => 'Course_Automated_Enrollment',
 5431:                      permission => (&Apache::lonnet::auto_run($cnum,$cdom)
 5432:                                          && $permission->{'cusr'}),
 5433:                      url  => '/adm/populate',
 5434:                      linktitle => 'Automated enrollment manager.',
 5435:                     }
 5436:                 );
 5437:             }
 5438:             push(@{ $menu[2]->{items} }, 
 5439:                 {
 5440:                  linktext => 'User Self-Enrollment',
 5441:                  icon => 'self_enroll.png',
 5442:                  #help => 'Course_Self_Enrollment',
 5443:                  url => '/adm/createuser?action=selfenroll',
 5444:                  permission => $permission->{'cusr'},
 5445:                  linktitle => 'Configure user self-enrollment.',
 5446:                 },
 5447:             );
 5448:         }
 5449:     } elsif ($context eq 'author') {
 5450:         push(@{ $menu[2]->{items} }, #Category: Administration
 5451:             {
 5452:              linktext => 'Change Log',
 5453:              icon => 'document-properties.png',
 5454:              #help => 'Course_User_Logs',
 5455:              url => '/adm/createuser?action=changelogs',
 5456:              permission => $permission->{'cusr'},
 5457:              linktitle => 'View change log.',
 5458:             },
 5459:         );
 5460:     }
 5461:     return Apache::lonhtmlcommon::generate_menu(@menu);
 5462: #               { text => 'View Log-in History',
 5463: #                 help => 'Course_User_Logins',
 5464: #                 action => 'logins',
 5465: #                 permission => $permission->{'cusr'},
 5466: #               });
 5467: }
 5468: 
 5469: sub restore_prev_selections {
 5470:     my %saveable_parameters = ('srchby'   => 'scalar',
 5471: 			       'srchin'   => 'scalar',
 5472: 			       'srchtype' => 'scalar',
 5473: 			       );
 5474:     &Apache::loncommon::store_settings('user','user_picker',
 5475: 				       \%saveable_parameters);
 5476:     &Apache::loncommon::restore_settings('user','user_picker',
 5477: 					 \%saveable_parameters);
 5478: }
 5479: 
 5480: sub print_selfenroll_menu {
 5481:     my ($r,$context,$permission) = @_;
 5482:     my $crstype = &Apache::loncommon::course_type();
 5483:     my $formname = 'enrollstudent';
 5484:     my $nolink = 1;
 5485:     my ($row,$lt) = &get_selfenroll_titles();
 5486:     my $groupslist = &Apache::lonuserutils::get_groupslist();
 5487:     my $setsec_js = 
 5488:         &Apache::lonuserutils::setsections_javascript($formname,$groupslist);
 5489:     my %alerts = &Apache::lonlocal::texthash(
 5490:         acto => 'Activation of self-enrollment was selected for the following domain(s)',
 5491:         butn => 'but no user types have been checked.',
 5492:         wilf => "Please uncheck 'activate' or check at least one type.",
 5493:     );
 5494:     my $selfenroll_js = <<"ENDSCRIPT";
 5495: function update_types(caller,num) {
 5496:     var delidx = getIndexByName('selfenroll_delete');
 5497:     var actidx = getIndexByName('selfenroll_activate');
 5498:     if (caller == 'selfenroll_all') {
 5499:         var selall;
 5500:         for (var i=0; i<document.$formname.selfenroll_all.length; i++) {
 5501:             if (document.$formname.selfenroll_all[i].checked) {
 5502:                 selall = document.$formname.selfenroll_all[i].value;
 5503:             }
 5504:         }
 5505:         if (selall == 1) {
 5506:             if (delidx != -1) {
 5507:                 if (document.$formname.selfenroll_delete.length) {
 5508:                     for (var j=0; j<document.$formname.selfenroll_delete.length; j++) {
 5509:                         document.$formname.selfenroll_delete[j].checked = true;
 5510:                     }
 5511:                 } else {
 5512:                     document.$formname.elements[delidx].checked = true;
 5513:                 }
 5514:             }
 5515:             if (actidx != -1) {
 5516:                 if (document.$formname.selfenroll_activate.length) {
 5517:                     for (var j=0; j<document.$formname.selfenroll_activate.length; j++) {
 5518:                         document.$formname.selfenroll_activate[j].checked = false;
 5519:                     }
 5520:                 } else {
 5521:                     document.$formname.elements[actidx].checked = false;
 5522:                 }
 5523:             }
 5524:             document.$formname.selfenroll_newdom.selectedIndex = 0; 
 5525:         }
 5526:     }
 5527:     if (caller == 'selfenroll_activate') {
 5528:         if (document.$formname.selfenroll_activate.length) {
 5529:             for (var j=0; j<document.$formname.selfenroll_activate.length; j++) {
 5530:                 if (document.$formname.selfenroll_activate[j].value == num) {
 5531:                     if (document.$formname.selfenroll_activate[j].checked) {
 5532:                         for (var i=0; i<document.$formname.selfenroll_all.length; i++) {
 5533:                             if (document.$formname.selfenroll_all[i].value == '1') {
 5534:                                 document.$formname.selfenroll_all[i].checked = false;
 5535:                             }
 5536:                             if (document.$formname.selfenroll_all[i].value == '0') {
 5537:                                 document.$formname.selfenroll_all[i].checked = true;
 5538:                             }
 5539:                         }
 5540:                     }
 5541:                 }
 5542:             }
 5543:         } else {
 5544:             for (var i=0; i<document.$formname.selfenroll_all.length; i++) {
 5545:                 if (document.$formname.selfenroll_all[i].value == '1') {
 5546:                     document.$formname.selfenroll_all[i].checked = false;
 5547:                 }
 5548:                 if (document.$formname.selfenroll_all[i].value == '0') {
 5549:                     document.$formname.selfenroll_all[i].checked = true;
 5550:                 }
 5551:             }
 5552:         }
 5553:     }
 5554:     if (caller == 'selfenroll_delete') {
 5555:         if (document.$formname.selfenroll_delete.length) {
 5556:             for (var j=0; j<document.$formname.selfenroll_delete.length; j++) {
 5557:                 if (document.$formname.selfenroll_delete[j].value == num) {
 5558:                     if (document.$formname.selfenroll_delete[j].checked) {
 5559:                         var delindex = getIndexByName('selfenroll_types_'+num);
 5560:                         if (delindex != -1) { 
 5561:                             if (document.$formname.elements[delindex].length) {
 5562:                                 for (var k=0; k<document.$formname.elements[delindex].length; k++) {
 5563:                                     document.$formname.elements[delindex][k].checked = false;
 5564:                                 }
 5565:                             } else {
 5566:                                 document.$formname.elements[delindex].checked = false;
 5567:                             }
 5568:                         }
 5569:                     }
 5570:                 }
 5571:             }
 5572:         } else {
 5573:             if (document.$formname.selfenroll_delete.checked) {
 5574:                 var delindex = getIndexByName('selfenroll_types_'+num);
 5575:                 if (delindex != -1) {
 5576:                     if (document.$formname.elements[delindex].length) {
 5577:                         for (var k=0; k<document.$formname.elements[delindex].length; k++) {
 5578:                             document.$formname.elements[delindex][k].checked = false;
 5579:                         }
 5580:                     } else {
 5581:                         document.$formname.elements[delindex].checked = false;
 5582:                     }
 5583:                 }
 5584:             }
 5585:         }
 5586:     }
 5587:     return;
 5588: }
 5589: 
 5590: function validate_types(form) {
 5591:     var needaction = new Array();
 5592:     var countfail = 0;
 5593:     var actidx = getIndexByName('selfenroll_activate');
 5594:     if (actidx != -1) {
 5595:         if (document.$formname.selfenroll_activate.length) {
 5596:             for (var j=0; j<document.$formname.selfenroll_activate.length; j++) {
 5597:                 var num = document.$formname.selfenroll_activate[j].value;
 5598:                 if (document.$formname.selfenroll_activate[j].checked) {
 5599:                     countfail = check_types(num,countfail,needaction)
 5600:                 }
 5601:             }
 5602:         } else {
 5603:             if (document.$formname.selfenroll_activate.checked) {
 5604:                 var num = document.enrollstudent.selfenroll_activate.value;
 5605:                 countfail = check_types(num,countfail,needaction)
 5606:             }
 5607:         }
 5608:     }
 5609:     if (countfail > 0) {
 5610:         var msg = "$alerts{'acto'}\\n";
 5611:         var loopend = needaction.length -1;
 5612:         if (loopend > 0) {
 5613:             for (var m=0; m<loopend; m++) {
 5614:                 msg += needaction[m]+", ";
 5615:             }
 5616:         }
 5617:         msg += needaction[loopend]+"\\n$alerts{'butn'}\\n$alerts{'wilf'}";
 5618:         alert(msg);
 5619:         return; 
 5620:     }
 5621:     setSections(form);
 5622: }
 5623: 
 5624: function check_types(num,countfail,needaction) {
 5625:     var typeidx = getIndexByName('selfenroll_types_'+num);
 5626:     var count = 0;
 5627:     if (typeidx != -1) {
 5628:         if (document.$formname.elements[typeidx].length) {
 5629:             for (var k=0; k<document.$formname.elements[typeidx].length; k++) {
 5630:                 if (document.$formname.elements[typeidx][k].checked) {
 5631:                     count ++;
 5632:                 }
 5633:             }
 5634:         } else {
 5635:             if (document.$formname.elements[typeidx].checked) {
 5636:                 count ++;
 5637:             }
 5638:         }
 5639:         if (count == 0) {
 5640:             var domidx = getIndexByName('selfenroll_dom_'+num);
 5641:             if (domidx != -1) {
 5642:                 var domname = document.$formname.elements[domidx].value;
 5643:                 needaction[countfail] = domname;
 5644:                 countfail ++;
 5645:             }
 5646:         }
 5647:     }
 5648:     return countfail;
 5649: }
 5650: 
 5651: function getIndexByName(item) {
 5652:     for (var i=0;i<document.$formname.elements.length;i++) {
 5653:         if (document.$formname.elements[i].name == item) {
 5654:             return i;
 5655:         }
 5656:     }
 5657:     return -1;
 5658: }
 5659: ENDSCRIPT
 5660:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5661:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 5662: 
 5663:     my $output = '<script type="text/javascript">'."\n".
 5664:                  '// <![CDATA['."\n".
 5665:                  $setsec_js."\n".$selfenroll_js."\n".
 5666:                  '// ]]>'."\n".
 5667:                  '</script>'."\n".
 5668:                  '<h3>'.$lt->{'selfenroll'}.'</h3>'."\n";
 5669:     my ($visible,$cansetvis,$vismsgs,$visactions) = &visible_in_cat($cdom,$cnum);
 5670:     if (ref($visactions) eq 'HASH') {
 5671:         if ($visible) {
 5672:             $output .= '<p class="LC_info">'.$visactions->{'vis'}.'</p>';
 5673:         } else {
 5674:             $output .= '<p class="LC_warning">'.$visactions->{'miss'}.'</p>'
 5675:                       .$visactions->{'yous'}.
 5676:                        '<p>'.$visactions->{'gen'}.'<br />'.$visactions->{'coca'};
 5677:             if (ref($vismsgs) eq 'ARRAY') {
 5678:                 $output .= '<br />'.$visactions->{'make'}.'<ul>';
 5679:                 foreach my $item (@{$vismsgs}) {
 5680:                     $output .= '<li>'.$visactions->{$item}.'</li>';
 5681:                 }
 5682:                 $output .= '</ul>';
 5683:             }
 5684:             $output .= '</p>';
 5685:         }
 5686:     }
 5687:     $output .= '<form name="'.$formname.'" method="post" action="/adm/createuser">'."\n".
 5688:                &Apache::lonhtmlcommon::start_pick_box();
 5689:     if (ref($row) eq 'ARRAY') {
 5690:         foreach my $item (@{$row}) {
 5691:             my $title = $item; 
 5692:             if (ref($lt) eq 'HASH') {
 5693:                 $title = $lt->{$item};
 5694:             }
 5695:             $output .= &Apache::lonhtmlcommon::row_title($title);
 5696:             if ($item eq 'types') {
 5697:                 my $curr_types = $env{'course.'.$env{'request.course.id'}.'.internal.selfenroll_types'};
 5698:                 my $showdomdesc = 1;
 5699:                 my $includeempty = 1;
 5700:                 my $num = 0;
 5701:                 $output .= &Apache::loncommon::start_data_table().
 5702:                            &Apache::loncommon::start_data_table_row()
 5703:                            .'<td colspan="2"><span class="LC_nobreak"><label>'
 5704:                            .&mt('Any user in any domain:')
 5705:                            .'&nbsp;<input type="radio" name="selfenroll_all" value="1" ';
 5706:                 if ($curr_types eq '*') {
 5707:                     $output .= ' checked="checked" '; 
 5708:                 }
 5709:                 $output .= 'onchange="javascript:update_types('.
 5710:                            "'selfenroll_all'".');" />'.&mt('Yes').'</label>'.
 5711:                            '&nbsp;&nbsp;<input type="radio" name="selfenroll_all" value="0" ';
 5712:                 if ($curr_types ne '*') {
 5713:                     $output .= ' checked="checked" ';
 5714:                 }
 5715:                 $output .= ' onchange="javascript:update_types('.
 5716:                            "'selfenroll_all'".');"/>'.&mt('No').'</label></td>'.
 5717:                            &Apache::loncommon::end_data_table_row().
 5718:                            &Apache::loncommon::end_data_table().
 5719:                            &mt('Or').'<br />'.
 5720:                            &Apache::loncommon::start_data_table();
 5721:                 my %currdoms;
 5722:                 if ($curr_types eq '') {
 5723:                     $output .= &new_selfenroll_dom_row($cdom,'0');
 5724:                 } elsif ($curr_types ne '*') {
 5725:                     my @entries = split(/;/,$curr_types);
 5726:                     if (@entries > 0) {
 5727:                         foreach my $entry (@entries) {
 5728:                             my ($currdom,$typestr) = split(/:/,$entry);
 5729:                             $currdoms{$currdom} = 1;
 5730:                             my $domdesc = &Apache::lonnet::domain($currdom);
 5731:                             my @currinsttypes = split(',',$typestr);
 5732:                             $output .= &Apache::loncommon::start_data_table_row()
 5733:                                        .'<td valign="top"><span class="LC_nobreak">'.&mt('Domain:').'<b>'
 5734:                                        .'&nbsp;'.$domdesc.' ('.$currdom.')'
 5735:                                        .'</b><input type="hidden" name="selfenroll_dom_'.$num
 5736:                                        .'" value="'.$currdom.'" /></span><br />'
 5737:                                        .'<span class="LC_nobreak"><label><input type="checkbox" '
 5738:                                        .'name="selfenroll_delete" value="'.$num.'" onchange="javascript:update_types('."'selfenroll_delete','$num'".');" />'
 5739:                                        .&mt('Delete').'</label></span></td>';
 5740:                             $output .= '<td valign="top">&nbsp;&nbsp;'.&mt('User types:').'<br />'
 5741:                                        .&selfenroll_inst_types($num,$currdom,\@currinsttypes).'</td>'
 5742:                                        .&Apache::loncommon::end_data_table_row();
 5743:                             $num ++;
 5744:                         }
 5745:                     }
 5746:                 }
 5747:                 my $add_domtitle = &mt('Users in additional domain:');
 5748:                 if ($curr_types eq '*') { 
 5749:                     $add_domtitle = &mt('Users in specific domain:');
 5750:                 } elsif ($curr_types eq '') {
 5751:                     $add_domtitle = &mt('Users in other domain:');
 5752:                 }
 5753:                 $output .= &Apache::loncommon::start_data_table_row()
 5754:                            .'<td colspan="2"><span class="LC_nobreak">'.$add_domtitle.'</span><br />'
 5755:                            .&Apache::loncommon::select_dom_form('','selfenroll_newdom',
 5756:                                                                 $includeempty,$showdomdesc)
 5757:                            .'<input type="hidden" name="selfenroll_types_total" value="'.$num.'" />'
 5758:                            .'</td>'.&Apache::loncommon::end_data_table_row()
 5759:                            .&Apache::loncommon::end_data_table();
 5760:             } elsif ($item eq 'registered') {
 5761:                 my ($regon,$regoff);
 5762:                 if ($env{'course.'.$env{'request.course.id'}.'.internal.selfenroll_registered'}) {
 5763:                     $regon = ' checked="checked" ';
 5764:                     $regoff = ' ';
 5765:                 } else {
 5766:                     $regon = ' ';
 5767:                     $regoff = ' checked="checked" ';
 5768:                 }
 5769:                 $output .= '<label>'.
 5770:                            '<input type="radio" name="selfenroll_registered" value="1"'.$regon.'/>'.
 5771:                            &mt('Yes').'</label>&nbsp;&nbsp;<label>'.
 5772:                            '<input type="radio" name="selfenroll_registered" value="0"'.$regoff.'/>'.
 5773:                            &mt('No').'</label>';
 5774:             } elsif ($item eq 'enroll_dates') {
 5775:                 my $starttime = $env{'course.'.$env{'request.course.id'}.'.internal.selfenroll_start_date'};
 5776:                 my $endtime = $env{'course.'.$env{'request.course.id'}.'.internal.selfenroll_end_date'};
 5777:                 if ($starttime eq '') {
 5778:                     $starttime = $env{'course.'.$env{'request.course.id'}.'.default_enrollment_start_date'};
 5779:                 }
 5780:                 if ($endtime eq '') {
 5781:                     $endtime = $env{'course.'.$env{'request.course.id'}.'.default_enrollment_end_date'};
 5782:                 }
 5783:                 my $startform =
 5784:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_start_date',$starttime,
 5785:                                       undef,undef,undef,undef,undef,undef,undef,$nolink);
 5786:                 my $endform =
 5787:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_end_date',$endtime,
 5788:                                       undef,undef,undef,undef,undef,undef,undef,$nolink);
 5789:                 $output .= &selfenroll_date_forms($startform,$endform);
 5790:             } elsif ($item eq 'access_dates') {
 5791:                 my $starttime = $env{'course.'.$env{'request.course.id'}.'.internal.selfenroll_start_access'};
 5792:                 my $endtime = $env{'course.'.$env{'request.course.id'}.'.internal.selfenroll_end_access'};
 5793:                 if ($starttime eq '') {
 5794:                     $starttime = $env{'course.'.$env{'request.course.id'}.'.default_enrollment_start_date'};
 5795:                 }
 5796:                 if ($endtime eq '') {
 5797:                     $endtime = $env{'course.'.$env{'request.course.id'}.'.default_enrollment_end_date'};
 5798:                 }
 5799:                 my $startform =
 5800:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_start_access',$starttime,
 5801:                                       undef,undef,undef,undef,undef,undef,undef,$nolink);
 5802:                 my $endform =
 5803:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_end_access',$endtime,
 5804:                                       undef,undef,undef,undef,undef,undef,undef,$nolink);
 5805:                 $output .= &selfenroll_date_forms($startform,$endform);
 5806:             } elsif ($item eq 'section') {
 5807:                 my $currsec = $env{'course.'.$env{'request.course.id'}.'.internal.selfenroll_section'}; 
 5808:                 my %sections_count = &Apache::loncommon::get_sections($cdom,$cnum);
 5809:                 my $newsecval;
 5810:                 if ($currsec ne 'none' && $currsec ne '') {
 5811:                     if (!defined($sections_count{$currsec})) {
 5812:                         $newsecval = $currsec;
 5813:                     }
 5814:                 }
 5815:                 my $sections_select = 
 5816:                     &Apache::lonuserutils::course_sections(\%sections_count,'st',$currsec);
 5817:                 $output .= '<table class="LC_createuser">'."\n".
 5818:                            '<tr class="LC_section_row">'."\n".
 5819:                            '<td align="center">'.&mt('Existing sections')."\n".
 5820:                            '<br />'.$sections_select.'</td><td align="center">'.
 5821:                            &mt('New section').'<br />'."\n".
 5822:                            '<input type="text" name="newsec" size="15" value="'.$newsecval.'" />'."\n".
 5823:                            '<input type="hidden" name="sections" value="" />'."\n".
 5824:                            '<input type="hidden" name="state" value="done" />'."\n".
 5825:                            '</td></tr></table>'."\n";
 5826:             } elsif ($item eq 'approval') {
 5827:                 my ($appon,$appoff);
 5828:                 my $cid = $env{'request.course.id'};
 5829:                 my $currnotified = $env{'course.'.$cid.'.internal.selfenroll_notifylist'};
 5830:                 if ($env{'course.'.$cid.'.internal.selfenroll_approval'}) {
 5831:                     $appon = ' checked="checked" ';
 5832:                     $appoff = ' ';
 5833:                 } else {
 5834:                     $appon = ' ';
 5835:                     $appoff = ' checked="checked" ';
 5836:                 }
 5837:                 $output .= '<label>'.
 5838:                            '<input type="radio" name="selfenroll_approval" value="1"'.$appon.'/>'.
 5839:                            &mt('Yes').'</label>&nbsp;&nbsp;<label>'.
 5840:                            '<input type="radio" name="selfenroll_approval" value="0"'.$appoff.'/>'.
 5841:                            &mt('No').'</label>';
 5842:                 my %advhash = &Apache::lonnet::get_course_adv_roles($cid,1);
 5843:                 my (@ccs,%notified);
 5844:                 my $ccrole = 'cc';
 5845:                 if ($crstype eq 'Community') {
 5846:                     $ccrole = 'co';
 5847:                 }
 5848:                 if ($advhash{$ccrole}) {
 5849:                     @ccs = split(/,/,$advhash{$ccrole});
 5850:                 }
 5851:                 if ($currnotified) {
 5852:                     foreach my $current (split(/,/,$currnotified)) {
 5853:                         $notified{$current} = 1;
 5854:                         if (!grep(/^\Q$current\E$/,@ccs)) {
 5855:                             push(@ccs,$current);
 5856:                         }
 5857:                     }
 5858:                 }
 5859:                 if (@ccs) {
 5860:                     $output .= '<br />'.&mt('Personnel to be notified when an enrollment request needs approval, or has been approved:').'&nbsp;'.&Apache::loncommon::start_data_table().
 5861:                                &Apache::loncommon::start_data_table_row();
 5862:                     my $count = 0;
 5863:                     my $numcols = 4;
 5864:                     foreach my $cc (sort(@ccs)) {
 5865:                         my $notifyon;
 5866:                         my ($ccuname,$ccudom) = split(/:/,$cc);
 5867:                         if ($notified{$cc}) {
 5868:                             $notifyon = ' checked="checked" ';
 5869:                         }
 5870:                         if ($count && !$count%$numcols) {
 5871:                             $output .= &Apache::loncommon::end_data_table_row().
 5872:                                        &Apache::loncommon::start_data_table_row()
 5873:                         }
 5874:                         $output .= '<td><span class="LC_nobreak"><label>'.
 5875:                                    '<input type="checkbox" name="selfenroll_notify"'.$notifyon.' value="'.$cc.'" />'.
 5876:                                    &Apache::loncommon::plainname($ccuname,$ccudom).
 5877:                                    '</label></span></td>';
 5878:                         $count ++;
 5879:                     }
 5880:                     my $rem = $count%$numcols;
 5881:                     if ($rem) {
 5882:                         my $emptycols = $numcols - $rem;
 5883:                         for (my $i=0; $i<$emptycols; $i++) { 
 5884:                             $output .= '<td>&nbsp;</td>';
 5885:                         }
 5886:                     }
 5887:                     $output .= &Apache::loncommon::end_data_table_row().
 5888:                                &Apache::loncommon::end_data_table();
 5889:                 }
 5890:             } elsif ($item eq 'limit') {
 5891:                 my ($crslimit,$selflimit,$nolimit);
 5892:                 my $cid = $env{'request.course.id'};
 5893:                 my $currlim = $env{'course.'.$cid.'.internal.selfenroll_limit'};
 5894:                 my $currcap = $env{'course.'.$cid.'.internal.selfenroll_cap'};
 5895:                 $nolimit = ' checked="checked" ';
 5896:                 if ($currlim eq 'allstudents') {
 5897:                     $crslimit = ' checked="checked" ';
 5898:                     $selflimit = ' ';
 5899:                     $nolimit = ' ';
 5900:                 } elsif ($currlim eq 'selfenrolled') {
 5901:                     $crslimit = ' ';
 5902:                     $selflimit = ' checked="checked" ';
 5903:                     $nolimit = ' '; 
 5904:                 } else {
 5905:                     $crslimit = ' ';
 5906:                     $selflimit = ' ';
 5907:                 }
 5908:                 $output .= '<table><tr><td><label>'.
 5909:                            '<input type="radio" name="selfenroll_limit" value="none"'.$nolimit.'/>'.
 5910:                            &mt('No limit').'</label></td><td><label>'.
 5911:                            '<input type="radio" name="selfenroll_limit" value="allstudents"'.$crslimit.'/>'.
 5912:                            &mt('Limit by total students').'</label></td><td><label>'.
 5913:                            '<input type="radio" name="selfenroll_limit" value="selfenrolled"'.$selflimit.'/>'.
 5914:                            &mt('Limit by total self-enrolled students').
 5915:                            '</td></tr><tr>'.
 5916:                            '<td>&nbsp;</td><td colspan="2"><span class="LC_nobreak">'.
 5917:                            ('&nbsp;'x3).&mt('Maximum number allowed: ').
 5918:                            '<input type="text" name="selfenroll_cap" size = "5" value="'.$currcap.'" /></td></tr></table>';
 5919:             }
 5920:             $output .= &Apache::lonhtmlcommon::row_closure(1);
 5921:         }
 5922:     }
 5923:     $output .= &Apache::lonhtmlcommon::end_pick_box().
 5924:                '<br /><input type="button" name="selfenrollconf" value="'
 5925:                .&mt('Save').'" onclick="validate_types(this.form);" />'
 5926:                .'<input type="hidden" name="action" value="selfenroll" /></form>';
 5927:     $r->print($output);
 5928:     return;
 5929: }
 5930: 
 5931: sub visible_in_cat {
 5932:     my ($cdom,$cnum) = @_;
 5933:     my %domconf = &Apache::lonnet::get_dom('configuration',['coursecategories'],$cdom);
 5934:     my ($cathash,%settable,@vismsgs,$cansetvis);
 5935:     my %visactions = &Apache::lonlocal::texthash(
 5936:                    vis => 'Your course/community currently appears in the Course/Community Catalog for this domain.',
 5937:                    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.',
 5938:                    miss => 'Your course/community does not currently appear in the Course/Community Catalog for this domain.',
 5939:                    yous => 'You should remedy this if you plan to allow self-enrollment, otherwise students will have difficulty finding your course.',
 5940:                    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.',
 5941:                    make => 'Make any changes to self-enrollment settings below, click "Save", then take action to include the course in the Catalog:',
 5942:                    take => 'Take the following action to ensure the course appears in the Catalog:',
 5943:                    dc_unhide  => 'Ask a domain coordinator to change the "Exclude from course catalog" setting.',
 5944:                    dc_addinst => 'Ask a domain coordinator to enable display the catalog of "Official courses (with institutional codes)".',
 5945:                    dc_instcode => 'Ask a domain coordinator to assign an institutional code (if this is an official course).',
 5946:                    dc_catalog  => 'Ask a domain coordinator to enable or create at least one course category in the domain.',
 5947:                    dc_categories => 'Ask a domain coordinator to create a hierarchy of categories and sub categories for courses in the domain.',
 5948:                    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',
 5949:                    dc_addcat => 'Ask a domain coordinator to assign a category to the course.',
 5950:     );
 5951:     $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>"');
 5952:     $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>"');
 5953:     $visactions{'addcat'} = &mt('Use [_1]Categorize course[_2] to assign a category to the course.','"<a href="/adm/courseprefs?phase=display&actions=courseinfo">','</a>"');
 5954:     if (ref($domconf{'coursecategories'}) eq 'HASH') {
 5955:         if ($domconf{'coursecategories'}{'togglecats'} eq 'crs') {
 5956:             $settable{'togglecats'} = 1;
 5957:         }
 5958:         if ($domconf{'coursecategories'}{'categorize'} eq 'crs') {
 5959:             $settable{'categorize'} = 1;
 5960:         }
 5961:         $cathash = $domconf{'coursecategories'}{'cats'};
 5962:     }
 5963:     if ($settable{'togglecats'} && $settable{'categorize'}) {
 5964:         $cansetvis = &mt('You are able to both assign a course category and choose to exclude this course from the catalog.');   
 5965:     } elsif ($settable{'togglecats'}) {
 5966:         $cansetvis = &mt('You are able to choose to exclude this course from the catalog, but only a Domain Coordinator may assign a course category.'); 
 5967:     } elsif ($settable{'categorize'}) {
 5968:         $cansetvis = &mt('You may assign a course category, but only a Domain Coordinator may choose to exclude this course from the catalog.');  
 5969:     } else {
 5970:         $cansetvis = &mt('Only a Domain Coordinator may assign a course category or choose to exclude this course from the catalog.'); 
 5971:     }
 5972:      
 5973:     my %currsettings =
 5974:         &Apache::lonnet::get('environment',['hidefromcat','categories','internal.coursecode'],
 5975:                              $cdom,$cnum);
 5976:     my $visible = 0;
 5977:     if ($currsettings{'internal.coursecode'} ne '') {
 5978:         if (ref($domconf{'coursecategories'}) eq 'HASH') {
 5979:             $cathash = $domconf{'coursecategories'}{'cats'};
 5980:             if (ref($cathash) eq 'HASH') {
 5981:                 if ($cathash->{'instcode::0'} eq '') {
 5982:                     push(@vismsgs,'dc_addinst'); 
 5983:                 } else {
 5984:                     $visible = 1;
 5985:                 }
 5986:             } else {
 5987:                 $visible = 1;
 5988:             }
 5989:         } else {
 5990:             $visible = 1;
 5991:         }
 5992:     } else {
 5993:         if (ref($cathash) eq 'HASH') {
 5994:             if ($cathash->{'instcode::0'} ne '') {
 5995:                 push(@vismsgs,'dc_instcode');
 5996:             }
 5997:         } else {
 5998:             push(@vismsgs,'dc_instcode');
 5999:         }
 6000:     }
 6001:     if ($currsettings{'categories'} ne '') {
 6002:         my $cathash;
 6003:         if (ref($domconf{'coursecategories'}) eq 'HASH') {
 6004:             $cathash = $domconf{'coursecategories'}{'cats'};
 6005:             if (ref($cathash) eq 'HASH') {
 6006:                 if (keys(%{$cathash}) == 0) {
 6007:                     push(@vismsgs,'dc_catalog');
 6008:                 } elsif ((keys(%{$cathash}) == 1) && ($cathash->{'instcode::0'} ne '')) {
 6009:                     push(@vismsgs,'dc_categories');
 6010:                 } else {
 6011:                     my @currcategories = split('&',$currsettings{'categories'});
 6012:                     my $matched = 0;
 6013:                     foreach my $cat (@currcategories) {
 6014:                         if ($cathash->{$cat} ne '') {
 6015:                             $visible = 1;
 6016:                             $matched = 1;
 6017:                             last;
 6018:                         }
 6019:                     }
 6020:                     if (!$matched) {
 6021:                         if ($settable{'categorize'}) { 
 6022:                             push(@vismsgs,'chgcat');
 6023:                         } else {
 6024:                             push(@vismsgs,'dc_chgcat');
 6025:                         }
 6026:                     }
 6027:                 }
 6028:             }
 6029:         }
 6030:     } else {
 6031:         if (ref($cathash) eq 'HASH') {
 6032:             if ((keys(%{$cathash}) > 1) || 
 6033:                 (keys(%{$cathash}) == 1) && ($cathash->{'instcode::0'} eq '')) {
 6034:                 if ($settable{'categorize'}) {
 6035:                     push(@vismsgs,'addcat');
 6036:                 } else {
 6037:                     push(@vismsgs,'dc_addcat');
 6038:                 }
 6039:             }
 6040:         }
 6041:     }
 6042:     if ($currsettings{'hidefromcat'} eq 'yes') {
 6043:         $visible = 0;
 6044:         if ($settable{'togglecats'}) {
 6045:             unshift(@vismsgs,'unhide');
 6046:         } else {
 6047:             unshift(@vismsgs,'dc_unhide')
 6048:         }
 6049:     }
 6050:     return ($visible,$cansetvis,\@vismsgs,\%visactions);
 6051: }
 6052: 
 6053: sub new_selfenroll_dom_row {
 6054:     my ($newdom,$num) = @_;
 6055:     my $domdesc = &Apache::lonnet::domain($newdom);
 6056:     my $output;
 6057:     if ($domdesc ne '') {
 6058:         $output .= &Apache::loncommon::start_data_table_row()
 6059:                    .'<td valign="top"><span class="LC_nobreak">'.&mt('Domain:').'&nbsp;<b>'.$domdesc
 6060:                    .' ('.$newdom.')</b><input type="hidden" name="selfenroll_dom_'.$num
 6061:                    .'" value="'.$newdom.'" /></span><br />'
 6062:                    .'<span class="LC_nobreak"><label><input type="checkbox" '
 6063:                    .'name="selfenroll_activate" value="'.$num.'" '
 6064:                    .'onchange="javascript:update_types('
 6065:                    ."'selfenroll_activate','$num'".');" />'
 6066:                    .&mt('Activate').'</label></span></td>';
 6067:         my @currinsttypes;
 6068:         $output .= '<td>'.&mt('User types:').'<br />'
 6069:                    .&selfenroll_inst_types($num,$newdom,\@currinsttypes).'</td>'
 6070:                    .&Apache::loncommon::end_data_table_row();
 6071:     }
 6072:     return $output;
 6073: }
 6074: 
 6075: sub selfenroll_inst_types {
 6076:     my ($num,$currdom,$currinsttypes) = @_;
 6077:     my $output;
 6078:     my $numinrow = 4;
 6079:     my $count = 0;
 6080:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($currdom);
 6081:     my $othervalue = 'any';
 6082:     if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 6083:         if (keys(%{$usertypes}) > 0) {
 6084:             $othervalue = 'other';
 6085:         }
 6086:         $output .= '<table><tr>';
 6087:         foreach my $type (@{$types}) {
 6088:             if (($count > 0) && ($count%$numinrow == 0)) {
 6089:                 $output .= '</tr><tr>';
 6090:             }
 6091:             if (defined($usertypes->{$type})) {
 6092:                 my $esc_type = &escape($type);
 6093:                 $output .= '<td><span class="LC_nobreak"><label><input type = "checkbox" value="'.
 6094:                            $esc_type.'" ';
 6095:                 if (ref($currinsttypes) eq 'ARRAY') {
 6096:                     if (@{$currinsttypes} > 0) {
 6097:                         if (grep(/^any$/,@{$currinsttypes})) {
 6098:                             $output .= 'checked="checked"';
 6099:                         } elsif (grep(/^\Q$esc_type\E$/,@{$currinsttypes})) {
 6100:                             $output .= 'checked="checked"';
 6101:                         }
 6102:                     } else {
 6103:                         $output .= 'checked="checked"';
 6104:                     }
 6105:                 }
 6106:                 $output .= ' name="selfenroll_types_'.$num.'" />'.$usertypes->{$type}.'</label></span></td>';
 6107:             }
 6108:             $count ++;
 6109:         }
 6110:         if (($count > 0) && ($count%$numinrow == 0)) {
 6111:             $output .= '</tr><tr>';
 6112:         }
 6113:         $output .= '<td><span class="LC_nobreak"><label><input type = "checkbox" value="'.$othervalue.'"';
 6114:         if (ref($currinsttypes) eq 'ARRAY') {
 6115:             if (@{$currinsttypes} > 0) {
 6116:                 if (grep(/^any$/,@{$currinsttypes})) { 
 6117:                     $output .= ' checked="checked"';
 6118:                 } elsif ($othervalue eq 'other') {
 6119:                     if (grep(/^\Q$othervalue\E$/,@{$currinsttypes})) {
 6120:                         $output .= ' checked="checked"';
 6121:                     }
 6122:                 }
 6123:             } else {
 6124:                 $output .= ' checked="checked"';
 6125:             }
 6126:         } else {
 6127:             $output .= ' checked="checked"';
 6128:         }
 6129:         $output .= ' name="selfenroll_types_'.$num.'" />'.$othertitle.'</label></span></td></tr></table>';
 6130:     }
 6131:     return $output;
 6132: }
 6133: 
 6134: sub selfenroll_date_forms {
 6135:     my ($startform,$endform) = @_;
 6136:     my $output .= &Apache::lonhtmlcommon::start_pick_box()."\n".
 6137:                   &Apache::lonhtmlcommon::row_title(&mt('Start date'),
 6138:                                                     'LC_oddrow_value')."\n".
 6139:                   $startform."\n".
 6140:                   &Apache::lonhtmlcommon::row_closure(1).
 6141:                   &Apache::lonhtmlcommon::row_title(&mt('End date'),
 6142:                                                    'LC_oddrow_value')."\n".
 6143:                   $endform."\n".
 6144:                   &Apache::lonhtmlcommon::row_closure(1).
 6145:                   &Apache::lonhtmlcommon::end_pick_box();
 6146:     return $output;
 6147: }
 6148: 
 6149: sub print_userchangelogs_display {
 6150:     my ($r,$context,$permission) = @_;
 6151:     my $formname = 'rolelog';
 6152:     my ($username,$domain,$crstype,%roleslog);
 6153:     if ($context eq 'domain') {
 6154:         $domain = $env{'request.role.domain'};
 6155:         %roleslog=&Apache::lonnet::dump_dom('nohist_rolelog',$domain);
 6156:     } else {
 6157:         if ($context eq 'course') { 
 6158:             $domain = $env{'course.'.$env{'request.course.id'}.'.domain'};
 6159:             $username = $env{'course.'.$env{'request.course.id'}.'.num'};
 6160:             $crstype = &Apache::loncommon::course_type();
 6161:             my %saveable_parameters = ('show' => 'scalar',);
 6162:             &Apache::loncommon::store_course_settings('roles_log',
 6163:                                                       \%saveable_parameters);
 6164:             &Apache::loncommon::restore_course_settings('roles_log',
 6165:                                                         \%saveable_parameters);
 6166:         } elsif ($context eq 'author') {
 6167:             $domain = $env{'user.domain'}; 
 6168:             if ($env{'request.role'} =~ m{^au\./\Q$domain\E/$}) {
 6169:                 $username = $env{'user.name'};
 6170:             } else {
 6171:                 undef($domain);
 6172:             }
 6173:         }
 6174:         if ($domain ne '' && $username ne '') { 
 6175:             %roleslog=&Apache::lonnet::dump('nohist_rolelog',$domain,$username);
 6176:         }
 6177:     }
 6178:     if ((keys(%roleslog))[0]=~/^error\:/) { undef(%roleslog); }
 6179: 
 6180:     # set defaults
 6181:     my $now = time();
 6182:     my $defstart = $now - (7*24*3600); #7 days ago 
 6183:     my %defaults = (
 6184:                      page               => '1',
 6185:                      show               => '10',
 6186:                      role               => 'any',
 6187:                      chgcontext         => 'any',
 6188:                      rolelog_start_date => $defstart,
 6189:                      rolelog_end_date   => $now,
 6190:                    );
 6191:     my $more_records = 0;
 6192: 
 6193:     # set current
 6194:     my %curr;
 6195:     foreach my $item ('show','page','role','chgcontext') {
 6196:         $curr{$item} = $env{'form.'.$item};
 6197:     }
 6198:     my ($startdate,$enddate) = 
 6199:         &Apache::lonuserutils::get_dates_from_form('rolelog_start_date','rolelog_end_date');
 6200:     $curr{'rolelog_start_date'} = $startdate;
 6201:     $curr{'rolelog_end_date'} = $enddate;
 6202:     foreach my $key (keys(%defaults)) {
 6203:         if ($curr{$key} eq '') {
 6204:             $curr{$key} = $defaults{$key};
 6205:         }
 6206:     }
 6207:     my (%whodunit,%changed,$version);
 6208:     ($version) = ($r->dir_config('lonVersion') =~ /^([\d\.]+)\-/);
 6209:     my ($minshown,$maxshown);
 6210:     $minshown = 1;
 6211:     my $count = 0;
 6212:     if ($curr{'show'} ne &mt('all')) { 
 6213:         $maxshown = $curr{'page'} * $curr{'show'};
 6214:         if ($curr{'page'} > 1) {
 6215:             $minshown = 1 + ($curr{'page'} - 1) * $curr{'show'};
 6216:         }
 6217:     }
 6218: 
 6219:     # Form Header
 6220:     $r->print('<form action="/adm/createuser" method="post" name="'.$formname.'">'.
 6221:               &role_display_filter($context,$formname,$domain,$username,\%curr,
 6222:                                    $version,$crstype));
 6223: 
 6224:     # Create navigation
 6225:     my ($nav_script,$nav_links) = &userlogdisplay_nav($formname,\%curr,$more_records);
 6226:     my $showntableheader = 0;
 6227: 
 6228:     # Table Header
 6229:     my $tableheader = 
 6230:         &Apache::loncommon::start_data_table_header_row()
 6231:        .'<th>&nbsp;</th>'
 6232:        .'<th>'.&mt('When').'</th>'
 6233:        .'<th>'.&mt('Who made the change').'</th>'
 6234:        .'<th>'.&mt('Changed User').'</th>'
 6235:        .'<th>'.&mt('Role').'</th>';
 6236: 
 6237:     if ($context eq 'course') {
 6238:         $tableheader .= '<th>'.&mt('Section').'</th>';
 6239:     }
 6240:     $tableheader .=
 6241:         '<th>'.&mt('Context').'</th>'
 6242:        .'<th>'.&mt('Start').'</th>'
 6243:        .'<th>'.&mt('End').'</th>'
 6244:        .&Apache::loncommon::end_data_table_header_row();
 6245: 
 6246:     # Display user change log data
 6247:     foreach my $id (sort { $roleslog{$b}{'exe_time'}<=>$roleslog{$a}{'exe_time'} } (keys(%roleslog))) {
 6248:         next if (($roleslog{$id}{'exe_time'} < $curr{'rolelog_start_date'}) ||
 6249:                  ($roleslog{$id}{'exe_time'} > $curr{'rolelog_end_date'}));
 6250:         if ($curr{'show'} ne &mt('all')) {
 6251:             if ($count >= $curr{'page'} * $curr{'show'}) {
 6252:                 $more_records = 1;
 6253:                 last;
 6254:             }
 6255:         }
 6256:         if ($curr{'role'} ne 'any') {
 6257:             next if ($roleslog{$id}{'logentry'}{'role'} ne $curr{'role'}); 
 6258:         }
 6259:         if ($curr{'chgcontext'} ne 'any') {
 6260:             if ($curr{'chgcontext'} eq 'selfenroll') {
 6261:                 next if (!$roleslog{$id}{'logentry'}{'selfenroll'});
 6262:             } else {
 6263:                 next if ($roleslog{$id}{'logentry'}{'context'} ne $curr{'chgcontext'});
 6264:             }
 6265:         }
 6266:         $count ++;
 6267:         next if ($count < $minshown);
 6268:         unless ($showntableheader) {
 6269:             $r->print($nav_script
 6270:                      .$nav_links
 6271:                      .&Apache::loncommon::start_data_table()
 6272:                      .$tableheader);
 6273:             $r->rflush();
 6274:             $showntableheader = 1;
 6275:         }
 6276:         if ($whodunit{$roleslog{$id}{'exe_uname'}.':'.$roleslog{$id}{'exe_udom'}} eq '') {
 6277:             $whodunit{$roleslog{$id}{'exe_uname'}.':'.$roleslog{$id}{'exe_udom'}} =
 6278:                 &Apache::loncommon::plainname($roleslog{$id}{'exe_uname'},$roleslog{$id}{'exe_udom'});
 6279:         }
 6280:         if ($changed{$roleslog{$id}{'uname'}.':'.$roleslog{$id}{'udom'}} eq '') {
 6281:             $changed{$roleslog{$id}{'uname'}.':'.$roleslog{$id}{'udom'}} =
 6282:                 &Apache::loncommon::plainname($roleslog{$id}{'uname'},$roleslog{$id}{'udom'});
 6283:         }
 6284:         my $sec = $roleslog{$id}{'logentry'}{'section'};
 6285:         if ($sec eq '') {
 6286:             $sec = &mt('None');
 6287:         }
 6288:         my ($rolestart,$roleend);
 6289:         if ($roleslog{$id}{'delflag'}) {
 6290:             $rolestart = &mt('deleted');
 6291:             $roleend = &mt('deleted');
 6292:         } else {
 6293:             $rolestart = $roleslog{$id}{'logentry'}{'start'};
 6294:             $roleend = $roleslog{$id}{'logentry'}{'end'};
 6295:             if ($rolestart eq '' || $rolestart == 0) {
 6296:                 $rolestart = &mt('No start date'); 
 6297:             } else {
 6298:                 $rolestart = &Apache::lonlocal::locallocaltime($rolestart);
 6299:             }
 6300:             if ($roleend eq '' || $roleend == 0) { 
 6301:                 $roleend = &mt('No end date');
 6302:             } else {
 6303:                 $roleend = &Apache::lonlocal::locallocaltime($roleend);
 6304:             }
 6305:         }
 6306:         my $chgcontext = $roleslog{$id}{'logentry'}{'context'};
 6307:         if ($roleslog{$id}{'logentry'}{'selfenroll'}) {
 6308:             $chgcontext = 'selfenroll';
 6309:         }
 6310:         my %lt = &rolechg_contexts($context,$crstype);
 6311:         if ($chgcontext ne '' && $lt{$chgcontext} ne '') {
 6312:             $chgcontext = $lt{$chgcontext};
 6313:         }
 6314:         $r->print(
 6315:             &Apache::loncommon::start_data_table_row()
 6316:            .'<td>'.$count.'</td>'
 6317:            .'<td>'.&Apache::lonlocal::locallocaltime($roleslog{$id}{'exe_time'}).'</td>'
 6318:            .'<td>'.$whodunit{$roleslog{$id}{'exe_uname'}.':'.$roleslog{$id}{'exe_udom'}}.'</td>'
 6319:            .'<td>'.$changed{$roleslog{$id}{'uname'}.':'.$roleslog{$id}{'udom'}}.'</td>'
 6320:            .'<td>'.&Apache::lonnet::plaintext($roleslog{$id}{'logentry'}{'role'},$crstype).'</td>');
 6321:         if ($context eq 'course') { 
 6322:             $r->print('<td>'.$sec.'</td>');
 6323:         }
 6324:         $r->print(
 6325:             '<td>'.$chgcontext.'</td>'
 6326:            .'<td>'.$rolestart.'</td>'
 6327:            .'<td>'.$roleend.'</td>'
 6328:            .&Apache::loncommon::end_data_table_row()."\n");
 6329:     }
 6330: 
 6331:     if ($showntableheader) { # Table footer, if content displayed above
 6332:         $r->print(&Apache::loncommon::end_data_table()
 6333:                  .$nav_links);
 6334:     } else { # No content displayed above
 6335:         $r->print('<p class="LC_info">'
 6336:                  .&mt('There are no records to display.')
 6337:                  .'</p>'
 6338:         );
 6339:     }
 6340: 
 6341:     # Form Footer
 6342:     $r->print( 
 6343:         '<input type="hidden" name="page" value="'.$curr{'page'}.'" />'
 6344:        .'<input type="hidden" name="action" value="changelogs" />'
 6345:        .'</form>');
 6346:     return;
 6347: }
 6348: 
 6349: sub userlogdisplay_nav {
 6350:     my ($formname,$curr,$more_records) = @_;
 6351:     my ($nav_script,$nav_links);
 6352:     if (ref($curr) eq 'HASH') {
 6353:         # Create Navigation:
 6354:         # Navigation Script
 6355:         $nav_script = <<"ENDSCRIPT";
 6356: <script type="text/javascript">
 6357: // <![CDATA[
 6358: function chgPage(caller) {
 6359:     if (caller == 'previous') {
 6360:         document.$formname.page.value --;
 6361:     }
 6362:     if (caller == 'next') {
 6363:         document.$formname.page.value ++;
 6364:     }
 6365:     document.$formname.submit();
 6366:     return;
 6367: }
 6368: // ]]>
 6369: </script>
 6370: ENDSCRIPT
 6371:         # Navigation Buttons
 6372:         $nav_links = '<p>';
 6373:         if (($curr->{'page'} > 1) || ($more_records)) {
 6374:             if ($curr->{'page'} > 1) {
 6375:                 $nav_links .= '<input type="button"'
 6376:                              .' onclick="javascript:chgPage('."'previous'".');"'
 6377:                              .' value="'.&mt('Previous [_1] changes',$curr->{'show'})
 6378:                              .'" /> ';
 6379:             }
 6380:             if ($more_records) {
 6381:                 $nav_links .= '<input type="button"'
 6382:                              .' onclick="javascript:chgPage('."'next'".');"'
 6383:                              .' value="'.&mt('Next [_1] changes',$curr->{'show'})
 6384:                              .'" />';
 6385:             }
 6386:         }
 6387:         $nav_links .= '</p>';
 6388:     }
 6389:     return ($nav_script,$nav_links);
 6390: }
 6391: 
 6392: sub role_display_filter {
 6393:     my ($context,$formname,$cdom,$cnum,$curr,$version,$crstype) = @_;
 6394:     my $lctype;
 6395:     if ($context eq 'course') {
 6396:         $lctype = lc($crstype);
 6397:     }
 6398:     my $nolink = 1;
 6399:     my $output = '<table><tr><td valign="top">'.
 6400:                  '<span class="LC_nobreak"><b>'.&mt('Changes/page:').'</b></span><br />'.
 6401:                  &Apache::lonmeta::selectbox('show',$curr->{'show'},undef,
 6402:                                               (&mt('all'),5,10,20,50,100,1000,10000)).
 6403:                  '</td><td>&nbsp;&nbsp;</td>';
 6404:     my $startform =
 6405:         &Apache::lonhtmlcommon::date_setter($formname,'rolelog_start_date',
 6406:                                             $curr->{'rolelog_start_date'},undef,
 6407:                                             undef,undef,undef,undef,undef,undef,$nolink);
 6408:     my $endform =
 6409:         &Apache::lonhtmlcommon::date_setter($formname,'rolelog_end_date',
 6410:                                             $curr->{'rolelog_end_date'},undef,
 6411:                                             undef,undef,undef,undef,undef,undef,$nolink);
 6412:     my %lt = &rolechg_contexts($context,$crstype);
 6413:     $output .= '<td valign="top"><b>'.&mt('Window during which changes occurred:').'</b><br />'.
 6414:                '<table><tr><td>'.&mt('After:').
 6415:                '</td><td>'.$startform.'</td></tr>'.
 6416:                '<tr><td>'.&mt('Before:').'</td>'.
 6417:                '<td>'.$endform.'</td></tr></table>'.
 6418:                '</td>'.
 6419:                '<td>&nbsp;&nbsp;</td>'.
 6420:                '<td valign="top"><b>'.&mt('Role:').'</b><br />'.
 6421:                '<select name="role"><option value="any"';
 6422:     if ($curr->{'role'} eq 'any') {
 6423:         $output .= ' selected="selected"';
 6424:     }
 6425:     $output .=  '>'.&mt('Any').'</option>'."\n";
 6426:     my @roles = &Apache::lonuserutils::roles_by_context($context,1,$crstype);
 6427:     foreach my $role (@roles) {
 6428:         my $plrole;
 6429:         if ($role eq 'cr') {
 6430:             $plrole = &mt('Custom Role');
 6431:         } else {
 6432:             $plrole=&Apache::lonnet::plaintext($role,$crstype);
 6433:         }
 6434:         my $selstr = '';
 6435:         if ($role eq $curr->{'role'}) {
 6436:             $selstr = ' selected="selected"';
 6437:         }
 6438:         $output .= '  <option value="'.$role.'"'.$selstr.'>'.$plrole.'</option>';
 6439:     }
 6440:     $output .= '</select></td>'.
 6441:                '<td>&nbsp;&nbsp;</td>'.
 6442:                '<td valign="top"><b>'.
 6443:                &mt('Context:').'</b><br /><select name="chgcontext">';
 6444:     my @posscontexts;
 6445:     if ($context eq 'course') {
 6446:         @posscontexts = ('any','automated','updatenow','createcourse','course','domain','selfenroll','requestcourses');
 6447:     } elsif ($context eq 'domain') {
 6448:         @posscontexts = ('any','domain','requestauthor','domconfig','server');
 6449:     } else {
 6450:         @posscontexts = ('any','author','domain');
 6451:     } 
 6452:     foreach my $chgtype (@posscontexts) {
 6453:         my $selstr = '';
 6454:         if ($curr->{'chgcontext'} eq $chgtype) {
 6455:             $selstr = ' selected="selected"';
 6456:         }
 6457:         if ($context eq 'course') {
 6458:             if (($chgtype eq 'automated') || ($chgtype eq 'updatenow')) {
 6459:                 next if (!&Apache::lonnet::auto_run($cnum,$cdom));
 6460:             }
 6461:         }
 6462:         $output .= '<option value="'.$chgtype.'"'.$selstr.'>'.$lt{$chgtype}.'</option>'."\n";
 6463:     }
 6464:     $output .= '</select></td>'
 6465:               .'</tr></table>';
 6466: 
 6467:     # Update Display button
 6468:     $output .= '<p>'
 6469:               .'<input type="submit" value="'.&mt('Update Display').'" />'
 6470:               .'</p>';
 6471: 
 6472:     # Server version info
 6473:     my $needsrev = '2.11.0';
 6474:     if ($context eq 'course') {
 6475:         $needsrev = '2.7.0';
 6476:     }
 6477:     
 6478:     $output .= '<p class="LC_info">'
 6479:               .&mt('Only changes made from servers running LON-CAPA [_1] or later are displayed.'
 6480:                   ,$needsrev);
 6481:     if ($version) {
 6482:         $output .= ' '.&mt('This LON-CAPA server is version [_1]',$version);
 6483:     }
 6484:     $output .= '</p><hr />';
 6485:     return $output;
 6486: }
 6487: 
 6488: sub rolechg_contexts {
 6489:     my ($context,$crstype) = @_;
 6490:     my %lt;
 6491:     if ($context eq 'course') {
 6492:         %lt = &Apache::lonlocal::texthash (
 6493:                                              any          => 'Any',
 6494:                                              automated    => 'Automated Enrollment',
 6495:                                              updatenow    => 'Roster Update',
 6496:                                              createcourse => 'Course Creation',
 6497:                                              course       => 'User Management in course',
 6498:                                              domain       => 'User Management in domain',
 6499:                                              selfenroll   => 'Self-enrolled',
 6500:                                              requestcourses => 'Course Request',
 6501:                                          );
 6502:         if ($crstype eq 'Community') {
 6503:             $lt{'createcourse'} = &mt('Community Creation');
 6504:             $lt{'course'} = &mt('User Management in community');
 6505:             $lt{'requestcourses'} = &mt('Community Request');
 6506:         }
 6507:     } elsif ($context eq 'domain') {
 6508:         %lt = &Apache::lonlocal::texthash (
 6509:                                              any           => 'Any',
 6510:                                              domain        => 'User Management in domain',
 6511:                                              requestauthor => 'Authoring Request',
 6512:                                              server        => 'Command line script (DC role)',
 6513:                                              domconfig     => 'Self-enrolled',
 6514:                                          );
 6515:     } else {
 6516:         %lt = &Apache::lonlocal::texthash (
 6517:                                              any    => 'Any',
 6518:                                              domain => 'User Management in domain',
 6519:                                              author => 'User Management by author',
 6520:                                          );
 6521:     } 
 6522:     return %lt;
 6523: }
 6524: 
 6525: #-------------------------------------------------- functions for &phase_two
 6526: sub user_search_result {
 6527:     my ($context,$srch) = @_;
 6528:     my %allhomes;
 6529:     my %inst_matches;
 6530:     my %srch_results;
 6531:     my ($response,$currstate,$forcenewuser,$dirsrchres);
 6532:     $srch->{'srchterm'} =~ s/\s+/ /g;
 6533:     if ($srch->{'srchby'} !~ /^(uname|lastname|lastfirst)$/) {
 6534:         $response = &mt('Invalid search.');
 6535:     }
 6536:     if ($srch->{'srchin'} !~ /^(crs|dom|alc|instd)$/) {
 6537:         $response = &mt('Invalid search.');
 6538:     }
 6539:     if ($srch->{'srchtype'} !~ /^(exact|contains|begins)$/) {
 6540:         $response = &mt('Invalid search.');
 6541:     }
 6542:     if ($srch->{'srchterm'} eq '') {
 6543:         $response = &mt('You must enter a search term.');
 6544:     }
 6545:     if ($srch->{'srchterm'} =~ /^\s+$/) {
 6546:         $response = &mt('Your search term must contain more than just spaces.');
 6547:     }
 6548:     if (($srch->{'srchin'} eq 'dom') || ($srch->{'srchin'} eq 'instd')) {
 6549:         if (($srch->{'srchdomain'} eq '') || 
 6550: 	    ! (&Apache::lonnet::domain($srch->{'srchdomain'}))) {
 6551:             $response = &mt('You must specify a valid domain when searching in a domain or institutional directory.')
 6552:         }
 6553:     }
 6554:     if (($srch->{'srchin'} eq 'dom') || ($srch->{'srchin'} eq 'crs') ||
 6555:         ($srch->{'srchin'} eq 'alc')) {
 6556:         if ($srch->{'srchby'} eq 'uname') {
 6557:             my $unamecheck = $srch->{'srchterm'};
 6558:             if ($srch->{'srchtype'} eq 'contains') {
 6559:                 if ($unamecheck !~ /^\w/) {
 6560:                     $unamecheck = 'a'.$unamecheck; 
 6561:                 }
 6562:             }
 6563:             if ($unamecheck !~ /^$match_username$/) {
 6564:                 $response = &mt('You must specify a valid username. Only the following are allowed: letters numbers - . @');
 6565:             }
 6566:         }
 6567:     }
 6568:     if ($response ne '') {
 6569:         $response = '<span class="LC_warning">'.$response.'</span>';
 6570:     }
 6571:     if ($srch->{'srchin'} eq 'instd') {
 6572:         my $instd_chk = &directorysrch_check($srch);
 6573:         if ($instd_chk ne 'ok') {
 6574:             $response = '<span class="LC_warning">'.$instd_chk.'</span>'.
 6575:                         '<br />'.&mt('You may want to search in the LON-CAPA domain instead of the institutional directory.').'<br /><br />';
 6576:         }
 6577:     }
 6578:     if ($response ne '') {
 6579:         return ($currstate,$response);
 6580:     }
 6581:     if ($srch->{'srchby'} eq 'uname') {
 6582:         if (($srch->{'srchin'} eq 'dom') || ($srch->{'srchin'} eq 'crs')) {
 6583:             if ($env{'form.forcenew'}) {
 6584:                 if ($srch->{'srchdomain'} ne $env{'request.role.domain'}) {
 6585:                     my $uhome=&Apache::lonnet::homeserver($srch->{'srchterm'},$srch->{'srchdomain'});
 6586:                     if ($uhome eq 'no_host') {
 6587:                         my $domdesc = &Apache::lonnet::domain($env{'request.role.domain'},'description');
 6588:                         my $showdom = &display_domain_info($env{'request.role.domain'});
 6589:                         $response = &mt('New users can only be created in the domain to which your current role belongs - [_1].',$showdom);
 6590:                     } else {
 6591:                         $currstate = 'modify';
 6592:                     }
 6593:                 } else {
 6594:                     $currstate = 'modify';
 6595:                 }
 6596:             } else {
 6597:                 if ($srch->{'srchin'} eq 'dom') {
 6598:                     if ($srch->{'srchtype'} eq 'exact') {
 6599:                         my $uhome=&Apache::lonnet::homeserver($srch->{'srchterm'},$srch->{'srchdomain'});
 6600:                         if ($uhome eq 'no_host') {
 6601:                             ($currstate,$response,$forcenewuser) =
 6602:                                 &build_search_response($context,$srch,%srch_results);
 6603:                         } else {
 6604:                             $currstate = 'modify';
 6605:                             my $uname = $srch->{'srchterm'};
 6606:                             my $udom = $srch->{'srchdomain'};
 6607:                             $srch_results{$uname.':'.$udom} =
 6608:                                 { &Apache::lonnet::get('environment',
 6609:                                                        ['firstname',
 6610:                                                         'lastname',
 6611:                                                         'permanentemail'],
 6612:                                                          $udom,$uname)
 6613:                                 };
 6614:                         }
 6615:                     } else {
 6616:                         %srch_results = &Apache::lonnet::usersearch($srch);
 6617:                         ($currstate,$response,$forcenewuser) =
 6618:                             &build_search_response($context,$srch,%srch_results);
 6619:                     }
 6620:                 } else {
 6621:                     my $courseusers = &get_courseusers();
 6622:                     if ($srch->{'srchtype'} eq 'exact') {
 6623:                         if (exists($courseusers->{$srch->{'srchterm'}.':'.$srch->{'srchdomain'}})) {
 6624:                             $currstate = 'modify';
 6625:                         } else {
 6626:                             ($currstate,$response,$forcenewuser) =
 6627:                                 &build_search_response($context,$srch,%srch_results);
 6628:                         }
 6629:                     } else {
 6630:                         foreach my $user (keys(%$courseusers)) {
 6631:                             my ($cuname,$cudomain) = split(/:/,$user);
 6632:                             if ($cudomain eq $srch->{'srchdomain'}) {
 6633:                                 my $matched = 0;
 6634:                                 if ($srch->{'srchtype'} eq 'begins') {
 6635:                                     if ($cuname =~ /^\Q$srch->{'srchterm'}\E/i) {
 6636:                                         $matched = 1;
 6637:                                     }
 6638:                                 } else {
 6639:                                     if ($cuname =~ /\Q$srch->{'srchterm'}\E/i) {
 6640:                                         $matched = 1;
 6641:                                     }
 6642:                                 }
 6643:                                 if ($matched) {
 6644:                                     $srch_results{$user} = 
 6645: 					{&Apache::lonnet::get('environment',
 6646: 							     ['firstname',
 6647: 							      'lastname',
 6648: 							      'permanentemail'],
 6649: 							      $cudomain,$cuname)};
 6650:                                 }
 6651:                             }
 6652:                         }
 6653:                         ($currstate,$response,$forcenewuser) =
 6654:                             &build_search_response($context,$srch,%srch_results);
 6655:                     }
 6656:                 }
 6657:             }
 6658:         } elsif ($srch->{'srchin'} eq 'alc') {
 6659:             $currstate = 'query';
 6660:         } elsif ($srch->{'srchin'} eq 'instd') {
 6661:             ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query($srch);
 6662:             if ($dirsrchres eq 'ok') {
 6663:                 ($currstate,$response,$forcenewuser) = 
 6664:                     &build_search_response($context,$srch,%srch_results);
 6665:             } else {
 6666:                 my $showdom = &display_domain_info($srch->{'srchdomain'});
 6667:                 $response = '<span class="LC_warning">'.
 6668:                     &mt('Institutional directory search is not available in domain: [_1]',$showdom).
 6669:                     '</span><br />'.
 6670:                     &mt('You may want to search in the LON-CAPA domain instead of the institutional directory.').
 6671:                     '<br /><br />'; 
 6672:             }
 6673:         }
 6674:     } else {
 6675:         if ($srch->{'srchin'} eq 'dom') {
 6676:             %srch_results = &Apache::lonnet::usersearch($srch);
 6677:             ($currstate,$response,$forcenewuser) = 
 6678:                 &build_search_response($context,$srch,%srch_results); 
 6679:         } elsif ($srch->{'srchin'} eq 'crs') {
 6680:             my $courseusers = &get_courseusers(); 
 6681:             foreach my $user (keys(%$courseusers)) {
 6682:                 my ($uname,$udom) = split(/:/,$user);
 6683:                 my %names = &Apache::loncommon::getnames($uname,$udom);
 6684:                 my %emails = &Apache::loncommon::getemails($uname,$udom);
 6685:                 if ($srch->{'srchby'} eq 'lastname') {
 6686:                     if ((($srch->{'srchtype'} eq 'exact') && 
 6687:                          ($names{'lastname'} eq $srch->{'srchterm'})) || 
 6688:                         (($srch->{'srchtype'} eq 'begins') &&
 6689:                          ($names{'lastname'} =~ /^\Q$srch->{'srchterm'}\E/i)) ||
 6690:                         (($srch->{'srchtype'} eq 'contains') &&
 6691:                          ($names{'lastname'} =~ /\Q$srch->{'srchterm'}\E/i))) {
 6692:                         $srch_results{$user} = {firstname => $names{'firstname'},
 6693:                                             lastname => $names{'lastname'},
 6694:                                             permanentemail => $emails{'permanentemail'},
 6695:                                            };
 6696:                     }
 6697:                 } elsif ($srch->{'srchby'} eq 'lastfirst') {
 6698:                     my ($srchlast,$srchfirst) = split(/,/,$srch->{'srchterm'});
 6699:                     $srchlast =~ s/\s+$//;
 6700:                     $srchfirst =~ s/^\s+//;
 6701:                     if ($srch->{'srchtype'} eq 'exact') {
 6702:                         if (($names{'lastname'} eq $srchlast) &&
 6703:                             ($names{'firstname'} eq $srchfirst)) {
 6704:                             $srch_results{$user} = {firstname => $names{'firstname'},
 6705:                                                 lastname => $names{'lastname'},
 6706:                                                 permanentemail => $emails{'permanentemail'},
 6707: 
 6708:                                            };
 6709:                         }
 6710:                     } elsif ($srch->{'srchtype'} eq 'begins') {
 6711:                         if (($names{'lastname'} =~ /^\Q$srchlast\E/i) &&
 6712:                             ($names{'firstname'} =~ /^\Q$srchfirst\E/i)) {
 6713:                             $srch_results{$user} = {firstname => $names{'firstname'},
 6714:                                                 lastname => $names{'lastname'},
 6715:                                                 permanentemail => $emails{'permanentemail'},
 6716:                                                };
 6717:                         }
 6718:                     } else {
 6719:                         if (($names{'lastname'} =~ /\Q$srchlast\E/i) && 
 6720:                             ($names{'firstname'} =~ /\Q$srchfirst\E/i)) {
 6721:                             $srch_results{$user} = {firstname => $names{'firstname'},
 6722:                                                 lastname => $names{'lastname'},
 6723:                                                 permanentemail => $emails{'permanentemail'},
 6724:                                                };
 6725:                         }
 6726:                     }
 6727:                 }
 6728:             }
 6729:             ($currstate,$response,$forcenewuser) = 
 6730:                 &build_search_response($context,$srch,%srch_results); 
 6731:         } elsif ($srch->{'srchin'} eq 'alc') {
 6732:             $currstate = 'query';
 6733:         } elsif ($srch->{'srchin'} eq 'instd') {
 6734:             ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query($srch); 
 6735:             if ($dirsrchres eq 'ok') {
 6736:                 ($currstate,$response,$forcenewuser) = 
 6737:                     &build_search_response($context,$srch,%srch_results);
 6738:             } else {
 6739:                 my $showdom = &display_domain_info($srch->{'srchdomain'});                $response = '<span class="LC_warning">'.
 6740:                     &mt('Institutional directory search is not available in domain: [_1]',$showdom).
 6741:                     '</span><br />'.
 6742:                     &mt('You may want to search in the LON-CAPA domain instead of the institutional directory.').
 6743:                     '<br /><br />';
 6744:             }
 6745:         }
 6746:     }
 6747:     return ($currstate,$response,$forcenewuser,\%srch_results);
 6748: }
 6749: 
 6750: sub directorysrch_check {
 6751:     my ($srch) = @_;
 6752:     my $can_search = 0;
 6753:     my $response;
 6754:     my %dom_inst_srch = &Apache::lonnet::get_dom('configuration',
 6755:                                              ['directorysrch'],$srch->{'srchdomain'});
 6756:     my $showdom = &display_domain_info($srch->{'srchdomain'});
 6757:     if (ref($dom_inst_srch{'directorysrch'}) eq 'HASH') {
 6758:         if (!$dom_inst_srch{'directorysrch'}{'available'}) {
 6759:             return &mt('Institutional directory search is not available in domain: [_1]',$showdom); 
 6760:         }
 6761:         if ($dom_inst_srch{'directorysrch'}{'localonly'}) {
 6762:             if ($env{'request.role.domain'} ne $srch->{'srchdomain'}) {
 6763:                 return &mt('Institutional directory search in domain: [_1] is only allowed for users with a current role in the domain.',$showdom); 
 6764:             }
 6765:             my @usertypes = split(/:/,$env{'environment.inststatus'});
 6766:             if (!@usertypes) {
 6767:                 push(@usertypes,'default');
 6768:             }
 6769:             if (ref($dom_inst_srch{'directorysrch'}{'cansearch'}) eq 'ARRAY') {
 6770:                 foreach my $type (@usertypes) {
 6771:                     if (grep(/^\Q$type\E$/,@{$dom_inst_srch{'directorysrch'}{'cansearch'}})) {
 6772:                         $can_search = 1;
 6773:                         last;
 6774:                     }
 6775:                 }
 6776:             }
 6777:             if (!$can_search) {
 6778:                 my ($insttypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($srch->{'srchdomain'});
 6779:                 my @longtypes; 
 6780:                 foreach my $item (@usertypes) {
 6781:                     if (defined($insttypes->{$item})) { 
 6782:                         push (@longtypes,$insttypes->{$item});
 6783:                     } elsif ($item eq 'default') {
 6784:                         push (@longtypes,&mt('other')); 
 6785:                     }
 6786:                 }
 6787:                 my $insttype_str = join(', ',@longtypes); 
 6788:                 return &mt('Institutional directory search in domain: [_1] is not available to your user type: ',$showdom).$insttype_str;
 6789:             }
 6790:         } else {
 6791:             $can_search = 1;
 6792:         }
 6793:     } else {
 6794:         return &mt('Institutional directory search has not been configured for domain: [_1]',$showdom);
 6795:     }
 6796:     my %longtext = &Apache::lonlocal::texthash (
 6797:                        uname     => 'username',
 6798:                        lastfirst => 'last name, first name',
 6799:                        lastname  => 'last name',
 6800:                        contains  => 'contains',
 6801:                        exact     => 'as exact match to',
 6802:                        begins    => 'begins with',
 6803:                    );
 6804:     if ($can_search) {
 6805:         if (ref($dom_inst_srch{'directorysrch'}{'searchby'}) eq 'ARRAY') {
 6806:             if (!grep(/^\Q$srch->{'srchby'}\E$/,@{$dom_inst_srch{'directorysrch'}{'searchby'}})) {
 6807:                 return &mt('Institutional directory search in domain: [_1] is not available for searching by "[_2]"',$showdom,$longtext{$srch->{'srchby'}});
 6808:             }
 6809:         } else {
 6810:             return &mt('Institutional directory search in domain: [_1] is not available.', $showdom);
 6811:         }
 6812:     }
 6813:     if ($can_search) {
 6814:         if (ref($dom_inst_srch{'directorysrch'}{'searchtypes'}) eq 'ARRAY') {
 6815:             if (grep(/^\Q$srch->{'srchtype'}\E/,@{$dom_inst_srch{'directorysrch'}{'searchtypes'}})) {
 6816:                 return 'ok';
 6817:             } else {
 6818:                 return &mt('Institutional directory search in domain [_1] is not available for the requested search type: "[_2]"',$showdom,$longtext{$srch->{'srchtype'}});
 6819:             }
 6820:         } else {
 6821:             if ((($dom_inst_srch{'directorysrch'}{'searchtypes'} eq 'specify') &&
 6822:                  ($srch->{'srchtype'} eq 'exact' || $srch->{'srchtype'} eq 'contains')) ||
 6823:                 ($dom_inst_srch{'directorysrch'}{'searchtypes'} eq $srch->{'srchtype'})) {
 6824:                 return 'ok';
 6825:             } else {
 6826:                 return &mt('Institutional directory search in domain [_1] is not available for the requested search type: "[_2]"',$showdom,$longtext{$srch->{'srchtype'}});
 6827:             }
 6828:         }
 6829:     }
 6830: }
 6831: 
 6832: sub get_courseusers {
 6833:     my %advhash;
 6834:     my $classlist = &Apache::loncoursedata::get_classlist();
 6835:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles();
 6836:     foreach my $role (sort(keys(%coursepersonnel))) {
 6837:         foreach my $user (split(/\,/,$coursepersonnel{$role})) {
 6838: 	    if (!exists($classlist->{$user})) {
 6839: 		$classlist->{$user} = [];
 6840: 	    }
 6841:         }
 6842:     }
 6843:     return $classlist;
 6844: }
 6845: 
 6846: sub build_search_response {
 6847:     my ($context,$srch,%srch_results) = @_;
 6848:     my ($currstate,$response,$forcenewuser);
 6849:     my %names = (
 6850:           'uname'     => 'username',
 6851:           'lastname'  => 'last name',
 6852:           'lastfirst' => 'last name, first name',
 6853:           'crs'       => 'this course',
 6854:           'dom'       => 'LON-CAPA domain',
 6855:           'instd'     => 'the institutional directory for domain',
 6856:     );
 6857: 
 6858:     my %single = (
 6859:                    begins   => 'A match',
 6860:                    contains => 'A match',
 6861:                    exact    => 'An exact match',
 6862:                  );
 6863:     my %nomatch = (
 6864:                    begins   => 'No match',
 6865:                    contains => 'No match',
 6866:                    exact    => 'No exact match',
 6867:                   );
 6868:     if (keys(%srch_results) > 1) {
 6869:         $currstate = 'select';
 6870:     } else {
 6871:         if (keys(%srch_results) == 1) {
 6872:             $currstate = 'modify';
 6873:             $response = &mt("$single{$srch->{'srchtype'}} was found for the $names{$srch->{'srchby'}} ([_1]) in $names{$srch->{'srchin'}}.",$srch->{'srchterm'});
 6874:             if ($srch->{'srchin'} eq 'dom' || $srch->{'srchin'} eq 'instd') {
 6875:                 $response .= ': '.&display_domain_info($srch->{'srchdomain'});
 6876:             }
 6877:         } else { # Search has nothing found. Prepare message to user.
 6878:             $response = '<span class="LC_warning">';
 6879:             if ($srch->{'srchin'} eq 'dom' || $srch->{'srchin'} eq 'instd') {
 6880:                 $response .= &mt("$nomatch{$srch->{'srchtype'}} found for the $names{$srch->{'srchby'}} [_1] in $names{$srch->{'srchin'}}: [_2]",
 6881:                                  '<b>'.$srch->{'srchterm'}.'</b>',
 6882:                                  &display_domain_info($srch->{'srchdomain'}));
 6883:             } else {
 6884:                 $response .= &mt("$nomatch{$srch->{'srchtype'}} found for the $names{$srch->{'srchby'}} [_1] in $names{$srch->{'srchin'}}.",
 6885:                                  '<b>'.$srch->{'srchterm'}.'</b>');
 6886:             }
 6887:             $response .= '</span>';
 6888: 
 6889:             if ($srch->{'srchin'} ne 'alc') {
 6890:                 $forcenewuser = 1;
 6891:                 my $cansrchinst = 0; 
 6892:                 if ($srch->{'srchdomain'}) {
 6893:                     my %domconfig = &Apache::lonnet::get_dom('configuration',['directorysrch'],$srch->{'srchdomain'});
 6894:                     if (ref($domconfig{'directorysrch'}) eq 'HASH') {
 6895:                         if ($domconfig{'directorysrch'}{'available'}) {
 6896:                             $cansrchinst = 1;
 6897:                         } 
 6898:                     }
 6899:                 }
 6900:                 if ((($srch->{'srchby'} eq 'lastfirst') || 
 6901:                      ($srch->{'srchby'} eq 'lastname')) &&
 6902:                     ($srch->{'srchin'} eq 'dom')) {
 6903:                     if ($cansrchinst) {
 6904:                         $response .= '<br />'.&mt('You may want to broaden your search to a search of the institutional directory for the domain.');
 6905:                     }
 6906:                 }
 6907:                 if ($srch->{'srchin'} eq 'crs') {
 6908:                     $response .= '<br />'.&mt('You may want to broaden your search to the selected LON-CAPA domain.');
 6909:                 }
 6910:             }
 6911:             my $createdom = $env{'request.role.domain'};
 6912:             if ($context eq 'requestcrs') {
 6913:                 if ($env{'form.coursedom'} ne '') {
 6914:                     $createdom = $env{'form.coursedom'};
 6915:                 }
 6916:             }
 6917:             if (!($srch->{'srchby'} eq 'uname' && $srch->{'srchin'} eq 'dom' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchdomain'} eq $createdom)) {
 6918:                 my $cancreate =
 6919:                     &Apache::lonuserutils::can_create_user($createdom,$context);
 6920:                 my $targetdom = '<span class="LC_cusr_emph">'.$createdom.'</span>';
 6921:                 if ($cancreate) {
 6922:                     my $showdom = &display_domain_info($createdom); 
 6923:                     $response .= '<br /><br />'
 6924:                                 .'<b>'.&mt('To add a new user:').'</b>'
 6925:                                 .'<br />';
 6926:                     if ($context eq 'requestcrs') {
 6927:                         $response .= &mt("(You can only define new users in the new course's domain - [_1])",$targetdom);
 6928:                     } else {
 6929:                         $response .= &mt("(You can only create new users in your current role's domain - [_1])",$targetdom);
 6930:                     }
 6931:                     $response .='<ul><li>'
 6932:                                 .&mt("Set 'Domain/institution to search' to: [_1]",'<span class="LC_cusr_emph">'.$showdom.'</span>')
 6933:                                 .'</li><li>'
 6934:                                 .&mt("Set 'Search criteria' to: [_1]username is ..... in selected LON-CAPA domain[_2]",'<span class="LC_cusr_emph">','</span>')
 6935:                                 .'</li><li>'
 6936:                                 .&mt('Provide the proposed username')
 6937:                                 .'</li><li>'
 6938:                                 .&mt("Click 'Search'")
 6939:                                 .'</li></ul><br />';
 6940:                 } else {
 6941:                     my $helplink = ' href="javascript:helpMenu('."'display'".')"';
 6942:                     $response .= '<br /><br />';
 6943:                     if ($context eq 'requestcrs') {
 6944:                         $response .= &mt("You are not authorized to define new users in the new course's domain - [_1].",$targetdom);
 6945:                     } else {
 6946:                         $response .= &mt("You are not authorized to create new users in your current role's domain - [_1].",$targetdom);
 6947:                     }
 6948:                     $response .= '<br />'
 6949:                                  .&mt('Please contact the [_1]helpdesk[_2] if you need to create a new user.'
 6950:                                     ,' <a'.$helplink.'>'
 6951:                                     ,'</a>')
 6952:                                  .'<br /><br />';
 6953:                 }
 6954:             }
 6955:         }
 6956:     }
 6957:     return ($currstate,$response,$forcenewuser);
 6958: }
 6959: 
 6960: sub display_domain_info {
 6961:     my ($dom) = @_;
 6962:     my $output = $dom;
 6963:     if ($dom ne '') { 
 6964:         my $domdesc = &Apache::lonnet::domain($dom,'description');
 6965:         if ($domdesc ne '') {
 6966:             $output .= ' <span class="LC_cusr_emph">('.$domdesc.')</span>';
 6967:         }
 6968:     }
 6969:     return $output;
 6970: }
 6971: 
 6972: sub crumb_utilities {
 6973:     my %elements = (
 6974:        crtuser => {
 6975:            srchterm => 'text',
 6976:            srchin => 'selectbox',
 6977:            srchby => 'selectbox',
 6978:            srchtype => 'selectbox',
 6979:            srchdomain => 'selectbox',
 6980:        },
 6981:        crtusername => {
 6982:            srchterm => 'text',
 6983:            srchdomain => 'selectbox',
 6984:        },
 6985:        docustom => {
 6986:            rolename => 'selectbox',
 6987:            newrolename => 'textbox',
 6988:        },
 6989:        studentform => {
 6990:            srchterm => 'text',
 6991:            srchin => 'selectbox',
 6992:            srchby => 'selectbox',
 6993:            srchtype => 'selectbox',
 6994:            srchdomain => 'selectbox',
 6995:        },
 6996:     );
 6997: 
 6998:     my $jsback .= qq|
 6999: function backPage(formname,prevphase,prevstate) {
 7000:     if (typeof prevphase == 'undefined') {
 7001:         formname.phase.value = '';
 7002:     }
 7003:     else {  
 7004:         formname.phase.value = prevphase;
 7005:     }
 7006:     if (typeof prevstate == 'undefined') {
 7007:         formname.currstate.value = '';
 7008:     }
 7009:     else {
 7010:         formname.currstate.value = prevstate;
 7011:     }
 7012:     formname.submit();
 7013: }
 7014: |;
 7015:     return ($jsback,\%elements);
 7016: }
 7017: 
 7018: sub course_level_table {
 7019:     my ($inccourses,$showcredits,$defaultcredits) = @_;
 7020:     return unless (ref($inccourses) eq 'HASH');
 7021:     my $table = '';
 7022: # Custom Roles?
 7023: 
 7024:     my %customroles=&Apache::lonuserutils::my_custom_roles();
 7025:     my %lt=&Apache::lonlocal::texthash(
 7026:             'exs'  => "Existing sections",
 7027:             'new'  => "Define new section",
 7028:             'ssd'  => "Set Start Date",
 7029:             'sed'  => "Set End Date",
 7030:             'crl'  => "Course Level",
 7031:             'act'  => "Activate",
 7032:             'rol'  => "Role",
 7033:             'ext'  => "Extent",
 7034:             'grs'  => "Section",
 7035:             'crd'  => "Credits",
 7036:             'sta'  => "Start",
 7037:             'end'  => "End"
 7038:     );
 7039: 
 7040:     foreach my $protectedcourse (sort(keys(%{$inccourses}))) {
 7041: 	my $thiscourse=$protectedcourse;
 7042: 	$thiscourse=~s:_:/:g;
 7043: 	my %coursedata=&Apache::lonnet::coursedescription($thiscourse);
 7044:         my $isowner = &Apache::lonuserutils::is_courseowner($protectedcourse,$coursedata{'internal.courseowner'});
 7045: 	my $area=$coursedata{'description'};
 7046:         my $crstype=$coursedata{'type'};
 7047: 	if (!defined($area)) { $area=&mt('Unavailable course').': '.$protectedcourse; }
 7048: 	my ($domain,$cnum)=split(/\//,$thiscourse);
 7049:         my %sections_count;
 7050:         if (defined($env{'request.course.id'})) {
 7051:             if ($env{'request.course.id'} eq $domain.'_'.$cnum) {
 7052:                 %sections_count = 
 7053: 		    &Apache::loncommon::get_sections($domain,$cnum);
 7054:             }
 7055:         }
 7056:         my @roles = &Apache::lonuserutils::roles_by_context('course','',$crstype);
 7057: 	foreach my $role (@roles) {
 7058:             my $plrole=&Apache::lonnet::plaintext($role,$crstype);
 7059: 	    if ((&Apache::lonnet::allowed('c'.$role,$thiscourse)) ||
 7060:                 ((($role eq 'cc') || ($role eq 'co')) && ($isowner))) {
 7061:                 $table .= &course_level_row($protectedcourse,$role,$area,$domain,
 7062:                                             $plrole,\%sections_count,\%lt,
 7063:                                             $defaultcredits,$crstype);
 7064:             } elsif ($env{'request.course.sec'} ne '') {
 7065:                 if (&Apache::lonnet::allowed('c'.$role,$thiscourse.'/'.
 7066:                                              $env{'request.course.sec'})) {
 7067:                     $table .= &course_level_row($protectedcourse,$role,$area,$domain,
 7068:                                                 $plrole,\%sections_count,\%lt,
 7069:                                                 $defaultcredits,$crstype);
 7070:                 }
 7071:             }
 7072:         }
 7073:         if (&Apache::lonnet::allowed('ccr',$thiscourse)) {
 7074:             foreach my $cust (sort(keys(%customroles))) {
 7075:                 next if ($crstype eq 'Community' && $customroles{$cust} =~ /bre\&S/);
 7076:                 my $role = 'cr_cr_'.$env{'user.domain'}.'_'.$env{'user.name'}.'_'.$cust;
 7077:                 $table .= &course_level_row($protectedcourse,$role,$area,$domain,
 7078:                                             $cust,\%sections_count,\%lt);
 7079:             }
 7080: 	}
 7081:     }
 7082:     return '' if ($table eq ''); # return nothing if there is nothing 
 7083:                                  # in the table
 7084:     my $result;
 7085:     if (!$env{'request.course.id'}) {
 7086:         $result = '<h4>'.$lt{'crl'}.'</h4>'."\n";
 7087:     }
 7088:     $result .= 
 7089: &Apache::loncommon::start_data_table().
 7090: &Apache::loncommon::start_data_table_header_row().
 7091: '<th>'.$lt{'act'}.'</th><th>'.$lt{'rol'}.'</th>'."\n".
 7092: '<th>'.$lt{'ext'}.'</th><th>'.$lt{'crd'}.'</th>'."\n".
 7093: '<th>'.$lt{'grs'}.'</th><th>'.$lt{'sta'}.'</th>'."\n".
 7094: '<th>'.$lt{'end'}.'</th>'.
 7095: &Apache::loncommon::end_data_table_header_row().
 7096: $table.
 7097: &Apache::loncommon::end_data_table();
 7098:     return $result;
 7099: }
 7100: 
 7101: sub course_level_row {
 7102:     my ($protectedcourse,$role,$area,$domain,$plrole,$sections_count,
 7103:         $lt,$defaultcredits,$crstype) = @_;
 7104:     my $creditem;
 7105:     my $row = &Apache::loncommon::start_data_table_row().
 7106:               ' <td><input type="checkbox" name="act_'.
 7107:               $protectedcourse.'_'.$role.'" /></td>'."\n".
 7108:               ' <td>'.$plrole.'</td>'."\n".
 7109:               ' <td>'.$area.'<br />Domain: '.$domain.'</td>'."\n";
 7110:     if (($role eq 'st') && ($crstype eq 'Course')) {
 7111:         $row .= 
 7112:             '<td><input type="text" name="credits_'.$protectedcourse.'_'.
 7113:             $role.'" size="3" value="'.$defaultcredits.'" /></td>';
 7114:     } else {
 7115:         $row .= '<td>&nbsp;</td>';
 7116:     }
 7117:     if (($role eq 'cc') || ($role eq 'co')) {
 7118:         $row .= '<td>&nbsp;</td>';
 7119:     } elsif ($env{'request.course.sec'} ne '') {
 7120:         $row .= ' <td><input type="hidden" value="'.
 7121:                 $env{'request.course.sec'}.'" '.
 7122:                 'name="sec_'.$protectedcourse.'_'.$role.'" />'.
 7123:                 $env{'request.course.sec'}.'</td>';
 7124:     } else {
 7125:         if (ref($sections_count) eq 'HASH') {
 7126:             my $currsec = 
 7127:                 &Apache::lonuserutils::course_sections($sections_count,
 7128:                                                        $protectedcourse.'_'.$role);
 7129:             $row .= '<td><table class="LC_createuser">'."\n".
 7130:                     '<tr class="LC_section_row">'."\n".
 7131:                     ' <td valign="top">'.$lt->{'exs'}.'<br />'.
 7132:                        $currsec.'</td>'."\n".
 7133:                      ' <td>&nbsp;&nbsp;</td>'."\n".
 7134:                      ' <td valign="top">&nbsp;'.$lt->{'new'}.'<br />'.
 7135:                      '<input type="text" name="newsec_'.$protectedcourse.'_'.$role.
 7136:                      '" value="" />'.
 7137:                      '<input type="hidden" '.
 7138:                      'name="sec_'.$protectedcourse.'_'.$role.'" /></td>'."\n".
 7139:                      '</tr></table></td>'."\n";
 7140:         } else {
 7141:             $row .= '<td><input type="text" size="10" '.
 7142:                     'name="sec_'.$protectedcourse.'_'.$role.'" /></td>'."\n";
 7143:         }
 7144:     }
 7145:     $row .= <<ENDTIMEENTRY;
 7146: <td><input type="hidden" name="start_$protectedcourse\_$role" value="" />
 7147: <a href=
 7148: "javascript:pjump('date_start','Start Date $plrole',document.cu.start_$protectedcourse\_$role.value,'start_$protectedcourse\_$role','cu.pres','dateset')">$lt->{'ssd'}</a></td>
 7149: <td><input type="hidden" name="end_$protectedcourse\_$role" value="" />
 7150: <a href=
 7151: "javascript:pjump('date_end','End Date $plrole',document.cu.end_$protectedcourse\_$role.value,'end_$protectedcourse\_$role','cu.pres','dateset')">$lt->{'sed'}</a></td>
 7152: ENDTIMEENTRY
 7153:     $row .= &Apache::loncommon::end_data_table_row();
 7154:     return $row;
 7155: }
 7156: 
 7157: sub course_level_dc {
 7158:     my ($dcdom,$showcredits) = @_;
 7159:     my %customroles=&Apache::lonuserutils::my_custom_roles();
 7160:     my @roles = &Apache::lonuserutils::roles_by_context('course');
 7161:     my $hiddenitems = '<input type="hidden" name="dcdomain" value="'.$dcdom.'" />'.
 7162:                       '<input type="hidden" name="origdom" value="'.$dcdom.'" />'.
 7163:                       '<input type="hidden" name="dccourse" value="" />';
 7164:     my $courseform=&Apache::loncommon::selectcourse_link
 7165:             ('cu','dccourse','dcdomain','coursedesc',undef,undef,'Select','crstype');
 7166:     my $credit_elem;
 7167:     if ($showcredits) {
 7168:         $credit_elem = 'credits';
 7169:     }
 7170:     my $cb_jscript = &Apache::loncommon::coursebrowser_javascript($dcdom,'currsec','cu','role','Course/Community Browser',$credit_elem);
 7171:     my %lt=&Apache::lonlocal::texthash(
 7172:                     'rol'  => "Role",
 7173:                     'grs'  => "Section",
 7174:                     'exs'  => "Existing sections",
 7175:                     'new'  => "Define new section", 
 7176:                     'sta'  => "Start",
 7177:                     'end'  => "End",
 7178:                     'ssd'  => "Set Start Date",
 7179:                     'sed'  => "Set End Date",
 7180:                     'scc'  => "Course/Community",
 7181:                     'crd'  => "Credits",
 7182:                   );
 7183:     my $header = '<h4>'.&mt('Course/Community Level').'</h4>'.
 7184:                  &Apache::loncommon::start_data_table().
 7185:                  &Apache::loncommon::start_data_table_header_row().
 7186:                  '<th>'.$lt{'scc'}.'</th><th>'.$lt{'rol'}.'</th>'."\n".
 7187:                  '<th>'.$lt{'grs'}.'</th><th>'.$lt{'crd'}.'</th>'."\n".
 7188:                  '<th>'.$lt{'sta'}.'</th><th>'.$lt{'end'}.'</th>'."\n".
 7189:                  &Apache::loncommon::end_data_table_header_row();
 7190:     my $otheritems = &Apache::loncommon::start_data_table_row()."\n".
 7191:                      '<td><br /><span class="LC_nobreak"><input type="text" name="coursedesc" value="" onfocus="this.blur();opencrsbrowser('."'cu','dccourse','dcdomain','coursedesc','','','','crstype'".')" />'.
 7192:                      $courseform.('&nbsp;' x4).'</span></td>'."\n".
 7193:                      '<td valign="top"><br /><select name="role">'."\n";
 7194:     foreach my $role (@roles) {
 7195:         my $plrole=&Apache::lonnet::plaintext($role);
 7196:         $otheritems .= '  <option value="'.$role.'">'.$plrole.'</option>';
 7197:     }
 7198:     if ( keys %customroles > 0) {
 7199:         foreach my $cust (sort keys %customroles) {
 7200:             my $custrole='cr_cr_'.$env{'user.domain'}.
 7201:                     '_'.$env{'user.name'}.'_'.$cust;
 7202:             $otheritems .= '  <option value="'.$custrole.'">'.$cust.'</option>';
 7203:         }
 7204:     }
 7205:     $otheritems .= '</select></td><td>'.
 7206:                      '<table border="0" cellspacing="0" cellpadding="0">'.
 7207:                      '<tr><td valign="top"><b>'.$lt{'exs'}.'</b><br /><select name="currsec">'.
 7208:                      ' <option value="">&lt;--'.&mt('Pick course first').'</option></select></td>'.
 7209:                      '<td>&nbsp;&nbsp;</td>'.
 7210:                      '<td valign="top">&nbsp;<b>'.$lt{'new'}.'</b><br />'.
 7211:                      '<input type="text" name="newsec" value="" />'.
 7212:                      '<input type="hidden" name="section" value="" />'.
 7213:                      '<input type="hidden" name="groups" value="" />'.
 7214:                      '<input type="hidden" name="crstype" value="" /></td>'.
 7215:                      '</tr></table></td>'."\n";
 7216:     if ($showcredits) {
 7217:         $otheritems .= '<td><br />'."\n".
 7218:                        '<input type="text" size="3" name="credits" value="" />'."\n";
 7219:     }
 7220:     $otheritems .= <<ENDTIMEENTRY;
 7221: <td><br /><input type="hidden" name="start" value='' />
 7222: <a href=
 7223: "javascript:pjump('date_start','Start Date',document.cu.start.value,'start','cu.pres','dateset')">$lt{'ssd'}</a></td>
 7224: <td><br /><input type="hidden" name="end" value='' />
 7225: <a href=
 7226: "javascript:pjump('date_end','End Date',document.cu.end.value,'end','cu.pres','dateset')">$lt{'sed'}</a></td>
 7227: ENDTIMEENTRY
 7228:     $otheritems .= &Apache::loncommon::end_data_table_row().
 7229:                    &Apache::loncommon::end_data_table()."\n";
 7230:     return $cb_jscript.$header.$hiddenitems.$otheritems;
 7231: }
 7232: 
 7233: sub update_selfenroll_config {
 7234:     my ($r,$context,$permission) = @_;
 7235:     my ($row,$lt) = &get_selfenroll_titles();
 7236:     my %curr_groups = &Apache::longroup::coursegroups();
 7237:     my (%changes,%warning);
 7238:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7239:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7240:     my $curr_types;
 7241:     if (ref($row) eq 'ARRAY') {
 7242:         foreach my $item (@{$row}) {
 7243:             if ($item eq 'enroll_dates') {
 7244:                 my (%currenrolldate,%newenrolldate);
 7245:                 foreach my $type ('start','end') {
 7246:                     $currenrolldate{$type} = $env{'course.'.$env{'request.course.id'}.'.internal.selfenroll_'.$type.'_date'};
 7247:                     $newenrolldate{$type} = &Apache::lonhtmlcommon::get_date_from_form('selfenroll_'.$type.'_date');
 7248:                     if ($newenrolldate{$type} ne $currenrolldate{$type}) {
 7249:                         $changes{'internal.selfenroll_'.$type.'_date'} = $newenrolldate{$type};
 7250:                     }
 7251:                 }
 7252:             } elsif ($item eq 'access_dates') {
 7253:                 my (%currdate,%newdate);
 7254:                 foreach my $type ('start','end') {
 7255:                     $currdate{$type} = $env{'course.'.$env{'request.course.id'}.'.internal.selfenroll_'.$type.'_access'};
 7256:                     $newdate{$type} = &Apache::lonhtmlcommon::get_date_from_form('selfenroll_'.$type.'_access');
 7257:                     if ($newdate{$type} ne $currdate{$type}) {
 7258:                         $changes{'internal.selfenroll_'.$type.'_access'} = $newdate{$type};
 7259:                     }
 7260:                 }
 7261:             } elsif ($item eq 'types') {
 7262:                 $curr_types =
 7263:                     $env{'course.'.$env{'request.course.id'}.'.internal.selfenroll_'.$item};
 7264:                 if ($env{'form.selfenroll_all'}) {
 7265:                     if ($curr_types ne '*') {
 7266:                         $changes{'internal.selfenroll_types'} = '*';
 7267:                     } else {
 7268:                         next;
 7269:                     }
 7270:                 } else {
 7271:                     my %currdoms;
 7272:                     my @entries = split(/;/,$curr_types);
 7273:                     my @deletedoms = &Apache::loncommon::get_env_multiple('form.selfenroll_delete');
 7274:                     my @activations = &Apache::loncommon::get_env_multiple('form.selfenroll_activate');
 7275:                     my $newnum = 0;
 7276:                     my @latesttypes;
 7277:                     foreach my $num (@activations) {
 7278:                         my @types = &Apache::loncommon::get_env_multiple('form.selfenroll_types_'.$num);
 7279:                         if (@types > 0) {
 7280:                             @types = sort(@types);
 7281:                             my $typestr = join(',',@types);
 7282:                             my $typedom = $env{'form.selfenroll_dom_'.$num};
 7283:                             $latesttypes[$newnum] = $typedom.':'.$typestr;
 7284:                             $currdoms{$typedom} = 1;
 7285:                             $newnum ++;
 7286:                         }
 7287:                     }
 7288:                     for (my $j=0; $j<$env{'form.selfenroll_types_total'}; $j++) {
 7289:                         if ((!grep(/^$j$/,@deletedoms)) && (!grep(/^$j$/,@activations))) {
 7290:                             my @types = &Apache::loncommon::get_env_multiple('form.selfenroll_types_'.$j);
 7291:                             if (@types > 0) {
 7292:                                 @types = sort(@types);
 7293:                                 my $typestr = join(',',@types);
 7294:                                 my $typedom = $env{'form.selfenroll_dom_'.$j};
 7295:                                 $latesttypes[$newnum] = $typedom.':'.$typestr;
 7296:                                 $currdoms{$typedom} = 1;
 7297:                                 $newnum ++;
 7298:                             }
 7299:                         }
 7300:                     }
 7301:                     if ($env{'form.selfenroll_newdom'} ne '') {
 7302:                         my $typedom = $env{'form.selfenroll_newdom'};
 7303:                         if ((!defined($currdoms{$typedom})) && 
 7304:                             (&Apache::lonnet::domain($typedom) ne '')) {
 7305:                             my $typestr;
 7306:                             my ($othertitle,$usertypes,$types) = 
 7307:                                 &Apache::loncommon::sorted_inst_types($typedom);
 7308:                             my $othervalue = 'any';
 7309:                             if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 7310:                                 if (@{$types} > 0) {
 7311:                                     my @esc_types = map { &escape($_); } @{$types};
 7312:                                     $othervalue = 'other';
 7313:                                     $typestr = join(',',(@esc_types,$othervalue));
 7314:                                 }
 7315:                                 $typestr = $othervalue;
 7316:                             } else {
 7317:                                 $typestr = $othervalue;
 7318:                             } 
 7319:                             $latesttypes[$newnum] = $typedom.':'.$typestr;
 7320:                             $newnum ++ ;
 7321:                         }
 7322:                     }
 7323:                     my $selfenroll_types = join(';',@latesttypes);
 7324:                     if ($selfenroll_types ne $curr_types) {
 7325:                         $changes{'internal.selfenroll_types'} = $selfenroll_types;
 7326:                     }
 7327:                 }
 7328:             } elsif ($item eq 'limit') {
 7329:                 my $newlimit = $env{'form.selfenroll_limit'};
 7330:                 my $newcap = $env{'form.selfenroll_cap'};
 7331:                 $newcap =~s/\s+//g;
 7332:                 my $currlimit =  $env{'course.'.$env{'request.course.id'}.'.internal.selfenroll_limit'};
 7333:                 $currlimit = 'none' if ($currlimit eq '');
 7334:                 my $currcap = $env{'course.'.$env{'request.course.id'}.'.internal.selfenroll_cap'};
 7335:                 if ($newlimit ne $currlimit) {
 7336:                     if ($newlimit ne 'none') {
 7337:                         if ($newcap =~ /^\d+$/) {
 7338:                             if ($newcap ne $currcap) {
 7339:                                 $changes{'internal.selfenroll_cap'} = $newcap;
 7340:                             }
 7341:                             $changes{'internal.selfenroll_limit'} = $newlimit;
 7342:                         } else {
 7343:                             $warning{$item} = &mt('Maximum enrollment setting unchanged.').'<br />'.&mt('The value provided was invalid - it must be a positive integer if enrollment is being limited.'); 
 7344:                         }
 7345:                     } elsif ($currcap ne '') {
 7346:                         $changes{'internal.selfenroll_cap'} = '';
 7347:                         $changes{'internal.selfenroll_limit'} = $newlimit; 
 7348:                     }
 7349:                 } elsif ($currlimit ne 'none') {
 7350:                     if ($newcap =~ /^\d+$/) {
 7351:                         if ($newcap ne $currcap) {
 7352:                             $changes{'internal.selfenroll_cap'} = $newcap;
 7353:                         }
 7354:                     } else {
 7355:                         $warning{$item} = &mt('Maximum enrollment setting unchanged.').'<br />'.&mt('The value provided was invalid - it must be a positive integer if enrollment is being limited.');
 7356:                     }
 7357:                 }
 7358:             } elsif ($item eq 'approval') {
 7359:                 my (@currnotified,@newnotified);
 7360:                 my $currapproval = $env{'course.'.$env{'request.course.id'}.'.internal.selfenroll_approval'};
 7361:                 my $currnotifylist = $env{'course.'.$env{'request.course.id'}.'.internal.selfenroll_notifylist'};
 7362:                 if ($currnotifylist ne '') {
 7363:                     @currnotified = split(/,/,$currnotifylist);
 7364:                     @currnotified = sort(@currnotified);
 7365:                 }
 7366:                 my $newapproval = $env{'form.selfenroll_approval'};
 7367:                 @newnotified = &Apache::loncommon::get_env_multiple('form.selfenroll_notify');
 7368:                 @newnotified = sort(@newnotified);
 7369:                 if ($newapproval ne $currapproval) {
 7370:                     $changes{'internal.selfenroll_approval'} = $newapproval;
 7371:                     if (!$newapproval) {
 7372:                         if ($currnotifylist ne '') {
 7373:                             $changes{'internal.selfenroll_notifylist'} = '';
 7374:                         }
 7375:                     } else {
 7376:                         my @differences =  
 7377:                             &Apache::loncommon::compare_arrays(\@currnotified,\@newnotified);
 7378:                         if (@differences > 0) {
 7379:                             if (@newnotified > 0) {
 7380:                                 $changes{'internal.selfenroll_notifylist'} = join(',',@newnotified);
 7381:                             } else {
 7382:                                 $changes{'internal.selfenroll_notifylist'} = join(',',@newnotified);
 7383:                             }
 7384:                         }
 7385:                     }
 7386:                 } else {
 7387:                     my @differences = &Apache::loncommon::compare_arrays(\@currnotified,\@newnotified);
 7388:                     if (@differences > 0) {
 7389:                         if (@newnotified > 0) {
 7390:                             $changes{'internal.selfenroll_notifylist'} = join(',',@newnotified);
 7391:                         } else {
 7392:                             $changes{'internal.selfenroll_notifylist'} = '';
 7393:                         }
 7394:                     }
 7395:                 }
 7396:             } else {
 7397:                 my $curr_val = 
 7398:                     $env{'course.'.$env{'request.course.id'}.'.internal.selfenroll_'.$item};
 7399:                 my $newval = $env{'form.selfenroll_'.$item};
 7400:                 if ($item eq 'section') {
 7401:                     $newval = $env{'form.sections'};
 7402:                     if (defined($curr_groups{$newval})) {
 7403:                         $newval = $curr_val;
 7404:                         $warning{$item} = &mt('Section for self-enrolled users unchanged as the proposed section is a group').'<br />'.&mt('Group names and section names must be distinct');
 7405:                     } elsif ($newval eq 'all') {
 7406:                         $newval = $curr_val;
 7407:                         $warning{$item} = &mt('Section for self-enrolled users unchanged, as "all" is a reserved section name.');
 7408:                     }
 7409:                     if ($newval eq '') {
 7410:                         $newval = 'none';
 7411:                     }
 7412:                 }
 7413:                 if ($newval ne $curr_val) {
 7414:                     $changes{'internal.selfenroll_'.$item} = $newval;
 7415:                 }
 7416:             }
 7417:         }
 7418:         if (keys(%warning) > 0) {
 7419:             foreach my $item (@{$row}) {
 7420:                 if (exists($warning{$item})) {
 7421:                     $r->print($warning{$item}.'<br />');
 7422:                 }
 7423:             } 
 7424:         }
 7425:         if (keys(%changes) > 0) {
 7426:             my $putresult = &Apache::lonnet::put('environment',\%changes,$cdom,$cnum);
 7427:             if ($putresult eq 'ok') {
 7428:                 if ((exists($changes{'internal.selfenroll_types'})) ||
 7429:                     (exists($changes{'internal.selfenroll_start_date'}))  ||
 7430:                     (exists($changes{'internal.selfenroll_end_date'}))) {
 7431:                     my %crsinfo = &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',
 7432:                                                                 $cnum,undef,undef,'Course');
 7433:                     my $chome = &Apache::lonnet::homeserver($cnum,$cdom);
 7434:                     if (ref($crsinfo{$env{'request.course.id'}}) eq 'HASH') {
 7435:                         foreach my $item ('selfenroll_types','selfenroll_start_date','selfenroll_end_date') {
 7436:                             if (exists($changes{'internal.'.$item})) {
 7437:                                 $crsinfo{$env{'request.course.id'}}{$item} = 
 7438:                                     $changes{'internal.'.$item};
 7439:                             }
 7440:                         }
 7441:                         my $crsputresult =
 7442:                             &Apache::lonnet::courseidput($cdom,\%crsinfo,
 7443:                                                          $chome,'notime');
 7444:                     }
 7445:                 }
 7446:                 $r->print(&mt('The following changes were made to self-enrollment settings:').'<ul>');
 7447:                 foreach my $item (@{$row}) {
 7448:                     my $title = $item;
 7449:                     if (ref($lt) eq 'HASH') {
 7450:                         $title = $lt->{$item};
 7451:                     }
 7452:                     if ($item eq 'enroll_dates') {
 7453:                         foreach my $type ('start','end') {
 7454:                             if (exists($changes{'internal.selfenroll_'.$type.'_date'})) {
 7455:                                 my $newdate = &Apache::lonlocal::locallocaltime($changes{'internal.selfenroll_'.$type.'_date'});
 7456:                                 $r->print('<li>'.&mt('[_1]: "[_2]" set to "[_3]".',
 7457:                                           $title,$type,$newdate).'</li>');
 7458:                             }
 7459:                         }
 7460:                     } elsif ($item eq 'access_dates') {
 7461:                         foreach my $type ('start','end') {
 7462:                             if (exists($changes{'internal.selfenroll_'.$type.'_access'})) {
 7463:                                 my $newdate = &Apache::lonlocal::locallocaltime($changes{'internal.selfenroll_'.$type.'_access'});
 7464:                                 $r->print('<li>'.&mt('[_1]: "[_2]" set to "[_3]".',
 7465:                                           $title,$type,$newdate).'</li>');
 7466:                             }
 7467:                         }
 7468:                     } elsif ($item eq 'limit') {
 7469:                         if ((exists($changes{'internal.selfenroll_limit'})) ||
 7470:                             (exists($changes{'internal.selfenroll_cap'}))) {
 7471:                             my ($newval,$newcap);
 7472:                             if ($changes{'internal.selfenroll_cap'} ne '') {
 7473:                                 $newcap = $changes{'internal.selfenroll_cap'}
 7474:                             } else {
 7475:                                 $newcap = $env{'course.'.$env{'request.course.id'}.'.internal.selfenroll_cap'};
 7476:                             }
 7477:                             if ($changes{'internal.selfenroll_limit'} eq 'none') {
 7478:                                 $newval = &mt('No limit');
 7479:                             } elsif ($changes{'internal.selfenroll_limit'} eq 
 7480:                                      'allstudents') {
 7481:                                 $newval = &mt('New self-enrollment no longer allowed when total (all students) reaches [_1].',$newcap);
 7482:                             } elsif ($changes{'internal.selfenroll_limit'} eq 'selfenrolled') {
 7483:                                 $newval = &mt('New self-enrollment no longer allowed when total number of self-enrolled students reaches [_1].',$newcap);
 7484:                             } else {
 7485:                                 my $currlimit =  $env{'course.'.$env{'request.course.id'}.'.internal.selfenroll_limit'};
 7486:                                 if ($currlimit eq 'allstudents') {
 7487:                                     $newval = &mt('New self-enrollment no longer allowed when total (all students) reaches [_1].',$newcap);
 7488:                                 } elsif ($changes{'internal.selfenroll_limit'} eq 'selfenrolled') {
 7489:                                     $newval =  &mt('New self-enrollment no longer allowed when total number of self-enrolled students reaches [_1].',$newcap);
 7490:                                 }
 7491:                             }
 7492:                             $r->print('<li>'.&mt('"[_1]" set to "[_2]".',$title,$newval).'</li>'."\n");
 7493:                         }
 7494:                     } elsif ($item eq 'approval') {
 7495:                         if ((exists($changes{'internal.selfenroll_approval'})) ||
 7496:                             (exists($changes{'internal.selfenroll_notifylist'}))) {
 7497:                             my ($newval,$newnotify);
 7498:                             if (exists($changes{'internal.selfenroll_notifylist'})) {
 7499:                                 $newnotify = $changes{'internal.selfenroll_notifylist'};
 7500:                             } else {   
 7501:                                 $newnotify = $env{'course.'.$env{'request.course.id'}.'.internal.selfenroll_notifylist'};
 7502:                             }
 7503:                             if ($changes{'internal.selfenroll_approval'}) {
 7504:                                 $newval = &mt('Yes');
 7505:                             } elsif ($changes{'internal.selfenroll_approval'} eq '0') {
 7506:                                 $newval = &mt('No');
 7507:                             } else {
 7508:                                 my $currapproval = 
 7509:                                     $env{'course.'.$env{'request.course.id'}.'.internal.selfenroll_approval'};
 7510:                                 if ($currapproval) {
 7511:                                     $newval = &mt('Yes');
 7512:                                 } else {
 7513:                                     $newval = &mt('No');
 7514:                                 }
 7515:                             }
 7516:                             $r->print('<li>'.&mt('"[_1]" set to "[_2]".',$title,$newval));
 7517:                             if ($newnotify) {
 7518:                                 $r->print('<br />'.&mt('The following will be notified when an enrollment request needs approval, or has been approved: [_1].',$newnotify));
 7519:                             } else {
 7520:                                 $r->print('<br />'.&mt('No notifications sent when an enrollment request needs approval, or has been approved.'));
 7521:                             }
 7522:                             $r->print('</li>'."\n");
 7523:                         }
 7524:                     } else {
 7525:                         if (exists($changes{'internal.selfenroll_'.$item})) {
 7526:                             my $newval = $changes{'internal.selfenroll_'.$item};
 7527:                             if ($item eq 'types') {
 7528:                                 if ($newval eq '') {
 7529:                                     $newval = &mt('None');
 7530:                                 } elsif ($newval eq '*') {
 7531:                                     $newval = &mt('Any user in any domain');
 7532:                                 }
 7533:                             } elsif ($item eq 'registered') {
 7534:                                 if ($newval eq '1') {
 7535:                                     $newval = &mt('Yes');
 7536:                                 } elsif ($newval eq '0') {
 7537:                                     $newval = &mt('No');
 7538:                                 }
 7539:                             }
 7540:                             $r->print('<li>'.&mt('"[_1]" set to "[_2]".',$title,$newval).'</li>'."\n");
 7541:                         }
 7542:                     }
 7543:                 }
 7544:                 $r->print('</ul>');
 7545:                 my %newenvhash;
 7546:                 foreach my $key (keys(%changes)) {
 7547:                     $newenvhash{'course.'.$env{'request.course.id'}.'.'.$key} = $changes{$key};
 7548:                 }
 7549:                 &Apache::lonnet::appenv(\%newenvhash);
 7550:             } else {
 7551:                 $r->print(&mt('An error occurred when saving changes to self-enrollment settings in this course.').'<br />'.&mt('The error was: [_1].',$putresult));
 7552:             }
 7553:         } else {
 7554:             $r->print(&mt('No changes were made to the existing self-enrollment settings in this course.'));
 7555:         }
 7556:     } else {
 7557:         $r->print(&mt('No changes were made to the existing self-enrollment settings in this course.'));
 7558:     }
 7559:     my ($visible,$cansetvis,$vismsgs,$visactions) = &visible_in_cat($cdom,$cnum);
 7560:     if (ref($visactions) eq 'HASH') {
 7561:         if (!$visible) {
 7562:             $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
 7563:                       '<br />');
 7564:             if (ref($vismsgs) eq 'ARRAY') {
 7565:                 $r->print('<br />'.$visactions->{'take'}.'<ul>');
 7566:                 foreach my $item (@{$vismsgs}) {
 7567:                     $r->print('<li>'.$visactions->{$item}.'</li>');
 7568:                 }
 7569:                 $r->print('</ul>');
 7570:             }
 7571:             $r->print($cansetvis);
 7572:         }
 7573:     } 
 7574:     return;
 7575: }
 7576: 
 7577: sub get_selfenroll_titles {
 7578:     my @row = ('types','registered','enroll_dates','access_dates','section',
 7579:                'approval','limit');
 7580:     my %lt = &Apache::lonlocal::texthash (
 7581:                 types        => 'Users allowed to self-enroll in this course',
 7582:                 registered   => 'Restrict self-enrollment to students officially registered for the course',
 7583:                 enroll_dates => 'Dates self-enrollment available',
 7584:                 access_dates => 'Course access dates assigned to self-enrolling users',
 7585:                 section      => 'Section assigned to self-enrolling users',
 7586:                 approval     => 'Self-enrollment requests need approval?',
 7587:                 limit        => 'Enrollment limit',
 7588:              );
 7589:     return (\@row,\%lt);
 7590: }
 7591: 
 7592: #---------------------------------------------- end functions for &phase_two
 7593: 
 7594: #--------------------------------- functions for &phase_two and &phase_three
 7595: 
 7596: #--------------------------end of functions for &phase_two and &phase_three
 7597: 
 7598: 1;
 7599: __END__
 7600: 
 7601: 

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