File:  [LON-CAPA] / loncom / interface / loncreateuser.pm
Revision 1.371: download - view: text, annotated - select for diffs
Mon Dec 31 15:28:36 2012 UTC (11 years, 4 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Information to show in user list.
- Don't gray out role checkbox, if custom role selected as role to show.

    1: # The LearningOnline Network with CAPA
    2: # Create a user
    3: #
    4: # $Id: loncreateuser.pm,v 1.371 2012/12/31 15:28:36 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 portfolio_quota {
  126:     my ($ccuname,$ccdomain) = @_;
  127:     my %lt = &Apache::lonlocal::texthash(
  128:                    'usrt'      => "User Tools",
  129:                    'disk'      => "Disk space allocated to user's portfolio files",
  130:                    'cuqu'      => "Current quota",
  131:                    'cust'      => "Custom quota",
  132:                    'defa'      => "Default",
  133:                    'chqu'      => "Change quota",
  134:     );
  135:     my ($currquota,$quotatype,$inststatus,$defquota) = 
  136:         &Apache::loncommon::get_user_quota($ccuname,$ccdomain);
  137:     my ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($ccdomain);
  138:     my ($longinsttype,$showquota,$custom_on,$custom_off,$defaultinfo);
  139:     if ($inststatus ne '') {
  140:         if ($usertypes->{$inststatus} ne '') {
  141:             $longinsttype = $usertypes->{$inststatus};
  142:         }
  143:     }
  144:     $custom_on = ' ';
  145:     $custom_off = ' checked="checked" ';
  146:     my $quota_javascript = <<"END_SCRIPT";
  147: <script type="text/javascript">
  148: // <![CDATA[
  149: function quota_changes(caller) {
  150:     if (caller == "custom") {
  151:         if (document.cu.customquota[0].checked) {
  152:             document.cu.portfolioquota.value = "";
  153:         }
  154:     }
  155:     if (caller == "quota") {
  156:         document.cu.customquota[1].checked = true;
  157:     }
  158: }
  159: // ]]>
  160: </script>
  161: END_SCRIPT
  162:     if ($quotatype eq 'custom') {
  163:         $custom_on = $custom_off;
  164:         $custom_off = ' ';
  165:         $showquota = $currquota;
  166:         if ($longinsttype eq '') {
  167:             $defaultinfo = &mt('For this user, the default quota would be [_1]'
  168:                             .' Mb.',$defquota);
  169:         } else {
  170:             $defaultinfo = &mt("For this user, the default quota would be [_1]".
  171:                                " Mb, as determined by the user's institutional".
  172:                                " affiliation ([_2]).",$defquota,$longinsttype);
  173:         }
  174:     } else {
  175:         if ($longinsttype eq '') {
  176:             $defaultinfo = &mt('For this user, the default quota is [_1]'
  177:                             .' Mb.',$defquota);
  178:         } else {
  179:             $defaultinfo = &mt("For this user, the default quota of [_1]".
  180:                                " Mb, is determined by the user's institutional".
  181:                                " affiliation ([_2]).",$defquota,$longinsttype);
  182:         }
  183:     }
  184: 
  185:     my $output = $quota_javascript."\n".
  186:                  '<h3>'.$lt{'usrt'}.'</h3>'."\n".
  187:                  &Apache::loncommon::start_data_table();
  188: 
  189:     if (&Apache::lonnet::allowed('mut',$ccdomain)) {
  190:         $output .= &build_tools_display($ccuname,$ccdomain,'tools');
  191:     }
  192:     if (&Apache::lonnet::allowed('mpq',$ccdomain)) {
  193:         $output .= '<tr class="LC_info_row">'."\n".
  194:                    '    <td>'.$lt{'disk'}.'</td>'."\n".
  195:                    '  </tr>'."\n".
  196:                    &Apache::loncommon::start_data_table_row()."\n".
  197:                    '  <td>'.$lt{'cuqu'}.': '.
  198:                    $currquota.'&nbsp;Mb.&nbsp;&nbsp;'.
  199:                    $defaultinfo.'</td>'."\n".
  200:                    &Apache::loncommon::end_data_table_row()."\n".
  201:                    &Apache::loncommon::start_data_table_row()."\n".
  202:                    '  <td><span class="LC_nobreak">'.$lt{'chqu'}.
  203:                    ': <label>'.
  204:                    '<input type="radio" name="customquota" value="0" '.
  205:                    $custom_off.' onchange="javascript:quota_changes('."'custom'".')"'.
  206:                    ' />'.$lt{'defa'}.'&nbsp;('.$defquota.' Mb).</label>&nbsp;'.
  207:                    '&nbsp;<label><input type="radio" name="customquota" value="1" '. 
  208:                    $custom_on.'  onchange="javascript:quota_changes('."'custom'".')" />'.
  209:                    $lt{'cust'}.':</label>&nbsp;'.
  210:                    '<input type="text" name="portfolioquota" size ="5" value="'.
  211:                    $showquota.'" onfocus="javascript:quota_changes('."'quota'".')" '.
  212:                    '/>&nbsp;Mb</span></td>'."\n".
  213:                    &Apache::loncommon::end_data_table_row()."\n";
  214:     }  
  215:     $output .= &Apache::loncommon::end_data_table();
  216:     return $output;
  217: }
  218: 
  219: sub build_tools_display {
  220:     my ($ccuname,$ccdomain,$context) = @_;
  221:     my (@usertools,%userenv,$output,@options,%validations,%reqtitles,%reqdisplay,
  222:         $colspan,$isadv,%domconfig);
  223:     my %lt = &Apache::lonlocal::texthash (
  224:                    'blog'       => "Personal User Blog",
  225:                    'aboutme'    => "Personal Information Page",
  226:                    'webdav'     => "WebDAV access to authoring spaces (if SSL and author/co-author)",
  227:                    'portfolio'  => "Personal User Portfolio",
  228:                    'avai'       => "Available",
  229:                    'cusa'       => "availability",
  230:                    'chse'       => "Change setting",
  231:                    'usde'       => "Use default",
  232:                    'uscu'       => "Use custom",
  233:                    'official'   => 'Can request creation of official courses',
  234:                    'unofficial' => 'Can request creation of unofficial courses',
  235:                    'community'  => 'Can request creation of communities',
  236:                    'requestauthor'  => 'Can request author space',
  237:     );
  238:     if ($context eq 'requestcourses') {
  239:         %userenv = &Apache::lonnet::userenvironment($ccdomain,$ccuname,
  240:                       'requestcourses.official','requestcourses.unofficial',
  241:                       'requestcourses.community');
  242:         @usertools = ('official','unofficial','community');
  243:         @options =('norequest','approval','autolimit','validate');
  244:         %validations = &Apache::lonnet::auto_courserequest_checks($ccdomain);
  245:         %reqtitles = &courserequest_titles();
  246:         %reqdisplay = &courserequest_display();
  247:         $colspan = ' colspan="2"';
  248:         %domconfig =
  249:             &Apache::lonnet::get_dom('configuration',['requestcourses'],$ccdomain);
  250:         $isadv = &Apache::lonnet::is_advanced_user($ccuname,$ccdomain);
  251:     } elsif ($context eq 'requestauthor') {
  252:         %userenv = &Apache::lonnet::userenvironment($ccdomain,$ccuname,
  253:                                                     'requestauthor');
  254:         @usertools = ('requestauthor');
  255:         @options =('norequest','approval','automatic');
  256:         %reqtitles = &requestauthor_titles();
  257:         %reqdisplay = &requestauthor_display();
  258:         $colspan = ' colspan="2"';
  259:         %domconfig =
  260:             &Apache::lonnet::get_dom('configuration',['requestauthor'],$ccdomain);
  261:     } else {
  262:         %userenv = &Apache::lonnet::userenvironment($ccdomain,$ccuname,
  263:                           'tools.aboutme','tools.portfolio','tools.blog',
  264:                           'tools.webdav');
  265:         @usertools = ('aboutme','blog','webdav','portfolio');
  266:     }
  267:     foreach my $item (@usertools) {
  268:         my ($custom_access,$curr_access,$cust_on,$cust_off,$tool_on,$tool_off,
  269:             $currdisp,$custdisp,$custradio);
  270:         $cust_off = 'checked="checked" ';
  271:         $tool_on = 'checked="checked" ';
  272:         $curr_access =  
  273:             &Apache::lonnet::usertools_access($ccuname,$ccdomain,$item,undef,
  274:                                               $context);
  275:         if ($context eq 'requestauthor') {
  276:             if ($userenv{$context} ne '') {
  277:                 $cust_on = ' checked="checked" ';
  278:                 $cust_off = '';
  279:             }  
  280:         } elsif ($userenv{$context.'.'.$item} ne '') {
  281:             $cust_on = ' checked="checked" ';
  282:             $cust_off = '';
  283:         }
  284:         if ($context eq 'requestcourses') {
  285:             if ($userenv{$context.'.'.$item} eq '') {
  286:                 $custom_access = &mt('Currently from default setting.');
  287:             } else {
  288:                 $custom_access = &mt('Currently from custom setting.');
  289:             }
  290:         } elsif ($context eq 'requestauthor') {
  291:             if ($userenv{$context} eq '') {
  292:                 $custom_access = &mt('Currently from default setting.');
  293:             } else {
  294:                 $custom_access = &mt('Currently from custom setting.');
  295:             }
  296:         } else {
  297:             if ($userenv{$context.'.'.$item} eq '') {
  298:                 $custom_access =
  299:                     &mt('Availability determined currently from default setting.');
  300:                 if (!$curr_access) {
  301:                     $tool_off = 'checked="checked" ';
  302:                     $tool_on = '';
  303:                 }
  304:             } else {
  305:                 $custom_access =
  306:                     &mt('Availability determined currently from custom setting.');
  307:                 if ($userenv{$context.'.'.$item} == 0) {
  308:                     $tool_off = 'checked="checked" ';
  309:                     $tool_on = '';
  310:                 }
  311:             }
  312:         }
  313:         $output .= '  <tr class="LC_info_row">'."\n".
  314:                    '   <td'.$colspan.'>'.$lt{$item}.'</td>'."\n".
  315:                    '  </tr>'."\n".
  316:                    &Apache::loncommon::start_data_table_row()."\n";
  317:         if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
  318:             my ($curroption,$currlimit);
  319:             my $envkey = $context.'.'.$item;
  320:             if ($context eq 'requestauthor') {
  321:                 $envkey = $context;
  322:             }
  323:             if ($userenv{$envkey} ne '') {
  324:                 $curroption = $userenv{$envkey};
  325:             } else {
  326:                 my (@inststatuses);
  327:                 if ($context eq 'requestcourses') {
  328:                     $curroption =
  329:                         &Apache::loncoursequeueadmin::get_processtype('course',$ccuname,$ccdomain,
  330:                                                                       $isadv,$ccdomain,$item,
  331:                                                                       \@inststatuses,\%domconfig);
  332:                 } else {
  333:                      $curroption = 
  334:                          &Apache::loncoursequeueadmin::get_processtype('requestauthor',$ccuname,$ccdomain,
  335:                                                                        $isadv,$ccdomain,undef,
  336:                                                                        \@inststatuses,\%domconfig);
  337:                 }
  338:             }
  339:             if (!$curroption) {
  340:                 $curroption = 'norequest';
  341:             }
  342:             if ($curroption =~ /^autolimit=(\d*)$/) {
  343:                 $currlimit = $1;
  344:                 if ($currlimit eq '') {
  345:                     $currdisp = &mt('Yes, automatic creation');
  346:                 } else {
  347:                     $currdisp = &mt('Yes, up to [quant,_1,request]/user',$currlimit);
  348:                 }
  349:             } else {
  350:                 $currdisp = $reqdisplay{$curroption};
  351:             }
  352:             $custdisp = '<table>';
  353:             foreach my $option (@options) {
  354:                 my $val = $option;
  355:                 if ($option eq 'norequest') {
  356:                     $val = 0;
  357:                 }
  358:                 if ($option eq 'validate') {
  359:                     my $canvalidate = 0;
  360:                     if (ref($validations{$item}) eq 'HASH') {
  361:                         if ($validations{$item}{'_custom_'}) {
  362:                             $canvalidate = 1;
  363:                         }
  364:                     }
  365:                     next if (!$canvalidate);
  366:                 }
  367:                 my $checked = '';
  368:                 if ($option eq $curroption) {
  369:                     $checked = ' checked="checked"';
  370:                 } elsif ($option eq 'autolimit') {
  371:                     if ($curroption =~ /^autolimit/) {
  372:                         $checked = ' checked="checked"';
  373:                     }
  374:                 }
  375:                 my $name = 'crsreq_'.$item;
  376:                 if ($context eq 'requestauthor') {
  377:                     $name = $item;
  378:                 }
  379:                 $custdisp .= '<tr><td><span class="LC_nobreak"><label>'.
  380:                              '<input type="radio" name="'.$name.'" '.
  381:                              'value="'.$val.'"'.$checked.' />'.
  382:                              $reqtitles{$option}.'</label>&nbsp;';
  383:                 if ($option eq 'autolimit') {
  384:                     $custdisp .= '<input type="text" name="'.$name.
  385:                                  '_limit" size="1" '.
  386:                                  'value="'.$currlimit.'" /></span><br />'.
  387:                                  $reqtitles{'unlimited'};
  388:                 } else {
  389:                     $custdisp .= '</span>';
  390:                 }
  391:                 $custdisp .= '</td></tr>';
  392:             }
  393:             $custdisp .= '</table>';
  394:             $custradio = '</span></td><td>'.&mt('Custom setting').'<br />'.$custdisp;
  395:         } else {
  396:             $currdisp = ($curr_access?&mt('Yes'):&mt('No'));
  397:             my $name = $context.'_'.$item;
  398:             if ($context eq 'requestauthor') {
  399:                 $name = $context;
  400:             }
  401:             $custdisp = '<span class="LC_nobreak"><label>'.
  402:                         '<input type="radio" name="'.$name.'"'.
  403:                         ' value="1" '.$tool_on.'/>'.&mt('On').'</label>&nbsp;<label>'.
  404:                         '<input type="radio" name="'.$name.'" value="0" '.
  405:                         $tool_off.'/>'.&mt('Off').'</label></span>';
  406:             $custradio = ('&nbsp;'x2).'--'.$lt{'cusa'}.':&nbsp;'.$custdisp.
  407:                           '</span>';
  408:         }
  409:         $output .= '  <td'.$colspan.'>'.$custom_access.('&nbsp;'x4).
  410:                    $lt{'avai'}.': '.$currdisp.'</td>'."\n".
  411:                    &Apache::loncommon::end_data_table_row()."\n".
  412:                    &Apache::loncommon::start_data_table_row()."\n".
  413:                    '  <td style="vertical-align:top;"><span class="LC_nobreak">'.
  414:                    $lt{'chse'}.': <label>'.
  415:                    '<input type="radio" name="custom'.$item.'" value="0" '.
  416:                    $cust_off.'/>'.$lt{'usde'}.'</label>'.('&nbsp;' x3).
  417:                    '<label><input type="radio" name="custom'.$item.'" value="1" '.
  418:                    $cust_on.'/>'.$lt{'uscu'}.'</label>'.$custradio.'</td>'.
  419:                    &Apache::loncommon::end_data_table_row()."\n";
  420:     }
  421:     return $output;
  422: }
  423: 
  424: sub coursereq_externaluser {
  425:     my ($ccuname,$ccdomain,$cdom) = @_;
  426:     my (@usertools,@options,%validations,%userenv,$output);
  427:     my %lt = &Apache::lonlocal::texthash (
  428:                    'official'   => 'Can request creation of official courses',
  429:                    'unofficial' => 'Can request creation of unofficial courses',
  430:                    'community'  => 'Can request creation of communities',
  431:     );
  432: 
  433:     %userenv = &Apache::lonnet::userenvironment($ccdomain,$ccuname,
  434:                       'reqcrsotherdom.official','reqcrsotherdom.unofficial',
  435:                       'reqcrsotherdom.community');
  436:     @usertools = ('official','unofficial','community');
  437:     @options = ('approval','validate','autolimit');
  438:     %validations = &Apache::lonnet::auto_courserequest_checks($cdom);
  439:     my $optregex = join('|',@options);
  440:     my %reqtitles = &courserequest_titles();
  441:     foreach my $item (@usertools) {
  442:         my ($curroption,$currlimit,$tooloff);
  443:         if ($userenv{'reqcrsotherdom.'.$item} ne '') {
  444:             my @curr = split(',',$userenv{'reqcrsotherdom.'.$item});
  445:             foreach my $req (@curr) {
  446:                 if ($req =~ /^\Q$cdom\E\:($optregex)=?(\d*)$/) {
  447:                     $curroption = $1;
  448:                     $currlimit = $2;
  449:                     last;
  450:                 }
  451:             }
  452:             if (!$curroption) {
  453:                 $curroption = 'norequest';
  454:                 $tooloff = ' checked="checked"';
  455:             }
  456:         } else {
  457:             $curroption = 'norequest';
  458:             $tooloff = ' checked="checked"';
  459:         }
  460:         $output.= &Apache::loncommon::start_data_table_row()."\n".
  461:                   '  <td><span class="LC_nobreak">'.$lt{$item}.': </span></td><td>'.
  462:                   '<table><tr><td valign="top">'."\n".
  463:                   '<label><input type="radio" name="reqcrsotherdom_'.$item.
  464:                   '" value=""'.$tooloff.' />'.$reqtitles{'norequest'}.
  465:                   '</label></td>';
  466:         foreach my $option (@options) {
  467:             if ($option eq 'validate') {
  468:                 my $canvalidate = 0;
  469:                 if (ref($validations{$item}) eq 'HASH') {
  470:                     if ($validations{$item}{'_external_'}) {
  471:                         $canvalidate = 1;
  472:                     }
  473:                 }
  474:                 next if (!$canvalidate);
  475:             }
  476:             my $checked = '';
  477:             if ($option eq $curroption) {
  478:                 $checked = ' checked="checked"';
  479:             }
  480:             $output .= '<td valign="top"><span class="LC_nobreak"><label>'.
  481:                        '<input type="radio" name="reqcrsotherdom_'.$item.
  482:                        '" value="'.$option.'"'.$checked.' />'.
  483:                        $reqtitles{$option}.'</label>';
  484:             if ($option eq 'autolimit') {
  485:                 $output .= '&nbsp;<input type="text" name="reqcrsotherdom_'.
  486:                            $item.'_limit" size="1" '.
  487:                            'value="'.$currlimit.'" /></span>'.
  488:                            '<br />'.$reqtitles{'unlimited'};
  489:             } else {
  490:                 $output .= '</span>';
  491:             }
  492:             $output .= '</td>';
  493:         }
  494:         $output .= '</td></tr></table></td>'."\n".
  495:                    &Apache::loncommon::end_data_table_row()."\n";
  496:     }
  497:     return $output;
  498: }
  499: 
  500: sub domainrole_req {
  501:     my ($ccuname,$ccdomain) = @_;
  502:     return '<br /><h3>'.
  503:            &mt('User Can Request Assignment of Domain Roles?').
  504:            '</h3>'."\n".
  505:            &Apache::loncommon::start_data_table().
  506:            &build_tools_display($ccuname,$ccdomain,
  507:                                 'requestauthor').
  508:            &Apache::loncommon::end_data_table();
  509: }
  510: 
  511: sub courserequest_titles {
  512:     my %titles = &Apache::lonlocal::texthash (
  513:                                    official   => 'Official',
  514:                                    unofficial => 'Unofficial',
  515:                                    community  => 'Communities',
  516:                                    norequest  => 'Not allowed',
  517:                                    approval   => 'Approval by Dom. Coord.',
  518:                                    validate   => 'With validation',
  519:                                    autolimit  => 'Numerical limit',
  520:                                    unlimited  => '(blank for unlimited)',
  521:                  );
  522:     return %titles;
  523: }
  524: 
  525: sub courserequest_display {
  526:     my %titles = &Apache::lonlocal::texthash (
  527:                                    approval   => 'Yes, need approval',
  528:                                    validate   => 'Yes, with validation',
  529:                                    norequest  => 'No',
  530:    );
  531:    return %titles;
  532: }
  533: 
  534: sub requestauthor_titles {
  535:     my %titles = &Apache::lonlocal::texthash (
  536:                                    norequest  => 'Not allowed',
  537:                                    approval   => 'Approval by Dom. Coord.',
  538:                                    automatic  => 'Automatic approval',
  539:                  );
  540:     return %titles;
  541: 
  542: }
  543: 
  544: sub requestauthor_display {
  545:     my %titles = &Apache::lonlocal::texthash (
  546:                                    approval   => 'Yes, need approval',
  547:                                    automatic  => 'Yes, automatic approval',
  548:                                    norequest  => 'No',
  549:    );
  550:    return %titles;
  551: }
  552: 
  553: sub curr_requestauthor {
  554:     my ($uname,$udom,$isadv,$inststatuses,$domconfig) = @_;
  555:     return unless ((ref($inststatuses) eq 'ARRAY') && (ref($domconfig) eq 'HASH'));
  556:     if ($uname eq '' || $udom eq '') {
  557:         $uname = $env{'user.name'};
  558:         $udom = $env{'user.domain'};
  559:         $isadv = $env{'user.adv'};
  560:     }
  561:     my (%userenv,%settings,$val);
  562:     my @options = ('automatic','approval');
  563:     %userenv =
  564:         &Apache::lonnet::userenvironment($udom,$uname,'requestauthor','inststatus');
  565:     if ($userenv{'requestauthor'}) {
  566:         $val = $userenv{'requestauthor'};
  567:         @{$inststatuses} = ('_custom_');
  568:     } else {
  569:         my %alltasks;
  570:         if (ref($domconfig->{'requestauthor'}) eq 'HASH') {
  571:             %settings = %{$domconfig->{'requestauthor'}};
  572:             if (($isadv) && ($settings{'_LC_adv'} ne '')) {
  573:                 $val = $settings{'_LC_adv'};
  574:                 @{$inststatuses} = ('_LC_adv_');
  575:             } else {
  576:                 if ($userenv{'inststatus'} ne '') {
  577:                     @{$inststatuses} = split(',',$userenv{'inststatus'});
  578:                 } else {
  579:                     @{$inststatuses} = ('default');
  580:                 }
  581:                 foreach my $status (@{$inststatuses}) {
  582:                     if (exists($settings{$status})) {
  583:                         my $value = $settings{$status};
  584:                         next unless ($value);
  585:                         unless (exists($alltasks{$value})) {
  586:                             if (ref($alltasks{$value}) eq 'ARRAY') {
  587:                                 unless(grep(/^\Q$status\E$/,@{$alltasks{$value}})) {
  588:                                     push(@{$alltasks{$value}},$status);
  589:                                 }
  590:                             } else {
  591:                                 @{$alltasks{$value}} = ($status);
  592:                             }
  593:                         }
  594:                     }
  595:                 }
  596:                 foreach my $option (@options) {
  597:                     if ($alltasks{$option}) {
  598:                         $val = $option;
  599:                         last;
  600:                     }
  601:                 }
  602:             }
  603:         }
  604:     }
  605:     return $val;
  606: }
  607: 
  608: # =================================================================== Phase one
  609: 
  610: sub print_username_entry_form {
  611:     my ($r,$context,$response,$srch,$forcenewuser,$crstype,$brcrum) = @_;
  612:     my $defdom=$env{'request.role.domain'};
  613:     my $formtoset = 'crtuser';
  614:     if (exists($env{'form.startrolename'})) {
  615:         $formtoset = 'docustom';
  616:         $env{'form.rolename'} = $env{'form.startrolename'};
  617:     } elsif ($env{'form.origform'} eq 'crtusername') {
  618:         $formtoset =  $env{'form.origform'};
  619:     }
  620: 
  621:     my ($jsback,$elements) = &crumb_utilities();
  622: 
  623:     my $jscript = &Apache::loncommon::studentbrowser_javascript()."\n".
  624:         '<script type="text/javascript">'."\n".
  625:         '// <![CDATA['."\n".
  626:         &Apache::lonhtmlcommon::set_form_elements($elements->{$formtoset})."\n".
  627:         '// ]]>'."\n".
  628:         '</script>'."\n";
  629: 
  630:     my %existingroles=&Apache::lonuserutils::my_custom_roles($crstype);
  631:     if (($env{'form.action'} eq 'custom') && (keys(%existingroles) > 0)
  632:         && (&Apache::lonnet::allowed('mcr','/'))) {
  633:         $jscript .= &customrole_javascript();
  634:     }
  635:     my $helpitem = 'Course_Change_Privileges';
  636:     if ($env{'form.action'} eq 'custom') {
  637:         $helpitem = 'Course_Editing_Custom_Roles';
  638:     } elsif ($env{'form.action'} eq 'singlestudent') {
  639:         $helpitem = 'Course_Add_Student';
  640:     }
  641:     my %breadcrumb_text = &singleuser_breadcrumb($crstype);
  642:     if ($env{'form.action'} eq 'custom') {
  643:         push(@{$brcrum},
  644:                  {href=>"javascript:backPage(document.crtuser)",       
  645:                   text=>"Pick custom role",
  646:                   help => $helpitem,}
  647:                  );
  648:     } else {
  649:         push (@{$brcrum},
  650:                   {href => "javascript:backPage(document.crtuser)",
  651:                    text => $breadcrumb_text{'search'},
  652:                    help => $helpitem,
  653:                    faq  => 282,
  654:                    bug  => 'Instructor Interface',}
  655:                   );
  656:     }
  657:     my %loaditems = (
  658:                 'onload' => "javascript:setFormElements(document.$formtoset)",
  659:                     );
  660:     my $args = {bread_crumbs           => $brcrum,
  661:                 bread_crumbs_component => 'User Management',
  662:                 add_entries            => \%loaditems,};
  663:     $r->print(&Apache::loncommon::start_page('User Management',$jscript,$args));
  664: 
  665:     my %lt=&Apache::lonlocal::texthash(
  666:                     'srst' => 'Search for a user and enroll as a student',
  667:                     'srme' => 'Search for a user and enroll as a member',
  668:                     'srad' => 'Search for a user and modify/add user information or roles',
  669: 		    'usr'  => "Username",
  670:                     'dom'  => "Domain",
  671:                     'ecrp' => "Define or Edit Custom Role",
  672:                     'nr'   => "role name",
  673:                     'cre'  => "Next",
  674: 				       );
  675: 
  676:     if ($env{'form.action'} eq 'custom') {
  677:         if (&Apache::lonnet::allowed('mcr','/')) {
  678:             my $newroletext = &mt('Define new custom role:');
  679:             $r->print('<form action="/adm/createuser" method="post" name="docustom">'.
  680:                       '<input type="hidden" name="action" value="'.$env{'form.action'}.'" />'.
  681:                       '<input type="hidden" name="phase" value="selected_custom_edit" />'.
  682:                       '<h3>'.$lt{'ecrp'}.'</h3>'.
  683:                       &Apache::loncommon::start_data_table().
  684:                       &Apache::loncommon::start_data_table_row().
  685:                       '<td>');
  686:             if (keys(%existingroles) > 0) {
  687:                 $r->print('<br /><label><input type="radio" name="customroleaction" value="new" checked="checked" onclick="setCustomFields();" /><b>'.$newroletext.'</b></label>');
  688:             } else {
  689:                 $r->print('<br /><input type="hidden" name="customroleaction" value="new" /><b>'.$newroletext.'</b>');
  690:             }
  691:             $r->print('</td><td align="center">'.$lt{'nr'}.'<br /><input type="text" size="15" name="newrolename" onfocus="setCustomAction('."'new'".');" /></td>'.
  692:                       &Apache::loncommon::end_data_table_row());
  693:             if (keys(%existingroles) > 0) {
  694:                 $r->print(&Apache::loncommon::start_data_table_row().'<td><br />'.
  695:                           '<label><input type="radio" name="customroleaction" value="edit" onclick="setCustomFields();"/><b>'.
  696:                           &mt('View/Modify existing role:').'</b></label></td>'.
  697:                           '<td align="center"><br />'.
  698:                           '<select name="rolename" onchange="setCustomAction('."'edit'".');">'.
  699:                           '<option value="" selected="selected">'.
  700:                           &mt('Select'));
  701:                 foreach my $role (sort(keys(%existingroles))) {
  702:                     $r->print('<option value="'.$role.'">'.$role.'</option>');
  703:                 }
  704:                 $r->print('</select>'.
  705:                           '</td>'.
  706:                           &Apache::loncommon::end_data_table_row());
  707:             }
  708:             $r->print(&Apache::loncommon::end_data_table().'<p>'.
  709:                       '<input name="customeditor" type="submit" value="'.
  710:                       $lt{'cre'}.'" /></p>'.
  711:                       '</form>');
  712:         }
  713:     } else {
  714:         my $actiontext = $lt{'srad'};
  715:         if ($env{'form.action'} eq 'singlestudent') {
  716:             if ($crstype eq 'Community') {
  717:                 $actiontext = $lt{'srme'};
  718:             } else {
  719:                 $actiontext = $lt{'srst'};
  720:             }
  721:         }
  722:         $r->print("<h3>$actiontext</h3>");
  723:         if ($env{'form.origform'} ne 'crtusername') {
  724:             $r->print("\n".$response);
  725:         }
  726:         $r->print(&entry_form($defdom,$srch,$forcenewuser,$context,$response,$crstype));
  727:     }
  728: }
  729: 
  730: sub customrole_javascript {
  731:     my $js = <<"END";
  732: <script type="text/javascript">
  733: // <![CDATA[
  734: 
  735: function setCustomFields() {
  736:     if (document.docustom.customroleaction.length > 0) {
  737:         for (var i=0; i<document.docustom.customroleaction.length; i++) {
  738:             if (document.docustom.customroleaction[i].checked) {
  739:                 if (document.docustom.customroleaction[i].value == 'new') {
  740:                     document.docustom.rolename.selectedIndex = 0;
  741:                 } else {
  742:                     document.docustom.newrolename.value = '';
  743:                 }
  744:             }
  745:         }
  746:     }
  747:     return;
  748: }
  749: 
  750: function setCustomAction(caller) {
  751:     if (document.docustom.customroleaction.length > 0) {
  752:         for (var i=0; i<document.docustom.customroleaction.length; i++) {
  753:             if (document.docustom.customroleaction[i].value == caller) {
  754:                 document.docustom.customroleaction[i].checked = true;
  755:             }
  756:         }
  757:     }
  758:     setCustomFields();
  759:     return;
  760: }
  761: 
  762: // ]]>
  763: </script>
  764: END
  765:     return $js;
  766: }
  767: 
  768: sub entry_form {
  769:     my ($dom,$srch,$forcenewuser,$context,$responsemsg,$crstype) = @_;
  770:     my ($usertype,$inexact);
  771:     if (ref($srch) eq 'HASH') {
  772:         if (($srch->{'srchin'} eq 'dom') &&
  773:             ($srch->{'srchby'} eq 'uname') &&
  774:             ($srch->{'srchtype'} eq 'exact') &&
  775:             ($srch->{'srchdomain'} ne '') &&
  776:             ($srch->{'srchterm'} ne '')) {
  777:             my (%curr_rules,%got_rules);
  778:             my ($rules,$ruleorder) =
  779:                 &Apache::lonnet::inst_userrules($srch->{'srchdomain'},'username');
  780:             $usertype = &Apache::lonuserutils::check_usertype($srch->{'srchdomain'},$srch->{'srchterm'},$rules,\%curr_rules,\%got_rules);
  781:         } else {
  782:             $inexact = 1;
  783:         }
  784:     }
  785:     my $cancreate =
  786:         &Apache::lonuserutils::can_create_user($dom,$context,$usertype);
  787:     my $userpicker = 
  788:        &Apache::loncommon::user_picker($dom,$srch,$forcenewuser,
  789:                                        'document.crtuser',$cancreate,$usertype);
  790:     my $srchbutton = &mt('Search');
  791:     if ($env{'form.action'} eq 'singlestudent') {
  792:         $srchbutton = &mt('Search and Enroll');
  793:     } elsif ($cancreate && $responsemsg ne '' && $inexact) {
  794:         $srchbutton = &mt('Search or Add New User');
  795:     }
  796:     my $output = <<"ENDBLOCK";
  797: <form action="/adm/createuser" method="post" name="crtuser">
  798: <input type="hidden" name="action" value="$env{'form.action'}" />
  799: <input type="hidden" name="phase" value="get_user_info" />
  800: $userpicker
  801: <input name="userrole" type="button" value="$srchbutton" onclick="javascript:validateEntry(document.crtuser)" />
  802: </form>
  803: ENDBLOCK
  804:     if ($env{'form.phase'} eq '') {
  805:         my $defdom=$env{'request.role.domain'};
  806:         my $domform = &Apache::loncommon::select_dom_form($defdom,'srchdomain');
  807:         my %lt=&Apache::lonlocal::texthash(
  808:                   'enro' => 'Enroll one student',
  809:                   'enrm' => 'Enroll one member',
  810:                   'admo' => 'Add/modify a single user',
  811:                   'crea' => 'create new user if required',
  812:                   'uskn' => "username is known",
  813:                   'crnu' => 'Create a new user',
  814:                   'usr'  => 'Username',
  815:                   'dom'  => 'in domain',
  816:                   'enrl' => 'Enroll',
  817:                   'cram'  => 'Create/Modify user',
  818:         );
  819:         my $sellink=&Apache::loncommon::selectstudent_link('crtusername','srchterm','srchdomain');
  820:         my ($title,$buttontext,$showresponse);
  821:         if ($env{'form.action'} eq 'singlestudent') {
  822:             if ($crstype eq 'Community') {
  823:                 $title = $lt{'enrm'};
  824:             } else {
  825:                 $title = $lt{'enro'};
  826:             }
  827:             $buttontext = $lt{'enrl'};
  828:         } else {
  829:             $title = $lt{'admo'};
  830:             $buttontext = $lt{'cram'};
  831:         }
  832:         if ($cancreate) {
  833:             $title .= ' <span class="LC_cusr_subheading">('.$lt{'crea'}.')</span>';
  834:         } else {
  835:             $title .= ' <span class="LC_cusr_subheading">('.$lt{'uskn'}.')</span>';
  836:         }
  837:         if ($env{'form.origform'} eq 'crtusername') {
  838:             $showresponse = $responsemsg;
  839:         }
  840:         $output .= <<"ENDDOCUMENT";
  841: <br />
  842: <form action="/adm/createuser" method="post" name="crtusername">
  843: <input type="hidden" name="action" value="$env{'form.action'}" />
  844: <input type="hidden" name="phase" value="createnewuser" />
  845: <input type="hidden" name="srchtype" value="exact" />
  846: <input type="hidden" name="srchby" value="uname" />
  847: <input type="hidden" name="srchin" value="dom" />
  848: <input type="hidden" name="forcenewuser" value="1" />
  849: <input type="hidden" name="origform" value="crtusername" />
  850: <h3>$title</h3>
  851: $showresponse
  852: <table>
  853:  <tr>
  854:   <td>$lt{'usr'}:</td>
  855:   <td><input type="text" size="15" name="srchterm" /></td>
  856:   <td>&nbsp;$lt{'dom'}:</td><td>$domform</td>
  857:   <td>&nbsp;$sellink&nbsp;</td>
  858:   <td>&nbsp;<input name="userrole" type="submit" value="$buttontext" /></td>
  859:  </tr>
  860: </table>
  861: </form>
  862: ENDDOCUMENT
  863:     }
  864:     return $output;
  865: }
  866: 
  867: sub user_modification_js {
  868:     my ($pjump_def,$dc_setcourse_code,$nondc_setsection_code,$groupslist)=@_;
  869:     
  870:     return <<END;
  871: <script type="text/javascript" language="Javascript">
  872: // <![CDATA[
  873: 
  874:     $pjump_def
  875:     $dc_setcourse_code
  876: 
  877:     function dateset() {
  878:         eval("document.cu."+document.cu.pres_marker.value+
  879:             ".value=document.cu.pres_value.value");
  880:         modalWindow.close();
  881:     }
  882: 
  883:     $nondc_setsection_code
  884: // ]]>
  885: </script>
  886: END
  887: }
  888: 
  889: # =================================================================== Phase two
  890: sub print_user_selection_page {
  891:     my ($r,$response,$srch,$srch_results,$srcharray,$context,$opener_elements,$crstype,$brcrum) = @_;
  892:     my @fields = ('username','domain','lastname','firstname','permanentemail');
  893:     my $sortby = $env{'form.sortby'};
  894: 
  895:     if (!grep(/^\Q$sortby\E$/,@fields)) {
  896:         $sortby = 'lastname';
  897:     }
  898: 
  899:     my ($jsback,$elements) = &crumb_utilities();
  900: 
  901:     my $jscript = (<<ENDSCRIPT);
  902: <script type="text/javascript">
  903: // <![CDATA[
  904: function pickuser(uname,udom) {
  905:     document.usersrchform.seluname.value=uname;
  906:     document.usersrchform.seludom.value=udom;
  907:     document.usersrchform.phase.value="userpicked";
  908:     document.usersrchform.submit();
  909: }
  910: 
  911: $jsback
  912: // ]]>
  913: </script>
  914: ENDSCRIPT
  915: 
  916:     my %lt=&Apache::lonlocal::texthash(
  917:                                        'usrch'          => "User Search to add/modify roles",
  918:                                        'stusrch'        => "User Search to enroll student",
  919:                                        'memsrch'        => "User Search to enroll member",
  920:                                        'usel'           => "Select a user to add/modify roles",
  921:                                        'stusel'         => "Select a user to enroll as a student",
  922:                                        'memsel'         => "Select a user to enroll as a member",
  923:                                        'username'       => "username",
  924:                                        'domain'         => "domain",
  925:                                        'lastname'       => "last name",
  926:                                        'firstname'      => "first name",
  927:                                        'permanentemail' => "permanent e-mail",
  928:                                       );
  929:     if ($context eq 'requestcrs') {
  930:         $r->print('<div>');
  931:     } else {
  932:         my %breadcrumb_text = &singleuser_breadcrumb($crstype);
  933:         my $helpitem;
  934:         if ($env{'form.action'} eq 'singleuser') {
  935:             $helpitem = 'Course_Change_Privileges';
  936:         } elsif ($env{'form.action'} eq 'singlestudent') {
  937:             $helpitem = 'Course_Add_Student';
  938:         }
  939:         push (@{$brcrum},
  940:                   {href => "javascript:backPage(document.usersrchform,'','')",
  941:                    text => $breadcrumb_text{'search'},
  942:                    faq  => 282,
  943:                    bug  => 'Instructor Interface',},
  944:                   {href => "javascript:backPage(document.usersrchform,'get_user_info','select')",
  945:                    text => $breadcrumb_text{'userpicked'},
  946:                    faq  => 282,
  947:                    bug  => 'Instructor Interface',
  948:                    help => $helpitem}
  949:                   );
  950:         $r->print(&Apache::loncommon::start_page('User Management',$jscript,{bread_crumbs => $brcrum}));
  951:         if ($env{'form.action'} eq 'singleuser') {
  952:             $r->print("<b>$lt{'usrch'}</b><br />");
  953:             $r->print(&entry_form($srch->{'srchdomain'},$srch,undef,$context,undef,$crstype));
  954:             $r->print('<h3>'.$lt{'usel'}.'</h3>');
  955:         } elsif ($env{'form.action'} eq 'singlestudent') {
  956:             $r->print($jscript."<b>");
  957:             if ($crstype eq 'Community') {
  958:                 $r->print($lt{'memsrch'});
  959:             } else {
  960:                 $r->print($lt{'stusrch'});
  961:             }
  962:             $r->print("</b><br />");
  963:             $r->print(&entry_form($srch->{'srchdomain'},$srch,undef,$context,undef,$crstype));
  964:             $r->print('</form><h3>');
  965:             if ($crstype eq 'Community') {
  966:                 $r->print($lt{'memsel'});
  967:             } else {
  968:                 $r->print($lt{'stusel'});
  969:             }
  970:             $r->print('</h3>');
  971:         }
  972:     }
  973:     $r->print('<form name="usersrchform" method="post">'.
  974:               &Apache::loncommon::start_data_table()."\n".
  975:               &Apache::loncommon::start_data_table_header_row()."\n".
  976:               ' <th> </th>'."\n");
  977:     foreach my $field (@fields) {
  978:         $r->print(' <th><a href="javascript:document.usersrchform.sortby.value='.
  979:                   "'".$field."'".';document.usersrchform.submit();">'.
  980:                   $lt{$field}.'</a></th>'."\n");
  981:     }
  982:     $r->print(&Apache::loncommon::end_data_table_header_row());
  983: 
  984:     my @sorted_users = sort {
  985:         lc($srch_results->{$a}->{$sortby})   cmp lc($srch_results->{$b}->{$sortby})
  986:             ||
  987:         lc($srch_results->{$a}->{lastname})  cmp lc($srch_results->{$b}->{lastname})
  988:             ||
  989:         lc($srch_results->{$a}->{firstname}) cmp lc($srch_results->{$b}->{firstname})
  990: 	    ||
  991: 	lc($a) cmp lc($b)
  992:         } (keys(%$srch_results));
  993: 
  994:     foreach my $user (@sorted_users) {
  995:         my ($uname,$udom) = split(/:/,$user);
  996:         my $onclick;
  997:         if ($context eq 'requestcrs') {
  998:             $onclick =
  999:                 'onclick="javascript:gochoose('."'$uname','$udom',".
 1000:                                                "'$srch_results->{$user}->{firstname}',".
 1001:                                                "'$srch_results->{$user}->{lastname}',".
 1002:                                                "'$srch_results->{$user}->{permanentemail}'".');"';
 1003:         } else {
 1004:             $onclick =
 1005:                 ' onclick="javascript:pickuser('."'".$uname."'".','."'".$udom."'".');"';
 1006:         }
 1007:         $r->print(&Apache::loncommon::start_data_table_row().
 1008:                   '<td><input type="button" name="seluser" value="'.&mt('Select').'" '.
 1009:                   $onclick.' /></td>'.
 1010:                   '<td><tt>'.$uname.'</tt></td>'.
 1011:                   '<td><tt>'.$udom.'</tt></td>');
 1012:         foreach my $field ('lastname','firstname','permanentemail') {
 1013:             $r->print('<td>'.$srch_results->{$user}->{$field}.'</td>');
 1014:         }
 1015:         $r->print(&Apache::loncommon::end_data_table_row());
 1016:     }
 1017:     $r->print(&Apache::loncommon::end_data_table().'<br /><br />');
 1018:     if (ref($srcharray) eq 'ARRAY') {
 1019:         foreach my $item (@{$srcharray}) {
 1020:             $r->print('<input type="hidden" name="'.$item.'" value="'.$env{'form.'.$item}.'" />'."\n");
 1021:         }
 1022:     }
 1023:     $r->print(' <input type="hidden" name="sortby" value="'.$sortby.'" />'."\n".
 1024:               ' <input type="hidden" name="seluname" value="" />'."\n".
 1025:               ' <input type="hidden" name="seludom" value="" />'."\n".
 1026:               ' <input type="hidden" name="currstate" value="select" />'."\n".
 1027:               ' <input type="hidden" name="phase" value="get_user_info" />'."\n".
 1028:               ' <input type="hidden" name="action" value="'.$env{'form.action'}.'" />'."\n");
 1029:     if ($context eq 'requestcrs') {
 1030:         $r->print($opener_elements.'</form></div>');
 1031:     } else {
 1032:         $r->print($response.'</form>');
 1033:     }
 1034: }
 1035: 
 1036: sub print_user_query_page {
 1037:     my ($r,$caller,$brcrum) = @_;
 1038: # FIXME - this is for a network-wide name search (similar to catalog search)
 1039: # To use frames with similar behavior to catalog/portfolio search.
 1040: # To be implemented. 
 1041:     return;
 1042: }
 1043: 
 1044: sub print_user_modification_page {
 1045:     my ($r,$ccuname,$ccdomain,$srch,$response,$context,$permission,$crstype,$brcrum) = @_;
 1046:     if (($ccuname eq '') || ($ccdomain eq '')) {
 1047:         my $usermsg = &mt('No username and/or domain provided.');
 1048:         $env{'form.phase'} = '';
 1049: 	&print_username_entry_form($r,$context,$usermsg,'','',$crstype,$brcrum);
 1050:         return;
 1051:     }
 1052:     my ($form,$formname);
 1053:     if ($env{'form.action'} eq 'singlestudent') {
 1054:         $form = 'document.enrollstudent';
 1055:         $formname = 'enrollstudent';
 1056:     } else {
 1057:         $form = 'document.cu';
 1058:         $formname = 'cu';
 1059:     }
 1060:     my %abv_auth = &auth_abbrev();
 1061:     my (%rulematch,%inst_results,$newuser,%alerts,%curr_rules,%got_rules);
 1062:     my $uhome=&Apache::lonnet::homeserver($ccuname,$ccdomain);
 1063:     if ($uhome eq 'no_host') {
 1064:         my $usertype;
 1065:         my ($rules,$ruleorder) =
 1066:             &Apache::lonnet::inst_userrules($ccdomain,'username');
 1067:             $usertype =
 1068:                 &Apache::lonuserutils::check_usertype($ccdomain,$ccuname,$rules,
 1069:                                                       \%curr_rules,\%got_rules);
 1070:         my $cancreate =
 1071:             &Apache::lonuserutils::can_create_user($ccdomain,$context,
 1072:                                                    $usertype);
 1073:         if (!$cancreate) {
 1074:             my $helplink = 'javascript:helpMenu('."'display'".')';
 1075:             my %usertypetext = (
 1076:                 official   => 'institutional',
 1077:                 unofficial => 'non-institutional',
 1078:             );
 1079:             my $response;
 1080:             if ($env{'form.origform'} eq 'crtusername') {
 1081:                 $response = '<span class="LC_warning">'.
 1082:                             &mt('No match found for the username [_1] in LON-CAPA domain: [_2]',
 1083:                                 '<b>'.$ccuname.'</b>',$ccdomain).
 1084:                             '</span><br />';
 1085:             }
 1086:             $response .= '<p class="LC_warning">'
 1087:                         .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
 1088:                         .' '
 1089:                         .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
 1090:                             ,'<a href="'.$helplink.'">','</a>')
 1091:                         .'</p><br />';
 1092:             $env{'form.phase'} = '';
 1093:             &print_username_entry_form($r,$context,$response,undef,undef,$crstype,$brcrum);
 1094:             return;
 1095:         }
 1096:         $newuser = 1;
 1097:         my $checkhash;
 1098:         my $checks = { 'username' => 1 };
 1099:         $checkhash->{$ccuname.':'.$ccdomain} = { 'newuser' => $newuser };
 1100:         &Apache::loncommon::user_rule_check($checkhash,$checks,
 1101:             \%alerts,\%rulematch,\%inst_results,\%curr_rules,\%got_rules);
 1102:         if (ref($alerts{'username'}) eq 'HASH') {
 1103:             if (ref($alerts{'username'}{$ccdomain}) eq 'HASH') {
 1104:                 my $domdesc =
 1105:                     &Apache::lonnet::domain($ccdomain,'description');
 1106:                 if ($alerts{'username'}{$ccdomain}{$ccuname}) {
 1107:                     my $userchkmsg;
 1108:                     if (ref($curr_rules{$ccdomain}) eq 'HASH') {  
 1109:                         $userchkmsg = 
 1110:                             &Apache::loncommon::instrule_disallow_msg('username',
 1111:                                                                  $domdesc,1).
 1112:                         &Apache::loncommon::user_rule_formats($ccdomain,
 1113:                             $domdesc,$curr_rules{$ccdomain}{'username'},
 1114:                             'username');
 1115:                     }
 1116:                     $env{'form.phase'} = '';
 1117:                     &print_username_entry_form($r,$context,$userchkmsg,undef,undef,$crstype,$brcrum);
 1118:                     return;
 1119:                 }
 1120:             }
 1121:         }
 1122:     } else {
 1123:         $newuser = 0;
 1124:     }
 1125:     if ($response) {
 1126:         $response = '<br />'.$response;
 1127:     }
 1128: 
 1129:     my $pjump_def = &Apache::lonhtmlcommon::pjump_javascript_definition();
 1130:     my $dc_setcourse_code = '';
 1131:     my $nondc_setsection_code = '';                                        
 1132:     my %loaditem;
 1133: 
 1134:     my $groupslist = &Apache::lonuserutils::get_groupslist();
 1135: 
 1136:     my $js = &validation_javascript($context,$ccdomain,$pjump_def,
 1137:                                $groupslist,$newuser,$formname,\%loaditem);
 1138:     my %breadcrumb_text = &singleuser_breadcrumb($crstype);
 1139:     my $helpitem = 'Course_Change_Privileges';
 1140:     if ($env{'form.action'} eq 'singlestudent') {
 1141:         $helpitem = 'Course_Add_Student';
 1142:     }
 1143:     push (@{$brcrum},
 1144:         {href => "javascript:backPage($form)",
 1145:          text => $breadcrumb_text{'search'},
 1146:          faq  => 282,
 1147:          bug  => 'Instructor Interface',});
 1148:     if ($env{'form.phase'} eq 'userpicked') {
 1149:        push(@{$brcrum},
 1150:               {href => "javascript:backPage($form,'get_user_info','select')",
 1151:                text => $breadcrumb_text{'userpicked'},
 1152:                faq  => 282,
 1153:                bug  => 'Instructor Interface',});
 1154:     }
 1155:     push(@{$brcrum},
 1156:             {href => "javascript:backPage($form,'$env{'form.phase'}','modify')",
 1157:              text => $breadcrumb_text{'modify'},
 1158:              faq  => 282,
 1159:              bug  => 'Instructor Interface',
 1160:              help => $helpitem});
 1161:     my $args = {'add_entries'           => \%loaditem,
 1162:                 'bread_crumbs'          => $brcrum,
 1163:                 'bread_crumbs_component' => 'User Management'};
 1164:     if ($env{'form.popup'}) {
 1165:         $args->{'no_nav_bar'} = 1;
 1166:     }
 1167:     my $start_page =
 1168:         &Apache::loncommon::start_page('User Management',$js,$args);
 1169: 
 1170:     my $forminfo =<<"ENDFORMINFO";
 1171: <form action="/adm/createuser" method="post" name="$formname">
 1172: <input type="hidden" name="phase" value="update_user_data" />
 1173: <input type="hidden" name="ccuname" value="$ccuname" />
 1174: <input type="hidden" name="ccdomain" value="$ccdomain" />
 1175: <input type="hidden" name="pres_value"  value="" />
 1176: <input type="hidden" name="pres_type"   value="" />
 1177: <input type="hidden" name="pres_marker" value="" />
 1178: ENDFORMINFO
 1179:     my (%inccourses,$roledom);
 1180:     if ($context eq 'course') {
 1181:         $inccourses{$env{'request.course.id'}}=1;
 1182:         $roledom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 1183:     } elsif ($context eq 'author') {
 1184:         $roledom = $env{'request.role.domain'};
 1185:     } elsif ($context eq 'domain') {
 1186:         foreach my $key (keys(%env)) {
 1187:             $roledom = $env{'request.role.domain'};
 1188:             if ($key=~/^user\.priv\.cm\.\/($roledom)\/($match_username)/) {
 1189:                 $inccourses{$1.'_'.$2}=1;
 1190:             }
 1191:         }
 1192:     } else {
 1193:         foreach my $key (keys(%env)) {
 1194: 	    if ($key=~/^user\.priv\.cm\.\/($match_domain)\/($match_username)/) {
 1195: 	        $inccourses{$1.'_'.$2}=1;
 1196:             }
 1197:         }
 1198:     }
 1199:     if ($newuser) {
 1200:         my ($portfolioform,$domroleform);
 1201:         if ((&Apache::lonnet::allowed('mpq',$env{'request.role.domain'})) ||
 1202:             (&Apache::lonnet::allowed('mut',$env{'request.role.domain'}))) {
 1203:             # Current user has quota or user tools modification privileges
 1204:             $portfolioform = '<br />'.&portfolio_quota($ccuname,$ccdomain);
 1205:         }
 1206:         if (&Apache::lonnet::allowed('cau',$env{'request.role.domain'})) {
 1207:             $domroleform = '<br />'.&domainrole_req($ccuname,$ccdomain);
 1208:         }
 1209:         &initialize_authen_forms($ccdomain,$formname);
 1210:         my %lt=&Apache::lonlocal::texthash(
 1211:                 'cnu'            => 'Create New User',
 1212:                 'ast'            => 'as a student',
 1213:                 'ame'            => 'as a member',
 1214:                 'ind'            => 'in domain',
 1215:                 'lg'             => 'Login Data',
 1216:                 'hs'             => "Home Server",
 1217:         );
 1218: 	$r->print(<<ENDTITLE);
 1219: $start_page
 1220: $response
 1221: $forminfo
 1222: <script type="text/javascript" language="Javascript">
 1223: // <![CDATA[
 1224: $loginscript
 1225: // ]]>
 1226: </script>
 1227: <input type='hidden' name='makeuser' value='1' />
 1228: <h2>$lt{'cnu'} "$ccuname" $lt{'ind'} $ccdomain
 1229: ENDTITLE
 1230:         if ($env{'form.action'} eq 'singlestudent') {
 1231:             if ($crstype eq 'Community') {
 1232:                 $r->print(' ('.$lt{'ame'}.')');
 1233:             } else {
 1234:                 $r->print(' ('.$lt{'ast'}.')');
 1235:             }
 1236:         }
 1237:         $r->print('</h2>'."\n".'<div class="LC_left_float">');
 1238:         my $personal_table = 
 1239:             &personal_data_display($ccuname,$ccdomain,$newuser,$context,
 1240:                                    $inst_results{$ccuname.':'.$ccdomain});
 1241:         $r->print($personal_table);
 1242:         my ($home_server_pick,$numlib) = 
 1243:             &Apache::loncommon::home_server_form_item($ccdomain,'hserver',
 1244:                                                       'default','hide');
 1245:         if ($numlib > 1) {
 1246:             $r->print("
 1247: <br />
 1248: $lt{'hs'}: $home_server_pick
 1249: <br />");
 1250:         } else {
 1251:             $r->print($home_server_pick);
 1252:         }
 1253:         if (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) {
 1254:             $r->print('<br /><h3>'.
 1255:                       &mt('User Can Request Creation of Courses/Communities in this Domain?').'</h3>'.
 1256:                       &Apache::loncommon::start_data_table().
 1257:                       &build_tools_display($ccuname,$ccdomain,
 1258:                                            'requestcourses').
 1259:                       &Apache::loncommon::end_data_table());
 1260:         }
 1261:         $r->print('</div>'."\n".'<div class="LC_left_float"><h3>'.
 1262:                   $lt{'lg'}.'</h3>');
 1263:         my ($fixedauth,$varauth,$authmsg); 
 1264:         if (ref($rulematch{$ccuname.':'.$ccdomain}) eq 'HASH') {
 1265:             my $matchedrule = $rulematch{$ccuname.':'.$ccdomain}{'username'};
 1266:             my ($rules,$ruleorder) = 
 1267:                 &Apache::lonnet::inst_userrules($ccdomain,'username');
 1268:             if (ref($rules) eq 'HASH') {
 1269:                 if (ref($rules->{$matchedrule}) eq 'HASH') {
 1270:                     my $authtype = $rules->{$matchedrule}{'authtype'};
 1271:                     if ($authtype !~ /^(krb4|krb5|int|fsys|loc)$/) {
 1272:                         $r->print(&Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc));
 1273:                     } else { 
 1274:                         my $authparm = $rules->{$matchedrule}{'authparm'};
 1275:                         $authmsg = $rules->{$matchedrule}{'authmsg'};
 1276:                         if ($authtype =~ /^krb(4|5)$/) {
 1277:                             my $ver = $1;
 1278:                             if ($authparm ne '') {
 1279:                                 $fixedauth = <<"KERB"; 
 1280: <input type="hidden" name="login" value="krb" />
 1281: <input type="hidden" name="krbver" value="$ver" />
 1282: <input type="hidden" name="krbarg" value="$authparm" />
 1283: KERB
 1284:                             }
 1285:                         } else {
 1286:                             $fixedauth = 
 1287: '<input type="hidden" name="login" value="'.$authtype.'" />'."\n";
 1288:                             if ($rules->{$matchedrule}{'authparmfixed'}) {
 1289:                                 $fixedauth .=    
 1290: '<input type="hidden" name="'.$authtype.'arg" value="'.$authparm.'" />'."\n";
 1291:                             } else {
 1292:                                 if ($authtype eq 'int') {
 1293:                                     $varauth = '<br />'.
 1294: &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>';
 1295:                                 } elsif ($authtype eq 'loc') {
 1296:                                     $varauth = '<br />'.
 1297: &mt('[_1] Local Authentication with argument [_2]','','<input type="text" name="'.$authtype.'arg" value="" />')."\n";
 1298:                                 } else {
 1299:                                     $varauth =
 1300: '<input type="text" name="'.$authtype.'arg" value="" />'."\n";
 1301:                                 }
 1302:                             }
 1303:                         }
 1304:                     }
 1305:                 } else {
 1306:                     $r->print(&Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc));
 1307:                 }
 1308:             }
 1309:             if ($authmsg) {
 1310:                 $r->print(<<ENDAUTH);
 1311: $fixedauth
 1312: $authmsg
 1313: $varauth
 1314: ENDAUTH
 1315:             }
 1316:         } else {
 1317:             $r->print(&Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc)); 
 1318:         }
 1319:         $r->print($portfolioform.$domroleform);
 1320:         if ($env{'form.action'} eq 'singlestudent') {
 1321:             $r->print(&date_sections_select($context,$newuser,$formname,
 1322:                                             $permission));
 1323:         }
 1324:         $r->print('</div><div class="LC_clear_float_footer"></div>');
 1325:     } else { # user already exists
 1326: 	my %lt=&Apache::lonlocal::texthash(
 1327:                     'cup'  => "Modify existing user: ",
 1328:                     'ens'  => "Enroll one student: ",
 1329:                     'enm'  => "Enroll one member: ",
 1330:                     'id'   => "in domain",
 1331: 				       );
 1332: 	$r->print(<<ENDCHANGEUSER);
 1333: $start_page
 1334: $forminfo
 1335: <h2>
 1336: ENDCHANGEUSER
 1337:         if ($env{'form.action'} eq 'singlestudent') {
 1338:             if ($crstype eq 'Community') {
 1339:                 $r->print($lt{'enm'});
 1340:             } else {
 1341:                 $r->print($lt{'ens'});
 1342:             }
 1343:         } else {
 1344:             $r->print($lt{'cup'});
 1345:         }
 1346:         $r->print(' "'.$ccuname.'" '.$lt{'id'}.' "'.$ccdomain.'"</h2>'.
 1347:                   "\n".'<div class="LC_left_float">');
 1348:         my ($personal_table,$showforceid) = 
 1349:             &personal_data_display($ccuname,$ccdomain,$newuser,$context,
 1350:                                    $inst_results{$ccuname.':'.$ccdomain});
 1351:         $r->print($personal_table);
 1352:         if ($showforceid) {
 1353:             $r->print('<table>'.&Apache::lonuserutils::forceid_change($context).'</table>');
 1354:         }
 1355:         if (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) {
 1356:             $r->print('<br /><h3>'.&mt('User Can Request Creation of Courses/Communities in this Domain?').'</h3>'.
 1357:                       &Apache::loncommon::start_data_table());
 1358:             if ($env{'request.role.domain'} eq $ccdomain) {
 1359:                 $r->print(&build_tools_display($ccuname,$ccdomain,'requestcourses'));
 1360:             } else {
 1361:                 $r->print(&coursereq_externaluser($ccuname,$ccdomain,
 1362:                                                   $env{'request.role.domain'}));
 1363:             }
 1364:             $r->print(&Apache::loncommon::end_data_table());
 1365:         }
 1366:         $r->print('</div>');
 1367:         my @order = ('auth','quota','tools','requestauthor');
 1368:         my %user_text;
 1369:         my ($isadv,$isauthor) = 
 1370:             &Apache::lonnet::is_advanced_user($ccuname,$ccdomain);
 1371:         if ((!$isauthor) && 
 1372:             (&Apache::lonnet::allowed('cau',$env{'request.role.domain'}))) {
 1373:             $user_text{'requestauthor'} = &domainrole_req($ccuname,$ccdomain);
 1374:         }
 1375:         $user_text{'auth'} =  &user_authentication($ccuname,$ccdomain,$formname);
 1376:         if ((&Apache::lonnet::allowed('mpq',$ccdomain)) ||
 1377:             (&Apache::lonnet::allowed('mut',$ccdomain))) {
 1378:             # Current user has quota modification privileges
 1379:             $user_text{'quota'} = &portfolio_quota($ccuname,$ccdomain);
 1380:         }
 1381:         if (!&Apache::lonnet::allowed('mpq',$ccdomain)) {
 1382:             if (&Apache::lonnet::allowed('mpq',$env{'request.role.domain'})) {
 1383:                 # Get the user's portfolio information
 1384:                 my %portq = &Apache::lonnet::get('environment',['portfolioquota'],
 1385:                                                  $ccdomain,$ccuname);
 1386:                 my %lt=&Apache::lonlocal::texthash(
 1387:                     'dska'  => "Disk space allocated to user's portfolio files",
 1388:                     'youd'  => "You do not have privileges to modify the portfolio quota for this user.",
 1389:                     'ichr'  => "If a change is required, contact a domain coordinator for the domain",
 1390:                 );
 1391:                 $user_text{'quota'} = <<ENDNOPORTPRIV;
 1392: <h3>$lt{'dska'}</h3>
 1393: $lt{'youd'} $lt{'ichr'}: $ccdomain
 1394: ENDNOPORTPRIV
 1395:             }
 1396:         }
 1397:         if (!&Apache::lonnet::allowed('mut',$ccdomain)) {
 1398:             if (&Apache::lonnet::allowed('mut',$env{'request.role.domain'})) {
 1399:                 my %lt=&Apache::lonlocal::texthash(
 1400:                     'utav'  => "User Tools Availability",
 1401:                     'yodo'  => "You do not have privileges to modify Portfolio, Blog, WebDAV, or Personal Information Page settings for this user.",
 1402:                     'ifch'  => "If a change is required, contact a domain coordinator for the domain",
 1403:                 );
 1404:                 $user_text{'tools'} = <<ENDNOTOOLSPRIV;
 1405: <h3>$lt{'utav'}</h3>
 1406: $lt{'yodo'} $lt{'ifch'}: $ccdomain
 1407: ENDNOTOOLSPRIV
 1408:             }
 1409:         }
 1410:         my $gotdiv = 0; 
 1411:         foreach my $item (@order) {
 1412:             if ($user_text{$item} ne '') {
 1413:                 unless ($gotdiv) {
 1414:                     $r->print('<div class="LC_left_float">');
 1415:                     $gotdiv = 1;
 1416:                 }
 1417:                 $r->print('<br />'.$user_text{$item});
 1418:             }
 1419:         }
 1420:         if ($env{'form.action'} eq 'singlestudent') {
 1421:             unless ($gotdiv) {
 1422:                 $r->print('<div class="LC_left_float">');
 1423:             }
 1424:             $r->print(&date_sections_select($context,$newuser,$formname));
 1425:         } 
 1426:         if ($gotdiv) {
 1427:             $r->print('</div><div class="LC_clear_float_footer"></div>');
 1428:         }
 1429:         if ($env{'form.action'} ne 'singlestudent') {
 1430:             &display_existing_roles($r,$ccuname,$ccdomain,\%inccourses,$context,
 1431:                                     $roledom,$crstype);
 1432:         }
 1433:     } ## End of new user/old user logic
 1434:     if ($env{'form.action'} eq 'singlestudent') {
 1435:         my $btntxt;
 1436:         if ($crstype eq 'Community') {
 1437:             $btntxt = &mt('Enroll Member');
 1438:         } else {
 1439:             $btntxt = &mt('Enroll Student');
 1440:         }
 1441:         $r->print('<br /><input type="button" value="'.$btntxt.'" onclick="setSections(this.form)" />'."\n");
 1442:     } else {
 1443:         $r->print('<h3>'.&mt('Add Roles').'</h3>');
 1444:         my $addrolesdisplay = 0;
 1445:         if ($context eq 'domain' || $context eq 'author') {
 1446:             $addrolesdisplay = &new_coauthor_roles($r,$ccuname,$ccdomain);
 1447:         }
 1448:         if ($context eq 'domain') {
 1449:             my $add_domainroles = &new_domain_roles($r,$ccdomain);
 1450:             if (!$addrolesdisplay) {
 1451:                 $addrolesdisplay = $add_domainroles;
 1452:             }
 1453:             $r->print(&course_level_dc($env{'request.role.domain'},'Course'));
 1454:             $r->print('<br /><input type="button" value="'.&mt('Save').'" onclick="setCourse()" />'."\n");
 1455:         } elsif ($context eq 'author') {
 1456:             if ($addrolesdisplay) {
 1457:                 $r->print('<br /><input type="button" value="'.&mt('Save').'"');
 1458:                 if ($newuser) {
 1459:                     $r->print(' onclick="auth_check()" \>'."\n");
 1460:                 } else {
 1461:                     $r->print('onclick="this.form.submit()" \>'."\n");
 1462:                 }
 1463:             } else {
 1464:                 $r->print('<br /><a href="javascript:backPage(document.cu)">'.
 1465:                           &mt('Back to previous page').'</a>');
 1466:             }
 1467:         } else {
 1468:             $r->print(&course_level_table(%inccourses));
 1469:             $r->print('<br /><input type="button" value="'.&mt('Save').'" onclick="setSections(this.form)" />'."\n");
 1470:         }
 1471:     }
 1472:     $r->print(&Apache::lonhtmlcommon::echo_form_input(['phase','userrole','ccdomain','prevphase','currstate','ccuname','ccdomain']));
 1473:     $r->print('<input type="hidden" name="currstate" value="" />');
 1474:     $r->print('<input type="hidden" name="prevphase" value="'.$env{'form.phase'}.'" /></form>');
 1475:     return;
 1476: }
 1477: 
 1478: sub singleuser_breadcrumb {
 1479:     my ($crstype) = @_;
 1480:     my %breadcrumb_text;
 1481:     if ($env{'form.action'} eq 'singlestudent') {
 1482:         if ($crstype eq 'Community') {
 1483:             $breadcrumb_text{'search'} = 'Enroll a member';
 1484:         } else {
 1485:             $breadcrumb_text{'search'} = 'Enroll a student';
 1486:         }
 1487:         $breadcrumb_text{'userpicked'} = 'Select a user',
 1488:         $breadcrumb_text{'modify'} = 'Set section/dates',
 1489:     } else {
 1490:         $breadcrumb_text{'search'} = 'Create/modify a user';
 1491:         $breadcrumb_text{'userpicked'} = 'Select a user',
 1492:         $breadcrumb_text{'modify'} = 'Set user role',
 1493:     }
 1494:     return %breadcrumb_text;
 1495: }
 1496: 
 1497: sub date_sections_select {
 1498:     my ($context,$newuser,$formname,$permission) = @_;
 1499:     my $cid = $env{'request.course.id'};
 1500:     my ($cnum,$cdom) = &Apache::lonuserutils::get_course_identity($cid);
 1501:     my $date_table = '<h3>'.&mt('Starting and Ending Dates').'</h3>'."\n".
 1502:         &Apache::lonuserutils::date_setting_table(undef,undef,$context,
 1503:                                                   undef,$formname,$permission);
 1504:     my $rowtitle = 'Section';
 1505:     my $secbox = '<h3>'.&mt('Section').'</h3>'."\n".
 1506:         &Apache::lonuserutils::section_picker($cdom,$cnum,'st',$rowtitle,
 1507:                                               $permission);
 1508:     my $output = $date_table.$secbox;
 1509:     return $output;
 1510: }
 1511: 
 1512: sub validation_javascript {
 1513:     my ($context,$ccdomain,$pjump_def,$groupslist,$newuser,$formname,
 1514:         $loaditem) = @_;
 1515:     my $dc_setcourse_code = '';
 1516:     my $nondc_setsection_code = '';
 1517:     if ($context eq 'domain') {
 1518:         my $dcdom = $env{'request.role.domain'};
 1519:         $loaditem->{'onload'} = "document.cu.coursedesc.value='';";
 1520:         $dc_setcourse_code = 
 1521:             &Apache::lonuserutils::dc_setcourse_js('cu','singleuser',$context);
 1522:     } else {
 1523:         my $checkauth; 
 1524:         if (($newuser) || (&Apache::lonnet::allowed('mau',$ccdomain))) {
 1525:             $checkauth = 1;
 1526:         }
 1527:         if ($context eq 'course') {
 1528:             $nondc_setsection_code =
 1529:                 &Apache::lonuserutils::setsections_javascript($formname,$groupslist,
 1530:                                                               undef,$checkauth);
 1531:         }
 1532:         if ($checkauth) {
 1533:             $nondc_setsection_code .= 
 1534:                 &Apache::lonuserutils::verify_authen($formname,$context);
 1535:         }
 1536:     }
 1537:     my $js = &user_modification_js($pjump_def,$dc_setcourse_code,
 1538:                                    $nondc_setsection_code,$groupslist);
 1539:     my ($jsback,$elements) = &crumb_utilities();
 1540:     $js .= "\n".
 1541:            '<script type="text/javascript">'."\n".
 1542:            '// <![CDATA['."\n".
 1543:            $jsback."\n".
 1544:            '// ]]>'."\n".
 1545:            '</script>'."\n";
 1546:     return $js;
 1547: }
 1548: 
 1549: sub display_existing_roles {
 1550:     my ($r,$ccuname,$ccdomain,$inccourses,$context,$roledom,$crstype) = @_;
 1551:     my $now=time;
 1552:     my %lt=&Apache::lonlocal::texthash(
 1553:                     'rer'  => "Existing Roles",
 1554:                     'rev'  => "Revoke",
 1555:                     'del'  => "Delete",
 1556:                     'ren'  => "Re-Enable",
 1557:                     'rol'  => "Role",
 1558:                     'ext'  => "Extent",
 1559:                     'sta'  => "Start",
 1560:                     'end'  => "End",
 1561:                                        );
 1562:     my (%rolesdump,%roletext,%sortrole,%roleclass,%rolepriv);
 1563:     if ($context eq 'course' || $context eq 'author') {
 1564:         my @roles = &Apache::lonuserutils::roles_by_context($context,1,$crstype);
 1565:         my %roleshash = 
 1566:             &Apache::lonnet::get_my_roles($ccuname,$ccdomain,'userroles',
 1567:                               ['active','previous','future'],\@roles,$roledom,1);
 1568:         foreach my $key (keys(%roleshash)) {
 1569:             my ($start,$end) = split(':',$roleshash{$key});
 1570:             next if ($start eq '-1' || $end eq '-1');
 1571:             my ($rnum,$rdom,$role,$sec) = split(':',$key);
 1572:             if ($context eq 'course') {
 1573:                 next unless (($rnum eq $env{'course.'.$env{'request.course.id'}.'.num'})
 1574:                              && ($rdom eq $env{'course.'.$env{'request.course.id'}.'.domain'}));
 1575:             } elsif ($context eq 'author') {
 1576:                 next unless (($rnum eq $env{'user.name'}) && ($rdom eq $env{'request.role.domain'}));
 1577:             }
 1578:             my ($newkey,$newvalue,$newrole);
 1579:             $newkey = '/'.$rdom.'/'.$rnum;
 1580:             if ($sec ne '') {
 1581:                 $newkey .= '/'.$sec;
 1582:             }
 1583:             $newvalue = $role;
 1584:             if ($role =~ /^cr/) {
 1585:                 $newrole = 'cr';
 1586:             } else {
 1587:                 $newrole = $role;
 1588:             }
 1589:             $newkey .= '_'.$newrole;
 1590:             if ($start ne '' && $end ne '') {
 1591:                 $newvalue .= '_'.$end.'_'.$start;
 1592:             } elsif ($end ne '') {
 1593:                 $newvalue .= '_'.$end;
 1594:             }
 1595:             $rolesdump{$newkey} = $newvalue;
 1596:         }
 1597:     } else {
 1598:         %rolesdump=&Apache::lonnet::dump('roles',$ccdomain,$ccuname);
 1599:     }
 1600:     # Build up table of user roles to allow revocation and re-enabling of roles.
 1601:     my ($tmp) = keys(%rolesdump);
 1602:     return if ($tmp =~ /^(con_lost|error)/i);
 1603:     foreach my $area (sort { my $a1=join('_',(split('_',$a))[1,0]);
 1604:                                 my $b1=join('_',(split('_',$b))[1,0]);
 1605:                                 return $a1 cmp $b1;
 1606:                             } keys(%rolesdump)) {
 1607:         next if ($area =~ /^rolesdef/);
 1608:         my $envkey=$area;
 1609:         my $role = $rolesdump{$area};
 1610:         my $thisrole=$area;
 1611:         $area =~ s/\_\w\w$//;
 1612:         my ($role_code,$role_end_time,$role_start_time) =
 1613:             split(/_/,$role);
 1614: # Is this a custom role? Get role owner and title.
 1615:         my ($croleudom,$croleuname,$croletitle)=
 1616:             ($role_code=~m{^cr/($match_domain)/($match_username)/(\w+)$});
 1617:         my $allowed=0;
 1618:         my $delallowed=0;
 1619:         my $sortkey=$role_code;
 1620:         my $class='Unknown';
 1621:         if ($area =~ m{^/($match_domain)/($match_courseid)} ) {
 1622:             $class='Course';
 1623:             my ($coursedom,$coursedir) = ($1,$2);
 1624:             my $cid = $1.'_'.$2;
 1625:             # $1.'_'.$2 is the course id (eg. 103_12345abcef103l3).
 1626:             my %coursedata=
 1627:                 &Apache::lonnet::coursedescription($cid);
 1628:             if ($coursedir =~ /^$match_community$/) {
 1629:                 $class='Community';
 1630:             }
 1631:             $sortkey.="\0$coursedom";
 1632:             my $carea;
 1633:             if (defined($coursedata{'description'})) {
 1634:                 $carea=$coursedata{'description'}.
 1635:                     '<br />'.&mt('Domain').': '.$coursedom.('&nbsp;'x8).
 1636:     &Apache::loncommon::syllabuswrapper(&mt('Syllabus'),$coursedir,$coursedom);
 1637:                 $sortkey.="\0".$coursedata{'description'};
 1638:             } else {
 1639:                 if ($class eq 'Community') {
 1640:                     $carea=&mt('Unavailable community').': '.$area;
 1641:                     $sortkey.="\0".&mt('Unavailable community').': '.$area;
 1642:                 } else {
 1643:                     $carea=&mt('Unavailable course').': '.$area;
 1644:                     $sortkey.="\0".&mt('Unavailable course').': '.$area;
 1645:                 }
 1646:             }
 1647:             $sortkey.="\0$coursedir";
 1648:             $inccourses->{$cid}=1;
 1649:             if ((&Apache::lonnet::allowed('c'.$role_code,$coursedom.'/'.$coursedir)) ||
 1650:                 (&Apache::lonnet::allowed('c'.$role_code,$ccdomain))) {
 1651:                 $allowed=1;
 1652:             }
 1653:             unless ($allowed) {
 1654:                 my $isowner = &Apache::lonuserutils::is_courseowner($cid,$coursedata{'internal.courseowner'});
 1655:                 if ($isowner) {
 1656:                     if (($role_code eq 'co') && ($class eq 'Community')) {
 1657:                         $allowed = 1;
 1658:                     } elsif (($role_code eq 'cc') && ($class eq 'Course')) {
 1659:                         $allowed = 1;
 1660:                     }
 1661:                 }
 1662:             } 
 1663:             if ((&Apache::lonnet::allowed('dro',$coursedom)) ||
 1664:                 (&Apache::lonnet::allowed('dro',$ccdomain))) {
 1665:                 $delallowed=1;
 1666:             }
 1667: # - custom role. Needs more info, too
 1668:             if ($croletitle) {
 1669:                 if (&Apache::lonnet::allowed('ccr',$coursedom.'/'.$coursedir)) {
 1670:                     $allowed=1;
 1671:                     $thisrole.='.'.$role_code;
 1672:                 }
 1673:             }
 1674:             if ($area=~m{^/($match_domain)/($match_courseid)/(\w+)}) {
 1675:                 $carea.='<br />Section: '.$3;
 1676:                 $sortkey.="\0$3";
 1677:                 if (!$allowed) {
 1678:                     if ($env{'request.course.sec'} eq $3) {
 1679:                         if (&Apache::lonnet::allowed('c'.$role_code,$1.'/'.$2.'/'.$3)) {
 1680:                             $allowed = 1;
 1681:                         }
 1682:                     }
 1683:                 }
 1684:             }
 1685:             $area=$carea;
 1686:         } else {
 1687:             $sortkey.="\0".$area;
 1688:             # Determine if current user is able to revoke privileges
 1689:             if ($area=~m{^/($match_domain)/}) {
 1690:                 if ((&Apache::lonnet::allowed('c'.$role_code,$1)) ||
 1691:                    (&Apache::lonnet::allowed('c'.$role_code,$ccdomain))) {
 1692:                    $allowed=1;
 1693:                 }
 1694:                 if (((&Apache::lonnet::allowed('dro',$1))  ||
 1695:                     (&Apache::lonnet::allowed('dro',$ccdomain))) &&
 1696:                     ($role_code ne 'dc')) {
 1697:                     $delallowed=1;
 1698:                 }
 1699:             } else {
 1700:                 if (&Apache::lonnet::allowed('c'.$role_code,'/')) {
 1701:                     $allowed=1;
 1702:                 }
 1703:             }
 1704:             if ($role_code eq 'ca' || $role_code eq 'au' || $role_code eq 'aa') {
 1705:                 $class='Construction Space';
 1706:             } elsif ($role_code eq 'su') {
 1707:                 $class='System';
 1708:             } else {
 1709:                 $class='Domain';
 1710:             }
 1711:         }
 1712:         if (($role_code eq 'ca') || ($role_code eq 'aa')) {
 1713:             $area=~m{/($match_domain)/($match_username)};
 1714:             if (&Apache::lonuserutils::authorpriv($2,$1)) {
 1715:                 $allowed=1;
 1716:             } else {
 1717:                 $allowed=0;
 1718:             }
 1719:         }
 1720:         my $row = '';
 1721:         $row.= '<td>';
 1722:         my $active=1;
 1723:         $active=0 if (($role_end_time) && ($now>$role_end_time));
 1724:         if (($active) && ($allowed)) {
 1725:             $row.= '<input type="checkbox" name="rev:'.$thisrole.'" />';
 1726:         } else {
 1727:             if ($active) {
 1728:                $row.='&nbsp;';
 1729:             } else {
 1730:                $row.=&mt('expired or revoked');
 1731:             }
 1732:         }
 1733:         $row.='</td><td>';
 1734:         if ($allowed && !$active) {
 1735:             $row.= '<input type="checkbox" name="ren:'.$thisrole.'" />';
 1736:         } else {
 1737:             $row.='&nbsp;';
 1738:         }
 1739:         $row.='</td><td>';
 1740:         if ($delallowed) {
 1741:             $row.= '<input type="checkbox" name="del:'.$thisrole.'" />';
 1742:         } else {
 1743:             $row.='&nbsp;';
 1744:         }
 1745:         my $plaintext='';
 1746:         if (!$croletitle) {
 1747:             $plaintext=&Apache::lonnet::plaintext($role_code,$class)
 1748:         } else {
 1749:             $plaintext=
 1750:                 &mt('Customrole [_1][_2]defined by [_3]',
 1751:                         '"'.$croletitle.'"',
 1752:                         '<br />',
 1753:                         $croleuname.':'.$croleudom);
 1754:         }
 1755:         $row.= '</td><td>'.$plaintext.
 1756:                '</td><td>'.$area.
 1757:                '</td><td>'.($role_start_time?&Apache::lonlocal::locallocaltime($role_start_time)
 1758:                                             : '&nbsp;' ).
 1759:                '</td><td>'.($role_end_time  ?&Apache::lonlocal::locallocaltime($role_end_time)
 1760:                                             : '&nbsp;' )
 1761:                ."</td>";
 1762:         $sortrole{$sortkey}=$envkey;
 1763:         $roletext{$envkey}=$row;
 1764:         $roleclass{$envkey}=$class;
 1765:         $rolepriv{$envkey}=$allowed;
 1766:     } # end of foreach        (table building loop)
 1767: 
 1768:     my $rolesdisplay = 0;
 1769:     my %output = ();
 1770:     foreach my $type ('Construction Space','Course','Community','Domain','System','Unknown') {
 1771:         $output{$type} = '';
 1772:         foreach my $which (sort {uc($a) cmp uc($b)} (keys(%sortrole))) {
 1773:             if ( ($roleclass{$sortrole{$which}} =~ /^\Q$type\E/ ) && ($rolepriv{$sortrole{$which}}) ) {
 1774:                  $output{$type}.=
 1775:                       &Apache::loncommon::start_data_table_row().
 1776:                       $roletext{$sortrole{$which}}.
 1777:                       &Apache::loncommon::end_data_table_row();
 1778:             }
 1779:         }
 1780:         unless($output{$type} eq '') {
 1781:             $output{$type} = '<tr class="LC_info_row">'.
 1782:                       "<td align='center' colspan='7'>".&mt($type)."</td></tr>".
 1783:                       $output{$type};
 1784:             $rolesdisplay = 1;
 1785:         }
 1786:     }
 1787:     if ($rolesdisplay == 1) {
 1788:         my $contextrole='';
 1789:         if ($env{'request.course.id'}) {
 1790:             if (&Apache::loncommon::course_type() eq 'Community') {
 1791:                 $contextrole = &mt('Existing Roles in this Community');
 1792:             } else {
 1793:                 $contextrole = &mt('Existing Roles in this Course');
 1794:             }
 1795:         } elsif ($env{'request.role'} =~ /^au\./) {
 1796:             $contextrole = &mt('Existing Co-Author Roles in your Construction Space');
 1797:         } else {
 1798:             $contextrole = &mt('Existing Roles in this Domain');
 1799:         }
 1800:         $r->print('
 1801: <h3>'.$lt{'rer'}.'</h3>'.
 1802: '<div>'.$contextrole.'</div>'.
 1803: &Apache::loncommon::start_data_table("LC_createuser").
 1804: &Apache::loncommon::start_data_table_header_row().
 1805: '<th>'.$lt{'rev'}.'</th><th>'.$lt{'ren'}.'</th><th>'.$lt{'del'}.
 1806: '</th><th>'.$lt{'rol'}.'</th><th>'.$lt{'ext'}.
 1807: '</th><th>'.$lt{'sta'}.'</th><th>'.$lt{'end'}.'</th>'.
 1808: &Apache::loncommon::end_data_table_header_row());
 1809:         foreach my $type ('Construction Space','Course','Community','Domain','System','Unknown') {
 1810:             if ($output{$type}) {
 1811:                 $r->print($output{$type}."\n");
 1812:             }
 1813:         }
 1814:         $r->print(&Apache::loncommon::end_data_table());
 1815:     }
 1816:     return;
 1817: }
 1818: 
 1819: sub new_coauthor_roles {
 1820:     my ($r,$ccuname,$ccdomain) = @_;
 1821:     my $addrolesdisplay = 0;
 1822:     #
 1823:     # Co-Author
 1824:     #
 1825:     if (&Apache::lonuserutils::authorpriv($env{'user.name'},
 1826:                                           $env{'request.role.domain'}) &&
 1827:         ($env{'user.name'} ne $ccuname || $env{'user.domain'} ne $ccdomain)) {
 1828:         # No sense in assigning co-author role to yourself
 1829:         $addrolesdisplay = 1;
 1830:         my $cuname=$env{'user.name'};
 1831:         my $cudom=$env{'request.role.domain'};
 1832:         my %lt=&Apache::lonlocal::texthash(
 1833:                     'cs'   => "Construction Space",
 1834:                     'act'  => "Activate",
 1835:                     'rol'  => "Role",
 1836:                     'ext'  => "Extent",
 1837:                     'sta'  => "Start",
 1838:                     'end'  => "End",
 1839:                     'cau'  => "Co-Author",
 1840:                     'caa'  => "Assistant Co-Author",
 1841:                     'ssd'  => "Set Start Date",
 1842:                     'sed'  => "Set End Date"
 1843:                                        );
 1844:         $r->print('<h4>'.$lt{'cs'}.'</h4>'."\n".
 1845:                   &Apache::loncommon::start_data_table()."\n".
 1846:                   &Apache::loncommon::start_data_table_header_row()."\n".
 1847:                   '<th>'.$lt{'act'}.'</th><th>'.$lt{'rol'}.'</th>'.
 1848:                   '<th>'.$lt{'ext'}.'</th><th>'.$lt{'sta'}.'</th>'.
 1849:                   '<th>'.$lt{'end'}.'</th>'."\n".
 1850:                   &Apache::loncommon::end_data_table_header_row()."\n".
 1851:                   &Apache::loncommon::start_data_table_row().'
 1852:            <td>
 1853:             <input type="checkbox" name="act_'.$cudom.'_'.$cuname.'_ca" />
 1854:            </td>
 1855:            <td>'.$lt{'cau'}.'</td>
 1856:            <td>'.$cudom.'_'.$cuname.'</td>
 1857:            <td><input type="hidden" name="start_'.$cudom.'_'.$cuname.'_ca" value="" />
 1858:              <a href=
 1859: "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>
 1860: <td><input type="hidden" name="end_'.$cudom.'_'.$cuname.'_ca" value="" />
 1861: <a href=
 1862: "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".
 1863:               &Apache::loncommon::end_data_table_row()."\n".
 1864:               &Apache::loncommon::start_data_table_row()."\n".
 1865: '<td><input type="checkbox" name="act_'.$cudom.'_'.$cuname.'_aa" /></td>
 1866: <td>'.$lt{'caa'}.'</td>
 1867: <td>'.$cudom.'_'.$cuname.'</td>
 1868: <td><input type="hidden" name="start_'.$cudom.'_'.$cuname.'_aa" value="" />
 1869: <a href=
 1870: "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>
 1871: <td><input type="hidden" name="end_'.$cudom.'_'.$cuname.'_aa" value="" />
 1872: <a href=
 1873: "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".
 1874:              &Apache::loncommon::end_data_table_row()."\n".
 1875:              &Apache::loncommon::end_data_table());
 1876:     } elsif ($env{'request.role'} =~ /^au\./) {
 1877:         if (!(&Apache::lonuserutils::authorpriv($env{'user.name'},
 1878:                                                 $env{'request.role.domain'}))) {
 1879:             $r->print('<span class="LC_error">'.
 1880:                       &mt('You do not have privileges to assign co-author roles.').
 1881:                       '</span>');
 1882:         } elsif (($env{'user.name'} eq $ccuname) &&
 1883:              ($env{'user.domain'} eq $ccdomain)) {
 1884:             $r->print(&mt('Assigning yourself a co-author or assistant co-author role in your own author area in Construction Space is not permitted'));
 1885:         }
 1886:     }
 1887:     return $addrolesdisplay;;
 1888: }
 1889: 
 1890: sub new_domain_roles {
 1891:     my ($r,$ccdomain) = @_;
 1892:     my $addrolesdisplay = 0;
 1893:     #
 1894:     # Domain level
 1895:     #
 1896:     my $num_domain_level = 0;
 1897:     my $domaintext =
 1898:     '<h4>'.&mt('Domain Level').'</h4>'.
 1899:     &Apache::loncommon::start_data_table().
 1900:     &Apache::loncommon::start_data_table_header_row().
 1901:     '<th>'.&mt('Activate').'</th><th>'.&mt('Role').'</th><th>'.
 1902:     &mt('Extent').'</th>'.
 1903:     '<th>'.&mt('Start').'</th><th>'.&mt('End').'</th>'.
 1904:     &Apache::loncommon::end_data_table_header_row();
 1905:     my @allroles = &Apache::lonuserutils::roles_by_context('domain');
 1906:     foreach my $thisdomain (sort(&Apache::lonnet::all_domains())) {
 1907:         foreach my $role (@allroles) {
 1908:             next if ($role eq 'ad');
 1909:             next if (($role eq 'au') && ($ccdomain ne $thisdomain));
 1910:             if (&Apache::lonnet::allowed('c'.$role,$thisdomain)) {
 1911:                my $plrole=&Apache::lonnet::plaintext($role);
 1912:                my %lt=&Apache::lonlocal::texthash(
 1913:                     'ssd'  => "Set Start Date",
 1914:                     'sed'  => "Set End Date"
 1915:                                        );
 1916:                $num_domain_level ++;
 1917:                $domaintext .=
 1918: &Apache::loncommon::start_data_table_row().
 1919: '<td><input type="checkbox" name="act_'.$thisdomain.'_'.$role.'" /></td>
 1920: <td>'.$plrole.'</td>
 1921: <td>'.$thisdomain.'</td>
 1922: <td><input type="hidden" name="start_'.$thisdomain.'_'.$role.'" value="" />
 1923: <a href=
 1924: "javascript:pjump('."'date_start','Start Date $plrole',document.cu.start_$thisdomain\_$role.value,'start_$thisdomain\_$role','cu.pres','dateset'".')">'.$lt{'ssd'}.'</a></td>
 1925: <td><input type="hidden" name="end_'.$thisdomain.'_'.$role.'" value="" />
 1926: <a href=
 1927: "javascript:pjump('."'date_end','End Date $plrole',document.cu.end_$thisdomain\_$role.value,'end_$thisdomain\_$role','cu.pres','dateset'".')">'.$lt{'sed'}.'</a></td>'.
 1928: &Apache::loncommon::end_data_table_row();
 1929:             }
 1930:         }
 1931:     }
 1932:     $domaintext.= &Apache::loncommon::end_data_table();
 1933:     if ($num_domain_level > 0) {
 1934:         $r->print($domaintext);
 1935:         $addrolesdisplay = 1;
 1936:     }
 1937:     return $addrolesdisplay;
 1938: }
 1939: 
 1940: sub user_authentication {
 1941:     my ($ccuname,$ccdomain,$formname) = @_;
 1942:     my $currentauth=&Apache::lonnet::queryauthenticate($ccuname,$ccdomain);
 1943:     my $outcome;
 1944:     # Check for a bad authentication type
 1945:     if ($currentauth !~ /^(krb4|krb5|unix|internal|localauth):/) {
 1946:         # bad authentication scheme
 1947:         my %lt=&Apache::lonlocal::texthash(
 1948:                        'err'   => "ERROR",
 1949:                        'uuas'  => "This user has an unrecognized authentication scheme",
 1950:                        'adcs'  => "Please alert a domain coordinator of this situation",
 1951:                        'sldb'  => "Please specify login data below",
 1952:                        'ld'    => "Login Data"
 1953:         );
 1954:         if (&Apache::lonnet::allowed('mau',$ccdomain)) {
 1955:             &initialize_authen_forms($ccdomain,$formname);
 1956: 
 1957:             my $choices = &Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc);
 1958:             $outcome = <<ENDBADAUTH;
 1959: <script type="text/javascript" language="Javascript">
 1960: // <![CDATA[
 1961: $loginscript
 1962: // ]]>
 1963: </script>
 1964: <span class="LC_error">$lt{'err'}:
 1965: $lt{'uuas'} ($currentauth). $lt{'sldb'}.</span>
 1966: <h3>$lt{'ld'}</h3>
 1967: $choices
 1968: ENDBADAUTH
 1969:         } else {
 1970:             # This user is not allowed to modify the user's
 1971:             # authentication scheme, so just notify them of the problem
 1972:             $outcome = <<ENDBADAUTH;
 1973: <span class="LC_error"> $lt{'err'}: 
 1974: $lt{'uuas'} ($currentauth). $lt{'adcs'}.
 1975: </span>
 1976: ENDBADAUTH
 1977:         }
 1978:     } else { # Authentication type is valid
 1979:         &initialize_authen_forms($ccdomain,$formname,$currentauth,'modifyuser');
 1980:         my ($authformcurrent,$can_modify,@authform_others) =
 1981:             &modify_login_block($ccdomain,$currentauth);
 1982:         if (&Apache::lonnet::allowed('mau',$ccdomain)) {
 1983:             # Current user has login modification privileges
 1984:             my %lt=&Apache::lonlocal::texthash (
 1985:                            'ld'    => "Login Data",
 1986:                            'ccld'  => "Change Current Login Data",
 1987:                            'enld'  => "Enter New Login Data"
 1988:                                                );
 1989:             $outcome =
 1990:                        '<script type="text/javascript" language="Javascript">'."\n".
 1991:                        '// <![CDATA['."\n".
 1992:                        $loginscript."\n".
 1993:                        '// ]]>'."\n".
 1994:                        '</script>'."\n".
 1995:                        '<h3>'.$lt{'ld'}.'</h3>'.
 1996:                        &Apache::loncommon::start_data_table().
 1997:                        &Apache::loncommon::start_data_table_row().
 1998:                        '<td>'.$authformnop;
 1999:             if ($can_modify) {
 2000:                 $outcome .= '</td>'."\n".
 2001:                             &Apache::loncommon::end_data_table_row().
 2002:                             &Apache::loncommon::start_data_table_row().
 2003:                             '<td>'.$authformcurrent.'</td>'.
 2004:                             &Apache::loncommon::end_data_table_row()."\n";
 2005:             } else {
 2006:                 $outcome .= '&nbsp;('.$authformcurrent.')</td>'.
 2007:                             &Apache::loncommon::end_data_table_row()."\n";
 2008:             }
 2009:             foreach my $item (@authform_others) { 
 2010:                 $outcome .= &Apache::loncommon::start_data_table_row().
 2011:                             '<td>'.$item.'</td>'.
 2012:                             &Apache::loncommon::end_data_table_row()."\n";
 2013:             }
 2014:             $outcome .= &Apache::loncommon::end_data_table();
 2015:         } else {
 2016:             if (&Apache::lonnet::allowed('mau',$env{'request.role.domain'})) {
 2017:                 my %lt=&Apache::lonlocal::texthash(
 2018:                            'ccld'  => "Change Current Login Data",
 2019:                            'yodo'  => "You do not have privileges to modify the authentication configuration for this user.",
 2020:                            'ifch'  => "If a change is required, contact a domain coordinator for the domain",
 2021:                 );
 2022:                 $outcome .= <<ENDNOPRIV;
 2023: <h3>$lt{'ccld'}</h3>
 2024: $lt{'yodo'} $lt{'ifch'}: $ccdomain
 2025: <input type="hidden" name="login" value="nochange" />
 2026: ENDNOPRIV
 2027:             }
 2028:         }
 2029:     }  ## End of "check for bad authentication type" logic
 2030:     return $outcome;
 2031: }
 2032: 
 2033: sub modify_login_block {
 2034:     my ($dom,$currentauth) = @_;
 2035:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 2036:     my ($authnum,%can_assign) =
 2037:         &Apache::loncommon::get_assignable_auth($dom);
 2038:     my ($authformcurrent,@authform_others,$show_override_msg);
 2039:     if ($currentauth=~/^krb(4|5):/) {
 2040:         $authformcurrent=$authformkrb;
 2041:         if ($can_assign{'int'}) {
 2042:             push(@authform_others,$authformint);
 2043:         }
 2044:         if ($can_assign{'loc'}) {
 2045:             push(@authform_others,$authformloc);
 2046:         }
 2047:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2048:             $show_override_msg = 1;
 2049:         }
 2050:     } elsif ($currentauth=~/^internal:/) {
 2051:         $authformcurrent=$authformint;
 2052:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2053:             push(@authform_others,$authformkrb);
 2054:         }
 2055:         if ($can_assign{'loc'}) {
 2056:             push(@authform_others,$authformloc);
 2057:         }
 2058:         if ($can_assign{'int'}) {
 2059:             $show_override_msg = 1;
 2060:         }
 2061:     } elsif ($currentauth=~/^unix:/) {
 2062:         $authformcurrent=$authformfsys;
 2063:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2064:             push(@authform_others,$authformkrb);
 2065:         }
 2066:         if ($can_assign{'int'}) {
 2067:             push(@authform_others,$authformint);
 2068:         }
 2069:         if ($can_assign{'loc'}) {
 2070:             push(@authform_others,$authformloc);
 2071:         }
 2072:         if ($can_assign{'fsys'}) {
 2073:             $show_override_msg = 1;
 2074:         }
 2075:     } elsif ($currentauth=~/^localauth:/) {
 2076:         $authformcurrent=$authformloc;
 2077:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2078:             push(@authform_others,$authformkrb);
 2079:         }
 2080:         if ($can_assign{'int'}) {
 2081:             push(@authform_others,$authformint);
 2082:         }
 2083:         if ($can_assign{'loc'}) {
 2084:             $show_override_msg = 1;
 2085:         }
 2086:     }
 2087:     if ($show_override_msg) {
 2088:         $authformcurrent = '<table><tr><td colspan="3">'.$authformcurrent.
 2089:                            '</td></tr>'."\n".
 2090:                            '<tr><td>&nbsp;&nbsp;&nbsp;</td>'.
 2091:                            '<td><b>'.&mt('Currently in use').'</b></td>'.
 2092:                            '<td align="right"><span class="LC_cusr_emph">'.
 2093:                             &mt('will override current values').
 2094:                             '</span></td></tr></table>';
 2095:     }
 2096:     return ($authformcurrent,$show_override_msg,@authform_others); 
 2097: }
 2098: 
 2099: sub personal_data_display {
 2100:     my ($ccuname,$ccdomain,$newuser,$context,$inst_results,$rolesarray) = @_;
 2101:     my ($output,$showforceid,%userenv,%canmodify,%canmodify_status);
 2102:     my @userinfo = ('firstname','middlename','lastname','generation',
 2103:                     'permanentemail','id');
 2104:     my $rowcount = 0;
 2105:     my $editable = 0;
 2106:     %canmodify_status = 
 2107:         &Apache::lonuserutils::can_modify_userinfo($context,$ccdomain,
 2108:                                                    ['inststatus'],$rolesarray);
 2109:     if (!$newuser) {
 2110:         # Get the users information
 2111:         %userenv = &Apache::lonnet::get('environment',
 2112:                    ['firstname','middlename','lastname','generation',
 2113:                     'permanentemail','id','inststatus'],$ccdomain,$ccuname);
 2114:         %canmodify =
 2115:             &Apache::lonuserutils::can_modify_userinfo($context,$ccdomain,
 2116:                                                        \@userinfo,$rolesarray);
 2117:     } elsif ($context eq 'selfcreate') {
 2118:         %canmodify = &selfcreate_canmodify($context,$ccdomain,\@userinfo,
 2119:                                            $inst_results,$rolesarray);
 2120:     }
 2121:     my %lt=&Apache::lonlocal::texthash(
 2122:                 'pd'             => "Personal Data",
 2123:                 'firstname'      => "First Name",
 2124:                 'middlename'     => "Middle Name",
 2125:                 'lastname'       => "Last Name",
 2126:                 'generation'     => "Generation",
 2127:                 'permanentemail' => "Permanent e-mail address",
 2128:                 'id'             => "Student/Employee ID",
 2129:                 'lg'             => "Login Data",
 2130:                 'inststatus'     => "Affiliation",
 2131:     );
 2132:     my %textboxsize = (
 2133:                        firstname      => '15',
 2134:                        middlename     => '15',
 2135:                        lastname       => '15',
 2136:                        generation     => '5',
 2137:                        permanentemail => '25',
 2138:                        id             => '15',
 2139:                       );
 2140:     my $genhelp=&Apache::loncommon::help_open_topic('Generation');
 2141:     $output = '<h3>'.$lt{'pd'}.'</h3>'.
 2142:               &Apache::lonhtmlcommon::start_pick_box();
 2143:     foreach my $item (@userinfo) {
 2144:         my $rowtitle = $lt{$item};
 2145:         my $hiderow = 0;
 2146:         if ($item eq 'generation') {
 2147:             $rowtitle = $genhelp.$rowtitle;
 2148:         }
 2149:         my $row = &Apache::lonhtmlcommon::row_title($rowtitle,undef,'LC_oddrow_value')."\n";
 2150:         if ($newuser) {
 2151:             if (ref($inst_results) eq 'HASH') {
 2152:                 if ($inst_results->{$item} ne '') {
 2153:                     $row .= '<input type="hidden" name="c'.$item.'" value="'.$inst_results->{$item}.'" />'.$inst_results->{$item};
 2154:                 } else {
 2155:                     if ($context eq 'selfcreate') {
 2156:                         if ($canmodify{$item}) { 
 2157:                             $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="" />';
 2158:                             $editable ++;
 2159:                         } else {
 2160:                             $hiderow = 1;
 2161:                         }
 2162:                     } else {
 2163:                         $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="" />';
 2164:                     }
 2165:                 }
 2166:             } else {
 2167:                 if ($context eq 'selfcreate') {
 2168:                     if (($item eq 'permanentemail') && ($newuser eq 'email')) {
 2169:                         $row .= $ccuname;
 2170:                     } else {
 2171:                         if ($canmodify{$item}) {
 2172:                             $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="" />';
 2173:                             $editable ++;
 2174:                         } else {
 2175:                             $hiderow = 1;
 2176:                         }
 2177:                     }
 2178:                 } else {
 2179:                     $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="" />';
 2180:                 }
 2181:             }
 2182:         } else {
 2183:             if ($canmodify{$item}) {
 2184:                 $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="'.$userenv{$item}.'" />';
 2185:             } else {
 2186:                 $row .= $userenv{$item};
 2187:             }
 2188:             if ($item eq 'id') {
 2189:                 $showforceid = $canmodify{$item};
 2190:             }
 2191:         }
 2192:         $row .= &Apache::lonhtmlcommon::row_closure(1);
 2193:         if (!$hiderow) {
 2194:             $output .= $row;
 2195:             $rowcount ++;
 2196:         }
 2197:     }
 2198:     if (($canmodify_status{'inststatus'}) || ($context ne 'selfcreate')) {
 2199:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($ccdomain);
 2200:         if (ref($types) eq 'ARRAY') {
 2201:             if (@{$types} > 0) {
 2202:                 my ($hiderow,$shown);
 2203:                 if ($canmodify_status{'inststatus'}) {
 2204:                     $shown = &pick_inst_statuses($userenv{'inststatus'},$usertypes,$types);
 2205:                 } else {
 2206:                     if ($userenv{'inststatus'} eq '') {
 2207:                         $hiderow = 1;
 2208:                     } else {
 2209:                         my @showitems;
 2210:                         foreach my $item ( map { &unescape($_); } split(':',$userenv{'inststatus'})) {
 2211:                             if (exists($usertypes->{$item})) {
 2212:                                 push(@showitems,$usertypes->{$item});
 2213:                             } else {
 2214:                                 push(@showitems,$item);
 2215:                             }
 2216:                         }
 2217:                         if (@showitems) {
 2218:                             $shown = join(', ',@showitems);
 2219:                         } else {
 2220:                             $hiderow = 1;
 2221:                         }
 2222:                     }
 2223:                 }
 2224:                 if (!$hiderow) {
 2225:                     my $row = &Apache::lonhtmlcommon::row_title(&mt('Affliations'),undef,'LC_oddrow_value')."\n".
 2226:                               $shown.&Apache::lonhtmlcommon::row_closure(1); 
 2227:                     if ($context eq 'selfcreate') {
 2228:                         $rowcount ++;
 2229:                     }
 2230:                     $output .= $row;
 2231:                 }
 2232:             }
 2233:         }
 2234:     }
 2235:     $output .= &Apache::lonhtmlcommon::end_pick_box();
 2236:     if (wantarray) {
 2237:         if ($context eq 'selfcreate') {
 2238:             return($output,$rowcount,$editable);
 2239:         } else {
 2240:             return ($output,$showforceid);
 2241:         }
 2242:     } else {
 2243:         return $output;
 2244:     }
 2245: }
 2246: 
 2247: sub pick_inst_statuses {
 2248:     my ($curr,$usertypes,$types) = @_;
 2249:     my ($output,$rem,@currtypes);
 2250:     if ($curr ne '') {
 2251:         @currtypes = map { &unescape($_); } split(/:/,$curr);
 2252:     }
 2253:     my $numinrow = 2;
 2254:     if (ref($types) eq 'ARRAY') {
 2255:         $output = '<table>';
 2256:         my $lastcolspan; 
 2257:         for (my $i=0; $i<@{$types}; $i++) {
 2258:             if (defined($usertypes->{$types->[$i]})) {
 2259:                 my $rem = $i%($numinrow);
 2260:                 if ($rem == 0) {
 2261:                     if ($i<@{$types}-1) {
 2262:                         if ($i > 0) { 
 2263:                             $output .= '</tr>';
 2264:                         }
 2265:                         $output .= '<tr>';
 2266:                     }
 2267:                 } elsif ($i==@{$types}-1) {
 2268:                     my $colsleft = $numinrow - $rem;
 2269:                     if ($colsleft > 1) {
 2270:                         $lastcolspan = ' colspan="'.$colsleft.'"';
 2271:                     }
 2272:                 }
 2273:                 my $check = ' ';
 2274:                 if (grep(/^\Q$types->[$i]\E$/,@currtypes)) {
 2275:                     $check = ' checked="checked" ';
 2276:                 }
 2277:                 $output .= '<td class="LC_left_item"'.$lastcolspan.'>'.
 2278:                            '<span class="LC_nobreak"><label>'.
 2279:                            '<input type="checkbox" name="inststatus" '.
 2280:                            'value="'.$types->[$i].'"'.$check.'/>'.
 2281:                            $usertypes->{$types->[$i]}.'</label></span></td>';
 2282:             }
 2283:         }
 2284:         $output .= '</tr></table>';
 2285:     }
 2286:     return $output;
 2287: }
 2288: 
 2289: sub selfcreate_canmodify {
 2290:     my ($context,$dom,$userinfo,$inst_results,$rolesarray) = @_;
 2291:     if (ref($inst_results) eq 'HASH') {
 2292:         my @inststatuses = &get_inststatuses($inst_results);
 2293:         if (@inststatuses == 0) {
 2294:             @inststatuses = ('default');
 2295:         }
 2296:         $rolesarray = \@inststatuses;
 2297:     }
 2298:     my %canmodify =
 2299:         &Apache::lonuserutils::can_modify_userinfo($context,$dom,$userinfo,
 2300:                                                    $rolesarray);
 2301:     return %canmodify;
 2302: }
 2303: 
 2304: sub get_inststatuses {
 2305:     my ($insthashref) = @_;
 2306:     my @inststatuses = ();
 2307:     if (ref($insthashref) eq 'HASH') {
 2308:         if (ref($insthashref->{'inststatus'}) eq 'ARRAY') {
 2309:             @inststatuses = @{$insthashref->{'inststatus'}};
 2310:         }
 2311:     }
 2312:     return @inststatuses;
 2313: }
 2314: 
 2315: # ================================================================= Phase Three
 2316: sub update_user_data {
 2317:     my ($r,$context,$crstype,$brcrum) = @_; 
 2318:     my $uhome=&Apache::lonnet::homeserver($env{'form.ccuname'},
 2319:                                           $env{'form.ccdomain'});
 2320:     # Error messages
 2321:     my $error     = '<span class="LC_error">'.&mt('Error').': ';
 2322:     my $end       = '</span><br /><br />';
 2323:     my $rtnlink   = '<a href="javascript:backPage(document.userupdate,'.
 2324:                     "'$env{'form.prevphase'}','modify')".'" />'.
 2325:                     &mt('Return to previous page').'</a>'.
 2326:                     &Apache::loncommon::end_page();
 2327:     my $now = time;
 2328:     my $title;
 2329:     if (exists($env{'form.makeuser'})) {
 2330: 	$title='Set Privileges for New User';
 2331:     } else {
 2332:         $title='Modify User Privileges';
 2333:     }
 2334:     my $newuser = 0;
 2335:     my ($jsback,$elements) = &crumb_utilities();
 2336:     my $jscript = '<script type="text/javascript">'."\n".
 2337:                   '// <![CDATA['."\n".
 2338:                   $jsback."\n".
 2339:                   '// ]]>'."\n".
 2340:                   '</script>'."\n";
 2341:     my %breadcrumb_text = &singleuser_breadcrumb($crstype);
 2342:     push (@{$brcrum},
 2343:              {href => "javascript:backPage(document.userupdate)",
 2344:               text => $breadcrumb_text{'search'},
 2345:               faq  => 282,
 2346:               bug  => 'Instructor Interface',}
 2347:              );
 2348:     if ($env{'form.prevphase'} eq 'userpicked') {
 2349:         push(@{$brcrum},
 2350:                {href => "javascript:backPage(document.userupdate,'get_user_info','select')",
 2351:                 text => $breadcrumb_text{'userpicked'},
 2352:                 faq  => 282,
 2353:                 bug  => 'Instructor Interface',});
 2354:     }
 2355:     my $helpitem = 'Course_Change_Privileges';
 2356:     if ($env{'form.action'} eq 'singlestudent') {
 2357:         $helpitem = 'Course_Add_Student';
 2358:     }
 2359:     push(@{$brcrum}, 
 2360:             {href => "javascript:backPage(document.userupdate,'$env{'form.prevphase'}','modify')",
 2361:              text => $breadcrumb_text{'modify'},
 2362:              faq  => 282,
 2363:              bug  => 'Instructor Interface',},
 2364:             {href => "/adm/createuser",
 2365:              text => "Result",
 2366:              faq  => 282,
 2367:              bug  => 'Instructor Interface',
 2368:              help => $helpitem});
 2369:     my $args = {bread_crumbs          => $brcrum,
 2370:                 bread_crumbs_component => 'User Management'};
 2371:     if ($env{'form.popup'}) {
 2372:         $args->{'no_nav_bar'} = 1;
 2373:     }
 2374:     $r->print(&Apache::loncommon::start_page($title,$jscript,$args));
 2375:     $r->print(&update_result_form($uhome));
 2376:     # Check Inputs
 2377:     if (! $env{'form.ccuname'} ) {
 2378: 	$r->print($error.&mt('No login name specified').'.'.$end.$rtnlink);
 2379: 	return;
 2380:     }
 2381:     if (  $env{'form.ccuname'} ne 
 2382: 	  &LONCAPA::clean_username($env{'form.ccuname'}) ) {
 2383: 	$r->print($error.&mt('Invalid login name.').'  '.
 2384: 		  &mt('Only letters, numbers, periods, dashes, @, and underscores are valid.').
 2385: 		  $end.$rtnlink);
 2386: 	return;
 2387:     }
 2388:     if (! $env{'form.ccdomain'}       ) {
 2389: 	$r->print($error.&mt('No domain specified').'.'.$end.$rtnlink);
 2390: 	return;
 2391:     }
 2392:     if (  $env{'form.ccdomain'} ne
 2393: 	  &LONCAPA::clean_domain($env{'form.ccdomain'}) ) {
 2394: 	$r->print($error.&mt('Invalid domain name.').'  '.
 2395: 		  &mt('Only letters, numbers, periods, dashes, and underscores are valid.').
 2396: 		  $end.$rtnlink);
 2397: 	return;
 2398:     }
 2399:     if ($uhome eq 'no_host') {
 2400:         $newuser = 1;
 2401:     }
 2402:     if (! exists($env{'form.makeuser'})) {
 2403:         # Modifying an existing user, so check the validity of the name
 2404:         if ($uhome eq 'no_host') {
 2405:             $r->print($error.&mt('Unable to determine home server for ').
 2406:                       $env{'form.ccuname'}.&mt(' in domain ').
 2407:                       $env{'form.ccdomain'}.'.');
 2408:             return;
 2409:         }
 2410:     }
 2411:     # Determine authentication method and password for the user being modified
 2412:     my $amode='';
 2413:     my $genpwd='';
 2414:     if ($env{'form.login'} eq 'krb') {
 2415: 	$amode='krb';
 2416: 	$amode.=$env{'form.krbver'};
 2417: 	$genpwd=$env{'form.krbarg'};
 2418:     } elsif ($env{'form.login'} eq 'int') {
 2419: 	$amode='internal';
 2420: 	$genpwd=$env{'form.intarg'};
 2421:     } elsif ($env{'form.login'} eq 'fsys') {
 2422: 	$amode='unix';
 2423: 	$genpwd=$env{'form.fsysarg'};
 2424:     } elsif ($env{'form.login'} eq 'loc') {
 2425: 	$amode='localauth';
 2426: 	$genpwd=$env{'form.locarg'};
 2427: 	$genpwd=" " if (!$genpwd);
 2428:     } elsif (($env{'form.login'} eq 'nochange') ||
 2429:              ($env{'form.login'} eq ''        )) { 
 2430:         # There is no need to tell the user we did not change what they
 2431:         # did not ask us to change.
 2432:         # If they are creating a new user but have not specified login
 2433:         # information this will be caught below.
 2434:     } else {
 2435:             $r->print($error.&mt('Invalid login mode or password').$end.$rtnlink);
 2436:             return;
 2437:     }
 2438: 
 2439:     $r->print('<h3>'.&mt('User [_1] in domain [_2]',
 2440:                         $env{'form.ccuname'}.' ('.&Apache::loncommon::plainname($env{'form.ccuname'},
 2441:                         $env{'form.ccdomain'}).')', $env{'form.ccdomain'}).'</h3>');
 2442:     my %prog_state = &Apache::lonhtmlcommon::Create_PrgWin($r,2);
 2443: 
 2444:     my (%alerts,%rulematch,%inst_results,%curr_rules);
 2445:     my @userinfo = ('firstname','middlename','lastname','generation','permanentemail','id');
 2446:     my @usertools = ('aboutme','blog','webdav','portfolio');
 2447:     my @requestcourses = ('official','unofficial','community');
 2448:     my @requestauthor = ('requestauthor');
 2449:     my ($othertitle,$usertypes,$types) = 
 2450:         &Apache::loncommon::sorted_inst_types($env{'form.ccdomain'});
 2451:     my %canmodify_status =
 2452:         &Apache::lonuserutils::can_modify_userinfo($context,$env{'form.ccdomain'},
 2453:                                                    ['inststatus']);
 2454:     if ($env{'form.makeuser'}) {
 2455: 	$r->print('<h3>'.&mt('Creating new account.').'</h3>');
 2456:         # Check for the authentication mode and password
 2457:         if (! $amode || ! $genpwd) {
 2458: 	    $r->print($error.&mt('Invalid login mode or password').$end.$rtnlink);    
 2459: 	    return;
 2460: 	}
 2461:         # Determine desired host
 2462:         my $desiredhost = $env{'form.hserver'};
 2463:         if (lc($desiredhost) eq 'default') {
 2464:             $desiredhost = undef;
 2465:         } else {
 2466:             my %home_servers = 
 2467: 		&Apache::lonnet::get_servers($env{'form.ccdomain'},'library');
 2468:             if (! exists($home_servers{$desiredhost})) {
 2469:                 $r->print($error.&mt('Invalid home server specified').$end.$rtnlink);
 2470:                 return;
 2471:             }
 2472:         }
 2473:         # Check ID format
 2474:         my %checkhash;
 2475:         my %checks = ('id' => 1);
 2476:         %{$checkhash{$env{'form.ccuname'}.':'.$env{'form.ccdomain'}}} = (
 2477:             'newuser' => $newuser, 
 2478:             'id' => $env{'form.cid'},
 2479:         );
 2480:         if ($env{'form.cid'} ne '') {
 2481:             &Apache::loncommon::user_rule_check(\%checkhash,\%checks,\%alerts,
 2482:                                           \%rulematch,\%inst_results,\%curr_rules);
 2483:             if (ref($alerts{'id'}) eq 'HASH') {
 2484:                 if (ref($alerts{'id'}{$env{'form.ccdomain'}}) eq 'HASH') {
 2485:                     my $domdesc =
 2486:                         &Apache::lonnet::domain($env{'form.ccdomain'},'description');
 2487:                     if ($alerts{'id'}{$env{'form.ccdomain'}}{$env{'form.cid'}}) {
 2488:                         my $userchkmsg;
 2489:                         if (ref($curr_rules{$env{'form.ccdomain'}}) eq 'HASH') {
 2490:                             $userchkmsg  = 
 2491:                                 &Apache::loncommon::instrule_disallow_msg('id',
 2492:                                                                     $domdesc,1).
 2493:                                 &Apache::loncommon::user_rule_formats($env{'form.ccdomain'},
 2494:                                     $domdesc,$curr_rules{$env{'form.ccdomain'}}{'id'},'id');
 2495:                         }
 2496:                         $r->print($error.&mt('Invalid ID format').$end.
 2497:                                   $userchkmsg.$rtnlink);
 2498:                         return;
 2499:                     }
 2500:                 }
 2501:             }
 2502:         }
 2503:         &Apache::lonhtmlcommon::Increment_PrgWin($r, \%prog_state);
 2504: 	# Call modifyuser
 2505: 	my $result = &Apache::lonnet::modifyuser
 2506: 	    ($env{'form.ccdomain'},$env{'form.ccuname'},$env{'form.cid'},
 2507:              $amode,$genpwd,$env{'form.cfirstname'},
 2508:              $env{'form.cmiddlename'},$env{'form.clastname'},
 2509:              $env{'form.cgeneration'},undef,$desiredhost,
 2510:              $env{'form.cpermanentemail'});
 2511: 	$r->print(&mt('Generating user').': '.$result);
 2512:         $uhome = &Apache::lonnet::homeserver($env{'form.ccuname'},
 2513:                                                $env{'form.ccdomain'});
 2514:         my (%changeHash,%newcustom,%changed,%changedinfo);
 2515:         if ($uhome ne 'no_host') {
 2516:             if ($context eq 'domain') {
 2517:                 if ($env{'form.customquota'} == 1) {
 2518:                     if ($env{'form.portfolioquota'} eq '') {
 2519:                         $newcustom{'quota'} = 0;
 2520:                     } else {
 2521:                         $newcustom{'quota'} = $env{'form.portfolioquota'};
 2522:                         $newcustom{'quota'} =~ s/[^\d\.]//g;
 2523:                     }
 2524:                     $changed{'quota'} = &quota_admin($newcustom{'quota'},\%changeHash);
 2525:                 }
 2526:                 foreach my $item (@usertools) {
 2527:                     if ($env{'form.custom'.$item} == 1) {
 2528:                         $newcustom{$item} = $env{'form.tools_'.$item};
 2529:                         $changed{$item} = &tool_admin($item,$newcustom{$item},
 2530:                                                      \%changeHash,'tools');
 2531:                     }
 2532:                 }
 2533:                 foreach my $item (@requestcourses) {
 2534:                     if ($env{'form.custom'.$item} == 1) {
 2535:                         $newcustom{$item} = $env{'form.crsreq_'.$item};
 2536:                         if ($env{'form.crsreq_'.$item} eq 'autolimit') {
 2537:                             $newcustom{$item} .= '=';
 2538:                             unless ($env{'form.crsreq_'.$item.'_limit'} =~ /\D/) {
 2539:                                 $newcustom{$item} .= $env{'form.crsreq_'.$item.'_limit'};
 2540:                             }
 2541:                         }
 2542:                         $changed{$item} = &tool_admin($item,$newcustom{$item},
 2543:                                                       \%changeHash,'requestcourses');
 2544:                     }
 2545:                 }
 2546:                 if ($env{'form.customrequestauthor'} == 1) {
 2547:                     $newcustom{'requestauthor'} = $env{'form.requestauthor'};
 2548:                     $changed{'requestauthor'} = &tool_admin('requestauthor',
 2549:                                                     $newcustom{'requestauthor'},
 2550:                                                     \%changeHash,'requestauthor');
 2551:                 }
 2552:             }
 2553:             if ($canmodify_status{'inststatus'}) {
 2554:                 if (exists($env{'form.inststatus'})) {
 2555:                     my @inststatuses = &Apache::loncommon::get_env_multiple('form.inststatus');
 2556:                     if (@inststatuses > 0) {
 2557:                         $changeHash{'inststatus'} = join(',',@inststatuses);
 2558:                         $changed{'inststatus'} = $changeHash{'inststatus'};
 2559:                     }
 2560:                 }
 2561:             }
 2562:             if (keys(%changed)) {
 2563:                 foreach my $item (@userinfo) {
 2564:                     $changeHash{$item}  = $env{'form.c'.$item};
 2565:                 }
 2566:                 my $chgresult =
 2567:                      &Apache::lonnet::put('environment',\%changeHash,
 2568:                                           $env{'form.ccdomain'},$env{'form.ccuname'});
 2569:             } 
 2570:         }
 2571:         $r->print('<br />'.&mt('Home server').': '.$uhome.' '.
 2572:                   &Apache::lonnet::hostname($uhome));
 2573:     } elsif (($env{'form.login'} ne 'nochange') &&
 2574:              ($env{'form.login'} ne ''        )) {
 2575: 	# Modify user privileges
 2576:         if (! $amode || ! $genpwd) {
 2577: 	    $r->print($error.'Invalid login mode or password'.$end.$rtnlink);    
 2578: 	    return;
 2579: 	}
 2580: 	# Only allow authentification modification if the person has authority
 2581: 	if (&Apache::lonnet::allowed('mau',$env{'form.ccdomain'})) {
 2582: 	    $r->print('Modifying authentication: '.
 2583:                       &Apache::lonnet::modifyuserauth(
 2584: 		       $env{'form.ccdomain'},$env{'form.ccuname'},
 2585:                        $amode,$genpwd));
 2586:             $r->print('<br />'.&mt('Home server').': '.&Apache::lonnet::homeserver
 2587: 		  ($env{'form.ccuname'},$env{'form.ccdomain'}));
 2588: 	} else {
 2589: 	    # Okay, this is a non-fatal error.
 2590: 	    $r->print($error.&mt('You do not have the authority to modify this users authentification information').'.'.$end);    
 2591: 	}
 2592:     }
 2593:     $r->rflush(); # Finish display of header before time consuming actions start
 2594:     &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state);
 2595:     ##
 2596:     my (@userroles,%userupdate,$cnum,$cdom,%namechanged);
 2597:     if ($context eq 'course') {
 2598:         ($cnum,$cdom) = &Apache::lonuserutils::get_course_identity();
 2599:         $crstype = &Apache::loncommon::course_type($cdom.'_'.$cnum);
 2600:     }
 2601:     if (! $env{'form.makeuser'} ) {
 2602:         # Check for need to change
 2603:         my %userenv = &Apache::lonnet::get
 2604:             ('environment',['firstname','middlename','lastname','generation',
 2605:              'id','permanentemail','portfolioquota','inststatus','tools.aboutme',
 2606:              'tools.blog','tools.webdav','tools.portfolio',
 2607:              'requestcourses.official','requestcourses.unofficial',
 2608:              'requestcourses.community','reqcrsotherdom.official',
 2609:              'reqcrsotherdom.unofficial','reqcrsotherdom.community',
 2610:              'requestauthor'],
 2611:               $env{'form.ccdomain'},$env{'form.ccuname'});
 2612:         my ($tmp) = keys(%userenv);
 2613:         if ($tmp =~ /^(con_lost|error)/i) { 
 2614:             %userenv = ();
 2615:         }
 2616:         my $no_forceid_alert;
 2617:         # Check to see if user information can be changed
 2618:         my %domconfig =
 2619:             &Apache::lonnet::get_dom('configuration',['usermodification'],
 2620:                                      $env{'form.ccdomain'});
 2621:         my @statuses = ('active','future');
 2622:         my %roles = &Apache::lonnet::get_my_roles($env{'form.ccuname'},$env{'form.ccdomain'},'userroles',\@statuses,undef,$env{'request.role.domain'});
 2623:         my ($auname,$audom);
 2624:         if ($context eq 'author') {
 2625:             $auname = $env{'user.name'};
 2626:             $audom = $env{'user.domain'};     
 2627:         }
 2628:         foreach my $item (keys(%roles)) {
 2629:             my ($rolenum,$roledom,$role) = split(/:/,$item,-1);
 2630:             if ($context eq 'course') {
 2631:                 if ($cnum ne '' && $cdom ne '') {
 2632:                     if ($rolenum eq $cnum && $roledom eq $cdom) {
 2633:                         if (!grep(/^\Q$role\E$/,@userroles)) {
 2634:                             push(@userroles,$role);
 2635:                         }
 2636:                     }
 2637:                 }
 2638:             } elsif ($context eq 'author') {
 2639:                 if ($rolenum eq $auname && $roledom eq $audom) {
 2640:                     if (!grep(/^\Q$role\E$/,@userroles)) { 
 2641:                         push(@userroles,$role);
 2642:                     }
 2643:                 }
 2644:             }
 2645:         }
 2646:         if ($env{'form.action'} eq 'singlestudent') {
 2647:             if (!grep(/^st$/,@userroles)) {
 2648:                 push(@userroles,'st');
 2649:             }
 2650:         } else {
 2651:             # Check for course or co-author roles being activated or re-enabled
 2652:             if ($context eq 'author' || $context eq 'course') {
 2653:                 foreach my $key (keys(%env)) {
 2654:                     if ($context eq 'author') {
 2655:                         if ($key=~/^form\.act_\Q$audom\E_\Q$auname\E_([^_]+)/) {
 2656:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 2657:                                 push(@userroles,$1);
 2658:                             }
 2659:                         } elsif ($key =~/^form\.ren\:\Q$audom\E\/\Q$auname\E_([^_]+)/) {
 2660:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 2661:                                 push(@userroles,$1);
 2662:                             }
 2663:                         }
 2664:                     } elsif ($context eq 'course') {
 2665:                         if ($key=~/^form\.act_\Q$cdom\E_\Q$cnum\E_([^_]+)/) {
 2666:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 2667:                                 push(@userroles,$1);
 2668:                             }
 2669:                         } elsif ($key =~/^form\.ren\:\Q$cdom\E\/\Q$cnum\E(\/?\w*)_([^_]+)/) {
 2670:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 2671:                                 push(@userroles,$1);
 2672:                             }
 2673:                         }
 2674:                     }
 2675:                 }
 2676:             }
 2677:         }
 2678:         #Check to see if we can change personal data for the user 
 2679:         my (@mod_disallowed,@longroles);
 2680:         foreach my $role (@userroles) {
 2681:             if ($role eq 'cr') {
 2682:                 push(@longroles,'Custom');
 2683:             } else {
 2684:                 push(@longroles,&Apache::lonnet::plaintext($role,$crstype)); 
 2685:             }
 2686:         }
 2687:         my %canmodify = &Apache::lonuserutils::can_modify_userinfo($context,$env{'form.ccdomain'},\@userinfo,\@userroles);
 2688:         foreach my $item (@userinfo) {
 2689:             # Strip leading and trailing whitespace
 2690:             $env{'form.c'.$item} =~ s/(\s+$|^\s+)//g;
 2691:             if (!$canmodify{$item}) {
 2692:                 if (defined($env{'form.c'.$item})) {
 2693:                     if ($env{'form.c'.$item} ne $userenv{$item}) {
 2694:                         push(@mod_disallowed,$item);
 2695:                     }
 2696:                 }
 2697:                 $env{'form.c'.$item} = $userenv{$item};
 2698:             }
 2699:         }
 2700:         # Check to see if we can change the Student/Employee ID
 2701:         my $forceid = $env{'form.forceid'};
 2702:         my $recurseid = $env{'form.recurseid'};
 2703:         my (%alerts,%rulematch,%idinst_results,%curr_rules,%got_rules);
 2704:         my %uidhash = &Apache::lonnet::idrget($env{'form.ccdomain'},
 2705:                                             $env{'form.ccuname'});
 2706:         if (($uidhash{$env{'form.ccuname'}}) && 
 2707:             ($uidhash{$env{'form.ccuname'}}!~/error\:/) && 
 2708:             (!$forceid)) {
 2709:             if ($env{'form.cid'} ne $uidhash{$env{'form.ccuname'}}) {
 2710:                 $env{'form.cid'} = $userenv{'id'};
 2711:                 $no_forceid_alert = &mt('New student/employee ID does not match existing ID for this user.')
 2712:                                    .'<br />'
 2713:                                    .&mt("Change is not permitted without checking the 'Force ID change' checkbox on the previous page.")
 2714:                                    .'<br />'."\n";
 2715:             }
 2716:         }
 2717:         if ($env{'form.cid'} ne $userenv{'id'}) {
 2718:             my $checkhash;
 2719:             my $checks = { 'id' => 1 };
 2720:             $checkhash->{$env{'form.ccuname'}.':'.$env{'form.ccdomain'}} = 
 2721:                    { 'newuser' => $newuser,
 2722:                      'id'  => $env{'form.cid'}, 
 2723:                    };
 2724:             &Apache::loncommon::user_rule_check($checkhash,$checks,
 2725:                 \%alerts,\%rulematch,\%idinst_results,\%curr_rules,\%got_rules);
 2726:             if (ref($alerts{'id'}) eq 'HASH') {
 2727:                 if (ref($alerts{'id'}{$env{'form.ccdomain'}}) eq 'HASH') {
 2728:                    $env{'form.cid'} = $userenv{'id'};
 2729:                 }
 2730:             }
 2731:         }
 2732:         my ($quotachanged,$oldportfolioquota,$newportfolioquota,$oldinststatus,
 2733:             $newinststatus,$oldisdefault,$newisdefault,%oldsettings,
 2734:             %oldsettingstext,%newsettings,%newsettingstext,@disporder,
 2735:             $olddefquota,$oldsettingstatus,$newdefquota,$newsettingstatus);
 2736:         @disporder = ('inststatus');
 2737:         if ($env{'request.role.domain'} eq $env{'form.ccdomain'}) {
 2738:             push(@disporder,'requestcourses','requestauthor');
 2739:         } else {
 2740:             push(@disporder,'reqcrsotherdom');
 2741:         }
 2742:         push(@disporder,('quota','tools'));
 2743:         $oldinststatus = $userenv{'inststatus'};
 2744:         ($olddefquota,$oldsettingstatus) = 
 2745:             &Apache::loncommon::default_quota($env{'form.ccdomain'},$oldinststatus);
 2746:         ($newdefquota,$newsettingstatus) = ($olddefquota,$oldsettingstatus);
 2747:         my %canshow;
 2748:         if (&Apache::lonnet::allowed('mpq',$env{'form.ccdomain'})) {
 2749:             $canshow{'quota'} = 1;
 2750:         }
 2751:         if (&Apache::lonnet::allowed('mut',$env{'form.ccdomain'})) {
 2752:             $canshow{'tools'} = 1;
 2753:         }
 2754:         if (&Apache::lonnet::allowed('ccc',$env{'form.ccdomain'})) {
 2755:             $canshow{'requestcourses'} = 1;
 2756:         } elsif (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) {
 2757:             $canshow{'reqcrsotherdom'} = 1;
 2758:         }
 2759:         if (&Apache::lonnet::allowed('mau',$env{'form.ccdomain'})) {
 2760:             $canshow{'inststatus'} = 1;
 2761:         }
 2762:         if (&Apache::lonnet::allowed('cau',$env{'form.ccdomain'})) {
 2763:             $canshow{'requestauthor'} = 1;
 2764:         }
 2765:         my (%changeHash,%changed);
 2766:         if ($oldinststatus eq '') {
 2767:             $oldsettings{'inststatus'} = $othertitle; 
 2768:         } else {
 2769:             if (ref($usertypes) eq 'HASH') {
 2770:                 $oldsettings{'inststatus'} = join(', ',map{ $usertypes->{ &unescape($_) }; } (split(/:/,$userenv{'inststatus'})));
 2771:             } else {
 2772:                 $oldsettings{'inststatus'} = join(', ',map{ &unescape($_); } (split(/:/,$userenv{'inststatus'})));
 2773:             }
 2774:         }
 2775:         $changeHash{'inststatus'} = $userenv{'inststatus'};
 2776:         if ($canmodify_status{'inststatus'}) {
 2777:             $canshow{'inststatus'} = 1;
 2778:             if (exists($env{'form.inststatus'})) {
 2779:                 my @inststatuses = &Apache::loncommon::get_env_multiple('form.inststatus');
 2780:                 if (@inststatuses > 0) {
 2781:                     $newinststatus = join(':',map { &escape($_); } @inststatuses);
 2782:                     $changeHash{'inststatus'} = $newinststatus;
 2783:                     if ($newinststatus ne $oldinststatus) {
 2784:                         $changed{'inststatus'} = $newinststatus;
 2785:                         ($newdefquota,$newsettingstatus) =
 2786:                             &Apache::loncommon::default_quota($env{'form.ccdomain'},$newinststatus);
 2787:                     }
 2788:                     if (ref($usertypes) eq 'HASH') {
 2789:                         $newsettings{'inststatus'} = join(', ',map{ $usertypes->{$_}; } (@inststatuses)); 
 2790:                     } else {
 2791:                         $newsettings{'inststatus'} = join(', ',@inststatuses);
 2792:                     }
 2793:                 }
 2794:             } else {
 2795:                 $newinststatus = '';
 2796:                 $changeHash{'inststatus'} = $newinststatus;
 2797:                 $newsettings{'inststatus'} = $othertitle;
 2798:                 if ($newinststatus ne $oldinststatus) {
 2799:                     $changed{'inststatus'} = $changeHash{'inststatus'};
 2800:                     ($newdefquota,$newsettingstatus) =
 2801:                         &Apache::loncommon::default_quota($env{'form.ccdomain'},$newinststatus);
 2802:                 }
 2803:             }
 2804:         } elsif ($context ne 'selfcreate') {
 2805:             $canshow{'inststatus'} = 1;
 2806:             $newsettings{'inststatus'} = $oldsettings{'inststatus'};
 2807:         }
 2808:         $changeHash{'portfolioquota'} = $userenv{'portfolioquota'};
 2809:         if ($context eq 'domain') {
 2810:             if ($userenv{'portfolioquota'} ne '') {
 2811:                 $oldportfolioquota = $userenv{'portfolioquota'};
 2812:                 if ($env{'form.customquota'} == 1) {
 2813:                     if ($env{'form.portfolioquota'} eq '') {
 2814:                         $newportfolioquota = 0;
 2815:                     } else {
 2816:                         $newportfolioquota = $env{'form.portfolioquota'};
 2817:                         $newportfolioquota =~ s/[^\d\.]//g;
 2818:                     }
 2819:                     if ($newportfolioquota != $oldportfolioquota) {
 2820:                         $changed{'quota'} = &quota_admin($newportfolioquota,\%changeHash);
 2821:                     }
 2822:                 } else {
 2823:                     $changed{'quota'} = &quota_admin('',\%changeHash);
 2824:                     $newportfolioquota = $newdefquota;
 2825:                     $newisdefault = 1;
 2826:                 }
 2827:             } else {
 2828:                 $oldisdefault = 1;
 2829:                 $oldportfolioquota = $olddefquota;
 2830:                 if ($env{'form.customquota'} == 1) {
 2831:                     if ($env{'form.portfolioquota'} eq '') {
 2832:                         $newportfolioquota = 0;
 2833:                     } else {
 2834:                         $newportfolioquota = $env{'form.portfolioquota'};
 2835:                         $newportfolioquota =~ s/[^\d\.]//g;
 2836:                     }
 2837:                     $changed{'quota'} = &quota_admin($newportfolioquota,\%changeHash);
 2838:                 } else {
 2839:                     $newportfolioquota = $newdefquota;
 2840:                     $newisdefault = 1;
 2841:                 }
 2842:             }
 2843:             if ($oldisdefault) {
 2844:                 $oldsettingstext{'quota'} = &get_defaultquota_text($oldsettingstatus);
 2845:             }
 2846:             if ($newisdefault) {
 2847:                 $newsettingstext{'quota'} = &get_defaultquota_text($newsettingstatus);
 2848:             }
 2849:             &tool_changes('tools',\@usertools,\%oldsettings,\%oldsettingstext,\%userenv,
 2850:                           \%changeHash,\%changed,\%newsettings,\%newsettingstext);
 2851:             if ($env{'form.ccdomain'} eq $env{'request.role.domain'}) {
 2852:                 &tool_changes('requestcourses',\@requestcourses,\%oldsettings,\%oldsettingstext,
 2853:                               \%userenv,\%changeHash,\%changed,\%newsettings,\%newsettingstext);
 2854:                 &tool_changes('requestauthor',\@requestauthor,\%oldsettings,\%oldsettingstext,\%userenv,\%changeHash,\%changed,\%newsettings,\%newsettingstext);
 2855:             } else {
 2856:                 &tool_changes('reqcrsotherdom',\@requestcourses,\%oldsettings,\%oldsettingstext,
 2857:                               \%userenv,\%changeHash,\%changed,\%newsettings,\%newsettingstext);
 2858:             }
 2859:         }
 2860:         foreach my $item (@userinfo) {
 2861:             if ($env{'form.c'.$item} ne $userenv{$item}) {
 2862:                 $namechanged{$item} = 1;
 2863:             }
 2864:         }
 2865:         $oldsettings{'quota'} = $oldportfolioquota.' Mb';
 2866:         $newsettings{'quota'} = $newportfolioquota.' Mb';
 2867:         if ((keys(%namechanged) > 0) || (keys(%changed) > 0)) {
 2868:             my ($chgresult,$namechgresult);
 2869:             if (keys(%changed) > 0) {
 2870:                 $chgresult = 
 2871:                     &Apache::lonnet::put('environment',\%changeHash,
 2872:                                   $env{'form.ccdomain'},$env{'form.ccuname'});
 2873:                 if ($chgresult eq 'ok') {
 2874:                     if (($env{'user.name'} eq $env{'form.ccuname'}) &&
 2875:                         ($env{'user.domain'} eq $env{'form.ccdomain'})) {
 2876:                         my %newenvhash;
 2877:                         foreach my $key (keys(%changed)) {
 2878:                             if (($key eq 'official') || ($key eq 'unofficial')
 2879:                                 || ($key eq 'community')) {
 2880:                                 $newenvhash{'environment.requestcourses.'.$key} =
 2881:                                     $changeHash{'requestcourses.'.$key};
 2882:                                 if ($changeHash{'requestcourses.'.$key}) {
 2883:                                     $newenvhash{'environment.canrequest.'.$key} = 1;
 2884:                                 } else {
 2885:                                     $newenvhash{'environment.canrequest.'.$key} =
 2886:           &Apache::lonnet::usertools_access($env{'user.name'},$env{'user.domain'},
 2887:                                             $key,'reload','requestcourses');
 2888:                                 }
 2889:                             } elsif ($key eq 'requestauthor') {
 2890:                                 $newenvhash{'environment.'.$key} = $changeHash{$key};
 2891:                                 if ($changeHash{$key}) {
 2892:                                     $newenvhash{'environment.canrequest.author'} = 1;
 2893:                                 } else {
 2894:                                     $newenvhash{'environment.canrequest.author'} =
 2895:           &Apache::lonnet::usertools_access($env{'user.name'},$env{'user.domain'},
 2896:                                             $key,'reload','requestauthor');
 2897:                                 }
 2898:                             } elsif ($key ne 'quota') {
 2899:                                 $newenvhash{'environment.tools.'.$key} = 
 2900:                                     $changeHash{'tools.'.$key};
 2901:                                 if ($changeHash{'tools.'.$key} ne '') {
 2902:                                     $newenvhash{'environment.availabletools.'.$key} =
 2903:                                         $changeHash{'tools.'.$key};
 2904:                                 } else {
 2905:                                     $newenvhash{'environment.availabletools.'.$key} =
 2906:           &Apache::lonnet::usertools_access($env{'user.name'},$env{'user.domain'},
 2907:           $key,'reload','tools');
 2908:                                 }
 2909:                             }
 2910:                         }
 2911:                         if (keys(%newenvhash)) {
 2912:                             &Apache::lonnet::appenv(\%newenvhash);
 2913:                         }
 2914:                     }
 2915:                 }
 2916:             }
 2917:             if (keys(%namechanged) > 0) {
 2918:                 foreach my $field (@userinfo) {
 2919:                     $changeHash{$field}  = $env{'form.c'.$field};
 2920:                 }
 2921: # Make the change
 2922:                 $namechgresult =
 2923:                     &Apache::lonnet::modifyuser($env{'form.ccdomain'},
 2924:                         $env{'form.ccuname'},$changeHash{'id'},undef,undef,
 2925:                         $changeHash{'firstname'},$changeHash{'middlename'},
 2926:                         $changeHash{'lastname'},$changeHash{'generation'},
 2927:                         $changeHash{'id'},undef,$changeHash{'permanentemail'},undef,\@userinfo);
 2928:                 %userupdate = (
 2929:                                lastname   => $env{'form.clastname'},
 2930:                                middlename => $env{'form.cmiddlename'},
 2931:                                firstname  => $env{'form.cfirstname'},
 2932:                                generation => $env{'form.cgeneration'},
 2933:                                id         => $env{'form.cid'},
 2934:                              );
 2935:             }
 2936:             if (((keys(%namechanged) > 0) && $namechgresult eq 'ok') || 
 2937:                 ((keys(%changed) > 0) && $chgresult eq 'ok')) {
 2938:             # Tell the user we changed the name
 2939:                 &display_userinfo($r,1,\@disporder,\%canshow,\@requestcourses,
 2940:                                   \@usertools,\@requestauthor,\%userenv,\%changed,\%namechanged,
 2941:                                   \%oldsettings, \%oldsettingstext,\%newsettings,
 2942:                                   \%newsettingstext);
 2943:                 if ($env{'form.cid'} ne $userenv{'id'}) {
 2944:                     &Apache::lonnet::idput($env{'form.ccdomain'},
 2945:                          ($env{'form.ccuname'} => $env{'form.cid'}));
 2946:                     if (($recurseid) &&
 2947:                         (&Apache::lonnet::allowed('mau',$env{'form.ccdomain'}))) {
 2948:                         my $idresult = 
 2949:                             &Apache::lonuserutils::propagate_id_change(
 2950:                                 $env{'form.ccuname'},$env{'form.ccdomain'},
 2951:                                 \%userupdate);
 2952:                         $r->print('<br />'.$idresult.'<br />');
 2953:                     }
 2954:                 }
 2955:                 if (($env{'form.ccdomain'} eq $env{'user.domain'}) && 
 2956:                     ($env{'form.ccuname'} eq $env{'user.name'})) {
 2957:                     my %newenvhash;
 2958:                     foreach my $key (keys(%changeHash)) {
 2959:                         $newenvhash{'environment.'.$key} = $changeHash{$key};
 2960:                     }
 2961:                     &Apache::lonnet::appenv(\%newenvhash);
 2962:                 }
 2963:             } else { # error occurred
 2964:                 $r->print('<span class="LC_error">'.&mt('Unable to successfully change environment for').' '.
 2965:                       $env{'form.ccuname'}.' '.&mt('in domain').' '.
 2966:                       $env{'form.ccdomain'}.'</span><br />');
 2967:             }
 2968:         } else { # End of if ($env ... ) logic
 2969:             # They did not want to change the users name, quota, tool availability,
 2970:             # or ability to request creation of courses, 
 2971:             # but we can still tell them what the name and quota and availabilities are  
 2972:             &display_userinfo($r,undef,\@disporder,\%canshow,\@requestcourses,
 2973:                               \@usertools,\@requestauthor,\%userenv,\%changed,\%namechanged,\%oldsettings,
 2974:                               \%oldsettingstext,\%newsettings,\%newsettingstext);
 2975:         }
 2976:         if (@mod_disallowed) {
 2977:             my ($rolestr,$contextname);
 2978:             if (@longroles > 0) {
 2979:                 $rolestr = join(', ',@longroles);
 2980:             } else {
 2981:                 $rolestr = &mt('No roles');
 2982:             }
 2983:             if ($context eq 'course') {
 2984:                 $contextname = &mt('course');
 2985:             } elsif ($context eq 'author') {
 2986:                 $contextname = &mt('co-author');
 2987:             }
 2988:             $r->print(&mt('The following fields were not updated: ').'<ul>');
 2989:             my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
 2990:             foreach my $field (@mod_disallowed) {
 2991:                 $r->print('<li>'.$fieldtitles{$field}.'</li>'."\n"); 
 2992:             }
 2993:             $r->print('</ul>');
 2994:             if (@mod_disallowed == 1) {
 2995:                 $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));
 2996:             } else {
 2997:                 $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));
 2998:             }
 2999:             my $helplink = 'javascript:helpMenu('."'display'".')';
 3000:             $r->print('<span class="LC_cusr_emph">'.$rolestr.'</span><br />'
 3001:                      .&mt('Please contact your [_1]helpdesk[_2] for more information.'
 3002:                          ,'<a href="'.$helplink.'">','</a>')
 3003:                       .'<br />');
 3004:         }
 3005:         $r->print('<span class="LC_warning">'
 3006:                   .$no_forceid_alert
 3007:                   .&Apache::lonuserutils::print_namespacing_alerts($env{'form.ccdomain'},\%alerts,\%curr_rules)
 3008:                   .'</span>');
 3009:     }
 3010:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 3011:     if ($env{'form.action'} eq 'singlestudent') {
 3012:         &enroll_single_student($r,$uhome,$amode,$genpwd,$now,$newuser,$context,$crstype);
 3013:         $r->print('<p><a href="javascript:backPage(document.userupdate)">');
 3014:         if ($crstype eq 'Community') {
 3015:             $r->print(&mt('Enroll Another Member'));
 3016:         } else {
 3017:             $r->print(&mt('Enroll Another Student'));
 3018:         }
 3019:         $r->print('</a></p>');
 3020:     } else {
 3021:         my @rolechanges = &update_roles($r,$context);
 3022:         if (keys(%namechanged) > 0) {
 3023:             if ($context eq 'course') {
 3024:                 if (@userroles > 0) {
 3025:                     if ((@rolechanges == 0) || 
 3026:                         (!(grep(/^st$/,@rolechanges)))) {
 3027:                         if (grep(/^st$/,@userroles)) {
 3028:                             my $classlistupdated =
 3029:                                 &Apache::lonuserutils::update_classlist($cdom,
 3030:                                               $cnum,$env{'form.ccdomain'},
 3031:                                        $env{'form.ccuname'},\%userupdate);
 3032:                         }
 3033:                     }
 3034:                 }
 3035:             }
 3036:         }
 3037:         my $userinfo = &Apache::loncommon::plainname($env{'form.ccuname'},
 3038:                                                      $env{'form.ccdomain'});
 3039:         if ($env{'form.popup'}) {
 3040:             $r->print('<p><a href="javascript:window.close()">'.&mt('Close window').'</a></p>');
 3041:         } else {
 3042:             $r->print('<br />'.&Apache::lonhtmlcommon::actionbox(['<a href="javascript:backPage(document.userupdate,'."'$env{'form.prevphase'}','modify'".')">'
 3043:                      .&mt('Modify this user: [_1]','<span class="LC_cusr_emph">'.$env{'form.ccuname'}.':'.$env{'form.ccdomain'}.' ('.$userinfo.')</span>').'</a>',
 3044:                      '<a href="javascript:backPage(document.userupdate)">'.&mt('Create/Modify Another User').'</a>']));
 3045:         }
 3046:     }
 3047: }
 3048: 
 3049: sub display_userinfo {
 3050:     my ($r,$changed,$order,$canshow,$requestcourses,$usertools,$requestauthor,
 3051:         $userenv,$changedhash,$namechangedhash,$oldsetting,$oldsettingtext,
 3052:         $newsetting,$newsettingtext) = @_;
 3053:     return unless (ref($order) eq 'ARRAY' &&
 3054:                    ref($canshow) eq 'HASH' && 
 3055:                    ref($requestcourses) eq 'ARRAY' && 
 3056:                    ref($requestauthor) eq 'ARRAY' &&
 3057:                    ref($usertools) eq 'ARRAY' && 
 3058:                    ref($userenv) eq 'HASH' &&
 3059:                    ref($changedhash) eq 'HASH' &&
 3060:                    ref($oldsetting) eq 'HASH' &&
 3061:                    ref($oldsettingtext) eq 'HASH' &&
 3062:                    ref($newsetting) eq 'HASH' &&
 3063:                    ref($newsettingtext) eq 'HASH');
 3064:     my %lt=&Apache::lonlocal::texthash(
 3065:          'ui'             => 'User Information (unchanged)',
 3066:          'uic'            => 'User Information Changed',
 3067:          'firstname'      => 'First Name',
 3068:          'middlename'     => 'Middle Name',
 3069:          'lastname'       => 'Last Name',
 3070:          'generation'     => 'Generation',
 3071:          'id'             => 'Student/Employee ID',
 3072:          'permanentemail' => 'Permanent e-mail address',
 3073:          'quota'          => 'Disk space allocated to portfolio files',
 3074:          'blog'           => 'Blog Availability',
 3075:          'webdav'         => 'WebDAV Availability',
 3076:          'aboutme'        => 'Personal Information Page Availability',
 3077:          'portfolio'      => 'Portfolio Availability',
 3078:          'official'       => 'Can Request Official Courses',
 3079:          'unofficial'     => 'Can Request Unofficial Courses',
 3080:          'community'      => 'Can Request Communities',
 3081:          'requestauthor'  => 'Can Request Author Role',
 3082:          'inststatus'     => "Affiliation",
 3083:          'prvs'           => 'Previous Value:',
 3084:          'chto'           => 'Changed To:'
 3085:     );
 3086:     my $title = $lt{'ui'}; 
 3087:     if ($changed) {
 3088:         $title = $lt{'uic'};
 3089:         $r->print('<h4>'.$title.'</h4>'.
 3090:                 &Apache::loncommon::start_data_table().
 3091:                 &Apache::loncommon::start_data_table_header_row());
 3092:         $r->print("<th>&nbsp;</th>\n");
 3093:         $r->print('<th><b>'.$lt{'prvs'}.'</b></th>');
 3094:         $r->print('<th><span class="LC_nobreak"><b>'.$lt{'chto'}.'</b></span></th>');
 3095:         $r->print(&Apache::loncommon::end_data_table_header_row());
 3096:         my @userinfo = ('firstname','middlename','lastname','generation','permanentemail','id');
 3097:         
 3098: 
 3099:         foreach my $item (@userinfo) {
 3100:             my $value = $env{'form.c'.$item};
 3101:             #show changes only:
 3102:             unless($value eq $userenv->{$item}){
 3103:                 $r->print(&Apache::loncommon::start_data_table_row());
 3104: 
 3105:                 $r->print("<td>$lt{$item}</td>\n");
 3106:                 $r->print('<td>'.$userenv->{$item}.' </td>');
 3107:                 $r->print("<td>$value </td>\n");
 3108: 
 3109:                 $r->print(&Apache::loncommon::end_data_table_row());
 3110:             }
 3111:         }
 3112:         foreach my $entry (@{$order}) {
 3113:             if ($canshow->{$entry} && ($newsetting->{$entry} ne $newsetting->{$entry})) {
 3114:                 $r->print(&Apache::loncommon::start_data_table_row());
 3115:                 if (($entry eq 'requestcourses') || ($entry eq 'reqcrsotherdom')) {
 3116:                     foreach my $item (@{$requestcourses}) {
 3117:                         $r->print("<td>$lt{$item}</td>\n");
 3118:                         $r->print("<td>$oldsetting->{$item} $oldsettingtext->{$item}</td>\n");
 3119:                         my $value = $newsetting->{$item}.' '.$newsettingtext->{$item};
 3120:                         if ($changedhash->{$item}) {
 3121:                             $value = '<span class="LC_cusr_emph">'.$value.'</span>';
 3122:                         }
 3123:                         $r->print("<td>$value </td>\n");
 3124:                     }
 3125:                 } elsif ($entry eq 'tools') {
 3126:                     foreach my $item (@{$usertools}) {
 3127:                         $r->print("<td>$lt{$item}</td>\n");
 3128:                         $r->print("<td>$oldsetting->{$item} $oldsettingtext->{$item}</td>\n");
 3129:                         my $value = $newsetting->{$item}.' '.$newsettingtext->{$item};
 3130:                         if ($changedhash->{$item}) {
 3131:                             $value = '<span class="LC_cusr_emph">'.$value.'</span>';
 3132:                         }
 3133:                         $r->print("<td>$value </td>\n");
 3134:                     }
 3135:                 } else {
 3136:                     $r->print("<td>$lt{$entry}</td>\n");
 3137:                     $r->print("<td>$oldsetting->{$entry} $oldsettingtext->{$entry} </td>\n");
 3138:                     my $value = $newsetting->{$entry}.' '.$newsettingtext->{$entry};
 3139:                     if ($changedhash->{$entry}) {
 3140:                         $value = '<span class="LC_cusr_emph">'.$value.'</span>';
 3141:                     }
 3142:                     $r->print("<td>$value </td>\n");
 3143:                 }
 3144:                 $r->print(&Apache::loncommon::end_data_table_row());
 3145:             }
 3146:         }
 3147:         $r->print(&Apache::loncommon::end_data_table().'<br />');
 3148:     }
 3149:     return;
 3150: }
 3151: 
 3152: sub tool_changes {
 3153:     my ($context,$usertools,$oldaccess,$oldaccesstext,$userenv,$changeHash,
 3154:         $changed,$newaccess,$newaccesstext) = @_;
 3155:     if (!((ref($usertools) eq 'ARRAY') && (ref($oldaccess) eq 'HASH') &&
 3156:           (ref($oldaccesstext) eq 'HASH') && (ref($userenv) eq 'HASH') &&
 3157:           (ref($changeHash) eq 'HASH') && (ref($changed) eq 'HASH') &&
 3158:           (ref($newaccess) eq 'HASH') && (ref($newaccesstext) eq 'HASH'))) {
 3159:         return;
 3160:     }
 3161:     if ($context eq 'reqcrsotherdom') {
 3162:         my @options = ('approval','validate','autolimit');
 3163:         my $optregex = join('|',@options);
 3164:         my %reqdisplay = &courserequest_display();
 3165:         my $cdom = $env{'request.role.domain'};
 3166:         foreach my $tool (@{$usertools}) {
 3167:             $oldaccesstext->{$tool} = &mt('No');
 3168:             $newaccesstext->{$tool} = $oldaccesstext->{$tool};
 3169:             $changeHash->{$context.'.'.$tool} = $userenv->{$context.'.'.$tool};
 3170:             my $newop;
 3171:             if ($env{'form.'.$context.'_'.$tool}) {
 3172:                 $newop = $env{'form.'.$context.'_'.$tool};
 3173:                 if ($newop eq 'autolimit') {
 3174:                     my $limit = $env{'form.'.$context.'_'.$tool.'_limit'};
 3175:                     $limit =~ s/\D+//g;
 3176:                     $newop .= '='.$limit;
 3177:                 }
 3178:             }
 3179:             if ($userenv->{$context.'.'.$tool} eq '') {
 3180:                 if ($newop) {
 3181:                     $changed->{$tool}=&tool_admin($tool,$cdom.':'.$newop,
 3182:                                                   $changeHash,$context);
 3183:                     if ($changed->{$tool}) {
 3184:                         $newaccesstext->{$tool} = &mt('Yes');
 3185:                     } else {
 3186:                         $newaccesstext->{$tool} = $oldaccesstext->{$tool};
 3187:                     }
 3188:                 }
 3189:             } else {
 3190:                 my @curr = split(',',$userenv->{$context.'.'.$tool});
 3191:                 my @new;
 3192:                 my $changedoms;
 3193:                 foreach my $req (@curr) {
 3194:                     if ($req =~ /^\Q$cdom\E\:($optregex\=?\d*)$/) {
 3195:                         $oldaccesstext->{$tool} = &mt('Yes');
 3196:                         my $oldop = $1;
 3197:                         if ($oldop ne $newop) {
 3198:                             $changedoms = 1;
 3199:                             foreach my $item (@curr) {
 3200:                                 my ($reqdom,$option) = split(':',$item);
 3201:                                 unless ($reqdom eq $cdom) {
 3202:                                     push(@new,$item);
 3203:                                 }
 3204:                             }
 3205:                             if ($newop) {
 3206:                                 push(@new,$cdom.':'.$newop);
 3207:                             }
 3208:                             @new = sort(@new);
 3209:                         }
 3210:                         last;
 3211:                     }
 3212:                 }
 3213:                 if ((!$changedoms) && ($newop)) {
 3214:                     $changedoms = 1;
 3215:                     @new = sort(@curr,$cdom.':'.$newop);
 3216:                 }
 3217:                 if ($changedoms) {
 3218:                     my $newdomstr;
 3219:                     if (@new) {
 3220:                         $newdomstr = join(',',@new);
 3221:                     }
 3222:                     $changed->{$tool}=&tool_admin($tool,$newdomstr,$changeHash,
 3223:                                                   $context);
 3224:                     if ($changed->{$tool}) {
 3225:                         if ($env{'form.'.$context.'_'.$tool}) {
 3226:                             if ($env{'form.'.$context.'_'.$tool} eq 'autolimit') {
 3227:                                 my $limit = $env{'form.'.$context.'_'.$tool.'_limit'};
 3228:                                 $limit =~ s/\D+//g;
 3229:                                 if ($limit) {
 3230:                                     $newaccesstext->{$tool} = &mt('Yes, up to limit of [quant,_1,request] per user.',$limit);
 3231:                                 } else {
 3232:                                     $newaccesstext->{$tool} = &mt('Yes, processed automatically');
 3233:                                 }
 3234:                             } else {
 3235:                                 $newaccesstext->{$tool} = $reqdisplay{$env{'form.'.$context.'_'.$tool}};
 3236:                             }
 3237:                         } else {
 3238:                             $newaccesstext->{$tool} = &mt('No');
 3239:                         }
 3240:                     }
 3241:                 }
 3242:             }
 3243:         }
 3244:         return;
 3245:     }
 3246:     foreach my $tool (@{$usertools}) {
 3247:         my ($newval,$envkey);
 3248:         $envkey = $context.'.'.$tool;
 3249:         if ($context eq 'requestcourses') {
 3250:             $newval = $env{'form.crsreq_'.$tool};
 3251:             if ($newval eq 'autolimit') {
 3252:                 $newval .= '='.$env{'form.crsreq_'.$tool.'_limit'};
 3253:             }
 3254:         } elsif ($context eq 'requestauthor') {
 3255:             $newval = $env{'form.'.$context};
 3256:             $envkey = $context;
 3257:         } else {
 3258:             $newval = $env{'form.'.$context.'_'.$tool};
 3259:         }
 3260:         if ($userenv->{$envkey} ne '') {
 3261:             $oldaccess->{$tool} = &mt('custom');
 3262:             if ($userenv->{$envkey}) {
 3263:                 $oldaccesstext->{$tool} = &mt("availability set to 'on'");
 3264:             } else {
 3265:                 $oldaccesstext->{$tool} = &mt("availability set to 'off'");
 3266:             }
 3267:             $changeHash->{$envkey} = $userenv->{$envkey};
 3268:             if ($env{'form.custom'.$tool} == 1) {
 3269:                 if ($newval ne $userenv->{$envkey}) {
 3270:                     $changed->{$tool} = &tool_admin($tool,$newval,$changeHash,
 3271:                                                     $context);
 3272:                     if ($changed->{$tool}) {
 3273:                         $newaccess->{$tool} = &mt('custom');
 3274:                         if ($newval) {
 3275:                             $newaccesstext->{$tool} = &mt("availability set to 'on'");
 3276:                         } else {
 3277:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3278:                         }
 3279:                     } else {
 3280:                         $newaccess->{$tool} = $oldaccess->{$tool};
 3281:                         if ($userenv->{$context.'.'.$tool}) {
 3282:                             $newaccesstext->{$tool} = &mt("availability set to 'on'");
 3283:                         } else {
 3284:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3285:                         }
 3286:                     }
 3287:                 } else {
 3288:                     $newaccess->{$tool} = $oldaccess->{$tool};
 3289:                     $newaccesstext->{$tool} = $oldaccesstext->{$tool};
 3290:                 }
 3291:             } else {
 3292:                 $changed->{$tool} = &tool_admin($tool,'',$changeHash,$context);
 3293:                 if ($changed->{$tool}) {
 3294:                     $newaccess->{$tool} = &mt('default');
 3295:                 } else {
 3296:                     $newaccess->{$tool} = $oldaccess->{$tool};
 3297:                     if ($userenv->{$context.'.'.$tool}) {
 3298:                         $newaccesstext->{$tool} = &mt("availability set to 'on'");
 3299:                     } else {
 3300:                         $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3301:                     }
 3302:                 }
 3303:             }
 3304:         } else {
 3305:             $oldaccess->{$tool} = &mt('default');
 3306:             if ($env{'form.custom'.$tool} == 1) {
 3307:                 $changed->{$tool} = &tool_admin($tool,$newval,$changeHash,
 3308:                                                 $context);
 3309:                 if ($changed->{$tool}) {
 3310:                     $newaccess->{$tool} = &mt('custom');
 3311:                     if ($newval) {
 3312:                         $newaccesstext->{$tool} = &mt("availability set to 'on'");
 3313:                     } else {
 3314:                         $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3315:                     }
 3316:                 } else {
 3317:                     $newaccess->{$tool} = $oldaccess->{$tool};
 3318:                 }
 3319:             } else {
 3320:                 $newaccess->{$tool} = $oldaccess->{$tool};
 3321:             }
 3322:         }
 3323:     }
 3324:     return;
 3325: }
 3326: 
 3327: sub update_roles {
 3328:     my ($r,$context) = @_;
 3329:     my $now=time;
 3330:     my @rolechanges;
 3331:     my %disallowed;
 3332:     $r->print('<h3>'.&mt('Modifying Roles').'</h3>');
 3333:     foreach my $key (keys (%env)) {
 3334: 	next if (! $env{$key});
 3335:         next if ($key eq 'form.action');
 3336: 	# Revoke roles
 3337: 	if ($key=~/^form\.rev/) {
 3338: 	    if ($key=~/^form\.rev\:([^\_]+)\_([^\_\.]+)$/) {
 3339: # Revoke standard role
 3340: 		my ($scope,$role) = ($1,$2);
 3341: 		my $result =
 3342: 		    &Apache::lonnet::revokerole($env{'form.ccdomain'},
 3343: 						$env{'form.ccuname'},
 3344: 						$scope,$role,'','',$context);
 3345:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
 3346:                             &mt('Revoking [_1] in [_2]',
 3347:                                 &Apache::lonnet::plaintext($role),
 3348:                                 '"'.&cid_to_cname($scope).'"'),
 3349:                                 $result ne "ok").'<br />');
 3350:                 if ($result ne "ok") {
 3351:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 3352:                 }
 3353: 		if ($role eq 'st') {
 3354: 		    my $result = 
 3355:                         &Apache::lonuserutils::classlist_drop($scope,
 3356:                             $env{'form.ccuname'},$env{'form.ccdomain'},
 3357: 			    $now);
 3358:                     $r->print(&Apache::lonhtmlcommon::confirm_success($result));
 3359: 		}
 3360:                 if (!grep(/^\Q$role\E$/,@rolechanges)) {
 3361:                     push(@rolechanges,$role);
 3362:                 }
 3363: 	    }
 3364: 	    if ($key=~m{^form\.rev\:([^_]+)_cr\.cr/($match_domain)/($match_username)/(\w+)$}s) {
 3365: # Revoke custom role
 3366:                 my $result = &Apache::lonnet::revokecustomrole(
 3367:                     $env{'form.ccdomain'},$env{'form.ccuname'},$1,$2,$3,$4,'','',$context);
 3368:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
 3369:                             &mt('Revoking custom role [_1] by [_2] in [_3]',
 3370:                                 $4,$3.':'.$2,'"'.&cid_to_cname($1).'"'),
 3371:                             $result ne 'ok').'<br />');
 3372:                 if ($result ne "ok") {
 3373:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 3374:                 }
 3375:                 if (!grep(/^cr$/,@rolechanges)) {
 3376:                     push(@rolechanges,'cr');
 3377:                 }
 3378: 	    }
 3379: 	} elsif ($key=~/^form\.del/) {
 3380: 	    if ($key=~/^form\.del\:([^\_]+)\_([^\_\.]+)$/) {
 3381: # Delete standard role
 3382: 		my ($scope,$role) = ($1,$2);
 3383: 		my $result =
 3384: 		    &Apache::lonnet::assignrole($env{'form.ccdomain'},
 3385: 						$env{'form.ccuname'},
 3386: 						$scope,$role,$now,0,1,'',
 3387:                                                 $context);
 3388:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
 3389:                             &mt('Deleting [_1] in [_2]',
 3390:                                 &Apache::lonnet::plaintext($role),
 3391:                                 '"'.&cid_to_cname($scope).'"'),
 3392:                             $result ne 'ok').'<br />');
 3393:                 if ($result ne "ok") {
 3394:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 3395:                 }
 3396: 
 3397: 		if ($role eq 'st') {
 3398: 		    my $result = 
 3399:                         &Apache::lonuserutils::classlist_drop($scope,
 3400:                             $env{'form.ccuname'},$env{'form.ccdomain'},
 3401: 			    $now);
 3402: 		    $r->print(&Apache::lonhtmlcommon::confirm_success($result));
 3403: 		}
 3404:                 if (!grep(/^\Q$role\E$/,@rolechanges)) {
 3405:                     push(@rolechanges,$role);
 3406:                 }
 3407:             }
 3408: 	    if ($key=~m{^form\.del\:([^_]+)_cr\.cr/($match_domain)/($match_username)/(\w+)$}) {
 3409:                 my ($url,$rdom,$rnam,$rolename) = ($1,$2,$3,$4);
 3410: # Delete custom role
 3411:                 my $result =
 3412:                     &Apache::lonnet::assigncustomrole($env{'form.ccdomain'},
 3413:                         $env{'form.ccuname'},$url,$rdom,$rnam,$rolename,$now,
 3414:                         0,1,$context);
 3415:                 $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('Deleting custom role [_1] by [_2] in [_3]',
 3416:                       $rolename,$rnam.':'.$rdom,'"'.&cid_to_cname($1).'"'),
 3417:                       $result ne "ok").'<br />');
 3418:                 if ($result ne "ok") {
 3419:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 3420:                 }
 3421: 
 3422:                 if (!grep(/^cr$/,@rolechanges)) {
 3423:                     push(@rolechanges,'cr');
 3424:                 }
 3425:             }
 3426: 	} elsif ($key=~/^form\.ren/) {
 3427:             my $udom = $env{'form.ccdomain'};
 3428:             my $uname = $env{'form.ccuname'};
 3429: # Re-enable standard role
 3430: 	    if ($key=~/^form\.ren\:([^\_]+)\_([^\_\.]+)$/) {
 3431:                 my $url = $1;
 3432:                 my $role = $2;
 3433:                 my $logmsg;
 3434:                 my $output;
 3435:                 if ($role eq 'st') {
 3436:                     if ($url =~ m-^/($match_domain)/($match_courseid)/?(\w*)$-) {
 3437:                         my $result = &Apache::loncommon::commit_studentrole(\$logmsg,$udom,$uname,$url,$role,$now,0,$1,$2,$3);
 3438:                         if (($result =~ /^error/) || ($result eq 'not_in_class') || ($result eq 'unknown_course') || ($result eq 'refused')) {
 3439:                             if ($result eq 'refused' && $logmsg) {
 3440:                                 $output = $logmsg;
 3441:                             } else { 
 3442:                                 $output = &mt('Error: [_1]',$result)."\n";
 3443:                             }
 3444:                         } else {
 3445:                             $output = &Apache::lonhtmlcommon::confirm_success(&mt('Assigning [_1] in [_2] starting [_3]',&Apache::lonnet::plaintext($role),
 3446:                                         '"'.&cid_to_cname($url).'"',&Apache::lonlocal::locallocaltime($now))).'<br />'.$logmsg.'<br />';
 3447:                         }
 3448:                     }
 3449:                 } else {
 3450: 		    my $result=&Apache::lonnet::assignrole($env{'form.ccdomain'},
 3451:                                $env{'form.ccuname'},$url,$role,0,$now,'','',
 3452:                                $context);
 3453:                         $output = &Apache::lonhtmlcommon::confirm_success(&mt('Re-enabling [_1] in [_2]',
 3454:                                         &Apache::lonnet::plaintext($role),'"'.&cid_to_cname($url).'"'),$result ne "ok").'<br />';
 3455:                     if ($result ne "ok") {
 3456:                         $output .= &mt('Error: [_1]',$result).'<br />';
 3457:                     }
 3458:                 }
 3459:                 $r->print($output);
 3460:                 if (!grep(/^\Q$role\E$/,@rolechanges)) {
 3461:                     push(@rolechanges,$role);
 3462:                 }
 3463: 	    }
 3464: # Re-enable custom role
 3465: 	    if ($key=~m{^form\.ren\:([^_]+)_cr\.cr/($match_domain)/($match_username)/(\w+)$}) {
 3466:                 my ($url,$rdom,$rnam,$rolename) = ($1,$2,$3,$4);
 3467:                 my $result = &Apache::lonnet::assigncustomrole(
 3468:                                $env{'form.ccdomain'}, $env{'form.ccuname'},
 3469:                                $url,$rdom,$rnam,$rolename,0,$now,undef,$context);
 3470:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
 3471:                     &mt('Re-enabling custom role [_1] by [_2] in [_3]',
 3472:                         $rolename,$rnam.':'.$rdom,'"'.&cid_to_cname($1).'"'),
 3473:                     $result ne "ok").'<br />');
 3474:                 if ($result ne "ok") {
 3475:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 3476:                 }
 3477:                 if (!grep(/^cr$/,@rolechanges)) {
 3478:                     push(@rolechanges,'cr');
 3479:                 }
 3480:             }
 3481: 	} elsif ($key=~/^form\.act/) {
 3482:             my $udom = $env{'form.ccdomain'};
 3483:             my $uname = $env{'form.ccuname'};
 3484: 	    if ($key=~/^form\.act\_($match_domain)\_($match_courseid)\_cr_cr_($match_domain)_($match_username)_([^\_]+)$/) {
 3485:                 # Activate a custom role
 3486: 		my ($one,$two,$three,$four,$five)=($1,$2,$3,$4,$5);
 3487: 		my $url='/'.$one.'/'.$two;
 3488: 		my $full=$one.'_'.$two.'_cr_cr_'.$three.'_'.$four.'_'.$five;
 3489: 
 3490:                 my $start = ( $env{'form.start_'.$full} ?
 3491:                               $env{'form.start_'.$full} :
 3492:                               $now );
 3493:                 my $end   = ( $env{'form.end_'.$full} ?
 3494:                               $env{'form.end_'.$full} :
 3495:                               0 );
 3496:                                                                                      
 3497:                 # split multiple sections
 3498:                 my %sections = ();
 3499:                 my $num_sections = &build_roles($env{'form.sec_'.$full},\%sections,$5);
 3500:                 if ($num_sections == 0) {
 3501:                     $r->print(&Apache::loncommon::commit_customrole($udom,$uname,$url,$three,$four,$five,$start,$end,$context));
 3502:                 } else {
 3503: 		    my %curr_groups =
 3504: 			&Apache::longroup::coursegroups($one,$two);
 3505:                     foreach my $sec (sort {$a cmp $b} keys %sections) {
 3506:                         if (($sec eq 'none') || ($sec eq 'all') || 
 3507:                             exists($curr_groups{$sec})) {
 3508:                             $disallowed{$sec} = $url;
 3509:                             next;
 3510:                         }
 3511:                         my $securl = $url.'/'.$sec;
 3512: 		        $r->print(&Apache::loncommon::commit_customrole($udom,$uname,$securl,$three,$four,$five,$start,$end,$context));
 3513:                     }
 3514:                 }
 3515:                 if (!grep(/^cr$/,@rolechanges)) {
 3516:                     push(@rolechanges,'cr');
 3517:                 }
 3518: 	    } elsif ($key=~/^form\.act\_($match_domain)\_($match_name)\_([^\_]+)$/) {
 3519: 		# Activate roles for sections with 3 id numbers
 3520: 		# set start, end times, and the url for the class
 3521: 		my ($one,$two,$three)=($1,$2,$3);
 3522: 		my $start = ( $env{'form.start_'.$one.'_'.$two.'_'.$three} ? 
 3523: 			      $env{'form.start_'.$one.'_'.$two.'_'.$three} : 
 3524: 			      $now );
 3525: 		my $end   = ( $env{'form.end_'.$one.'_'.$two.'_'.$three} ? 
 3526: 			      $env{'form.end_'.$one.'_'.$two.'_'.$three} :
 3527: 			      0 );
 3528: 		my $url='/'.$one.'/'.$two;
 3529:                 my $type = 'three';
 3530:                 # split multiple sections
 3531:                 my %sections = ();
 3532:                 my $num_sections = &build_roles($env{'form.sec_'.$one.'_'.$two.'_'.$three},\%sections,$three);
 3533:                 if ($num_sections == 0) {
 3534:                     $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$three,$start,$end,$one,$two,'',$context));
 3535:                 } else {
 3536:                     my %curr_groups = 
 3537: 			&Apache::longroup::coursegroups($one,$two);
 3538:                     my $emptysec = 0;
 3539:                     foreach my $sec (sort {$a cmp $b} keys %sections) {
 3540:                         $sec =~ s/\W//g;
 3541:                         if ($sec ne '') {
 3542:                             if (($sec eq 'none') || ($sec eq 'all') || 
 3543:                                 exists($curr_groups{$sec})) {
 3544:                                 $disallowed{$sec} = $url;
 3545:                                 next;
 3546:                             }
 3547:                             my $securl = $url.'/'.$sec;
 3548:                             $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$securl,$three,$start,$end,$one,$two,$sec,$context));
 3549:                         } else {
 3550:                             $emptysec = 1;
 3551:                         }
 3552:                     }
 3553:                     if ($emptysec) {
 3554:                         $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$three,$start,$end,$one,$two,'',$context));
 3555:                     }
 3556:                 }
 3557:                 if (!grep(/^\Q$three\E$/,@rolechanges)) {
 3558:                     push(@rolechanges,$three);
 3559:                 }
 3560: 	    } elsif ($key=~/^form\.act\_([^\_]+)\_([^\_]+)$/) {
 3561: 		# Activate roles for sections with two id numbers
 3562: 		# set start, end times, and the url for the class
 3563: 		my $start = ( $env{'form.start_'.$1.'_'.$2} ? 
 3564: 			      $env{'form.start_'.$1.'_'.$2} : 
 3565: 			      $now );
 3566: 		my $end   = ( $env{'form.end_'.$1.'_'.$2} ? 
 3567: 			      $env{'form.end_'.$1.'_'.$2} :
 3568: 			      0 );
 3569:                 my $one = $1;
 3570:                 my $two = $2;
 3571: 		my $url='/'.$one.'/';
 3572:                 # split multiple sections
 3573:                 my %sections = ();
 3574:                 my $num_sections = &build_roles($env{'form.sec_'.$one.'_'.$two},\%sections,$two);
 3575:                 if ($num_sections == 0) {
 3576:                     $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$two,$start,$end,$one,undef,'',$context));
 3577:                 } else {
 3578:                     my $emptysec = 0;
 3579:                     foreach my $sec (sort {$a cmp $b} keys %sections) {
 3580:                         if ($sec ne '') {
 3581:                             my $securl = $url.'/'.$sec;
 3582:                             $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$securl,$two,$start,$end,$one,undef,$sec,$context));
 3583:                         } else {
 3584:                             $emptysec = 1;
 3585:                         }
 3586:                     }
 3587:                     if ($emptysec) {
 3588:                         $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$two,$start,$end,$one,undef,'',$context));
 3589:                     }
 3590:                 }
 3591:                 if (!grep(/^\Q$two\E$/,@rolechanges)) {
 3592:                     push(@rolechanges,$two);
 3593:                 }
 3594: 	    } else {
 3595: 		$r->print('<p><span class="LC_error">'.&mt('ERROR').': '.&mt('Unknown command').' <tt>'.$key.'</tt></span></p><br />');
 3596:             }
 3597:             foreach my $key (sort(keys(%disallowed))) {
 3598:                 $r->print('<p class="LC_warning">');
 3599:                 if (($key eq 'none') || ($key eq 'all')) {  
 3600:                     $r->print(&mt('[_1] may not be used as the name for a section, as it is a reserved word.','<tt>'.$key.'</tt>'));
 3601:                 } else {
 3602:                     $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>'));
 3603:                 }
 3604:                 $r->print('</p><p>'
 3605:                          .&mt('Please [_1]go back[_2] and choose a different section name.'
 3606:                              ,'<a href="javascript:history.go(-1)'
 3607:                              ,'</a>')
 3608:                          .'</p><br />'
 3609:                 );
 3610:             }
 3611: 	}
 3612:     } # End of foreach (keys(%env))
 3613: # Flush the course logs so reverse user roles immediately updated
 3614:     $r->register_cleanup(\&Apache::lonnet::flushcourselogs);
 3615:     if (@rolechanges == 0) {
 3616:         $r->print(&mt('No roles to modify'));
 3617:     }
 3618:     return @rolechanges;
 3619: }
 3620: 
 3621: sub enroll_single_student {
 3622:     my ($r,$uhome,$amode,$genpwd,$now,$newuser,$context,$crstype) = @_;
 3623:     $r->print('<h3>');
 3624:     if ($crstype eq 'Community') {
 3625:         $r->print(&mt('Enrolling Member'));
 3626:     } else {
 3627:         $r->print(&mt('Enrolling Student'));
 3628:     }
 3629:     $r->print('</h3>');
 3630: 
 3631:     # Remove non alphanumeric values from section
 3632:     $env{'form.sections'}=~s/\W//g;
 3633: 
 3634:     # Clean out any old student roles the user has in this class.
 3635:     &Apache::lonuserutils::modifystudent($env{'form.ccdomain'},
 3636:          $env{'form.ccuname'},$env{'request.course.id'},undef,$uhome);
 3637:     my ($startdate,$enddate) = &Apache::lonuserutils::get_dates_from_form();
 3638:     my $enroll_result =
 3639:         &Apache::lonnet::modify_student_enrollment($env{'form.ccdomain'},
 3640:             $env{'form.ccuname'},$env{'form.cid'},$env{'form.cfirstname'},
 3641:             $env{'form.cmiddlename'},$env{'form.clastname'},
 3642:             $env{'form.generation'},$env{'form.sections'},$enddate,
 3643:             $startdate,'manual',undef,$env{'request.course.id'},'',$context);
 3644:     if ($enroll_result =~ /^ok/) {
 3645:         $r->print(&mt('<b>[_1]</b> enrolled',$env{'form.ccuname'}.':'.$env{'form.ccdomain'}));
 3646:         if ($env{'form.sections'} ne '') {
 3647:             $r->print(' '.&mt('in section [_1]',$env{'form.sections'}));
 3648:         }
 3649:         my ($showstart,$showend);
 3650:         if ($startdate <= $now) {
 3651:             $showstart = &mt('Access starts immediately');
 3652:         } else {
 3653:             $showstart = &mt('Access starts: ').&Apache::lonlocal::locallocaltime($startdate);
 3654:         }
 3655:         if ($enddate == 0) {
 3656:             $showend = &mt('ends: no ending date');
 3657:         } else {
 3658:             $showend = &mt('ends: ').&Apache::lonlocal::locallocaltime($enddate);
 3659:         }
 3660:         $r->print('.<br />'.$showstart.'; '.$showend);
 3661:         if ($startdate <= $now && !$newuser) {
 3662:             $r->print('<p> ');
 3663:             if ($crstype eq 'Community') {
 3664:                 $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.'));
 3665:             } else {
 3666:                 $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.'));
 3667:            }
 3668:            $r->print('</p>');
 3669:         }
 3670:     } else {
 3671:         $r->print(&mt('unable to enroll').": ".$enroll_result);
 3672:     }
 3673:     return;
 3674: }
 3675: 
 3676: sub get_defaultquota_text {
 3677:     my ($settingstatus) = @_;
 3678:     my $defquotatext; 
 3679:     if ($settingstatus eq '') {
 3680:         $defquotatext = &mt('(default)');
 3681:     } else {
 3682:         my ($usertypes,$order) =
 3683:             &Apache::lonnet::retrieve_inst_usertypes($env{'form.ccdomain'});
 3684:         if ($usertypes->{$settingstatus} eq '') {
 3685:             $defquotatext = &mt('(default)');
 3686:         } else {
 3687:             $defquotatext = &mt('(default for [_1])',$usertypes->{$settingstatus});
 3688:         }
 3689:     }
 3690:     return $defquotatext;
 3691: }
 3692: 
 3693: sub update_result_form {
 3694:     my ($uhome) = @_;
 3695:     my $outcome = 
 3696:     '<form name="userupdate" method="post" action="">'."\n";
 3697:     foreach my $item ('srchby','srchin','srchtype','srchterm','srchdomain','ccuname','ccdomain') {
 3698:         $outcome .= '<input type="hidden" name="'.$item.'" value="'.$env{'form.'.$item}.'" />'."\n";
 3699:     }
 3700:     if ($env{'form.origname'} ne '') {
 3701:         $outcome .= '<input type="hidden" name="origname" value="'.$env{'form.origname'}.'" />'."\n";
 3702:     }
 3703:     foreach my $item ('sortby','seluname','seludom') {
 3704:         if (exists($env{'form.'.$item})) {
 3705:             $outcome .= '<input type="hidden" name="'.$item.'" value="'.$env{'form.'.$item}.'" />'."\n";
 3706:         }
 3707:     }
 3708:     if ($uhome eq 'no_host') {
 3709:         $outcome .= '<input type="hidden" name="forcenewuser" value="1" />'."\n";
 3710:     }
 3711:     $outcome .= '<input type="hidden" name="phase" value="" />'."\n".
 3712:                 '<input type ="hidden" name="currstate" value="" />'."\n".
 3713:                 '<input type ="hidden" name="action" value="'.$env{'form.action'}.'" />'."\n".
 3714:                 '</form>';
 3715:     return $outcome;
 3716: }
 3717: 
 3718: sub quota_admin {
 3719:     my ($setquota,$changeHash) = @_;
 3720:     my $quotachanged;
 3721:     if (&Apache::lonnet::allowed('mpq',$env{'form.ccdomain'})) {
 3722:         # Current user has quota modification privileges
 3723:         if (ref($changeHash) eq 'HASH') {
 3724:             $quotachanged = 1;
 3725:             $changeHash->{'portfolioquota'} = $setquota;
 3726:         }
 3727:     }
 3728:     return $quotachanged;
 3729: }
 3730: 
 3731: sub tool_admin {
 3732:     my ($tool,$settool,$changeHash,$context) = @_;
 3733:     my $canchange = 0; 
 3734:     if ($context eq 'requestcourses') {
 3735:         if (&Apache::lonnet::allowed('ccc',$env{'form.ccdomain'})) {
 3736:             $canchange = 1;
 3737:         }
 3738:     } elsif ($context eq 'reqcrsotherdom') {
 3739:         if (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) {
 3740:             $canchange = 1;
 3741:         }
 3742:     } elsif ($context eq 'requestauthor') {
 3743:         if (&Apache::lonnet::allowed('cau',$env{'request.role.domain'})) {
 3744:             $canchange = 1;
 3745:         }
 3746:     } elsif (&Apache::lonnet::allowed('mut',$env{'form.ccdomain'})) {
 3747:         # Current user has quota modification privileges
 3748:         $canchange = 1;
 3749:     }
 3750:     my $toolchanged;
 3751:     if ($canchange) {
 3752:         if (ref($changeHash) eq 'HASH') {
 3753:             $toolchanged = 1;
 3754:             if ($tool eq 'requestauthor') {
 3755:                 $changeHash->{$context} = $settool;
 3756:             } else {
 3757:                 $changeHash->{$context.'.'.$tool} = $settool;
 3758:             }
 3759:         }
 3760:     }
 3761:     return $toolchanged;
 3762: }
 3763: 
 3764: sub build_roles {
 3765:     my ($sectionstr,$sections,$role) = @_;
 3766:     my $num_sections = 0;
 3767:     if ($sectionstr=~ /,/) {
 3768:         my @secnums = split/,/,$sectionstr;
 3769:         if ($role eq 'st') {
 3770:             $secnums[0] =~ s/\W//g;
 3771:             $$sections{$secnums[0]} = 1;
 3772:             $num_sections = 1;
 3773:         } else {
 3774:             foreach my $sec (@secnums) {
 3775:                 $sec =~ ~s/\W//g;
 3776:                 if (!($sec eq "")) {
 3777:                     if (exists($$sections{$sec})) {
 3778:                         $$sections{$sec} ++;
 3779:                     } else {
 3780:                         $$sections{$sec} = 1;
 3781:                         $num_sections ++;
 3782:                     }
 3783:                 }
 3784:             }
 3785:         }
 3786:     } else {
 3787:         $sectionstr=~s/\W//g;
 3788:         unless ($sectionstr eq '') {
 3789:             $$sections{$sectionstr} = 1;
 3790:             $num_sections ++;
 3791:         }
 3792:     }
 3793: 
 3794:     return $num_sections;
 3795: }
 3796: 
 3797: # ========================================================== Custom Role Editor
 3798: 
 3799: sub custom_role_editor {
 3800:     my ($r,$brcrum) = @_;
 3801:     my $action = $env{'form.customroleaction'};
 3802:     my $rolename; 
 3803:     if ($action eq 'new') {
 3804:         $rolename=$env{'form.newrolename'};
 3805:     } else {
 3806:         $rolename=$env{'form.rolename'};
 3807:     }
 3808: 
 3809:     my ($crstype,$context);
 3810:     if ($env{'request.course.id'}) {
 3811:         $crstype = &Apache::loncommon::course_type();
 3812:         $context = 'course';
 3813:     } else {
 3814:         $context = 'domain';
 3815:         $crstype = $env{'form.templatecrstype'};
 3816:     }
 3817: 
 3818:     $rolename=~s/[^A-Za-z0-9]//gs;
 3819:     if (!$rolename || $env{'form.phase'} eq 'pickrole') {
 3820: 	&print_username_entry_form($r,undef,undef,undef,undef,$crstype,$brcrum);
 3821:         return;
 3822:     }
 3823: 
 3824: # ------------------------------------------------------- What can be assigned?
 3825:     my %full=();
 3826:     my %courselevel=();
 3827:     my %courselevelcurrent=();
 3828:     my $syspriv='';
 3829:     my $dompriv='';
 3830:     my $coursepriv='';
 3831:     my $body_top;
 3832:     my ($rdummy,$roledef)=
 3833: 			 &Apache::lonnet::get('roles',["rolesdef_$rolename"]);
 3834: # ------------------------------------------------------- Does this role exist?
 3835:     $body_top .= '<h2>';
 3836:     if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 3837: 	$body_top .= &mt('Existing Role').' "';
 3838: # ------------------------------------------------- Get current role privileges
 3839: 	($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 3840:         if ($crstype eq 'Community') {
 3841:             $syspriv =~ s/bre\&S//;   
 3842:         }
 3843:     } else {
 3844: 	$body_top .= &mt('New Role').' "';
 3845: 	$roledef='';
 3846:     }
 3847:     $body_top .= $rolename.'"</h2>';
 3848:     foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
 3849: 	my ($priv,$restrict)=split(/\&/,$item);
 3850:         if (!$restrict) { $restrict='F'; }
 3851:         $courselevel{$priv}=$restrict;
 3852:         if ($coursepriv=~/\:$priv/) {
 3853: 	    $courselevelcurrent{$priv}=1;
 3854: 	}
 3855: 	$full{$priv}=1;
 3856:     }
 3857:     my %domainlevel=();
 3858:     my %domainlevelcurrent=();
 3859:     foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:d'})) {
 3860: 	my ($priv,$restrict)=split(/\&/,$item);
 3861:         if (!$restrict) { $restrict='F'; }
 3862:         $domainlevel{$priv}=$restrict;
 3863:         if ($dompriv=~/\:$priv/) {
 3864: 	    $domainlevelcurrent{$priv}=1;
 3865: 	}
 3866: 	$full{$priv}=1;
 3867:     }
 3868:     my %systemlevel=();
 3869:     my %systemlevelcurrent=();
 3870:     foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:s'})) {
 3871: 	my ($priv,$restrict)=split(/\&/,$item);
 3872:         if (!$restrict) { $restrict='F'; }
 3873:         $systemlevel{$priv}=$restrict;
 3874:         if ($syspriv=~/\:$priv/) {
 3875: 	    $systemlevelcurrent{$priv}=1;
 3876: 	}
 3877: 	$full{$priv}=1;
 3878:     }
 3879:     my ($jsback,$elements) = &crumb_utilities();
 3880:     my $button_code = "\n";
 3881:     my $head_script = "\n";
 3882:     $head_script .= '<script type="text/javascript">'."\n"
 3883:                    .'// <![CDATA['."\n";
 3884:     my @template_roles = ("in","ta","ep");
 3885:     if ($context eq 'domain') {
 3886:         push(@template_roles,"ad");
 3887:     }
 3888:     push(@template_roles,"st");
 3889:     if ($crstype eq 'Community') {
 3890:         unshift(@template_roles,'co');
 3891:     } else {
 3892:         unshift(@template_roles,'cc');
 3893:     }
 3894:     foreach my $role (@template_roles) {
 3895:         $head_script .= &make_script_template($role,$crstype);
 3896:         $button_code .= &make_button_code($role,$crstype).' ';
 3897:     }
 3898:     my $context_code;
 3899:     if ($context eq 'domain') {
 3900:         my $checkedCommunity = '';
 3901:         my $checkedCourse = ' checked="checked"';
 3902:         if ($env{'form.templatecrstype'} eq 'Community') {
 3903:             $checkedCommunity = $checkedCourse;
 3904:             $checkedCourse = '';
 3905:         }
 3906:         $context_code = '<label>'.
 3907:                         '<input type="radio" name="templatecrstype" value="Course"'.$checkedCourse.' onclick="this.form.submit();">'.
 3908:                         &mt('Course').
 3909:                         '</label>'.('&nbsp;' x2).
 3910:                         '<label>'.
 3911:                         '<input type="radio" name="templatecrstype" value="Community"'.$checkedCommunity.' onclick="this.form.submit();">'.
 3912:                         &mt('Community').
 3913:                         '</label>'.
 3914:                         '</fieldset>'.
 3915:                         '<input type="hidden" name="customroleaction" value="'.
 3916:                         $action.'" />';
 3917:         if ($env{'form.customroleaction'} eq 'new') {
 3918:             $context_code .= '<input type="hidden" name="newrolename" value="'.
 3919:                              $rolename.'" />';
 3920:         } else {
 3921:             $context_code .= '<input type="hidden" name="rolename" value="'.
 3922:                              $rolename.'" />';
 3923:         }
 3924:         $context_code .= '<input type="hidden" name="action" value="custom" />'.
 3925:                          '<input type="hidden" name="phase" value="selected_custom_edit" />';
 3926:     }
 3927: 
 3928:     $head_script .= "\n".$jsback."\n"
 3929:                    .'// ]]>'."\n"
 3930:                    .'</script>'."\n";
 3931:     push (@{$brcrum},
 3932:               {href => "javascript:backPage(document.form1,'pickrole','')",
 3933:                text => "Pick custom role",
 3934:                faq  => 282,bug=>'Instructor Interface',},
 3935:               {href => "javascript:backPage(document.form1,'','')",
 3936:                text => "Edit custom role",
 3937:                faq  => 282,
 3938:                bug  => 'Instructor Interface',
 3939:                help => 'Course_Editing_Custom_Roles'}
 3940:               );
 3941:     my $args = { bread_crumbs          => $brcrum,
 3942:                  bread_crumbs_component => 'User Management'};
 3943:  
 3944:     $r->print(&Apache::loncommon::start_page('Custom Role Editor',
 3945:                                              $head_script,$args).
 3946:               $body_top);
 3947:     my %lt=&Apache::lonlocal::texthash(
 3948: 		    'prv'  => "Privilege",
 3949: 		    'crl'  => "Course Level",
 3950:                     'dml'  => "Domain Level",
 3951:                     'ssl'  => "System Level");
 3952: 
 3953:     $r->print('<div class="LC_left_float">'
 3954:              .'<form action=""><fieldset>'
 3955:              .'<legend>'.&mt('Select a Template').'</legend>'
 3956:              .$button_code
 3957:              .'</fieldset></form></div>');
 3958:     if ($context_code) {
 3959:         $r->print('<div class="LC_left_float">'
 3960:                  .'<form action="/adm/createuser" method="post"><fieldset>'
 3961:                  .'<legend>'.&mt('Context').'</legend>'
 3962:                  .$context_code
 3963:                  .'</form>'
 3964:                  .'</div>'
 3965:         );
 3966:     }
 3967:     $r->print('<br clear="all" />');
 3968: 
 3969:     $r->print(<<ENDCCF);
 3970: <form name="form1" method="post">
 3971: <input type="hidden" name="phase" value="set_custom_roles" />
 3972: <input type="hidden" name="rolename" value="$rolename" />
 3973: ENDCCF
 3974:     $r->print(&Apache::loncommon::start_data_table().
 3975:               &Apache::loncommon::start_data_table_header_row(). 
 3976: '<th>'.$lt{'prv'}.'</th><th>'.$lt{'crl'}.'</th><th>'.$lt{'dml'}.
 3977: '</th><th>'.$lt{'ssl'}.'</th>'.
 3978:               &Apache::loncommon::end_data_table_header_row());
 3979:     foreach my $priv (sort(keys(%full))) {
 3980:         my $privtext = &Apache::lonnet::plaintext($priv,$crstype);
 3981:         $r->print(&Apache::loncommon::start_data_table_row().
 3982: 	          '<td>'.$privtext.'</td><td>'.
 3983:     ($courselevel{$priv}?'<input type="checkbox" name="'.$priv.'_c"'.
 3984:     ($courselevelcurrent{$priv}?' checked="checked"':'').' />':'&nbsp;').
 3985:     '</td><td>'.
 3986:     ($domainlevel{$priv}?'<input type="checkbox" name="'.$priv.'_d"'.
 3987:     ($domainlevelcurrent{$priv}?' checked="checked"':'').' />':'&nbsp;').
 3988:     '</td><td>');
 3989:         if ($priv eq 'bre' && $crstype eq 'Community') {
 3990:             $r->print('&nbsp;');  
 3991:         } else {
 3992:             $r->print($systemlevel{$priv}?'<input type="checkbox" name="'.$priv.'_s"'.
 3993:                       ($systemlevelcurrent{$priv}?' checked="checked"':'').' />':'&nbsp;');
 3994:         }
 3995:         $r->print('</td>'.
 3996:                   &Apache::loncommon::end_data_table_row());
 3997:     }
 3998:     $r->print(&Apache::loncommon::end_data_table().
 3999:    '<input type="hidden" name="action" value="'.$env{'form.action'}.'" />'.
 4000:    '<input type="hidden" name="startrolename" value="'.$env{'form.rolename'}.
 4001:    '" />'."\n".'<input type="hidden" name="currstate" value="" />'."\n".   
 4002:    '<input type="reset" value="'.&mt("Reset").'" />'."\n".
 4003:    '<input type="submit" value="'.&mt('Save').'" /></form>');
 4004: }
 4005: # --------------------------------------------------------
 4006: sub make_script_template {
 4007:     my ($role,$crstype) = @_;
 4008:     my %full_c=();
 4009:     my %full_d=();
 4010:     my %full_s=();
 4011:     my $return_script;
 4012:     foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
 4013:         my ($priv,$restrict)=split(/\&/,$item);
 4014:         $full_c{$priv}=1;
 4015:     }
 4016:     foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:d'})) {
 4017:         my ($priv,$restrict)=split(/\&/,$item);
 4018:         $full_d{$priv}=1;
 4019:     }
 4020:     foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:s'})) {
 4021:         next if (($crstype eq 'Community') && ($item eq 'bre&S'));
 4022:         my ($priv,$restrict)=split(/\&/,$item);
 4023:         $full_s{$priv}=1;
 4024:     }
 4025:     $return_script .= 'function set_'.$role.'() {'."\n";
 4026:     my @temp = split(/:/,$Apache::lonnet::pr{$role.':c'});
 4027:     my %role_c;
 4028:     foreach my $priv (@temp) {
 4029:         my ($priv_item, $dummy) = split(/\&/,$priv);
 4030:         $role_c{$priv_item} = 1;
 4031:     }
 4032:     my %role_d;
 4033:     @temp = split(/:/,$Apache::lonnet::pr{$role.':d'});
 4034:     foreach my $priv(@temp) {
 4035:         my ($priv_item, $dummy) = split(/\&/,$priv);
 4036:         $role_d{$priv_item} = 1;
 4037:     }
 4038:     my %role_s;
 4039:     @temp = split(/:/,$Apache::lonnet::pr{$role.':s'});
 4040:     foreach my $priv(@temp) {
 4041:         my ($priv_item, $dummy) = split(/\&/,$priv);
 4042:         $role_s{$priv_item} = 1;
 4043:     }
 4044:     foreach my $priv_item (keys(%full_c)) {
 4045:         my ($priv, $dummy) = split(/\&/,$priv_item);
 4046:         if ((exists($role_c{$priv})) || (exists($role_d{$priv})) || 
 4047:             (exists($role_s{$priv}))) {
 4048:             $return_script .= "document.form1.$priv"."_c.checked = true;\n";
 4049:         } else {
 4050:             $return_script .= "document.form1.$priv"."_c.checked = false;\n";
 4051:         }
 4052:     }
 4053:     foreach my $priv_item (keys(%full_d)) {
 4054:         my ($priv, $dummy) = split(/\&/,$priv_item);
 4055:         if ((exists($role_d{$priv})) || (exists($role_s{$priv}))) {
 4056:             $return_script .= "document.form1.$priv"."_d.checked = true;\n";
 4057:         } else {
 4058:             $return_script .= "document.form1.$priv"."_d.checked = false;\n";
 4059:         }
 4060:     }
 4061:     foreach my $priv_item (keys(%full_s)) {
 4062:         my ($priv, $dummy) = split(/\&/,$priv_item);
 4063:         if (exists($role_s{$priv})) {
 4064:             $return_script .= "document.form1.$priv"."_s.checked = true;\n";
 4065:         } else {
 4066:             $return_script .= "document.form1.$priv"."_s.checked = false;\n";
 4067:         }
 4068:     }
 4069:     $return_script .= '}'."\n";
 4070:     return ($return_script);
 4071: }
 4072: # ----------------------------------------------------------
 4073: sub make_button_code {
 4074:     my ($role,$crstype) = @_;
 4075:     my $label = &Apache::lonnet::plaintext($role,$crstype);
 4076:     my $button_code = '<input type="button" onclick="set_'.$role.'()" value="'.$label.'" />';
 4077:     return ($button_code);
 4078: }
 4079: # ---------------------------------------------------------- Call to definerole
 4080: sub set_custom_role {
 4081:     my ($r,$context,$brcrum) = @_;
 4082:     my $rolename=$env{'form.rolename'};
 4083:     $rolename=~s/[^A-Za-z0-9]//gs;
 4084:     if (!$rolename) {
 4085: 	&custom_role_editor($r,$brcrum);
 4086:         return;
 4087:     }
 4088:     my ($jsback,$elements) = &crumb_utilities();
 4089:     my $jscript = '<script type="text/javascript">'
 4090:                  .'// <![CDATA['."\n"
 4091:                  .$jsback."\n"
 4092:                  .'// ]]>'."\n"
 4093:                  .'</script>'."\n";
 4094:     push(@{$brcrum},
 4095:         {href => "javascript:backPage(document.customresult,'pickrole','')",
 4096:          text => "Pick custom role",
 4097:          faq  => 282,
 4098:          bug  => 'Instructor Interface',},
 4099:         {href => "javascript:backPage(document.customresult,'selected_custom_edit','')",
 4100:          text => "Edit custom role",
 4101:          faq  => 282,
 4102:          bug  => 'Instructor Interface',},
 4103:         {href => "javascript:backPage(document.customresult,'set_custom_roles','')",
 4104:          text => "Result",
 4105:          faq  => 282,
 4106:          bug  => 'Instructor Interface',
 4107:          help => 'Course_Editing_Custom_Roles'},
 4108:         );
 4109:     my $args = { bread_crumbs           => $brcrum,
 4110:                  bread_crumbs_component => 'User Management'}; 
 4111:     $r->print(&Apache::loncommon::start_page('Save Custom Role',$jscript,$args));
 4112: 
 4113:     my ($rdummy,$roledef)=
 4114: 	&Apache::lonnet::get('roles',["rolesdef_$rolename"]);
 4115: 
 4116: # ------------------------------------------------------- Does this role exist?
 4117:     $r->print('<h3>');
 4118:     if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 4119: 	$r->print(&mt('Existing Role').' "');
 4120:     } else {
 4121: 	$r->print(&mt('New Role').' "');
 4122: 	$roledef='';
 4123:     }
 4124:     $r->print($rolename.'"</h3>');
 4125: # ------------------------------------------------------- What can be assigned?
 4126:     my $sysrole='';
 4127:     my $domrole='';
 4128:     my $courole='';
 4129: 
 4130:     foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
 4131: 	my ($priv,$restrict)=split(/\&/,$item);
 4132:         if (!$restrict) { $restrict=''; }
 4133:         if ($env{'form.'.$priv.'_c'}) {
 4134: 	    $courole.=':'.$item;
 4135: 	}
 4136:     }
 4137: 
 4138:     foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:d'})) {
 4139: 	my ($priv,$restrict)=split(/\&/,$item);
 4140:         if (!$restrict) { $restrict=''; }
 4141:         if ($env{'form.'.$priv.'_d'}) {
 4142: 	    $domrole.=':'.$item;
 4143: 	}
 4144:     }
 4145: 
 4146:     foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:s'})) {
 4147: 	my ($priv,$restrict)=split(/\&/,$item);
 4148:         if (!$restrict) { $restrict=''; }
 4149:         if ($env{'form.'.$priv.'_s'}) {
 4150: 	    $sysrole.=':'.$item;
 4151: 	}
 4152:     }
 4153:     $r->print('<br />Defining Role: '.
 4154: 	   &Apache::lonnet::definerole($rolename,$sysrole,$domrole,$courole));
 4155:     if ($env{'request.course.id'}) {
 4156:         my $url='/'.$env{'request.course.id'};
 4157:         $url=~s/\_/\//g;
 4158: 	$r->print('<br />'.&mt('Assigning Role to Self').': '.
 4159: 	      &Apache::lonnet::assigncustomrole($env{'user.domain'},
 4160: 						$env{'user.name'},
 4161: 						$url,
 4162: 						$env{'user.domain'},
 4163: 						$env{'user.name'},
 4164: 						$rolename,undef,undef,undef,$context));
 4165:     }
 4166:     $r->print('<p><a href="javascript:backPage(document.customresult,'."'pickrole'".')">'.&mt('Create or edit another custom role').'</a></p><form name="customresult" method="post">');
 4167:     $r->print(&Apache::lonhtmlcommon::echo_form_input([]).'</form>');
 4168: }
 4169: 
 4170: # ================================================================ Main Handler
 4171: sub handler {
 4172:     my $r = shift;
 4173:     if ($r->header_only) {
 4174:        &Apache::loncommon::content_type($r,'text/html');
 4175:        $r->send_http_header;
 4176:        return OK;
 4177:     }
 4178:     my ($context,$crstype);
 4179:     if ($env{'request.course.id'}) {
 4180:         $context = 'course';
 4181:         $crstype = &Apache::loncommon::course_type();
 4182:     } elsif ($env{'request.role'} =~ /^au\./) {
 4183:         $context = 'author';
 4184:     } else {
 4185:         $context = 'domain';
 4186:     }
 4187:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 4188:         ['action','state','callingform','roletype','showrole','bulkaction','popup','phase',
 4189:          'username','domain','srchterm','srchdomain','srchin','srchby','srchtype']);
 4190:     &Apache::lonhtmlcommon::clear_breadcrumbs();
 4191:     my $args;
 4192:     my $brcrum = [];
 4193:     my $bread_crumbs_component = 'User Management';
 4194:     if ($env{'form.action'} ne 'dateselect') {
 4195:         $brcrum = [{href=>"/adm/createuser",
 4196:                     text=>"User Management",
 4197:                     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'}
 4198:                   ];
 4199:     }
 4200:     #SD Following files not added to help, because the corresponding .tex-files seem to
 4201:     #be missing: Course_Approve_Selfenroll,Course_User_Logs,
 4202:     my ($permission,$allowed) = 
 4203:         &Apache::lonuserutils::get_permission($context,$crstype);
 4204:     if (!$allowed) {
 4205:         if ($context eq 'course') {
 4206:             $r->internal_redirect('/adm/viewclasslist');
 4207:             return OK;
 4208:         }
 4209:         $env{'user.error.msg'}=
 4210:             "/adm/createuser:cst:0:0:Cannot create/modify user data ".
 4211:                                  "or view user status.";
 4212:         return HTTP_NOT_ACCEPTABLE;
 4213:     }
 4214: 
 4215:     &Apache::loncommon::content_type($r,'text/html');
 4216:     $r->send_http_header;
 4217: 
 4218:     # Main switch on form.action and form.state, as appropriate
 4219:     if (! exists($env{'form.action'})) {
 4220:         $args = {bread_crumbs => $brcrum,
 4221:                  bread_crumbs_component => $bread_crumbs_component}; 
 4222:         $r->print(&header(undef,$args));
 4223:         $r->print(&print_main_menu($permission,$context,$crstype));
 4224:     } elsif ($env{'form.action'} eq 'upload' && $permission->{'cusr'}) {
 4225:         push(@{$brcrum},
 4226:               { href => '/adm/createuser?action=upload&state=',
 4227:                 text => 'Upload Users List',
 4228:                 help => 'Course_Create_Class_List',
 4229:               });
 4230:         $bread_crumbs_component = 'Upload Users List';
 4231:         $args = {bread_crumbs           => $brcrum,
 4232:                  bread_crumbs_component => $bread_crumbs_component};
 4233:         $r->print(&header(undef,$args));
 4234:         $r->print('<form name="studentform" method="post" '.
 4235:                   'enctype="multipart/form-data" '.
 4236:                   ' action="/adm/createuser">'."\n");
 4237:         if (! exists($env{'form.state'})) {
 4238:             &Apache::lonuserutils::print_first_users_upload_form($r,$context);
 4239:         } elsif ($env{'form.state'} eq 'got_file') {
 4240:             &Apache::lonuserutils::print_upload_manager_form($r,$context,
 4241:                                                              $permission,$crstype);
 4242:         } elsif ($env{'form.state'} eq 'enrolling') {
 4243:             if ($env{'form.datatoken'}) {
 4244:                 &Apache::lonuserutils::upfile_drop_add($r,$context,$permission);
 4245:             }
 4246:         } else {
 4247:             &Apache::lonuserutils::print_first_users_upload_form($r,$context);
 4248:         }
 4249:     } elsif ((($env{'form.action'} eq 'singleuser') || ($env{'form.action'}
 4250:              eq 'singlestudent')) && ($permission->{'cusr'})) {
 4251:         my $phase = $env{'form.phase'};
 4252:         my @search = ('srchterm','srchby','srchin','srchtype','srchdomain');
 4253: 	&Apache::loncreateuser::restore_prev_selections();
 4254: 	my $srch;
 4255: 	foreach my $item (@search) {
 4256: 	    $srch->{$item} = $env{'form.'.$item};
 4257: 	}
 4258:         if (($phase eq 'get_user_info') || ($phase eq 'userpicked') ||
 4259:             ($phase eq 'createnewuser')) {
 4260:             if ($env{'form.phase'} eq 'createnewuser') {
 4261:                 my $response;
 4262:                 if ($env{'form.srchterm'} !~ /^$match_username$/) {
 4263:                     my $response =
 4264:                         '<span class="LC_warning">'
 4265:                        .&mt('You must specify a valid username. Only the following are allowed:'
 4266:                            .' letters numbers - . @')
 4267:                        .'</span>';
 4268:                     $env{'form.phase'} = '';
 4269:                     &print_username_entry_form($r,$context,$response,$srch,undef,$crstype,$brcrum);
 4270:                 } else {
 4271:                     my $ccuname =&LONCAPA::clean_username($srch->{'srchterm'});
 4272:                     my $ccdomain=&LONCAPA::clean_domain($srch->{'srchdomain'});
 4273:                     &print_user_modification_page($r,$ccuname,$ccdomain,
 4274:                                                   $srch,$response,$context,
 4275:                                                   $permission,$crstype,$brcrum);
 4276:                 }
 4277:             } elsif ($env{'form.phase'} eq 'get_user_info') {
 4278:                 my ($currstate,$response,$forcenewuser,$results) = 
 4279:                     &user_search_result($context,$srch);
 4280:                 if ($env{'form.currstate'} eq 'modify') {
 4281:                     $currstate = $env{'form.currstate'};
 4282:                 }
 4283:                 if ($currstate eq 'select') {
 4284:                     &print_user_selection_page($r,$response,$srch,$results,
 4285:                                                \@search,$context,undef,$crstype,
 4286:                                                $brcrum);
 4287:                 } elsif ($currstate eq 'modify') {
 4288:                     my ($ccuname,$ccdomain);
 4289:                     if (($srch->{'srchby'} eq 'uname') && 
 4290:                         ($srch->{'srchtype'} eq 'exact')) {
 4291:                         $ccuname = $srch->{'srchterm'};
 4292:                         $ccdomain= $srch->{'srchdomain'};
 4293:                     } else {
 4294:                         my @matchedunames = keys(%{$results});
 4295:                         ($ccuname,$ccdomain) = split(/:/,$matchedunames[0]);
 4296:                     }
 4297:                     $ccuname =&LONCAPA::clean_username($ccuname);
 4298:                     $ccdomain=&LONCAPA::clean_domain($ccdomain);
 4299:                     if ($env{'form.forcenewuser'}) {
 4300:                         $response = '';
 4301:                     }
 4302:                     &print_user_modification_page($r,$ccuname,$ccdomain,
 4303:                                                   $srch,$response,$context,
 4304:                                                   $permission,$crstype,$brcrum);
 4305:                 } elsif ($currstate eq 'query') {
 4306:                     &print_user_query_page($r,'createuser',$brcrum);
 4307:                 } else {
 4308:                     $env{'form.phase'} = '';
 4309:                     &print_username_entry_form($r,$context,$response,$srch,
 4310:                                                $forcenewuser,$crstype,$brcrum);
 4311:                 }
 4312:             } elsif ($env{'form.phase'} eq 'userpicked') {
 4313:                 my $ccuname = &LONCAPA::clean_username($env{'form.seluname'});
 4314:                 my $ccdomain = &LONCAPA::clean_domain($env{'form.seludom'});
 4315:                 &print_user_modification_page($r,$ccuname,$ccdomain,$srch,'',
 4316:                                               $context,$permission,$crstype,
 4317:                                               $brcrum);
 4318:             }
 4319:         } elsif ($env{'form.phase'} eq 'update_user_data') {
 4320:             &update_user_data($r,$context,$crstype,$brcrum);
 4321:         } else {
 4322:             &print_username_entry_form($r,$context,undef,$srch,undef,$crstype,
 4323:                                        $brcrum);
 4324:         }
 4325:     } elsif ($env{'form.action'} eq 'custom' && $permission->{'custom'}) {
 4326:         if ($env{'form.phase'} eq 'set_custom_roles') {
 4327:             &set_custom_role($r,$context,$brcrum);
 4328:         } else {
 4329:             &custom_role_editor($r,$brcrum);
 4330:         }
 4331:     } elsif (($env{'form.action'} eq 'processauthorreq') &&
 4332:              ($permission->{'cusr'}) && 
 4333:              (&Apache::lonnet::allowed('cau',$env{'request.role.domain'}))) {
 4334:         push(@{$brcrum},
 4335:                  {href => '/adm/createuser?action=processauthorreq',
 4336:                   text => 'Authoring space requests',
 4337:                   help => 'Domain_Role_Approvals'});
 4338:         $bread_crumbs_component = 'Authoring requests';
 4339:         if ($env{'form.state'} eq 'done') {
 4340:             push(@{$brcrum},
 4341:                      {href => '/adm/createuser?action=authorreqqueue',
 4342:                       text => 'Result',
 4343:                       help => 'Domain_Role_Approvals'});
 4344:             $bread_crumbs_component = 'Authoring request result';
 4345:         }
 4346:         $args = { bread_crumbs           => $brcrum,
 4347:                   bread_crumbs_component => $bread_crumbs_component};
 4348:         $r->print(&header(undef,$args));
 4349:         if (!exists($env{'form.state'})) {
 4350:             $r->print(&Apache::loncoursequeueadmin::display_queued_requests('requestauthor',
 4351:                                                                             $env{'request.role.domain'}));
 4352:         } elsif ($env{'form.state'} eq 'done') {
 4353:             $r->print('<h3>'.&mt('Authoring request processing').'</h3>'."\n");
 4354:             $r->print(&Apache::loncoursequeueadmin::update_request_queue('requestauthor',
 4355:                                                                          $env{'request.role.domain'}));
 4356:         }
 4357:     } elsif (($env{'form.action'} eq 'listusers') && 
 4358:              ($permission->{'view'} || $permission->{'cusr'})) {
 4359:         if ($env{'form.phase'} eq 'bulkchange') {
 4360:             push(@{$brcrum},
 4361:                     {href => '/adm/createuser?action=listusers',
 4362:                      text => "List Users"},
 4363:                     {href => "/adm/createuser",
 4364:                      text => "Result",
 4365:                      help => 'Course_View_Class_List'});
 4366:             $bread_crumbs_component = 'Update Users';
 4367:             $args = {bread_crumbs           => $brcrum,
 4368:                      bread_crumbs_component => $bread_crumbs_component};
 4369:             $r->print(&header(undef,$args));
 4370:             my $setting = $env{'form.roletype'};
 4371:             my $choice = $env{'form.bulkaction'};
 4372:             if ($permission->{'cusr'}) {
 4373:                 &Apache::lonuserutils::update_user_list($r,$context,$setting,$choice,$crstype);
 4374:             } else {
 4375:                 $r->print(&mt('You are not authorized to make bulk changes to user roles'));
 4376:                 $r->print('<p><a href="/adm/createuser?action=listusers">'.&mt('Display User Lists').'</a>');
 4377:             }
 4378:         } else {
 4379:             push(@{$brcrum},
 4380:                     {href => '/adm/createuser?action=listusers',
 4381:                      text => "List Users",
 4382:                      help => 'Course_View_Class_List'});
 4383:             $bread_crumbs_component = 'List Users';
 4384:             $args = {bread_crumbs           => $brcrum,
 4385:                      bread_crumbs_component => $bread_crumbs_component};
 4386:             my ($cb_jscript,$jscript,$totcodes,$codetitles,$idlist,$idlist_titles);
 4387:             my $formname = 'studentform';
 4388:             my $hidecall = "hide_searching();";
 4389:             if (($context eq 'domain') && (($env{'form.roletype'} eq 'course') ||
 4390:                 ($env{'form.roletype'} eq 'community'))) {
 4391:                 if ($env{'form.roletype'} eq 'course') {
 4392:                     ($cb_jscript,$jscript,$totcodes,$codetitles,$idlist,$idlist_titles) = 
 4393:                         &Apache::lonuserutils::courses_selector($env{'request.role.domain'},
 4394:                                                                 $formname);
 4395:                 } elsif ($env{'form.roletype'} eq 'community') {
 4396:                     $cb_jscript = 
 4397:                         &Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'});
 4398:                     my %elements = (
 4399:                                       coursepick => 'radio',
 4400:                                       coursetotal => 'text',
 4401:                                       courselist => 'text',
 4402:                                    );
 4403:                     $jscript = &Apache::lonhtmlcommon::set_form_elements(\%elements);
 4404:                 }
 4405:                 $jscript .= &verify_user_display($context)."\n".
 4406:                             &Apache::loncommon::check_uncheck_jscript();
 4407:                 my $js = &add_script($jscript).$cb_jscript;
 4408:                 my $loadcode = 
 4409:                     &Apache::lonuserutils::course_selector_loadcode($formname);
 4410:                 if ($loadcode ne '') {
 4411:                     $args->{add_entries} = {onload => "$loadcode;$hidecall"};
 4412:                 } else {
 4413:                     $args->{add_entries} = {onload => $hidecall};
 4414:                 }
 4415:                 $r->print(&header($js,$args));
 4416:             } else {
 4417:                 $args->{add_entries} = {onload => $hidecall};
 4418:                 $jscript = &verify_user_display($context).
 4419:                            &Apache::loncommon::check_uncheck_jscript(); 
 4420:                 $r->print(&header(&add_script($jscript),$args));
 4421:             }
 4422:             &Apache::lonuserutils::print_userlist($r,undef,$permission,$context,
 4423:                          $formname,$totcodes,$codetitles,$idlist,$idlist_titles);
 4424:         }
 4425:     } elsif ($env{'form.action'} eq 'drop' && $permission->{'cusr'}) {
 4426:         my $brtext;
 4427:         if ($crstype eq 'Community') {
 4428:             $brtext = 'Drop Members';
 4429:         } else {
 4430:             $brtext = 'Drop Students';
 4431:         }
 4432:         push(@{$brcrum},
 4433:                 {href => '/adm/createuser?action=drop',
 4434:                  text => $brtext,
 4435:                  help => 'Course_Drop_Student'});
 4436:         if ($env{'form.state'} eq 'done') {
 4437:             push(@{$brcrum},
 4438:                      {href=>'/adm/createuser?action=drop',
 4439:                       text=>"Result"});
 4440:         }
 4441:         $bread_crumbs_component = $brtext;
 4442:         $args = {bread_crumbs           => $brcrum,
 4443:                  bread_crumbs_component => $bread_crumbs_component}; 
 4444:         $r->print(&header(undef,$args));
 4445:         if (!exists($env{'form.state'})) {
 4446:             &Apache::lonuserutils::print_drop_menu($r,$context,$permission,$crstype);
 4447:         } elsif ($env{'form.state'} eq 'done') {
 4448:             &Apache::lonuserutils::update_user_list($r,$context,undef,
 4449:                                                     $env{'form.action'});
 4450:         }
 4451:     } elsif ($env{'form.action'} eq 'dateselect') {
 4452:         if ($permission->{'cusr'}) {
 4453:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 4454:                       &Apache::lonuserutils::date_section_selector($context,
 4455:                                                                    $permission,$crstype));
 4456:         } else {
 4457:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 4458:                      '<span class="LC_error">'.&mt('You do not have permission to modify dates or sections for users').'</span>'); 
 4459:         }
 4460:     } elsif ($env{'form.action'} eq 'selfenroll') {
 4461:         push(@{$brcrum},
 4462:                 {href => '/adm/createuser?action=selfenroll',
 4463:                  text => "Configure Self-enrollment",
 4464:                  help => 'Course_Self_Enrollment'});
 4465:         if (!exists($env{'form.state'})) {
 4466:             $args = { bread_crumbs           => $brcrum,
 4467:                       bread_crumbs_component => 'Configure Self-enrollment'};
 4468:             $r->print(&header(undef,$args));
 4469:             $r->print('<h3>'.&mt('Self-enrollment with a student role').'</h3>'."\n");
 4470:             &print_selfenroll_menu($r,$context,$permission);
 4471:         } elsif ($env{'form.state'} eq 'done') {
 4472:             push (@{$brcrum},
 4473:                       {href=>'/adm/createuser?action=selfenroll',
 4474:                        text=>"Result"});
 4475:             $args = { bread_crumbs           => $brcrum,
 4476:                       bread_crumbs_component => 'Self-enrollment result'};
 4477:             $r->print(&header(undef,$args));
 4478:             $r->print('<h3>'.&mt('Self-enrollment with a student role').'</h3>'."\n");
 4479:             &update_selfenroll_config($r,$context,$permission);
 4480:         }
 4481:     } elsif ($env{'form.action'} eq 'selfenrollqueue') {
 4482:         push(@{$brcrum},
 4483:                  {href => '/adm/createuser?action=selfenrollqueue',
 4484:                   text => 'Enrollment requests',
 4485:                   help => 'Course_Self_Enrollment'});
 4486:         $bread_crumbs_component = 'Enrollment requests';
 4487:         if ($env{'form.state'} eq 'done') {
 4488:             push(@{$brcrum},
 4489:                      {href => '/adm/createuser?action=selfenrollqueue',
 4490:                       text => 'Result',
 4491:                       help => 'Course_Self_Enrollment'});
 4492:             $bread_crumbs_component = 'Enrollment result';
 4493:         }
 4494:         $args = { bread_crumbs           => $brcrum,
 4495:                   bread_crumbs_component => $bread_crumbs_component};
 4496:         $r->print(&header(undef,$args));
 4497:         my $cid = $env{'request.course.id'};
 4498:         my $cdom = $env{'course.'.$cid.'.domain'};
 4499:         my $cnum = $env{'course.'.$cid.'.num'};
 4500:         my $coursedesc = $env{'course.'.$cid.'.description'};
 4501:         if (!exists($env{'form.state'})) {
 4502:             $r->print('<h3>'.&mt('Pending enrollment requests').'</h3>'."\n");
 4503:             $r->print(&Apache::loncoursequeueadmin::display_queued_requests($context,
 4504:                                                                        $cdom,$cnum));
 4505:         } elsif ($env{'form.state'} eq 'done') {
 4506:             $r->print('<h3>'.&mt('Enrollment request processing').'</h3>'."\n");
 4507:             $r->print(&Apache::loncoursequeueadmin::update_request_queue($context,
 4508:                           $cdom,$cnum,$coursedesc));
 4509:         }
 4510:     } elsif ($env{'form.action'} eq 'changelogs') {
 4511:         my $helpitem;
 4512:         if ($context eq 'course') {
 4513:             $helpitem = 'Course_User_Logs';
 4514:         }
 4515:         push (@{$brcrum},
 4516:                  {href => '/adm/createuser?action=changelogs',
 4517:                   text => 'User Management Logs',
 4518:                   help => $helpitem});
 4519:         $bread_crumbs_component = 'User Changes';
 4520:         $args = { bread_crumbs           => $brcrum,
 4521:                   bread_crumbs_component => $bread_crumbs_component};
 4522:         $r->print(&header(undef,$args));
 4523:         &print_userchangelogs_display($r,$context,$permission);
 4524:     } else {
 4525:         $bread_crumbs_component = 'User Management';
 4526:         $args = { bread_crumbs           => $brcrum,
 4527:                   bread_crumbs_component => $bread_crumbs_component};
 4528:         $r->print(&header(undef,$args));
 4529:         $r->print(&print_main_menu($permission,$context,$crstype));
 4530:     }
 4531:     $r->print(&Apache::loncommon::end_page());
 4532:     return OK;
 4533: }
 4534: 
 4535: sub header {
 4536:     my ($jscript,$args) = @_;
 4537:     my $start_page;
 4538:     if (ref($args) eq 'HASH') {
 4539:         $start_page=&Apache::loncommon::start_page('User Management',$jscript,$args);
 4540:     } else {
 4541:         $start_page=&Apache::loncommon::start_page('User Management',$jscript);
 4542:     }
 4543:     return $start_page;
 4544: }
 4545: 
 4546: sub add_script {
 4547:     my ($js) = @_;
 4548:     return '<script type="text/javascript">'."\n"
 4549:           .'// <![CDATA['."\n"
 4550:           .$js."\n"
 4551:           .'// ]]>'."\n"
 4552:           .'</script>'."\n";
 4553: }
 4554: 
 4555: sub verify_user_display {
 4556:     my ($context) = @_;
 4557:     my $photos;
 4558:     if (($context eq 'course') && $env{'request.course.id'}) {
 4559:         $photos = $env{'course.'.$env{'request.course.id'}.'.internal.showphoto'};
 4560:     }
 4561:     my $output = <<"END";
 4562: 
 4563: function hide_searching() {
 4564:     if (document.getElementById('searching')) {
 4565:         document.getElementById('searching').style.display = 'none';
 4566:     }
 4567:     return;
 4568: }
 4569: 
 4570: function display_update() {
 4571:     document.studentform.action.value = 'listusers';
 4572:     document.studentform.phase.value = 'display';
 4573:     document.studentform.submit();
 4574: }
 4575: 
 4576: function updateCols(caller) {
 4577:     var context = '$context';
 4578:     var photos = '$photos';
 4579:     if (caller == 'Status') {
 4580:         if (document.studentform.Status.options[document.studentform.Status.selectedIndex].value == 'Any') {
 4581:             document.getElementById('showcolstatus').checked = true;
 4582:             document.getElementById('showcolstatus').disabled = '';
 4583:             document.getElementById('showcolstart').checked = true;
 4584:             document.getElementById('showcolend').checked = true;
 4585:         } else {
 4586:             document.getElementById('showcolstatus').checked = false;
 4587:             document.getElementById('showcolstatus').disabled = 'disabled';
 4588:             document.getElementById('showcolstart').checked = false;
 4589:             document.getElementById('showcolend').checked = false;
 4590:         }
 4591:     }
 4592:     if (caller == 'output') {
 4593:         if (photos == 1) {
 4594:             if (document.getElementById('showcolphoto')) {
 4595:                 var photoitem = document.getElementById('showcolphoto');
 4596:                 if (document.studentform.output.options[document.studentform.output.selectedIndex].value == 'html') {
 4597:                     photoitem.checked = true;
 4598:                     photoitem.disabled = '';
 4599:                 } else {
 4600:                     photoitem.checked = false;
 4601:                     photoitem.disabled = 'disabled';
 4602:                 }
 4603:             }
 4604:         }
 4605:     }
 4606:     if (caller == 'showrole') {
 4607:         if ((document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'Any') ||
 4608:             (document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'cr')) {
 4609:             document.getElementById('showcolrole').checked = true;
 4610:             document.getElementById('showcolrole').disabled = '';
 4611:         } else {
 4612:             document.getElementById('showcolrole').checked = false;
 4613:             document.getElementById('showcolrole').disabled = 'disabled';
 4614:         }
 4615:     }
 4616:     return;
 4617: }
 4618: 
 4619: END
 4620:     return $output;
 4621: 
 4622: }
 4623: 
 4624: ###############################################################
 4625: ###############################################################
 4626: #  Menu Phase One
 4627: sub print_main_menu {
 4628:     my ($permission,$context,$crstype) = @_;
 4629:     my $linkcontext = $context;
 4630:     my $stuterm = lc(&Apache::lonnet::plaintext('st',$crstype));
 4631:     if (($context eq 'course') && ($crstype eq 'Community')) {
 4632:         $linkcontext = lc($crstype);
 4633:         $stuterm = 'Members';
 4634:     }
 4635:     my %links = (
 4636:                 domain => {
 4637:                             upload     => 'Upload a File of Users',
 4638:                             singleuser => 'Add/Modify a User',
 4639:                             listusers  => 'Manage Users',
 4640:                             },
 4641:                 author => {
 4642:                             upload     => 'Upload a File of Co-authors',
 4643:                             singleuser => 'Add/Modify a Co-author',
 4644:                             listusers  => 'Manage Co-authors',
 4645:                             },
 4646:                 course => {
 4647:                             upload     => 'Upload a File of Course Users',
 4648:                             singleuser => 'Add/Modify a Course User',
 4649:                             listusers  => 'List and Modify Multiple Course Users',
 4650:                             },
 4651:                 community => {
 4652:                             upload     => 'Upload a File of Community Users',
 4653:                             singleuser => 'Add/Modify a Community User',
 4654:                             listusers  => 'List and Modify Multiple Community Users',
 4655:                            },
 4656:                 );
 4657:      my %linktitles = (
 4658:                 domain => {
 4659:                             singleuser => 'Add a user to the domain, and/or a course or community in the domain.',
 4660:                             listusers  => 'Show and manage users in this domain.',
 4661:                             },
 4662:                 author => {
 4663:                             singleuser => 'Add a user with a co- or assistant author role.',
 4664:                             listusers  => 'Show and manage co- or assistant authors.',
 4665:                             },
 4666:                 course => {
 4667:                             singleuser => 'Add a user with a certain role to this course.',
 4668:                             listusers  => 'Show and manage users in this course.',
 4669:                             },
 4670:                 community => {
 4671:                             singleuser => 'Add a user with a certain role to this community.',
 4672:                             listusers  => 'Show and manage users in this community.',
 4673:                            },
 4674:                 );
 4675:   my @menu = ( {categorytitle => 'Single Users', 
 4676:          items =>
 4677:          [
 4678:             {
 4679:              linktext => $links{$linkcontext}{'singleuser'},
 4680:              icon => 'edit-redo.png',
 4681:              #help => 'Course_Change_Privileges',
 4682:              url => '/adm/createuser?action=singleuser',
 4683:              permission => $permission->{'cusr'},
 4684:              linktitle => $linktitles{$linkcontext}{'singleuser'},
 4685:             },
 4686:          ]},
 4687: 
 4688:          {categorytitle => 'Multiple Users',
 4689:          items => 
 4690:          [
 4691:             {
 4692:              linktext => $links{$linkcontext}{'upload'},
 4693:              icon => 'uplusr.png',
 4694:              #help => 'Course_Create_Class_List',
 4695:              url => '/adm/createuser?action=upload',
 4696:              permission => $permission->{'cusr'},
 4697:              linktitle => 'Upload a CSV or a text file containing users.',
 4698:             },
 4699:             {
 4700:              linktext => $links{$linkcontext}{'listusers'},
 4701:              icon => 'mngcu.png',
 4702:              #help => 'Course_View_Class_List',
 4703:              url => '/adm/createuser?action=listusers',
 4704:              permission => ($permission->{'view'} || $permission->{'cusr'}),
 4705:              linktitle => $linktitles{$linkcontext}{'listusers'}, 
 4706:             },
 4707: 
 4708:          ]},
 4709: 
 4710:          {categorytitle => 'Administration',
 4711:          items => [ ]},
 4712:        );
 4713:             
 4714:     if ($context eq 'domain'){
 4715:         
 4716:         push(@{ $menu[2]->{items} }, #Category: Administration
 4717:             {
 4718:              linktext => 'Custom Roles',
 4719:              icon => 'emblem-photos.png',
 4720:              #help => 'Course_Editing_Custom_Roles',
 4721:              url => '/adm/createuser?action=custom',
 4722:              permission => $permission->{'custom'},
 4723:              linktitle => 'Configure a custom role.',
 4724:             },
 4725:             {
 4726:              linktext => 'Authoring Space Requests',
 4727:              icon => 'selfenrl-queue.png',
 4728:              #help => 'Domain_Role_Approvals',
 4729:              url => '/adm/createuser?action=processauthorreq',
 4730:              permission => $permission->{'cusr'},
 4731:              linktitle => 'Approve or reject author role requests',
 4732:             },
 4733:             {
 4734:              linktext => 'Change Log',
 4735:              icon => 'document-properties.png',
 4736:              #help => 'Course_User_Logs',
 4737:              url => '/adm/createuser?action=changelogs',
 4738:              permission => $permission->{'cusr'},
 4739:              linktitle => 'View change log.',
 4740:             },
 4741:         );
 4742:         
 4743:     }elsif ($context eq 'course'){
 4744:         my ($cnum,$cdom) = &Apache::lonuserutils::get_course_identity();
 4745: 
 4746:         my %linktext = (
 4747:                          'Course'    => {
 4748:                                           single => 'Add/Modify a Student', 
 4749:                                           drop   => 'Drop Students',
 4750:                                           groups => 'Course Groups',
 4751:                                         },
 4752:                          'Community' => {
 4753:                                           single => 'Add/Modify a Member', 
 4754:                                           drop   => 'Drop Members',
 4755:                                           groups => 'Community Groups',
 4756:                                         },
 4757:                        );
 4758: 
 4759:         my %linktitle = (
 4760:             'Course' => {
 4761:                   single => 'Add a user with the role of student to this course',
 4762:                   drop   => 'Remove a student from this course.',
 4763:                   groups => 'Manage course groups',
 4764:                         },
 4765:             'Community' => {
 4766:                   single => 'Add a user with the role of member to this community',
 4767:                   drop   => 'Remove a member from this community.',
 4768:                   groups => 'Manage community groups',
 4769:                            },
 4770:         );
 4771: 
 4772:         push(@{ $menu[0]->{items} }, #Category: Single Users
 4773:             {   
 4774:              linktext => $linktext{$crstype}{'single'},
 4775:              #help => 'Course_Add_Student',
 4776:              icon => 'list-add.png',
 4777:              url => '/adm/createuser?action=singlestudent',
 4778:              permission => $permission->{'cusr'},
 4779:              linktitle => $linktitle{$crstype}{'single'},
 4780:             },
 4781:         );
 4782:         
 4783:         push(@{ $menu[1]->{items} }, #Category: Multiple Users 
 4784:             {
 4785:              linktext => $linktext{$crstype}{'drop'},
 4786:              icon => 'edit-undo.png',
 4787:              #help => 'Course_Drop_Student',
 4788:              url => '/adm/createuser?action=drop',
 4789:              permission => $permission->{'cusr'},
 4790:              linktitle => $linktitle{$crstype}{'drop'},
 4791:             },
 4792:         );
 4793:         push(@{ $menu[2]->{items} }, #Category: Administration
 4794:             {    
 4795:              linktext => 'Custom Roles',
 4796:              icon => 'emblem-photos.png',
 4797:              #help => 'Course_Editing_Custom_Roles',
 4798:              url => '/adm/createuser?action=custom',
 4799:              permission => $permission->{'custom'},
 4800:              linktitle => 'Configure a custom role.',
 4801:             },
 4802:             {
 4803:              linktext => $linktext{$crstype}{'groups'},
 4804:              icon => 'grps.png',
 4805:              #help => 'Course_Manage_Group',
 4806:              url => '/adm/coursegroups?refpage=cusr',
 4807:              permission => $permission->{'grp_manage'},
 4808:              linktitle => $linktitle{$crstype}{'groups'},
 4809:             },
 4810:             {
 4811:              linktext => 'Change Log',
 4812:              icon => 'document-properties.png',
 4813:              #help => 'Course_User_Logs',
 4814:              url => '/adm/createuser?action=changelogs',
 4815:              permission => $permission->{'cusr'},
 4816:              linktitle => 'View change log.',
 4817:             },
 4818:         );
 4819:         if ($env{'course.'.$env{'request.course.id'}.'.internal.selfenroll_approval'}) {
 4820:             push(@{ $menu[2]->{items} },
 4821:                     {   
 4822:                      linktext => 'Enrollment Requests',
 4823:                      icon => 'selfenrl-queue.png',
 4824:                      #help => 'Course_Approve_Selfenroll',
 4825:                      url => '/adm/createuser?action=selfenrollqueue',
 4826:                      permission => $permission->{'cusr'},
 4827:                      linktitle =>'Approve or reject enrollment requests.',
 4828:                     },
 4829:             );
 4830:         }
 4831:         
 4832:         if (!exists($permission->{'cusr_section'})){
 4833:             if ($crstype ne 'Community') {
 4834:                 push(@{ $menu[2]->{items} },
 4835:                     {
 4836:                      linktext => 'Automated Enrollment',
 4837:                      icon => 'roles.png',
 4838:                      #help => 'Course_Automated_Enrollment',
 4839:                      permission => (&Apache::lonnet::auto_run($cnum,$cdom)
 4840:                                          && $permission->{'cusr'}),
 4841:                      url  => '/adm/populate',
 4842:                      linktitle => 'Automated enrollment manager.',
 4843:                     }
 4844:                 );
 4845:             }
 4846:             push(@{ $menu[2]->{items} }, 
 4847:                 {
 4848:                  linktext => 'User Self-Enrollment',
 4849:                  icon => 'self_enroll.png',
 4850:                  #help => 'Course_Self_Enrollment',
 4851:                  url => '/adm/createuser?action=selfenroll',
 4852:                  permission => $permission->{'cusr'},
 4853:                  linktitle => 'Configure user self-enrollment.',
 4854:                 },
 4855:             );
 4856:         }
 4857:     } elsif ($context eq 'author') {
 4858:         push(@{ $menu[2]->{items} }, #Category: Administration
 4859:             {
 4860:              linktext => 'Change Log',
 4861:              icon => 'document-properties.png',
 4862:              #help => 'Course_User_Logs',
 4863:              url => '/adm/createuser?action=changelogs',
 4864:              permission => $permission->{'cusr'},
 4865:              linktitle => 'View change log.',
 4866:             },
 4867:         );
 4868:     }
 4869:     return Apache::lonhtmlcommon::generate_menu(@menu);
 4870: #               { text => 'View Log-in History',
 4871: #                 help => 'Course_User_Logins',
 4872: #                 action => 'logins',
 4873: #                 permission => $permission->{'cusr'},
 4874: #               });
 4875: }
 4876: 
 4877: sub restore_prev_selections {
 4878:     my %saveable_parameters = ('srchby'   => 'scalar',
 4879: 			       'srchin'   => 'scalar',
 4880: 			       'srchtype' => 'scalar',
 4881: 			       );
 4882:     &Apache::loncommon::store_settings('user','user_picker',
 4883: 				       \%saveable_parameters);
 4884:     &Apache::loncommon::restore_settings('user','user_picker',
 4885: 					 \%saveable_parameters);
 4886: }
 4887: 
 4888: sub print_selfenroll_menu {
 4889:     my ($r,$context,$permission) = @_;
 4890:     my $crstype = &Apache::loncommon::course_type();
 4891:     my $formname = 'enrollstudent';
 4892:     my $nolink = 1;
 4893:     my ($row,$lt) = &get_selfenroll_titles();
 4894:     my $groupslist = &Apache::lonuserutils::get_groupslist();
 4895:     my $setsec_js = 
 4896:         &Apache::lonuserutils::setsections_javascript($formname,$groupslist);
 4897:     my %alerts = &Apache::lonlocal::texthash(
 4898:         acto => 'Activation of self-enrollment was selected for the following domain(s)',
 4899:         butn => 'but no user types have been checked.',
 4900:         wilf => "Please uncheck 'activate' or check at least one type.",
 4901:     );
 4902:     my $selfenroll_js = <<"ENDSCRIPT";
 4903: function update_types(caller,num) {
 4904:     var delidx = getIndexByName('selfenroll_delete');
 4905:     var actidx = getIndexByName('selfenroll_activate');
 4906:     if (caller == 'selfenroll_all') {
 4907:         var selall;
 4908:         for (var i=0; i<document.$formname.selfenroll_all.length; i++) {
 4909:             if (document.$formname.selfenroll_all[i].checked) {
 4910:                 selall = document.$formname.selfenroll_all[i].value;
 4911:             }
 4912:         }
 4913:         if (selall == 1) {
 4914:             if (delidx != -1) {
 4915:                 if (document.$formname.selfenroll_delete.length) {
 4916:                     for (var j=0; j<document.$formname.selfenroll_delete.length; j++) {
 4917:                         document.$formname.selfenroll_delete[j].checked = true;
 4918:                     }
 4919:                 } else {
 4920:                     document.$formname.elements[delidx].checked = true;
 4921:                 }
 4922:             }
 4923:             if (actidx != -1) {
 4924:                 if (document.$formname.selfenroll_activate.length) {
 4925:                     for (var j=0; j<document.$formname.selfenroll_activate.length; j++) {
 4926:                         document.$formname.selfenroll_activate[j].checked = false;
 4927:                     }
 4928:                 } else {
 4929:                     document.$formname.elements[actidx].checked = false;
 4930:                 }
 4931:             }
 4932:             document.$formname.selfenroll_newdom.selectedIndex = 0; 
 4933:         }
 4934:     }
 4935:     if (caller == 'selfenroll_activate') {
 4936:         if (document.$formname.selfenroll_activate.length) {
 4937:             for (var j=0; j<document.$formname.selfenroll_activate.length; j++) {
 4938:                 if (document.$formname.selfenroll_activate[j].value == num) {
 4939:                     if (document.$formname.selfenroll_activate[j].checked) {
 4940:                         for (var i=0; i<document.$formname.selfenroll_all.length; i++) {
 4941:                             if (document.$formname.selfenroll_all[i].value == '1') {
 4942:                                 document.$formname.selfenroll_all[i].checked = false;
 4943:                             }
 4944:                             if (document.$formname.selfenroll_all[i].value == '0') {
 4945:                                 document.$formname.selfenroll_all[i].checked = true;
 4946:                             }
 4947:                         }
 4948:                     }
 4949:                 }
 4950:             }
 4951:         } else {
 4952:             for (var i=0; i<document.$formname.selfenroll_all.length; i++) {
 4953:                 if (document.$formname.selfenroll_all[i].value == '1') {
 4954:                     document.$formname.selfenroll_all[i].checked = false;
 4955:                 }
 4956:                 if (document.$formname.selfenroll_all[i].value == '0') {
 4957:                     document.$formname.selfenroll_all[i].checked = true;
 4958:                 }
 4959:             }
 4960:         }
 4961:     }
 4962:     if (caller == 'selfenroll_delete') {
 4963:         if (document.$formname.selfenroll_delete.length) {
 4964:             for (var j=0; j<document.$formname.selfenroll_delete.length; j++) {
 4965:                 if (document.$formname.selfenroll_delete[j].value == num) {
 4966:                     if (document.$formname.selfenroll_delete[j].checked) {
 4967:                         var delindex = getIndexByName('selfenroll_types_'+num);
 4968:                         if (delindex != -1) { 
 4969:                             if (document.$formname.elements[delindex].length) {
 4970:                                 for (var k=0; k<document.$formname.elements[delindex].length; k++) {
 4971:                                     document.$formname.elements[delindex][k].checked = false;
 4972:                                 }
 4973:                             } else {
 4974:                                 document.$formname.elements[delindex].checked = false;
 4975:                             }
 4976:                         }
 4977:                     }
 4978:                 }
 4979:             }
 4980:         } else {
 4981:             if (document.$formname.selfenroll_delete.checked) {
 4982:                 var delindex = getIndexByName('selfenroll_types_'+num);
 4983:                 if (delindex != -1) {
 4984:                     if (document.$formname.elements[delindex].length) {
 4985:                         for (var k=0; k<document.$formname.elements[delindex].length; k++) {
 4986:                             document.$formname.elements[delindex][k].checked = false;
 4987:                         }
 4988:                     } else {
 4989:                         document.$formname.elements[delindex].checked = false;
 4990:                     }
 4991:                 }
 4992:             }
 4993:         }
 4994:     }
 4995:     return;
 4996: }
 4997: 
 4998: function validate_types(form) {
 4999:     var needaction = new Array();
 5000:     var countfail = 0;
 5001:     var actidx = getIndexByName('selfenroll_activate');
 5002:     if (actidx != -1) {
 5003:         if (document.$formname.selfenroll_activate.length) {
 5004:             for (var j=0; j<document.$formname.selfenroll_activate.length; j++) {
 5005:                 var num = document.$formname.selfenroll_activate[j].value;
 5006:                 if (document.$formname.selfenroll_activate[j].checked) {
 5007:                     countfail = check_types(num,countfail,needaction)
 5008:                 }
 5009:             }
 5010:         } else {
 5011:             if (document.$formname.selfenroll_activate.checked) {
 5012:                 var num = document.enrollstudent.selfenroll_activate.value;
 5013:                 countfail = check_types(num,countfail,needaction)
 5014:             }
 5015:         }
 5016:     }
 5017:     if (countfail > 0) {
 5018:         var msg = "$alerts{'acto'}\\n";
 5019:         var loopend = needaction.length -1;
 5020:         if (loopend > 0) {
 5021:             for (var m=0; m<loopend; m++) {
 5022:                 msg += needaction[m]+", ";
 5023:             }
 5024:         }
 5025:         msg += needaction[loopend]+"\\n$alerts{'butn'}\\n$alerts{'wilf'}";
 5026:         alert(msg);
 5027:         return; 
 5028:     }
 5029:     setSections(form);
 5030: }
 5031: 
 5032: function check_types(num,countfail,needaction) {
 5033:     var typeidx = getIndexByName('selfenroll_types_'+num);
 5034:     var count = 0;
 5035:     if (typeidx != -1) {
 5036:         if (document.$formname.elements[typeidx].length) {
 5037:             for (var k=0; k<document.$formname.elements[typeidx].length; k++) {
 5038:                 if (document.$formname.elements[typeidx][k].checked) {
 5039:                     count ++;
 5040:                 }
 5041:             }
 5042:         } else {
 5043:             if (document.$formname.elements[typeidx].checked) {
 5044:                 count ++;
 5045:             }
 5046:         }
 5047:         if (count == 0) {
 5048:             var domidx = getIndexByName('selfenroll_dom_'+num);
 5049:             if (domidx != -1) {
 5050:                 var domname = document.$formname.elements[domidx].value;
 5051:                 needaction[countfail] = domname;
 5052:                 countfail ++;
 5053:             }
 5054:         }
 5055:     }
 5056:     return countfail;
 5057: }
 5058: 
 5059: function getIndexByName(item) {
 5060:     for (var i=0;i<document.$formname.elements.length;i++) {
 5061:         if (document.$formname.elements[i].name == item) {
 5062:             return i;
 5063:         }
 5064:     }
 5065:     return -1;
 5066: }
 5067: ENDSCRIPT
 5068:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5069:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 5070: 
 5071:     my $output = '<script type="text/javascript">'."\n".
 5072:                  '// <![CDATA['."\n".
 5073:                  $setsec_js."\n".$selfenroll_js."\n".
 5074:                  '// ]]>'."\n".
 5075:                  '</script>'."\n".
 5076:                  '<h3>'.$lt->{'selfenroll'}.'</h3>'."\n";
 5077:     my ($visible,$cansetvis,$vismsgs,$visactions) = &visible_in_cat($cdom,$cnum);
 5078:     if (ref($visactions) eq 'HASH') {
 5079:         if ($visible) {
 5080:             $output .= '<p class="LC_info">'.$visactions->{'vis'}.'</p>';
 5081:         } else {
 5082:             $output .= '<p class="LC_warning">'.$visactions->{'miss'}.'</p>'
 5083:                       .$visactions->{'yous'}.
 5084:                        '<p>'.$visactions->{'gen'}.'<br />'.$visactions->{'coca'};
 5085:             if (ref($vismsgs) eq 'ARRAY') {
 5086:                 $output .= '<br />'.$visactions->{'make'}.'<ul>';
 5087:                 foreach my $item (@{$vismsgs}) {
 5088:                     $output .= '<li>'.$visactions->{$item}.'</li>';
 5089:                 }
 5090:                 $output .= '</ul>';
 5091:             }
 5092:             $output .= '</p>';
 5093:         }
 5094:     }
 5095:     $output .= '<form name="'.$formname.'" method="post" action="/adm/createuser">'."\n".
 5096:                &Apache::lonhtmlcommon::start_pick_box();
 5097:     if (ref($row) eq 'ARRAY') {
 5098:         foreach my $item (@{$row}) {
 5099:             my $title = $item; 
 5100:             if (ref($lt) eq 'HASH') {
 5101:                 $title = $lt->{$item};
 5102:             }
 5103:             $output .= &Apache::lonhtmlcommon::row_title($title);
 5104:             if ($item eq 'types') {
 5105:                 my $curr_types = $env{'course.'.$env{'request.course.id'}.'.internal.selfenroll_types'};
 5106:                 my $showdomdesc = 1;
 5107:                 my $includeempty = 1;
 5108:                 my $num = 0;
 5109:                 $output .= &Apache::loncommon::start_data_table().
 5110:                            &Apache::loncommon::start_data_table_row()
 5111:                            .'<td colspan="2"><span class="LC_nobreak"><label>'
 5112:                            .&mt('Any user in any domain:')
 5113:                            .'&nbsp;<input type="radio" name="selfenroll_all" value="1" ';
 5114:                 if ($curr_types eq '*') {
 5115:                     $output .= ' checked="checked" '; 
 5116:                 }
 5117:                 $output .= 'onchange="javascript:update_types('.
 5118:                            "'selfenroll_all'".');" />'.&mt('Yes').'</label>'.
 5119:                            '&nbsp;&nbsp;<input type="radio" name="selfenroll_all" value="0" ';
 5120:                 if ($curr_types ne '*') {
 5121:                     $output .= ' checked="checked" ';
 5122:                 }
 5123:                 $output .= ' onchange="javascript:update_types('.
 5124:                            "'selfenroll_all'".');"/>'.&mt('No').'</label></td>'.
 5125:                            &Apache::loncommon::end_data_table_row().
 5126:                            &Apache::loncommon::end_data_table().
 5127:                            &mt('Or').'<br />'.
 5128:                            &Apache::loncommon::start_data_table();
 5129:                 my %currdoms;
 5130:                 if ($curr_types eq '') {
 5131:                     $output .= &new_selfenroll_dom_row($cdom,'0');
 5132:                 } elsif ($curr_types ne '*') {
 5133:                     my @entries = split(/;/,$curr_types);
 5134:                     if (@entries > 0) {
 5135:                         foreach my $entry (@entries) {
 5136:                             my ($currdom,$typestr) = split(/:/,$entry);
 5137:                             $currdoms{$currdom} = 1;
 5138:                             my $domdesc = &Apache::lonnet::domain($currdom);
 5139:                             my @currinsttypes = split(',',$typestr);
 5140:                             $output .= &Apache::loncommon::start_data_table_row()
 5141:                                        .'<td valign="top"><span class="LC_nobreak">'.&mt('Domain:').'<b>'
 5142:                                        .'&nbsp;'.$domdesc.' ('.$currdom.')'
 5143:                                        .'</b><input type="hidden" name="selfenroll_dom_'.$num
 5144:                                        .'" value="'.$currdom.'" /></span><br />'
 5145:                                        .'<span class="LC_nobreak"><label><input type="checkbox" '
 5146:                                        .'name="selfenroll_delete" value="'.$num.'" onchange="javascript:update_types('."'selfenroll_delete','$num'".');" />'
 5147:                                        .&mt('Delete').'</label></span></td>';
 5148:                             $output .= '<td valign="top">&nbsp;&nbsp;'.&mt('User types:').'<br />'
 5149:                                        .&selfenroll_inst_types($num,$currdom,\@currinsttypes).'</td>'
 5150:                                        .&Apache::loncommon::end_data_table_row();
 5151:                             $num ++;
 5152:                         }
 5153:                     }
 5154:                 }
 5155:                 my $add_domtitle = &mt('Users in additional domain:');
 5156:                 if ($curr_types eq '*') { 
 5157:                     $add_domtitle = &mt('Users in specific domain:');
 5158:                 } elsif ($curr_types eq '') {
 5159:                     $add_domtitle = &mt('Users in other domain:');
 5160:                 }
 5161:                 $output .= &Apache::loncommon::start_data_table_row()
 5162:                            .'<td colspan="2"><span class="LC_nobreak">'.$add_domtitle.'</span><br />'
 5163:                            .&Apache::loncommon::select_dom_form('','selfenroll_newdom',
 5164:                                                                 $includeempty,$showdomdesc)
 5165:                            .'<input type="hidden" name="selfenroll_types_total" value="'.$num.'" />'
 5166:                            .'</td>'.&Apache::loncommon::end_data_table_row()
 5167:                            .&Apache::loncommon::end_data_table();
 5168:             } elsif ($item eq 'registered') {
 5169:                 my ($regon,$regoff);
 5170:                 if ($env{'course.'.$env{'request.course.id'}.'.internal.selfenroll_registered'}) {
 5171:                     $regon = ' checked="checked" ';
 5172:                     $regoff = ' ';
 5173:                 } else {
 5174:                     $regon = ' ';
 5175:                     $regoff = ' checked="checked" ';
 5176:                 }
 5177:                 $output .= '<label>'.
 5178:                            '<input type="radio" name="selfenroll_registered" value="1"'.$regon.'/>'.
 5179:                            &mt('Yes').'</label>&nbsp;&nbsp;<label>'.
 5180:                            '<input type="radio" name="selfenroll_registered" value="0"'.$regoff.'/>'.
 5181:                            &mt('No').'</label>';
 5182:             } elsif ($item eq 'enroll_dates') {
 5183:                 my $starttime = $env{'course.'.$env{'request.course.id'}.'.internal.selfenroll_start_date'};
 5184:                 my $endtime = $env{'course.'.$env{'request.course.id'}.'.internal.selfenroll_end_date'};
 5185:                 if ($starttime eq '') {
 5186:                     $starttime = $env{'course.'.$env{'request.course.id'}.'.default_enrollment_start_date'};
 5187:                 }
 5188:                 if ($endtime eq '') {
 5189:                     $endtime = $env{'course.'.$env{'request.course.id'}.'.default_enrollment_end_date'};
 5190:                 }
 5191:                 my $startform =
 5192:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_start_date',$starttime,
 5193:                                       undef,undef,undef,undef,undef,undef,undef,$nolink);
 5194:                 my $endform =
 5195:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_end_date',$endtime,
 5196:                                       undef,undef,undef,undef,undef,undef,undef,$nolink);
 5197:                 $output .= &selfenroll_date_forms($startform,$endform);
 5198:             } elsif ($item eq 'access_dates') {
 5199:                 my $starttime = $env{'course.'.$env{'request.course.id'}.'.internal.selfenroll_start_access'};
 5200:                 my $endtime = $env{'course.'.$env{'request.course.id'}.'.internal.selfenroll_end_access'};
 5201:                 if ($starttime eq '') {
 5202:                     $starttime = $env{'course.'.$env{'request.course.id'}.'.default_enrollment_start_date'};
 5203:                 }
 5204:                 if ($endtime eq '') {
 5205:                     $endtime = $env{'course.'.$env{'request.course.id'}.'.default_enrollment_end_date'};
 5206:                 }
 5207:                 my $startform =
 5208:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_start_access',$starttime,
 5209:                                       undef,undef,undef,undef,undef,undef,undef,$nolink);
 5210:                 my $endform =
 5211:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_end_access',$endtime,
 5212:                                       undef,undef,undef,undef,undef,undef,undef,$nolink);
 5213:                 $output .= &selfenroll_date_forms($startform,$endform);
 5214:             } elsif ($item eq 'section') {
 5215:                 my $currsec = $env{'course.'.$env{'request.course.id'}.'.internal.selfenroll_section'}; 
 5216:                 my %sections_count = &Apache::loncommon::get_sections($cdom,$cnum);
 5217:                 my $newsecval;
 5218:                 if ($currsec ne 'none' && $currsec ne '') {
 5219:                     if (!defined($sections_count{$currsec})) {
 5220:                         $newsecval = $currsec;
 5221:                     }
 5222:                 }
 5223:                 my $sections_select = 
 5224:                     &Apache::lonuserutils::course_sections(\%sections_count,'st',$currsec);
 5225:                 $output .= '<table class="LC_createuser">'."\n".
 5226:                            '<tr class="LC_section_row">'."\n".
 5227:                            '<td align="center">'.&mt('Existing sections')."\n".
 5228:                            '<br />'.$sections_select.'</td><td align="center">'.
 5229:                            &mt('New section').'<br />'."\n".
 5230:                            '<input type="text" name="newsec" size="15" value="'.$newsecval.'" />'."\n".
 5231:                            '<input type="hidden" name="sections" value="" />'."\n".
 5232:                            '<input type="hidden" name="state" value="done" />'."\n".
 5233:                            '</td></tr></table>'."\n";
 5234:             } elsif ($item eq 'approval') {
 5235:                 my ($appon,$appoff);
 5236:                 my $cid = $env{'request.course.id'};
 5237:                 my $currnotified = $env{'course.'.$cid.'.internal.selfenroll_notifylist'};
 5238:                 if ($env{'course.'.$cid.'.internal.selfenroll_approval'}) {
 5239:                     $appon = ' checked="checked" ';
 5240:                     $appoff = ' ';
 5241:                 } else {
 5242:                     $appon = ' ';
 5243:                     $appoff = ' checked="checked" ';
 5244:                 }
 5245:                 $output .= '<label>'.
 5246:                            '<input type="radio" name="selfenroll_approval" value="1"'.$appon.'/>'.
 5247:                            &mt('Yes').'</label>&nbsp;&nbsp;<label>'.
 5248:                            '<input type="radio" name="selfenroll_approval" value="0"'.$appoff.'/>'.
 5249:                            &mt('No').'</label>';
 5250:                 my %advhash = &Apache::lonnet::get_course_adv_roles($cid,1);
 5251:                 my (@ccs,%notified);
 5252:                 my $ccrole = 'cc';
 5253:                 if ($crstype eq 'Community') {
 5254:                     $ccrole = 'co';
 5255:                 }
 5256:                 if ($advhash{$ccrole}) {
 5257:                     @ccs = split(/,/,$advhash{$ccrole});
 5258:                 }
 5259:                 if ($currnotified) {
 5260:                     foreach my $current (split(/,/,$currnotified)) {
 5261:                         $notified{$current} = 1;
 5262:                         if (!grep(/^\Q$current\E$/,@ccs)) {
 5263:                             push(@ccs,$current);
 5264:                         }
 5265:                     }
 5266:                 }
 5267:                 if (@ccs) {
 5268:                     $output .= '<br />'.&mt('Personnel to be notified when an enrollment request needs approval, or has been approved:').'&nbsp;'.&Apache::loncommon::start_data_table().
 5269:                                &Apache::loncommon::start_data_table_row();
 5270:                     my $count = 0;
 5271:                     my $numcols = 4;
 5272:                     foreach my $cc (sort(@ccs)) {
 5273:                         my $notifyon;
 5274:                         my ($ccuname,$ccudom) = split(/:/,$cc);
 5275:                         if ($notified{$cc}) {
 5276:                             $notifyon = ' checked="checked" ';
 5277:                         }
 5278:                         if ($count && !$count%$numcols) {
 5279:                             $output .= &Apache::loncommon::end_data_table_row().
 5280:                                        &Apache::loncommon::start_data_table_row()
 5281:                         }
 5282:                         $output .= '<td><span class="LC_nobreak"><label>'.
 5283:                                    '<input type="checkbox" name="selfenroll_notify"'.$notifyon.' value="'.$cc.'" />'.
 5284:                                    &Apache::loncommon::plainname($ccuname,$ccudom).
 5285:                                    '</label></span></td>';
 5286:                         $count ++;
 5287:                     }
 5288:                     my $rem = $count%$numcols;
 5289:                     if ($rem) {
 5290:                         my $emptycols = $numcols - $rem;
 5291:                         for (my $i=0; $i<$emptycols; $i++) { 
 5292:                             $output .= '<td>&nbsp;</td>';
 5293:                         }
 5294:                     }
 5295:                     $output .= &Apache::loncommon::end_data_table_row().
 5296:                                &Apache::loncommon::end_data_table();
 5297:                 }
 5298:             } elsif ($item eq 'limit') {
 5299:                 my ($crslimit,$selflimit,$nolimit);
 5300:                 my $cid = $env{'request.course.id'};
 5301:                 my $currlim = $env{'course.'.$cid.'.internal.selfenroll_limit'};
 5302:                 my $currcap = $env{'course.'.$cid.'.internal.selfenroll_cap'};
 5303:                 $nolimit = ' checked="checked" ';
 5304:                 if ($currlim eq 'allstudents') {
 5305:                     $crslimit = ' checked="checked" ';
 5306:                     $selflimit = ' ';
 5307:                     $nolimit = ' ';
 5308:                 } elsif ($currlim eq 'selfenrolled') {
 5309:                     $crslimit = ' ';
 5310:                     $selflimit = ' checked="checked" ';
 5311:                     $nolimit = ' '; 
 5312:                 } else {
 5313:                     $crslimit = ' ';
 5314:                     $selflimit = ' ';
 5315:                 }
 5316:                 $output .= '<table><tr><td><label>'.
 5317:                            '<input type="radio" name="selfenroll_limit" value="none"'.$nolimit.'/>'.
 5318:                            &mt('No limit').'</label></td><td><label>'.
 5319:                            '<input type="radio" name="selfenroll_limit" value="allstudents"'.$crslimit.'/>'.
 5320:                            &mt('Limit by total students').'</label></td><td><label>'.
 5321:                            '<input type="radio" name="selfenroll_limit" value="selfenrolled"'.$selflimit.'/>'.
 5322:                            &mt('Limit by total self-enrolled students').
 5323:                            '</td></tr><tr>'.
 5324:                            '<td>&nbsp;</td><td colspan="2"><span class="LC_nobreak">'.
 5325:                            ('&nbsp;'x3).&mt('Maximum number allowed: ').
 5326:                            '<input type="text" name="selfenroll_cap" size = "5" value="'.$currcap.'" /></td></tr></table>';
 5327:             }
 5328:             $output .= &Apache::lonhtmlcommon::row_closure(1);
 5329:         }
 5330:     }
 5331:     $output .= &Apache::lonhtmlcommon::end_pick_box().
 5332:                '<br /><input type="button" name="selfenrollconf" value="'
 5333:                .&mt('Save').'" onclick="validate_types(this.form);" />'
 5334:                .'<input type="hidden" name="action" value="selfenroll" /></form>';
 5335:     $r->print($output);
 5336:     return;
 5337: }
 5338: 
 5339: sub visible_in_cat {
 5340:     my ($cdom,$cnum) = @_;
 5341:     my %domconf = &Apache::lonnet::get_dom('configuration',['coursecategories'],$cdom);
 5342:     my ($cathash,%settable,@vismsgs,$cansetvis);
 5343:     my %visactions = &Apache::lonlocal::texthash(
 5344:                    vis => 'Your course/community currently appears in the Course/Community Catalog for this domain.',
 5345:                    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.',
 5346:                    miss => 'Your course/community does not currently appear in the Course/Community Catalog for this domain.',
 5347:                    yous => 'You should remedy this if you plan to allow self-enrollment, otherwise students will have difficulty finding your course.',
 5348:                    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.',
 5349:                    make => 'Make any changes to self-enrollment settings below, click "Save", then take action to include the course in the Catalog:',
 5350:                    take => 'Take the following action to ensure the course appears in the Catalog:',
 5351:                    dc_unhide  => 'Ask a domain coordinator to change the "Exclude from course catalog" setting.',
 5352:                    dc_addinst => 'Ask a domain coordinator to enable display the catalog of "Official courses (with institutional codes)".',
 5353:                    dc_instcode => 'Ask a domain coordinator to assign an institutional code (if this is an official course).',
 5354:                    dc_catalog  => 'Ask a domain coordinator to enable or create at least one course category in the domain.',
 5355:                    dc_categories => 'Ask a domain coordinator to create a hierarchy of categories and sub categories for courses in the domain.',
 5356:                    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',
 5357:                    dc_addcat => 'Ask a domain coordinator to assign a category to the course.',
 5358:     );
 5359:     $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>"');
 5360:     $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>"');
 5361:     $visactions{'addcat'} = &mt('Use [_1]Categorize course[_2] to assign a category to the course.','"<a href="/adm/courseprefs?phase=display&actions=courseinfo">','</a>"');
 5362:     if (ref($domconf{'coursecategories'}) eq 'HASH') {
 5363:         if ($domconf{'coursecategories'}{'togglecats'} eq 'crs') {
 5364:             $settable{'togglecats'} = 1;
 5365:         }
 5366:         if ($domconf{'coursecategories'}{'categorize'} eq 'crs') {
 5367:             $settable{'categorize'} = 1;
 5368:         }
 5369:         $cathash = $domconf{'coursecategories'}{'cats'};
 5370:     }
 5371:     if ($settable{'togglecats'} && $settable{'categorize'}) {
 5372:         $cansetvis = &mt('You are able to both assign a course category and choose to exclude this course from the catalog.');   
 5373:     } elsif ($settable{'togglecats'}) {
 5374:         $cansetvis = &mt('You are able to choose to exclude this course from the catalog, but only a Domain Coordinator may assign a course category.'); 
 5375:     } elsif ($settable{'categorize'}) {
 5376:         $cansetvis = &mt('You may assign a course category, but only a Domain Coordinator may choose to exclude this course from the catalog.');  
 5377:     } else {
 5378:         $cansetvis = &mt('Only a Domain Coordinator may assign a course category or choose to exclude this course from the catalog.'); 
 5379:     }
 5380:      
 5381:     my %currsettings =
 5382:         &Apache::lonnet::get('environment',['hidefromcat','categories','internal.coursecode'],
 5383:                              $cdom,$cnum);
 5384:     my $visible = 0;
 5385:     if ($currsettings{'internal.coursecode'} ne '') {
 5386:         if (ref($domconf{'coursecategories'}) eq 'HASH') {
 5387:             $cathash = $domconf{'coursecategories'}{'cats'};
 5388:             if (ref($cathash) eq 'HASH') {
 5389:                 if ($cathash->{'instcode::0'} eq '') {
 5390:                     push(@vismsgs,'dc_addinst'); 
 5391:                 } else {
 5392:                     $visible = 1;
 5393:                 }
 5394:             } else {
 5395:                 $visible = 1;
 5396:             }
 5397:         } else {
 5398:             $visible = 1;
 5399:         }
 5400:     } else {
 5401:         if (ref($cathash) eq 'HASH') {
 5402:             if ($cathash->{'instcode::0'} ne '') {
 5403:                 push(@vismsgs,'dc_instcode');
 5404:             }
 5405:         } else {
 5406:             push(@vismsgs,'dc_instcode');
 5407:         }
 5408:     }
 5409:     if ($currsettings{'categories'} ne '') {
 5410:         my $cathash;
 5411:         if (ref($domconf{'coursecategories'}) eq 'HASH') {
 5412:             $cathash = $domconf{'coursecategories'}{'cats'};
 5413:             if (ref($cathash) eq 'HASH') {
 5414:                 if (keys(%{$cathash}) == 0) {
 5415:                     push(@vismsgs,'dc_catalog');
 5416:                 } elsif ((keys(%{$cathash}) == 1) && ($cathash->{'instcode::0'} ne '')) {
 5417:                     push(@vismsgs,'dc_categories');
 5418:                 } else {
 5419:                     my @currcategories = split('&',$currsettings{'categories'});
 5420:                     my $matched = 0;
 5421:                     foreach my $cat (@currcategories) {
 5422:                         if ($cathash->{$cat} ne '') {
 5423:                             $visible = 1;
 5424:                             $matched = 1;
 5425:                             last;
 5426:                         }
 5427:                     }
 5428:                     if (!$matched) {
 5429:                         if ($settable{'categorize'}) { 
 5430:                             push(@vismsgs,'chgcat');
 5431:                         } else {
 5432:                             push(@vismsgs,'dc_chgcat');
 5433:                         }
 5434:                     }
 5435:                 }
 5436:             }
 5437:         }
 5438:     } else {
 5439:         if (ref($cathash) eq 'HASH') {
 5440:             if ((keys(%{$cathash}) > 1) || 
 5441:                 (keys(%{$cathash}) == 1) && ($cathash->{'instcode::0'} eq '')) {
 5442:                 if ($settable{'categorize'}) {
 5443:                     push(@vismsgs,'addcat');
 5444:                 } else {
 5445:                     push(@vismsgs,'dc_addcat');
 5446:                 }
 5447:             }
 5448:         }
 5449:     }
 5450:     if ($currsettings{'hidefromcat'} eq 'yes') {
 5451:         $visible = 0;
 5452:         if ($settable{'togglecats'}) {
 5453:             unshift(@vismsgs,'unhide');
 5454:         } else {
 5455:             unshift(@vismsgs,'dc_unhide')
 5456:         }
 5457:     }
 5458:     return ($visible,$cansetvis,\@vismsgs,\%visactions);
 5459: }
 5460: 
 5461: sub new_selfenroll_dom_row {
 5462:     my ($newdom,$num) = @_;
 5463:     my $domdesc = &Apache::lonnet::domain($newdom);
 5464:     my $output;
 5465:     if ($domdesc ne '') {
 5466:         $output .= &Apache::loncommon::start_data_table_row()
 5467:                    .'<td valign="top"><span class="LC_nobreak">'.&mt('Domain:').'&nbsp;<b>'.$domdesc
 5468:                    .' ('.$newdom.')</b><input type="hidden" name="selfenroll_dom_'.$num
 5469:                    .'" value="'.$newdom.'" /></span><br />'
 5470:                    .'<span class="LC_nobreak"><label><input type="checkbox" '
 5471:                    .'name="selfenroll_activate" value="'.$num.'" '
 5472:                    .'onchange="javascript:update_types('
 5473:                    ."'selfenroll_activate','$num'".');" />'
 5474:                    .&mt('Activate').'</label></span></td>';
 5475:         my @currinsttypes;
 5476:         $output .= '<td>'.&mt('User types:').'<br />'
 5477:                    .&selfenroll_inst_types($num,$newdom,\@currinsttypes).'</td>'
 5478:                    .&Apache::loncommon::end_data_table_row();
 5479:     }
 5480:     return $output;
 5481: }
 5482: 
 5483: sub selfenroll_inst_types {
 5484:     my ($num,$currdom,$currinsttypes) = @_;
 5485:     my $output;
 5486:     my $numinrow = 4;
 5487:     my $count = 0;
 5488:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($currdom);
 5489:     my $othervalue = 'any';
 5490:     if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 5491:         if (keys(%{$usertypes}) > 0) {
 5492:             $othervalue = 'other';
 5493:         }
 5494:         $output .= '<table><tr>';
 5495:         foreach my $type (@{$types}) {
 5496:             if (($count > 0) && ($count%$numinrow == 0)) {
 5497:                 $output .= '</tr><tr>';
 5498:             }
 5499:             if (defined($usertypes->{$type})) {
 5500:                 my $esc_type = &escape($type);
 5501:                 $output .= '<td><span class="LC_nobreak"><label><input type = "checkbox" value="'.
 5502:                            $esc_type.'" ';
 5503:                 if (ref($currinsttypes) eq 'ARRAY') {
 5504:                     if (@{$currinsttypes} > 0) {
 5505:                         if (grep(/^any$/,@{$currinsttypes})) {
 5506:                             $output .= 'checked="checked"';
 5507:                         } elsif (grep(/^\Q$esc_type\E$/,@{$currinsttypes})) {
 5508:                             $output .= 'checked="checked"';
 5509:                         }
 5510:                     } else {
 5511:                         $output .= 'checked="checked"';
 5512:                     }
 5513:                 }
 5514:                 $output .= ' name="selfenroll_types_'.$num.'" />'.$usertypes->{$type}.'</label></span></td>';
 5515:             }
 5516:             $count ++;
 5517:         }
 5518:         if (($count > 0) && ($count%$numinrow == 0)) {
 5519:             $output .= '</tr><tr>';
 5520:         }
 5521:         $output .= '<td><span class="LC_nobreak"><label><input type = "checkbox" value="'.$othervalue.'"';
 5522:         if (ref($currinsttypes) eq 'ARRAY') {
 5523:             if (@{$currinsttypes} > 0) {
 5524:                 if (grep(/^any$/,@{$currinsttypes})) { 
 5525:                     $output .= ' checked="checked"';
 5526:                 } elsif ($othervalue eq 'other') {
 5527:                     if (grep(/^\Q$othervalue\E$/,@{$currinsttypes})) {
 5528:                         $output .= ' checked="checked"';
 5529:                     }
 5530:                 }
 5531:             } else {
 5532:                 $output .= ' checked="checked"';
 5533:             }
 5534:         } else {
 5535:             $output .= ' checked="checked"';
 5536:         }
 5537:         $output .= ' name="selfenroll_types_'.$num.'" />'.$othertitle.'</label></span></td></tr></table>';
 5538:     }
 5539:     return $output;
 5540: }
 5541: 
 5542: sub selfenroll_date_forms {
 5543:     my ($startform,$endform) = @_;
 5544:     my $output .= &Apache::lonhtmlcommon::start_pick_box()."\n".
 5545:                   &Apache::lonhtmlcommon::row_title(&mt('Start date'),
 5546:                                                     'LC_oddrow_value')."\n".
 5547:                   $startform."\n".
 5548:                   &Apache::lonhtmlcommon::row_closure(1).
 5549:                   &Apache::lonhtmlcommon::row_title(&mt('End date'),
 5550:                                                    'LC_oddrow_value')."\n".
 5551:                   $endform."\n".
 5552:                   &Apache::lonhtmlcommon::row_closure(1).
 5553:                   &Apache::lonhtmlcommon::end_pick_box();
 5554:     return $output;
 5555: }
 5556: 
 5557: sub print_userchangelogs_display {
 5558:     my ($r,$context,$permission) = @_;
 5559:     my $formname = 'rolelog';
 5560:     my ($username,$domain,$crstype,%roleslog);
 5561:     if ($context eq 'domain') {
 5562:         $domain = $env{'request.role.domain'};
 5563:         %roleslog=&Apache::lonnet::dump_dom('nohist_rolelog',$domain);
 5564:     } else {
 5565:         if ($context eq 'course') { 
 5566:             $domain = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5567:             $username = $env{'course.'.$env{'request.course.id'}.'.num'};
 5568:             $crstype = &Apache::loncommon::course_type();
 5569:             my %saveable_parameters = ('show' => 'scalar',);
 5570:             &Apache::loncommon::store_course_settings('roles_log',
 5571:                                                       \%saveable_parameters);
 5572:             &Apache::loncommon::restore_course_settings('roles_log',
 5573:                                                         \%saveable_parameters);
 5574:         } elsif ($context eq 'author') {
 5575:             $domain = $env{'user.domain'}; 
 5576:             if ($env{'request.role'} =~ m{^au\./\Q$domain\E/$}) {
 5577:                 $username = $env{'user.name'};
 5578:             } else {
 5579:                 undef($domain);
 5580:             }
 5581:         }
 5582:         if ($domain ne '' && $username ne '') { 
 5583:             %roleslog=&Apache::lonnet::dump('nohist_rolelog',$domain,$username);
 5584:         }
 5585:     }
 5586:     if ((keys(%roleslog))[0]=~/^error\:/) { undef(%roleslog); }
 5587: 
 5588:     # set defaults
 5589:     my $now = time();
 5590:     my $defstart = $now - (7*24*3600); #7 days ago 
 5591:     my %defaults = (
 5592:                      page               => '1',
 5593:                      show               => '10',
 5594:                      role               => 'any',
 5595:                      chgcontext         => 'any',
 5596:                      rolelog_start_date => $defstart,
 5597:                      rolelog_end_date   => $now,
 5598:                    );
 5599:     my $more_records = 0;
 5600: 
 5601:     # set current
 5602:     my %curr;
 5603:     foreach my $item ('show','page','role','chgcontext') {
 5604:         $curr{$item} = $env{'form.'.$item};
 5605:     }
 5606:     my ($startdate,$enddate) = 
 5607:         &Apache::lonuserutils::get_dates_from_form('rolelog_start_date','rolelog_end_date');
 5608:     $curr{'rolelog_start_date'} = $startdate;
 5609:     $curr{'rolelog_end_date'} = $enddate;
 5610:     foreach my $key (keys(%defaults)) {
 5611:         if ($curr{$key} eq '') {
 5612:             $curr{$key} = $defaults{$key};
 5613:         }
 5614:     }
 5615:     my (%whodunit,%changed,$version);
 5616:     ($version) = ($r->dir_config('lonVersion') =~ /^([\d\.]+)\-/);
 5617:     my ($minshown,$maxshown);
 5618:     $minshown = 1;
 5619:     my $count = 0;
 5620:     if ($curr{'show'} ne &mt('all')) { 
 5621:         $maxshown = $curr{'page'} * $curr{'show'};
 5622:         if ($curr{'page'} > 1) {
 5623:             $minshown = 1 + ($curr{'page'} - 1) * $curr{'show'};
 5624:         }
 5625:     }
 5626: 
 5627:     # Form Header
 5628:     $r->print('<form action="/adm/createuser" method="post" name="'.$formname.'">'.
 5629:               &role_display_filter($context,$formname,$domain,$username,\%curr,
 5630:                                    $version,$crstype));
 5631: 
 5632:     # Create navigation
 5633:     my ($nav_script,$nav_links) = &userlogdisplay_nav($formname,\%curr,$more_records);
 5634:     my $showntableheader = 0;
 5635: 
 5636:     # Table Header
 5637:     my $tableheader = 
 5638:         &Apache::loncommon::start_data_table_header_row()
 5639:        .'<th>&nbsp;</th>'
 5640:        .'<th>'.&mt('When').'</th>'
 5641:        .'<th>'.&mt('Who made the change').'</th>'
 5642:        .'<th>'.&mt('Changed User').'</th>'
 5643:        .'<th>'.&mt('Role').'</th>';
 5644: 
 5645:     if ($context eq 'course') {
 5646:         $tableheader .= '<th>'.&mt('Section').'</th>';
 5647:     }
 5648:     $tableheader .=
 5649:         '<th>'.&mt('Context').'</th>'
 5650:        .'<th>'.&mt('Start').'</th>'
 5651:        .'<th>'.&mt('End').'</th>'
 5652:        .&Apache::loncommon::end_data_table_header_row();
 5653: 
 5654:     # Display user change log data
 5655:     foreach my $id (sort { $roleslog{$b}{'exe_time'}<=>$roleslog{$a}{'exe_time'} } (keys(%roleslog))) {
 5656:         next if (($roleslog{$id}{'exe_time'} < $curr{'rolelog_start_date'}) ||
 5657:                  ($roleslog{$id}{'exe_time'} > $curr{'rolelog_end_date'}));
 5658:         if ($curr{'show'} ne &mt('all')) {
 5659:             if ($count >= $curr{'page'} * $curr{'show'}) {
 5660:                 $more_records = 1;
 5661:                 last;
 5662:             }
 5663:         }
 5664:         if ($curr{'role'} ne 'any') {
 5665:             next if ($roleslog{$id}{'logentry'}{'role'} ne $curr{'role'}); 
 5666:         }
 5667:         if ($curr{'chgcontext'} ne 'any') {
 5668:             if ($curr{'chgcontext'} eq 'selfenroll') {
 5669:                 next if (!$roleslog{$id}{'logentry'}{'selfenroll'});
 5670:             } else {
 5671:                 next if ($roleslog{$id}{'logentry'}{'context'} ne $curr{'chgcontext'});
 5672:             }
 5673:         }
 5674:         $count ++;
 5675:         next if ($count < $minshown);
 5676:         unless ($showntableheader) {
 5677:             $r->print($nav_script
 5678:                      .$nav_links
 5679:                      .&Apache::loncommon::start_data_table()
 5680:                      .$tableheader);
 5681:             $r->rflush();
 5682:             $showntableheader = 1;
 5683:         }
 5684:         if ($whodunit{$roleslog{$id}{'exe_uname'}.':'.$roleslog{$id}{'exe_udom'}} eq '') {
 5685:             $whodunit{$roleslog{$id}{'exe_uname'}.':'.$roleslog{$id}{'exe_udom'}} =
 5686:                 &Apache::loncommon::plainname($roleslog{$id}{'exe_uname'},$roleslog{$id}{'exe_udom'});
 5687:         }
 5688:         if ($changed{$roleslog{$id}{'uname'}.':'.$roleslog{$id}{'udom'}} eq '') {
 5689:             $changed{$roleslog{$id}{'uname'}.':'.$roleslog{$id}{'udom'}} =
 5690:                 &Apache::loncommon::plainname($roleslog{$id}{'uname'},$roleslog{$id}{'udom'});
 5691:         }
 5692:         my $sec = $roleslog{$id}{'logentry'}{'section'};
 5693:         if ($sec eq '') {
 5694:             $sec = &mt('None');
 5695:         }
 5696:         my ($rolestart,$roleend);
 5697:         if ($roleslog{$id}{'delflag'}) {
 5698:             $rolestart = &mt('deleted');
 5699:             $roleend = &mt('deleted');
 5700:         } else {
 5701:             $rolestart = $roleslog{$id}{'logentry'}{'start'};
 5702:             $roleend = $roleslog{$id}{'logentry'}{'end'};
 5703:             if ($rolestart eq '' || $rolestart == 0) {
 5704:                 $rolestart = &mt('No start date'); 
 5705:             } else {
 5706:                 $rolestart = &Apache::lonlocal::locallocaltime($rolestart);
 5707:             }
 5708:             if ($roleend eq '' || $roleend == 0) { 
 5709:                 $roleend = &mt('No end date');
 5710:             } else {
 5711:                 $roleend = &Apache::lonlocal::locallocaltime($roleend);
 5712:             }
 5713:         }
 5714:         my $chgcontext = $roleslog{$id}{'logentry'}{'context'};
 5715:         if ($roleslog{$id}{'logentry'}{'selfenroll'}) {
 5716:             $chgcontext = 'selfenroll';
 5717:         }
 5718:         my %lt = &rolechg_contexts($context,$crstype);
 5719:         if ($chgcontext ne '' && $lt{$chgcontext} ne '') {
 5720:             $chgcontext = $lt{$chgcontext};
 5721:         }
 5722:         $r->print(
 5723:             &Apache::loncommon::start_data_table_row()
 5724:            .'<td>'.$count.'</td>'
 5725:            .'<td>'.&Apache::lonlocal::locallocaltime($roleslog{$id}{'exe_time'}).'</td>'
 5726:            .'<td>'.$whodunit{$roleslog{$id}{'exe_uname'}.':'.$roleslog{$id}{'exe_udom'}}.'</td>'
 5727:            .'<td>'.$changed{$roleslog{$id}{'uname'}.':'.$roleslog{$id}{'udom'}}.'</td>'
 5728:            .'<td>'.&Apache::lonnet::plaintext($roleslog{$id}{'logentry'}{'role'},$crstype).'</td>');
 5729:         if ($context eq 'course') { 
 5730:             $r->print('<td>'.$sec.'</td>');
 5731:         }
 5732:         $r->print(
 5733:             '<td>'.$chgcontext.'</td>'
 5734:            .'<td>'.$rolestart.'</td>'
 5735:            .'<td>'.$roleend.'</td>'
 5736:            .&Apache::loncommon::end_data_table_row()."\n");
 5737:     }
 5738: 
 5739:     if ($showntableheader) { # Table footer, if content displayed above
 5740:         $r->print(&Apache::loncommon::end_data_table()
 5741:                  .$nav_links);
 5742:     } else { # No content displayed above
 5743:         $r->print('<p class="LC_info">'
 5744:                  .&mt('There are no records to display.')
 5745:                  .'</p>'
 5746:         );
 5747:     }
 5748: 
 5749:     # Form Footer
 5750:     $r->print( 
 5751:         '<input type="hidden" name="page" value="'.$curr{'page'}.'" />'
 5752:        .'<input type="hidden" name="action" value="changelogs" />'
 5753:        .'</form>');
 5754:     return;
 5755: }
 5756: 
 5757: sub userlogdisplay_nav {
 5758:     my ($formname,$curr,$more_records) = @_;
 5759:     my ($nav_script,$nav_links);
 5760:     if (ref($curr) eq 'HASH') {
 5761:         # Create Navigation:
 5762:         # Navigation Script
 5763:         $nav_script = <<"ENDSCRIPT";
 5764: <script type="text/javascript">
 5765: // <![CDATA[
 5766: function chgPage(caller) {
 5767:     if (caller == 'previous') {
 5768:         document.$formname.page.value --;
 5769:     }
 5770:     if (caller == 'next') {
 5771:         document.$formname.page.value ++;
 5772:     }
 5773:     document.$formname.submit();
 5774:     return;
 5775: }
 5776: // ]]>
 5777: </script>
 5778: ENDSCRIPT
 5779:         # Navigation Buttons
 5780:         $nav_links = '<p>';
 5781:         if (($curr->{'page'} > 1) || ($more_records)) {
 5782:             if ($curr->{'page'} > 1) {
 5783:                 $nav_links .= '<input type="button"'
 5784:                              .' onclick="javascript:chgPage('."'previous'".');"'
 5785:                              .' value="'.&mt('Previous [_1] changes',$curr->{'show'})
 5786:                              .'" /> ';
 5787:             }
 5788:             if ($more_records) {
 5789:                 $nav_links .= '<input type="button"'
 5790:                              .' onclick="javascript:chgPage('."'next'".');"'
 5791:                              .' value="'.&mt('Next [_1] changes',$curr->{'show'})
 5792:                              .'" />';
 5793:             }
 5794:         }
 5795:         $nav_links .= '</p>';
 5796:     }
 5797:     return ($nav_script,$nav_links);
 5798: }
 5799: 
 5800: sub role_display_filter {
 5801:     my ($context,$formname,$cdom,$cnum,$curr,$version,$crstype) = @_;
 5802:     my $lctype;
 5803:     if ($context eq 'course') {
 5804:         $lctype = lc($crstype);
 5805:     }
 5806:     my $nolink = 1;
 5807:     my $output = '<table><tr><td valign="top">'.
 5808:                  '<span class="LC_nobreak"><b>'.&mt('Changes/page:').'</b></span><br />'.
 5809:                  &Apache::lonmeta::selectbox('show',$curr->{'show'},undef,
 5810:                                               (&mt('all'),5,10,20,50,100,1000,10000)).
 5811:                  '</td><td>&nbsp;&nbsp;</td>';
 5812:     my $startform =
 5813:         &Apache::lonhtmlcommon::date_setter($formname,'rolelog_start_date',
 5814:                                             $curr->{'rolelog_start_date'},undef,
 5815:                                             undef,undef,undef,undef,undef,undef,$nolink);
 5816:     my $endform =
 5817:         &Apache::lonhtmlcommon::date_setter($formname,'rolelog_end_date',
 5818:                                             $curr->{'rolelog_end_date'},undef,
 5819:                                             undef,undef,undef,undef,undef,undef,$nolink);
 5820:     my %lt = &rolechg_contexts($context,$crstype);
 5821:     $output .= '<td valign="top"><b>'.&mt('Window during which changes occurred:').'</b><br />'.
 5822:                '<table><tr><td>'.&mt('After:').
 5823:                '</td><td>'.$startform.'</td></tr>'.
 5824:                '<tr><td>'.&mt('Before:').'</td>'.
 5825:                '<td>'.$endform.'</td></tr></table>'.
 5826:                '</td>'.
 5827:                '<td>&nbsp;&nbsp;</td>'.
 5828:                '<td valign="top"><b>'.&mt('Role:').'</b><br />'.
 5829:                '<select name="role"><option value="any"';
 5830:     if ($curr->{'role'} eq 'any') {
 5831:         $output .= ' selected="selected"';
 5832:     }
 5833:     $output .=  '>'.&mt('Any').'</option>'."\n";
 5834:     my @roles = &Apache::lonuserutils::roles_by_context($context,1,$crstype);
 5835:     foreach my $role (@roles) {
 5836:         my $plrole;
 5837:         if ($role eq 'cr') {
 5838:             $plrole = &mt('Custom Role');
 5839:         } else {
 5840:             $plrole=&Apache::lonnet::plaintext($role,$crstype);
 5841:         }
 5842:         my $selstr = '';
 5843:         if ($role eq $curr->{'role'}) {
 5844:             $selstr = ' selected="selected"';
 5845:         }
 5846:         $output .= '  <option value="'.$role.'"'.$selstr.'>'.$plrole.'</option>';
 5847:     }
 5848:     $output .= '</select></td>'.
 5849:                '<td>&nbsp;&nbsp;</td>'.
 5850:                '<td valign="top"><b>'.
 5851:                &mt('Context:').'</b><br /><select name="chgcontext">';
 5852:     my @posscontexts;
 5853:     if ($context eq 'course') {
 5854:         @posscontexts = ('any','auto','updatenow','createcourse','course','domain','selfenroll','requestcourses');
 5855:     } elsif ($context eq 'domain') {
 5856:         @posscontexts = ('any','domain','requestauthor','domconfig','server');
 5857:     } else {
 5858:         @posscontexts = ('any','author','domain');
 5859:     } 
 5860:     foreach my $chgtype (@posscontexts) {
 5861:         my $selstr = '';
 5862:         if ($curr->{'chgcontext'} eq $chgtype) {
 5863:             $selstr = ' selected="selected"';
 5864:         }
 5865:         if ($context eq 'course') {
 5866:             if (($chgtype eq 'auto') || ($chgtype eq 'updatenow')) {
 5867:                 next if (!&Apache::lonnet::auto_run($cnum,$cdom));
 5868:             }
 5869:         }
 5870:         $output .= '<option value="'.$chgtype.'"'.$selstr.'>'.$lt{$chgtype}.'</option>'."\n";
 5871:     }
 5872:     $output .= '</select></td>'
 5873:               .'</tr></table>';
 5874: 
 5875:     # Update Display button
 5876:     $output .= '<p>'
 5877:               .'<input type="submit" value="'.&mt('Update Display').'" />'
 5878:               .'</p>';
 5879: 
 5880:     # Server version info
 5881:     my $needsrev = '2.11.0';
 5882:     if ($context eq 'course') {
 5883:         $needsrev = '2.7.0';
 5884:     }
 5885:     
 5886:     $output .= '<p class="LC_info">'
 5887:               .&mt('Only changes made from servers running LON-CAPA [_1] or later are displayed.'
 5888:                   ,$needsrev);
 5889:     if ($version) {
 5890:         $output .= ' '.&mt('This LON-CAPA server is version [_1]',$version);
 5891:     }
 5892:     $output .= '</p><hr />';
 5893:     return $output;
 5894: }
 5895: 
 5896: sub rolechg_contexts {
 5897:     my ($context,$crstype) = @_;
 5898:     my %lt;
 5899:     if ($context eq 'course') {
 5900:         %lt = &Apache::lonlocal::texthash (
 5901:                                              any          => 'Any',
 5902:                                              auto         => 'Automated enrollment',
 5903:                                              updatenow    => 'Roster Update',
 5904:                                              createcourse => 'Course Creation',
 5905:                                              course       => 'User Management in course',
 5906:                                              domain       => 'User Management in domain',
 5907:                                              selfenroll   => 'Self-enrolled',
 5908:                                              requestcourses => 'Course Request',
 5909:                                          );
 5910:         if ($crstype eq 'Community') {
 5911:             $lt{'createcourse'} = &mt('Community Creation');
 5912:             $lt{'course'} = &mt('User Management in community');
 5913:             $lt{'requestcourses'} = &mt('Community Request');
 5914:         }
 5915:     } elsif ($context eq 'domain') {
 5916:         %lt = &Apache::lonlocal::texthash (
 5917:                                              any           => 'Any',
 5918:                                              domain        => 'User Management in domain',
 5919:                                              requestauthor => 'Authoring Request',
 5920:                                              server        => 'Command line script (DC role)',
 5921:                                              domconfig     => 'Self-enrolled',
 5922:                                          );
 5923:     } else {
 5924:         %lt = &Apache::lonlocal::texthash (
 5925:                                              any    => 'Any',
 5926:                                              domain => 'User Management in domain',
 5927:                                              author => 'User Management by author',
 5928:                                          );
 5929:     } 
 5930:     return %lt;
 5931: }
 5932: 
 5933: #-------------------------------------------------- functions for &phase_two
 5934: sub user_search_result {
 5935:     my ($context,$srch) = @_;
 5936:     my %allhomes;
 5937:     my %inst_matches;
 5938:     my %srch_results;
 5939:     my ($response,$currstate,$forcenewuser,$dirsrchres);
 5940:     $srch->{'srchterm'} =~ s/\s+/ /g;
 5941:     if ($srch->{'srchby'} !~ /^(uname|lastname|lastfirst)$/) {
 5942:         $response = &mt('Invalid search.');
 5943:     }
 5944:     if ($srch->{'srchin'} !~ /^(crs|dom|alc|instd)$/) {
 5945:         $response = &mt('Invalid search.');
 5946:     }
 5947:     if ($srch->{'srchtype'} !~ /^(exact|contains|begins)$/) {
 5948:         $response = &mt('Invalid search.');
 5949:     }
 5950:     if ($srch->{'srchterm'} eq '') {
 5951:         $response = &mt('You must enter a search term.');
 5952:     }
 5953:     if ($srch->{'srchterm'} =~ /^\s+$/) {
 5954:         $response = &mt('Your search term must contain more than just spaces.');
 5955:     }
 5956:     if (($srch->{'srchin'} eq 'dom') || ($srch->{'srchin'} eq 'instd')) {
 5957:         if (($srch->{'srchdomain'} eq '') || 
 5958: 	    ! (&Apache::lonnet::domain($srch->{'srchdomain'}))) {
 5959:             $response = &mt('You must specify a valid domain when searching in a domain or institutional directory.')
 5960:         }
 5961:     }
 5962:     if (($srch->{'srchin'} eq 'dom') || ($srch->{'srchin'} eq 'crs') ||
 5963:         ($srch->{'srchin'} eq 'alc')) {
 5964:         if ($srch->{'srchby'} eq 'uname') {
 5965:             my $unamecheck = $srch->{'srchterm'};
 5966:             if ($srch->{'srchtype'} eq 'contains') {
 5967:                 if ($unamecheck !~ /^\w/) {
 5968:                     $unamecheck = 'a'.$unamecheck; 
 5969:                 }
 5970:             }
 5971:             if ($unamecheck !~ /^$match_username$/) {
 5972:                 $response = &mt('You must specify a valid username. Only the following are allowed: letters numbers - . @');
 5973:             }
 5974:         }
 5975:     }
 5976:     if ($response ne '') {
 5977:         $response = '<span class="LC_warning">'.$response.'</span>';
 5978:     }
 5979:     if ($srch->{'srchin'} eq 'instd') {
 5980:         my $instd_chk = &directorysrch_check($srch);
 5981:         if ($instd_chk ne 'ok') {
 5982:             $response = '<span class="LC_warning">'.$instd_chk.'</span>'.
 5983:                         '<br />'.&mt('You may want to search in the LON-CAPA domain instead of the institutional directory.').'<br /><br />';
 5984:         }
 5985:     }
 5986:     if ($response ne '') {
 5987:         return ($currstate,$response);
 5988:     }
 5989:     if ($srch->{'srchby'} eq 'uname') {
 5990:         if (($srch->{'srchin'} eq 'dom') || ($srch->{'srchin'} eq 'crs')) {
 5991:             if ($env{'form.forcenew'}) {
 5992:                 if ($srch->{'srchdomain'} ne $env{'request.role.domain'}) {
 5993:                     my $uhome=&Apache::lonnet::homeserver($srch->{'srchterm'},$srch->{'srchdomain'});
 5994:                     if ($uhome eq 'no_host') {
 5995:                         my $domdesc = &Apache::lonnet::domain($env{'request.role.domain'},'description');
 5996:                         my $showdom = &display_domain_info($env{'request.role.domain'});
 5997:                         $response = &mt('New users can only be created in the domain to which your current role belongs - [_1].',$showdom);
 5998:                     } else {
 5999:                         $currstate = 'modify';
 6000:                     }
 6001:                 } else {
 6002:                     $currstate = 'modify';
 6003:                 }
 6004:             } else {
 6005:                 if ($srch->{'srchin'} eq 'dom') {
 6006:                     if ($srch->{'srchtype'} eq 'exact') {
 6007:                         my $uhome=&Apache::lonnet::homeserver($srch->{'srchterm'},$srch->{'srchdomain'});
 6008:                         if ($uhome eq 'no_host') {
 6009:                             ($currstate,$response,$forcenewuser) =
 6010:                                 &build_search_response($context,$srch,%srch_results);
 6011:                         } else {
 6012:                             $currstate = 'modify';
 6013:                             my $uname = $srch->{'srchterm'};
 6014:                             my $udom = $srch->{'srchdomain'};
 6015:                             $srch_results{$uname.':'.$udom} =
 6016:                                 { &Apache::lonnet::get('environment',
 6017:                                                        ['firstname',
 6018:                                                         'lastname',
 6019:                                                         'permanentemail'],
 6020:                                                          $udom,$uname)
 6021:                                 };
 6022:                         }
 6023:                     } else {
 6024:                         %srch_results = &Apache::lonnet::usersearch($srch);
 6025:                         ($currstate,$response,$forcenewuser) =
 6026:                             &build_search_response($context,$srch,%srch_results);
 6027:                     }
 6028:                 } else {
 6029:                     my $courseusers = &get_courseusers();
 6030:                     if ($srch->{'srchtype'} eq 'exact') {
 6031:                         if (exists($courseusers->{$srch->{'srchterm'}.':'.$srch->{'srchdomain'}})) {
 6032:                             $currstate = 'modify';
 6033:                         } else {
 6034:                             ($currstate,$response,$forcenewuser) =
 6035:                                 &build_search_response($context,$srch,%srch_results);
 6036:                         }
 6037:                     } else {
 6038:                         foreach my $user (keys(%$courseusers)) {
 6039:                             my ($cuname,$cudomain) = split(/:/,$user);
 6040:                             if ($cudomain eq $srch->{'srchdomain'}) {
 6041:                                 my $matched = 0;
 6042:                                 if ($srch->{'srchtype'} eq 'begins') {
 6043:                                     if ($cuname =~ /^\Q$srch->{'srchterm'}\E/i) {
 6044:                                         $matched = 1;
 6045:                                     }
 6046:                                 } else {
 6047:                                     if ($cuname =~ /\Q$srch->{'srchterm'}\E/i) {
 6048:                                         $matched = 1;
 6049:                                     }
 6050:                                 }
 6051:                                 if ($matched) {
 6052:                                     $srch_results{$user} = 
 6053: 					{&Apache::lonnet::get('environment',
 6054: 							     ['firstname',
 6055: 							      'lastname',
 6056: 							      'permanentemail'],
 6057: 							      $cudomain,$cuname)};
 6058:                                 }
 6059:                             }
 6060:                         }
 6061:                         ($currstate,$response,$forcenewuser) =
 6062:                             &build_search_response($context,$srch,%srch_results);
 6063:                     }
 6064:                 }
 6065:             }
 6066:         } elsif ($srch->{'srchin'} eq 'alc') {
 6067:             $currstate = 'query';
 6068:         } elsif ($srch->{'srchin'} eq 'instd') {
 6069:             ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query($srch);
 6070:             if ($dirsrchres eq 'ok') {
 6071:                 ($currstate,$response,$forcenewuser) = 
 6072:                     &build_search_response($context,$srch,%srch_results);
 6073:             } else {
 6074:                 my $showdom = &display_domain_info($srch->{'srchdomain'});
 6075:                 $response = '<span class="LC_warning">'.
 6076:                     &mt('Institutional directory search is not available in domain: [_1]',$showdom).
 6077:                     '</span><br />'.
 6078:                     &mt('You may want to search in the LON-CAPA domain instead of the institutional directory.').
 6079:                     '<br /><br />'; 
 6080:             }
 6081:         }
 6082:     } else {
 6083:         if ($srch->{'srchin'} eq 'dom') {
 6084:             %srch_results = &Apache::lonnet::usersearch($srch);
 6085:             ($currstate,$response,$forcenewuser) = 
 6086:                 &build_search_response($context,$srch,%srch_results); 
 6087:         } elsif ($srch->{'srchin'} eq 'crs') {
 6088:             my $courseusers = &get_courseusers(); 
 6089:             foreach my $user (keys(%$courseusers)) {
 6090:                 my ($uname,$udom) = split(/:/,$user);
 6091:                 my %names = &Apache::loncommon::getnames($uname,$udom);
 6092:                 my %emails = &Apache::loncommon::getemails($uname,$udom);
 6093:                 if ($srch->{'srchby'} eq 'lastname') {
 6094:                     if ((($srch->{'srchtype'} eq 'exact') && 
 6095:                          ($names{'lastname'} eq $srch->{'srchterm'})) || 
 6096:                         (($srch->{'srchtype'} eq 'begins') &&
 6097:                          ($names{'lastname'} =~ /^\Q$srch->{'srchterm'}\E/i)) ||
 6098:                         (($srch->{'srchtype'} eq 'contains') &&
 6099:                          ($names{'lastname'} =~ /\Q$srch->{'srchterm'}\E/i))) {
 6100:                         $srch_results{$user} = {firstname => $names{'firstname'},
 6101:                                             lastname => $names{'lastname'},
 6102:                                             permanentemail => $emails{'permanentemail'},
 6103:                                            };
 6104:                     }
 6105:                 } elsif ($srch->{'srchby'} eq 'lastfirst') {
 6106:                     my ($srchlast,$srchfirst) = split(/,/,$srch->{'srchterm'});
 6107:                     $srchlast =~ s/\s+$//;
 6108:                     $srchfirst =~ s/^\s+//;
 6109:                     if ($srch->{'srchtype'} eq 'exact') {
 6110:                         if (($names{'lastname'} eq $srchlast) &&
 6111:                             ($names{'firstname'} eq $srchfirst)) {
 6112:                             $srch_results{$user} = {firstname => $names{'firstname'},
 6113:                                                 lastname => $names{'lastname'},
 6114:                                                 permanentemail => $emails{'permanentemail'},
 6115: 
 6116:                                            };
 6117:                         }
 6118:                     } elsif ($srch->{'srchtype'} eq 'begins') {
 6119:                         if (($names{'lastname'} =~ /^\Q$srchlast\E/i) &&
 6120:                             ($names{'firstname'} =~ /^\Q$srchfirst\E/i)) {
 6121:                             $srch_results{$user} = {firstname => $names{'firstname'},
 6122:                                                 lastname => $names{'lastname'},
 6123:                                                 permanentemail => $emails{'permanentemail'},
 6124:                                                };
 6125:                         }
 6126:                     } else {
 6127:                         if (($names{'lastname'} =~ /\Q$srchlast\E/i) && 
 6128:                             ($names{'firstname'} =~ /\Q$srchfirst\E/i)) {
 6129:                             $srch_results{$user} = {firstname => $names{'firstname'},
 6130:                                                 lastname => $names{'lastname'},
 6131:                                                 permanentemail => $emails{'permanentemail'},
 6132:                                                };
 6133:                         }
 6134:                     }
 6135:                 }
 6136:             }
 6137:             ($currstate,$response,$forcenewuser) = 
 6138:                 &build_search_response($context,$srch,%srch_results); 
 6139:         } elsif ($srch->{'srchin'} eq 'alc') {
 6140:             $currstate = 'query';
 6141:         } elsif ($srch->{'srchin'} eq 'instd') {
 6142:             ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query($srch); 
 6143:             if ($dirsrchres eq 'ok') {
 6144:                 ($currstate,$response,$forcenewuser) = 
 6145:                     &build_search_response($context,$srch,%srch_results);
 6146:             } else {
 6147:                 my $showdom = &display_domain_info($srch->{'srchdomain'});                $response = '<span class="LC_warning">'.
 6148:                     &mt('Institutional directory search is not available in domain: [_1]',$showdom).
 6149:                     '</span><br />'.
 6150:                     &mt('You may want to search in the LON-CAPA domain instead of the institutional directory.').
 6151:                     '<br /><br />';
 6152:             }
 6153:         }
 6154:     }
 6155:     return ($currstate,$response,$forcenewuser,\%srch_results);
 6156: }
 6157: 
 6158: sub directorysrch_check {
 6159:     my ($srch) = @_;
 6160:     my $can_search = 0;
 6161:     my $response;
 6162:     my %dom_inst_srch = &Apache::lonnet::get_dom('configuration',
 6163:                                              ['directorysrch'],$srch->{'srchdomain'});
 6164:     my $showdom = &display_domain_info($srch->{'srchdomain'});
 6165:     if (ref($dom_inst_srch{'directorysrch'}) eq 'HASH') {
 6166:         if (!$dom_inst_srch{'directorysrch'}{'available'}) {
 6167:             return &mt('Institutional directory search is not available in domain: [_1]',$showdom); 
 6168:         }
 6169:         if ($dom_inst_srch{'directorysrch'}{'localonly'}) {
 6170:             if ($env{'request.role.domain'} ne $srch->{'srchdomain'}) {
 6171:                 return &mt('Institutional directory search in domain: [_1] is only allowed for users with a current role in the domain.',$showdom); 
 6172:             }
 6173:             my @usertypes = split(/:/,$env{'environment.inststatus'});
 6174:             if (!@usertypes) {
 6175:                 push(@usertypes,'default');
 6176:             }
 6177:             if (ref($dom_inst_srch{'directorysrch'}{'cansearch'}) eq 'ARRAY') {
 6178:                 foreach my $type (@usertypes) {
 6179:                     if (grep(/^\Q$type\E$/,@{$dom_inst_srch{'directorysrch'}{'cansearch'}})) {
 6180:                         $can_search = 1;
 6181:                         last;
 6182:                     }
 6183:                 }
 6184:             }
 6185:             if (!$can_search) {
 6186:                 my ($insttypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($srch->{'srchdomain'});
 6187:                 my @longtypes; 
 6188:                 foreach my $item (@usertypes) {
 6189:                     if (defined($insttypes->{$item})) { 
 6190:                         push (@longtypes,$insttypes->{$item});
 6191:                     } elsif ($item eq 'default') {
 6192:                         push (@longtypes,&mt('other')); 
 6193:                     }
 6194:                 }
 6195:                 my $insttype_str = join(', ',@longtypes); 
 6196:                 return &mt('Institutional directory search in domain: [_1] is not available to your user type: ',$showdom).$insttype_str;
 6197:             }
 6198:         } else {
 6199:             $can_search = 1;
 6200:         }
 6201:     } else {
 6202:         return &mt('Institutional directory search has not been configured for domain: [_1]',$showdom);
 6203:     }
 6204:     my %longtext = &Apache::lonlocal::texthash (
 6205:                        uname     => 'username',
 6206:                        lastfirst => 'last name, first name',
 6207:                        lastname  => 'last name',
 6208:                        contains  => 'contains',
 6209:                        exact     => 'as exact match to',
 6210:                        begins    => 'begins with',
 6211:                    );
 6212:     if ($can_search) {
 6213:         if (ref($dom_inst_srch{'directorysrch'}{'searchby'}) eq 'ARRAY') {
 6214:             if (!grep(/^\Q$srch->{'srchby'}\E$/,@{$dom_inst_srch{'directorysrch'}{'searchby'}})) {
 6215:                 return &mt('Institutional directory search in domain: [_1] is not available for searching by "[_2]"',$showdom,$longtext{$srch->{'srchby'}});
 6216:             }
 6217:         } else {
 6218:             return &mt('Institutional directory search in domain: [_1] is not available.', $showdom);
 6219:         }
 6220:     }
 6221:     if ($can_search) {
 6222:         if (ref($dom_inst_srch{'directorysrch'}{'searchtypes'}) eq 'ARRAY') {
 6223:             if (grep(/^\Q$srch->{'srchtype'}\E/,@{$dom_inst_srch{'directorysrch'}{'searchtypes'}})) {
 6224:                 return 'ok';
 6225:             } else {
 6226:                 return &mt('Institutional directory search in domain [_1] is not available for the requested search type: "[_2]"',$showdom,$longtext{$srch->{'srchtype'}});
 6227:             }
 6228:         } else {
 6229:             if ((($dom_inst_srch{'directorysrch'}{'searchtypes'} eq 'specify') &&
 6230:                  ($srch->{'srchtype'} eq 'exact' || $srch->{'srchtype'} eq 'contains')) ||
 6231:                 ($dom_inst_srch{'directorysrch'}{'searchtypes'} eq $srch->{'srchtype'})) {
 6232:                 return 'ok';
 6233:             } else {
 6234:                 return &mt('Institutional directory search in domain [_1] is not available for the requested search type: "[_2]"',$showdom,$longtext{$srch->{'srchtype'}});
 6235:             }
 6236:         }
 6237:     }
 6238: }
 6239: 
 6240: sub get_courseusers {
 6241:     my %advhash;
 6242:     my $classlist = &Apache::loncoursedata::get_classlist();
 6243:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles();
 6244:     foreach my $role (sort(keys(%coursepersonnel))) {
 6245:         foreach my $user (split(/\,/,$coursepersonnel{$role})) {
 6246: 	    if (!exists($classlist->{$user})) {
 6247: 		$classlist->{$user} = [];
 6248: 	    }
 6249:         }
 6250:     }
 6251:     return $classlist;
 6252: }
 6253: 
 6254: sub build_search_response {
 6255:     my ($context,$srch,%srch_results) = @_;
 6256:     my ($currstate,$response,$forcenewuser);
 6257:     my %names = (
 6258:           'uname'     => 'username',
 6259:           'lastname'  => 'last name',
 6260:           'lastfirst' => 'last name, first name',
 6261:           'crs'       => 'this course',
 6262:           'dom'       => 'LON-CAPA domain',
 6263:           'instd'     => 'the institutional directory for domain',
 6264:     );
 6265: 
 6266:     my %single = (
 6267:                    begins   => 'A match',
 6268:                    contains => 'A match',
 6269:                    exact    => 'An exact match',
 6270:                  );
 6271:     my %nomatch = (
 6272:                    begins   => 'No match',
 6273:                    contains => 'No match',
 6274:                    exact    => 'No exact match',
 6275:                   );
 6276:     if (keys(%srch_results) > 1) {
 6277:         $currstate = 'select';
 6278:     } else {
 6279:         if (keys(%srch_results) == 1) {
 6280:             $currstate = 'modify';
 6281:             $response = &mt("$single{$srch->{'srchtype'}} was found for the $names{$srch->{'srchby'}} ([_1]) in $names{$srch->{'srchin'}}.",$srch->{'srchterm'});
 6282:             if ($srch->{'srchin'} eq 'dom' || $srch->{'srchin'} eq 'instd') {
 6283:                 $response .= ': '.&display_domain_info($srch->{'srchdomain'});
 6284:             }
 6285:         } else { # Search has nothing found. Prepare message to user.
 6286:             $response = '<span class="LC_warning">';
 6287:             if ($srch->{'srchin'} eq 'dom' || $srch->{'srchin'} eq 'instd') {
 6288:                 $response .= &mt("$nomatch{$srch->{'srchtype'}} found for the $names{$srch->{'srchby'}} [_1] in $names{$srch->{'srchin'}}: [_2]",
 6289:                                  '<b>'.$srch->{'srchterm'}.'</b>',
 6290:                                  &display_domain_info($srch->{'srchdomain'}));
 6291:             } else {
 6292:                 $response .= &mt("$nomatch{$srch->{'srchtype'}} found for the $names{$srch->{'srchby'}} [_1] in $names{$srch->{'srchin'}}.",
 6293:                                  '<b>'.$srch->{'srchterm'}.'</b>');
 6294:             }
 6295:             $response .= '</span>';
 6296: 
 6297:             if ($srch->{'srchin'} ne 'alc') {
 6298:                 $forcenewuser = 1;
 6299:                 my $cansrchinst = 0; 
 6300:                 if ($srch->{'srchdomain'}) {
 6301:                     my %domconfig = &Apache::lonnet::get_dom('configuration',['directorysrch'],$srch->{'srchdomain'});
 6302:                     if (ref($domconfig{'directorysrch'}) eq 'HASH') {
 6303:                         if ($domconfig{'directorysrch'}{'available'}) {
 6304:                             $cansrchinst = 1;
 6305:                         } 
 6306:                     }
 6307:                 }
 6308:                 if ((($srch->{'srchby'} eq 'lastfirst') || 
 6309:                      ($srch->{'srchby'} eq 'lastname')) &&
 6310:                     ($srch->{'srchin'} eq 'dom')) {
 6311:                     if ($cansrchinst) {
 6312:                         $response .= '<br />'.&mt('You may want to broaden your search to a search of the institutional directory for the domain.');
 6313:                     }
 6314:                 }
 6315:                 if ($srch->{'srchin'} eq 'crs') {
 6316:                     $response .= '<br />'.&mt('You may want to broaden your search to the selected LON-CAPA domain.');
 6317:                 }
 6318:             }
 6319:             my $createdom = $env{'request.role.domain'};
 6320:             if ($context eq 'requestcrs') {
 6321:                 if ($env{'form.coursedom'} ne '') {
 6322:                     $createdom = $env{'form.coursedom'};
 6323:                 }
 6324:             }
 6325:             if (!($srch->{'srchby'} eq 'uname' && $srch->{'srchin'} eq 'dom' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchdomain'} eq $createdom)) {
 6326:                 my $cancreate =
 6327:                     &Apache::lonuserutils::can_create_user($createdom,$context);
 6328:                 my $targetdom = '<span class="LC_cusr_emph">'.$createdom.'</span>';
 6329:                 if ($cancreate) {
 6330:                     my $showdom = &display_domain_info($createdom); 
 6331:                     $response .= '<br /><br />'
 6332:                                 .'<b>'.&mt('To add a new user:').'</b>'
 6333:                                 .'<br />';
 6334:                     if ($context eq 'requestcrs') {
 6335:                         $response .= &mt("(You can only define new users in the new course's domain - [_1])",$targetdom);
 6336:                     } else {
 6337:                         $response .= &mt("(You can only create new users in your current role's domain - [_1])",$targetdom);
 6338:                     }
 6339:                     $response .='<ul><li>'
 6340:                                 .&mt("Set 'Domain/institution to search' to: [_1]",'<span class="LC_cusr_emph">'.$showdom.'</span>')
 6341:                                 .'</li><li>'
 6342:                                 .&mt("Set 'Search criteria' to: [_1]username is ..... in selected LON-CAPA domain[_2]",'<span class="LC_cusr_emph">','</span>')
 6343:                                 .'</li><li>'
 6344:                                 .&mt('Provide the proposed username')
 6345:                                 .'</li><li>'
 6346:                                 .&mt("Click 'Search'")
 6347:                                 .'</li></ul><br />';
 6348:                 } else {
 6349:                     my $helplink = ' href="javascript:helpMenu('."'display'".')"';
 6350:                     $response .= '<br /><br />';
 6351:                     if ($context eq 'requestcrs') {
 6352:                         $response .= &mt("You are not authorized to define new users in the new course's domain - [_1].",$targetdom);
 6353:                     } else {
 6354:                         $response .= &mt("You are not authorized to create new users in your current role's domain - [_1].",$targetdom);
 6355:                     }
 6356:                     $response .= '<br />'
 6357:                                  .&mt('Please contact the [_1]helpdesk[_2] if you need to create a new user.'
 6358:                                     ,' <a'.$helplink.'>'
 6359:                                     ,'</a>')
 6360:                                  .'<br /><br />';
 6361:                 }
 6362:             }
 6363:         }
 6364:     }
 6365:     return ($currstate,$response,$forcenewuser);
 6366: }
 6367: 
 6368: sub display_domain_info {
 6369:     my ($dom) = @_;
 6370:     my $output = $dom;
 6371:     if ($dom ne '') { 
 6372:         my $domdesc = &Apache::lonnet::domain($dom,'description');
 6373:         if ($domdesc ne '') {
 6374:             $output .= ' <span class="LC_cusr_emph">('.$domdesc.')</span>';
 6375:         }
 6376:     }
 6377:     return $output;
 6378: }
 6379: 
 6380: sub crumb_utilities {
 6381:     my %elements = (
 6382:        crtuser => {
 6383:            srchterm => 'text',
 6384:            srchin => 'selectbox',
 6385:            srchby => 'selectbox',
 6386:            srchtype => 'selectbox',
 6387:            srchdomain => 'selectbox',
 6388:        },
 6389:        crtusername => {
 6390:            srchterm => 'text',
 6391:            srchdomain => 'selectbox',
 6392:        },
 6393:        docustom => {
 6394:            rolename => 'selectbox',
 6395:            newrolename => 'textbox',
 6396:        },
 6397:        studentform => {
 6398:            srchterm => 'text',
 6399:            srchin => 'selectbox',
 6400:            srchby => 'selectbox',
 6401:            srchtype => 'selectbox',
 6402:            srchdomain => 'selectbox',
 6403:        },
 6404:     );
 6405: 
 6406:     my $jsback .= qq|
 6407: function backPage(formname,prevphase,prevstate) {
 6408:     if (typeof prevphase == 'undefined') {
 6409:         formname.phase.value = '';
 6410:     }
 6411:     else {  
 6412:         formname.phase.value = prevphase;
 6413:     }
 6414:     if (typeof prevstate == 'undefined') {
 6415:         formname.currstate.value = '';
 6416:     }
 6417:     else {
 6418:         formname.currstate.value = prevstate;
 6419:     }
 6420:     formname.submit();
 6421: }
 6422: |;
 6423:     return ($jsback,\%elements);
 6424: }
 6425: 
 6426: sub course_level_table {
 6427:     my (%inccourses) = @_;
 6428:     my $table = '';
 6429: # Custom Roles?
 6430: 
 6431:     my %customroles=&Apache::lonuserutils::my_custom_roles();
 6432:     my %lt=&Apache::lonlocal::texthash(
 6433:             'exs'  => "Existing sections",
 6434:             'new'  => "Define new section",
 6435:             'ssd'  => "Set Start Date",
 6436:             'sed'  => "Set End Date",
 6437:             'crl'  => "Course Level",
 6438:             'act'  => "Activate",
 6439:             'rol'  => "Role",
 6440:             'ext'  => "Extent",
 6441:             'grs'  => "Section",
 6442:             'sta'  => "Start",
 6443:             'end'  => "End"
 6444:     );
 6445: 
 6446:     foreach my $protectedcourse (sort(keys(%inccourses))) {
 6447: 	my $thiscourse=$protectedcourse;
 6448: 	$thiscourse=~s:_:/:g;
 6449: 	my %coursedata=&Apache::lonnet::coursedescription($thiscourse);
 6450:         my $isowner = &Apache::lonuserutils::is_courseowner($protectedcourse,$coursedata{'internal.courseowner'});
 6451: 	my $area=$coursedata{'description'};
 6452:         my $crstype=$coursedata{'type'};
 6453: 	if (!defined($area)) { $area=&mt('Unavailable course').': '.$protectedcourse; }
 6454: 	my ($domain,$cnum)=split(/\//,$thiscourse);
 6455:         my %sections_count;
 6456:         if (defined($env{'request.course.id'})) {
 6457:             if ($env{'request.course.id'} eq $domain.'_'.$cnum) {
 6458:                 %sections_count = 
 6459: 		    &Apache::loncommon::get_sections($domain,$cnum);
 6460:             }
 6461:         }
 6462:         my @roles = &Apache::lonuserutils::roles_by_context('course','',$crstype);
 6463: 	foreach my $role (@roles) {
 6464:             my $plrole=&Apache::lonnet::plaintext($role,$crstype);
 6465: 	    if ((&Apache::lonnet::allowed('c'.$role,$thiscourse)) ||
 6466:                 ((($role eq 'cc') || ($role eq 'co')) && ($isowner))) {
 6467:                 $table .= &course_level_row($protectedcourse,$role,$area,$domain,
 6468:                                             $plrole,\%sections_count,\%lt);
 6469:             } elsif ($env{'request.course.sec'} ne '') {
 6470:                 if (&Apache::lonnet::allowed('c'.$role,$thiscourse.'/'.
 6471:                                              $env{'request.course.sec'})) {
 6472:                     $table .= &course_level_row($protectedcourse,$role,$area,$domain,
 6473:                                                 $plrole,\%sections_count,\%lt);
 6474:                 }
 6475:             }
 6476:         }
 6477:         if (&Apache::lonnet::allowed('ccr',$thiscourse)) {
 6478:             foreach my $cust (sort(keys(%customroles))) {
 6479:                 next if ($crstype eq 'Community' && $customroles{$cust} =~ /bre\&S/);
 6480:                 my $role = 'cr_cr_'.$env{'user.domain'}.'_'.$env{'user.name'}.'_'.$cust;
 6481:                 $table .= &course_level_row($protectedcourse,$role,$area,$domain,
 6482:                                             $cust,\%sections_count,\%lt);
 6483:             }
 6484: 	}
 6485:     }
 6486:     return '' if ($table eq ''); # return nothing if there is nothing 
 6487:                                  # in the table
 6488:     my $result;
 6489:     if (!$env{'request.course.id'}) {
 6490:         $result = '<h4>'.$lt{'crl'}.'</h4>'."\n";
 6491:     }
 6492:     $result .= 
 6493: &Apache::loncommon::start_data_table().
 6494: &Apache::loncommon::start_data_table_header_row().
 6495: '<th>'.$lt{'act'}.'</th><th>'.$lt{'rol'}.'</th><th>'.$lt{'ext'}.'</th>
 6496: <th>'.$lt{'grs'}.'</th><th>'.$lt{'sta'}.'</th><th>'.$lt{'end'}.'</th>'.
 6497: &Apache::loncommon::end_data_table_header_row().
 6498: $table.
 6499: &Apache::loncommon::end_data_table();
 6500:     return $result;
 6501: }
 6502: 
 6503: sub course_level_row {
 6504:     my ($protectedcourse,$role,$area,$domain,$plrole,$sections_count,$lt) = @_;
 6505:     my $row = &Apache::loncommon::start_data_table_row().
 6506:               ' <td><input type="checkbox" name="act_'.
 6507:               $protectedcourse.'_'.$role.'" /></td>'."\n".
 6508:               ' <td>'.$plrole.'</td>'."\n".
 6509:               ' <td>'.$area.'<br />Domain: '.$domain.'</td>'."\n";
 6510:     if (($role eq 'cc') || ($role eq 'co')) {
 6511:         $row .= '<td>&nbsp;</td>';
 6512:     } elsif ($env{'request.course.sec'} ne '') {
 6513:         $row .= ' <td><input type="hidden" value="'.
 6514:                 $env{'request.course.sec'}.'" '.
 6515:                 'name="sec_'.$protectedcourse.'_'.$role.'" />'.
 6516:                 $env{'request.course.sec'}.'</td>';
 6517:     } else {
 6518:         if (ref($sections_count) eq 'HASH') {
 6519:             my $currsec = 
 6520:                 &Apache::lonuserutils::course_sections($sections_count,
 6521:                                                        $protectedcourse.'_'.$role);
 6522:             $row .= '<td><table class="LC_createuser">'."\n".
 6523:                     '<tr class="LC_section_row">'."\n".
 6524:                     ' <td valign="top">'.$lt->{'exs'}.'<br />'.
 6525:                        $currsec.'</td>'."\n".
 6526:                      ' <td>&nbsp;&nbsp;</td>'."\n".
 6527:                      ' <td valign="top">&nbsp;'.$lt->{'new'}.'<br />'.
 6528:                      '<input type="text" name="newsec_'.$protectedcourse.'_'.$role.
 6529:                      '" value="" />'.
 6530:                      '<input type="hidden" '.
 6531:                      'name="sec_'.$protectedcourse.'_'.$role.'" /></td>'."\n".
 6532:                      '</tr></table></td>'."\n";
 6533:         } else {
 6534:             $row .= '<td><input type="text" size="10" '.
 6535:                       'name="sec_'.$protectedcourse.'_'.$role.'" /></td>'."\n";
 6536:         }
 6537:     }
 6538:     $row .= <<ENDTIMEENTRY;
 6539: <td><input type="hidden" name="start_$protectedcourse\_$role" value="" />
 6540: <a href=
 6541: "javascript:pjump('date_start','Start Date $plrole',document.cu.start_$protectedcourse\_$role.value,'start_$protectedcourse\_$role','cu.pres','dateset')">$lt->{'ssd'}</a></td>
 6542: <td><input type="hidden" name="end_$protectedcourse\_$role" value="" />
 6543: <a href=
 6544: "javascript:pjump('date_end','End Date $plrole',document.cu.end_$protectedcourse\_$role.value,'end_$protectedcourse\_$role','cu.pres','dateset')">$lt->{'sed'}</a></td>
 6545: ENDTIMEENTRY
 6546:     $row .= &Apache::loncommon::end_data_table_row();
 6547:     return $row;
 6548: }
 6549: 
 6550: sub course_level_dc {
 6551:     my ($dcdom) = @_;
 6552:     my %customroles=&Apache::lonuserutils::my_custom_roles();
 6553:     my @roles = &Apache::lonuserutils::roles_by_context('course');
 6554:     my $hiddenitems = '<input type="hidden" name="dcdomain" value="'.$dcdom.'" />'.
 6555:                       '<input type="hidden" name="origdom" value="'.$dcdom.'" />'.
 6556:                       '<input type="hidden" name="dccourse" value="" />';
 6557:     my $courseform=&Apache::loncommon::selectcourse_link
 6558:             ('cu','dccourse','dcdomain','coursedesc',undef,undef,'Select','crstype');
 6559:     my $cb_jscript = &Apache::loncommon::coursebrowser_javascript($dcdom,'currsec','cu','role','Course/Community Browser');
 6560:     my %lt=&Apache::lonlocal::texthash(
 6561:                     'rol'  => "Role",
 6562:                     'grs'  => "Section",
 6563:                     'exs'  => "Existing sections",
 6564:                     'new'  => "Define new section", 
 6565:                     'sta'  => "Start",
 6566:                     'end'  => "End",
 6567:                     'ssd'  => "Set Start Date",
 6568:                     'sed'  => "Set End Date",
 6569:                     'scc'  => "Course/Community"
 6570:                   );
 6571:     my $header = '<h4>'.&mt('Course/Community Level').'</h4>'.
 6572:                  &Apache::loncommon::start_data_table().
 6573:                  &Apache::loncommon::start_data_table_header_row().
 6574:                  '<th>'.$lt{'scc'}.'</th><th>'.$lt{'rol'}.'</th><th>'.$lt{'grs'}.'</th><th>'.$lt{'sta'}.'</th><th>'.$lt{'end'}.'</th>'.
 6575:                  &Apache::loncommon::end_data_table_header_row();
 6576:     my $otheritems = &Apache::loncommon::start_data_table_row()."\n".
 6577:                      '<td><br /><span class="LC_nobreak"><input type="text" name="coursedesc" value="" onfocus="this.blur();opencrsbrowser('."'cu','dccourse','dcdomain','coursedesc','','','','crstype'".')" />'.
 6578:                      $courseform.('&nbsp;' x4).'</span></td>'."\n".
 6579:                      '<td valign><br /><select name="role">'."\n";
 6580:     foreach my $role (@roles) {
 6581:         my $plrole=&Apache::lonnet::plaintext($role);
 6582:         $otheritems .= '  <option value="'.$role.'">'.$plrole;
 6583:     }
 6584:     if ( keys %customroles > 0) {
 6585:         foreach my $cust (sort keys %customroles) {
 6586:             my $custrole='cr_cr_'.$env{'user.domain'}.
 6587:                     '_'.$env{'user.name'}.'_'.$cust;
 6588:             $otheritems .= '  <option value="'.$custrole.'">'.$cust;
 6589:         }
 6590:     }
 6591:     $otheritems .= '</select></td><td>'.
 6592:                      '<table border="0" cellspacing="0" cellpadding="0">'.
 6593:                      '<tr><td valign="top"><b>'.$lt{'exs'}.'</b><br /><select name="currsec">'.
 6594:                      ' <option value=""><--'.&mt('Pick course first').'</select></td>'.
 6595:                      '<td>&nbsp;&nbsp;</td>'.
 6596:                      '<td valign="top">&nbsp;<b>'.$lt{'new'}.'</b><br />'.
 6597:                      '<input type="text" name="newsec" value="" />'.
 6598:                      '<input type="hidden" name="section" value="" />'.
 6599:                      '<input type="hidden" name="groups" value="" />'.
 6600:                      '<input type="hidden" name="crstype" value="" /></td>'.
 6601:                      '</tr></table></td>';
 6602:     $otheritems .= <<ENDTIMEENTRY;
 6603: <td><br /><input type="hidden" name="start" value='' />
 6604: <a href=
 6605: "javascript:pjump('date_start','Start Date',document.cu.start.value,'start','cu.pres','dateset')">$lt{'ssd'}</a></td>
 6606: <td><br /><input type="hidden" name="end" value='' />
 6607: <a href=
 6608: "javascript:pjump('date_end','End Date',document.cu.end.value,'end','cu.pres','dateset')">$lt{'sed'}</a></td>
 6609: ENDTIMEENTRY
 6610:     $otheritems .= &Apache::loncommon::end_data_table_row().
 6611:                    &Apache::loncommon::end_data_table()."\n";
 6612:     return $cb_jscript.$header.$hiddenitems.$otheritems;
 6613: }
 6614: 
 6615: sub update_selfenroll_config {
 6616:     my ($r,$context,$permission) = @_;
 6617:     my ($row,$lt) = &get_selfenroll_titles();
 6618:     my %curr_groups = &Apache::longroup::coursegroups();
 6619:     my (%changes,%warning);
 6620:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 6621:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 6622:     my $curr_types;
 6623:     if (ref($row) eq 'ARRAY') {
 6624:         foreach my $item (@{$row}) {
 6625:             if ($item eq 'enroll_dates') {
 6626:                 my (%currenrolldate,%newenrolldate);
 6627:                 foreach my $type ('start','end') {
 6628:                     $currenrolldate{$type} = $env{'course.'.$env{'request.course.id'}.'.internal.selfenroll_'.$type.'_date'};
 6629:                     $newenrolldate{$type} = &Apache::lonhtmlcommon::get_date_from_form('selfenroll_'.$type.'_date');
 6630:                     if ($newenrolldate{$type} ne $currenrolldate{$type}) {
 6631:                         $changes{'internal.selfenroll_'.$type.'_date'} = $newenrolldate{$type};
 6632:                     }
 6633:                 }
 6634:             } elsif ($item eq 'access_dates') {
 6635:                 my (%currdate,%newdate);
 6636:                 foreach my $type ('start','end') {
 6637:                     $currdate{$type} = $env{'course.'.$env{'request.course.id'}.'.internal.selfenroll_'.$type.'_access'};
 6638:                     $newdate{$type} = &Apache::lonhtmlcommon::get_date_from_form('selfenroll_'.$type.'_access');
 6639:                     if ($newdate{$type} ne $currdate{$type}) {
 6640:                         $changes{'internal.selfenroll_'.$type.'_access'} = $newdate{$type};
 6641:                     }
 6642:                 }
 6643:             } elsif ($item eq 'types') {
 6644:                 $curr_types =
 6645:                     $env{'course.'.$env{'request.course.id'}.'.internal.selfenroll_'.$item};
 6646:                 if ($env{'form.selfenroll_all'}) {
 6647:                     if ($curr_types ne '*') {
 6648:                         $changes{'internal.selfenroll_types'} = '*';
 6649:                     } else {
 6650:                         next;
 6651:                     }
 6652:                 } else {
 6653:                     my %currdoms;
 6654:                     my @entries = split(/;/,$curr_types);
 6655:                     my @deletedoms = &Apache::loncommon::get_env_multiple('form.selfenroll_delete');
 6656:                     my @activations = &Apache::loncommon::get_env_multiple('form.selfenroll_activate');
 6657:                     my $newnum = 0;
 6658:                     my @latesttypes;
 6659:                     foreach my $num (@activations) {
 6660:                         my @types = &Apache::loncommon::get_env_multiple('form.selfenroll_types_'.$num);
 6661:                         if (@types > 0) {
 6662:                             @types = sort(@types);
 6663:                             my $typestr = join(',',@types);
 6664:                             my $typedom = $env{'form.selfenroll_dom_'.$num};
 6665:                             $latesttypes[$newnum] = $typedom.':'.$typestr;
 6666:                             $currdoms{$typedom} = 1;
 6667:                             $newnum ++;
 6668:                         }
 6669:                     }
 6670:                     for (my $j=0; $j<$env{'form.selfenroll_types_total'}; $j++) {
 6671:                         if ((!grep(/^$j$/,@deletedoms)) && (!grep(/^$j$/,@activations))) {
 6672:                             my @types = &Apache::loncommon::get_env_multiple('form.selfenroll_types_'.$j);
 6673:                             if (@types > 0) {
 6674:                                 @types = sort(@types);
 6675:                                 my $typestr = join(',',@types);
 6676:                                 my $typedom = $env{'form.selfenroll_dom_'.$j};
 6677:                                 $latesttypes[$newnum] = $typedom.':'.$typestr;
 6678:                                 $currdoms{$typedom} = 1;
 6679:                                 $newnum ++;
 6680:                             }
 6681:                         }
 6682:                     }
 6683:                     if ($env{'form.selfenroll_newdom'} ne '') {
 6684:                         my $typedom = $env{'form.selfenroll_newdom'};
 6685:                         if ((!defined($currdoms{$typedom})) && 
 6686:                             (&Apache::lonnet::domain($typedom) ne '')) {
 6687:                             my $typestr;
 6688:                             my ($othertitle,$usertypes,$types) = 
 6689:                                 &Apache::loncommon::sorted_inst_types($typedom);
 6690:                             my $othervalue = 'any';
 6691:                             if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 6692:                                 if (@{$types} > 0) {
 6693:                                     my @esc_types = map { &escape($_); } @{$types};
 6694:                                     $othervalue = 'other';
 6695:                                     $typestr = join(',',(@esc_types,$othervalue));
 6696:                                 }
 6697:                                 $typestr = $othervalue;
 6698:                             } else {
 6699:                                 $typestr = $othervalue;
 6700:                             } 
 6701:                             $latesttypes[$newnum] = $typedom.':'.$typestr;
 6702:                             $newnum ++ ;
 6703:                         }
 6704:                     }
 6705:                     my $selfenroll_types = join(';',@latesttypes);
 6706:                     if ($selfenroll_types ne $curr_types) {
 6707:                         $changes{'internal.selfenroll_types'} = $selfenroll_types;
 6708:                     }
 6709:                 }
 6710:             } elsif ($item eq 'limit') {
 6711:                 my $newlimit = $env{'form.selfenroll_limit'};
 6712:                 my $newcap = $env{'form.selfenroll_cap'};
 6713:                 $newcap =~s/\s+//g;
 6714:                 my $currlimit =  $env{'course.'.$env{'request.course.id'}.'.internal.selfenroll_limit'};
 6715:                 $currlimit = 'none' if ($currlimit eq '');
 6716:                 my $currcap = $env{'course.'.$env{'request.course.id'}.'.internal.selfenroll_cap'};
 6717:                 if ($newlimit ne $currlimit) {
 6718:                     if ($newlimit ne 'none') {
 6719:                         if ($newcap =~ /^\d+$/) {
 6720:                             if ($newcap ne $currcap) {
 6721:                                 $changes{'internal.selfenroll_cap'} = $newcap;
 6722:                             }
 6723:                             $changes{'internal.selfenroll_limit'} = $newlimit;
 6724:                         } else {
 6725:                             $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.'); 
 6726:                         }
 6727:                     } elsif ($currcap ne '') {
 6728:                         $changes{'internal.selfenroll_cap'} = '';
 6729:                         $changes{'internal.selfenroll_limit'} = $newlimit; 
 6730:                     }
 6731:                 } elsif ($currlimit ne 'none') {
 6732:                     if ($newcap =~ /^\d+$/) {
 6733:                         if ($newcap ne $currcap) {
 6734:                             $changes{'internal.selfenroll_cap'} = $newcap;
 6735:                         }
 6736:                     } else {
 6737:                         $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.');
 6738:                     }
 6739:                 }
 6740:             } elsif ($item eq 'approval') {
 6741:                 my (@currnotified,@newnotified);
 6742:                 my $currapproval = $env{'course.'.$env{'request.course.id'}.'.internal.selfenroll_approval'};
 6743:                 my $currnotifylist = $env{'course.'.$env{'request.course.id'}.'.internal.selfenroll_notifylist'};
 6744:                 if ($currnotifylist ne '') {
 6745:                     @currnotified = split(/,/,$currnotifylist);
 6746:                     @currnotified = sort(@currnotified);
 6747:                 }
 6748:                 my $newapproval = $env{'form.selfenroll_approval'};
 6749:                 @newnotified = &Apache::loncommon::get_env_multiple('form.selfenroll_notify');
 6750:                 @newnotified = sort(@newnotified);
 6751:                 if ($newapproval ne $currapproval) {
 6752:                     $changes{'internal.selfenroll_approval'} = $newapproval;
 6753:                     if (!$newapproval) {
 6754:                         if ($currnotifylist ne '') {
 6755:                             $changes{'internal.selfenroll_notifylist'} = '';
 6756:                         }
 6757:                     } else {
 6758:                         my @differences =  
 6759:                             &Apache::loncommon::compare_arrays(\@currnotified,\@newnotified);
 6760:                         if (@differences > 0) {
 6761:                             if (@newnotified > 0) {
 6762:                                 $changes{'internal.selfenroll_notifylist'} = join(',',@newnotified);
 6763:                             } else {
 6764:                                 $changes{'internal.selfenroll_notifylist'} = join(',',@newnotified);
 6765:                             }
 6766:                         }
 6767:                     }
 6768:                 } else {
 6769:                     my @differences = &Apache::loncommon::compare_arrays(\@currnotified,\@newnotified);
 6770:                     if (@differences > 0) {
 6771:                         if (@newnotified > 0) {
 6772:                             $changes{'internal.selfenroll_notifylist'} = join(',',@newnotified);
 6773:                         } else {
 6774:                             $changes{'internal.selfenroll_notifylist'} = '';
 6775:                         }
 6776:                     }
 6777:                 }
 6778:             } else {
 6779:                 my $curr_val = 
 6780:                     $env{'course.'.$env{'request.course.id'}.'.internal.selfenroll_'.$item};
 6781:                 my $newval = $env{'form.selfenroll_'.$item};
 6782:                 if ($item eq 'section') {
 6783:                     $newval = $env{'form.sections'};
 6784:                     if (defined($curr_groups{$newval})) {
 6785:                         $newval = $curr_val;
 6786:                         $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');
 6787:                     } elsif ($newval eq 'all') {
 6788:                         $newval = $curr_val;
 6789:                         $warning{$item} = &mt('Section for self-enrolled users unchanged, as "all" is a reserved section name.');
 6790:                     }
 6791:                     if ($newval eq '') {
 6792:                         $newval = 'none';
 6793:                     }
 6794:                 }
 6795:                 if ($newval ne $curr_val) {
 6796:                     $changes{'internal.selfenroll_'.$item} = $newval;
 6797:                 }
 6798:             }
 6799:         }
 6800:         if (keys(%warning) > 0) {
 6801:             foreach my $item (@{$row}) {
 6802:                 if (exists($warning{$item})) {
 6803:                     $r->print($warning{$item}.'<br />');
 6804:                 }
 6805:             } 
 6806:         }
 6807:         if (keys(%changes) > 0) {
 6808:             my $putresult = &Apache::lonnet::put('environment',\%changes,$cdom,$cnum);
 6809:             if ($putresult eq 'ok') {
 6810:                 if ((exists($changes{'internal.selfenroll_types'})) ||
 6811:                     (exists($changes{'internal.selfenroll_start_date'}))  ||
 6812:                     (exists($changes{'internal.selfenroll_end_date'}))) {
 6813:                     my %crsinfo = &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',
 6814:                                                                 $cnum,undef,undef,'Course');
 6815:                     my $chome = &Apache::lonnet::homeserver($cnum,$cdom);
 6816:                     if (ref($crsinfo{$env{'request.course.id'}}) eq 'HASH') {
 6817:                         foreach my $item ('selfenroll_types','selfenroll_start_date','selfenroll_end_date') {
 6818:                             if (exists($changes{'internal.'.$item})) {
 6819:                                 $crsinfo{$env{'request.course.id'}}{$item} = 
 6820:                                     $changes{'internal.'.$item};
 6821:                             }
 6822:                         }
 6823:                         my $crsputresult =
 6824:                             &Apache::lonnet::courseidput($cdom,\%crsinfo,
 6825:                                                          $chome,'notime');
 6826:                     }
 6827:                 }
 6828:                 $r->print(&mt('The following changes were made to self-enrollment settings:').'<ul>');
 6829:                 foreach my $item (@{$row}) {
 6830:                     my $title = $item;
 6831:                     if (ref($lt) eq 'HASH') {
 6832:                         $title = $lt->{$item};
 6833:                     }
 6834:                     if ($item eq 'enroll_dates') {
 6835:                         foreach my $type ('start','end') {
 6836:                             if (exists($changes{'internal.selfenroll_'.$type.'_date'})) {
 6837:                                 my $newdate = &Apache::lonlocal::locallocaltime($changes{'internal.selfenroll_'.$type.'_date'});
 6838:                                 $r->print('<li>'.&mt('[_1]: "[_2]" set to "[_3]".',
 6839:                                           $title,$type,$newdate).'</li>');
 6840:                             }
 6841:                         }
 6842:                     } elsif ($item eq 'access_dates') {
 6843:                         foreach my $type ('start','end') {
 6844:                             if (exists($changes{'internal.selfenroll_'.$type.'_access'})) {
 6845:                                 my $newdate = &Apache::lonlocal::locallocaltime($changes{'internal.selfenroll_'.$type.'_access'});
 6846:                                 $r->print('<li>'.&mt('[_1]: "[_2]" set to "[_3]".',
 6847:                                           $title,$type,$newdate).'</li>');
 6848:                             }
 6849:                         }
 6850:                     } elsif ($item eq 'limit') {
 6851:                         if ((exists($changes{'internal.selfenroll_limit'})) ||
 6852:                             (exists($changes{'internal.selfenroll_cap'}))) {
 6853:                             my ($newval,$newcap);
 6854:                             if ($changes{'internal.selfenroll_cap'} ne '') {
 6855:                                 $newcap = $changes{'internal.selfenroll_cap'}
 6856:                             } else {
 6857:                                 $newcap = $env{'course.'.$env{'request.course.id'}.'.internal.selfenroll_cap'};
 6858:                             }
 6859:                             if ($changes{'internal.selfenroll_limit'} eq 'none') {
 6860:                                 $newval = &mt('No limit');
 6861:                             } elsif ($changes{'internal.selfenroll_limit'} eq 
 6862:                                      'allstudents') {
 6863:                                 $newval = &mt('New self-enrollment no longer allowed when total (all students) reaches [_1].',$newcap);
 6864:                             } elsif ($changes{'internal.selfenroll_limit'} eq 'selfenrolled') {
 6865:                                 $newval = &mt('New self-enrollment no longer allowed when total number of self-enrolled students reaches [_1].',$newcap);
 6866:                             } else {
 6867:                                 my $currlimit =  $env{'course.'.$env{'request.course.id'}.'.internal.selfenroll_limit'};
 6868:                                 if ($currlimit eq 'allstudents') {
 6869:                                     $newval = &mt('New self-enrollment no longer allowed when total (all students) reaches [_1].',$newcap);
 6870:                                 } elsif ($changes{'internal.selfenroll_limit'} eq 'selfenrolled') {
 6871:                                     $newval =  &mt('New self-enrollment no longer allowed when total number of self-enrolled students reaches [_1].',$newcap);
 6872:                                 }
 6873:                             }
 6874:                             $r->print('<li>'.&mt('"[_1]" set to "[_2]".',$title,$newval).'</li>'."\n");
 6875:                         }
 6876:                     } elsif ($item eq 'approval') {
 6877:                         if ((exists($changes{'internal.selfenroll_approval'})) ||
 6878:                             (exists($changes{'internal.selfenroll_notifylist'}))) {
 6879:                             my ($newval,$newnotify);
 6880:                             if (exists($changes{'internal.selfenroll_notifylist'})) {
 6881:                                 $newnotify = $changes{'internal.selfenroll_notifylist'};
 6882:                             } else {   
 6883:                                 $newnotify = $env{'course.'.$env{'request.course.id'}.'.internal.selfenroll_notifylist'};
 6884:                             }
 6885:                             if ($changes{'internal.selfenroll_approval'}) {
 6886:                                 $newval = &mt('Yes');
 6887:                             } elsif ($changes{'internal.selfenroll_approval'} eq '0') {
 6888:                                 $newval = &mt('No');
 6889:                             } else {
 6890:                                 my $currapproval = 
 6891:                                     $env{'course.'.$env{'request.course.id'}.'.internal.selfenroll_approval'};
 6892:                                 if ($currapproval) {
 6893:                                     $newval = &mt('Yes');
 6894:                                 } else {
 6895:                                     $newval = &mt('No');
 6896:                                 }
 6897:                             }
 6898:                             $r->print('<li>'.&mt('"[_1]" set to "[_2]".',$title,$newval));
 6899:                             if ($newnotify) {
 6900:                                 $r->print('<br />'.&mt('The following will be notified when an enrollment request needs approval, or has been approved: [_1].',$newnotify));
 6901:                             } else {
 6902:                                 $r->print('<br />'.&mt('No notifications sent when an enrollment request needs approval, or has been approved.'));
 6903:                             }
 6904:                             $r->print('</li>'."\n");
 6905:                         }
 6906:                     } else {
 6907:                         if (exists($changes{'internal.selfenroll_'.$item})) {
 6908:                             my $newval = $changes{'internal.selfenroll_'.$item};
 6909:                             if ($item eq 'types') {
 6910:                                 if ($newval eq '') {
 6911:                                     $newval = &mt('None');
 6912:                                 } elsif ($newval eq '*') {
 6913:                                     $newval = &mt('Any user in any domain');
 6914:                                 }
 6915:                             } elsif ($item eq 'registered') {
 6916:                                 if ($newval eq '1') {
 6917:                                     $newval = &mt('Yes');
 6918:                                 } elsif ($newval eq '0') {
 6919:                                     $newval = &mt('No');
 6920:                                 }
 6921:                             }
 6922:                             $r->print('<li>'.&mt('"[_1]" set to "[_2]".',$title,$newval).'</li>'."\n");
 6923:                         }
 6924:                     }
 6925:                 }
 6926:                 $r->print('</ul>');
 6927:                 my %newenvhash;
 6928:                 foreach my $key (keys(%changes)) {
 6929:                     $newenvhash{'course.'.$env{'request.course.id'}.'.'.$key} = $changes{$key};
 6930:                 }
 6931:                 &Apache::lonnet::appenv(\%newenvhash);
 6932:             } else {
 6933:                 $r->print(&mt('An error occurred when saving changes to self-enrollment settings in this course.').'<br />'.&mt('The error was: [_1].',$putresult));
 6934:             }
 6935:         } else {
 6936:             $r->print(&mt('No changes were made to the existing self-enrollment settings in this course.'));
 6937:         }
 6938:     } else {
 6939:         $r->print(&mt('No changes were made to the existing self-enrollment settings in this course.'));
 6940:     }
 6941:     my ($visible,$cansetvis,$vismsgs,$visactions) = &visible_in_cat($cdom,$cnum);
 6942:     if (ref($visactions) eq 'HASH') {
 6943:         if (!$visible) {
 6944:             $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
 6945:                       '<br />');
 6946:             if (ref($vismsgs) eq 'ARRAY') {
 6947:                 $r->print('<br />'.$visactions->{'take'}.'<ul>');
 6948:                 foreach my $item (@{$vismsgs}) {
 6949:                     $r->print('<li>'.$visactions->{$item}.'</li>');
 6950:                 }
 6951:                 $r->print('</ul>');
 6952:             }
 6953:             $r->print($cansetvis);
 6954:         }
 6955:     } 
 6956:     return;
 6957: }
 6958: 
 6959: sub get_selfenroll_titles {
 6960:     my @row = ('types','registered','enroll_dates','access_dates','section',
 6961:                'approval','limit');
 6962:     my %lt = &Apache::lonlocal::texthash (
 6963:                 types        => 'Users allowed to self-enroll in this course',
 6964:                 registered   => 'Restrict self-enrollment to students officially registered for the course',
 6965:                 enroll_dates => 'Dates self-enrollment available',
 6966:                 access_dates => 'Course access dates assigned to self-enrolling users',
 6967:                 section      => 'Section assigned to self-enrolling users',
 6968:                 approval     => 'Self-enrollment requests need approval?',
 6969:                 limit        => 'Enrollment limit',
 6970:              );
 6971:     return (\@row,\%lt);
 6972: }
 6973: 
 6974: #---------------------------------------------- end functions for &phase_two
 6975: 
 6976: #--------------------------------- functions for &phase_two and &phase_three
 6977: 
 6978: #--------------------------end of functions for &phase_two and &phase_three
 6979: sub cid_to_cname(){
 6980:     my $courseid = shift;
 6981:     $courseid =~ s/^\///;
 6982:     $courseid =~ s/\//_/;
 6983:     return $env{'course.'.$courseid.'.description'};
 6984: }
 6985: 1;
 6986: __END__
 6987: 
 6988: 

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