File:  [LON-CAPA] / loncom / interface / loncreateuser.pm
Revision 1.325: download - view: text, annotated - select for diffs
Thu Nov 12 16:09:10 2009 UTC (14 years, 6 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Remove unused line added in rev 1.150.

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

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