File:  [LON-CAPA] / loncom / interface / loncreateuser.pm
Revision 1.329.2.4: download - view: text, annotated - select for diffs
Sun Sep 19 16:44:44 2010 UTC (13 years, 9 months ago) by raeburn
Branches: GCI_3
- Customization for GCI_3.
  - Usernames added for new users added via "Add/Modify a Student" must be e-mail addresses. Lower case enforced for new users.
  - Case sensitivity eliminated when searching for existing users, unless
    exact match to existing user with case used in search term.
  - Customization of wording for GCI.

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

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