File:  [LON-CAPA] / loncom / interface / loncreateuser.pm
Revision 1.331: download - view: text, annotated - select for diffs
Tue Dec 29 20:00:26 2009 UTC (14 years, 6 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- environment.canrequest is either 0 or 1.

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

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