File:  [LON-CAPA] / loncom / interface / loncreateuser.pm
Revision 1.350: download - view: text, annotated - select for diffs
Sun Sep 26 01:57:21 2010 UTC (13 years, 9 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- skip check for loncapa version (via "extra" hashref passed to lonnet::dump)
  when getting dump of roles for purposes other than rolesinit.

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

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