File:  [LON-CAPA] / loncom / interface / loncreateuser.pm
Revision 1.338: download - view: text, annotated - select for diffs
Fri Apr 2 14:18:50 2010 UTC (14 years, 1 month ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Retrieval of default quota information needs user's institutional status.
- Code readability - add a linefeed.

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

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