File:  [LON-CAPA] / loncom / interface / loncreateuser.pm
Revision 1.310: download - view: text, annotated - select for diffs
Thu Aug 27 13:00:59 2009 UTC (14 years, 9 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Exact search by username (when used in lonpickuser.pm) requires population of the results hash.

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

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