File:  [LON-CAPA] / loncom / interface / loncreateuser.pm
Revision 1.311: download - view: text, annotated - select for diffs
Fri Aug 28 00:02:37 2009 UTC (14 years, 10 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Bug 5992.

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

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