File:  [LON-CAPA] / loncom / interface / loncreateuser.pm
Revision 1.429: download - view: text, annotated - select for diffs
Wed Jan 18 21:00:05 2017 UTC (7 years, 5 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Ad hoc roles for helpdesk personnel.
 - Course configuration (available for editing by course owner).
   - can override domain defaults for which dh role users can use ad hoc role(s)
     in course.
   - can override domain defaults set for course-level privileges for ad hoc
     role(s).

    1: # The LearningOnline Network with CAPA
    2: # Create a user
    3: #
    4: # $Id: loncreateuser.pm,v 1.429 2017/01/18 21:00:05 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:                      localauth => 'loc',
  118:                      unix      => 'fsys',
  119:                    );
  120:     return %abv_auth;
  121: }
  122: 
  123: # ====================================================
  124: 
  125: sub user_quotas {
  126:     my ($ccuname,$ccdomain) = @_;
  127:     my %lt = &Apache::lonlocal::texthash(
  128:                    'usrt'      => "User Tools",
  129:                    'cust'      => "Custom quota",
  130:                    'chqu'      => "Change quota",
  131:     );
  132:    
  133:     my $quota_javascript = <<"END_SCRIPT";
  134: <script type="text/javascript">
  135: // <![CDATA[
  136: function quota_changes(caller,context) {
  137:     var customoff = document.getElementById('custom_'+context+'quota_off');
  138:     var customon = document.getElementById('custom_'+context+'quota_on');
  139:     var number = document.getElementById(context+'quota');
  140:     if (caller == "custom") {
  141:         if (customoff) {
  142:             if (customoff.checked) {
  143:                 number.value = "";
  144:             }
  145:         }
  146:     }
  147:     if (caller == "quota") {
  148:         if (customon) {
  149:             customon.checked = true;
  150:         }
  151:     }
  152:     return;
  153: }
  154: // ]]>
  155: </script>
  156: END_SCRIPT
  157:     my $longinsttype;
  158:     my ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($ccdomain);
  159:     my $output = $quota_javascript."\n".
  160:                  '<h3>'.$lt{'usrt'}.'</h3>'."\n".
  161:                  &Apache::loncommon::start_data_table();
  162: 
  163:     if ((&Apache::lonnet::allowed('mut',$ccdomain)) ||
  164:         (&Apache::lonnet::allowed('udp',$ccdomain))) {
  165:         $output .= &build_tools_display($ccuname,$ccdomain,'tools');
  166:     }
  167: 
  168:     my %titles = &Apache::lonlocal::texthash (
  169:                     portfolio => "Disk space allocated to user's portfolio files",
  170:                     author    => "Disk space allocated to user's Authoring Space (if role assigned)",
  171:                  );
  172:     foreach my $name ('portfolio','author') {
  173:         my ($currquota,$quotatype,$inststatus,$defquota) =
  174:             &Apache::loncommon::get_user_quota($ccuname,$ccdomain,$name);
  175:         if ($longinsttype eq '') { 
  176:             if ($inststatus ne '') {
  177:                 if ($usertypes->{$inststatus} ne '') {
  178:                     $longinsttype = $usertypes->{$inststatus};
  179:                 }
  180:             }
  181:         }
  182:         my ($showquota,$custom_on,$custom_off,$defaultinfo);
  183:         $custom_on = ' ';
  184:         $custom_off = ' checked="checked" ';
  185:         if ($quotatype eq 'custom') {
  186:             $custom_on = $custom_off;
  187:             $custom_off = ' ';
  188:             $showquota = $currquota;
  189:             if ($longinsttype eq '') {
  190:                 $defaultinfo = &mt('For this user, the default quota would be [_1]'
  191:                               .' MB.',$defquota);
  192:             } else {
  193:                 $defaultinfo = &mt("For this user, the default quota would be [_1]".
  194:                                    " MB, as determined by the user's institutional".
  195:                                    " affiliation ([_2]).",$defquota,$longinsttype);
  196:             }
  197:         } else {
  198:             if ($longinsttype eq '') {
  199:                 $defaultinfo = &mt('For this user, the default quota is [_1]'
  200:                               .' MB.',$defquota);
  201:             } else {
  202:                 $defaultinfo = &mt("For this user, the default quota of [_1]".
  203:                                    " MB, is determined by the user's institutional".
  204:                                    " affiliation ([_2]).",$defquota,$longinsttype);
  205:             }
  206:         }
  207: 
  208:         if (&Apache::lonnet::allowed('mpq',$ccdomain)) {
  209:             $output .= '<tr class="LC_info_row">'."\n".
  210:                        '    <td>'.$titles{$name}.'</td>'."\n".
  211:                        '  </tr>'."\n".
  212:                        &Apache::loncommon::start_data_table_row()."\n".
  213:                        '  <td><span class="LC_nobreak">'.
  214:                        &mt('Current quota: [_1] MB',$currquota).'</span>&nbsp;&nbsp;'.
  215:                        $defaultinfo.'</td>'."\n".
  216:                        &Apache::loncommon::end_data_table_row()."\n".
  217:                        &Apache::loncommon::start_data_table_row()."\n".
  218:                        '  <td><span class="LC_nobreak">'.$lt{'chqu'}.
  219:                        ': <label>'.
  220:                        '<input type="radio" name="custom_'.$name.'quota" id="custom_'.$name.'quota_off" '.
  221:                        'value="0" '.$custom_off.' onchange="javascript:quota_changes('."'custom','$name'".');"'.
  222:                        ' /><span class="LC_nobreak">'.
  223:                        &mt('Default ([_1] MB)',$defquota).'</span></label>&nbsp;'.
  224:                        '&nbsp;<label><input type="radio" name="custom_'.$name.'quota" id="custom_'.$name.'quota_on" '.
  225:                        'value="1" '.$custom_on.'  onchange="javascript:quota_changes('."'custom','$name'".');"'.
  226:                        ' />'.$lt{'cust'}.':</label>&nbsp;'.
  227:                        '<input type="text" name="'.$name.'quota" id="'.$name.'quota" size ="5" '.
  228:                        'value="'.$showquota.'" onfocus="javascript:quota_changes('."'quota','$name'".');"'.
  229:                        ' />&nbsp;'.&mt('MB').'</span></td>'."\n".
  230:                        &Apache::loncommon::end_data_table_row()."\n";
  231:         }
  232:     }
  233:     $output .= &Apache::loncommon::end_data_table();
  234:     return $output;
  235: }
  236: 
  237: sub build_tools_display {
  238:     my ($ccuname,$ccdomain,$context) = @_;
  239:     my (@usertools,%userenv,$output,@options,%validations,%reqtitles,%reqdisplay,
  240:         $colspan,$isadv,%domconfig);
  241:     my %lt = &Apache::lonlocal::texthash (
  242:                    'blog'       => "Personal User Blog",
  243:                    'aboutme'    => "Personal Information Page",
  244:                    'webdav'     => "WebDAV access to Authoring Spaces (if SSL and author/co-author)",
  245:                    'portfolio'  => "Personal User Portfolio",
  246:                    'avai'       => "Available",
  247:                    'cusa'       => "availability",
  248:                    'chse'       => "Change setting",
  249:                    'usde'       => "Use default",
  250:                    'uscu'       => "Use custom",
  251:                    'official'   => 'Can request creation of official courses',
  252:                    'unofficial' => 'Can request creation of unofficial courses',
  253:                    'community'  => 'Can request creation of communities',
  254:                    'textbook'   => 'Can request creation of textbook courses',
  255:                    'placement'  => 'Can request creation of placement tests',
  256:                    'requestauthor'  => 'Can request author space',
  257:     );
  258:     if ($context eq 'requestcourses') {
  259:         %userenv = &Apache::lonnet::userenvironment($ccdomain,$ccuname,
  260:                       'requestcourses.official','requestcourses.unofficial',
  261:                       'requestcourses.community','requestcourses.textbook',
  262:                       'requestcourses.placement');
  263:         @usertools = ('official','unofficial','community','textbook','placement');
  264:         @options =('norequest','approval','autolimit','validate');
  265:         %validations = &Apache::lonnet::auto_courserequest_checks($ccdomain);
  266:         %reqtitles = &courserequest_titles();
  267:         %reqdisplay = &courserequest_display();
  268:         $colspan = ' colspan="2"';
  269:         %domconfig =
  270:             &Apache::lonnet::get_dom('configuration',['requestcourses'],$ccdomain);
  271:         $isadv = &Apache::lonnet::is_advanced_user($ccdomain,$ccuname);
  272:     } elsif ($context eq 'requestauthor') {
  273:         %userenv = &Apache::lonnet::userenvironment($ccdomain,$ccuname,
  274:                                                     'requestauthor');
  275:         @usertools = ('requestauthor');
  276:         @options =('norequest','approval','automatic');
  277:         %reqtitles = &requestauthor_titles();
  278:         %reqdisplay = &requestauthor_display();
  279:         $colspan = ' colspan="2"';
  280:         %domconfig =
  281:             &Apache::lonnet::get_dom('configuration',['requestauthor'],$ccdomain);
  282:     } else {
  283:         %userenv = &Apache::lonnet::userenvironment($ccdomain,$ccuname,
  284:                           'tools.aboutme','tools.portfolio','tools.blog',
  285:                           'tools.webdav');
  286:         @usertools = ('aboutme','blog','webdav','portfolio');
  287:     }
  288:     foreach my $item (@usertools) {
  289:         my ($custom_access,$curr_access,$cust_on,$cust_off,$tool_on,$tool_off,
  290:             $currdisp,$custdisp,$custradio);
  291:         $cust_off = 'checked="checked" ';
  292:         $tool_on = 'checked="checked" ';
  293:         $curr_access =  
  294:             &Apache::lonnet::usertools_access($ccuname,$ccdomain,$item,undef,
  295:                                               $context);
  296:         if ($context eq 'requestauthor') {
  297:             if ($userenv{$context} ne '') {
  298:                 $cust_on = ' checked="checked" ';
  299:                 $cust_off = '';
  300:             }  
  301:         } elsif ($userenv{$context.'.'.$item} ne '') {
  302:             $cust_on = ' checked="checked" ';
  303:             $cust_off = '';
  304:         }
  305:         if ($context eq 'requestcourses') {
  306:             if ($userenv{$context.'.'.$item} eq '') {
  307:                 $custom_access = &mt('Currently from default setting.');
  308:             } else {
  309:                 $custom_access = &mt('Currently from custom setting.');
  310:             }
  311:         } elsif ($context eq 'requestauthor') {
  312:             if ($userenv{$context} eq '') {
  313:                 $custom_access = &mt('Currently from default setting.');
  314:             } else {
  315:                 $custom_access = &mt('Currently from custom setting.');
  316:             }
  317:         } else {
  318:             if ($userenv{$context.'.'.$item} eq '') {
  319:                 $custom_access =
  320:                     &mt('Availability determined currently from default setting.');
  321:                 if (!$curr_access) {
  322:                     $tool_off = 'checked="checked" ';
  323:                     $tool_on = '';
  324:                 }
  325:             } else {
  326:                 $custom_access =
  327:                     &mt('Availability determined currently from custom setting.');
  328:                 if ($userenv{$context.'.'.$item} == 0) {
  329:                     $tool_off = 'checked="checked" ';
  330:                     $tool_on = '';
  331:                 }
  332:             }
  333:         }
  334:         $output .= '  <tr class="LC_info_row">'."\n".
  335:                    '   <td'.$colspan.'>'.$lt{$item}.'</td>'."\n".
  336:                    '  </tr>'."\n".
  337:                    &Apache::loncommon::start_data_table_row()."\n";
  338:   
  339:         if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
  340:             my ($curroption,$currlimit);
  341:             my $envkey = $context.'.'.$item;
  342:             if ($context eq 'requestauthor') {
  343:                 $envkey = $context;
  344:             }
  345:             if ($userenv{$envkey} ne '') {
  346:                 $curroption = $userenv{$envkey};
  347:             } else {
  348:                 my (@inststatuses);
  349:                 if ($context eq 'requestcourses') {
  350:                     $curroption =
  351:                         &Apache::loncoursequeueadmin::get_processtype('course',$ccuname,$ccdomain,
  352:                                                                       $isadv,$ccdomain,$item,
  353:                                                                       \@inststatuses,\%domconfig);
  354:                 } else {
  355:                      $curroption = 
  356:                          &Apache::loncoursequeueadmin::get_processtype('requestauthor',$ccuname,$ccdomain,
  357:                                                                        $isadv,$ccdomain,undef,
  358:                                                                        \@inststatuses,\%domconfig);
  359:                 }
  360:             }
  361:             if (!$curroption) {
  362:                 $curroption = 'norequest';
  363:             }
  364:             if ($curroption =~ /^autolimit=(\d*)$/) {
  365:                 $currlimit = $1;
  366:                 if ($currlimit eq '') {
  367:                     $currdisp = &mt('Yes, automatic creation');
  368:                 } else {
  369:                     $currdisp = &mt('Yes, up to [quant,_1,request]/user',$currlimit);
  370:                 }
  371:             } else {
  372:                 $currdisp = $reqdisplay{$curroption};
  373:             }
  374:             $custdisp = '<table>';
  375:             foreach my $option (@options) {
  376:                 my $val = $option;
  377:                 if ($option eq 'norequest') {
  378:                     $val = 0;
  379:                 }
  380:                 if ($option eq 'validate') {
  381:                     my $canvalidate = 0;
  382:                     if (ref($validations{$item}) eq 'HASH') {
  383:                         if ($validations{$item}{'_custom_'}) {
  384:                             $canvalidate = 1;
  385:                         }
  386:                     }
  387:                     next if (!$canvalidate);
  388:                 }
  389:                 my $checked = '';
  390:                 if ($option eq $curroption) {
  391:                     $checked = ' checked="checked"';
  392:                 } elsif ($option eq 'autolimit') {
  393:                     if ($curroption =~ /^autolimit/) {
  394:                         $checked = ' checked="checked"';
  395:                     }
  396:                 }
  397:                 my $name = 'crsreq_'.$item;
  398:                 if ($context eq 'requestauthor') {
  399:                     $name = $item;
  400:                 }
  401:                 $custdisp .= '<tr><td><span class="LC_nobreak"><label>'.
  402:                              '<input type="radio" name="'.$name.'" '.
  403:                              'value="'.$val.'"'.$checked.' />'.
  404:                              $reqtitles{$option}.'</label>&nbsp;';
  405:                 if ($option eq 'autolimit') {
  406:                     $custdisp .= '<input type="text" name="'.$name.
  407:                                  '_limit" size="1" '.
  408:                                  'value="'.$currlimit.'" /></span><br />'.
  409:                                  $reqtitles{'unlimited'};
  410:                 } else {
  411:                     $custdisp .= '</span>';
  412:                 }
  413:                 $custdisp .= '</td></tr>';
  414:             }
  415:             $custdisp .= '</table>';
  416:             $custradio = '</span></td><td>'.&mt('Custom setting').'<br />'.$custdisp;
  417:         } else {
  418:             $currdisp = ($curr_access?&mt('Yes'):&mt('No'));
  419:             my $name = $context.'_'.$item;
  420:             if ($context eq 'requestauthor') {
  421:                 $name = $context;
  422:             }
  423:             $custdisp = '<span class="LC_nobreak"><label>'.
  424:                         '<input type="radio" name="'.$name.'"'.
  425:                         ' value="1" '.$tool_on.'/>'.&mt('On').'</label>&nbsp;<label>'.
  426:                         '<input type="radio" name="'.$name.'" value="0" '.
  427:                         $tool_off.'/>'.&mt('Off').'</label></span>';
  428:             $custradio = ('&nbsp;'x2).'--'.$lt{'cusa'}.':&nbsp;'.$custdisp.
  429:                           '</span>';
  430:         }
  431:         $output .= '  <td'.$colspan.'>'.$custom_access.('&nbsp;'x4).
  432:                    $lt{'avai'}.': '.$currdisp.'</td>'."\n".
  433:                    &Apache::loncommon::end_data_table_row()."\n";
  434:         unless (&Apache::lonnet::allowed('udp',$ccdomain)) {
  435:             $output .=
  436:                    &Apache::loncommon::start_data_table_row()."\n".
  437:                    '  <td style="vertical-align:top;"><span class="LC_nobreak">'.
  438:                    $lt{'chse'}.': <label>'.
  439:                    '<input type="radio" name="custom'.$item.'" value="0" '.
  440:                    $cust_off.'/>'.$lt{'usde'}.'</label>'.('&nbsp;' x3).
  441:                    '<label><input type="radio" name="custom'.$item.'" value="1" '.
  442:                    $cust_on.'/>'.$lt{'uscu'}.'</label>'.$custradio.'</td>'.
  443:                    &Apache::loncommon::end_data_table_row()."\n";
  444:         }
  445:     }
  446:     return $output;
  447: }
  448: 
  449: sub coursereq_externaluser {
  450:     my ($ccuname,$ccdomain,$cdom) = @_;
  451:     my (@usertools,@options,%validations,%userenv,$output);
  452:     my %lt = &Apache::lonlocal::texthash (
  453:                    'official'   => 'Can request creation of official courses',
  454:                    'unofficial' => 'Can request creation of unofficial courses',
  455:                    'community'  => 'Can request creation of communities',
  456:                    'textbook'   => 'Can request creation of textbook courses',
  457:                    'placement'  => 'Can request creation of placement tests',
  458:     );
  459: 
  460:     %userenv = &Apache::lonnet::userenvironment($ccdomain,$ccuname,
  461:                       'reqcrsotherdom.official','reqcrsotherdom.unofficial',
  462:                       'reqcrsotherdom.community','reqcrsotherdom.textbook',
  463:                       'reqcrsotherdom.placement');
  464:     @usertools = ('official','unofficial','community','textbook','placement');
  465:     @options = ('approval','validate','autolimit');
  466:     %validations = &Apache::lonnet::auto_courserequest_checks($cdom);
  467:     my $optregex = join('|',@options);
  468:     my %reqtitles = &courserequest_titles();
  469:     foreach my $item (@usertools) {
  470:         my ($curroption,$currlimit,$tooloff);
  471:         if ($userenv{'reqcrsotherdom.'.$item} ne '') {
  472:             my @curr = split(',',$userenv{'reqcrsotherdom.'.$item});
  473:             foreach my $req (@curr) {
  474:                 if ($req =~ /^\Q$cdom\E\:($optregex)=?(\d*)$/) {
  475:                     $curroption = $1;
  476:                     $currlimit = $2;
  477:                     last;
  478:                 }
  479:             }
  480:             if (!$curroption) {
  481:                 $curroption = 'norequest';
  482:                 $tooloff = ' checked="checked"';
  483:             }
  484:         } else {
  485:             $curroption = 'norequest';
  486:             $tooloff = ' checked="checked"';
  487:         }
  488:         $output.= &Apache::loncommon::start_data_table_row()."\n".
  489:                   '  <td><span class="LC_nobreak">'.$lt{$item}.': </span></td><td>'.
  490:                   '<table><tr><td valign="top">'."\n".
  491:                   '<label><input type="radio" name="reqcrsotherdom_'.$item.
  492:                   '" value=""'.$tooloff.' />'.$reqtitles{'norequest'}.
  493:                   '</label></td>';
  494:         foreach my $option (@options) {
  495:             if ($option eq 'validate') {
  496:                 my $canvalidate = 0;
  497:                 if (ref($validations{$item}) eq 'HASH') {
  498:                     if ($validations{$item}{'_external_'}) {
  499:                         $canvalidate = 1;
  500:                     }
  501:                 }
  502:                 next if (!$canvalidate);
  503:             }
  504:             my $checked = '';
  505:             if ($option eq $curroption) {
  506:                 $checked = ' checked="checked"';
  507:             }
  508:             $output .= '<td valign="top"><span class="LC_nobreak"><label>'.
  509:                        '<input type="radio" name="reqcrsotherdom_'.$item.
  510:                        '" value="'.$option.'"'.$checked.' />'.
  511:                        $reqtitles{$option}.'</label>';
  512:             if ($option eq 'autolimit') {
  513:                 $output .= '&nbsp;<input type="text" name="reqcrsotherdom_'.
  514:                            $item.'_limit" size="1" '.
  515:                            'value="'.$currlimit.'" /></span>'.
  516:                            '<br />'.$reqtitles{'unlimited'};
  517:             } else {
  518:                 $output .= '</span>';
  519:             }
  520:             $output .= '</td>';
  521:         }
  522:         $output .= '</td></tr></table></td>'."\n".
  523:                    &Apache::loncommon::end_data_table_row()."\n";
  524:     }
  525:     return $output;
  526: }
  527: 
  528: sub domainrole_req {
  529:     my ($ccuname,$ccdomain) = @_;
  530:     return '<br /><h3>'.
  531:            &mt('User Can Request Assignment of Domain Roles?').
  532:            '</h3>'."\n".
  533:            &Apache::loncommon::start_data_table().
  534:            &build_tools_display($ccuname,$ccdomain,
  535:                                 'requestauthor').
  536:            &Apache::loncommon::end_data_table();
  537: }
  538: 
  539: sub courserequest_titles {
  540:     my %titles = &Apache::lonlocal::texthash (
  541:                                    official   => 'Official',
  542:                                    unofficial => 'Unofficial',
  543:                                    community  => 'Communities',
  544:                                    textbook   => 'Textbook',
  545:                                    placement  => 'Placement Tests',
  546:                                    norequest  => 'Not allowed',
  547:                                    approval   => 'Approval by Dom. Coord.',
  548:                                    validate   => 'With validation',
  549:                                    autolimit  => 'Numerical limit',
  550:                                    unlimited  => '(blank for unlimited)',
  551:                  );
  552:     return %titles;
  553: }
  554: 
  555: sub courserequest_display {
  556:     my %titles = &Apache::lonlocal::texthash (
  557:                                    approval   => 'Yes, need approval',
  558:                                    validate   => 'Yes, with validation',
  559:                                    norequest  => 'No',
  560:    );
  561:    return %titles;
  562: }
  563: 
  564: sub requestauthor_titles {
  565:     my %titles = &Apache::lonlocal::texthash (
  566:                                    norequest  => 'Not allowed',
  567:                                    approval   => 'Approval by Dom. Coord.',
  568:                                    automatic  => 'Automatic approval',
  569:                  );
  570:     return %titles;
  571: 
  572: }
  573: 
  574: sub requestauthor_display {
  575:     my %titles = &Apache::lonlocal::texthash (
  576:                                    approval   => 'Yes, need approval',
  577:                                    automatic  => 'Yes, automatic approval',
  578:                                    norequest  => 'No',
  579:    );
  580:    return %titles;
  581: }
  582: 
  583: sub requestchange_display {
  584:     my %titles = &Apache::lonlocal::texthash (
  585:                                    approval   => "availability set to 'on' (approval required)", 
  586:                                    automatic  => "availability set to 'on' (automatic approval)",
  587:                                    norequest  => "availability set to 'off'",
  588:    );
  589:    return %titles;
  590: }
  591: 
  592: sub curr_requestauthor {
  593:     my ($uname,$udom,$isadv,$inststatuses,$domconfig) = @_;
  594:     return unless ((ref($inststatuses) eq 'ARRAY') && (ref($domconfig) eq 'HASH'));
  595:     if ($uname eq '' || $udom eq '') {
  596:         $uname = $env{'user.name'};
  597:         $udom = $env{'user.domain'};
  598:         $isadv = $env{'user.adv'};
  599:     }
  600:     my (%userenv,%settings,$val);
  601:     my @options = ('automatic','approval');
  602:     %userenv =
  603:         &Apache::lonnet::userenvironment($udom,$uname,'requestauthor','inststatus');
  604:     if ($userenv{'requestauthor'}) {
  605:         $val = $userenv{'requestauthor'};
  606:         @{$inststatuses} = ('_custom_');
  607:     } else {
  608:         my %alltasks;
  609:         if (ref($domconfig->{'requestauthor'}) eq 'HASH') {
  610:             %settings = %{$domconfig->{'requestauthor'}};
  611:             if (($isadv) && ($settings{'_LC_adv'} ne '')) {
  612:                 $val = $settings{'_LC_adv'};
  613:                 @{$inststatuses} = ('_LC_adv_');
  614:             } else {
  615:                 if ($userenv{'inststatus'} ne '') {
  616:                     @{$inststatuses} = split(',',$userenv{'inststatus'});
  617:                 } else {
  618:                     @{$inststatuses} = ('default');
  619:                 }
  620:                 foreach my $status (@{$inststatuses}) {
  621:                     if (exists($settings{$status})) {
  622:                         my $value = $settings{$status};
  623:                         next unless ($value);
  624:                         unless (exists($alltasks{$value})) {
  625:                             if (ref($alltasks{$value}) eq 'ARRAY') {
  626:                                 unless(grep(/^\Q$status\E$/,@{$alltasks{$value}})) {
  627:                                     push(@{$alltasks{$value}},$status);
  628:                                 }
  629:                             } else {
  630:                                 @{$alltasks{$value}} = ($status);
  631:                             }
  632:                         }
  633:                     }
  634:                 }
  635:                 foreach my $option (@options) {
  636:                     if ($alltasks{$option}) {
  637:                         $val = $option;
  638:                         last;
  639:                     }
  640:                 }
  641:             }
  642:         }
  643:     }
  644:     return $val;
  645: }
  646: 
  647: # =================================================================== Phase one
  648: 
  649: sub print_username_entry_form {
  650:     my ($r,$context,$response,$srch,$forcenewuser,$crstype,$brcrum) = @_;
  651:     my $defdom=$env{'request.role.domain'};
  652:     my $formtoset = 'crtuser';
  653:     if (exists($env{'form.startrolename'})) {
  654:         $formtoset = 'docustom';
  655:         $env{'form.rolename'} = $env{'form.startrolename'};
  656:     } elsif ($env{'form.origform'} eq 'crtusername') {
  657:         $formtoset =  $env{'form.origform'};
  658:     }
  659: 
  660:     my ($jsback,$elements) = &crumb_utilities();
  661: 
  662:     my $jscript = &Apache::loncommon::studentbrowser_javascript()."\n".
  663:         '<script type="text/javascript">'."\n".
  664:         '// <![CDATA['."\n".
  665:         &Apache::lonhtmlcommon::set_form_elements($elements->{$formtoset})."\n".
  666:         '// ]]>'."\n".
  667:         '</script>'."\n";
  668: 
  669:     my %existingroles=&Apache::lonuserutils::my_custom_roles($crstype);
  670:     if (($env{'form.action'} eq 'custom') && (keys(%existingroles) > 0)
  671:         && (&Apache::lonnet::allowed('mcr','/'))) {
  672:         $jscript .= &customrole_javascript();
  673:     }
  674:     my $helpitem = 'Course_Change_Privileges';
  675:     if ($env{'form.action'} eq 'custom') {
  676:         $helpitem = 'Course_Editing_Custom_Roles';
  677:     } elsif ($env{'form.action'} eq 'singlestudent') {
  678:         $helpitem = 'Course_Add_Student';
  679:     } elsif ($env{'form.action'} eq 'accesslogs') {
  680:         $helpitem = 'Domain_User_Access_Logs';
  681:     }
  682:     my %breadcrumb_text = &singleuser_breadcrumb($crstype,$context,$defdom);
  683:     if ($env{'form.action'} eq 'custom') {
  684:         push(@{$brcrum},
  685:                  {href=>"javascript:backPage(document.crtuser)",       
  686:                   text=>"Pick custom role",
  687:                   help => $helpitem,}
  688:                  );
  689:     } else {
  690:         push (@{$brcrum},
  691:                   {href => "javascript:backPage(document.crtuser)",
  692:                    text => $breadcrumb_text{'search'},
  693:                    help => $helpitem,
  694:                    faq  => 282,
  695:                    bug  => 'Instructor Interface',}
  696:                   );
  697:     }
  698:     my %loaditems = (
  699:                 'onload' => "javascript:setFormElements(document.$formtoset)",
  700:                     );
  701:     my $args = {bread_crumbs           => $brcrum,
  702:                 bread_crumbs_component => 'User Management',
  703:                 add_entries            => \%loaditems,};
  704:     $r->print(&Apache::loncommon::start_page('User Management',$jscript,$args));
  705: 
  706:     my %lt=&Apache::lonlocal::texthash(
  707:                     'srst' => 'Search for a user and enroll as a student',
  708:                     'srme' => 'Search for a user and enroll as a member',
  709:                     'srad' => 'Search for a user and modify/add user information or roles',
  710:                     'srvu' => 'Search for a user and view user information and roles',
  711:                     'srva' => 'Search for a user and view access log information',
  712: 		    'usr'  => "Username",
  713:                     'dom'  => "Domain",
  714:                     'ecrp' => "Define or Edit Custom Role",
  715:                     'nr'   => "role name",
  716:                     'cre'  => "Next",
  717: 				       );
  718: 
  719:     if ($env{'form.action'} eq 'custom') {
  720:         if (&Apache::lonnet::allowed('mcr','/')) {
  721:             my $newroletext = &mt('Define new custom role:');
  722:             $r->print('<form action="/adm/createuser" method="post" name="docustom">'.
  723:                       '<input type="hidden" name="action" value="'.$env{'form.action'}.'" />'.
  724:                       '<input type="hidden" name="phase" value="selected_custom_edit" />'.
  725:                       '<h3>'.$lt{'ecrp'}.'</h3>'.
  726:                       &Apache::loncommon::start_data_table().
  727:                       &Apache::loncommon::start_data_table_row().
  728:                       '<td>');
  729:             if (keys(%existingroles) > 0) {
  730:                 $r->print('<br /><label><input type="radio" name="customroleaction" value="new" checked="checked" onclick="setCustomFields();" /><b>'.$newroletext.'</b></label>');
  731:             } else {
  732:                 $r->print('<br /><input type="hidden" name="customroleaction" value="new" /><b>'.$newroletext.'</b>');
  733:             }
  734:             $r->print('</td><td align="center">'.$lt{'nr'}.'<br /><input type="text" size="15" name="newrolename" onfocus="setCustomAction('."'new'".');" /></td>'.
  735:                       &Apache::loncommon::end_data_table_row());
  736:             if (keys(%existingroles) > 0) {
  737:                 $r->print(&Apache::loncommon::start_data_table_row().'<td><br />'.
  738:                           '<label><input type="radio" name="customroleaction" value="edit" onclick="setCustomFields();"/><b>'.
  739:                           &mt('View/Modify existing role:').'</b></label></td>'.
  740:                           '<td align="center"><br />'.
  741:                           '<select name="rolename" onchange="setCustomAction('."'edit'".');">'.
  742:                           '<option value="" selected="selected">'.
  743:                           &mt('Select'));
  744:                 foreach my $role (sort(keys(%existingroles))) {
  745:                     $r->print('<option value="'.$role.'">'.$role.'</option>');
  746:                 }
  747:                 $r->print('</select>'.
  748:                           '</td>'.
  749:                           &Apache::loncommon::end_data_table_row());
  750:             }
  751:             $r->print(&Apache::loncommon::end_data_table().'<p>'.
  752:                       '<input name="customeditor" type="submit" value="'.
  753:                       $lt{'cre'}.'" /></p>'.
  754:                       '</form>');
  755:         }
  756:     } else {
  757:         my $actiontext = $lt{'srad'};
  758:         if ($env{'form.action'} eq 'singlestudent') {
  759:             if ($crstype eq 'Community') {
  760:                 $actiontext = $lt{'srme'};
  761:             } else {
  762:                 $actiontext = $lt{'srst'};
  763:             }
  764:         } elsif ($env{'form.action'} eq 'accesslogs') {
  765:             $actiontext = $lt{'srva'};
  766:         } elsif (($env{'form.action'} eq 'singleuser') &&
  767:                  ($context eq 'domain') && (!&Apache::lonnet::allowed('mau',$defdom))) {
  768:             $actiontext = $lt{'srvu'};
  769:         }
  770:         $r->print("<h3>$actiontext</h3>");
  771:         if ($env{'form.origform'} ne 'crtusername') {
  772:             if ($response) {
  773:                $r->print("\n<div>$response</div>".
  774:                          '<br clear="all" />');
  775:             }
  776:         }
  777:         $r->print(&entry_form($defdom,$srch,$forcenewuser,$context,$response,$crstype,1));
  778:     }
  779: }
  780: 
  781: sub customrole_javascript {
  782:     my $js = <<"END";
  783: <script type="text/javascript">
  784: // <![CDATA[
  785: 
  786: function setCustomFields() {
  787:     if (document.docustom.customroleaction.length > 0) {
  788:         for (var i=0; i<document.docustom.customroleaction.length; i++) {
  789:             if (document.docustom.customroleaction[i].checked) {
  790:                 if (document.docustom.customroleaction[i].value == 'new') {
  791:                     document.docustom.rolename.selectedIndex = 0;
  792:                 } else {
  793:                     document.docustom.newrolename.value = '';
  794:                 }
  795:             }
  796:         }
  797:     }
  798:     return;
  799: }
  800: 
  801: function setCustomAction(caller) {
  802:     if (document.docustom.customroleaction.length > 0) {
  803:         for (var i=0; i<document.docustom.customroleaction.length; i++) {
  804:             if (document.docustom.customroleaction[i].value == caller) {
  805:                 document.docustom.customroleaction[i].checked = true;
  806:             }
  807:         }
  808:     }
  809:     setCustomFields();
  810:     return;
  811: }
  812: 
  813: // ]]>
  814: </script>
  815: END
  816:     return $js;
  817: }
  818: 
  819: sub entry_form {
  820:     my ($dom,$srch,$forcenewuser,$context,$responsemsg,$crstype,$fixeddom) = @_;
  821:     my ($usertype,$inexact);
  822:     if (ref($srch) eq 'HASH') {
  823:         if (($srch->{'srchin'} eq 'dom') &&
  824:             ($srch->{'srchby'} eq 'uname') &&
  825:             ($srch->{'srchtype'} eq 'exact') &&
  826:             ($srch->{'srchdomain'} ne '') &&
  827:             ($srch->{'srchterm'} ne '')) {
  828:             my (%curr_rules,%got_rules);
  829:             my ($rules,$ruleorder) =
  830:                 &Apache::lonnet::inst_userrules($srch->{'srchdomain'},'username');
  831:             $usertype = &Apache::lonuserutils::check_usertype($srch->{'srchdomain'},$srch->{'srchterm'},$rules,\%curr_rules,\%got_rules);
  832:         } else {
  833:             $inexact = 1;
  834:         }
  835:     }
  836:     my $cancreate =
  837:         &Apache::lonuserutils::can_create_user($dom,$context,$usertype);
  838:     my ($userpicker,$cansearch) = 
  839:        &Apache::loncommon::user_picker($dom,$srch,$forcenewuser,
  840:                                        'document.crtuser',$cancreate,$usertype,$context,$fixeddom);
  841:     my $srchbutton = &mt('Search');
  842:     if ($env{'form.action'} eq 'singlestudent') {
  843:         $srchbutton = &mt('Search and Enroll');
  844:     } elsif ($env{'form.action'} eq 'accesslogs') {
  845:         $srchbutton = &mt('Search');
  846:     } elsif ($cancreate && $responsemsg ne '' && $inexact) {
  847:         $srchbutton = &mt('Search or Add New User');
  848:     }
  849:     my $output;
  850:     if ($cansearch) {
  851:         $output = <<"ENDBLOCK";
  852: <form action="/adm/createuser" method="post" name="crtuser">
  853: <input type="hidden" name="action" value="$env{'form.action'}" />
  854: <input type="hidden" name="phase" value="get_user_info" />
  855: $userpicker
  856: <input name="userrole" type="button" value="$srchbutton" onclick="javascript:validateEntry(document.crtuser)" />
  857: </form>
  858: ENDBLOCK
  859:     } else {
  860:         $output = '<p>'.$userpicker.'</p>';
  861:     }
  862:     if (($env{'form.phase'} eq '') && ($env{'form.action'} ne 'accesslogs') &&
  863:         (!(($env{'form.action'} eq 'singleuser') && ($context eq 'domain') && 
  864:         (!&Apache::lonnet::allowed('mau',$env{'request.role.domain'}))))) {
  865:         my $defdom=$env{'request.role.domain'};
  866:         my $domform = &Apache::loncommon::select_dom_form($defdom,'srchdomain');
  867:         my %lt=&Apache::lonlocal::texthash(
  868:                   'enro' => 'Enroll one student',
  869:                   'enrm' => 'Enroll one member',
  870:                   'admo' => 'Add/modify a single user',
  871:                   'crea' => 'create new user if required',
  872:                   'uskn' => "username is known",
  873:                   'crnu' => 'Create a new user',
  874:                   'usr'  => 'Username',
  875:                   'dom'  => 'in domain',
  876:                   'enrl' => 'Enroll',
  877:                   'cram'  => 'Create/Modify user',
  878:         );
  879:         my $sellink=&Apache::loncommon::selectstudent_link('crtusername','srchterm','srchdomain');
  880:         my ($title,$buttontext,$showresponse);
  881:         if ($env{'form.action'} eq 'singlestudent') {
  882:             if ($crstype eq 'Community') {
  883:                 $title = $lt{'enrm'};
  884:             } else {
  885:                 $title = $lt{'enro'};
  886:             }
  887:             $buttontext = $lt{'enrl'};
  888:         } else {
  889:             $title = $lt{'admo'};
  890:             $buttontext = $lt{'cram'};
  891:         }
  892:         if ($cancreate) {
  893:             $title .= ' <span class="LC_cusr_subheading">('.$lt{'crea'}.')</span>';
  894:         } else {
  895:             $title .= ' <span class="LC_cusr_subheading">('.$lt{'uskn'}.')</span>';
  896:         }
  897:         if ($env{'form.origform'} eq 'crtusername') {
  898:             $showresponse = $responsemsg;
  899:         }
  900:         $output .= <<"ENDDOCUMENT";
  901: <br />
  902: <form action="/adm/createuser" method="post" name="crtusername">
  903: <input type="hidden" name="action" value="$env{'form.action'}" />
  904: <input type="hidden" name="phase" value="createnewuser" />
  905: <input type="hidden" name="srchtype" value="exact" />
  906: <input type="hidden" name="srchby" value="uname" />
  907: <input type="hidden" name="srchin" value="dom" />
  908: <input type="hidden" name="forcenewuser" value="1" />
  909: <input type="hidden" name="origform" value="crtusername" />
  910: <h3>$title</h3>
  911: $showresponse
  912: <table>
  913:  <tr>
  914:   <td>$lt{'usr'}:</td>
  915:   <td><input type="text" size="15" name="srchterm" /></td>
  916:   <td>&nbsp;$lt{'dom'}:</td><td>$domform</td>
  917:   <td>&nbsp;$sellink&nbsp;</td>
  918:   <td>&nbsp;<input name="userrole" type="submit" value="$buttontext" /></td>
  919:  </tr>
  920: </table>
  921: </form>
  922: ENDDOCUMENT
  923:     }
  924:     return $output;
  925: }
  926: 
  927: sub user_modification_js {
  928:     my ($pjump_def,$dc_setcourse_code,$nondc_setsection_code,$groupslist)=@_;
  929:     
  930:     return <<END;
  931: <script type="text/javascript" language="Javascript">
  932: // <![CDATA[
  933: 
  934:     $pjump_def
  935:     $dc_setcourse_code
  936: 
  937:     function dateset() {
  938:         eval("document.cu."+document.cu.pres_marker.value+
  939:             ".value=document.cu.pres_value.value");
  940:         modalWindow.close();
  941:     }
  942: 
  943:     $nondc_setsection_code
  944: // ]]>
  945: </script>
  946: END
  947: }
  948: 
  949: # =================================================================== Phase two
  950: sub print_user_selection_page {
  951:     my ($r,$response,$srch,$srch_results,$srcharray,$context,$opener_elements,$crstype,$brcrum) = @_;
  952:     my @fields = ('username','domain','lastname','firstname','permanentemail');
  953:     my $sortby = $env{'form.sortby'};
  954: 
  955:     if (!grep(/^\Q$sortby\E$/,@fields)) {
  956:         $sortby = 'lastname';
  957:     }
  958: 
  959:     my ($jsback,$elements) = &crumb_utilities();
  960: 
  961:     my $jscript = (<<ENDSCRIPT);
  962: <script type="text/javascript">
  963: // <![CDATA[
  964: function pickuser(uname,udom) {
  965:     document.usersrchform.seluname.value=uname;
  966:     document.usersrchform.seludom.value=udom;
  967:     document.usersrchform.phase.value="userpicked";
  968:     document.usersrchform.submit();
  969: }
  970: 
  971: $jsback
  972: // ]]>
  973: </script>
  974: ENDSCRIPT
  975: 
  976:     my %lt=&Apache::lonlocal::texthash(
  977:                                        'usrch'          => "User Search to add/modify roles",
  978:                                        'stusrch'        => "User Search to enroll student",
  979:                                        'memsrch'        => "User Search to enroll member",
  980:                                        'srcva'          => "Search for a user and view access log information",
  981:                                        'usrvu'          => "User Search to view user roles",
  982:                                        'usel'           => "Select a user to add/modify roles",
  983:                                        'suvr'           => "Select a user to view roles",
  984:                                        'stusel'         => "Select a user to enroll as a student",
  985:                                        'memsel'         => "Select a user to enroll as a member",
  986:                                        'vacsel'         => "Select a user to view access log",
  987:                                        'username'       => "username",
  988:                                        'domain'         => "domain",
  989:                                        'lastname'       => "last name",
  990:                                        'firstname'      => "first name",
  991:                                        'permanentemail' => "permanent e-mail",
  992:                                       );
  993:     if ($context eq 'requestcrs') {
  994:         $r->print('<div>');
  995:     } else {
  996:         my %breadcrumb_text = &singleuser_breadcrumb($crstype,$context,$srch->{'srchdomain'});
  997:         my $helpitem;
  998:         if ($env{'form.action'} eq 'singleuser') {
  999:             $helpitem = 'Course_Change_Privileges';
 1000:         } elsif ($env{'form.action'} eq 'singlestudent') {
 1001:             $helpitem = 'Course_Add_Student';
 1002:         }
 1003:         push (@{$brcrum},
 1004:                   {href => "javascript:backPage(document.usersrchform,'','')",
 1005:                    text => $breadcrumb_text{'search'},
 1006:                    faq  => 282,
 1007:                    bug  => 'Instructor Interface',},
 1008:                   {href => "javascript:backPage(document.usersrchform,'get_user_info','select')",
 1009:                    text => $breadcrumb_text{'userpicked'},
 1010:                    faq  => 282,
 1011:                    bug  => 'Instructor Interface',
 1012:                    help => $helpitem}
 1013:                   );
 1014:         $r->print(&Apache::loncommon::start_page('User Management',$jscript,{bread_crumbs => $brcrum}));
 1015:         if ($env{'form.action'} eq 'singleuser') {
 1016:             my $readonly;
 1017:             if (($context eq 'domain') && (!&Apache::lonnet::allowed('mau',$srch->{'srchdomain'}))) {
 1018:                 $readonly = 1;
 1019:                 $r->print("<b>$lt{'usrvu'}</b><br />");
 1020:             } else {
 1021:                 $r->print("<b>$lt{'usrch'}</b><br />");
 1022:             }
 1023:             $r->print(&entry_form($srch->{'srchdomain'},$srch,undef,$context,undef,$crstype));
 1024:             if ($readonly) {
 1025:                 $r->print('<h3>'.$lt{'suvr'}.'</h3>');
 1026:             } else {
 1027:                 $r->print('<h3>'.$lt{'usel'}.'</h3>');
 1028:             }
 1029:         } elsif ($env{'form.action'} eq 'singlestudent') {
 1030:             $r->print($jscript."<b>");
 1031:             if ($crstype eq 'Community') {
 1032:                 $r->print($lt{'memsrch'});
 1033:             } else {
 1034:                 $r->print($lt{'stusrch'});
 1035:             }
 1036:             $r->print("</b><br />");
 1037:             $r->print(&entry_form($srch->{'srchdomain'},$srch,undef,$context,undef,$crstype));
 1038:             $r->print('</form><h3>');
 1039:             if ($crstype eq 'Community') {
 1040:                 $r->print($lt{'memsel'});
 1041:             } else {
 1042:                 $r->print($lt{'stusel'});
 1043:             }
 1044:             $r->print('</h3>');
 1045:         } elsif ($env{'form.action'} eq 'accesslogs') {
 1046:             $r->print("<b>$lt{'srcva'}</b><br />");
 1047:             $r->print(&entry_form($srch->{'srchdomain'},$srch,undef,'accesslogs',undef,undef,1));
 1048:             $r->print('<h3>'.$lt{'vacsel'}.'</h3>');
 1049:         }
 1050:     }
 1051:     $r->print('<form name="usersrchform" method="post" action="">'.
 1052:               &Apache::loncommon::start_data_table()."\n".
 1053:               &Apache::loncommon::start_data_table_header_row()."\n".
 1054:               ' <th> </th>'."\n");
 1055:     foreach my $field (@fields) {
 1056:         $r->print(' <th><a href="javascript:document.usersrchform.sortby.value='.
 1057:                   "'".$field."'".';document.usersrchform.submit();">'.
 1058:                   $lt{$field}.'</a></th>'."\n");
 1059:     }
 1060:     $r->print(&Apache::loncommon::end_data_table_header_row());
 1061: 
 1062:     my @sorted_users = sort {
 1063:         lc($srch_results->{$a}->{$sortby})   cmp lc($srch_results->{$b}->{$sortby})
 1064:             ||
 1065:         lc($srch_results->{$a}->{lastname})  cmp lc($srch_results->{$b}->{lastname})
 1066:             ||
 1067:         lc($srch_results->{$a}->{firstname}) cmp lc($srch_results->{$b}->{firstname})
 1068: 	    ||
 1069: 	lc($a) cmp lc($b)
 1070:         } (keys(%$srch_results));
 1071: 
 1072:     foreach my $user (@sorted_users) {
 1073:         my ($uname,$udom) = split(/:/,$user);
 1074:         my $onclick;
 1075:         if ($context eq 'requestcrs') {
 1076:             $onclick =
 1077:                 'onclick="javascript:gochoose('."'$uname','$udom',".
 1078:                                                "'$srch_results->{$user}->{firstname}',".
 1079:                                                "'$srch_results->{$user}->{lastname}',".
 1080:                                                "'$srch_results->{$user}->{permanentemail}'".');"';
 1081:         } else {
 1082:             $onclick =
 1083:                 ' onclick="javascript:pickuser('."'".$uname."'".','."'".$udom."'".');"';
 1084:         }
 1085:         $r->print(&Apache::loncommon::start_data_table_row().
 1086:                   '<td><input type="button" name="seluser" value="'.&mt('Select').'" '.
 1087:                   $onclick.' /></td>'.
 1088:                   '<td><tt>'.$uname.'</tt></td>'.
 1089:                   '<td><tt>'.$udom.'</tt></td>');
 1090:         foreach my $field ('lastname','firstname','permanentemail') {
 1091:             $r->print('<td>'.$srch_results->{$user}->{$field}.'</td>');
 1092:         }
 1093:         $r->print(&Apache::loncommon::end_data_table_row());
 1094:     }
 1095:     $r->print(&Apache::loncommon::end_data_table().'<br /><br />');
 1096:     if (ref($srcharray) eq 'ARRAY') {
 1097:         foreach my $item (@{$srcharray}) {
 1098:             $r->print('<input type="hidden" name="'.$item.'" value="'.$env{'form.'.$item}.'" />'."\n");
 1099:         }
 1100:     }
 1101:     $r->print(' <input type="hidden" name="sortby" value="'.$sortby.'" />'."\n".
 1102:               ' <input type="hidden" name="seluname" value="" />'."\n".
 1103:               ' <input type="hidden" name="seludom" value="" />'."\n".
 1104:               ' <input type="hidden" name="currstate" value="select" />'."\n".
 1105:               ' <input type="hidden" name="phase" value="get_user_info" />'."\n".
 1106:               ' <input type="hidden" name="action" value="'.$env{'form.action'}.'" />'."\n");
 1107:     if ($context eq 'requestcrs') {
 1108:         $r->print($opener_elements.'</form></div>');
 1109:     } else {
 1110:         $r->print($response.'</form>');
 1111:     }
 1112: }
 1113: 
 1114: sub print_user_query_page {
 1115:     my ($r,$caller,$brcrum) = @_;
 1116: # FIXME - this is for a network-wide name search (similar to catalog search)
 1117: # To use frames with similar behavior to catalog/portfolio search.
 1118: # To be implemented. 
 1119:     return;
 1120: }
 1121: 
 1122: sub print_user_modification_page {
 1123:     my ($r,$ccuname,$ccdomain,$srch,$response,$context,$permission,$crstype,
 1124:         $brcrum,$showcredits) = @_;
 1125:     if (($ccuname eq '') || ($ccdomain eq '')) {
 1126:         my $usermsg = &mt('No username and/or domain provided.');
 1127:         $env{'form.phase'} = '';
 1128: 	&print_username_entry_form($r,$context,$usermsg,'','',$crstype,$brcrum);
 1129:         return;
 1130:     }
 1131:     my ($form,$formname);
 1132:     if ($env{'form.action'} eq 'singlestudent') {
 1133:         $form = 'document.enrollstudent';
 1134:         $formname = 'enrollstudent';
 1135:     } else {
 1136:         $form = 'document.cu';
 1137:         $formname = 'cu';
 1138:     }
 1139:     my %abv_auth = &auth_abbrev();
 1140:     my (%rulematch,%inst_results,$newuser,%alerts,%curr_rules,%got_rules);
 1141:     my $uhome=&Apache::lonnet::homeserver($ccuname,$ccdomain);
 1142:     if ($uhome eq 'no_host') {
 1143:         my $usertype;
 1144:         my ($rules,$ruleorder) =
 1145:             &Apache::lonnet::inst_userrules($ccdomain,'username');
 1146:             $usertype =
 1147:                 &Apache::lonuserutils::check_usertype($ccdomain,$ccuname,$rules,
 1148:                                                       \%curr_rules,\%got_rules);
 1149:         my $cancreate =
 1150:             &Apache::lonuserutils::can_create_user($ccdomain,$context,
 1151:                                                    $usertype);
 1152:         if (!$cancreate) {
 1153:             my $helplink = 'javascript:helpMenu('."'display'".')';
 1154:             my %usertypetext = (
 1155:                 official   => 'institutional',
 1156:                 unofficial => 'non-institutional',
 1157:             );
 1158:             my $response;
 1159:             if ($env{'form.origform'} eq 'crtusername') {
 1160:                 $response = '<span class="LC_warning">'.
 1161:                             &mt('No match found for the username [_1] in LON-CAPA domain: [_2]',
 1162:                                 '<b>'.$ccuname.'</b>',$ccdomain).
 1163:                             '</span><br />';
 1164:             }
 1165:             $response .= '<p class="LC_warning">'
 1166:                         .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
 1167:                         .' ';
 1168:             if ($context eq 'domain') {
 1169:                 $response .= &mt('Please contact a [_1] for assistance.',
 1170:                                  &Apache::lonnet::plaintext('dc'));
 1171:             } else {
 1172:                 $response .= &mt('Please contact the [_1]helpdesk[_2] for assistance.'
 1173:                                 ,'<a href="'.$helplink.'">','</a>');
 1174:             }
 1175:             $response .= '</p><br />';
 1176:             $env{'form.phase'} = '';
 1177:             &print_username_entry_form($r,$context,$response,undef,undef,$crstype,$brcrum);
 1178:             return;
 1179:         }
 1180:         $newuser = 1;
 1181:         my $checkhash;
 1182:         my $checks = { 'username' => 1 };
 1183:         $checkhash->{$ccuname.':'.$ccdomain} = { 'newuser' => $newuser };
 1184:         &Apache::loncommon::user_rule_check($checkhash,$checks,
 1185:             \%alerts,\%rulematch,\%inst_results,\%curr_rules,\%got_rules);
 1186:         if (ref($alerts{'username'}) eq 'HASH') {
 1187:             if (ref($alerts{'username'}{$ccdomain}) eq 'HASH') {
 1188:                 my $domdesc =
 1189:                     &Apache::lonnet::domain($ccdomain,'description');
 1190:                 if ($alerts{'username'}{$ccdomain}{$ccuname}) {
 1191:                     my $userchkmsg;
 1192:                     if (ref($curr_rules{$ccdomain}) eq 'HASH') {  
 1193:                         $userchkmsg = 
 1194:                             &Apache::loncommon::instrule_disallow_msg('username',
 1195:                                                                  $domdesc,1).
 1196:                         &Apache::loncommon::user_rule_formats($ccdomain,
 1197:                             $domdesc,$curr_rules{$ccdomain}{'username'},
 1198:                             'username');
 1199:                     }
 1200:                     $env{'form.phase'} = '';
 1201:                     &print_username_entry_form($r,$context,$userchkmsg,undef,undef,$crstype,$brcrum);
 1202:                     return;
 1203:                 }
 1204:             }
 1205:         }
 1206:     } else {
 1207:         $newuser = 0;
 1208:     }
 1209:     if ($response) {
 1210:         $response = '<br />'.$response;
 1211:     }
 1212: 
 1213:     my $pjump_def = &Apache::lonhtmlcommon::pjump_javascript_definition();
 1214:     my $dc_setcourse_code = '';
 1215:     my $nondc_setsection_code = '';                                        
 1216:     my %loaditem;
 1217: 
 1218:     my $groupslist = &Apache::lonuserutils::get_groupslist();
 1219: 
 1220:     my $js = &validation_javascript($context,$ccdomain,$pjump_def,$crstype,
 1221:                                $groupslist,$newuser,$formname,\%loaditem);
 1222:     my %breadcrumb_text = &singleuser_breadcrumb($crstype,$context,$ccdomain);
 1223:     my $helpitem = 'Course_Change_Privileges';
 1224:     if ($env{'form.action'} eq 'singlestudent') {
 1225:         $helpitem = 'Course_Add_Student';
 1226:     }
 1227:     push (@{$brcrum},
 1228:         {href => "javascript:backPage($form)",
 1229:          text => $breadcrumb_text{'search'},
 1230:          faq  => 282,
 1231:          bug  => 'Instructor Interface',});
 1232:     if ($env{'form.phase'} eq 'userpicked') {
 1233:        push(@{$brcrum},
 1234:               {href => "javascript:backPage($form,'get_user_info','select')",
 1235:                text => $breadcrumb_text{'userpicked'},
 1236:                faq  => 282,
 1237:                bug  => 'Instructor Interface',});
 1238:     }
 1239:     push(@{$brcrum},
 1240:             {href => "javascript:backPage($form,'$env{'form.phase'}','modify')",
 1241:              text => $breadcrumb_text{'modify'},
 1242:              faq  => 282,
 1243:              bug  => 'Instructor Interface',
 1244:              help => $helpitem});
 1245:     my $args = {'add_entries'           => \%loaditem,
 1246:                 'bread_crumbs'          => $brcrum,
 1247:                 'bread_crumbs_component' => 'User Management'};
 1248:     if ($env{'form.popup'}) {
 1249:         $args->{'no_nav_bar'} = 1;
 1250:     }
 1251:     my $start_page =
 1252:         &Apache::loncommon::start_page('User Management',$js,$args);
 1253: 
 1254:     my $forminfo =<<"ENDFORMINFO";
 1255: <form action="/adm/createuser" method="post" name="$formname">
 1256: <input type="hidden" name="phase" value="update_user_data" />
 1257: <input type="hidden" name="ccuname" value="$ccuname" />
 1258: <input type="hidden" name="ccdomain" value="$ccdomain" />
 1259: <input type="hidden" name="pres_value"  value="" />
 1260: <input type="hidden" name="pres_type"   value="" />
 1261: <input type="hidden" name="pres_marker" value="" />
 1262: ENDFORMINFO
 1263:     my (%inccourses,$roledom,$defaultcredits);
 1264:     if ($context eq 'course') {
 1265:         $inccourses{$env{'request.course.id'}}=1;
 1266:         $roledom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 1267:         if ($showcredits) {
 1268:             $defaultcredits = &Apache::lonuserutils::get_defaultcredits();
 1269:         }
 1270:     } elsif ($context eq 'author') {
 1271:         $roledom = $env{'request.role.domain'};
 1272:     } elsif ($context eq 'domain') {
 1273:         foreach my $key (keys(%env)) {
 1274:             $roledom = $env{'request.role.domain'};
 1275:             if ($key=~/^user\.priv\.cm\.\/($roledom)\/($match_username)/) {
 1276:                 $inccourses{$1.'_'.$2}=1;
 1277:             }
 1278:         }
 1279:     } else {
 1280:         foreach my $key (keys(%env)) {
 1281: 	    if ($key=~/^user\.priv\.cm\.\/($match_domain)\/($match_username)/) {
 1282: 	        $inccourses{$1.'_'.$2}=1;
 1283:             }
 1284:         }
 1285:     }
 1286:     my $title = '';
 1287:     if ($newuser) {
 1288:         my ($portfolioform,$domroleform);
 1289:         if ((&Apache::lonnet::allowed('mpq',$env{'request.role.domain'})) ||
 1290:             (&Apache::lonnet::allowed('mut',$env{'request.role.domain'}))) {
 1291:             # Current user has quota or user tools modification privileges
 1292:             $portfolioform = '<br />'.&user_quotas($ccuname,$ccdomain);
 1293:         }
 1294:         if ((&Apache::lonnet::allowed('cau',$env{'request.role.domain'})) &&
 1295:             ($ccdomain eq $env{'request.role.domain'})) {
 1296:             $domroleform = '<br />'.&domainrole_req($ccuname,$ccdomain);
 1297:         }
 1298:         &initialize_authen_forms($ccdomain,$formname);
 1299:         my %lt=&Apache::lonlocal::texthash(
 1300:                 'lg'             => 'Login Data',
 1301:                 'hs'             => "Home Server",
 1302:         );
 1303: 	$r->print(<<ENDTITLE);
 1304: $start_page
 1305: $response
 1306: $forminfo
 1307: <script type="text/javascript" language="Javascript">
 1308: // <![CDATA[
 1309: $loginscript
 1310: // ]]>
 1311: </script>
 1312: <input type='hidden' name='makeuser' value='1' />
 1313: ENDTITLE
 1314:         if ($env{'form.action'} eq 'singlestudent') {
 1315:             if ($crstype eq 'Community') {
 1316:                 $title = &mt('Create New User [_1] in domain [_2] as a member',
 1317:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1318:             } else {
 1319:                 $title = &mt('Create New User [_1] in domain [_2] as a student',
 1320:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1321:             }
 1322:         } else {
 1323:                 $title = &mt('Create New User [_1] in domain [_2]',
 1324:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1325:         }
 1326:         $r->print('<h2>'.$title.'</h2>'."\n");
 1327:         $r->print('<div class="LC_left_float">');
 1328:         $r->print(&personal_data_display($ccuname,$ccdomain,$newuser,$context,
 1329:                                          $inst_results{$ccuname.':'.$ccdomain}));
 1330:         # Option to disable student/employee ID conflict checking not offerred for new users.
 1331:         my ($home_server_pick,$numlib) = 
 1332:             &Apache::loncommon::home_server_form_item($ccdomain,'hserver',
 1333:                                                       'default','hide');
 1334:         if ($numlib > 1) {
 1335:             $r->print("
 1336: <br />
 1337: $lt{'hs'}: $home_server_pick
 1338: <br />");
 1339:         } else {
 1340:             $r->print($home_server_pick);
 1341:         }
 1342:         if (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) {
 1343:             $r->print('<br /><h3>'.
 1344:                       &mt('User Can Request Creation of Courses/Communities in this Domain?').'</h3>'.
 1345:                       &Apache::loncommon::start_data_table().
 1346:                       &build_tools_display($ccuname,$ccdomain,
 1347:                                            'requestcourses').
 1348:                       &Apache::loncommon::end_data_table());
 1349:         }
 1350:         $r->print('</div>'."\n".'<div class="LC_left_float"><h3>'.
 1351:                   $lt{'lg'}.'</h3>');
 1352:         my ($fixedauth,$varauth,$authmsg); 
 1353:         if (ref($rulematch{$ccuname.':'.$ccdomain}) eq 'HASH') {
 1354:             my $matchedrule = $rulematch{$ccuname.':'.$ccdomain}{'username'};
 1355:             my ($rules,$ruleorder) = 
 1356:                 &Apache::lonnet::inst_userrules($ccdomain,'username');
 1357:             if (ref($rules) eq 'HASH') {
 1358:                 if (ref($rules->{$matchedrule}) eq 'HASH') {
 1359:                     my $authtype = $rules->{$matchedrule}{'authtype'};
 1360:                     if ($authtype !~ /^(krb4|krb5|int|fsys|loc)$/) {
 1361:                         $r->print(&Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc));
 1362:                     } else { 
 1363:                         my $authparm = $rules->{$matchedrule}{'authparm'};
 1364:                         $authmsg = $rules->{$matchedrule}{'authmsg'};
 1365:                         if ($authtype =~ /^krb(4|5)$/) {
 1366:                             my $ver = $1;
 1367:                             if ($authparm ne '') {
 1368:                                 $fixedauth = <<"KERB"; 
 1369: <input type="hidden" name="login" value="krb" />
 1370: <input type="hidden" name="krbver" value="$ver" />
 1371: <input type="hidden" name="krbarg" value="$authparm" />
 1372: KERB
 1373:                             }
 1374:                         } else {
 1375:                             $fixedauth = 
 1376: '<input type="hidden" name="login" value="'.$authtype.'" />'."\n";
 1377:                             if ($rules->{$matchedrule}{'authparmfixed'}) {
 1378:                                 $fixedauth .=    
 1379: '<input type="hidden" name="'.$authtype.'arg" value="'.$authparm.'" />'."\n";
 1380:                             } else {
 1381:                                 if ($authtype eq 'int') {
 1382:                                     $varauth = '<br />'.
 1383: &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>';
 1384:                                 } elsif ($authtype eq 'loc') {
 1385:                                     $varauth = '<br />'.
 1386: &mt('[_1] Local Authentication with argument [_2]','','<input type="text" name="'.$authtype.'arg" value="" />')."\n";
 1387:                                 } else {
 1388:                                     $varauth =
 1389: '<input type="text" name="'.$authtype.'arg" value="" />'."\n";
 1390:                                 }
 1391:                             }
 1392:                         }
 1393:                     }
 1394:                 } else {
 1395:                     $r->print(&Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc));
 1396:                 }
 1397:             }
 1398:             if ($authmsg) {
 1399:                 $r->print(<<ENDAUTH);
 1400: $fixedauth
 1401: $authmsg
 1402: $varauth
 1403: ENDAUTH
 1404:             }
 1405:         } else {
 1406:             $r->print(&Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc)); 
 1407:         }
 1408:         $r->print($portfolioform.$domroleform);
 1409:         if ($env{'form.action'} eq 'singlestudent') {
 1410:             $r->print(&date_sections_select($context,$newuser,$formname,
 1411:                                             $permission,$crstype,$ccuname,
 1412:                                             $ccdomain,$showcredits));
 1413:         }
 1414:         $r->print('</div><div class="LC_clear_float_footer"></div>');
 1415:     } else { # user already exists
 1416: 	$r->print($start_page.$forminfo);
 1417:         if ($env{'form.action'} eq 'singlestudent') {
 1418:             if ($crstype eq 'Community') {
 1419:                 $title = &mt('Enroll one member: [_1] in domain [_2]',
 1420:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1421:             } else {
 1422:                 $title = &mt('Enroll one student: [_1] in domain [_2]',
 1423:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1424:             }
 1425:         } else {
 1426:             if ($permission->{'cusr'}) {
 1427:                 $title = &mt('Modify existing user: [_1] in domain [_2]',
 1428:                              '"'.$ccuname.'"','"'.$ccdomain.'"');
 1429:             } else {
 1430:                 $title = &mt('Existing user: [_1] in domain [_2]',
 1431:                              '"'.$ccuname.'"','"'.$ccdomain.'"');
 1432:             }
 1433:         }
 1434:         $r->print('<h2>'.$title.'</h2>'."\n");
 1435:         $r->print('<div class="LC_left_float">');
 1436:         $r->print(&personal_data_display($ccuname,$ccdomain,$newuser,$context,
 1437:                                          $inst_results{$ccuname.':'.$ccdomain}));
 1438:         if ((&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) || 
 1439:             (&Apache::lonnet::allowed('udp',$env{'request.role.domain'}))) {
 1440:             $r->print('<br /><h3>'.&mt('User Can Request Creation of Courses/Communities in this Domain?').'</h3>'.
 1441:                       &Apache::loncommon::start_data_table());
 1442:             if ($env{'request.role.domain'} eq $ccdomain) {
 1443:                 $r->print(&build_tools_display($ccuname,$ccdomain,'requestcourses'));
 1444:             } else {
 1445:                 $r->print(&coursereq_externaluser($ccuname,$ccdomain,
 1446:                                                   $env{'request.role.domain'}));
 1447:             }
 1448:             $r->print(&Apache::loncommon::end_data_table());
 1449:         }
 1450:         $r->print('</div>');
 1451:         my @order = ('auth','quota','tools','requestauthor');
 1452:         my %user_text;
 1453:         my ($isadv,$isauthor) = 
 1454:             &Apache::lonnet::is_advanced_user($ccdomain,$ccuname);
 1455:         if ((!$isauthor) && 
 1456:             ((&Apache::lonnet::allowed('cau',$env{'request.role.domain'})) ||
 1457:              (&Apache::lonnet::allowed('udp',$env{'request.role.domain'}))) &&
 1458:             ($env{'request.role.domain'} eq $ccdomain)) {
 1459:             $user_text{'requestauthor'} = &domainrole_req($ccuname,$ccdomain);
 1460:         }
 1461:         $user_text{'auth'} =  &user_authentication($ccuname,$ccdomain,$formname);
 1462:         if ((&Apache::lonnet::allowed('mpq',$ccdomain)) ||
 1463:             (&Apache::lonnet::allowed('mut',$ccdomain)) ||
 1464:             (&Apache::lonnet::allowed('udp',$ccdomain))) {
 1465:             # Current user has quota modification privileges
 1466:             $user_text{'quota'} = &user_quotas($ccuname,$ccdomain);
 1467:         }
 1468:         if (!&Apache::lonnet::allowed('mpq',$ccdomain)) {
 1469:             if (&Apache::lonnet::allowed('mpq',$env{'request.role.domain'})) {
 1470:                 my %lt=&Apache::lonlocal::texthash(
 1471:                     'dska'  => "Disk quotas for user's portfolio and Authoring Space",
 1472:                     'youd'  => "You do not have privileges to modify the portfolio and/or Authoring Space quotas for this user.",
 1473:                     'ichr'  => "If a change is required, contact a domain coordinator for the domain",
 1474:                 );
 1475:                 $user_text{'quota'} = <<ENDNOPORTPRIV;
 1476: <h3>$lt{'dska'}</h3>
 1477: $lt{'youd'} $lt{'ichr'}: $ccdomain
 1478: ENDNOPORTPRIV
 1479:             }
 1480:         }
 1481:         if (!&Apache::lonnet::allowed('mut',$ccdomain)) {
 1482:             if (&Apache::lonnet::allowed('mut',$env{'request.role.domain'})) {
 1483:                 my %lt=&Apache::lonlocal::texthash(
 1484:                     'utav'  => "User Tools Availability",
 1485:                     'yodo'  => "You do not have privileges to modify Portfolio, Blog, WebDAV, or Personal Information Page settings for this user.",
 1486:                     'ifch'  => "If a change is required, contact a domain coordinator for the domain",
 1487:                 );
 1488:                 $user_text{'tools'} = <<ENDNOTOOLSPRIV;
 1489: <h3>$lt{'utav'}</h3>
 1490: $lt{'yodo'} $lt{'ifch'}: $ccdomain
 1491: ENDNOTOOLSPRIV
 1492:             }
 1493:         }
 1494:         my $gotdiv = 0; 
 1495:         foreach my $item (@order) {
 1496:             if ($user_text{$item} ne '') {
 1497:                 unless ($gotdiv) {
 1498:                     $r->print('<div class="LC_left_float">');
 1499:                     $gotdiv = 1;
 1500:                 }
 1501:                 $r->print('<br />'.$user_text{$item});
 1502:             }
 1503:         }
 1504:         if ($env{'form.action'} eq 'singlestudent') {
 1505:             unless ($gotdiv) {
 1506:                 $r->print('<div class="LC_left_float">');
 1507:             }
 1508:             my $credits;
 1509:             if ($showcredits) {
 1510:                 $credits = &get_user_credits($ccuname,$ccdomain,$defaultcredits);
 1511:                 if ($credits eq '') {
 1512:                     $credits = $defaultcredits;
 1513:                 }
 1514:             }
 1515:             $r->print(&date_sections_select($context,$newuser,$formname,
 1516:                                             $permission,$crstype,$ccuname,
 1517:                                             $ccdomain,$showcredits));
 1518:         }
 1519:         if ($gotdiv) {
 1520:             $r->print('</div><div class="LC_clear_float_footer"></div>');
 1521:         }
 1522:         my $statuses;
 1523:         if (($context eq 'domain') && (&Apache::lonnet::allowed('udp',$ccdomain)) &&
 1524:             (!&Apache::lonnet::allowed('mau',$ccdomain))) {
 1525:             $statuses = ['active'];
 1526:         } elsif (($context eq 'course') && ((&Apache::lonnet::allowed('vcl',$env{'request.course.id'})) ||
 1527:                  ($env{'request.course.sec'} &&
 1528:                   &Apache::lonnet::allowed('vcl',$env{'request.course.id'}.'/'.$env{'request.course.sec'})))) {
 1529:             $statuses = ['active'];   
 1530:         }
 1531:         if ($env{'form.action'} ne 'singlestudent') {
 1532:             &display_existing_roles($r,$ccuname,$ccdomain,\%inccourses,$context,
 1533:                                     $roledom,$crstype,$showcredits,$statuses);
 1534:         }
 1535:     } ## End of new user/old user logic
 1536:     if ($env{'form.action'} eq 'singlestudent') {
 1537:         my $btntxt;
 1538:         if ($crstype eq 'Community') {
 1539:             $btntxt = &mt('Enroll Member');
 1540:         } else {
 1541:             $btntxt = &mt('Enroll Student');
 1542:         }
 1543:         $r->print('<br /><input type="button" value="'.$btntxt.'" onclick="setSections(this.form)" />'."\n");
 1544:     } elsif ($permission->{'cusr'}) {
 1545:         $r->print('<div class="LC_left_float">'.
 1546:                   '<fieldset><legend>'.&mt('Add Roles').'</legend>');
 1547:         my $addrolesdisplay = 0;
 1548:         if ($context eq 'domain' || $context eq 'author') {
 1549:             $addrolesdisplay = &new_coauthor_roles($r,$ccuname,$ccdomain);
 1550:         }
 1551:         if ($context eq 'domain') {
 1552:             my $add_domainroles = &new_domain_roles($r,$ccdomain);
 1553:             if (!$addrolesdisplay) {
 1554:                 $addrolesdisplay = $add_domainroles;
 1555:             }
 1556:             $r->print(&course_level_dc($env{'request.role.domain'},$showcredits));
 1557:             $r->print('</fieldset></div><div class="LC_clear_float_footer"></div>'.
 1558:                       '<br /><input type="button" value="'.&mt('Save').'" onclick="setCourse()" />'."\n");
 1559:         } elsif ($context eq 'author') {
 1560:             if ($addrolesdisplay) {
 1561:                 $r->print('</fieldset></div><div class="LC_clear_float_footer"></div>'.
 1562:                           '<br /><input type="button" value="'.&mt('Save').'"');
 1563:                 if ($newuser) {
 1564:                     $r->print(' onclick="auth_check()" \>'."\n");
 1565:                 } else {
 1566:                     $r->print('onclick="this.form.submit()" \>'."\n");
 1567:                 }
 1568:             } else {
 1569:                 $r->print('</fieldset></div>'.
 1570:                           '<div class="LC_clear_float_footer"></div>'.
 1571:                           '<br /><a href="javascript:backPage(document.cu)">'.
 1572:                           &mt('Back to previous page').'</a>');
 1573:             }
 1574:         } else {
 1575:             $r->print(&course_level_table(\%inccourses,$showcredits,$defaultcredits));
 1576:             $r->print('</fieldset></div><div class="LC_clear_float_footer"></div>'.
 1577:                       '<br /><input type="button" value="'.&mt('Save').'" onclick="setSections(this.form)" />'."\n");
 1578:         }
 1579:     }
 1580:     $r->print(&Apache::lonhtmlcommon::echo_form_input(['phase','userrole','ccdomain','prevphase','currstate','ccuname','ccdomain']));
 1581:     $r->print('<input type="hidden" name="currstate" value="" />');
 1582:     $r->print('<input type="hidden" name="prevphase" value="'.$env{'form.phase'}.'" /></form><br /><br />');
 1583:     return;
 1584: }
 1585: 
 1586: sub singleuser_breadcrumb {
 1587:     my ($crstype,$context,$domain) = @_;
 1588:     my %breadcrumb_text;
 1589:     if ($env{'form.action'} eq 'singlestudent') {
 1590:         if ($crstype eq 'Community') {
 1591:             $breadcrumb_text{'search'} = 'Enroll a member';
 1592:         } else {
 1593:             $breadcrumb_text{'search'} = 'Enroll a student';
 1594:         }
 1595:         $breadcrumb_text{'userpicked'} = 'Select a user';
 1596:         $breadcrumb_text{'modify'} = 'Set section/dates';
 1597:     } elsif ($env{'form.action'} eq 'accesslogs') {
 1598:         $breadcrumb_text{'search'} = 'View access logs for a user';
 1599:         $breadcrumb_text{'userpicked'} = 'Select a user';
 1600:         $breadcrumb_text{'activity'} = 'Activity';
 1601:     } elsif (($env{'form.action'} eq 'singleuser') && ($context eq 'domain') &&
 1602:              (!&Apache::lonnet::allowed('mau',$domain))) {
 1603:         $breadcrumb_text{'search'} = "View user's roles";
 1604:         $breadcrumb_text{'userpicked'} = 'Select a user';
 1605:         $breadcrumb_text{'modify'} = 'User roles';
 1606:     } else {
 1607:         $breadcrumb_text{'search'} = 'Create/modify a user';
 1608:         $breadcrumb_text{'userpicked'} = 'Select a user';
 1609:         $breadcrumb_text{'modify'} = 'Set user role';
 1610:     }
 1611:     return %breadcrumb_text;
 1612: }
 1613: 
 1614: sub date_sections_select {
 1615:     my ($context,$newuser,$formname,$permission,$crstype,$ccuname,$ccdomain,
 1616:         $showcredits) = @_;
 1617:     my $credits;
 1618:     if ($showcredits) {
 1619:         my $defaultcredits = &Apache::lonuserutils::get_defaultcredits();
 1620:         $credits = &get_user_credits($ccuname,$ccdomain,$defaultcredits);
 1621:         if ($credits eq '') {
 1622:             $credits = $defaultcredits;
 1623:         }
 1624:     }
 1625:     my $cid = $env{'request.course.id'};
 1626:     my ($cnum,$cdom) = &Apache::lonuserutils::get_course_identity($cid);
 1627:     my $date_table = '<h3>'.&mt('Starting and Ending Dates').'</h3>'."\n".
 1628:         &Apache::lonuserutils::date_setting_table(undef,undef,$context,
 1629:                                                   undef,$formname,$permission);
 1630:     my $rowtitle = 'Section';
 1631:     my $secbox = '<h3>'.&mt('Section and Credits').'</h3>'."\n".
 1632:         &Apache::lonuserutils::section_picker($cdom,$cnum,'st',$rowtitle,
 1633:                                               $permission,$context,'',$crstype,
 1634:                                               $showcredits,$credits);
 1635:     my $output = $date_table.$secbox;
 1636:     return $output;
 1637: }
 1638: 
 1639: sub validation_javascript {
 1640:     my ($context,$ccdomain,$pjump_def,$crstype,$groupslist,$newuser,$formname,
 1641:         $loaditem) = @_;
 1642:     my $dc_setcourse_code = '';
 1643:     my $nondc_setsection_code = '';
 1644:     if ($context eq 'domain') {
 1645:         my $dcdom = $env{'request.role.domain'};
 1646:         $loaditem->{'onload'} = "document.cu.coursedesc.value='';";
 1647:         $dc_setcourse_code = 
 1648:             &Apache::lonuserutils::dc_setcourse_js('cu','singleuser',$context);
 1649:     } else {
 1650:         my $checkauth; 
 1651:         if (($newuser) || (&Apache::lonnet::allowed('mau',$ccdomain))) {
 1652:             $checkauth = 1;
 1653:         }
 1654:         if ($context eq 'course') {
 1655:             $nondc_setsection_code =
 1656:                 &Apache::lonuserutils::setsections_javascript($formname,$groupslist,
 1657:                                                               undef,$checkauth,
 1658:                                                               $crstype);
 1659:         }
 1660:         if ($checkauth) {
 1661:             $nondc_setsection_code .= 
 1662:                 &Apache::lonuserutils::verify_authen($formname,$context);
 1663:         }
 1664:     }
 1665:     my $js = &user_modification_js($pjump_def,$dc_setcourse_code,
 1666:                                    $nondc_setsection_code,$groupslist);
 1667:     my ($jsback,$elements) = &crumb_utilities();
 1668:     $js .= "\n".
 1669:            '<script type="text/javascript">'."\n".
 1670:            '// <![CDATA['."\n".
 1671:            $jsback."\n".
 1672:            '// ]]>'."\n".
 1673:            '</script>'."\n";
 1674:     return $js;
 1675: }
 1676: 
 1677: sub display_existing_roles {
 1678:     my ($r,$ccuname,$ccdomain,$inccourses,$context,$roledom,$crstype,
 1679:         $showcredits,$statuses) = @_;
 1680:     my $now=time;
 1681:     my $showall = 1;
 1682:     my ($showexpired,$showactive);
 1683:     if ((ref($statuses) eq 'ARRAY') && (@{$statuses} > 0)) {
 1684:         $showall = 0;
 1685:         if (grep(/^expired$/,@{$statuses})) {
 1686:             $showexpired = 1;
 1687:         }
 1688:         if (grep(/^active$/,@{$statuses})) {
 1689:             $showactive = 1;
 1690:         }
 1691:         if ($showexpired && $showactive) {
 1692:             $showall = 1;
 1693:         }
 1694:     }
 1695:     my %lt=&Apache::lonlocal::texthash(
 1696:                     'rer'  => "Existing Roles",
 1697:                     'rev'  => "Revoke",
 1698:                     'del'  => "Delete",
 1699:                     'ren'  => "Re-Enable",
 1700:                     'rol'  => "Role",
 1701:                     'ext'  => "Extent",
 1702:                     'crd'  => "Credits",
 1703:                     'sta'  => "Start",
 1704:                     'end'  => "End",
 1705:                                        );
 1706:     my (%rolesdump,%roletext,%sortrole,%roleclass,%rolepriv);
 1707:     if ($context eq 'course' || $context eq 'author') {
 1708:         my @roles = &Apache::lonuserutils::roles_by_context($context,1,$crstype);
 1709:         my %roleshash = 
 1710:             &Apache::lonnet::get_my_roles($ccuname,$ccdomain,'userroles',
 1711:                               ['active','previous','future'],\@roles,$roledom,1);
 1712:         foreach my $key (keys(%roleshash)) {
 1713:             my ($start,$end) = split(':',$roleshash{$key});
 1714:             next if ($start eq '-1' || $end eq '-1');
 1715:             my ($rnum,$rdom,$role,$sec) = split(':',$key);
 1716:             if ($context eq 'course') {
 1717:                 next unless (($rnum eq $env{'course.'.$env{'request.course.id'}.'.num'})
 1718:                              && ($rdom eq $env{'course.'.$env{'request.course.id'}.'.domain'}));
 1719:             } elsif ($context eq 'author') {
 1720:                 next unless (($rnum eq $env{'user.name'}) && ($rdom eq $env{'request.role.domain'}));
 1721:             }
 1722:             my ($newkey,$newvalue,$newrole);
 1723:             $newkey = '/'.$rdom.'/'.$rnum;
 1724:             if ($sec ne '') {
 1725:                 $newkey .= '/'.$sec;
 1726:             }
 1727:             $newvalue = $role;
 1728:             if ($role =~ /^cr/) {
 1729:                 $newrole = 'cr';
 1730:             } else {
 1731:                 $newrole = $role;
 1732:             }
 1733:             $newkey .= '_'.$newrole;
 1734:             if ($start ne '' && $end ne '') {
 1735:                 $newvalue .= '_'.$end.'_'.$start;
 1736:             } elsif ($end ne '') {
 1737:                 $newvalue .= '_'.$end;
 1738:             }
 1739:             $rolesdump{$newkey} = $newvalue;
 1740:         }
 1741:     } else {
 1742:         %rolesdump=&Apache::lonnet::dump('roles',$ccdomain,$ccuname);
 1743:     }
 1744:     # Build up table of user roles to allow revocation and re-enabling of roles.
 1745:     my ($tmp) = keys(%rolesdump);
 1746:     return if ($tmp =~ /^(con_lost|error)/i);
 1747:     foreach my $area (sort { my $a1=join('_',(split('_',$a))[1,0]);
 1748:                                 my $b1=join('_',(split('_',$b))[1,0]);
 1749:                                 return $a1 cmp $b1;
 1750:                             } keys(%rolesdump)) {
 1751:         next if ($area =~ /^rolesdef/);
 1752:         my $envkey=$area;
 1753:         my $role = $rolesdump{$area};
 1754:         my $thisrole=$area;
 1755:         $area =~ s/\_\w\w$//;
 1756:         my ($role_code,$role_end_time,$role_start_time) =
 1757:             split(/_/,$role);
 1758:         my $active=1;
 1759:         $active=0 if (($role_end_time) && ($now>$role_end_time));
 1760:         if ($active) {
 1761:             next unless($showall || $showactive);
 1762:         } else {
 1763:             next unless($showall || $showexpired); 
 1764:         }
 1765: # Is this a custom role? Get role owner and title.
 1766:         my ($croleudom,$croleuname,$croletitle)=
 1767:             ($role_code=~m{^cr/($match_domain)/($match_username)/(\w+)$});
 1768:         my $allowed=0;
 1769:         my $delallowed=0;
 1770:         my $sortkey=$role_code;
 1771:         my $class='Unknown';
 1772:         my $credits='';
 1773:         my $csec;
 1774:         if ($area =~ m{^/($match_domain)/($match_courseid)}) {
 1775:             $class='Course';
 1776:             my ($coursedom,$coursedir) = ($1,$2);
 1777:             my $cid = $1.'_'.$2;
 1778:             # $1.'_'.$2 is the course id (eg. 103_12345abcef103l3).
 1779:             next if ($envkey =~ m{^/$match_domain/$match_courseid/[A-Za-z0-9]+_gr$});
 1780:             my %coursedata=
 1781:                 &Apache::lonnet::coursedescription($cid);
 1782:             if ($coursedir =~ /^$match_community$/) {
 1783:                 $class='Community';
 1784:             }
 1785:             $sortkey.="\0$coursedom";
 1786:             my $carea;
 1787:             if (defined($coursedata{'description'})) {
 1788:                 $carea=$coursedata{'description'}.
 1789:                     '<br />'.&mt('Domain').': '.$coursedom.('&nbsp;'x8).
 1790:     &Apache::loncommon::syllabuswrapper(&mt('Syllabus'),$coursedir,$coursedom);
 1791:                 $sortkey.="\0".$coursedata{'description'};
 1792:             } else {
 1793:                 if ($class eq 'Community') {
 1794:                     $carea=&mt('Unavailable community').': '.$area;
 1795:                     $sortkey.="\0".&mt('Unavailable community').': '.$area;
 1796:                 } else {
 1797:                     $carea=&mt('Unavailable course').': '.$area;
 1798:                     $sortkey.="\0".&mt('Unavailable course').': '.$area;
 1799:                 }
 1800:             }
 1801:             $sortkey.="\0$coursedir";
 1802:             $inccourses->{$cid}=1;
 1803:             if (($showcredits) && ($class eq 'Course') && ($role_code eq 'st')) {
 1804:                 my $defaultcredits = $coursedata{'internal.defaultcredits'};
 1805:                 $credits =
 1806:                     &get_user_credits($ccuname,$ccdomain,$defaultcredits,
 1807:                                       $coursedom,$coursedir);
 1808:                 if ($credits eq '') {
 1809:                     $credits = $defaultcredits;
 1810:                 }
 1811:             }
 1812:             if ((&Apache::lonnet::allowed('c'.$role_code,$coursedom.'/'.$coursedir)) ||
 1813:                 (&Apache::lonnet::allowed('c'.$role_code,$ccdomain))) {
 1814:                 $allowed=1;
 1815:             }
 1816:             unless ($allowed) {
 1817:                 my $isowner = &Apache::lonuserutils::is_courseowner($cid,$coursedata{'internal.courseowner'});
 1818:                 if ($isowner) {
 1819:                     if (($role_code eq 'co') && ($class eq 'Community')) {
 1820:                         $allowed = 1;
 1821:                     } elsif (($role_code eq 'cc') && ($class eq 'Course')) {
 1822:                         $allowed = 1;
 1823:                     }
 1824:                 }
 1825:             } 
 1826:             if ((&Apache::lonnet::allowed('dro',$coursedom)) ||
 1827:                 (&Apache::lonnet::allowed('dro',$ccdomain))) {
 1828:                 $delallowed=1;
 1829:             }
 1830: # - custom role. Needs more info, too
 1831:             if ($croletitle) {
 1832:                 if (&Apache::lonnet::allowed('ccr',$coursedom.'/'.$coursedir)) {
 1833:                     $allowed=1;
 1834:                     $thisrole.='.'.$role_code;
 1835:                 }
 1836:             }
 1837:             if ($area=~m{^/($match_domain/$match_courseid/(\w+))}) {
 1838:                 $csec = $2;
 1839:                 $carea.='<br />'.&mt('Section: [_1]',$csec);
 1840:                 $sortkey.="\0$csec";
 1841:                 if (!$allowed) {
 1842:                     if ($env{'request.course.sec'} eq $csec) {
 1843:                         if (&Apache::lonnet::allowed('c'.$role_code,$1)) {
 1844:                             $allowed = 1;
 1845:                         }
 1846:                     }
 1847:                 }
 1848:             }
 1849:             $area=$carea;
 1850:         } else {
 1851:             $sortkey.="\0".$area;
 1852:             # Determine if current user is able to revoke privileges
 1853:             if ($area=~m{^/($match_domain)/}) {
 1854:                 if ((&Apache::lonnet::allowed('c'.$role_code,$1)) ||
 1855:                    (&Apache::lonnet::allowed('c'.$role_code,$ccdomain))) {
 1856:                    $allowed=1;
 1857:                 }
 1858:                 if (((&Apache::lonnet::allowed('dro',$1))  ||
 1859:                     (&Apache::lonnet::allowed('dro',$ccdomain))) &&
 1860:                     ($role_code ne 'dc')) {
 1861:                     $delallowed=1;
 1862:                 }
 1863:             } else {
 1864:                 if (&Apache::lonnet::allowed('c'.$role_code,'/')) {
 1865:                     $allowed=1;
 1866:                 }
 1867:             }
 1868:             if ($role_code eq 'ca' || $role_code eq 'au' || $role_code eq 'aa') {
 1869:                 $class='Authoring Space';
 1870:             } elsif ($role_code eq 'su') {
 1871:                 $class='System';
 1872:             } else {
 1873:                 $class='Domain';
 1874:             }
 1875:         }
 1876:         if (($role_code eq 'ca') || ($role_code eq 'aa')) {
 1877:             $area=~m{/($match_domain)/($match_username)};
 1878:             if (&Apache::lonuserutils::authorpriv($2,$1)) {
 1879:                 $allowed=1;
 1880:             } else {
 1881:                 $allowed=0;
 1882:             }
 1883:         }
 1884:         my $row = '';
 1885:         if ($showall) {
 1886:             $row.= '<td>';
 1887:             if (($active) && ($allowed)) {
 1888:                 $row.= '<input type="checkbox" name="rev:'.$thisrole.'" />';
 1889:             } else {
 1890:                 if ($active) {
 1891:                     $row.='&nbsp;';
 1892:                 } else {
 1893:                     $row.=&mt('expired or revoked');
 1894:                 }
 1895:             }
 1896:             $row.='</td><td>';
 1897:             if ($allowed && !$active) {
 1898:                 $row.= '<input type="checkbox" name="ren:'.$thisrole.'" />';
 1899:             } else {
 1900:                 $row.='&nbsp;';
 1901:             }
 1902:             $row.='</td><td>';
 1903:             if ($delallowed) {
 1904:                 $row.= '<input type="checkbox" name="del:'.$thisrole.'" />';
 1905:             } else {
 1906:                 $row.='&nbsp;';
 1907:             }
 1908:             $row.= '</td>'; 
 1909:         }
 1910:         my $plaintext='';
 1911:         if (!$croletitle) {
 1912:             $plaintext=&Apache::lonnet::plaintext($role_code,$class);
 1913:             if (($showcredits) && ($credits ne '')) {
 1914:                 $plaintext .= '<br/ ><span class="LC_nobreak">'.
 1915:                               '<span class="LC_fontsize_small">'.
 1916:                               &mt('Credits: [_1]',$credits).
 1917:                               '</span></span>';
 1918:             }
 1919:         } else {
 1920:             $plaintext=
 1921:                 &mt('Custom role [_1][_2]defined by [_3]',
 1922:                         '"'.$croletitle.'"',
 1923:                         '<br />',
 1924:                         $croleuname.':'.$croleudom);
 1925:         }
 1926:         $row.= '<td>'.$plaintext.'</td>'.
 1927:                '<td>'.$area.'</td>'.
 1928:                '<td>'.($role_start_time?&Apache::lonlocal::locallocaltime($role_start_time)
 1929:                                             : '&nbsp;' ).'</td>'.
 1930:                '<td>'.($role_end_time  ?&Apache::lonlocal::locallocaltime($role_end_time)
 1931:                                             : '&nbsp;' ).'</td>';
 1932:         $sortrole{$sortkey}=$envkey;
 1933:         $roletext{$envkey}=$row;
 1934:         $roleclass{$envkey}=$class;
 1935:         if ($allowed) {
 1936:             $rolepriv{$envkey}='edit';
 1937:         } else {
 1938:             if ($context eq 'domain') {
 1939:                 if ((&Apache::lonnet::allowed('vur',$ccdomain)) &&
 1940:                     ($envkey=~m{^/$ccdomain/})) {
 1941:                     $rolepriv{$envkey}='view';
 1942:                 }
 1943:             } elsif ($context eq 'course') {
 1944:                 if ((&Apache::lonnet::allowed('vcl',$env{'request.course.id'})) ||
 1945:                     ($env{'request.course.sec'} && ($env{'request.course.sec'} eq $csec) &&
 1946:                      &Apache::lonnet::allowed('vcl',$env{'request.course.id'}.'/'.$env{'request.course.sec'}))) {
 1947:                     $rolepriv{$envkey}='view';
 1948:                 }
 1949:             }
 1950:         }
 1951:     } # end of foreach        (table building loop)
 1952: 
 1953:     my $rolesdisplay = 0;
 1954:     my %output = ();
 1955:     foreach my $type ('Authoring Space','Course','Community','Domain','System','Unknown') {
 1956:         $output{$type} = '';
 1957:         foreach my $which (sort {uc($a) cmp uc($b)} (keys(%sortrole))) {
 1958:             if ( ($roleclass{$sortrole{$which}} =~ /^\Q$type\E/ ) && ($rolepriv{$sortrole{$which}}) ) {
 1959:                  $output{$type}.=
 1960:                       &Apache::loncommon::start_data_table_row().
 1961:                       $roletext{$sortrole{$which}}.
 1962:                       &Apache::loncommon::end_data_table_row();
 1963:             }
 1964:         }
 1965:         unless($output{$type} eq '') {
 1966:             $output{$type} = '<tr class="LC_info_row">'.
 1967:                       "<td align='center' colspan='7'>".&mt($type)."</td></tr>".
 1968:                       $output{$type};
 1969:             $rolesdisplay = 1;
 1970:         }
 1971:     }
 1972:     if ($rolesdisplay == 1) {
 1973:         my $contextrole='';
 1974:         if ($env{'request.course.id'}) {
 1975:             if (&Apache::loncommon::course_type() eq 'Community') {
 1976:                 $contextrole = &mt('Existing Roles in this Community');
 1977:             } else {
 1978:                 $contextrole = &mt('Existing Roles in this Course');
 1979:             }
 1980:         } elsif ($env{'request.role'} =~ /^au\./) {
 1981:             $contextrole = &mt('Existing Co-Author Roles in your Authoring Space');
 1982:         } else {
 1983:             if ($showall) {
 1984:                 $contextrole = &mt('Existing Roles in this Domain');
 1985:             } elsif ($showactive) {
 1986:                 $contextrole = &mt('Unexpired Roles in this Domain');
 1987:             } elsif ($showexpired) {
 1988:                 $contextrole = &mt('Expired or Revoked Roles in this Domain');
 1989:             }
 1990:         }
 1991:         $r->print('<div class="LC_left_float">'.
 1992: '<fieldset><legend>'.$contextrole.'</legend>'.
 1993: &Apache::loncommon::start_data_table("LC_createuser").
 1994: &Apache::loncommon::start_data_table_header_row());
 1995:         if ($showall) {
 1996:             $r->print(
 1997: '<th>'.$lt{'rev'}.'</th><th>'.$lt{'ren'}.'</th><th>'.$lt{'del'}.'</th>'
 1998:             );
 1999:         } elsif ($showexpired) {
 2000:             $r->print('<th>'.$lt{'rev'}.'</th>');
 2001:         }
 2002:         $r->print(
 2003: '<th>'.$lt{'rol'}.'</th><th>'.$lt{'ext'}.'</th>'.
 2004: '<th>'.$lt{'sta'}.'</th><th>'.$lt{'end'}.'</th>'.
 2005: &Apache::loncommon::end_data_table_header_row());
 2006:         foreach my $type ('Authoring Space','Course','Community','Domain','System','Unknown') {
 2007:             if ($output{$type}) {
 2008:                 $r->print($output{$type}."\n");
 2009:             }
 2010:         }
 2011:         $r->print(&Apache::loncommon::end_data_table().
 2012:                   '</fieldset></div>');
 2013:     }
 2014:     return;
 2015: }
 2016: 
 2017: sub new_coauthor_roles {
 2018:     my ($r,$ccuname,$ccdomain) = @_;
 2019:     my $addrolesdisplay = 0;
 2020:     #
 2021:     # Co-Author
 2022:     #
 2023:     if (&Apache::lonuserutils::authorpriv($env{'user.name'},
 2024:                                           $env{'request.role.domain'}) &&
 2025:         ($env{'user.name'} ne $ccuname || $env{'user.domain'} ne $ccdomain)) {
 2026:         # No sense in assigning co-author role to yourself
 2027:         $addrolesdisplay = 1;
 2028:         my $cuname=$env{'user.name'};
 2029:         my $cudom=$env{'request.role.domain'};
 2030:         my %lt=&Apache::lonlocal::texthash(
 2031:                     'cs'   => "Authoring Space",
 2032:                     'act'  => "Activate",
 2033:                     'rol'  => "Role",
 2034:                     'ext'  => "Extent",
 2035:                     'sta'  => "Start",
 2036:                     'end'  => "End",
 2037:                     'cau'  => "Co-Author",
 2038:                     'caa'  => "Assistant Co-Author",
 2039:                     'ssd'  => "Set Start Date",
 2040:                     'sed'  => "Set End Date"
 2041:                                        );
 2042:         $r->print('<h4>'.$lt{'cs'}.'</h4>'."\n".
 2043:                   &Apache::loncommon::start_data_table()."\n".
 2044:                   &Apache::loncommon::start_data_table_header_row()."\n".
 2045:                   '<th>'.$lt{'act'}.'</th><th>'.$lt{'rol'}.'</th>'.
 2046:                   '<th>'.$lt{'ext'}.'</th><th>'.$lt{'sta'}.'</th>'.
 2047:                   '<th>'.$lt{'end'}.'</th>'."\n".
 2048:                   &Apache::loncommon::end_data_table_header_row()."\n".
 2049:                   &Apache::loncommon::start_data_table_row().'
 2050:            <td>
 2051:             <input type="checkbox" name="act_'.$cudom.'_'.$cuname.'_ca" />
 2052:            </td>
 2053:            <td>'.$lt{'cau'}.'</td>
 2054:            <td>'.$cudom.'_'.$cuname.'</td>
 2055:            <td><input type="hidden" name="start_'.$cudom.'_'.$cuname.'_ca" value="" />
 2056:              <a href=
 2057: "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>
 2058: <td><input type="hidden" name="end_'.$cudom.'_'.$cuname.'_ca" value="" />
 2059: <a href=
 2060: "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".
 2061:               &Apache::loncommon::end_data_table_row()."\n".
 2062:               &Apache::loncommon::start_data_table_row()."\n".
 2063: '<td><input type="checkbox" name="act_'.$cudom.'_'.$cuname.'_aa" /></td>
 2064: <td>'.$lt{'caa'}.'</td>
 2065: <td>'.$cudom.'_'.$cuname.'</td>
 2066: <td><input type="hidden" name="start_'.$cudom.'_'.$cuname.'_aa" value="" />
 2067: <a href=
 2068: "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>
 2069: <td><input type="hidden" name="end_'.$cudom.'_'.$cuname.'_aa" value="" />
 2070: <a href=
 2071: "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".
 2072:              &Apache::loncommon::end_data_table_row()."\n".
 2073:              &Apache::loncommon::end_data_table());
 2074:     } elsif ($env{'request.role'} =~ /^au\./) {
 2075:         if (!(&Apache::lonuserutils::authorpriv($env{'user.name'},
 2076:                                                 $env{'request.role.domain'}))) {
 2077:             $r->print('<span class="LC_error">'.
 2078:                       &mt('You do not have privileges to assign co-author roles.').
 2079:                       '</span>');
 2080:         } elsif (($env{'user.name'} eq $ccuname) &&
 2081:              ($env{'user.domain'} eq $ccdomain)) {
 2082:             $r->print(&mt('Assigning yourself a co-author or assistant co-author role in your own author area in Authoring Space is not permitted'));
 2083:         }
 2084:     }
 2085:     return $addrolesdisplay;;
 2086: }
 2087: 
 2088: sub new_domain_roles {
 2089:     my ($r,$ccdomain) = @_;
 2090:     my $addrolesdisplay = 0;
 2091:     #
 2092:     # Domain level
 2093:     #
 2094:     my $num_domain_level = 0;
 2095:     my $domaintext =
 2096:     '<h4>'.&mt('Domain Level').'</h4>'.
 2097:     &Apache::loncommon::start_data_table().
 2098:     &Apache::loncommon::start_data_table_header_row().
 2099:     '<th>'.&mt('Activate').'</th><th>'.&mt('Role').'</th><th>'.
 2100:     &mt('Extent').'</th>'.
 2101:     '<th>'.&mt('Start').'</th><th>'.&mt('End').'</th>'.
 2102:     &Apache::loncommon::end_data_table_header_row();
 2103:     my @allroles = &Apache::lonuserutils::roles_by_context('domain');
 2104:     foreach my $thisdomain (sort(&Apache::lonnet::all_domains())) {
 2105:         foreach my $role (@allroles) {
 2106:             next if ($role eq 'ad');
 2107:             next if (($role eq 'au') && ($ccdomain ne $thisdomain));
 2108:             if (&Apache::lonnet::allowed('c'.$role,$thisdomain)) {
 2109:                my $plrole=&Apache::lonnet::plaintext($role);
 2110:                my %lt=&Apache::lonlocal::texthash(
 2111:                     'ssd'  => "Set Start Date",
 2112:                     'sed'  => "Set End Date"
 2113:                                        );
 2114:                $num_domain_level ++;
 2115:                $domaintext .=
 2116: &Apache::loncommon::start_data_table_row().
 2117: '<td><input type="checkbox" name="act_'.$thisdomain.'_'.$role.'" /></td>
 2118: <td>'.$plrole.'</td>
 2119: <td>'.$thisdomain.'</td>
 2120: <td><input type="hidden" name="start_'.$thisdomain.'_'.$role.'" value="" />
 2121: <a href=
 2122: "javascript:pjump('."'date_start','Start Date $plrole',document.cu.start_$thisdomain\_$role.value,'start_$thisdomain\_$role','cu.pres','dateset'".')">'.$lt{'ssd'}.'</a></td>
 2123: <td><input type="hidden" name="end_'.$thisdomain.'_'.$role.'" value="" />
 2124: <a href=
 2125: "javascript:pjump('."'date_end','End Date $plrole',document.cu.end_$thisdomain\_$role.value,'end_$thisdomain\_$role','cu.pres','dateset'".')">'.$lt{'sed'}.'</a></td>'.
 2126: &Apache::loncommon::end_data_table_row();
 2127:             }
 2128:         }
 2129:     }
 2130:     $domaintext.= &Apache::loncommon::end_data_table();
 2131:     if ($num_domain_level > 0) {
 2132:         $r->print($domaintext);
 2133:         $addrolesdisplay = 1;
 2134:     }
 2135:     return $addrolesdisplay;
 2136: }
 2137: 
 2138: sub user_authentication {
 2139:     my ($ccuname,$ccdomain,$formname) = @_;
 2140:     my $currentauth=&Apache::lonnet::queryauthenticate($ccuname,$ccdomain);
 2141:     my $outcome;
 2142:     my %lt=&Apache::lonlocal::texthash(
 2143:                    'err'   => "ERROR",
 2144:                    'uuas'  => "This user has an unrecognized authentication scheme",
 2145:                    'adcs'  => "Please alert a domain coordinator of this situation",
 2146:                    'sldb'  => "Please specify login data below",
 2147:                    'ld'    => "Login Data"
 2148:     );
 2149:     # Check for a bad authentication type
 2150:     if ($currentauth !~ /^(krb4|krb5|unix|internal|localauth):/) {
 2151:         # bad authentication scheme
 2152:         if (&Apache::lonnet::allowed('mau',$ccdomain)) {
 2153:             &initialize_authen_forms($ccdomain,$formname);
 2154: 
 2155:             my $choices = &Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc);
 2156:             $outcome = <<ENDBADAUTH;
 2157: <script type="text/javascript" language="Javascript">
 2158: // <![CDATA[
 2159: $loginscript
 2160: // ]]>
 2161: </script>
 2162: <span class="LC_error">$lt{'err'}:
 2163: $lt{'uuas'} ($currentauth). $lt{'sldb'}.</span>
 2164: <h3>$lt{'ld'}</h3>
 2165: $choices
 2166: ENDBADAUTH
 2167:         } else {
 2168:             # This user is not allowed to modify the user's
 2169:             # authentication scheme, so just notify them of the problem
 2170:             $outcome = <<ENDBADAUTH;
 2171: <span class="LC_error"> $lt{'err'}: 
 2172: $lt{'uuas'} ($currentauth). $lt{'adcs'}.
 2173: </span>
 2174: ENDBADAUTH
 2175:         }
 2176:     } else { # Authentication type is valid
 2177:         
 2178:         &initialize_authen_forms($ccdomain,$formname,$currentauth,'modifyuser');
 2179:         my ($authformcurrent,$can_modify,@authform_others) =
 2180:             &modify_login_block($ccdomain,$currentauth);
 2181:         if (&Apache::lonnet::allowed('mau',$ccdomain)) {
 2182:             # Current user has login modification privileges
 2183:             $outcome =
 2184:                        '<script type="text/javascript" language="Javascript">'."\n".
 2185:                        '// <![CDATA['."\n".
 2186:                        $loginscript."\n".
 2187:                        '// ]]>'."\n".
 2188:                        '</script>'."\n".
 2189:                        '<h3>'.$lt{'ld'}.'</h3>'.
 2190:                        &Apache::loncommon::start_data_table().
 2191:                        &Apache::loncommon::start_data_table_row().
 2192:                        '<td>'.$authformnop;
 2193:             if (($can_modify) && (&Apache::lonnet::allowed('mau',$ccdomain))) {
 2194:                 $outcome .= '</td>'."\n".
 2195:                             &Apache::loncommon::end_data_table_row().
 2196:                             &Apache::loncommon::start_data_table_row().
 2197:                             '<td>'.$authformcurrent.'</td>'.
 2198:                             &Apache::loncommon::end_data_table_row()."\n";
 2199:             } else {
 2200:                 $outcome .= '&nbsp;('.$authformcurrent.')</td>'.
 2201:                             &Apache::loncommon::end_data_table_row()."\n";
 2202:             }
 2203:             if (&Apache::lonnet::allowed('mau',$ccdomain)) {
 2204:                 foreach my $item (@authform_others) { 
 2205:                     $outcome .= &Apache::loncommon::start_data_table_row().
 2206:                                 '<td>'.$item.'</td>'.
 2207:                                 &Apache::loncommon::end_data_table_row()."\n";
 2208:                 }
 2209:             }
 2210:             $outcome .= &Apache::loncommon::end_data_table();
 2211:         } else {
 2212:             if (&Apache::lonnet::allowed('udp',$ccdomain)) {
 2213:                 # Current user has rights to view domain preferences for user's domain
 2214:                 my $result;
 2215:                 if ($currentauth =~ /^krb(4|5):([^:]*)$/) {
 2216:                     my ($krbver,$krbrealm) = ($1,$2);
 2217:                     if ($krbrealm eq '') {
 2218:                         $result = &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
 2219:                     } else {
 2220:                         $result = &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
 2221:                                       $krbrealm,$krbver);
 2222:                     }
 2223:                 } elsif ($currentauth =~ /^internal:/) {
 2224:                     $result = &mt('Currently internally authenticated.');
 2225:                 } elsif ($currentauth =~ /^localauth:/) {
 2226:                     $result = &mt('Currently using local (institutional) authentication.');
 2227:                 } elsif ($currentauth =~ /^unix:/) {
 2228:                     $result = &mt('Currently Filesystem Authenticated.');
 2229:                 }
 2230:                 $outcome = '<h3>'.$lt{'ld'}.'</h3>'.
 2231:                            &Apache::loncommon::start_data_table().
 2232:                            &Apache::loncommon::start_data_table_row().
 2233:                            '<td>'.$result.'</td>'.
 2234:                            &Apache::loncommon::end_data_table_row()."\n".
 2235:                            &Apache::loncommon::end_data_table();
 2236:             } elsif (&Apache::lonnet::allowed('mau',$env{'request.role.domain'})) {
 2237:                 my %lt=&Apache::lonlocal::texthash(
 2238:                            'ccld'  => "Change Current Login Data",
 2239:                            'yodo'  => "You do not have privileges to modify the authentication configuration for this user.",
 2240:                            'ifch'  => "If a change is required, contact a domain coordinator for the domain",
 2241:                 );
 2242:                 $outcome .= <<ENDNOPRIV;
 2243: <h3>$lt{'ccld'}</h3>
 2244: $lt{'yodo'} $lt{'ifch'}: $ccdomain
 2245: <input type="hidden" name="login" value="nochange" />
 2246: ENDNOPRIV
 2247:             }
 2248:         }
 2249:     }  ## End of "check for bad authentication type" logic
 2250:     return $outcome;
 2251: }
 2252: 
 2253: sub modify_login_block {
 2254:     my ($dom,$currentauth) = @_;
 2255:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 2256:     my ($authnum,%can_assign) =
 2257:         &Apache::loncommon::get_assignable_auth($dom);
 2258:     my ($authformcurrent,@authform_others,$show_override_msg);
 2259:     if ($currentauth=~/^krb(4|5):/) {
 2260:         $authformcurrent=$authformkrb;
 2261:         if ($can_assign{'int'}) {
 2262:             push(@authform_others,$authformint);
 2263:         }
 2264:         if ($can_assign{'loc'}) {
 2265:             push(@authform_others,$authformloc);
 2266:         }
 2267:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2268:             $show_override_msg = 1;
 2269:         }
 2270:     } elsif ($currentauth=~/^internal:/) {
 2271:         $authformcurrent=$authformint;
 2272:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2273:             push(@authform_others,$authformkrb);
 2274:         }
 2275:         if ($can_assign{'loc'}) {
 2276:             push(@authform_others,$authformloc);
 2277:         }
 2278:         if ($can_assign{'int'}) {
 2279:             $show_override_msg = 1;
 2280:         }
 2281:     } elsif ($currentauth=~/^unix:/) {
 2282:         $authformcurrent=$authformfsys;
 2283:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2284:             push(@authform_others,$authformkrb);
 2285:         }
 2286:         if ($can_assign{'int'}) {
 2287:             push(@authform_others,$authformint);
 2288:         }
 2289:         if ($can_assign{'loc'}) {
 2290:             push(@authform_others,$authformloc);
 2291:         }
 2292:         if ($can_assign{'fsys'}) {
 2293:             $show_override_msg = 1;
 2294:         }
 2295:     } elsif ($currentauth=~/^localauth:/) {
 2296:         $authformcurrent=$authformloc;
 2297:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2298:             push(@authform_others,$authformkrb);
 2299:         }
 2300:         if ($can_assign{'int'}) {
 2301:             push(@authform_others,$authformint);
 2302:         }
 2303:         if ($can_assign{'loc'}) {
 2304:             $show_override_msg = 1;
 2305:         }
 2306:     }
 2307:     if ($show_override_msg) {
 2308:         $authformcurrent = '<table><tr><td colspan="3">'.$authformcurrent.
 2309:                            '</td></tr>'."\n".
 2310:                            '<tr><td>&nbsp;&nbsp;&nbsp;</td>'.
 2311:                            '<td><b>'.&mt('Currently in use').'</b></td>'.
 2312:                            '<td align="right"><span class="LC_cusr_emph">'.
 2313:                             &mt('will override current values').
 2314:                             '</span></td></tr></table>';
 2315:     }
 2316:     return ($authformcurrent,$show_override_msg,@authform_others); 
 2317: }
 2318: 
 2319: sub personal_data_display {
 2320:     my ($ccuname,$ccdomain,$newuser,$context,$inst_results,$rolesarray,
 2321:         $now,$captchaform,$emailusername,$usertype) = @_;
 2322:     my ($output,%userenv,%canmodify,%canmodify_status);
 2323:     my @userinfo = ('firstname','middlename','lastname','generation',
 2324:                     'permanentemail','id');
 2325:     my $rowcount = 0;
 2326:     my $editable = 0;
 2327:     my %textboxsize = (
 2328:                        firstname      => '15',
 2329:                        middlename     => '15',
 2330:                        lastname       => '15',
 2331:                        generation     => '5',
 2332:                        permanentemail => '25',
 2333:                        id             => '15',
 2334:                       );
 2335: 
 2336:     my %lt=&Apache::lonlocal::texthash(
 2337:                 'pd'             => "Personal Data",
 2338:                 'firstname'      => "First Name",
 2339:                 'middlename'     => "Middle Name",
 2340:                 'lastname'       => "Last Name",
 2341:                 'generation'     => "Generation",
 2342:                 'permanentemail' => "Permanent e-mail address",
 2343:                 'id'             => "Student/Employee ID",
 2344:                 'lg'             => "Login Data",
 2345:                 'inststatus'     => "Affiliation",
 2346:                 'email'          => 'E-mail address',
 2347:                 'valid'          => 'Validation',
 2348:     );
 2349: 
 2350:     %canmodify_status =
 2351:         &Apache::lonuserutils::can_modify_userinfo($context,$ccdomain,
 2352:                                                    ['inststatus'],$rolesarray);
 2353:     if (!$newuser) {
 2354:         # Get the users information
 2355:         %userenv = &Apache::lonnet::get('environment',
 2356:                    ['firstname','middlename','lastname','generation',
 2357:                     'permanentemail','id','inststatus'],$ccdomain,$ccuname);
 2358:         %canmodify =
 2359:             &Apache::lonuserutils::can_modify_userinfo($context,$ccdomain,
 2360:                                                        \@userinfo,$rolesarray);
 2361:     } elsif ($context eq 'selfcreate') {
 2362:         if ($newuser eq 'email') {
 2363:             if (ref($emailusername) eq 'HASH') {
 2364:                 if (ref($emailusername->{$usertype}) eq 'HASH') {
 2365:                     my ($infofields,$infotitles) = &Apache::loncommon::emailusername_info();
 2366:                     @userinfo = ();          
 2367:                     if ((ref($infofields) eq 'ARRAY') && (ref($infotitles) eq 'HASH')) {
 2368:                         foreach my $field (@{$infofields}) { 
 2369:                             if ($emailusername->{$usertype}->{$field}) {
 2370:                                 push(@userinfo,$field);
 2371:                                 $canmodify{$field} = 1;
 2372:                                 unless ($textboxsize{$field}) {
 2373:                                     $textboxsize{$field} = 25;
 2374:                                 }
 2375:                                 unless ($lt{$field}) {
 2376:                                     $lt{$field} = $infotitles->{$field};
 2377:                                 }
 2378:                                 if ($emailusername->{$usertype}->{$field} eq 'required') {
 2379:                                     $lt{$field} .= '<b>*</b>';
 2380:                                 }
 2381:                             }
 2382:                         }
 2383:                     }
 2384:                 }
 2385:             }
 2386:         } else {
 2387:             %canmodify = &selfcreate_canmodify($context,$ccdomain,\@userinfo,
 2388:                                                $inst_results,$rolesarray);
 2389:         }
 2390:     }
 2391: 
 2392:     my $genhelp=&Apache::loncommon::help_open_topic('Generation');
 2393:     $output = '<h3>'.$lt{'pd'}.'</h3>'.
 2394:               &Apache::lonhtmlcommon::start_pick_box();
 2395:     if (($context eq 'selfcreate') && ($newuser eq 'email')) {
 2396:         $output .= &Apache::lonhtmlcommon::row_title($lt{'email'}.'<b>*</b>',undef,
 2397:                                                      'LC_oddrow_value')."\n".
 2398:                    '<input type="text" name="uname" size="25" value="" autocomplete="off" />';
 2399:         $rowcount ++;
 2400:         $output .= &Apache::lonhtmlcommon::row_closure(1);
 2401:         my $upassone = '<input type="password" name="upass'.$now.'" size="20" autocomplete="off" />';
 2402:         my $upasstwo = '<input type="password" name="upasscheck'.$now.'" size="20" autocomplete="off" />';
 2403:         $output .= &Apache::lonhtmlcommon::row_title(&mt('Password').'<b>*</b>',
 2404:                                                     'LC_pick_box_title',
 2405:                                                     'LC_oddrow_value')."\n".
 2406:                    $upassone."\n".
 2407:                    &Apache::lonhtmlcommon::row_closure(1)."\n".
 2408:                    &Apache::lonhtmlcommon::row_title(&mt('Confirm password').'<b>*</b>',
 2409:                                                      'LC_pick_box_title',
 2410:                                                      'LC_oddrow_value')."\n".
 2411:                    $upasstwo.
 2412:                    &Apache::lonhtmlcommon::row_closure()."\n";
 2413:     }
 2414:     foreach my $item (@userinfo) {
 2415:         my $rowtitle = $lt{$item};
 2416:         my $hiderow = 0;
 2417:         if ($item eq 'generation') {
 2418:             $rowtitle = $genhelp.$rowtitle;
 2419:         }
 2420:         my $row = &Apache::lonhtmlcommon::row_title($rowtitle,undef,'LC_oddrow_value')."\n";
 2421:         if ($newuser) {
 2422:             if (ref($inst_results) eq 'HASH') {
 2423:                 if ($inst_results->{$item} ne '') {
 2424:                     $row .= '<input type="hidden" name="c'.$item.'" value="'.$inst_results->{$item}.'" />'.$inst_results->{$item};
 2425:                 } else {
 2426:                     if ($context eq 'selfcreate') {
 2427:                         if ($canmodify{$item}) {
 2428:                             $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="" autocomplete="off" />';
 2429:                             $editable ++;
 2430:                         } else {
 2431:                             $hiderow = 1;
 2432:                         }
 2433:                     } else {
 2434:                         $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="" />';
 2435:                     }
 2436:                 }
 2437:             } else {
 2438:                 if ($context eq 'selfcreate') {
 2439:                     if ($canmodify{$item}) {
 2440:                         if ($newuser eq 'email') {
 2441:                             $row .= '<input type="text" name="'.$item.'" size="'.$textboxsize{$item}.'" value="" autocomplete="off" />';
 2442:                         } else {
 2443:                             $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="" autocomplete="off" />';
 2444:                         }
 2445:                         $editable ++;
 2446:                     } else {
 2447:                         $hiderow = 1;
 2448:                     }
 2449:                 } else {
 2450:                     $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="" />';
 2451:                 }
 2452:             }
 2453:         } else {
 2454:             if ($canmodify{$item}) {
 2455:                 $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="'.$userenv{$item}.'" />';
 2456:                 if (($item eq 'id') && (!$newuser)) {
 2457:                     $row .= '<br />'.&Apache::lonuserutils::forceid_change($context);
 2458:                 }
 2459:             } else {
 2460:                 $row .= $userenv{$item};
 2461:             }
 2462:         }
 2463:         $row .= &Apache::lonhtmlcommon::row_closure(1);
 2464:         if (!$hiderow) {
 2465:             $output .= $row;
 2466:             $rowcount ++;
 2467:         }
 2468:     }
 2469:     if (($canmodify_status{'inststatus'}) || ($context ne 'selfcreate')) {
 2470:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($ccdomain);
 2471:         if (ref($types) eq 'ARRAY') {
 2472:             if (@{$types} > 0) {
 2473:                 my ($hiderow,$shown);
 2474:                 if ($canmodify_status{'inststatus'}) {
 2475:                     $shown = &pick_inst_statuses($userenv{'inststatus'},$usertypes,$types);
 2476:                 } else {
 2477:                     if ($userenv{'inststatus'} eq '') {
 2478:                         $hiderow = 1;
 2479:                     } else {
 2480:                         my @showitems;
 2481:                         foreach my $item ( map { &unescape($_); } split(':',$userenv{'inststatus'})) {
 2482:                             if (exists($usertypes->{$item})) {
 2483:                                 push(@showitems,$usertypes->{$item});
 2484:                             } else {
 2485:                                 push(@showitems,$item);
 2486:                             }
 2487:                         }
 2488:                         if (@showitems) {
 2489:                             $shown = join(', ',@showitems);
 2490:                         } else {
 2491:                             $hiderow = 1;
 2492:                         }
 2493:                     }
 2494:                 }
 2495:                 if (!$hiderow) {
 2496:                     my $row = &Apache::lonhtmlcommon::row_title(&mt('Affiliations'),undef,'LC_oddrow_value')."\n".
 2497:                               $shown.&Apache::lonhtmlcommon::row_closure(1); 
 2498:                     if ($context eq 'selfcreate') {
 2499:                         $rowcount ++;
 2500:                     }
 2501:                     $output .= $row;
 2502:                 }
 2503:             }
 2504:         }
 2505:     }
 2506:     if (($context eq 'selfcreate') && ($newuser eq 'email')) {
 2507:         if ($captchaform) {
 2508:             $output .= &Apache::lonhtmlcommon::row_title($lt{'valid'}.'*',
 2509:                                                          'LC_pick_box_title')."\n".
 2510:                        $captchaform."\n".'<br /><br />'.
 2511:                        &Apache::lonhtmlcommon::row_closure(1); 
 2512:             $rowcount ++;
 2513:         }
 2514:         my $submit_text = &mt('Create account');
 2515:         $output .= &Apache::lonhtmlcommon::row_title()."\n".
 2516:                    '<br /><input type="submit" name="createaccount" value="'.
 2517:                    $submit_text.'" />'.
 2518:                    '<input type="hidden" name="type" value="'.$usertype.'" />'.
 2519:                    &Apache::lonhtmlcommon::row_closure(1);
 2520:     }
 2521:     $output .= &Apache::lonhtmlcommon::end_pick_box();
 2522:     if (wantarray) {
 2523:         if ($context eq 'selfcreate') {
 2524:             return($output,$rowcount,$editable);
 2525:         } else {
 2526:             return $output;
 2527:         }
 2528:     } else {
 2529:         return $output;
 2530:     }
 2531: }
 2532: 
 2533: sub pick_inst_statuses {
 2534:     my ($curr,$usertypes,$types) = @_;
 2535:     my ($output,$rem,@currtypes);
 2536:     if ($curr ne '') {
 2537:         @currtypes = map { &unescape($_); } split(/:/,$curr);
 2538:     }
 2539:     my $numinrow = 2;
 2540:     if (ref($types) eq 'ARRAY') {
 2541:         $output = '<table>';
 2542:         my $lastcolspan; 
 2543:         for (my $i=0; $i<@{$types}; $i++) {
 2544:             if (defined($usertypes->{$types->[$i]})) {
 2545:                 my $rem = $i%($numinrow);
 2546:                 if ($rem == 0) {
 2547:                     if ($i<@{$types}-1) {
 2548:                         if ($i > 0) { 
 2549:                             $output .= '</tr>';
 2550:                         }
 2551:                         $output .= '<tr>';
 2552:                     }
 2553:                 } elsif ($i==@{$types}-1) {
 2554:                     my $colsleft = $numinrow - $rem;
 2555:                     if ($colsleft > 1) {
 2556:                         $lastcolspan = ' colspan="'.$colsleft.'"';
 2557:                     }
 2558:                 }
 2559:                 my $check = ' ';
 2560:                 if (grep(/^\Q$types->[$i]\E$/,@currtypes)) {
 2561:                     $check = ' checked="checked" ';
 2562:                 }
 2563:                 $output .= '<td class="LC_left_item"'.$lastcolspan.'>'.
 2564:                            '<span class="LC_nobreak"><label>'.
 2565:                            '<input type="checkbox" name="inststatus" '.
 2566:                            'value="'.$types->[$i].'"'.$check.'/>'.
 2567:                            $usertypes->{$types->[$i]}.'</label></span></td>';
 2568:             }
 2569:         }
 2570:         $output .= '</tr></table>';
 2571:     }
 2572:     return $output;
 2573: }
 2574: 
 2575: sub selfcreate_canmodify {
 2576:     my ($context,$dom,$userinfo,$inst_results,$rolesarray) = @_;
 2577:     if (ref($inst_results) eq 'HASH') {
 2578:         my @inststatuses = &get_inststatuses($inst_results);
 2579:         if (@inststatuses == 0) {
 2580:             @inststatuses = ('default');
 2581:         }
 2582:         $rolesarray = \@inststatuses;
 2583:     }
 2584:     my %canmodify =
 2585:         &Apache::lonuserutils::can_modify_userinfo($context,$dom,$userinfo,
 2586:                                                    $rolesarray);
 2587:     return %canmodify;
 2588: }
 2589: 
 2590: sub get_inststatuses {
 2591:     my ($insthashref) = @_;
 2592:     my @inststatuses = ();
 2593:     if (ref($insthashref) eq 'HASH') {
 2594:         if (ref($insthashref->{'inststatus'}) eq 'ARRAY') {
 2595:             @inststatuses = @{$insthashref->{'inststatus'}};
 2596:         }
 2597:     }
 2598:     return @inststatuses;
 2599: }
 2600: 
 2601: # ================================================================= Phase Three
 2602: sub update_user_data {
 2603:     my ($r,$context,$crstype,$brcrum,$showcredits) = @_; 
 2604:     my $uhome=&Apache::lonnet::homeserver($env{'form.ccuname'},
 2605:                                           $env{'form.ccdomain'});
 2606:     # Error messages
 2607:     my $error     = '<span class="LC_error">'.&mt('Error').': ';
 2608:     my $end       = '</span><br /><br />';
 2609:     my $rtnlink   = '<a href="javascript:backPage(document.userupdate,'.
 2610:                     "'$env{'form.prevphase'}','modify')".'" />'.
 2611:                     &mt('Return to previous page').'</a>'.
 2612:                     &Apache::loncommon::end_page();
 2613:     my $now = time;
 2614:     my $title;
 2615:     if (exists($env{'form.makeuser'})) {
 2616: 	$title='Set Privileges for New User';
 2617:     } else {
 2618:         $title='Modify User Privileges';
 2619:     }
 2620:     my $newuser = 0;
 2621:     my ($jsback,$elements) = &crumb_utilities();
 2622:     my $jscript = '<script type="text/javascript">'."\n".
 2623:                   '// <![CDATA['."\n".
 2624:                   $jsback."\n".
 2625:                   '// ]]>'."\n".
 2626:                   '</script>'."\n";
 2627:     my %breadcrumb_text = &singleuser_breadcrumb($crstype,$context,$env{'form.ccdomain'});
 2628:     push (@{$brcrum},
 2629:              {href => "javascript:backPage(document.userupdate)",
 2630:               text => $breadcrumb_text{'search'},
 2631:               faq  => 282,
 2632:               bug  => 'Instructor Interface',}
 2633:              );
 2634:     if ($env{'form.prevphase'} eq 'userpicked') {
 2635:         push(@{$brcrum},
 2636:                {href => "javascript:backPage(document.userupdate,'get_user_info','select')",
 2637:                 text => $breadcrumb_text{'userpicked'},
 2638:                 faq  => 282,
 2639:                 bug  => 'Instructor Interface',});
 2640:     }
 2641:     my $helpitem = 'Course_Change_Privileges';
 2642:     if ($env{'form.action'} eq 'singlestudent') {
 2643:         $helpitem = 'Course_Add_Student';
 2644:     }
 2645:     push(@{$brcrum}, 
 2646:             {href => "javascript:backPage(document.userupdate,'$env{'form.prevphase'}','modify')",
 2647:              text => $breadcrumb_text{'modify'},
 2648:              faq  => 282,
 2649:              bug  => 'Instructor Interface',},
 2650:             {href => "/adm/createuser",
 2651:              text => "Result",
 2652:              faq  => 282,
 2653:              bug  => 'Instructor Interface',
 2654:              help => $helpitem});
 2655:     my $args = {bread_crumbs          => $brcrum,
 2656:                 bread_crumbs_component => 'User Management'};
 2657:     if ($env{'form.popup'}) {
 2658:         $args->{'no_nav_bar'} = 1;
 2659:     }
 2660:     $r->print(&Apache::loncommon::start_page($title,$jscript,$args));
 2661:     $r->print(&update_result_form($uhome));
 2662:     # Check Inputs
 2663:     if (! $env{'form.ccuname'} ) {
 2664: 	$r->print($error.&mt('No login name specified').'.'.$end.$rtnlink);
 2665: 	return;
 2666:     }
 2667:     if (  $env{'form.ccuname'} ne 
 2668: 	  &LONCAPA::clean_username($env{'form.ccuname'}) ) {
 2669: 	$r->print($error.&mt('Invalid login name.').'  '.
 2670: 		  &mt('Only letters, numbers, periods, dashes, @, and underscores are valid.').
 2671: 		  $end.$rtnlink);
 2672: 	return;
 2673:     }
 2674:     if (! $env{'form.ccdomain'}       ) {
 2675: 	$r->print($error.&mt('No domain specified').'.'.$end.$rtnlink);
 2676: 	return;
 2677:     }
 2678:     if (  $env{'form.ccdomain'} ne
 2679: 	  &LONCAPA::clean_domain($env{'form.ccdomain'}) ) {
 2680: 	$r->print($error.&mt('Invalid domain name.').'  '.
 2681: 		  &mt('Only letters, numbers, periods, dashes, and underscores are valid.').
 2682: 		  $end.$rtnlink);
 2683: 	return;
 2684:     }
 2685:     if ($uhome eq 'no_host') {
 2686:         $newuser = 1;
 2687:     }
 2688:     if (! exists($env{'form.makeuser'})) {
 2689:         # Modifying an existing user, so check the validity of the name
 2690:         if ($uhome eq 'no_host') {
 2691:             $r->print(
 2692:                 $error
 2693:                .'<p class="LC_error">'
 2694:                .&mt('Unable to determine home server for [_1] in domain [_2].',
 2695:                         '"'.$env{'form.ccuname'}.'"','"'.$env{'form.ccdomain'}.'"')
 2696:                .'</p>');
 2697:             return;
 2698:         }
 2699:     }
 2700:     # Determine authentication method and password for the user being modified
 2701:     my $amode='';
 2702:     my $genpwd='';
 2703:     if ($env{'form.login'} eq 'krb') {
 2704: 	$amode='krb';
 2705: 	$amode.=$env{'form.krbver'};
 2706: 	$genpwd=$env{'form.krbarg'};
 2707:     } elsif ($env{'form.login'} eq 'int') {
 2708: 	$amode='internal';
 2709: 	$genpwd=$env{'form.intarg'};
 2710:     } elsif ($env{'form.login'} eq 'fsys') {
 2711: 	$amode='unix';
 2712: 	$genpwd=$env{'form.fsysarg'};
 2713:     } elsif ($env{'form.login'} eq 'loc') {
 2714: 	$amode='localauth';
 2715: 	$genpwd=$env{'form.locarg'};
 2716: 	$genpwd=" " if (!$genpwd);
 2717:     } elsif (($env{'form.login'} eq 'nochange') ||
 2718:              ($env{'form.login'} eq ''        )) { 
 2719:         # There is no need to tell the user we did not change what they
 2720:         # did not ask us to change.
 2721:         # If they are creating a new user but have not specified login
 2722:         # information this will be caught below.
 2723:     } else {
 2724:             $r->print($error.&mt('Invalid login mode or password').$end.$rtnlink);
 2725:             return;
 2726:     }
 2727: 
 2728:     $r->print('<h3>'.&mt('User [_1] in domain [_2]',
 2729:                         $env{'form.ccuname'}.' ('.&Apache::loncommon::plainname($env{'form.ccuname'},
 2730:                         $env{'form.ccdomain'}).')', $env{'form.ccdomain'}).'</h3>');
 2731:     my %prog_state = &Apache::lonhtmlcommon::Create_PrgWin($r,2);
 2732: 
 2733:     my (%alerts,%rulematch,%inst_results,%curr_rules);
 2734:     my @userinfo = ('firstname','middlename','lastname','generation','permanentemail','id');
 2735:     my @usertools = ('aboutme','blog','webdav','portfolio');
 2736:     my @requestcourses = ('official','unofficial','community','textbook','placement');
 2737:     my @requestauthor = ('requestauthor');
 2738:     my ($othertitle,$usertypes,$types) = 
 2739:         &Apache::loncommon::sorted_inst_types($env{'form.ccdomain'});
 2740:     my %canmodify_status =
 2741:         &Apache::lonuserutils::can_modify_userinfo($context,$env{'form.ccdomain'},
 2742:                                                    ['inststatus']);
 2743:     if ($env{'form.makeuser'}) {
 2744: 	$r->print('<h3>'.&mt('Creating new account.').'</h3>');
 2745:         # Check for the authentication mode and password
 2746:         if (! $amode || ! $genpwd) {
 2747: 	    $r->print($error.&mt('Invalid login mode or password').$end.$rtnlink);    
 2748: 	    return;
 2749: 	}
 2750:         # Determine desired host
 2751:         my $desiredhost = $env{'form.hserver'};
 2752:         if (lc($desiredhost) eq 'default') {
 2753:             $desiredhost = undef;
 2754:         } else {
 2755:             my %home_servers = 
 2756: 		&Apache::lonnet::get_servers($env{'form.ccdomain'},'library');
 2757:             if (! exists($home_servers{$desiredhost})) {
 2758:                 $r->print($error.&mt('Invalid home server specified').$end.$rtnlink);
 2759:                 return;
 2760:             }
 2761:         }
 2762:         # Check ID format
 2763:         my %checkhash;
 2764:         my %checks = ('id' => 1);
 2765:         %{$checkhash{$env{'form.ccuname'}.':'.$env{'form.ccdomain'}}} = (
 2766:             'newuser' => $newuser, 
 2767:             'id' => $env{'form.cid'},
 2768:         );
 2769:         if ($env{'form.cid'} ne '') {
 2770:             &Apache::loncommon::user_rule_check(\%checkhash,\%checks,\%alerts,
 2771:                                           \%rulematch,\%inst_results,\%curr_rules);
 2772:             if (ref($alerts{'id'}) eq 'HASH') {
 2773:                 if (ref($alerts{'id'}{$env{'form.ccdomain'}}) eq 'HASH') {
 2774:                     my $domdesc =
 2775:                         &Apache::lonnet::domain($env{'form.ccdomain'},'description');
 2776:                     if ($alerts{'id'}{$env{'form.ccdomain'}}{$env{'form.cid'}}) {
 2777:                         my $userchkmsg;
 2778:                         if (ref($curr_rules{$env{'form.ccdomain'}}) eq 'HASH') {
 2779:                             $userchkmsg  = 
 2780:                                 &Apache::loncommon::instrule_disallow_msg('id',
 2781:                                                                     $domdesc,1).
 2782:                                 &Apache::loncommon::user_rule_formats($env{'form.ccdomain'},
 2783:                                     $domdesc,$curr_rules{$env{'form.ccdomain'}}{'id'},'id');
 2784:                         }
 2785:                         $r->print($error.&mt('Invalid ID format').$end.
 2786:                                   $userchkmsg.$rtnlink);
 2787:                         return;
 2788:                     }
 2789:                 }
 2790:             }
 2791:         }
 2792:         &Apache::lonhtmlcommon::Increment_PrgWin($r, \%prog_state);
 2793: 	# Call modifyuser
 2794: 	my $result = &Apache::lonnet::modifyuser
 2795: 	    ($env{'form.ccdomain'},$env{'form.ccuname'},$env{'form.cid'},
 2796:              $amode,$genpwd,$env{'form.cfirstname'},
 2797:              $env{'form.cmiddlename'},$env{'form.clastname'},
 2798:              $env{'form.cgeneration'},undef,$desiredhost,
 2799:              $env{'form.cpermanentemail'});
 2800: 	$r->print(&mt('Generating user').': '.$result);
 2801:         $uhome = &Apache::lonnet::homeserver($env{'form.ccuname'},
 2802:                                                $env{'form.ccdomain'});
 2803:         my (%changeHash,%newcustom,%changed,%changedinfo);
 2804:         if ($uhome ne 'no_host') {
 2805:             if ($context eq 'domain') {
 2806:                 foreach my $name ('portfolio','author') {
 2807:                     if ($env{'form.custom_'.$name.'quota'} == 1) {
 2808:                         if ($env{'form.'.$name.'quota'} eq '') {
 2809:                             $newcustom{$name.'quota'} = 0;
 2810:                         } else {
 2811:                             $newcustom{$name.'quota'} = $env{'form.'.$name.'quota'};
 2812:                             $newcustom{$name.'quota'} =~ s/[^\d\.]//g;
 2813:                         }
 2814:                         if (&quota_admin($newcustom{$name.'quota'},\%changeHash,$name)) {
 2815:                             $changed{$name.'quota'} = 1;
 2816:                         }
 2817:                     }
 2818:                 }
 2819:                 foreach my $item (@usertools) {
 2820:                     if ($env{'form.custom'.$item} == 1) {
 2821:                         $newcustom{$item} = $env{'form.tools_'.$item};
 2822:                         $changed{$item} = &tool_admin($item,$newcustom{$item},
 2823:                                                      \%changeHash,'tools');
 2824:                     }
 2825:                 }
 2826:                 foreach my $item (@requestcourses) {
 2827:                     if ($env{'form.custom'.$item} == 1) {
 2828:                         $newcustom{$item} = $env{'form.crsreq_'.$item};
 2829:                         if ($env{'form.crsreq_'.$item} eq 'autolimit') {
 2830:                             $newcustom{$item} .= '=';
 2831:                             $env{'form.crsreq_'.$item.'_limit'} =~ s/\D+//g;
 2832:                             if ($env{'form.crsreq_'.$item.'_limit'}) {
 2833:                                 $newcustom{$item} .= $env{'form.crsreq_'.$item.'_limit'};
 2834:                             }
 2835:                         }
 2836:                         $changed{$item} = &tool_admin($item,$newcustom{$item},
 2837:                                                       \%changeHash,'requestcourses');
 2838:                     }
 2839:                 }
 2840:                 if ($env{'form.customrequestauthor'} == 1) {
 2841:                     $newcustom{'requestauthor'} = $env{'form.requestauthor'};
 2842:                     $changed{'requestauthor'} = &tool_admin('requestauthor',
 2843:                                                     $newcustom{'requestauthor'},
 2844:                                                     \%changeHash,'requestauthor');
 2845:                 }
 2846:             }
 2847:             if ($canmodify_status{'inststatus'}) {
 2848:                 if (exists($env{'form.inststatus'})) {
 2849:                     my @inststatuses = &Apache::loncommon::get_env_multiple('form.inststatus');
 2850:                     if (@inststatuses > 0) {
 2851:                         $changeHash{'inststatus'} = join(',',@inststatuses);
 2852:                         $changed{'inststatus'} = $changeHash{'inststatus'};
 2853:                     }
 2854:                 }
 2855:             }
 2856:             if (keys(%changed)) {
 2857:                 foreach my $item (@userinfo) {
 2858:                     $changeHash{$item}  = $env{'form.c'.$item};
 2859:                 }
 2860:                 my $chgresult =
 2861:                      &Apache::lonnet::put('environment',\%changeHash,
 2862:                                           $env{'form.ccdomain'},$env{'form.ccuname'});
 2863:             } 
 2864:         }
 2865:         $r->print('<br />'.&mt('Home server').': '.$uhome.' '.
 2866:                   &Apache::lonnet::hostname($uhome));
 2867:     } elsif (($env{'form.login'} ne 'nochange') &&
 2868:              ($env{'form.login'} ne ''        )) {
 2869: 	# Modify user privileges
 2870:         if (! $amode || ! $genpwd) {
 2871: 	    $r->print($error.'Invalid login mode or password'.$end.$rtnlink);    
 2872: 	    return;
 2873: 	}
 2874: 	# Only allow authentication modification if the person has authority
 2875: 	if (&Apache::lonnet::allowed('mau',$env{'form.ccdomain'})) {
 2876: 	    $r->print('Modifying authentication: '.
 2877:                       &Apache::lonnet::modifyuserauth(
 2878: 		       $env{'form.ccdomain'},$env{'form.ccuname'},
 2879:                        $amode,$genpwd));
 2880:             $r->print('<br />'.&mt('Home server').': '.&Apache::lonnet::homeserver
 2881: 		  ($env{'form.ccuname'},$env{'form.ccdomain'}));
 2882: 	} else {
 2883: 	    # Okay, this is a non-fatal error.
 2884: 	    $r->print($error.&mt('You do not have the authority to modify this users authentication information.').$end);    
 2885: 	}
 2886:     }
 2887:     $r->rflush(); # Finish display of header before time consuming actions start
 2888:     &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state);
 2889:     ##
 2890:     my (@userroles,%userupdate,$cnum,$cdom,$defaultcredits,%namechanged);
 2891:     if ($context eq 'course') {
 2892:         ($cnum,$cdom) =
 2893:             &Apache::lonuserutils::get_course_identity();
 2894:         $crstype = &Apache::loncommon::course_type($cdom.'_'.$cnum);
 2895:         if ($showcredits) {
 2896:            $defaultcredits = &Apache::lonuserutils::get_defaultcredits($cdom,$cnum);
 2897:         }
 2898:     }
 2899:     if (! $env{'form.makeuser'} ) {
 2900:         # Check for need to change
 2901:         my %userenv = &Apache::lonnet::get
 2902:             ('environment',['firstname','middlename','lastname','generation',
 2903:              'id','permanentemail','portfolioquota','authorquota','inststatus',
 2904:              'tools.aboutme','tools.blog','tools.webdav','tools.portfolio',
 2905:              'requestcourses.official','requestcourses.unofficial',
 2906:              'requestcourses.community','requestcourses.textbook',
 2907:              'reqcrsotherdom.official','reqcrsotherdom.unofficial',
 2908:              'reqcrsotherdom.community','reqcrsotherdom.textbook',
 2909:              'reqcrsotherdom.placement','requestauthor'],
 2910:               $env{'form.ccdomain'},$env{'form.ccuname'});
 2911:         my ($tmp) = keys(%userenv);
 2912:         if ($tmp =~ /^(con_lost|error)/i) { 
 2913:             %userenv = ();
 2914:         }
 2915:         my $no_forceid_alert;
 2916:         # Check to see if user information can be changed
 2917:         my %domconfig =
 2918:             &Apache::lonnet::get_dom('configuration',['usermodification'],
 2919:                                      $env{'form.ccdomain'});
 2920:         my @statuses = ('active','future');
 2921:         my %roles = &Apache::lonnet::get_my_roles($env{'form.ccuname'},$env{'form.ccdomain'},'userroles',\@statuses,undef,$env{'request.role.domain'});
 2922:         my ($auname,$audom);
 2923:         if ($context eq 'author') {
 2924:             $auname = $env{'user.name'};
 2925:             $audom = $env{'user.domain'};     
 2926:         }
 2927:         foreach my $item (keys(%roles)) {
 2928:             my ($rolenum,$roledom,$role) = split(/:/,$item,-1);
 2929:             if ($context eq 'course') {
 2930:                 if ($cnum ne '' && $cdom ne '') {
 2931:                     if ($rolenum eq $cnum && $roledom eq $cdom) {
 2932:                         if (!grep(/^\Q$role\E$/,@userroles)) {
 2933:                             push(@userroles,$role);
 2934:                         }
 2935:                     }
 2936:                 }
 2937:             } elsif ($context eq 'author') {
 2938:                 if ($rolenum eq $auname && $roledom eq $audom) {
 2939:                     if (!grep(/^\Q$role\E$/,@userroles)) { 
 2940:                         push(@userroles,$role);
 2941:                     }
 2942:                 }
 2943:             }
 2944:         }
 2945:         if ($env{'form.action'} eq 'singlestudent') {
 2946:             if (!grep(/^st$/,@userroles)) {
 2947:                 push(@userroles,'st');
 2948:             }
 2949:         } else {
 2950:             # Check for course or co-author roles being activated or re-enabled
 2951:             if ($context eq 'author' || $context eq 'course') {
 2952:                 foreach my $key (keys(%env)) {
 2953:                     if ($context eq 'author') {
 2954:                         if ($key=~/^form\.act_\Q$audom\E_\Q$auname\E_([^_]+)/) {
 2955:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 2956:                                 push(@userroles,$1);
 2957:                             }
 2958:                         } elsif ($key =~/^form\.ren\:\Q$audom\E\/\Q$auname\E_([^_]+)/) {
 2959:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 2960:                                 push(@userroles,$1);
 2961:                             }
 2962:                         }
 2963:                     } elsif ($context eq 'course') {
 2964:                         if ($key=~/^form\.act_\Q$cdom\E_\Q$cnum\E_([^_]+)/) {
 2965:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 2966:                                 push(@userroles,$1);
 2967:                             }
 2968:                         } elsif ($key =~/^form\.ren\:\Q$cdom\E\/\Q$cnum\E(\/?\w*)_([^_]+)/) {
 2969:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 2970:                                 push(@userroles,$1);
 2971:                             }
 2972:                         }
 2973:                     }
 2974:                 }
 2975:             }
 2976:         }
 2977:         #Check to see if we can change personal data for the user 
 2978:         my (@mod_disallowed,@longroles);
 2979:         foreach my $role (@userroles) {
 2980:             if ($role eq 'cr') {
 2981:                 push(@longroles,'Custom');
 2982:             } else {
 2983:                 push(@longroles,&Apache::lonnet::plaintext($role,$crstype)); 
 2984:             }
 2985:         }
 2986:         my %canmodify = &Apache::lonuserutils::can_modify_userinfo($context,$env{'form.ccdomain'},\@userinfo,\@userroles);
 2987:         foreach my $item (@userinfo) {
 2988:             # Strip leading and trailing whitespace
 2989:             $env{'form.c'.$item} =~ s/(\s+$|^\s+)//g;
 2990:             if (!$canmodify{$item}) {
 2991:                 if (defined($env{'form.c'.$item})) {
 2992:                     if ($env{'form.c'.$item} ne $userenv{$item}) {
 2993:                         push(@mod_disallowed,$item);
 2994:                     }
 2995:                 }
 2996:                 $env{'form.c'.$item} = $userenv{$item};
 2997:             }
 2998:         }
 2999:         # Check to see if we can change the Student/Employee ID
 3000:         my $forceid = $env{'form.forceid'};
 3001:         my $recurseid = $env{'form.recurseid'};
 3002:         my (%alerts,%rulematch,%idinst_results,%curr_rules,%got_rules);
 3003:         my %uidhash = &Apache::lonnet::idrget($env{'form.ccdomain'},
 3004:                                             $env{'form.ccuname'});
 3005:         if (($uidhash{$env{'form.ccuname'}}) && 
 3006:             ($uidhash{$env{'form.ccuname'}}!~/error\:/) && 
 3007:             (!$forceid)) {
 3008:             if ($env{'form.cid'} ne $uidhash{$env{'form.ccuname'}}) {
 3009:                 $env{'form.cid'} = $userenv{'id'};
 3010:                 $no_forceid_alert = &mt('New student/employee ID does not match existing ID for this user.')
 3011:                                    .'<br />'
 3012:                                    .&mt("Change is not permitted without checking the 'Force ID change' checkbox on the previous page.")
 3013:                                    .'<br />'."\n";
 3014:             }
 3015:         }
 3016:         if ($env{'form.cid'} ne $userenv{'id'}) {
 3017:             my $checkhash;
 3018:             my $checks = { 'id' => 1 };
 3019:             $checkhash->{$env{'form.ccuname'}.':'.$env{'form.ccdomain'}} = 
 3020:                    { 'newuser' => $newuser,
 3021:                      'id'  => $env{'form.cid'}, 
 3022:                    };
 3023:             &Apache::loncommon::user_rule_check($checkhash,$checks,
 3024:                 \%alerts,\%rulematch,\%idinst_results,\%curr_rules,\%got_rules);
 3025:             if (ref($alerts{'id'}) eq 'HASH') {
 3026:                 if (ref($alerts{'id'}{$env{'form.ccdomain'}}) eq 'HASH') {
 3027:                    $env{'form.cid'} = $userenv{'id'};
 3028:                 }
 3029:             }
 3030:         }
 3031:         my (%quotachanged,%oldquota,%newquota,%olddefquota,%newdefquota, 
 3032:             $oldinststatus,$newinststatus,%oldisdefault,%newisdefault,%oldsettings,
 3033:             %oldsettingstext,%newsettings,%newsettingstext,@disporder,
 3034:             %oldsettingstatus,%newsettingstatus);
 3035:         @disporder = ('inststatus');
 3036:         if ($env{'request.role.domain'} eq $env{'form.ccdomain'}) {
 3037:             push(@disporder,'requestcourses','requestauthor');
 3038:         } else {
 3039:             push(@disporder,'reqcrsotherdom');
 3040:         }
 3041:         push(@disporder,('quota','tools'));
 3042:         $oldinststatus = $userenv{'inststatus'};
 3043:         foreach my $name ('portfolio','author') {
 3044:             ($olddefquota{$name},$oldsettingstatus{$name}) = 
 3045:                 &Apache::loncommon::default_quota($env{'form.ccdomain'},$oldinststatus,$name);
 3046:             ($newdefquota{$name},$newsettingstatus{$name}) = ($olddefquota{$name},$oldsettingstatus{$name});
 3047:         }
 3048:         my %canshow;
 3049:         if (&Apache::lonnet::allowed('mpq',$env{'form.ccdomain'})) {
 3050:             $canshow{'quota'} = 1;
 3051:         }
 3052:         if (&Apache::lonnet::allowed('mut',$env{'form.ccdomain'})) {
 3053:             $canshow{'tools'} = 1;
 3054:         }
 3055:         if (&Apache::lonnet::allowed('ccc',$env{'form.ccdomain'})) {
 3056:             $canshow{'requestcourses'} = 1;
 3057:         } elsif (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) {
 3058:             $canshow{'reqcrsotherdom'} = 1;
 3059:         }
 3060:         if (&Apache::lonnet::allowed('mau',$env{'form.ccdomain'})) {
 3061:             $canshow{'inststatus'} = 1;
 3062:         }
 3063:         if (&Apache::lonnet::allowed('cau',$env{'form.ccdomain'})) {
 3064:             $canshow{'requestauthor'} = 1;
 3065:         }
 3066:         my (%changeHash,%changed);
 3067:         if ($oldinststatus eq '') {
 3068:             $oldsettings{'inststatus'} = $othertitle; 
 3069:         } else {
 3070:             if (ref($usertypes) eq 'HASH') {
 3071:                 $oldsettings{'inststatus'} = join(', ',map{ $usertypes->{ &unescape($_) }; } (split(/:/,$userenv{'inststatus'})));
 3072:             } else {
 3073:                 $oldsettings{'inststatus'} = join(', ',map{ &unescape($_); } (split(/:/,$userenv{'inststatus'})));
 3074:             }
 3075:         }
 3076:         $changeHash{'inststatus'} = $userenv{'inststatus'};
 3077:         if ($canmodify_status{'inststatus'}) {
 3078:             $canshow{'inststatus'} = 1;
 3079:             if (exists($env{'form.inststatus'})) {
 3080:                 my @inststatuses = &Apache::loncommon::get_env_multiple('form.inststatus');
 3081:                 if (@inststatuses > 0) {
 3082:                     $newinststatus = join(':',map { &escape($_); } @inststatuses);
 3083:                     $changeHash{'inststatus'} = $newinststatus;
 3084:                     if ($newinststatus ne $oldinststatus) {
 3085:                         $changed{'inststatus'} = $newinststatus;
 3086:                         foreach my $name ('portfolio','author') {
 3087:                             ($newdefquota{$name},$newsettingstatus{$name}) =
 3088:                                 &Apache::loncommon::default_quota($env{'form.ccdomain'},$newinststatus,$name);
 3089:                         }
 3090:                     }
 3091:                     if (ref($usertypes) eq 'HASH') {
 3092:                         $newsettings{'inststatus'} = join(', ',map{ $usertypes->{$_}; } (@inststatuses)); 
 3093:                     } else {
 3094:                         $newsettings{'inststatus'} = join(', ',@inststatuses);
 3095:                     }
 3096:                 }
 3097:             } else {
 3098:                 $newinststatus = '';
 3099:                 $changeHash{'inststatus'} = $newinststatus;
 3100:                 $newsettings{'inststatus'} = $othertitle;
 3101:                 if ($newinststatus ne $oldinststatus) {
 3102:                     $changed{'inststatus'} = $changeHash{'inststatus'};
 3103:                     foreach my $name ('portfolio','author') {
 3104:                         ($newdefquota{$name},$newsettingstatus{$name}) =
 3105:                             &Apache::loncommon::default_quota($env{'form.ccdomain'},$newinststatus,$name);
 3106:                     }
 3107:                 }
 3108:             }
 3109:         } elsif ($context ne 'selfcreate') {
 3110:             $canshow{'inststatus'} = 1;
 3111:             $newsettings{'inststatus'} = $oldsettings{'inststatus'};
 3112:         }
 3113:         foreach my $name ('portfolio','author') {
 3114:             $changeHash{$name.'quota'} = $userenv{$name.'quota'};
 3115:         }
 3116:         if ($context eq 'domain') {
 3117:             foreach my $name ('portfolio','author') {
 3118:                 if ($userenv{$name.'quota'} ne '') {
 3119:                     $oldquota{$name} = $userenv{$name.'quota'};
 3120:                     if ($env{'form.custom_'.$name.'quota'} == 1) {
 3121:                         if ($env{'form.'.$name.'quota'} eq '') {
 3122:                             $newquota{$name} = 0;
 3123:                         } else {
 3124:                             $newquota{$name} = $env{'form.'.$name.'quota'};
 3125:                             $newquota{$name} =~ s/[^\d\.]//g;
 3126:                         }
 3127:                         if ($newquota{$name} != $oldquota{$name}) {
 3128:                             if (&quota_admin($newquota{$name},\%changeHash,$name)) {
 3129:                                 $changed{$name.'quota'} = 1;
 3130:                             }
 3131:                         }
 3132:                     } else {
 3133:                         if (&quota_admin('',\%changeHash,$name)) {
 3134:                             $changed{$name.'quota'} = 1;
 3135:                             $newquota{$name} = $newdefquota{$name};
 3136:                             $newisdefault{$name} = 1;
 3137:                         }
 3138:                     }
 3139:                 } else {
 3140:                     $oldisdefault{$name} = 1;
 3141:                     $oldquota{$name} = $olddefquota{$name};
 3142:                     if ($env{'form.custom_'.$name.'quota'} == 1) {
 3143:                         if ($env{'form.'.$name.'quota'} eq '') {
 3144:                             $newquota{$name} = 0;
 3145:                         } else {
 3146:                             $newquota{$name} = $env{'form.'.$name.'quota'};
 3147:                             $newquota{$name} =~ s/[^\d\.]//g;
 3148:                         }
 3149:                         if (&quota_admin($newquota{$name},\%changeHash,$name)) {
 3150:                             $changed{$name.'quota'} = 1;
 3151:                         }
 3152:                     } else {
 3153:                         $newquota{$name} = $newdefquota{$name};
 3154:                         $newisdefault{$name} = 1;
 3155:                     }
 3156:                 }
 3157:                 if ($oldisdefault{$name}) {
 3158:                     $oldsettingstext{'quota'}{$name} = &get_defaultquota_text($oldsettingstatus{$name});
 3159:                 }  else {
 3160:                     $oldsettingstext{'quota'}{$name} = &mt('custom quota: [_1] MB',$oldquota{$name});
 3161:                 }
 3162:                 if ($newisdefault{$name}) {
 3163:                     $newsettingstext{'quota'}{$name} = &get_defaultquota_text($newsettingstatus{$name});
 3164:                 } else {
 3165:                     $newsettingstext{'quota'}{$name} = &mt('custom quota: [_1] MB',$newquota{$name});
 3166:                 }
 3167:             }
 3168:             &tool_changes('tools',\@usertools,\%oldsettings,\%oldsettingstext,\%userenv,
 3169:                           \%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3170:             if ($env{'form.ccdomain'} eq $env{'request.role.domain'}) {
 3171:                 &tool_changes('requestcourses',\@requestcourses,\%oldsettings,\%oldsettingstext,
 3172:                               \%userenv,\%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3173:                 &tool_changes('requestauthor',\@requestauthor,\%oldsettings,\%oldsettingstext,
 3174:                               \%userenv,\%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3175:             } else {
 3176:                 &tool_changes('reqcrsotherdom',\@requestcourses,\%oldsettings,\%oldsettingstext,
 3177:                               \%userenv,\%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3178:             }
 3179:         }
 3180:         foreach my $item (@userinfo) {
 3181:             if ($env{'form.c'.$item} ne $userenv{$item}) {
 3182:                 $namechanged{$item} = 1;
 3183:             }
 3184:         }
 3185:         foreach my $name ('portfolio','author') {
 3186:             $oldsettings{'quota'}{$name} = &mt('[_1] MB',$oldquota{$name});
 3187:             $newsettings{'quota'}{$name} = &mt('[_1] MB',$newquota{$name});
 3188:         }
 3189:         if ((keys(%namechanged) > 0) || (keys(%changed) > 0)) {
 3190:             my ($chgresult,$namechgresult);
 3191:             if (keys(%changed) > 0) {
 3192:                 $chgresult = 
 3193:                     &Apache::lonnet::put('environment',\%changeHash,
 3194:                                   $env{'form.ccdomain'},$env{'form.ccuname'});
 3195:                 if ($chgresult eq 'ok') {
 3196:                     if (($env{'user.name'} eq $env{'form.ccuname'}) &&
 3197:                         ($env{'user.domain'} eq $env{'form.ccdomain'})) {
 3198:                         my %newenvhash;
 3199:                         foreach my $key (keys(%changed)) {
 3200:                             if (($key eq 'official') || ($key eq 'unofficial') ||
 3201:                                 ($key eq 'community') || ($key eq 'textbook') ||
 3202:                                 ($key eq 'placement')) {
 3203:                                 $newenvhash{'environment.requestcourses.'.$key} =
 3204:                                     $changeHash{'requestcourses.'.$key};
 3205:                                 if ($changeHash{'requestcourses.'.$key}) {
 3206:                                     $newenvhash{'environment.canrequest.'.$key} = 1;
 3207:                                 } else {
 3208:                                     $newenvhash{'environment.canrequest.'.$key} =
 3209:           &Apache::lonnet::usertools_access($env{'user.name'},$env{'user.domain'},
 3210:                                             $key,'reload','requestcourses');
 3211:                                 }
 3212:                             } elsif ($key eq 'requestauthor') {
 3213:                                 $newenvhash{'environment.'.$key} = $changeHash{$key};
 3214:                                 if ($changeHash{$key}) {
 3215:                                     $newenvhash{'environment.canrequest.author'} = 1;
 3216:                                 } else {
 3217:                                     $newenvhash{'environment.canrequest.author'} =
 3218:           &Apache::lonnet::usertools_access($env{'user.name'},$env{'user.domain'},
 3219:                                             $key,'reload','requestauthor');
 3220:                                 }
 3221:                             } elsif ($key ne 'quota') {
 3222:                                 $newenvhash{'environment.tools.'.$key} = 
 3223:                                     $changeHash{'tools.'.$key};
 3224:                                 if ($changeHash{'tools.'.$key} ne '') {
 3225:                                     $newenvhash{'environment.availabletools.'.$key} =
 3226:                                         $changeHash{'tools.'.$key};
 3227:                                 } else {
 3228:                                     $newenvhash{'environment.availabletools.'.$key} =
 3229:           &Apache::lonnet::usertools_access($env{'user.name'},$env{'user.domain'},
 3230:           $key,'reload','tools');
 3231:                                 }
 3232:                             }
 3233:                         }
 3234:                         if (keys(%newenvhash)) {
 3235:                             &Apache::lonnet::appenv(\%newenvhash);
 3236:                         }
 3237:                     }
 3238:                 }
 3239:             }
 3240:             if (keys(%namechanged) > 0) {
 3241:                 foreach my $field (@userinfo) {
 3242:                     $changeHash{$field}  = $env{'form.c'.$field};
 3243:                 }
 3244: # Make the change
 3245:                 $namechgresult =
 3246:                     &Apache::lonnet::modifyuser($env{'form.ccdomain'},
 3247:                         $env{'form.ccuname'},$changeHash{'id'},undef,undef,
 3248:                         $changeHash{'firstname'},$changeHash{'middlename'},
 3249:                         $changeHash{'lastname'},$changeHash{'generation'},
 3250:                         $changeHash{'id'},undef,$changeHash{'permanentemail'},undef,\@userinfo);
 3251:                 %userupdate = (
 3252:                                lastname   => $env{'form.clastname'},
 3253:                                middlename => $env{'form.cmiddlename'},
 3254:                                firstname  => $env{'form.cfirstname'},
 3255:                                generation => $env{'form.cgeneration'},
 3256:                                id         => $env{'form.cid'},
 3257:                              );
 3258:             }
 3259:             if (((keys(%namechanged) > 0) && $namechgresult eq 'ok') || 
 3260:                 ((keys(%changed) > 0) && $chgresult eq 'ok')) {
 3261:             # Tell the user we changed the name
 3262:                 &display_userinfo($r,1,\@disporder,\%canshow,\@requestcourses,
 3263:                                   \@usertools,\@requestauthor,\%userenv,\%changed,\%namechanged,
 3264:                                   \%oldsettings, \%oldsettingstext,\%newsettings,
 3265:                                   \%newsettingstext);
 3266:                 if ($env{'form.cid'} ne $userenv{'id'}) {
 3267:                     &Apache::lonnet::idput($env{'form.ccdomain'},
 3268:                          {$env{'form.ccuname'} => $env{'form.cid'}},$uhome,'ids');
 3269:                     if (($recurseid) &&
 3270:                         (&Apache::lonnet::allowed('mau',$env{'form.ccdomain'}))) {
 3271:                         my $idresult = 
 3272:                             &Apache::lonuserutils::propagate_id_change(
 3273:                                 $env{'form.ccuname'},$env{'form.ccdomain'},
 3274:                                 \%userupdate);
 3275:                         $r->print('<br />'.$idresult.'<br />');
 3276:                     }
 3277:                 }
 3278:                 if (($env{'form.ccdomain'} eq $env{'user.domain'}) && 
 3279:                     ($env{'form.ccuname'} eq $env{'user.name'})) {
 3280:                     my %newenvhash;
 3281:                     foreach my $key (keys(%changeHash)) {
 3282:                         $newenvhash{'environment.'.$key} = $changeHash{$key};
 3283:                     }
 3284:                     &Apache::lonnet::appenv(\%newenvhash);
 3285:                 }
 3286:             } else { # error occurred
 3287:                 $r->print(
 3288:                     '<p class="LC_error">'
 3289:                    .&mt('Unable to successfully change environment for [_1] in domain [_2].',
 3290:                             '"'.$env{'form.ccuname'}.'"',
 3291:                             '"'.$env{'form.ccdomain'}.'"')
 3292:                    .'</p>');
 3293:             }
 3294:         } else { # End of if ($env ... ) logic
 3295:             # They did not want to change the users name, quota, tool availability,
 3296:             # or ability to request creation of courses, 
 3297:             # but we can still tell them what the name and quota and availabilities are  
 3298:             &display_userinfo($r,undef,\@disporder,\%canshow,\@requestcourses,
 3299:                               \@usertools,\@requestauthor,\%userenv,\%changed,\%namechanged,\%oldsettings,
 3300:                               \%oldsettingstext,\%newsettings,\%newsettingstext);
 3301:         }
 3302:         if (@mod_disallowed) {
 3303:             my ($rolestr,$contextname);
 3304:             if (@longroles > 0) {
 3305:                 $rolestr = join(', ',@longroles);
 3306:             } else {
 3307:                 $rolestr = &mt('No roles');
 3308:             }
 3309:             if ($context eq 'course') {
 3310:                 $contextname = 'course';
 3311:             } elsif ($context eq 'author') {
 3312:                 $contextname = 'co-author';
 3313:             }
 3314:             $r->print(&mt('The following fields were not updated: ').'<ul>');
 3315:             my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
 3316:             foreach my $field (@mod_disallowed) {
 3317:                 $r->print('<li>'.$fieldtitles{$field}.'</li>'."\n"); 
 3318:             }
 3319:             $r->print('</ul>');
 3320:             if (@mod_disallowed == 1) {
 3321:                 $r->print(&mt("You do not have the authority to change this field given the user's current set of active/future $contextname roles:"));
 3322:             } else {
 3323:                 $r->print(&mt("You do not have the authority to change these fields given the user's current set of active/future $contextname roles:"));
 3324:             }
 3325:             my $helplink = 'javascript:helpMenu('."'display'".')';
 3326:             $r->print('<span class="LC_cusr_emph">'.$rolestr.'</span><br />'
 3327:                      .&mt('Please contact your [_1]helpdesk[_2] for more information.'
 3328:                          ,'<a href="'.$helplink.'">','</a>')
 3329:                       .'<br />');
 3330:         }
 3331:         $r->print('<span class="LC_warning">'
 3332:                   .$no_forceid_alert
 3333:                   .&Apache::lonuserutils::print_namespacing_alerts($env{'form.ccdomain'},\%alerts,\%curr_rules)
 3334:                   .'</span>');
 3335:     }
 3336:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 3337:     if ($env{'form.action'} eq 'singlestudent') {
 3338:         &enroll_single_student($r,$uhome,$amode,$genpwd,$now,$newuser,$context,
 3339:                                $crstype,$showcredits,$defaultcredits);
 3340:         my $linktext = ($crstype eq 'Community' ?
 3341:             &mt('Enroll Another Member') : &mt('Enroll Another Student'));
 3342:         $r->print(
 3343:             &Apache::lonhtmlcommon::actionbox([
 3344:                 '<a href="javascript:backPage(document.userupdate)">'
 3345:                .($crstype eq 'Community' ? 
 3346:                     &mt('Enroll Another Member') : &mt('Enroll Another Student'))
 3347:                .'</a>']));
 3348:     } else {
 3349:         my @rolechanges = &update_roles($r,$context,$showcredits);
 3350:         if (keys(%namechanged) > 0) {
 3351:             if ($context eq 'course') {
 3352:                 if (@userroles > 0) {
 3353:                     if ((@rolechanges == 0) || 
 3354:                         (!(grep(/^st$/,@rolechanges)))) {
 3355:                         if (grep(/^st$/,@userroles)) {
 3356:                             my $classlistupdated =
 3357:                                 &Apache::lonuserutils::update_classlist($cdom,
 3358:                                               $cnum,$env{'form.ccdomain'},
 3359:                                        $env{'form.ccuname'},\%userupdate);
 3360:                         }
 3361:                     }
 3362:                 }
 3363:             }
 3364:         }
 3365:         my $userinfo = &Apache::loncommon::plainname($env{'form.ccuname'},
 3366:                                                      $env{'form.ccdomain'});
 3367:         if ($env{'form.popup'}) {
 3368:             $r->print('<p><a href="javascript:window.close()">'.&mt('Close window').'</a></p>');
 3369:         } else {
 3370:             $r->print('<br />'.&Apache::lonhtmlcommon::actionbox(['<a href="javascript:backPage(document.userupdate,'."'$env{'form.prevphase'}','modify'".')">'
 3371:                      .&mt('Modify this user: [_1]','<span class="LC_cusr_emph">'.$env{'form.ccuname'}.':'.$env{'form.ccdomain'}.' ('.$userinfo.')</span>').'</a>',
 3372:                      '<a href="javascript:backPage(document.userupdate)">'.&mt('Create/Modify Another User').'</a>']));
 3373:         }
 3374:     }
 3375: }
 3376: 
 3377: sub display_userinfo {
 3378:     my ($r,$changed,$order,$canshow,$requestcourses,$usertools,$requestauthor,
 3379:         $userenv,$changedhash,$namechangedhash,$oldsetting,$oldsettingtext,
 3380:         $newsetting,$newsettingtext) = @_;
 3381:     return unless (ref($order) eq 'ARRAY' &&
 3382:                    ref($canshow) eq 'HASH' && 
 3383:                    ref($requestcourses) eq 'ARRAY' && 
 3384:                    ref($requestauthor) eq 'ARRAY' &&
 3385:                    ref($usertools) eq 'ARRAY' && 
 3386:                    ref($userenv) eq 'HASH' &&
 3387:                    ref($changedhash) eq 'HASH' &&
 3388:                    ref($oldsetting) eq 'HASH' &&
 3389:                    ref($oldsettingtext) eq 'HASH' &&
 3390:                    ref($newsetting) eq 'HASH' &&
 3391:                    ref($newsettingtext) eq 'HASH');
 3392:     my %lt=&Apache::lonlocal::texthash(
 3393:          'ui'             => 'User Information',
 3394:          'uic'            => 'User Information Changed',
 3395:          'firstname'      => 'First Name',
 3396:          'middlename'     => 'Middle Name',
 3397:          'lastname'       => 'Last Name',
 3398:          'generation'     => 'Generation',
 3399:          'id'             => 'Student/Employee ID',
 3400:          'permanentemail' => 'Permanent e-mail address',
 3401:          'portfolioquota' => 'Disk space allocated to portfolio files',
 3402:          'authorquota'    => 'Disk space allocated to Authoring Space',
 3403:          'blog'           => 'Blog Availability',
 3404:          'webdav'         => 'WebDAV Availability',
 3405:          'aboutme'        => 'Personal Information Page Availability',
 3406:          'portfolio'      => 'Portfolio Availability',
 3407:          'official'       => 'Can Request Official Courses',
 3408:          'unofficial'     => 'Can Request Unofficial Courses',
 3409:          'community'      => 'Can Request Communities',
 3410:          'textbook'       => 'Can Request Textbook Courses',
 3411:          'placement'      => 'Can Request Placement Tests',
 3412:          'requestauthor'  => 'Can Request Author Role',
 3413:          'inststatus'     => "Affiliation",
 3414:          'prvs'           => 'Previous Value:',
 3415:          'chto'           => 'Changed To:'
 3416:     );
 3417:     if ($changed) {
 3418:         $r->print('<h3>'.$lt{'uic'}.'</h3>'.
 3419:                 &Apache::loncommon::start_data_table().
 3420:                 &Apache::loncommon::start_data_table_header_row());
 3421:         $r->print("<th>&nbsp;</th>\n");
 3422:         $r->print('<th><b>'.$lt{'prvs'}.'</b></th>');
 3423:         $r->print('<th><span class="LC_nobreak"><b>'.$lt{'chto'}.'</b></span></th>');
 3424:         $r->print(&Apache::loncommon::end_data_table_header_row());
 3425:         my @userinfo = ('firstname','middlename','lastname','generation','permanentemail','id');
 3426: 
 3427:         foreach my $item (@userinfo) {
 3428:             my $value = $env{'form.c'.$item};
 3429:             #show changes only:
 3430:             unless ($value eq $userenv->{$item}){
 3431:                 $r->print(&Apache::loncommon::start_data_table_row());
 3432:                 $r->print("<td>$lt{$item}</td>\n");
 3433:                 $r->print("<td>".$userenv->{$item}."</td>\n");
 3434:                 $r->print("<td>$value </td>\n");
 3435:                 $r->print(&Apache::loncommon::end_data_table_row());
 3436:             }
 3437:         }
 3438:         foreach my $entry (@{$order}) {
 3439:             if ($canshow->{$entry}) {
 3440:                 if (($entry eq 'requestcourses') || ($entry eq 'reqcrsotherdom') || ($entry eq 'requestauthor')) {
 3441:                     my @items;
 3442:                     if ($entry eq 'requestauthor') {
 3443:                         @items = ($entry);
 3444:                     } else {
 3445:                         @items = @{$requestcourses};
 3446:                     }
 3447:                     foreach my $item (@items) {
 3448:                         if (($newsetting->{$item} ne $oldsetting->{$item}) || 
 3449:                             ($newsettingtext->{$item} ne $oldsettingtext->{$item})) {
 3450:                             $r->print(&Apache::loncommon::start_data_table_row()."\n");  
 3451:                             $r->print("<td>$lt{$item}</td>\n");
 3452:                             $r->print("<td>".$oldsetting->{$item});
 3453:                             if ($oldsettingtext->{$item}) {
 3454:                                 if ($oldsetting->{$item}) {
 3455:                                     $r->print(' -- ');
 3456:                                 }
 3457:                                 $r->print($oldsettingtext->{$item});
 3458:                             }
 3459:                             $r->print("</td>\n");
 3460:                             $r->print("<td>".$newsetting->{$item});
 3461:                             if ($newsettingtext->{$item}) {
 3462:                                 if ($newsetting->{$item}) {
 3463:                                     $r->print(' -- ');
 3464:                                 }
 3465:                                 $r->print($newsettingtext->{$item});
 3466:                             }
 3467:                             $r->print("</td>\n");
 3468:                             $r->print(&Apache::loncommon::end_data_table_row()."\n");
 3469:                         }
 3470:                     }
 3471:                 } elsif ($entry eq 'tools') {
 3472:                     foreach my $item (@{$usertools}) {
 3473:                         if ($newsetting->{$item} ne $oldsetting->{$item}) {
 3474:                             $r->print(&Apache::loncommon::start_data_table_row()."\n");
 3475:                             $r->print("<td>$lt{$item}</td>\n");
 3476:                             $r->print("<td>".$oldsetting->{$item}.' '.$oldsettingtext->{$item}."</td>\n");
 3477:                             $r->print("<td>".$newsetting->{$item}.' '.$newsettingtext->{$item}."</td>\n");
 3478:                             $r->print(&Apache::loncommon::end_data_table_row()."\n");
 3479:                         }
 3480:                     }
 3481:                 } elsif ($entry eq 'quota') {
 3482:                     if ((ref($oldsetting->{$entry}) eq 'HASH') && (ref($oldsettingtext->{$entry}) eq 'HASH') &&
 3483:                         (ref($newsetting->{$entry}) eq 'HASH') && (ref($newsettingtext->{$entry}) eq 'HASH')) {
 3484:                         foreach my $name ('portfolio','author') {
 3485:                             if ($newsetting->{$entry}->{$name} ne $oldsetting->{$entry}->{$name}) {
 3486:                                 $r->print(&Apache::loncommon::start_data_table_row()."\n");
 3487:                                 $r->print("<td>$lt{$name.$entry}</td>\n");
 3488:                                 $r->print("<td>".$oldsettingtext->{$entry}->{$name}."</td>\n");
 3489:                                 $r->print("<td>".$newsettingtext->{$entry}->{$name}."</td>\n");
 3490:                                 $r->print(&Apache::loncommon::end_data_table_row()."\n");
 3491:                             }
 3492:                         }
 3493:                     }
 3494:                 } else {
 3495:                     if ($newsetting->{$entry} ne $oldsetting->{$entry}) {
 3496:                         $r->print(&Apache::loncommon::start_data_table_row()."\n");
 3497:                         $r->print("<td>$lt{$entry}</td>\n");
 3498:                         $r->print("<td>".$oldsetting->{$entry}.' '.$oldsettingtext->{$entry}."</td>\n");
 3499:                         $r->print("<td>".$newsetting->{$entry}.' '.$newsettingtext->{$entry}."</td>\n");
 3500:                         $r->print(&Apache::loncommon::end_data_table_row()."\n");
 3501:                     }
 3502:                 }
 3503:             }
 3504:         }
 3505:         $r->print(&Apache::loncommon::end_data_table().'<br />');
 3506:     } else {
 3507:         $r->print('<h3>'.$lt{'ui'}.'</h3>'.
 3508:                   '<p>'.&mt('No changes made to user information').'</p>');
 3509:     }
 3510:     return;
 3511: }
 3512: 
 3513: sub tool_changes {
 3514:     my ($context,$usertools,$oldaccess,$oldaccesstext,$userenv,$changeHash,
 3515:         $changed,$newaccess,$newaccesstext) = @_;
 3516:     if (!((ref($usertools) eq 'ARRAY') && (ref($oldaccess) eq 'HASH') &&
 3517:           (ref($oldaccesstext) eq 'HASH') && (ref($userenv) eq 'HASH') &&
 3518:           (ref($changeHash) eq 'HASH') && (ref($changed) eq 'HASH') &&
 3519:           (ref($newaccess) eq 'HASH') && (ref($newaccesstext) eq 'HASH'))) {
 3520:         return;
 3521:     }
 3522:     my %reqdisplay = &requestchange_display();
 3523:     if ($context eq 'reqcrsotherdom') {
 3524:         my @options = ('approval','validate','autolimit');
 3525:         my $optregex = join('|',@options);
 3526:         my $cdom = $env{'request.role.domain'};
 3527:         foreach my $tool (@{$usertools}) {
 3528:             $oldaccesstext->{$tool} = &mt("availability set to 'off'");
 3529:             $newaccesstext->{$tool} = $oldaccesstext->{$tool};
 3530:             $changeHash->{$context.'.'.$tool} = $userenv->{$context.'.'.$tool};
 3531:             my ($newop,$limit);
 3532:             if ($env{'form.'.$context.'_'.$tool}) {
 3533:                 $newop = $env{'form.'.$context.'_'.$tool};
 3534:                 if ($newop eq 'autolimit') {
 3535:                     $limit = $env{'form.'.$context.'_'.$tool.'_limit'};
 3536:                     $limit =~ s/\D+//g;
 3537:                     $newop .= '='.$limit;
 3538:                 }
 3539:             }
 3540:             if ($userenv->{$context.'.'.$tool} eq '') {
 3541:                 if ($newop) {
 3542:                     $changed->{$tool}=&tool_admin($tool,$cdom.':'.$newop,
 3543:                                                   $changeHash,$context);
 3544:                     if ($changed->{$tool}) {
 3545:                         if ($newop =~ /^autolimit/) {
 3546:                             if ($limit) {
 3547:                                 $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3548:                             } else {
 3549:                                 $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3550:                             }
 3551:                         } else {
 3552:                             $newaccesstext->{$tool} = $reqdisplay{$newop};
 3553:                         }
 3554:                     } else {
 3555:                         $newaccesstext->{$tool} = $oldaccesstext->{$tool};
 3556:                     }
 3557:                 }
 3558:             } else {
 3559:                 my @curr = split(',',$userenv->{$context.'.'.$tool});
 3560:                 my @new;
 3561:                 my $changedoms;
 3562:                 foreach my $req (@curr) {
 3563:                     if ($req =~ /^\Q$cdom\E\:($optregex\=?\d*)$/) {
 3564:                         my $oldop = $1;
 3565:                         if ($oldop =~ /^autolimit=(\d*)/) {
 3566:                             my $limit = $1;
 3567:                             if ($limit) {
 3568:                                 $oldaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3569:                             } else {
 3570:                                 $oldaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3571:                             }
 3572:                         } else {
 3573:                             $oldaccesstext->{$tool} = $reqdisplay{$oldop};
 3574:                         }
 3575:                         if ($oldop ne $newop) {
 3576:                             $changedoms = 1;
 3577:                             foreach my $item (@curr) {
 3578:                                 my ($reqdom,$option) = split(':',$item);
 3579:                                 unless ($reqdom eq $cdom) {
 3580:                                     push(@new,$item);
 3581:                                 }
 3582:                             }
 3583:                             if ($newop) {
 3584:                                 push(@new,$cdom.':'.$newop);
 3585:                             }
 3586:                             @new = sort(@new);
 3587:                         }
 3588:                         last;
 3589:                     }
 3590:                 }
 3591:                 if ((!$changedoms) && ($newop)) {
 3592:                     $changedoms = 1;
 3593:                     @new = sort(@curr,$cdom.':'.$newop);
 3594:                 }
 3595:                 if ($changedoms) {
 3596:                     my $newdomstr;
 3597:                     if (@new) {
 3598:                         $newdomstr = join(',',@new);
 3599:                     }
 3600:                     $changed->{$tool}=&tool_admin($tool,$newdomstr,$changeHash,
 3601:                                                   $context);
 3602:                     if ($changed->{$tool}) {
 3603:                         if ($env{'form.'.$context.'_'.$tool}) {
 3604:                             if ($env{'form.'.$context.'_'.$tool} eq 'autolimit') {
 3605:                                 my $limit = $env{'form.'.$context.'_'.$tool.'_limit'};
 3606:                                 $limit =~ s/\D+//g;
 3607:                                 if ($limit) {
 3608:                                     $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3609:                                 } else {
 3610:                                     $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3611:                                 }
 3612:                             } else {
 3613:                                 $newaccesstext->{$tool} = $reqdisplay{$env{'form.'.$context.'_'.$tool}};
 3614:                             }
 3615:                         } else {
 3616:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3617:                         }
 3618:                     }
 3619:                 }
 3620:             }
 3621:         }
 3622:         return;
 3623:     }
 3624:     foreach my $tool (@{$usertools}) {
 3625:         my ($newval,$limit,$envkey);
 3626:         $envkey = $context.'.'.$tool;
 3627:         if ($context eq 'requestcourses') {
 3628:             $newval = $env{'form.crsreq_'.$tool};
 3629:             if ($newval eq 'autolimit') {
 3630:                 $limit = $env{'form.crsreq_'.$tool.'_limit'};
 3631:                 $limit =~ s/\D+//g;
 3632:                 $newval .= '='.$limit;
 3633:             }
 3634:         } elsif ($context eq 'requestauthor') {
 3635:             $newval = $env{'form.'.$context};
 3636:             $envkey = $context;
 3637:         } else {
 3638:             $newval = $env{'form.'.$context.'_'.$tool};
 3639:         }
 3640:         if ($userenv->{$envkey} ne '') {
 3641:             $oldaccess->{$tool} = &mt('custom');
 3642:             if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 3643:                 if ($userenv->{$envkey} =~ /^autolimit=(\d*)$/) {
 3644:                     my $currlimit = $1;
 3645:                     if ($currlimit eq '') {
 3646:                         $oldaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3647:                     } else {
 3648:                         $oldaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$currlimit);
 3649:                     }
 3650:                 } elsif ($userenv->{$envkey}) {
 3651:                     $oldaccesstext->{$tool} = $reqdisplay{$userenv->{$envkey}};
 3652:                 } else {
 3653:                     $oldaccesstext->{$tool} = &mt("availability set to 'off'");
 3654:                 }
 3655:             } else {
 3656:                 if ($userenv->{$envkey}) {
 3657:                     $oldaccesstext->{$tool} = &mt("availability set to 'on'");
 3658:                 } else {
 3659:                     $oldaccesstext->{$tool} = &mt("availability set to 'off'");
 3660:                 }
 3661:             }
 3662:             $changeHash->{$envkey} = $userenv->{$envkey};
 3663:             if ($env{'form.custom'.$tool} == 1) {
 3664:                 if ($newval ne $userenv->{$envkey}) {
 3665:                     $changed->{$tool} = &tool_admin($tool,$newval,$changeHash,
 3666:                                                     $context);
 3667:                     if ($changed->{$tool}) {
 3668:                         $newaccess->{$tool} = &mt('custom');
 3669:                         if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 3670:                             if ($newval =~ /^autolimit/) {
 3671:                                 if ($limit) {
 3672:                                     $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3673:                                 } else {
 3674:                                     $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3675:                                 }
 3676:                             } elsif ($newval) {
 3677:                                 $newaccesstext->{$tool} = $reqdisplay{$newval};
 3678:                             } else {
 3679:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3680:                             }
 3681:                         } else {
 3682:                             if ($newval) {
 3683:                                 $newaccesstext->{$tool} = &mt("availability set to 'on'");
 3684:                             } else {
 3685:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3686:                             }
 3687:                         }
 3688:                     } else {
 3689:                         $newaccess->{$tool} = $oldaccess->{$tool};
 3690:                         if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 3691:                             if ($newval =~ /^autolimit/) {
 3692:                                 if ($limit) {
 3693:                                     $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3694:                                 } else {
 3695:                                     $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3696:                                 }
 3697:                             } elsif ($newval) {
 3698:                                 $newaccesstext->{$tool} = $reqdisplay{$newval};
 3699:                             } else {
 3700:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3701:                             }
 3702:                         } else {
 3703:                             if ($userenv->{$context.'.'.$tool}) {
 3704:                                 $newaccesstext->{$tool} = &mt("availability set to 'on'");
 3705:                             } else {
 3706:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3707:                             }
 3708:                         }
 3709:                     }
 3710:                 } else {
 3711:                     $newaccess->{$tool} = $oldaccess->{$tool};
 3712:                     $newaccesstext->{$tool} = $oldaccesstext->{$tool};
 3713:                 }
 3714:             } else {
 3715:                 $changed->{$tool} = &tool_admin($tool,'',$changeHash,$context);
 3716:                 if ($changed->{$tool}) {
 3717:                     $newaccess->{$tool} = &mt('default');
 3718:                 } else {
 3719:                     $newaccess->{$tool} = $oldaccess->{$tool};
 3720:                     if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 3721:                         if ($newval =~ /^autolimit/) {
 3722:                             if ($limit) {
 3723:                                 $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3724:                             } else {
 3725:                                 $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3726:                             }
 3727:                         } elsif ($newval) {
 3728:                             $newaccesstext->{$tool} = $reqdisplay{$newval};
 3729:                         } else {
 3730:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3731:                         }
 3732:                     } else {
 3733:                         if ($userenv->{$context.'.'.$tool}) {
 3734:                             $newaccesstext->{$tool} = &mt("availability set to 'on'");
 3735:                         } else {
 3736:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3737:                         }
 3738:                     }
 3739:                 }
 3740:             }
 3741:         } else {
 3742:             $oldaccess->{$tool} = &mt('default');
 3743:             if ($env{'form.custom'.$tool} == 1) {
 3744:                 $changed->{$tool} = &tool_admin($tool,$newval,$changeHash,
 3745:                                                 $context);
 3746:                 if ($changed->{$tool}) {
 3747:                     $newaccess->{$tool} = &mt('custom');
 3748:                     if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 3749:                         if ($newval =~ /^autolimit/) {
 3750:                             if ($limit) {
 3751:                                 $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3752:                             } else {
 3753:                                 $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3754:                             }
 3755:                         } elsif ($newval) {
 3756:                             $newaccesstext->{$tool} = $reqdisplay{$newval};
 3757:                         } else {
 3758:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3759:                         }
 3760:                     } else {
 3761:                         if ($newval) {
 3762:                             $newaccesstext->{$tool} = &mt("availability set to 'on'");
 3763:                         } else {
 3764:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3765:                         }
 3766:                     }
 3767:                 } else {
 3768:                     $newaccess->{$tool} = $oldaccess->{$tool};
 3769:                 }
 3770:             } else {
 3771:                 $newaccess->{$tool} = $oldaccess->{$tool};
 3772:             }
 3773:         }
 3774:     }
 3775:     return;
 3776: }
 3777: 
 3778: sub update_roles {
 3779:     my ($r,$context,$showcredits) = @_;
 3780:     my $now=time;
 3781:     my @rolechanges;
 3782:     my %disallowed;
 3783:     $r->print('<h3>'.&mt('Modifying Roles').'</h3>');
 3784:     foreach my $key (keys(%env)) {
 3785: 	next if (! $env{$key});
 3786:         next if ($key eq 'form.action');
 3787: 	# Revoke roles
 3788: 	if ($key=~/^form\.rev/) {
 3789: 	    if ($key=~/^form\.rev\:([^\_]+)\_([^\_\.]+)$/) {
 3790: # Revoke standard role
 3791: 		my ($scope,$role) = ($1,$2);
 3792: 		my $result =
 3793: 		    &Apache::lonnet::revokerole($env{'form.ccdomain'},
 3794: 						$env{'form.ccuname'},
 3795: 						$scope,$role,'','',$context);
 3796:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
 3797:                             &mt('Revoking [_1] in [_2]',
 3798:                                 &Apache::lonnet::plaintext($role),
 3799:                                 &Apache::loncommon::show_role_extent($scope,$context,$role)),
 3800:                                 $result ne "ok").'<br />');
 3801:                 if ($result ne "ok") {
 3802:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 3803:                 }
 3804: 		if ($role eq 'st') {
 3805: 		    my $result = 
 3806:                         &Apache::lonuserutils::classlist_drop($scope,
 3807:                             $env{'form.ccuname'},$env{'form.ccdomain'},
 3808: 			    $now);
 3809:                     $r->print(&Apache::lonhtmlcommon::confirm_success($result));
 3810: 		}
 3811:                 if (!grep(/^\Q$role\E$/,@rolechanges)) {
 3812:                     push(@rolechanges,$role);
 3813:                 }
 3814: 	    }
 3815: 	    if ($key=~m{^form\.rev\:([^_]+)_cr\.cr/($match_domain)/($match_username)/(\w+)$}s) {
 3816: # Revoke custom role
 3817:                 my $result = &Apache::lonnet::revokecustomrole(
 3818:                     $env{'form.ccdomain'},$env{'form.ccuname'},$1,$2,$3,$4,'','',$context);
 3819:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
 3820:                             &mt('Revoking custom role [_1] by [_2] in [_3]',
 3821:                                 $4,$3.':'.$2,&Apache::loncommon::show_role_extent($1,$context,'cr')),
 3822:                             $result ne 'ok').'<br />');
 3823:                 if ($result ne "ok") {
 3824:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 3825:                 }
 3826:                 if (!grep(/^cr$/,@rolechanges)) {
 3827:                     push(@rolechanges,'cr');
 3828:                 }
 3829: 	    }
 3830: 	} elsif ($key=~/^form\.del/) {
 3831: 	    if ($key=~/^form\.del\:([^\_]+)\_([^\_\.]+)$/) {
 3832: # Delete standard role
 3833: 		my ($scope,$role) = ($1,$2);
 3834: 		my $result =
 3835: 		    &Apache::lonnet::assignrole($env{'form.ccdomain'},
 3836: 						$env{'form.ccuname'},
 3837: 						$scope,$role,$now,0,1,'',
 3838:                                                 $context);
 3839:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
 3840:                             &mt('Deleting [_1] in [_2]',
 3841:                                 &Apache::lonnet::plaintext($role),
 3842:                                 &Apache::loncommon::show_role_extent($scope,$context,$role)),
 3843:                             $result ne 'ok').'<br />');
 3844:                 if ($result ne "ok") {
 3845:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 3846:                 }
 3847: 
 3848: 		if ($role eq 'st') {
 3849: 		    my $result = 
 3850:                         &Apache::lonuserutils::classlist_drop($scope,
 3851:                             $env{'form.ccuname'},$env{'form.ccdomain'},
 3852: 			    $now);
 3853: 		    $r->print(&Apache::lonhtmlcommon::confirm_success($result));
 3854: 		}
 3855:                 if (!grep(/^\Q$role\E$/,@rolechanges)) {
 3856:                     push(@rolechanges,$role);
 3857:                 }
 3858:             }
 3859: 	    if ($key=~m{^form\.del\:([^_]+)_cr\.cr/($match_domain)/($match_username)/(\w+)$}) {
 3860:                 my ($url,$rdom,$rnam,$rolename) = ($1,$2,$3,$4);
 3861: # Delete custom role
 3862:                 my $result =
 3863:                     &Apache::lonnet::assigncustomrole($env{'form.ccdomain'},
 3864:                         $env{'form.ccuname'},$url,$rdom,$rnam,$rolename,$now,
 3865:                         0,1,$context);
 3866:                 $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('Deleting custom role [_1] by [_2] in [_3]',
 3867:                       $rolename,$rnam.':'.$rdom,&Apache::loncommon::show_role_extent($1,$context,'cr')),
 3868:                       $result ne "ok").'<br />');
 3869:                 if ($result ne "ok") {
 3870:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 3871:                 }
 3872: 
 3873:                 if (!grep(/^cr$/,@rolechanges)) {
 3874:                     push(@rolechanges,'cr');
 3875:                 }
 3876:             }
 3877: 	} elsif ($key=~/^form\.ren/) {
 3878:             my $udom = $env{'form.ccdomain'};
 3879:             my $uname = $env{'form.ccuname'};
 3880: # Re-enable standard role
 3881: 	    if ($key=~/^form\.ren\:([^\_]+)\_([^\_\.]+)$/) {
 3882:                 my $url = $1;
 3883:                 my $role = $2;
 3884:                 my $logmsg;
 3885:                 my $output;
 3886:                 if ($role eq 'st') {
 3887:                     if ($url =~ m-^/($match_domain)/($match_courseid)/?(\w*)$-) {
 3888:                         my ($cdom,$cnum,$csec) = ($1,$2,$3);
 3889:                         my $credits;
 3890:                         if ($showcredits) {
 3891:                             my $defaultcredits = 
 3892:                                 &Apache::lonuserutils::get_defaultcredits($cdom,$cnum);
 3893:                             $credits = &get_user_credits($defaultcredits,$cdom,$cnum);
 3894:                         }
 3895:                         my $result = &Apache::loncommon::commit_studentrole(\$logmsg,$udom,$uname,$url,$role,$now,0,$cdom,$cnum,$csec,$context,$credits);
 3896:                         if (($result =~ /^error/) || ($result eq 'not_in_class') || ($result eq 'unknown_course') || ($result eq 'refused')) {
 3897:                             if ($result eq 'refused' && $logmsg) {
 3898:                                 $output = $logmsg;
 3899:                             } else { 
 3900:                                 $output = &mt('Error: [_1]',$result)."\n";
 3901:                             }
 3902:                         } else {
 3903:                             $output = &Apache::lonhtmlcommon::confirm_success(&mt('Assigning [_1] in [_2] starting [_3]',
 3904:                                         &Apache::lonnet::plaintext($role),
 3905:                                         &Apache::loncommon::show_role_extent($url,$context,'st'),
 3906:                                         &Apache::lonlocal::locallocaltime($now))).'<br />'.$logmsg.'<br />';
 3907:                         }
 3908:                     }
 3909:                 } else {
 3910: 		    my $result=&Apache::lonnet::assignrole($env{'form.ccdomain'},
 3911:                                $env{'form.ccuname'},$url,$role,0,$now,'','',
 3912:                                $context);
 3913:                         $output = &Apache::lonhtmlcommon::confirm_success(&mt('Re-enabling [_1] in [_2]',
 3914:                                         &Apache::lonnet::plaintext($role),
 3915:                                         &Apache::loncommon::show_role_extent($url,$context,$role)),$result ne "ok").'<br />';
 3916:                     if ($result ne "ok") {
 3917:                         $output .= &mt('Error: [_1]',$result).'<br />';
 3918:                     }
 3919:                 }
 3920:                 $r->print($output);
 3921:                 if (!grep(/^\Q$role\E$/,@rolechanges)) {
 3922:                     push(@rolechanges,$role);
 3923:                 }
 3924: 	    }
 3925: # Re-enable custom role
 3926: 	    if ($key=~m{^form\.ren\:([^_]+)_cr\.cr/($match_domain)/($match_username)/(\w+)$}) {
 3927:                 my ($url,$rdom,$rnam,$rolename) = ($1,$2,$3,$4);
 3928:                 my $result = &Apache::lonnet::assigncustomrole(
 3929:                                $env{'form.ccdomain'}, $env{'form.ccuname'},
 3930:                                $url,$rdom,$rnam,$rolename,0,$now,undef,$context);
 3931:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
 3932:                     &mt('Re-enabling custom role [_1] by [_2] in [_3]',
 3933:                         $rolename,$rnam.':'.$rdom,&Apache::loncommon::show_role_extent($1,$context,'cr')),
 3934:                     $result ne "ok").'<br />');
 3935:                 if ($result ne "ok") {
 3936:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 3937:                 }
 3938:                 if (!grep(/^cr$/,@rolechanges)) {
 3939:                     push(@rolechanges,'cr');
 3940:                 }
 3941:             }
 3942: 	} elsif ($key=~/^form\.act/) {
 3943:             my $udom = $env{'form.ccdomain'};
 3944:             my $uname = $env{'form.ccuname'};
 3945: 	    if ($key=~/^form\.act\_($match_domain)\_($match_courseid)\_cr_cr_($match_domain)_($match_username)_([^\_]+)$/) {
 3946:                 # Activate a custom role
 3947: 		my ($one,$two,$three,$four,$five)=($1,$2,$3,$4,$5);
 3948: 		my $url='/'.$one.'/'.$two;
 3949: 		my $full=$one.'_'.$two.'_cr_cr_'.$three.'_'.$four.'_'.$five;
 3950: 
 3951:                 my $start = ( $env{'form.start_'.$full} ?
 3952:                               $env{'form.start_'.$full} :
 3953:                               $now );
 3954:                 my $end   = ( $env{'form.end_'.$full} ?
 3955:                               $env{'form.end_'.$full} :
 3956:                               0 );
 3957:                                                                                      
 3958:                 # split multiple sections
 3959:                 my %sections = ();
 3960:                 my $num_sections = &build_roles($env{'form.sec_'.$full},\%sections,$5);
 3961:                 if ($num_sections == 0) {
 3962:                     $r->print(&Apache::loncommon::commit_customrole($udom,$uname,$url,$three,$four,$five,$start,$end,$context));
 3963:                 } else {
 3964: 		    my %curr_groups =
 3965: 			&Apache::longroup::coursegroups($one,$two);
 3966:                     foreach my $sec (sort {$a cmp $b} keys(%sections)) {
 3967:                         if (($sec eq 'none') || ($sec eq 'all') || 
 3968:                             exists($curr_groups{$sec})) {
 3969:                             $disallowed{$sec} = $url;
 3970:                             next;
 3971:                         }
 3972:                         my $securl = $url.'/'.$sec;
 3973: 		        $r->print(&Apache::loncommon::commit_customrole($udom,$uname,$securl,$three,$four,$five,$start,$end,$context));
 3974:                     }
 3975:                 }
 3976:                 if (!grep(/^cr$/,@rolechanges)) {
 3977:                     push(@rolechanges,'cr');
 3978:                 }
 3979: 	    } elsif ($key=~/^form\.act\_($match_domain)\_($match_name)\_([^\_]+)$/) {
 3980: 		# Activate roles for sections with 3 id numbers
 3981: 		# set start, end times, and the url for the class
 3982: 		my ($one,$two,$three)=($1,$2,$3);
 3983: 		my $start = ( $env{'form.start_'.$one.'_'.$two.'_'.$three} ? 
 3984: 			      $env{'form.start_'.$one.'_'.$two.'_'.$three} : 
 3985: 			      $now );
 3986: 		my $end   = ( $env{'form.end_'.$one.'_'.$two.'_'.$three} ? 
 3987: 			      $env{'form.end_'.$one.'_'.$two.'_'.$three} :
 3988: 			      0 );
 3989: 		my $url='/'.$one.'/'.$two;
 3990:                 my $type = 'three';
 3991:                 # split multiple sections
 3992:                 my %sections = ();
 3993:                 my $num_sections = &build_roles($env{'form.sec_'.$one.'_'.$two.'_'.$three},\%sections,$three);
 3994:                 my $credits;
 3995:                 if ($three eq 'st') {
 3996:                     if ($showcredits) { 
 3997:                         my $defaultcredits = 
 3998:                             &Apache::lonuserutils::get_defaultcredits($one,$two);
 3999:                         $credits = $env{'form.credits_'.$one.'_'.$two.'_'.$three};
 4000:                         $credits =~ s/[^\d\.]//g;
 4001:                         if ($credits eq $defaultcredits) {
 4002:                             undef($credits);
 4003:                         }
 4004:                     }
 4005:                 }
 4006:                 if ($num_sections == 0) {
 4007:                     $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$three,$start,$end,$one,$two,'',$context,$credits));
 4008:                 } else {
 4009:                     my %curr_groups = 
 4010: 			&Apache::longroup::coursegroups($one,$two);
 4011:                     my $emptysec = 0;
 4012:                     foreach my $sec (sort {$a cmp $b} keys(%sections)) {
 4013:                         $sec =~ s/\W//g;
 4014:                         if ($sec ne '') {
 4015:                             if (($sec eq 'none') || ($sec eq 'all') || 
 4016:                                 exists($curr_groups{$sec})) {
 4017:                                 $disallowed{$sec} = $url;
 4018:                                 next;
 4019:                             }
 4020:                             my $securl = $url.'/'.$sec;
 4021:                             $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$securl,$three,$start,$end,$one,$two,$sec,$context,$credits));
 4022:                         } else {
 4023:                             $emptysec = 1;
 4024:                         }
 4025:                     }
 4026:                     if ($emptysec) {
 4027:                         $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$three,$start,$end,$one,$two,'',$context,$credits));
 4028:                     }
 4029:                 }
 4030:                 if (!grep(/^\Q$three\E$/,@rolechanges)) {
 4031:                     push(@rolechanges,$three);
 4032:                 }
 4033: 	    } elsif ($key=~/^form\.act\_([^\_]+)\_([^\_]+)$/) {
 4034: 		# Activate roles for sections with two id numbers
 4035: 		# set start, end times, and the url for the class
 4036: 		my $start = ( $env{'form.start_'.$1.'_'.$2} ? 
 4037: 			      $env{'form.start_'.$1.'_'.$2} : 
 4038: 			      $now );
 4039: 		my $end   = ( $env{'form.end_'.$1.'_'.$2} ? 
 4040: 			      $env{'form.end_'.$1.'_'.$2} :
 4041: 			      0 );
 4042:                 my $one = $1;
 4043:                 my $two = $2;
 4044: 		my $url='/'.$one.'/';
 4045:                 # split multiple sections
 4046:                 my %sections = ();
 4047:                 my $num_sections = &build_roles($env{'form.sec_'.$one.'_'.$two},\%sections,$two);
 4048:                 if ($num_sections == 0) {
 4049:                     $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$two,$start,$end,$one,undef,'',$context));
 4050:                 } else {
 4051:                     my $emptysec = 0;
 4052:                     foreach my $sec (sort {$a cmp $b} keys(%sections)) {
 4053:                         if ($sec ne '') {
 4054:                             my $securl = $url.'/'.$sec;
 4055:                             $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$securl,$two,$start,$end,$one,undef,$sec,$context));
 4056:                         } else {
 4057:                             $emptysec = 1;
 4058:                         }
 4059:                     }
 4060:                     if ($emptysec) {
 4061:                         $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$two,$start,$end,$one,undef,'',$context));
 4062:                     }
 4063:                 }
 4064:                 if (!grep(/^\Q$two\E$/,@rolechanges)) {
 4065:                     push(@rolechanges,$two);
 4066:                 }
 4067: 	    } else {
 4068: 		$r->print('<p><span class="LC_error">'.&mt('ERROR').': '.&mt('Unknown command').' <tt>'.$key.'</tt></span></p><br />');
 4069:             }
 4070:             foreach my $key (sort(keys(%disallowed))) {
 4071:                 $r->print('<p class="LC_warning">');
 4072:                 if (($key eq 'none') || ($key eq 'all')) {  
 4073:                     $r->print(&mt('[_1] may not be used as the name for a section, as it is a reserved word.','<tt>'.$key.'</tt>'));
 4074:                 } else {
 4075:                     $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>'));
 4076:                 }
 4077:                 $r->print('</p><p>'
 4078:                          .&mt('Please [_1]go back[_2] and choose a different section name.'
 4079:                              ,'<a href="javascript:history.go(-1)'
 4080:                              ,'</a>')
 4081:                          .'</p><br />'
 4082:                 );
 4083:             }
 4084: 	}
 4085:     } # End of foreach (keys(%env))
 4086: # Flush the course logs so reverse user roles immediately updated
 4087:     $r->register_cleanup(\&Apache::lonnet::flushcourselogs);
 4088:     if (@rolechanges == 0) {
 4089:         $r->print('<p>'.&mt('No roles to modify').'</p>');
 4090:     }
 4091:     return @rolechanges;
 4092: }
 4093: 
 4094: sub get_user_credits {
 4095:     my ($uname,$udom,$defaultcredits,$cdom,$cnum) = @_;
 4096:     if ($cdom eq '' || $cnum eq '') {
 4097:         return unless ($env{'request.course.id'});
 4098:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4099:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4100:     }
 4101:     my $credits;
 4102:     my %currhash =
 4103:         &Apache::lonnet::get('classlist',[$uname.':'.$udom],$cdom,$cnum);
 4104:     if (keys(%currhash) > 0) {
 4105:         my @items = split(/:/,$currhash{$uname.':'.$udom});
 4106:         my $crdidx = &Apache::loncoursedata::CL_CREDITS() - 3;
 4107:         $credits = $items[$crdidx];
 4108:         $credits =~ s/[^\d\.]//g;
 4109:     }
 4110:     if ($credits eq $defaultcredits) {
 4111:         undef($credits);
 4112:     }
 4113:     return $credits;
 4114: }
 4115: 
 4116: sub enroll_single_student {
 4117:     my ($r,$uhome,$amode,$genpwd,$now,$newuser,$context,$crstype,
 4118:         $showcredits,$defaultcredits) = @_;
 4119:     $r->print('<h3>');
 4120:     if ($crstype eq 'Community') {
 4121:         $r->print(&mt('Enrolling Member'));
 4122:     } else {
 4123:         $r->print(&mt('Enrolling Student'));
 4124:     }
 4125:     $r->print('</h3>');
 4126: 
 4127:     # Remove non alphanumeric values from section
 4128:     $env{'form.sections'}=~s/\W//g;
 4129: 
 4130:     my $credits;
 4131:     if (($showcredits) && ($env{'form.credits'} ne '')) {
 4132:         $credits = $env{'form.credits'};
 4133:         $credits =~ s/[^\d\.]//g;
 4134:         if ($credits ne '') {
 4135:             if ($credits eq $defaultcredits) {
 4136:                 undef($credits);
 4137:             }
 4138:         }
 4139:     }
 4140: 
 4141:     # Clean out any old student roles the user has in this class.
 4142:     &Apache::lonuserutils::modifystudent($env{'form.ccdomain'},
 4143:          $env{'form.ccuname'},$env{'request.course.id'},undef,$uhome);
 4144:     my ($startdate,$enddate) = &Apache::lonuserutils::get_dates_from_form();
 4145:     my $enroll_result =
 4146:         &Apache::lonnet::modify_student_enrollment($env{'form.ccdomain'},
 4147:             $env{'form.ccuname'},$env{'form.cid'},$env{'form.cfirstname'},
 4148:             $env{'form.cmiddlename'},$env{'form.clastname'},
 4149:             $env{'form.generation'},$env{'form.sections'},$enddate,
 4150:             $startdate,'manual',undef,$env{'request.course.id'},'',$context,
 4151:             $credits);
 4152:     if ($enroll_result =~ /^ok/) {
 4153:         $r->print(&mt('[_1] enrolled','<b>'.$env{'form.ccuname'}.':'.$env{'form.ccdomain'}.'</b>'));
 4154:         if ($env{'form.sections'} ne '') {
 4155:             $r->print(' '.&mt('in section [_1]',$env{'form.sections'}));
 4156:         }
 4157:         my ($showstart,$showend);
 4158:         if ($startdate <= $now) {
 4159:             $showstart = &mt('Access starts immediately');
 4160:         } else {
 4161:             $showstart = &mt('Access starts: ').&Apache::lonlocal::locallocaltime($startdate);
 4162:         }
 4163:         if ($enddate == 0) {
 4164:             $showend = &mt('ends: no ending date');
 4165:         } else {
 4166:             $showend = &mt('ends: ').&Apache::lonlocal::locallocaltime($enddate);
 4167:         }
 4168:         $r->print('.<br />'.$showstart.'; '.$showend);
 4169:         if ($startdate <= $now && !$newuser) {
 4170:             $r->print('<p class="LC_info">');
 4171:             if ($crstype eq 'Community') {
 4172:                 $r->print(&mt('If the member is currently logged-in to LON-CAPA, the new role can be displayed by using the "Check for changes" link on the Roles/Courses page.'));
 4173:             } else {
 4174:                 $r->print(&mt('If the student is currently logged-in to LON-CAPA, the new role can be displayed by using the "Check for changes" link on the Roles/Courses page.'));
 4175:            }
 4176:            $r->print('</p>');
 4177:         }
 4178:     } else {
 4179:         $r->print(&mt('unable to enroll').": ".$enroll_result);
 4180:     }
 4181:     return;
 4182: }
 4183: 
 4184: sub get_defaultquota_text {
 4185:     my ($settingstatus) = @_;
 4186:     my $defquotatext; 
 4187:     if ($settingstatus eq '') {
 4188:         $defquotatext = &mt('default');
 4189:     } else {
 4190:         my ($usertypes,$order) =
 4191:             &Apache::lonnet::retrieve_inst_usertypes($env{'form.ccdomain'});
 4192:         if ($usertypes->{$settingstatus} eq '') {
 4193:             $defquotatext = &mt('default');
 4194:         } else {
 4195:             $defquotatext = &mt('default for [_1]',$usertypes->{$settingstatus});
 4196:         }
 4197:     }
 4198:     return $defquotatext;
 4199: }
 4200: 
 4201: sub update_result_form {
 4202:     my ($uhome) = @_;
 4203:     my $outcome = 
 4204:     '<form name="userupdate" method="post" action="">'."\n";
 4205:     foreach my $item ('srchby','srchin','srchtype','srchterm','srchdomain','ccuname','ccdomain') {
 4206:         $outcome .= '<input type="hidden" name="'.$item.'" value="'.$env{'form.'.$item}.'" />'."\n";
 4207:     }
 4208:     if ($env{'form.origname'} ne '') {
 4209:         $outcome .= '<input type="hidden" name="origname" value="'.$env{'form.origname'}.'" />'."\n";
 4210:     }
 4211:     foreach my $item ('sortby','seluname','seludom') {
 4212:         if (exists($env{'form.'.$item})) {
 4213:             $outcome .= '<input type="hidden" name="'.$item.'" value="'.$env{'form.'.$item}.'" />'."\n";
 4214:         }
 4215:     }
 4216:     if ($uhome eq 'no_host') {
 4217:         $outcome .= '<input type="hidden" name="forcenewuser" value="1" />'."\n";
 4218:     }
 4219:     $outcome .= '<input type="hidden" name="phase" value="" />'."\n".
 4220:                 '<input type="hidden" name="currstate" value="" />'."\n".
 4221:                 '<input type="hidden" name="action" value="'.$env{'form.action'}.'" />'."\n".
 4222:                 '</form>';
 4223:     return $outcome;
 4224: }
 4225: 
 4226: sub quota_admin {
 4227:     my ($setquota,$changeHash,$name) = @_;
 4228:     my $quotachanged;
 4229:     if (&Apache::lonnet::allowed('mpq',$env{'form.ccdomain'})) {
 4230:         # Current user has quota modification privileges
 4231:         if (ref($changeHash) eq 'HASH') {
 4232:             $quotachanged = 1;
 4233:             $changeHash->{$name.'quota'} = $setquota;
 4234:         }
 4235:     }
 4236:     return $quotachanged;
 4237: }
 4238: 
 4239: sub tool_admin {
 4240:     my ($tool,$settool,$changeHash,$context) = @_;
 4241:     my $canchange = 0; 
 4242:     if ($context eq 'requestcourses') {
 4243:         if (&Apache::lonnet::allowed('ccc',$env{'form.ccdomain'})) {
 4244:             $canchange = 1;
 4245:         }
 4246:     } elsif ($context eq 'reqcrsotherdom') {
 4247:         if (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) {
 4248:             $canchange = 1;
 4249:         }
 4250:     } elsif ($context eq 'requestauthor') {
 4251:         if (&Apache::lonnet::allowed('cau',$env{'request.role.domain'})) {
 4252:             $canchange = 1;
 4253:         }
 4254:     } elsif (&Apache::lonnet::allowed('mut',$env{'form.ccdomain'})) {
 4255:         # Current user has quota modification privileges
 4256:         $canchange = 1;
 4257:     }
 4258:     my $toolchanged;
 4259:     if ($canchange) {
 4260:         if (ref($changeHash) eq 'HASH') {
 4261:             $toolchanged = 1;
 4262:             if ($tool eq 'requestauthor') {
 4263:                 $changeHash->{$context} = $settool;
 4264:             } else {
 4265:                 $changeHash->{$context.'.'.$tool} = $settool;
 4266:             }
 4267:         }
 4268:     }
 4269:     return $toolchanged;
 4270: }
 4271: 
 4272: sub build_roles {
 4273:     my ($sectionstr,$sections,$role) = @_;
 4274:     my $num_sections = 0;
 4275:     if ($sectionstr=~ /,/) {
 4276:         my @secnums = split/,/,$sectionstr;
 4277:         if ($role eq 'st') {
 4278:             $secnums[0] =~ s/\W//g;
 4279:             $$sections{$secnums[0]} = 1;
 4280:             $num_sections = 1;
 4281:         } else {
 4282:             foreach my $sec (@secnums) {
 4283:                 $sec =~ ~s/\W//g;
 4284:                 if (!($sec eq "")) {
 4285:                     if (exists($$sections{$sec})) {
 4286:                         $$sections{$sec} ++;
 4287:                     } else {
 4288:                         $$sections{$sec} = 1;
 4289:                         $num_sections ++;
 4290:                     }
 4291:                 }
 4292:             }
 4293:         }
 4294:     } else {
 4295:         $sectionstr=~s/\W//g;
 4296:         unless ($sectionstr eq '') {
 4297:             $$sections{$sectionstr} = 1;
 4298:             $num_sections ++;
 4299:         }
 4300:     }
 4301: 
 4302:     return $num_sections;
 4303: }
 4304: 
 4305: # ========================================================== Custom Role Editor
 4306: 
 4307: sub custom_role_editor {
 4308:     my ($r,$brcrum,$prefix) = @_;
 4309:     my $action = $env{'form.customroleaction'};
 4310:     my $rolename; 
 4311:     if ($action eq 'new') {
 4312:         $rolename=$env{'form.newrolename'};
 4313:     } else {
 4314:         $rolename=$env{'form.rolename'};
 4315:     }
 4316: 
 4317:     my ($crstype,$context);
 4318:     if ($env{'request.course.id'}) {
 4319:         $crstype = &Apache::loncommon::course_type();
 4320:         $context = 'course';
 4321:     } else {
 4322:         $context = 'domain';
 4323:         $crstype = 'course';
 4324:     }
 4325: 
 4326:     $rolename=~s/[^A-Za-z0-9]//gs;
 4327:     if (!$rolename || $env{'form.phase'} eq 'pickrole') {
 4328: 	&print_username_entry_form($r,undef,undef,undef,undef,$crstype,$brcrum);
 4329:         return;
 4330:     }
 4331: 
 4332:     my $formname = 'form1';
 4333:     my %privs=();
 4334:     my $body_top = '<h2>';
 4335: # ------------------------------------------------------- Does this role exist?
 4336:     my ($rdummy,$roledef)=
 4337: 			 &Apache::lonnet::get('roles',["rolesdef_$rolename"]);
 4338:     if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 4339:         $body_top .= &mt('Existing Role').' "';
 4340: # ------------------------------------------------- Get current role privileges
 4341:         ($privs{'system'},$privs{'domain'},$privs{'course'})=split(/\_/,$roledef);
 4342:         if ($privs{'system'} =~ /bre\&S/) {
 4343:             if ($context eq 'domain') {
 4344:                 $crstype = 'Course';
 4345:             } elsif ($crstype eq 'Community') {
 4346:                 $privs{'system'} =~ s/bre\&S//;
 4347:             }
 4348:         } elsif ($context eq 'domain') {
 4349:             $crstype = 'Course';
 4350:         }
 4351:     } else {
 4352:         $body_top .= &mt('New Role').' "';
 4353:         $roledef='';
 4354:     }
 4355:     $body_top .= $rolename.'"</h2>';
 4356: 
 4357: # ------------------------------------------------------- What can be assigned?
 4358:     my %full=();
 4359:     my %levels=(
 4360:                  course => {},
 4361:                  domain => {},
 4362:                  system => {},
 4363:                );
 4364:     my %levelscurrent=(
 4365:                         course => {},
 4366:                         domain => {},
 4367:                         system => {},
 4368:                       );
 4369:     &Apache::lonuserutils::custom_role_privs(\%privs,\%full,\%levels,\%levelscurrent);
 4370:     my ($jsback,$elements) = &crumb_utilities();
 4371:     my @templateroles = &Apache::lonuserutils::custom_template_roles($context,$crstype);
 4372:     my $head_script =
 4373:         &Apache::lonuserutils::custom_roledefs_js($context,$crstype,$formname,
 4374:                                                   \%full,\@templateroles,$jsback);
 4375:     push (@{$brcrum},
 4376:               {href => "javascript:backPage(document.$formname,'pickrole','')",
 4377:                text => "Pick custom role",
 4378:                faq  => 282,bug=>'Instructor Interface',},
 4379:               {href => "javascript:backPage(document.$formname,'','')",
 4380:                text => "Edit custom role",
 4381:                faq  => 282,
 4382:                bug  => 'Instructor Interface',
 4383:                help => 'Course_Editing_Custom_Roles'}
 4384:               );
 4385:     my $args = { bread_crumbs          => $brcrum,
 4386:                  bread_crumbs_component => 'User Management'};
 4387:  
 4388:     $r->print(&Apache::loncommon::start_page('Custom Role Editor',
 4389:                                              $head_script,$args).
 4390:               $body_top);
 4391:     $r->print('<form name="'.$formname.'" method="post" action="">'."\n".
 4392:               &Apache::lonuserutils::custom_role_header($context,$crstype,
 4393:                                                         \@templateroles,$prefix));
 4394: 
 4395:     $r->print(<<ENDCCF);
 4396: <input type="hidden" name="phase" value="set_custom_roles" />
 4397: <input type="hidden" name="rolename" value="$rolename" />
 4398: ENDCCF
 4399:     $r->print(&Apache::lonuserutils::custom_role_table($crstype,\%full,\%levels,
 4400:                                                        \%levelscurrent,$prefix));
 4401:     $r->print(&Apache::loncommon::end_data_table().
 4402:    '<input type="hidden" name="action" value="'.$env{'form.action'}.'" />'.
 4403:    '<input type="hidden" name="startrolename" value="'.$env{'form.rolename'}.
 4404:    '" />'."\n".'<input type="hidden" name="currstate" value="" />'."\n".
 4405:    '<input type="reset" value="'.&mt("Reset").'" />'."\n".
 4406:    '<input type="submit" value="'.&mt('Save').'" /></form>');
 4407: }
 4408: 
 4409: # ---------------------------------------------------------- Call to definerole
 4410: sub set_custom_role {
 4411:     my ($r,$context,$brcrum,$prefix) = @_;
 4412:     my $rolename=$env{'form.rolename'};
 4413:     $rolename=~s/[^A-Za-z0-9]//gs;
 4414:     if (!$rolename) {
 4415: 	&custom_role_editor($r,$brcrum,$prefix);
 4416:         return;
 4417:     }
 4418:     my ($jsback,$elements) = &crumb_utilities();
 4419:     my $jscript = '<script type="text/javascript">'
 4420:                  .'// <![CDATA['."\n"
 4421:                  .$jsback."\n"
 4422:                  .'// ]]>'."\n"
 4423:                  .'</script>'."\n";
 4424:     push(@{$brcrum},
 4425:         {href => "javascript:backPage(document.customresult,'pickrole','')",
 4426:          text => "Pick custom role",
 4427:          faq  => 282,
 4428:          bug  => 'Instructor Interface',},
 4429:         {href => "javascript:backPage(document.customresult,'selected_custom_edit','')",
 4430:          text => "Edit custom role",
 4431:          faq  => 282,
 4432:          bug  => 'Instructor Interface',},
 4433:         {href => "javascript:backPage(document.customresult,'set_custom_roles','')",
 4434:          text => "Result",
 4435:          faq  => 282,
 4436:          bug  => 'Instructor Interface',
 4437:          help => 'Course_Editing_Custom_Roles'},
 4438:         );
 4439:     my $args = { bread_crumbs           => $brcrum,
 4440:                  bread_crumbs_component => 'User Management'};
 4441:     $r->print(&Apache::loncommon::start_page('Save Custom Role',$jscript,$args));
 4442: 
 4443:     my $newrole;
 4444:     my ($rdummy,$roledef)=
 4445: 	&Apache::lonnet::get('roles',["rolesdef_$rolename"]);
 4446: 
 4447: # ------------------------------------------------------- Does this role exist?
 4448:     $r->print('<h3>');
 4449:     if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 4450: 	$r->print(&mt('Existing Role').' "');
 4451:     } else {
 4452: 	$r->print(&mt('New Role').' "');
 4453: 	$roledef='';
 4454:         $newrole = 1;
 4455:     }
 4456:     $r->print($rolename.'"</h3>');
 4457: # ------------------------------------------------- Assign role and show result
 4458: 
 4459:     my $errmsg;
 4460:     my %newprivs = &Apache::lonuserutils::custom_role_update($rolename,$prefix);
 4461:     # Assign role and return result
 4462:     my $result = &Apache::lonnet::definerole($rolename,$newprivs{'s'},$newprivs{'d'},
 4463:                                              $newprivs{'c'});
 4464:     if ($result ne 'ok') {
 4465:         $errmsg = ': '.$result;
 4466:     }
 4467:     my $message =
 4468:         &Apache::lonhtmlcommon::confirm_success(
 4469:             &mt('Defining Role').$errmsg, ($result eq 'ok' ? 0 : 1));
 4470:     if ($env{'request.course.id'}) {
 4471:         my $url='/'.$env{'request.course.id'};
 4472:         $url=~s/\_/\//g;
 4473:         $result =
 4474:             &Apache::lonnet::assigncustomrole(
 4475:                 $env{'user.domain'},$env{'user.name'},
 4476:                 $url,
 4477:                 $env{'user.domain'},$env{'user.name'},
 4478:                 $rolename,undef,undef,undef,$context);
 4479:         if ($result ne 'ok') {
 4480:             $errmsg = ': '.$result;
 4481:         }
 4482:         $message .=
 4483:             '<br />'
 4484:            .&Apache::lonhtmlcommon::confirm_success(
 4485:                 &mt('Assigning Role to Self').$errmsg, ($result eq 'ok' ? 0 : 1));
 4486:     }
 4487:     $r->print(
 4488:         &Apache::loncommon::confirmwrapper($message)
 4489:        .'<br />'
 4490:        .&Apache::lonhtmlcommon::actionbox([
 4491:             '<a href="javascript:backPage(document.customresult,'."'pickrole'".')">'
 4492:            .&mt('Create or edit another custom role')
 4493:            .'</a>'])
 4494:        .'<form name="customresult" method="post" action="">'
 4495:        .&Apache::lonhtmlcommon::echo_form_input([])
 4496:        .'</form>'
 4497:     );
 4498: }
 4499: 
 4500: # ================================================================ Main Handler
 4501: sub handler {
 4502:     my $r = shift;
 4503:     if ($r->header_only) {
 4504:        &Apache::loncommon::content_type($r,'text/html');
 4505:        $r->send_http_header;
 4506:        return OK;
 4507:     }
 4508:     my ($context,$crstype);
 4509:     if ($env{'request.course.id'}) {
 4510:         $context = 'course';
 4511:         $crstype = &Apache::loncommon::course_type();
 4512:     } elsif ($env{'request.role'} =~ /^au\./) {
 4513:         $context = 'author';
 4514:     } else {
 4515:         $context = 'domain';
 4516:     }
 4517: 
 4518:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 4519:         ['action','state','callingform','roletype','showrole','bulkaction','popup','phase',
 4520:          'username','domain','srchterm','srchdomain','srchin','srchby','srchtype','queue']);
 4521:     &Apache::lonhtmlcommon::clear_breadcrumbs();
 4522:     my $args;
 4523:     my $brcrum = [];
 4524:     my $bread_crumbs_component = 'User Management';
 4525:     if (($env{'form.action'} ne 'dateselect') && ($env{'form.action'} ne 'displayuserreq')) {
 4526:         $brcrum = [{href=>"/adm/createuser",
 4527:                     text=>"User Management",
 4528:                     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'}
 4529:                   ];
 4530:     }
 4531:     #SD Following files not added to help, because the corresponding .tex-files seem to
 4532:     #be missing: Course_Approve_Selfenroll,Course_User_Logs,
 4533:     my ($permission,$allowed) = 
 4534:         &Apache::lonuserutils::get_permission($context,$crstype);
 4535:     if (!$allowed) {
 4536:         if ($context eq 'course') {
 4537:             $r->internal_redirect('/adm/viewclasslist');
 4538:             return OK;
 4539:         }
 4540:         $env{'user.error.msg'}=
 4541:             "/adm/createuser:cst:0:0:Cannot create/modify user data ".
 4542:                                  "or view user status.";
 4543:         return HTTP_NOT_ACCEPTABLE;
 4544:     }
 4545: 
 4546:     &Apache::loncommon::content_type($r,'text/html');
 4547:     $r->send_http_header;
 4548: 
 4549:     my $showcredits;
 4550:     if ((($context eq 'course') && ($crstype eq 'Course')) || 
 4551:          ($context eq 'domain')) {
 4552:         my %domdefaults = 
 4553:             &Apache::lonnet::get_domain_defaults($env{'request.role.domain'});
 4554:         if ($domdefaults{'officialcredits'} || $domdefaults{'unofficialcredits'}) {
 4555:             $showcredits = 1;
 4556:         }
 4557:     }
 4558: 
 4559:     # Main switch on form.action and form.state, as appropriate
 4560:     if (! exists($env{'form.action'})) {
 4561:         $args = {bread_crumbs => $brcrum,
 4562:                  bread_crumbs_component => $bread_crumbs_component}; 
 4563:         $r->print(&header(undef,$args));
 4564:         $r->print(&print_main_menu($permission,$context,$crstype));
 4565:     } elsif ($env{'form.action'} eq 'upload' && $permission->{'cusr'}) {
 4566:         push(@{$brcrum},
 4567:               { href => '/adm/createuser?action=upload&state=',
 4568:                 text => 'Upload Users List',
 4569:                 help => 'Course_Create_Class_List',
 4570:               });
 4571:         $bread_crumbs_component = 'Upload Users List';
 4572:         $args = {bread_crumbs           => $brcrum,
 4573:                  bread_crumbs_component => $bread_crumbs_component};
 4574:         $r->print(&header(undef,$args));
 4575:         $r->print('<form name="studentform" method="post" '.
 4576:                   'enctype="multipart/form-data" '.
 4577:                   ' action="/adm/createuser">'."\n");
 4578:         if (! exists($env{'form.state'})) {
 4579:             &Apache::lonuserutils::print_first_users_upload_form($r,$context);
 4580:         } elsif ($env{'form.state'} eq 'got_file') {
 4581:             &Apache::lonuserutils::print_upload_manager_form($r,$context,$permission,
 4582:                                                              $crstype,$showcredits);
 4583:         } elsif ($env{'form.state'} eq 'enrolling') {
 4584:             if ($env{'form.datatoken'}) {
 4585:                 &Apache::lonuserutils::upfile_drop_add($r,$context,$permission,
 4586:                                                        $showcredits);
 4587:             }
 4588:         } else {
 4589:             &Apache::lonuserutils::print_first_users_upload_form($r,$context);
 4590:         }
 4591:     } elsif (((($env{'form.action'} eq 'singleuser') || ($env{'form.action'}
 4592:               eq 'singlestudent')) && ($permission->{'cusr'})) ||
 4593:              (($env{'form.action'} eq 'singleuser') && ($permission->{'view'})) ||
 4594:              (($env{'form.action'} eq 'accesslogs') && ($permission->{'activity'}))) {
 4595:         my $phase = $env{'form.phase'};
 4596:         my @search = ('srchterm','srchby','srchin','srchtype','srchdomain');
 4597: 	&Apache::loncreateuser::restore_prev_selections();
 4598: 	my $srch;
 4599: 	foreach my $item (@search) {
 4600: 	    $srch->{$item} = $env{'form.'.$item};
 4601: 	}
 4602:         if (($phase eq 'get_user_info') || ($phase eq 'userpicked') ||
 4603:             ($phase eq 'createnewuser') || ($phase eq 'activity')) {
 4604:             if ($env{'form.phase'} eq 'createnewuser') {
 4605:                 my $response;
 4606:                 if ($env{'form.srchterm'} !~ /^$match_username$/) {
 4607:                     my $response =
 4608:                         '<span class="LC_warning">'
 4609:                        .&mt('You must specify a valid username. Only the following are allowed:'
 4610:                            .' letters numbers - . @')
 4611:                        .'</span>';
 4612:                     $env{'form.phase'} = '';
 4613:                     &print_username_entry_form($r,$context,$response,$srch,undef,
 4614:                                                $crstype,$brcrum,$showcredits);
 4615:                 } else {
 4616:                     my $ccuname =&LONCAPA::clean_username($srch->{'srchterm'});
 4617:                     my $ccdomain=&LONCAPA::clean_domain($srch->{'srchdomain'});
 4618:                     &print_user_modification_page($r,$ccuname,$ccdomain,
 4619:                                                   $srch,$response,$context,
 4620:                                                   $permission,$crstype,$brcrum,
 4621:                                                   $showcredits);
 4622:                 }
 4623:             } elsif ($env{'form.phase'} eq 'get_user_info') {
 4624:                 my ($currstate,$response,$forcenewuser,$results) = 
 4625:                     &user_search_result($context,$srch);
 4626:                 if ($env{'form.currstate'} eq 'modify') {
 4627:                     $currstate = $env{'form.currstate'};
 4628:                 }
 4629:                 if ($currstate eq 'select') {
 4630:                     &print_user_selection_page($r,$response,$srch,$results,
 4631:                                                \@search,$context,undef,$crstype,
 4632:                                                $brcrum);
 4633:                 } elsif (($currstate eq 'modify') || ($env{'form.action'} eq 'accesslogs')) {
 4634:                     my ($ccuname,$ccdomain,$uhome);
 4635:                     if (($srch->{'srchby'} eq 'uname') && 
 4636:                         ($srch->{'srchtype'} eq 'exact')) {
 4637:                         $ccuname = $srch->{'srchterm'};
 4638:                         $ccdomain= $srch->{'srchdomain'};
 4639:                     } else {
 4640:                         my @matchedunames = keys(%{$results});
 4641:                         ($ccuname,$ccdomain) = split(/:/,$matchedunames[0]);
 4642:                     }
 4643:                     $ccuname =&LONCAPA::clean_username($ccuname);
 4644:                     $ccdomain=&LONCAPA::clean_domain($ccdomain);
 4645:                     if ($env{'form.action'} eq 'accesslogs') {
 4646:                         my $uhome;
 4647:                         if (($ccuname ne '') && ($ccdomain ne '')) {
 4648:                            $uhome = &Apache::lonnet::homeserver($ccuname,$ccdomain);
 4649:                         }
 4650:                         if (($uhome eq '') || ($uhome eq 'no_host')) {
 4651:                             $env{'form.phase'} = '';
 4652:                             undef($forcenewuser);
 4653:                             #if ($response) {
 4654:                             #    unless ($response =~ m{\Q<br /><br />\E$}) {
 4655:                             #        $response .= '<br /><br />';
 4656:                             #    }
 4657:                             #}
 4658:                             &print_username_entry_form($r,$context,$response,$srch,
 4659:                                                        $forcenewuser,$crstype,$brcrum);
 4660:                         } else {
 4661:                             &print_useraccesslogs_display($r,$ccuname,$ccdomain,$permission,$brcrum);
 4662:                         }
 4663:                     } else {
 4664:                         if ($env{'form.forcenewuser'}) {
 4665:                             $response = '';
 4666:                         }
 4667:                         &print_user_modification_page($r,$ccuname,$ccdomain,
 4668:                                                       $srch,$response,$context,
 4669:                                                       $permission,$crstype,$brcrum);
 4670:                     }
 4671:                 } elsif ($currstate eq 'query') {
 4672:                     &print_user_query_page($r,'createuser',$brcrum);
 4673:                 } else {
 4674:                     $env{'form.phase'} = '';
 4675:                     &print_username_entry_form($r,$context,$response,$srch,
 4676:                                                $forcenewuser,$crstype,$brcrum);
 4677:                 }
 4678:             } elsif ($env{'form.phase'} eq 'userpicked') {
 4679:                 my $ccuname = &LONCAPA::clean_username($env{'form.seluname'});
 4680:                 my $ccdomain = &LONCAPA::clean_domain($env{'form.seludom'});
 4681:                 if ($env{'form.action'} eq 'accesslogs') {
 4682:                     &print_useraccesslogs_display($r,$ccuname,$ccdomain,$permission,$brcrum);
 4683:                 } else {
 4684:                     &print_user_modification_page($r,$ccuname,$ccdomain,$srch,'',
 4685:                                                   $context,$permission,$crstype,
 4686:                                                   $brcrum);
 4687:                 }
 4688:             } elsif ($env{'form.action'} eq 'accesslogs') {
 4689:                 my $ccuname = &LONCAPA::clean_username($env{'form.accessuname'});
 4690:                 my $ccdomain = &LONCAPA::clean_domain($env{'form.accessudom'});
 4691:                 &print_useraccesslogs_display($r,$ccuname,$ccdomain,$permission,$brcrum);
 4692:             }
 4693:         } elsif ($env{'form.phase'} eq 'update_user_data') {
 4694:             &update_user_data($r,$context,$crstype,$brcrum,$showcredits);
 4695:         } else {
 4696:             &print_username_entry_form($r,$context,undef,$srch,undef,$crstype,
 4697:                                        $brcrum);
 4698:         }
 4699:     } elsif ($env{'form.action'} eq 'custom' && $permission->{'custom'}) {
 4700:         my $prefix;
 4701:         if ($env{'form.phase'} eq 'set_custom_roles') {
 4702:             &set_custom_role($r,$context,$brcrum,$prefix);
 4703:         } else {
 4704:             &custom_role_editor($r,$brcrum,$prefix);
 4705:         }
 4706:     } elsif (($env{'form.action'} eq 'processauthorreq') &&
 4707:              ($permission->{'cusr'}) && 
 4708:              (&Apache::lonnet::allowed('cau',$env{'request.role.domain'}))) {
 4709:         push(@{$brcrum},
 4710:                  {href => '/adm/createuser?action=processauthorreq',
 4711:                   text => 'Authoring Space requests',
 4712:                   help => 'Domain_Role_Approvals'});
 4713:         $bread_crumbs_component = 'Authoring requests';
 4714:         if ($env{'form.state'} eq 'done') {
 4715:             push(@{$brcrum},
 4716:                      {href => '/adm/createuser?action=authorreqqueue',
 4717:                       text => 'Result',
 4718:                       help => 'Domain_Role_Approvals'});
 4719:             $bread_crumbs_component = 'Authoring request result';
 4720:         }
 4721:         $args = { bread_crumbs           => $brcrum,
 4722:                   bread_crumbs_component => $bread_crumbs_component};
 4723:         my $js = &usernamerequest_javascript();
 4724:         $r->print(&header(&add_script($js),$args));
 4725:         if (!exists($env{'form.state'})) {
 4726:             $r->print(&Apache::loncoursequeueadmin::display_queued_requests('requestauthor',
 4727:                                                                             $env{'request.role.domain'}));
 4728:         } elsif ($env{'form.state'} eq 'done') {
 4729:             $r->print('<h3>'.&mt('Authoring request processing').'</h3>'."\n");
 4730:             $r->print(&Apache::loncoursequeueadmin::update_request_queue('requestauthor',
 4731:                                                                          $env{'request.role.domain'}));
 4732:         }
 4733:     } elsif (($env{'form.action'} eq 'processusernamereq') &&
 4734:              ($permission->{'cusr'}) &&
 4735:              (&Apache::lonnet::allowed('cau',$env{'request.role.domain'}))) {
 4736:         push(@{$brcrum},
 4737:                  {href => '/adm/createuser?action=processusernamereq',
 4738:                   text => 'LON-CAPA account requests',
 4739:                   help => 'Domain_Username_Approvals'});
 4740:         $bread_crumbs_component = 'Account requests';
 4741:         if ($env{'form.state'} eq 'done') {
 4742:             push(@{$brcrum},
 4743:                      {href => '/adm/createuser?action=usernamereqqueue',
 4744:                       text => 'Result',
 4745:                       help => 'Domain_Username_Approvals'});
 4746:             $bread_crumbs_component = 'LON-CAPA account request result';
 4747:         }
 4748:         $args = { bread_crumbs           => $brcrum,
 4749:                   bread_crumbs_component => $bread_crumbs_component};
 4750:         my $js = &usernamerequest_javascript();
 4751:         $r->print(&header(&add_script($js),$args));
 4752:         if (!exists($env{'form.state'})) {
 4753:             $r->print(&Apache::loncoursequeueadmin::display_queued_requests('requestusername',
 4754:                                                                             $env{'request.role.domain'}));
 4755:         } elsif ($env{'form.state'} eq 'done') {
 4756:             $r->print('<h3>'.&mt('LON-CAPA account request processing').'</h3>'."\n");
 4757:             $r->print(&Apache::loncoursequeueadmin::update_request_queue('requestusername',
 4758:                                                                          $env{'request.role.domain'}));
 4759:         }
 4760:     } elsif (($env{'form.action'} eq 'displayuserreq') &&
 4761:              ($permission->{'cusr'})) {
 4762:         my $dom = $env{'form.domain'};
 4763:         my $uname = $env{'form.username'};
 4764:         my $warning;
 4765:         if (($dom =~ /^$match_domain$/) && (&Apache::lonnet::domain($dom) ne '')) {
 4766:             if (($dom eq $env{'request.role.domain'}) && (&Apache::lonnet::allowed('ccc',$dom))) {
 4767:                 if (($uname =~ /^$match_username$/) && ($env{'form.queue'} eq 'approval')) {
 4768:                     my $uhome = &Apache::lonnet::homeserver($uname,$dom);
 4769:                     if ($uhome eq 'no_host') {
 4770:                         my $queue = $env{'form.queue'};
 4771:                         my $reqkey = &escape($uname).'_'.$queue; 
 4772:                         my $namespace = 'usernamequeue';
 4773:                         my $domconfig = &Apache::lonnet::get_domainconfiguser($dom);
 4774:                         my %queued =
 4775:                             &Apache::lonnet::get($namespace,[$reqkey],$dom,$domconfig);
 4776:                         unless ($queued{$reqkey}) {
 4777:                             $warning = &mt('No information was found for this LON-CAPA account request.');
 4778:                         }
 4779:                     } else {
 4780:                         $warning = &mt('A LON-CAPA account already exists for the requested username and domain.');
 4781:                     }
 4782:                 } else {
 4783:                     $warning = &mt('LON-CAPA account request status check is for an invalid username.');
 4784:                 }
 4785:             } else {
 4786:                 $warning = &mt('You do not have rights to view LON-CAPA account requests in the domain specified.');
 4787:             }
 4788:         } else {
 4789:             $warning = &mt('LON-CAPA account request status check is for an invalid domain.');
 4790:         }
 4791:         my $args = { only_body => 1 };
 4792:         $r->print(&header(undef,$args).
 4793:                   '<h3>'.&mt('LON-CAPA Account Request Details').'</h3>');
 4794:         if ($warning ne '') {
 4795:             $r->print('<div class="LC_warning">'.$warning.'</div>');
 4796:         } else {
 4797:             my ($infofields,$infotitles) = &Apache::loncommon::emailusername_info();
 4798:             my $domconfiguser = &Apache::lonnet::get_domainconfiguser($dom);
 4799:             my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 4800:             if (ref($domconfig{'usercreation'}) eq 'HASH') {
 4801:                 if (ref($domconfig{'usercreation'}{'cancreate'}) eq 'HASH') {
 4802:                     if (ref($domconfig{'usercreation'}{'cancreate'}{'emailusername'}) eq 'HASH') {
 4803:                         my %info =
 4804:                             &Apache::lonnet::get('nohist_requestedusernames',[$uname],$dom,$domconfiguser);
 4805:                         if (ref($info{$uname}) eq 'HASH') {
 4806:                             my $usertype = $info{$uname}{'inststatus'};
 4807:                             unless ($usertype) {
 4808:                                 $usertype = 'default';
 4809:                             }
 4810:                             if (ref($domconfig{'usercreation'}{'cancreate'}{'emailusername'}{$usertype}) eq 'HASH') {
 4811:                                 if ((ref($infofields) eq 'ARRAY') && (ref($infotitles) eq 'HASH')) {
 4812:                                     $r->print('<div>'.&Apache::lonhtmlcommon::start_pick_box());
 4813:                                     my ($num,$count,$showstatus);
 4814:                                     $count = scalar(keys(%{$domconfig{'usercreation'}{'cancreate'}{'emailusername'}{$usertype}}));
 4815:                                     unless ($usertype eq 'default') {
 4816:                                         my ($othertitle,$usertypes,$types) = 
 4817:                                             &Apache::loncommon::sorted_inst_types($dom);
 4818:                                         if (ref($usertypes) eq 'HASH') {
 4819:                                             if ($usertypes->{$usertype}) {
 4820:                                                 $showstatus = $usertypes->{$usertype};
 4821:                                                 $count ++;
 4822:                                             }
 4823:                                         }
 4824:                                     }
 4825:                                     foreach my $field (@{$infofields}) {
 4826:                                         next unless ($domconfig{'usercreation'}{'cancreate'}{'emailusername'}{$usertype}{$field});
 4827:                                         next unless ($infotitles->{$field});
 4828:                                         $r->print(&Apache::lonhtmlcommon::row_title($infotitles->{$field}).
 4829:                                                   $info{$uname}{$field});
 4830:                                         $num ++;
 4831:                                         if ($count == $num) {
 4832:                                             $r->print(&Apache::lonhtmlcommon::row_closure(1));
 4833:                                         } else {
 4834:                                             $r->print(&Apache::lonhtmlcommon::row_closure());
 4835:                                         }
 4836:                                     }
 4837:                                     if ($showstatus) {
 4838:                                         $r->print(&Apache::lonhtmlcommon::row_title(&mt('Status type (self-reported)')).
 4839:                                                   $showstatus.
 4840:                                                   &Apache::lonhtmlcommon::row_closure(1));
 4841:                                     }
 4842:                                     $r->print(&Apache::lonhtmlcommon::end_pick_box().'</div>');
 4843:                                 }
 4844:                             }
 4845:                         }
 4846:                     }
 4847:                 }
 4848:             }
 4849:             $r->print(&close_popup_form());
 4850:         }
 4851:     } elsif (($env{'form.action'} eq 'listusers') && 
 4852:              ($permission->{'view'} || $permission->{'cusr'})) {
 4853:         if ($env{'form.phase'} eq 'bulkchange') {
 4854:             push(@{$brcrum},
 4855:                     {href => '/adm/createuser?action=listusers',
 4856:                      text => "List Users"},
 4857:                     {href => "/adm/createuser",
 4858:                      text => "Result",
 4859:                      help => 'Course_View_Class_List'});
 4860:             $bread_crumbs_component = 'Update Users';
 4861:             $args = {bread_crumbs           => $brcrum,
 4862:                      bread_crumbs_component => $bread_crumbs_component};
 4863:             $r->print(&header(undef,$args));
 4864:             my $setting = $env{'form.roletype'};
 4865:             my $choice = $env{'form.bulkaction'};
 4866:             if ($permission->{'cusr'}) {
 4867:                 &Apache::lonuserutils::update_user_list($r,$context,$setting,$choice,$crstype);
 4868:             } else {
 4869:                 $r->print(&mt('You are not authorized to make bulk changes to user roles'));
 4870:                 $r->print('<p><a href="/adm/createuser?action=listusers">'.&mt('Display User Lists').'</a>');
 4871:             }
 4872:         } else {
 4873:             push(@{$brcrum},
 4874:                     {href => '/adm/createuser?action=listusers',
 4875:                      text => "List Users",
 4876:                      help => 'Course_View_Class_List'});
 4877:             $bread_crumbs_component = 'List Users';
 4878:             $args = {bread_crumbs           => $brcrum,
 4879:                      bread_crumbs_component => $bread_crumbs_component};
 4880:             my ($cb_jscript,$jscript,$totcodes,$codetitles,$idlist,$idlist_titles);
 4881:             my $formname = 'studentform';
 4882:             my $hidecall = "hide_searching();";
 4883:             if (($context eq 'domain') && (($env{'form.roletype'} eq 'course') ||
 4884:                 ($env{'form.roletype'} eq 'community'))) {
 4885:                 if ($env{'form.roletype'} eq 'course') {
 4886:                     ($cb_jscript,$jscript,$totcodes,$codetitles,$idlist,$idlist_titles) = 
 4887:                         &Apache::lonuserutils::courses_selector($env{'request.role.domain'},
 4888:                                                                 $formname);
 4889:                 } elsif ($env{'form.roletype'} eq 'community') {
 4890:                     $cb_jscript = 
 4891:                         &Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'});
 4892:                     my %elements = (
 4893:                                       coursepick => 'radio',
 4894:                                       coursetotal => 'text',
 4895:                                       courselist => 'text',
 4896:                                    );
 4897:                     $jscript = &Apache::lonhtmlcommon::set_form_elements(\%elements);
 4898:                 }
 4899:                 $jscript .= &verify_user_display($context)."\n".
 4900:                             &Apache::loncommon::check_uncheck_jscript();
 4901:                 my $js = &add_script($jscript).$cb_jscript;
 4902:                 my $loadcode = 
 4903:                     &Apache::lonuserutils::course_selector_loadcode($formname);
 4904:                 if ($loadcode ne '') {
 4905:                     $args->{add_entries} = {onload => "$loadcode;$hidecall"};
 4906:                 } else {
 4907:                     $args->{add_entries} = {onload => $hidecall};
 4908:                 }
 4909:                 $r->print(&header($js,$args));
 4910:             } else {
 4911:                 $args->{add_entries} = {onload => $hidecall};
 4912:                 $jscript = &verify_user_display($context).
 4913:                            &Apache::loncommon::check_uncheck_jscript(); 
 4914:                 $r->print(&header(&add_script($jscript),$args));
 4915:             }
 4916:             &Apache::lonuserutils::print_userlist($r,undef,$permission,$context,
 4917:                          $formname,$totcodes,$codetitles,$idlist,$idlist_titles,
 4918:                          $showcredits);
 4919:         }
 4920:     } elsif ($env{'form.action'} eq 'drop' && $permission->{'cusr'}) {
 4921:         my $brtext;
 4922:         if ($crstype eq 'Community') {
 4923:             $brtext = 'Drop Members';
 4924:         } else {
 4925:             $brtext = 'Drop Students';
 4926:         }
 4927:         push(@{$brcrum},
 4928:                 {href => '/adm/createuser?action=drop',
 4929:                  text => $brtext,
 4930:                  help => 'Course_Drop_Student'});
 4931:         if ($env{'form.state'} eq 'done') {
 4932:             push(@{$brcrum},
 4933:                      {href=>'/adm/createuser?action=drop',
 4934:                       text=>"Result"});
 4935:         }
 4936:         $bread_crumbs_component = $brtext;
 4937:         $args = {bread_crumbs           => $brcrum,
 4938:                  bread_crumbs_component => $bread_crumbs_component}; 
 4939:         $r->print(&header(undef,$args));
 4940:         if (!exists($env{'form.state'})) {
 4941:             &Apache::lonuserutils::print_drop_menu($r,$context,$permission,$crstype);
 4942:         } elsif ($env{'form.state'} eq 'done') {
 4943:             &Apache::lonuserutils::update_user_list($r,$context,undef,
 4944:                                                     $env{'form.action'});
 4945:         }
 4946:     } elsif ($env{'form.action'} eq 'dateselect') {
 4947:         if ($permission->{'cusr'}) {
 4948:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 4949:                       &Apache::lonuserutils::date_section_selector($context,$permission,
 4950:                                                                    $crstype,$showcredits));
 4951:         } else {
 4952:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 4953:                      '<span class="LC_error">'.&mt('You do not have permission to modify dates or sections for users').'</span>'); 
 4954:         }
 4955:     } elsif ($env{'form.action'} eq 'selfenroll') {
 4956:         if ($permission->{selfenrolladmin}) {
 4957:             my $cid = $env{'request.course.id'};
 4958:             my $cdom = $env{'course.'.$cid.'.domain'};
 4959:             my $cnum = $env{'course.'.$cid.'.num'};
 4960:             my %currsettings = (
 4961:                 selfenroll_types              => $env{'course.'.$cid.'.internal.selfenroll_types'},
 4962:                 selfenroll_registered         => $env{'course.'.$cid.'.internal.selfenroll_registered'},
 4963:                 selfenroll_section            => $env{'course.'.$cid.'.internal.selfenroll_section'},
 4964:                 selfenroll_notifylist         => $env{'course.'.$cid.'.internal.selfenroll_notifylist'},
 4965:                 selfenroll_approval           => $env{'course.'.$cid.'.internal.selfenroll_approval'},
 4966:                 selfenroll_limit              => $env{'course.'.$cid.'.internal.selfenroll_limit'},
 4967:                 selfenroll_cap                => $env{'course.'.$cid.'.internal.selfenroll_cap'},
 4968:                 selfenroll_start_date         => $env{'course.'.$cid.'.internal.selfenroll_start_date'},
 4969:                 selfenroll_end_date           => $env{'course.'.$cid.'.internal.selfenroll_end_date'},
 4970:                 selfenroll_start_access       => $env{'course.'.$cid.'.internal.selfenroll_start_access'},
 4971:                 selfenroll_end_access         => $env{'course.'.$cid.'.internal.selfenroll_end_access'},
 4972:                 default_enrollment_start_date => $env{'course.'.$cid.'.default_enrollment_start_date'},
 4973:                 default_enrollment_end_date   => $env{'course.'.$cid.'.default_enrollment_end_date'},
 4974:                 uniquecode                    => $env{'course.'.$cid.'.internal.uniquecode'},
 4975:             );
 4976:             push(@{$brcrum},
 4977:                     {href => '/adm/createuser?action=selfenroll',
 4978:                      text => "Configure Self-enrollment",
 4979:                      help => 'Course_Self_Enrollment'});
 4980:             if (!exists($env{'form.state'})) {
 4981:                 $args = { bread_crumbs           => $brcrum,
 4982:                           bread_crumbs_component => 'Configure Self-enrollment'};
 4983:                 $r->print(&header(undef,$args));
 4984:                 $r->print('<h3>'.&mt('Self-enrollment with a student role').'</h3>'."\n");
 4985:                 &print_selfenroll_menu($r,'course',$cid,$cdom,$cnum,\%currsettings);
 4986:             } elsif ($env{'form.state'} eq 'done') {
 4987:                 push (@{$brcrum},
 4988:                           {href=>'/adm/createuser?action=selfenroll',
 4989:                            text=>"Result"});
 4990:                 $args = { bread_crumbs           => $brcrum,
 4991:                           bread_crumbs_component => 'Self-enrollment result'};
 4992:                 $r->print(&header(undef,$args));
 4993:                 $r->print('<h3>'.&mt('Self-enrollment with a student role').'</h3>'."\n");
 4994:                 &update_selfenroll_config($r,$cid,$cdom,$cnum,$context,$crstype,\%currsettings);
 4995:             }
 4996:         } else {
 4997:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 4998:                      '<span class="LC_error">'.&mt('You do not have permission to configure self-enrollment').'</span>');
 4999:         }
 5000:     } elsif ($env{'form.action'} eq 'selfenrollqueue') {
 5001:         if ($permission->{selfenrolladmin}) {
 5002:             push(@{$brcrum},
 5003:                      {href => '/adm/createuser?action=selfenrollqueue',
 5004:                       text => 'Enrollment requests',
 5005:                       help => 'Course_Self_Enrollment'});
 5006:             $bread_crumbs_component = 'Enrollment requests';
 5007:             if ($env{'form.state'} eq 'done') {
 5008:                 push(@{$brcrum},
 5009:                          {href => '/adm/createuser?action=selfenrollqueue',
 5010:                           text => 'Result',
 5011:                           help => 'Course_Self_Enrollment'});
 5012:                 $bread_crumbs_component = 'Enrollment result';
 5013:             }
 5014:             $args = { bread_crumbs           => $brcrum,
 5015:                       bread_crumbs_component => $bread_crumbs_component};
 5016:             $r->print(&header(undef,$args));
 5017:             my $cid = $env{'request.course.id'};
 5018:             my $cdom = $env{'course.'.$cid.'.domain'};
 5019:             my $cnum = $env{'course.'.$cid.'.num'};
 5020:             my $coursedesc = $env{'course.'.$cid.'.description'};
 5021:             if (!exists($env{'form.state'})) {
 5022:                 $r->print('<h3>'.&mt('Pending enrollment requests').'</h3>'."\n");
 5023:                 $r->print(&Apache::loncoursequeueadmin::display_queued_requests($context,
 5024:                                                                                 $cdom,$cnum));
 5025:             } elsif ($env{'form.state'} eq 'done') {
 5026:                 $r->print('<h3>'.&mt('Enrollment request processing').'</h3>'."\n");
 5027:                 $r->print(&Apache::loncoursequeueadmin::update_request_queue($context,
 5028:                                $cdom,$cnum,$coursedesc));
 5029:             }
 5030:         } else {
 5031:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 5032:                      '<span class="LC_error">'.&mt('You do not have permission to manage self-enrollment').'</span>');
 5033:         }
 5034:     } elsif ($env{'form.action'} eq 'changelogs') {
 5035:         if ($permission->{cusr} || $permission->{view}) {
 5036:             &print_userchangelogs_display($r,$context,$permission,$brcrum);
 5037:         } else {
 5038:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 5039:                      '<span class="LC_error">'.&mt('You do not have permission to view change logs').'</span>');
 5040:         }
 5041:     } elsif ($env{'form.action'} eq 'helpdesk') {
 5042:         if (($permission->{'owner'}) || ($permission->{'co-owner'})) {
 5043:             if ($env{'form.state'} eq 'process') {
 5044:                 if ($permission->{'owner'}) {
 5045:                     &update_helpdeskaccess($r,$permission,$brcrum);
 5046:                 } else {
 5047:                     &print_helpdeskaccess_display($r,$permission,$brcrum);
 5048:                 }    
 5049:             } else {
 5050:                 &print_helpdeskaccess_display($r,$permission,$brcrum);
 5051:             }
 5052:         } else {
 5053:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 5054:                       '<span class="LC_error">'.&mt('You do not have permission to view helpdesk access').'</span>');
 5055:         }
 5056:     } else {
 5057:         $bread_crumbs_component = 'User Management';
 5058:         $args = { bread_crumbs           => $brcrum,
 5059:                   bread_crumbs_component => $bread_crumbs_component};
 5060:         $r->print(&header(undef,$args));
 5061:         $r->print(&print_main_menu($permission,$context,$crstype));
 5062:     }
 5063:     $r->print(&Apache::loncommon::end_page());
 5064:     return OK;
 5065: }
 5066: 
 5067: sub header {
 5068:     my ($jscript,$args) = @_;
 5069:     my $start_page;
 5070:     if (ref($args) eq 'HASH') {
 5071:         $start_page=&Apache::loncommon::start_page('User Management',$jscript,$args);
 5072:     } else {
 5073:         $start_page=&Apache::loncommon::start_page('User Management',$jscript);
 5074:     }
 5075:     return $start_page;
 5076: }
 5077: 
 5078: sub add_script {
 5079:     my ($js) = @_;
 5080:     return '<script type="text/javascript">'."\n"
 5081:           .'// <![CDATA['."\n"
 5082:           .$js."\n"
 5083:           .'// ]]>'."\n"
 5084:           .'</script>'."\n";
 5085: }
 5086: 
 5087: sub usernamerequest_javascript {
 5088:     my $js = <<ENDJS;
 5089: 
 5090: function openusernamereqdisplay(dom,uname,queue) {
 5091:     var url = '/adm/createuser?action=displayuserreq';
 5092:     url += '&domain='+dom+'&username='+uname+'&queue='+queue;
 5093:     var title = 'Account_Request_Browser';
 5094:     var options = 'scrollbars=1,resizable=1,menubar=0';
 5095:     options += ',width=700,height=600';
 5096:     var stdeditbrowser = open(url,title,options,'1');
 5097:     stdeditbrowser.focus();
 5098:     return;
 5099: }
 5100:  
 5101: ENDJS
 5102: }
 5103: 
 5104: sub close_popup_form {
 5105:     my $close= &mt('Close Window');
 5106:     return << "END";
 5107: <p><form name="displayreq" action="" method="post">
 5108: <input type="button" name="closeme" value="$close" onclick="javascript:self.close();" />
 5109: </form></p>
 5110: END
 5111: }
 5112: 
 5113: sub verify_user_display {
 5114:     my ($context) = @_;
 5115:     my %lt = &Apache::lonlocal::texthash (
 5116:         course    => 'course(s): description, section(s), status',
 5117:         community => 'community(s): description, section(s), status',
 5118:         author    => 'author',
 5119:     );
 5120:     my $photos;
 5121:     if (($context eq 'course') && $env{'request.course.id'}) {
 5122:         $photos = $env{'course.'.$env{'request.course.id'}.'.internal.showphoto'};
 5123:     }
 5124:     my $output = <<"END";
 5125: 
 5126: function hide_searching() {
 5127:     if (document.getElementById('searching')) {
 5128:         document.getElementById('searching').style.display = 'none';
 5129:     }
 5130:     return;
 5131: }
 5132: 
 5133: function display_update() {
 5134:     document.studentform.action.value = 'listusers';
 5135:     document.studentform.phase.value = 'display';
 5136:     document.studentform.submit();
 5137: }
 5138: 
 5139: function updateCols(caller) {
 5140:     var context = '$context';
 5141:     var photos = '$photos';
 5142:     if (caller == 'Status') {
 5143:         if ((context == 'domain') && 
 5144:             ((document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'course') ||
 5145:              (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'community'))) {
 5146:             document.getElementById('showcolstatus').checked = false;
 5147:             document.getElementById('showcolstatus').disabled = 'disabled';
 5148:             document.getElementById('showcolstart').checked = false;
 5149:             document.getElementById('showcolend').checked = false;
 5150:         } else {
 5151:             if (document.studentform.Status.options[document.studentform.Status.selectedIndex].value == 'Any') {
 5152:                 document.getElementById('showcolstatus').checked = true;
 5153:                 document.getElementById('showcolstatus').disabled = '';
 5154:                 document.getElementById('showcolstart').checked = true;
 5155:                 document.getElementById('showcolend').checked = true;
 5156:             } else {
 5157:                 document.getElementById('showcolstatus').checked = false;
 5158:                 document.getElementById('showcolstatus').disabled = 'disabled';
 5159:                 document.getElementById('showcolstart').checked = false;
 5160:                 document.getElementById('showcolend').checked = false;
 5161:             }
 5162:         }
 5163:     }
 5164:     if (caller == 'output') {
 5165:         if (photos == 1) {
 5166:             if (document.getElementById('showcolphoto')) {
 5167:                 var photoitem = document.getElementById('showcolphoto');
 5168:                 if (document.studentform.output.options[document.studentform.output.selectedIndex].value == 'html') {
 5169:                     photoitem.checked = true;
 5170:                     photoitem.disabled = '';
 5171:                 } else {
 5172:                     photoitem.checked = false;
 5173:                     photoitem.disabled = 'disabled';
 5174:                 }
 5175:             }
 5176:         }
 5177:     }
 5178:     if (caller == 'showrole') {
 5179:         if ((document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'Any') ||
 5180:             (document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'cr')) {
 5181:             document.getElementById('showcolrole').checked = true;
 5182:             document.getElementById('showcolrole').disabled = '';
 5183:         } else {
 5184:             document.getElementById('showcolrole').checked = false;
 5185:             document.getElementById('showcolrole').disabled = 'disabled';
 5186:         }
 5187:         if (context == 'domain') {
 5188:             var quotausageshow = 0;
 5189:             if ((document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'course') ||
 5190:                 (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'community')) {
 5191:                 document.getElementById('showcolstatus').checked = false;
 5192:                 document.getElementById('showcolstatus').disabled = 'disabled';
 5193:                 document.getElementById('showcolstart').checked = false;
 5194:                 document.getElementById('showcolend').checked = false;
 5195:             } else {
 5196:                 if (document.studentform.Status.options[document.studentform.Status.selectedIndex].value == 'Any') {
 5197:                     document.getElementById('showcolstatus').checked = true;
 5198:                     document.getElementById('showcolstatus').disabled = '';
 5199:                     document.getElementById('showcolstart').checked = true;
 5200:                     document.getElementById('showcolend').checked = true;
 5201:                 }
 5202:             }
 5203:             if (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'domain') {
 5204:                 document.getElementById('showcolextent').disabled = 'disabled';
 5205:                 document.getElementById('showcolextent').checked = 'false';
 5206:                 document.getElementById('showextent').style.display='none';
 5207:                 document.getElementById('showcoltextextent').innerHTML = '';
 5208:                 if ((document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'au') ||
 5209:                     (document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'Any')) {
 5210:                     if (document.getElementById('showcolauthorusage')) {
 5211:                         document.getElementById('showcolauthorusage').disabled = '';
 5212:                     }
 5213:                     if (document.getElementById('showcolauthorquota')) {
 5214:                         document.getElementById('showcolauthorquota').disabled = '';
 5215:                     }
 5216:                     quotausageshow = 1;
 5217:                 }
 5218:             } else {
 5219:                 document.getElementById('showextent').style.display='block';
 5220:                 document.getElementById('showextent').style.textAlign='left';
 5221:                 document.getElementById('showextent').style.textFace='normal';
 5222:                 if (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'author') {
 5223:                     document.getElementById('showcolextent').disabled = '';
 5224:                     document.getElementById('showcolextent').checked = 'true';
 5225:                     document.getElementById('showcoltextextent').innerHTML="$lt{'author'}";
 5226:                 } else {
 5227:                     document.getElementById('showcolextent').disabled = '';
 5228:                     document.getElementById('showcolextent').checked = 'true';
 5229:                     if (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'community') {
 5230:                         document.getElementById('showcoltextextent').innerHTML="$lt{'community'}";
 5231:                     } else {
 5232:                         document.getElementById('showcoltextextent').innerHTML="$lt{'course'}";
 5233:                     }
 5234:                 }
 5235:             }
 5236:             if (quotausageshow == 0)  {
 5237:                 if (document.getElementById('showcolauthorusage')) {
 5238:                     document.getElementById('showcolauthorusage').checked = false;
 5239:                     document.getElementById('showcolauthorusage').disabled = 'disabled';
 5240:                 }
 5241:                 if (document.getElementById('showcolauthorquota')) {
 5242:                     document.getElementById('showcolauthorquota').checked = false;
 5243:                     document.getElementById('showcolauthorquota').disabled = 'disabled';
 5244:                 }
 5245:             }
 5246:         }
 5247:     }
 5248:     return;
 5249: }
 5250: 
 5251: END
 5252:     return $output;
 5253: 
 5254: }
 5255: 
 5256: ###############################################################
 5257: ###############################################################
 5258: #  Menu Phase One
 5259: sub print_main_menu {
 5260:     my ($permission,$context,$crstype) = @_;
 5261:     my $linkcontext = $context;
 5262:     my $stuterm = lc(&Apache::lonnet::plaintext('st',$crstype));
 5263:     if (($context eq 'course') && ($crstype eq 'Community')) {
 5264:         $linkcontext = lc($crstype);
 5265:         $stuterm = 'Members';
 5266:     }
 5267:     my %links = (
 5268:                 domain => {
 5269:                             upload     => 'Upload a File of Users',
 5270:                             singleuser => 'Add/Modify a User',
 5271:                             listusers  => 'Manage Users',
 5272:                             },
 5273:                 author => {
 5274:                             upload     => 'Upload a File of Co-authors',
 5275:                             singleuser => 'Add/Modify a Co-author',
 5276:                             listusers  => 'Manage Co-authors',
 5277:                             },
 5278:                 course => {
 5279:                             upload     => 'Upload a File of Course Users',
 5280:                             singleuser => 'Add/Modify a Course User',
 5281:                             listusers  => 'List and Modify Multiple Course Users',
 5282:                             },
 5283:                 community => {
 5284:                             upload     => 'Upload a File of Community Users',
 5285:                             singleuser => 'Add/Modify a Community User',
 5286:                             listusers  => 'List and Modify Multiple Community Users',
 5287:                            },
 5288:                 );
 5289:      my %linktitles = (
 5290:                 domain => {
 5291:                             singleuser => 'Add a user to the domain, and/or a course or community in the domain.',
 5292:                             listusers  => 'Show and manage users in this domain.',
 5293:                             },
 5294:                 author => {
 5295:                             singleuser => 'Add a user with a co- or assistant author role.',
 5296:                             listusers  => 'Show and manage co- or assistant authors.',
 5297:                             },
 5298:                 course => {
 5299:                             singleuser => 'Add a user with a certain role to this course.',
 5300:                             listusers  => 'Show and manage users in this course.',
 5301:                             },
 5302:                 community => {
 5303:                             singleuser => 'Add a user with a certain role to this community.',
 5304:                             listusers  => 'Show and manage users in this community.',
 5305:                            },
 5306:                 );
 5307:   if ($linkcontext eq 'domain') {
 5308:       unless ($permission->{'cusr'}) {
 5309:           $links{'domain'}{'singleuser'} = 'View a User'; 
 5310:           $linktitles{'domain'}{'singleuser'} = 'View information about a user in the domain';
 5311:           
 5312:       }
 5313:   } elsif ($linkcontext eq 'course') {
 5314:       unless ($permission->{'cusr'}) {
 5315:           $links{'course'}{'singleuser'} = 'View a Course User';
 5316:           $linktitles{'course'}{'singleuser'} = 'View information about a user in this course';
 5317:           $links{'course'}{'listusers'} = 'List Course Users';
 5318:           $linktitles{'course'}{'listusers'} = 'Show information about users in this course';
 5319:       }
 5320:   } elsif ($linkcontext eq 'community') {
 5321:       unless ($permission->{'cusr'}) {
 5322:           $links{'community'}{'singleuser'} = 'View a Community User';
 5323:           $linktitles{'community'}{'singleuser'} = 'View information about a user in this community';
 5324:           $links{'community'}{'listusers'} = 'List Community Users';
 5325:           $linktitles{'community'}{'listusers'} = 'Show information about users in this community';
 5326:       }
 5327:   }
 5328:   my @menu = ( {categorytitle => 'Single Users', 
 5329:          items =>
 5330:          [
 5331:             {
 5332:              linktext => $links{$linkcontext}{'singleuser'},
 5333:              icon => 'edit-redo.png',
 5334:              #help => 'Course_Change_Privileges',
 5335:              url => '/adm/createuser?action=singleuser',
 5336:              permission => ($permission->{'view'} || $permission->{'cusr'}),
 5337:              linktitle => $linktitles{$linkcontext}{'singleuser'},
 5338:             },
 5339:          ]},
 5340: 
 5341:          {categorytitle => 'Multiple Users',
 5342:          items => 
 5343:          [
 5344:             {
 5345:              linktext => $links{$linkcontext}{'upload'},
 5346:              icon => 'uplusr.png',
 5347:              #help => 'Course_Create_Class_List',
 5348:              url => '/adm/createuser?action=upload',
 5349:              permission => $permission->{'cusr'},
 5350:              linktitle => 'Upload a CSV or a text file containing users.',
 5351:             },
 5352:             {
 5353:              linktext => $links{$linkcontext}{'listusers'},
 5354:              icon => 'mngcu.png',
 5355:              #help => 'Course_View_Class_List',
 5356:              url => '/adm/createuser?action=listusers',
 5357:              permission => ($permission->{'view'} || $permission->{'cusr'}),
 5358:              linktitle => $linktitles{$linkcontext}{'listusers'}, 
 5359:             },
 5360: 
 5361:          ]},
 5362: 
 5363:          {categorytitle => 'Administration',
 5364:          items => [ ]},
 5365:        );
 5366: 
 5367:     if ($context eq 'domain'){
 5368:         push(@{  $menu[0]->{items} }, # Single Users
 5369:             {
 5370:              linktext => 'User Access Log',
 5371:              icon => 'document-properties.png',
 5372:              #help => 'Domain_User_Access_Logs',
 5373:              url => '/adm/createuser?action=accesslogs',
 5374:              permission => $permission->{'activity'},
 5375:              linktitle => 'View user access log.',
 5376:             }
 5377:         );
 5378:         
 5379:         push(@{ $menu[2]->{items} }, #Category: Administration
 5380:             {
 5381:              linktext => 'Custom Roles',
 5382:              icon => 'emblem-photos.png',
 5383:              #help => 'Course_Editing_Custom_Roles',
 5384:              url => '/adm/createuser?action=custom',
 5385:              permission => $permission->{'custom'},
 5386:              linktitle => 'Configure a custom role.',
 5387:             },
 5388:             {
 5389:              linktext => 'Authoring Space Requests',
 5390:              icon => 'selfenrl-queue.png',
 5391:              #help => 'Domain_Role_Approvals',
 5392:              url => '/adm/createuser?action=processauthorreq',
 5393:              permission => $permission->{'cusr'},
 5394:              linktitle => 'Approve or reject author role requests',
 5395:             },
 5396:             {
 5397:              linktext => 'LON-CAPA Account Requests',
 5398:              icon => 'list-add.png',
 5399:              #help => 'Domain_Username_Approvals',
 5400:              url => '/adm/createuser?action=processusernamereq',
 5401:              permission => $permission->{'cusr'},
 5402:              linktitle => 'Approve or reject LON-CAPA account requests',
 5403:             },
 5404:             {
 5405:              linktext => 'Change Log',
 5406:              icon => 'document-properties.png',
 5407:              #help => 'Course_User_Logs',
 5408:              url => '/adm/createuser?action=changelogs',
 5409:              permission => ($permission->{'cusr'} || $permission->{'view'}),
 5410:              linktitle => 'View change log.',
 5411:             },
 5412:         );
 5413:         
 5414:     }elsif ($context eq 'course'){
 5415:         my ($cnum,$cdom) = &Apache::lonuserutils::get_course_identity();
 5416: 
 5417:         my %linktext = (
 5418:                          'Course'    => {
 5419:                                           single => 'Add/Modify a Student', 
 5420:                                           drop   => 'Drop Students',
 5421:                                           groups => 'Course Groups',
 5422:                                         },
 5423:                          'Community' => {
 5424:                                           single => 'Add/Modify a Member', 
 5425:                                           drop   => 'Drop Members',
 5426:                                           groups => 'Community Groups',
 5427:                                         },
 5428:                        );
 5429:         $linktext{'Placement'} = $linktext{'Course'};
 5430: 
 5431:         my %linktitle = (
 5432:             'Course' => {
 5433:                   single => 'Add a user with the role of student to this course',
 5434:                   drop   => 'Remove a student from this course.',
 5435:                   groups => 'Manage course groups',
 5436:                         },
 5437:             'Community' => {
 5438:                   single => 'Add a user with the role of member to this community',
 5439:                   drop   => 'Remove a member from this community.',
 5440:                   groups => 'Manage community groups',
 5441:                            },
 5442:         );
 5443: 
 5444:         $linktitle{'Placement'} = $linktitle{'Course'};
 5445: 
 5446:         push(@{ $menu[0]->{items} }, #Category: Single Users
 5447:             {   
 5448:              linktext => $linktext{$crstype}{'single'},
 5449:              #help => 'Course_Add_Student',
 5450:              icon => 'list-add.png',
 5451:              url => '/adm/createuser?action=singlestudent',
 5452:              permission => $permission->{'cusr'},
 5453:              linktitle => $linktitle{$crstype}{'single'},
 5454:             },
 5455:         );
 5456:         
 5457:         push(@{ $menu[1]->{items} }, #Category: Multiple Users 
 5458:             {
 5459:              linktext => $linktext{$crstype}{'drop'},
 5460:              icon => 'edit-undo.png',
 5461:              #help => 'Course_Drop_Student',
 5462:              url => '/adm/createuser?action=drop',
 5463:              permission => $permission->{'cusr'},
 5464:              linktitle => $linktitle{$crstype}{'drop'},
 5465:             },
 5466:         );
 5467:         push(@{ $menu[2]->{items} }, #Category: Administration
 5468:             {
 5469:              linktext => 'Helpdesk Access',
 5470:              icon => 'helpdesk-access.png',
 5471:              #help => 'Course_Helpdesk_Access',
 5472:              url => '/adm/createuser?action=helpdesk',
 5473:              permission => ($permission->{'owner'} || $permission->{'co-owner'}),
 5474:              linktitle => 'Helpdesk access options',
 5475:             },
 5476:             {
 5477:              linktext => 'Custom Roles',
 5478:              icon => 'emblem-photos.png',
 5479:              #help => 'Course_Editing_Custom_Roles',
 5480:              url => '/adm/createuser?action=custom',
 5481:              permission => $permission->{'custom'},
 5482:              linktitle => 'Configure a custom role.',
 5483:             },
 5484:             {
 5485:              linktext => $linktext{$crstype}{'groups'},
 5486:              icon => 'grps.png',
 5487:              #help => 'Course_Manage_Group',
 5488:              url => '/adm/coursegroups?refpage=cusr',
 5489:              permission => $permission->{'grp_manage'},
 5490:              linktitle => $linktitle{$crstype}{'groups'},
 5491:             },
 5492:             {
 5493:              linktext => 'Change Log',
 5494:              icon => 'document-properties.png',
 5495:              #help => 'Course_User_Logs',
 5496:              url => '/adm/createuser?action=changelogs',
 5497:              permission => ($permission->{'view'} || $permission->{'cusr'}),
 5498:              linktitle => 'View change log.',
 5499:             },
 5500:         );
 5501:         if ($env{'course.'.$env{'request.course.id'}.'.internal.selfenroll_approval'}) {
 5502:             push(@{ $menu[2]->{items} },
 5503:                     {
 5504:                      linktext => 'Enrollment Requests',
 5505:                      icon => 'selfenrl-queue.png',
 5506:                      #help => 'Course_Approve_Selfenroll',
 5507:                      url => '/adm/createuser?action=selfenrollqueue',
 5508:                      permission => $permission->{'selfenrolladmin'},
 5509:                      linktitle =>'Approve or reject enrollment requests.',
 5510:                     },
 5511:             );
 5512:         }
 5513:         
 5514:         if (!exists($permission->{'cusr_section'})){
 5515:             if ($crstype ne 'Community') {
 5516:                 push(@{ $menu[2]->{items} },
 5517:                     {
 5518:                      linktext => 'Automated Enrollment',
 5519:                      icon => 'roles.png',
 5520:                      #help => 'Course_Automated_Enrollment',
 5521:                      permission => (&Apache::lonnet::auto_run($cnum,$cdom)
 5522:                                          && (($permission->{'cusr'}) ||
 5523:                                              ($permission->{'view'}))),
 5524:                      url  => '/adm/populate',
 5525:                      linktitle => 'Automated enrollment manager.',
 5526:                     }
 5527:                 );
 5528:             }
 5529:             push(@{ $menu[2]->{items} }, 
 5530:                 {
 5531:                  linktext => 'User Self-Enrollment',
 5532:                  icon => 'self_enroll.png',
 5533:                  #help => 'Course_Self_Enrollment',
 5534:                  url => '/adm/createuser?action=selfenroll',
 5535:                  permission => $permission->{'selfenrolladmin'},
 5536:                  linktitle => 'Configure user self-enrollment.',
 5537:                 },
 5538:             );
 5539:         }
 5540:     } elsif ($context eq 'author') {
 5541:         push(@{ $menu[2]->{items} }, #Category: Administration
 5542:             {
 5543:              linktext => 'Change Log',
 5544:              icon => 'document-properties.png',
 5545:              #help => 'Course_User_Logs',
 5546:              url => '/adm/createuser?action=changelogs',
 5547:              permission => $permission->{'cusr'},
 5548:              linktitle => 'View change log.',
 5549:             },
 5550:         );
 5551:     }
 5552:     return Apache::lonhtmlcommon::generate_menu(@menu);
 5553: #               { text => 'View Log-in History',
 5554: #                 help => 'Course_User_Logins',
 5555: #                 action => 'logins',
 5556: #                 permission => $permission->{'cusr'},
 5557: #               });
 5558: }
 5559: 
 5560: sub restore_prev_selections {
 5561:     my %saveable_parameters = ('srchby'   => 'scalar',
 5562: 			       'srchin'   => 'scalar',
 5563: 			       'srchtype' => 'scalar',
 5564: 			       );
 5565:     &Apache::loncommon::store_settings('user','user_picker',
 5566: 				       \%saveable_parameters);
 5567:     &Apache::loncommon::restore_settings('user','user_picker',
 5568: 					 \%saveable_parameters);
 5569: }
 5570: 
 5571: sub print_selfenroll_menu {
 5572:     my ($r,$context,$cid,$cdom,$cnum,$currsettings,$additional,$readonly) = @_;
 5573:     my $crstype = &Apache::loncommon::course_type();
 5574:     my $formname = 'selfenroll';
 5575:     my $nolink = 1;
 5576:     my ($row,$lt) = &Apache::lonuserutils::get_selfenroll_titles();
 5577:     my $groupslist = &Apache::lonuserutils::get_groupslist();
 5578:     my $setsec_js = 
 5579:         &Apache::lonuserutils::setsections_javascript($formname,$groupslist);
 5580:     my %alerts = &Apache::lonlocal::texthash(
 5581:         acto => 'Activation of self-enrollment was selected for the following domain(s)',
 5582:         butn => 'but no user types have been checked.',
 5583:         wilf => "Please uncheck 'activate' or check at least one type.",
 5584:     );
 5585:     my $disabled;
 5586:     if ($readonly) {
 5587:        $disabled = ' disabled="disabled"';
 5588:     }
 5589:     &js_escape(\%alerts);
 5590:     my $selfenroll_js = <<"ENDSCRIPT";
 5591: function update_types(caller,num) {
 5592:     var delidx = getIndexByName('selfenroll_delete');
 5593:     var actidx = getIndexByName('selfenroll_activate');
 5594:     if (caller == 'selfenroll_all') {
 5595:         var selall;
 5596:         for (var i=0; i<document.$formname.selfenroll_all.length; i++) {
 5597:             if (document.$formname.selfenroll_all[i].checked) {
 5598:                 selall = document.$formname.selfenroll_all[i].value;
 5599:             }
 5600:         }
 5601:         if (selall == 1) {
 5602:             if (delidx != -1) {
 5603:                 if (document.$formname.selfenroll_delete.length) {
 5604:                     for (var j=0; j<document.$formname.selfenroll_delete.length; j++) {
 5605:                         document.$formname.selfenroll_delete[j].checked = true;
 5606:                     }
 5607:                 } else {
 5608:                     document.$formname.elements[delidx].checked = true;
 5609:                 }
 5610:             }
 5611:             if (actidx != -1) {
 5612:                 if (document.$formname.selfenroll_activate.length) {
 5613:                     for (var j=0; j<document.$formname.selfenroll_activate.length; j++) {
 5614:                         document.$formname.selfenroll_activate[j].checked = false;
 5615:                     }
 5616:                 } else {
 5617:                     document.$formname.elements[actidx].checked = false;
 5618:                 }
 5619:             }
 5620:             document.$formname.selfenroll_newdom.selectedIndex = 0; 
 5621:         }
 5622:     }
 5623:     if (caller == 'selfenroll_activate') {
 5624:         if (document.$formname.selfenroll_activate.length) {
 5625:             for (var j=0; j<document.$formname.selfenroll_activate.length; j++) {
 5626:                 if (document.$formname.selfenroll_activate[j].value == num) {
 5627:                     if (document.$formname.selfenroll_activate[j].checked) {
 5628:                         for (var i=0; i<document.$formname.selfenroll_all.length; i++) {
 5629:                             if (document.$formname.selfenroll_all[i].value == '1') {
 5630:                                 document.$formname.selfenroll_all[i].checked = false;
 5631:                             }
 5632:                             if (document.$formname.selfenroll_all[i].value == '0') {
 5633:                                 document.$formname.selfenroll_all[i].checked = true;
 5634:                             }
 5635:                         }
 5636:                     }
 5637:                 }
 5638:             }
 5639:         } else {
 5640:             for (var i=0; i<document.$formname.selfenroll_all.length; i++) {
 5641:                 if (document.$formname.selfenroll_all[i].value == '1') {
 5642:                     document.$formname.selfenroll_all[i].checked = false;
 5643:                 }
 5644:                 if (document.$formname.selfenroll_all[i].value == '0') {
 5645:                     document.$formname.selfenroll_all[i].checked = true;
 5646:                 }
 5647:             }
 5648:         }
 5649:     }
 5650:     if (caller == 'selfenroll_delete') {
 5651:         if (document.$formname.selfenroll_delete.length) {
 5652:             for (var j=0; j<document.$formname.selfenroll_delete.length; j++) {
 5653:                 if (document.$formname.selfenroll_delete[j].value == num) {
 5654:                     if (document.$formname.selfenroll_delete[j].checked) {
 5655:                         var delindex = getIndexByName('selfenroll_types_'+num);
 5656:                         if (delindex != -1) { 
 5657:                             if (document.$formname.elements[delindex].length) {
 5658:                                 for (var k=0; k<document.$formname.elements[delindex].length; k++) {
 5659:                                     document.$formname.elements[delindex][k].checked = false;
 5660:                                 }
 5661:                             } else {
 5662:                                 document.$formname.elements[delindex].checked = false;
 5663:                             }
 5664:                         }
 5665:                     }
 5666:                 }
 5667:             }
 5668:         } else {
 5669:             if (document.$formname.selfenroll_delete.checked) {
 5670:                 var delindex = getIndexByName('selfenroll_types_'+num);
 5671:                 if (delindex != -1) {
 5672:                     if (document.$formname.elements[delindex].length) {
 5673:                         for (var k=0; k<document.$formname.elements[delindex].length; k++) {
 5674:                             document.$formname.elements[delindex][k].checked = false;
 5675:                         }
 5676:                     } else {
 5677:                         document.$formname.elements[delindex].checked = false;
 5678:                     }
 5679:                 }
 5680:             }
 5681:         }
 5682:     }
 5683:     return;
 5684: }
 5685: 
 5686: function validate_types(form) {
 5687:     var needaction = new Array();
 5688:     var countfail = 0;
 5689:     var actidx = getIndexByName('selfenroll_activate');
 5690:     if (actidx != -1) {
 5691:         if (document.$formname.selfenroll_activate.length) {
 5692:             for (var j=0; j<document.$formname.selfenroll_activate.length; j++) {
 5693:                 var num = document.$formname.selfenroll_activate[j].value;
 5694:                 if (document.$formname.selfenroll_activate[j].checked) {
 5695:                     countfail = check_types(num,countfail,needaction)
 5696:                 }
 5697:             }
 5698:         } else {
 5699:             if (document.$formname.selfenroll_activate.checked) {
 5700:                 var num = document.$formname.selfenroll_activate.value;
 5701:                 countfail = check_types(num,countfail,needaction)
 5702:             }
 5703:         }
 5704:     }
 5705:     if (countfail > 0) {
 5706:         var msg = "$alerts{'acto'}\\n";
 5707:         var loopend = needaction.length -1;
 5708:         if (loopend > 0) {
 5709:             for (var m=0; m<loopend; m++) {
 5710:                 msg += needaction[m]+", ";
 5711:             }
 5712:         }
 5713:         msg += needaction[loopend]+"\\n$alerts{'butn'}\\n$alerts{'wilf'}";
 5714:         alert(msg);
 5715:         return; 
 5716:     }
 5717:     setSections(form);
 5718: }
 5719: 
 5720: function check_types(num,countfail,needaction) {
 5721:     var typeidx = getIndexByName('selfenroll_types_'+num);
 5722:     var count = 0;
 5723:     if (typeidx != -1) {
 5724:         if (document.$formname.elements[typeidx].length) {
 5725:             for (var k=0; k<document.$formname.elements[typeidx].length; k++) {
 5726:                 if (document.$formname.elements[typeidx][k].checked) {
 5727:                     count ++;
 5728:                 }
 5729:             }
 5730:         } else {
 5731:             if (document.$formname.elements[typeidx].checked) {
 5732:                 count ++;
 5733:             }
 5734:         }
 5735:         if (count == 0) {
 5736:             var domidx = getIndexByName('selfenroll_dom_'+num);
 5737:             if (domidx != -1) {
 5738:                 var domname = document.$formname.elements[domidx].value;
 5739:                 needaction[countfail] = domname;
 5740:                 countfail ++;
 5741:             }
 5742:         }
 5743:     }
 5744:     return countfail;
 5745: }
 5746: 
 5747: function toggleNotify() {
 5748:     var selfenrollApproval = 0;
 5749:     if (document.$formname.selfenroll_approval.length) {
 5750:         for (var i=0; i<document.$formname.selfenroll_approval.length; i++) {
 5751:             if (document.$formname.selfenroll_approval[i].checked) {
 5752:                 selfenrollApproval = document.$formname.selfenroll_approval[i].value;
 5753:                 break;        
 5754:             }
 5755:         }
 5756:     }
 5757:     if (document.getElementById('notified')) {
 5758:         if (selfenrollApproval == 0) {
 5759:             document.getElementById('notified').style.display='none';
 5760:         } else {
 5761:             document.getElementById('notified').style.display='block';
 5762:         }
 5763:     }
 5764:     return;
 5765: }
 5766: 
 5767: function getIndexByName(item) {
 5768:     for (var i=0;i<document.$formname.elements.length;i++) {
 5769:         if (document.$formname.elements[i].name == item) {
 5770:             return i;
 5771:         }
 5772:     }
 5773:     return -1;
 5774: }
 5775: ENDSCRIPT
 5776: 
 5777:     my $output = '<script type="text/javascript">'."\n".
 5778:                  '// <![CDATA['."\n".
 5779:                  $setsec_js."\n".$selfenroll_js."\n".
 5780:                  '// ]]>'."\n".
 5781:                  '</script>'."\n".
 5782:                  '<h3>'.$lt->{'selfenroll'}.'</h3>'."\n";
 5783:  
 5784:     my $visactions = &cat_visibility();
 5785:     my ($cathash,%cattype);
 5786:     my %domconfig = &Apache::lonnet::get_dom('configuration',['coursecategories'],$cdom);
 5787:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 5788:         $cathash = $domconfig{'coursecategories'}{'cats'};
 5789:         $cattype{'auth'} = $domconfig{'coursecategories'}{'auth'};
 5790:         $cattype{'unauth'} = $domconfig{'coursecategories'}{'unauth'};
 5791:         if ($cattype{'auth'} eq '') {
 5792:             $cattype{'auth'} = 'std';
 5793:         }
 5794:         if ($cattype{'unauth'} eq '') {
 5795:             $cattype{'unauth'} = 'std';
 5796:         }
 5797:     } else {
 5798:         $cathash = {};
 5799:         $cattype{'auth'} = 'std';
 5800:         $cattype{'unauth'} = 'std';
 5801:     }
 5802:     if (($cattype{'auth'} eq 'none') && ($cattype{'unauth'} eq 'none')) {
 5803:         $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
 5804:                   '<br />'.
 5805:                   '<br />'.$visactions->{'take'}.'<ul>'.
 5806:                   '<li>'.$visactions->{'dc_chgconf'}.'</li>'.
 5807:                   '</ul>');
 5808:     } elsif (($cattype{'auth'} !~ /^(std|domonly)$/) && ($cattype{'unauth'} !~ /^(std|domonly)$/)) {
 5809:         if ($currsettings->{'uniquecode'}) {
 5810:             $r->print('<span class="LC_info">'.$visactions->{'vis'}.'</span>');
 5811:         } else {
 5812:             $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
 5813:                   '<br />'.
 5814:                   '<br />'.$visactions->{'take'}.'<ul>'.
 5815:                   '<li>'.$visactions->{'dc_setcode'}.'</li>'.
 5816:                   '</ul><br />');
 5817:         }
 5818:     } else {
 5819:         my ($visible,$cansetvis,$vismsgs) = &visible_in_stdcat($cdom,$cnum,\%domconfig);
 5820:         if (ref($visactions) eq 'HASH') {
 5821:             if ($visible) {
 5822:                 $output .= '<p class="LC_info">'.$visactions->{'vis'}.'</p>';
 5823:            } else {
 5824:                 $output .= '<p class="LC_warning">'.$visactions->{'miss'}.'</p>'
 5825:                           .$visactions->{'yous'}.
 5826:                            '<p>'.$visactions->{'gen'}.'<br />'.$visactions->{'coca'};
 5827:                 if (ref($vismsgs) eq 'ARRAY') {
 5828:                     $output .= '<br />'.$visactions->{'make'}.'<ul>';
 5829:                     foreach my $item (@{$vismsgs}) {
 5830:                         $output .= '<li>'.$visactions->{$item}.'</li>';
 5831:                     }
 5832:                     $output .= '</ul>';
 5833:                 }
 5834:                 $output .= '</p>';
 5835:             }
 5836:         }
 5837:     }
 5838:     my $actionhref = '/adm/createuser';
 5839:     if ($context eq 'domain') {
 5840:         $actionhref = '/adm/modifycourse';
 5841:     }
 5842: 
 5843:     my %noedit;
 5844:     unless ($context eq 'domain') {
 5845:         %noedit = &get_noedit_fields($cdom,$cnum,$crstype,$row);
 5846:     }
 5847:     $output .= '<form name="'.$formname.'" method="post" action="'.$actionhref.'">'."\n".
 5848:                &Apache::lonhtmlcommon::start_pick_box();
 5849:     if (ref($row) eq 'ARRAY') {
 5850:         foreach my $item (@{$row}) {
 5851:             my $title = $item; 
 5852:             if (ref($lt) eq 'HASH') {
 5853:                 $title = $lt->{$item};
 5854:             }
 5855:             $output .= &Apache::lonhtmlcommon::row_title($title);
 5856:             if ($item eq 'types') {
 5857:                 my $curr_types;
 5858:                 if (ref($currsettings) eq 'HASH') {
 5859:                     $curr_types = $currsettings->{'selfenroll_types'};
 5860:                 }
 5861:                 if ($noedit{$item}) {
 5862:                     if ($curr_types eq '*') {
 5863:                         $output .= &mt('Any user in any domain');   
 5864:                     } else {
 5865:                         my @entries = split(/;/,$curr_types);
 5866:                         if (@entries > 0) {
 5867:                             $output .= '<ul>'; 
 5868:                             foreach my $entry (@entries) {
 5869:                                 my ($currdom,$typestr) = split(/:/,$entry);
 5870:                                 next if ($typestr eq '');
 5871:                                 my $domdesc = &Apache::lonnet::domain($currdom);
 5872:                                 my @currinsttypes = split(',',$typestr);
 5873:                                 my ($othertitle,$usertypes,$types) = 
 5874:                                     &Apache::loncommon::sorted_inst_types($currdom);
 5875:                                 if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 5876:                                     $usertypes->{'any'} = &mt('any user'); 
 5877:                                     if (keys(%{$usertypes}) > 0) {
 5878:                                         $usertypes->{'other'} = &mt('other users');
 5879:                                     }
 5880:                                     my @longinsttypes = map { $usertypes->{$_}; } @currinsttypes;
 5881:                                     $output .= '<li>'.$domdesc.':'.join(', ',@longinsttypes).'</li>';
 5882:                                  }
 5883:                             }
 5884:                             $output .= '</ul>';
 5885:                         } else {
 5886:                             $output .= &mt('None');
 5887:                         }
 5888:                     }
 5889:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 5890:                     next;
 5891:                 }
 5892:                 my $showdomdesc = 1;
 5893:                 my $includeempty = 1;
 5894:                 my $num = 0;
 5895:                 $output .= &Apache::loncommon::start_data_table().
 5896:                            &Apache::loncommon::start_data_table_row()
 5897:                            .'<td colspan="2"><span class="LC_nobreak"><label>'
 5898:                            .&mt('Any user in any domain:')
 5899:                            .'&nbsp;<input type="radio" name="selfenroll_all" value="1" ';
 5900:                 if ($curr_types eq '*') {
 5901:                     $output .= ' checked="checked" '; 
 5902:                 }
 5903:                 $output .= 'onchange="javascript:update_types('.
 5904:                            "'selfenroll_all'".');"'.$disabled.' />'.&mt('Yes').'</label>'.
 5905:                            '&nbsp;&nbsp;<input type="radio" name="selfenroll_all" value="0" ';
 5906:                 if ($curr_types ne '*') {
 5907:                     $output .= ' checked="checked" ';
 5908:                 }
 5909:                 $output .= ' onchange="javascript:update_types('.
 5910:                            "'selfenroll_all'".');"'.$disabled.' />'.&mt('No').'</label></td>'.
 5911:                            &Apache::loncommon::end_data_table_row().
 5912:                            &Apache::loncommon::end_data_table().
 5913:                            &mt('Or').'<br />'.
 5914:                            &Apache::loncommon::start_data_table();
 5915:                 my %currdoms;
 5916:                 if ($curr_types eq '') {
 5917:                     $output .= &new_selfenroll_dom_row($cdom,'0');
 5918:                 } elsif ($curr_types ne '*') {
 5919:                     my @entries = split(/;/,$curr_types);
 5920:                     if (@entries > 0) {
 5921:                         foreach my $entry (@entries) {
 5922:                             my ($currdom,$typestr) = split(/:/,$entry);
 5923:                             $currdoms{$currdom} = 1;
 5924:                             my $domdesc = &Apache::lonnet::domain($currdom);
 5925:                             my @currinsttypes = split(',',$typestr);
 5926:                             $output .= &Apache::loncommon::start_data_table_row()
 5927:                                        .'<td valign="top"><span class="LC_nobreak">'.&mt('Domain:').'<b>'
 5928:                                        .'&nbsp;'.$domdesc.' ('.$currdom.')'
 5929:                                        .'</b><input type="hidden" name="selfenroll_dom_'.$num
 5930:                                        .'" value="'.$currdom.'" /></span><br />'
 5931:                                        .'<span class="LC_nobreak"><label><input type="checkbox" '
 5932:                                        .'name="selfenroll_delete" value="'.$num.'" onchange="javascript:update_types('."'selfenroll_delete','$num'".');"'.$disabled.' />'
 5933:                                        .&mt('Delete').'</label></span></td>';
 5934:                             $output .= '<td valign="top">&nbsp;&nbsp;'.&mt('User types:').'<br />'
 5935:                                        .&selfenroll_inst_types($num,$currdom,\@currinsttypes,$readonly).'</td>'
 5936:                                        .&Apache::loncommon::end_data_table_row();
 5937:                             $num ++;
 5938:                         }
 5939:                     }
 5940:                 }
 5941:                 my $add_domtitle = &mt('Users in additional domain:');
 5942:                 if ($curr_types eq '*') { 
 5943:                     $add_domtitle = &mt('Users in specific domain:');
 5944:                 } elsif ($curr_types eq '') {
 5945:                     $add_domtitle = &mt('Users in other domain:');
 5946:                 }
 5947:                 $output .= &Apache::loncommon::start_data_table_row()
 5948:                            .'<td colspan="2"><span class="LC_nobreak">'.$add_domtitle.'</span><br />'
 5949:                            .&Apache::loncommon::select_dom_form('','selfenroll_newdom',
 5950:                                                                 $includeempty,$showdomdesc,'','','',$readonly)
 5951:                            .'<input type="hidden" name="selfenroll_types_total" value="'.$num.'" />'
 5952:                            .'</td>'.&Apache::loncommon::end_data_table_row()
 5953:                            .&Apache::loncommon::end_data_table();
 5954:             } elsif ($item eq 'registered') {
 5955:                 my ($regon,$regoff);
 5956:                 my $registered;
 5957:                 if (ref($currsettings) eq 'HASH') {
 5958:                     $registered = $currsettings->{'selfenroll_registered'};
 5959:                 }
 5960:                 if ($noedit{$item}) {
 5961:                     if ($registered) {
 5962:                         $output .= &mt('Must be registered in course');
 5963:                     } else {
 5964:                         $output .= &mt('No requirement');
 5965:                     }
 5966:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 5967:                     next;
 5968:                 }
 5969:                 if ($registered) {
 5970:                     $regon = ' checked="checked" ';
 5971:                     $regoff = '';
 5972:                 } else {
 5973:                     $regon = '';
 5974:                     $regoff = ' checked="checked" ';
 5975:                 }
 5976:                 $output .= '<label>'.
 5977:                            '<input type="radio" name="selfenroll_registered" value="1"'.$regon.$disabled.' />'.
 5978:                            &mt('Yes').'</label>&nbsp;&nbsp;<label>'.
 5979:                            '<input type="radio" name="selfenroll_registered" value="0"'.$regoff.$disabled.' />'.
 5980:                            &mt('No').'</label>';
 5981:             } elsif ($item eq 'enroll_dates') {
 5982:                 my ($starttime,$endtime);
 5983:                 if (ref($currsettings) eq 'HASH') {
 5984:                     $starttime = $currsettings->{'selfenroll_start_date'};
 5985:                     $endtime = $currsettings->{'selfenroll_end_date'};
 5986:                     if ($starttime eq '') {
 5987:                         $starttime = $currsettings->{'default_enrollment_start_date'};
 5988:                     }
 5989:                     if ($endtime eq '') {
 5990:                         $endtime = $currsettings->{'default_enrollment_end_date'};
 5991:                     }
 5992:                 }
 5993:                 if ($noedit{$item}) {
 5994:                     $output .= &mt('From: [_1], to: [_2]',&Apache::lonlocal::locallocaltime($starttime),
 5995:                                                           &Apache::lonlocal::locallocaltime($endtime));
 5996:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 5997:                     next;
 5998:                 }
 5999:                 my $startform =
 6000:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_start_date',$starttime,
 6001:                                       $disabled,undef,undef,undef,undef,undef,undef,$nolink);
 6002:                 my $endform =
 6003:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_end_date',$endtime,
 6004:                                       $disabled,undef,undef,undef,undef,undef,undef,$nolink);
 6005:                 $output .= &selfenroll_date_forms($startform,$endform);
 6006:             } elsif ($item eq 'access_dates') {
 6007:                 my ($starttime,$endtime);
 6008:                 if (ref($currsettings) eq 'HASH') {
 6009:                     $starttime = $currsettings->{'selfenroll_start_access'};
 6010:                     $endtime = $currsettings->{'selfenroll_end_access'};
 6011:                     if ($starttime eq '') {
 6012:                         $starttime = $currsettings->{'default_enrollment_start_date'};
 6013:                     }
 6014:                     if ($endtime eq '') {
 6015:                         $endtime = $currsettings->{'default_enrollment_end_date'};
 6016:                     }
 6017:                 }
 6018:                 if ($noedit{$item}) {
 6019:                     $output .= &mt('From: [_1], to: [_2]',&Apache::lonlocal::locallocaltime($starttime),
 6020:                                                           &Apache::lonlocal::locallocaltime($endtime));
 6021:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 6022:                     next;
 6023:                 }
 6024:                 my $startform =
 6025:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_start_access',$starttime,
 6026:                                       $disabled,undef,undef,undef,undef,undef,undef,$nolink);
 6027:                 my $endform =
 6028:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_end_access',$endtime,
 6029:                                       $disabled,undef,undef,undef,undef,undef,undef,$nolink);
 6030:                 $output .= &selfenroll_date_forms($startform,$endform);
 6031:             } elsif ($item eq 'section') {
 6032:                 my $currsec;
 6033:                 if (ref($currsettings) eq 'HASH') {
 6034:                     $currsec = $currsettings->{'selfenroll_section'};
 6035:                 }
 6036:                 my %sections_count = &Apache::loncommon::get_sections($cdom,$cnum);
 6037:                 my $newsecval;
 6038:                 if ($currsec ne 'none' && $currsec ne '') {
 6039:                     if (!defined($sections_count{$currsec})) {
 6040:                         $newsecval = $currsec;
 6041:                     }
 6042:                 }
 6043:                 if ($noedit{$item}) {
 6044:                     if ($currsec ne '') {
 6045:                         $output .= $currsec;
 6046:                     } else {
 6047:                         $output .= &mt('No specific section');
 6048:                     }
 6049:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 6050:                     next;
 6051:                 }
 6052:                 my $sections_select = 
 6053:                     &Apache::lonuserutils::course_sections(\%sections_count,'st',$currsec,$disabled);
 6054:                 $output .= '<table class="LC_createuser">'."\n".
 6055:                            '<tr class="LC_section_row">'."\n".
 6056:                            '<td align="center">'.&mt('Existing sections')."\n".
 6057:                            '<br />'.$sections_select.'</td><td align="center">'.
 6058:                            &mt('New section').'<br />'."\n".
 6059:                            '<input type="text" name="newsec" size="15" value="'.$newsecval.'"'.$disabled.' />'."\n".
 6060:                            '<input type="hidden" name="sections" value="" />'."\n".
 6061:                            '</td></tr></table>'."\n";
 6062:             } elsif ($item eq 'approval') {
 6063:                 my ($currnotified,$currapproval,%appchecked);
 6064:                 my %selfdescs = &Apache::lonuserutils::selfenroll_default_descs();
 6065:                 if (ref($currsettings) eq 'HASH') { 
 6066:                     $currnotified = $currsettings->{'selfenroll_notifylist'};
 6067:                     $currapproval = $currsettings->{'selfenroll_approval'};
 6068:                 }
 6069:                 if ($currapproval !~ /^[012]$/) {
 6070:                     $currapproval = 0;
 6071:                 }
 6072:                 if ($noedit{$item}) {
 6073:                     $output .=  $selfdescs{'approval'}{$currapproval}.
 6074:                                 '<br />'.&mt('(Set by Domain Coordinator)');
 6075:                     next;
 6076:                 }
 6077:                 $appchecked{$currapproval} = ' checked="checked"';
 6078:                 for my $i (0..2) {
 6079:                     $output .= '<label>'.
 6080:                                '<input type="radio" name="selfenroll_approval" value="'.$i.'"'.
 6081:                                $appchecked{$i}.' onclick="toggleNotify();"'.$disabled.' />'.
 6082:                                $selfdescs{'approval'}{$i}.'</label>'.('&nbsp;'x2);
 6083:                 }
 6084:                 my %advhash = &Apache::lonnet::get_course_adv_roles($cid,1);
 6085:                 my (@ccs,%notified);
 6086:                 my $ccrole = 'cc';
 6087:                 if ($crstype eq 'Community') {
 6088:                     $ccrole = 'co';
 6089:                 }
 6090:                 if ($advhash{$ccrole}) {
 6091:                     @ccs = split(/,/,$advhash{$ccrole});
 6092:                 }
 6093:                 if ($currnotified) {
 6094:                     foreach my $current (split(/,/,$currnotified)) {
 6095:                         $notified{$current} = 1;
 6096:                         if (!grep(/^\Q$current\E$/,@ccs)) {
 6097:                             push(@ccs,$current);
 6098:                         }
 6099:                     }
 6100:                 }
 6101:                 if (@ccs) {
 6102:                     my $style;
 6103:                     unless ($currapproval) {
 6104:                         $style = ' style="display: none;"'; 
 6105:                     }
 6106:                     $output .= '<br /><div id="notified"'.$style.'>'.
 6107:                                &mt('Personnel to be notified when an enrollment request needs approval, or has been approved:').'&nbsp;'.
 6108:                                &Apache::loncommon::start_data_table().
 6109:                                &Apache::loncommon::start_data_table_row();
 6110:                     my $count = 0;
 6111:                     my $numcols = 4;
 6112:                     foreach my $cc (sort(@ccs)) {
 6113:                         my $notifyon;
 6114:                         my ($ccuname,$ccudom) = split(/:/,$cc);
 6115:                         if ($notified{$cc}) {
 6116:                             $notifyon = ' checked="checked" ';
 6117:                         }
 6118:                         if ($count && !$count%$numcols) {
 6119:                             $output .= &Apache::loncommon::end_data_table_row().
 6120:                                        &Apache::loncommon::start_data_table_row()
 6121:                         }
 6122:                         $output .= '<td><span class="LC_nobreak"><label>'.
 6123:                                    '<input type="checkbox" name="selfenroll_notify"'.$notifyon.' value="'.$cc.'"'.$disabled.' />'.
 6124:                                    &Apache::loncommon::plainname($ccuname,$ccudom).
 6125:                                    '</label></span></td>';
 6126:                         $count ++;
 6127:                     }
 6128:                     my $rem = $count%$numcols;
 6129:                     if ($rem) {
 6130:                         my $emptycols = $numcols - $rem;
 6131:                         for (my $i=0; $i<$emptycols; $i++) { 
 6132:                             $output .= '<td>&nbsp;</td>';
 6133:                         }
 6134:                     }
 6135:                     $output .= &Apache::loncommon::end_data_table_row().
 6136:                                &Apache::loncommon::end_data_table().
 6137:                                '</div>';
 6138:                 }
 6139:             } elsif ($item eq 'limit') {
 6140:                 my ($crslimit,$selflimit,$nolimit,$currlim,$currcap);
 6141:                 if (ref($currsettings) eq 'HASH') {
 6142:                     $currlim = $currsettings->{'selfenroll_limit'};
 6143:                     $currcap = $currsettings->{'selfenroll_cap'};
 6144:                 }
 6145:                 if ($noedit{$item}) {
 6146:                     if (($currlim eq 'allstudents') || ($currlim eq 'selfenrolled')) {
 6147:                         if ($currlim eq 'allstudents') {
 6148:                             $output .= &mt('Limit by total students');
 6149:                         } elsif ($currlim eq 'selfenrolled') {
 6150:                             $output .= &mt('Limit by total self-enrolled students');
 6151:                         }
 6152:                         $output .= ' '.&mt('Maximum: [_1]',$currcap).
 6153:                                    '<br />'.&mt('(Set by Domain Coordinator)');
 6154:                     } else {
 6155:                         $output .= &mt('No limit').'<br />'.&mt('(Set by Domain Coordinator)');
 6156:                     }
 6157:                     next;
 6158:                 }
 6159:                 if ($currlim eq 'allstudents') {
 6160:                     $crslimit = ' checked="checked" ';
 6161:                     $selflimit = ' ';
 6162:                     $nolimit = ' ';
 6163:                 } elsif ($currlim eq 'selfenrolled') {
 6164:                     $crslimit = ' ';
 6165:                     $selflimit = ' checked="checked" ';
 6166:                     $nolimit = ' '; 
 6167:                 } else {
 6168:                     $crslimit = ' ';
 6169:                     $selflimit = ' ';
 6170:                     $nolimit = ' checked="checked" ';
 6171:                 }
 6172:                 $output .= '<table><tr><td><label>'.
 6173:                            '<input type="radio" name="selfenroll_limit" value="none"'.$nolimit.$disabled.'/>'.
 6174:                            &mt('No limit').'</label></td><td><label>'.
 6175:                            '<input type="radio" name="selfenroll_limit" value="allstudents"'.$crslimit.$disabled.'/>'.
 6176:                            &mt('Limit by total students').'</label></td><td><label>'.
 6177:                            '<input type="radio" name="selfenroll_limit" value="selfenrolled"'.$selflimit.$disabled.'/>'.
 6178:                            &mt('Limit by total self-enrolled students').
 6179:                            '</td></tr><tr>'.
 6180:                            '<td>&nbsp;</td><td colspan="2"><span class="LC_nobreak">'.
 6181:                            ('&nbsp;'x3).&mt('Maximum number allowed: ').
 6182:                            '<input type="text" name="selfenroll_cap" size = "5" value="'.$currcap.'"'.$disabled.' /></td></tr></table>';
 6183:             }
 6184:             $output .= &Apache::lonhtmlcommon::row_closure(1);
 6185:         }
 6186:     }
 6187:     $output .= &Apache::lonhtmlcommon::end_pick_box().'<br />';
 6188:     unless ($readonly) {
 6189:         $output .= '<input type="button" name="selfenrollconf" value="'
 6190:                    .&mt('Save').'" onclick="validate_types(this.form);" />';
 6191:     }
 6192:     $output .= '<input type="hidden" name="action" value="selfenroll" />'
 6193:               .'<input type="hidden" name="state" value="done" />'."\n"
 6194:               .$additional.'</form>';
 6195:     $r->print($output);
 6196:     return;
 6197: }
 6198: 
 6199: sub get_noedit_fields {
 6200:     my ($cdom,$cnum,$crstype,$row) = @_;
 6201:     my %noedit;
 6202:     if (ref($row) eq 'ARRAY') {
 6203:         my %settings = &Apache::lonnet::get('environment',['internal.coursecode','internal.textbook',
 6204:                                                            'internal.selfenrollmgrdc',
 6205:                                                            'internal.selfenrollmgrcc'],$cdom,$cnum);
 6206:         my $type = &Apache::lonuserutils::get_extended_type($cdom,$cnum,$crstype,\%settings);
 6207:         my (%specific_managebydc,%specific_managebycc,%default_managebydc);
 6208:         map { $specific_managebydc{$_} = 1; } (split(/,/,$settings{'internal.selfenrollmgrdc'}));
 6209:         map { $specific_managebycc{$_} = 1; } (split(/,/,$settings{'internal.selfenrollmgrcc'}));
 6210:         my %domdefaults = &Apache::lonnet::get_domain_defaults($cdom);
 6211:         map { $default_managebydc{$_} = 1; } (split(/,/,$domdefaults{$type.'selfenrolladmdc'}));
 6212: 
 6213:         foreach my $item (@{$row}) {
 6214:             next if ($specific_managebycc{$item});
 6215:             if (($specific_managebydc{$item}) || ($default_managebydc{$item})) {
 6216:                 $noedit{$item} = 1;
 6217:             }
 6218:         }
 6219:     }
 6220:     return %noedit;
 6221: } 
 6222: 
 6223: sub visible_in_stdcat {
 6224:     my ($cdom,$cnum,$domconf) = @_;
 6225:     my ($cathash,%settable,@vismsgs,$cansetvis,$visible);
 6226:     unless (ref($domconf) eq 'HASH') {
 6227:         return ($visible,$cansetvis,\@vismsgs);
 6228:     }
 6229:     if (ref($domconf->{'coursecategories'}) eq 'HASH') {
 6230:         if ($domconf->{'coursecategories'}{'togglecats'} eq 'crs') {
 6231:             $settable{'togglecats'} = 1;
 6232:         }
 6233:         if ($domconf->{'coursecategories'}{'categorize'} eq 'crs') {
 6234:             $settable{'categorize'} = 1;
 6235:         }
 6236:         $cathash = $domconf->{'coursecategories'}{'cats'};
 6237:     }
 6238:     if ($settable{'togglecats'} && $settable{'categorize'}) {
 6239:         $cansetvis = &mt('You are able to both assign a course category and choose to exclude this course from the catalog.');   
 6240:     } elsif ($settable{'togglecats'}) {
 6241:         $cansetvis = &mt('You are able to choose to exclude this course from the catalog, but only a Domain Coordinator may assign a course category.'); 
 6242:     } elsif ($settable{'categorize'}) {
 6243:         $cansetvis = &mt('You may assign a course category, but only a Domain Coordinator may choose to exclude this course from the catalog.');  
 6244:     } else {
 6245:         $cansetvis = &mt('Only a Domain Coordinator may assign a course category or choose to exclude this course from the catalog.'); 
 6246:     }
 6247:      
 6248:     my %currsettings =
 6249:         &Apache::lonnet::get('environment',['hidefromcat','categories','internal.coursecode'],
 6250:                              $cdom,$cnum);
 6251:     $visible = 0;
 6252:     if ($currsettings{'internal.coursecode'} ne '') {
 6253:         if (ref($domconf->{'coursecategories'}) eq 'HASH') {
 6254:             $cathash = $domconf->{'coursecategories'}{'cats'};
 6255:             if (ref($cathash) eq 'HASH') {
 6256:                 if ($cathash->{'instcode::0'} eq '') {
 6257:                     push(@vismsgs,'dc_addinst'); 
 6258:                 } else {
 6259:                     $visible = 1;
 6260:                 }
 6261:             } else {
 6262:                 $visible = 1;
 6263:             }
 6264:         } else {
 6265:             $visible = 1;
 6266:         }
 6267:     } else {
 6268:         if (ref($cathash) eq 'HASH') {
 6269:             if ($cathash->{'instcode::0'} ne '') {
 6270:                 push(@vismsgs,'dc_instcode');
 6271:             }
 6272:         } else {
 6273:             push(@vismsgs,'dc_instcode');
 6274:         }
 6275:     }
 6276:     if ($currsettings{'categories'} ne '') {
 6277:         my $cathash;
 6278:         if (ref($domconf->{'coursecategories'}) eq 'HASH') {
 6279:             $cathash = $domconf->{'coursecategories'}{'cats'};
 6280:             if (ref($cathash) eq 'HASH') {
 6281:                 if (keys(%{$cathash}) == 0) {
 6282:                     push(@vismsgs,'dc_catalog');
 6283:                 } elsif ((keys(%{$cathash}) == 1) && ($cathash->{'instcode::0'} ne '')) {
 6284:                     push(@vismsgs,'dc_categories');
 6285:                 } else {
 6286:                     my @currcategories = split('&',$currsettings{'categories'});
 6287:                     my $matched = 0;
 6288:                     foreach my $cat (@currcategories) {
 6289:                         if ($cathash->{$cat} ne '') {
 6290:                             $visible = 1;
 6291:                             $matched = 1;
 6292:                             last;
 6293:                         }
 6294:                     }
 6295:                     if (!$matched) {
 6296:                         if ($settable{'categorize'}) { 
 6297:                             push(@vismsgs,'chgcat');
 6298:                         } else {
 6299:                             push(@vismsgs,'dc_chgcat');
 6300:                         }
 6301:                     }
 6302:                 }
 6303:             }
 6304:         }
 6305:     } else {
 6306:         if (ref($cathash) eq 'HASH') {
 6307:             if ((keys(%{$cathash}) > 1) || 
 6308:                 (keys(%{$cathash}) == 1) && ($cathash->{'instcode::0'} eq '')) {
 6309:                 if ($settable{'categorize'}) {
 6310:                     push(@vismsgs,'addcat');
 6311:                 } else {
 6312:                     push(@vismsgs,'dc_addcat');
 6313:                 }
 6314:             }
 6315:         }
 6316:     }
 6317:     if ($currsettings{'hidefromcat'} eq 'yes') {
 6318:         $visible = 0;
 6319:         if ($settable{'togglecats'}) {
 6320:             unshift(@vismsgs,'unhide');
 6321:         } else {
 6322:             unshift(@vismsgs,'dc_unhide')
 6323:         }
 6324:     }
 6325:     return ($visible,$cansetvis,\@vismsgs);
 6326: }
 6327: 
 6328: sub cat_visibility {
 6329:     my %visactions = &Apache::lonlocal::texthash(
 6330:                    vis => 'This course/community currently appears in the Course/Community Catalog for this domain.',
 6331:                    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.',
 6332:                    miss => 'This course/community does not currently appear in the Course/Community Catalog for this domain.',
 6333:                    none => 'Display of a course catalog is disabled for this domain.',
 6334:                    yous => 'You should remedy this if you plan to allow self-enrollment, otherwise students will have difficulty finding this course.',
 6335:                    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.',
 6336:                    make => 'Make any changes to self-enrollment settings below, click "Save", then take action to include the course in the Catalog:',
 6337:                    take => 'Take the following action to ensure the course appears in the Catalog:',
 6338:                    dc_chgconf => 'Ask a domain coordinator to change the Catalog type for this domain.',
 6339:                    dc_setcode => 'Ask a domain coordinator to assign a six character code to the course',
 6340:                    dc_unhide  => 'Ask a domain coordinator to change the "Exclude from course catalog" setting.',
 6341:                    dc_addinst => 'Ask a domain coordinator to enable display the catalog of "Official courses (with institutional codes)".',
 6342:                    dc_instcode => 'Ask a domain coordinator to assign an institutional code (if this is an official course).',
 6343:                    dc_catalog  => 'Ask a domain coordinator to enable or create at least one course category in the domain.',
 6344:                    dc_categories => 'Ask a domain coordinator to create a hierarchy of categories and sub categories for courses in the domain.',
 6345:                    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',
 6346:                    dc_addcat => 'Ask a domain coordinator to assign a category to the course.',
 6347:     );
 6348:     $visactions{'unhide'} = &mt('Use [_1]Categorize course[_2] to change the "Exclude from course catalog" setting.','<a href="/adm/courseprefs?phase=display&actions=courseinfo">','</a>"');
 6349:     $visactions{'chgcat'} = &mt('Use [_1]Categorize course[_2] to change the category assigned to the course, as the one currently assigned is no longer used in the domain.','"<a href="/adm/courseprefs?phase=display&actions=courseinfo">','</a>"');
 6350:     $visactions{'addcat'} = &mt('Use [_1]Categorize course[_2] to assign a category to the course.','"<a href="/adm/courseprefs?phase=display&actions=courseinfo">','</a>"');
 6351:     return \%visactions;
 6352: }
 6353: 
 6354: sub new_selfenroll_dom_row {
 6355:     my ($newdom,$num) = @_;
 6356:     my $domdesc = &Apache::lonnet::domain($newdom);
 6357:     my $output;
 6358:     if ($domdesc ne '') {
 6359:         $output .= &Apache::loncommon::start_data_table_row()
 6360:                    .'<td valign="top"><span class="LC_nobreak">'.&mt('Domain:').'&nbsp;<b>'.$domdesc
 6361:                    .' ('.$newdom.')</b><input type="hidden" name="selfenroll_dom_'.$num
 6362:                    .'" value="'.$newdom.'" /></span><br />'
 6363:                    .'<span class="LC_nobreak"><label><input type="checkbox" '
 6364:                    .'name="selfenroll_activate" value="'.$num.'" '
 6365:                    .'onchange="javascript:update_types('
 6366:                    ."'selfenroll_activate','$num'".');" />'
 6367:                    .&mt('Activate').'</label></span></td>';
 6368:         my @currinsttypes;
 6369:         $output .= '<td>'.&mt('User types:').'<br />'
 6370:                    .&selfenroll_inst_types($num,$newdom,\@currinsttypes).'</td>'
 6371:                    .&Apache::loncommon::end_data_table_row();
 6372:     }
 6373:     return $output;
 6374: }
 6375: 
 6376: sub selfenroll_inst_types {
 6377:     my ($num,$currdom,$currinsttypes,$readonly) = @_;
 6378:     my $output;
 6379:     my $numinrow = 4;
 6380:     my $count = 0;
 6381:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($currdom);
 6382:     my $othervalue = 'any';
 6383:     my $disabled;
 6384:     if ($readonly) {
 6385:         $disabled = ' disabled="disabled"';
 6386:     }
 6387:     if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 6388:         if (keys(%{$usertypes}) > 0) {
 6389:             $othervalue = 'other';
 6390:         }
 6391:         $output .= '<table><tr>';
 6392:         foreach my $type (@{$types}) {
 6393:             if (($count > 0) && ($count%$numinrow == 0)) {
 6394:                 $output .= '</tr><tr>';
 6395:             }
 6396:             if (defined($usertypes->{$type})) {
 6397:                 my $esc_type = &escape($type);
 6398:                 $output .= '<td><span class="LC_nobreak"><label><input type = "checkbox" value="'.
 6399:                            $esc_type.'" ';
 6400:                 if (ref($currinsttypes) eq 'ARRAY') {
 6401:                     if (@{$currinsttypes} > 0) {
 6402:                         if (grep(/^any$/,@{$currinsttypes})) {
 6403:                             $output .= 'checked="checked"';
 6404:                         } elsif (grep(/^\Q$esc_type\E$/,@{$currinsttypes})) {
 6405:                             $output .= 'checked="checked"';
 6406:                         }
 6407:                     } else {
 6408:                         $output .= 'checked="checked"';
 6409:                     }
 6410:                 }
 6411:                 $output .= ' name="selfenroll_types_'.$num.'"'.$disabled.' />'.$usertypes->{$type}.'</label></span></td>';
 6412:             }
 6413:             $count ++;
 6414:         }
 6415:         if (($count > 0) && ($count%$numinrow == 0)) {
 6416:             $output .= '</tr><tr>';
 6417:         }
 6418:         $output .= '<td><span class="LC_nobreak"><label><input type = "checkbox" value="'.$othervalue.'"';
 6419:         if (ref($currinsttypes) eq 'ARRAY') {
 6420:             if (@{$currinsttypes} > 0) {
 6421:                 if (grep(/^any$/,@{$currinsttypes})) { 
 6422:                     $output .= ' checked="checked"';
 6423:                 } elsif ($othervalue eq 'other') {
 6424:                     if (grep(/^\Q$othervalue\E$/,@{$currinsttypes})) {
 6425:                         $output .= ' checked="checked"';
 6426:                     }
 6427:                 }
 6428:             } else {
 6429:                 $output .= ' checked="checked"';
 6430:             }
 6431:         } else {
 6432:             $output .= ' checked="checked"';
 6433:         }
 6434:         $output .= ' name="selfenroll_types_'.$num.'"'.$disabled.' />'.$othertitle.'</label></span></td></tr></table>';
 6435:     }
 6436:     return $output;
 6437: }
 6438: 
 6439: sub selfenroll_date_forms {
 6440:     my ($startform,$endform) = @_;
 6441:     my $output .= &Apache::lonhtmlcommon::start_pick_box()."\n".
 6442:                   &Apache::lonhtmlcommon::row_title(&mt('Start date'),
 6443:                                                     'LC_oddrow_value')."\n".
 6444:                   $startform."\n".
 6445:                   &Apache::lonhtmlcommon::row_closure(1).
 6446:                   &Apache::lonhtmlcommon::row_title(&mt('End date'),
 6447:                                                    'LC_oddrow_value')."\n".
 6448:                   $endform."\n".
 6449:                   &Apache::lonhtmlcommon::row_closure(1).
 6450:                   &Apache::lonhtmlcommon::end_pick_box();
 6451:     return $output;
 6452: }
 6453: 
 6454: sub print_userchangelogs_display {
 6455:     my ($r,$context,$permission,$brcrum) = @_;
 6456:     my $formname = 'rolelog';
 6457:     my ($username,$domain,$crstype,$viewablesec,%roleslog);
 6458:     if ($context eq 'domain') {
 6459:         $domain = $env{'request.role.domain'};
 6460:         %roleslog=&Apache::lonnet::dump_dom('nohist_rolelog',$domain);
 6461:     } else {
 6462:         if ($context eq 'course') { 
 6463:             $domain = $env{'course.'.$env{'request.course.id'}.'.domain'};
 6464:             $username = $env{'course.'.$env{'request.course.id'}.'.num'};
 6465:             $crstype = &Apache::loncommon::course_type();
 6466:             $viewablesec = &Apache::lonuserutils::viewable_section($permission);
 6467:             my %saveable_parameters = ('show' => 'scalar',);
 6468:             &Apache::loncommon::store_course_settings('roles_log',
 6469:                                                       \%saveable_parameters);
 6470:             &Apache::loncommon::restore_course_settings('roles_log',
 6471:                                                         \%saveable_parameters);
 6472:         } elsif ($context eq 'author') {
 6473:             $domain = $env{'user.domain'}; 
 6474:             if ($env{'request.role'} =~ m{^au\./\Q$domain\E/$}) {
 6475:                 $username = $env{'user.name'};
 6476:             } else {
 6477:                 undef($domain);
 6478:             }
 6479:         }
 6480:         if ($domain ne '' && $username ne '') { 
 6481:             %roleslog=&Apache::lonnet::dump('nohist_rolelog',$domain,$username);
 6482:         }
 6483:     }
 6484:     if ((keys(%roleslog))[0]=~/^error\:/) { undef(%roleslog); }
 6485: 
 6486:     my $helpitem;
 6487:     if ($context eq 'course') {
 6488:         $helpitem = 'Course_User_Logs';
 6489:     }
 6490:     push (@{$brcrum},
 6491:              {href => '/adm/createuser?action=changelogs',
 6492:               text => 'User Management Logs',
 6493:               help => $helpitem});
 6494:     my $bread_crumbs_component = 'User Changes';
 6495:     my $args = { bread_crumbs           => $brcrum,
 6496:                  bread_crumbs_component => $bread_crumbs_component};
 6497: 
 6498:     # Create navigation javascript
 6499:     my $jsnav = &userlogdisplay_js($formname);
 6500: 
 6501:     my $jscript = (<<ENDSCRIPT);
 6502: <script type="text/javascript">
 6503: // <![CDATA[
 6504: $jsnav
 6505: // ]]>
 6506: </script>
 6507: ENDSCRIPT
 6508: 
 6509:     # print page header
 6510:     $r->print(&header($jscript,$args));
 6511: 
 6512:     # set defaults
 6513:     my $now = time();
 6514:     my $defstart = $now - (7*24*3600); #7 days ago 
 6515:     my %defaults = (
 6516:                      page               => '1',
 6517:                      show               => '10',
 6518:                      role               => 'any',
 6519:                      chgcontext         => 'any',
 6520:                      rolelog_start_date => $defstart,
 6521:                      rolelog_end_date   => $now,
 6522:                    );
 6523:     my $more_records = 0;
 6524: 
 6525:     # set current
 6526:     my %curr;
 6527:     foreach my $item ('show','page','role','chgcontext') {
 6528:         $curr{$item} = $env{'form.'.$item};
 6529:     }
 6530:     my ($startdate,$enddate) = 
 6531:         &Apache::lonuserutils::get_dates_from_form('rolelog_start_date','rolelog_end_date');
 6532:     $curr{'rolelog_start_date'} = $startdate;
 6533:     $curr{'rolelog_end_date'} = $enddate;
 6534:     foreach my $key (keys(%defaults)) {
 6535:         if ($curr{$key} eq '') {
 6536:             $curr{$key} = $defaults{$key};
 6537:         }
 6538:     }
 6539:     my (%whodunit,%changed,$version);
 6540:     ($version) = ($r->dir_config('lonVersion') =~ /^([\d\.]+)\-/);
 6541:     my ($minshown,$maxshown);
 6542:     $minshown = 1;
 6543:     my $count = 0;
 6544:     if ($curr{'show'} =~ /\D/) {
 6545:         $curr{'page'} = 1;
 6546:     } else {
 6547:         $maxshown = $curr{'page'} * $curr{'show'};
 6548:         if ($curr{'page'} > 1) {
 6549:             $minshown = 1 + ($curr{'page'} - 1) * $curr{'show'};
 6550:         }
 6551:     }
 6552: 
 6553:     # Form Header
 6554:     $r->print('<form action="/adm/createuser" method="post" name="'.$formname.'">'.
 6555:               &role_display_filter($context,$formname,$domain,$username,\%curr,
 6556:                                    $version,$crstype));
 6557: 
 6558:     my $showntableheader = 0;
 6559: 
 6560:     # Table Header
 6561:     my $tableheader = 
 6562:         &Apache::loncommon::start_data_table_header_row()
 6563:        .'<th>&nbsp;</th>'
 6564:        .'<th>'.&mt('When').'</th>'
 6565:        .'<th>'.&mt('Who made the change').'</th>'
 6566:        .'<th>'.&mt('Changed User').'</th>'
 6567:        .'<th>'.&mt('Role').'</th>';
 6568: 
 6569:     if ($context eq 'course') {
 6570:         $tableheader .= '<th>'.&mt('Section').'</th>';
 6571:     }
 6572:     $tableheader .=
 6573:         '<th>'.&mt('Context').'</th>'
 6574:        .'<th>'.&mt('Start').'</th>'
 6575:        .'<th>'.&mt('End').'</th>'
 6576:        .&Apache::loncommon::end_data_table_header_row();
 6577: 
 6578:     # Display user change log data
 6579:     foreach my $id (sort { $roleslog{$b}{'exe_time'}<=>$roleslog{$a}{'exe_time'} } (keys(%roleslog))) {
 6580:         next if (($roleslog{$id}{'exe_time'} < $curr{'rolelog_start_date'}) ||
 6581:                  ($roleslog{$id}{'exe_time'} > $curr{'rolelog_end_date'}));
 6582:         if ($curr{'show'} !~ /\D/) {
 6583:             if ($count >= $curr{'page'} * $curr{'show'}) {
 6584:                 $more_records = 1;
 6585:                 last;
 6586:             }
 6587:         }
 6588:         if ($curr{'role'} ne 'any') {
 6589:             next if ($roleslog{$id}{'logentry'}{'role'} ne $curr{'role'}); 
 6590:         }
 6591:         if ($curr{'chgcontext'} ne 'any') {
 6592:             if ($curr{'chgcontext'} eq 'selfenroll') {
 6593:                 next if (!$roleslog{$id}{'logentry'}{'selfenroll'});
 6594:             } else {
 6595:                 next if ($roleslog{$id}{'logentry'}{'context'} ne $curr{'chgcontext'});
 6596:             }
 6597:         }
 6598:         if (($context eq 'course') && ($viewablesec ne '')) {
 6599:             next if ($roleslog{$id}{'logentry'}{'section'} ne $viewablesec); 
 6600:         }
 6601:         $count ++;
 6602:         next if ($count < $minshown);
 6603:         unless ($showntableheader) {
 6604:             $r->print(&Apache::loncommon::start_data_table()
 6605:                      .$tableheader);
 6606:             $r->rflush();
 6607:             $showntableheader = 1;
 6608:         }
 6609:         if ($whodunit{$roleslog{$id}{'exe_uname'}.':'.$roleslog{$id}{'exe_udom'}} eq '') {
 6610:             $whodunit{$roleslog{$id}{'exe_uname'}.':'.$roleslog{$id}{'exe_udom'}} =
 6611:                 &Apache::loncommon::plainname($roleslog{$id}{'exe_uname'},$roleslog{$id}{'exe_udom'});
 6612:         }
 6613:         if ($changed{$roleslog{$id}{'uname'}.':'.$roleslog{$id}{'udom'}} eq '') {
 6614:             $changed{$roleslog{$id}{'uname'}.':'.$roleslog{$id}{'udom'}} =
 6615:                 &Apache::loncommon::plainname($roleslog{$id}{'uname'},$roleslog{$id}{'udom'});
 6616:         }
 6617:         my $sec = $roleslog{$id}{'logentry'}{'section'};
 6618:         if ($sec eq '') {
 6619:             $sec = &mt('None');
 6620:         }
 6621:         my ($rolestart,$roleend);
 6622:         if ($roleslog{$id}{'delflag'}) {
 6623:             $rolestart = &mt('deleted');
 6624:             $roleend = &mt('deleted');
 6625:         } else {
 6626:             $rolestart = $roleslog{$id}{'logentry'}{'start'};
 6627:             $roleend = $roleslog{$id}{'logentry'}{'end'};
 6628:             if ($rolestart eq '' || $rolestart == 0) {
 6629:                 $rolestart = &mt('No start date'); 
 6630:             } else {
 6631:                 $rolestart = &Apache::lonlocal::locallocaltime($rolestart);
 6632:             }
 6633:             if ($roleend eq '' || $roleend == 0) { 
 6634:                 $roleend = &mt('No end date');
 6635:             } else {
 6636:                 $roleend = &Apache::lonlocal::locallocaltime($roleend);
 6637:             }
 6638:         }
 6639:         my $chgcontext = $roleslog{$id}{'logentry'}{'context'};
 6640:         if ($roleslog{$id}{'logentry'}{'selfenroll'}) {
 6641:             $chgcontext = 'selfenroll';
 6642:         }
 6643:         my %lt = &rolechg_contexts($context,$crstype);
 6644:         if ($chgcontext ne '' && $lt{$chgcontext} ne '') {
 6645:             $chgcontext = $lt{$chgcontext};
 6646:         }
 6647:         $r->print(
 6648:             &Apache::loncommon::start_data_table_row()
 6649:            .'<td>'.$count.'</td>'
 6650:            .'<td>'.&Apache::lonlocal::locallocaltime($roleslog{$id}{'exe_time'}).'</td>'
 6651:            .'<td>'.$whodunit{$roleslog{$id}{'exe_uname'}.':'.$roleslog{$id}{'exe_udom'}}.'</td>'
 6652:            .'<td>'.$changed{$roleslog{$id}{'uname'}.':'.$roleslog{$id}{'udom'}}.'</td>'
 6653:            .'<td>'.&Apache::lonnet::plaintext($roleslog{$id}{'logentry'}{'role'},$crstype).'</td>');
 6654:         if ($context eq 'course') { 
 6655:             $r->print('<td>'.$sec.'</td>');
 6656:         }
 6657:         $r->print(
 6658:             '<td>'.$chgcontext.'</td>'
 6659:            .'<td>'.$rolestart.'</td>'
 6660:            .'<td>'.$roleend.'</td>'
 6661:            .&Apache::loncommon::end_data_table_row()."\n");
 6662:     }
 6663: 
 6664:     if ($showntableheader) { # Table footer, if content displayed above
 6665:         $r->print(&Apache::loncommon::end_data_table().
 6666:                   &userlogdisplay_navlinks(\%curr,$more_records));
 6667:     } else { # No content displayed above
 6668:         $r->print('<p class="LC_info">'
 6669:                  .&mt('There are no records to display.')
 6670:                  .'</p>'
 6671:         );
 6672:     }
 6673: 
 6674:     # Form Footer
 6675:     $r->print( 
 6676:         '<input type="hidden" name="page" value="'.$curr{'page'}.'" />'
 6677:        .'<input type="hidden" name="action" value="changelogs" />'
 6678:        .'</form>');
 6679:     return;
 6680: }
 6681: 
 6682: sub print_useraccesslogs_display {
 6683:     my ($r,$uname,$udom,$permission,$brcrum) = @_;
 6684:     my $formname = 'accesslog';
 6685:     my $form = 'document.accesslog';
 6686: 
 6687: # set breadcrumbs
 6688:     my %breadcrumb_text = &singleuser_breadcrumb('','domain',$udom);
 6689:     push (@{$brcrum},
 6690:         {href => "javascript:backPage($form)",
 6691:          text => $breadcrumb_text{'search'}});
 6692:     my (@prevphases,$prevphasestr);
 6693:     if ($env{'form.prevphases'}) {
 6694:         @prevphases = split(/,/,$env{'form.prevphases'});
 6695:         $prevphasestr = $env{'form.prevphases'};
 6696:     }
 6697:     if (($env{'form.phase'} eq 'userpicked') || (grep(/^userpicked$/,@prevphases))) {
 6698:         push(@{$brcrum},
 6699:               {href => "javascript:backPage($form,'get_user_info','select')",
 6700:                text => $breadcrumb_text{'userpicked'}});
 6701:         if ($env{'form.phase'} eq 'userpicked') {
 6702:             $prevphasestr = 'userpicked';
 6703:         }
 6704:     }
 6705:     push(@{$brcrum},
 6706:              {href => '/adm/createuser?action=accesslogs',
 6707:               text => 'User access logs',
 6708:               help => 'Domain_User_Access_Logs'});
 6709:     my $bread_crumbs_component = 'User Access Logs';
 6710:     my $args = { bread_crumbs           => $brcrum,
 6711:                  bread_crumbs_component => 'User Management'};
 6712:     if ($env{'form.popup'}) {
 6713:         $args->{'no_nav_bar'} = 1;
 6714:     }
 6715: 
 6716: # set javascript
 6717:     my ($jsback,$elements) = &crumb_utilities();
 6718:     my $jsnav = &userlogdisplay_js($formname);
 6719: 
 6720:     my $jscript = (<<ENDSCRIPT);
 6721: <script type="text/javascript">
 6722: // <![CDATA[
 6723: 
 6724: $jsback
 6725: $jsnav
 6726: 
 6727: // ]]>
 6728: </script>
 6729: 
 6730: ENDSCRIPT
 6731: 
 6732: # print page header
 6733:     $r->print(&header($jscript,$args));
 6734: 
 6735: # early out unless log data can be displayed.
 6736:     unless ($permission->{'activity'}) {
 6737:         $r->print('<p class="LC_warning">'
 6738:                  .&mt('You do not have rights to display user access logs.')
 6739:                  .'</p>'
 6740:                  .&earlyout_accesslog_form($formname,$prevphasestr,$udom));
 6741:         return;
 6742:     }
 6743: 
 6744:     unless ($udom eq $env{'request.role.domain'}) {
 6745:         $r->print('<p class="LC_warning">'
 6746:                  .&mt("User's domain must match role's domain")
 6747:                  .'</p>'
 6748:                  .&earlyout_accesslog_form($formname,$prevphasestr,$udom));
 6749:         return;
 6750:     }
 6751: 
 6752:     if (($uname eq '') || ($udom eq '')) {
 6753:         $r->print('<p class="LC_warning">'
 6754:                  .&mt('Invalid username or domain')
 6755:                  .'</p>'
 6756:                  .&earlyout_accesslog_form($formname,$prevphasestr,$udom));
 6757:         return;
 6758:     }
 6759: 
 6760: # set defaults
 6761:     my $now = time();
 6762:     my $defstart = $now - (7*24*3600);
 6763:     my %defaults = (
 6764:                      page                 => '1',
 6765:                      show                 => '10',
 6766:                      activity             => 'any',
 6767:                      accesslog_start_date => $defstart,
 6768:                      accesslog_end_date   => $now,
 6769:                    );
 6770:     my $more_records = 0;
 6771: 
 6772: # set current
 6773:     my %curr;
 6774:     foreach my $item ('show','page','activity') {
 6775:         $curr{$item} = $env{'form.'.$item};
 6776:     }
 6777:     my ($startdate,$enddate) =
 6778:         &Apache::lonuserutils::get_dates_from_form('accesslog_start_date','accesslog_end_date');
 6779:     $curr{'accesslog_start_date'} = $startdate;
 6780:     $curr{'accesslog_end_date'} = $enddate;
 6781:     foreach my $key (keys(%defaults)) {
 6782:         if ($curr{$key} eq '') {
 6783:             $curr{$key} = $defaults{$key};
 6784:         }
 6785:     }
 6786:     my ($minshown,$maxshown);
 6787:     $minshown = 1;
 6788:     my $count = 0;
 6789:     if ($curr{'show'} =~ /\D/) {
 6790:         $curr{'page'} = 1;
 6791:     } else {
 6792:         $maxshown = $curr{'page'} * $curr{'show'};
 6793:         if ($curr{'page'} > 1) {
 6794:             $minshown = 1 + ($curr{'page'} - 1) * $curr{'show'};
 6795:         }
 6796:     }
 6797: 
 6798: # form header
 6799:     $r->print('<form action="/adm/createuser" method="post" name="'.$formname.'">'.
 6800:               &activity_display_filter($formname,\%curr));
 6801: 
 6802:     my $showntableheader = 0;
 6803:     my ($nav_script,$nav_links);
 6804: 
 6805: # table header
 6806:     my $tableheader =
 6807:         &Apache::loncommon::start_data_table_header_row()
 6808:        .'<th>&nbsp;</th>'
 6809:        .'<th>'.&mt('When').'</th>'
 6810:        .'<th>'.&mt('HostID').'</th>'
 6811:        .'<th>'.&mt('Event').'</th>'
 6812:        .'<th>'.&mt('Other data').'</th>'
 6813:        .&Apache::loncommon::end_data_table_header_row();
 6814: 
 6815:     my %filters=(
 6816:         start  => $curr{'accesslog_start_date'},
 6817:         end    => $curr{'accesslog_end_date'},
 6818:         action => $curr{'activity'},
 6819:     );
 6820: 
 6821:     my $reply = &Apache::lonnet::userlog_query($uname,$udom,%filters);
 6822:     unless ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 6823:         my (%courses,%missing);
 6824:         my @results = split(/\&/,$reply);
 6825:         foreach my $item (reverse(@results)) {
 6826:             my ($timestamp,$host,$event) = split(/:/,$item);
 6827:             next unless ($event =~ /^(Log|Role)/);
 6828:             if ($curr{'show'} !~ /\D/) {
 6829:                 if ($count >= $curr{'page'} * $curr{'show'}) {
 6830:                     $more_records = 1;
 6831:                     last;
 6832:                 }
 6833:             }
 6834:             $count ++;
 6835:             next if ($count < $minshown);
 6836:             unless ($showntableheader) {
 6837:                 $r->print($nav_script
 6838:                          .&Apache::loncommon::start_data_table()
 6839:                          .$tableheader);
 6840:                 $r->rflush();
 6841:                 $showntableheader = 1;
 6842:             }
 6843:             my ($shown,$extra);
 6844:             my ($event,$data) = split(/\s+/,&unescape($event));
 6845:             if ($event eq 'Role') {
 6846:                 my ($rolecode,$extent) = split(/\./,$data,2);
 6847:                 next if ($extent eq '');
 6848:                 my ($crstype,$desc,$info);
 6849:                 if ($extent =~ m{^/($match_domain)/($match_courseid)(?:/(\w+)|)$}) {
 6850:                     my ($cdom,$cnum,$sec) = ($1,$2,$3);
 6851:                     my $cid = $cdom.'_'.$cnum;
 6852:                     if (exists($courses{$cid})) {
 6853:                         $crstype = $courses{$cid}{'type'};
 6854:                         $desc = $courses{$cid}{'description'};
 6855:                     } elsif ($missing{$cid}) {
 6856:                         $crstype = 'Course';
 6857:                         $desc = 'Course/Community';
 6858:                     } else {
 6859:                         my %crsinfo = &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 6860:                         if (ref($crsinfo{$cdom.'_'.$cnum}) eq 'HASH') {
 6861:                             $courses{$cid} = $crsinfo{$cid};
 6862:                             $crstype = $crsinfo{$cid}{'type'};
 6863:                             $desc = $crsinfo{$cid}{'description'};
 6864:                         } else {
 6865:                             $missing{$cid} = 1;
 6866:                         }
 6867:                     }
 6868:                     $extra = &mt($crstype).': <a href="/public/'.$cdom.'/'.$cnum.'/syllabus">'.$desc.'</a>';
 6869:                     if ($sec ne '') {
 6870:                        $extra .= ' ('.&mt('Section: [_1]',$sec).')';
 6871:                     }
 6872:                 } elsif ($extent =~ m{^/($match_domain)/($match_username|$)}) {
 6873:                     my ($dom,$name) = ($1,$2);
 6874:                     if ($rolecode eq 'au') {
 6875:                         $extra = '';
 6876:                     } elsif ($rolecode =~ /^(ca|aa)$/) {
 6877:                         $extra = &mt('Authoring Space: [_1]',$name.':'.$dom);
 6878:                     } elsif ($rolecode =~ /^(li|dg|dh|dc|sc)$/) {
 6879:                         $extra = &mt('Domain: [_1]',$dom);
 6880:                     }
 6881:                 }
 6882:                 my $rolename;
 6883:                 if ($rolecode =~ m{^cr/($match_domain)/($match_username)/(\w+)}) {
 6884:                     my $role = $3;
 6885:                     my $owner = "($2:$1)";
 6886:                     if ($2 eq $1.'-domainconfig') {
 6887:                         $owner = '(ad hoc)';
 6888:                     }
 6889:                     $rolename = &mt('Custom role: [_1]',$role.' '.$owner);
 6890:                 } else {
 6891:                     $rolename = &Apache::lonnet::plaintext($rolecode,$crstype);
 6892:                 }
 6893:                 $shown = &mt('Role selection: [_1]',$rolename);
 6894:             } else {
 6895:                 $shown = &mt($event);
 6896:                 if ($data ne '') {
 6897:                    $extra = &mt('Client IP address: [_1]',$data);
 6898:                 }
 6899:             }
 6900:             $r->print(
 6901:             &Apache::loncommon::start_data_table_row()
 6902:            .'<td>'.$count.'</td>'
 6903:            .'<td>'.&Apache::lonlocal::locallocaltime($timestamp).'</td>'
 6904:            .'<td>'.$host.'</td>'
 6905:            .'<td>'.$shown.'</td>'
 6906:            .'<td>'.$extra.'</td>'
 6907:            .&Apache::loncommon::end_data_table_row()."\n");
 6908:         }
 6909:     }
 6910: 
 6911:     if ($showntableheader) { # Table footer, if content displayed above
 6912:         $r->print(&Apache::loncommon::end_data_table().
 6913:                   &userlogdisplay_navlinks(\%curr,$more_records));
 6914:     } else { # No content displayed above
 6915:         $r->print('<p class="LC_info">'
 6916:                  .&mt('There are no records to display.')
 6917:                  .'</p>');
 6918:     }
 6919: 
 6920:     if ($env{'form.popup'} == 1) {
 6921:         $r->print('<input type="hidden" name="popup" value="1" />'."\n");
 6922:     }
 6923: 
 6924:     # Form Footer
 6925:     $r->print(
 6926:         '<input type="hidden" name="currstate" value="" />'
 6927:        .'<input type="hidden" name="accessuname" value="'.$uname.'" />'
 6928:        .'<input type="hidden" name="accessudom" value="'.$udom.'" />'
 6929:        .'<input type="hidden" name="page" value="'.$curr{'page'}.'" />'
 6930:        .'<input type="hidden" name="prevphases" value="'.$prevphasestr.'" />'
 6931:        .'<input type="hidden" name="phase" value="activity" />'
 6932:        .'<input type="hidden" name="action" value="accesslogs" />'
 6933:        .'<input type="hidden" name="srchdomain" value="'.$udom.'" />'
 6934:        .'<input type="hidden" name="srchby" value="'.$env{'form.srchby'}.'" />'
 6935:        .'<input type="hidden" name="srchtype" value="'.$env{'form.srchtype'}.'" />'
 6936:        .'<input type="hidden" name="srchterm" value="'.&HTML::Entities::encode($env{'form.srchterm'},'<>"&').'" />'
 6937:        .'<input type="hidden" name="srchin" value="'.$env{'form.srchin'}.'" />'
 6938:        .'</form>');
 6939:     return;
 6940: }
 6941: 
 6942: sub earlyout_accesslog_form {
 6943:     my ($formname,$prevphasestr,$udom) = @_;
 6944:     my $srchterm = &HTML::Entities::encode($env{'form.srchterm'},'<>"&');
 6945:    return <<"END";
 6946: <form action="/adm/createuser" method="post" name="$formname">
 6947: <input type="hidden" name="currstate" value="" />
 6948: <input type="hidden" name="prevphases" value="$prevphasestr" />
 6949: <input type="hidden" name="phase" value="activity" />
 6950: <input type="hidden" name="action" value="accesslogs" />
 6951: <input type="hidden" name="srchdomain" value="$udom" />
 6952: <input type="hidden" name="srchby" value="$env{'form.srchby'}" />
 6953: <input type="hidden" name="srchtype" value="$env{'form.srchtype'}" />
 6954: <input type="hidden" name="srchterm" value="$srchterm" />
 6955: <input type="hidden" name="srchin" value="$env{'form.srchin'}" />
 6956: </form>
 6957: END
 6958: }
 6959: 
 6960: sub activity_display_filter {
 6961:     my ($formname,$curr) = @_;
 6962:     my $nolink = 1;
 6963:     my $output = '<table><tr><td valign="top">'.
 6964:                  '<span class="LC_nobreak"><b>'.&mt('Actions/page:').'</b></span><br />'.
 6965:                  &Apache::lonmeta::selectbox('show',$curr->{'show'},undef,
 6966:                                               (&mt('all'),5,10,20,50,100,1000,10000)).
 6967:                  '</td><td>&nbsp;&nbsp;</td>';
 6968:     my $startform =
 6969:         &Apache::lonhtmlcommon::date_setter($formname,'accesslog_start_date',
 6970:                                             $curr->{'accesslog_start_date'},undef,
 6971:                                             undef,undef,undef,undef,undef,undef,$nolink);
 6972:     my $endform =
 6973:         &Apache::lonhtmlcommon::date_setter($formname,'accesslog_end_date',
 6974:                                             $curr->{'accesslog_end_date'},undef,
 6975:                                             undef,undef,undef,undef,undef,undef,$nolink);
 6976:     my %lt = &Apache::lonlocal::texthash (
 6977:                                           activity => 'Activity',
 6978:                                           Role     => 'Role selection',
 6979:                                           log      => 'Log-in or Logout',
 6980:     );
 6981:     $output .= '<td valign="top"><b>'.&mt('Window during which actions occurred:').'</b><br />'.
 6982:                '<table><tr><td>'.&mt('After:').
 6983:                '</td><td>'.$startform.'</td></tr>'.
 6984:                '<tr><td>'.&mt('Before:').'</td>'.
 6985:                '<td>'.$endform.'</td></tr></table>'.
 6986:                '</td>'.
 6987:                '<td>&nbsp;&nbsp;</td>'.
 6988:                '<td valign="top"><b>'.&mt('Activities').'</b><br />'.
 6989:                '<select name="activity"><option value="any"';
 6990:     if ($curr->{'activity'} eq 'any') {
 6991:         $output .= ' selected="selected"';
 6992:     }
 6993:     $output .= '>'.&mt('Any').'</option>'."\n";
 6994:     foreach my $activity ('Role','log') {
 6995:         my $selstr = '';
 6996:         if ($activity eq $curr->{'activity'}) {
 6997:             $selstr = ' selected="selected"';
 6998:         }
 6999:         $output .= '<option value="'.$activity.'"'.$selstr.'>'.$lt{$activity}.'</option>';
 7000:     }
 7001:     $output .= '</select></td>'.
 7002:                '</tr></table>';
 7003:     # Update Display button
 7004:     $output .= '<p>'
 7005:               .'<input type="submit" value="'.&mt('Update Display').'" />'
 7006:               .'</p>';
 7007:     return $output;
 7008: }
 7009: 
 7010: sub userlogdisplay_js {
 7011:     my ($formname) = @_;
 7012:     return <<"ENDSCRIPT";
 7013: 
 7014: function chgPage(caller) {
 7015:     if (caller == 'previous') {
 7016:         document.$formname.page.value --;
 7017:     }
 7018:     if (caller == 'next') {
 7019:         document.$formname.page.value ++;
 7020:     }
 7021:     document.$formname.submit();
 7022:     return;
 7023: }
 7024: ENDSCRIPT
 7025: }
 7026: 
 7027: sub userlogdisplay_navlinks {
 7028:     my ($curr,$more_records) = @_;
 7029:     return unless(ref($curr) eq 'HASH');
 7030:     # Navigation Buttons
 7031:     my $nav_links = '<p>';
 7032:     if (($curr->{'page'} > 1) || ($more_records)) {
 7033:         if (($curr->{'page'} > 1) && ($curr->{'show'} !~ /\D/)) {
 7034:             $nav_links .= '<input type="button"'
 7035:                          .' onclick="javascript:chgPage('."'previous'".');"'
 7036:                          .' value="'.&mt('Previous [_1] changes',$curr->{'show'})
 7037:                          .'" /> ';
 7038:         }
 7039:         if ($more_records) {
 7040:             $nav_links .= '<input type="button"'
 7041:                          .' onclick="javascript:chgPage('."'next'".');"'
 7042:                          .' value="'.&mt('Next [_1] changes',$curr->{'show'})
 7043:                          .'" />';
 7044:         }
 7045:     }
 7046:     $nav_links .= '</p>';
 7047:     return $nav_links;
 7048: }
 7049: 
 7050: sub role_display_filter {
 7051:     my ($context,$formname,$cdom,$cnum,$curr,$version,$crstype) = @_;
 7052:     my $lctype;
 7053:     if ($context eq 'course') {
 7054:         $lctype = lc($crstype);
 7055:     }
 7056:     my $nolink = 1;
 7057:     my $output = '<table><tr><td valign="top">'.
 7058:                  '<span class="LC_nobreak"><b>'.&mt('Changes/page:').'</b></span><br />'.
 7059:                  &Apache::lonmeta::selectbox('show',$curr->{'show'},undef,
 7060:                                               (&mt('all'),5,10,20,50,100,1000,10000)).
 7061:                  '</td><td>&nbsp;&nbsp;</td>';
 7062:     my $startform =
 7063:         &Apache::lonhtmlcommon::date_setter($formname,'rolelog_start_date',
 7064:                                             $curr->{'rolelog_start_date'},undef,
 7065:                                             undef,undef,undef,undef,undef,undef,$nolink);
 7066:     my $endform =
 7067:         &Apache::lonhtmlcommon::date_setter($formname,'rolelog_end_date',
 7068:                                             $curr->{'rolelog_end_date'},undef,
 7069:                                             undef,undef,undef,undef,undef,undef,$nolink);
 7070:     my %lt = &rolechg_contexts($context,$crstype);
 7071:     $output .= '<td valign="top"><b>'.&mt('Window during which changes occurred:').'</b><br />'.
 7072:                '<table><tr><td>'.&mt('After:').
 7073:                '</td><td>'.$startform.'</td></tr>'.
 7074:                '<tr><td>'.&mt('Before:').'</td>'.
 7075:                '<td>'.$endform.'</td></tr></table>'.
 7076:                '</td>'.
 7077:                '<td>&nbsp;&nbsp;</td>'.
 7078:                '<td valign="top"><b>'.&mt('Role:').'</b><br />'.
 7079:                '<select name="role"><option value="any"';
 7080:     if ($curr->{'role'} eq 'any') {
 7081:         $output .= ' selected="selected"';
 7082:     }
 7083:     $output .=  '>'.&mt('Any').'</option>'."\n";
 7084:     my @roles = &Apache::lonuserutils::roles_by_context($context,1,$crstype);
 7085:     foreach my $role (@roles) {
 7086:         my $plrole;
 7087:         if ($role eq 'cr') {
 7088:             $plrole = &mt('Custom Role');
 7089:         } else {
 7090:             $plrole=&Apache::lonnet::plaintext($role,$crstype);
 7091:         }
 7092:         my $selstr = '';
 7093:         if ($role eq $curr->{'role'}) {
 7094:             $selstr = ' selected="selected"';
 7095:         }
 7096:         $output .= '  <option value="'.$role.'"'.$selstr.'>'.$plrole.'</option>';
 7097:     }
 7098:     $output .= '</select></td>'.
 7099:                '<td>&nbsp;&nbsp;</td>'.
 7100:                '<td valign="top"><b>'.
 7101:                &mt('Context:').'</b><br /><select name="chgcontext">';
 7102:     my @posscontexts;
 7103:     if ($context eq 'course') {
 7104:         @posscontexts = ('any','automated','updatenow','createcourse','course','domain','selfenroll','requestcourses');
 7105:     } elsif ($context eq 'domain') {
 7106:         @posscontexts = ('any','domain','requestauthor','domconfig','server');
 7107:     } else {
 7108:         @posscontexts = ('any','author','domain');
 7109:     } 
 7110:     foreach my $chgtype (@posscontexts) {
 7111:         my $selstr = '';
 7112:         if ($curr->{'chgcontext'} eq $chgtype) {
 7113:             $selstr = ' selected="selected"';
 7114:         }
 7115:         if ($context eq 'course') {
 7116:             if (($chgtype eq 'automated') || ($chgtype eq 'updatenow')) {
 7117:                 next if (!&Apache::lonnet::auto_run($cnum,$cdom));
 7118:             }
 7119:         }
 7120:         $output .= '<option value="'.$chgtype.'"'.$selstr.'>'.$lt{$chgtype}.'</option>'."\n";
 7121:     }
 7122:     $output .= '</select></td>'
 7123:               .'</tr></table>';
 7124: 
 7125:     # Update Display button
 7126:     $output .= '<p>'
 7127:               .'<input type="submit" value="'.&mt('Update Display').'" />'
 7128:               .'</p>';
 7129: 
 7130:     # Server version info
 7131:     my $needsrev = '2.11.0';
 7132:     if ($context eq 'course') {
 7133:         $needsrev = '2.7.0';
 7134:     }
 7135:     
 7136:     $output .= '<p class="LC_info">'
 7137:               .&mt('Only changes made from servers running LON-CAPA [_1] or later are displayed.'
 7138:                   ,$needsrev);
 7139:     if ($version) {
 7140:         $output .= ' '.&mt('This LON-CAPA server is version [_1]',$version);
 7141:     }
 7142:     $output .= '</p><hr />';
 7143:     return $output;
 7144: }
 7145: 
 7146: sub rolechg_contexts {
 7147:     my ($context,$crstype) = @_;
 7148:     my %lt;
 7149:     if ($context eq 'course') {
 7150:         %lt = &Apache::lonlocal::texthash (
 7151:                                              any          => 'Any',
 7152:                                              automated    => 'Automated Enrollment',
 7153:                                              updatenow    => 'Roster Update',
 7154:                                              createcourse => 'Course Creation',
 7155:                                              course       => 'User Management in course',
 7156:                                              domain       => 'User Management in domain',
 7157:                                              selfenroll   => 'Self-enrolled',
 7158:                                              requestcourses => 'Course Request',
 7159:                                          );
 7160:         if ($crstype eq 'Community') {
 7161:             $lt{'createcourse'} = &mt('Community Creation');
 7162:             $lt{'course'} = &mt('User Management in community');
 7163:             $lt{'requestcourses'} = &mt('Community Request');
 7164:         }
 7165:     } elsif ($context eq 'domain') {
 7166:         %lt = &Apache::lonlocal::texthash (
 7167:                                              any           => 'Any',
 7168:                                              domain        => 'User Management in domain',
 7169:                                              requestauthor => 'Authoring Request',
 7170:                                              server        => 'Command line script (DC role)',
 7171:                                              domconfig     => 'Self-enrolled',
 7172:                                          );
 7173:     } else {
 7174:         %lt = &Apache::lonlocal::texthash (
 7175:                                              any    => 'Any',
 7176:                                              domain => 'User Management in domain',
 7177:                                              author => 'User Management by author',
 7178:                                          );
 7179:     } 
 7180:     return %lt;
 7181: }
 7182: 
 7183: sub print_helpdeskaccess_display {
 7184:     my ($r,$permission,$brcrum) = @_;
 7185:     my $formname = 'helpdeskaccess';
 7186:     my $helpitem = 'Course_Helpdesk_Access';
 7187:     push (@{$brcrum},
 7188:              {href => '/adm/createuser?action=helpdesk',
 7189:               text => 'Helpdesk Access',
 7190:               help => $helpitem});
 7191:     my $bread_crumbs_component = 'Helpdesk Staff Access';
 7192:     my $args = { bread_crumbs           => $brcrum,
 7193:                  bread_crumbs_component => $bread_crumbs_component};
 7194: 
 7195:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7196:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7197:     my $confname = $cdom.'-domainconfig';
 7198:     my $crstype = &Apache::loncommon::course_type();
 7199: 
 7200:     my @accesstypes = ('all','none');
 7201:     my ($numstatustypes,@jsarray);
 7202:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($cdom);
 7203:     if (ref($types) eq 'ARRAY') {
 7204:         if (@{$types} > 0) {                
 7205:             $numstatustypes = scalar(@{$types});
 7206:             push(@accesstypes,'status');
 7207:             @jsarray = ('bystatus');
 7208:         }
 7209:     }
 7210:     my %customroles = &get_domain_customroles($cdom,$confname);
 7211:     my %domhelpdesk = &Apache::lonnet::get_active_domroles($cdom,['dh']);
 7212:     if (keys(%domhelpdesk)) {
 7213:        push(@accesstypes,('inc','exc'));
 7214:        push(@jsarray,('notinc','notexc'));
 7215:     }
 7216:     push(@jsarray,'privs');
 7217:     my $hiddenstr = join("','",@jsarray);
 7218:     my $rolestr = join("','",sort(keys(%customroles)));
 7219: 
 7220:     my $jscript;
 7221:     my (%settings,%overridden);
 7222:     if (keys(%customroles)) {
 7223:         &get_adhocrole_settings($env{'request.course.id'},\@accesstypes,
 7224:                                 $types,\%customroles,\%settings,\%overridden);
 7225:         my %jsfull=();
 7226:         my %jslevels= (
 7227:                      course => {},
 7228:                      domain => {},
 7229:                      system => {},
 7230:                     );
 7231:         my %jslevelscurrent=(
 7232:                            course => {},
 7233:                            domain => {},
 7234:                            system => {},
 7235:                           );
 7236:         my (%privs,%jsprivs);
 7237:         &Apache::lonuserutils::custom_role_privs(\%privs,\%jsfull,\%jslevels,\%jslevelscurrent);
 7238:         foreach my $priv (keys(%jsfull)) {
 7239:             if ($jslevels{'course'}{$priv}) {
 7240:                 $jsprivs{$priv} = 1;
 7241:             }
 7242:         }
 7243:         my (%elements,%stored);
 7244:         foreach my $role (keys(%customroles)) {
 7245:             $elements{$role.'_access'} = 'radio';
 7246:             $elements{$role.'_incrs'} = 'radio';
 7247:             if ($numstatustypes) {
 7248:                 $elements{$role.'_status'} = 'checkbox';
 7249:             }
 7250:             if (keys(%domhelpdesk) > 0) {
 7251:                 $elements{$role.'_staff_inc'} = 'checkbox';
 7252:                 $elements{$role.'_staff_exc'} = 'checkbox';
 7253:             }
 7254:             $elements{$role.'_override'} = 'checkbox';      
 7255:             if (ref($settings{$role}) eq 'HASH') {
 7256:                 if ($settings{$role}{'access'} ne '') {
 7257:                     my $curraccess = $settings{$role}{'access'};
 7258:                     $stored{$role.'_access'} = $curraccess;
 7259:                     $stored{$role.'_incrs'} = 1;
 7260:                     if ($curraccess eq 'status') {
 7261:                         if (ref($settings{$role}{'status'}) eq 'ARRAY') {
 7262:                             $stored{$role.'_status'} = $settings{$role}{'status'};
 7263:                         }
 7264:                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 7265:                         if (ref($settings{$role}{$curraccess}) eq 'ARRAY') {
 7266:                             $stored{$role.'_staff_'.$curraccess} = $settings{$role}{$curraccess};
 7267:                         }
 7268:                     }
 7269:                 } else {
 7270:                     $stored{$role.'_incrs'} = 0;
 7271:                 }
 7272:                 $stored{$role.'_override'} = [];
 7273:                 if ($env{'course.'.$env{'request.course.id'}.'.internal.adhocpriv.'.$role}) {
 7274:                     if (ref($settings{$role}{'off'}) eq 'ARRAY') {
 7275:                         foreach my $priv (@{$settings{$role}{'off'}}) {
 7276:                             push(@{$stored{$role.'_override'}},$priv);
 7277:                         }
 7278:                     }
 7279:                     if (ref($settings{$role}{'on'}) eq 'ARRAY') {
 7280:                         foreach my $priv (@{$settings{$role}{'on'}}) {
 7281:                             unless (grep(/^$priv$/,@{$stored{$role.'_override'}})) {
 7282:                                 push(@{$stored{$role.'_override'}},$priv);
 7283:                             }
 7284:                         }
 7285:                     }
 7286:                 }
 7287:             } else {
 7288:                 $stored{$role.'_incrs'} = 0;
 7289:             }
 7290:         }
 7291:         $jscript = &Apache::lonhtmlcommon::set_form_elements(\%elements,\%stored);
 7292:     }
 7293: 
 7294:     my $js = <<"ENDJS";
 7295: <script type="text/javascript">
 7296: // <![CDATA[
 7297: $jscript;
 7298: 
 7299: function switchRoleTab(caller,role) {
 7300:     if (document.getElementById(role+'_maindiv')) {
 7301:         if (caller.id != 'LC_current_minitab') {
 7302:             if (document.getElementById('LC_current_minitab')) {
 7303:                 document.getElementById('LC_current_minitab').id=null;
 7304:             }
 7305:             var roledivs = Array('$rolestr');
 7306:             if (roledivs.length > 0) {
 7307:                 for (var i=0; i<roledivs.length; i++) {
 7308:                     if (document.getElementById(roledivs[i]+'_maindiv')) {
 7309:                         document.getElementById(roledivs[i]+'_maindiv').style.display='none';
 7310:                     }
 7311:                 }
 7312:             }
 7313:             caller.id = 'LC_current_minitab';
 7314:             document.getElementById(role+'_maindiv').style.display='block';
 7315:         }
 7316:     }
 7317:     return false;
 7318: }         
 7319: 
 7320: function helpdeskAccess(role) {
 7321:     var curraccess = null;
 7322:     if (document.$formname.elements[role+'_access'].length) {
 7323:         for (var i=0; i<document.$formname.elements[role+'_access'].length; i++) {
 7324:             if (document.$formname.elements[role+'_access'][i].checked) {
 7325:                 curraccess = document.$formname.elements[role+'_access'][i].value;
 7326:             }
 7327:         }
 7328:     }
 7329:     var shown = Array();
 7330:     var hidden = Array();
 7331:     if (curraccess == 'none') {
 7332:         hidden = Array ('$hiddenstr'); 
 7333:     } else {
 7334:         if (curraccess == 'status') {
 7335:             shown = Array ('bystatus','privs'); 
 7336:             hidden = Array ('notinc','notexc');    
 7337:         } else {
 7338:             if (curraccess == 'exc') {
 7339:                 shown = Array ('notexc','privs');
 7340:                 hidden = Array ('notinc','bystatus');
 7341:             }
 7342:             if (curraccess == 'inc') {
 7343:                 shown = Array ('notinc','privs');
 7344:                 hidden = Array ('notexc','bystatus');
 7345:             }
 7346:             if (curraccess == 'all') {
 7347:                 shown = Array ('privs');
 7348:                 hidden = Array ('notinc','notexc','bystatus');
 7349:             }
 7350:         }
 7351:     }
 7352:     if (hidden.length > 0) {
 7353:         for (var i=0; i<hidden.length; i++) {
 7354:             if (document.getElementById(role+'_'+hidden[i])) {
 7355:                 document.getElementById(role+'_'+hidden[i]).style.display = 'none'; 
 7356:             }
 7357:         }
 7358:     }
 7359:     if (shown.length > 0) {
 7360:         for (var i=0; i<shown.length; i++) {
 7361:             if (document.getElementById(role+'_'+shown[i])) {
 7362:                 if (shown[i] == 'privs') {
 7363:                     document.getElementById(role+'_'+shown[i]).style.display = 'block';
 7364:                 } else {
 7365:                     document.getElementById(role+'_'+shown[i]).style.display = 'inline';
 7366:                 }
 7367:             }
 7368:         }
 7369:     }
 7370:     return;
 7371: }
 7372: 
 7373: function toggleAccess(role) {
 7374:     if ((document.getElementById(role+'_setincrs')) &&
 7375:         (document.getElementById(role+'_setindom'))) {
 7376:         for (var i=0; i<document.$formname.elements[role+'_incrs'].length; i++) {
 7377:             if (document.$formname.elements[role+'_incrs'][i].checked) {
 7378:                 if (document.$formname.elements[role+'_incrs'][i].value == 1) {
 7379:                     document.getElementById(role+'_setindom').style.display = 'none';
 7380:                     document.getElementById(role+'_setincrs').style.display = 'block'; 
 7381:                 } else {
 7382:                     document.getElementById(role+'_setincrs').style.display = 'none';
 7383:                     document.getElementById(role+'_setindom').style.display = 'block';
 7384:                 }
 7385:                 break;
 7386:             }
 7387:         }
 7388:     }
 7389:     return;
 7390: }
 7391: 
 7392: // ]]>
 7393: </script>
 7394: ENDJS
 7395: 
 7396:     $args->{add_entries} = {onload => "javascript:setFormElements(document.$formname)"};
 7397: 
 7398:     # print page header
 7399:     $r->print(&header($js,$args));
 7400:     # print form header
 7401:     $r->print('<form action="/adm/createuser" method="post" name="'.$formname.'">');
 7402: 
 7403:     if (keys(%customroles)) {
 7404:         my %lt = &Apache::lonlocal::texthash(
 7405:                     'aco'    => 'As course owner you may override the defaults set in the domain for role usage and/or privileges.',
 7406:                     'rou'    => 'Role usage',
 7407:                     'whi'    => 'Which helpdesk personnel may use this role?',
 7408:                     'udd'    => 'Use domain default',
 7409:                     'all'    => 'All',
 7410:                     'none'   => 'None',
 7411:                     'status' => 'Determined based on institutional status',
 7412:                     'inc'    => 'Include all, but exclude specific personnel',  
 7413:                     'exc'    => 'Exclude all, but include specific personnel',
 7414:                     'hel'    => 'Helpdesk',
 7415:                     'rpr'    => 'Role privileges',
 7416:                  );
 7417:         $lt{'tfh'} = &mt("Custom [_1]ad hoc[_2] course roles available for use by the domain's helpdesk are as follows",'<i>','</i>');
 7418:         my %domconfig = &Apache::lonnet::get_dom('configuration',['helpsettings'],$cdom);
 7419:         my (%domcurrent,%ordered,%description,%domusage,$disabled);
 7420:         if (ref($domconfig{'helpsettings'}) eq 'HASH') {
 7421:             if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
 7422:                 %domcurrent = %{$domconfig{'helpsettings'}{'adhoc'}};
 7423:             }
 7424:         }
 7425:         my $count = 0;
 7426:         foreach my $role (sort(keys(%customroles))) {
 7427:             my ($order,$desc,$access_in_dom);
 7428:             if (ref($domcurrent{$role}) eq 'HASH') {
 7429:                 $order = $domcurrent{$role}{'order'};
 7430:                 $desc = $domcurrent{$role}{'desc'};
 7431:                 $access_in_dom = $domcurrent{$role}{'access'};
 7432:             }
 7433:             if ($order eq '') {
 7434:                 $order = $count;
 7435:             }
 7436:             $ordered{$order} = $role;
 7437:             if ($desc ne '') {
 7438:                 $description{$role} = $desc;
 7439:             } else {
 7440:                 $description{$role}= $role;
 7441:             }
 7442:             $count++;
 7443:         }
 7444:         %domusage = &domain_adhoc_access(\%customroles,\%domcurrent,\@accesstypes,$usertypes,$othertitle);
 7445:         my @roles_by_num = ();
 7446:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 7447:             push(@roles_by_num,$ordered{$item});
 7448:         } 
 7449:         $r->print('<p>'.$lt{'tfh'}.': <i>'.join('</i>, <i>',map { $description{$_}; } @roles_by_num).'</i>.');
 7450:         if ($permission->{'owner'}) {
 7451:             $r->print('<br />'.$lt{'aco'}.'</p><p>');
 7452:             $r->print('<input type="hidden" name="state" value="process" />'.
 7453:                       '<input type="submit" value="'.&mt('Save changes').'" />');
 7454:         } else {
 7455:             if ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'}) {
 7456:                 my ($ownername,$ownerdom) = split(/:/,$env{'course.'.$env{'request.course.id'}.'.internal.courseowner'});
 7457:                 $r->print('<br />'.&mt('The course owner -- [_1] -- can override the default access and/or privileges for these ad hoc roles.',
 7458:                                     &Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($ownername,$ownerdom),$ownername,$ownerdom)));
 7459:             }
 7460:             $disabled = ' disabled="disabled"';
 7461:         }
 7462:         $r->print('</p>');
 7463: 
 7464:         $r->print('<div id="LC_minitab_header"><ul>');
 7465:         my $count = 0;
 7466:         my %visibility;
 7467:         foreach my $role (@roles_by_num) {
 7468:             my $id;
 7469:             if ($count == 0) {
 7470:                 $id=' id="LC_current_minitab"';
 7471:                 $visibility{$role} = ' style="display:block"';    
 7472:             } else {
 7473:                 $visibility{$role} = ' style="display:none"';
 7474:             }
 7475:             $count ++;
 7476:             $r->print('<li'.$id.'><a href="#" onclick="javascript:switchRoleTab(this.parentNode,'."'$role'".');">'.$description{$role}.'</a></li>');
 7477:         }
 7478:         $r->print('</ul></div>');
 7479: 
 7480:         foreach my $role (@roles_by_num) {
 7481:             my %usecheck = (
 7482:                              all => ' checked="checked"',
 7483:                            );
 7484:             my %displaydiv = (
 7485:                                 status => 'none',
 7486:                                 inc    => 'none',
 7487:                                 exc    => 'none',
 7488:                                 priv   => 'block',
 7489:                              );
 7490:             my (%selected,$overridden,$incrscheck,$indomcheck,$indomvis,$incrsvis);
 7491:             if (ref($settings{$role}) eq 'HASH') { 
 7492:                 if ($settings{$role}{'access'} ne '') {
 7493:                     $indomvis = ' style="display:none"';
 7494:                     $incrsvis = ' style="display:block"';
 7495:                     $incrscheck = ' checked="checked"'; 
 7496:                     if ($settings{$role}{'access'} ne 'all') {
 7497:                         $usecheck{$settings{$role}{'access'}} = $usecheck{'all'};
 7498:                         delete($usecheck{'all'});
 7499:                         if ($settings{$role}{'access'} eq 'status') {
 7500:                             my $access = 'status';
 7501:                             $displaydiv{$access} = 'inline';
 7502:                             if (ref($settings{$role}{$access}) eq 'ARRAY') {
 7503:                                 $selected{$access} = $settings{$role}{$access};
 7504:                             }
 7505:                         } elsif ($settings{$role}{'access'} =~ /^(inc|exc)$/) {
 7506:                             my $access = $1;
 7507:                             $displaydiv{$access} = 'inline';
 7508:                             if (ref($settings{$role}{$access}) eq 'ARRAY') {
 7509:                                 $selected{$access} = $settings{$role}{$access};
 7510:                             }
 7511:                         } elsif ($settings{$role}{'access'} eq 'none') {
 7512:                             $displaydiv{'priv'} = 'none';
 7513:                         }
 7514:                     }
 7515:                 } else {
 7516:                     $indomcheck = ' checked="checked"';
 7517:                     $indomvis = ' style="display:block"';
 7518:                     $incrsvis = ' style="display:none"';
 7519:                 }
 7520:             } else {
 7521:                 $indomcheck = ' checked="checked"';
 7522:                 $indomvis = ' style="display:block"'; 
 7523:                 $incrsvis = ' style="display:none"';
 7524:             }
 7525:             $r->print('<div class="LC_left_float" id="'.$role.'_maindiv"'.$visibility{$role}.'>'.
 7526:                       '<fieldset><legend>'.$lt{'rou'}.'</legend>'.
 7527:                       '<p>'.$lt{'whi'}.' <span class="LC_nobreak">'.
 7528:                       '<label><input type="radio" name="'.$role.'_incrs" value="1"'.$incrscheck.' onclick="toggleAccess('."'$role'".');"'.$disabled.'>'.
 7529:                       &mt('Set here in [_1]',lc($crstype)).'</label>'.
 7530:                       '<span>'.('&nbsp;'x2).
 7531:                       '<label><input type="radio" name="'.$role.'_incrs" value="0"'.$indomcheck.' onclick="toggleAccess('."'$role'".');"'.$disabled.'>'.
 7532:                       $lt{'udd'}.'</label><span></p>'.
 7533:                       '<div id="'.$role.'_setindom"'.$indomvis.'>'.
 7534:                       '<span class="LC_cusr_emph">'.$domusage{$role}.'</span></div>'.
 7535:                       '<div id="'.$role.'_setincrs"'.$incrsvis.'>');
 7536:             foreach my $access (@accesstypes) {
 7537:                 $r->print('<p><label><input type="radio" name="'.$role.'_access" value="'.$access.'" '.$usecheck{$access}.
 7538:                           ' onclick="helpdeskAccess('."'$role'".');"'.$disabled.' />'.$lt{$access}.'</label>');
 7539:                 if ($access eq 'status') {
 7540:                     $r->print('<div id="'.$role.'_bystatus" style="display:'.$displaydiv{$access}.'">'.
 7541:                               &Apache::lonuserutils::adhoc_status_types($cdom,undef,$role,$selected{$access},
 7542:                                                                         $othertitle,$usertypes,$types,$disabled).
 7543:                               '</div>');
 7544:                 } elsif (($access eq 'inc') && (keys(%domhelpdesk) > 0)) {
 7545:                     $r->print('<div id="'.$role.'_notinc" style="display:'.$displaydiv{$access}.'">'.
 7546:                               &Apache::lonuserutils::adhoc_staff($access,undef,$role,$selected{$access},
 7547:                                                                  \%domhelpdesk,$disabled).
 7548:                               '</div>');
 7549:                 } elsif (($access eq 'exc') && (keys(%domhelpdesk) > 0)) {
 7550:                     $r->print('<div id="'.$role.'_notexc" style="display:'.$displaydiv{$access}.'">'.
 7551:                               &Apache::lonuserutils::adhoc_staff($access,undef,$role,$selected{$access},
 7552:                                                                  \%domhelpdesk,$disabled).
 7553:                               '</div>');
 7554:                 }
 7555:                 $r->print('</p>');
 7556:             }
 7557:             $r->print('</div></fieldset>');
 7558:             my %full=();
 7559:             my %levels= (
 7560:                          course => {},
 7561:                          domain => {},
 7562:                          system => {},
 7563:                         );
 7564:             my %levelscurrent=(
 7565:                                course => {},
 7566:                                domain => {},
 7567:                                system => {},
 7568:                               );
 7569:             &Apache::lonuserutils::custom_role_privs($customroles{$role},\%full,\%levels,\%levelscurrent);
 7570:             $r->print('<fieldset id="'.$role.'_privs" style="display:'.$displaydiv{'priv'}.'">'.
 7571:                       '<legend>'.$lt{'rpr'}.'</legend>'.
 7572:                       &role_priv_table($role,$permission,$crstype,\%full,\%levels,\%levelscurrent,$overridden{$role}).
 7573:                       '</fieldset></div><div style="padding:0;clear:both;margin:0;border:0"></div>');
 7574:         }
 7575:         if ($permission->{'owner'}) {
 7576:             $r->print('<p><input type="submit" value="'.&mt('Save changes').'" /></p>');
 7577:         }
 7578:     } else {
 7579:         $r->print(&mt('Helpdesk roles have not yet been created in this domain.'));
 7580:     }
 7581:     # Form Footer
 7582:     $r->print('<input type="hidden" name="action" value="helpdesk" />'
 7583:              .'</form>');
 7584:     return;
 7585: }
 7586: 
 7587: sub domain_adhoc_access {
 7588:     my ($roles,$domcurrent,$accesstypes,$usertypes,$othertitle) = @_;
 7589:     my %domusage;
 7590:     return unless ((ref($roles) eq 'HASH') && (ref($domcurrent) eq 'HASH') && (ref($accesstypes) eq 'ARRAY'));
 7591:     foreach my $role (keys(%{$roles})) {
 7592:         if (ref($domcurrent->{$role}) eq 'HASH') {
 7593:             my $access = $domcurrent->{$role}{'access'};
 7594:             if (($access eq '') || (!grep(/^\Q$access\E$/,@{$accesstypes}))) {
 7595:                 $access = 'all';
 7596:                 $domusage{$role} = &mt('Any user in domain with active [_1] role',&Apache::lonnet::plaintext('dh'));
 7597:             } elsif ($access eq 'status') {
 7598:                 if (ref($domcurrent->{$role}{$access}) eq 'ARRAY') {
 7599:                     my @shown;
 7600:                     foreach my $type (@{$domcurrent->{$role}{$access}}) {
 7601:                         unless ($type eq 'default') {
 7602:                             if ($usertypes->{$type}) {
 7603:                                 push(@shown,$usertypes->{$type});
 7604:                             }
 7605:                         }
 7606:                     }
 7607:                     if (grep(/^default$/,@{$domcurrent->{$role}{$access}})) {
 7608:                         push(@shown,$othertitle);
 7609:                     }
 7610:                     if (@shown) {
 7611:                         my $shownstatus = join(' '.&mt('or').' ',@shown);
 7612:                         $domusage{$role} = &mt('Any user in domain with active [_1] role, and institutional status: [_2]',
 7613:                                                &Apache::lonnet::plaintext('dh'),$shownstatus);
 7614:                     } else {
 7615:                         $domusage{$role} = &mt('No one in the domain');
 7616:                     }
 7617:                 }
 7618:             } elsif ($access eq 'inc') {
 7619:                 my @dominc = ();
 7620:                 if (ref($domcurrent->{$role}{'inc'}) eq 'ARRAY') {
 7621:                     foreach my $user (@{$domcurrent->{$role}{'inc'}}) {
 7622:                         my ($uname,$udom) = split(/:/,$user);
 7623:                         push(@dominc,&Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($uname,$udom),$uname,$udom));
 7624:                     }
 7625:                     my $showninc = join(', ',@dominc);
 7626:                     if ($showninc ne '') {
 7627:                         $domusage{$role} = &mt('Include any user in domain with active [_1] role, except: [_2]',
 7628:                                                &Apache::lonnet::plaintext('dh'),$showninc);
 7629:                     } else {
 7630:                         $domusage{$role} = &mt('Any user in domain with active [_1] role',&Apache::lonnet::plaintext('dh'));
 7631:                     }
 7632:                 }
 7633:             } elsif ($access eq 'exc') {
 7634:                 my @domexc = ();
 7635:                 if (ref($domcurrent->{$role}{'exc'}) eq 'ARRAY') {
 7636:                     foreach my $user (@{$domcurrent->{$role}{'exc'}}) {
 7637:                         my ($uname,$udom) = split(/:/,$user);
 7638:                         push(@domexc,&Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($uname,$udom),$uname,$udom));
 7639:                     }
 7640:                 }
 7641:                 my $shownexc = join(', ',@domexc);
 7642:                 if ($shownexc ne '') {
 7643:                     $domusage{$role} = &mt('Only the following in the domain with active [_1] role: [_2]',
 7644:                                            &Apache::lonnet::plaintext('dh'),$shownexc);
 7645:                 } else {
 7646:                     $domusage{$role} = &mt('No one in the domain');
 7647:                 }
 7648:             } elsif ($access eq 'none') {
 7649:                 $domusage{$role} = &mt('No one in the domain');
 7650:             } elsif ($access eq 'all') {
 7651:                 $domusage{$role} = &mt('Any user in domain with active [_1] role',&Apache::lonnet::plaintext('dh'));
 7652:             }
 7653:         } else {
 7654:             $domusage{$role} = &mt('Any user in domain with active [_1] role',&Apache::lonnet::plaintext('dh'));
 7655:         }
 7656:     }
 7657:     return %domusage;
 7658: }
 7659: 
 7660: sub get_domain_customroles {
 7661:     my ($cdom,$confname) = @_;
 7662:     my %existing=&Apache::lonnet::dump('roles',$cdom,$confname,'rolesdef_');
 7663:     my %customroles;
 7664:     foreach my $key (keys(%existing)) {
 7665:         if ($key=~/^rolesdef\_(\w+)$/) {
 7666:             my $rolename = $1;
 7667:             my %privs;
 7668:             ($privs{'system'},$privs{'domain'},$privs{'course'}) = split(/\_/,$existing{$key});
 7669:             $customroles{$rolename} = \%privs;
 7670:         }
 7671:     }
 7672:     return %customroles;
 7673: }
 7674: 
 7675: sub role_priv_table {
 7676:     my ($role,$permission,$crstype,$full,$levels,$levelscurrent,$overridden) = @_;
 7677:     return unless ((ref($full) eq 'HASH') && (ref($levels) eq 'HASH') &&
 7678:                    (ref($levelscurrent) eq 'HASH'));
 7679:     my %lt=&Apache::lonlocal::texthash (
 7680:                     'crl'  => 'Course Level Privilege',
 7681:                     'def'  => 'Domain Defaults',
 7682:                     'ove'  => 'Override in Course',
 7683:                     'ine'  => 'In effect',
 7684:                     'dis'  => 'Disabled',
 7685:                     'ena'  => 'Enabled',
 7686:                    );
 7687:     if ($crstype eq 'Community') {
 7688:         $lt{'ove'} = 'Override in Community',
 7689:     }
 7690:     my @status = ('Disabled','Enabled');
 7691:     my (%on,%off);
 7692:     if (ref($overridden) eq 'HASH') {
 7693:         if (ref($overridden->{'on'}) eq 'ARRAY') {
 7694:             map { $on{$_} = 1; } (@{$overridden->{'on'}});
 7695:         }
 7696:         if (ref($overridden->{'off'}) eq 'ARRAY') {
 7697:             map { $off{$_} = 1; } (@{$overridden->{'off'}});
 7698:         }
 7699:     }
 7700:     my $output=&Apache::loncommon::start_data_table().
 7701:                &Apache::loncommon::start_data_table_header_row().
 7702:                '<th>'.$lt{'crl'}.'</th><th>'.$lt{'def'}.'</th><th>'.$lt{'ove'}.
 7703:                '</th><th>'.$lt{'ine'}.'</th>'.
 7704:                &Apache::loncommon::end_data_table_header_row();
 7705:     foreach my $priv (sort(keys(%{$full}))) {
 7706:         next unless ($levels->{'course'}{$priv});
 7707:         my $privtext = &Apache::lonnet::plaintext($priv,$crstype);
 7708:         my ($default,$ineffect);
 7709:         if ($levelscurrent->{'course'}{$priv}) {
 7710:             $default = '<img src="/adm/lonIcons/navmap.correct.gif" alt="'.$lt{'ena'}.'" />';
 7711:             $ineffect = $default;
 7712:         }
 7713:         my ($customstatus,$checked);
 7714:         $output .= &Apache::loncommon::start_data_table_row().
 7715:                    '<td>'.$privtext.'</td>'.
 7716:                    '<td>'.$default.'</td><td>';
 7717:         if (($levelscurrent->{'course'}{$priv}) && ($off{$priv})) {
 7718:             if ($permission->{'owner'}) {
 7719:                 $checked = ' checked="checked"';
 7720:             }
 7721:             $customstatus = '<img src="/adm/lonIcons/navmap.wrong.gif" alt="'.$lt{'dis'}.'" />';
 7722:             $ineffect = $customstatus; 
 7723:         } elsif ((!$levelscurrent->{'course'}{$priv}) && ($on{$priv})) {
 7724:             if ($permission->{'owner'}) {
 7725:                 $checked = ' checked="checked"'; 
 7726:             }
 7727:             $customstatus = '<img src="/adm/lonIcons/navmap.correct.gif" alt="'.$lt{'ena'}.'" />';
 7728:             $ineffect = $customstatus; 
 7729:         }
 7730:         if ($permission->{'owner'}) {
 7731:             $output .= '<input type="checkbox" name="'.$role.'_override" value="'.$priv.'"'.$checked.' />';
 7732:         } else {
 7733:             $output .= $customstatus;
 7734:         }
 7735:         $output .= '</td><td>'.$ineffect.'</td>'.
 7736:                    &Apache::loncommon::end_data_table_row();
 7737:     }
 7738:     $output .= &Apache::loncommon::end_data_table();
 7739:     return $output;
 7740: }
 7741: 
 7742: sub get_adhocrole_settings {
 7743:     my ($cid,$accesstypes,$types,$customroles,$settings,$overridden) = @_;  
 7744:     return unless ((ref($accesstypes) eq 'ARRAY') && (ref($customroles) eq 'HASH') &&
 7745:                    (ref($settings) eq 'HASH') && (ref($overridden) eq 'HASH'));
 7746:     foreach my $role (split(/,/,$env{'course.'.$cid.'.internal.adhocaccess'})) {
 7747:         my ($curraccess,$rest) = split(/=/,$env{'course.'.$cid.'.internal.adhoc.'.$role});
 7748:         if (($curraccess ne '') && (grep(/^\Q$curraccess\E$/,@{$accesstypes}))) {
 7749:             $settings->{$role}{'access'} = $curraccess;
 7750:             if (($curraccess eq 'status') && (ref($types) eq 'ARRAY')) {
 7751:                 my @status = split(/,/,$rest);
 7752:                 my @currstatus;
 7753:                 foreach my $type (@status) {
 7754:                     if ($type eq 'default') {
 7755:                         push(@currstatus,$type);
 7756:                     } elsif (grep(/^\Q$type\E$/,@{$types})) {
 7757:                         push(@currstatus,$type);
 7758:                     }
 7759:                 }
 7760:                 if (@currstatus) {
 7761:                     $settings->{$role}{$curraccess} = \@currstatus;
 7762:                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 7763:                     my @personnel = split(/,/,$rest);
 7764:                     $settings->{$role}{$curraccess} = \@personnel;
 7765:                 }
 7766:             }
 7767:         }
 7768:     }
 7769:     foreach my $role (keys(%{$customroles})) {
 7770:         if ($env{'course.'.$cid.'.internal.adhocpriv.'.$role}) {
 7771:             my %currentprivs;
 7772:             if (ref($customroles->{$role}) eq 'HASH') {
 7773:                 if (exists($customroles->{$role}{'course'})) {
 7774:                     my %full=();
 7775:                     my %levels= (
 7776:                                   course => {},
 7777:                                   domain => {},
 7778:                                   system => {},
 7779:                                 );
 7780:                     my %levelscurrent=(
 7781:                                         course => {},
 7782:                                         domain => {},
 7783:                                         system => {},
 7784:                                       );
 7785:                     &Apache::lonuserutils::custom_role_privs($customroles->{$role},\%full,\%levels,\%levelscurrent);
 7786:                     %currentprivs = %{$levelscurrent{'course'}};
 7787:                 }
 7788:             }
 7789:             foreach my $item (split(/,/,$env{'course.'.$cid.'.internal.adhocpriv.'.$role})) {
 7790:                 next if ($item eq '');
 7791:                 my ($rule,$rest) = split(/=/,$item);
 7792:                 next unless (($rule eq 'off') || ($rule eq 'on'));
 7793:                 foreach my $priv (split(/:/,$rest)) {
 7794:                     if ($priv ne '') {
 7795:                         if ($rule eq 'off') {
 7796:                             push(@{$overridden->{$role}{'off'}},$priv);
 7797:                             if ($currentprivs{$priv}) {
 7798:                                 push(@{$settings->{$role}{'off'}},$priv);
 7799:                             }
 7800:                         } else {
 7801:                             push(@{$overridden->{$role}{'on'}},$priv);
 7802:                             unless ($currentprivs{$priv}) {
 7803:                                 push(@{$settings->{$role}{'on'}},$priv);
 7804:                             }
 7805:                         }
 7806:                     }
 7807:                 }
 7808:             }
 7809:         }
 7810:     }
 7811:     return;
 7812: }
 7813: 
 7814: sub update_helpdeskaccess {
 7815:     my ($r,$permission,$brcrum) = @_;
 7816:     my $helpitem = 'Course_Helpdesk_Access';
 7817:     push (@{$brcrum},
 7818:              {href => '/adm/createuser?action=helpdesk',
 7819:               text => 'Helpdesk Access',
 7820:               help => $helpitem},
 7821:              {href => '/adm/createuser?action=helpdesk',
 7822:               text => 'Result',
 7823:               help => $helpitem}
 7824:          );
 7825:     my $bread_crumbs_component = 'Helpdesk Staff Access';
 7826:     my $args = { bread_crumbs           => $brcrum,
 7827:                  bread_crumbs_component => $bread_crumbs_component};
 7828: 
 7829:     # print page header
 7830:     $r->print(&header('',$args));
 7831:     unless ((ref($permission) eq 'HASH') && ($permission->{'owner'})) {
 7832:         $r->print('<p class="LC_error">'.&mt('You do not have permission to change helpdesk access.').'</p>');
 7833:         return;
 7834:     }
 7835:     my @accesstypes = ('all','none','status','inc','exc');
 7836:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7837:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7838:     my $confname = $cdom.'-domainconfig';
 7839:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($cdom);
 7840:     my $crstype = &Apache::loncommon::course_type();
 7841:     my %customroles = &get_domain_customroles($cdom,$confname);
 7842:     my (%settings,%overridden);
 7843:     &get_adhocrole_settings($env{'request.course.id'},\@accesstypes,
 7844:                             $types,\%customroles,\%settings,\%overridden);
 7845:     my %domhelpdesk = &Apache::lonnet::get_active_domroles($cdom,['dh']);
 7846:     my (%changed,%storehash,@todelete);
 7847: 
 7848:     if (keys(%customroles)) {
 7849:         my (%newsettings,@incrs);
 7850:         foreach my $role (keys(%customroles)) {
 7851:             $newsettings{$role} = {
 7852:                                     access => '',
 7853:                                     status => '',
 7854:                                     exc    => '',
 7855:                                     inc    => '',
 7856:                                     on     => '',
 7857:                                     off    => '',
 7858:                                   };
 7859:             my %current;
 7860:             if (ref($settings{$role}) eq 'HASH') {
 7861:                 %current = %{$settings{$role}};
 7862:             }
 7863:             if (ref($overridden{$role}) eq 'HASH') {
 7864:                 $current{'overridden'} = $overridden{$role};
 7865:             }
 7866:             if ($env{'form.'.$role.'_incrs'}) {
 7867:                 my $access = $env{'form.'.$role.'_access'};
 7868:                 if (grep(/^\Q$access\E$/,@accesstypes)) {
 7869:                     push(@incrs,$role);
 7870:                     unless ($current{'access'} eq $access) {
 7871:                         $changed{$role}{'access'} = 1;
 7872:                         $storehash{'internal.adhoc.'.$role} = $access; 
 7873:                     }
 7874:                     if ($access eq 'status') {
 7875:                         my @statuses = &Apache::loncommon::get_env_multiple('form.'.$role.'_status');
 7876:                         my @stored;
 7877:                         my @shownstatus;
 7878:                         if (ref($types) eq 'ARRAY') {
 7879:                             foreach my $type (sort(@statuses)) {
 7880:                                 if ($type eq 'default') {
 7881:                                     push(@stored,$type);
 7882:                                 } elsif (grep(/^\Q$type\E$/,@{$types})) {
 7883:                                     push(@stored,$type);
 7884:                                     push(@shownstatus,$usertypes->{$type});
 7885:                                 }
 7886:                             }
 7887:                             if (grep(/^default$/,@statuses)) {
 7888:                                 push(@shownstatus,$othertitle);
 7889:                             }
 7890:                             $storehash{'internal.adhoc.'.$role} .= '='.join(',',@stored);
 7891:                         }
 7892:                         $newsettings{$role}{'status'} = join(' '.&mt('or').' ',@shownstatus);
 7893:                         if (ref($current{'status'}) eq 'ARRAY') {
 7894:                             my @diffs = &Apache::loncommon::compare_arrays(\@stored,$current{'status'});
 7895:                             if (@diffs) {
 7896:                                 $changed{$role}{'status'} = 1;
 7897:                             }
 7898:                         } elsif (@stored) {
 7899:                             $changed{$role}{'status'} = 1;
 7900:                         }
 7901:                     } elsif (($access eq 'inc') || ($access eq 'exc')) {
 7902:                         my @personnel = &Apache::loncommon::get_env_multiple('form.'.$role.'_staff_'.$access);
 7903:                         my @newspecstaff;
 7904:                         my @stored;
 7905:                         my @currstaff;
 7906:                         foreach my $person (sort(@personnel)) {
 7907:                             if ($domhelpdesk{$person}) {
 7908:                                 push(@stored,$person); 
 7909:                             }
 7910:                         }
 7911:                         if (ref($current{$access}) eq 'ARRAY') {
 7912:                             my @diffs = &Apache::loncommon::compare_arrays(\@stored,$current{$access});
 7913:                             if (@diffs) {
 7914:                                 $changed{$role}{$access} = 1;
 7915:                             }
 7916:                         } elsif (@stored) {
 7917:                             $changed{$role}{$access} = 1;
 7918:                         }
 7919:                         $storehash{'internal.adhoc.'.$role} .= '='.join(',',@stored);
 7920:                         foreach my $person (@stored) {
 7921:                             my ($uname,$udom) = split(/:/,$person);
 7922:                             push(@newspecstaff,&Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($uname,$udom,'lastname'),$uname,$udom));
 7923:                         }
 7924:                         $newsettings{$role}{$access} = join(', ',sort(@newspecstaff));
 7925:                     }
 7926:                     $newsettings{$role}{'access'} = $access;
 7927:                 }
 7928:             } else {
 7929:                 if (($current{'access'} ne '') && (grep(/^\Q$current{'access'}\E$/,@accesstypes))) {
 7930:                     $changed{$role}{'access'} = 1;
 7931:                     $newsettings{$role} = {};
 7932:                     push(@todelete,'internal.adhoc.'.$role);
 7933:                 }
 7934:             }
 7935:             if (($env{'form.'.$role.'_incrs'}) && ($env{'form.'.$role.'_access'} eq 'none')) {
 7936:                 if (ref($current{'overridden'}) eq 'HASH') {
 7937:                     push(@todelete,'internal.adhocpriv.'.$role);
 7938:                 }
 7939:             } else {
 7940:                 my %full=();
 7941:                 my %levels= (
 7942:                              course => {},
 7943:                              domain => {},
 7944:                              system => {},
 7945:                             );
 7946:                 my %levelscurrent=(
 7947:                                    course => {},
 7948:                                    domain => {},
 7949:                                    system => {},
 7950:                                   );
 7951:                 &Apache::lonuserutils::custom_role_privs($customroles{$role},\%full,\%levels,\%levelscurrent);
 7952:                 my (@updatedon,@updatedoff,@override);
 7953:                 @override = &Apache::loncommon::get_env_multiple('form.'.$role.'_override');
 7954:                 if (@override) { 
 7955:                     foreach my $priv (sort(keys(%full))) {
 7956:                         next unless ($levels{'course'}{$priv});
 7957:                         if (grep(/^\Q$priv\E$/,@override)) {
 7958:                             if ($levelscurrent{'course'}{$priv}) {
 7959:                                 push(@updatedoff,$priv);
 7960:                             } else {
 7961:                                 push(@updatedon,$priv);
 7962:                             }
 7963:                         }
 7964:                     }
 7965:                 }
 7966:                 if (@updatedon) {
 7967:                     $newsettings{$role}{'on'} = join('</li><li>', map { &Apache::lonnet::plaintext($_,$crstype) } (@updatedon)); 
 7968:                 }
 7969:                 if (@updatedoff) {
 7970:                     $newsettings{$role}{'off'} = join('</li><li>', map { &Apache::lonnet::plaintext($_,$crstype) } (@updatedoff));
 7971:                 }
 7972:                 if (ref($current{'overridden'}) eq 'HASH') {
 7973:                     if (ref($current{'overridden'}{'on'}) eq 'ARRAY') {
 7974:                         if (@updatedon) {
 7975:                             my @diffs = &Apache::loncommon::compare_arrays(\@updatedon,$current{'overridden'}{'on'});
 7976:                             if (@diffs) {
 7977:                                 $changed{$role}{'on'} = 1;
 7978:                             }
 7979:                         } else {
 7980:                             $changed{$role}{'on'} = 1;
 7981:                         }
 7982:                     } elsif (@updatedon) {
 7983:                         $changed{$role}{'on'} = 1;
 7984:                     }
 7985:                     if (ref($current{'overridden'}{'off'}) eq 'ARRAY') {
 7986:                         if (@updatedoff) {
 7987:                             my @diffs = &Apache::loncommon::compare_arrays(\@updatedoff,$current{'overridden'}{'off'});
 7988:                             if (@diffs) {
 7989:                                 $changed{$role}{'off'} = 1;
 7990:                             }
 7991:                         } else {
 7992:                             $changed{$role}{'off'} = 1;
 7993:                         }
 7994:                     } elsif (@updatedoff) {
 7995:                         $changed{$role}{'off'} = 1;
 7996:                     }
 7997:                 } else {
 7998:                     if (@updatedon) {
 7999:                         $changed{$role}{'on'} = 1;
 8000:                     }
 8001:                     if (@updatedoff) {
 8002:                         $changed{$role}{'off'} = 1;
 8003:                     }
 8004:                 }
 8005:                 if (ref($changed{$role}) eq 'HASH') {
 8006:                     if (($changed{$role}{'on'} || $changed{$role}{'off'})) {
 8007:                         my $newpriv;
 8008:                         if (@updatedon) {
 8009:                             $newpriv = 'on='.join(':',@updatedon);
 8010:                         }
 8011:                         if (@updatedoff) {
 8012:                             $newpriv .= ($newpriv ? ',' : '' ).'off='.join(':',@updatedoff);
 8013:                         }
 8014:                         if ($newpriv eq '') {
 8015:                             push(@todelete,'internal.adhocpriv.'.$role);
 8016:                         } else {
 8017:                             $storehash{'internal.adhocpriv.'.$role} = $newpriv;
 8018:                         }
 8019:                     }
 8020:                 }
 8021:             }
 8022:         }
 8023:         if (@incrs) {
 8024:             $storehash{'internal.adhocaccess'} = join(',',@incrs);
 8025:         } elsif (@todelete) {
 8026:             push(@todelete,'internal.adhocaccess');
 8027:         }
 8028:         if (keys(%changed)) {
 8029:             my ($putres,$delres);
 8030:             if (keys(%storehash)) {
 8031:                 $putres = &Apache::lonnet::put('environment',\%storehash,$cdom,$cnum);
 8032:                 my %newenvhash;
 8033:                 foreach my $key (keys(%storehash)) {
 8034:                     $newenvhash{'course.'.$env{'request.course.id'}.'.'.$key} = $storehash{$key};
 8035:                 }
 8036:                 &Apache::lonnet::appenv(\%newenvhash);
 8037:             }
 8038:             if (@todelete) {
 8039:                 $delres = &Apache::lonnet::del('environment',\@todelete,$cdom,$cnum);
 8040:                 foreach my $key (@todelete) {
 8041:                     &Apache::lonnet::delenv('course.'.$env{'request.course.id'}.'.'.$key);
 8042:                 }
 8043:             }
 8044:             if (($putres eq 'ok') || ($delres eq 'ok')) {
 8045:                 my %domconfig = &Apache::lonnet::get_dom('configuration',['helpsettings'],$cdom);
 8046:                 my (%domcurrent,%ordered,%description,%domusage);
 8047:                 if (ref($domconfig{'helpsettings'}) eq 'HASH') {
 8048:                     if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
 8049:                         %domcurrent = %{$domconfig{'helpsettings'}{'adhoc'}};
 8050:                     }
 8051:                 }
 8052:                 my $count = 0;
 8053:                 foreach my $role (sort(keys(%customroles))) {
 8054:                     my ($order,$desc);
 8055:                     if (ref($domcurrent{$role}) eq 'HASH') {
 8056:                         $order = $domcurrent{$role}{'order'};
 8057:                         $desc = $domcurrent{$role}{'desc'};
 8058:                     }
 8059:                     if ($order eq '') {
 8060:                         $order = $count;
 8061:                     }
 8062:                     $ordered{$order} = $role;
 8063:                     if ($desc ne '') {
 8064:                         $description{$role} = $desc;
 8065:                     } else {
 8066:                         $description{$role}= $role;
 8067:                     }
 8068:                     $count++;
 8069:                 }
 8070:                 my @roles_by_num = ();
 8071:                 foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 8072:                     push(@roles_by_num,$ordered{$item});
 8073:                 }
 8074:                 %domusage = &domain_adhoc_access(\%changed,\%domcurrent,\@accesstypes,$usertypes,$othertitle);
 8075:                 $r->print(&mt('Helpdesk access settings have been changed as follows').'<br />'); 
 8076:                 $r->print('<ul>');
 8077:                 foreach my $role (@roles_by_num) {
 8078:                     next unless (ref($changed{$role}) eq 'HASH');
 8079:                     $r->print('<li>'.&mt('Ad hoc role').': <b>'.$description{$role}.'</b>'.
 8080:                               '<ul>');
 8081:                     if ($changed{$role}{'access'} || $changed{$role}{'status'} || $changed{$role}{'inc'} || $changed{$role}{'exc'}) { 
 8082:                         $r->print('<li>');
 8083:                         if ($env{'form.'.$role.'_incrs'}) {
 8084:                             if ($newsettings{$role}{'access'} eq 'all') {
 8085:                                 $r->print(&mt('All helpdesk staff can access '.lc($crstype).' with this role.'));
 8086:                             } elsif ($newsettings{$role}{'access'} eq 'none') {
 8087:                                 $r->print(&mt('No helpdesk staff can access '.lc($crstype).' with this role.'));
 8088:                             } elsif ($newsettings{$role}{'access'} eq 'status') {
 8089:                                 if ($newsettings{$role}{'status'}) {
 8090:                                     my ($access,$rest) = split(/=/,$storehash{'internal.adhoc.'.$role});
 8091:                                     if (split(/,/,$rest) > 1) {  
 8092:                                         $r->print(&mt('Helpdesk staff can use this role if their institutional type is one of: [_1].',
 8093:                                                       $newsettings{$role}{'status'}));
 8094:                                     } else {
 8095:                                         $r->print(&mt('Helpdesk staff can use this role if their institutional type is: [_1].',
 8096:                                                       $newsettings{$role}{'status'}));
 8097:                                     }
 8098:                                 } else {
 8099:                                     $r->print(&mt('No helpdesk staff can access '.lc($crstype).' with this role.'));
 8100:                                 }
 8101:                             } elsif ($newsettings{$role}{'access'} eq 'exc') {
 8102:                                 if ($newsettings{$role}{'exc'}) {
 8103:                                     $r->print(&mt('Helpdesk staff who can use this role are as follows:').' '.$newsettings{$role}{'exc'}.'.');
 8104:                                 } else {
 8105:                                     $r->print(&mt('No helpdesk staff can access '.lc($crstype).' with this role.'));
 8106:                                 }
 8107:                             } elsif ($newsettings{$role}{'access'} eq 'inc') {
 8108:                                 if ($newsettings{$role}{'inc'}) {
 8109:                                     $r->print(&mt('All helpdesk staff may use this role except the following:').' '.$newsettings{$role}{'inc'}.'.');
 8110:                                 } else {
 8111:                                     $r->print(&mt('All helpdesk staff may use this role.'));
 8112:                                 }
 8113:                             }
 8114:                         } else {
 8115:                             $r->print(&mt('Default access set in the domain now applies.').'<br />'.
 8116:                                       '<span class="LC_cusr_emph">'.$domusage{$role}.'</span>');
 8117:                         }
 8118:                         $r->print('</li>');
 8119:                     }
 8120:                     unless ($newsettings{$role}{'access'} eq 'none') {
 8121:                         if ($changed{$role}{'off'}) {
 8122:                             if ($newsettings{$role}{'off'}) {
 8123:                                 $r->print('<li>'.&mt('Privileges which are available by default for this ad hoc role, but are disabled for this specific '.lc($crstype).':').
 8124:                                           '<ul><li>'.$newsettings{$role}{'off'}.'</li></ul></li>');
 8125:                             } else {
 8126:                                 $r->print('<li>'.&mt('All privileges available by default for this ad hoc role are enabled.').'</li>'); 
 8127:                             }
 8128:                         }
 8129:                         if ($changed{$role}{'on'}) {  
 8130:                             if ($newsettings{$role}{'on'}) {
 8131:                                 $r->print('<li>'.&mt('Privileges which are not available by default for this ad hoc role, but are enabled for this specific '.lc($crstype).':').
 8132:                                           '<ul><li>'.$newsettings{$role}{'on'}.'</li></ul></li>');
 8133:                             } else {
 8134:                                 $r->print('<li>'.&mt('None of the privileges unavailable by default for this ad hoc role are enabled.').'</li>'); 
 8135:                             }
 8136:                         }
 8137:                     }
 8138:                     $r->print('</ul></li>');
 8139:                 }
 8140:                 $r->print('</ul>');
 8141:             }
 8142:         } else {
 8143:             $r->print(&mt('No changes made to helpdesk access settings.')); 
 8144:         }
 8145:     }
 8146:     return;
 8147: }
 8148: 
 8149: #-------------------------------------------------- functions for &phase_two
 8150: sub user_search_result {
 8151:     my ($context,$srch) = @_;
 8152:     my %allhomes;
 8153:     my %inst_matches;
 8154:     my %srch_results;
 8155:     my ($response,$currstate,$forcenewuser,$dirsrchres);
 8156:     $srch->{'srchterm'} =~ s/\s+/ /g;
 8157:     if ($srch->{'srchby'} !~ /^(uname|lastname|lastfirst)$/) {
 8158:         $response = &mt('Invalid search.');
 8159:     }
 8160:     if ($srch->{'srchin'} !~ /^(crs|dom|alc|instd)$/) {
 8161:         $response = &mt('Invalid search.');
 8162:     }
 8163:     if ($srch->{'srchtype'} !~ /^(exact|contains|begins)$/) {
 8164:         $response = &mt('Invalid search.');
 8165:     }
 8166:     if ($srch->{'srchterm'} eq '') {
 8167:         $response = &mt('You must enter a search term.');
 8168:     }
 8169:     if ($srch->{'srchterm'} =~ /^\s+$/) {
 8170:         $response = &mt('Your search term must contain more than just spaces.');
 8171:     }
 8172:     if (($srch->{'srchin'} eq 'dom') || ($srch->{'srchin'} eq 'instd')) {
 8173:         if (($srch->{'srchdomain'} eq '') || 
 8174: 	    ! (&Apache::lonnet::domain($srch->{'srchdomain'}))) {
 8175:             $response = &mt('You must specify a valid domain when searching in a domain or institutional directory.')
 8176:         }
 8177:     }
 8178:     if (($srch->{'srchin'} eq 'dom') || ($srch->{'srchin'} eq 'crs') ||
 8179:         ($srch->{'srchin'} eq 'alc')) {
 8180:         if ($srch->{'srchby'} eq 'uname') {
 8181:             my $unamecheck = $srch->{'srchterm'};
 8182:             if ($srch->{'srchtype'} eq 'contains') {
 8183:                 if ($unamecheck !~ /^\w/) {
 8184:                     $unamecheck = 'a'.$unamecheck; 
 8185:                 }
 8186:             }
 8187:             if ($unamecheck !~ /^$match_username$/) {
 8188:                 $response = &mt('You must specify a valid username. Only the following are allowed: letters numbers - . @');
 8189:             }
 8190:         }
 8191:     }
 8192:     if ($response ne '') {
 8193:         $response = '<span class="LC_warning">'.$response.'</span><br />';
 8194:     }
 8195:     if ($srch->{'srchin'} eq 'instd') {
 8196:         my $instd_chk = &instdirectorysrch_check($srch);
 8197:         if ($instd_chk ne 'ok') {
 8198:             my $domd_chk = &domdirectorysrch_check($srch);
 8199:             $response .= '<span class="LC_warning">'.$instd_chk.'</span><br />';
 8200:             if ($domd_chk eq 'ok') {
 8201:                 $response .= &mt('You may want to search in the LON-CAPA domain instead of the institutional directory.');
 8202:             }
 8203:             $response .= '<br />';
 8204:         }
 8205:     } else {
 8206:         unless (($context eq 'requestcrs') && ($srch->{'srchtype'} eq 'exact')) {
 8207:             my $domd_chk = &domdirectorysrch_check($srch);
 8208:             if ($domd_chk ne 'ok') {
 8209:                 my $instd_chk = &instdirectorysrch_check($srch);
 8210:                 $response .= '<span class="LC_warning">'.$domd_chk.'</span><br />';
 8211:                 if ($instd_chk eq 'ok') {
 8212:                     $response .= &mt('You may want to search in the institutional directory instead of the LON-CAPA domain.');
 8213:                 }
 8214:                 $response .= '<br />';
 8215:             }
 8216:         }
 8217:     }
 8218:     if ($response ne '') {
 8219:         return ($currstate,$response);
 8220:     }
 8221:     if ($srch->{'srchby'} eq 'uname') {
 8222:         if (($srch->{'srchin'} eq 'dom') || ($srch->{'srchin'} eq 'crs')) {
 8223:             if ($env{'form.forcenew'}) {
 8224:                 if ($srch->{'srchdomain'} ne $env{'request.role.domain'}) {
 8225:                     my $uhome=&Apache::lonnet::homeserver($srch->{'srchterm'},$srch->{'srchdomain'});
 8226:                     if ($uhome eq 'no_host') {
 8227:                         my $domdesc = &Apache::lonnet::domain($env{'request.role.domain'},'description');
 8228:                         my $showdom = &display_domain_info($env{'request.role.domain'});
 8229:                         $response = &mt('New users can only be created in the domain to which your current role belongs - [_1].',$showdom);
 8230:                     } else {
 8231:                         $currstate = 'modify';
 8232:                     }
 8233:                 } else {
 8234:                     $currstate = 'modify';
 8235:                 }
 8236:             } else {
 8237:                 if ($srch->{'srchin'} eq 'dom') {
 8238:                     if ($srch->{'srchtype'} eq 'exact') {
 8239:                         my $uhome=&Apache::lonnet::homeserver($srch->{'srchterm'},$srch->{'srchdomain'});
 8240:                         if ($uhome eq 'no_host') {
 8241:                             ($currstate,$response,$forcenewuser) =
 8242:                                 &build_search_response($context,$srch,%srch_results);
 8243:                         } else {
 8244:                             $currstate = 'modify';
 8245:                             if ($env{'form.action'} eq 'accesslogs') {
 8246:                                 $currstate = 'activity';
 8247:                             }
 8248:                             my $uname = $srch->{'srchterm'};
 8249:                             my $udom = $srch->{'srchdomain'};
 8250:                             $srch_results{$uname.':'.$udom} =
 8251:                                 { &Apache::lonnet::get('environment',
 8252:                                                        ['firstname',
 8253:                                                         'lastname',
 8254:                                                         'permanentemail'],
 8255:                                                          $udom,$uname)
 8256:                                 };
 8257:                         }
 8258:                     } else {
 8259:                         %srch_results = &Apache::lonnet::usersearch($srch);
 8260:                         ($currstate,$response,$forcenewuser) =
 8261:                             &build_search_response($context,$srch,%srch_results);
 8262:                     }
 8263:                 } else {
 8264:                     my $courseusers = &get_courseusers();
 8265:                     if ($srch->{'srchtype'} eq 'exact') {
 8266:                         if (exists($courseusers->{$srch->{'srchterm'}.':'.$srch->{'srchdomain'}})) {
 8267:                             $currstate = 'modify';
 8268:                         } else {
 8269:                             ($currstate,$response,$forcenewuser) =
 8270:                                 &build_search_response($context,$srch,%srch_results);
 8271:                         }
 8272:                     } else {
 8273:                         foreach my $user (keys(%$courseusers)) {
 8274:                             my ($cuname,$cudomain) = split(/:/,$user);
 8275:                             if ($cudomain eq $srch->{'srchdomain'}) {
 8276:                                 my $matched = 0;
 8277:                                 if ($srch->{'srchtype'} eq 'begins') {
 8278:                                     if ($cuname =~ /^\Q$srch->{'srchterm'}\E/i) {
 8279:                                         $matched = 1;
 8280:                                     }
 8281:                                 } else {
 8282:                                     if ($cuname =~ /\Q$srch->{'srchterm'}\E/i) {
 8283:                                         $matched = 1;
 8284:                                     }
 8285:                                 }
 8286:                                 if ($matched) {
 8287:                                     $srch_results{$user} = 
 8288: 					{&Apache::lonnet::get('environment',
 8289: 							     ['firstname',
 8290: 							      'lastname',
 8291: 							      'permanentemail'],
 8292: 							      $cudomain,$cuname)};
 8293:                                 }
 8294:                             }
 8295:                         }
 8296:                         ($currstate,$response,$forcenewuser) =
 8297:                             &build_search_response($context,$srch,%srch_results);
 8298:                     }
 8299:                 }
 8300:             }
 8301:         } elsif ($srch->{'srchin'} eq 'alc') {
 8302:             $currstate = 'query';
 8303:         } elsif ($srch->{'srchin'} eq 'instd') {
 8304:             ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query($srch);
 8305:             if ($dirsrchres eq 'ok') {
 8306:                 ($currstate,$response,$forcenewuser) = 
 8307:                     &build_search_response($context,$srch,%srch_results);
 8308:             } else {
 8309:                 my $showdom = &display_domain_info($srch->{'srchdomain'});
 8310:                 $response = '<span class="LC_warning">'.
 8311:                     &mt('Institutional directory search is not available in domain: [_1]',$showdom).
 8312:                     '</span><br />'.
 8313:                     &mt('You may want to search in the LON-CAPA domain instead of the institutional directory.').
 8314:                     '<br />'; 
 8315:             }
 8316:         }
 8317:     } else {
 8318:         if ($srch->{'srchin'} eq 'dom') {
 8319:             %srch_results = &Apache::lonnet::usersearch($srch);
 8320:             ($currstate,$response,$forcenewuser) = 
 8321:                 &build_search_response($context,$srch,%srch_results); 
 8322:         } elsif ($srch->{'srchin'} eq 'crs') {
 8323:             my $courseusers = &get_courseusers(); 
 8324:             foreach my $user (keys(%$courseusers)) {
 8325:                 my ($uname,$udom) = split(/:/,$user);
 8326:                 my %names = &Apache::loncommon::getnames($uname,$udom);
 8327:                 my %emails = &Apache::loncommon::getemails($uname,$udom);
 8328:                 if ($srch->{'srchby'} eq 'lastname') {
 8329:                     if ((($srch->{'srchtype'} eq 'exact') && 
 8330:                          ($names{'lastname'} eq $srch->{'srchterm'})) || 
 8331:                         (($srch->{'srchtype'} eq 'begins') &&
 8332:                          ($names{'lastname'} =~ /^\Q$srch->{'srchterm'}\E/i)) ||
 8333:                         (($srch->{'srchtype'} eq 'contains') &&
 8334:                          ($names{'lastname'} =~ /\Q$srch->{'srchterm'}\E/i))) {
 8335:                         $srch_results{$user} = {firstname => $names{'firstname'},
 8336:                                             lastname => $names{'lastname'},
 8337:                                             permanentemail => $emails{'permanentemail'},
 8338:                                            };
 8339:                     }
 8340:                 } elsif ($srch->{'srchby'} eq 'lastfirst') {
 8341:                     my ($srchlast,$srchfirst) = split(/,/,$srch->{'srchterm'});
 8342:                     $srchlast =~ s/\s+$//;
 8343:                     $srchfirst =~ s/^\s+//;
 8344:                     if ($srch->{'srchtype'} eq 'exact') {
 8345:                         if (($names{'lastname'} eq $srchlast) &&
 8346:                             ($names{'firstname'} eq $srchfirst)) {
 8347:                             $srch_results{$user} = {firstname => $names{'firstname'},
 8348:                                                 lastname => $names{'lastname'},
 8349:                                                 permanentemail => $emails{'permanentemail'},
 8350: 
 8351:                                            };
 8352:                         }
 8353:                     } elsif ($srch->{'srchtype'} eq 'begins') {
 8354:                         if (($names{'lastname'} =~ /^\Q$srchlast\E/i) &&
 8355:                             ($names{'firstname'} =~ /^\Q$srchfirst\E/i)) {
 8356:                             $srch_results{$user} = {firstname => $names{'firstname'},
 8357:                                                 lastname => $names{'lastname'},
 8358:                                                 permanentemail => $emails{'permanentemail'},
 8359:                                                };
 8360:                         }
 8361:                     } else {
 8362:                         if (($names{'lastname'} =~ /\Q$srchlast\E/i) && 
 8363:                             ($names{'firstname'} =~ /\Q$srchfirst\E/i)) {
 8364:                             $srch_results{$user} = {firstname => $names{'firstname'},
 8365:                                                 lastname => $names{'lastname'},
 8366:                                                 permanentemail => $emails{'permanentemail'},
 8367:                                                };
 8368:                         }
 8369:                     }
 8370:                 }
 8371:             }
 8372:             ($currstate,$response,$forcenewuser) = 
 8373:                 &build_search_response($context,$srch,%srch_results); 
 8374:         } elsif ($srch->{'srchin'} eq 'alc') {
 8375:             $currstate = 'query';
 8376:         } elsif ($srch->{'srchin'} eq 'instd') {
 8377:             ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query($srch); 
 8378:             if ($dirsrchres eq 'ok') {
 8379:                 ($currstate,$response,$forcenewuser) = 
 8380:                     &build_search_response($context,$srch,%srch_results);
 8381:             } else {
 8382:                 my $showdom = &display_domain_info($srch->{'srchdomain'});
 8383:                 $response = '<span class="LC_warning">'.
 8384:                     &mt('Institutional directory search is not available in domain: [_1]',$showdom).
 8385:                     '</span><br />'.
 8386:                     &mt('You may want to search in the LON-CAPA domain instead of the institutional directory.').
 8387:                     '<br />';
 8388:             }
 8389:         }
 8390:     }
 8391:     return ($currstate,$response,$forcenewuser,\%srch_results);
 8392: }
 8393: 
 8394: sub domdirectorysrch_check {
 8395:     my ($srch) = @_;
 8396:     my $response;
 8397:     my %dom_inst_srch = &Apache::lonnet::get_dom('configuration',
 8398:                                              ['directorysrch'],$srch->{'srchdomain'});
 8399:     my $showdom = &display_domain_info($srch->{'srchdomain'});
 8400:     if (ref($dom_inst_srch{'directorysrch'}) eq 'HASH') {
 8401:         if ($dom_inst_srch{'directorysrch'}{'lcavailable'} eq '0') {
 8402:             return &mt('LON-CAPA directory search is not available in domain: [_1]',$showdom);
 8403:         }
 8404:         if ($dom_inst_srch{'directorysrch'}{'lclocalonly'}) {
 8405:             if ($env{'request.role.domain'} ne $srch->{'srchdomain'}) {
 8406:                 return &mt('LON-CAPA directory search in domain: [_1] is only allowed for users with a current role in the domain.',$showdom);
 8407:             }
 8408:         }
 8409:     }
 8410:     return 'ok';
 8411: }
 8412: 
 8413: sub instdirectorysrch_check {
 8414:     my ($srch) = @_;
 8415:     my $can_search = 0;
 8416:     my $response;
 8417:     my %dom_inst_srch = &Apache::lonnet::get_dom('configuration',
 8418:                                              ['directorysrch'],$srch->{'srchdomain'});
 8419:     my $showdom = &display_domain_info($srch->{'srchdomain'});
 8420:     if (ref($dom_inst_srch{'directorysrch'}) eq 'HASH') {
 8421:         if (!$dom_inst_srch{'directorysrch'}{'available'}) {
 8422:             return &mt('Institutional directory search is not available in domain: [_1]',$showdom); 
 8423:         }
 8424:         if ($dom_inst_srch{'directorysrch'}{'localonly'}) {
 8425:             if ($env{'request.role.domain'} ne $srch->{'srchdomain'}) {
 8426:                 return &mt('Institutional directory search in domain: [_1] is only allowed for users with a current role in the domain.',$showdom); 
 8427:             }
 8428:             my @usertypes = split(/:/,$env{'environment.inststatus'});
 8429:             if (!@usertypes) {
 8430:                 push(@usertypes,'default');
 8431:             }
 8432:             if (ref($dom_inst_srch{'directorysrch'}{'cansearch'}) eq 'ARRAY') {
 8433:                 foreach my $type (@usertypes) {
 8434:                     if (grep(/^\Q$type\E$/,@{$dom_inst_srch{'directorysrch'}{'cansearch'}})) {
 8435:                         $can_search = 1;
 8436:                         last;
 8437:                     }
 8438:                 }
 8439:             }
 8440:             if (!$can_search) {
 8441:                 my ($insttypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($srch->{'srchdomain'});
 8442:                 my @longtypes; 
 8443:                 foreach my $item (@usertypes) {
 8444:                     if (defined($insttypes->{$item})) { 
 8445:                         push (@longtypes,$insttypes->{$item});
 8446:                     } elsif ($item eq 'default') {
 8447:                         push (@longtypes,&mt('other')); 
 8448:                     }
 8449:                 }
 8450:                 my $insttype_str = join(', ',@longtypes); 
 8451:                 return &mt('Institutional directory search in domain: [_1] is not available to your user type: ',$showdom).$insttype_str;
 8452:             }
 8453:         } else {
 8454:             $can_search = 1;
 8455:         }
 8456:     } else {
 8457:         return &mt('Institutional directory search has not been configured for domain: [_1]',$showdom);
 8458:     }
 8459:     my %longtext = &Apache::lonlocal::texthash (
 8460:                        uname     => 'username',
 8461:                        lastfirst => 'last name, first name',
 8462:                        lastname  => 'last name',
 8463:                        contains  => 'contains',
 8464:                        exact     => 'as exact match to',
 8465:                        begins    => 'begins with',
 8466:                    );
 8467:     if ($can_search) {
 8468:         if (ref($dom_inst_srch{'directorysrch'}{'searchby'}) eq 'ARRAY') {
 8469:             if (!grep(/^\Q$srch->{'srchby'}\E$/,@{$dom_inst_srch{'directorysrch'}{'searchby'}})) {
 8470:                 return &mt('Institutional directory search in domain: [_1] is not available for searching by "[_2]"',$showdom,$longtext{$srch->{'srchby'}});
 8471:             }
 8472:         } else {
 8473:             return &mt('Institutional directory search in domain: [_1] is not available.', $showdom);
 8474:         }
 8475:     }
 8476:     if ($can_search) {
 8477:         if (ref($dom_inst_srch{'directorysrch'}{'searchtypes'}) eq 'ARRAY') {
 8478:             if (grep(/^\Q$srch->{'srchtype'}\E/,@{$dom_inst_srch{'directorysrch'}{'searchtypes'}})) {
 8479:                 return 'ok';
 8480:             } else {
 8481:                 return &mt('Institutional directory search in domain [_1] is not available for the requested search type: "[_2]"',$showdom,$longtext{$srch->{'srchtype'}});
 8482:             }
 8483:         } else {
 8484:             if ((($dom_inst_srch{'directorysrch'}{'searchtypes'} eq 'specify') &&
 8485:                  ($srch->{'srchtype'} eq 'exact' || $srch->{'srchtype'} eq 'contains')) ||
 8486:                 ($dom_inst_srch{'directorysrch'}{'searchtypes'} eq $srch->{'srchtype'})) {
 8487:                 return 'ok';
 8488:             } else {
 8489:                 return &mt('Institutional directory search in domain [_1] is not available for the requested search type: "[_2]"',$showdom,$longtext{$srch->{'srchtype'}});
 8490:             }
 8491:         }
 8492:     }
 8493: }
 8494: 
 8495: sub get_courseusers {
 8496:     my %advhash;
 8497:     my $classlist = &Apache::loncoursedata::get_classlist();
 8498:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles();
 8499:     foreach my $role (sort(keys(%coursepersonnel))) {
 8500:         foreach my $user (split(/\,/,$coursepersonnel{$role})) {
 8501: 	    if (!exists($classlist->{$user})) {
 8502: 		$classlist->{$user} = [];
 8503: 	    }
 8504:         }
 8505:     }
 8506:     return $classlist;
 8507: }
 8508: 
 8509: sub build_search_response {
 8510:     my ($context,$srch,%srch_results) = @_;
 8511:     my ($currstate,$response,$forcenewuser);
 8512:     my %names = (
 8513:           'uname'     => 'username',
 8514:           'lastname'  => 'last name',
 8515:           'lastfirst' => 'last name, first name',
 8516:           'crs'       => 'this course',
 8517:           'dom'       => 'LON-CAPA domain',
 8518:           'instd'     => 'the institutional directory for domain',
 8519:     );
 8520: 
 8521:     my %single = (
 8522:                    begins   => 'A match',
 8523:                    contains => 'A match',
 8524:                    exact    => 'An exact match',
 8525:                  );
 8526:     my %nomatch = (
 8527:                    begins   => 'No match',
 8528:                    contains => 'No match',
 8529:                    exact    => 'No exact match',
 8530:                   );
 8531:     if (keys(%srch_results) > 1) {
 8532:         $currstate = 'select';
 8533:     } else {
 8534:         if (keys(%srch_results) == 1) {
 8535:             if ($env{'form.action'} eq 'accesslogs') {
 8536:                 $currstate = 'activity';
 8537:             } else {
 8538:                 $currstate = 'modify';
 8539:             }
 8540:             $response = &mt("$single{$srch->{'srchtype'}} was found for the $names{$srch->{'srchby'}} ([_1]) in $names{$srch->{'srchin'}}.",$srch->{'srchterm'});
 8541:             if ($srch->{'srchin'} eq 'dom' || $srch->{'srchin'} eq 'instd') {
 8542:                 $response .= ': '.&display_domain_info($srch->{'srchdomain'});
 8543:             }
 8544:         } else { # Search has nothing found. Prepare message to user.
 8545:             $response = '<span class="LC_warning">';
 8546:             if ($srch->{'srchin'} eq 'dom' || $srch->{'srchin'} eq 'instd') {
 8547:                 $response .= &mt("$nomatch{$srch->{'srchtype'}} found for the $names{$srch->{'srchby'}} [_1] in $names{$srch->{'srchin'}}: [_2]",
 8548:                                  '<b>'.$srch->{'srchterm'}.'</b>',
 8549:                                  &display_domain_info($srch->{'srchdomain'}));
 8550:             } else {
 8551:                 $response .= &mt("$nomatch{$srch->{'srchtype'}} found for the $names{$srch->{'srchby'}} [_1] in $names{$srch->{'srchin'}}.",
 8552:                                  '<b>'.$srch->{'srchterm'}.'</b>');
 8553:             }
 8554:             $response .= '</span>';
 8555: 
 8556:             if ($srch->{'srchin'} ne 'alc') {
 8557:                 $forcenewuser = 1;
 8558:                 my $cansrchinst = 0; 
 8559:                 if ($srch->{'srchdomain'}) {
 8560:                     my %domconfig = &Apache::lonnet::get_dom('configuration',['directorysrch'],$srch->{'srchdomain'});
 8561:                     if (ref($domconfig{'directorysrch'}) eq 'HASH') {
 8562:                         if ($domconfig{'directorysrch'}{'available'}) {
 8563:                             $cansrchinst = 1;
 8564:                         } 
 8565:                     }
 8566:                 }
 8567:                 if ((($srch->{'srchby'} eq 'lastfirst') || 
 8568:                      ($srch->{'srchby'} eq 'lastname')) &&
 8569:                     ($srch->{'srchin'} eq 'dom')) {
 8570:                     if ($cansrchinst) {
 8571:                         $response .= '<br />'.&mt('You may want to broaden your search to a search of the institutional directory for the domain.');
 8572:                     }
 8573:                 }
 8574:                 if ($srch->{'srchin'} eq 'crs') {
 8575:                     $response .= '<br />'.&mt('You may want to broaden your search to the selected LON-CAPA domain.');
 8576:                 }
 8577:             }
 8578:             my $createdom = $env{'request.role.domain'};
 8579:             if ($context eq 'requestcrs') {
 8580:                 if ($env{'form.coursedom'} ne '') {
 8581:                     $createdom = $env{'form.coursedom'};
 8582:                 }
 8583:             }
 8584:             unless (($env{'form.action'} eq 'accesslogs') || (($srch->{'srchby'} eq 'uname') && ($srch->{'srchin'} eq 'dom') &&
 8585:                     ($srch->{'srchtype'} eq 'exact') && ($srch->{'srchdomain'} eq $createdom))) {
 8586:                 my $cancreate =
 8587:                     &Apache::lonuserutils::can_create_user($createdom,$context);
 8588:                 my $targetdom = '<span class="LC_cusr_emph">'.$createdom.'</span>';
 8589:                 if ($cancreate) {
 8590:                     my $showdom = &display_domain_info($createdom); 
 8591:                     $response .= '<br /><br />'
 8592:                                 .'<b>'.&mt('To add a new user:').'</b>'
 8593:                                 .'<br />';
 8594:                     if ($context eq 'requestcrs') {
 8595:                         $response .= &mt("(You can only define new users in the new course's domain - [_1])",$targetdom);
 8596:                     } else {
 8597:                         $response .= &mt("(You can only create new users in your current role's domain - [_1])",$targetdom);
 8598:                     }
 8599:                     $response .='<ul><li>'
 8600:                                 .&mt("Set 'Domain/institution to search' to: [_1]",'<span class="LC_cusr_emph">'.$showdom.'</span>')
 8601:                                 .'</li><li>'
 8602:                                 .&mt("Set 'Search criteria' to: [_1]username is ..... in selected LON-CAPA domain[_2]",'<span class="LC_cusr_emph">','</span>')
 8603:                                 .'</li><li>'
 8604:                                 .&mt('Provide the proposed username')
 8605:                                 .'</li><li>'
 8606:                                 .&mt("Click 'Search'")
 8607:                                 .'</li></ul><br />';
 8608:                 } else {
 8609:                     unless (($context eq 'domain') && ($env{'form.action'} eq 'singleuser')) {
 8610:                         my $helplink = ' href="javascript:helpMenu('."'display'".')"';
 8611:                         $response .= '<br /><br />';
 8612:                         if ($context eq 'requestcrs') {
 8613:                             $response .= &mt("You are not authorized to define new users in the new course's domain - [_1].",$targetdom);
 8614:                         } else {
 8615:                             $response .= &mt("You are not authorized to create new users in your current role's domain - [_1].",$targetdom);
 8616:                         }
 8617:                         $response .= '<br />'
 8618:                                      .&mt('Please contact the [_1]helpdesk[_2] if you need to create a new user.'
 8619:                                         ,' <a'.$helplink.'>'
 8620:                                         ,'</a>')
 8621:                                      .'<br />';
 8622:                     
 8623:                     }
 8624:                 }
 8625:             }
 8626:         }
 8627:     }
 8628:     return ($currstate,$response,$forcenewuser);
 8629: }
 8630: 
 8631: sub display_domain_info {
 8632:     my ($dom) = @_;
 8633:     my $output = $dom;
 8634:     if ($dom ne '') { 
 8635:         my $domdesc = &Apache::lonnet::domain($dom,'description');
 8636:         if ($domdesc ne '') {
 8637:             $output .= ' <span class="LC_cusr_emph">('.$domdesc.')</span>';
 8638:         }
 8639:     }
 8640:     return $output;
 8641: }
 8642: 
 8643: sub crumb_utilities {
 8644:     my %elements = (
 8645:        crtuser => {
 8646:            srchterm => 'text',
 8647:            srchin => 'selectbox',
 8648:            srchby => 'selectbox',
 8649:            srchtype => 'selectbox',
 8650:            srchdomain => 'selectbox',
 8651:        },
 8652:        crtusername => {
 8653:            srchterm => 'text',
 8654:            srchdomain => 'selectbox',
 8655:        },
 8656:        docustom => {
 8657:            rolename => 'selectbox',
 8658:            newrolename => 'textbox',
 8659:        },
 8660:        studentform => {
 8661:            srchterm => 'text',
 8662:            srchin => 'selectbox',
 8663:            srchby => 'selectbox',
 8664:            srchtype => 'selectbox',
 8665:            srchdomain => 'selectbox',
 8666:        },
 8667:     );
 8668: 
 8669:     my $jsback .= qq|
 8670: function backPage(formname,prevphase,prevstate) {
 8671:     if (typeof prevphase == 'undefined') {
 8672:         formname.phase.value = '';
 8673:     }
 8674:     else {  
 8675:         formname.phase.value = prevphase;
 8676:     }
 8677:     if (typeof prevstate == 'undefined') {
 8678:         formname.currstate.value = '';
 8679:     }
 8680:     else {
 8681:         formname.currstate.value = prevstate;
 8682:     }
 8683:     formname.submit();
 8684: }
 8685: |;
 8686:     return ($jsback,\%elements);
 8687: }
 8688: 
 8689: sub course_level_table {
 8690:     my ($inccourses,$showcredits,$defaultcredits) = @_;
 8691:     return unless (ref($inccourses) eq 'HASH');
 8692:     my $table = '';
 8693: # Custom Roles?
 8694: 
 8695:     my %customroles=&Apache::lonuserutils::my_custom_roles();
 8696:     my %lt=&Apache::lonlocal::texthash(
 8697:             'exs'  => "Existing sections",
 8698:             'new'  => "Define new section",
 8699:             'ssd'  => "Set Start Date",
 8700:             'sed'  => "Set End Date",
 8701:             'crl'  => "Course Level",
 8702:             'act'  => "Activate",
 8703:             'rol'  => "Role",
 8704:             'ext'  => "Extent",
 8705:             'grs'  => "Section",
 8706:             'crd'  => "Credits",
 8707:             'sta'  => "Start",
 8708:             'end'  => "End"
 8709:     );
 8710: 
 8711:     foreach my $protectedcourse (sort(keys(%{$inccourses}))) {
 8712: 	my $thiscourse=$protectedcourse;
 8713: 	$thiscourse=~s:_:/:g;
 8714: 	my %coursedata=&Apache::lonnet::coursedescription($thiscourse);
 8715:         my $isowner = &Apache::lonuserutils::is_courseowner($protectedcourse,$coursedata{'internal.courseowner'});
 8716: 	my $area=$coursedata{'description'};
 8717:         my $crstype=$coursedata{'type'};
 8718: 	if (!defined($area)) { $area=&mt('Unavailable course').': '.$protectedcourse; }
 8719: 	my ($domain,$cnum)=split(/\//,$thiscourse);
 8720:         my %sections_count;
 8721:         if (defined($env{'request.course.id'})) {
 8722:             if ($env{'request.course.id'} eq $domain.'_'.$cnum) {
 8723:                 %sections_count = 
 8724: 		    &Apache::loncommon::get_sections($domain,$cnum);
 8725:             }
 8726:         }
 8727:         my @roles = &Apache::lonuserutils::roles_by_context('course','',$crstype);
 8728: 	foreach my $role (@roles) {
 8729:             my $plrole=&Apache::lonnet::plaintext($role,$crstype);
 8730: 	    if ((&Apache::lonnet::allowed('c'.$role,$thiscourse)) ||
 8731:                 ((($role eq 'cc') || ($role eq 'co')) && ($isowner))) {
 8732:                 $table .= &course_level_row($protectedcourse,$role,$area,$domain,
 8733:                                             $plrole,\%sections_count,\%lt,
 8734:                                             $showcredits,$defaultcredits,$crstype);
 8735:             } elsif ($env{'request.course.sec'} ne '') {
 8736:                 if (&Apache::lonnet::allowed('c'.$role,$thiscourse.'/'.
 8737:                                              $env{'request.course.sec'})) {
 8738:                     $table .= &course_level_row($protectedcourse,$role,$area,$domain,
 8739:                                                 $plrole,\%sections_count,\%lt,
 8740:                                                 $showcredits,$defaultcredits,$crstype);
 8741:                 }
 8742:             }
 8743:         }
 8744:         if (&Apache::lonnet::allowed('ccr',$thiscourse)) {
 8745:             foreach my $cust (sort(keys(%customroles))) {
 8746:                 next if ($crstype eq 'Community' && $customroles{$cust} =~ /bre\&S/);
 8747:                 my $role = 'cr_cr_'.$env{'user.domain'}.'_'.$env{'user.name'}.'_'.$cust;
 8748:                 $table .= &course_level_row($protectedcourse,$role,$area,$domain,
 8749:                                             $cust,\%sections_count,\%lt,
 8750:                                             $showcredits,$defaultcredits,$crstype);
 8751:             }
 8752: 	}
 8753:     }
 8754:     return '' if ($table eq ''); # return nothing if there is nothing 
 8755:                                  # in the table
 8756:     my $result;
 8757:     if (!$env{'request.course.id'}) {
 8758:         $result = '<h4>'.$lt{'crl'}.'</h4>'."\n";
 8759:     }
 8760:     $result .= 
 8761: &Apache::loncommon::start_data_table().
 8762: &Apache::loncommon::start_data_table_header_row().
 8763: '<th>'.$lt{'act'}.'</th><th>'.$lt{'rol'}.'</th>'."\n".
 8764: '<th>'.$lt{'ext'}.'</th><th>'."\n";
 8765:     if ($showcredits) {
 8766:         $result .= $lt{'crd'}.'</th>';
 8767:     }
 8768:     $result .=
 8769: '<th>'.$lt{'grs'}.'</th><th>'.$lt{'sta'}.'</th>'."\n".
 8770: '<th>'.$lt{'end'}.'</th>'.
 8771: &Apache::loncommon::end_data_table_header_row().
 8772: $table.
 8773: &Apache::loncommon::end_data_table();
 8774:     return $result;
 8775: }
 8776: 
 8777: sub course_level_row {
 8778:     my ($protectedcourse,$role,$area,$domain,$plrole,$sections_count,
 8779:         $lt,$showcredits,$defaultcredits,$crstype) = @_;
 8780:     my $creditem;
 8781:     my $row = &Apache::loncommon::start_data_table_row().
 8782:               ' <td><input type="checkbox" name="act_'.
 8783:               $protectedcourse.'_'.$role.'" /></td>'."\n".
 8784:               ' <td>'.$plrole.'</td>'."\n".
 8785:               ' <td>'.$area.'<br />Domain: '.$domain.'</td>'."\n";
 8786:     if (($showcredits) && ($role eq 'st') && ($crstype eq 'Course')) {
 8787:         $row .= 
 8788:             '<td><input type="text" name="credits_'.$protectedcourse.'_'.
 8789:             $role.'" size="3" value="'.$defaultcredits.'" /></td>';
 8790:     } else {
 8791:         $row .= '<td>&nbsp;</td>';
 8792:     }
 8793:     if (($role eq 'cc') || ($role eq 'co')) {
 8794:         $row .= '<td>&nbsp;</td>';
 8795:     } elsif ($env{'request.course.sec'} ne '') {
 8796:         $row .= ' <td><input type="hidden" value="'.
 8797:                 $env{'request.course.sec'}.'" '.
 8798:                 'name="sec_'.$protectedcourse.'_'.$role.'" />'.
 8799:                 $env{'request.course.sec'}.'</td>';
 8800:     } else {
 8801:         if (ref($sections_count) eq 'HASH') {
 8802:             my $currsec = 
 8803:                 &Apache::lonuserutils::course_sections($sections_count,
 8804:                                                        $protectedcourse.'_'.$role);
 8805:             $row .= '<td><table class="LC_createuser">'."\n".
 8806:                     '<tr class="LC_section_row">'."\n".
 8807:                     ' <td valign="top">'.$lt->{'exs'}.'<br />'.
 8808:                        $currsec.'</td>'."\n".
 8809:                      ' <td>&nbsp;&nbsp;</td>'."\n".
 8810:                      ' <td valign="top">&nbsp;'.$lt->{'new'}.'<br />'.
 8811:                      '<input type="text" name="newsec_'.$protectedcourse.'_'.$role.
 8812:                      '" value="" />'.
 8813:                      '<input type="hidden" '.
 8814:                      'name="sec_'.$protectedcourse.'_'.$role.'" /></td>'."\n".
 8815:                      '</tr></table></td>'."\n";
 8816:         } else {
 8817:             $row .= '<td><input type="text" size="10" '.
 8818:                     'name="sec_'.$protectedcourse.'_'.$role.'" /></td>'."\n";
 8819:         }
 8820:     }
 8821:     $row .= <<ENDTIMEENTRY;
 8822: <td><input type="hidden" name="start_$protectedcourse\_$role" value="" />
 8823: <a href=
 8824: "javascript:pjump('date_start','Start Date $plrole',document.cu.start_$protectedcourse\_$role.value,'start_$protectedcourse\_$role','cu.pres','dateset')">$lt->{'ssd'}</a></td>
 8825: <td><input type="hidden" name="end_$protectedcourse\_$role" value="" />
 8826: <a href=
 8827: "javascript:pjump('date_end','End Date $plrole',document.cu.end_$protectedcourse\_$role.value,'end_$protectedcourse\_$role','cu.pres','dateset')">$lt->{'sed'}</a></td>
 8828: ENDTIMEENTRY
 8829:     $row .= &Apache::loncommon::end_data_table_row();
 8830:     return $row;
 8831: }
 8832: 
 8833: sub course_level_dc {
 8834:     my ($dcdom,$showcredits) = @_;
 8835:     my %customroles=&Apache::lonuserutils::my_custom_roles();
 8836:     my @roles = &Apache::lonuserutils::roles_by_context('course');
 8837:     my $hiddenitems = '<input type="hidden" name="dcdomain" value="'.$dcdom.'" />'.
 8838:                       '<input type="hidden" name="origdom" value="'.$dcdom.'" />'.
 8839:                       '<input type="hidden" name="dccourse" value="" />';
 8840:     my $courseform=&Apache::loncommon::selectcourse_link
 8841:             ('cu','dccourse','dcdomain','coursedesc',undef,undef,'Select','crstype');
 8842:     my $credit_elem;
 8843:     if ($showcredits) {
 8844:         $credit_elem = 'credits';
 8845:     }
 8846:     my $cb_jscript = &Apache::loncommon::coursebrowser_javascript($dcdom,'currsec','cu','role','Course/Community Browser',$credit_elem);
 8847:     my %lt=&Apache::lonlocal::texthash(
 8848:                     'rol'  => "Role",
 8849:                     'grs'  => "Section",
 8850:                     'exs'  => "Existing sections",
 8851:                     'new'  => "Define new section", 
 8852:                     'sta'  => "Start",
 8853:                     'end'  => "End",
 8854:                     'ssd'  => "Set Start Date",
 8855:                     'sed'  => "Set End Date",
 8856:                     'scc'  => "Course/Community",
 8857:                     'crd'  => "Credits",
 8858:                   );
 8859:     my $header = '<h4>'.&mt('Course/Community Level').'</h4>'.
 8860:                  &Apache::loncommon::start_data_table().
 8861:                  &Apache::loncommon::start_data_table_header_row().
 8862:                  '<th>'.$lt{'scc'}.'</th><th>'.$lt{'rol'}.'</th>'."\n".
 8863:                  '<th>'.$lt{'grs'}.'</th>'."\n";
 8864:     $header .=   '<th>'.$lt{'crd'}.'</th>'."\n" if ($showcredits);
 8865:     $header .=   '<th>'.$lt{'sta'}.'</th><th>'.$lt{'end'}.'</th>'."\n".
 8866:                  &Apache::loncommon::end_data_table_header_row();
 8867:     my $otheritems = &Apache::loncommon::start_data_table_row()."\n".
 8868:                      '<td><br /><span class="LC_nobreak"><input type="text" name="coursedesc" value="" onfocus="this.blur();opencrsbrowser('."'cu','dccourse','dcdomain','coursedesc','','','','crstype'".')" />'.
 8869:                      $courseform.('&nbsp;' x4).'</span></td>'."\n".
 8870:                      '<td valign="top"><br /><select name="role">'."\n";
 8871:     foreach my $role (@roles) {
 8872:         my $plrole=&Apache::lonnet::plaintext($role);
 8873:         $otheritems .= '  <option value="'.$role.'">'.$plrole.'</option>';
 8874:     }
 8875:     if ( keys(%customroles) > 0) {
 8876:         foreach my $cust (sort(keys(%customroles))) {
 8877:             my $custrole='cr_cr_'.$env{'user.domain'}.
 8878:                     '_'.$env{'user.name'}.'_'.$cust;
 8879:             $otheritems .= '  <option value="'.$custrole.'">'.$cust.'</option>';
 8880:         }
 8881:     }
 8882:     $otheritems .= '</select></td><td>'.
 8883:                      '<table border="0" cellspacing="0" cellpadding="0">'.
 8884:                      '<tr><td valign="top"><b>'.$lt{'exs'}.'</b><br /><select name="currsec">'.
 8885:                      ' <option value="">&lt;--'.&mt('Pick course first').'</option></select></td>'.
 8886:                      '<td>&nbsp;&nbsp;</td>'.
 8887:                      '<td valign="top">&nbsp;<b>'.$lt{'new'}.'</b><br />'.
 8888:                      '<input type="text" name="newsec" value="" />'.
 8889:                      '<input type="hidden" name="section" value="" />'.
 8890:                      '<input type="hidden" name="groups" value="" />'.
 8891:                      '<input type="hidden" name="crstype" value="" /></td>'.
 8892:                      '</tr></table></td>'."\n";
 8893:     if ($showcredits) {
 8894:         $otheritems .= '<td><br />'."\n".
 8895:                        '<input type="text" size="3" name="credits" value="" /></td>'."\n";
 8896:     }
 8897:     $otheritems .= <<ENDTIMEENTRY;
 8898: <td><br /><input type="hidden" name="start" value='' />
 8899: <a href=
 8900: "javascript:pjump('date_start','Start Date',document.cu.start.value,'start','cu.pres','dateset')">$lt{'ssd'}</a></td>
 8901: <td><br /><input type="hidden" name="end" value='' />
 8902: <a href=
 8903: "javascript:pjump('date_end','End Date',document.cu.end.value,'end','cu.pres','dateset')">$lt{'sed'}</a></td>
 8904: ENDTIMEENTRY
 8905:     $otheritems .= &Apache::loncommon::end_data_table_row().
 8906:                    &Apache::loncommon::end_data_table()."\n";
 8907:     return $cb_jscript.$header.$hiddenitems.$otheritems;
 8908: }
 8909: 
 8910: sub update_selfenroll_config {
 8911:     my ($r,$cid,$cdom,$cnum,$context,$crstype,$currsettings) = @_;
 8912:     return unless (ref($currsettings) eq 'HASH');
 8913:     my ($row,$lt) = &Apache::lonuserutils::get_selfenroll_titles();
 8914:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
 8915:     my (%changes,%warning);
 8916:     my $curr_types;
 8917:     my %noedit;
 8918:     unless ($context eq 'domain') {
 8919:         %noedit = &get_noedit_fields($cdom,$cnum,$crstype,$row);
 8920:     }
 8921:     if (ref($row) eq 'ARRAY') {
 8922:         foreach my $item (@{$row}) {
 8923:             next if ($noedit{$item});
 8924:             if ($item eq 'enroll_dates') {
 8925:                 my (%currenrolldate,%newenrolldate);
 8926:                 foreach my $type ('start','end') {
 8927:                     $currenrolldate{$type} = $currsettings->{'selfenroll_'.$type.'_date'};
 8928:                     $newenrolldate{$type} = &Apache::lonhtmlcommon::get_date_from_form('selfenroll_'.$type.'_date');
 8929:                     if ($newenrolldate{$type} ne $currenrolldate{$type}) {
 8930:                         $changes{'internal.selfenroll_'.$type.'_date'} = $newenrolldate{$type};
 8931:                     }
 8932:                 }
 8933:             } elsif ($item eq 'access_dates') {
 8934:                 my (%currdate,%newdate);
 8935:                 foreach my $type ('start','end') {
 8936:                     $currdate{$type} = $currsettings->{'selfenroll_'.$type.'_access'};
 8937:                     $newdate{$type} = &Apache::lonhtmlcommon::get_date_from_form('selfenroll_'.$type.'_access');
 8938:                     if ($newdate{$type} ne $currdate{$type}) {
 8939:                         $changes{'internal.selfenroll_'.$type.'_access'} = $newdate{$type};
 8940:                     }
 8941:                 }
 8942:             } elsif ($item eq 'types') {
 8943:                 $curr_types = $currsettings->{'selfenroll_'.$item};
 8944:                 if ($env{'form.selfenroll_all'}) {
 8945:                     if ($curr_types ne '*') {
 8946:                         $changes{'internal.selfenroll_types'} = '*';
 8947:                     } else {
 8948:                         next;
 8949:                     }
 8950:                 } else {
 8951:                     my %currdoms;
 8952:                     my @entries = split(/;/,$curr_types);
 8953:                     my @deletedoms = &Apache::loncommon::get_env_multiple('form.selfenroll_delete');
 8954:                     my @activations = &Apache::loncommon::get_env_multiple('form.selfenroll_activate');
 8955:                     my $newnum = 0;
 8956:                     my @latesttypes;
 8957:                     foreach my $num (@activations) {
 8958:                         my @types = &Apache::loncommon::get_env_multiple('form.selfenroll_types_'.$num);
 8959:                         if (@types > 0) {
 8960:                             @types = sort(@types);
 8961:                             my $typestr = join(',',@types);
 8962:                             my $typedom = $env{'form.selfenroll_dom_'.$num};
 8963:                             $latesttypes[$newnum] = $typedom.':'.$typestr;
 8964:                             $currdoms{$typedom} = 1;
 8965:                             $newnum ++;
 8966:                         }
 8967:                     }
 8968:                     for (my $j=0; $j<$env{'form.selfenroll_types_total'}; $j++) {
 8969:                         if ((!grep(/^$j$/,@deletedoms)) && (!grep(/^$j$/,@activations))) {
 8970:                             my @types = &Apache::loncommon::get_env_multiple('form.selfenroll_types_'.$j);
 8971:                             if (@types > 0) {
 8972:                                 @types = sort(@types);
 8973:                                 my $typestr = join(',',@types);
 8974:                                 my $typedom = $env{'form.selfenroll_dom_'.$j};
 8975:                                 $latesttypes[$newnum] = $typedom.':'.$typestr;
 8976:                                 $currdoms{$typedom} = 1;
 8977:                                 $newnum ++;
 8978:                             }
 8979:                         }
 8980:                     }
 8981:                     if ($env{'form.selfenroll_newdom'} ne '') {
 8982:                         my $typedom = $env{'form.selfenroll_newdom'};
 8983:                         if ((!defined($currdoms{$typedom})) && 
 8984:                             (&Apache::lonnet::domain($typedom) ne '')) {
 8985:                             my $typestr;
 8986:                             my ($othertitle,$usertypes,$types) = 
 8987:                                 &Apache::loncommon::sorted_inst_types($typedom);
 8988:                             my $othervalue = 'any';
 8989:                             if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 8990:                                 if (@{$types} > 0) {
 8991:                                     my @esc_types = map { &escape($_); } @{$types};
 8992:                                     $othervalue = 'other';
 8993:                                     $typestr = join(',',(@esc_types,$othervalue));
 8994:                                 }
 8995:                                 $typestr = $othervalue;
 8996:                             } else {
 8997:                                 $typestr = $othervalue;
 8998:                             } 
 8999:                             $latesttypes[$newnum] = $typedom.':'.$typestr;
 9000:                             $newnum ++ ;
 9001:                         }
 9002:                     }
 9003:                     my $selfenroll_types = join(';',@latesttypes);
 9004:                     if ($selfenroll_types ne $curr_types) {
 9005:                         $changes{'internal.selfenroll_types'} = $selfenroll_types;
 9006:                     }
 9007:                 }
 9008:             } elsif ($item eq 'limit') {
 9009:                 my $newlimit = $env{'form.selfenroll_limit'};
 9010:                 my $newcap = $env{'form.selfenroll_cap'};
 9011:                 $newcap =~s/\s+//g;
 9012:                 my $currlimit =  $currsettings->{'selfenroll_limit'};
 9013:                 $currlimit = 'none' if ($currlimit eq '');
 9014:                 my $currcap = $currsettings->{'selfenroll_cap'};
 9015:                 if ($newlimit ne $currlimit) {
 9016:                     if ($newlimit ne 'none') {
 9017:                         if ($newcap =~ /^\d+$/) {
 9018:                             if ($newcap ne $currcap) {
 9019:                                 $changes{'internal.selfenroll_cap'} = $newcap;
 9020:                             }
 9021:                             $changes{'internal.selfenroll_limit'} = $newlimit;
 9022:                         } else {
 9023:                             $warning{$item} = &mt('Maximum enrollment setting unchanged.').'<br />'.
 9024:                                 &mt('The value provided was invalid - it must be a positive integer if enrollment is being limited.'); 
 9025:                         }
 9026:                     } elsif ($currcap ne '') {
 9027:                         $changes{'internal.selfenroll_cap'} = '';
 9028:                         $changes{'internal.selfenroll_limit'} = $newlimit; 
 9029:                     }
 9030:                 } elsif ($currlimit ne 'none') {
 9031:                     if ($newcap =~ /^\d+$/) {
 9032:                         if ($newcap ne $currcap) {
 9033:                             $changes{'internal.selfenroll_cap'} = $newcap;
 9034:                         }
 9035:                     } else {
 9036:                         $warning{$item} = &mt('Maximum enrollment setting unchanged.').'<br />'.
 9037:                             &mt('The value provided was invalid - it must be a positive integer if enrollment is being limited.');
 9038:                     }
 9039:                 }
 9040:             } elsif ($item eq 'approval') {
 9041:                 my (@currnotified,@newnotified);
 9042:                 my $currapproval = $currsettings->{'selfenroll_approval'};
 9043:                 my $currnotifylist = $currsettings->{'selfenroll_notifylist'};
 9044:                 if ($currnotifylist ne '') {
 9045:                     @currnotified = split(/,/,$currnotifylist);
 9046:                     @currnotified = sort(@currnotified);
 9047:                 }
 9048:                 my $newapproval = $env{'form.selfenroll_approval'};
 9049:                 @newnotified = &Apache::loncommon::get_env_multiple('form.selfenroll_notify');
 9050:                 @newnotified = sort(@newnotified);
 9051:                 if ($newapproval ne $currapproval) {
 9052:                     $changes{'internal.selfenroll_approval'} = $newapproval;
 9053:                     if (!$newapproval) {
 9054:                         if ($currnotifylist ne '') {
 9055:                             $changes{'internal.selfenroll_notifylist'} = '';
 9056:                         }
 9057:                     } else {
 9058:                         my @differences =  
 9059:                             &Apache::loncommon::compare_arrays(\@currnotified,\@newnotified);
 9060:                         if (@differences > 0) {
 9061:                             if (@newnotified > 0) {
 9062:                                 $changes{'internal.selfenroll_notifylist'} = join(',',@newnotified);
 9063:                             } else {
 9064:                                 $changes{'internal.selfenroll_notifylist'} = join(',',@newnotified);
 9065:                             }
 9066:                         }
 9067:                     }
 9068:                 } else {
 9069:                     my @differences = &Apache::loncommon::compare_arrays(\@currnotified,\@newnotified);
 9070:                     if (@differences > 0) {
 9071:                         if (@newnotified > 0) {
 9072:                             $changes{'internal.selfenroll_notifylist'} = join(',',@newnotified);
 9073:                         } else {
 9074:                             $changes{'internal.selfenroll_notifylist'} = '';
 9075:                         }
 9076:                     }
 9077:                 }
 9078:             } else {
 9079:                 my $curr_val = $currsettings->{'selfenroll_'.$item};
 9080:                 my $newval = $env{'form.selfenroll_'.$item};
 9081:                 if ($item eq 'section') {
 9082:                     $newval = $env{'form.sections'};
 9083:                     if (defined($curr_groups{$newval})) {
 9084:                         $newval = $curr_val;
 9085:                         $warning{$item} = &mt('Section for self-enrolled users unchanged as the proposed section is a group').'<br />'.
 9086:                                           &mt('Group names and section names must be distinct');
 9087:                     } elsif ($newval eq 'all') {
 9088:                         $newval = $curr_val;
 9089:                         $warning{$item} = &mt('Section for self-enrolled users unchanged, as "all" is a reserved section name.');
 9090:                     }
 9091:                     if ($newval eq '') {
 9092:                         $newval = 'none';
 9093:                     }
 9094:                 }
 9095:                 if ($newval ne $curr_val) {
 9096:                     $changes{'internal.selfenroll_'.$item} = $newval;
 9097:                 }
 9098:             }
 9099:         }
 9100:         if (keys(%warning) > 0) {
 9101:             foreach my $item (@{$row}) {
 9102:                 if (exists($warning{$item})) {
 9103:                     $r->print($warning{$item}.'<br />');
 9104:                 }
 9105:             } 
 9106:         }
 9107:         if (keys(%changes) > 0) {
 9108:             my $putresult = &Apache::lonnet::put('environment',\%changes,$cdom,$cnum);
 9109:             if ($putresult eq 'ok') {
 9110:                 if ((exists($changes{'internal.selfenroll_types'})) ||
 9111:                     (exists($changes{'internal.selfenroll_start_date'}))  ||
 9112:                     (exists($changes{'internal.selfenroll_end_date'}))) {
 9113:                     my %crsinfo = &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',
 9114:                                                                 $cnum,undef,undef,'Course');
 9115:                     my $chome = &Apache::lonnet::homeserver($cnum,$cdom);
 9116:                     if (ref($crsinfo{$cid}) eq 'HASH') {
 9117:                         foreach my $item ('selfenroll_types','selfenroll_start_date','selfenroll_end_date') {
 9118:                             if (exists($changes{'internal.'.$item})) {
 9119:                                 $crsinfo{$cid}{$item} = $changes{'internal.'.$item};
 9120:                             }
 9121:                         }
 9122:                         my $crsputresult =
 9123:                             &Apache::lonnet::courseidput($cdom,\%crsinfo,
 9124:                                                          $chome,'notime');
 9125:                     }
 9126:                 }
 9127:                 $r->print(&mt('The following changes were made to self-enrollment settings:').'<ul>');
 9128:                 foreach my $item (@{$row}) {
 9129:                     my $title = $item;
 9130:                     if (ref($lt) eq 'HASH') {
 9131:                         $title = $lt->{$item};
 9132:                     }
 9133:                     if ($item eq 'enroll_dates') {
 9134:                         foreach my $type ('start','end') {
 9135:                             if (exists($changes{'internal.selfenroll_'.$type.'_date'})) {
 9136:                                 my $newdate = &Apache::lonlocal::locallocaltime($changes{'internal.selfenroll_'.$type.'_date'});
 9137:                                 $r->print('<li>'.&mt('[_1]: "[_2]" set to "[_3]".',
 9138:                                           $title,$type,$newdate).'</li>');
 9139:                             }
 9140:                         }
 9141:                     } elsif ($item eq 'access_dates') {
 9142:                         foreach my $type ('start','end') {
 9143:                             if (exists($changes{'internal.selfenroll_'.$type.'_access'})) {
 9144:                                 my $newdate = &Apache::lonlocal::locallocaltime($changes{'internal.selfenroll_'.$type.'_access'});
 9145:                                 $r->print('<li>'.&mt('[_1]: "[_2]" set to "[_3]".',
 9146:                                           $title,$type,$newdate).'</li>');
 9147:                             }
 9148:                         }
 9149:                     } elsif ($item eq 'limit') {
 9150:                         if ((exists($changes{'internal.selfenroll_limit'})) ||
 9151:                             (exists($changes{'internal.selfenroll_cap'}))) {
 9152:                             my ($newval,$newcap);
 9153:                             if ($changes{'internal.selfenroll_cap'} ne '') {
 9154:                                 $newcap = $changes{'internal.selfenroll_cap'}
 9155:                             } else {
 9156:                                 $newcap = $currsettings->{'selfenroll_cap'};
 9157:                             }
 9158:                             if ($changes{'internal.selfenroll_limit'} eq 'none') {
 9159:                                 $newval = &mt('No limit');
 9160:                             } elsif ($changes{'internal.selfenroll_limit'} eq 
 9161:                                      'allstudents') {
 9162:                                 $newval = &mt('New self-enrollment no longer allowed when total (all students) reaches [_1].',$newcap);
 9163:                             } elsif ($changes{'internal.selfenroll_limit'} eq 'selfenrolled') {
 9164:                                 $newval = &mt('New self-enrollment no longer allowed when total number of self-enrolled students reaches [_1].',$newcap);
 9165:                             } else {
 9166:                                 my $currlimit =  $currsettings->{'selfenroll_limit'};
 9167:                                 if ($currlimit eq 'allstudents') {
 9168:                                     $newval = &mt('New self-enrollment no longer allowed when total (all students) reaches [_1].',$newcap);
 9169:                                 } elsif ($changes{'internal.selfenroll_limit'} eq 'selfenrolled') {
 9170:                                     $newval =  &mt('New self-enrollment no longer allowed when total number of self-enrolled students reaches [_1].',$newcap);
 9171:                                 }
 9172:                             }
 9173:                             $r->print('<li>'.&mt('"[_1]" set to "[_2]".',$title,$newval).'</li>'."\n");
 9174:                         }
 9175:                     } elsif ($item eq 'approval') {
 9176:                         if ((exists($changes{'internal.selfenroll_approval'})) ||
 9177:                             (exists($changes{'internal.selfenroll_notifylist'}))) {
 9178:                             my %selfdescs = &Apache::lonuserutils::selfenroll_default_descs();
 9179:                             my ($newval,$newnotify);
 9180:                             if (exists($changes{'internal.selfenroll_notifylist'})) {
 9181:                                 $newnotify = $changes{'internal.selfenroll_notifylist'};
 9182:                             } else {   
 9183:                                 $newnotify = $currsettings->{'selfenroll_notifylist'};
 9184:                             }
 9185:                             if (exists($changes{'internal.selfenroll_approval'})) {
 9186:                                 if ($changes{'internal.selfenroll_approval'} !~ /^[012]$/) {
 9187:                                     $changes{'internal.selfenroll_approval'} = '0';
 9188:                                 }
 9189:                                 $newval = $selfdescs{'approval'}{$changes{'internal.selfenroll_approval'}};
 9190:                             } else {
 9191:                                 my $currapproval = $currsettings->{'selfenroll_approval'}; 
 9192:                                 if ($currapproval !~ /^[012]$/) {
 9193:                                     $currapproval = 0;
 9194:                                 }
 9195:                                 $newval = $selfdescs{'approval'}{$currapproval};
 9196:                             }
 9197:                             $r->print('<li>'.&mt('"[_1]" set to "[_2]".',$title,$newval));
 9198:                             if ($newnotify) {
 9199:                                 $r->print('<br />'.&mt('The following will be notified when an enrollment request needs approval, or has been approved: [_1].',$newnotify));
 9200:                             } else {
 9201:                                 $r->print('<br />'.&mt('No notifications sent when an enrollment request needs approval, or has been approved.'));
 9202:                             }
 9203:                             $r->print('</li>'."\n");
 9204:                         }
 9205:                     } else {
 9206:                         if (exists($changes{'internal.selfenroll_'.$item})) {
 9207:                             my $newval = $changes{'internal.selfenroll_'.$item};
 9208:                             if ($item eq 'types') {
 9209:                                 if ($newval eq '') {
 9210:                                     $newval = &mt('None');
 9211:                                 } elsif ($newval eq '*') {
 9212:                                     $newval = &mt('Any user in any domain');
 9213:                                 }
 9214:                             } elsif ($item eq 'registered') {
 9215:                                 if ($newval eq '1') {
 9216:                                     $newval = &mt('Yes');
 9217:                                 } elsif ($newval eq '0') {
 9218:                                     $newval = &mt('No');
 9219:                                 }
 9220:                             }
 9221:                             $r->print('<li>'.&mt('"[_1]" set to "[_2]".',$title,$newval).'</li>'."\n");
 9222:                         }
 9223:                     }
 9224:                 }
 9225:                 $r->print('</ul>');
 9226:                 if ($env{'course.'.$cid.'.description'} ne '') {
 9227:                     my %newenvhash;
 9228:                     foreach my $key (keys(%changes)) {
 9229:                         $newenvhash{'course.'.$cid.'.'.$key} = $changes{$key};
 9230:                     }
 9231:                     &Apache::lonnet::appenv(\%newenvhash);
 9232:                 }
 9233:             } else {
 9234:                 $r->print(&mt('An error occurred when saving changes to self-enrollment settings in this course.').'<br />'.
 9235:                           &mt('The error was: [_1].',$putresult));
 9236:             }
 9237:         } else {
 9238:             $r->print(&mt('No changes were made to the existing self-enrollment settings in this course.'));
 9239:         }
 9240:     } else {
 9241:         $r->print(&mt('No changes were made to the existing self-enrollment settings in this course.'));
 9242:     }
 9243:     my $visactions = &cat_visibility();
 9244:     my ($cathash,%cattype);
 9245:     my %domconfig = &Apache::lonnet::get_dom('configuration',['coursecategories'],$cdom);
 9246:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 9247:         $cathash = $domconfig{'coursecategories'}{'cats'};
 9248:         $cattype{'auth'} = $domconfig{'coursecategories'}{'auth'};
 9249:         $cattype{'unauth'} = $domconfig{'coursecategories'}{'unauth'};
 9250:     } else {
 9251:         $cathash = {};
 9252:         $cattype{'auth'} = 'std';
 9253:         $cattype{'unauth'} = 'std';
 9254:     }
 9255:     if (($cattype{'auth'} eq 'none') && ($cattype{'unauth'} eq 'none')) {
 9256:         $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
 9257:                   '<br />'.
 9258:                   '<br />'.$visactions->{'take'}.'<ul>'.
 9259:                   '<li>'.$visactions->{'dc_chgconf'}.'</li>'.
 9260:                   '</ul>');
 9261:     } elsif (($cattype{'auth'} !~ /^(std|domonly)$/) && ($cattype{'unauth'} !~ /^(std|domonly)$/)) {
 9262:         if ($currsettings->{'uniquecode'}) {
 9263:             $r->print('<span class="LC_info">'.$visactions->{'vis'}.'</span>');
 9264:         } else {
 9265:             $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
 9266:                   '<br />'.
 9267:                   '<br />'.$visactions->{'take'}.'<ul>'.
 9268:                   '<li>'.$visactions->{'dc_setcode'}.'</li>'.
 9269:                   '</ul><br />');
 9270:         }
 9271:     } else {
 9272:         my ($visible,$cansetvis,$vismsgs) = &visible_in_stdcat($cdom,$cnum,\%domconfig);
 9273:         if (ref($visactions) eq 'HASH') {
 9274:             if (!$visible) {
 9275:                 $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
 9276:                           '<br />');
 9277:                 if (ref($vismsgs) eq 'ARRAY') {
 9278:                     $r->print('<br />'.$visactions->{'take'}.'<ul>');
 9279:                     foreach my $item (@{$vismsgs}) {
 9280:                         $r->print('<li>'.$visactions->{$item}.'</li>');
 9281:                     }
 9282:                     $r->print('</ul>');
 9283:                 }
 9284:                 $r->print($cansetvis);
 9285:             }
 9286:         }
 9287:     } 
 9288:     return;
 9289: }
 9290: 
 9291: #---------------------------------------------- end functions for &phase_two
 9292: 
 9293: #--------------------------------- functions for &phase_two and &phase_three
 9294: 
 9295: #--------------------------end of functions for &phase_two and &phase_three
 9296: 
 9297: 1;
 9298: __END__
 9299: 
 9300: 

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