File:  [LON-CAPA] / loncom / interface / loncreateuser.pm
Revision 1.406.2.11: download - view: text, annotated - select for diffs
Tue Jan 24 05:35:35 2017 UTC (7 years, 4 months ago) by raeburn
Branches: version_2_11_X
- Helpdesk Access menu item moved to correct context (i.e., course not domain).
- Some white space changes.

    1: # The LearningOnline Network with CAPA
    2: # Create a user
    3: #
    4: # $Id: loncreateuser.pm,v 1.406.2.11 2017/01/24 05:35:35 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:                    'requestauthor'  => 'Can request author space',
  256:     );
  257:     if ($context eq 'requestcourses') {
  258:         %userenv = &Apache::lonnet::userenvironment($ccdomain,$ccuname,
  259:                       'requestcourses.official','requestcourses.unofficial',
  260:                       'requestcourses.community','requestcourses.textbook');
  261:         @usertools = ('official','unofficial','community','textbook');
  262:         @options =('norequest','approval','autolimit','validate');
  263:         %validations = &Apache::lonnet::auto_courserequest_checks($ccdomain);
  264:         %reqtitles = &courserequest_titles();
  265:         %reqdisplay = &courserequest_display();
  266:         $colspan = ' colspan="2"';
  267:         %domconfig =
  268:             &Apache::lonnet::get_dom('configuration',['requestcourses'],$ccdomain);
  269:         $isadv = &Apache::lonnet::is_advanced_user($ccdomain,$ccuname);
  270:     } elsif ($context eq 'requestauthor') {
  271:         %userenv = &Apache::lonnet::userenvironment($ccdomain,$ccuname,
  272:                                                     'requestauthor');
  273:         @usertools = ('requestauthor');
  274:         @options =('norequest','approval','automatic');
  275:         %reqtitles = &requestauthor_titles();
  276:         %reqdisplay = &requestauthor_display();
  277:         $colspan = ' colspan="2"';
  278:         %domconfig =
  279:             &Apache::lonnet::get_dom('configuration',['requestauthor'],$ccdomain);
  280:     } else {
  281:         %userenv = &Apache::lonnet::userenvironment($ccdomain,$ccuname,
  282:                           'tools.aboutme','tools.portfolio','tools.blog',
  283:                           'tools.webdav');
  284:         @usertools = ('aboutme','blog','webdav','portfolio');
  285:     }
  286:     foreach my $item (@usertools) {
  287:         my ($custom_access,$curr_access,$cust_on,$cust_off,$tool_on,$tool_off,
  288:             $currdisp,$custdisp,$custradio);
  289:         $cust_off = 'checked="checked" ';
  290:         $tool_on = 'checked="checked" ';
  291:         $curr_access =  
  292:             &Apache::lonnet::usertools_access($ccuname,$ccdomain,$item,undef,
  293:                                               $context);
  294:         if ($context eq 'requestauthor') {
  295:             if ($userenv{$context} ne '') {
  296:                 $cust_on = ' checked="checked" ';
  297:                 $cust_off = '';
  298:             }  
  299:         } elsif ($userenv{$context.'.'.$item} ne '') {
  300:             $cust_on = ' checked="checked" ';
  301:             $cust_off = '';
  302:         }
  303:         if ($context eq 'requestcourses') {
  304:             if ($userenv{$context.'.'.$item} eq '') {
  305:                 $custom_access = &mt('Currently from default setting.');
  306:             } else {
  307:                 $custom_access = &mt('Currently from custom setting.');
  308:             }
  309:         } elsif ($context eq 'requestauthor') {
  310:             if ($userenv{$context} eq '') {
  311:                 $custom_access = &mt('Currently from default setting.');
  312:             } else {
  313:                 $custom_access = &mt('Currently from custom setting.');
  314:             }
  315:         } else {
  316:             if ($userenv{$context.'.'.$item} eq '') {
  317:                 $custom_access =
  318:                     &mt('Availability determined currently from default setting.');
  319:                 if (!$curr_access) {
  320:                     $tool_off = 'checked="checked" ';
  321:                     $tool_on = '';
  322:                 }
  323:             } else {
  324:                 $custom_access =
  325:                     &mt('Availability determined currently from custom setting.');
  326:                 if ($userenv{$context.'.'.$item} == 0) {
  327:                     $tool_off = 'checked="checked" ';
  328:                     $tool_on = '';
  329:                 }
  330:             }
  331:         }
  332:         $output .= '  <tr class="LC_info_row">'."\n".
  333:                    '   <td'.$colspan.'>'.$lt{$item}.'</td>'."\n".
  334:                    '  </tr>'."\n".
  335:                    &Apache::loncommon::start_data_table_row()."\n";
  336:         if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
  337:             my ($curroption,$currlimit);
  338:             my $envkey = $context.'.'.$item;
  339:             if ($context eq 'requestauthor') {
  340:                 $envkey = $context;
  341:             }
  342:             if ($userenv{$envkey} ne '') {
  343:                 $curroption = $userenv{$envkey};
  344:             } else {
  345:                 my (@inststatuses);
  346:                 if ($context eq 'requestcourses') {
  347:                     $curroption =
  348:                         &Apache::loncoursequeueadmin::get_processtype('course',$ccuname,$ccdomain,
  349:                                                                       $isadv,$ccdomain,$item,
  350:                                                                       \@inststatuses,\%domconfig);
  351:                 } else {
  352:                      $curroption = 
  353:                          &Apache::loncoursequeueadmin::get_processtype('requestauthor',$ccuname,$ccdomain,
  354:                                                                        $isadv,$ccdomain,undef,
  355:                                                                        \@inststatuses,\%domconfig);
  356:                 }
  357:             }
  358:             if (!$curroption) {
  359:                 $curroption = 'norequest';
  360:             }
  361:             if ($curroption =~ /^autolimit=(\d*)$/) {
  362:                 $currlimit = $1;
  363:                 if ($currlimit eq '') {
  364:                     $currdisp = &mt('Yes, automatic creation');
  365:                 } else {
  366:                     $currdisp = &mt('Yes, up to [quant,_1,request]/user',$currlimit);
  367:                 }
  368:             } else {
  369:                 $currdisp = $reqdisplay{$curroption};
  370:             }
  371:             $custdisp = '<table>';
  372:             foreach my $option (@options) {
  373:                 my $val = $option;
  374:                 if ($option eq 'norequest') {
  375:                     $val = 0;
  376:                 }
  377:                 if ($option eq 'validate') {
  378:                     my $canvalidate = 0;
  379:                     if (ref($validations{$item}) eq 'HASH') {
  380:                         if ($validations{$item}{'_custom_'}) {
  381:                             $canvalidate = 1;
  382:                         }
  383:                     }
  384:                     next if (!$canvalidate);
  385:                 }
  386:                 my $checked = '';
  387:                 if ($option eq $curroption) {
  388:                     $checked = ' checked="checked"';
  389:                 } elsif ($option eq 'autolimit') {
  390:                     if ($curroption =~ /^autolimit/) {
  391:                         $checked = ' checked="checked"';
  392:                     }
  393:                 }
  394:                 my $name = 'crsreq_'.$item;
  395:                 if ($context eq 'requestauthor') {
  396:                     $name = $item;
  397:                 }
  398:                 $custdisp .= '<tr><td><span class="LC_nobreak"><label>'.
  399:                              '<input type="radio" name="'.$name.'" '.
  400:                              'value="'.$val.'"'.$checked.' />'.
  401:                              $reqtitles{$option}.'</label>&nbsp;';
  402:                 if ($option eq 'autolimit') {
  403:                     $custdisp .= '<input type="text" name="'.$name.
  404:                                  '_limit" size="1" '.
  405:                                  'value="'.$currlimit.'" /></span><br />'.
  406:                                  $reqtitles{'unlimited'};
  407:                 } else {
  408:                     $custdisp .= '</span>';
  409:                 }
  410:                 $custdisp .= '</td></tr>';
  411:             }
  412:             $custdisp .= '</table>';
  413:             $custradio = '</span></td><td>'.&mt('Custom setting').'<br />'.$custdisp;
  414:         } else {
  415:             $currdisp = ($curr_access?&mt('Yes'):&mt('No'));
  416:             my $name = $context.'_'.$item;
  417:             if ($context eq 'requestauthor') {
  418:                 $name = $context;
  419:             }
  420:             $custdisp = '<span class="LC_nobreak"><label>'.
  421:                         '<input type="radio" name="'.$name.'"'.
  422:                         ' value="1" '.$tool_on.'/>'.&mt('On').'</label>&nbsp;<label>'.
  423:                         '<input type="radio" name="'.$name.'" value="0" '.
  424:                         $tool_off.'/>'.&mt('Off').'</label></span>';
  425:             $custradio = ('&nbsp;'x2).'--'.$lt{'cusa'}.':&nbsp;'.$custdisp.
  426:                           '</span>';
  427:         }
  428:         $output .= '  <td'.$colspan.'>'.$custom_access.('&nbsp;'x4).
  429:                    $lt{'avai'}.': '.$currdisp.'</td>'."\n".
  430:                    &Apache::loncommon::end_data_table_row()."\n";
  431:         unless (&Apache::lonnet::allowed('udp',$ccdomain)) {
  432:             $output .=
  433:                    &Apache::loncommon::start_data_table_row()."\n".
  434:                    '  <td style="vertical-align:top;"><span class="LC_nobreak">'.
  435:                    $lt{'chse'}.': <label>'.
  436:                    '<input type="radio" name="custom'.$item.'" value="0" '.
  437:                    $cust_off.'/>'.$lt{'usde'}.'</label>'.('&nbsp;' x3).
  438:                    '<label><input type="radio" name="custom'.$item.'" value="1" '.
  439:                    $cust_on.'/>'.$lt{'uscu'}.'</label>'.$custradio.'</td>'.
  440:                    &Apache::loncommon::end_data_table_row()."\n";
  441:         }
  442:     }
  443:     return $output;
  444: }
  445: 
  446: sub coursereq_externaluser {
  447:     my ($ccuname,$ccdomain,$cdom) = @_;
  448:     my (@usertools,@options,%validations,%userenv,$output);
  449:     my %lt = &Apache::lonlocal::texthash (
  450:                    'official'   => 'Can request creation of official courses',
  451:                    'unofficial' => 'Can request creation of unofficial courses',
  452:                    'community'  => 'Can request creation of communities',
  453:                    'textbook'   => 'Can request creation of textbook courses',
  454:     );
  455: 
  456:     %userenv = &Apache::lonnet::userenvironment($ccdomain,$ccuname,
  457:                       'reqcrsotherdom.official','reqcrsotherdom.unofficial',
  458:                       'reqcrsotherdom.community','reqcrsotherdom.textbook');
  459:     @usertools = ('official','unofficial','community','textbook');
  460:     @options = ('approval','validate','autolimit');
  461:     %validations = &Apache::lonnet::auto_courserequest_checks($cdom);
  462:     my $optregex = join('|',@options);
  463:     my %reqtitles = &courserequest_titles();
  464:     foreach my $item (@usertools) {
  465:         my ($curroption,$currlimit,$tooloff);
  466:         if ($userenv{'reqcrsotherdom.'.$item} ne '') {
  467:             my @curr = split(',',$userenv{'reqcrsotherdom.'.$item});
  468:             foreach my $req (@curr) {
  469:                 if ($req =~ /^\Q$cdom\E\:($optregex)=?(\d*)$/) {
  470:                     $curroption = $1;
  471:                     $currlimit = $2;
  472:                     last;
  473:                 }
  474:             }
  475:             if (!$curroption) {
  476:                 $curroption = 'norequest';
  477:                 $tooloff = ' checked="checked"';
  478:             }
  479:         } else {
  480:             $curroption = 'norequest';
  481:             $tooloff = ' checked="checked"';
  482:         }
  483:         $output.= &Apache::loncommon::start_data_table_row()."\n".
  484:                   '  <td><span class="LC_nobreak">'.$lt{$item}.': </span></td><td>'.
  485:                   '<table><tr><td valign="top">'."\n".
  486:                   '<label><input type="radio" name="reqcrsotherdom_'.$item.
  487:                   '" value=""'.$tooloff.' />'.$reqtitles{'norequest'}.
  488:                   '</label></td>';
  489:         foreach my $option (@options) {
  490:             if ($option eq 'validate') {
  491:                 my $canvalidate = 0;
  492:                 if (ref($validations{$item}) eq 'HASH') {
  493:                     if ($validations{$item}{'_external_'}) {
  494:                         $canvalidate = 1;
  495:                     }
  496:                 }
  497:                 next if (!$canvalidate);
  498:             }
  499:             my $checked = '';
  500:             if ($option eq $curroption) {
  501:                 $checked = ' checked="checked"';
  502:             }
  503:             $output .= '<td valign="top"><span class="LC_nobreak"><label>'.
  504:                        '<input type="radio" name="reqcrsotherdom_'.$item.
  505:                        '" value="'.$option.'"'.$checked.' />'.
  506:                        $reqtitles{$option}.'</label>';
  507:             if ($option eq 'autolimit') {
  508:                 $output .= '&nbsp;<input type="text" name="reqcrsotherdom_'.
  509:                            $item.'_limit" size="1" '.
  510:                            'value="'.$currlimit.'" /></span>'.
  511:                            '<br />'.$reqtitles{'unlimited'};
  512:             } else {
  513:                 $output .= '</span>';
  514:             }
  515:             $output .= '</td>';
  516:         }
  517:         $output .= '</td></tr></table></td>'."\n".
  518:                    &Apache::loncommon::end_data_table_row()."\n";
  519:     }
  520:     return $output;
  521: }
  522: 
  523: sub domainrole_req {
  524:     my ($ccuname,$ccdomain) = @_;
  525:     return '<br /><h3>'.
  526:            &mt('User Can Request Assignment of Domain Roles?').
  527:            '</h3>'."\n".
  528:            &Apache::loncommon::start_data_table().
  529:            &build_tools_display($ccuname,$ccdomain,
  530:                                 'requestauthor').
  531:            &Apache::loncommon::end_data_table();
  532: }
  533: 
  534: sub courserequest_titles {
  535:     my %titles = &Apache::lonlocal::texthash (
  536:                                    official   => 'Official',
  537:                                    unofficial => 'Unofficial',
  538:                                    community  => 'Communities',
  539:                                    textbook   => 'Textbook',
  540:                                    norequest  => 'Not allowed',
  541:                                    approval   => 'Approval by Dom. Coord.',
  542:                                    validate   => 'With validation',
  543:                                    autolimit  => 'Numerical limit',
  544:                                    unlimited  => '(blank for unlimited)',
  545:                  );
  546:     return %titles;
  547: }
  548: 
  549: sub courserequest_display {
  550:     my %titles = &Apache::lonlocal::texthash (
  551:                                    approval   => 'Yes, need approval',
  552:                                    validate   => 'Yes, with validation',
  553:                                    norequest  => 'No',
  554:    );
  555:    return %titles;
  556: }
  557: 
  558: sub requestauthor_titles {
  559:     my %titles = &Apache::lonlocal::texthash (
  560:                                    norequest  => 'Not allowed',
  561:                                    approval   => 'Approval by Dom. Coord.',
  562:                                    automatic  => 'Automatic approval',
  563:                  );
  564:     return %titles;
  565: 
  566: }
  567: 
  568: sub requestauthor_display {
  569:     my %titles = &Apache::lonlocal::texthash (
  570:                                    approval   => 'Yes, need approval',
  571:                                    automatic  => 'Yes, automatic approval',
  572:                                    norequest  => 'No',
  573:    );
  574:    return %titles;
  575: }
  576: 
  577: sub requestchange_display {
  578:     my %titles = &Apache::lonlocal::texthash (
  579:                                    approval   => "availability set to 'on' (approval required)", 
  580:                                    automatic  => "availability set to 'on' (automatic approval)",
  581:                                    norequest  => "availability set to 'off'",
  582:    );
  583:    return %titles;
  584: }
  585: 
  586: sub curr_requestauthor {
  587:     my ($uname,$udom,$isadv,$inststatuses,$domconfig) = @_;
  588:     return unless ((ref($inststatuses) eq 'ARRAY') && (ref($domconfig) eq 'HASH'));
  589:     if ($uname eq '' || $udom eq '') {
  590:         $uname = $env{'user.name'};
  591:         $udom = $env{'user.domain'};
  592:         $isadv = $env{'user.adv'};
  593:     }
  594:     my (%userenv,%settings,$val);
  595:     my @options = ('automatic','approval');
  596:     %userenv =
  597:         &Apache::lonnet::userenvironment($udom,$uname,'requestauthor','inststatus');
  598:     if ($userenv{'requestauthor'}) {
  599:         $val = $userenv{'requestauthor'};
  600:         @{$inststatuses} = ('_custom_');
  601:     } else {
  602:         my %alltasks;
  603:         if (ref($domconfig->{'requestauthor'}) eq 'HASH') {
  604:             %settings = %{$domconfig->{'requestauthor'}};
  605:             if (($isadv) && ($settings{'_LC_adv'} ne '')) {
  606:                 $val = $settings{'_LC_adv'};
  607:                 @{$inststatuses} = ('_LC_adv_');
  608:             } else {
  609:                 if ($userenv{'inststatus'} ne '') {
  610:                     @{$inststatuses} = split(',',$userenv{'inststatus'});
  611:                 } else {
  612:                     @{$inststatuses} = ('default');
  613:                 }
  614:                 foreach my $status (@{$inststatuses}) {
  615:                     if (exists($settings{$status})) {
  616:                         my $value = $settings{$status};
  617:                         next unless ($value);
  618:                         unless (exists($alltasks{$value})) {
  619:                             if (ref($alltasks{$value}) eq 'ARRAY') {
  620:                                 unless(grep(/^\Q$status\E$/,@{$alltasks{$value}})) {
  621:                                     push(@{$alltasks{$value}},$status);
  622:                                 }
  623:                             } else {
  624:                                 @{$alltasks{$value}} = ($status);
  625:                             }
  626:                         }
  627:                     }
  628:                 }
  629:                 foreach my $option (@options) {
  630:                     if ($alltasks{$option}) {
  631:                         $val = $option;
  632:                         last;
  633:                     }
  634:                 }
  635:             }
  636:         }
  637:     }
  638:     return $val;
  639: }
  640: 
  641: # =================================================================== Phase one
  642: 
  643: sub print_username_entry_form {
  644:     my ($r,$context,$response,$srch,$forcenewuser,$crstype,$brcrum) = @_;
  645:     my $defdom=$env{'request.role.domain'};
  646:     my $formtoset = 'crtuser';
  647:     if (exists($env{'form.startrolename'})) {
  648:         $formtoset = 'docustom';
  649:         $env{'form.rolename'} = $env{'form.startrolename'};
  650:     } elsif ($env{'form.origform'} eq 'crtusername') {
  651:         $formtoset =  $env{'form.origform'};
  652:     }
  653: 
  654:     my ($jsback,$elements) = &crumb_utilities();
  655: 
  656:     my $jscript = &Apache::loncommon::studentbrowser_javascript()."\n".
  657:         '<script type="text/javascript">'."\n".
  658:         '// <![CDATA['."\n".
  659:         &Apache::lonhtmlcommon::set_form_elements($elements->{$formtoset})."\n".
  660:         '// ]]>'."\n".
  661:         '</script>'."\n";
  662: 
  663:     my %existingroles=&Apache::lonuserutils::my_custom_roles($crstype);
  664:     if (($env{'form.action'} eq 'custom') && (keys(%existingroles) > 0)
  665:         && (&Apache::lonnet::allowed('mcr','/'))) {
  666:         $jscript .= &customrole_javascript();
  667:     }
  668:     my $helpitem = 'Course_Change_Privileges';
  669:     if ($env{'form.action'} eq 'custom') {
  670:         $helpitem = 'Course_Editing_Custom_Roles';
  671:     } elsif ($env{'form.action'} eq 'singlestudent') {
  672:         $helpitem = 'Course_Add_Student';
  673:     } elsif ($env{'form.action'} eq 'accesslogs') {
  674:         $helpitem = 'Domain_User_Access_Logs';
  675:     }
  676:     my %breadcrumb_text = &singleuser_breadcrumb($crstype,$context,$defdom);
  677:     if ($env{'form.action'} eq 'custom') {
  678:         push(@{$brcrum},
  679:                  {href=>"javascript:backPage(document.crtuser)",       
  680:                   text=>"Pick custom role",
  681:                   help => $helpitem,}
  682:                  );
  683:     } else {
  684:         push (@{$brcrum},
  685:                   {href => "javascript:backPage(document.crtuser)",
  686:                    text => $breadcrumb_text{'search'},
  687:                    help => $helpitem,
  688:                    faq  => 282,
  689:                    bug  => 'Instructor Interface',}
  690:                   );
  691:     }
  692:     my %loaditems = (
  693:                 'onload' => "javascript:setFormElements(document.$formtoset)",
  694:                     );
  695:     my $args = {bread_crumbs           => $brcrum,
  696:                 bread_crumbs_component => 'User Management',
  697:                 add_entries            => \%loaditems,};
  698:     $r->print(&Apache::loncommon::start_page('User Management',$jscript,$args));
  699: 
  700:     my %lt=&Apache::lonlocal::texthash(
  701:                     'srst' => 'Search for a user and enroll as a student',
  702:                     'srme' => 'Search for a user and enroll as a member',
  703:                     'srad' => 'Search for a user and modify/add user information or roles',
  704:                     'srvu' => 'Search for a user and view user information and roles',
  705:                     'srva' => 'Search for a user and view access log information',
  706: 		    'usr'  => "Username",
  707:                     'dom'  => "Domain",
  708:                     'ecrp' => "Define or Edit Custom Role",
  709:                     'nr'   => "role name",
  710:                     'cre'  => "Next",
  711: 				       );
  712: 
  713:     if ($env{'form.action'} eq 'custom') {
  714:         if (&Apache::lonnet::allowed('mcr','/')) {
  715:             my $newroletext = &mt('Define new custom role:');
  716:             $r->print('<form action="/adm/createuser" method="post" name="docustom">'.
  717:                       '<input type="hidden" name="action" value="'.$env{'form.action'}.'" />'.
  718:                       '<input type="hidden" name="phase" value="selected_custom_edit" />'.
  719:                       '<h3>'.$lt{'ecrp'}.'</h3>'.
  720:                       &Apache::loncommon::start_data_table().
  721:                       &Apache::loncommon::start_data_table_row().
  722:                       '<td>');
  723:             if (keys(%existingroles) > 0) {
  724:                 $r->print('<br /><label><input type="radio" name="customroleaction" value="new" checked="checked" onclick="setCustomFields();" /><b>'.$newroletext.'</b></label>');
  725:             } else {
  726:                 $r->print('<br /><input type="hidden" name="customroleaction" value="new" /><b>'.$newroletext.'</b>');
  727:             }
  728:             $r->print('</td><td align="center">'.$lt{'nr'}.'<br /><input type="text" size="15" name="newrolename" onfocus="setCustomAction('."'new'".');" /></td>'.
  729:                       &Apache::loncommon::end_data_table_row());
  730:             if (keys(%existingroles) > 0) {
  731:                 $r->print(&Apache::loncommon::start_data_table_row().'<td><br />'.
  732:                           '<label><input type="radio" name="customroleaction" value="edit" onclick="setCustomFields();"/><b>'.
  733:                           &mt('View/Modify existing role:').'</b></label></td>'.
  734:                           '<td align="center"><br />'.
  735:                           '<select name="rolename" onchange="setCustomAction('."'edit'".');">'.
  736:                           '<option value="" selected="selected">'.
  737:                           &mt('Select'));
  738:                 foreach my $role (sort(keys(%existingroles))) {
  739:                     $r->print('<option value="'.$role.'">'.$role.'</option>');
  740:                 }
  741:                 $r->print('</select>'.
  742:                           '</td>'.
  743:                           &Apache::loncommon::end_data_table_row());
  744:             }
  745:             $r->print(&Apache::loncommon::end_data_table().'<p>'.
  746:                       '<input name="customeditor" type="submit" value="'.
  747:                       $lt{'cre'}.'" /></p>'.
  748:                       '</form>');
  749:         }
  750:     } else {
  751:         my $actiontext = $lt{'srad'};
  752:         if ($env{'form.action'} eq 'singlestudent') {
  753:             if ($crstype eq 'Community') {
  754:                 $actiontext = $lt{'srme'};
  755:             } else {
  756:                 $actiontext = $lt{'srst'};
  757:             }
  758:         } elsif ($env{'form.action'} eq 'accesslogs') {
  759:             $actiontext = $lt{'srva'};
  760:         } elsif (($env{'form.action'} eq 'singleuser') &&
  761:                  ($context eq 'domain') && (!&Apache::lonnet::allowed('mau',$defdom))) {
  762:             $actiontext = $lt{'srvu'};
  763:         }
  764:         $r->print("<h3>$actiontext</h3>");
  765:         if ($env{'form.origform'} ne 'crtusername') {
  766:             if ($response) {
  767:                $r->print("\n<div>$response</div>".
  768:                          '<br clear="all" />');
  769:             }
  770:         }
  771:         $r->print(&entry_form($defdom,$srch,$forcenewuser,$context,$response,$crstype,1));
  772:     }
  773: }
  774: 
  775: sub customrole_javascript {
  776:     my $js = <<"END";
  777: <script type="text/javascript">
  778: // <![CDATA[
  779: 
  780: function setCustomFields() {
  781:     if (document.docustom.customroleaction.length > 0) {
  782:         for (var i=0; i<document.docustom.customroleaction.length; i++) {
  783:             if (document.docustom.customroleaction[i].checked) {
  784:                 if (document.docustom.customroleaction[i].value == 'new') {
  785:                     document.docustom.rolename.selectedIndex = 0;
  786:                 } else {
  787:                     document.docustom.newrolename.value = '';
  788:                 }
  789:             }
  790:         }
  791:     }
  792:     return;
  793: }
  794: 
  795: function setCustomAction(caller) {
  796:     if (document.docustom.customroleaction.length > 0) {
  797:         for (var i=0; i<document.docustom.customroleaction.length; i++) {
  798:             if (document.docustom.customroleaction[i].value == caller) {
  799:                 document.docustom.customroleaction[i].checked = true;
  800:             }
  801:         }
  802:     }
  803:     setCustomFields();
  804:     return;
  805: }
  806: 
  807: // ]]>
  808: </script>
  809: END
  810:     return $js;
  811: }
  812: 
  813: sub entry_form {
  814:     my ($dom,$srch,$forcenewuser,$context,$responsemsg,$crstype,$fixeddom) = @_;
  815:     my ($usertype,$inexact);
  816:     if (ref($srch) eq 'HASH') {
  817:         if (($srch->{'srchin'} eq 'dom') &&
  818:             ($srch->{'srchby'} eq 'uname') &&
  819:             ($srch->{'srchtype'} eq 'exact') &&
  820:             ($srch->{'srchdomain'} ne '') &&
  821:             ($srch->{'srchterm'} ne '')) {
  822:             my (%curr_rules,%got_rules);
  823:             my ($rules,$ruleorder) =
  824:                 &Apache::lonnet::inst_userrules($srch->{'srchdomain'},'username');
  825:             $usertype = &Apache::lonuserutils::check_usertype($srch->{'srchdomain'},$srch->{'srchterm'},$rules,\%curr_rules,\%got_rules);
  826:         } else {
  827:             $inexact = 1;
  828:         }
  829:     }
  830:     my $cancreate =
  831:         &Apache::lonuserutils::can_create_user($dom,$context,$usertype);
  832:     my ($userpicker,$cansearch) = 
  833:        &Apache::loncommon::user_picker($dom,$srch,$forcenewuser,
  834:                                        'document.crtuser',$cancreate,$usertype,$context,$fixeddom);
  835:     my $srchbutton = &mt('Search');
  836:     if ($env{'form.action'} eq 'singlestudent') {
  837:         $srchbutton = &mt('Search and Enroll');
  838:     } elsif ($env{'form.action'} eq 'accesslogs') {
  839:         $srchbutton = &mt('Search');
  840:     } elsif ($cancreate && $responsemsg ne '' && $inexact) {
  841:         $srchbutton = &mt('Search or Add New User');
  842:     }
  843:     my $output;
  844:     if ($cansearch) {
  845:         $output = <<"ENDBLOCK";
  846: <form action="/adm/createuser" method="post" name="crtuser">
  847: <input type="hidden" name="action" value="$env{'form.action'}" />
  848: <input type="hidden" name="phase" value="get_user_info" />
  849: $userpicker
  850: <input name="userrole" type="button" value="$srchbutton" onclick="javascript:validateEntry(document.crtuser)" />
  851: </form>
  852: ENDBLOCK
  853:     } else {
  854:         $output = '<p>'.$userpicker.'</p>';
  855:     }
  856:     if (($env{'form.phase'} eq '') && ($env{'form.action'} ne 'accesslogs') &&
  857:         (!(($env{'form.action'} eq 'singleuser') && ($context eq 'domain') &&
  858:         (!&Apache::lonnet::allowed('mau',$env{'request.role.domain'}))))) {
  859:         my $defdom=$env{'request.role.domain'};
  860:         my $domform = &Apache::loncommon::select_dom_form($defdom,'srchdomain');
  861:         my %lt=&Apache::lonlocal::texthash(
  862:                   'enro' => 'Enroll one student',
  863:                   'enrm' => 'Enroll one member',
  864:                   'admo' => 'Add/modify a single user',
  865:                   'crea' => 'create new user if required',
  866:                   'uskn' => "username is known",
  867:                   'crnu' => 'Create a new user',
  868:                   'usr'  => 'Username',
  869:                   'dom'  => 'in domain',
  870:                   'enrl' => 'Enroll',
  871:                   'cram'  => 'Create/Modify user',
  872:         );
  873:         my $sellink=&Apache::loncommon::selectstudent_link('crtusername','srchterm','srchdomain');
  874:         my ($title,$buttontext,$showresponse);
  875:         if ($env{'form.action'} eq 'singlestudent') {
  876:             if ($crstype eq 'Community') {
  877:                 $title = $lt{'enrm'};
  878:             } else {
  879:                 $title = $lt{'enro'};
  880:             }
  881:             $buttontext = $lt{'enrl'};
  882:         } else {
  883:             $title = $lt{'admo'};
  884:             $buttontext = $lt{'cram'};
  885:         }
  886:         if ($cancreate) {
  887:             $title .= ' <span class="LC_cusr_subheading">('.$lt{'crea'}.')</span>';
  888:         } else {
  889:             $title .= ' <span class="LC_cusr_subheading">('.$lt{'uskn'}.')</span>';
  890:         }
  891:         if ($env{'form.origform'} eq 'crtusername') {
  892:             $showresponse = $responsemsg;
  893:         }
  894:         $output .= <<"ENDDOCUMENT";
  895: <br />
  896: <form action="/adm/createuser" method="post" name="crtusername">
  897: <input type="hidden" name="action" value="$env{'form.action'}" />
  898: <input type="hidden" name="phase" value="createnewuser" />
  899: <input type="hidden" name="srchtype" value="exact" />
  900: <input type="hidden" name="srchby" value="uname" />
  901: <input type="hidden" name="srchin" value="dom" />
  902: <input type="hidden" name="forcenewuser" value="1" />
  903: <input type="hidden" name="origform" value="crtusername" />
  904: <h3>$title</h3>
  905: $showresponse
  906: <table>
  907:  <tr>
  908:   <td>$lt{'usr'}:</td>
  909:   <td><input type="text" size="15" name="srchterm" /></td>
  910:   <td>&nbsp;$lt{'dom'}:</td><td>$domform</td>
  911:   <td>&nbsp;$sellink&nbsp;</td>
  912:   <td>&nbsp;<input name="userrole" type="submit" value="$buttontext" /></td>
  913:  </tr>
  914: </table>
  915: </form>
  916: ENDDOCUMENT
  917:     }
  918:     return $output;
  919: }
  920: 
  921: sub user_modification_js {
  922:     my ($pjump_def,$dc_setcourse_code,$nondc_setsection_code,$groupslist)=@_;
  923:     
  924:     return <<END;
  925: <script type="text/javascript" language="Javascript">
  926: // <![CDATA[
  927: 
  928:     $pjump_def
  929:     $dc_setcourse_code
  930: 
  931:     function dateset() {
  932:         eval("document.cu."+document.cu.pres_marker.value+
  933:             ".value=document.cu.pres_value.value");
  934:         modalWindow.close();
  935:     }
  936: 
  937:     $nondc_setsection_code
  938: // ]]>
  939: </script>
  940: END
  941: }
  942: 
  943: # =================================================================== Phase two
  944: sub print_user_selection_page {
  945:     my ($r,$response,$srch,$srch_results,$srcharray,$context,$opener_elements,$crstype,$brcrum) = @_;
  946:     my @fields = ('username','domain','lastname','firstname','permanentemail');
  947:     my $sortby = $env{'form.sortby'};
  948: 
  949:     if (!grep(/^\Q$sortby\E$/,@fields)) {
  950:         $sortby = 'lastname';
  951:     }
  952: 
  953:     my ($jsback,$elements) = &crumb_utilities();
  954: 
  955:     my $jscript = (<<ENDSCRIPT);
  956: <script type="text/javascript">
  957: // <![CDATA[
  958: function pickuser(uname,udom) {
  959:     document.usersrchform.seluname.value=uname;
  960:     document.usersrchform.seludom.value=udom;
  961:     document.usersrchform.phase.value="userpicked";
  962:     document.usersrchform.submit();
  963: }
  964: 
  965: $jsback
  966: // ]]>
  967: </script>
  968: ENDSCRIPT
  969: 
  970:     my %lt=&Apache::lonlocal::texthash(
  971:                                        'usrch'          => "User Search to add/modify roles",
  972:                                        'stusrch'        => "User Search to enroll student",
  973:                                        'memsrch'        => "User Search to enroll member",
  974:                                        'srcva'          => "Search for a user and view access log information",
  975:                                        'usrvu'          => "User Search to view user roles",
  976:                                        'usel'           => "Select a user to add/modify roles",
  977:                                        'suvr'           => "Select a user to view roles",
  978:                                        'stusel'         => "Select a user to enroll as a student",
  979:                                        'memsel'         => "Select a user to enroll as a member",
  980:                                        'vacsel'         => "Select a user to view access log",
  981:                                        'username'       => "username",
  982:                                        'domain'         => "domain",
  983:                                        'lastname'       => "last name",
  984:                                        'firstname'      => "first name",
  985:                                        'permanentemail' => "permanent e-mail",
  986:                                       );
  987:     if ($context eq 'requestcrs') {
  988:         $r->print('<div>');
  989:     } else {
  990:         my %breadcrumb_text = &singleuser_breadcrumb($crstype,$context,$srch->{'srchdomain'});
  991:         my $helpitem;
  992:         if ($env{'form.action'} eq 'singleuser') {
  993:             $helpitem = 'Course_Change_Privileges';
  994:         } elsif ($env{'form.action'} eq 'singlestudent') {
  995:             $helpitem = 'Course_Add_Student';
  996:         }
  997:         push (@{$brcrum},
  998:                   {href => "javascript:backPage(document.usersrchform,'','')",
  999:                    text => $breadcrumb_text{'search'},
 1000:                    faq  => 282,
 1001:                    bug  => 'Instructor Interface',},
 1002:                   {href => "javascript:backPage(document.usersrchform,'get_user_info','select')",
 1003:                    text => $breadcrumb_text{'userpicked'},
 1004:                    faq  => 282,
 1005:                    bug  => 'Instructor Interface',
 1006:                    help => $helpitem}
 1007:                   );
 1008:         $r->print(&Apache::loncommon::start_page('User Management',$jscript,{bread_crumbs => $brcrum}));
 1009:         if ($env{'form.action'} eq 'singleuser') {
 1010:             my $readonly;
 1011:             if (($context eq 'domain') && (!&Apache::lonnet::allowed('mau',$srch->{'srchdomain'}))) {
 1012:                 $readonly = 1;
 1013:                 $r->print("<b>$lt{'usrvu'}</b><br />");
 1014:             } else {
 1015:                 $r->print("<b>$lt{'usrch'}</b><br />");
 1016:             }
 1017:             $r->print(&entry_form($srch->{'srchdomain'},$srch,undef,$context,undef,$crstype));
 1018:             if ($readonly) {
 1019:                 $r->print('<h3>'.$lt{'suvr'}.'</h3>');
 1020:             } else {
 1021:                 $r->print('<h3>'.$lt{'usel'}.'</h3>');
 1022:             }
 1023:         } elsif ($env{'form.action'} eq 'singlestudent') {
 1024:             $r->print($jscript."<b>");
 1025:             if ($crstype eq 'Community') {
 1026:                 $r->print($lt{'memsrch'});
 1027:             } else {
 1028:                 $r->print($lt{'stusrch'});
 1029:             }
 1030:             $r->print("</b><br />");
 1031:             $r->print(&entry_form($srch->{'srchdomain'},$srch,undef,$context,undef,$crstype));
 1032:             $r->print('</form><h3>');
 1033:             if ($crstype eq 'Community') {
 1034:                 $r->print($lt{'memsel'});
 1035:             } else {
 1036:                 $r->print($lt{'stusel'});
 1037:             }
 1038:             $r->print('</h3>');
 1039:         } elsif ($env{'form.action'} eq 'accesslogs') {
 1040:             $r->print("<b>$lt{'srcva'}</b><br />");
 1041:             $r->print(&entry_form($srch->{'srchdomain'},$srch,undef,'accesslogs',undef,undef,1));
 1042:             $r->print('<h3>'.$lt{'vacsel'}.'</h3>');
 1043:         }
 1044:     }
 1045:     $r->print('<form name="usersrchform" method="post" action="">'.
 1046:               &Apache::loncommon::start_data_table()."\n".
 1047:               &Apache::loncommon::start_data_table_header_row()."\n".
 1048:               ' <th> </th>'."\n");
 1049:     foreach my $field (@fields) {
 1050:         $r->print(' <th><a href="javascript:document.usersrchform.sortby.value='.
 1051:                   "'".$field."'".';document.usersrchform.submit();">'.
 1052:                   $lt{$field}.'</a></th>'."\n");
 1053:     }
 1054:     $r->print(&Apache::loncommon::end_data_table_header_row());
 1055: 
 1056:     my @sorted_users = sort {
 1057:         lc($srch_results->{$a}->{$sortby})   cmp lc($srch_results->{$b}->{$sortby})
 1058:             ||
 1059:         lc($srch_results->{$a}->{lastname})  cmp lc($srch_results->{$b}->{lastname})
 1060:             ||
 1061:         lc($srch_results->{$a}->{firstname}) cmp lc($srch_results->{$b}->{firstname})
 1062: 	    ||
 1063: 	lc($a) cmp lc($b)
 1064:         } (keys(%$srch_results));
 1065: 
 1066:     foreach my $user (@sorted_users) {
 1067:         my ($uname,$udom) = split(/:/,$user);
 1068:         my $onclick;
 1069:         if ($context eq 'requestcrs') {
 1070:             $onclick =
 1071:                 'onclick="javascript:gochoose('."'$uname','$udom',".
 1072:                                                "'$srch_results->{$user}->{firstname}',".
 1073:                                                "'$srch_results->{$user}->{lastname}',".
 1074:                                                "'$srch_results->{$user}->{permanentemail}'".');"';
 1075:         } else {
 1076:             $onclick =
 1077:                 ' onclick="javascript:pickuser('."'".$uname."'".','."'".$udom."'".');"';
 1078:         }
 1079:         $r->print(&Apache::loncommon::start_data_table_row().
 1080:                   '<td><input type="button" name="seluser" value="'.&mt('Select').'" '.
 1081:                   $onclick.' /></td>'.
 1082:                   '<td><tt>'.$uname.'</tt></td>'.
 1083:                   '<td><tt>'.$udom.'</tt></td>');
 1084:         foreach my $field ('lastname','firstname','permanentemail') {
 1085:             $r->print('<td>'.$srch_results->{$user}->{$field}.'</td>');
 1086:         }
 1087:         $r->print(&Apache::loncommon::end_data_table_row());
 1088:     }
 1089:     $r->print(&Apache::loncommon::end_data_table().'<br /><br />');
 1090:     if (ref($srcharray) eq 'ARRAY') {
 1091:         foreach my $item (@{$srcharray}) {
 1092:             $r->print('<input type="hidden" name="'.$item.'" value="'.$env{'form.'.$item}.'" />'."\n");
 1093:         }
 1094:     }
 1095:     $r->print(' <input type="hidden" name="sortby" value="'.$sortby.'" />'."\n".
 1096:               ' <input type="hidden" name="seluname" value="" />'."\n".
 1097:               ' <input type="hidden" name="seludom" value="" />'."\n".
 1098:               ' <input type="hidden" name="currstate" value="select" />'."\n".
 1099:               ' <input type="hidden" name="phase" value="get_user_info" />'."\n".
 1100:               ' <input type="hidden" name="action" value="'.$env{'form.action'}.'" />'."\n");
 1101:     if ($context eq 'requestcrs') {
 1102:         $r->print($opener_elements.'</form></div>');
 1103:     } else {
 1104:         $r->print($response.'</form>');
 1105:     }
 1106: }
 1107: 
 1108: sub print_user_query_page {
 1109:     my ($r,$caller,$brcrum) = @_;
 1110: # FIXME - this is for a network-wide name search (similar to catalog search)
 1111: # To use frames with similar behavior to catalog/portfolio search.
 1112: # To be implemented. 
 1113:     return;
 1114: }
 1115: 
 1116: sub print_user_modification_page {
 1117:     my ($r,$ccuname,$ccdomain,$srch,$response,$context,$permission,$crstype,
 1118:         $brcrum,$showcredits) = @_;
 1119:     if (($ccuname eq '') || ($ccdomain eq '')) {
 1120:         my $usermsg = &mt('No username and/or domain provided.');
 1121:         $env{'form.phase'} = '';
 1122: 	&print_username_entry_form($r,$context,$usermsg,'','',$crstype,$brcrum);
 1123:         return;
 1124:     }
 1125:     my ($form,$formname);
 1126:     if ($env{'form.action'} eq 'singlestudent') {
 1127:         $form = 'document.enrollstudent';
 1128:         $formname = 'enrollstudent';
 1129:     } else {
 1130:         $form = 'document.cu';
 1131:         $formname = 'cu';
 1132:     }
 1133:     my %abv_auth = &auth_abbrev();
 1134:     my (%rulematch,%inst_results,$newuser,%alerts,%curr_rules,%got_rules);
 1135:     my $uhome=&Apache::lonnet::homeserver($ccuname,$ccdomain);
 1136:     if ($uhome eq 'no_host') {
 1137:         my $usertype;
 1138:         my ($rules,$ruleorder) =
 1139:             &Apache::lonnet::inst_userrules($ccdomain,'username');
 1140:             $usertype =
 1141:                 &Apache::lonuserutils::check_usertype($ccdomain,$ccuname,$rules,
 1142:                                                       \%curr_rules,\%got_rules);
 1143:         my $cancreate =
 1144:             &Apache::lonuserutils::can_create_user($ccdomain,$context,
 1145:                                                    $usertype);
 1146:         if (!$cancreate) {
 1147:             my $helplink = 'javascript:helpMenu('."'display'".')';
 1148:             my %usertypetext = (
 1149:                 official   => 'institutional',
 1150:                 unofficial => 'non-institutional',
 1151:             );
 1152:             my $response;
 1153:             if ($env{'form.origform'} eq 'crtusername') {
 1154:                 $response = '<span class="LC_warning">'.
 1155:                             &mt('No match found for the username [_1] in LON-CAPA domain: [_2]',
 1156:                                 '<b>'.$ccuname.'</b>',$ccdomain).
 1157:                             '</span><br />';
 1158:             }
 1159:             $response .= '<p class="LC_warning">'
 1160:                         .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
 1161:                         .' ';
 1162:             if ($context eq 'domain') {
 1163:                 $response .= &mt('Please contact a [_1] for assistance.',
 1164:                                  &Apache::lonnet::plaintext('dc'));
 1165:             } else {
 1166:                 $response .= &mt('Please contact the [_1]helpdesk[_2] for assistance.'
 1167:                                 ,'<a href="'.$helplink.'">','</a>');
 1168:             }
 1169:             $response .= '</p><br />';
 1170:             $env{'form.phase'} = '';
 1171:             &print_username_entry_form($r,$context,$response,undef,undef,$crstype,$brcrum);
 1172:             return;
 1173:         }
 1174:         $newuser = 1;
 1175:         my $checkhash;
 1176:         my $checks = { 'username' => 1 };
 1177:         $checkhash->{$ccuname.':'.$ccdomain} = { 'newuser' => $newuser };
 1178:         &Apache::loncommon::user_rule_check($checkhash,$checks,
 1179:             \%alerts,\%rulematch,\%inst_results,\%curr_rules,\%got_rules);
 1180:         if (ref($alerts{'username'}) eq 'HASH') {
 1181:             if (ref($alerts{'username'}{$ccdomain}) eq 'HASH') {
 1182:                 my $domdesc =
 1183:                     &Apache::lonnet::domain($ccdomain,'description');
 1184:                 if ($alerts{'username'}{$ccdomain}{$ccuname}) {
 1185:                     my $userchkmsg;
 1186:                     if (ref($curr_rules{$ccdomain}) eq 'HASH') {  
 1187:                         $userchkmsg = 
 1188:                             &Apache::loncommon::instrule_disallow_msg('username',
 1189:                                                                  $domdesc,1).
 1190:                         &Apache::loncommon::user_rule_formats($ccdomain,
 1191:                             $domdesc,$curr_rules{$ccdomain}{'username'},
 1192:                             'username');
 1193:                     }
 1194:                     $env{'form.phase'} = '';
 1195:                     &print_username_entry_form($r,$context,$userchkmsg,undef,undef,$crstype,$brcrum);
 1196:                     return;
 1197:                 }
 1198:             }
 1199:         }
 1200:     } else {
 1201:         $newuser = 0;
 1202:     }
 1203:     if ($response) {
 1204:         $response = '<br />'.$response;
 1205:     }
 1206: 
 1207:     my $pjump_def = &Apache::lonhtmlcommon::pjump_javascript_definition();
 1208:     my $dc_setcourse_code = '';
 1209:     my $nondc_setsection_code = '';                                        
 1210:     my %loaditem;
 1211: 
 1212:     my $groupslist = &Apache::lonuserutils::get_groupslist();
 1213: 
 1214:     my $js = &validation_javascript($context,$ccdomain,$pjump_def,$crstype,
 1215:                                $groupslist,$newuser,$formname,\%loaditem);
 1216:     my %breadcrumb_text = &singleuser_breadcrumb($crstype,$context,$ccdomain);
 1217:     my $helpitem = 'Course_Change_Privileges';
 1218:     if ($env{'form.action'} eq 'singlestudent') {
 1219:         $helpitem = 'Course_Add_Student';
 1220:     }
 1221:     push (@{$brcrum},
 1222:         {href => "javascript:backPage($form)",
 1223:          text => $breadcrumb_text{'search'},
 1224:          faq  => 282,
 1225:          bug  => 'Instructor Interface',});
 1226:     if ($env{'form.phase'} eq 'userpicked') {
 1227:        push(@{$brcrum},
 1228:               {href => "javascript:backPage($form,'get_user_info','select')",
 1229:                text => $breadcrumb_text{'userpicked'},
 1230:                faq  => 282,
 1231:                bug  => 'Instructor Interface',});
 1232:     }
 1233:     push(@{$brcrum},
 1234:             {href => "javascript:backPage($form,'$env{'form.phase'}','modify')",
 1235:              text => $breadcrumb_text{'modify'},
 1236:              faq  => 282,
 1237:              bug  => 'Instructor Interface',
 1238:              help => $helpitem});
 1239:     my $args = {'add_entries'           => \%loaditem,
 1240:                 'bread_crumbs'          => $brcrum,
 1241:                 'bread_crumbs_component' => 'User Management'};
 1242:     if ($env{'form.popup'}) {
 1243:         $args->{'no_nav_bar'} = 1;
 1244:     }
 1245:     my $start_page =
 1246:         &Apache::loncommon::start_page('User Management',$js,$args);
 1247: 
 1248:     my $forminfo =<<"ENDFORMINFO";
 1249: <form action="/adm/createuser" method="post" name="$formname">
 1250: <input type="hidden" name="phase" value="update_user_data" />
 1251: <input type="hidden" name="ccuname" value="$ccuname" />
 1252: <input type="hidden" name="ccdomain" value="$ccdomain" />
 1253: <input type="hidden" name="pres_value"  value="" />
 1254: <input type="hidden" name="pres_type"   value="" />
 1255: <input type="hidden" name="pres_marker" value="" />
 1256: ENDFORMINFO
 1257:     my (%inccourses,$roledom,$defaultcredits);
 1258:     if ($context eq 'course') {
 1259:         $inccourses{$env{'request.course.id'}}=1;
 1260:         $roledom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 1261:         if ($showcredits) {
 1262:             $defaultcredits = &Apache::lonuserutils::get_defaultcredits();
 1263:         }
 1264:     } elsif ($context eq 'author') {
 1265:         $roledom = $env{'request.role.domain'};
 1266:     } elsif ($context eq 'domain') {
 1267:         foreach my $key (keys(%env)) {
 1268:             $roledom = $env{'request.role.domain'};
 1269:             if ($key=~/^user\.priv\.cm\.\/($roledom)\/($match_username)/) {
 1270:                 $inccourses{$1.'_'.$2}=1;
 1271:             }
 1272:         }
 1273:     } else {
 1274:         foreach my $key (keys(%env)) {
 1275: 	    if ($key=~/^user\.priv\.cm\.\/($match_domain)\/($match_username)/) {
 1276: 	        $inccourses{$1.'_'.$2}=1;
 1277:             }
 1278:         }
 1279:     }
 1280:     my $title = '';
 1281:     if ($newuser) {
 1282:         my ($portfolioform,$domroleform);
 1283:         if ((&Apache::lonnet::allowed('mpq',$env{'request.role.domain'})) ||
 1284:             (&Apache::lonnet::allowed('mut',$env{'request.role.domain'}))) {
 1285:             # Current user has quota or user tools modification privileges
 1286:             $portfolioform = '<br />'.&user_quotas($ccuname,$ccdomain);
 1287:         }
 1288:         if ((&Apache::lonnet::allowed('cau',$env{'request.role.domain'})) &&
 1289:             ($ccdomain eq $env{'request.role.domain'})) {
 1290:             $domroleform = '<br />'.&domainrole_req($ccuname,$ccdomain);
 1291:         }
 1292:         &initialize_authen_forms($ccdomain,$formname);
 1293:         my %lt=&Apache::lonlocal::texthash(
 1294:                 'lg'             => 'Login Data',
 1295:                 'hs'             => "Home Server",
 1296:         );
 1297: 	$r->print(<<ENDTITLE);
 1298: $start_page
 1299: $response
 1300: $forminfo
 1301: <script type="text/javascript" language="Javascript">
 1302: // <![CDATA[
 1303: $loginscript
 1304: // ]]>
 1305: </script>
 1306: <input type='hidden' name='makeuser' value='1' />
 1307: ENDTITLE
 1308:         if ($env{'form.action'} eq 'singlestudent') {
 1309:             if ($crstype eq 'Community') {
 1310:                 $title = &mt('Create New User [_1] in domain [_2] as a member',
 1311:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1312:             } else {
 1313:                 $title = &mt('Create New User [_1] in domain [_2] as a student',
 1314:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1315:             }
 1316:         } else {
 1317:                 $title = &mt('Create New User [_1] in domain [_2]',
 1318:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1319:         }
 1320:         $r->print('<h2>'.$title.'</h2>'."\n");
 1321:         $r->print('<div class="LC_left_float">');
 1322:         $r->print(&personal_data_display($ccuname,$ccdomain,$newuser,$context,
 1323:                                          $inst_results{$ccuname.':'.$ccdomain}));
 1324:         # Option to disable student/employee ID conflict checking not offerred for new users.
 1325:         my ($home_server_pick,$numlib) = 
 1326:             &Apache::loncommon::home_server_form_item($ccdomain,'hserver',
 1327:                                                       'default','hide');
 1328:         if ($numlib > 1) {
 1329:             $r->print("
 1330: <br />
 1331: $lt{'hs'}: $home_server_pick
 1332: <br />");
 1333:         } else {
 1334:             $r->print($home_server_pick);
 1335:         }
 1336:         if (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) {
 1337:             $r->print('<br /><h3>'.
 1338:                       &mt('User Can Request Creation of Courses/Communities in this Domain?').'</h3>'.
 1339:                       &Apache::loncommon::start_data_table().
 1340:                       &build_tools_display($ccuname,$ccdomain,
 1341:                                            'requestcourses').
 1342:                       &Apache::loncommon::end_data_table());
 1343:         }
 1344:         $r->print('</div>'."\n".'<div class="LC_left_float"><h3>'.
 1345:                   $lt{'lg'}.'</h3>');
 1346:         my ($fixedauth,$varauth,$authmsg); 
 1347:         if (ref($rulematch{$ccuname.':'.$ccdomain}) eq 'HASH') {
 1348:             my $matchedrule = $rulematch{$ccuname.':'.$ccdomain}{'username'};
 1349:             my ($rules,$ruleorder) = 
 1350:                 &Apache::lonnet::inst_userrules($ccdomain,'username');
 1351:             if (ref($rules) eq 'HASH') {
 1352:                 if (ref($rules->{$matchedrule}) eq 'HASH') {
 1353:                     my $authtype = $rules->{$matchedrule}{'authtype'};
 1354:                     if ($authtype !~ /^(krb4|krb5|int|fsys|loc)$/) {
 1355:                         $r->print(&Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc));
 1356:                     } else { 
 1357:                         my $authparm = $rules->{$matchedrule}{'authparm'};
 1358:                         $authmsg = $rules->{$matchedrule}{'authmsg'};
 1359:                         if ($authtype =~ /^krb(4|5)$/) {
 1360:                             my $ver = $1;
 1361:                             if ($authparm ne '') {
 1362:                                 $fixedauth = <<"KERB"; 
 1363: <input type="hidden" name="login" value="krb" />
 1364: <input type="hidden" name="krbver" value="$ver" />
 1365: <input type="hidden" name="krbarg" value="$authparm" />
 1366: KERB
 1367:                             }
 1368:                         } else {
 1369:                             $fixedauth = 
 1370: '<input type="hidden" name="login" value="'.$authtype.'" />'."\n";
 1371:                             if ($rules->{$matchedrule}{'authparmfixed'}) {
 1372:                                 $fixedauth .=    
 1373: '<input type="hidden" name="'.$authtype.'arg" value="'.$authparm.'" />'."\n";
 1374:                             } else {
 1375:                                 if ($authtype eq 'int') {
 1376:                                     $varauth = '<br />'.
 1377: &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>';
 1378:                                 } elsif ($authtype eq 'loc') {
 1379:                                     $varauth = '<br />'.
 1380: &mt('[_1] Local Authentication with argument [_2]','','<input type="text" name="'.$authtype.'arg" value="" />')."\n";
 1381:                                 } else {
 1382:                                     $varauth =
 1383: '<input type="text" name="'.$authtype.'arg" value="" />'."\n";
 1384:                                 }
 1385:                             }
 1386:                         }
 1387:                     }
 1388:                 } else {
 1389:                     $r->print(&Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc));
 1390:                 }
 1391:             }
 1392:             if ($authmsg) {
 1393:                 $r->print(<<ENDAUTH);
 1394: $fixedauth
 1395: $authmsg
 1396: $varauth
 1397: ENDAUTH
 1398:             }
 1399:         } else {
 1400:             $r->print(&Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc)); 
 1401:         }
 1402:         $r->print($portfolioform.$domroleform);
 1403:         if ($env{'form.action'} eq 'singlestudent') {
 1404:             $r->print(&date_sections_select($context,$newuser,$formname,
 1405:                                             $permission,$crstype,$ccuname,
 1406:                                             $ccdomain,$showcredits));
 1407:         }
 1408:         $r->print('</div><div class="LC_clear_float_footer"></div>');
 1409:     } else { # user already exists
 1410: 	$r->print($start_page.$forminfo);
 1411:         if ($env{'form.action'} eq 'singlestudent') {
 1412:             if ($crstype eq 'Community') {
 1413:                 $title = &mt('Enroll one member: [_1] in domain [_2]',
 1414:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1415:             } else {
 1416:                 $title = &mt('Enroll one student: [_1] in domain [_2]',
 1417:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1418:             }
 1419:         } else {
 1420:             if ($permission->{'cusr'}) {
 1421:                 $title = &mt('Modify existing user: [_1] in domain [_2]',
 1422:                              '"'.$ccuname.'"','"'.$ccdomain.'"');
 1423:             } else {
 1424:                 $title = &mt('Existing user: [_1] in domain [_2]',
 1425:                              '"'.$ccuname.'"','"'.$ccdomain.'"');
 1426:             }
 1427:         }
 1428:         $r->print('<h2>'.$title.'</h2>'."\n");
 1429:         $r->print('<div class="LC_left_float">');
 1430:         $r->print(&personal_data_display($ccuname,$ccdomain,$newuser,$context,
 1431:                                          $inst_results{$ccuname.':'.$ccdomain}));
 1432:         if ((&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) ||
 1433:             (&Apache::lonnet::allowed('udp',$env{'request.role.domain'}))) {
 1434:             $r->print('<br /><h3>'.&mt('User Can Request Creation of Courses/Communities in this Domain?').'</h3>'.
 1435:                       &Apache::loncommon::start_data_table());
 1436:             if ($env{'request.role.domain'} eq $ccdomain) {
 1437:                 $r->print(&build_tools_display($ccuname,$ccdomain,'requestcourses'));
 1438:             } else {
 1439:                 $r->print(&coursereq_externaluser($ccuname,$ccdomain,
 1440:                                                   $env{'request.role.domain'}));
 1441:             }
 1442:             $r->print(&Apache::loncommon::end_data_table());
 1443:         }
 1444:         $r->print('</div>');
 1445:         my @order = ('auth','quota','tools','requestauthor');
 1446:         my %user_text;
 1447:         my ($isadv,$isauthor) = 
 1448:             &Apache::lonnet::is_advanced_user($ccdomain,$ccuname);
 1449:         if ((!$isauthor) && 
 1450:             ((&Apache::lonnet::allowed('cau',$env{'request.role.domain'})) ||
 1451:              (&Apache::lonnet::allowed('udp',$env{'request.role.domain'}))) &&
 1452:              ($env{'request.role.domain'} eq $ccdomain)) {
 1453:             $user_text{'requestauthor'} = &domainrole_req($ccuname,$ccdomain);
 1454:         }
 1455:         $user_text{'auth'} =  &user_authentication($ccuname,$ccdomain,$formname);
 1456:         if ((&Apache::lonnet::allowed('mpq',$ccdomain)) ||
 1457:             (&Apache::lonnet::allowed('mut',$ccdomain)) ||
 1458:             (&Apache::lonnet::allowed('udp',$ccdomain))) {
 1459:             # Current user has quota modification privileges
 1460:             $user_text{'quota'} = &user_quotas($ccuname,$ccdomain);
 1461:         }
 1462:         if (!&Apache::lonnet::allowed('mpq',$ccdomain)) {
 1463:             if (&Apache::lonnet::allowed('mpq',$env{'request.role.domain'})) {
 1464:                 my %lt=&Apache::lonlocal::texthash(
 1465:                     'dska'  => "Disk quotas for user's portfolio and Authoring Space",
 1466:                     'youd'  => "You do not have privileges to modify the portfolio and/or Authoring Space quotas for this user.",
 1467:                     'ichr'  => "If a change is required, contact a domain coordinator for the domain",
 1468:                 );
 1469:                 $user_text{'quota'} = <<ENDNOPORTPRIV;
 1470: <h3>$lt{'dska'}</h3>
 1471: $lt{'youd'} $lt{'ichr'}: $ccdomain
 1472: ENDNOPORTPRIV
 1473:             }
 1474:         }
 1475:         if (!&Apache::lonnet::allowed('mut',$ccdomain)) {
 1476:             if (&Apache::lonnet::allowed('mut',$env{'request.role.domain'})) {
 1477:                 my %lt=&Apache::lonlocal::texthash(
 1478:                     'utav'  => "User Tools Availability",
 1479:                     'yodo'  => "You do not have privileges to modify Portfolio, Blog, WebDAV, or Personal Information Page settings for this user.",
 1480:                     'ifch'  => "If a change is required, contact a domain coordinator for the domain",
 1481:                 );
 1482:                 $user_text{'tools'} = <<ENDNOTOOLSPRIV;
 1483: <h3>$lt{'utav'}</h3>
 1484: $lt{'yodo'} $lt{'ifch'}: $ccdomain
 1485: ENDNOTOOLSPRIV
 1486:             }
 1487:         }
 1488:         my $gotdiv = 0; 
 1489:         foreach my $item (@order) {
 1490:             if ($user_text{$item} ne '') {
 1491:                 unless ($gotdiv) {
 1492:                     $r->print('<div class="LC_left_float">');
 1493:                     $gotdiv = 1;
 1494:                 }
 1495:                 $r->print('<br />'.$user_text{$item});
 1496:             }
 1497:         }
 1498:         if ($env{'form.action'} eq 'singlestudent') {
 1499:             unless ($gotdiv) {
 1500:                 $r->print('<div class="LC_left_float">');
 1501:             }
 1502:             my $credits;
 1503:             if ($showcredits) {
 1504:                 $credits = &get_user_credits($ccuname,$ccdomain,$defaultcredits);
 1505:                 if ($credits eq '') {
 1506:                     $credits = $defaultcredits;
 1507:                 }
 1508:             }
 1509:             $r->print(&date_sections_select($context,$newuser,$formname,
 1510:                                             $permission,$crstype,$ccuname,
 1511:                                             $ccdomain,$showcredits));
 1512:         }
 1513:         if ($gotdiv) {
 1514:             $r->print('</div><div class="LC_clear_float_footer"></div>');
 1515:         }
 1516:         my $statuses;
 1517:         if (($context eq 'domain') && (&Apache::lonnet::allowed('udp',$ccdomain)) &&
 1518:             (!&Apache::lonnet::allowed('mau',$ccdomain))) {
 1519:             $statuses = ['active'];
 1520:         } elsif (($context eq 'course') && ((&Apache::lonnet::allowed('vcl',$env{'request.course.id'})) ||
 1521:                  ($env{'request.course.sec'} &&
 1522:                   &Apache::lonnet::allowed('vcl',$env{'request.course.id'}.'/'.$env{'request.course.sec'})))) {
 1523:             $statuses = ['active'];
 1524:         }
 1525:         if ($env{'form.action'} ne 'singlestudent') {
 1526:             &display_existing_roles($r,$ccuname,$ccdomain,\%inccourses,$context,
 1527:                                     $roledom,$crstype,$showcredits,$statuses);
 1528:         }
 1529:     } ## End of new user/old user logic
 1530:     if ($env{'form.action'} eq 'singlestudent') {
 1531:         my $btntxt;
 1532:         if ($crstype eq 'Community') {
 1533:             $btntxt = &mt('Enroll Member');
 1534:         } else {
 1535:             $btntxt = &mt('Enroll Student');
 1536:         }
 1537:         $r->print('<br /><input type="button" value="'.$btntxt.'" onclick="setSections(this.form)" />'."\n");
 1538:     } elsif ($permission->{'cusr'}) {
 1539:         $r->print('<div class="LC_left_float">'.
 1540:                   '<fieldset><legend>'.&mt('Add Roles').'</legend>');
 1541:         my $addrolesdisplay = 0;
 1542:         if ($context eq 'domain' || $context eq 'author') {
 1543:             $addrolesdisplay = &new_coauthor_roles($r,$ccuname,$ccdomain);
 1544:         }
 1545:         if ($context eq 'domain') {
 1546:             my $add_domainroles = &new_domain_roles($r,$ccdomain);
 1547:             if (!$addrolesdisplay) {
 1548:                 $addrolesdisplay = $add_domainroles;
 1549:             }
 1550:             $r->print(&course_level_dc($env{'request.role.domain'},$showcredits));
 1551:             $r->print('</fieldset></div><div class="LC_clear_float_footer"></div>'.
 1552:                       '<br /><input type="button" value="'.&mt('Save').'" onclick="setCourse()" />'."\n");
 1553:         } elsif ($context eq 'author') {
 1554:             if ($addrolesdisplay) {
 1555:                 $r->print('</fieldset></div><div class="LC_clear_float_footer"></div>'.
 1556:                           '<br /><input type="button" value="'.&mt('Save').'"');
 1557:                 if ($newuser) {
 1558:                     $r->print(' onclick="auth_check()" \>'."\n");
 1559:                 } else {
 1560:                     $r->print('onclick="this.form.submit()" \>'."\n");
 1561:                 }
 1562:             } else {
 1563:                 $r->print('</fieldset></div>'.
 1564:                           '<div class="LC_clear_float_footer"></div>'.
 1565:                           '<br /><a href="javascript:backPage(document.cu)">'.
 1566:                           &mt('Back to previous page').'</a>');
 1567:             }
 1568:         } else {
 1569:             $r->print(&course_level_table(\%inccourses,$showcredits,$defaultcredits));
 1570:             $r->print('</fieldset></div><div class="LC_clear_float_footer"></div>'.
 1571:                       '<br /><input type="button" value="'.&mt('Save').'" onclick="setSections(this.form)" />'."\n");
 1572:         }
 1573:     }
 1574:     $r->print(&Apache::lonhtmlcommon::echo_form_input(['phase','userrole','ccdomain','prevphase','currstate','ccuname','ccdomain']));
 1575:     $r->print('<input type="hidden" name="currstate" value="" />');
 1576:     $r->print('<input type="hidden" name="prevphase" value="'.$env{'form.phase'}.'" /></form><br /><br />');
 1577:     return;
 1578: }
 1579: 
 1580: sub singleuser_breadcrumb {
 1581:     my ($crstype,$context,$domain) = @_;
 1582:     my %breadcrumb_text;
 1583:     if ($env{'form.action'} eq 'singlestudent') {
 1584:         if ($crstype eq 'Community') {
 1585:             $breadcrumb_text{'search'} = 'Enroll a member';
 1586:         } else {
 1587:             $breadcrumb_text{'search'} = 'Enroll a student';
 1588:         }
 1589:         $breadcrumb_text{'userpicked'} = 'Select a user';
 1590:         $breadcrumb_text{'modify'} = 'Set section/dates';
 1591:     } elsif ($env{'form.action'} eq 'accesslogs') {
 1592:         $breadcrumb_text{'search'} = 'View access logs for a user';
 1593:         $breadcrumb_text{'userpicked'} = 'Select a user';
 1594:         $breadcrumb_text{'activity'} = 'Activity';
 1595:     } elsif (($env{'form.action'} eq 'singleuser') && ($context eq 'domain') &&
 1596:              (!&Apache::lonnet::allowed('mau',$domain))) {
 1597:         $breadcrumb_text{'search'} = "View user's roles";
 1598:         $breadcrumb_text{'userpicked'} = 'Select a user';
 1599:         $breadcrumb_text{'modify'} = 'User roles';
 1600:     } else {
 1601:         $breadcrumb_text{'search'} = 'Create/modify a user';
 1602:         $breadcrumb_text{'userpicked'} = 'Select a user';
 1603:         $breadcrumb_text{'modify'} = 'Set user role';
 1604:     }
 1605:     return %breadcrumb_text;
 1606: }
 1607: 
 1608: sub date_sections_select {
 1609:     my ($context,$newuser,$formname,$permission,$crstype,$ccuname,$ccdomain,
 1610:         $showcredits) = @_;
 1611:     my $credits;
 1612:     if ($showcredits) {
 1613:         my $defaultcredits = &Apache::lonuserutils::get_defaultcredits();
 1614:         $credits = &get_user_credits($ccuname,$ccdomain,$defaultcredits);
 1615:         if ($credits eq '') {
 1616:             $credits = $defaultcredits;
 1617:         }
 1618:     }
 1619:     my $cid = $env{'request.course.id'};
 1620:     my ($cnum,$cdom) = &Apache::lonuserutils::get_course_identity($cid);
 1621:     my $date_table = '<h3>'.&mt('Starting and Ending Dates').'</h3>'."\n".
 1622:         &Apache::lonuserutils::date_setting_table(undef,undef,$context,
 1623:                                                   undef,$formname,$permission);
 1624:     my $rowtitle = 'Section';
 1625:     my $secbox = '<h3>'.&mt('Section and Credits').'</h3>'."\n".
 1626:         &Apache::lonuserutils::section_picker($cdom,$cnum,'st',$rowtitle,
 1627:                                               $permission,$context,'',$crstype,
 1628:                                               $showcredits,$credits);
 1629:     my $output = $date_table.$secbox;
 1630:     return $output;
 1631: }
 1632: 
 1633: sub validation_javascript {
 1634:     my ($context,$ccdomain,$pjump_def,$crstype,$groupslist,$newuser,$formname,
 1635:         $loaditem) = @_;
 1636:     my $dc_setcourse_code = '';
 1637:     my $nondc_setsection_code = '';
 1638:     if ($context eq 'domain') {
 1639:         my $dcdom = $env{'request.role.domain'};
 1640:         $loaditem->{'onload'} = "document.cu.coursedesc.value='';";
 1641:         $dc_setcourse_code = 
 1642:             &Apache::lonuserutils::dc_setcourse_js('cu','singleuser',$context);
 1643:     } else {
 1644:         my $checkauth; 
 1645:         if (($newuser) || (&Apache::lonnet::allowed('mau',$ccdomain))) {
 1646:             $checkauth = 1;
 1647:         }
 1648:         if ($context eq 'course') {
 1649:             $nondc_setsection_code =
 1650:                 &Apache::lonuserutils::setsections_javascript($formname,$groupslist,
 1651:                                                               undef,$checkauth,
 1652:                                                               $crstype);
 1653:         }
 1654:         if ($checkauth) {
 1655:             $nondc_setsection_code .= 
 1656:                 &Apache::lonuserutils::verify_authen($formname,$context);
 1657:         }
 1658:     }
 1659:     my $js = &user_modification_js($pjump_def,$dc_setcourse_code,
 1660:                                    $nondc_setsection_code,$groupslist);
 1661:     my ($jsback,$elements) = &crumb_utilities();
 1662:     $js .= "\n".
 1663:            '<script type="text/javascript">'."\n".
 1664:            '// <![CDATA['."\n".
 1665:            $jsback."\n".
 1666:            '// ]]>'."\n".
 1667:            '</script>'."\n";
 1668:     return $js;
 1669: }
 1670: 
 1671: sub display_existing_roles {
 1672:     my ($r,$ccuname,$ccdomain,$inccourses,$context,$roledom,$crstype,
 1673:         $showcredits,$statuses) = @_;
 1674:     my $now=time;
 1675:     my $showall = 1;
 1676:     my ($showexpired,$showactive);
 1677:     if ((ref($statuses) eq 'ARRAY') && (@{$statuses} > 0)) {
 1678:         $showall = 0;
 1679:         if (grep(/^expired$/,@{$statuses})) {
 1680:             $showexpired = 1;
 1681:         }
 1682:         if (grep(/^active$/,@{$statuses})) {
 1683:             $showactive = 1;
 1684:         }
 1685:         if ($showexpired && $showactive) {
 1686:             $showall = 1;
 1687:         }
 1688:     }
 1689:     my %lt=&Apache::lonlocal::texthash(
 1690:                     'rer'  => "Existing Roles",
 1691:                     'rev'  => "Revoke",
 1692:                     'del'  => "Delete",
 1693:                     'ren'  => "Re-Enable",
 1694:                     'rol'  => "Role",
 1695:                     'ext'  => "Extent",
 1696:                     'crd'  => "Credits",
 1697:                     'sta'  => "Start",
 1698:                     'end'  => "End",
 1699:                                        );
 1700:     my (%rolesdump,%roletext,%sortrole,%roleclass,%rolepriv);
 1701:     if ($context eq 'course' || $context eq 'author') {
 1702:         my @roles = &Apache::lonuserutils::roles_by_context($context,1,$crstype);
 1703:         my %roleshash = 
 1704:             &Apache::lonnet::get_my_roles($ccuname,$ccdomain,'userroles',
 1705:                               ['active','previous','future'],\@roles,$roledom,1);
 1706:         foreach my $key (keys(%roleshash)) {
 1707:             my ($start,$end) = split(':',$roleshash{$key});
 1708:             next if ($start eq '-1' || $end eq '-1');
 1709:             my ($rnum,$rdom,$role,$sec) = split(':',$key);
 1710:             if ($context eq 'course') {
 1711:                 next unless (($rnum eq $env{'course.'.$env{'request.course.id'}.'.num'})
 1712:                              && ($rdom eq $env{'course.'.$env{'request.course.id'}.'.domain'}));
 1713:             } elsif ($context eq 'author') {
 1714:                 next unless (($rnum eq $env{'user.name'}) && ($rdom eq $env{'request.role.domain'}));
 1715:             }
 1716:             my ($newkey,$newvalue,$newrole);
 1717:             $newkey = '/'.$rdom.'/'.$rnum;
 1718:             if ($sec ne '') {
 1719:                 $newkey .= '/'.$sec;
 1720:             }
 1721:             $newvalue = $role;
 1722:             if ($role =~ /^cr/) {
 1723:                 $newrole = 'cr';
 1724:             } else {
 1725:                 $newrole = $role;
 1726:             }
 1727:             $newkey .= '_'.$newrole;
 1728:             if ($start ne '' && $end ne '') {
 1729:                 $newvalue .= '_'.$end.'_'.$start;
 1730:             } elsif ($end ne '') {
 1731:                 $newvalue .= '_'.$end;
 1732:             }
 1733:             $rolesdump{$newkey} = $newvalue;
 1734:         }
 1735:     } else {
 1736:         %rolesdump=&Apache::lonnet::dump('roles',$ccdomain,$ccuname);
 1737:     }
 1738:     # Build up table of user roles to allow revocation and re-enabling of roles.
 1739:     my ($tmp) = keys(%rolesdump);
 1740:     return if ($tmp =~ /^(con_lost|error)/i);
 1741:     foreach my $area (sort { my $a1=join('_',(split('_',$a))[1,0]);
 1742:                                 my $b1=join('_',(split('_',$b))[1,0]);
 1743:                                 return $a1 cmp $b1;
 1744:                             } keys(%rolesdump)) {
 1745:         next if ($area =~ /^rolesdef/);
 1746:         my $envkey=$area;
 1747:         my $role = $rolesdump{$area};
 1748:         my $thisrole=$area;
 1749:         $area =~ s/\_\w\w$//;
 1750:         my ($role_code,$role_end_time,$role_start_time) =
 1751:             split(/_/,$role);
 1752:         my $active=1;
 1753:         $active=0 if (($role_end_time) && ($now>$role_end_time));
 1754:         if ($active) {
 1755:             next unless($showall || $showactive);
 1756:         } else {
 1757:             next unless($showall || $showexpired);
 1758:         }
 1759: # Is this a custom role? Get role owner and title.
 1760:         my ($croleudom,$croleuname,$croletitle)=
 1761:             ($role_code=~m{^cr/($match_domain)/($match_username)/(\w+)$});
 1762:         my $allowed=0;
 1763:         my $delallowed=0;
 1764:         my $sortkey=$role_code;
 1765:         my $class='Unknown';
 1766:         my $credits='';
 1767:         my $csec;
 1768:         if ($area =~ m{^/($match_domain)/($match_courseid)}) {
 1769:             $class='Course';
 1770:             my ($coursedom,$coursedir) = ($1,$2);
 1771:             my $cid = $1.'_'.$2;
 1772:             # $1.'_'.$2 is the course id (eg. 103_12345abcef103l3).
 1773:             next if ($envkey =~ m{^/$match_domain/$match_courseid/[A-Za-z0-9]+_gr$});
 1774:             my %coursedata=
 1775:                 &Apache::lonnet::coursedescription($cid);
 1776:             if ($coursedir =~ /^$match_community$/) {
 1777:                 $class='Community';
 1778:             }
 1779:             $sortkey.="\0$coursedom";
 1780:             my $carea;
 1781:             if (defined($coursedata{'description'})) {
 1782:                 $carea=$coursedata{'description'}.
 1783:                     '<br />'.&mt('Domain').': '.$coursedom.('&nbsp;'x8).
 1784:     &Apache::loncommon::syllabuswrapper(&mt('Syllabus'),$coursedir,$coursedom);
 1785:                 $sortkey.="\0".$coursedata{'description'};
 1786:             } else {
 1787:                 if ($class eq 'Community') {
 1788:                     $carea=&mt('Unavailable community').': '.$area;
 1789:                     $sortkey.="\0".&mt('Unavailable community').': '.$area;
 1790:                 } else {
 1791:                     $carea=&mt('Unavailable course').': '.$area;
 1792:                     $sortkey.="\0".&mt('Unavailable course').': '.$area;
 1793:                 }
 1794:             }
 1795:             $sortkey.="\0$coursedir";
 1796:             $inccourses->{$cid}=1;
 1797:             if (($showcredits) && ($class eq 'Course') && ($role_code eq 'st')) {
 1798:                 my $defaultcredits = $coursedata{'internal.defaultcredits'};
 1799:                 $credits =
 1800:                     &get_user_credits($ccuname,$ccdomain,$defaultcredits,
 1801:                                       $coursedom,$coursedir);
 1802:                 if ($credits eq '') {
 1803:                     $credits = $defaultcredits;
 1804:                 }
 1805:             }
 1806:             if ((&Apache::lonnet::allowed('c'.$role_code,$coursedom.'/'.$coursedir)) ||
 1807:                 (&Apache::lonnet::allowed('c'.$role_code,$ccdomain))) {
 1808:                 $allowed=1;
 1809:             }
 1810:             unless ($allowed) {
 1811:                 my $isowner = &Apache::lonuserutils::is_courseowner($cid,$coursedata{'internal.courseowner'});
 1812:                 if ($isowner) {
 1813:                     if (($role_code eq 'co') && ($class eq 'Community')) {
 1814:                         $allowed = 1;
 1815:                     } elsif (($role_code eq 'cc') && ($class eq 'Course')) {
 1816:                         $allowed = 1;
 1817:                     }
 1818:                 }
 1819:             } 
 1820:             if ((&Apache::lonnet::allowed('dro',$coursedom)) ||
 1821:                 (&Apache::lonnet::allowed('dro',$ccdomain))) {
 1822:                 $delallowed=1;
 1823:             }
 1824: # - custom role. Needs more info, too
 1825:             if ($croletitle) {
 1826:                 if (&Apache::lonnet::allowed('ccr',$coursedom.'/'.$coursedir)) {
 1827:                     $allowed=1;
 1828:                     $thisrole.='.'.$role_code;
 1829:                 }
 1830:             }
 1831:             if ($area=~m{^/($match_domain/$match_courseid/(\w+))}) {
 1832:                 $csec = $2;
 1833:                 $carea.='<br />'.&mt('Section: [_1]',$csec);
 1834:                 $sortkey.="\0$csec";
 1835:                 if (!$allowed) {
 1836:                     if ($env{'request.course.sec'} eq $csec) {
 1837:                         if (&Apache::lonnet::allowed('c'.$role_code,$1)) {
 1838:                             $allowed = 1;
 1839:                         }
 1840:                     }
 1841:                 }
 1842:             }
 1843:             $area=$carea;
 1844:         } else {
 1845:             $sortkey.="\0".$area;
 1846:             # Determine if current user is able to revoke privileges
 1847:             if ($area=~m{^/($match_domain)/}) {
 1848:                 if ((&Apache::lonnet::allowed('c'.$role_code,$1)) ||
 1849:                    (&Apache::lonnet::allowed('c'.$role_code,$ccdomain))) {
 1850:                    $allowed=1;
 1851:                 }
 1852:                 if (((&Apache::lonnet::allowed('dro',$1))  ||
 1853:                     (&Apache::lonnet::allowed('dro',$ccdomain))) &&
 1854:                     ($role_code ne 'dc')) {
 1855:                     $delallowed=1;
 1856:                 }
 1857:             } else {
 1858:                 if (&Apache::lonnet::allowed('c'.$role_code,'/')) {
 1859:                     $allowed=1;
 1860:                 }
 1861:             }
 1862:             if ($role_code eq 'ca' || $role_code eq 'au' || $role_code eq 'aa') {
 1863:                 $class='Authoring Space';
 1864:             } elsif ($role_code eq 'su') {
 1865:                 $class='System';
 1866:             } else {
 1867:                 $class='Domain';
 1868:             }
 1869:         }
 1870:         if (($role_code eq 'ca') || ($role_code eq 'aa')) {
 1871:             $area=~m{/($match_domain)/($match_username)};
 1872:             if (&Apache::lonuserutils::authorpriv($2,$1)) {
 1873:                 $allowed=1;
 1874:             } else {
 1875:                 $allowed=0;
 1876:             }
 1877:         }
 1878:         my $row = '';
 1879:         if ($showall) {
 1880:             $row.= '<td>';
 1881:             if (($active) && ($allowed)) {
 1882:                 $row.= '<input type="checkbox" name="rev:'.$thisrole.'" />';
 1883:             } else {
 1884:                 if ($active) {
 1885:                     $row.='&nbsp;';
 1886:                 } else {
 1887:                     $row.=&mt('expired or revoked');
 1888:                 }
 1889:             }
 1890:             $row.='</td><td>';
 1891:             if ($allowed && !$active) {
 1892:                 $row.= '<input type="checkbox" name="ren:'.$thisrole.'" />';
 1893:             } else {
 1894:                 $row.='&nbsp;';
 1895:             }
 1896:             $row.='</td><td>';
 1897:             if ($delallowed) {
 1898:                 $row.= '<input type="checkbox" name="del:'.$thisrole.'" />';
 1899:             } else {
 1900:                 $row.='&nbsp;';
 1901:             }
 1902:             $row.= '</td>';
 1903:         }
 1904:         my $plaintext='';
 1905:         if (!$croletitle) {
 1906:             $plaintext=&Apache::lonnet::plaintext($role_code,$class);
 1907:             if (($showcredits) && ($credits ne '')) {
 1908:                 $plaintext .= '<br/ ><span class="LC_nobreak">'.
 1909:                               '<span class="LC_fontsize_small">'.
 1910:                               &mt('Credits: [_1]',$credits).
 1911:                               '</span></span>';
 1912:             }
 1913:         } else {
 1914:             $plaintext=
 1915:                 &mt('Custom role [_1][_2]defined by [_3]',
 1916:                         '"'.$croletitle.'"',
 1917:                         '<br />',
 1918:                         $croleuname.':'.$croleudom);
 1919:         }
 1920:         $row.= '<td>'.$plaintext.'</td>'.
 1921:                '<td>'.$area.'</td>'.
 1922:                '<td>'.($role_start_time?&Apache::lonlocal::locallocaltime($role_start_time)
 1923:                                             : '&nbsp;' ).'</td>'.
 1924:                '<td>'.($role_end_time  ?&Apache::lonlocal::locallocaltime($role_end_time)
 1925:                                             : '&nbsp;' ).'</td>';
 1926:         $sortrole{$sortkey}=$envkey;
 1927:         $roletext{$envkey}=$row;
 1928:         $roleclass{$envkey}=$class;
 1929:         if ($allowed) {
 1930:             $rolepriv{$envkey}='edit';
 1931:         } else {
 1932:             if ($context eq 'domain') {
 1933:                 if ((&Apache::lonnet::allowed('vur',$ccdomain)) &&
 1934:                     ($envkey=~m{^/$ccdomain/})) {
 1935:                     $rolepriv{$envkey}='view';
 1936:                 }
 1937:             } elsif ($context eq 'course') {
 1938:                 if ((&Apache::lonnet::allowed('vcl',$env{'request.course.id'})) ||
 1939:                     ($env{'request.course.sec'} && ($env{'request.course.sec'} eq $csec) &&
 1940:                      &Apache::lonnet::allowed('vcl',$env{'request.course.id'}.'/'.$env{'request.course.sec'}))) {
 1941:                     $rolepriv{$envkey}='view';
 1942:                 }
 1943:             }
 1944:         }
 1945:     } # end of foreach        (table building loop)
 1946: 
 1947:     my $rolesdisplay = 0;
 1948:     my %output = ();
 1949:     foreach my $type ('Authoring Space','Course','Community','Domain','System','Unknown') {
 1950:         $output{$type} = '';
 1951:         foreach my $which (sort {uc($a) cmp uc($b)} (keys(%sortrole))) {
 1952:             if ( ($roleclass{$sortrole{$which}} =~ /^\Q$type\E/ ) && ($rolepriv{$sortrole{$which}}) ) {
 1953:                  $output{$type}.=
 1954:                       &Apache::loncommon::start_data_table_row().
 1955:                       $roletext{$sortrole{$which}}.
 1956:                       &Apache::loncommon::end_data_table_row();
 1957:             }
 1958:         }
 1959:         unless($output{$type} eq '') {
 1960:             $output{$type} = '<tr class="LC_info_row">'.
 1961:                       "<td align='center' colspan='7'>".&mt($type)."</td></tr>".
 1962:                       $output{$type};
 1963:             $rolesdisplay = 1;
 1964:         }
 1965:     }
 1966:     if ($rolesdisplay == 1) {
 1967:         my $contextrole='';
 1968:         if ($env{'request.course.id'}) {
 1969:             if (&Apache::loncommon::course_type() eq 'Community') {
 1970:                 $contextrole = &mt('Existing Roles in this Community');
 1971:             } else {
 1972:                 $contextrole = &mt('Existing Roles in this Course');
 1973:             }
 1974:         } elsif ($env{'request.role'} =~ /^au\./) {
 1975:             $contextrole = &mt('Existing Co-Author Roles in your Authoring Space');
 1976:         } else {
 1977:             if ($showall) {
 1978:                 $contextrole = &mt('Existing Roles in this Domain');
 1979:             } elsif ($showactive) {
 1980:                 $contextrole = &mt('Unexpired Roles in this Domain');
 1981:             } elsif ($showexpired) {
 1982:                 $contextrole = &mt('Expired or Revoked Roles in this Domain');
 1983:             }
 1984:         }
 1985:         $r->print('<div class="LC_left_float">'.
 1986: '<fieldset><legend>'.$contextrole.'</legend>'.
 1987: &Apache::loncommon::start_data_table("LC_createuser").
 1988: &Apache::loncommon::start_data_table_header_row());
 1989:         if ($showall) {
 1990:             $r->print(
 1991: '<th>'.$lt{'rev'}.'</th><th>'.$lt{'ren'}.'</th><th>'.$lt{'del'}.'</th>'
 1992:             );
 1993:         } elsif ($showexpired) {
 1994:             $r->print('<th>'.$lt{'rev'}.'</th>');
 1995:         }
 1996:         $r->print(
 1997: '<th>'.$lt{'rol'}.'</th><th>'.$lt{'ext'}.'</th>'.
 1998: '<th>'.$lt{'sta'}.'</th><th>'.$lt{'end'}.'</th>'.
 1999: &Apache::loncommon::end_data_table_header_row());
 2000:         foreach my $type ('Authoring Space','Course','Community','Domain','System','Unknown') {
 2001:             if ($output{$type}) {
 2002:                 $r->print($output{$type}."\n");
 2003:             }
 2004:         }
 2005:         $r->print(&Apache::loncommon::end_data_table().
 2006:                   '</fieldset></div>');
 2007:     }
 2008:     return;
 2009: }
 2010: 
 2011: sub new_coauthor_roles {
 2012:     my ($r,$ccuname,$ccdomain) = @_;
 2013:     my $addrolesdisplay = 0;
 2014:     #
 2015:     # Co-Author
 2016:     #
 2017:     if (&Apache::lonuserutils::authorpriv($env{'user.name'},
 2018:                                           $env{'request.role.domain'}) &&
 2019:         ($env{'user.name'} ne $ccuname || $env{'user.domain'} ne $ccdomain)) {
 2020:         # No sense in assigning co-author role to yourself
 2021:         $addrolesdisplay = 1;
 2022:         my $cuname=$env{'user.name'};
 2023:         my $cudom=$env{'request.role.domain'};
 2024:         my %lt=&Apache::lonlocal::texthash(
 2025:                     'cs'   => "Authoring Space",
 2026:                     'act'  => "Activate",
 2027:                     'rol'  => "Role",
 2028:                     'ext'  => "Extent",
 2029:                     'sta'  => "Start",
 2030:                     'end'  => "End",
 2031:                     'cau'  => "Co-Author",
 2032:                     'caa'  => "Assistant Co-Author",
 2033:                     'ssd'  => "Set Start Date",
 2034:                     'sed'  => "Set End Date"
 2035:                                        );
 2036:         $r->print('<h4>'.$lt{'cs'}.'</h4>'."\n".
 2037:                   &Apache::loncommon::start_data_table()."\n".
 2038:                   &Apache::loncommon::start_data_table_header_row()."\n".
 2039:                   '<th>'.$lt{'act'}.'</th><th>'.$lt{'rol'}.'</th>'.
 2040:                   '<th>'.$lt{'ext'}.'</th><th>'.$lt{'sta'}.'</th>'.
 2041:                   '<th>'.$lt{'end'}.'</th>'."\n".
 2042:                   &Apache::loncommon::end_data_table_header_row()."\n".
 2043:                   &Apache::loncommon::start_data_table_row().'
 2044:            <td>
 2045:             <input type="checkbox" name="act_'.$cudom.'_'.$cuname.'_ca" />
 2046:            </td>
 2047:            <td>'.$lt{'cau'}.'</td>
 2048:            <td>'.$cudom.'_'.$cuname.'</td>
 2049:            <td><input type="hidden" name="start_'.$cudom.'_'.$cuname.'_ca" value="" />
 2050:              <a href=
 2051: "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>
 2052: <td><input type="hidden" name="end_'.$cudom.'_'.$cuname.'_ca" value="" />
 2053: <a href=
 2054: "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".
 2055:               &Apache::loncommon::end_data_table_row()."\n".
 2056:               &Apache::loncommon::start_data_table_row()."\n".
 2057: '<td><input type="checkbox" name="act_'.$cudom.'_'.$cuname.'_aa" /></td>
 2058: <td>'.$lt{'caa'}.'</td>
 2059: <td>'.$cudom.'_'.$cuname.'</td>
 2060: <td><input type="hidden" name="start_'.$cudom.'_'.$cuname.'_aa" value="" />
 2061: <a href=
 2062: "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>
 2063: <td><input type="hidden" name="end_'.$cudom.'_'.$cuname.'_aa" value="" />
 2064: <a href=
 2065: "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".
 2066:              &Apache::loncommon::end_data_table_row()."\n".
 2067:              &Apache::loncommon::end_data_table());
 2068:     } elsif ($env{'request.role'} =~ /^au\./) {
 2069:         if (!(&Apache::lonuserutils::authorpriv($env{'user.name'},
 2070:                                                 $env{'request.role.domain'}))) {
 2071:             $r->print('<span class="LC_error">'.
 2072:                       &mt('You do not have privileges to assign co-author roles.').
 2073:                       '</span>');
 2074:         } elsif (($env{'user.name'} eq $ccuname) &&
 2075:              ($env{'user.domain'} eq $ccdomain)) {
 2076:             $r->print(&mt('Assigning yourself a co-author or assistant co-author role in your own author area in Authoring Space is not permitted'));
 2077:         }
 2078:     }
 2079:     return $addrolesdisplay;;
 2080: }
 2081: 
 2082: sub new_domain_roles {
 2083:     my ($r,$ccdomain) = @_;
 2084:     my $addrolesdisplay = 0;
 2085:     #
 2086:     # Domain level
 2087:     #
 2088:     my $num_domain_level = 0;
 2089:     my $domaintext =
 2090:     '<h4>'.&mt('Domain Level').'</h4>'.
 2091:     &Apache::loncommon::start_data_table().
 2092:     &Apache::loncommon::start_data_table_header_row().
 2093:     '<th>'.&mt('Activate').'</th><th>'.&mt('Role').'</th><th>'.
 2094:     &mt('Extent').'</th>'.
 2095:     '<th>'.&mt('Start').'</th><th>'.&mt('End').'</th>'.
 2096:     &Apache::loncommon::end_data_table_header_row();
 2097:     my @allroles = &Apache::lonuserutils::roles_by_context('domain');
 2098:     foreach my $thisdomain (sort(&Apache::lonnet::all_domains())) {
 2099:         foreach my $role (@allroles) {
 2100:             next if ($role eq 'ad');
 2101:             next if (($role eq 'au') && ($ccdomain ne $thisdomain));
 2102:             if (&Apache::lonnet::allowed('c'.$role,$thisdomain)) {
 2103:                my $plrole=&Apache::lonnet::plaintext($role);
 2104:                my %lt=&Apache::lonlocal::texthash(
 2105:                     'ssd'  => "Set Start Date",
 2106:                     'sed'  => "Set End Date"
 2107:                                        );
 2108:                $num_domain_level ++;
 2109:                $domaintext .=
 2110: &Apache::loncommon::start_data_table_row().
 2111: '<td><input type="checkbox" name="act_'.$thisdomain.'_'.$role.'" /></td>
 2112: <td>'.$plrole.'</td>
 2113: <td>'.$thisdomain.'</td>
 2114: <td><input type="hidden" name="start_'.$thisdomain.'_'.$role.'" value="" />
 2115: <a href=
 2116: "javascript:pjump('."'date_start','Start Date $plrole',document.cu.start_$thisdomain\_$role.value,'start_$thisdomain\_$role','cu.pres','dateset'".')">'.$lt{'ssd'}.'</a></td>
 2117: <td><input type="hidden" name="end_'.$thisdomain.'_'.$role.'" value="" />
 2118: <a href=
 2119: "javascript:pjump('."'date_end','End Date $plrole',document.cu.end_$thisdomain\_$role.value,'end_$thisdomain\_$role','cu.pres','dateset'".')">'.$lt{'sed'}.'</a></td>'.
 2120: &Apache::loncommon::end_data_table_row();
 2121:             }
 2122:         }
 2123:     }
 2124:     $domaintext.= &Apache::loncommon::end_data_table();
 2125:     if ($num_domain_level > 0) {
 2126:         $r->print($domaintext);
 2127:         $addrolesdisplay = 1;
 2128:     }
 2129:     return $addrolesdisplay;
 2130: }
 2131: 
 2132: sub user_authentication {
 2133:     my ($ccuname,$ccdomain,$formname) = @_;
 2134:     my $currentauth=&Apache::lonnet::queryauthenticate($ccuname,$ccdomain);
 2135:     my $outcome;
 2136:     my %lt=&Apache::lonlocal::texthash(
 2137:                    'err'   => "ERROR",
 2138:                    'uuas'  => "This user has an unrecognized authentication scheme",
 2139:                    'adcs'  => "Please alert a domain coordinator of this situation",
 2140:                    'sldb'  => "Please specify login data below",
 2141:                    'ld'    => "Login Data"
 2142:     );
 2143:     # Check for a bad authentication type
 2144:     if ($currentauth !~ /^(krb4|krb5|unix|internal|localauth):/) {
 2145:         # bad authentication scheme
 2146:         if (&Apache::lonnet::allowed('mau',$ccdomain)) {
 2147:             &initialize_authen_forms($ccdomain,$formname);
 2148: 
 2149:             my $choices = &Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc);
 2150:             $outcome = <<ENDBADAUTH;
 2151: <script type="text/javascript" language="Javascript">
 2152: // <![CDATA[
 2153: $loginscript
 2154: // ]]>
 2155: </script>
 2156: <span class="LC_error">$lt{'err'}:
 2157: $lt{'uuas'} ($currentauth). $lt{'sldb'}.</span>
 2158: <h3>$lt{'ld'}</h3>
 2159: $choices
 2160: ENDBADAUTH
 2161:         } else {
 2162:             # This user is not allowed to modify the user's
 2163:             # authentication scheme, so just notify them of the problem
 2164:             $outcome = <<ENDBADAUTH;
 2165: <span class="LC_error"> $lt{'err'}: 
 2166: $lt{'uuas'} ($currentauth). $lt{'adcs'}.
 2167: </span>
 2168: ENDBADAUTH
 2169:         }
 2170:     } else { # Authentication type is valid
 2171:         &initialize_authen_forms($ccdomain,$formname,$currentauth,'modifyuser');
 2172:         my ($authformcurrent,$can_modify,@authform_others) =
 2173:             &modify_login_block($ccdomain,$currentauth);
 2174:         if (&Apache::lonnet::allowed('mau',$ccdomain)) {
 2175:             # Current user has login modification privileges
 2176:             $outcome =
 2177:                        '<script type="text/javascript" language="Javascript">'."\n".
 2178:                        '// <![CDATA['."\n".
 2179:                        $loginscript."\n".
 2180:                        '// ]]>'."\n".
 2181:                        '</script>'."\n".
 2182:                        '<h3>'.$lt{'ld'}.'</h3>'.
 2183:                        &Apache::loncommon::start_data_table().
 2184:                        &Apache::loncommon::start_data_table_row().
 2185:                        '<td>'.$authformnop;
 2186:             if (($can_modify) && (&Apache::lonnet::allowed('mau',$ccdomain))) {
 2187:                 $outcome .= '</td>'."\n".
 2188:                             &Apache::loncommon::end_data_table_row().
 2189:                             &Apache::loncommon::start_data_table_row().
 2190:                             '<td>'.$authformcurrent.'</td>'.
 2191:                             &Apache::loncommon::end_data_table_row()."\n";
 2192:             } else {
 2193:                 $outcome .= '&nbsp;('.$authformcurrent.')</td>'.
 2194:                             &Apache::loncommon::end_data_table_row()."\n";
 2195:             }
 2196:             if (&Apache::lonnet::allowed('mau',$ccdomain)) {
 2197:                 foreach my $item (@authform_others) { 
 2198:                     $outcome .= &Apache::loncommon::start_data_table_row().
 2199:                                 '<td>'.$item.'</td>'.
 2200:                                 &Apache::loncommon::end_data_table_row()."\n";
 2201:                 }
 2202:             }
 2203:             $outcome .= &Apache::loncommon::end_data_table();
 2204:         } else {
 2205:             if (&Apache::lonnet::allowed('udp',$ccdomain)) {
 2206:                 # Current user has rights to view domain preferences for user's domain
 2207:                 my $result;
 2208:                 if ($currentauth =~ /^krb(4|5):([^:]*)$/) {
 2209:                     my ($krbver,$krbrealm) = ($1,$2);
 2210:                     if ($krbrealm eq '') {
 2211:                         $result = &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
 2212:                     } else {
 2213:                         $result = &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
 2214:                                       $krbrealm,$krbver);
 2215:                     }
 2216:                 } elsif ($currentauth =~ /^internal:/) {
 2217:                     $result = &mt('Currently internally authenticated.');
 2218:                 } elsif ($currentauth =~ /^localauth:/) {
 2219:                     $result = &mt('Currently using local (institutional) authentication.');
 2220:                 } elsif ($currentauth =~ /^unix:/) {
 2221:                     $result = &mt('Currently Filesystem Authenticated.');
 2222:                 }
 2223:                 $outcome = '<h3>'.$lt{'ld'}.'</h3>'.
 2224:                            &Apache::loncommon::start_data_table().
 2225:                            &Apache::loncommon::start_data_table_row().
 2226:                            '<td>'.$result.'</td>'.
 2227:                            &Apache::loncommon::end_data_table_row()."\n".
 2228:                            &Apache::loncommon::end_data_table();
 2229:             } elsif (&Apache::lonnet::allowed('mau',$env{'request.role.domain'})) {
 2230:                 my %lt=&Apache::lonlocal::texthash(
 2231:                            'ccld'  => "Change Current Login Data",
 2232:                            'yodo'  => "You do not have privileges to modify the authentication configuration for this user.",
 2233:                            'ifch'  => "If a change is required, contact a domain coordinator for the domain",
 2234:                 );
 2235:                 $outcome .= <<ENDNOPRIV;
 2236: <h3>$lt{'ccld'}</h3>
 2237: $lt{'yodo'} $lt{'ifch'}: $ccdomain
 2238: <input type="hidden" name="login" value="nochange" />
 2239: ENDNOPRIV
 2240:             }
 2241:         }
 2242:     }  ## End of "check for bad authentication type" logic
 2243:     return $outcome;
 2244: }
 2245: 
 2246: sub modify_login_block {
 2247:     my ($dom,$currentauth) = @_;
 2248:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 2249:     my ($authnum,%can_assign) =
 2250:         &Apache::loncommon::get_assignable_auth($dom);
 2251:     my ($authformcurrent,@authform_others,$show_override_msg);
 2252:     if ($currentauth=~/^krb(4|5):/) {
 2253:         $authformcurrent=$authformkrb;
 2254:         if ($can_assign{'int'}) {
 2255:             push(@authform_others,$authformint);
 2256:         }
 2257:         if ($can_assign{'loc'}) {
 2258:             push(@authform_others,$authformloc);
 2259:         }
 2260:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2261:             $show_override_msg = 1;
 2262:         }
 2263:     } elsif ($currentauth=~/^internal:/) {
 2264:         $authformcurrent=$authformint;
 2265:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2266:             push(@authform_others,$authformkrb);
 2267:         }
 2268:         if ($can_assign{'loc'}) {
 2269:             push(@authform_others,$authformloc);
 2270:         }
 2271:         if ($can_assign{'int'}) {
 2272:             $show_override_msg = 1;
 2273:         }
 2274:     } elsif ($currentauth=~/^unix:/) {
 2275:         $authformcurrent=$authformfsys;
 2276:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2277:             push(@authform_others,$authformkrb);
 2278:         }
 2279:         if ($can_assign{'int'}) {
 2280:             push(@authform_others,$authformint);
 2281:         }
 2282:         if ($can_assign{'loc'}) {
 2283:             push(@authform_others,$authformloc);
 2284:         }
 2285:         if ($can_assign{'fsys'}) {
 2286:             $show_override_msg = 1;
 2287:         }
 2288:     } elsif ($currentauth=~/^localauth:/) {
 2289:         $authformcurrent=$authformloc;
 2290:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2291:             push(@authform_others,$authformkrb);
 2292:         }
 2293:         if ($can_assign{'int'}) {
 2294:             push(@authform_others,$authformint);
 2295:         }
 2296:         if ($can_assign{'loc'}) {
 2297:             $show_override_msg = 1;
 2298:         }
 2299:     }
 2300:     if ($show_override_msg) {
 2301:         $authformcurrent = '<table><tr><td colspan="3">'.$authformcurrent.
 2302:                            '</td></tr>'."\n".
 2303:                            '<tr><td>&nbsp;&nbsp;&nbsp;</td>'.
 2304:                            '<td><b>'.&mt('Currently in use').'</b></td>'.
 2305:                            '<td align="right"><span class="LC_cusr_emph">'.
 2306:                             &mt('will override current values').
 2307:                             '</span></td></tr></table>';
 2308:     }
 2309:     return ($authformcurrent,$show_override_msg,@authform_others); 
 2310: }
 2311: 
 2312: sub personal_data_display {
 2313:     my ($ccuname,$ccdomain,$newuser,$context,$inst_results,$rolesarray,
 2314:         $now,$captchaform,$emailusername,$usertype) = @_;
 2315:     my ($output,%userenv,%canmodify,%canmodify_status);
 2316:     my @userinfo = ('firstname','middlename','lastname','generation',
 2317:                     'permanentemail','id');
 2318:     my $rowcount = 0;
 2319:     my $editable = 0;
 2320:     my %textboxsize = (
 2321:                        firstname      => '15',
 2322:                        middlename     => '15',
 2323:                        lastname       => '15',
 2324:                        generation     => '5',
 2325:                        permanentemail => '25',
 2326:                        id             => '15',
 2327:                       );
 2328: 
 2329:     my %lt=&Apache::lonlocal::texthash(
 2330:                 'pd'             => "Personal Data",
 2331:                 'firstname'      => "First Name",
 2332:                 'middlename'     => "Middle Name",
 2333:                 'lastname'       => "Last Name",
 2334:                 'generation'     => "Generation",
 2335:                 'permanentemail' => "Permanent e-mail address",
 2336:                 'id'             => "Student/Employee ID",
 2337:                 'lg'             => "Login Data",
 2338:                 'inststatus'     => "Affiliation",
 2339:                 'email'          => 'E-mail address',
 2340:                 'valid'          => 'Validation',
 2341:     );
 2342: 
 2343:     %canmodify_status =
 2344:         &Apache::lonuserutils::can_modify_userinfo($context,$ccdomain,
 2345:                                                    ['inststatus'],$rolesarray);
 2346:     if (!$newuser) {
 2347:         # Get the users information
 2348:         %userenv = &Apache::lonnet::get('environment',
 2349:                    ['firstname','middlename','lastname','generation',
 2350:                     'permanentemail','id','inststatus'],$ccdomain,$ccuname);
 2351:         %canmodify =
 2352:             &Apache::lonuserutils::can_modify_userinfo($context,$ccdomain,
 2353:                                                        \@userinfo,$rolesarray);
 2354:     } elsif ($context eq 'selfcreate') {
 2355:         if ($newuser eq 'email') {
 2356:             if (ref($emailusername) eq 'HASH') {
 2357:                 if (ref($emailusername->{$usertype}) eq 'HASH') {
 2358:                     my ($infofields,$infotitles) = &Apache::loncommon::emailusername_info();
 2359:                     @userinfo = ();          
 2360:                     if ((ref($infofields) eq 'ARRAY') && (ref($infotitles) eq 'HASH')) {
 2361:                         foreach my $field (@{$infofields}) { 
 2362:                             if ($emailusername->{$usertype}->{$field}) {
 2363:                                 push(@userinfo,$field);
 2364:                                 $canmodify{$field} = 1;
 2365:                                 unless ($textboxsize{$field}) {
 2366:                                     $textboxsize{$field} = 25;
 2367:                                 }
 2368:                                 unless ($lt{$field}) {
 2369:                                     $lt{$field} = $infotitles->{$field};
 2370:                                 }
 2371:                                 if ($emailusername->{$usertype}->{$field} eq 'required') {
 2372:                                     $lt{$field} .= '<b>*</b>';
 2373:                                 }
 2374:                             }
 2375:                         }
 2376:                     }
 2377:                 }
 2378:             }
 2379:         } else {
 2380:             %canmodify = &selfcreate_canmodify($context,$ccdomain,\@userinfo,
 2381:                                                $inst_results,$rolesarray);
 2382:         }
 2383:     }
 2384: 
 2385:     my $genhelp=&Apache::loncommon::help_open_topic('Generation');
 2386:     $output = '<h3>'.$lt{'pd'}.'</h3>'.
 2387:               &Apache::lonhtmlcommon::start_pick_box();
 2388:     if (($context eq 'selfcreate') && ($newuser eq 'email')) {
 2389:         $output .= &Apache::lonhtmlcommon::row_title($lt{'email'}.'<b>*</b>',undef,
 2390:                                                      'LC_oddrow_value')."\n".
 2391:                    '<input type="text" name="uname" size="25" value="" autocomplete="off" />';
 2392:         $rowcount ++;
 2393:         $output .= &Apache::lonhtmlcommon::row_closure(1);
 2394:         my $upassone = '<input type="password" name="upass'.$now.'" size="20" autocomplete="off" />';
 2395:         my $upasstwo = '<input type="password" name="upasscheck'.$now.'" size="20" autocomplete="off" />';
 2396:         $output .= &Apache::lonhtmlcommon::row_title(&mt('Password').'<b>*</b>',
 2397:                                                     'LC_pick_box_title',
 2398:                                                     'LC_oddrow_value')."\n".
 2399:                    $upassone."\n".
 2400:                    &Apache::lonhtmlcommon::row_closure(1)."\n".
 2401:                    &Apache::lonhtmlcommon::row_title(&mt('Confirm password').'<b>*</b>',
 2402:                                                      'LC_pick_box_title',
 2403:                                                      'LC_oddrow_value')."\n".
 2404:                    $upasstwo.
 2405:                    &Apache::lonhtmlcommon::row_closure()."\n";
 2406:     }
 2407:     foreach my $item (@userinfo) {
 2408:         my $rowtitle = $lt{$item};
 2409:         my $hiderow = 0;
 2410:         if ($item eq 'generation') {
 2411:             $rowtitle = $genhelp.$rowtitle;
 2412:         }
 2413:         my $row = &Apache::lonhtmlcommon::row_title($rowtitle,undef,'LC_oddrow_value')."\n";
 2414:         if ($newuser) {
 2415:             if (ref($inst_results) eq 'HASH') {
 2416:                 if ($inst_results->{$item} ne '') {
 2417:                     $row .= '<input type="hidden" name="c'.$item.'" value="'.$inst_results->{$item}.'" />'.$inst_results->{$item};
 2418:                 } else {
 2419:                     if ($context eq 'selfcreate') {
 2420:                         if ($canmodify{$item}) {
 2421:                             $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="" autocomplete="off" />';
 2422:                             $editable ++;
 2423:                         } else {
 2424:                             $hiderow = 1;
 2425:                         }
 2426:                     } else {
 2427:                         $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="" />';
 2428:                     }
 2429:                 }
 2430:             } else {
 2431:                 if ($context eq 'selfcreate') {
 2432:                     if ($canmodify{$item}) {
 2433:                         if ($newuser eq 'email') {
 2434:                             $row .= '<input type="text" name="'.$item.'" size="'.$textboxsize{$item}.'" value="" autocomplete="off" />';
 2435:                         } else {
 2436:                             $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="" autocomplete="off" />';
 2437:                         }
 2438:                         $editable ++;
 2439:                     } else {
 2440:                         $hiderow = 1;
 2441:                     }
 2442:                 } else {
 2443:                     $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="" />';
 2444:                 }
 2445:             }
 2446:         } else {
 2447:             if ($canmodify{$item}) {
 2448:                 $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="'.$userenv{$item}.'" />';
 2449:                 if (($item eq 'id') && (!$newuser)) {
 2450:                     $row .= '<br />'.&Apache::lonuserutils::forceid_change($context);
 2451:                 }
 2452:             } else {
 2453:                 $row .= $userenv{$item};
 2454:             }
 2455:         }
 2456:         $row .= &Apache::lonhtmlcommon::row_closure(1);
 2457:         if (!$hiderow) {
 2458:             $output .= $row;
 2459:             $rowcount ++;
 2460:         }
 2461:     }
 2462:     if (($canmodify_status{'inststatus'}) || ($context ne 'selfcreate')) {
 2463:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($ccdomain);
 2464:         if (ref($types) eq 'ARRAY') {
 2465:             if (@{$types} > 0) {
 2466:                 my ($hiderow,$shown);
 2467:                 if ($canmodify_status{'inststatus'}) {
 2468:                     $shown = &pick_inst_statuses($userenv{'inststatus'},$usertypes,$types);
 2469:                 } else {
 2470:                     if ($userenv{'inststatus'} eq '') {
 2471:                         $hiderow = 1;
 2472:                     } else {
 2473:                         my @showitems;
 2474:                         foreach my $item ( map { &unescape($_); } split(':',$userenv{'inststatus'})) {
 2475:                             if (exists($usertypes->{$item})) {
 2476:                                 push(@showitems,$usertypes->{$item});
 2477:                             } else {
 2478:                                 push(@showitems,$item);
 2479:                             }
 2480:                         }
 2481:                         if (@showitems) {
 2482:                             $shown = join(', ',@showitems);
 2483:                         } else {
 2484:                             $hiderow = 1;
 2485:                         }
 2486:                     }
 2487:                 }
 2488:                 if (!$hiderow) {
 2489:                     my $row = &Apache::lonhtmlcommon::row_title(&mt('Affiliations'),undef,'LC_oddrow_value')."\n".
 2490:                               $shown.&Apache::lonhtmlcommon::row_closure(1); 
 2491:                     if ($context eq 'selfcreate') {
 2492:                         $rowcount ++;
 2493:                     }
 2494:                     $output .= $row;
 2495:                 }
 2496:             }
 2497:         }
 2498:     }
 2499:     if (($context eq 'selfcreate') && ($newuser eq 'email')) {
 2500:         if ($captchaform) {
 2501:             $output .= &Apache::lonhtmlcommon::row_title($lt{'valid'}.'*',
 2502:                                                          'LC_pick_box_title')."\n".
 2503:                        $captchaform."\n".'<br /><br />'.
 2504:                        &Apache::lonhtmlcommon::row_closure(1); 
 2505:             $rowcount ++;
 2506:         }
 2507:         my $submit_text = &mt('Create account');
 2508:         $output .= &Apache::lonhtmlcommon::row_title()."\n".
 2509:                    '<br /><input type="submit" name="createaccount" value="'.
 2510:                    $submit_text.'" />'.
 2511:                    '<input type="hidden" name="type" value="'.$usertype.'" />'.
 2512:                    &Apache::lonhtmlcommon::row_closure(1);
 2513:     }
 2514:     $output .= &Apache::lonhtmlcommon::end_pick_box();
 2515:     if (wantarray) {
 2516:         if ($context eq 'selfcreate') {
 2517:             return($output,$rowcount,$editable);
 2518:         } else {
 2519:             return $output;
 2520:         }
 2521:     } else {
 2522:         return $output;
 2523:     }
 2524: }
 2525: 
 2526: sub pick_inst_statuses {
 2527:     my ($curr,$usertypes,$types) = @_;
 2528:     my ($output,$rem,@currtypes);
 2529:     if ($curr ne '') {
 2530:         @currtypes = map { &unescape($_); } split(/:/,$curr);
 2531:     }
 2532:     my $numinrow = 2;
 2533:     if (ref($types) eq 'ARRAY') {
 2534:         $output = '<table>';
 2535:         my $lastcolspan; 
 2536:         for (my $i=0; $i<@{$types}; $i++) {
 2537:             if (defined($usertypes->{$types->[$i]})) {
 2538:                 my $rem = $i%($numinrow);
 2539:                 if ($rem == 0) {
 2540:                     if ($i<@{$types}-1) {
 2541:                         if ($i > 0) { 
 2542:                             $output .= '</tr>';
 2543:                         }
 2544:                         $output .= '<tr>';
 2545:                     }
 2546:                 } elsif ($i==@{$types}-1) {
 2547:                     my $colsleft = $numinrow - $rem;
 2548:                     if ($colsleft > 1) {
 2549:                         $lastcolspan = ' colspan="'.$colsleft.'"';
 2550:                     }
 2551:                 }
 2552:                 my $check = ' ';
 2553:                 if (grep(/^\Q$types->[$i]\E$/,@currtypes)) {
 2554:                     $check = ' checked="checked" ';
 2555:                 }
 2556:                 $output .= '<td class="LC_left_item"'.$lastcolspan.'>'.
 2557:                            '<span class="LC_nobreak"><label>'.
 2558:                            '<input type="checkbox" name="inststatus" '.
 2559:                            'value="'.$types->[$i].'"'.$check.'/>'.
 2560:                            $usertypes->{$types->[$i]}.'</label></span></td>';
 2561:             }
 2562:         }
 2563:         $output .= '</tr></table>';
 2564:     }
 2565:     return $output;
 2566: }
 2567: 
 2568: sub selfcreate_canmodify {
 2569:     my ($context,$dom,$userinfo,$inst_results,$rolesarray) = @_;
 2570:     if (ref($inst_results) eq 'HASH') {
 2571:         my @inststatuses = &get_inststatuses($inst_results);
 2572:         if (@inststatuses == 0) {
 2573:             @inststatuses = ('default');
 2574:         }
 2575:         $rolesarray = \@inststatuses;
 2576:     }
 2577:     my %canmodify =
 2578:         &Apache::lonuserutils::can_modify_userinfo($context,$dom,$userinfo,
 2579:                                                    $rolesarray);
 2580:     return %canmodify;
 2581: }
 2582: 
 2583: sub get_inststatuses {
 2584:     my ($insthashref) = @_;
 2585:     my @inststatuses = ();
 2586:     if (ref($insthashref) eq 'HASH') {
 2587:         if (ref($insthashref->{'inststatus'}) eq 'ARRAY') {
 2588:             @inststatuses = @{$insthashref->{'inststatus'}};
 2589:         }
 2590:     }
 2591:     return @inststatuses;
 2592: }
 2593: 
 2594: # ================================================================= Phase Three
 2595: sub update_user_data {
 2596:     my ($r,$context,$crstype,$brcrum,$showcredits) = @_; 
 2597:     my $uhome=&Apache::lonnet::homeserver($env{'form.ccuname'},
 2598:                                           $env{'form.ccdomain'});
 2599:     # Error messages
 2600:     my $error     = '<span class="LC_error">'.&mt('Error').': ';
 2601:     my $end       = '</span><br /><br />';
 2602:     my $rtnlink   = '<a href="javascript:backPage(document.userupdate,'.
 2603:                     "'$env{'form.prevphase'}','modify')".'" />'.
 2604:                     &mt('Return to previous page').'</a>'.
 2605:                     &Apache::loncommon::end_page();
 2606:     my $now = time;
 2607:     my $title;
 2608:     if (exists($env{'form.makeuser'})) {
 2609: 	$title='Set Privileges for New User';
 2610:     } else {
 2611:         $title='Modify User Privileges';
 2612:     }
 2613:     my $newuser = 0;
 2614:     my ($jsback,$elements) = &crumb_utilities();
 2615:     my $jscript = '<script type="text/javascript">'."\n".
 2616:                   '// <![CDATA['."\n".
 2617:                   $jsback."\n".
 2618:                   '// ]]>'."\n".
 2619:                   '</script>'."\n";
 2620:     my %breadcrumb_text = &singleuser_breadcrumb($crstype,$context,$env{'form.ccdomain'});
 2621:     push (@{$brcrum},
 2622:              {href => "javascript:backPage(document.userupdate)",
 2623:               text => $breadcrumb_text{'search'},
 2624:               faq  => 282,
 2625:               bug  => 'Instructor Interface',}
 2626:              );
 2627:     if ($env{'form.prevphase'} eq 'userpicked') {
 2628:         push(@{$brcrum},
 2629:                {href => "javascript:backPage(document.userupdate,'get_user_info','select')",
 2630:                 text => $breadcrumb_text{'userpicked'},
 2631:                 faq  => 282,
 2632:                 bug  => 'Instructor Interface',});
 2633:     }
 2634:     my $helpitem = 'Course_Change_Privileges';
 2635:     if ($env{'form.action'} eq 'singlestudent') {
 2636:         $helpitem = 'Course_Add_Student';
 2637:     }
 2638:     push(@{$brcrum}, 
 2639:             {href => "javascript:backPage(document.userupdate,'$env{'form.prevphase'}','modify')",
 2640:              text => $breadcrumb_text{'modify'},
 2641:              faq  => 282,
 2642:              bug  => 'Instructor Interface',},
 2643:             {href => "/adm/createuser",
 2644:              text => "Result",
 2645:              faq  => 282,
 2646:              bug  => 'Instructor Interface',
 2647:              help => $helpitem});
 2648:     my $args = {bread_crumbs          => $brcrum,
 2649:                 bread_crumbs_component => 'User Management'};
 2650:     if ($env{'form.popup'}) {
 2651:         $args->{'no_nav_bar'} = 1;
 2652:     }
 2653:     $r->print(&Apache::loncommon::start_page($title,$jscript,$args));
 2654:     $r->print(&update_result_form($uhome));
 2655:     # Check Inputs
 2656:     if (! $env{'form.ccuname'} ) {
 2657: 	$r->print($error.&mt('No login name specified').'.'.$end.$rtnlink);
 2658: 	return;
 2659:     }
 2660:     if (  $env{'form.ccuname'} ne 
 2661: 	  &LONCAPA::clean_username($env{'form.ccuname'}) ) {
 2662: 	$r->print($error.&mt('Invalid login name.').'  '.
 2663: 		  &mt('Only letters, numbers, periods, dashes, @, and underscores are valid.').
 2664: 		  $end.$rtnlink);
 2665: 	return;
 2666:     }
 2667:     if (! $env{'form.ccdomain'}       ) {
 2668: 	$r->print($error.&mt('No domain specified').'.'.$end.$rtnlink);
 2669: 	return;
 2670:     }
 2671:     if (  $env{'form.ccdomain'} ne
 2672: 	  &LONCAPA::clean_domain($env{'form.ccdomain'}) ) {
 2673: 	$r->print($error.&mt('Invalid domain name.').'  '.
 2674: 		  &mt('Only letters, numbers, periods, dashes, and underscores are valid.').
 2675: 		  $end.$rtnlink);
 2676: 	return;
 2677:     }
 2678:     if ($uhome eq 'no_host') {
 2679:         $newuser = 1;
 2680:     }
 2681:     if (! exists($env{'form.makeuser'})) {
 2682:         # Modifying an existing user, so check the validity of the name
 2683:         if ($uhome eq 'no_host') {
 2684:             $r->print(
 2685:                 $error
 2686:                .'<p class="LC_error">'
 2687:                .&mt('Unable to determine home server for [_1] in domain [_2].',
 2688:                         '"'.$env{'form.ccuname'}.'"','"'.$env{'form.ccdomain'}.'"')
 2689:                .'</p>');
 2690:             return;
 2691:         }
 2692:     }
 2693:     # Determine authentication method and password for the user being modified
 2694:     my $amode='';
 2695:     my $genpwd='';
 2696:     if ($env{'form.login'} eq 'krb') {
 2697: 	$amode='krb';
 2698: 	$amode.=$env{'form.krbver'};
 2699: 	$genpwd=$env{'form.krbarg'};
 2700:     } elsif ($env{'form.login'} eq 'int') {
 2701: 	$amode='internal';
 2702: 	$genpwd=$env{'form.intarg'};
 2703:     } elsif ($env{'form.login'} eq 'fsys') {
 2704: 	$amode='unix';
 2705: 	$genpwd=$env{'form.fsysarg'};
 2706:     } elsif ($env{'form.login'} eq 'loc') {
 2707: 	$amode='localauth';
 2708: 	$genpwd=$env{'form.locarg'};
 2709: 	$genpwd=" " if (!$genpwd);
 2710:     } elsif (($env{'form.login'} eq 'nochange') ||
 2711:              ($env{'form.login'} eq ''        )) { 
 2712:         # There is no need to tell the user we did not change what they
 2713:         # did not ask us to change.
 2714:         # If they are creating a new user but have not specified login
 2715:         # information this will be caught below.
 2716:     } else {
 2717:             $r->print($error.&mt('Invalid login mode or password').$end.$rtnlink);
 2718:             return;
 2719:     }
 2720: 
 2721:     $r->print('<h3>'.&mt('User [_1] in domain [_2]',
 2722:                         $env{'form.ccuname'}.' ('.&Apache::loncommon::plainname($env{'form.ccuname'},
 2723:                         $env{'form.ccdomain'}).')', $env{'form.ccdomain'}).'</h3>');
 2724:     my %prog_state = &Apache::lonhtmlcommon::Create_PrgWin($r,2);
 2725: 
 2726:     my (%alerts,%rulematch,%inst_results,%curr_rules);
 2727:     my @userinfo = ('firstname','middlename','lastname','generation','permanentemail','id');
 2728:     my @usertools = ('aboutme','blog','webdav','portfolio');
 2729:     my @requestcourses = ('official','unofficial','community','textbook');
 2730:     my @requestauthor = ('requestauthor');
 2731:     my ($othertitle,$usertypes,$types) = 
 2732:         &Apache::loncommon::sorted_inst_types($env{'form.ccdomain'});
 2733:     my %canmodify_status =
 2734:         &Apache::lonuserutils::can_modify_userinfo($context,$env{'form.ccdomain'},
 2735:                                                    ['inststatus']);
 2736:     if ($env{'form.makeuser'}) {
 2737: 	$r->print('<h3>'.&mt('Creating new account.').'</h3>');
 2738:         # Check for the authentication mode and password
 2739:         if (! $amode || ! $genpwd) {
 2740: 	    $r->print($error.&mt('Invalid login mode or password').$end.$rtnlink);    
 2741: 	    return;
 2742: 	}
 2743:         # Determine desired host
 2744:         my $desiredhost = $env{'form.hserver'};
 2745:         if (lc($desiredhost) eq 'default') {
 2746:             $desiredhost = undef;
 2747:         } else {
 2748:             my %home_servers = 
 2749: 		&Apache::lonnet::get_servers($env{'form.ccdomain'},'library');
 2750:             if (! exists($home_servers{$desiredhost})) {
 2751:                 $r->print($error.&mt('Invalid home server specified').$end.$rtnlink);
 2752:                 return;
 2753:             }
 2754:         }
 2755:         # Check ID format
 2756:         my %checkhash;
 2757:         my %checks = ('id' => 1);
 2758:         %{$checkhash{$env{'form.ccuname'}.':'.$env{'form.ccdomain'}}} = (
 2759:             'newuser' => $newuser, 
 2760:             'id' => $env{'form.cid'},
 2761:         );
 2762:         if ($env{'form.cid'} ne '') {
 2763:             &Apache::loncommon::user_rule_check(\%checkhash,\%checks,\%alerts,
 2764:                                           \%rulematch,\%inst_results,\%curr_rules);
 2765:             if (ref($alerts{'id'}) eq 'HASH') {
 2766:                 if (ref($alerts{'id'}{$env{'form.ccdomain'}}) eq 'HASH') {
 2767:                     my $domdesc =
 2768:                         &Apache::lonnet::domain($env{'form.ccdomain'},'description');
 2769:                     if ($alerts{'id'}{$env{'form.ccdomain'}}{$env{'form.cid'}}) {
 2770:                         my $userchkmsg;
 2771:                         if (ref($curr_rules{$env{'form.ccdomain'}}) eq 'HASH') {
 2772:                             $userchkmsg  = 
 2773:                                 &Apache::loncommon::instrule_disallow_msg('id',
 2774:                                                                     $domdesc,1).
 2775:                                 &Apache::loncommon::user_rule_formats($env{'form.ccdomain'},
 2776:                                     $domdesc,$curr_rules{$env{'form.ccdomain'}}{'id'},'id');
 2777:                         }
 2778:                         $r->print($error.&mt('Invalid ID format').$end.
 2779:                                   $userchkmsg.$rtnlink);
 2780:                         return;
 2781:                     }
 2782:                 }
 2783:             }
 2784:         }
 2785:         &Apache::lonhtmlcommon::Increment_PrgWin($r, \%prog_state);
 2786: 	# Call modifyuser
 2787: 	my $result = &Apache::lonnet::modifyuser
 2788: 	    ($env{'form.ccdomain'},$env{'form.ccuname'},$env{'form.cid'},
 2789:              $amode,$genpwd,$env{'form.cfirstname'},
 2790:              $env{'form.cmiddlename'},$env{'form.clastname'},
 2791:              $env{'form.cgeneration'},undef,$desiredhost,
 2792:              $env{'form.cpermanentemail'});
 2793: 	$r->print(&mt('Generating user').': '.$result);
 2794:         $uhome = &Apache::lonnet::homeserver($env{'form.ccuname'},
 2795:                                                $env{'form.ccdomain'});
 2796:         my (%changeHash,%newcustom,%changed,%changedinfo);
 2797:         if ($uhome ne 'no_host') {
 2798:             if ($context eq 'domain') {
 2799:                 foreach my $name ('portfolio','author') {
 2800:                     if ($env{'form.custom_'.$name.'quota'} == 1) {
 2801:                         if ($env{'form.'.$name.'quota'} eq '') {
 2802:                             $newcustom{$name.'quota'} = 0;
 2803:                         } else {
 2804:                             $newcustom{$name.'quota'} = $env{'form.'.$name.'quota'};
 2805:                             $newcustom{$name.'quota'} =~ s/[^\d\.]//g;
 2806:                         }
 2807:                         if (&quota_admin($newcustom{$name.'quota'},\%changeHash,$name)) {
 2808:                             $changed{$name.'quota'} = 1;
 2809:                         }
 2810:                     }
 2811:                 }
 2812:                 foreach my $item (@usertools) {
 2813:                     if ($env{'form.custom'.$item} == 1) {
 2814:                         $newcustom{$item} = $env{'form.tools_'.$item};
 2815:                         $changed{$item} = &tool_admin($item,$newcustom{$item},
 2816:                                                      \%changeHash,'tools');
 2817:                     }
 2818:                 }
 2819:                 foreach my $item (@requestcourses) {
 2820:                     if ($env{'form.custom'.$item} == 1) {
 2821:                         $newcustom{$item} = $env{'form.crsreq_'.$item};
 2822:                         if ($env{'form.crsreq_'.$item} eq 'autolimit') {
 2823:                             $newcustom{$item} .= '=';
 2824:                             $env{'form.crsreq_'.$item.'_limit'} =~ s/\D+//g;
 2825:                             if ($env{'form.crsreq_'.$item.'_limit'}) {
 2826:                                 $newcustom{$item} .= $env{'form.crsreq_'.$item.'_limit'};
 2827:                             }
 2828:                         }
 2829:                         $changed{$item} = &tool_admin($item,$newcustom{$item},
 2830:                                                       \%changeHash,'requestcourses');
 2831:                     }
 2832:                 }
 2833:                 if ($env{'form.customrequestauthor'} == 1) {
 2834:                     $newcustom{'requestauthor'} = $env{'form.requestauthor'};
 2835:                     $changed{'requestauthor'} = &tool_admin('requestauthor',
 2836:                                                     $newcustom{'requestauthor'},
 2837:                                                     \%changeHash,'requestauthor');
 2838:                 }
 2839:             }
 2840:             if ($canmodify_status{'inststatus'}) {
 2841:                 if (exists($env{'form.inststatus'})) {
 2842:                     my @inststatuses = &Apache::loncommon::get_env_multiple('form.inststatus');
 2843:                     if (@inststatuses > 0) {
 2844:                         $changeHash{'inststatus'} = join(',',@inststatuses);
 2845:                         $changed{'inststatus'} = $changeHash{'inststatus'};
 2846:                     }
 2847:                 }
 2848:             }
 2849:             if (keys(%changed)) {
 2850:                 foreach my $item (@userinfo) {
 2851:                     $changeHash{$item}  = $env{'form.c'.$item};
 2852:                 }
 2853:                 my $chgresult =
 2854:                      &Apache::lonnet::put('environment',\%changeHash,
 2855:                                           $env{'form.ccdomain'},$env{'form.ccuname'});
 2856:             } 
 2857:         }
 2858:         $r->print('<br />'.&mt('Home server').': '.$uhome.' '.
 2859:                   &Apache::lonnet::hostname($uhome));
 2860:     } elsif (($env{'form.login'} ne 'nochange') &&
 2861:              ($env{'form.login'} ne ''        )) {
 2862: 	# Modify user privileges
 2863:         if (! $amode || ! $genpwd) {
 2864: 	    $r->print($error.'Invalid login mode or password'.$end.$rtnlink);    
 2865: 	    return;
 2866: 	}
 2867: 	# Only allow authentication modification if the person has authority
 2868: 	if (&Apache::lonnet::allowed('mau',$env{'form.ccdomain'})) {
 2869: 	    $r->print('Modifying authentication: '.
 2870:                       &Apache::lonnet::modifyuserauth(
 2871: 		       $env{'form.ccdomain'},$env{'form.ccuname'},
 2872:                        $amode,$genpwd));
 2873:             $r->print('<br />'.&mt('Home server').': '.&Apache::lonnet::homeserver
 2874: 		  ($env{'form.ccuname'},$env{'form.ccdomain'}));
 2875: 	} else {
 2876: 	    # Okay, this is a non-fatal error.
 2877: 	    $r->print($error.&mt('You do not have the authority to modify this users authentication information.').$end);    
 2878: 	}
 2879:     }
 2880:     $r->rflush(); # Finish display of header before time consuming actions start
 2881:     &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state);
 2882:     ##
 2883:     my (@userroles,%userupdate,$cnum,$cdom,$defaultcredits,%namechanged);
 2884:     if ($context eq 'course') {
 2885:         ($cnum,$cdom) =
 2886:             &Apache::lonuserutils::get_course_identity();
 2887:         $crstype = &Apache::loncommon::course_type($cdom.'_'.$cnum);
 2888:         if ($showcredits) {
 2889:            $defaultcredits = &Apache::lonuserutils::get_defaultcredits($cdom,$cnum);
 2890:         }
 2891:     }
 2892:     if (! $env{'form.makeuser'} ) {
 2893:         # Check for need to change
 2894:         my %userenv = &Apache::lonnet::get
 2895:             ('environment',['firstname','middlename','lastname','generation',
 2896:              'id','permanentemail','portfolioquota','authorquota','inststatus',
 2897:              'tools.aboutme','tools.blog','tools.webdav','tools.portfolio',
 2898:              'requestcourses.official','requestcourses.unofficial',
 2899:              'requestcourses.community','requestcourses.textbook',
 2900:              'reqcrsotherdom.official','reqcrsotherdom.unofficial',
 2901:              'reqcrsotherdom.community','reqcrsotherdom.textbook',
 2902:              'requestauthor'],
 2903:               $env{'form.ccdomain'},$env{'form.ccuname'});
 2904:         my ($tmp) = keys(%userenv);
 2905:         if ($tmp =~ /^(con_lost|error)/i) { 
 2906:             %userenv = ();
 2907:         }
 2908:         my $no_forceid_alert;
 2909:         # Check to see if user information can be changed
 2910:         my %domconfig =
 2911:             &Apache::lonnet::get_dom('configuration',['usermodification'],
 2912:                                      $env{'form.ccdomain'});
 2913:         my @statuses = ('active','future');
 2914:         my %roles = &Apache::lonnet::get_my_roles($env{'form.ccuname'},$env{'form.ccdomain'},'userroles',\@statuses,undef,$env{'request.role.domain'});
 2915:         my ($auname,$audom);
 2916:         if ($context eq 'author') {
 2917:             $auname = $env{'user.name'};
 2918:             $audom = $env{'user.domain'};     
 2919:         }
 2920:         foreach my $item (keys(%roles)) {
 2921:             my ($rolenum,$roledom,$role) = split(/:/,$item,-1);
 2922:             if ($context eq 'course') {
 2923:                 if ($cnum ne '' && $cdom ne '') {
 2924:                     if ($rolenum eq $cnum && $roledom eq $cdom) {
 2925:                         if (!grep(/^\Q$role\E$/,@userroles)) {
 2926:                             push(@userroles,$role);
 2927:                         }
 2928:                     }
 2929:                 }
 2930:             } elsif ($context eq 'author') {
 2931:                 if ($rolenum eq $auname && $roledom eq $audom) {
 2932:                     if (!grep(/^\Q$role\E$/,@userroles)) { 
 2933:                         push(@userroles,$role);
 2934:                     }
 2935:                 }
 2936:             }
 2937:         }
 2938:         if ($env{'form.action'} eq 'singlestudent') {
 2939:             if (!grep(/^st$/,@userroles)) {
 2940:                 push(@userroles,'st');
 2941:             }
 2942:         } else {
 2943:             # Check for course or co-author roles being activated or re-enabled
 2944:             if ($context eq 'author' || $context eq 'course') {
 2945:                 foreach my $key (keys(%env)) {
 2946:                     if ($context eq 'author') {
 2947:                         if ($key=~/^form\.act_\Q$audom\E_\Q$auname\E_([^_]+)/) {
 2948:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 2949:                                 push(@userroles,$1);
 2950:                             }
 2951:                         } elsif ($key =~/^form\.ren\:\Q$audom\E\/\Q$auname\E_([^_]+)/) {
 2952:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 2953:                                 push(@userroles,$1);
 2954:                             }
 2955:                         }
 2956:                     } elsif ($context eq 'course') {
 2957:                         if ($key=~/^form\.act_\Q$cdom\E_\Q$cnum\E_([^_]+)/) {
 2958:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 2959:                                 push(@userroles,$1);
 2960:                             }
 2961:                         } elsif ($key =~/^form\.ren\:\Q$cdom\E\/\Q$cnum\E(\/?\w*)_([^_]+)/) {
 2962:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 2963:                                 push(@userroles,$1);
 2964:                             }
 2965:                         }
 2966:                     }
 2967:                 }
 2968:             }
 2969:         }
 2970:         #Check to see if we can change personal data for the user 
 2971:         my (@mod_disallowed,@longroles);
 2972:         foreach my $role (@userroles) {
 2973:             if ($role eq 'cr') {
 2974:                 push(@longroles,'Custom');
 2975:             } else {
 2976:                 push(@longroles,&Apache::lonnet::plaintext($role,$crstype)); 
 2977:             }
 2978:         }
 2979:         my %canmodify = &Apache::lonuserutils::can_modify_userinfo($context,$env{'form.ccdomain'},\@userinfo,\@userroles);
 2980:         foreach my $item (@userinfo) {
 2981:             # Strip leading and trailing whitespace
 2982:             $env{'form.c'.$item} =~ s/(\s+$|^\s+)//g;
 2983:             if (!$canmodify{$item}) {
 2984:                 if (defined($env{'form.c'.$item})) {
 2985:                     if ($env{'form.c'.$item} ne $userenv{$item}) {
 2986:                         push(@mod_disallowed,$item);
 2987:                     }
 2988:                 }
 2989:                 $env{'form.c'.$item} = $userenv{$item};
 2990:             }
 2991:         }
 2992:         # Check to see if we can change the Student/Employee ID
 2993:         my $forceid = $env{'form.forceid'};
 2994:         my $recurseid = $env{'form.recurseid'};
 2995:         my (%alerts,%rulematch,%idinst_results,%curr_rules,%got_rules);
 2996:         my %uidhash = &Apache::lonnet::idrget($env{'form.ccdomain'},
 2997:                                             $env{'form.ccuname'});
 2998:         if (($uidhash{$env{'form.ccuname'}}) && 
 2999:             ($uidhash{$env{'form.ccuname'}}!~/error\:/) && 
 3000:             (!$forceid)) {
 3001:             if ($env{'form.cid'} ne $uidhash{$env{'form.ccuname'}}) {
 3002:                 $env{'form.cid'} = $userenv{'id'};
 3003:                 $no_forceid_alert = &mt('New student/employee ID does not match existing ID for this user.')
 3004:                                    .'<br />'
 3005:                                    .&mt("Change is not permitted without checking the 'Force ID change' checkbox on the previous page.")
 3006:                                    .'<br />'."\n";
 3007:             }
 3008:         }
 3009:         if ($env{'form.cid'} ne $userenv{'id'}) {
 3010:             my $checkhash;
 3011:             my $checks = { 'id' => 1 };
 3012:             $checkhash->{$env{'form.ccuname'}.':'.$env{'form.ccdomain'}} = 
 3013:                    { 'newuser' => $newuser,
 3014:                      'id'  => $env{'form.cid'}, 
 3015:                    };
 3016:             &Apache::loncommon::user_rule_check($checkhash,$checks,
 3017:                 \%alerts,\%rulematch,\%idinst_results,\%curr_rules,\%got_rules);
 3018:             if (ref($alerts{'id'}) eq 'HASH') {
 3019:                 if (ref($alerts{'id'}{$env{'form.ccdomain'}}) eq 'HASH') {
 3020:                    $env{'form.cid'} = $userenv{'id'};
 3021:                 }
 3022:             }
 3023:         }
 3024:         my (%quotachanged,%oldquota,%newquota,%olddefquota,%newdefquota, 
 3025:             $oldinststatus,$newinststatus,%oldisdefault,%newisdefault,%oldsettings,
 3026:             %oldsettingstext,%newsettings,%newsettingstext,@disporder,
 3027:             %oldsettingstatus,%newsettingstatus);
 3028:         @disporder = ('inststatus');
 3029:         if ($env{'request.role.domain'} eq $env{'form.ccdomain'}) {
 3030:             push(@disporder,'requestcourses','requestauthor');
 3031:         } else {
 3032:             push(@disporder,'reqcrsotherdom');
 3033:         }
 3034:         push(@disporder,('quota','tools'));
 3035:         $oldinststatus = $userenv{'inststatus'};
 3036:         foreach my $name ('portfolio','author') {
 3037:             ($olddefquota{$name},$oldsettingstatus{$name}) = 
 3038:                 &Apache::loncommon::default_quota($env{'form.ccdomain'},$oldinststatus,$name);
 3039:             ($newdefquota{$name},$newsettingstatus{$name}) = ($olddefquota{$name},$oldsettingstatus{$name});
 3040:         }
 3041:         my %canshow;
 3042:         if (&Apache::lonnet::allowed('mpq',$env{'form.ccdomain'})) {
 3043:             $canshow{'quota'} = 1;
 3044:         }
 3045:         if (&Apache::lonnet::allowed('mut',$env{'form.ccdomain'})) {
 3046:             $canshow{'tools'} = 1;
 3047:         }
 3048:         if (&Apache::lonnet::allowed('ccc',$env{'form.ccdomain'})) {
 3049:             $canshow{'requestcourses'} = 1;
 3050:         } elsif (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) {
 3051:             $canshow{'reqcrsotherdom'} = 1;
 3052:         }
 3053:         if (&Apache::lonnet::allowed('mau',$env{'form.ccdomain'})) {
 3054:             $canshow{'inststatus'} = 1;
 3055:         }
 3056:         if (&Apache::lonnet::allowed('cau',$env{'form.ccdomain'})) {
 3057:             $canshow{'requestauthor'} = 1;
 3058:         }
 3059:         my (%changeHash,%changed);
 3060:         if ($oldinststatus eq '') {
 3061:             $oldsettings{'inststatus'} = $othertitle; 
 3062:         } else {
 3063:             if (ref($usertypes) eq 'HASH') {
 3064:                 $oldsettings{'inststatus'} = join(', ',map{ $usertypes->{ &unescape($_) }; } (split(/:/,$userenv{'inststatus'})));
 3065:             } else {
 3066:                 $oldsettings{'inststatus'} = join(', ',map{ &unescape($_); } (split(/:/,$userenv{'inststatus'})));
 3067:             }
 3068:         }
 3069:         $changeHash{'inststatus'} = $userenv{'inststatus'};
 3070:         if ($canmodify_status{'inststatus'}) {
 3071:             $canshow{'inststatus'} = 1;
 3072:             if (exists($env{'form.inststatus'})) {
 3073:                 my @inststatuses = &Apache::loncommon::get_env_multiple('form.inststatus');
 3074:                 if (@inststatuses > 0) {
 3075:                     $newinststatus = join(':',map { &escape($_); } @inststatuses);
 3076:                     $changeHash{'inststatus'} = $newinststatus;
 3077:                     if ($newinststatus ne $oldinststatus) {
 3078:                         $changed{'inststatus'} = $newinststatus;
 3079:                         foreach my $name ('portfolio','author') {
 3080:                             ($newdefquota{$name},$newsettingstatus{$name}) =
 3081:                                 &Apache::loncommon::default_quota($env{'form.ccdomain'},$newinststatus,$name);
 3082:                         }
 3083:                     }
 3084:                     if (ref($usertypes) eq 'HASH') {
 3085:                         $newsettings{'inststatus'} = join(', ',map{ $usertypes->{$_}; } (@inststatuses)); 
 3086:                     } else {
 3087:                         $newsettings{'inststatus'} = join(', ',@inststatuses);
 3088:                     }
 3089:                 }
 3090:             } else {
 3091:                 $newinststatus = '';
 3092:                 $changeHash{'inststatus'} = $newinststatus;
 3093:                 $newsettings{'inststatus'} = $othertitle;
 3094:                 if ($newinststatus ne $oldinststatus) {
 3095:                     $changed{'inststatus'} = $changeHash{'inststatus'};
 3096:                     foreach my $name ('portfolio','author') {
 3097:                         ($newdefquota{$name},$newsettingstatus{$name}) =
 3098:                             &Apache::loncommon::default_quota($env{'form.ccdomain'},$newinststatus,$name);
 3099:                     }
 3100:                 }
 3101:             }
 3102:         } elsif ($context ne 'selfcreate') {
 3103:             $canshow{'inststatus'} = 1;
 3104:             $newsettings{'inststatus'} = $oldsettings{'inststatus'};
 3105:         }
 3106:         foreach my $name ('portfolio','author') {
 3107:             $changeHash{$name.'quota'} = $userenv{$name.'quota'};
 3108:         }
 3109:         if ($context eq 'domain') {
 3110:             foreach my $name ('portfolio','author') {
 3111:                 if ($userenv{$name.'quota'} ne '') {
 3112:                     $oldquota{$name} = $userenv{$name.'quota'};
 3113:                     if ($env{'form.custom_'.$name.'quota'} == 1) {
 3114:                         if ($env{'form.'.$name.'quota'} eq '') {
 3115:                             $newquota{$name} = 0;
 3116:                         } else {
 3117:                             $newquota{$name} = $env{'form.'.$name.'quota'};
 3118:                             $newquota{$name} =~ s/[^\d\.]//g;
 3119:                         }
 3120:                         if ($newquota{$name} != $oldquota{$name}) {
 3121:                             if (&quota_admin($newquota{$name},\%changeHash,$name)) {
 3122:                                 $changed{$name.'quota'} = 1;
 3123:                             }
 3124:                         }
 3125:                     } else {
 3126:                         if (&quota_admin('',\%changeHash,$name)) {
 3127:                             $changed{$name.'quota'} = 1;
 3128:                             $newquota{$name} = $newdefquota{$name};
 3129:                             $newisdefault{$name} = 1;
 3130:                         }
 3131:                     }
 3132:                 } else {
 3133:                     $oldisdefault{$name} = 1;
 3134:                     $oldquota{$name} = $olddefquota{$name};
 3135:                     if ($env{'form.custom_'.$name.'quota'} == 1) {
 3136:                         if ($env{'form.'.$name.'quota'} eq '') {
 3137:                             $newquota{$name} = 0;
 3138:                         } else {
 3139:                             $newquota{$name} = $env{'form.'.$name.'quota'};
 3140:                             $newquota{$name} =~ s/[^\d\.]//g;
 3141:                         }
 3142:                         if (&quota_admin($newquota{$name},\%changeHash,$name)) {
 3143:                             $changed{$name.'quota'} = 1;
 3144:                         }
 3145:                     } else {
 3146:                         $newquota{$name} = $newdefquota{$name};
 3147:                         $newisdefault{$name} = 1;
 3148:                     }
 3149:                 }
 3150:                 if ($oldisdefault{$name}) {
 3151:                     $oldsettingstext{'quota'}{$name} = &get_defaultquota_text($oldsettingstatus{$name});
 3152:                 }  else {
 3153:                     $oldsettingstext{'quota'}{$name} = &mt('custom quota: [_1] MB',$oldquota{$name});
 3154:                 }
 3155:                 if ($newisdefault{$name}) {
 3156:                     $newsettingstext{'quota'}{$name} = &get_defaultquota_text($newsettingstatus{$name});
 3157:                 } else {
 3158:                     $newsettingstext{'quota'}{$name} = &mt('custom quota: [_1] MB',$newquota{$name});
 3159:                 }
 3160:             }
 3161:             &tool_changes('tools',\@usertools,\%oldsettings,\%oldsettingstext,\%userenv,
 3162:                           \%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3163:             if ($env{'form.ccdomain'} eq $env{'request.role.domain'}) {
 3164:                 &tool_changes('requestcourses',\@requestcourses,\%oldsettings,\%oldsettingstext,
 3165:                               \%userenv,\%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3166:                 &tool_changes('requestauthor',\@requestauthor,\%oldsettings,\%oldsettingstext,
 3167:                               \%userenv,\%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3168:             } else {
 3169:                 &tool_changes('reqcrsotherdom',\@requestcourses,\%oldsettings,\%oldsettingstext,
 3170:                               \%userenv,\%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3171:             }
 3172:         }
 3173:         foreach my $item (@userinfo) {
 3174:             if ($env{'form.c'.$item} ne $userenv{$item}) {
 3175:                 $namechanged{$item} = 1;
 3176:             }
 3177:         }
 3178:         foreach my $name ('portfolio','author') {
 3179:             $oldsettings{'quota'}{$name} = &mt('[_1] MB',$oldquota{$name});
 3180:             $newsettings{'quota'}{$name} = &mt('[_1] MB',$newquota{$name});
 3181:         }
 3182:         if ((keys(%namechanged) > 0) || (keys(%changed) > 0)) {
 3183:             my ($chgresult,$namechgresult);
 3184:             if (keys(%changed) > 0) {
 3185:                 $chgresult = 
 3186:                     &Apache::lonnet::put('environment',\%changeHash,
 3187:                                   $env{'form.ccdomain'},$env{'form.ccuname'});
 3188:                 if ($chgresult eq 'ok') {
 3189:                     if (($env{'user.name'} eq $env{'form.ccuname'}) &&
 3190:                         ($env{'user.domain'} eq $env{'form.ccdomain'})) {
 3191:                         my %newenvhash;
 3192:                         foreach my $key (keys(%changed)) {
 3193:                             if (($key eq 'official') || ($key eq 'unofficial')
 3194:                                 || ($key eq 'community') || ($key eq 'textbook')) {
 3195:                                 $newenvhash{'environment.requestcourses.'.$key} =
 3196:                                     $changeHash{'requestcourses.'.$key};
 3197:                                 if ($changeHash{'requestcourses.'.$key}) {
 3198:                                     $newenvhash{'environment.canrequest.'.$key} = 1;
 3199:                                 } else {
 3200:                                     $newenvhash{'environment.canrequest.'.$key} =
 3201:           &Apache::lonnet::usertools_access($env{'user.name'},$env{'user.domain'},
 3202:                                             $key,'reload','requestcourses');
 3203:                                 }
 3204:                             } elsif ($key eq 'requestauthor') {
 3205:                                 $newenvhash{'environment.'.$key} = $changeHash{$key};
 3206:                                 if ($changeHash{$key}) {
 3207:                                     $newenvhash{'environment.canrequest.author'} = 1;
 3208:                                 } else {
 3209:                                     $newenvhash{'environment.canrequest.author'} =
 3210:           &Apache::lonnet::usertools_access($env{'user.name'},$env{'user.domain'},
 3211:                                             $key,'reload','requestauthor');
 3212:                                 }
 3213:                             } elsif ($key ne 'quota') {
 3214:                                 $newenvhash{'environment.tools.'.$key} = 
 3215:                                     $changeHash{'tools.'.$key};
 3216:                                 if ($changeHash{'tools.'.$key} ne '') {
 3217:                                     $newenvhash{'environment.availabletools.'.$key} =
 3218:                                         $changeHash{'tools.'.$key};
 3219:                                 } else {
 3220:                                     $newenvhash{'environment.availabletools.'.$key} =
 3221:           &Apache::lonnet::usertools_access($env{'user.name'},$env{'user.domain'},
 3222:           $key,'reload','tools');
 3223:                                 }
 3224:                             }
 3225:                         }
 3226:                         if (keys(%newenvhash)) {
 3227:                             &Apache::lonnet::appenv(\%newenvhash);
 3228:                         }
 3229:                     }
 3230:                 }
 3231:             }
 3232:             if (keys(%namechanged) > 0) {
 3233:                 foreach my $field (@userinfo) {
 3234:                     $changeHash{$field}  = $env{'form.c'.$field};
 3235:                 }
 3236: # Make the change
 3237:                 $namechgresult =
 3238:                     &Apache::lonnet::modifyuser($env{'form.ccdomain'},
 3239:                         $env{'form.ccuname'},$changeHash{'id'},undef,undef,
 3240:                         $changeHash{'firstname'},$changeHash{'middlename'},
 3241:                         $changeHash{'lastname'},$changeHash{'generation'},
 3242:                         $changeHash{'id'},undef,$changeHash{'permanentemail'},undef,\@userinfo);
 3243:                 %userupdate = (
 3244:                                lastname   => $env{'form.clastname'},
 3245:                                middlename => $env{'form.cmiddlename'},
 3246:                                firstname  => $env{'form.cfirstname'},
 3247:                                generation => $env{'form.cgeneration'},
 3248:                                id         => $env{'form.cid'},
 3249:                              );
 3250:             }
 3251:             if (((keys(%namechanged) > 0) && $namechgresult eq 'ok') || 
 3252:                 ((keys(%changed) > 0) && $chgresult eq 'ok')) {
 3253:             # Tell the user we changed the name
 3254:                 &display_userinfo($r,1,\@disporder,\%canshow,\@requestcourses,
 3255:                                   \@usertools,\@requestauthor,\%userenv,\%changed,\%namechanged,
 3256:                                   \%oldsettings, \%oldsettingstext,\%newsettings,
 3257:                                   \%newsettingstext);
 3258:                 if ($env{'form.cid'} ne $userenv{'id'}) {
 3259:                     &Apache::lonnet::idput($env{'form.ccdomain'},
 3260:                          {$env{'form.ccuname'} => $env{'form.cid'}});
 3261:                     if (($recurseid) &&
 3262:                         (&Apache::lonnet::allowed('mau',$env{'form.ccdomain'}))) {
 3263:                         my $idresult = 
 3264:                             &Apache::lonuserutils::propagate_id_change(
 3265:                                 $env{'form.ccuname'},$env{'form.ccdomain'},
 3266:                                 \%userupdate);
 3267:                         $r->print('<br />'.$idresult.'<br />');
 3268:                     }
 3269:                 }
 3270:                 if (($env{'form.ccdomain'} eq $env{'user.domain'}) && 
 3271:                     ($env{'form.ccuname'} eq $env{'user.name'})) {
 3272:                     my %newenvhash;
 3273:                     foreach my $key (keys(%changeHash)) {
 3274:                         $newenvhash{'environment.'.$key} = $changeHash{$key};
 3275:                     }
 3276:                     &Apache::lonnet::appenv(\%newenvhash);
 3277:                 }
 3278:             } else { # error occurred
 3279:                 $r->print(
 3280:                     '<p class="LC_error">'
 3281:                    .&mt('Unable to successfully change environment for [_1] in domain [_2].',
 3282:                             '"'.$env{'form.ccuname'}.'"',
 3283:                             '"'.$env{'form.ccdomain'}.'"')
 3284:                    .'</p>');
 3285:             }
 3286:         } else { # End of if ($env ... ) logic
 3287:             # They did not want to change the users name, quota, tool availability,
 3288:             # or ability to request creation of courses, 
 3289:             # but we can still tell them what the name and quota and availabilities are  
 3290:             &display_userinfo($r,undef,\@disporder,\%canshow,\@requestcourses,
 3291:                               \@usertools,\@requestauthor,\%userenv,\%changed,\%namechanged,\%oldsettings,
 3292:                               \%oldsettingstext,\%newsettings,\%newsettingstext);
 3293:         }
 3294:         if (@mod_disallowed) {
 3295:             my ($rolestr,$contextname);
 3296:             if (@longroles > 0) {
 3297:                 $rolestr = join(', ',@longroles);
 3298:             } else {
 3299:                 $rolestr = &mt('No roles');
 3300:             }
 3301:             if ($context eq 'course') {
 3302:                 $contextname = 'course';
 3303:             } elsif ($context eq 'author') {
 3304:                 $contextname = 'co-author';
 3305:             }
 3306:             $r->print(&mt('The following fields were not updated: ').'<ul>');
 3307:             my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
 3308:             foreach my $field (@mod_disallowed) {
 3309:                 $r->print('<li>'.$fieldtitles{$field}.'</li>'."\n"); 
 3310:             }
 3311:             $r->print('</ul>');
 3312:             if (@mod_disallowed == 1) {
 3313:                 $r->print(&mt("You do not have the authority to change this field given the user's current set of active/future $contextname roles:"));
 3314:             } else {
 3315:                 $r->print(&mt("You do not have the authority to change these fields given the user's current set of active/future $contextname roles:"));
 3316:             }
 3317:             my $helplink = 'javascript:helpMenu('."'display'".')';
 3318:             $r->print('<span class="LC_cusr_emph">'.$rolestr.'</span><br />'
 3319:                      .&mt('Please contact your [_1]helpdesk[_2] for more information.'
 3320:                          ,'<a href="'.$helplink.'">','</a>')
 3321:                       .'<br />');
 3322:         }
 3323:         $r->print('<span class="LC_warning">'
 3324:                   .$no_forceid_alert
 3325:                   .&Apache::lonuserutils::print_namespacing_alerts($env{'form.ccdomain'},\%alerts,\%curr_rules)
 3326:                   .'</span>');
 3327:     }
 3328:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 3329:     if ($env{'form.action'} eq 'singlestudent') {
 3330:         &enroll_single_student($r,$uhome,$amode,$genpwd,$now,$newuser,$context,
 3331:                                $crstype,$showcredits,$defaultcredits);
 3332:         my $linktext = ($crstype eq 'Community' ?
 3333:             &mt('Enroll Another Member') : &mt('Enroll Another Student'));
 3334:         $r->print(
 3335:             &Apache::lonhtmlcommon::actionbox([
 3336:                 '<a href="javascript:backPage(document.userupdate)">'
 3337:                .($crstype eq 'Community' ? 
 3338:                     &mt('Enroll Another Member') : &mt('Enroll Another Student'))
 3339:                .'</a>']));
 3340:     } else {
 3341:         my @rolechanges = &update_roles($r,$context,$showcredits);
 3342:         if (keys(%namechanged) > 0) {
 3343:             if ($context eq 'course') {
 3344:                 if (@userroles > 0) {
 3345:                     if ((@rolechanges == 0) || 
 3346:                         (!(grep(/^st$/,@rolechanges)))) {
 3347:                         if (grep(/^st$/,@userroles)) {
 3348:                             my $classlistupdated =
 3349:                                 &Apache::lonuserutils::update_classlist($cdom,
 3350:                                               $cnum,$env{'form.ccdomain'},
 3351:                                        $env{'form.ccuname'},\%userupdate);
 3352:                         }
 3353:                     }
 3354:                 }
 3355:             }
 3356:         }
 3357:         my $userinfo = &Apache::loncommon::plainname($env{'form.ccuname'},
 3358:                                                      $env{'form.ccdomain'});
 3359:         if ($env{'form.popup'}) {
 3360:             $r->print('<p><a href="javascript:window.close()">'.&mt('Close window').'</a></p>');
 3361:         } else {
 3362:             $r->print('<br />'.&Apache::lonhtmlcommon::actionbox(['<a href="javascript:backPage(document.userupdate,'."'$env{'form.prevphase'}','modify'".')">'
 3363:                      .&mt('Modify this user: [_1]','<span class="LC_cusr_emph">'.$env{'form.ccuname'}.':'.$env{'form.ccdomain'}.' ('.$userinfo.')</span>').'</a>',
 3364:                      '<a href="javascript:backPage(document.userupdate)">'.&mt('Create/Modify Another User').'</a>']));
 3365:         }
 3366:     }
 3367: }
 3368: 
 3369: sub display_userinfo {
 3370:     my ($r,$changed,$order,$canshow,$requestcourses,$usertools,$requestauthor,
 3371:         $userenv,$changedhash,$namechangedhash,$oldsetting,$oldsettingtext,
 3372:         $newsetting,$newsettingtext) = @_;
 3373:     return unless (ref($order) eq 'ARRAY' &&
 3374:                    ref($canshow) eq 'HASH' && 
 3375:                    ref($requestcourses) eq 'ARRAY' && 
 3376:                    ref($requestauthor) eq 'ARRAY' &&
 3377:                    ref($usertools) eq 'ARRAY' && 
 3378:                    ref($userenv) eq 'HASH' &&
 3379:                    ref($changedhash) eq 'HASH' &&
 3380:                    ref($oldsetting) eq 'HASH' &&
 3381:                    ref($oldsettingtext) eq 'HASH' &&
 3382:                    ref($newsetting) eq 'HASH' &&
 3383:                    ref($newsettingtext) eq 'HASH');
 3384:     my %lt=&Apache::lonlocal::texthash(
 3385:          'ui'             => 'User Information',
 3386:          'uic'            => 'User Information Changed',
 3387:          'firstname'      => 'First Name',
 3388:          'middlename'     => 'Middle Name',
 3389:          'lastname'       => 'Last Name',
 3390:          'generation'     => 'Generation',
 3391:          'id'             => 'Student/Employee ID',
 3392:          'permanentemail' => 'Permanent e-mail address',
 3393:          'portfolioquota' => 'Disk space allocated to portfolio files',
 3394:          'authorquota'    => 'Disk space allocated to Authoring Space',
 3395:          'blog'           => 'Blog Availability',
 3396:          'webdav'         => 'WebDAV Availability',
 3397:          'aboutme'        => 'Personal Information Page Availability',
 3398:          'portfolio'      => 'Portfolio Availability',
 3399:          'official'       => 'Can Request Official Courses',
 3400:          'unofficial'     => 'Can Request Unofficial Courses',
 3401:          'community'      => 'Can Request Communities',
 3402:          'textbook'       => 'Can Request Textbook Courses',
 3403:          'requestauthor'  => 'Can Request Author Role',
 3404:          'inststatus'     => "Affiliation",
 3405:          'prvs'           => 'Previous Value:',
 3406:          'chto'           => 'Changed To:'
 3407:     );
 3408:     if ($changed) {
 3409:         $r->print('<h3>'.$lt{'uic'}.'</h3>'.
 3410:                 &Apache::loncommon::start_data_table().
 3411:                 &Apache::loncommon::start_data_table_header_row());
 3412:         $r->print("<th>&nbsp;</th>\n");
 3413:         $r->print('<th><b>'.$lt{'prvs'}.'</b></th>');
 3414:         $r->print('<th><span class="LC_nobreak"><b>'.$lt{'chto'}.'</b></span></th>');
 3415:         $r->print(&Apache::loncommon::end_data_table_header_row());
 3416:         my @userinfo = ('firstname','middlename','lastname','generation','permanentemail','id');
 3417: 
 3418:         foreach my $item (@userinfo) {
 3419:             my $value = $env{'form.c'.$item};
 3420:             #show changes only:
 3421:             unless ($value eq $userenv->{$item}){
 3422:                 $r->print(&Apache::loncommon::start_data_table_row());
 3423:                 $r->print("<td>$lt{$item}</td>\n");
 3424:                 $r->print("<td>".$userenv->{$item}."</td>\n");
 3425:                 $r->print("<td>$value </td>\n");
 3426:                 $r->print(&Apache::loncommon::end_data_table_row());
 3427:             }
 3428:         }
 3429:         foreach my $entry (@{$order}) {
 3430:             if ($canshow->{$entry}) {
 3431:                 if (($entry eq 'requestcourses') || ($entry eq 'reqcrsotherdom') || ($entry eq 'requestauthor')) {
 3432:                     my @items;
 3433:                     if ($entry eq 'requestauthor') {
 3434:                         @items = ($entry);
 3435:                     } else {
 3436:                         @items = @{$requestcourses};
 3437:                     }
 3438:                     foreach my $item (@items) {
 3439:                         if (($newsetting->{$item} ne $oldsetting->{$item}) || 
 3440:                             ($newsettingtext->{$item} ne $oldsettingtext->{$item})) {
 3441:                             $r->print(&Apache::loncommon::start_data_table_row()."\n");  
 3442:                             $r->print("<td>$lt{$item}</td>\n");
 3443:                             $r->print("<td>".$oldsetting->{$item});
 3444:                             if ($oldsettingtext->{$item}) {
 3445:                                 if ($oldsetting->{$item}) {
 3446:                                     $r->print(' -- ');
 3447:                                 }
 3448:                                 $r->print($oldsettingtext->{$item});
 3449:                             }
 3450:                             $r->print("</td>\n");
 3451:                             $r->print("<td>".$newsetting->{$item});
 3452:                             if ($newsettingtext->{$item}) {
 3453:                                 if ($newsetting->{$item}) {
 3454:                                     $r->print(' -- ');
 3455:                                 }
 3456:                                 $r->print($newsettingtext->{$item});
 3457:                             }
 3458:                             $r->print("</td>\n");
 3459:                             $r->print(&Apache::loncommon::end_data_table_row()."\n");
 3460:                         }
 3461:                     }
 3462:                 } elsif ($entry eq 'tools') {
 3463:                     foreach my $item (@{$usertools}) {
 3464:                         if ($newsetting->{$item} ne $oldsetting->{$item}) {
 3465:                             $r->print(&Apache::loncommon::start_data_table_row()."\n");
 3466:                             $r->print("<td>$lt{$item}</td>\n");
 3467:                             $r->print("<td>".$oldsetting->{$item}.' '.$oldsettingtext->{$item}."</td>\n");
 3468:                             $r->print("<td>".$newsetting->{$item}.' '.$newsettingtext->{$item}."</td>\n");
 3469:                             $r->print(&Apache::loncommon::end_data_table_row()."\n");
 3470:                         }
 3471:                     }
 3472:                 } elsif ($entry eq 'quota') {
 3473:                     if ((ref($oldsetting->{$entry}) eq 'HASH') && (ref($oldsettingtext->{$entry}) eq 'HASH') &&
 3474:                         (ref($newsetting->{$entry}) eq 'HASH') && (ref($newsettingtext->{$entry}) eq 'HASH')) {
 3475:                         foreach my $name ('portfolio','author') {
 3476:                             if ($newsetting->{$entry}->{$name} ne $oldsetting->{$entry}->{$name}) {
 3477:                                 $r->print(&Apache::loncommon::start_data_table_row()."\n");
 3478:                                 $r->print("<td>$lt{$name.$entry}</td>\n");
 3479:                                 $r->print("<td>".$oldsettingtext->{$entry}->{$name}."</td>\n");
 3480:                                 $r->print("<td>".$newsettingtext->{$entry}->{$name}."</td>\n");
 3481:                                 $r->print(&Apache::loncommon::end_data_table_row()."\n");
 3482:                             }
 3483:                         }
 3484:                     }
 3485:                 } else {
 3486:                     if ($newsetting->{$entry} ne $oldsetting->{$entry}) {
 3487:                         $r->print(&Apache::loncommon::start_data_table_row()."\n");
 3488:                         $r->print("<td>$lt{$entry}</td>\n");
 3489:                         $r->print("<td>".$oldsetting->{$entry}.' '.$oldsettingtext->{$entry}."</td>\n");
 3490:                         $r->print("<td>".$newsetting->{$entry}.' '.$newsettingtext->{$entry}."</td>\n");
 3491:                         $r->print(&Apache::loncommon::end_data_table_row()."\n");
 3492:                     }
 3493:                 }
 3494:             }
 3495:         }
 3496:         $r->print(&Apache::loncommon::end_data_table().'<br />');
 3497:     } else {
 3498:         $r->print('<h3>'.$lt{'ui'}.'</h3>'.
 3499:                   '<p>'.&mt('No changes made to user information').'</p>');
 3500:     }
 3501:     return;
 3502: }
 3503: 
 3504: sub tool_changes {
 3505:     my ($context,$usertools,$oldaccess,$oldaccesstext,$userenv,$changeHash,
 3506:         $changed,$newaccess,$newaccesstext) = @_;
 3507:     if (!((ref($usertools) eq 'ARRAY') && (ref($oldaccess) eq 'HASH') &&
 3508:           (ref($oldaccesstext) eq 'HASH') && (ref($userenv) eq 'HASH') &&
 3509:           (ref($changeHash) eq 'HASH') && (ref($changed) eq 'HASH') &&
 3510:           (ref($newaccess) eq 'HASH') && (ref($newaccesstext) eq 'HASH'))) {
 3511:         return;
 3512:     }
 3513:     my %reqdisplay = &requestchange_display();
 3514:     if ($context eq 'reqcrsotherdom') {
 3515:         my @options = ('approval','validate','autolimit');
 3516:         my $optregex = join('|',@options);
 3517:         my $cdom = $env{'request.role.domain'};
 3518:         foreach my $tool (@{$usertools}) {
 3519:             $oldaccesstext->{$tool} = &mt("availability set to 'off'");
 3520:             $newaccesstext->{$tool} = $oldaccesstext->{$tool};
 3521:             $changeHash->{$context.'.'.$tool} = $userenv->{$context.'.'.$tool};
 3522:             my ($newop,$limit);
 3523:             if ($env{'form.'.$context.'_'.$tool}) {
 3524:                 $newop = $env{'form.'.$context.'_'.$tool};
 3525:                 if ($newop eq 'autolimit') {
 3526:                     $limit = $env{'form.'.$context.'_'.$tool.'_limit'};
 3527:                     $limit =~ s/\D+//g;
 3528:                     $newop .= '='.$limit;
 3529:                 }
 3530:             }
 3531:             if ($userenv->{$context.'.'.$tool} eq '') {
 3532:                 if ($newop) {
 3533:                     $changed->{$tool}=&tool_admin($tool,$cdom.':'.$newop,
 3534:                                                   $changeHash,$context);
 3535:                     if ($changed->{$tool}) {
 3536:                         if ($newop =~ /^autolimit/) {
 3537:                             if ($limit) {
 3538:                                 $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3539:                             } else {
 3540:                                 $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3541:                             }
 3542:                         } else {
 3543:                             $newaccesstext->{$tool} = $reqdisplay{$newop};
 3544:                         }
 3545:                     } else {
 3546:                         $newaccesstext->{$tool} = $oldaccesstext->{$tool};
 3547:                     }
 3548:                 }
 3549:             } else {
 3550:                 my @curr = split(',',$userenv->{$context.'.'.$tool});
 3551:                 my @new;
 3552:                 my $changedoms;
 3553:                 foreach my $req (@curr) {
 3554:                     if ($req =~ /^\Q$cdom\E\:($optregex\=?\d*)$/) {
 3555:                         my $oldop = $1;
 3556:                         if ($oldop =~ /^autolimit=(\d*)/) {
 3557:                             my $limit = $1;
 3558:                             if ($limit) {
 3559:                                 $oldaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3560:                             } else {
 3561:                                 $oldaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3562:                             }
 3563:                         } else {
 3564:                             $oldaccesstext->{$tool} = $reqdisplay{$oldop};
 3565:                         }
 3566:                         if ($oldop ne $newop) {
 3567:                             $changedoms = 1;
 3568:                             foreach my $item (@curr) {
 3569:                                 my ($reqdom,$option) = split(':',$item);
 3570:                                 unless ($reqdom eq $cdom) {
 3571:                                     push(@new,$item);
 3572:                                 }
 3573:                             }
 3574:                             if ($newop) {
 3575:                                 push(@new,$cdom.':'.$newop);
 3576:                             }
 3577:                             @new = sort(@new);
 3578:                         }
 3579:                         last;
 3580:                     }
 3581:                 }
 3582:                 if ((!$changedoms) && ($newop)) {
 3583:                     $changedoms = 1;
 3584:                     @new = sort(@curr,$cdom.':'.$newop);
 3585:                 }
 3586:                 if ($changedoms) {
 3587:                     my $newdomstr;
 3588:                     if (@new) {
 3589:                         $newdomstr = join(',',@new);
 3590:                     }
 3591:                     $changed->{$tool}=&tool_admin($tool,$newdomstr,$changeHash,
 3592:                                                   $context);
 3593:                     if ($changed->{$tool}) {
 3594:                         if ($env{'form.'.$context.'_'.$tool}) {
 3595:                             if ($env{'form.'.$context.'_'.$tool} eq 'autolimit') {
 3596:                                 my $limit = $env{'form.'.$context.'_'.$tool.'_limit'};
 3597:                                 $limit =~ s/\D+//g;
 3598:                                 if ($limit) {
 3599:                                     $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3600:                                 } else {
 3601:                                     $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3602:                                 }
 3603:                             } else {
 3604:                                 $newaccesstext->{$tool} = $reqdisplay{$env{'form.'.$context.'_'.$tool}};
 3605:                             }
 3606:                         } else {
 3607:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3608:                         }
 3609:                     }
 3610:                 }
 3611:             }
 3612:         }
 3613:         return;
 3614:     }
 3615:     foreach my $tool (@{$usertools}) {
 3616:         my ($newval,$limit,$envkey);
 3617:         $envkey = $context.'.'.$tool;
 3618:         if ($context eq 'requestcourses') {
 3619:             $newval = $env{'form.crsreq_'.$tool};
 3620:             if ($newval eq 'autolimit') {
 3621:                 $limit = $env{'form.crsreq_'.$tool.'_limit'};
 3622:                 $limit =~ s/\D+//g;
 3623:                 $newval .= '='.$limit;
 3624:             }
 3625:         } elsif ($context eq 'requestauthor') {
 3626:             $newval = $env{'form.'.$context};
 3627:             $envkey = $context;
 3628:         } else {
 3629:             $newval = $env{'form.'.$context.'_'.$tool};
 3630:         }
 3631:         if ($userenv->{$envkey} ne '') {
 3632:             $oldaccess->{$tool} = &mt('custom');
 3633:             if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 3634:                 if ($userenv->{$envkey} =~ /^autolimit=(\d*)$/) {
 3635:                     my $currlimit = $1;
 3636:                     if ($currlimit eq '') {
 3637:                         $oldaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3638:                     } else {
 3639:                         $oldaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$currlimit);
 3640:                     }
 3641:                 } elsif ($userenv->{$envkey}) {
 3642:                     $oldaccesstext->{$tool} = $reqdisplay{$userenv->{$envkey}};
 3643:                 } else {
 3644:                     $oldaccesstext->{$tool} = &mt("availability set to 'off'");
 3645:                 }
 3646:             } else {
 3647:                 if ($userenv->{$envkey}) {
 3648:                     $oldaccesstext->{$tool} = &mt("availability set to 'on'");
 3649:                 } else {
 3650:                     $oldaccesstext->{$tool} = &mt("availability set to 'off'");
 3651:                 }
 3652:             }
 3653:             $changeHash->{$envkey} = $userenv->{$envkey};
 3654:             if ($env{'form.custom'.$tool} == 1) {
 3655:                 if ($newval ne $userenv->{$envkey}) {
 3656:                     $changed->{$tool} = &tool_admin($tool,$newval,$changeHash,
 3657:                                                     $context);
 3658:                     if ($changed->{$tool}) {
 3659:                         $newaccess->{$tool} = &mt('custom');
 3660:                         if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 3661:                             if ($newval =~ /^autolimit/) {
 3662:                                 if ($limit) {
 3663:                                     $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3664:                                 } else {
 3665:                                     $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3666:                                 }
 3667:                             } elsif ($newval) {
 3668:                                 $newaccesstext->{$tool} = $reqdisplay{$newval};
 3669:                             } else {
 3670:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3671:                             }
 3672:                         } else {
 3673:                             if ($newval) {
 3674:                                 $newaccesstext->{$tool} = &mt("availability set to 'on'");
 3675:                             } else {
 3676:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3677:                             }
 3678:                         }
 3679:                     } else {
 3680:                         $newaccess->{$tool} = $oldaccess->{$tool};
 3681:                         if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 3682:                             if ($newval =~ /^autolimit/) {
 3683:                                 if ($limit) {
 3684:                                     $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3685:                                 } else {
 3686:                                     $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3687:                                 }
 3688:                             } elsif ($newval) {
 3689:                                 $newaccesstext->{$tool} = $reqdisplay{$newval};
 3690:                             } else {
 3691:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3692:                             }
 3693:                         } else {
 3694:                             if ($userenv->{$context.'.'.$tool}) {
 3695:                                 $newaccesstext->{$tool} = &mt("availability set to 'on'");
 3696:                             } else {
 3697:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3698:                             }
 3699:                         }
 3700:                     }
 3701:                 } else {
 3702:                     $newaccess->{$tool} = $oldaccess->{$tool};
 3703:                     $newaccesstext->{$tool} = $oldaccesstext->{$tool};
 3704:                 }
 3705:             } else {
 3706:                 $changed->{$tool} = &tool_admin($tool,'',$changeHash,$context);
 3707:                 if ($changed->{$tool}) {
 3708:                     $newaccess->{$tool} = &mt('default');
 3709:                 } else {
 3710:                     $newaccess->{$tool} = $oldaccess->{$tool};
 3711:                     if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 3712:                         if ($newval =~ /^autolimit/) {
 3713:                             if ($limit) {
 3714:                                 $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3715:                             } else {
 3716:                                 $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3717:                             }
 3718:                         } elsif ($newval) {
 3719:                             $newaccesstext->{$tool} = $reqdisplay{$newval};
 3720:                         } else {
 3721:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3722:                         }
 3723:                     } else {
 3724:                         if ($userenv->{$context.'.'.$tool}) {
 3725:                             $newaccesstext->{$tool} = &mt("availability set to 'on'");
 3726:                         } else {
 3727:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3728:                         }
 3729:                     }
 3730:                 }
 3731:             }
 3732:         } else {
 3733:             $oldaccess->{$tool} = &mt('default');
 3734:             if ($env{'form.custom'.$tool} == 1) {
 3735:                 $changed->{$tool} = &tool_admin($tool,$newval,$changeHash,
 3736:                                                 $context);
 3737:                 if ($changed->{$tool}) {
 3738:                     $newaccess->{$tool} = &mt('custom');
 3739:                     if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 3740:                         if ($newval =~ /^autolimit/) {
 3741:                             if ($limit) {
 3742:                                 $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3743:                             } else {
 3744:                                 $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3745:                             }
 3746:                         } elsif ($newval) {
 3747:                             $newaccesstext->{$tool} = $reqdisplay{$newval};
 3748:                         } else {
 3749:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3750:                         }
 3751:                     } else {
 3752:                         if ($newval) {
 3753:                             $newaccesstext->{$tool} = &mt("availability set to 'on'");
 3754:                         } else {
 3755:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3756:                         }
 3757:                     }
 3758:                 } else {
 3759:                     $newaccess->{$tool} = $oldaccess->{$tool};
 3760:                 }
 3761:             } else {
 3762:                 $newaccess->{$tool} = $oldaccess->{$tool};
 3763:             }
 3764:         }
 3765:     }
 3766:     return;
 3767: }
 3768: 
 3769: sub update_roles {
 3770:     my ($r,$context,$showcredits) = @_;
 3771:     my $now=time;
 3772:     my @rolechanges;
 3773:     my %disallowed;
 3774:     $r->print('<h3>'.&mt('Modifying Roles').'</h3>');
 3775:     foreach my $key (keys(%env)) {
 3776: 	next if (! $env{$key});
 3777:         next if ($key eq 'form.action');
 3778: 	# Revoke roles
 3779: 	if ($key=~/^form\.rev/) {
 3780: 	    if ($key=~/^form\.rev\:([^\_]+)\_([^\_\.]+)$/) {
 3781: # Revoke standard role
 3782: 		my ($scope,$role) = ($1,$2);
 3783: 		my $result =
 3784: 		    &Apache::lonnet::revokerole($env{'form.ccdomain'},
 3785: 						$env{'form.ccuname'},
 3786: 						$scope,$role,'','',$context);
 3787:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
 3788:                             &mt('Revoking [_1] in [_2]',
 3789:                                 &Apache::lonnet::plaintext($role),
 3790:                                 &Apache::loncommon::show_role_extent($scope,$context,$role)),
 3791:                                 $result ne "ok").'<br />');
 3792:                 if ($result ne "ok") {
 3793:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 3794:                 }
 3795: 		if ($role eq 'st') {
 3796: 		    my $result = 
 3797:                         &Apache::lonuserutils::classlist_drop($scope,
 3798:                             $env{'form.ccuname'},$env{'form.ccdomain'},
 3799: 			    $now);
 3800:                     $r->print(&Apache::lonhtmlcommon::confirm_success($result));
 3801: 		}
 3802:                 if (!grep(/^\Q$role\E$/,@rolechanges)) {
 3803:                     push(@rolechanges,$role);
 3804:                 }
 3805: 	    }
 3806: 	    if ($key=~m{^form\.rev\:([^_]+)_cr\.cr/($match_domain)/($match_username)/(\w+)$}s) {
 3807: # Revoke custom role
 3808:                 my $result = &Apache::lonnet::revokecustomrole(
 3809:                     $env{'form.ccdomain'},$env{'form.ccuname'},$1,$2,$3,$4,'','',$context);
 3810:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
 3811:                             &mt('Revoking custom role [_1] by [_2] in [_3]',
 3812:                                 $4,$3.':'.$2,&Apache::loncommon::show_role_extent($1,$context,'cr')),
 3813:                             $result ne 'ok').'<br />');
 3814:                 if ($result ne "ok") {
 3815:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 3816:                 }
 3817:                 if (!grep(/^cr$/,@rolechanges)) {
 3818:                     push(@rolechanges,'cr');
 3819:                 }
 3820: 	    }
 3821: 	} elsif ($key=~/^form\.del/) {
 3822: 	    if ($key=~/^form\.del\:([^\_]+)\_([^\_\.]+)$/) {
 3823: # Delete standard role
 3824: 		my ($scope,$role) = ($1,$2);
 3825: 		my $result =
 3826: 		    &Apache::lonnet::assignrole($env{'form.ccdomain'},
 3827: 						$env{'form.ccuname'},
 3828: 						$scope,$role,$now,0,1,'',
 3829:                                                 $context);
 3830:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
 3831:                             &mt('Deleting [_1] in [_2]',
 3832:                                 &Apache::lonnet::plaintext($role),
 3833:                                 &Apache::loncommon::show_role_extent($scope,$context,$role)),
 3834:                             $result ne 'ok').'<br />');
 3835:                 if ($result ne "ok") {
 3836:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 3837:                 }
 3838: 
 3839: 		if ($role eq 'st') {
 3840: 		    my $result = 
 3841:                         &Apache::lonuserutils::classlist_drop($scope,
 3842:                             $env{'form.ccuname'},$env{'form.ccdomain'},
 3843: 			    $now);
 3844: 		    $r->print(&Apache::lonhtmlcommon::confirm_success($result));
 3845: 		}
 3846:                 if (!grep(/^\Q$role\E$/,@rolechanges)) {
 3847:                     push(@rolechanges,$role);
 3848:                 }
 3849:             }
 3850: 	    if ($key=~m{^form\.del\:([^_]+)_cr\.cr/($match_domain)/($match_username)/(\w+)$}) {
 3851:                 my ($url,$rdom,$rnam,$rolename) = ($1,$2,$3,$4);
 3852: # Delete custom role
 3853:                 my $result =
 3854:                     &Apache::lonnet::assigncustomrole($env{'form.ccdomain'},
 3855:                         $env{'form.ccuname'},$url,$rdom,$rnam,$rolename,$now,
 3856:                         0,1,$context);
 3857:                 $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('Deleting custom role [_1] by [_2] in [_3]',
 3858:                       $rolename,$rnam.':'.$rdom,&Apache::loncommon::show_role_extent($1,$context,'cr')),
 3859:                       $result ne "ok").'<br />');
 3860:                 if ($result ne "ok") {
 3861:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 3862:                 }
 3863: 
 3864:                 if (!grep(/^cr$/,@rolechanges)) {
 3865:                     push(@rolechanges,'cr');
 3866:                 }
 3867:             }
 3868: 	} elsif ($key=~/^form\.ren/) {
 3869:             my $udom = $env{'form.ccdomain'};
 3870:             my $uname = $env{'form.ccuname'};
 3871: # Re-enable standard role
 3872: 	    if ($key=~/^form\.ren\:([^\_]+)\_([^\_\.]+)$/) {
 3873:                 my $url = $1;
 3874:                 my $role = $2;
 3875:                 my $logmsg;
 3876:                 my $output;
 3877:                 if ($role eq 'st') {
 3878:                     if ($url =~ m-^/($match_domain)/($match_courseid)/?(\w*)$-) {
 3879:                         my ($cdom,$cnum,$csec) = ($1,$2,$3);
 3880:                         my $credits;
 3881:                         if ($showcredits) {
 3882:                             my $defaultcredits = 
 3883:                                 &Apache::lonuserutils::get_defaultcredits($cdom,$cnum);
 3884:                             $credits = &get_user_credits($defaultcredits,$cdom,$cnum);
 3885:                         }
 3886:                         my $result = &Apache::loncommon::commit_studentrole(\$logmsg,$udom,$uname,$url,$role,$now,0,$cdom,$cnum,$csec,$context,$credits);
 3887:                         if (($result =~ /^error/) || ($result eq 'not_in_class') || ($result eq 'unknown_course') || ($result eq 'refused')) {
 3888:                             if ($result eq 'refused' && $logmsg) {
 3889:                                 $output = $logmsg;
 3890:                             } else { 
 3891:                                 $output = &mt('Error: [_1]',$result)."\n";
 3892:                             }
 3893:                         } else {
 3894:                             $output = &Apache::lonhtmlcommon::confirm_success(&mt('Assigning [_1] in [_2] starting [_3]',
 3895:                                         &Apache::lonnet::plaintext($role),
 3896:                                         &Apache::loncommon::show_role_extent($url,$context,'st'),
 3897:                                         &Apache::lonlocal::locallocaltime($now))).'<br />'.$logmsg.'<br />';
 3898:                         }
 3899:                     }
 3900:                 } else {
 3901: 		    my $result=&Apache::lonnet::assignrole($env{'form.ccdomain'},
 3902:                                $env{'form.ccuname'},$url,$role,0,$now,'','',
 3903:                                $context);
 3904:                         $output = &Apache::lonhtmlcommon::confirm_success(&mt('Re-enabling [_1] in [_2]',
 3905:                                         &Apache::lonnet::plaintext($role),
 3906:                                         &Apache::loncommon::show_role_extent($url,$context,$role)),$result ne "ok").'<br />';
 3907:                     if ($result ne "ok") {
 3908:                         $output .= &mt('Error: [_1]',$result).'<br />';
 3909:                     }
 3910:                 }
 3911:                 $r->print($output);
 3912:                 if (!grep(/^\Q$role\E$/,@rolechanges)) {
 3913:                     push(@rolechanges,$role);
 3914:                 }
 3915: 	    }
 3916: # Re-enable custom role
 3917: 	    if ($key=~m{^form\.ren\:([^_]+)_cr\.cr/($match_domain)/($match_username)/(\w+)$}) {
 3918:                 my ($url,$rdom,$rnam,$rolename) = ($1,$2,$3,$4);
 3919:                 my $result = &Apache::lonnet::assigncustomrole(
 3920:                                $env{'form.ccdomain'}, $env{'form.ccuname'},
 3921:                                $url,$rdom,$rnam,$rolename,0,$now,undef,$context);
 3922:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
 3923:                     &mt('Re-enabling custom role [_1] by [_2] in [_3]',
 3924:                         $rolename,$rnam.':'.$rdom,&Apache::loncommon::show_role_extent($1,$context,'cr')),
 3925:                     $result ne "ok").'<br />');
 3926:                 if ($result ne "ok") {
 3927:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 3928:                 }
 3929:                 if (!grep(/^cr$/,@rolechanges)) {
 3930:                     push(@rolechanges,'cr');
 3931:                 }
 3932:             }
 3933: 	} elsif ($key=~/^form\.act/) {
 3934:             my $udom = $env{'form.ccdomain'};
 3935:             my $uname = $env{'form.ccuname'};
 3936: 	    if ($key=~/^form\.act\_($match_domain)\_($match_courseid)\_cr_cr_($match_domain)_($match_username)_([^\_]+)$/) {
 3937:                 # Activate a custom role
 3938: 		my ($one,$two,$three,$four,$five)=($1,$2,$3,$4,$5);
 3939: 		my $url='/'.$one.'/'.$two;
 3940: 		my $full=$one.'_'.$two.'_cr_cr_'.$three.'_'.$four.'_'.$five;
 3941: 
 3942:                 my $start = ( $env{'form.start_'.$full} ?
 3943:                               $env{'form.start_'.$full} :
 3944:                               $now );
 3945:                 my $end   = ( $env{'form.end_'.$full} ?
 3946:                               $env{'form.end_'.$full} :
 3947:                               0 );
 3948:                                                                                      
 3949:                 # split multiple sections
 3950:                 my %sections = ();
 3951:                 my $num_sections = &build_roles($env{'form.sec_'.$full},\%sections,$5);
 3952:                 if ($num_sections == 0) {
 3953:                     $r->print(&Apache::loncommon::commit_customrole($udom,$uname,$url,$three,$four,$five,$start,$end,$context));
 3954:                 } else {
 3955: 		    my %curr_groups =
 3956: 			&Apache::longroup::coursegroups($one,$two);
 3957:                     foreach my $sec (sort {$a cmp $b} keys(%sections)) {
 3958:                         if (($sec eq 'none') || ($sec eq 'all') || 
 3959:                             exists($curr_groups{$sec})) {
 3960:                             $disallowed{$sec} = $url;
 3961:                             next;
 3962:                         }
 3963:                         my $securl = $url.'/'.$sec;
 3964: 		        $r->print(&Apache::loncommon::commit_customrole($udom,$uname,$securl,$three,$four,$five,$start,$end,$context));
 3965:                     }
 3966:                 }
 3967:                 if (!grep(/^cr$/,@rolechanges)) {
 3968:                     push(@rolechanges,'cr');
 3969:                 }
 3970: 	    } elsif ($key=~/^form\.act\_($match_domain)\_($match_name)\_([^\_]+)$/) {
 3971: 		# Activate roles for sections with 3 id numbers
 3972: 		# set start, end times, and the url for the class
 3973: 		my ($one,$two,$three)=($1,$2,$3);
 3974: 		my $start = ( $env{'form.start_'.$one.'_'.$two.'_'.$three} ? 
 3975: 			      $env{'form.start_'.$one.'_'.$two.'_'.$three} : 
 3976: 			      $now );
 3977: 		my $end   = ( $env{'form.end_'.$one.'_'.$two.'_'.$three} ? 
 3978: 			      $env{'form.end_'.$one.'_'.$two.'_'.$three} :
 3979: 			      0 );
 3980: 		my $url='/'.$one.'/'.$two;
 3981:                 my $type = 'three';
 3982:                 # split multiple sections
 3983:                 my %sections = ();
 3984:                 my $num_sections = &build_roles($env{'form.sec_'.$one.'_'.$two.'_'.$three},\%sections,$three);
 3985:                 my $credits;
 3986:                 if ($three eq 'st') {
 3987:                     if ($showcredits) { 
 3988:                         my $defaultcredits = 
 3989:                             &Apache::lonuserutils::get_defaultcredits($one,$two);
 3990:                         $credits = $env{'form.credits_'.$one.'_'.$two.'_'.$three};
 3991:                         $credits =~ s/[^\d\.]//g;
 3992:                         if ($credits eq $defaultcredits) {
 3993:                             undef($credits);
 3994:                         }
 3995:                     }
 3996:                 }
 3997:                 if ($num_sections == 0) {
 3998:                     $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$three,$start,$end,$one,$two,'',$context,$credits));
 3999:                 } else {
 4000:                     my %curr_groups = 
 4001: 			&Apache::longroup::coursegroups($one,$two);
 4002:                     my $emptysec = 0;
 4003:                     foreach my $sec (sort {$a cmp $b} keys(%sections)) {
 4004:                         $sec =~ s/\W//g;
 4005:                         if ($sec ne '') {
 4006:                             if (($sec eq 'none') || ($sec eq 'all') || 
 4007:                                 exists($curr_groups{$sec})) {
 4008:                                 $disallowed{$sec} = $url;
 4009:                                 next;
 4010:                             }
 4011:                             my $securl = $url.'/'.$sec;
 4012:                             $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$securl,$three,$start,$end,$one,$two,$sec,$context,$credits));
 4013:                         } else {
 4014:                             $emptysec = 1;
 4015:                         }
 4016:                     }
 4017:                     if ($emptysec) {
 4018:                         $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$three,$start,$end,$one,$two,'',$context,$credits));
 4019:                     }
 4020:                 }
 4021:                 if (!grep(/^\Q$three\E$/,@rolechanges)) {
 4022:                     push(@rolechanges,$three);
 4023:                 }
 4024: 	    } elsif ($key=~/^form\.act\_([^\_]+)\_([^\_]+)$/) {
 4025: 		# Activate roles for sections with two id numbers
 4026: 		# set start, end times, and the url for the class
 4027: 		my $start = ( $env{'form.start_'.$1.'_'.$2} ? 
 4028: 			      $env{'form.start_'.$1.'_'.$2} : 
 4029: 			      $now );
 4030: 		my $end   = ( $env{'form.end_'.$1.'_'.$2} ? 
 4031: 			      $env{'form.end_'.$1.'_'.$2} :
 4032: 			      0 );
 4033:                 my $one = $1;
 4034:                 my $two = $2;
 4035: 		my $url='/'.$one.'/';
 4036:                 # split multiple sections
 4037:                 my %sections = ();
 4038:                 my $num_sections = &build_roles($env{'form.sec_'.$one.'_'.$two},\%sections,$two);
 4039:                 if ($num_sections == 0) {
 4040:                     $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$two,$start,$end,$one,undef,'',$context));
 4041:                 } else {
 4042:                     my $emptysec = 0;
 4043:                     foreach my $sec (sort {$a cmp $b} keys(%sections)) {
 4044:                         if ($sec ne '') {
 4045:                             my $securl = $url.'/'.$sec;
 4046:                             $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$securl,$two,$start,$end,$one,undef,$sec,$context));
 4047:                         } else {
 4048:                             $emptysec = 1;
 4049:                         }
 4050:                     }
 4051:                     if ($emptysec) {
 4052:                         $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$two,$start,$end,$one,undef,'',$context));
 4053:                     }
 4054:                 }
 4055:                 if (!grep(/^\Q$two\E$/,@rolechanges)) {
 4056:                     push(@rolechanges,$two);
 4057:                 }
 4058: 	    } else {
 4059: 		$r->print('<p><span class="LC_error">'.&mt('ERROR').': '.&mt('Unknown command').' <tt>'.$key.'</tt></span></p><br />');
 4060:             }
 4061:             foreach my $key (sort(keys(%disallowed))) {
 4062:                 $r->print('<p class="LC_warning">');
 4063:                 if (($key eq 'none') || ($key eq 'all')) {  
 4064:                     $r->print(&mt('[_1] may not be used as the name for a section, as it is a reserved word.','<tt>'.$key.'</tt>'));
 4065:                 } else {
 4066:                     $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>'));
 4067:                 }
 4068:                 $r->print('</p><p>'
 4069:                          .&mt('Please [_1]go back[_2] and choose a different section name.'
 4070:                              ,'<a href="javascript:history.go(-1)'
 4071:                              ,'</a>')
 4072:                          .'</p><br />'
 4073:                 );
 4074:             }
 4075: 	}
 4076:     } # End of foreach (keys(%env))
 4077: # Flush the course logs so reverse user roles immediately updated
 4078:     $r->register_cleanup(\&Apache::lonnet::flushcourselogs);
 4079:     if (@rolechanges == 0) {
 4080:         $r->print('<p>'.&mt('No roles to modify').'</p>');
 4081:     }
 4082:     return @rolechanges;
 4083: }
 4084: 
 4085: sub get_user_credits {
 4086:     my ($uname,$udom,$defaultcredits,$cdom,$cnum) = @_;
 4087:     if ($cdom eq '' || $cnum eq '') {
 4088:         return unless ($env{'request.course.id'});
 4089:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4090:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4091:     }
 4092:     my $credits;
 4093:     my %currhash =
 4094:         &Apache::lonnet::get('classlist',[$uname.':'.$udom],$cdom,$cnum);
 4095:     if (keys(%currhash) > 0) {
 4096:         my @items = split(/:/,$currhash{$uname.':'.$udom});
 4097:         my $crdidx = &Apache::loncoursedata::CL_CREDITS() - 3;
 4098:         $credits = $items[$crdidx];
 4099:         $credits =~ s/[^\d\.]//g;
 4100:     }
 4101:     if ($credits eq $defaultcredits) {
 4102:         undef($credits);
 4103:     }
 4104:     return $credits;
 4105: }
 4106: 
 4107: sub enroll_single_student {
 4108:     my ($r,$uhome,$amode,$genpwd,$now,$newuser,$context,$crstype,
 4109:         $showcredits,$defaultcredits) = @_;
 4110:     $r->print('<h3>');
 4111:     if ($crstype eq 'Community') {
 4112:         $r->print(&mt('Enrolling Member'));
 4113:     } else {
 4114:         $r->print(&mt('Enrolling Student'));
 4115:     }
 4116:     $r->print('</h3>');
 4117: 
 4118:     # Remove non alphanumeric values from section
 4119:     $env{'form.sections'}=~s/\W//g;
 4120: 
 4121:     my $credits;
 4122:     if (($showcredits) && ($env{'form.credits'} ne '')) {
 4123:         $credits = $env{'form.credits'};
 4124:         $credits =~ s/[^\d\.]//g;
 4125:         if ($credits ne '') {
 4126:             if ($credits eq $defaultcredits) {
 4127:                 undef($credits);
 4128:             }
 4129:         }
 4130:     }
 4131: 
 4132:     # Clean out any old student roles the user has in this class.
 4133:     &Apache::lonuserutils::modifystudent($env{'form.ccdomain'},
 4134:          $env{'form.ccuname'},$env{'request.course.id'},undef,$uhome);
 4135:     my ($startdate,$enddate) = &Apache::lonuserutils::get_dates_from_form();
 4136:     my $enroll_result =
 4137:         &Apache::lonnet::modify_student_enrollment($env{'form.ccdomain'},
 4138:             $env{'form.ccuname'},$env{'form.cid'},$env{'form.cfirstname'},
 4139:             $env{'form.cmiddlename'},$env{'form.clastname'},
 4140:             $env{'form.generation'},$env{'form.sections'},$enddate,
 4141:             $startdate,'manual',undef,$env{'request.course.id'},'',$context,
 4142:             $credits);
 4143:     if ($enroll_result =~ /^ok/) {
 4144:         $r->print(&mt('[_1] enrolled','<b>'.$env{'form.ccuname'}.':'.$env{'form.ccdomain'}.'</b>'));
 4145:         if ($env{'form.sections'} ne '') {
 4146:             $r->print(' '.&mt('in section [_1]',$env{'form.sections'}));
 4147:         }
 4148:         my ($showstart,$showend);
 4149:         if ($startdate <= $now) {
 4150:             $showstart = &mt('Access starts immediately');
 4151:         } else {
 4152:             $showstart = &mt('Access starts: ').&Apache::lonlocal::locallocaltime($startdate);
 4153:         }
 4154:         if ($enddate == 0) {
 4155:             $showend = &mt('ends: no ending date');
 4156:         } else {
 4157:             $showend = &mt('ends: ').&Apache::lonlocal::locallocaltime($enddate);
 4158:         }
 4159:         $r->print('.<br />'.$showstart.'; '.$showend);
 4160:         if ($startdate <= $now && !$newuser) {
 4161:             $r->print('<p class="LC_info">');
 4162:             if ($crstype eq 'Community') {
 4163:                 $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.'));
 4164:             } else {
 4165:                 $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.'));
 4166:            }
 4167:            $r->print('</p>');
 4168:         }
 4169:     } else {
 4170:         $r->print(&mt('unable to enroll').": ".$enroll_result);
 4171:     }
 4172:     return;
 4173: }
 4174: 
 4175: sub get_defaultquota_text {
 4176:     my ($settingstatus) = @_;
 4177:     my $defquotatext; 
 4178:     if ($settingstatus eq '') {
 4179:         $defquotatext = &mt('default');
 4180:     } else {
 4181:         my ($usertypes,$order) =
 4182:             &Apache::lonnet::retrieve_inst_usertypes($env{'form.ccdomain'});
 4183:         if ($usertypes->{$settingstatus} eq '') {
 4184:             $defquotatext = &mt('default');
 4185:         } else {
 4186:             $defquotatext = &mt('default for [_1]',$usertypes->{$settingstatus});
 4187:         }
 4188:     }
 4189:     return $defquotatext;
 4190: }
 4191: 
 4192: sub update_result_form {
 4193:     my ($uhome) = @_;
 4194:     my $outcome = 
 4195:     '<form name="userupdate" method="post" action="">'."\n";
 4196:     foreach my $item ('srchby','srchin','srchtype','srchterm','srchdomain','ccuname','ccdomain') {
 4197:         $outcome .= '<input type="hidden" name="'.$item.'" value="'.$env{'form.'.$item}.'" />'."\n";
 4198:     }
 4199:     if ($env{'form.origname'} ne '') {
 4200:         $outcome .= '<input type="hidden" name="origname" value="'.$env{'form.origname'}.'" />'."\n";
 4201:     }
 4202:     foreach my $item ('sortby','seluname','seludom') {
 4203:         if (exists($env{'form.'.$item})) {
 4204:             $outcome .= '<input type="hidden" name="'.$item.'" value="'.$env{'form.'.$item}.'" />'."\n";
 4205:         }
 4206:     }
 4207:     if ($uhome eq 'no_host') {
 4208:         $outcome .= '<input type="hidden" name="forcenewuser" value="1" />'."\n";
 4209:     }
 4210:     $outcome .= '<input type="hidden" name="phase" value="" />'."\n".
 4211:                 '<input type="hidden" name="currstate" value="" />'."\n".
 4212:                 '<input type="hidden" name="action" value="'.$env{'form.action'}.'" />'."\n".
 4213:                 '</form>';
 4214:     return $outcome;
 4215: }
 4216: 
 4217: sub quota_admin {
 4218:     my ($setquota,$changeHash,$name) = @_;
 4219:     my $quotachanged;
 4220:     if (&Apache::lonnet::allowed('mpq',$env{'form.ccdomain'})) {
 4221:         # Current user has quota modification privileges
 4222:         if (ref($changeHash) eq 'HASH') {
 4223:             $quotachanged = 1;
 4224:             $changeHash->{$name.'quota'} = $setquota;
 4225:         }
 4226:     }
 4227:     return $quotachanged;
 4228: }
 4229: 
 4230: sub tool_admin {
 4231:     my ($tool,$settool,$changeHash,$context) = @_;
 4232:     my $canchange = 0; 
 4233:     if ($context eq 'requestcourses') {
 4234:         if (&Apache::lonnet::allowed('ccc',$env{'form.ccdomain'})) {
 4235:             $canchange = 1;
 4236:         }
 4237:     } elsif ($context eq 'reqcrsotherdom') {
 4238:         if (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) {
 4239:             $canchange = 1;
 4240:         }
 4241:     } elsif ($context eq 'requestauthor') {
 4242:         if (&Apache::lonnet::allowed('cau',$env{'request.role.domain'})) {
 4243:             $canchange = 1;
 4244:         }
 4245:     } elsif (&Apache::lonnet::allowed('mut',$env{'form.ccdomain'})) {
 4246:         # Current user has quota modification privileges
 4247:         $canchange = 1;
 4248:     }
 4249:     my $toolchanged;
 4250:     if ($canchange) {
 4251:         if (ref($changeHash) eq 'HASH') {
 4252:             $toolchanged = 1;
 4253:             if ($tool eq 'requestauthor') {
 4254:                 $changeHash->{$context} = $settool;
 4255:             } else {
 4256:                 $changeHash->{$context.'.'.$tool} = $settool;
 4257:             }
 4258:         }
 4259:     }
 4260:     return $toolchanged;
 4261: }
 4262: 
 4263: sub build_roles {
 4264:     my ($sectionstr,$sections,$role) = @_;
 4265:     my $num_sections = 0;
 4266:     if ($sectionstr=~ /,/) {
 4267:         my @secnums = split/,/,$sectionstr;
 4268:         if ($role eq 'st') {
 4269:             $secnums[0] =~ s/\W//g;
 4270:             $$sections{$secnums[0]} = 1;
 4271:             $num_sections = 1;
 4272:         } else {
 4273:             foreach my $sec (@secnums) {
 4274:                 $sec =~ ~s/\W//g;
 4275:                 if (!($sec eq "")) {
 4276:                     if (exists($$sections{$sec})) {
 4277:                         $$sections{$sec} ++;
 4278:                     } else {
 4279:                         $$sections{$sec} = 1;
 4280:                         $num_sections ++;
 4281:                     }
 4282:                 }
 4283:             }
 4284:         }
 4285:     } else {
 4286:         $sectionstr=~s/\W//g;
 4287:         unless ($sectionstr eq '') {
 4288:             $$sections{$sectionstr} = 1;
 4289:             $num_sections ++;
 4290:         }
 4291:     }
 4292: 
 4293:     return $num_sections;
 4294: }
 4295: 
 4296: # ========================================================== Custom Role Editor
 4297: 
 4298: sub custom_role_editor {
 4299:     my ($r,$brcrum,$prefix) = @_;
 4300:     my $action = $env{'form.customroleaction'};
 4301:     my $rolename; 
 4302:     if ($action eq 'new') {
 4303:         $rolename=$env{'form.newrolename'};
 4304:     } else {
 4305:         $rolename=$env{'form.rolename'};
 4306:     }
 4307: 
 4308:     my ($crstype,$context);
 4309:     if ($env{'request.course.id'}) {
 4310:         $crstype = &Apache::loncommon::course_type();
 4311:         $context = 'course';
 4312:     } else {
 4313:         $context = 'domain';
 4314:         $crstype = 'course';
 4315:     }
 4316: 
 4317:     $rolename=~s/[^A-Za-z0-9]//gs;
 4318:     if (!$rolename || $env{'form.phase'} eq 'pickrole') {
 4319: 	&print_username_entry_form($r,undef,undef,undef,undef,$crstype,$brcrum);
 4320:         return;
 4321:     }
 4322: 
 4323:     my $formname = 'form1';
 4324:     my %privs=();
 4325:     my $body_top = '<h2>';
 4326: # ------------------------------------------------------- Does this role exist?
 4327:     my ($rdummy,$roledef)=
 4328: 			 &Apache::lonnet::get('roles',["rolesdef_$rolename"]);
 4329:     if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 4330:         $body_top .= &mt('Existing Role').' "';
 4331: # ------------------------------------------------- Get current role privileges
 4332:         ($privs{'system'},$privs{'domain'},$privs{'course'})=split(/\_/,$roledef);
 4333:         if ($privs{'system'} =~ /bre\&S/) {
 4334:             if ($context eq 'domain') {
 4335:                 $crstype = 'Course';
 4336:             } elsif ($crstype eq 'Community') {
 4337:                 $privs{'system'} =~ s/bre\&S//;
 4338:             }
 4339:         } elsif ($context eq 'domain') {
 4340:             $crstype = 'Course';
 4341:         }
 4342:     } else {
 4343:         $body_top .= &mt('New Role').' "';
 4344:         $roledef='';
 4345:     }
 4346:     $body_top .= $rolename.'"</h2>';
 4347: 
 4348: # ------------------------------------------------------- What can be assigned?
 4349:     my %full=();
 4350:     my %levels=(
 4351:                  course => {},
 4352:                  domain => {},
 4353:                  system => {},
 4354:                );
 4355:     my %levelscurrent=(
 4356:                         course => {},
 4357:                         domain => {},
 4358:                         system => {},
 4359:                       );
 4360:     &Apache::lonuserutils::custom_role_privs(\%privs,\%full,\%levels,\%levelscurrent);
 4361:     my ($jsback,$elements) = &crumb_utilities();
 4362:     my @templateroles = &Apache::lonuserutils::custom_template_roles($context,$crstype);
 4363:     my $head_script =
 4364:         &Apache::lonuserutils::custom_roledefs_js($context,$crstype,$formname,
 4365:                                                   \%full,\@templateroles,$jsback);
 4366:     push (@{$brcrum},
 4367:               {href => "javascript:backPage(document.$formname,'pickrole','')",
 4368:                text => "Pick custom role",
 4369:                faq  => 282,bug=>'Instructor Interface',},
 4370:               {href => "javascript:backPage(document.$formname,'','')",
 4371:                text => "Edit custom role",
 4372:                faq  => 282,
 4373:                bug  => 'Instructor Interface',
 4374:                help => 'Course_Editing_Custom_Roles'}
 4375:               );
 4376:     my $args = { bread_crumbs          => $brcrum,
 4377:                  bread_crumbs_component => 'User Management'};
 4378:     $r->print(&Apache::loncommon::start_page('Custom Role Editor',
 4379:                                              $head_script,$args).
 4380:               $body_top);
 4381:     $r->print('<form name="'.$formname.'" method="post" action="">'."\n".
 4382:               &Apache::lonuserutils::custom_role_header($context,$crstype,
 4383:                                                         \@templateroles,$prefix));
 4384: 
 4385:     $r->print(<<ENDCCF);
 4386: <input type="hidden" name="phase" value="set_custom_roles" />
 4387: <input type="hidden" name="rolename" value="$rolename" />
 4388: ENDCCF
 4389:     $r->print(&Apache::lonuserutils::custom_role_table($crstype,\%full,\%levels,
 4390:                                                        \%levelscurrent,$prefix));
 4391:     $r->print(&Apache::loncommon::end_data_table().
 4392:    '<input type="hidden" name="action" value="'.$env{'form.action'}.'" />'.
 4393:    '<input type="hidden" name="startrolename" value="'.$env{'form.rolename'}.
 4394:    '" />'."\n".'<input type="hidden" name="currstate" value="" />'."\n".
 4395:    '<input type="reset" value="'.&mt("Reset").'" />'."\n".
 4396:    '<input type="submit" value="'.&mt('Save').'" /></form>');
 4397: }
 4398: 
 4399: # ---------------------------------------------------------- Call to definerole
 4400: sub set_custom_role {
 4401:     my ($r,$context,$brcrum,$prefix) = @_;
 4402:     my $rolename=$env{'form.rolename'};
 4403:     $rolename=~s/[^A-Za-z0-9]//gs;
 4404:     if (!$rolename) {
 4405: 	&custom_role_editor($r,$brcrum,$prefix);
 4406:         return;
 4407:     }
 4408:     my ($jsback,$elements) = &crumb_utilities();
 4409:     my $jscript = '<script type="text/javascript">'
 4410:                  .'// <![CDATA['."\n"
 4411:                  .$jsback."\n"
 4412:                  .'// ]]>'."\n"
 4413:                  .'</script>'."\n";
 4414:     push(@{$brcrum},
 4415:         {href => "javascript:backPage(document.customresult,'pickrole','')",
 4416:          text => "Pick custom role",
 4417:          faq  => 282,
 4418:          bug  => 'Instructor Interface',},
 4419:         {href => "javascript:backPage(document.customresult,'selected_custom_edit','')",
 4420:          text => "Edit custom role",
 4421:          faq  => 282,
 4422:          bug  => 'Instructor Interface',},
 4423:         {href => "javascript:backPage(document.customresult,'set_custom_roles','')",
 4424:          text => "Result",
 4425:          faq  => 282,
 4426:          bug  => 'Instructor Interface',
 4427:          help => 'Course_Editing_Custom_Roles'},
 4428:         );
 4429:     my $args = { bread_crumbs           => $brcrum,
 4430:                  bread_crumbs_component => 'User Management'};
 4431:     $r->print(&Apache::loncommon::start_page('Save Custom Role',$jscript,$args));
 4432: 
 4433:     my $newrole;
 4434:     my ($rdummy,$roledef)=
 4435: 	&Apache::lonnet::get('roles',["rolesdef_$rolename"]);
 4436: 
 4437: # ------------------------------------------------------- Does this role exist?
 4438:     $r->print('<h3>');
 4439:     if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 4440: 	$r->print(&mt('Existing Role').' "');
 4441:     } else {
 4442: 	$r->print(&mt('New Role').' "');
 4443: 	$roledef='';
 4444:         $newrole = 1;
 4445:     }
 4446:     $r->print($rolename.'"</h3>');
 4447: # ------------------------------------------------- Assign role and show result
 4448: 
 4449:     my $errmsg;
 4450:     my %newprivs = &Apache::lonuserutils::custom_role_update($rolename,$prefix);
 4451:     # Assign role and return result
 4452:     my $result = &Apache::lonnet::definerole($rolename,$newprivs{'s'},$newprivs{'d'},
 4453:                                              $newprivs{'c'});
 4454:     if ($result ne 'ok') {
 4455:         $errmsg = ': '.$result;
 4456:     }
 4457:     my $message =
 4458:         &Apache::lonhtmlcommon::confirm_success(
 4459:             &mt('Defining Role').$errmsg, ($result eq 'ok' ? 0 : 1));
 4460:     if ($env{'request.course.id'}) {
 4461:         my $url='/'.$env{'request.course.id'};
 4462:         $url=~s/\_/\//g;
 4463:         $result =
 4464:             &Apache::lonnet::assigncustomrole(
 4465:                 $env{'user.domain'},$env{'user.name'},
 4466:                 $url,
 4467:                 $env{'user.domain'},$env{'user.name'},
 4468:                 $rolename,undef,undef,undef,$context);
 4469:         if ($result ne 'ok') {
 4470:             $errmsg = ': '.$result;
 4471:         }
 4472:         $message .=
 4473:             '<br />'
 4474:            .&Apache::lonhtmlcommon::confirm_success(
 4475:                 &mt('Assigning Role to Self').$errmsg, ($result eq 'ok' ? 0 : 1));
 4476:     }
 4477:     $r->print(
 4478:         &Apache::loncommon::confirmwrapper($message)
 4479:        .'<br />'
 4480:        .&Apache::lonhtmlcommon::actionbox([
 4481:             '<a href="javascript:backPage(document.customresult,'."'pickrole'".')">'
 4482:            .&mt('Create or edit another custom role')
 4483:            .'</a>'])
 4484:        .'<form name="customresult" method="post" action="">'
 4485:        .&Apache::lonhtmlcommon::echo_form_input([])
 4486:        .'</form>'
 4487:     );
 4488: }
 4489: 
 4490: # ================================================================ Main Handler
 4491: sub handler {
 4492:     my $r = shift;
 4493:     if ($r->header_only) {
 4494:        &Apache::loncommon::content_type($r,'text/html');
 4495:        $r->send_http_header;
 4496:        return OK;
 4497:     }
 4498:     my ($context,$crstype);
 4499:     if ($env{'request.course.id'}) {
 4500:         $context = 'course';
 4501:         $crstype = &Apache::loncommon::course_type();
 4502:     } elsif ($env{'request.role'} =~ /^au\./) {
 4503:         $context = 'author';
 4504:     } else {
 4505:         $context = 'domain';
 4506:     }
 4507: 
 4508:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 4509:         ['action','state','callingform','roletype','showrole','bulkaction','popup','phase',
 4510:          'username','domain','srchterm','srchdomain','srchin','srchby','srchtype','queue']);
 4511:     &Apache::lonhtmlcommon::clear_breadcrumbs();
 4512:     my $args;
 4513:     my $brcrum = [];
 4514:     my $bread_crumbs_component = 'User Management';
 4515:     if (($env{'form.action'} ne 'dateselect') && ($env{'form.action'} ne 'displayuserreq')) {
 4516:         $brcrum = [{href=>"/adm/createuser",
 4517:                     text=>"User Management",
 4518:                     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'}
 4519:                   ];
 4520:     }
 4521:     #SD Following files not added to help, because the corresponding .tex-files seem to
 4522:     #be missing: Course_Approve_Selfenroll,Course_User_Logs,
 4523:     my ($permission,$allowed) = 
 4524:         &Apache::lonuserutils::get_permission($context,$crstype);
 4525:     if (!$allowed) {
 4526:         if ($context eq 'course') {
 4527:             $r->internal_redirect('/adm/viewclasslist');
 4528:             return OK;
 4529:         }
 4530:         $env{'user.error.msg'}=
 4531:             "/adm/createuser:cst:0:0:Cannot create/modify user data ".
 4532:                                  "or view user status.";
 4533:         return HTTP_NOT_ACCEPTABLE;
 4534:     }
 4535: 
 4536:     &Apache::loncommon::content_type($r,'text/html');
 4537:     $r->send_http_header;
 4538: 
 4539:     my $showcredits;
 4540:     if ((($context eq 'course') && ($crstype eq 'Course')) || 
 4541:          ($context eq 'domain')) {
 4542:         my %domdefaults = 
 4543:             &Apache::lonnet::get_domain_defaults($env{'request.role.domain'});
 4544:         if ($domdefaults{'officialcredits'} || $domdefaults{'unofficialcredits'}) {
 4545:             $showcredits = 1;
 4546:         }
 4547:     }
 4548: 
 4549:     # Main switch on form.action and form.state, as appropriate
 4550:     if (! exists($env{'form.action'})) {
 4551:         $args = {bread_crumbs => $brcrum,
 4552:                  bread_crumbs_component => $bread_crumbs_component}; 
 4553:         $r->print(&header(undef,$args));
 4554:         $r->print(&print_main_menu($permission,$context,$crstype));
 4555:     } elsif ($env{'form.action'} eq 'upload' && $permission->{'cusr'}) {
 4556:         push(@{$brcrum},
 4557:               { href => '/adm/createuser?action=upload&state=',
 4558:                 text => 'Upload Users List',
 4559:                 help => 'Course_Create_Class_List',
 4560:               });
 4561:         $bread_crumbs_component = 'Upload Users List';
 4562:         $args = {bread_crumbs           => $brcrum,
 4563:                  bread_crumbs_component => $bread_crumbs_component};
 4564:         $r->print(&header(undef,$args));
 4565:         $r->print('<form name="studentform" method="post" '.
 4566:                   'enctype="multipart/form-data" '.
 4567:                   ' action="/adm/createuser">'."\n");
 4568:         if (! exists($env{'form.state'})) {
 4569:             &Apache::lonuserutils::print_first_users_upload_form($r,$context);
 4570:         } elsif ($env{'form.state'} eq 'got_file') {
 4571:             &Apache::lonuserutils::print_upload_manager_form($r,$context,$permission,
 4572:                                                              $crstype,$showcredits);
 4573:         } elsif ($env{'form.state'} eq 'enrolling') {
 4574:             if ($env{'form.datatoken'}) {
 4575:                 &Apache::lonuserutils::upfile_drop_add($r,$context,$permission,
 4576:                                                        $showcredits);
 4577:             }
 4578:         } else {
 4579:             &Apache::lonuserutils::print_first_users_upload_form($r,$context);
 4580:         }
 4581:     } elsif (((($env{'form.action'} eq 'singleuser') || ($env{'form.action'}
 4582:               eq 'singlestudent')) && ($permission->{'cusr'})) ||
 4583:              (($env{'form.action'} eq 'singleuser') && ($permission->{'view'})) ||
 4584:              (($env{'form.action'} eq 'accesslogs') && ($permission->{'activity'}))) {
 4585:         my $phase = $env{'form.phase'};
 4586:         my @search = ('srchterm','srchby','srchin','srchtype','srchdomain');
 4587: 	&Apache::loncreateuser::restore_prev_selections();
 4588: 	my $srch;
 4589: 	foreach my $item (@search) {
 4590: 	    $srch->{$item} = $env{'form.'.$item};
 4591: 	}
 4592:         if (($phase eq 'get_user_info') || ($phase eq 'userpicked') ||
 4593:             ($phase eq 'createnewuser') || ($phase eq 'activity')) {
 4594:             if ($env{'form.phase'} eq 'createnewuser') {
 4595:                 my $response;
 4596:                 if ($env{'form.srchterm'} !~ /^$match_username$/) {
 4597:                     my $response =
 4598:                         '<span class="LC_warning">'
 4599:                        .&mt('You must specify a valid username. Only the following are allowed:'
 4600:                            .' letters numbers - . @')
 4601:                        .'</span>';
 4602:                     $env{'form.phase'} = '';
 4603:                     &print_username_entry_form($r,$context,$response,$srch,undef,
 4604:                                                $crstype,$brcrum,$showcredits);
 4605:                 } else {
 4606:                     my $ccuname =&LONCAPA::clean_username($srch->{'srchterm'});
 4607:                     my $ccdomain=&LONCAPA::clean_domain($srch->{'srchdomain'});
 4608:                     &print_user_modification_page($r,$ccuname,$ccdomain,
 4609:                                                   $srch,$response,$context,
 4610:                                                   $permission,$crstype,$brcrum,
 4611:                                                   $showcredits);
 4612:                 }
 4613:             } elsif ($env{'form.phase'} eq 'get_user_info') {
 4614:                 my ($currstate,$response,$forcenewuser,$results) = 
 4615:                     &user_search_result($context,$srch);
 4616:                 if ($env{'form.currstate'} eq 'modify') {
 4617:                     $currstate = $env{'form.currstate'};
 4618:                 }
 4619:                 if ($currstate eq 'select') {
 4620:                     &print_user_selection_page($r,$response,$srch,$results,
 4621:                                                \@search,$context,undef,$crstype,
 4622:                                                $brcrum);
 4623:                 } elsif (($currstate eq 'modify') || ($env{'form.action'} eq 'accesslogs')) {
 4624:                     my ($ccuname,$ccdomain,$uhome);
 4625:                     if (($srch->{'srchby'} eq 'uname') && 
 4626:                         ($srch->{'srchtype'} eq 'exact')) {
 4627:                         $ccuname = $srch->{'srchterm'};
 4628:                         $ccdomain= $srch->{'srchdomain'};
 4629:                     } else {
 4630:                         my @matchedunames = keys(%{$results});
 4631:                         ($ccuname,$ccdomain) = split(/:/,$matchedunames[0]);
 4632:                     }
 4633:                     $ccuname =&LONCAPA::clean_username($ccuname);
 4634:                     $ccdomain=&LONCAPA::clean_domain($ccdomain);
 4635:                     if ($env{'form.action'} eq 'accesslogs') {
 4636:                         my $uhome;
 4637:                         if (($ccuname ne '') && ($ccdomain ne '')) {
 4638:                            $uhome = &Apache::lonnet::homeserver($ccuname,$ccdomain);
 4639:                         }
 4640:                         if (($uhome eq '') || ($uhome eq 'no_host')) {
 4641:                             $env{'form.phase'} = '';
 4642:                             undef($forcenewuser);
 4643:                             #if ($response) {
 4644:                             #    unless ($response =~ m{\Q<br /><br />\E$}) {
 4645:                             #        $response .= '<br /><br />';
 4646:                             #    }
 4647:                             #}
 4648:                             &print_username_entry_form($r,$context,$response,$srch,
 4649:                                                        $forcenewuser,$crstype,$brcrum);
 4650:                         } else {
 4651:                             &print_useraccesslogs_display($r,$ccuname,$ccdomain,$permission,$brcrum);
 4652:                         }
 4653:                     } else {
 4654:                         if ($env{'form.forcenewuser'}) {
 4655:                             $response = '';
 4656:                         }
 4657:                         &print_user_modification_page($r,$ccuname,$ccdomain,
 4658:                                                       $srch,$response,$context,
 4659:                                                       $permission,$crstype,$brcrum);
 4660:                     }
 4661:                 } elsif ($currstate eq 'query') {
 4662:                     &print_user_query_page($r,'createuser',$brcrum);
 4663:                 } else {
 4664:                     $env{'form.phase'} = '';
 4665:                     &print_username_entry_form($r,$context,$response,$srch,
 4666:                                                $forcenewuser,$crstype,$brcrum);
 4667:                 }
 4668:             } elsif ($env{'form.phase'} eq 'userpicked') {
 4669:                 my $ccuname = &LONCAPA::clean_username($env{'form.seluname'});
 4670:                 my $ccdomain = &LONCAPA::clean_domain($env{'form.seludom'});
 4671:                 if ($env{'form.action'} eq 'accesslogs') {
 4672:                     &print_useraccesslogs_display($r,$ccuname,$ccdomain,$permission,$brcrum);
 4673:                 } else {
 4674:                     &print_user_modification_page($r,$ccuname,$ccdomain,$srch,'',
 4675:                                                   $context,$permission,$crstype,
 4676:                                                   $brcrum);
 4677:                 }
 4678:             } elsif ($env{'form.action'} eq 'accesslogs') {
 4679:                 my $ccuname = &LONCAPA::clean_username($env{'form.accessuname'});
 4680:                 my $ccdomain = &LONCAPA::clean_domain($env{'form.accessudom'});
 4681:                 &print_useraccesslogs_display($r,$ccuname,$ccdomain,$permission,$brcrum);
 4682:             }
 4683:         } elsif ($env{'form.phase'} eq 'update_user_data') {
 4684:             &update_user_data($r,$context,$crstype,$brcrum,$showcredits);
 4685:         } else {
 4686:             &print_username_entry_form($r,$context,undef,$srch,undef,$crstype,
 4687:                                        $brcrum);
 4688:         }
 4689:     } elsif ($env{'form.action'} eq 'custom' && $permission->{'custom'}) {
 4690:         my $prefix;
 4691:         if ($env{'form.phase'} eq 'set_custom_roles') {
 4692:             &set_custom_role($r,$context,$brcrum,$prefix);
 4693:         } else {
 4694:             &custom_role_editor($r,$brcrum,$prefix);
 4695:         }
 4696:     } elsif (($env{'form.action'} eq 'processauthorreq') &&
 4697:              ($permission->{'cusr'}) && 
 4698:              (&Apache::lonnet::allowed('cau',$env{'request.role.domain'}))) {
 4699:         push(@{$brcrum},
 4700:                  {href => '/adm/createuser?action=processauthorreq',
 4701:                   text => 'Authoring Space requests',
 4702:                   help => 'Domain_Role_Approvals'});
 4703:         $bread_crumbs_component = 'Authoring requests';
 4704:         if ($env{'form.state'} eq 'done') {
 4705:             push(@{$brcrum},
 4706:                      {href => '/adm/createuser?action=authorreqqueue',
 4707:                       text => 'Result',
 4708:                       help => 'Domain_Role_Approvals'});
 4709:             $bread_crumbs_component = 'Authoring request result';
 4710:         }
 4711:         $args = { bread_crumbs           => $brcrum,
 4712:                   bread_crumbs_component => $bread_crumbs_component};
 4713:         my $js = &usernamerequest_javascript();
 4714:         $r->print(&header(&add_script($js),$args));
 4715:         if (!exists($env{'form.state'})) {
 4716:             $r->print(&Apache::loncoursequeueadmin::display_queued_requests('requestauthor',
 4717:                                                                             $env{'request.role.domain'}));
 4718:         } elsif ($env{'form.state'} eq 'done') {
 4719:             $r->print('<h3>'.&mt('Authoring request processing').'</h3>'."\n");
 4720:             $r->print(&Apache::loncoursequeueadmin::update_request_queue('requestauthor',
 4721:                                                                          $env{'request.role.domain'}));
 4722:         }
 4723:     } elsif (($env{'form.action'} eq 'processusernamereq') &&
 4724:              ($permission->{'cusr'}) &&
 4725:              (&Apache::lonnet::allowed('cau',$env{'request.role.domain'}))) {
 4726:         push(@{$brcrum},
 4727:                  {href => '/adm/createuser?action=processusernamereq',
 4728:                   text => 'LON-CAPA account requests',
 4729:                   help => 'Domain_Username_Approvals'});
 4730:         $bread_crumbs_component = 'Account requests';
 4731:         if ($env{'form.state'} eq 'done') {
 4732:             push(@{$brcrum},
 4733:                      {href => '/adm/createuser?action=usernamereqqueue',
 4734:                       text => 'Result',
 4735:                       help => 'Domain_Username_Approvals'});
 4736:             $bread_crumbs_component = 'LON-CAPA account request result';
 4737:         }
 4738:         $args = { bread_crumbs           => $brcrum,
 4739:                   bread_crumbs_component => $bread_crumbs_component};
 4740:         my $js = &usernamerequest_javascript();
 4741:         $r->print(&header(&add_script($js),$args));
 4742:         if (!exists($env{'form.state'})) {
 4743:             $r->print(&Apache::loncoursequeueadmin::display_queued_requests('requestusername',
 4744:                                                                             $env{'request.role.domain'}));
 4745:         } elsif ($env{'form.state'} eq 'done') {
 4746:             $r->print('<h3>'.&mt('LON-CAPA account request processing').'</h3>'."\n");
 4747:             $r->print(&Apache::loncoursequeueadmin::update_request_queue('requestusername',
 4748:                                                                          $env{'request.role.domain'}));
 4749:         }
 4750:     } elsif (($env{'form.action'} eq 'displayuserreq') &&
 4751:              ($permission->{'cusr'})) {
 4752:         my $dom = $env{'form.domain'};
 4753:         my $uname = $env{'form.username'};
 4754:         my $warning;
 4755:         if (($dom =~ /^$match_domain$/) && (&Apache::lonnet::domain($dom) ne '')) {
 4756:             if (($dom eq $env{'request.role.domain'}) && (&Apache::lonnet::allowed('ccc',$dom))) {
 4757:                 if (($uname =~ /^$match_username$/) && ($env{'form.queue'} eq 'approval')) {
 4758:                     my $uhome = &Apache::lonnet::homeserver($uname,$dom);
 4759:                     if ($uhome eq 'no_host') {
 4760:                         my $queue = $env{'form.queue'};
 4761:                         my $reqkey = &escape($uname).'_'.$queue; 
 4762:                         my $namespace = 'usernamequeue';
 4763:                         my $domconfig = &Apache::lonnet::get_domainconfiguser($dom);
 4764:                         my %queued =
 4765:                             &Apache::lonnet::get($namespace,[$reqkey],$dom,$domconfig);
 4766:                         unless ($queued{$reqkey}) {
 4767:                             $warning = &mt('No information was found for this LON-CAPA account request.');
 4768:                         }
 4769:                     } else {
 4770:                         $warning = &mt('A LON-CAPA account already exists for the requested username and domain.');
 4771:                     }
 4772:                 } else {
 4773:                     $warning = &mt('LON-CAPA account request status check is for an invalid username.');
 4774:                 }
 4775:             } else {
 4776:                 $warning = &mt('You do not have rights to view LON-CAPA account requests in the domain specified.');
 4777:             }
 4778:         } else {
 4779:             $warning = &mt('LON-CAPA account request status check is for an invalid domain.');
 4780:         }
 4781:         my $args = { only_body => 1 };
 4782:         $r->print(&header(undef,$args).
 4783:                   '<h3>'.&mt('LON-CAPA Account Request Details').'</h3>');
 4784:         if ($warning ne '') {
 4785:             $r->print('<div class="LC_warning">'.$warning.'</div>');
 4786:         } else {
 4787:             my ($infofields,$infotitles) = &Apache::loncommon::emailusername_info();
 4788:             my $domconfiguser = &Apache::lonnet::get_domainconfiguser($dom);
 4789:             my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 4790:             if (ref($domconfig{'usercreation'}) eq 'HASH') {
 4791:                 if (ref($domconfig{'usercreation'}{'cancreate'}) eq 'HASH') {
 4792:                     if (ref($domconfig{'usercreation'}{'cancreate'}{'emailusername'}) eq 'HASH') {
 4793:                         my %info =
 4794:                             &Apache::lonnet::get('nohist_requestedusernames',[$uname],$dom,$domconfiguser);
 4795:                         if (ref($info{$uname}) eq 'HASH') {
 4796:                             my $usertype = $info{$uname}{'inststatus'};
 4797:                             unless ($usertype) {
 4798:                                 $usertype = 'default';
 4799:                             }
 4800:                             if (ref($domconfig{'usercreation'}{'cancreate'}{'emailusername'}{$usertype}) eq 'HASH') {
 4801:                                 if ((ref($infofields) eq 'ARRAY') && (ref($infotitles) eq 'HASH')) {
 4802:                                     $r->print('<div>'.&Apache::lonhtmlcommon::start_pick_box());
 4803:                                     my ($num,$count,$showstatus);
 4804:                                     $count = scalar(keys(%{$domconfig{'usercreation'}{'cancreate'}{'emailusername'}{$usertype}}));
 4805:                                     unless ($usertype eq 'default') {
 4806:                                         my ($othertitle,$usertypes,$types) = 
 4807:                                             &Apache::loncommon::sorted_inst_types($dom);
 4808:                                         if (ref($usertypes) eq 'HASH') {
 4809:                                             if ($usertypes->{$usertype}) {
 4810:                                                 $showstatus = $usertypes->{$usertype};
 4811:                                                 $count ++;
 4812:                                             }
 4813:                                         }
 4814:                                     }
 4815:                                     foreach my $field (@{$infofields}) {
 4816:                                         next unless ($domconfig{'usercreation'}{'cancreate'}{'emailusername'}{$usertype}{$field});
 4817:                                         next unless ($infotitles->{$field});
 4818:                                         $r->print(&Apache::lonhtmlcommon::row_title($infotitles->{$field}).
 4819:                                                   $info{$uname}{$field});
 4820:                                         $num ++;
 4821:                                         if ($count == $num) {
 4822:                                             $r->print(&Apache::lonhtmlcommon::row_closure(1));
 4823:                                         } else {
 4824:                                             $r->print(&Apache::lonhtmlcommon::row_closure());
 4825:                                         }
 4826:                                     }
 4827:                                     if ($showstatus) {
 4828:                                         $r->print(&Apache::lonhtmlcommon::row_title(&mt('Status type (self-reported)')).
 4829:                                                   $showstatus.
 4830:                                                   &Apache::lonhtmlcommon::row_closure(1));
 4831:                                     }
 4832:                                     $r->print(&Apache::lonhtmlcommon::end_pick_box().'</div>');
 4833:                                 }
 4834:                             }
 4835:                         }
 4836:                     }
 4837:                 }
 4838:             }
 4839:             $r->print(&close_popup_form());
 4840:         }
 4841:     } elsif (($env{'form.action'} eq 'listusers') && 
 4842:              ($permission->{'view'} || $permission->{'cusr'})) {
 4843:         if ($env{'form.phase'} eq 'bulkchange') {
 4844:             push(@{$brcrum},
 4845:                     {href => '/adm/createuser?action=listusers',
 4846:                      text => "List Users"},
 4847:                     {href => "/adm/createuser",
 4848:                      text => "Result",
 4849:                      help => 'Course_View_Class_List'});
 4850:             $bread_crumbs_component = 'Update Users';
 4851:             $args = {bread_crumbs           => $brcrum,
 4852:                      bread_crumbs_component => $bread_crumbs_component};
 4853:             $r->print(&header(undef,$args));
 4854:             my $setting = $env{'form.roletype'};
 4855:             my $choice = $env{'form.bulkaction'};
 4856:             if ($permission->{'cusr'}) {
 4857:                 &Apache::lonuserutils::update_user_list($r,$context,$setting,$choice,$crstype);
 4858:             } else {
 4859:                 $r->print(&mt('You are not authorized to make bulk changes to user roles'));
 4860:                 $r->print('<p><a href="/adm/createuser?action=listusers">'.&mt('Display User Lists').'</a>');
 4861:             }
 4862:         } else {
 4863:             push(@{$brcrum},
 4864:                     {href => '/adm/createuser?action=listusers',
 4865:                      text => "List Users",
 4866:                      help => 'Course_View_Class_List'});
 4867:             $bread_crumbs_component = 'List Users';
 4868:             $args = {bread_crumbs           => $brcrum,
 4869:                      bread_crumbs_component => $bread_crumbs_component};
 4870:             my ($cb_jscript,$jscript,$totcodes,$codetitles,$idlist,$idlist_titles);
 4871:             my $formname = 'studentform';
 4872:             my $hidecall = "hide_searching();";
 4873:             if (($context eq 'domain') && (($env{'form.roletype'} eq 'course') ||
 4874:                 ($env{'form.roletype'} eq 'community'))) {
 4875:                 if ($env{'form.roletype'} eq 'course') {
 4876:                     ($cb_jscript,$jscript,$totcodes,$codetitles,$idlist,$idlist_titles) = 
 4877:                         &Apache::lonuserutils::courses_selector($env{'request.role.domain'},
 4878:                                                                 $formname);
 4879:                 } elsif ($env{'form.roletype'} eq 'community') {
 4880:                     $cb_jscript = 
 4881:                         &Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'});
 4882:                     my %elements = (
 4883:                                       coursepick => 'radio',
 4884:                                       coursetotal => 'text',
 4885:                                       courselist => 'text',
 4886:                                    );
 4887:                     $jscript = &Apache::lonhtmlcommon::set_form_elements(\%elements);
 4888:                 }
 4889:                 $jscript .= &verify_user_display($context)."\n".
 4890:                             &Apache::loncommon::check_uncheck_jscript();
 4891:                 my $js = &add_script($jscript).$cb_jscript;
 4892:                 my $loadcode = 
 4893:                     &Apache::lonuserutils::course_selector_loadcode($formname);
 4894:                 if ($loadcode ne '') {
 4895:                     $args->{add_entries} = {onload => "$loadcode;$hidecall"};
 4896:                 } else {
 4897:                     $args->{add_entries} = {onload => $hidecall};
 4898:                 }
 4899:                 $r->print(&header($js,$args));
 4900:             } else {
 4901:                 $args->{add_entries} = {onload => $hidecall};
 4902:                 $jscript = &verify_user_display($context).
 4903:                            &Apache::loncommon::check_uncheck_jscript(); 
 4904:                 $r->print(&header(&add_script($jscript),$args));
 4905:             }
 4906:             &Apache::lonuserutils::print_userlist($r,undef,$permission,$context,
 4907:                          $formname,$totcodes,$codetitles,$idlist,$idlist_titles,
 4908:                          $showcredits);
 4909:         }
 4910:     } elsif ($env{'form.action'} eq 'drop' && $permission->{'cusr'}) {
 4911:         my $brtext;
 4912:         if ($crstype eq 'Community') {
 4913:             $brtext = 'Drop Members';
 4914:         } else {
 4915:             $brtext = 'Drop Students';
 4916:         }
 4917:         push(@{$brcrum},
 4918:                 {href => '/adm/createuser?action=drop',
 4919:                  text => $brtext,
 4920:                  help => 'Course_Drop_Student'});
 4921:         if ($env{'form.state'} eq 'done') {
 4922:             push(@{$brcrum},
 4923:                      {href=>'/adm/createuser?action=drop',
 4924:                       text=>"Result"});
 4925:         }
 4926:         $bread_crumbs_component = $brtext;
 4927:         $args = {bread_crumbs           => $brcrum,
 4928:                  bread_crumbs_component => $bread_crumbs_component}; 
 4929:         $r->print(&header(undef,$args));
 4930:         if (!exists($env{'form.state'})) {
 4931:             &Apache::lonuserutils::print_drop_menu($r,$context,$permission,$crstype);
 4932:         } elsif ($env{'form.state'} eq 'done') {
 4933:             &Apache::lonuserutils::update_user_list($r,$context,undef,
 4934:                                                     $env{'form.action'});
 4935:         }
 4936:     } elsif ($env{'form.action'} eq 'dateselect') {
 4937:         if ($permission->{'cusr'}) {
 4938:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 4939:                       &Apache::lonuserutils::date_section_selector($context,$permission,
 4940:                                                                    $crstype,$showcredits));
 4941:         } else {
 4942:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 4943:                      '<span class="LC_error">'.&mt('You do not have permission to modify dates or sections for users').'</span>'); 
 4944:         }
 4945:     } elsif ($env{'form.action'} eq 'selfenroll') {
 4946:         if ($permission->{selfenrolladmin}) {
 4947:             my $cid = $env{'request.course.id'};
 4948:             my $cdom = $env{'course.'.$cid.'.domain'};
 4949:             my $cnum = $env{'course.'.$cid.'.num'};
 4950:             my %currsettings = (
 4951:                 selfenroll_types              => $env{'course.'.$cid.'.internal.selfenroll_types'},
 4952:                 selfenroll_registered         => $env{'course.'.$cid.'.internal.selfenroll_registered'},
 4953:                 selfenroll_section            => $env{'course.'.$cid.'.internal.selfenroll_section'},
 4954:                 selfenroll_notifylist         => $env{'course.'.$cid.'.internal.selfenroll_notifylist'},
 4955:                 selfenroll_approval           => $env{'course.'.$cid.'.internal.selfenroll_approval'},
 4956:                 selfenroll_limit              => $env{'course.'.$cid.'.internal.selfenroll_limit'},
 4957:                 selfenroll_cap                => $env{'course.'.$cid.'.internal.selfenroll_cap'},
 4958:                 selfenroll_start_date         => $env{'course.'.$cid.'.internal.selfenroll_start_date'},
 4959:                 selfenroll_end_date           => $env{'course.'.$cid.'.internal.selfenroll_end_date'},
 4960:                 selfenroll_start_access       => $env{'course.'.$cid.'.internal.selfenroll_start_access'},
 4961:                 selfenroll_end_access         => $env{'course.'.$cid.'.internal.selfenroll_end_access'},
 4962:                 default_enrollment_start_date => $env{'course.'.$cid.'.default_enrollment_start_date'},
 4963:                 default_enrollment_end_date   => $env{'course.'.$cid.'.default_enrollment_end_date'},
 4964:                 uniquecode                    => $env{'course.'.$cid.'.internal.uniquecode'},
 4965:             );
 4966:             push(@{$brcrum},
 4967:                     {href => '/adm/createuser?action=selfenroll',
 4968:                      text => "Configure Self-enrollment",
 4969:                      help => 'Course_Self_Enrollment'});
 4970:             if (!exists($env{'form.state'})) {
 4971:                 $args = { bread_crumbs           => $brcrum,
 4972:                           bread_crumbs_component => 'Configure Self-enrollment'};
 4973:                 $r->print(&header(undef,$args));
 4974:                 $r->print('<h3>'.&mt('Self-enrollment with a student role').'</h3>'."\n");
 4975:                 &print_selfenroll_menu($r,'course',$cid,$cdom,$cnum,\%currsettings);
 4976:             } elsif ($env{'form.state'} eq 'done') {
 4977:                 push (@{$brcrum},
 4978:                           {href=>'/adm/createuser?action=selfenroll',
 4979:                            text=>"Result"});
 4980:                 $args = { bread_crumbs           => $brcrum,
 4981:                           bread_crumbs_component => 'Self-enrollment result'};
 4982:                 $r->print(&header(undef,$args));
 4983:                 $r->print('<h3>'.&mt('Self-enrollment with a student role').'</h3>'."\n");
 4984:                 &update_selfenroll_config($r,$cid,$cdom,$cnum,$context,$crstype,\%currsettings);
 4985:             }
 4986:         } else {
 4987:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 4988:                      '<span class="LC_error">'.&mt('You do not have permission to configure self-enrollment').'</span>');
 4989:         }
 4990:     } elsif ($env{'form.action'} eq 'selfenrollqueue') {
 4991:         if ($permission->{selfenrolladmin}) {
 4992:             push(@{$brcrum},
 4993:                      {href => '/adm/createuser?action=selfenrollqueue',
 4994:                       text => 'Enrollment requests',
 4995:                       help => 'Course_Self_Enrollment'});
 4996:             $bread_crumbs_component = 'Enrollment requests';
 4997:             if ($env{'form.state'} eq 'done') {
 4998:                 push(@{$brcrum},
 4999:                          {href => '/adm/createuser?action=selfenrollqueue',
 5000:                           text => 'Result',
 5001:                           help => 'Course_Self_Enrollment'});
 5002:                 $bread_crumbs_component = 'Enrollment result';
 5003:             }
 5004:             $args = { bread_crumbs           => $brcrum,
 5005:                       bread_crumbs_component => $bread_crumbs_component};
 5006:             $r->print(&header(undef,$args));
 5007:             my $cid = $env{'request.course.id'};
 5008:             my $cdom = $env{'course.'.$cid.'.domain'};
 5009:             my $cnum = $env{'course.'.$cid.'.num'};
 5010:             my $coursedesc = $env{'course.'.$cid.'.description'};
 5011:             if (!exists($env{'form.state'})) {
 5012:                 $r->print('<h3>'.&mt('Pending enrollment requests').'</h3>'."\n");
 5013:                 $r->print(&Apache::loncoursequeueadmin::display_queued_requests($context,
 5014:                                                                                 $cdom,$cnum));
 5015:             } elsif ($env{'form.state'} eq 'done') {
 5016:                 $r->print('<h3>'.&mt('Enrollment request processing').'</h3>'."\n");
 5017:                 $r->print(&Apache::loncoursequeueadmin::update_request_queue($context,
 5018:                               $cdom,$cnum,$coursedesc));
 5019:             }
 5020:         } else {
 5021:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 5022:                      '<span class="LC_error">'.&mt('You do not have permission to manage self-enrollment').'</span>');
 5023:         }
 5024:     } elsif ($env{'form.action'} eq 'changelogs') {
 5025:         if ($permission->{cusr} || $permission->{view}) {
 5026:             &print_userchangelogs_display($r,$context,$permission,$brcrum);
 5027:         } else {
 5028:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 5029:                      '<span class="LC_error">'.&mt('You do not have permission to view change logs').'</span>');
 5030:         }
 5031:     } elsif ($env{'form.action'} eq 'helpdesk') {
 5032:         if (($permission->{'owner'}) || ($permission->{'co-owner'})) {
 5033:             if ($env{'form.state'} eq 'process') {
 5034:                 if ($permission->{'owner'}) {
 5035:                     &update_helpdeskaccess($r,$permission,$brcrum);
 5036:                 } else {
 5037:                     &print_helpdeskaccess_display($r,$permission,$brcrum);
 5038:                 }
 5039:             } else {
 5040:                 &print_helpdeskaccess_display($r,$permission,$brcrum);
 5041:             }
 5042:         } else {
 5043:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 5044:                       '<span class="LC_error">'.&mt('You do not have permission to view helpdesk access').'</span>');
 5045:         }
 5046:     } else {
 5047:         $bread_crumbs_component = 'User Management';
 5048:         $args = { bread_crumbs           => $brcrum,
 5049:                   bread_crumbs_component => $bread_crumbs_component};
 5050:         $r->print(&header(undef,$args));
 5051:         $r->print(&print_main_menu($permission,$context,$crstype));
 5052:     }
 5053:     $r->print(&Apache::loncommon::end_page());
 5054:     return OK;
 5055: }
 5056: 
 5057: sub header {
 5058:     my ($jscript,$args) = @_;
 5059:     my $start_page;
 5060:     if (ref($args) eq 'HASH') {
 5061:         $start_page=&Apache::loncommon::start_page('User Management',$jscript,$args);
 5062:     } else {
 5063:         $start_page=&Apache::loncommon::start_page('User Management',$jscript);
 5064:     }
 5065:     return $start_page;
 5066: }
 5067: 
 5068: sub add_script {
 5069:     my ($js) = @_;
 5070:     return '<script type="text/javascript">'."\n"
 5071:           .'// <![CDATA['."\n"
 5072:           .$js."\n"
 5073:           .'// ]]>'."\n"
 5074:           .'</script>'."\n";
 5075: }
 5076: 
 5077: sub usernamerequest_javascript {
 5078:     my $js = <<ENDJS;
 5079: 
 5080: function openusernamereqdisplay(dom,uname,queue) {
 5081:     var url = '/adm/createuser?action=displayuserreq';
 5082:     url += '&domain='+dom+'&username='+uname+'&queue='+queue;
 5083:     var title = 'Account_Request_Browser';
 5084:     var options = 'scrollbars=1,resizable=1,menubar=0';
 5085:     options += ',width=700,height=600';
 5086:     var stdeditbrowser = open(url,title,options,'1');
 5087:     stdeditbrowser.focus();
 5088:     return;
 5089: }
 5090:  
 5091: ENDJS
 5092: }
 5093: 
 5094: sub close_popup_form {
 5095:     my $close= &mt('Close Window');
 5096:     return << "END";
 5097: <p><form name="displayreq" action="" method="post">
 5098: <input type="button" name="closeme" value="$close" onclick="javascript:self.close();" />
 5099: </form></p>
 5100: END
 5101: }
 5102: 
 5103: sub verify_user_display {
 5104:     my ($context) = @_;
 5105:     my %lt = &Apache::lonlocal::texthash (
 5106:         course    => 'course(s): description, section(s), status',
 5107:         community => 'community(s): description, section(s), status',
 5108:         author    => 'author',
 5109:     );
 5110:     my $photos;
 5111:     if (($context eq 'course') && $env{'request.course.id'}) {
 5112:         $photos = $env{'course.'.$env{'request.course.id'}.'.internal.showphoto'};
 5113:     }
 5114:     my $output = <<"END";
 5115: 
 5116: function hide_searching() {
 5117:     if (document.getElementById('searching')) {
 5118:         document.getElementById('searching').style.display = 'none';
 5119:     }
 5120:     return;
 5121: }
 5122: 
 5123: function display_update() {
 5124:     document.studentform.action.value = 'listusers';
 5125:     document.studentform.phase.value = 'display';
 5126:     document.studentform.submit();
 5127: }
 5128: 
 5129: function updateCols(caller) {
 5130:     var context = '$context';
 5131:     var photos = '$photos';
 5132:     if (caller == 'Status') {
 5133:         if ((context == 'domain') && 
 5134:             ((document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'course') ||
 5135:              (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'community'))) {
 5136:             document.getElementById('showcolstatus').checked = false;
 5137:             document.getElementById('showcolstatus').disabled = 'disabled';
 5138:             document.getElementById('showcolstart').checked = false;
 5139:             document.getElementById('showcolend').checked = false;
 5140:         } else {
 5141:             if (document.studentform.Status.options[document.studentform.Status.selectedIndex].value == 'Any') {
 5142:                 document.getElementById('showcolstatus').checked = true;
 5143:                 document.getElementById('showcolstatus').disabled = '';
 5144:                 document.getElementById('showcolstart').checked = true;
 5145:                 document.getElementById('showcolend').checked = true;
 5146:             } else {
 5147:                 document.getElementById('showcolstatus').checked = false;
 5148:                 document.getElementById('showcolstatus').disabled = 'disabled';
 5149:                 document.getElementById('showcolstart').checked = false;
 5150:                 document.getElementById('showcolend').checked = false;
 5151:             }
 5152:         }
 5153:     }
 5154:     if (caller == 'output') {
 5155:         if (photos == 1) {
 5156:             if (document.getElementById('showcolphoto')) {
 5157:                 var photoitem = document.getElementById('showcolphoto');
 5158:                 if (document.studentform.output.options[document.studentform.output.selectedIndex].value == 'html') {
 5159:                     photoitem.checked = true;
 5160:                     photoitem.disabled = '';
 5161:                 } else {
 5162:                     photoitem.checked = false;
 5163:                     photoitem.disabled = 'disabled';
 5164:                 }
 5165:             }
 5166:         }
 5167:     }
 5168:     if (caller == 'showrole') {
 5169:         if ((document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'Any') ||
 5170:             (document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'cr')) {
 5171:             document.getElementById('showcolrole').checked = true;
 5172:             document.getElementById('showcolrole').disabled = '';
 5173:         } else {
 5174:             document.getElementById('showcolrole').checked = false;
 5175:             document.getElementById('showcolrole').disabled = 'disabled';
 5176:         }
 5177:         if (context == 'domain') {
 5178:             var quotausageshow = 0;
 5179:             if ((document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'course') ||
 5180:                 (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'community')) {
 5181:                 document.getElementById('showcolstatus').checked = false;
 5182:                 document.getElementById('showcolstatus').disabled = 'disabled';
 5183:                 document.getElementById('showcolstart').checked = false;
 5184:                 document.getElementById('showcolend').checked = false;
 5185:             } else {
 5186:                 if (document.studentform.Status.options[document.studentform.Status.selectedIndex].value == 'Any') {
 5187:                     document.getElementById('showcolstatus').checked = true;
 5188:                     document.getElementById('showcolstatus').disabled = '';
 5189:                     document.getElementById('showcolstart').checked = true;
 5190:                     document.getElementById('showcolend').checked = true;
 5191:                 }
 5192:             }
 5193:             if (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'domain') {
 5194:                 document.getElementById('showcolextent').disabled = 'disabled';
 5195:                 document.getElementById('showcolextent').checked = 'false';
 5196:                 document.getElementById('showextent').style.display='none';
 5197:                 document.getElementById('showcoltextextent').innerHTML = '';
 5198:                 if ((document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'au') ||
 5199:                     (document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'Any')) {
 5200:                     if (document.getElementById('showcolauthorusage')) {
 5201:                         document.getElementById('showcolauthorusage').disabled = '';
 5202:                     }
 5203:                     if (document.getElementById('showcolauthorquota')) {
 5204:                         document.getElementById('showcolauthorquota').disabled = '';
 5205:                     }
 5206:                     quotausageshow = 1;
 5207:                 }
 5208:             } else {
 5209:                 document.getElementById('showextent').style.display='block';
 5210:                 document.getElementById('showextent').style.textAlign='left';
 5211:                 document.getElementById('showextent').style.textFace='normal';
 5212:                 if (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'author') {
 5213:                     document.getElementById('showcolextent').disabled = '';
 5214:                     document.getElementById('showcolextent').checked = 'true';
 5215:                     document.getElementById('showcoltextextent').innerHTML="$lt{'author'}";
 5216:                 } else {
 5217:                     document.getElementById('showcolextent').disabled = '';
 5218:                     document.getElementById('showcolextent').checked = 'true';
 5219:                     if (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'community') {
 5220:                         document.getElementById('showcoltextextent').innerHTML="$lt{'community'}";
 5221:                     } else {
 5222:                         document.getElementById('showcoltextextent').innerHTML="$lt{'course'}";
 5223:                     }
 5224:                 }
 5225:             }
 5226:             if (quotausageshow == 0)  {
 5227:                 if (document.getElementById('showcolauthorusage')) {
 5228:                     document.getElementById('showcolauthorusage').checked = false;
 5229:                     document.getElementById('showcolauthorusage').disabled = 'disabled';
 5230:                 }
 5231:                 if (document.getElementById('showcolauthorquota')) {
 5232:                     document.getElementById('showcolauthorquota').checked = false;
 5233:                     document.getElementById('showcolauthorquota').disabled = 'disabled';
 5234:                 }
 5235:             }
 5236:         }
 5237:     }
 5238:     return;
 5239: }
 5240: 
 5241: END
 5242:     return $output;
 5243: 
 5244: }
 5245: 
 5246: ###############################################################
 5247: ###############################################################
 5248: #  Menu Phase One
 5249: sub print_main_menu {
 5250:     my ($permission,$context,$crstype) = @_;
 5251:     my $linkcontext = $context;
 5252:     my $stuterm = lc(&Apache::lonnet::plaintext('st',$crstype));
 5253:     if (($context eq 'course') && ($crstype eq 'Community')) {
 5254:         $linkcontext = lc($crstype);
 5255:         $stuterm = 'Members';
 5256:     }
 5257:     my %links = (
 5258:                 domain => {
 5259:                             upload     => 'Upload a File of Users',
 5260:                             singleuser => 'Add/Modify a User',
 5261:                             listusers  => 'Manage Users',
 5262:                             },
 5263:                 author => {
 5264:                             upload     => 'Upload a File of Co-authors',
 5265:                             singleuser => 'Add/Modify a Co-author',
 5266:                             listusers  => 'Manage Co-authors',
 5267:                             },
 5268:                 course => {
 5269:                             upload     => 'Upload a File of Course Users',
 5270:                             singleuser => 'Add/Modify a Course User',
 5271:                             listusers  => 'List and Modify Multiple Course Users',
 5272:                             },
 5273:                 community => {
 5274:                             upload     => 'Upload a File of Community Users',
 5275:                             singleuser => 'Add/Modify a Community User',
 5276:                             listusers  => 'List and Modify Multiple Community Users',
 5277:                            },
 5278:                 );
 5279:      my %linktitles = (
 5280:                 domain => {
 5281:                             singleuser => 'Add a user to the domain, and/or a course or community in the domain.',
 5282:                             listusers  => 'Show and manage users in this domain.',
 5283:                             },
 5284:                 author => {
 5285:                             singleuser => 'Add a user with a co- or assistant author role.',
 5286:                             listusers  => 'Show and manage co- or assistant authors.',
 5287:                             },
 5288:                 course => {
 5289:                             singleuser => 'Add a user with a certain role to this course.',
 5290:                             listusers  => 'Show and manage users in this course.',
 5291:                             },
 5292:                 community => {
 5293:                             singleuser => 'Add a user with a certain role to this community.',
 5294:                             listusers  => 'Show and manage users in this community.',
 5295:                            },
 5296:                 );
 5297:   if ($linkcontext eq 'domain') {
 5298:       unless ($permission->{'cusr'}) {
 5299:           $links{'domain'}{'singleuser'} = 'View a User';
 5300:           $linktitles{'domain'}{'singleuser'} = 'View information about a user in the domain';
 5301:       }
 5302:   } elsif ($linkcontext eq 'course') {
 5303:       unless ($permission->{'cusr'}) {
 5304:           $links{'course'}{'singleuser'} = 'View a Course User';
 5305:           $linktitles{'course'}{'singleuser'} = 'View information about a user in this course';
 5306:           $links{'course'}{'listusers'} = 'List Course Users';
 5307:           $linktitles{'course'}{'listusers'} = 'Show information about users in this course';
 5308:       }
 5309:   } elsif ($linkcontext eq 'community') {
 5310:       unless ($permission->{'cusr'}) {
 5311:           $links{'community'}{'singleuser'} = 'View a Community User';
 5312:           $linktitles{'community'}{'singleuser'} = 'View information about a user in this community';
 5313:           $links{'community'}{'listusers'} = 'List Community Users';
 5314:           $linktitles{'community'}{'listusers'} = 'Show information about users in this community';
 5315:       }
 5316:   }
 5317:   my @menu = ( {categorytitle => 'Single Users', 
 5318:          items =>
 5319:          [
 5320:             {
 5321:              linktext => $links{$linkcontext}{'singleuser'},
 5322:              icon => 'edit-redo.png',
 5323:              #help => 'Course_Change_Privileges',
 5324:              url => '/adm/createuser?action=singleuser',
 5325:              permission => ($permission->{'view'} || $permission->{'cusr'}),
 5326:              linktitle => $linktitles{$linkcontext}{'singleuser'},
 5327:             },
 5328:          ]},
 5329: 
 5330:          {categorytitle => 'Multiple Users',
 5331:          items => 
 5332:          [
 5333:             {
 5334:              linktext => $links{$linkcontext}{'upload'},
 5335:              icon => 'uplusr.png',
 5336:              #help => 'Course_Create_Class_List',
 5337:              url => '/adm/createuser?action=upload',
 5338:              permission => $permission->{'cusr'},
 5339:              linktitle => 'Upload a CSV or a text file containing users.',
 5340:             },
 5341:             {
 5342:              linktext => $links{$linkcontext}{'listusers'},
 5343:              icon => 'mngcu.png',
 5344:              #help => 'Course_View_Class_List',
 5345:              url => '/adm/createuser?action=listusers',
 5346:              permission => ($permission->{'view'} || $permission->{'cusr'}),
 5347:              linktitle => $linktitles{$linkcontext}{'listusers'}, 
 5348:             },
 5349: 
 5350:          ]},
 5351: 
 5352:          {categorytitle => 'Administration',
 5353:          items => [ ]},
 5354:        );
 5355: 
 5356:     if ($context eq 'domain'){
 5357:         push(@{  $menu[0]->{items} }, # Single Users
 5358:             {
 5359:              linktext => 'User Access Log',
 5360:              icon => 'document-properties.png',
 5361:              #help => 'Domain_User_Access_Logs',
 5362:              url => '/adm/createuser?action=accesslogs',
 5363:              permission => $permission->{'activity'},
 5364:              linktitle => 'View user access log.',
 5365:             }
 5366:         );
 5367:         
 5368:         push(@{ $menu[2]->{items} }, #Category: Administration
 5369:             {
 5370:              linktext => 'Custom Roles',
 5371:              icon => 'emblem-photos.png',
 5372:              #help => 'Course_Editing_Custom_Roles',
 5373:              url => '/adm/createuser?action=custom',
 5374:              permission => $permission->{'custom'},
 5375:              linktitle => 'Configure a custom role.',
 5376:             },
 5377:             {
 5378:              linktext => 'Authoring Space Requests',
 5379:              icon => 'selfenrl-queue.png',
 5380:              #help => 'Domain_Role_Approvals',
 5381:              url => '/adm/createuser?action=processauthorreq',
 5382:              permission => $permission->{'cusr'},
 5383:              linktitle => 'Approve or reject author role requests',
 5384:             },
 5385:             {
 5386:              linktext => 'LON-CAPA Account Requests',
 5387:              icon => 'list-add.png',
 5388:              #help => 'Domain_Username_Approvals',
 5389:              url => '/adm/createuser?action=processusernamereq',
 5390:              permission => $permission->{'cusr'},
 5391:              linktitle => 'Approve or reject LON-CAPA account requests',
 5392:             },
 5393:             {
 5394:              linktext => 'Change Log',
 5395:              icon => 'document-properties.png',
 5396:              #help => 'Course_User_Logs',
 5397:              url => '/adm/createuser?action=changelogs',
 5398:              permission => ($permission->{'cusr'} || $permission->{'view'}),
 5399:              linktitle => 'View change log.',
 5400:             },
 5401:         );
 5402:         
 5403:     }elsif ($context eq 'course'){
 5404:         my ($cnum,$cdom) = &Apache::lonuserutils::get_course_identity();
 5405: 
 5406:         my %linktext = (
 5407:                          'Course'    => {
 5408:                                           single => 'Add/Modify a Student', 
 5409:                                           drop   => 'Drop Students',
 5410:                                           groups => 'Course Groups',
 5411:                                         },
 5412:                          'Community' => {
 5413:                                           single => 'Add/Modify a Member', 
 5414:                                           drop   => 'Drop Members',
 5415:                                           groups => 'Community Groups',
 5416:                                         },
 5417:                        );
 5418: 
 5419:         my %linktitle = (
 5420:             'Course' => {
 5421:                   single => 'Add a user with the role of student to this course',
 5422:                   drop   => 'Remove a student from this course.',
 5423:                   groups => 'Manage course groups',
 5424:                         },
 5425:             'Community' => {
 5426:                   single => 'Add a user with the role of member to this community',
 5427:                   drop   => 'Remove a member from this community.',
 5428:                   groups => 'Manage community groups',
 5429:                            },
 5430:         );
 5431: 
 5432:         push(@{ $menu[0]->{items} }, #Category: Single Users
 5433:             {   
 5434:              linktext => $linktext{$crstype}{'single'},
 5435:              #help => 'Course_Add_Student',
 5436:              icon => 'list-add.png',
 5437:              url => '/adm/createuser?action=singlestudent',
 5438:              permission => $permission->{'cusr'},
 5439:              linktitle => $linktitle{$crstype}{'single'},
 5440:             },
 5441:         );
 5442:         
 5443:         push(@{ $menu[1]->{items} }, #Category: Multiple Users 
 5444:             {
 5445:              linktext => $linktext{$crstype}{'drop'},
 5446:              icon => 'edit-undo.png',
 5447:              #help => 'Course_Drop_Student',
 5448:              url => '/adm/createuser?action=drop',
 5449:              permission => $permission->{'cusr'},
 5450:              linktitle => $linktitle{$crstype}{'drop'},
 5451:             },
 5452:         );
 5453:         push(@{ $menu[2]->{items} }, #Category: Administration
 5454:             {
 5455:              linktext => 'Helpdesk Access',
 5456:              icon => 'helpdesk-access.png',
 5457:              #help => 'Course_Helpdesk_Access',
 5458:              url => '/adm/createuser?action=helpdesk',
 5459:              permission => ($permission->{'owner'} || $permission->{'co-owner'}),
 5460:              linktitle => 'Helpdesk access options',
 5461:             },
 5462:             {
 5463:              linktext => 'Custom Roles',
 5464:              icon => 'emblem-photos.png',
 5465:              #help => 'Course_Editing_Custom_Roles',
 5466:              url => '/adm/createuser?action=custom',
 5467:              permission => $permission->{'custom'},
 5468:              linktitle => 'Configure a custom role.',
 5469:             },
 5470:             {
 5471:              linktext => $linktext{$crstype}{'groups'},
 5472:              icon => 'grps.png',
 5473:              #help => 'Course_Manage_Group',
 5474:              url => '/adm/coursegroups?refpage=cusr',
 5475:              permission => $permission->{'grp_manage'},
 5476:              linktitle => $linktitle{$crstype}{'groups'},
 5477:             },
 5478:             {
 5479:              linktext => 'Change Log',
 5480:              icon => 'document-properties.png',
 5481:              #help => 'Course_User_Logs',
 5482:              url => '/adm/createuser?action=changelogs',
 5483:              permission => ($permission->{'view'} || $permission->{'cusr'}),
 5484:              linktitle => 'View change log.',
 5485:             },
 5486:         );
 5487:         if ($env{'course.'.$env{'request.course.id'}.'.internal.selfenroll_approval'}) {
 5488:             push(@{ $menu[2]->{items} },
 5489:                     {
 5490:                      linktext => 'Enrollment Requests',
 5491:                      icon => 'selfenrl-queue.png',
 5492:                      #help => 'Course_Approve_Selfenroll',
 5493:                      url => '/adm/createuser?action=selfenrollqueue',
 5494:                      permission => $permission->{'selfenrolladmin'},
 5495:                      linktitle =>'Approve or reject enrollment requests.',
 5496:                     },
 5497:             );
 5498:         }
 5499:         
 5500:         if (!exists($permission->{'cusr_section'})){
 5501:             if ($crstype ne 'Community') {
 5502:                 push(@{ $menu[2]->{items} },
 5503:                     {
 5504:                      linktext => 'Automated Enrollment',
 5505:                      icon => 'roles.png',
 5506:                      #help => 'Course_Automated_Enrollment',
 5507:                      permission => (&Apache::lonnet::auto_run($cnum,$cdom)
 5508:                                          && (($permission->{'cusr'}) ||
 5509:                                              ($permission->{'view'}))),
 5510:                      url  => '/adm/populate',
 5511:                      linktitle => 'Automated enrollment manager.',
 5512:                     }
 5513:                 );
 5514:             }
 5515:             push(@{ $menu[2]->{items} }, 
 5516:                 {
 5517:                  linktext => 'User Self-Enrollment',
 5518:                  icon => 'self_enroll.png',
 5519:                  #help => 'Course_Self_Enrollment',
 5520:                  url => '/adm/createuser?action=selfenroll',
 5521:                  permission => $permission->{'selfenrolladmin'},
 5522:                  linktitle => 'Configure user self-enrollment.',
 5523:                 },
 5524:             );
 5525:         }
 5526:     } elsif ($context eq 'author') {
 5527:         push(@{ $menu[2]->{items} }, #Category: Administration
 5528:             {
 5529:              linktext => 'Change Log',
 5530:              icon => 'document-properties.png',
 5531:              #help => 'Course_User_Logs',
 5532:              url => '/adm/createuser?action=changelogs',
 5533:              permission => $permission->{'cusr'},
 5534:              linktitle => 'View change log.',
 5535:             },
 5536:         );
 5537:     }
 5538:     return Apache::lonhtmlcommon::generate_menu(@menu);
 5539: #               { text => 'View Log-in History',
 5540: #                 help => 'Course_User_Logins',
 5541: #                 action => 'logins',
 5542: #                 permission => $permission->{'cusr'},
 5543: #               });
 5544: }
 5545: 
 5546: sub restore_prev_selections {
 5547:     my %saveable_parameters = ('srchby'   => 'scalar',
 5548: 			       'srchin'   => 'scalar',
 5549: 			       'srchtype' => 'scalar',
 5550: 			       );
 5551:     &Apache::loncommon::store_settings('user','user_picker',
 5552: 				       \%saveable_parameters);
 5553:     &Apache::loncommon::restore_settings('user','user_picker',
 5554: 					 \%saveable_parameters);
 5555: }
 5556: 
 5557: sub print_selfenroll_menu {
 5558:     my ($r,$context,$cid,$cdom,$cnum,$currsettings,$additional,$readonly) = @_;
 5559:     my $crstype = &Apache::loncommon::course_type();
 5560:     my $formname = 'selfenroll';
 5561:     my $nolink = 1;
 5562:     my ($row,$lt) = &Apache::lonuserutils::get_selfenroll_titles();
 5563:     my $groupslist = &Apache::lonuserutils::get_groupslist();
 5564:     my $setsec_js = 
 5565:         &Apache::lonuserutils::setsections_javascript($formname,$groupslist);
 5566:     my %alerts = &Apache::lonlocal::texthash(
 5567:         acto => 'Activation of self-enrollment was selected for the following domain(s)',
 5568:         butn => 'but no user types have been checked.',
 5569:         wilf => "Please uncheck 'activate' or check at least one type.",
 5570:     );
 5571:     my $disabled;
 5572:     if ($readonly) {
 5573:        $disabled = ' disabled="disabled"';
 5574:     }
 5575:     &js_escape(\%alerts);
 5576:     my $selfenroll_js = <<"ENDSCRIPT";
 5577: function update_types(caller,num) {
 5578:     var delidx = getIndexByName('selfenroll_delete');
 5579:     var actidx = getIndexByName('selfenroll_activate');
 5580:     if (caller == 'selfenroll_all') {
 5581:         var selall;
 5582:         for (var i=0; i<document.$formname.selfenroll_all.length; i++) {
 5583:             if (document.$formname.selfenroll_all[i].checked) {
 5584:                 selall = document.$formname.selfenroll_all[i].value;
 5585:             }
 5586:         }
 5587:         if (selall == 1) {
 5588:             if (delidx != -1) {
 5589:                 if (document.$formname.selfenroll_delete.length) {
 5590:                     for (var j=0; j<document.$formname.selfenroll_delete.length; j++) {
 5591:                         document.$formname.selfenroll_delete[j].checked = true;
 5592:                     }
 5593:                 } else {
 5594:                     document.$formname.elements[delidx].checked = true;
 5595:                 }
 5596:             }
 5597:             if (actidx != -1) {
 5598:                 if (document.$formname.selfenroll_activate.length) {
 5599:                     for (var j=0; j<document.$formname.selfenroll_activate.length; j++) {
 5600:                         document.$formname.selfenroll_activate[j].checked = false;
 5601:                     }
 5602:                 } else {
 5603:                     document.$formname.elements[actidx].checked = false;
 5604:                 }
 5605:             }
 5606:             document.$formname.selfenroll_newdom.selectedIndex = 0; 
 5607:         }
 5608:     }
 5609:     if (caller == 'selfenroll_activate') {
 5610:         if (document.$formname.selfenroll_activate.length) {
 5611:             for (var j=0; j<document.$formname.selfenroll_activate.length; j++) {
 5612:                 if (document.$formname.selfenroll_activate[j].value == num) {
 5613:                     if (document.$formname.selfenroll_activate[j].checked) {
 5614:                         for (var i=0; i<document.$formname.selfenroll_all.length; i++) {
 5615:                             if (document.$formname.selfenroll_all[i].value == '1') {
 5616:                                 document.$formname.selfenroll_all[i].checked = false;
 5617:                             }
 5618:                             if (document.$formname.selfenroll_all[i].value == '0') {
 5619:                                 document.$formname.selfenroll_all[i].checked = true;
 5620:                             }
 5621:                         }
 5622:                     }
 5623:                 }
 5624:             }
 5625:         } else {
 5626:             for (var i=0; i<document.$formname.selfenroll_all.length; i++) {
 5627:                 if (document.$formname.selfenroll_all[i].value == '1') {
 5628:                     document.$formname.selfenroll_all[i].checked = false;
 5629:                 }
 5630:                 if (document.$formname.selfenroll_all[i].value == '0') {
 5631:                     document.$formname.selfenroll_all[i].checked = true;
 5632:                 }
 5633:             }
 5634:         }
 5635:     }
 5636:     if (caller == 'selfenroll_delete') {
 5637:         if (document.$formname.selfenroll_delete.length) {
 5638:             for (var j=0; j<document.$formname.selfenroll_delete.length; j++) {
 5639:                 if (document.$formname.selfenroll_delete[j].value == num) {
 5640:                     if (document.$formname.selfenroll_delete[j].checked) {
 5641:                         var delindex = getIndexByName('selfenroll_types_'+num);
 5642:                         if (delindex != -1) { 
 5643:                             if (document.$formname.elements[delindex].length) {
 5644:                                 for (var k=0; k<document.$formname.elements[delindex].length; k++) {
 5645:                                     document.$formname.elements[delindex][k].checked = false;
 5646:                                 }
 5647:                             } else {
 5648:                                 document.$formname.elements[delindex].checked = false;
 5649:                             }
 5650:                         }
 5651:                     }
 5652:                 }
 5653:             }
 5654:         } else {
 5655:             if (document.$formname.selfenroll_delete.checked) {
 5656:                 var delindex = getIndexByName('selfenroll_types_'+num);
 5657:                 if (delindex != -1) {
 5658:                     if (document.$formname.elements[delindex].length) {
 5659:                         for (var k=0; k<document.$formname.elements[delindex].length; k++) {
 5660:                             document.$formname.elements[delindex][k].checked = false;
 5661:                         }
 5662:                     } else {
 5663:                         document.$formname.elements[delindex].checked = false;
 5664:                     }
 5665:                 }
 5666:             }
 5667:         }
 5668:     }
 5669:     return;
 5670: }
 5671: 
 5672: function validate_types(form) {
 5673:     var needaction = new Array();
 5674:     var countfail = 0;
 5675:     var actidx = getIndexByName('selfenroll_activate');
 5676:     if (actidx != -1) {
 5677:         if (document.$formname.selfenroll_activate.length) {
 5678:             for (var j=0; j<document.$formname.selfenroll_activate.length; j++) {
 5679:                 var num = document.$formname.selfenroll_activate[j].value;
 5680:                 if (document.$formname.selfenroll_activate[j].checked) {
 5681:                     countfail = check_types(num,countfail,needaction)
 5682:                 }
 5683:             }
 5684:         } else {
 5685:             if (document.$formname.selfenroll_activate.checked) {
 5686:                 var num = document.$formname.selfenroll_activate.value;
 5687:                 countfail = check_types(num,countfail,needaction)
 5688:             }
 5689:         }
 5690:     }
 5691:     if (countfail > 0) {
 5692:         var msg = "$alerts{'acto'}\\n";
 5693:         var loopend = needaction.length -1;
 5694:         if (loopend > 0) {
 5695:             for (var m=0; m<loopend; m++) {
 5696:                 msg += needaction[m]+", ";
 5697:             }
 5698:         }
 5699:         msg += needaction[loopend]+"\\n$alerts{'butn'}\\n$alerts{'wilf'}";
 5700:         alert(msg);
 5701:         return; 
 5702:     }
 5703:     setSections(form);
 5704: }
 5705: 
 5706: function check_types(num,countfail,needaction) {
 5707:     var typeidx = getIndexByName('selfenroll_types_'+num);
 5708:     var count = 0;
 5709:     if (typeidx != -1) {
 5710:         if (document.$formname.elements[typeidx].length) {
 5711:             for (var k=0; k<document.$formname.elements[typeidx].length; k++) {
 5712:                 if (document.$formname.elements[typeidx][k].checked) {
 5713:                     count ++;
 5714:                 }
 5715:             }
 5716:         } else {
 5717:             if (document.$formname.elements[typeidx].checked) {
 5718:                 count ++;
 5719:             }
 5720:         }
 5721:         if (count == 0) {
 5722:             var domidx = getIndexByName('selfenroll_dom_'+num);
 5723:             if (domidx != -1) {
 5724:                 var domname = document.$formname.elements[domidx].value;
 5725:                 needaction[countfail] = domname;
 5726:                 countfail ++;
 5727:             }
 5728:         }
 5729:     }
 5730:     return countfail;
 5731: }
 5732: 
 5733: function toggleNotify() {
 5734:     var selfenrollApproval = 0;
 5735:     if (document.$formname.selfenroll_approval.length) {
 5736:         for (var i=0; i<document.$formname.selfenroll_approval.length; i++) {
 5737:             if (document.$formname.selfenroll_approval[i].checked) {
 5738:                 selfenrollApproval = document.$formname.selfenroll_approval[i].value;
 5739:                 break;        
 5740:             }
 5741:         }
 5742:     }
 5743:     if (document.getElementById('notified')) {
 5744:         if (selfenrollApproval == 0) {
 5745:             document.getElementById('notified').style.display='none';
 5746:         } else {
 5747:             document.getElementById('notified').style.display='block';
 5748:         }
 5749:     }
 5750:     return;
 5751: }
 5752: 
 5753: function getIndexByName(item) {
 5754:     for (var i=0;i<document.$formname.elements.length;i++) {
 5755:         if (document.$formname.elements[i].name == item) {
 5756:             return i;
 5757:         }
 5758:     }
 5759:     return -1;
 5760: }
 5761: ENDSCRIPT
 5762: 
 5763:     my $output = '<script type="text/javascript">'."\n".
 5764:                  '// <![CDATA['."\n".
 5765:                  $setsec_js."\n".$selfenroll_js."\n".
 5766:                  '// ]]>'."\n".
 5767:                  '</script>'."\n".
 5768:                  '<h3>'.$lt->{'selfenroll'}.'</h3>'."\n";
 5769:  
 5770:     my $visactions = &cat_visibility();
 5771:     my ($cathash,%cattype);
 5772:     my %domconfig = &Apache::lonnet::get_dom('configuration',['coursecategories'],$cdom);
 5773:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 5774:         $cathash = $domconfig{'coursecategories'}{'cats'};
 5775:         $cattype{'auth'} = $domconfig{'coursecategories'}{'auth'};
 5776:         $cattype{'unauth'} = $domconfig{'coursecategories'}{'unauth'};
 5777:         if ($cattype{'auth'} eq '') {
 5778:             $cattype{'auth'} = 'std';
 5779:         }
 5780:         if ($cattype{'unauth'} eq '') {
 5781:             $cattype{'unauth'} = 'std';
 5782:         }
 5783:     } else {
 5784:         $cathash = {};
 5785:         $cattype{'auth'} = 'std';
 5786:         $cattype{'unauth'} = 'std';
 5787:     }
 5788:     if (($cattype{'auth'} eq 'none') && ($cattype{'unauth'} eq 'none')) {
 5789:         $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
 5790:                   '<br />'.
 5791:                   '<br />'.$visactions->{'take'}.'<ul>'.
 5792:                   '<li>'.$visactions->{'dc_chgconf'}.'</li>'.
 5793:                   '</ul>');
 5794:     } elsif (($cattype{'auth'} !~ /^(std|domonly)$/) && ($cattype{'unauth'} !~ /^(std|domonly)$/)) {
 5795:         if ($currsettings->{'uniquecode'}) {
 5796:             $r->print('<span class="LC_info">'.$visactions->{'vis'}.'</span>');
 5797:         } else {
 5798:             $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
 5799:                   '<br />'.
 5800:                   '<br />'.$visactions->{'take'}.'<ul>'.
 5801:                   '<li>'.$visactions->{'dc_setcode'}.'</li>'.
 5802:                   '</ul><br />');
 5803:         }
 5804:     } else {
 5805:         my ($visible,$cansetvis,$vismsgs) = &visible_in_stdcat($cdom,$cnum,\%domconfig);
 5806:         if (ref($visactions) eq 'HASH') {
 5807:             if ($visible) {
 5808:                 $output .= '<p class="LC_info">'.$visactions->{'vis'}.'</p>';
 5809:            } else {
 5810:                 $output .= '<p class="LC_warning">'.$visactions->{'miss'}.'</p>'
 5811:                           .$visactions->{'yous'}.
 5812:                            '<p>'.$visactions->{'gen'}.'<br />'.$visactions->{'coca'};
 5813:                 if (ref($vismsgs) eq 'ARRAY') {
 5814:                     $output .= '<br />'.$visactions->{'make'}.'<ul>';
 5815:                     foreach my $item (@{$vismsgs}) {
 5816:                         $output .= '<li>'.$visactions->{$item}.'</li>';
 5817:                     }
 5818:                     $output .= '</ul>';
 5819:                 }
 5820:                 $output .= '</p>';
 5821:             }
 5822:         }
 5823:     }
 5824:     my $actionhref = '/adm/createuser';
 5825:     if ($context eq 'domain') {
 5826:         $actionhref = '/adm/modifycourse';
 5827:     }
 5828: 
 5829:     my %noedit;
 5830:     unless ($context eq 'domain') {
 5831:         %noedit = &get_noedit_fields($cdom,$cnum,$crstype,$row);
 5832:     }
 5833:     $output .= '<form name="'.$formname.'" method="post" action="'.$actionhref.'">'."\n".
 5834:                &Apache::lonhtmlcommon::start_pick_box();
 5835:     if (ref($row) eq 'ARRAY') {
 5836:         foreach my $item (@{$row}) {
 5837:             my $title = $item; 
 5838:             if (ref($lt) eq 'HASH') {
 5839:                 $title = $lt->{$item};
 5840:             }
 5841:             $output .= &Apache::lonhtmlcommon::row_title($title);
 5842:             if ($item eq 'types') {
 5843:                 my $curr_types;
 5844:                 if (ref($currsettings) eq 'HASH') {
 5845:                     $curr_types = $currsettings->{'selfenroll_types'};
 5846:                 }
 5847:                 if ($noedit{$item}) {
 5848:                     if ($curr_types eq '*') {
 5849:                         $output .= &mt('Any user in any domain');   
 5850:                     } else {
 5851:                         my @entries = split(/;/,$curr_types);
 5852:                         if (@entries > 0) {
 5853:                             $output .= '<ul>'; 
 5854:                             foreach my $entry (@entries) {
 5855:                                 my ($currdom,$typestr) = split(/:/,$entry);
 5856:                                 next if ($typestr eq '');
 5857:                                 my $domdesc = &Apache::lonnet::domain($currdom);
 5858:                                 my @currinsttypes = split(',',$typestr);
 5859:                                 my ($othertitle,$usertypes,$types) = 
 5860:                                     &Apache::loncommon::sorted_inst_types($currdom);
 5861:                                 if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 5862:                                     $usertypes->{'any'} = &mt('any user'); 
 5863:                                     if (keys(%{$usertypes}) > 0) {
 5864:                                         $usertypes->{'other'} = &mt('other users');
 5865:                                     }
 5866:                                     my @longinsttypes = map { $usertypes->{$_}; } @currinsttypes;
 5867:                                     $output .= '<li>'.$domdesc.':'.join(', ',@longinsttypes).'</li>';
 5868:                                  }
 5869:                             }
 5870:                             $output .= '</ul>';
 5871:                         } else {
 5872:                             $output .= &mt('None');
 5873:                         }
 5874:                     }
 5875:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 5876:                     next;
 5877:                 }
 5878:                 my $showdomdesc = 1;
 5879:                 my $includeempty = 1;
 5880:                 my $num = 0;
 5881:                 $output .= &Apache::loncommon::start_data_table().
 5882:                            &Apache::loncommon::start_data_table_row()
 5883:                            .'<td colspan="2"><span class="LC_nobreak"><label>'
 5884:                            .&mt('Any user in any domain:')
 5885:                            .'&nbsp;<input type="radio" name="selfenroll_all" value="1" ';
 5886:                 if ($curr_types eq '*') {
 5887:                     $output .= ' checked="checked" '; 
 5888:                 }
 5889:                 $output .= 'onchange="javascript:update_types('.
 5890:                            "'selfenroll_all'".');"'.$disabled.' />'.&mt('Yes').'</label>'.
 5891:                            '&nbsp;&nbsp;<input type="radio" name="selfenroll_all" value="0" ';
 5892:                 if ($curr_types ne '*') {
 5893:                     $output .= ' checked="checked" ';
 5894:                 }
 5895:                 $output .= ' onchange="javascript:update_types('.
 5896:                            "'selfenroll_all'".');"'.$disabled.' />'.&mt('No').'</label></td>'.
 5897:                            &Apache::loncommon::end_data_table_row().
 5898:                            &Apache::loncommon::end_data_table().
 5899:                            &mt('Or').'<br />'.
 5900:                            &Apache::loncommon::start_data_table();
 5901:                 my %currdoms;
 5902:                 if ($curr_types eq '') {
 5903:                     $output .= &new_selfenroll_dom_row($cdom,'0');
 5904:                 } elsif ($curr_types ne '*') {
 5905:                     my @entries = split(/;/,$curr_types);
 5906:                     if (@entries > 0) {
 5907:                         foreach my $entry (@entries) {
 5908:                             my ($currdom,$typestr) = split(/:/,$entry);
 5909:                             $currdoms{$currdom} = 1;
 5910:                             my $domdesc = &Apache::lonnet::domain($currdom);
 5911:                             my @currinsttypes = split(',',$typestr);
 5912:                             $output .= &Apache::loncommon::start_data_table_row()
 5913:                                        .'<td valign="top"><span class="LC_nobreak">'.&mt('Domain:').'<b>'
 5914:                                        .'&nbsp;'.$domdesc.' ('.$currdom.')'
 5915:                                        .'</b><input type="hidden" name="selfenroll_dom_'.$num
 5916:                                        .'" value="'.$currdom.'" /></span><br />'
 5917:                                        .'<span class="LC_nobreak"><label><input type="checkbox" '
 5918:                                        .'name="selfenroll_delete" value="'.$num.'" onchange="javascript:update_types('."'selfenroll_delete','$num'".');"'.$disabled.' />'
 5919:                                        .&mt('Delete').'</label></span></td>';
 5920:                             $output .= '<td valign="top">&nbsp;&nbsp;'.&mt('User types:').'<br />'
 5921:                                        .&selfenroll_inst_types($num,$currdom,\@currinsttypes,$readonly).'</td>'
 5922:                                        .&Apache::loncommon::end_data_table_row();
 5923:                             $num ++;
 5924:                         }
 5925:                     }
 5926:                 }
 5927:                 my $add_domtitle = &mt('Users in additional domain:');
 5928:                 if ($curr_types eq '*') { 
 5929:                     $add_domtitle = &mt('Users in specific domain:');
 5930:                 } elsif ($curr_types eq '') {
 5931:                     $add_domtitle = &mt('Users in other domain:');
 5932:                 }
 5933:                 $output .= &Apache::loncommon::start_data_table_row()
 5934:                            .'<td colspan="2"><span class="LC_nobreak">'.$add_domtitle.'</span><br />'
 5935:                            .&Apache::loncommon::select_dom_form('','selfenroll_newdom',
 5936:                                                                 $includeempty,$showdomdesc,'','','',$readonly)
 5937:                            .'<input type="hidden" name="selfenroll_types_total" value="'.$num.'" />'
 5938:                            .'</td>'.&Apache::loncommon::end_data_table_row()
 5939:                            .&Apache::loncommon::end_data_table();
 5940:             } elsif ($item eq 'registered') {
 5941:                 my ($regon,$regoff);
 5942:                 my $registered;
 5943:                 if (ref($currsettings) eq 'HASH') {
 5944:                     $registered = $currsettings->{'selfenroll_registered'};
 5945:                 }
 5946:                 if ($noedit{$item}) {
 5947:                     if ($registered) {
 5948:                         $output .= &mt('Must be registered in course');
 5949:                     } else {
 5950:                         $output .= &mt('No requirement');
 5951:                     }
 5952:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 5953:                     next;
 5954:                 }
 5955:                 if ($registered) {
 5956:                     $regon = ' checked="checked" ';
 5957:                     $regoff = '';
 5958:                 } else {
 5959:                     $regon = '';
 5960:                     $regoff = ' checked="checked" ';
 5961:                 }
 5962:                 $output .= '<label>'.
 5963:                            '<input type="radio" name="selfenroll_registered" value="1"'.$regon.$disabled.' />'.
 5964:                            &mt('Yes').'</label>&nbsp;&nbsp;<label>'.
 5965:                            '<input type="radio" name="selfenroll_registered" value="0"'.$regoff.$disabled.' />'.
 5966:                            &mt('No').'</label>';
 5967:             } elsif ($item eq 'enroll_dates') {
 5968:                 my ($starttime,$endtime);
 5969:                 if (ref($currsettings) eq 'HASH') {
 5970:                     $starttime = $currsettings->{'selfenroll_start_date'};
 5971:                     $endtime = $currsettings->{'selfenroll_end_date'};
 5972:                     if ($starttime eq '') {
 5973:                         $starttime = $currsettings->{'default_enrollment_start_date'};
 5974:                     }
 5975:                     if ($endtime eq '') {
 5976:                         $endtime = $currsettings->{'default_enrollment_end_date'};
 5977:                     }
 5978:                 }
 5979:                 if ($noedit{$item}) {
 5980:                     $output .= &mt('From: [_1], to: [_2]',&Apache::lonlocal::locallocaltime($starttime),
 5981:                                                           &Apache::lonlocal::locallocaltime($endtime));
 5982:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 5983:                     next;
 5984:                 }
 5985:                 my $startform =
 5986:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_start_date',$starttime,
 5987:                                       $disabled,undef,undef,undef,undef,undef,undef,$nolink);
 5988:                 my $endform =
 5989:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_end_date',$endtime,
 5990:                                       $disabled,undef,undef,undef,undef,undef,undef,$nolink);
 5991:                 $output .= &selfenroll_date_forms($startform,$endform);
 5992:             } elsif ($item eq 'access_dates') {
 5993:                 my ($starttime,$endtime);
 5994:                 if (ref($currsettings) eq 'HASH') {
 5995:                     $starttime = $currsettings->{'selfenroll_start_access'};
 5996:                     $endtime = $currsettings->{'selfenroll_end_access'};
 5997:                     if ($starttime eq '') {
 5998:                         $starttime = $currsettings->{'default_enrollment_start_date'};
 5999:                     }
 6000:                     if ($endtime eq '') {
 6001:                         $endtime = $currsettings->{'default_enrollment_end_date'};
 6002:                     }
 6003:                 }
 6004:                 if ($noedit{$item}) {
 6005:                     $output .= &mt('From: [_1], to: [_2]',&Apache::lonlocal::locallocaltime($starttime),
 6006:                                                           &Apache::lonlocal::locallocaltime($endtime));
 6007:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 6008:                     next;
 6009:                 }
 6010:                 my $startform =
 6011:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_start_access',$starttime,
 6012:                                       $disabled,undef,undef,undef,undef,undef,undef,$nolink);
 6013:                 my $endform =
 6014:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_end_access',$endtime,
 6015:                                       $disabled,undef,undef,undef,undef,undef,undef,$nolink);
 6016:                 $output .= &selfenroll_date_forms($startform,$endform);
 6017:             } elsif ($item eq 'section') {
 6018:                 my $currsec;
 6019:                 if (ref($currsettings) eq 'HASH') {
 6020:                     $currsec = $currsettings->{'selfenroll_section'};
 6021:                 }
 6022:                 my %sections_count = &Apache::loncommon::get_sections($cdom,$cnum);
 6023:                 my $newsecval;
 6024:                 if ($currsec ne 'none' && $currsec ne '') {
 6025:                     if (!defined($sections_count{$currsec})) {
 6026:                         $newsecval = $currsec;
 6027:                     }
 6028:                 }
 6029:                 if ($noedit{$item}) {
 6030:                     if ($currsec ne '') {
 6031:                         $output .= $currsec;
 6032:                     } else {
 6033:                         $output .= &mt('No specific section');
 6034:                     }
 6035:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 6036:                     next;
 6037:                 }
 6038:                 my $sections_select = 
 6039:                     &Apache::lonuserutils::course_sections(\%sections_count,'st',$currsec,$disabled);
 6040:                 $output .= '<table class="LC_createuser">'."\n".
 6041:                            '<tr class="LC_section_row">'."\n".
 6042:                            '<td align="center">'.&mt('Existing sections')."\n".
 6043:                            '<br />'.$sections_select.'</td><td align="center">'.
 6044:                            &mt('New section').'<br />'."\n".
 6045:                            '<input type="text" name="newsec" size="15" value="'.$newsecval.'"'.$disabled.' />'."\n".
 6046:                            '<input type="hidden" name="sections" value="" />'."\n".
 6047:                            '</td></tr></table>'."\n";
 6048:             } elsif ($item eq 'approval') {
 6049:                 my ($currnotified,$currapproval,%appchecked);
 6050:                 my %selfdescs = &Apache::lonuserutils::selfenroll_default_descs();
 6051:                 if (ref($currsettings) eq 'HASH') {
 6052:                     $currnotified = $currsettings->{'selfenroll_notifylist'};
 6053:                     $currapproval = $currsettings->{'selfenroll_approval'};
 6054:                 }
 6055:                 if ($currapproval !~ /^[012]$/) {
 6056:                     $currapproval = 0;
 6057:                 }
 6058:                 if ($noedit{$item}) {
 6059:                     $output .=  $selfdescs{'approval'}{$currapproval}.
 6060:                                 '<br />'.&mt('(Set by Domain Coordinator)');
 6061:                     next;
 6062:                 }
 6063:                 $appchecked{$currapproval} = ' checked="checked"';
 6064:                 for my $i (0..2) {
 6065:                     $output .= '<label>'.
 6066:                                '<input type="radio" name="selfenroll_approval" value="'.$i.'"'.
 6067:                                $appchecked{$i}.' onclick="toggleNotify();"'.$disabled.' />'.
 6068:                                $selfdescs{'approval'}{$i}.'</label>'.('&nbsp;'x2);
 6069:                 }
 6070:                 my %advhash = &Apache::lonnet::get_course_adv_roles($cid,1);
 6071:                 my (@ccs,%notified);
 6072:                 my $ccrole = 'cc';
 6073:                 if ($crstype eq 'Community') {
 6074:                     $ccrole = 'co';
 6075:                 }
 6076:                 if ($advhash{$ccrole}) {
 6077:                     @ccs = split(/,/,$advhash{$ccrole});
 6078:                 }
 6079:                 if ($currnotified) {
 6080:                     foreach my $current (split(/,/,$currnotified)) {
 6081:                         $notified{$current} = 1;
 6082:                         if (!grep(/^\Q$current\E$/,@ccs)) {
 6083:                             push(@ccs,$current);
 6084:                         }
 6085:                     }
 6086:                 }
 6087:                 if (@ccs) {
 6088:                     my $style;
 6089:                     unless ($currapproval) {
 6090:                         $style = ' style="display: none;"'; 
 6091:                     }
 6092:                     $output .= '<br /><div id="notified"'.$style.'>'.
 6093:                                &mt('Personnel to be notified when an enrollment request needs approval, or has been approved:').'&nbsp;'.
 6094:                                &Apache::loncommon::start_data_table().
 6095:                                &Apache::loncommon::start_data_table_row();
 6096:                     my $count = 0;
 6097:                     my $numcols = 4;
 6098:                     foreach my $cc (sort(@ccs)) {
 6099:                         my $notifyon;
 6100:                         my ($ccuname,$ccudom) = split(/:/,$cc);
 6101:                         if ($notified{$cc}) {
 6102:                             $notifyon = ' checked="checked" ';
 6103:                         }
 6104:                         if ($count && !$count%$numcols) {
 6105:                             $output .= &Apache::loncommon::end_data_table_row().
 6106:                                        &Apache::loncommon::start_data_table_row()
 6107:                         }
 6108:                         $output .= '<td><span class="LC_nobreak"><label>'.
 6109:                                    '<input type="checkbox" name="selfenroll_notify"'.$notifyon.' value="'.$cc.'"'.$disabled.' />'.
 6110:                                    &Apache::loncommon::plainname($ccuname,$ccudom).
 6111:                                    '</label></span></td>';
 6112:                         $count ++;
 6113:                     }
 6114:                     my $rem = $count%$numcols;
 6115:                     if ($rem) {
 6116:                         my $emptycols = $numcols - $rem;
 6117:                         for (my $i=0; $i<$emptycols; $i++) { 
 6118:                             $output .= '<td>&nbsp;</td>';
 6119:                         }
 6120:                     }
 6121:                     $output .= &Apache::loncommon::end_data_table_row().
 6122:                                &Apache::loncommon::end_data_table().
 6123:                                '</div>';
 6124:                 }
 6125:             } elsif ($item eq 'limit') {
 6126:                 my ($crslimit,$selflimit,$nolimit,$currlim,$currcap);
 6127:                 if (ref($currsettings) eq 'HASH') {
 6128:                     $currlim = $currsettings->{'selfenroll_limit'};
 6129:                     $currcap = $currsettings->{'selfenroll_cap'};
 6130:                 }
 6131:                 if ($noedit{$item}) {
 6132:                     if (($currlim eq 'allstudents') || ($currlim eq 'selfenrolled')) {
 6133:                         if ($currlim eq 'allstudents') {
 6134:                             $output .= &mt('Limit by total students');
 6135:                         } elsif ($currlim eq 'selfenrolled') {
 6136:                             $output .= &mt('Limit by total self-enrolled students');
 6137:                         }
 6138:                         $output .= ' '.&mt('Maximum: [_1]',$currcap).
 6139:                                    '<br />'.&mt('(Set by Domain Coordinator)');
 6140:                     } else {
 6141:                         $output .= &mt('No limit').'<br />'.&mt('(Set by Domain Coordinator)');
 6142:                     }
 6143:                     next;
 6144:                 }
 6145:                 if ($currlim eq 'allstudents') {
 6146:                     $crslimit = ' checked="checked" ';
 6147:                     $selflimit = ' ';
 6148:                     $nolimit = ' ';
 6149:                 } elsif ($currlim eq 'selfenrolled') {
 6150:                     $crslimit = ' ';
 6151:                     $selflimit = ' checked="checked" ';
 6152:                     $nolimit = ' '; 
 6153:                 } else {
 6154:                     $crslimit = ' ';
 6155:                     $selflimit = ' ';
 6156:                     $nolimit = ' checked="checked" ';
 6157:                 }
 6158:                 $output .= '<table><tr><td><label>'.
 6159:                            '<input type="radio" name="selfenroll_limit" value="none"'.$nolimit.$disabled.'/>'.
 6160:                            &mt('No limit').'</label></td><td><label>'.
 6161:                            '<input type="radio" name="selfenroll_limit" value="allstudents"'.$crslimit.$disabled.'/>'.
 6162:                            &mt('Limit by total students').'</label></td><td><label>'.
 6163:                            '<input type="radio" name="selfenroll_limit" value="selfenrolled"'.$selflimit.$disabled.'/>'.
 6164:                            &mt('Limit by total self-enrolled students').
 6165:                            '</td></tr><tr>'.
 6166:                            '<td>&nbsp;</td><td colspan="2"><span class="LC_nobreak">'.
 6167:                            ('&nbsp;'x3).&mt('Maximum number allowed: ').
 6168:                            '<input type="text" name="selfenroll_cap" size = "5" value="'.$currcap.'"'.$disabled.' /></td></tr></table>';
 6169:             }
 6170:             $output .= &Apache::lonhtmlcommon::row_closure(1);
 6171:         }
 6172:     }
 6173:     $output .= &Apache::lonhtmlcommon::end_pick_box().'<br />';
 6174:     unless ($readonly) {
 6175:         $output .= '<input type="button" name="selfenrollconf" value="'
 6176:                    .&mt('Save').'" onclick="validate_types(this.form);" />';
 6177:     }
 6178:     $output .= '<input type="hidden" name="action" value="selfenroll" />'
 6179:               .'<input type="hidden" name="state" value="done" />'."\n"
 6180:               .$additional.'</form>';
 6181:     $r->print($output);
 6182:     return;
 6183: }
 6184: 
 6185: sub get_noedit_fields {
 6186:     my ($cdom,$cnum,$crstype,$row) = @_;
 6187:     my %noedit;
 6188:     if (ref($row) eq 'ARRAY') {
 6189:         my %settings = &Apache::lonnet::get('environment',['internal.coursecode','internal.textbook',
 6190:                                                            'internal.selfenrollmgrdc',
 6191:                                                            'internal.selfenrollmgrcc'],$cdom,$cnum);
 6192:         my $type = &Apache::lonuserutils::get_extended_type($cdom,$cnum,$crstype,\%settings);
 6193:         my (%specific_managebydc,%specific_managebycc,%default_managebydc);
 6194:         map { $specific_managebydc{$_} = 1; } (split(/,/,$settings{'internal.selfenrollmgrdc'}));
 6195:         map { $specific_managebycc{$_} = 1; } (split(/,/,$settings{'internal.selfenrollmgrcc'}));
 6196:         my %domdefaults = &Apache::lonnet::get_domain_defaults($cdom);
 6197:         map { $default_managebydc{$_} = 1; } (split(/,/,$domdefaults{$type.'selfenrolladmdc'}));
 6198: 
 6199:         foreach my $item (@{$row}) {
 6200:             next if ($specific_managebycc{$item});
 6201:             if (($specific_managebydc{$item}) || ($default_managebydc{$item})) {
 6202:                 $noedit{$item} = 1;
 6203:             }
 6204:         }
 6205:     }
 6206:     return %noedit;
 6207: } 
 6208: 
 6209: sub visible_in_stdcat {
 6210:     my ($cdom,$cnum,$domconf) = @_;
 6211:     my ($cathash,%settable,@vismsgs,$cansetvis,$visible);
 6212:     unless (ref($domconf) eq 'HASH') {
 6213:         return ($visible,$cansetvis,\@vismsgs);
 6214:     }
 6215:     if (ref($domconf->{'coursecategories'}) eq 'HASH') {
 6216:         if ($domconf->{'coursecategories'}{'togglecats'} eq 'crs') {
 6217:             $settable{'togglecats'} = 1;
 6218:         }
 6219:         if ($domconf->{'coursecategories'}{'categorize'} eq 'crs') {
 6220:             $settable{'categorize'} = 1;
 6221:         }
 6222:         $cathash = $domconf->{'coursecategories'}{'cats'};
 6223:     }
 6224:     if ($settable{'togglecats'} && $settable{'categorize'}) {
 6225:         $cansetvis = &mt('You are able to both assign a course category and choose to exclude this course from the catalog.');   
 6226:     } elsif ($settable{'togglecats'}) {
 6227:         $cansetvis = &mt('You are able to choose to exclude this course from the catalog, but only a Domain Coordinator may assign a course category.'); 
 6228:     } elsif ($settable{'categorize'}) {
 6229:         $cansetvis = &mt('You may assign a course category, but only a Domain Coordinator may choose to exclude this course from the catalog.');  
 6230:     } else {
 6231:         $cansetvis = &mt('Only a Domain Coordinator may assign a course category or choose to exclude this course from the catalog.'); 
 6232:     }
 6233:      
 6234:     my %currsettings =
 6235:         &Apache::lonnet::get('environment',['hidefromcat','categories','internal.coursecode'],
 6236:                              $cdom,$cnum);
 6237:     $visible = 0;
 6238:     if ($currsettings{'internal.coursecode'} ne '') {
 6239:         if (ref($domconf->{'coursecategories'}) eq 'HASH') {
 6240:             $cathash = $domconf->{'coursecategories'}{'cats'};
 6241:             if (ref($cathash) eq 'HASH') {
 6242:                 if ($cathash->{'instcode::0'} eq '') {
 6243:                     push(@vismsgs,'dc_addinst'); 
 6244:                 } else {
 6245:                     $visible = 1;
 6246:                 }
 6247:             } else {
 6248:                 $visible = 1;
 6249:             }
 6250:         } else {
 6251:             $visible = 1;
 6252:         }
 6253:     } else {
 6254:         if (ref($cathash) eq 'HASH') {
 6255:             if ($cathash->{'instcode::0'} ne '') {
 6256:                 push(@vismsgs,'dc_instcode');
 6257:             }
 6258:         } else {
 6259:             push(@vismsgs,'dc_instcode');
 6260:         }
 6261:     }
 6262:     if ($currsettings{'categories'} ne '') {
 6263:         my $cathash;
 6264:         if (ref($domconf->{'coursecategories'}) eq 'HASH') {
 6265:             $cathash = $domconf->{'coursecategories'}{'cats'};
 6266:             if (ref($cathash) eq 'HASH') {
 6267:                 if (keys(%{$cathash}) == 0) {
 6268:                     push(@vismsgs,'dc_catalog');
 6269:                 } elsif ((keys(%{$cathash}) == 1) && ($cathash->{'instcode::0'} ne '')) {
 6270:                     push(@vismsgs,'dc_categories');
 6271:                 } else {
 6272:                     my @currcategories = split('&',$currsettings{'categories'});
 6273:                     my $matched = 0;
 6274:                     foreach my $cat (@currcategories) {
 6275:                         if ($cathash->{$cat} ne '') {
 6276:                             $visible = 1;
 6277:                             $matched = 1;
 6278:                             last;
 6279:                         }
 6280:                     }
 6281:                     if (!$matched) {
 6282:                         if ($settable{'categorize'}) { 
 6283:                             push(@vismsgs,'chgcat');
 6284:                         } else {
 6285:                             push(@vismsgs,'dc_chgcat');
 6286:                         }
 6287:                     }
 6288:                 }
 6289:             }
 6290:         }
 6291:     } else {
 6292:         if (ref($cathash) eq 'HASH') {
 6293:             if ((keys(%{$cathash}) > 1) || 
 6294:                 (keys(%{$cathash}) == 1) && ($cathash->{'instcode::0'} eq '')) {
 6295:                 if ($settable{'categorize'}) {
 6296:                     push(@vismsgs,'addcat');
 6297:                 } else {
 6298:                     push(@vismsgs,'dc_addcat');
 6299:                 }
 6300:             }
 6301:         }
 6302:     }
 6303:     if ($currsettings{'hidefromcat'} eq 'yes') {
 6304:         $visible = 0;
 6305:         if ($settable{'togglecats'}) {
 6306:             unshift(@vismsgs,'unhide');
 6307:         } else {
 6308:             unshift(@vismsgs,'dc_unhide')
 6309:         }
 6310:     }
 6311:     return ($visible,$cansetvis,\@vismsgs);
 6312: }
 6313: 
 6314: sub cat_visibility {
 6315:     my %visactions = &Apache::lonlocal::texthash(
 6316:                    vis => 'This course/community currently appears in the Course/Community Catalog for this domain.',
 6317:                    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.',
 6318:                    miss => 'This course/community does not currently appear in the Course/Community Catalog for this domain.',
 6319:                    none => 'Display of a course catalog is disabled for this domain.',
 6320:                    yous => 'You should remedy this if you plan to allow self-enrollment, otherwise students will have difficulty finding this course.',
 6321:                    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.',
 6322:                    make => 'Make any changes to self-enrollment settings below, click "Save", then take action to include the course in the Catalog:',
 6323:                    take => 'Take the following action to ensure the course appears in the Catalog:',
 6324:                    dc_chgconf => 'Ask a domain coordinator to change the Catalog type for this domain.',
 6325:                    dc_setcode => 'Ask a domain coordinator to assign a six character code to the course',
 6326:                    dc_unhide  => 'Ask a domain coordinator to change the "Exclude from course catalog" setting.',
 6327:                    dc_addinst => 'Ask a domain coordinator to enable display the catalog of "Official courses (with institutional codes)".',
 6328:                    dc_instcode => 'Ask a domain coordinator to assign an institutional code (if this is an official course).',
 6329:                    dc_catalog  => 'Ask a domain coordinator to enable or create at least one course category in the domain.',
 6330:                    dc_categories => 'Ask a domain coordinator to create a hierarchy of categories and sub categories for courses in the domain.',
 6331:                    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',
 6332:                    dc_addcat => 'Ask a domain coordinator to assign a category to the course.',
 6333:     );
 6334:     $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>"');
 6335:     $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>"');
 6336:     $visactions{'addcat'} = &mt('Use [_1]Categorize course[_2] to assign a category to the course.','"<a href="/adm/courseprefs?phase=display&actions=courseinfo">','</a>"');
 6337:     return \%visactions;
 6338: }
 6339: 
 6340: sub new_selfenroll_dom_row {
 6341:     my ($newdom,$num) = @_;
 6342:     my $domdesc = &Apache::lonnet::domain($newdom);
 6343:     my $output;
 6344:     if ($domdesc ne '') {
 6345:         $output .= &Apache::loncommon::start_data_table_row()
 6346:                    .'<td valign="top"><span class="LC_nobreak">'.&mt('Domain:').'&nbsp;<b>'.$domdesc
 6347:                    .' ('.$newdom.')</b><input type="hidden" name="selfenroll_dom_'.$num
 6348:                    .'" value="'.$newdom.'" /></span><br />'
 6349:                    .'<span class="LC_nobreak"><label><input type="checkbox" '
 6350:                    .'name="selfenroll_activate" value="'.$num.'" '
 6351:                    .'onchange="javascript:update_types('
 6352:                    ."'selfenroll_activate','$num'".');" />'
 6353:                    .&mt('Activate').'</label></span></td>';
 6354:         my @currinsttypes;
 6355:         $output .= '<td>'.&mt('User types:').'<br />'
 6356:                    .&selfenroll_inst_types($num,$newdom,\@currinsttypes).'</td>'
 6357:                    .&Apache::loncommon::end_data_table_row();
 6358:     }
 6359:     return $output;
 6360: }
 6361: 
 6362: sub selfenroll_inst_types {
 6363:     my ($num,$currdom,$currinsttypes,$readonly) = @_;
 6364:     my $output;
 6365:     my $numinrow = 4;
 6366:     my $count = 0;
 6367:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($currdom);
 6368:     my $othervalue = 'any';
 6369:     my $disabled;
 6370:     if ($readonly) {
 6371:         $disabled = ' disabled="disabled"';
 6372:     }
 6373:     if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 6374:         if (keys(%{$usertypes}) > 0) {
 6375:             $othervalue = 'other';
 6376:         }
 6377:         $output .= '<table><tr>';
 6378:         foreach my $type (@{$types}) {
 6379:             if (($count > 0) && ($count%$numinrow == 0)) {
 6380:                 $output .= '</tr><tr>';
 6381:             }
 6382:             if (defined($usertypes->{$type})) {
 6383:                 my $esc_type = &escape($type);
 6384:                 $output .= '<td><span class="LC_nobreak"><label><input type = "checkbox" value="'.
 6385:                            $esc_type.'" ';
 6386:                 if (ref($currinsttypes) eq 'ARRAY') {
 6387:                     if (@{$currinsttypes} > 0) {
 6388:                         if (grep(/^any$/,@{$currinsttypes})) {
 6389:                             $output .= 'checked="checked"';
 6390:                         } elsif (grep(/^\Q$esc_type\E$/,@{$currinsttypes})) {
 6391:                             $output .= 'checked="checked"';
 6392:                         }
 6393:                     } else {
 6394:                         $output .= 'checked="checked"';
 6395:                     }
 6396:                 }
 6397:                 $output .= ' name="selfenroll_types_'.$num.'"'.$disabled.' />'.$usertypes->{$type}.'</label></span></td>';
 6398:             }
 6399:             $count ++;
 6400:         }
 6401:         if (($count > 0) && ($count%$numinrow == 0)) {
 6402:             $output .= '</tr><tr>';
 6403:         }
 6404:         $output .= '<td><span class="LC_nobreak"><label><input type = "checkbox" value="'.$othervalue.'"';
 6405:         if (ref($currinsttypes) eq 'ARRAY') {
 6406:             if (@{$currinsttypes} > 0) {
 6407:                 if (grep(/^any$/,@{$currinsttypes})) { 
 6408:                     $output .= ' checked="checked"';
 6409:                 } elsif ($othervalue eq 'other') {
 6410:                     if (grep(/^\Q$othervalue\E$/,@{$currinsttypes})) {
 6411:                         $output .= ' checked="checked"';
 6412:                     }
 6413:                 }
 6414:             } else {
 6415:                 $output .= ' checked="checked"';
 6416:             }
 6417:         } else {
 6418:             $output .= ' checked="checked"';
 6419:         }
 6420:         $output .= ' name="selfenroll_types_'.$num.'"'.$disabled.' />'.$othertitle.'</label></span></td></tr></table>';
 6421:     }
 6422:     return $output;
 6423: }
 6424: 
 6425: sub selfenroll_date_forms {
 6426:     my ($startform,$endform) = @_;
 6427:     my $output .= &Apache::lonhtmlcommon::start_pick_box()."\n".
 6428:                   &Apache::lonhtmlcommon::row_title(&mt('Start date'),
 6429:                                                     'LC_oddrow_value')."\n".
 6430:                   $startform."\n".
 6431:                   &Apache::lonhtmlcommon::row_closure(1).
 6432:                   &Apache::lonhtmlcommon::row_title(&mt('End date'),
 6433:                                                    'LC_oddrow_value')."\n".
 6434:                   $endform."\n".
 6435:                   &Apache::lonhtmlcommon::row_closure(1).
 6436:                   &Apache::lonhtmlcommon::end_pick_box();
 6437:     return $output;
 6438: }
 6439: 
 6440: sub print_userchangelogs_display {
 6441:     my ($r,$context,$permission,$brcrum) = @_;
 6442:     my $formname = 'rolelog';
 6443:     my ($username,$domain,$crstype,$viewablesec,%roleslog);
 6444:     if ($context eq 'domain') {
 6445:         $domain = $env{'request.role.domain'};
 6446:         %roleslog=&Apache::lonnet::dump_dom('nohist_rolelog',$domain);
 6447:     } else {
 6448:         if ($context eq 'course') { 
 6449:             $domain = $env{'course.'.$env{'request.course.id'}.'.domain'};
 6450:             $username = $env{'course.'.$env{'request.course.id'}.'.num'};
 6451:             $crstype = &Apache::loncommon::course_type();
 6452:             $viewablesec = &Apache::lonuserutils::viewable_section($permission);
 6453:             my %saveable_parameters = ('show' => 'scalar',);
 6454:             &Apache::loncommon::store_course_settings('roles_log',
 6455:                                                       \%saveable_parameters);
 6456:             &Apache::loncommon::restore_course_settings('roles_log',
 6457:                                                         \%saveable_parameters);
 6458:         } elsif ($context eq 'author') {
 6459:             $domain = $env{'user.domain'}; 
 6460:             if ($env{'request.role'} =~ m{^au\./\Q$domain\E/$}) {
 6461:                 $username = $env{'user.name'};
 6462:             } else {
 6463:                 undef($domain);
 6464:             }
 6465:         }
 6466:         if ($domain ne '' && $username ne '') { 
 6467:             %roleslog=&Apache::lonnet::dump('nohist_rolelog',$domain,$username);
 6468:         }
 6469:     }
 6470:     if ((keys(%roleslog))[0]=~/^error\:/) { undef(%roleslog); }
 6471: 
 6472:     my $helpitem;
 6473:     if ($context eq 'course') {
 6474:         $helpitem = 'Course_User_Logs';
 6475:     }
 6476:     push (@{$brcrum},
 6477:              {href => '/adm/createuser?action=changelogs',
 6478:               text => 'User Management Logs',
 6479:               help => $helpitem});
 6480:     my $bread_crumbs_component = 'User Changes';
 6481:     my $args = { bread_crumbs           => $brcrum,
 6482:                  bread_crumbs_component => $bread_crumbs_component};
 6483: 
 6484:     # Create navigation javascript
 6485:     my $jsnav = &userlogdisplay_js($formname);
 6486: 
 6487:     my $jscript = (<<ENDSCRIPT);
 6488: <script type="text/javascript">
 6489: // <![CDATA[
 6490: $jsnav
 6491: // ]]>
 6492: </script>
 6493: ENDSCRIPT
 6494: 
 6495:     # print page header
 6496:     $r->print(&header($jscript,$args));
 6497: 
 6498:     # set defaults
 6499:     my $now = time();
 6500:     my $defstart = $now - (7*24*3600); #7 days ago 
 6501:     my %defaults = (
 6502:                      page               => '1',
 6503:                      show               => '10',
 6504:                      role               => 'any',
 6505:                      chgcontext         => 'any',
 6506:                      rolelog_start_date => $defstart,
 6507:                      rolelog_end_date   => $now,
 6508:                    );
 6509:     my $more_records = 0;
 6510: 
 6511:     # set current
 6512:     my %curr;
 6513:     foreach my $item ('show','page','role','chgcontext') {
 6514:         $curr{$item} = $env{'form.'.$item};
 6515:     }
 6516:     my ($startdate,$enddate) = 
 6517:         &Apache::lonuserutils::get_dates_from_form('rolelog_start_date','rolelog_end_date');
 6518:     $curr{'rolelog_start_date'} = $startdate;
 6519:     $curr{'rolelog_end_date'} = $enddate;
 6520:     foreach my $key (keys(%defaults)) {
 6521:         if ($curr{$key} eq '') {
 6522:             $curr{$key} = $defaults{$key};
 6523:         }
 6524:     }
 6525:     my (%whodunit,%changed,$version);
 6526:     ($version) = ($r->dir_config('lonVersion') =~ /^([\d\.]+)\-/);
 6527:     my ($minshown,$maxshown);
 6528:     $minshown = 1;
 6529:     my $count = 0;
 6530:     if ($curr{'show'} =~ /\D/) {
 6531:         $curr{'page'} = 1;
 6532:     } else {
 6533:         $maxshown = $curr{'page'} * $curr{'show'};
 6534:         if ($curr{'page'} > 1) {
 6535:             $minshown = 1 + ($curr{'page'} - 1) * $curr{'show'};
 6536:         }
 6537:     }
 6538: 
 6539:     # Form Header
 6540:     $r->print('<form action="/adm/createuser" method="post" name="'.$formname.'">'.
 6541:               &role_display_filter($context,$formname,$domain,$username,\%curr,
 6542:                                    $version,$crstype));
 6543: 
 6544:     my $showntableheader = 0;
 6545: 
 6546:     # Table Header
 6547:     my $tableheader = 
 6548:         &Apache::loncommon::start_data_table_header_row()
 6549:        .'<th>&nbsp;</th>'
 6550:        .'<th>'.&mt('When').'</th>'
 6551:        .'<th>'.&mt('Who made the change').'</th>'
 6552:        .'<th>'.&mt('Changed User').'</th>'
 6553:        .'<th>'.&mt('Role').'</th>';
 6554: 
 6555:     if ($context eq 'course') {
 6556:         $tableheader .= '<th>'.&mt('Section').'</th>';
 6557:     }
 6558:     $tableheader .=
 6559:         '<th>'.&mt('Context').'</th>'
 6560:        .'<th>'.&mt('Start').'</th>'
 6561:        .'<th>'.&mt('End').'</th>'
 6562:        .&Apache::loncommon::end_data_table_header_row();
 6563: 
 6564:     # Display user change log data
 6565:     foreach my $id (sort { $roleslog{$b}{'exe_time'}<=>$roleslog{$a}{'exe_time'} } (keys(%roleslog))) {
 6566:         next if (($roleslog{$id}{'exe_time'} < $curr{'rolelog_start_date'}) ||
 6567:                  ($roleslog{$id}{'exe_time'} > $curr{'rolelog_end_date'}));
 6568:         if ($curr{'show'} !~ /\D/) {
 6569:             if ($count >= $curr{'page'} * $curr{'show'}) {
 6570:                 $more_records = 1;
 6571:                 last;
 6572:             }
 6573:         }
 6574:         if ($curr{'role'} ne 'any') {
 6575:             next if ($roleslog{$id}{'logentry'}{'role'} ne $curr{'role'}); 
 6576:         }
 6577:         if ($curr{'chgcontext'} ne 'any') {
 6578:             if ($curr{'chgcontext'} eq 'selfenroll') {
 6579:                 next if (!$roleslog{$id}{'logentry'}{'selfenroll'});
 6580:             } else {
 6581:                 next if ($roleslog{$id}{'logentry'}{'context'} ne $curr{'chgcontext'});
 6582:             }
 6583:         }
 6584:         if (($context eq 'course') && ($viewablesec ne '')) {
 6585:             next if ($roleslog{$id}{'logentry'}{'section'} ne $viewablesec);
 6586:         }
 6587:         $count ++;
 6588:         next if ($count < $minshown);
 6589:         unless ($showntableheader) {
 6590:             $r->print(&Apache::loncommon::start_data_table()
 6591:                      .$tableheader);
 6592:             $r->rflush();
 6593:             $showntableheader = 1;
 6594:         }
 6595:         if ($whodunit{$roleslog{$id}{'exe_uname'}.':'.$roleslog{$id}{'exe_udom'}} eq '') {
 6596:             $whodunit{$roleslog{$id}{'exe_uname'}.':'.$roleslog{$id}{'exe_udom'}} =
 6597:                 &Apache::loncommon::plainname($roleslog{$id}{'exe_uname'},$roleslog{$id}{'exe_udom'});
 6598:         }
 6599:         if ($changed{$roleslog{$id}{'uname'}.':'.$roleslog{$id}{'udom'}} eq '') {
 6600:             $changed{$roleslog{$id}{'uname'}.':'.$roleslog{$id}{'udom'}} =
 6601:                 &Apache::loncommon::plainname($roleslog{$id}{'uname'},$roleslog{$id}{'udom'});
 6602:         }
 6603:         my $sec = $roleslog{$id}{'logentry'}{'section'};
 6604:         if ($sec eq '') {
 6605:             $sec = &mt('None');
 6606:         }
 6607:         my ($rolestart,$roleend);
 6608:         if ($roleslog{$id}{'delflag'}) {
 6609:             $rolestart = &mt('deleted');
 6610:             $roleend = &mt('deleted');
 6611:         } else {
 6612:             $rolestart = $roleslog{$id}{'logentry'}{'start'};
 6613:             $roleend = $roleslog{$id}{'logentry'}{'end'};
 6614:             if ($rolestart eq '' || $rolestart == 0) {
 6615:                 $rolestart = &mt('No start date'); 
 6616:             } else {
 6617:                 $rolestart = &Apache::lonlocal::locallocaltime($rolestart);
 6618:             }
 6619:             if ($roleend eq '' || $roleend == 0) { 
 6620:                 $roleend = &mt('No end date');
 6621:             } else {
 6622:                 $roleend = &Apache::lonlocal::locallocaltime($roleend);
 6623:             }
 6624:         }
 6625:         my $chgcontext = $roleslog{$id}{'logentry'}{'context'};
 6626:         if ($roleslog{$id}{'logentry'}{'selfenroll'}) {
 6627:             $chgcontext = 'selfenroll';
 6628:         }
 6629:         my %lt = &rolechg_contexts($context,$crstype);
 6630:         if ($chgcontext ne '' && $lt{$chgcontext} ne '') {
 6631:             $chgcontext = $lt{$chgcontext};
 6632:         }
 6633:         $r->print(
 6634:             &Apache::loncommon::start_data_table_row()
 6635:            .'<td>'.$count.'</td>'
 6636:            .'<td>'.&Apache::lonlocal::locallocaltime($roleslog{$id}{'exe_time'}).'</td>'
 6637:            .'<td>'.$whodunit{$roleslog{$id}{'exe_uname'}.':'.$roleslog{$id}{'exe_udom'}}.'</td>'
 6638:            .'<td>'.$changed{$roleslog{$id}{'uname'}.':'.$roleslog{$id}{'udom'}}.'</td>'
 6639:            .'<td>'.&Apache::lonnet::plaintext($roleslog{$id}{'logentry'}{'role'},$crstype).'</td>');
 6640:         if ($context eq 'course') { 
 6641:             $r->print('<td>'.$sec.'</td>');
 6642:         }
 6643:         $r->print(
 6644:             '<td>'.$chgcontext.'</td>'
 6645:            .'<td>'.$rolestart.'</td>'
 6646:            .'<td>'.$roleend.'</td>'
 6647:            .&Apache::loncommon::end_data_table_row()."\n");
 6648:     }
 6649: 
 6650:     if ($showntableheader) { # Table footer, if content displayed above
 6651:         $r->print(&Apache::loncommon::end_data_table().
 6652:                   &userlogdisplay_navlinks(\%curr,$more_records));
 6653:     } else { # No content displayed above
 6654:         $r->print('<p class="LC_info">'
 6655:                  .&mt('There are no records to display.')
 6656:                  .'</p>'
 6657:         );
 6658:     }
 6659: 
 6660:     # Form Footer
 6661:     $r->print( 
 6662:         '<input type="hidden" name="page" value="'.$curr{'page'}.'" />'
 6663:        .'<input type="hidden" name="action" value="changelogs" />'
 6664:        .'</form>');
 6665:     return;
 6666: }
 6667: 
 6668: sub print_useraccesslogs_display {
 6669:     my ($r,$uname,$udom,$permission,$brcrum) = @_;
 6670:     my $formname = 'accesslog';
 6671:     my $form = 'document.accesslog';
 6672: 
 6673: # set breadcrumbs
 6674:     my %breadcrumb_text = &singleuser_breadcrumb('','domain',$udom);
 6675:     push (@{$brcrum},
 6676:         {href => "javascript:backPage($form)",
 6677:          text => $breadcrumb_text{'search'}});
 6678:     my (@prevphases,$prevphasestr);
 6679:     if ($env{'form.prevphases'}) {
 6680:         @prevphases = split(/,/,$env{'form.prevphases'});
 6681:         $prevphasestr = $env{'form.prevphases'};
 6682:     }
 6683:     if (($env{'form.phase'} eq 'userpicked') || (grep(/^userpicked$/,@prevphases))) {
 6684:         push(@{$brcrum},
 6685:               {href => "javascript:backPage($form,'get_user_info','select')",
 6686:                text => $breadcrumb_text{'userpicked'}});
 6687:         if ($env{'form.phase'} eq 'userpicked') {
 6688:             $prevphasestr = 'userpicked';
 6689:         }
 6690:     }
 6691:     push(@{$brcrum},
 6692:              {href => '/adm/createuser?action=accesslogs',
 6693:               text => 'User access logs',
 6694:               help => 'Domain_User_Access_Logs'});
 6695:     my $bread_crumbs_component = 'User Access Logs';
 6696:     my $args = { bread_crumbs           => $brcrum,
 6697:                  bread_crumbs_component => 'User Management'};
 6698:     if ($env{'form.popup'}) {
 6699:         $args->{'no_nav_bar'} = 1;
 6700:     }
 6701: 
 6702: # set javascript
 6703:     my ($jsback,$elements) = &crumb_utilities();
 6704:     my $jsnav = &userlogdisplay_js($formname);
 6705: 
 6706:     my $jscript = (<<ENDSCRIPT);
 6707: <script type="text/javascript">
 6708: // <![CDATA[
 6709: 
 6710: $jsback
 6711: $jsnav
 6712: 
 6713: // ]]>
 6714: </script>
 6715: 
 6716: ENDSCRIPT
 6717: 
 6718: # print page header
 6719:     $r->print(&header($jscript,$args));
 6720: 
 6721: # early out unless log data can be displayed.
 6722:     unless ($permission->{'activity'}) {
 6723:         $r->print('<p class="LC_warning">'
 6724:                  .&mt('You do not have rights to display user access logs.')
 6725:                  .'</p>'
 6726:                  .&earlyout_accesslog_form($formname,$prevphasestr,$udom));
 6727:         return;
 6728:     }
 6729: 
 6730:     unless ($udom eq $env{'request.role.domain'}) {
 6731:         $r->print('<p class="LC_warning">'
 6732:                  .&mt("User's domain must match role's domain")
 6733:                  .'</p>'
 6734:                  .&earlyout_accesslog_form($formname,$prevphasestr,$udom));
 6735:         return;
 6736:     }
 6737: 
 6738:     if (($uname eq '') || ($udom eq '')) {
 6739:         $r->print('<p class="LC_warning">'
 6740:                  .&mt('Invalid username or domain')
 6741:                  .'</p>'
 6742:                  .&earlyout_accesslog_form($formname,$prevphasestr,$udom));
 6743:         return;
 6744:     }
 6745: 
 6746: # set defaults
 6747:     my $now = time();
 6748:     my $defstart = $now - (7*24*3600);
 6749:     my %defaults = (
 6750:                      page                 => '1',
 6751:                      show                 => '10',
 6752:                      activity             => 'any',
 6753:                      accesslog_start_date => $defstart,
 6754:                      accesslog_end_date   => $now,
 6755:                    );
 6756:     my $more_records = 0;
 6757: 
 6758: # set current
 6759:     my %curr;
 6760:     foreach my $item ('show','page','activity') {
 6761:         $curr{$item} = $env{'form.'.$item};
 6762:     }
 6763:     my ($startdate,$enddate) =
 6764:         &Apache::lonuserutils::get_dates_from_form('accesslog_start_date','accesslog_end_date');
 6765:     $curr{'accesslog_start_date'} = $startdate;
 6766:     $curr{'accesslog_end_date'} = $enddate;
 6767:     foreach my $key (keys(%defaults)) {
 6768:         if ($curr{$key} eq '') {
 6769:             $curr{$key} = $defaults{$key};
 6770:         }
 6771:     }
 6772:     my ($minshown,$maxshown);
 6773:     $minshown = 1;
 6774:     my $count = 0;
 6775:     if ($curr{'show'} =~ /\D/) {
 6776:         $curr{'page'} = 1;
 6777:     } else {
 6778:         $maxshown = $curr{'page'} * $curr{'show'};
 6779:         if ($curr{'page'} > 1) {
 6780:             $minshown = 1 + ($curr{'page'} - 1) * $curr{'show'};
 6781:         }
 6782:     }
 6783: 
 6784: # form header
 6785:     $r->print('<form action="/adm/createuser" method="post" name="'.$formname.'">'.
 6786:               &activity_display_filter($formname,\%curr));
 6787: 
 6788:     my $showntableheader = 0;
 6789:     my ($nav_script,$nav_links);
 6790: 
 6791: # table header
 6792:     my $tableheader =
 6793:         &Apache::loncommon::start_data_table_header_row()
 6794:        .'<th>&nbsp;</th>'
 6795:        .'<th>'.&mt('When').'</th>'
 6796:        .'<th>'.&mt('HostID').'</th>'
 6797:        .'<th>'.&mt('Event').'</th>'
 6798:        .'<th>'.&mt('Other data').'</th>'
 6799:        .&Apache::loncommon::end_data_table_header_row();
 6800: 
 6801:     my %filters=(
 6802:         start  => $curr{'accesslog_start_date'},
 6803:         end    => $curr{'accesslog_end_date'},
 6804:         action => $curr{'activity'},
 6805:     );
 6806: 
 6807:     my $reply = &Apache::lonnet::userlog_query($uname,$udom,%filters);
 6808:     unless ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 6809:         my (%courses,%missing);
 6810:         my @results = split(/\&/,$reply);
 6811:         foreach my $item (reverse(@results)) {
 6812:             my ($timestamp,$host,$event) = split(/:/,$item);
 6813:             next unless ($event =~ /^(Log|Role)/);
 6814:             if ($curr{'show'} !~ /\D/) {
 6815:                 if ($count >= $curr{'page'} * $curr{'show'}) {
 6816:                     $more_records = 1;
 6817:                     last;
 6818:                 }
 6819:             }
 6820:             $count ++;
 6821:             next if ($count < $minshown);
 6822:             unless ($showntableheader) {
 6823:                 $r->print($nav_script
 6824:                          .&Apache::loncommon::start_data_table()
 6825:                          .$tableheader);
 6826:                 $r->rflush();
 6827:                 $showntableheader = 1;
 6828:             }
 6829:             my ($shown,$extra);
 6830:             my ($event,$data) = split(/\s+/,&unescape($event));
 6831:             if ($event eq 'Role') {
 6832:                 my ($rolecode,$extent) = split(/\./,$data,2);
 6833:                 next if ($extent eq '');
 6834:                 my ($crstype,$desc,$info);
 6835:                 if ($extent =~ m{^/($match_domain)/($match_courseid)(?:/(\w+)|)$}) {
 6836:                     my ($cdom,$cnum,$sec) = ($1,$2,$3);
 6837:                     my $cid = $cdom.'_'.$cnum;
 6838:                     if (exists($courses{$cid})) {
 6839:                         $crstype = $courses{$cid}{'type'};
 6840:                         $desc = $courses{$cid}{'description'};
 6841:                     } elsif ($missing{$cid}) {
 6842:                         $crstype = 'Course';
 6843:                         $desc = 'Course/Community';
 6844:                     } else {
 6845:                         my %crsinfo = &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 6846:                         if (ref($crsinfo{$cdom.'_'.$cnum}) eq 'HASH') {
 6847:                             $courses{$cid} = $crsinfo{$cid};
 6848:                             $crstype = $crsinfo{$cid}{'type'};
 6849:                             $desc = $crsinfo{$cid}{'description'};
 6850:                         } else {
 6851:                             $missing{$cid} = 1;
 6852:                         }
 6853:                     }
 6854:                     $extra = &mt($crstype).': <a href="/public/'.$cdom.'/'.$cnum.'/syllabus">'.$desc.'</a>';
 6855:                     if ($sec ne '') {
 6856:                        $extra .= ' ('.&mt('Section: [_1]',$sec).')';
 6857:                     }
 6858:                 } elsif ($extent =~ m{^/($match_domain)/($match_username|$)}) {
 6859:                     my ($dom,$name) = ($1,$2);
 6860:                     if ($rolecode eq 'au') {
 6861:                         $extra = '';
 6862:                     } elsif ($rolecode =~ /^(ca|aa)$/) {
 6863:                         $extra = &mt('Authoring Space: [_1]',$name.':'.$dom);
 6864:                     } elsif ($rolecode =~ /^(li|dg|dh|dc|sc)$/) {
 6865:                         $extra = &mt('Domain: [_1]',$dom);
 6866:                     }
 6867:                 }
 6868:                 my $rolename;
 6869:                 if ($rolecode =~ m{^cr/($match_domain)/($match_username)/(\w+)}) {
 6870:                     my $role = $3;
 6871:                     my $owner = "($2:$1)";
 6872:                     if ($2 eq $1.'-domainconfig') {
 6873:                         $owner = '(ad hoc)';
 6874:                     }
 6875:                     $rolename = &mt('Custom role: [_1]',$role.' '.$owner);
 6876:                 } else {
 6877:                     $rolename = &Apache::lonnet::plaintext($rolecode,$crstype);
 6878:                 }
 6879:                 $shown = &mt('Role selection: [_1]',$rolename);
 6880:             } else {
 6881:                 $shown = &mt($event);
 6882:                 if ($data ne '') {
 6883:                    $extra = &mt('Client IP address: [_1]',$data);
 6884:                 }
 6885:             }
 6886:             $r->print(
 6887:             &Apache::loncommon::start_data_table_row()
 6888:            .'<td>'.$count.'</td>'
 6889:            .'<td>'.&Apache::lonlocal::locallocaltime($timestamp).'</td>'
 6890:            .'<td>'.$host.'</td>'
 6891:            .'<td>'.$shown.'</td>'
 6892:            .'<td>'.$extra.'</td>'
 6893:            .&Apache::loncommon::end_data_table_row()."\n");
 6894:         }
 6895:     }
 6896: 
 6897:     if ($showntableheader) { # Table footer, if content displayed above
 6898:         $r->print(&Apache::loncommon::end_data_table().
 6899:                   &userlogdisplay_navlinks(\%curr,$more_records));
 6900:     } else { # No content displayed above
 6901:         $r->print('<p class="LC_info">'
 6902:                  .&mt('There are no records to display.')
 6903:                  .'</p>');
 6904:     }
 6905: 
 6906:     if ($env{'form.popup'} == 1) {
 6907:         $r->print('<input type="hidden" name="popup" value="1" />'."\n");
 6908:     }
 6909: 
 6910:     # Form Footer
 6911:     $r->print(
 6912:         '<input type="hidden" name="currstate" value="" />'
 6913:        .'<input type="hidden" name="accessuname" value="'.$uname.'" />'
 6914:        .'<input type="hidden" name="accessudom" value="'.$udom.'" />'
 6915:        .'<input type="hidden" name="page" value="'.$curr{'page'}.'" />'
 6916:        .'<input type="hidden" name="prevphases" value="'.$prevphasestr.'" />'
 6917:        .'<input type="hidden" name="phase" value="activity" />'
 6918:        .'<input type="hidden" name="action" value="accesslogs" />'
 6919:        .'<input type="hidden" name="srchdomain" value="'.$udom.'" />'
 6920:        .'<input type="hidden" name="srchby" value="'.$env{'form.srchby'}.'" />'
 6921:        .'<input type="hidden" name="srchtype" value="'.$env{'form.srchtype'}.'" />'
 6922:        .'<input type="hidden" name="srchterm" value="'.&HTML::Entities::encode($env{'form.srchterm'},'<>"&').'" />'
 6923:        .'<input type="hidden" name="srchin" value="'.$env{'form.srchin'}.'" />'
 6924:        .'</form>');
 6925:     return;
 6926: }
 6927: 
 6928: sub earlyout_accesslog_form {
 6929:     my ($formname,$prevphasestr,$udom) = @_;
 6930:     my $srchterm = &HTML::Entities::encode($env{'form.srchterm'},'<>"&');
 6931:    return <<"END";
 6932: <form action="/adm/createuser" method="post" name="$formname">
 6933: <input type="hidden" name="currstate" value="" />
 6934: <input type="hidden" name="prevphases" value="$prevphasestr" />
 6935: <input type="hidden" name="phase" value="activity" />
 6936: <input type="hidden" name="action" value="accesslogs" />
 6937: <input type="hidden" name="srchdomain" value="$udom" />
 6938: <input type="hidden" name="srchby" value="$env{'form.srchby'}" />
 6939: <input type="hidden" name="srchtype" value="$env{'form.srchtype'}" />
 6940: <input type="hidden" name="srchterm" value="$srchterm" />
 6941: <input type="hidden" name="srchin" value="$env{'form.srchin'}" />
 6942: </form>
 6943: END
 6944: }
 6945: 
 6946: sub activity_display_filter {
 6947:     my ($formname,$curr) = @_;
 6948:     my $nolink = 1;
 6949:     my $output = '<table><tr><td valign="top">'.
 6950:                  '<span class="LC_nobreak"><b>'.&mt('Actions/page:').'</b></span><br />'.
 6951:                  &Apache::lonmeta::selectbox('show',$curr->{'show'},undef,
 6952:                                               (&mt('all'),5,10,20,50,100,1000,10000)).
 6953:                  '</td><td>&nbsp;&nbsp;</td>';
 6954:     my $startform =
 6955:         &Apache::lonhtmlcommon::date_setter($formname,'accesslog_start_date',
 6956:                                             $curr->{'accesslog_start_date'},undef,
 6957:                                             undef,undef,undef,undef,undef,undef,$nolink);
 6958:     my $endform =
 6959:         &Apache::lonhtmlcommon::date_setter($formname,'accesslog_end_date',
 6960:                                             $curr->{'accesslog_end_date'},undef,
 6961:                                             undef,undef,undef,undef,undef,undef,$nolink);
 6962:     my %lt = &Apache::lonlocal::texthash (
 6963:                                           activity => 'Activity',
 6964:                                           Role     => 'Role selection',
 6965:                                           log      => 'Log-in or Logout',
 6966:     );
 6967:     $output .= '<td valign="top"><b>'.&mt('Window during which actions occurred:').'</b><br />'.
 6968:                '<table><tr><td>'.&mt('After:').
 6969:                '</td><td>'.$startform.'</td></tr>'.
 6970:                '<tr><td>'.&mt('Before:').'</td>'.
 6971:                '<td>'.$endform.'</td></tr></table>'.
 6972:                '</td>'.
 6973:                '<td>&nbsp;&nbsp;</td>'.
 6974:                '<td valign="top"><b>'.&mt('Activities').'</b><br />'.
 6975:                '<select name="activity"><option value="any"';
 6976:     if ($curr->{'activity'} eq 'any') {
 6977:         $output .= ' selected="selected"';
 6978:     }
 6979:     $output .= '>'.&mt('Any').'</option>'."\n";
 6980:     foreach my $activity ('Role','log') {
 6981:         my $selstr = '';
 6982:         if ($activity eq $curr->{'activity'}) {
 6983:             $selstr = ' selected="selected"';
 6984:         }
 6985:         $output .= '<option value="'.$activity.'"'.$selstr.'>'.$lt{$activity}.'</option>';
 6986:     }
 6987:     $output .= '</select></td>'.
 6988:                '</tr></table>';
 6989:     # Update Display button
 6990:     $output .= '<p>'
 6991:               .'<input type="submit" value="'.&mt('Update Display').'" />'
 6992:               .'</p>';
 6993:     return $output;
 6994: }
 6995: 
 6996: sub userlogdisplay_js {
 6997:     my ($formname) = @_;
 6998:     return <<"ENDSCRIPT";
 6999: 
 7000: function chgPage(caller) {
 7001:     if (caller == 'previous') {
 7002:         document.$formname.page.value --;
 7003:     }
 7004:     if (caller == 'next') {
 7005:         document.$formname.page.value ++;
 7006:     }
 7007:     document.$formname.submit();
 7008:     return;
 7009: }
 7010: ENDSCRIPT
 7011: }
 7012: 
 7013: sub userlogdisplay_navlinks {
 7014:     my ($curr,$more_records) = @_;
 7015:     return unless(ref($curr) eq 'HASH');
 7016:     # Navigation Buttons
 7017:     my $nav_links = '<p>';
 7018:     if (($curr->{'page'} > 1) || ($more_records)) {
 7019:         if (($curr->{'page'} > 1) && ($curr->{'show'} !~ /\D/)) {
 7020:             $nav_links .= '<input type="button"'
 7021:                          .' onclick="javascript:chgPage('."'previous'".');"'
 7022:                          .' value="'.&mt('Previous [_1] changes',$curr->{'show'})
 7023:                          .'" /> ';
 7024:         }
 7025:         if ($more_records) {
 7026:             $nav_links .= '<input type="button"'
 7027:                          .' onclick="javascript:chgPage('."'next'".');"'
 7028:                          .' value="'.&mt('Next [_1] changes',$curr->{'show'})
 7029:                          .'" />';
 7030:         }
 7031:     }
 7032:     $nav_links .= '</p>';
 7033:     return $nav_links;
 7034: }
 7035: 
 7036: sub role_display_filter {
 7037:     my ($context,$formname,$cdom,$cnum,$curr,$version,$crstype) = @_;
 7038:     my $lctype;
 7039:     if ($context eq 'course') {
 7040:         $lctype = lc($crstype);
 7041:     }
 7042:     my $nolink = 1;
 7043:     my $output = '<table><tr><td valign="top">'.
 7044:                  '<span class="LC_nobreak"><b>'.&mt('Changes/page:').'</b></span><br />'.
 7045:                  &Apache::lonmeta::selectbox('show',$curr->{'show'},undef,
 7046:                                               (&mt('all'),5,10,20,50,100,1000,10000)).
 7047:                  '</td><td>&nbsp;&nbsp;</td>';
 7048:     my $startform =
 7049:         &Apache::lonhtmlcommon::date_setter($formname,'rolelog_start_date',
 7050:                                             $curr->{'rolelog_start_date'},undef,
 7051:                                             undef,undef,undef,undef,undef,undef,$nolink);
 7052:     my $endform =
 7053:         &Apache::lonhtmlcommon::date_setter($formname,'rolelog_end_date',
 7054:                                             $curr->{'rolelog_end_date'},undef,
 7055:                                             undef,undef,undef,undef,undef,undef,$nolink);
 7056:     my %lt = &rolechg_contexts($context,$crstype);
 7057:     $output .= '<td valign="top"><b>'.&mt('Window during which changes occurred:').'</b><br />'.
 7058:                '<table><tr><td>'.&mt('After:').
 7059:                '</td><td>'.$startform.'</td></tr>'.
 7060:                '<tr><td>'.&mt('Before:').'</td>'.
 7061:                '<td>'.$endform.'</td></tr></table>'.
 7062:                '</td>'.
 7063:                '<td>&nbsp;&nbsp;</td>'.
 7064:                '<td valign="top"><b>'.&mt('Role:').'</b><br />'.
 7065:                '<select name="role"><option value="any"';
 7066:     if ($curr->{'role'} eq 'any') {
 7067:         $output .= ' selected="selected"';
 7068:     }
 7069:     $output .=  '>'.&mt('Any').'</option>'."\n";
 7070:     my @roles = &Apache::lonuserutils::roles_by_context($context,1,$crstype);
 7071:     foreach my $role (@roles) {
 7072:         my $plrole;
 7073:         if ($role eq 'cr') {
 7074:             $plrole = &mt('Custom Role');
 7075:         } else {
 7076:             $plrole=&Apache::lonnet::plaintext($role,$crstype);
 7077:         }
 7078:         my $selstr = '';
 7079:         if ($role eq $curr->{'role'}) {
 7080:             $selstr = ' selected="selected"';
 7081:         }
 7082:         $output .= '  <option value="'.$role.'"'.$selstr.'>'.$plrole.'</option>';
 7083:     }
 7084:     $output .= '</select></td>'.
 7085:                '<td>&nbsp;&nbsp;</td>'.
 7086:                '<td valign="top"><b>'.
 7087:                &mt('Context:').'</b><br /><select name="chgcontext">';
 7088:     my @posscontexts;
 7089:     if ($context eq 'course') {
 7090:         @posscontexts = ('any','automated','updatenow','createcourse','course','domain','selfenroll','requestcourses');
 7091:     } elsif ($context eq 'domain') {
 7092:         @posscontexts = ('any','domain','requestauthor','domconfig','server');
 7093:     } else {
 7094:         @posscontexts = ('any','author','domain');
 7095:     } 
 7096:     foreach my $chgtype (@posscontexts) {
 7097:         my $selstr = '';
 7098:         if ($curr->{'chgcontext'} eq $chgtype) {
 7099:             $selstr = ' selected="selected"';
 7100:         }
 7101:         if ($context eq 'course') {
 7102:             if (($chgtype eq 'automated') || ($chgtype eq 'updatenow')) {
 7103:                 next if (!&Apache::lonnet::auto_run($cnum,$cdom));
 7104:             }
 7105:         }
 7106:         $output .= '<option value="'.$chgtype.'"'.$selstr.'>'.$lt{$chgtype}.'</option>'."\n";
 7107:     }
 7108:     $output .= '</select></td>'
 7109:               .'</tr></table>';
 7110: 
 7111:     # Update Display button
 7112:     $output .= '<p>'
 7113:               .'<input type="submit" value="'.&mt('Update Display').'" />'
 7114:               .'</p>';
 7115: 
 7116:     # Server version info
 7117:     my $needsrev = '2.11.0';
 7118:     if ($context eq 'course') {
 7119:         $needsrev = '2.7.0';
 7120:     }
 7121:     
 7122:     $output .= '<p class="LC_info">'
 7123:               .&mt('Only changes made from servers running LON-CAPA [_1] or later are displayed.'
 7124:                   ,$needsrev);
 7125:     if ($version) {
 7126:         $output .= ' '.&mt('This LON-CAPA server is version [_1]',$version);
 7127:     }
 7128:     $output .= '</p><hr />';
 7129:     return $output;
 7130: }
 7131: 
 7132: sub rolechg_contexts {
 7133:     my ($context,$crstype) = @_;
 7134:     my %lt;
 7135:     if ($context eq 'course') {
 7136:         %lt = &Apache::lonlocal::texthash (
 7137:                                              any          => 'Any',
 7138:                                              automated    => 'Automated Enrollment',
 7139:                                              updatenow    => 'Roster Update',
 7140:                                              createcourse => 'Course Creation',
 7141:                                              course       => 'User Management in course',
 7142:                                              domain       => 'User Management in domain',
 7143:                                              selfenroll   => 'Self-enrolled',
 7144:                                              requestcourses => 'Course Request',
 7145:                                          );
 7146:         if ($crstype eq 'Community') {
 7147:             $lt{'createcourse'} = &mt('Community Creation');
 7148:             $lt{'course'} = &mt('User Management in community');
 7149:             $lt{'requestcourses'} = &mt('Community Request');
 7150:         }
 7151:     } elsif ($context eq 'domain') {
 7152:         %lt = &Apache::lonlocal::texthash (
 7153:                                              any           => 'Any',
 7154:                                              domain        => 'User Management in domain',
 7155:                                              requestauthor => 'Authoring Request',
 7156:                                              server        => 'Command line script (DC role)',
 7157:                                              domconfig     => 'Self-enrolled',
 7158:                                          );
 7159:     } else {
 7160:         %lt = &Apache::lonlocal::texthash (
 7161:                                              any    => 'Any',
 7162:                                              domain => 'User Management in domain',
 7163:                                              author => 'User Management by author',
 7164:                                          );
 7165:     } 
 7166:     return %lt;
 7167: }
 7168: 
 7169: sub print_helpdeskaccess_display {
 7170:     my ($r,$permission,$brcrum) = @_;
 7171:     my $formname = 'helpdeskaccess';
 7172:     my $helpitem = 'Course_Helpdesk_Access';
 7173:     push (@{$brcrum},
 7174:              {href => '/adm/createuser?action=helpdesk',
 7175:               text => 'Helpdesk Access',
 7176:               help => $helpitem});
 7177:     my $bread_crumbs_component = 'Helpdesk Staff Access';
 7178:     my $args = { bread_crumbs           => $brcrum,
 7179:                  bread_crumbs_component => $bread_crumbs_component};
 7180: 
 7181:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7182:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7183:     my $confname = $cdom.'-domainconfig';
 7184:     my $crstype = &Apache::loncommon::course_type();
 7185: 
 7186:     my @accesstypes = ('all','none');
 7187:     my ($numstatustypes,@jsarray);
 7188:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($cdom);
 7189:     if (ref($types) eq 'ARRAY') {
 7190:         if (@{$types} > 0) {
 7191:             $numstatustypes = scalar(@{$types});
 7192:             push(@accesstypes,'status');
 7193:             @jsarray = ('bystatus');
 7194:         }
 7195:     }
 7196:     my %customroles = &get_domain_customroles($cdom,$confname);
 7197:     my %domhelpdesk = &Apache::lonnet::get_active_domroles($cdom,['dh']);
 7198:     if (keys(%domhelpdesk)) {
 7199:        push(@accesstypes,('inc','exc'));
 7200:        push(@jsarray,('notinc','notexc'));
 7201:     }
 7202:     push(@jsarray,'privs');
 7203:     my $hiddenstr = join("','",@jsarray);
 7204:     my $rolestr = join("','",sort(keys(%customroles)));
 7205: 
 7206:     my $jscript;
 7207:     my (%settings,%overridden);
 7208:     if (keys(%customroles)) {
 7209:         &get_adhocrole_settings($env{'request.course.id'},\@accesstypes,
 7210:                                 $types,\%customroles,\%settings,\%overridden);
 7211:         my %jsfull=();
 7212:         my %jslevels= (
 7213:                      course => {},
 7214:                      domain => {},
 7215:                      system => {},
 7216:                     );
 7217:         my %jslevelscurrent=(
 7218:                            course => {},
 7219:                            domain => {},
 7220:                            system => {},
 7221:                           );
 7222:         my (%privs,%jsprivs);
 7223:         &Apache::lonuserutils::custom_role_privs(\%privs,\%jsfull,\%jslevels,\%jslevelscurrent);
 7224:         foreach my $priv (keys(%jsfull)) {
 7225:             if ($jslevels{'course'}{$priv}) {
 7226:                 $jsprivs{$priv} = 1;
 7227:             }
 7228:         }
 7229:         my (%elements,%stored);
 7230:         foreach my $role (keys(%customroles)) {
 7231:             $elements{$role.'_access'} = 'radio';
 7232:             $elements{$role.'_incrs'} = 'radio';
 7233:             if ($numstatustypes) {
 7234:                 $elements{$role.'_status'} = 'checkbox';
 7235:             }
 7236:             if (keys(%domhelpdesk) > 0) {
 7237:                 $elements{$role.'_staff_inc'} = 'checkbox';
 7238:                 $elements{$role.'_staff_exc'} = 'checkbox';
 7239:             }
 7240:             $elements{$role.'_override'} = 'checkbox';
 7241:             if (ref($settings{$role}) eq 'HASH') {
 7242:                 if ($settings{$role}{'access'} ne '') {
 7243:                     my $curraccess = $settings{$role}{'access'};
 7244:                     $stored{$role.'_access'} = $curraccess;
 7245:                     $stored{$role.'_incrs'} = 1;
 7246:                     if ($curraccess eq 'status') {
 7247:                         if (ref($settings{$role}{'status'}) eq 'ARRAY') {
 7248:                             $stored{$role.'_status'} = $settings{$role}{'status'};
 7249:                         }
 7250:                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 7251:                         if (ref($settings{$role}{$curraccess}) eq 'ARRAY') {
 7252:                             $stored{$role.'_staff_'.$curraccess} = $settings{$role}{$curraccess};
 7253:                         }
 7254:                     }
 7255:                 } else {
 7256:                     $stored{$role.'_incrs'} = 0;
 7257:                 }
 7258:                 $stored{$role.'_override'} = [];
 7259:                 if ($env{'course.'.$env{'request.course.id'}.'.internal.adhocpriv.'.$role}) {
 7260:                     if (ref($settings{$role}{'off'}) eq 'ARRAY') {
 7261:                         foreach my $priv (@{$settings{$role}{'off'}}) {
 7262:                             push(@{$stored{$role.'_override'}},$priv);
 7263:                         }
 7264:                     }
 7265:                     if (ref($settings{$role}{'on'}) eq 'ARRAY') {
 7266:                         foreach my $priv (@{$settings{$role}{'on'}}) {
 7267:                             unless (grep(/^$priv$/,@{$stored{$role.'_override'}})) {
 7268:                                 push(@{$stored{$role.'_override'}},$priv);
 7269:                             }
 7270:                         }
 7271:                     }
 7272:                 }
 7273:             } else {
 7274:                 $stored{$role.'_incrs'} = 0;
 7275:             }
 7276:         }
 7277:         $jscript = &Apache::lonhtmlcommon::set_form_elements(\%elements,\%stored);
 7278:     }
 7279: 
 7280:     my $js = <<"ENDJS";
 7281: <script type="text/javascript">
 7282: // <![CDATA[
 7283: $jscript;
 7284: 
 7285: function switchRoleTab(caller,role) {
 7286:     if (document.getElementById(role+'_maindiv')) {
 7287:         if (caller.id != 'LC_current_minitab') {
 7288:             if (document.getElementById('LC_current_minitab')) {
 7289:                 document.getElementById('LC_current_minitab').id=null;
 7290:             }
 7291:             var roledivs = Array('$rolestr');
 7292:             if (roledivs.length > 0) {
 7293:                 for (var i=0; i<roledivs.length; i++) {
 7294:                     if (document.getElementById(roledivs[i]+'_maindiv')) {
 7295:                         document.getElementById(roledivs[i]+'_maindiv').style.display='none';
 7296:                     }
 7297:                 }
 7298:             }
 7299:             caller.id = 'LC_current_minitab';
 7300:             document.getElementById(role+'_maindiv').style.display='block';
 7301:         }
 7302:     }
 7303:     return false;
 7304: }
 7305: 
 7306: function helpdeskAccess(role) {
 7307:     var curraccess = null;
 7308:     if (document.$formname.elements[role+'_access'].length) {
 7309:         for (var i=0; i<document.$formname.elements[role+'_access'].length; i++) {
 7310:             if (document.$formname.elements[role+'_access'][i].checked) {
 7311:                 curraccess = document.$formname.elements[role+'_access'][i].value;
 7312:             }
 7313:         }
 7314:     }
 7315:     var shown = Array();
 7316:     var hidden = Array();
 7317:     if (curraccess == 'none') {
 7318:         hidden = Array ('$hiddenstr');
 7319:     } else {
 7320:         if (curraccess == 'status') {
 7321:             shown = Array ('bystatus','privs');
 7322:             hidden = Array ('notinc','notexc');
 7323:         } else {
 7324:             if (curraccess == 'exc') {
 7325:                 shown = Array ('notexc','privs');
 7326:                 hidden = Array ('notinc','bystatus');
 7327:             }
 7328:             if (curraccess == 'inc') {
 7329:                 shown = Array ('notinc','privs');
 7330:                 hidden = Array ('notexc','bystatus');
 7331:             }
 7332:             if (curraccess == 'all') {
 7333:                 shown = Array ('privs');
 7334:                 hidden = Array ('notinc','notexc','bystatus');
 7335:             }
 7336:         }
 7337:     }
 7338:     if (hidden.length > 0) {
 7339:         for (var i=0; i<hidden.length; i++) {
 7340:             if (document.getElementById(role+'_'+hidden[i])) {
 7341:                 document.getElementById(role+'_'+hidden[i]).style.display = 'none';
 7342:             }
 7343:         }
 7344:     }
 7345:     if (shown.length > 0) {
 7346:         for (var i=0; i<shown.length; i++) {
 7347:             if (document.getElementById(role+'_'+shown[i])) {
 7348:                 if (shown[i] == 'privs') {
 7349:                     document.getElementById(role+'_'+shown[i]).style.display = 'block';
 7350:                 } else {
 7351:                     document.getElementById(role+'_'+shown[i]).style.display = 'inline';
 7352:                 }
 7353:             }
 7354:         }
 7355:     }
 7356:     return;
 7357: }
 7358: 
 7359: function toggleAccess(role) {
 7360:     if ((document.getElementById(role+'_setincrs')) &&
 7361:         (document.getElementById(role+'_setindom'))) {
 7362:         for (var i=0; i<document.$formname.elements[role+'_incrs'].length; i++) {
 7363:             if (document.$formname.elements[role+'_incrs'][i].checked) {
 7364:                 if (document.$formname.elements[role+'_incrs'][i].value == 1) {
 7365:                     document.getElementById(role+'_setindom').style.display = 'none';
 7366:                     document.getElementById(role+'_setincrs').style.display = 'block';
 7367:                 } else {
 7368:                     document.getElementById(role+'_setincrs').style.display = 'none';
 7369:                     document.getElementById(role+'_setindom').style.display = 'block';
 7370:                 }
 7371:                 break;
 7372:             }
 7373:         }
 7374:     }
 7375:     return;
 7376: }
 7377: 
 7378: // ]]>
 7379: </script>
 7380: ENDJS
 7381: 
 7382:     $args->{add_entries} = {onload => "javascript:setFormElements(document.$formname)"};
 7383: 
 7384:     # print page header
 7385:     $r->print(&header($js,$args));
 7386:     # print form header
 7387:     $r->print('<form action="/adm/createuser" method="post" name="'.$formname.'">');
 7388: 
 7389:     if (keys(%customroles)) {
 7390:         my %lt = &Apache::lonlocal::texthash(
 7391:                     'aco'    => 'As course owner you may override the defaults set in the domain for role usage and/or privileges.',
 7392:                     'rou'    => 'Role usage',
 7393:                     'whi'    => 'Which helpdesk personnel may use this role?',
 7394:                     'udd'    => 'Use domain default',
 7395:                     'all'    => 'All',
 7396:                     'none'   => 'None',
 7397:                     'status' => 'Determined based on institutional status',
 7398:                     'inc'    => 'Include all, but exclude specific personnel',
 7399:                     'exc'    => 'Exclude all, but include specific personnel',
 7400:                     'hel'    => 'Helpdesk',
 7401:                     'rpr'    => 'Role privileges',
 7402:                  );
 7403:         $lt{'tfh'} = &mt("Custom [_1]ad hoc[_2] course roles available for use by the domain's helpdesk are as follows",'<i>','</i>');
 7404:         my %domconfig = &Apache::lonnet::get_dom('configuration',['helpsettings'],$cdom);
 7405:         my (%domcurrent,%ordered,%description,%domusage,$disabled);
 7406:         if (ref($domconfig{'helpsettings'}) eq 'HASH') {
 7407:             if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
 7408:                 %domcurrent = %{$domconfig{'helpsettings'}{'adhoc'}};
 7409:             }
 7410:         }
 7411:         my $count = 0;
 7412:         foreach my $role (sort(keys(%customroles))) {
 7413:             my ($order,$desc,$access_in_dom);
 7414:             if (ref($domcurrent{$role}) eq 'HASH') {
 7415:                 $order = $domcurrent{$role}{'order'};
 7416:                 $desc = $domcurrent{$role}{'desc'};
 7417:                 $access_in_dom = $domcurrent{$role}{'access'};
 7418:             }
 7419:             if ($order eq '') {
 7420:                 $order = $count;
 7421:             }
 7422:             $ordered{$order} = $role;
 7423:             if ($desc ne '') {
 7424:                 $description{$role} = $desc;
 7425:             } else {
 7426:                 $description{$role}= $role;
 7427:             }
 7428:             $count++;
 7429:         }
 7430:         %domusage = &domain_adhoc_access(\%customroles,\%domcurrent,\@accesstypes,$usertypes,$othertitle);
 7431:         my @roles_by_num = ();
 7432:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 7433:             push(@roles_by_num,$ordered{$item});
 7434:         }
 7435:         $r->print('<p>'.$lt{'tfh'}.': <i>'.join('</i>, <i>',map { $description{$_}; } @roles_by_num).'</i>.');
 7436:         if ($permission->{'owner'}) {
 7437:             $r->print('<br />'.$lt{'aco'}.'</p><p>');
 7438:             $r->print('<input type="hidden" name="state" value="process" />'.
 7439:                       '<input type="submit" value="'.&mt('Save changes').'" />');
 7440:         } else {
 7441:             if ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'}) {
 7442:                 my ($ownername,$ownerdom) = split(/:/,$env{'course.'.$env{'request.course.id'}.'.internal.courseowner'});
 7443:                 $r->print('<br />'.&mt('The course owner -- [_1] -- can override the default access and/or privileges for these ad hoc roles.',
 7444:                                     &Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($ownername,$ownerdom),$ownername,$ownerdom)));
 7445:             }
 7446:             $disabled = ' disabled="disabled"';
 7447:         }
 7448:         $r->print('</p>');
 7449: 
 7450:         $r->print('<div id="LC_minitab_header"><ul>');
 7451:         my $count = 0;
 7452:         my %visibility;
 7453:         foreach my $role (@roles_by_num) {
 7454:             my $id;
 7455:             if ($count == 0) {
 7456:                 $id=' id="LC_current_minitab"';
 7457:                 $visibility{$role} = ' style="display:block"';
 7458:             } else {
 7459:                 $visibility{$role} = ' style="display:none"';
 7460:             }
 7461:             $count ++;
 7462:             $r->print('<li'.$id.'><a href="#" onclick="javascript:switchRoleTab(this.parentNode,'."'$role'".');">'.$description{$role}.'</a></li>');
 7463:         }
 7464:         $r->print('</ul></div>');
 7465: 
 7466:         foreach my $role (@roles_by_num) {
 7467:             my %usecheck = (
 7468:                              all => ' checked="checked"',
 7469:                            );
 7470:             my %displaydiv = (
 7471:                                 status => 'none',
 7472:                                 inc    => 'none',
 7473:                                 exc    => 'none',
 7474:                                 priv   => 'block',
 7475:                              );
 7476:             my (%selected,$overridden,$incrscheck,$indomcheck,$indomvis,$incrsvis);
 7477:             if (ref($settings{$role}) eq 'HASH') {
 7478:                 if ($settings{$role}{'access'} ne '') {
 7479:                     $indomvis = ' style="display:none"';
 7480:                     $incrsvis = ' style="display:block"';
 7481:                     $incrscheck = ' checked="checked"';
 7482:                     if ($settings{$role}{'access'} ne 'all') {
 7483:                         $usecheck{$settings{$role}{'access'}} = $usecheck{'all'};
 7484:                         delete($usecheck{'all'});
 7485:                         if ($settings{$role}{'access'} eq 'status') {
 7486:                             my $access = 'status';
 7487:                             $displaydiv{$access} = 'inline';
 7488:                             if (ref($settings{$role}{$access}) eq 'ARRAY') {
 7489:                                 $selected{$access} = $settings{$role}{$access};
 7490:                             }
 7491:                         } elsif ($settings{$role}{'access'} =~ /^(inc|exc)$/) {
 7492:                             my $access = $1;
 7493:                             $displaydiv{$access} = 'inline';
 7494:                             if (ref($settings{$role}{$access}) eq 'ARRAY') {
 7495:                                 $selected{$access} = $settings{$role}{$access};
 7496:                             }
 7497:                         } elsif ($settings{$role}{'access'} eq 'none') {
 7498:                             $displaydiv{'priv'} = 'none';
 7499:                         }
 7500:                     }
 7501:                 } else {
 7502:                     $indomcheck = ' checked="checked"';
 7503:                     $indomvis = ' style="display:block"';
 7504:                     $incrsvis = ' style="display:none"';
 7505:                 }
 7506:             } else {
 7507:                 $indomcheck = ' checked="checked"';
 7508:                 $indomvis = ' style="display:block"';
 7509:                 $incrsvis = ' style="display:none"';
 7510:             }
 7511:             $r->print('<div class="LC_left_float" id="'.$role.'_maindiv"'.$visibility{$role}.'>'.
 7512:                       '<fieldset><legend>'.$lt{'rou'}.'</legend>'.
 7513:                       '<p>'.$lt{'whi'}.' <span class="LC_nobreak">'.
 7514:                       '<label><input type="radio" name="'.$role.'_incrs" value="1"'.$incrscheck.' onclick="toggleAccess('."'$role'".');"'.$disabled.'>'.
 7515:                       &mt('Set here in [_1]',lc($crstype)).'</label>'.
 7516:                       '<span>'.('&nbsp;'x2).
 7517:                       '<label><input type="radio" name="'.$role.'_incrs" value="0"'.$indomcheck.' onclick="toggleAccess('."'$role'".');"'.$disabled.'>'.
 7518:                       $lt{'udd'}.'</label><span></p>'.
 7519:                       '<div id="'.$role.'_setindom"'.$indomvis.'>'.
 7520:                       '<span class="LC_cusr_emph">'.$domusage{$role}.'</span></div>'.
 7521:                       '<div id="'.$role.'_setincrs"'.$incrsvis.'>');
 7522:             foreach my $access (@accesstypes) {
 7523:                 $r->print('<p><label><input type="radio" name="'.$role.'_access" value="'.$access.'" '.$usecheck{$access}.
 7524:                           ' onclick="helpdeskAccess('."'$role'".');"'.$disabled.' />'.$lt{$access}.'</label>');
 7525:                 if ($access eq 'status') {
 7526:                     $r->print('<div id="'.$role.'_bystatus" style="display:'.$displaydiv{$access}.'">'.
 7527:                               &Apache::lonuserutils::adhoc_status_types($cdom,undef,$role,$selected{$access},
 7528:                                                                         $othertitle,$usertypes,$types,$disabled).
 7529:                               '</div>');
 7530:                 } elsif (($access eq 'inc') && (keys(%domhelpdesk) > 0)) {
 7531:                     $r->print('<div id="'.$role.'_notinc" style="display:'.$displaydiv{$access}.'">'.
 7532:                               &Apache::lonuserutils::adhoc_staff($access,undef,$role,$selected{$access},
 7533:                                                                  \%domhelpdesk,$disabled).
 7534:                               '</div>');
 7535:                 } elsif (($access eq 'exc') && (keys(%domhelpdesk) > 0)) {
 7536:                     $r->print('<div id="'.$role.'_notexc" style="display:'.$displaydiv{$access}.'">'.
 7537:                               &Apache::lonuserutils::adhoc_staff($access,undef,$role,$selected{$access},
 7538:                                                                  \%domhelpdesk,$disabled).
 7539:                               '</div>');
 7540:                 }
 7541:                 $r->print('</p>');
 7542:             }
 7543:             $r->print('</div></fieldset>');
 7544:             my %full=();
 7545:             my %levels= (
 7546:                          course => {},
 7547:                          domain => {},
 7548:                          system => {},
 7549:                         );
 7550:             my %levelscurrent=(
 7551:                                course => {},
 7552:                                domain => {},
 7553:                                system => {},
 7554:                               );
 7555:             &Apache::lonuserutils::custom_role_privs($customroles{$role},\%full,\%levels,\%levelscurrent);
 7556:             $r->print('<fieldset id="'.$role.'_privs" style="display:'.$displaydiv{'priv'}.'">'.
 7557:                       '<legend>'.$lt{'rpr'}.'</legend>'.
 7558:                       &role_priv_table($role,$permission,$crstype,\%full,\%levels,\%levelscurrent,$overridden{$role}).
 7559:                       '</fieldset></div><div style="padding:0;clear:both;margin:0;border:0"></div>');
 7560:         }
 7561:         if ($permission->{'owner'}) {
 7562:             $r->print('<p><input type="submit" value="'.&mt('Save changes').'" /></p>');
 7563:         }
 7564:     } else {
 7565:         $r->print(&mt('Helpdesk roles have not yet been created in this domain.'));
 7566:     }
 7567:     # Form Footer
 7568:     $r->print('<input type="hidden" name="action" value="helpdesk" />'
 7569:              .'</form>');
 7570:     return;
 7571: }
 7572: 
 7573: sub domain_adhoc_access {
 7574:     my ($roles,$domcurrent,$accesstypes,$usertypes,$othertitle) = @_;
 7575:     my %domusage;
 7576:     return unless ((ref($roles) eq 'HASH') && (ref($domcurrent) eq 'HASH') && (ref($accesstypes) eq 'ARRAY'));
 7577:     foreach my $role (keys(%{$roles})) {
 7578:         if (ref($domcurrent->{$role}) eq 'HASH') {
 7579:             my $access = $domcurrent->{$role}{'access'};
 7580:             if (($access eq '') || (!grep(/^\Q$access\E$/,@{$accesstypes}))) {
 7581:                 $access = 'all';
 7582:                 $domusage{$role} = &mt('Any user in domain with active [_1] role',&Apache::lonnet::plaintext('dh'));
 7583:             } elsif ($access eq 'status') {
 7584:                 if (ref($domcurrent->{$role}{$access}) eq 'ARRAY') {
 7585:                     my @shown;
 7586:                     foreach my $type (@{$domcurrent->{$role}{$access}}) {
 7587:                         unless ($type eq 'default') {
 7588:                             if ($usertypes->{$type}) {
 7589:                                 push(@shown,$usertypes->{$type});
 7590:                             }
 7591:                         }
 7592:                     }
 7593:                     if (grep(/^default$/,@{$domcurrent->{$role}{$access}})) {
 7594:                         push(@shown,$othertitle);
 7595:                     }
 7596:                     if (@shown) {
 7597:                         my $shownstatus = join(' '.&mt('or').' ',@shown);
 7598:                         $domusage{$role} = &mt('Any user in domain with active [_1] role, and institutional status: [_2]',
 7599:                                                &Apache::lonnet::plaintext('dh'),$shownstatus);
 7600:                     } else {
 7601:                         $domusage{$role} = &mt('No one in the domain');
 7602:                     }
 7603:                 }
 7604:             } elsif ($access eq 'inc') {
 7605:                 my @dominc = ();
 7606:                 if (ref($domcurrent->{$role}{'inc'}) eq 'ARRAY') {
 7607:                     foreach my $user (@{$domcurrent->{$role}{'inc'}}) {
 7608:                         my ($uname,$udom) = split(/:/,$user);
 7609:                         push(@dominc,&Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($uname,$udom),$uname,$udom));
 7610:                     }
 7611:                     my $showninc = join(', ',@dominc);
 7612:                     if ($showninc ne '') {
 7613:                         $domusage{$role} = &mt('Include any user in domain with active [_1] role, except: [_2]',
 7614:                                                &Apache::lonnet::plaintext('dh'),$showninc);
 7615:                     } else {
 7616:                         $domusage{$role} = &mt('Any user in domain with active [_1] role',&Apache::lonnet::plaintext('dh'));
 7617:                     }
 7618:                 }
 7619:             } elsif ($access eq 'exc') {
 7620:                 my @domexc = ();
 7621:                 if (ref($domcurrent->{$role}{'exc'}) eq 'ARRAY') {
 7622:                     foreach my $user (@{$domcurrent->{$role}{'exc'}}) {
 7623:                         my ($uname,$udom) = split(/:/,$user);
 7624:                         push(@domexc,&Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($uname,$udom),$uname,$udom));
 7625:                     }
 7626:                 }
 7627:                 my $shownexc = join(', ',@domexc);
 7628:                 if ($shownexc ne '') {
 7629:                     $domusage{$role} = &mt('Only the following in the domain with active [_1] role: [_2]',
 7630:                                            &Apache::lonnet::plaintext('dh'),$shownexc);
 7631:                 } else {
 7632:                     $domusage{$role} = &mt('No one in the domain');
 7633:                 }
 7634:             } elsif ($access eq 'none') {
 7635:                 $domusage{$role} = &mt('No one in the domain');
 7636:             } elsif ($access eq 'all') {
 7637:                 $domusage{$role} = &mt('Any user in domain with active [_1] role',&Apache::lonnet::plaintext('dh'));
 7638:             }
 7639:         } else {
 7640:             $domusage{$role} = &mt('Any user in domain with active [_1] role',&Apache::lonnet::plaintext('dh'));
 7641:         }
 7642:     }
 7643:     return %domusage;
 7644: }
 7645: 
 7646: sub get_domain_customroles {
 7647:     my ($cdom,$confname) = @_;
 7648:     my %existing=&Apache::lonnet::dump('roles',$cdom,$confname,'rolesdef_');
 7649:     my %customroles;
 7650:     foreach my $key (keys(%existing)) {
 7651:         if ($key=~/^rolesdef\_(\w+)$/) {
 7652:             my $rolename = $1;
 7653:             my %privs;
 7654:             ($privs{'system'},$privs{'domain'},$privs{'course'}) = split(/\_/,$existing{$key});
 7655:             $customroles{$rolename} = \%privs;
 7656:         }
 7657:     }
 7658:     return %customroles;
 7659: }
 7660: 
 7661: sub role_priv_table {
 7662:     my ($role,$permission,$crstype,$full,$levels,$levelscurrent,$overridden) = @_;
 7663:     return unless ((ref($full) eq 'HASH') && (ref($levels) eq 'HASH') &&
 7664:                    (ref($levelscurrent) eq 'HASH'));
 7665:     my %lt=&Apache::lonlocal::texthash (
 7666:                     'crl'  => 'Course Level Privilege',
 7667:                     'def'  => 'Domain Defaults',
 7668:                     'ove'  => 'Override in Course',
 7669:                     'ine'  => 'In effect',
 7670:                     'dis'  => 'Disabled',
 7671:                     'ena'  => 'Enabled',
 7672:                    );
 7673:     if ($crstype eq 'Community') {
 7674:         $lt{'ove'} = 'Override in Community',
 7675:     }
 7676:     my @status = ('Disabled','Enabled');
 7677:     my (%on,%off);
 7678:     if (ref($overridden) eq 'HASH') {
 7679:         if (ref($overridden->{'on'}) eq 'ARRAY') {
 7680:             map { $on{$_} = 1; } (@{$overridden->{'on'}});
 7681:         }
 7682:         if (ref($overridden->{'off'}) eq 'ARRAY') {
 7683:             map { $off{$_} = 1; } (@{$overridden->{'off'}});
 7684:         }
 7685:     }
 7686:     my $output=&Apache::loncommon::start_data_table().
 7687:                &Apache::loncommon::start_data_table_header_row().
 7688:                '<th>'.$lt{'crl'}.'</th><th>'.$lt{'def'}.'</th><th>'.$lt{'ove'}.
 7689:                '</th><th>'.$lt{'ine'}.'</th>'.
 7690:                &Apache::loncommon::end_data_table_header_row();
 7691:     foreach my $priv (sort(keys(%{$full}))) {
 7692:         next unless ($levels->{'course'}{$priv});
 7693:         my $privtext = &Apache::lonnet::plaintext($priv,$crstype);
 7694:         my ($default,$ineffect);
 7695:         if ($levelscurrent->{'course'}{$priv}) {
 7696:             $default = '<img src="/adm/lonIcons/navmap.correct.gif" alt="'.$lt{'ena'}.'" />';
 7697:             $ineffect = $default;
 7698:         }
 7699:         my ($customstatus,$checked);
 7700:         $output .= &Apache::loncommon::start_data_table_row().
 7701:                    '<td>'.$privtext.'</td>'.
 7702:                    '<td>'.$default.'</td><td>';
 7703:         if (($levelscurrent->{'course'}{$priv}) && ($off{$priv})) {
 7704:             if ($permission->{'owner'}) {
 7705:                 $checked = ' checked="checked"';
 7706:             }
 7707:             $customstatus = '<img src="/adm/lonIcons/navmap.wrong.gif" alt="'.$lt{'dis'}.'" />';
 7708:             $ineffect = $customstatus;
 7709:         } elsif ((!$levelscurrent->{'course'}{$priv}) && ($on{$priv})) {
 7710:             if ($permission->{'owner'}) {
 7711:                 $checked = ' checked="checked"';
 7712:             }
 7713:             $customstatus = '<img src="/adm/lonIcons/navmap.correct.gif" alt="'.$lt{'ena'}.'" />';
 7714:             $ineffect = $customstatus;
 7715:         }
 7716:         if ($permission->{'owner'}) {
 7717:             $output .= '<input type="checkbox" name="'.$role.'_override" value="'.$priv.'"'.$checked.' />';
 7718:         } else {
 7719:             $output .= $customstatus;
 7720:         }
 7721:         $output .= '</td><td>'.$ineffect.'</td>'.
 7722:                    &Apache::loncommon::end_data_table_row();
 7723:     }
 7724:     $output .= &Apache::loncommon::end_data_table();
 7725:     return $output;
 7726: }
 7727: 
 7728: sub get_adhocrole_settings {
 7729:     my ($cid,$accesstypes,$types,$customroles,$settings,$overridden) = @_;
 7730:     return unless ((ref($accesstypes) eq 'ARRAY') && (ref($customroles) eq 'HASH') &&
 7731:                    (ref($settings) eq 'HASH') && (ref($overridden) eq 'HASH'));
 7732:     foreach my $role (split(/,/,$env{'course.'.$cid.'.internal.adhocaccess'})) {
 7733:         my ($curraccess,$rest) = split(/=/,$env{'course.'.$cid.'.internal.adhoc.'.$role});
 7734:         if (($curraccess ne '') && (grep(/^\Q$curraccess\E$/,@{$accesstypes}))) {
 7735:             $settings->{$role}{'access'} = $curraccess;
 7736:             if (($curraccess eq 'status') && (ref($types) eq 'ARRAY')) {
 7737:                 my @status = split(/,/,$rest);
 7738:                 my @currstatus;
 7739:                 foreach my $type (@status) {
 7740:                     if ($type eq 'default') {
 7741:                         push(@currstatus,$type);
 7742:                     } elsif (grep(/^\Q$type\E$/,@{$types})) {
 7743:                         push(@currstatus,$type);
 7744:                     }
 7745:                 }
 7746:                 if (@currstatus) {
 7747:                     $settings->{$role}{$curraccess} = \@currstatus;
 7748:                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 7749:                     my @personnel = split(/,/,$rest);
 7750:                     $settings->{$role}{$curraccess} = \@personnel;
 7751:                 }
 7752:             }
 7753:         }
 7754:     }
 7755:     foreach my $role (keys(%{$customroles})) {
 7756:         if ($env{'course.'.$cid.'.internal.adhocpriv.'.$role}) {
 7757:             my %currentprivs;
 7758:             if (ref($customroles->{$role}) eq 'HASH') {
 7759:                 if (exists($customroles->{$role}{'course'})) {
 7760:                     my %full=();
 7761:                     my %levels= (
 7762:                                   course => {},
 7763:                                   domain => {},
 7764:                                   system => {},
 7765:                                 );
 7766:                     my %levelscurrent=(
 7767:                                         course => {},
 7768:                                         domain => {},
 7769:                                         system => {},
 7770:                                       );
 7771:                     &Apache::lonuserutils::custom_role_privs($customroles->{$role},\%full,\%levels,\%levelscurrent);
 7772:                     %currentprivs = %{$levelscurrent{'course'}};
 7773:                 }
 7774:             }
 7775:             foreach my $item (split(/,/,$env{'course.'.$cid.'.internal.adhocpriv.'.$role})) {
 7776:                 next if ($item eq '');
 7777:                 my ($rule,$rest) = split(/=/,$item);
 7778:                 next unless (($rule eq 'off') || ($rule eq 'on'));
 7779:                 foreach my $priv (split(/:/,$rest)) {
 7780:                     if ($priv ne '') {
 7781:                         if ($rule eq 'off') {
 7782:                             push(@{$overridden->{$role}{'off'}},$priv);
 7783:                             if ($currentprivs{$priv}) {
 7784:                                 push(@{$settings->{$role}{'off'}},$priv);
 7785:                             }
 7786:                         } else {
 7787:                             push(@{$overridden->{$role}{'on'}},$priv);
 7788:                             unless ($currentprivs{$priv}) {
 7789:                                 push(@{$settings->{$role}{'on'}},$priv);
 7790:                             }
 7791:                         }
 7792:                     }
 7793:                 }
 7794:             }
 7795:         }
 7796:     }
 7797:     return;
 7798: }
 7799: 
 7800: sub update_helpdeskaccess {
 7801:     my ($r,$permission,$brcrum) = @_;
 7802:     my $helpitem = 'Course_Helpdesk_Access';
 7803:     push (@{$brcrum},
 7804:              {href => '/adm/createuser?action=helpdesk',
 7805:               text => 'Helpdesk Access',
 7806:               help => $helpitem},
 7807:              {href => '/adm/createuser?action=helpdesk',
 7808:               text => 'Result',
 7809:               help => $helpitem}
 7810:          );
 7811:     my $bread_crumbs_component = 'Helpdesk Staff Access';
 7812:     my $args = { bread_crumbs           => $brcrum,
 7813:                  bread_crumbs_component => $bread_crumbs_component};
 7814: 
 7815:     # print page header
 7816:     $r->print(&header('',$args));
 7817:     unless ((ref($permission) eq 'HASH') && ($permission->{'owner'})) {
 7818:         $r->print('<p class="LC_error">'.&mt('You do not have permission to change helpdesk access.').'</p>');
 7819:         return;
 7820:     }
 7821:     my @accesstypes = ('all','none','status','inc','exc');
 7822:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7823:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7824:     my $confname = $cdom.'-domainconfig';
 7825:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($cdom);
 7826:     my $crstype = &Apache::loncommon::course_type();
 7827:     my %customroles = &get_domain_customroles($cdom,$confname);
 7828:     my (%settings,%overridden);
 7829:     &get_adhocrole_settings($env{'request.course.id'},\@accesstypes,
 7830:                             $types,\%customroles,\%settings,\%overridden);
 7831:     my %domhelpdesk = &Apache::lonnet::get_active_domroles($cdom,['dh']);
 7832:     my (%changed,%storehash,@todelete);
 7833: 
 7834:     if (keys(%customroles)) {
 7835:         my (%newsettings,@incrs);
 7836:         foreach my $role (keys(%customroles)) {
 7837:             $newsettings{$role} = {
 7838:                                     access => '',
 7839:                                     status => '',
 7840:                                     exc    => '',
 7841:                                     inc    => '',
 7842:                                     on     => '',
 7843:                                     off    => '',
 7844:                                   };
 7845:             my %current;
 7846:             if (ref($settings{$role}) eq 'HASH') {
 7847:                 %current = %{$settings{$role}};
 7848:             }
 7849:             if (ref($overridden{$role}) eq 'HASH') {
 7850:                 $current{'overridden'} = $overridden{$role};
 7851:             }
 7852:             if ($env{'form.'.$role.'_incrs'}) {
 7853:                 my $access = $env{'form.'.$role.'_access'};
 7854:                 if (grep(/^\Q$access\E$/,@accesstypes)) {
 7855:                     push(@incrs,$role);
 7856:                     unless ($current{'access'} eq $access) {
 7857:                         $changed{$role}{'access'} = 1;
 7858:                         $storehash{'internal.adhoc.'.$role} = $access;
 7859:                     }
 7860:                     if ($access eq 'status') {
 7861:                         my @statuses = &Apache::loncommon::get_env_multiple('form.'.$role.'_status');
 7862:                         my @stored;
 7863:                         my @shownstatus;
 7864:                         if (ref($types) eq 'ARRAY') {
 7865:                             foreach my $type (sort(@statuses)) {
 7866:                                 if ($type eq 'default') {
 7867:                                     push(@stored,$type);
 7868:                                 } elsif (grep(/^\Q$type\E$/,@{$types})) {
 7869:                                     push(@stored,$type);
 7870:                                     push(@shownstatus,$usertypes->{$type});
 7871:                                 }
 7872:                             }
 7873:                             if (grep(/^default$/,@statuses)) {
 7874:                                 push(@shownstatus,$othertitle);
 7875:                             }
 7876:                             $storehash{'internal.adhoc.'.$role} .= '='.join(',',@stored);
 7877:                         }
 7878:                         $newsettings{$role}{'status'} = join(' '.&mt('or').' ',@shownstatus);
 7879:                         if (ref($current{'status'}) eq 'ARRAY') {
 7880:                             my @diffs = &Apache::loncommon::compare_arrays(\@stored,$current{'status'});
 7881:                             if (@diffs) {
 7882:                                 $changed{$role}{'status'} = 1;
 7883:                             }
 7884:                         } elsif (@stored) {
 7885:                             $changed{$role}{'status'} = 1;
 7886:                         }
 7887:                     } elsif (($access eq 'inc') || ($access eq 'exc')) {
 7888:                         my @personnel = &Apache::loncommon::get_env_multiple('form.'.$role.'_staff_'.$access);
 7889:                         my @newspecstaff;
 7890:                         my @stored;
 7891:                         my @currstaff;
 7892:                         foreach my $person (sort(@personnel)) {
 7893:                             if ($domhelpdesk{$person}) {
 7894:                                 push(@stored,$person);
 7895:                             }
 7896:                         }
 7897:                         if (ref($current{$access}) eq 'ARRAY') {
 7898:                             my @diffs = &Apache::loncommon::compare_arrays(\@stored,$current{$access});
 7899:                             if (@diffs) {
 7900:                                 $changed{$role}{$access} = 1;
 7901:                             }
 7902:                         } elsif (@stored) {
 7903:                             $changed{$role}{$access} = 1;
 7904:                         }
 7905:                         $storehash{'internal.adhoc.'.$role} .= '='.join(',',@stored);
 7906:                         foreach my $person (@stored) {
 7907:                             my ($uname,$udom) = split(/:/,$person);
 7908:                             push(@newspecstaff,&Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($uname,$udom,'lastname'),$uname,$udom));
 7909:                         }
 7910:                         $newsettings{$role}{$access} = join(', ',sort(@newspecstaff));
 7911:                     }
 7912:                     $newsettings{$role}{'access'} = $access;
 7913:                 }
 7914:             } else {
 7915:                 if (($current{'access'} ne '') && (grep(/^\Q$current{'access'}\E$/,@accesstypes))) {
 7916:                     $changed{$role}{'access'} = 1;
 7917:                     $newsettings{$role} = {};
 7918:                     push(@todelete,'internal.adhoc.'.$role);
 7919:                 }
 7920:             }
 7921:             if (($env{'form.'.$role.'_incrs'}) && ($env{'form.'.$role.'_access'} eq 'none')) {
 7922:                 if (ref($current{'overridden'}) eq 'HASH') {
 7923:                     push(@todelete,'internal.adhocpriv.'.$role);
 7924:                 }
 7925:             } else {
 7926:                 my %full=();
 7927:                 my %levels= (
 7928:                              course => {},
 7929:                              domain => {},
 7930:                              system => {},
 7931:                             );
 7932:                 my %levelscurrent=(
 7933:                                    course => {},
 7934:                                    domain => {},
 7935:                                    system => {},
 7936:                                   );
 7937:                 &Apache::lonuserutils::custom_role_privs($customroles{$role},\%full,\%levels,\%levelscurrent);
 7938:                 my (@updatedon,@updatedoff,@override);
 7939:                 @override = &Apache::loncommon::get_env_multiple('form.'.$role.'_override');
 7940:                 if (@override) {
 7941:                     foreach my $priv (sort(keys(%full))) {
 7942:                         next unless ($levels{'course'}{$priv});
 7943:                         if (grep(/^\Q$priv\E$/,@override)) {
 7944:                             if ($levelscurrent{'course'}{$priv}) {
 7945:                                 push(@updatedoff,$priv);
 7946:                             } else {
 7947:                                 push(@updatedon,$priv);
 7948:                             }
 7949:                         }
 7950:                     }
 7951:                 }
 7952:                 if (@updatedon) {
 7953:                     $newsettings{$role}{'on'} = join('</li><li>', map { &Apache::lonnet::plaintext($_,$crstype) } (@updatedon));
 7954:                 }
 7955:                 if (@updatedoff) {
 7956:                     $newsettings{$role}{'off'} = join('</li><li>', map { &Apache::lonnet::plaintext($_,$crstype) } (@updatedoff));
 7957:                 }
 7958:                 if (ref($current{'overridden'}) eq 'HASH') {
 7959:                     if (ref($current{'overridden'}{'on'}) eq 'ARRAY') {
 7960:                         if (@updatedon) {
 7961:                             my @diffs = &Apache::loncommon::compare_arrays(\@updatedon,$current{'overridden'}{'on'});
 7962:                             if (@diffs) {
 7963:                                 $changed{$role}{'on'} = 1;
 7964:                             }
 7965:                         } else {
 7966:                             $changed{$role}{'on'} = 1;
 7967:                         }
 7968:                     } elsif (@updatedon) {
 7969:                         $changed{$role}{'on'} = 1;
 7970:                     }
 7971:                     if (ref($current{'overridden'}{'off'}) eq 'ARRAY') {
 7972:                         if (@updatedoff) {
 7973:                             my @diffs = &Apache::loncommon::compare_arrays(\@updatedoff,$current{'overridden'}{'off'});
 7974:                             if (@diffs) {
 7975:                                 $changed{$role}{'off'} = 1;
 7976:                             }
 7977:                         } else {
 7978:                             $changed{$role}{'off'} = 1;
 7979:                         }
 7980:                     } elsif (@updatedoff) {
 7981:                         $changed{$role}{'off'} = 1;
 7982:                     }
 7983:                 } else {
 7984:                     if (@updatedon) {
 7985:                         $changed{$role}{'on'} = 1;
 7986:                     }
 7987:                     if (@updatedoff) {
 7988:                         $changed{$role}{'off'} = 1;
 7989:                     }
 7990:                 }
 7991:                 if (ref($changed{$role}) eq 'HASH') {
 7992:                     if (($changed{$role}{'on'} || $changed{$role}{'off'})) {
 7993:                         my $newpriv;
 7994:                         if (@updatedon) {
 7995:                             $newpriv = 'on='.join(':',@updatedon);
 7996:                         }
 7997:                         if (@updatedoff) {
 7998:                             $newpriv .= ($newpriv ? ',' : '' ).'off='.join(':',@updatedoff);
 7999:                         }
 8000:                         if ($newpriv eq '') {
 8001:                             push(@todelete,'internal.adhocpriv.'.$role);
 8002:                         } else {
 8003:                             $storehash{'internal.adhocpriv.'.$role} = $newpriv;
 8004:                         }
 8005:                     }
 8006:                 }
 8007:             }
 8008:         }
 8009:         if (@incrs) {
 8010:             $storehash{'internal.adhocaccess'} = join(',',@incrs);
 8011:         } elsif (@todelete) {
 8012:             push(@todelete,'internal.adhocaccess');
 8013:         }
 8014:         if (keys(%changed)) {
 8015:             my ($putres,$delres);
 8016:             if (keys(%storehash)) {
 8017:                 $putres = &Apache::lonnet::put('environment',\%storehash,$cdom,$cnum);
 8018:                 my %newenvhash;
 8019:                 foreach my $key (keys(%storehash)) {
 8020:                     $newenvhash{'course.'.$env{'request.course.id'}.'.'.$key} = $storehash{$key};
 8021:                 }
 8022:                 &Apache::lonnet::appenv(\%newenvhash);
 8023:             }
 8024:             if (@todelete) {
 8025:                 $delres = &Apache::lonnet::del('environment',\@todelete,$cdom,$cnum);
 8026:                 foreach my $key (@todelete) {
 8027:                     &Apache::lonnet::delenv('course.'.$env{'request.course.id'}.'.'.$key);
 8028:                 }
 8029:             }
 8030:             if (($putres eq 'ok') || ($delres eq 'ok')) {
 8031:                 my %domconfig = &Apache::lonnet::get_dom('configuration',['helpsettings'],$cdom);
 8032:                 my (%domcurrent,%ordered,%description,%domusage);
 8033:                 if (ref($domconfig{'helpsettings'}) eq 'HASH') {
 8034:                     if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
 8035:                         %domcurrent = %{$domconfig{'helpsettings'}{'adhoc'}};
 8036:                     }
 8037:                 }
 8038:                 my $count = 0;
 8039:                 foreach my $role (sort(keys(%customroles))) {
 8040:                     my ($order,$desc);
 8041:                     if (ref($domcurrent{$role}) eq 'HASH') {
 8042:                         $order = $domcurrent{$role}{'order'};
 8043:                         $desc = $domcurrent{$role}{'desc'};
 8044:                     }
 8045:                     if ($order eq '') {
 8046:                         $order = $count;
 8047:                     }
 8048:                     $ordered{$order} = $role;
 8049:                     if ($desc ne '') {
 8050:                         $description{$role} = $desc;
 8051:                     } else {
 8052:                         $description{$role}= $role;
 8053:                     }
 8054:                     $count++;
 8055:                 }
 8056:                 my @roles_by_num = ();
 8057:                 foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 8058:                     push(@roles_by_num,$ordered{$item});
 8059:                 }
 8060:                 %domusage = &domain_adhoc_access(\%changed,\%domcurrent,\@accesstypes,$usertypes,$othertitle);
 8061:                 $r->print(&mt('Helpdesk access settings have been changed as follows').'<br />');
 8062:                 $r->print('<ul>');
 8063:                 foreach my $role (@roles_by_num) {
 8064:                     next unless (ref($changed{$role}) eq 'HASH');
 8065:                     $r->print('<li>'.&mt('Ad hoc role').': <b>'.$description{$role}.'</b>'.
 8066:                               '<ul>');
 8067:                     if ($changed{$role}{'access'} || $changed{$role}{'status'} || $changed{$role}{'inc'} || $changed{$role}{'exc'}) {
 8068:                         $r->print('<li>');
 8069:                         if ($env{'form.'.$role.'_incrs'}) {
 8070:                             if ($newsettings{$role}{'access'} eq 'all') {
 8071:                                 $r->print(&mt('All helpdesk staff can access '.lc($crstype).' with this role.'));
 8072:                             } elsif ($newsettings{$role}{'access'} eq 'none') {
 8073:                                 $r->print(&mt('No helpdesk staff can access '.lc($crstype).' with this role.'));
 8074:                             } elsif ($newsettings{$role}{'access'} eq 'status') {
 8075:                                 if ($newsettings{$role}{'status'}) {
 8076:                                     my ($access,$rest) = split(/=/,$storehash{'internal.adhoc.'.$role});
 8077:                                     if (split(/,/,$rest) > 1) {
 8078:                                         $r->print(&mt('Helpdesk staff can use this role if their institutional type is one of: [_1].',
 8079:                                                       $newsettings{$role}{'status'}));
 8080:                                     } else {
 8081:                                         $r->print(&mt('Helpdesk staff can use this role if their institutional type is: [_1].',
 8082:                                                       $newsettings{$role}{'status'}));
 8083:                                     }
 8084:                                 } else {
 8085:                                     $r->print(&mt('No helpdesk staff can access '.lc($crstype).' with this role.'));
 8086:                                 }
 8087:                             } elsif ($newsettings{$role}{'access'} eq 'exc') {
 8088:                                 if ($newsettings{$role}{'exc'}) {
 8089:                                     $r->print(&mt('Helpdesk staff who can use this role are as follows:').' '.$newsettings{$role}{'exc'}.'.');
 8090:                                 } else {
 8091:                                     $r->print(&mt('No helpdesk staff can access '.lc($crstype).' with this role.'));
 8092:                                 }
 8093:                             } elsif ($newsettings{$role}{'access'} eq 'inc') {
 8094:                                 if ($newsettings{$role}{'inc'}) {
 8095:                                     $r->print(&mt('All helpdesk staff may use this role except the following:').' '.$newsettings{$role}{'inc'}.'.');
 8096:                                 } else {
 8097:                                     $r->print(&mt('All helpdesk staff may use this role.'));
 8098:                                 }
 8099:                             }
 8100:                         } else {
 8101:                             $r->print(&mt('Default access set in the domain now applies.').'<br />'.
 8102:                                       '<span class="LC_cusr_emph">'.$domusage{$role}.'</span>');
 8103:                         }
 8104:                         $r->print('</li>');
 8105:                     }
 8106:                     unless ($newsettings{$role}{'access'} eq 'none') {
 8107:                         if ($changed{$role}{'off'}) {
 8108:                             if ($newsettings{$role}{'off'}) {
 8109:                                 $r->print('<li>'.&mt('Privileges which are available by default for this ad hoc role, but are disabled for this specific '.lc($crstype).':').
 8110:                                           '<ul><li>'.$newsettings{$role}{'off'}.'</li></ul></li>');
 8111:                             } else {
 8112:                                 $r->print('<li>'.&mt('All privileges available by default for this ad hoc role are enabled.').'</li>');
 8113:                             }
 8114:                         }
 8115:                         if ($changed{$role}{'on'}) {
 8116:                             if ($newsettings{$role}{'on'}) {
 8117:                                 $r->print('<li>'.&mt('Privileges which are not available by default for this ad hoc role, but are enabled for this specific '.lc($crstype).':').
 8118:                                           '<ul><li>'.$newsettings{$role}{'on'}.'</li></ul></li>');
 8119:                             } else {
 8120:                                 $r->print('<li>'.&mt('None of the privileges unavailable by default for this ad hoc role are enabled.').'</li>');
 8121:                             }
 8122:                         }
 8123:                     }
 8124:                     $r->print('</ul></li>');
 8125:                 }
 8126:                 $r->print('</ul>');
 8127:             }
 8128:         } else {
 8129:             $r->print(&mt('No changes made to helpdesk access settings.'));
 8130:         }
 8131:     }
 8132:     return;
 8133: }
 8134: 
 8135: #-------------------------------------------------- functions for &phase_two
 8136: sub user_search_result {
 8137:     my ($context,$srch) = @_;
 8138:     my %allhomes;
 8139:     my %inst_matches;
 8140:     my %srch_results;
 8141:     my ($response,$currstate,$forcenewuser,$dirsrchres);
 8142:     $srch->{'srchterm'} =~ s/\s+/ /g;
 8143:     if ($srch->{'srchby'} !~ /^(uname|lastname|lastfirst)$/) {
 8144:         $response = &mt('Invalid search.');
 8145:     }
 8146:     if ($srch->{'srchin'} !~ /^(crs|dom|alc|instd)$/) {
 8147:         $response = &mt('Invalid search.');
 8148:     }
 8149:     if ($srch->{'srchtype'} !~ /^(exact|contains|begins)$/) {
 8150:         $response = &mt('Invalid search.');
 8151:     }
 8152:     if ($srch->{'srchterm'} eq '') {
 8153:         $response = &mt('You must enter a search term.');
 8154:     }
 8155:     if ($srch->{'srchterm'} =~ /^\s+$/) {
 8156:         $response = &mt('Your search term must contain more than just spaces.');
 8157:     }
 8158:     if (($srch->{'srchin'} eq 'dom') || ($srch->{'srchin'} eq 'instd')) {
 8159:         if (($srch->{'srchdomain'} eq '') || 
 8160: 	    ! (&Apache::lonnet::domain($srch->{'srchdomain'}))) {
 8161:             $response = &mt('You must specify a valid domain when searching in a domain or institutional directory.')
 8162:         }
 8163:     }
 8164:     if (($srch->{'srchin'} eq 'dom') || ($srch->{'srchin'} eq 'crs') ||
 8165:         ($srch->{'srchin'} eq 'alc')) {
 8166:         if ($srch->{'srchby'} eq 'uname') {
 8167:             my $unamecheck = $srch->{'srchterm'};
 8168:             if ($srch->{'srchtype'} eq 'contains') {
 8169:                 if ($unamecheck !~ /^\w/) {
 8170:                     $unamecheck = 'a'.$unamecheck; 
 8171:                 }
 8172:             }
 8173:             if ($unamecheck !~ /^$match_username$/) {
 8174:                 $response = &mt('You must specify a valid username. Only the following are allowed: letters numbers - . @');
 8175:             }
 8176:         }
 8177:     }
 8178:     if ($response ne '') {
 8179:         $response = '<span class="LC_warning">'.$response.'</span><br />';
 8180:     }
 8181:     if ($srch->{'srchin'} eq 'instd') {
 8182:         my $instd_chk = &instdirectorysrch_check($srch);
 8183:         if ($instd_chk ne 'ok') {
 8184:             my $domd_chk = &domdirectorysrch_check($srch);
 8185:             $response .= '<span class="LC_warning">'.$instd_chk.'</span><br />';
 8186:             if ($domd_chk eq 'ok') {
 8187:                 $response .= &mt('You may want to search in the LON-CAPA domain instead of the institutional directory.');
 8188:             }
 8189:             $response .= '<br />';
 8190:         }
 8191:     } else {
 8192:         unless (($context eq 'requestcrs') && ($srch->{'srchtype'} eq 'exact')) {
 8193:             my $domd_chk = &domdirectorysrch_check($srch);
 8194:             if ($domd_chk ne 'ok') {
 8195:                 my $instd_chk = &instdirectorysrch_check($srch);
 8196:                 $response .= '<span class="LC_warning">'.$domd_chk.'</span><br />';
 8197:                 if ($instd_chk eq 'ok') {
 8198:                     $response .= &mt('You may want to search in the institutional directory instead of the LON-CAPA domain.');
 8199:                 }
 8200:                 $response .= '<br />';
 8201:             }
 8202:         }
 8203:     }
 8204:     if ($response ne '') {
 8205:         return ($currstate,$response);
 8206:     }
 8207:     if ($srch->{'srchby'} eq 'uname') {
 8208:         if (($srch->{'srchin'} eq 'dom') || ($srch->{'srchin'} eq 'crs')) {
 8209:             if ($env{'form.forcenew'}) {
 8210:                 if ($srch->{'srchdomain'} ne $env{'request.role.domain'}) {
 8211:                     my $uhome=&Apache::lonnet::homeserver($srch->{'srchterm'},$srch->{'srchdomain'});
 8212:                     if ($uhome eq 'no_host') {
 8213:                         my $domdesc = &Apache::lonnet::domain($env{'request.role.domain'},'description');
 8214:                         my $showdom = &display_domain_info($env{'request.role.domain'});
 8215:                         $response = &mt('New users can only be created in the domain to which your current role belongs - [_1].',$showdom);
 8216:                     } else {
 8217:                         $currstate = 'modify';
 8218:                     }
 8219:                 } else {
 8220:                     $currstate = 'modify';
 8221:                 }
 8222:             } else {
 8223:                 if ($srch->{'srchin'} eq 'dom') {
 8224:                     if ($srch->{'srchtype'} eq 'exact') {
 8225:                         my $uhome=&Apache::lonnet::homeserver($srch->{'srchterm'},$srch->{'srchdomain'});
 8226:                         if ($uhome eq 'no_host') {
 8227:                             ($currstate,$response,$forcenewuser) =
 8228:                                 &build_search_response($context,$srch,%srch_results);
 8229:                         } else {
 8230:                             $currstate = 'modify';
 8231:                             if ($env{'form.action'} eq 'accesslogs') {
 8232:                                 $currstate = 'activity';
 8233:                             }
 8234:                             my $uname = $srch->{'srchterm'};
 8235:                             my $udom = $srch->{'srchdomain'};
 8236:                             $srch_results{$uname.':'.$udom} =
 8237:                                 { &Apache::lonnet::get('environment',
 8238:                                                        ['firstname',
 8239:                                                         'lastname',
 8240:                                                         'permanentemail'],
 8241:                                                          $udom,$uname)
 8242:                                 };
 8243:                         }
 8244:                     } else {
 8245:                         %srch_results = &Apache::lonnet::usersearch($srch);
 8246:                         ($currstate,$response,$forcenewuser) =
 8247:                             &build_search_response($context,$srch,%srch_results);
 8248:                     }
 8249:                 } else {
 8250:                     my $courseusers = &get_courseusers();
 8251:                     if ($srch->{'srchtype'} eq 'exact') {
 8252:                         if (exists($courseusers->{$srch->{'srchterm'}.':'.$srch->{'srchdomain'}})) {
 8253:                             $currstate = 'modify';
 8254:                         } else {
 8255:                             ($currstate,$response,$forcenewuser) =
 8256:                                 &build_search_response($context,$srch,%srch_results);
 8257:                         }
 8258:                     } else {
 8259:                         foreach my $user (keys(%$courseusers)) {
 8260:                             my ($cuname,$cudomain) = split(/:/,$user);
 8261:                             if ($cudomain eq $srch->{'srchdomain'}) {
 8262:                                 my $matched = 0;
 8263:                                 if ($srch->{'srchtype'} eq 'begins') {
 8264:                                     if ($cuname =~ /^\Q$srch->{'srchterm'}\E/i) {
 8265:                                         $matched = 1;
 8266:                                     }
 8267:                                 } else {
 8268:                                     if ($cuname =~ /\Q$srch->{'srchterm'}\E/i) {
 8269:                                         $matched = 1;
 8270:                                     }
 8271:                                 }
 8272:                                 if ($matched) {
 8273:                                     $srch_results{$user} = 
 8274: 					{&Apache::lonnet::get('environment',
 8275: 							     ['firstname',
 8276: 							      'lastname',
 8277: 							      'permanentemail'],
 8278: 							      $cudomain,$cuname)};
 8279:                                 }
 8280:                             }
 8281:                         }
 8282:                         ($currstate,$response,$forcenewuser) =
 8283:                             &build_search_response($context,$srch,%srch_results);
 8284:                     }
 8285:                 }
 8286:             }
 8287:         } elsif ($srch->{'srchin'} eq 'alc') {
 8288:             $currstate = 'query';
 8289:         } elsif ($srch->{'srchin'} eq 'instd') {
 8290:             ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query($srch);
 8291:             if ($dirsrchres eq 'ok') {
 8292:                 ($currstate,$response,$forcenewuser) = 
 8293:                     &build_search_response($context,$srch,%srch_results);
 8294:             } else {
 8295:                 my $showdom = &display_domain_info($srch->{'srchdomain'});
 8296:                 $response = '<span class="LC_warning">'.
 8297:                     &mt('Institutional directory search is not available in domain: [_1]',$showdom).
 8298:                     '</span><br />'.
 8299:                     &mt('You may want to search in the LON-CAPA domain instead of the institutional directory.').
 8300:                     '<br />'; 
 8301:             }
 8302:         }
 8303:     } else {
 8304:         if ($srch->{'srchin'} eq 'dom') {
 8305:             %srch_results = &Apache::lonnet::usersearch($srch);
 8306:             ($currstate,$response,$forcenewuser) = 
 8307:                 &build_search_response($context,$srch,%srch_results); 
 8308:         } elsif ($srch->{'srchin'} eq 'crs') {
 8309:             my $courseusers = &get_courseusers(); 
 8310:             foreach my $user (keys(%$courseusers)) {
 8311:                 my ($uname,$udom) = split(/:/,$user);
 8312:                 my %names = &Apache::loncommon::getnames($uname,$udom);
 8313:                 my %emails = &Apache::loncommon::getemails($uname,$udom);
 8314:                 if ($srch->{'srchby'} eq 'lastname') {
 8315:                     if ((($srch->{'srchtype'} eq 'exact') && 
 8316:                          ($names{'lastname'} eq $srch->{'srchterm'})) || 
 8317:                         (($srch->{'srchtype'} eq 'begins') &&
 8318:                          ($names{'lastname'} =~ /^\Q$srch->{'srchterm'}\E/i)) ||
 8319:                         (($srch->{'srchtype'} eq 'contains') &&
 8320:                          ($names{'lastname'} =~ /\Q$srch->{'srchterm'}\E/i))) {
 8321:                         $srch_results{$user} = {firstname => $names{'firstname'},
 8322:                                             lastname => $names{'lastname'},
 8323:                                             permanentemail => $emails{'permanentemail'},
 8324:                                            };
 8325:                     }
 8326:                 } elsif ($srch->{'srchby'} eq 'lastfirst') {
 8327:                     my ($srchlast,$srchfirst) = split(/,/,$srch->{'srchterm'});
 8328:                     $srchlast =~ s/\s+$//;
 8329:                     $srchfirst =~ s/^\s+//;
 8330:                     if ($srch->{'srchtype'} eq 'exact') {
 8331:                         if (($names{'lastname'} eq $srchlast) &&
 8332:                             ($names{'firstname'} eq $srchfirst)) {
 8333:                             $srch_results{$user} = {firstname => $names{'firstname'},
 8334:                                                 lastname => $names{'lastname'},
 8335:                                                 permanentemail => $emails{'permanentemail'},
 8336: 
 8337:                                            };
 8338:                         }
 8339:                     } elsif ($srch->{'srchtype'} eq 'begins') {
 8340:                         if (($names{'lastname'} =~ /^\Q$srchlast\E/i) &&
 8341:                             ($names{'firstname'} =~ /^\Q$srchfirst\E/i)) {
 8342:                             $srch_results{$user} = {firstname => $names{'firstname'},
 8343:                                                 lastname => $names{'lastname'},
 8344:                                                 permanentemail => $emails{'permanentemail'},
 8345:                                                };
 8346:                         }
 8347:                     } else {
 8348:                         if (($names{'lastname'} =~ /\Q$srchlast\E/i) && 
 8349:                             ($names{'firstname'} =~ /\Q$srchfirst\E/i)) {
 8350:                             $srch_results{$user} = {firstname => $names{'firstname'},
 8351:                                                 lastname => $names{'lastname'},
 8352:                                                 permanentemail => $emails{'permanentemail'},
 8353:                                                };
 8354:                         }
 8355:                     }
 8356:                 }
 8357:             }
 8358:             ($currstate,$response,$forcenewuser) = 
 8359:                 &build_search_response($context,$srch,%srch_results); 
 8360:         } elsif ($srch->{'srchin'} eq 'alc') {
 8361:             $currstate = 'query';
 8362:         } elsif ($srch->{'srchin'} eq 'instd') {
 8363:             ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query($srch); 
 8364:             if ($dirsrchres eq 'ok') {
 8365:                 ($currstate,$response,$forcenewuser) = 
 8366:                     &build_search_response($context,$srch,%srch_results);
 8367:             } else {
 8368:                 my $showdom = &display_domain_info($srch->{'srchdomain'});
 8369:                 $response = '<span class="LC_warning">'.
 8370:                     &mt('Institutional directory search is not available in domain: [_1]',$showdom).
 8371:                     '</span><br />'.
 8372:                     &mt('You may want to search in the LON-CAPA domain instead of the institutional directory.').
 8373:                     '<br />';
 8374:             }
 8375:         }
 8376:     }
 8377:     return ($currstate,$response,$forcenewuser,\%srch_results);
 8378: }
 8379: 
 8380: sub domdirectorysrch_check {
 8381:     my ($srch) = @_;
 8382:     my $response;
 8383:     my %dom_inst_srch = &Apache::lonnet::get_dom('configuration',
 8384:                                              ['directorysrch'],$srch->{'srchdomain'});
 8385:     my $showdom = &display_domain_info($srch->{'srchdomain'});
 8386:     if (ref($dom_inst_srch{'directorysrch'}) eq 'HASH') {
 8387:         if ($dom_inst_srch{'directorysrch'}{'lcavailable'} eq '0') {
 8388:             return &mt('LON-CAPA directory search is not available in domain: [_1]',$showdom);
 8389:         }
 8390:         if ($dom_inst_srch{'directorysrch'}{'lclocalonly'}) {
 8391:             if ($env{'request.role.domain'} ne $srch->{'srchdomain'}) {
 8392:                 return &mt('LON-CAPA directory search in domain: [_1] is only allowed for users with a current role in the domain.',$showdom);
 8393:             }
 8394:         }
 8395:     }
 8396:     return 'ok';
 8397: }
 8398: 
 8399: sub instdirectorysrch_check {
 8400:     my ($srch) = @_;
 8401:     my $can_search = 0;
 8402:     my $response;
 8403:     my %dom_inst_srch = &Apache::lonnet::get_dom('configuration',
 8404:                                              ['directorysrch'],$srch->{'srchdomain'});
 8405:     my $showdom = &display_domain_info($srch->{'srchdomain'});
 8406:     if (ref($dom_inst_srch{'directorysrch'}) eq 'HASH') {
 8407:         if (!$dom_inst_srch{'directorysrch'}{'available'}) {
 8408:             return &mt('Institutional directory search is not available in domain: [_1]',$showdom); 
 8409:         }
 8410:         if ($dom_inst_srch{'directorysrch'}{'localonly'}) {
 8411:             if ($env{'request.role.domain'} ne $srch->{'srchdomain'}) {
 8412:                 return &mt('Institutional directory search in domain: [_1] is only allowed for users with a current role in the domain.',$showdom); 
 8413:             }
 8414:             my @usertypes = split(/:/,$env{'environment.inststatus'});
 8415:             if (!@usertypes) {
 8416:                 push(@usertypes,'default');
 8417:             }
 8418:             if (ref($dom_inst_srch{'directorysrch'}{'cansearch'}) eq 'ARRAY') {
 8419:                 foreach my $type (@usertypes) {
 8420:                     if (grep(/^\Q$type\E$/,@{$dom_inst_srch{'directorysrch'}{'cansearch'}})) {
 8421:                         $can_search = 1;
 8422:                         last;
 8423:                     }
 8424:                 }
 8425:             }
 8426:             if (!$can_search) {
 8427:                 my ($insttypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($srch->{'srchdomain'});
 8428:                 my @longtypes; 
 8429:                 foreach my $item (@usertypes) {
 8430:                     if (defined($insttypes->{$item})) { 
 8431:                         push (@longtypes,$insttypes->{$item});
 8432:                     } elsif ($item eq 'default') {
 8433:                         push (@longtypes,&mt('other')); 
 8434:                     }
 8435:                 }
 8436:                 my $insttype_str = join(', ',@longtypes); 
 8437:                 return &mt('Institutional directory search in domain: [_1] is not available to your user type: ',$showdom).$insttype_str;
 8438:             }
 8439:         } else {
 8440:             $can_search = 1;
 8441:         }
 8442:     } else {
 8443:         return &mt('Institutional directory search has not been configured for domain: [_1]',$showdom);
 8444:     }
 8445:     my %longtext = &Apache::lonlocal::texthash (
 8446:                        uname     => 'username',
 8447:                        lastfirst => 'last name, first name',
 8448:                        lastname  => 'last name',
 8449:                        contains  => 'contains',
 8450:                        exact     => 'as exact match to',
 8451:                        begins    => 'begins with',
 8452:                    );
 8453:     if ($can_search) {
 8454:         if (ref($dom_inst_srch{'directorysrch'}{'searchby'}) eq 'ARRAY') {
 8455:             if (!grep(/^\Q$srch->{'srchby'}\E$/,@{$dom_inst_srch{'directorysrch'}{'searchby'}})) {
 8456:                 return &mt('Institutional directory search in domain: [_1] is not available for searching by "[_2]"',$showdom,$longtext{$srch->{'srchby'}});
 8457:             }
 8458:         } else {
 8459:             return &mt('Institutional directory search in domain: [_1] is not available.', $showdom);
 8460:         }
 8461:     }
 8462:     if ($can_search) {
 8463:         if (ref($dom_inst_srch{'directorysrch'}{'searchtypes'}) eq 'ARRAY') {
 8464:             if (grep(/^\Q$srch->{'srchtype'}\E/,@{$dom_inst_srch{'directorysrch'}{'searchtypes'}})) {
 8465:                 return 'ok';
 8466:             } else {
 8467:                 return &mt('Institutional directory search in domain [_1] is not available for the requested search type: "[_2]"',$showdom,$longtext{$srch->{'srchtype'}});
 8468:             }
 8469:         } else {
 8470:             if ((($dom_inst_srch{'directorysrch'}{'searchtypes'} eq 'specify') &&
 8471:                  ($srch->{'srchtype'} eq 'exact' || $srch->{'srchtype'} eq 'contains')) ||
 8472:                 ($dom_inst_srch{'directorysrch'}{'searchtypes'} eq $srch->{'srchtype'})) {
 8473:                 return 'ok';
 8474:             } else {
 8475:                 return &mt('Institutional directory search in domain [_1] is not available for the requested search type: "[_2]"',$showdom,$longtext{$srch->{'srchtype'}});
 8476:             }
 8477:         }
 8478:     }
 8479: }
 8480: 
 8481: sub get_courseusers {
 8482:     my %advhash;
 8483:     my $classlist = &Apache::loncoursedata::get_classlist();
 8484:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles();
 8485:     foreach my $role (sort(keys(%coursepersonnel))) {
 8486:         foreach my $user (split(/\,/,$coursepersonnel{$role})) {
 8487: 	    if (!exists($classlist->{$user})) {
 8488: 		$classlist->{$user} = [];
 8489: 	    }
 8490:         }
 8491:     }
 8492:     return $classlist;
 8493: }
 8494: 
 8495: sub build_search_response {
 8496:     my ($context,$srch,%srch_results) = @_;
 8497:     my ($currstate,$response,$forcenewuser);
 8498:     my %names = (
 8499:           'uname'     => 'username',
 8500:           'lastname'  => 'last name',
 8501:           'lastfirst' => 'last name, first name',
 8502:           'crs'       => 'this course',
 8503:           'dom'       => 'LON-CAPA domain',
 8504:           'instd'     => 'the institutional directory for domain',
 8505:     );
 8506: 
 8507:     my %single = (
 8508:                    begins   => 'A match',
 8509:                    contains => 'A match',
 8510:                    exact    => 'An exact match',
 8511:                  );
 8512:     my %nomatch = (
 8513:                    begins   => 'No match',
 8514:                    contains => 'No match',
 8515:                    exact    => 'No exact match',
 8516:                   );
 8517:     if (keys(%srch_results) > 1) {
 8518:         $currstate = 'select';
 8519:     } else {
 8520:         if (keys(%srch_results) == 1) {
 8521:             if ($env{'form.action'} eq 'accesslogs') {
 8522:                 $currstate = 'activity';
 8523:             } else {
 8524:                 $currstate = 'modify';
 8525:             }
 8526:             $response = &mt("$single{$srch->{'srchtype'}} was found for the $names{$srch->{'srchby'}} ([_1]) in $names{$srch->{'srchin'}}.",$srch->{'srchterm'});
 8527:             if ($srch->{'srchin'} eq 'dom' || $srch->{'srchin'} eq 'instd') {
 8528:                 $response .= ': '.&display_domain_info($srch->{'srchdomain'});
 8529:             }
 8530:         } else { # Search has nothing found. Prepare message to user.
 8531:             $response = '<span class="LC_warning">';
 8532:             if ($srch->{'srchin'} eq 'dom' || $srch->{'srchin'} eq 'instd') {
 8533:                 $response .= &mt("$nomatch{$srch->{'srchtype'}} found for the $names{$srch->{'srchby'}} [_1] in $names{$srch->{'srchin'}}: [_2]",
 8534:                                  '<b>'.$srch->{'srchterm'}.'</b>',
 8535:                                  &display_domain_info($srch->{'srchdomain'}));
 8536:             } else {
 8537:                 $response .= &mt("$nomatch{$srch->{'srchtype'}} found for the $names{$srch->{'srchby'}} [_1] in $names{$srch->{'srchin'}}.",
 8538:                                  '<b>'.$srch->{'srchterm'}.'</b>');
 8539:             }
 8540:             $response .= '</span>';
 8541: 
 8542:             if ($srch->{'srchin'} ne 'alc') {
 8543:                 $forcenewuser = 1;
 8544:                 my $cansrchinst = 0; 
 8545:                 if ($srch->{'srchdomain'}) {
 8546:                     my %domconfig = &Apache::lonnet::get_dom('configuration',['directorysrch'],$srch->{'srchdomain'});
 8547:                     if (ref($domconfig{'directorysrch'}) eq 'HASH') {
 8548:                         if ($domconfig{'directorysrch'}{'available'}) {
 8549:                             $cansrchinst = 1;
 8550:                         } 
 8551:                     }
 8552:                 }
 8553:                 if ((($srch->{'srchby'} eq 'lastfirst') || 
 8554:                      ($srch->{'srchby'} eq 'lastname')) &&
 8555:                     ($srch->{'srchin'} eq 'dom')) {
 8556:                     if ($cansrchinst) {
 8557:                         $response .= '<br />'.&mt('You may want to broaden your search to a search of the institutional directory for the domain.');
 8558:                     }
 8559:                 }
 8560:                 if ($srch->{'srchin'} eq 'crs') {
 8561:                     $response .= '<br />'.&mt('You may want to broaden your search to the selected LON-CAPA domain.');
 8562:                 }
 8563:             }
 8564:             my $createdom = $env{'request.role.domain'};
 8565:             if ($context eq 'requestcrs') {
 8566:                 if ($env{'form.coursedom'} ne '') {
 8567:                     $createdom = $env{'form.coursedom'};
 8568:                 }
 8569:             }
 8570:             unless (($env{'form.action'} eq 'accesslogs') || (($srch->{'srchby'} eq 'uname') && ($srch->{'srchin'} eq 'dom') &&
 8571:                     ($srch->{'srchtype'} eq 'exact') && ($srch->{'srchdomain'} eq $createdom))) {
 8572:                 my $cancreate =
 8573:                     &Apache::lonuserutils::can_create_user($createdom,$context);
 8574:                 my $targetdom = '<span class="LC_cusr_emph">'.$createdom.'</span>';
 8575:                 if ($cancreate) {
 8576:                     my $showdom = &display_domain_info($createdom); 
 8577:                     $response .= '<br /><br />'
 8578:                                 .'<b>'.&mt('To add a new user:').'</b>'
 8579:                                 .'<br />';
 8580:                     if ($context eq 'requestcrs') {
 8581:                         $response .= &mt("(You can only define new users in the new course's domain - [_1])",$targetdom);
 8582:                     } else {
 8583:                         $response .= &mt("(You can only create new users in your current role's domain - [_1])",$targetdom);
 8584:                     }
 8585:                     $response .='<ul><li>'
 8586:                                 .&mt("Set 'Domain/institution to search' to: [_1]",'<span class="LC_cusr_emph">'.$showdom.'</span>')
 8587:                                 .'</li><li>'
 8588:                                 .&mt("Set 'Search criteria' to: [_1]username is ..... in selected LON-CAPA domain[_2]",'<span class="LC_cusr_emph">','</span>')
 8589:                                 .'</li><li>'
 8590:                                 .&mt('Provide the proposed username')
 8591:                                 .'</li><li>'
 8592:                                 .&mt("Click 'Search'")
 8593:                                 .'</li></ul><br />';
 8594:                 } else {
 8595:                     unless (($context eq 'domain') && ($env{'form.action'} eq 'singleuser')) {
 8596:                         my $helplink = ' href="javascript:helpMenu('."'display'".')"';
 8597:                         $response .= '<br /><br />';
 8598:                         if ($context eq 'requestcrs') {
 8599:                             $response .= &mt("You are not authorized to define new users in the new course's domain - [_1].",$targetdom);
 8600:                         } else {
 8601:                             $response .= &mt("You are not authorized to create new users in your current role's domain - [_1].",$targetdom);
 8602:                         }
 8603:                         $response .= '<br />'
 8604:                                      .&mt('Please contact the [_1]helpdesk[_2] if you need to create a new user.'
 8605:                                         ,' <a'.$helplink.'>'
 8606:                                         ,'</a>')
 8607:                                      .'<br />';
 8608:                     }
 8609:                 }
 8610:             }
 8611:         }
 8612:     }
 8613:     return ($currstate,$response,$forcenewuser);
 8614: }
 8615: 
 8616: sub display_domain_info {
 8617:     my ($dom) = @_;
 8618:     my $output = $dom;
 8619:     if ($dom ne '') { 
 8620:         my $domdesc = &Apache::lonnet::domain($dom,'description');
 8621:         if ($domdesc ne '') {
 8622:             $output .= ' <span class="LC_cusr_emph">('.$domdesc.')</span>';
 8623:         }
 8624:     }
 8625:     return $output;
 8626: }
 8627: 
 8628: sub crumb_utilities {
 8629:     my %elements = (
 8630:        crtuser => {
 8631:            srchterm => 'text',
 8632:            srchin => 'selectbox',
 8633:            srchby => 'selectbox',
 8634:            srchtype => 'selectbox',
 8635:            srchdomain => 'selectbox',
 8636:        },
 8637:        crtusername => {
 8638:            srchterm => 'text',
 8639:            srchdomain => 'selectbox',
 8640:        },
 8641:        docustom => {
 8642:            rolename => 'selectbox',
 8643:            newrolename => 'textbox',
 8644:        },
 8645:        studentform => {
 8646:            srchterm => 'text',
 8647:            srchin => 'selectbox',
 8648:            srchby => 'selectbox',
 8649:            srchtype => 'selectbox',
 8650:            srchdomain => 'selectbox',
 8651:        },
 8652:     );
 8653: 
 8654:     my $jsback .= qq|
 8655: function backPage(formname,prevphase,prevstate) {
 8656:     if (typeof prevphase == 'undefined') {
 8657:         formname.phase.value = '';
 8658:     }
 8659:     else {  
 8660:         formname.phase.value = prevphase;
 8661:     }
 8662:     if (typeof prevstate == 'undefined') {
 8663:         formname.currstate.value = '';
 8664:     }
 8665:     else {
 8666:         formname.currstate.value = prevstate;
 8667:     }
 8668:     formname.submit();
 8669: }
 8670: |;
 8671:     return ($jsback,\%elements);
 8672: }
 8673: 
 8674: sub course_level_table {
 8675:     my ($inccourses,$showcredits,$defaultcredits) = @_;
 8676:     return unless (ref($inccourses) eq 'HASH');
 8677:     my $table = '';
 8678: # Custom Roles?
 8679: 
 8680:     my %customroles=&Apache::lonuserutils::my_custom_roles();
 8681:     my %lt=&Apache::lonlocal::texthash(
 8682:             'exs'  => "Existing sections",
 8683:             'new'  => "Define new section",
 8684:             'ssd'  => "Set Start Date",
 8685:             'sed'  => "Set End Date",
 8686:             'crl'  => "Course Level",
 8687:             'act'  => "Activate",
 8688:             'rol'  => "Role",
 8689:             'ext'  => "Extent",
 8690:             'grs'  => "Section",
 8691:             'crd'  => "Credits",
 8692:             'sta'  => "Start",
 8693:             'end'  => "End"
 8694:     );
 8695: 
 8696:     foreach my $protectedcourse (sort(keys(%{$inccourses}))) {
 8697: 	my $thiscourse=$protectedcourse;
 8698: 	$thiscourse=~s:_:/:g;
 8699: 	my %coursedata=&Apache::lonnet::coursedescription($thiscourse);
 8700:         my $isowner = &Apache::lonuserutils::is_courseowner($protectedcourse,$coursedata{'internal.courseowner'});
 8701: 	my $area=$coursedata{'description'};
 8702:         my $crstype=$coursedata{'type'};
 8703: 	if (!defined($area)) { $area=&mt('Unavailable course').': '.$protectedcourse; }
 8704: 	my ($domain,$cnum)=split(/\//,$thiscourse);
 8705:         my %sections_count;
 8706:         if (defined($env{'request.course.id'})) {
 8707:             if ($env{'request.course.id'} eq $domain.'_'.$cnum) {
 8708:                 %sections_count = 
 8709: 		    &Apache::loncommon::get_sections($domain,$cnum);
 8710:             }
 8711:         }
 8712:         my @roles = &Apache::lonuserutils::roles_by_context('course','',$crstype);
 8713: 	foreach my $role (@roles) {
 8714:             my $plrole=&Apache::lonnet::plaintext($role,$crstype);
 8715: 	    if ((&Apache::lonnet::allowed('c'.$role,$thiscourse)) ||
 8716:                 ((($role eq 'cc') || ($role eq 'co')) && ($isowner))) {
 8717:                 $table .= &course_level_row($protectedcourse,$role,$area,$domain,
 8718:                                             $plrole,\%sections_count,\%lt,
 8719:                                             $showcredits,$defaultcredits,$crstype);
 8720:             } elsif ($env{'request.course.sec'} ne '') {
 8721:                 if (&Apache::lonnet::allowed('c'.$role,$thiscourse.'/'.
 8722:                                              $env{'request.course.sec'})) {
 8723:                     $table .= &course_level_row($protectedcourse,$role,$area,$domain,
 8724:                                                 $plrole,\%sections_count,\%lt,
 8725:                                                 $showcredits,$defaultcredits,$crstype);
 8726:                 }
 8727:             }
 8728:         }
 8729:         if (&Apache::lonnet::allowed('ccr',$thiscourse)) {
 8730:             foreach my $cust (sort(keys(%customroles))) {
 8731:                 next if ($crstype eq 'Community' && $customroles{$cust} =~ /bre\&S/);
 8732:                 my $role = 'cr_cr_'.$env{'user.domain'}.'_'.$env{'user.name'}.'_'.$cust;
 8733:                 $table .= &course_level_row($protectedcourse,$role,$area,$domain,
 8734:                                             $cust,\%sections_count,\%lt,
 8735:                                             $showcredits,$defaultcredits,$crstype);
 8736:             }
 8737: 	}
 8738:     }
 8739:     return '' if ($table eq ''); # return nothing if there is nothing 
 8740:                                  # in the table
 8741:     my $result;
 8742:     if (!$env{'request.course.id'}) {
 8743:         $result = '<h4>'.$lt{'crl'}.'</h4>'."\n";
 8744:     }
 8745:     $result .= 
 8746: &Apache::loncommon::start_data_table().
 8747: &Apache::loncommon::start_data_table_header_row().
 8748: '<th>'.$lt{'act'}.'</th><th>'.$lt{'rol'}.'</th>'."\n".
 8749: '<th>'.$lt{'ext'}.'</th><th>'."\n";
 8750:     if ($showcredits) {
 8751:         $result .= $lt{'crd'}.'</th>';
 8752:     }
 8753:     $result .=
 8754: '<th>'.$lt{'grs'}.'</th><th>'.$lt{'sta'}.'</th>'."\n".
 8755: '<th>'.$lt{'end'}.'</th>'.
 8756: &Apache::loncommon::end_data_table_header_row().
 8757: $table.
 8758: &Apache::loncommon::end_data_table();
 8759:     return $result;
 8760: }
 8761: 
 8762: sub course_level_row {
 8763:     my ($protectedcourse,$role,$area,$domain,$plrole,$sections_count,
 8764:         $lt,$showcredits,$defaultcredits,$crstype) = @_;
 8765:     my $creditem;
 8766:     my $row = &Apache::loncommon::start_data_table_row().
 8767:               ' <td><input type="checkbox" name="act_'.
 8768:               $protectedcourse.'_'.$role.'" /></td>'."\n".
 8769:               ' <td>'.$plrole.'</td>'."\n".
 8770:               ' <td>'.$area.'<br />Domain: '.$domain.'</td>'."\n";
 8771:     if (($showcredits) && ($role eq 'st') && ($crstype eq 'Course')) {
 8772:         $row .= 
 8773:             '<td><input type="text" name="credits_'.$protectedcourse.'_'.
 8774:             $role.'" size="3" value="'.$defaultcredits.'" /></td>';
 8775:     } else {
 8776:         $row .= '<td>&nbsp;</td>';
 8777:     }
 8778:     if (($role eq 'cc') || ($role eq 'co')) {
 8779:         $row .= '<td>&nbsp;</td>';
 8780:     } elsif ($env{'request.course.sec'} ne '') {
 8781:         $row .= ' <td><input type="hidden" value="'.
 8782:                 $env{'request.course.sec'}.'" '.
 8783:                 'name="sec_'.$protectedcourse.'_'.$role.'" />'.
 8784:                 $env{'request.course.sec'}.'</td>';
 8785:     } else {
 8786:         if (ref($sections_count) eq 'HASH') {
 8787:             my $currsec = 
 8788:                 &Apache::lonuserutils::course_sections($sections_count,
 8789:                                                        $protectedcourse.'_'.$role);
 8790:             $row .= '<td><table class="LC_createuser">'."\n".
 8791:                     '<tr class="LC_section_row">'."\n".
 8792:                     ' <td valign="top">'.$lt->{'exs'}.'<br />'.
 8793:                        $currsec.'</td>'."\n".
 8794:                      ' <td>&nbsp;&nbsp;</td>'."\n".
 8795:                      ' <td valign="top">&nbsp;'.$lt->{'new'}.'<br />'.
 8796:                      '<input type="text" name="newsec_'.$protectedcourse.'_'.$role.
 8797:                      '" value="" />'.
 8798:                      '<input type="hidden" '.
 8799:                      'name="sec_'.$protectedcourse.'_'.$role.'" /></td>'."\n".
 8800:                      '</tr></table></td>'."\n";
 8801:         } else {
 8802:             $row .= '<td><input type="text" size="10" '.
 8803:                     'name="sec_'.$protectedcourse.'_'.$role.'" /></td>'."\n";
 8804:         }
 8805:     }
 8806:     $row .= <<ENDTIMEENTRY;
 8807: <td><input type="hidden" name="start_$protectedcourse\_$role" value="" />
 8808: <a href=
 8809: "javascript:pjump('date_start','Start Date $plrole',document.cu.start_$protectedcourse\_$role.value,'start_$protectedcourse\_$role','cu.pres','dateset')">$lt->{'ssd'}</a></td>
 8810: <td><input type="hidden" name="end_$protectedcourse\_$role" value="" />
 8811: <a href=
 8812: "javascript:pjump('date_end','End Date $plrole',document.cu.end_$protectedcourse\_$role.value,'end_$protectedcourse\_$role','cu.pres','dateset')">$lt->{'sed'}</a></td>
 8813: ENDTIMEENTRY
 8814:     $row .= &Apache::loncommon::end_data_table_row();
 8815:     return $row;
 8816: }
 8817: 
 8818: sub course_level_dc {
 8819:     my ($dcdom,$showcredits) = @_;
 8820:     my %customroles=&Apache::lonuserutils::my_custom_roles();
 8821:     my @roles = &Apache::lonuserutils::roles_by_context('course');
 8822:     my $hiddenitems = '<input type="hidden" name="dcdomain" value="'.$dcdom.'" />'.
 8823:                       '<input type="hidden" name="origdom" value="'.$dcdom.'" />'.
 8824:                       '<input type="hidden" name="dccourse" value="" />';
 8825:     my $courseform=&Apache::loncommon::selectcourse_link
 8826:             ('cu','dccourse','dcdomain','coursedesc',undef,undef,'Select','crstype');
 8827:     my $credit_elem;
 8828:     if ($showcredits) {
 8829:         $credit_elem = 'credits';
 8830:     }
 8831:     my $cb_jscript = &Apache::loncommon::coursebrowser_javascript($dcdom,'currsec','cu','role','Course/Community Browser',$credit_elem);
 8832:     my %lt=&Apache::lonlocal::texthash(
 8833:                     'rol'  => "Role",
 8834:                     'grs'  => "Section",
 8835:                     'exs'  => "Existing sections",
 8836:                     'new'  => "Define new section", 
 8837:                     'sta'  => "Start",
 8838:                     'end'  => "End",
 8839:                     'ssd'  => "Set Start Date",
 8840:                     'sed'  => "Set End Date",
 8841:                     'scc'  => "Course/Community",
 8842:                     'crd'  => "Credits",
 8843:                   );
 8844:     my $header = '<h4>'.&mt('Course/Community Level').'</h4>'.
 8845:                  &Apache::loncommon::start_data_table().
 8846:                  &Apache::loncommon::start_data_table_header_row().
 8847:                  '<th>'.$lt{'scc'}.'</th><th>'.$lt{'rol'}.'</th>'."\n".
 8848:                  '<th>'.$lt{'grs'}.'</th>'."\n";
 8849:     $header .=   '<th>'.$lt{'crd'}.'</th>'."\n" if ($showcredits);
 8850:     $header .=   '<th>'.$lt{'sta'}.'</th><th>'.$lt{'end'}.'</th>'."\n".
 8851:                  &Apache::loncommon::end_data_table_header_row();
 8852:     my $otheritems = &Apache::loncommon::start_data_table_row()."\n".
 8853:                      '<td><br /><span class="LC_nobreak"><input type="text" name="coursedesc" value="" onfocus="this.blur();opencrsbrowser('."'cu','dccourse','dcdomain','coursedesc','','','','crstype'".')" />'.
 8854:                      $courseform.('&nbsp;' x4).'</span></td>'."\n".
 8855:                      '<td valign="top"><br /><select name="role">'."\n";
 8856:     foreach my $role (@roles) {
 8857:         my $plrole=&Apache::lonnet::plaintext($role);
 8858:         $otheritems .= '  <option value="'.$role.'">'.$plrole.'</option>';
 8859:     }
 8860:     if ( keys(%customroles) > 0) {
 8861:         foreach my $cust (sort(keys(%customroles))) {
 8862:             my $custrole='cr_cr_'.$env{'user.domain'}.
 8863:                     '_'.$env{'user.name'}.'_'.$cust;
 8864:             $otheritems .= '  <option value="'.$custrole.'">'.$cust.'</option>';
 8865:         }
 8866:     }
 8867:     $otheritems .= '</select></td><td>'.
 8868:                      '<table border="0" cellspacing="0" cellpadding="0">'.
 8869:                      '<tr><td valign="top"><b>'.$lt{'exs'}.'</b><br /><select name="currsec">'.
 8870:                      ' <option value="">&lt;--'.&mt('Pick course first').'</option></select></td>'.
 8871:                      '<td>&nbsp;&nbsp;</td>'.
 8872:                      '<td valign="top">&nbsp;<b>'.$lt{'new'}.'</b><br />'.
 8873:                      '<input type="text" name="newsec" value="" />'.
 8874:                      '<input type="hidden" name="section" value="" />'.
 8875:                      '<input type="hidden" name="groups" value="" />'.
 8876:                      '<input type="hidden" name="crstype" value="" /></td>'.
 8877:                      '</tr></table></td>'."\n";
 8878:     if ($showcredits) {
 8879:         $otheritems .= '<td><br />'."\n".
 8880:                        '<input type="text" size="3" name="credits" value="" /></td>'."\n";
 8881:     }
 8882:     $otheritems .= <<ENDTIMEENTRY;
 8883: <td><br /><input type="hidden" name="start" value='' />
 8884: <a href=
 8885: "javascript:pjump('date_start','Start Date',document.cu.start.value,'start','cu.pres','dateset')">$lt{'ssd'}</a></td>
 8886: <td><br /><input type="hidden" name="end" value='' />
 8887: <a href=
 8888: "javascript:pjump('date_end','End Date',document.cu.end.value,'end','cu.pres','dateset')">$lt{'sed'}</a></td>
 8889: ENDTIMEENTRY
 8890:     $otheritems .= &Apache::loncommon::end_data_table_row().
 8891:                    &Apache::loncommon::end_data_table()."\n";
 8892:     return $cb_jscript.$header.$hiddenitems.$otheritems;
 8893: }
 8894: 
 8895: sub update_selfenroll_config {
 8896:     my ($r,$cid,$cdom,$cnum,$context,$crstype,$currsettings) = @_;
 8897:     return unless (ref($currsettings) eq 'HASH');
 8898:     my ($row,$lt) = &Apache::lonuserutils::get_selfenroll_titles();
 8899:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
 8900:     my (%changes,%warning);
 8901:     my $curr_types;
 8902:     my %noedit;
 8903:     unless ($context eq 'domain') {
 8904:         %noedit = &get_noedit_fields($cdom,$cnum,$crstype,$row);
 8905:     }
 8906:     if (ref($row) eq 'ARRAY') {
 8907:         foreach my $item (@{$row}) {
 8908:             next if ($noedit{$item});
 8909:             if ($item eq 'enroll_dates') {
 8910:                 my (%currenrolldate,%newenrolldate);
 8911:                 foreach my $type ('start','end') {
 8912:                     $currenrolldate{$type} = $currsettings->{'selfenroll_'.$type.'_date'};
 8913:                     $newenrolldate{$type} = &Apache::lonhtmlcommon::get_date_from_form('selfenroll_'.$type.'_date');
 8914:                     if ($newenrolldate{$type} ne $currenrolldate{$type}) {
 8915:                         $changes{'internal.selfenroll_'.$type.'_date'} = $newenrolldate{$type};
 8916:                     }
 8917:                 }
 8918:             } elsif ($item eq 'access_dates') {
 8919:                 my (%currdate,%newdate);
 8920:                 foreach my $type ('start','end') {
 8921:                     $currdate{$type} = $currsettings->{'selfenroll_'.$type.'_access'};
 8922:                     $newdate{$type} = &Apache::lonhtmlcommon::get_date_from_form('selfenroll_'.$type.'_access');
 8923:                     if ($newdate{$type} ne $currdate{$type}) {
 8924:                         $changes{'internal.selfenroll_'.$type.'_access'} = $newdate{$type};
 8925:                     }
 8926:                 }
 8927:             } elsif ($item eq 'types') {
 8928:                 $curr_types = $currsettings->{'selfenroll_'.$item};
 8929:                 if ($env{'form.selfenroll_all'}) {
 8930:                     if ($curr_types ne '*') {
 8931:                         $changes{'internal.selfenroll_types'} = '*';
 8932:                     } else {
 8933:                         next;
 8934:                     }
 8935:                 } else {
 8936:                     my %currdoms;
 8937:                     my @entries = split(/;/,$curr_types);
 8938:                     my @deletedoms = &Apache::loncommon::get_env_multiple('form.selfenroll_delete');
 8939:                     my @activations = &Apache::loncommon::get_env_multiple('form.selfenroll_activate');
 8940:                     my $newnum = 0;
 8941:                     my @latesttypes;
 8942:                     foreach my $num (@activations) {
 8943:                         my @types = &Apache::loncommon::get_env_multiple('form.selfenroll_types_'.$num);
 8944:                         if (@types > 0) {
 8945:                             @types = sort(@types);
 8946:                             my $typestr = join(',',@types);
 8947:                             my $typedom = $env{'form.selfenroll_dom_'.$num};
 8948:                             $latesttypes[$newnum] = $typedom.':'.$typestr;
 8949:                             $currdoms{$typedom} = 1;
 8950:                             $newnum ++;
 8951:                         }
 8952:                     }
 8953:                     for (my $j=0; $j<$env{'form.selfenroll_types_total'}; $j++) {
 8954:                         if ((!grep(/^$j$/,@deletedoms)) && (!grep(/^$j$/,@activations))) {
 8955:                             my @types = &Apache::loncommon::get_env_multiple('form.selfenroll_types_'.$j);
 8956:                             if (@types > 0) {
 8957:                                 @types = sort(@types);
 8958:                                 my $typestr = join(',',@types);
 8959:                                 my $typedom = $env{'form.selfenroll_dom_'.$j};
 8960:                                 $latesttypes[$newnum] = $typedom.':'.$typestr;
 8961:                                 $currdoms{$typedom} = 1;
 8962:                                 $newnum ++;
 8963:                             }
 8964:                         }
 8965:                     }
 8966:                     if ($env{'form.selfenroll_newdom'} ne '') {
 8967:                         my $typedom = $env{'form.selfenroll_newdom'};
 8968:                         if ((!defined($currdoms{$typedom})) && 
 8969:                             (&Apache::lonnet::domain($typedom) ne '')) {
 8970:                             my $typestr;
 8971:                             my ($othertitle,$usertypes,$types) = 
 8972:                                 &Apache::loncommon::sorted_inst_types($typedom);
 8973:                             my $othervalue = 'any';
 8974:                             if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 8975:                                 if (@{$types} > 0) {
 8976:                                     my @esc_types = map { &escape($_); } @{$types};
 8977:                                     $othervalue = 'other';
 8978:                                     $typestr = join(',',(@esc_types,$othervalue));
 8979:                                 }
 8980:                                 $typestr = $othervalue;
 8981:                             } else {
 8982:                                 $typestr = $othervalue;
 8983:                             } 
 8984:                             $latesttypes[$newnum] = $typedom.':'.$typestr;
 8985:                             $newnum ++ ;
 8986:                         }
 8987:                     }
 8988:                     my $selfenroll_types = join(';',@latesttypes);
 8989:                     if ($selfenroll_types ne $curr_types) {
 8990:                         $changes{'internal.selfenroll_types'} = $selfenroll_types;
 8991:                     }
 8992:                 }
 8993:             } elsif ($item eq 'limit') {
 8994:                 my $newlimit = $env{'form.selfenroll_limit'};
 8995:                 my $newcap = $env{'form.selfenroll_cap'};
 8996:                 $newcap =~s/\s+//g;
 8997:                 my $currlimit =  $currsettings->{'selfenroll_limit'};
 8998:                 $currlimit = 'none' if ($currlimit eq '');
 8999:                 my $currcap = $currsettings->{'selfenroll_cap'};
 9000:                 if ($newlimit ne $currlimit) {
 9001:                     if ($newlimit ne 'none') {
 9002:                         if ($newcap =~ /^\d+$/) {
 9003:                             if ($newcap ne $currcap) {
 9004:                                 $changes{'internal.selfenroll_cap'} = $newcap;
 9005:                             }
 9006:                             $changes{'internal.selfenroll_limit'} = $newlimit;
 9007:                         } else {
 9008:                             $warning{$item} = &mt('Maximum enrollment setting unchanged.').'<br />'.
 9009:                                 &mt('The value provided was invalid - it must be a positive integer if enrollment is being limited.'); 
 9010:                         }
 9011:                     } elsif ($currcap ne '') {
 9012:                         $changes{'internal.selfenroll_cap'} = '';
 9013:                         $changes{'internal.selfenroll_limit'} = $newlimit; 
 9014:                     }
 9015:                 } elsif ($currlimit ne 'none') {
 9016:                     if ($newcap =~ /^\d+$/) {
 9017:                         if ($newcap ne $currcap) {
 9018:                             $changes{'internal.selfenroll_cap'} = $newcap;
 9019:                         }
 9020:                     } else {
 9021:                         $warning{$item} = &mt('Maximum enrollment setting unchanged.').'<br />'.
 9022:                             &mt('The value provided was invalid - it must be a positive integer if enrollment is being limited.');
 9023:                     }
 9024:                 }
 9025:             } elsif ($item eq 'approval') {
 9026:                 my (@currnotified,@newnotified);
 9027:                 my $currapproval = $currsettings->{'selfenroll_approval'};
 9028:                 my $currnotifylist = $currsettings->{'selfenroll_notifylist'};
 9029:                 if ($currnotifylist ne '') {
 9030:                     @currnotified = split(/,/,$currnotifylist);
 9031:                     @currnotified = sort(@currnotified);
 9032:                 }
 9033:                 my $newapproval = $env{'form.selfenroll_approval'};
 9034:                 @newnotified = &Apache::loncommon::get_env_multiple('form.selfenroll_notify');
 9035:                 @newnotified = sort(@newnotified);
 9036:                 if ($newapproval ne $currapproval) {
 9037:                     $changes{'internal.selfenroll_approval'} = $newapproval;
 9038:                     if (!$newapproval) {
 9039:                         if ($currnotifylist ne '') {
 9040:                             $changes{'internal.selfenroll_notifylist'} = '';
 9041:                         }
 9042:                     } else {
 9043:                         my @differences =  
 9044:                             &Apache::loncommon::compare_arrays(\@currnotified,\@newnotified);
 9045:                         if (@differences > 0) {
 9046:                             if (@newnotified > 0) {
 9047:                                 $changes{'internal.selfenroll_notifylist'} = join(',',@newnotified);
 9048:                             } else {
 9049:                                 $changes{'internal.selfenroll_notifylist'} = join(',',@newnotified);
 9050:                             }
 9051:                         }
 9052:                     }
 9053:                 } else {
 9054:                     my @differences = &Apache::loncommon::compare_arrays(\@currnotified,\@newnotified);
 9055:                     if (@differences > 0) {
 9056:                         if (@newnotified > 0) {
 9057:                             $changes{'internal.selfenroll_notifylist'} = join(',',@newnotified);
 9058:                         } else {
 9059:                             $changes{'internal.selfenroll_notifylist'} = '';
 9060:                         }
 9061:                     }
 9062:                 }
 9063:             } else {
 9064:                 my $curr_val = $currsettings->{'selfenroll_'.$item};
 9065:                 my $newval = $env{'form.selfenroll_'.$item};
 9066:                 if ($item eq 'section') {
 9067:                     $newval = $env{'form.sections'};
 9068:                     if (defined($curr_groups{$newval})) {
 9069:                         $newval = $curr_val;
 9070:                         $warning{$item} = &mt('Section for self-enrolled users unchanged as the proposed section is a group').'<br />'.
 9071:                                           &mt('Group names and section names must be distinct');
 9072:                     } elsif ($newval eq 'all') {
 9073:                         $newval = $curr_val;
 9074:                         $warning{$item} = &mt('Section for self-enrolled users unchanged, as "all" is a reserved section name.');
 9075:                     }
 9076:                     if ($newval eq '') {
 9077:                         $newval = 'none';
 9078:                     }
 9079:                 }
 9080:                 if ($newval ne $curr_val) {
 9081:                     $changes{'internal.selfenroll_'.$item} = $newval;
 9082:                 }
 9083:             }
 9084:         }
 9085:         if (keys(%warning) > 0) {
 9086:             foreach my $item (@{$row}) {
 9087:                 if (exists($warning{$item})) {
 9088:                     $r->print($warning{$item}.'<br />');
 9089:                 }
 9090:             } 
 9091:         }
 9092:         if (keys(%changes) > 0) {
 9093:             my $putresult = &Apache::lonnet::put('environment',\%changes,$cdom,$cnum);
 9094:             if ($putresult eq 'ok') {
 9095:                 if ((exists($changes{'internal.selfenroll_types'})) ||
 9096:                     (exists($changes{'internal.selfenroll_start_date'}))  ||
 9097:                     (exists($changes{'internal.selfenroll_end_date'}))) {
 9098:                     my %crsinfo = &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',
 9099:                                                                 $cnum,undef,undef,'Course');
 9100:                     my $chome = &Apache::lonnet::homeserver($cnum,$cdom);
 9101:                     if (ref($crsinfo{$cid}) eq 'HASH') {
 9102:                         foreach my $item ('selfenroll_types','selfenroll_start_date','selfenroll_end_date') {
 9103:                             if (exists($changes{'internal.'.$item})) {
 9104:                                 $crsinfo{$cid}{$item} = $changes{'internal.'.$item};
 9105:                             }
 9106:                         }
 9107:                         my $crsputresult =
 9108:                             &Apache::lonnet::courseidput($cdom,\%crsinfo,
 9109:                                                          $chome,'notime');
 9110:                     }
 9111:                 }
 9112:                 $r->print(&mt('The following changes were made to self-enrollment settings:').'<ul>');
 9113:                 foreach my $item (@{$row}) {
 9114:                     my $title = $item;
 9115:                     if (ref($lt) eq 'HASH') {
 9116:                         $title = $lt->{$item};
 9117:                     }
 9118:                     if ($item eq 'enroll_dates') {
 9119:                         foreach my $type ('start','end') {
 9120:                             if (exists($changes{'internal.selfenroll_'.$type.'_date'})) {
 9121:                                 my $newdate = &Apache::lonlocal::locallocaltime($changes{'internal.selfenroll_'.$type.'_date'});
 9122:                                 $r->print('<li>'.&mt('[_1]: "[_2]" set to "[_3]".',
 9123:                                           $title,$type,$newdate).'</li>');
 9124:                             }
 9125:                         }
 9126:                     } elsif ($item eq 'access_dates') {
 9127:                         foreach my $type ('start','end') {
 9128:                             if (exists($changes{'internal.selfenroll_'.$type.'_access'})) {
 9129:                                 my $newdate = &Apache::lonlocal::locallocaltime($changes{'internal.selfenroll_'.$type.'_access'});
 9130:                                 $r->print('<li>'.&mt('[_1]: "[_2]" set to "[_3]".',
 9131:                                           $title,$type,$newdate).'</li>');
 9132:                             }
 9133:                         }
 9134:                     } elsif ($item eq 'limit') {
 9135:                         if ((exists($changes{'internal.selfenroll_limit'})) ||
 9136:                             (exists($changes{'internal.selfenroll_cap'}))) {
 9137:                             my ($newval,$newcap);
 9138:                             if ($changes{'internal.selfenroll_cap'} ne '') {
 9139:                                 $newcap = $changes{'internal.selfenroll_cap'}
 9140:                             } else {
 9141:                                 $newcap = $currsettings->{'selfenroll_cap'};
 9142:                             }
 9143:                             if ($changes{'internal.selfenroll_limit'} eq 'none') {
 9144:                                 $newval = &mt('No limit');
 9145:                             } elsif ($changes{'internal.selfenroll_limit'} eq 
 9146:                                      'allstudents') {
 9147:                                 $newval = &mt('New self-enrollment no longer allowed when total (all students) reaches [_1].',$newcap);
 9148:                             } elsif ($changes{'internal.selfenroll_limit'} eq 'selfenrolled') {
 9149:                                 $newval = &mt('New self-enrollment no longer allowed when total number of self-enrolled students reaches [_1].',$newcap);
 9150:                             } else {
 9151:                                 my $currlimit =  $currsettings->{'selfenroll_limit'};
 9152:                                 if ($currlimit eq 'allstudents') {
 9153:                                     $newval = &mt('New self-enrollment no longer allowed when total (all students) reaches [_1].',$newcap);
 9154:                                 } elsif ($changes{'internal.selfenroll_limit'} eq 'selfenrolled') {
 9155:                                     $newval =  &mt('New self-enrollment no longer allowed when total number of self-enrolled students reaches [_1].',$newcap);
 9156:                                 }
 9157:                             }
 9158:                             $r->print('<li>'.&mt('"[_1]" set to "[_2]".',$title,$newval).'</li>'."\n");
 9159:                         }
 9160:                     } elsif ($item eq 'approval') {
 9161:                         if ((exists($changes{'internal.selfenroll_approval'})) ||
 9162:                             (exists($changes{'internal.selfenroll_notifylist'}))) {
 9163:                             my %selfdescs = &Apache::lonuserutils::selfenroll_default_descs();
 9164:                             my ($newval,$newnotify);
 9165:                             if (exists($changes{'internal.selfenroll_notifylist'})) {
 9166:                                 $newnotify = $changes{'internal.selfenroll_notifylist'};
 9167:                             } else {   
 9168:                                 $newnotify = $currsettings->{'selfenroll_notifylist'};
 9169:                             }
 9170:                             if (exists($changes{'internal.selfenroll_approval'})) {
 9171:                                 if ($changes{'internal.selfenroll_approval'} !~ /^[012]$/) {
 9172:                                     $changes{'internal.selfenroll_approval'} = '0';
 9173:                                 }
 9174:                                 $newval = $selfdescs{'approval'}{$changes{'internal.selfenroll_approval'}};
 9175:                             } else {
 9176:                                 my $currapproval = $currsettings->{'selfenroll_approval'}; 
 9177:                                 if ($currapproval !~ /^[012]$/) {
 9178:                                     $currapproval = 0;
 9179:                                 }
 9180:                                 $newval = $selfdescs{'approval'}{$currapproval};
 9181:                             }
 9182:                             $r->print('<li>'.&mt('"[_1]" set to "[_2]".',$title,$newval));
 9183:                             if ($newnotify) {
 9184:                                 $r->print('<br />'.&mt('The following will be notified when an enrollment request needs approval, or has been approved: [_1].',$newnotify));
 9185:                             } else {
 9186:                                 $r->print('<br />'.&mt('No notifications sent when an enrollment request needs approval, or has been approved.'));
 9187:                             }
 9188:                             $r->print('</li>'."\n");
 9189:                         }
 9190:                     } else {
 9191:                         if (exists($changes{'internal.selfenroll_'.$item})) {
 9192:                             my $newval = $changes{'internal.selfenroll_'.$item};
 9193:                             if ($item eq 'types') {
 9194:                                 if ($newval eq '') {
 9195:                                     $newval = &mt('None');
 9196:                                 } elsif ($newval eq '*') {
 9197:                                     $newval = &mt('Any user in any domain');
 9198:                                 }
 9199:                             } elsif ($item eq 'registered') {
 9200:                                 if ($newval eq '1') {
 9201:                                     $newval = &mt('Yes');
 9202:                                 } elsif ($newval eq '0') {
 9203:                                     $newval = &mt('No');
 9204:                                 }
 9205:                             }
 9206:                             $r->print('<li>'.&mt('"[_1]" set to "[_2]".',$title,$newval).'</li>'."\n");
 9207:                         }
 9208:                     }
 9209:                 }
 9210:                 $r->print('</ul>');
 9211:                 if ($env{'course.'.$cid.'.description'} ne '') {
 9212:                     my %newenvhash;
 9213:                     foreach my $key (keys(%changes)) {
 9214:                         $newenvhash{'course.'.$cid.'.'.$key} = $changes{$key};
 9215:                     }
 9216:                     &Apache::lonnet::appenv(\%newenvhash);
 9217:                 }
 9218:             } else {
 9219:                 $r->print(&mt('An error occurred when saving changes to self-enrollment settings in this course.').'<br />'.
 9220:                           &mt('The error was: [_1].',$putresult));
 9221:             }
 9222:         } else {
 9223:             $r->print(&mt('No changes were made to the existing self-enrollment settings in this course.'));
 9224:         }
 9225:     } else {
 9226:         $r->print(&mt('No changes were made to the existing self-enrollment settings in this course.'));
 9227:     }
 9228:     my $visactions = &cat_visibility();
 9229:     my ($cathash,%cattype);
 9230:     my %domconfig = &Apache::lonnet::get_dom('configuration',['coursecategories'],$cdom);
 9231:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 9232:         $cathash = $domconfig{'coursecategories'}{'cats'};
 9233:         $cattype{'auth'} = $domconfig{'coursecategories'}{'auth'};
 9234:         $cattype{'unauth'} = $domconfig{'coursecategories'}{'unauth'};
 9235:     } else {
 9236:         $cathash = {};
 9237:         $cattype{'auth'} = 'std';
 9238:         $cattype{'unauth'} = 'std';
 9239:     }
 9240:     if (($cattype{'auth'} eq 'none') && ($cattype{'unauth'} eq 'none')) {
 9241:         $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
 9242:                   '<br />'.
 9243:                   '<br />'.$visactions->{'take'}.'<ul>'.
 9244:                   '<li>'.$visactions->{'dc_chgconf'}.'</li>'.
 9245:                   '</ul>');
 9246:     } elsif (($cattype{'auth'} !~ /^(std|domonly)$/) && ($cattype{'unauth'} !~ /^(std|domonly)$/)) {
 9247:         if ($currsettings->{'uniquecode'}) {
 9248:             $r->print('<span class="LC_info">'.$visactions->{'vis'}.'</span>');
 9249:         } else {
 9250:             $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
 9251:                   '<br />'.
 9252:                   '<br />'.$visactions->{'take'}.'<ul>'.
 9253:                   '<li>'.$visactions->{'dc_setcode'}.'</li>'.
 9254:                   '</ul><br />');
 9255:         }
 9256:     } else {
 9257:         my ($visible,$cansetvis,$vismsgs) = &visible_in_stdcat($cdom,$cnum,\%domconfig);
 9258:         if (ref($visactions) eq 'HASH') {
 9259:             if (!$visible) {
 9260:                 $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
 9261:                           '<br />');
 9262:                 if (ref($vismsgs) eq 'ARRAY') {
 9263:                     $r->print('<br />'.$visactions->{'take'}.'<ul>');
 9264:                     foreach my $item (@{$vismsgs}) {
 9265:                         $r->print('<li>'.$visactions->{$item}.'</li>');
 9266:                     }
 9267:                     $r->print('</ul>');
 9268:                 }
 9269:                 $r->print($cansetvis);
 9270:             }
 9271:         }
 9272:     } 
 9273:     return;
 9274: }
 9275: 
 9276: #---------------------------------------------- end functions for &phase_two
 9277: 
 9278: #--------------------------------- functions for &phase_two and &phase_three
 9279: 
 9280: #--------------------------end of functions for &phase_two and &phase_three
 9281: 
 9282: 1;
 9283: __END__
 9284: 
 9285: 

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